Esempio n. 1
0
 public void It_should_not_blow_up_when_it_gets_junk_input()
 {
     ConversionExtensions.CalculateLeanKitPriority("Roscoe").ShouldEqual(1);
     ConversionExtensions.CalculateLeanKitPriority("40").ShouldEqual(1);
     ConversionExtensions.CalculateLeanKitPriority("0").ShouldEqual(1);
     ConversionExtensions.CalculateLeanKitPriority("6").ShouldEqual(1);
 }
        private WndWindowStateConfiguration(
            WndWindowDefinition wndWindow,
            ColorRgba textColor,
            ColorRgba textBorderColor,
            WndDrawData wndDrawData,
            StretchableImage image,
            GraphicsDevice graphicsDevice,
            GraphicsDevice2D graphicsDevice2D)
        {
            TextColor       = textColor;
            TextBorderColor = textBorderColor;

            if (!wndWindow.Status.HasFlag(WndWindowStatusFlags.Image))
            {
                BackgroundColor = ConversionExtensions.ToColorRgbaF(wndDrawData.Items[0].Color);
            }

            if (BackgroundColor != null || wndWindow.Status.HasFlag(WndWindowStatusFlags.Border))
            {
                BorderColor = ConversionExtensions.ToColorRgbaF(wndDrawData.Items[0].BorderColor);
            }

            if (image != null)
            {
                ImageTexture = AddDisposable(image.RenderToTexture(graphicsDevice, graphicsDevice2D));
            }
        }
Esempio n. 3
0
 /// <summary>
 /// set up values from constructor and intialize global value
 /// </summary>
 /// <param name="steps">sequence of the different steps of multi-step predictions to learn</param>
 /// <param name="alpha">The alpha used to compute running averages of the bucket duty
 ///cycles for each activation pattern bit.A lower alpha results
 ///in longer term memory.</param>
 /// <param name="actValueAlpha"></param>
 private void Initialize(IList <int> steps, double alpha, double actValueAlpha)
 {
     this.steps         = steps;
     this.alpha         = alpha;
     this.actValueAlpha = actValueAlpha;
     //for null value add -1 instead of 0
     actualValues.Add(IsNumericType(default(T)) ? ConversionExtensions.Convert <T>(-1) : default(T));
 }
        private static void RegisterCustomTypeHandlers()
        {
            ConversionExtensions.RegisterCustomTypeConverter(typeof(TMP_FontAsset),
                                                             (value, xmlLayout) =>
            {
                var font = XmlLayoutUtilities.LoadResource <TMP_FontAsset>(value);

                if (font == null)
                {
                    Debug.LogWarning("[XmlLayout][TextMesh Pro] Unable to load TMP Font Asset '" + value + "'.");
                }

                return(font);
            });

            ConversionExtensions.RegisterCustomTypeConverter(typeof(TMPro.FontStyles),
                                                             (value) =>
            {
                var stylesEntries = value.Split('|');
                FontStyles styles = FontStyles.Normal;

                foreach (var style in stylesEntries)
                {
                    try
                    {
                        FontStyles s = (FontStyles)Enum.Parse(typeof(FontStyles), style);
                        styles      |= s;
                    }
                    catch { }
                }

                return(styles);
            });

            ConversionExtensions.RegisterCustomTypeConverter(typeof(TMPro.VertexGradient),
                                                             (value, xmlLayout) =>
            {
                var colorBlock = value.ToColorBlock(xmlLayout);

                return(new TMPro.VertexGradient(colorBlock.normalColor, colorBlock.highlightedColor, colorBlock.pressedColor, colorBlock.disabledColor));
            });

            ConversionExtensions.RegisterCustomTypeConverter(typeof(TMPro.TMP_SpriteAsset),
                                                             (value) =>
            {
                var spriteAsset = XmlLayoutUtilities.LoadResource <TMP_SpriteAsset>(value);

                if (spriteAsset == null)
                {
                    Debug.LogWarning("[XmlLayout][TextMesh Pro] Unable to load TMP Sprite Asset '" + value + "'.");
                }

                return(spriteAsset);
            });
        }
Esempio n. 5
0
        private WndWindowStateConfiguration(
            WndWindowDefinition wndWindow,
            ColorRgba textColor,
            ColorRgba textBorderColor,
            WndDrawData wndDrawData)
        {
            TextColor       = textColor;
            TextBorderColor = textBorderColor;

            if (!wndWindow.Status.HasFlag(WndWindowStatusFlags.Image))
            {
                BackgroundColor = ConversionExtensions.ToColorRgbaF(wndDrawData.Items[0].Color);
            }

            if (BackgroundColor != null || wndWindow.Status.HasFlag(WndWindowStatusFlags.Border))
            {
                BorderColor = ConversionExtensions.ToColorRgbaF(wndDrawData.Items[0].BorderColor);
            }
        }
Esempio n. 6
0
        public static List <Boerman.OpenAip.Airport> Parse(TextReader contents)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Intermediate.AirportIntermediate.OPENAIP));

            var intermediate = serializer.Deserialize(contents) as Intermediate.AirportIntermediate.OPENAIP;

            var list = intermediate?.Waypoints.Airport.Select(x => new Boerman.OpenAip.Airport
            {
                Country  = x.Country,
                ICAO     = x.ICAO,
                Location = new Point(
                    Convert.ToDouble(x.Geolocation.Longitude),
                    Convert.ToDouble(x.Geolocation.Langitude),
                    Convert.ToDouble(x.Geolocation.Elevation.Value)),
                Name   = x.Name,
                Type   = ConversionExtensions.Parse(x.Type, AirportType.AD_CLOSED),
                Radios = x.Radio?.Select(r => new Radio
                {
                    Category          = ConversionExtensions.Parse(r.Category, RadioCategory.OHER),
                    Type              = ConversionExtensions.Parse(r.Type, RadioType.OTHER),
                    Description       = r.Description,
                    Frequency         = r.Frequency,
                    TypeSpecification = r.TypeSpecification
                }).ToArray(),
                Runways = x.Runways?.Select(rw => new Runway
                {
                    Name       = rw.Name,
                    Surface    = ConversionExtensions.Parse(rw.Surface, SurfaceType.UNKN),
                    Length     = Convert.ToDecimal(rw.Length.Value),
                    Width      = Convert.ToDecimal(rw.Width.Value),
                    Strength   = rw.Strength != null ? (ConversionExtensions.Parse(rw.Strength.Unit, StrengthType.PCN), rw.Strength.Value) : ((StrengthType, string Value)?)null,
                    Operations = rw.Operations,
                    Directions = rw.Direction.Select(rwd => new RunwayDirection
                    {
                        LDA  = ConversionExtensions.ToNullableDecimal(rwd.Runs.LDA?.Value) ?? -1,
                        ILS  = rwd.LandingAids?.ILS ?? -1,
                        PAPI = ConversionExtensions.ToNullableBoolean(rwd.LandingAids?.PAPI) ?? false,
                        TC   = Convert.ToInt32(rwd.TC),
                        TORA = ConversionExtensions.ToNullableDecimal(rwd.Runs?.TORA.Value) ?? -1
                    }).ToArray()
                }).ToArray()
Esempio n. 7
0
 public void It_should_return_default_card_type_if_issue_has_no_matching_priority()
 {
     ConversionExtensions.CalculateLeanKitCardType(_mapping, "Bob").Id.ShouldEqual(_testBoard.CardTypes.Last().Id);
 }
Esempio n. 8
0
 public void It_should_map_priority_of_2_to_high()
 {
     ConversionExtensions.CalculateLeanKitPriority("2").ShouldEqual(2);
 }
Esempio n. 9
0
 public void It_should_map_priority_of_4_to_low()
 {
     ConversionExtensions.CalculateLeanKitPriority("4").ShouldEqual(0);
 }
Esempio n. 10
0
        /// <summary>
        /// Method computes the result after the data is provided by the temporal memory and encoder
        /// </summary>
        /// <param name="recordNum">Record number of this input pattern.
        /// Record numbers should normally increase sequentially by 1 each time unless there are missing records in the dataset.
        /// Knowing this information insures that we don't get confused by missing records.</param>
        /// <param name="classification">{@link Map} of the classification information:
        /// bucketIdx: index of the encoder bucket</param>
        /// <param name="patternNZ">list of the active indices from the output below</param>
        /// <param name="learn">if true, learn this sample</param>
        /// <param name="infer">if true, perform inference</param>
        /// <returns>ClassificationExperiment Object</returns>

        public ClassificationExperiment <T> Compute(int recordNum, Dictionary <string, object> classification, int[] patternNZ, bool learn, bool infer)
        {
            if (classification == null)
            {
                throw new ArgumentNullException(nameof(classification));
            }
            if (patternNZ == null)
            {
                throw new ArgumentNullException(nameof(patternNZ));
            }

            ClassificationExperiment <T> retVal = new ClassificationExperiment <T>();
            List <T> actualValues = (List <T>) this.actualValues;


            // Save the offset between recordNum and learnIteration if this is the first
            // compute
            if (recordNumMinusLearnIteration == -1)
            {
                recordNumMinusLearnIteration = recordNum - learnIteration;
            }

            // Update the learn iteration
            learnIteration = recordNum - recordNumMinusLearnIteration;


            if (patternNZHistory.Any(x => x.Item1 == learnIteration))
            {
                patternNZHistory.Add(Tuple.Create(learnIteration, patternNZ));
            }

            //-------------------------------------------------------------
            // For each active bit in the activationPattern, get the classification
            // votes
            //
            // Return value dict. For buckets which we don't have an actual value
            // for yet, just plug in any valid actual value. It doesn't matter what
            // we use because that bucket won't have non-zero likelihood anyways.
            if (infer)
            {
                // If doing 0-step prediction, we shouldn't use any knowledge
                // of the classification input during inference.
                object defaultValue = default(T);
                if (steps[0] == 0)
                {
                    defaultValue = 0;
                }
                else
                {
                    defaultValue = classification["actValue"];
                    if (defaultValue == null)
                    {
                        if (IsNumericType(default(T)))
                        {
                            defaultValue = ConversionExtensions.Convert <T>(-1);
                        }
                    }
                }

                T[] actValues = new T[this.actualValues.Count];

                for (int i = 0; i < actualValues.Count; i++)
                {
                    if (IsNumericType(default(T)))
                    {
                        actValues[i] = (T)(actualValues[i].Equals(ConversionExtensions.Convert <T>(-1)) ? ConversionExtensions.Convert <T>(defaultValue) : actualValues[i]);
                    }
                    else
                    {
                        actValues[i] = (T)(actualValues[i].Equals(default(T)) ? defaultValue : actualValues[i]);
                    }
                }

                retVal.setActualValues(actValues);

                // For each n-step prediction...
                foreach (int nSteps in steps)
                {
                    // Accumulate bucket index votes and actValues into these arrays
                    double[] sumVotes = new double[maxBucketIdx + 1];
                    double[] bitVotes = new double[maxBucketIdx + 1];

                    foreach (var bit in patternNZ)
                    {
                        var        key     = Tuple.Create(bit, nSteps);
                        BitHistory history = null;
                        activeBitHistory.TryGetValue(key, out history);
                        if (history == null)
                        {
                            continue;
                        }

                        history.Infer(bitVotes);

                        sumVotes = ArrayUtils.AddOffset(sumVotes, bitVotes);
                    }

                    // Return the votes for each bucket, normalized
                    double total = sumVotes.Sum();
                    if (total > 0)
                    {
                        sumVotes = ArrayUtils.Divide(sumVotes, total);
                    }
                    else
                    {
                        // If all buckets have zero probability then simply make all of the
                        // buckets equally likely. There is no actual prediction for this
                        // timestep so any of the possible predictions are just as good.
                        if (sumVotes.Length > 0)
                        {
                            double val = 1.0 / sumVotes.Length;
                            for (int i = 0; i < sumVotes.Length; i++)
                            {
                                sumVotes[i] = val;
                            }
                        }
                    }

                    retVal.setStats(nSteps, sumVotes);
                }
            }
            // ------------------------------------------------------------------------
            // Learning:
            // For each active bit in the activationPattern, store the classification
            // info. If the bucketIdx is None, we can't learn. This can happen when the
            // field is missing in a specific record.
            if (learn && classification["bucketIdx"] != null)
            {
                // Get classification info
                int    bucketIdx = (int)classification["bucketIdx"];
                object actValue  = null;
                if (classification["actValue"] == null)
                {
                    if (IsNumericType(default(T)))
                    {
                        actValue = ConversionExtensions.Convert <T>(-1);
                    }
                }
                else
                {
                    actValue = ConversionExtensions.Convert <T>(classification["actValue"]);
                }

                // Update maxBucketIndex
                maxBucketIdx = (int)Math.Max(maxBucketIdx, bucketIdx);

                // Update rolling average of actual values if it's a scalar. If it's
                // not, it must be a category, in which case each bucket only ever
                // sees one category so we don't need a running average.
                while (maxBucketIdx > actualValues.Count - 1)
                {
                    actualValues.Add(IsNumericType(default(T)) ? ConversionExtensions.Convert <T>(-1) : default(T));
                }
                if (actualValues[bucketIdx].Equals(IsNumericType(default(T)) ? ConversionExtensions.Convert <T>(-1) : default(T)))
                {
                    actualValues[bucketIdx] = (T)actValue;
                }
                else
                {
                    if (IsNumericType(actValue))
                    {
                        double val = ((1.0 - actValueAlpha) * Convert.ToDouble(actualValues[bucketIdx], enusFormatProvider)) +
                                     (actValueAlpha * (Convert.ToDouble(actValue, enusFormatProvider)));
                        actualValues[bucketIdx] = ConversionExtensions.Convert <T>(val);
                    }
                    else
                    {
                        actualValues[bucketIdx] = (T)actValue;
                    }
                }

                // Train each pattern that we have in our history that aligns with the
                // steps we have in steps
                int   nSteps         = -1;
                int   iteration      = 0;
                int[] learnPatternNZ = null;
                foreach (var n in steps)
                {
                    nSteps = n;
                    // Do we have the pattern that should be assigned to this classification
                    // in our pattern history? If not, skip it
                    bool found = false;
                    foreach (var t in patternNZHistory)
                    {
                        iteration      = t.Item1;
                        learnPatternNZ = t.Item2;
                        if (iteration == learnIteration - nSteps)
                        {
                            found = true;
                            break;
                        }
                        iteration++;
                    }
                    if (!found)
                    {
                        continue;
                    }

                    // Store classification info for each active bit from the pattern
                    // that we got nSteps time steps ago.
                    foreach (int bit in learnPatternNZ)
                    {
                        // Get the history structure for this bit and step
                        var        key     = Tuple.Create(bit, nSteps);
                        BitHistory history = null;
                        activeBitHistory.TryGetValue(key, out history);
                        if (history == null)
                        {
                            history = new BitHistory(alpha);
                            activeBitHistory.Add(key, history);
                        }
                        history.store(learnIteration, bucketIdx);
                    }
                }
            }

            return(retVal);
        }
Esempio n. 11
0
        /// <summary>
        /// Load data from 'itemData' and apply it to 'element'
        /// (Also iterates recursively through all child elements)
        /// </summary>
        /// <param name="element">Element to apply the data to</param>
        /// <param name="itemData">Object containing the data to use</param>
        /// <param name="dataSource">Required to locate the relevant properties e.g. {dataSource.someProperty}</param>
        /// <param name="elementTemplate">Used to determine which attribute(s) to replace with data from 'itemData'</param>
        internal void ApplyViewModelData(XmlElement element,
                                         object itemData,
                                         string dataSource,
                                         XmlElement elementTemplate,
                                         IObservableList list,
                                         string changedField = null,
                                         bool isTopLevel     = true,
                                         bool isFirstCall    = false)
        {
            // Iterate through the children first
            for (var x = 0; x < element.childElements.Count; x++)
            {
                var child = element.childElements[x];

                ApplyViewModelData(child, itemData, dataSource, elementTemplate.childElements[x], list, changedField, false, isFirstCall);
            }

            List <ListItemAttributeMatch> attributesMatched = new List <ListItemAttributeMatch>();

            // Get a list of potential attributes to replace with data
            var attributesToCheck = elementTemplate.attributes.Where(a => a.Value.StartsWith("{") && a.Value.EndsWith("}"))
                                    .ToDictionary(k => k.Key, v => v.Value.Replace("{", string.Empty).Replace("}", string.Empty));

            if (attributesToCheck.Count > 0)
            {
                // Get a list of all fields and properties provided by the ViewModel object
                var members = itemData.GetType()
                              .GetMembers()
                              .Where(m => {
                    return(changedField == null ||                                                              // If no specific changed field was provided, pull all members
                           m.Name == changedField ||                                                            // otherwise, pull the changed field
                           (m is PropertyInfo && !((PropertyInfo)m).IsAutoProperty()));                         // as well as all non-auto generated properties (e.g. properties other than { get; set; })
                })
                              .Where(m => m is PropertyInfo || m is FieldInfo)
                              .ToList();

                // intersect the fields/attributes
                var fieldsToApply = members.Where(m => attributesToCheck.Values.ToList().Any(a => a.StripChars('?') == (dataSource + "." + m.Name))).ToList();

                // Get the data from each field/property, and set the attribute on the element
                foreach (var field in fieldsToApply)
                {
                    var attribute = attributesToCheck.FirstOrDefault(a => a.Value.StripChars('?') == dataSource + "." + field.Name);
                    var value     = ConversionExtensions.ToString(((field is PropertyInfo ? ((PropertyInfo)field).GetValue(itemData, null) : ((FieldInfo)field).GetValue(itemData)) ?? string.Empty));

                    element.SetAttribute(attribute.Key, value);
                    attributesMatched.Add(new ListItemAttributeMatch
                    {
                        attribute   = attribute.Key,
                        field       = field.Name,
                        bindingType = attribute.Value.StartsWith("?") ? ViewModelBindingType.OneWay : ViewModelBindingType.TwoWay
                    });
                }
            }


            // Apply the attributes (if necessary)
            if (isFirstCall || attributesMatched.Count > 0)
            {
                element.ApplyAttributes(element.attributes.Clone());
            }

            var listItemComponent = element.GetComponent <XmlLayoutListItem>();

            if (listItemComponent != null && currentListElement != null)
            {
                if (isTopLevel)
                {
                    HandleListItemPositioning(listItemComponent);
                }
            }

            if (attributesMatched.Count > 0)
            {
                HandleTwoWayBinding(element, dataSource, list, itemData, attributesMatched);
            }
        }
Esempio n. 12
0
        // allows LayoutCopyService to copy node positions inside collapsed subgraphs
        protected void CopySavedBoundsFrom(IContainerNode otherContainer)
        {
            try
            {
                var otherSubGraph = otherContainer as GoSubGraph;
                if (otherSubGraph == null)
                {
                    return;
                }

                // build Cache of GoNode children
                ICache <string, GoNode> childNodes = new Cache <string, GoNode>(x => x.Text); //Text = Name

                foreach (GoNode childNode in Enumerable.Where <GoObject>(this, child => ConversionExtensions.IsAnImplementationOf <GoNode>(child)))
                {
                    if (!String.IsNullOrEmpty(childNode.Text))
                    {
                        addUnique(childNodes, childNode.Text, childNode);
                    }
                    else if (childNode.IsAnImplementationOf <INeighborhoodNode>()) //childNode.Text is empty and childNode is NeighborhoodNode
                    {
                        addUnique(childNodes, ((INeighborhoodNode)childNode).Name, childNode);
                    }
                }

                // store SavedBounds for each child GoNode with the same name
                foreach (GoNode otherNode in otherSubGraph.SavedBounds.Keys.Where(child => child.IsAnImplementationOf <GoNode>()))
                {
                    string name = otherNode.Text;
                    if (String.IsNullOrEmpty(name) && otherNode.IsAnImplementationOf <INeighborhoodNode>())
                    {
                        name = ((INeighborhoodNode)otherNode).Name;
                    }

                    if (!String.IsNullOrEmpty(name) && childNodes.Contains(name))
                    {
                        var childNode = childNodes[name];
                        if (SavedBounds.ContainsKey(childNode))
                        {
                            SavedBounds[childNode] = otherSubGraph.SavedBounds[otherNode];
                        }
                        else
                        {
                            SavedBounds.Add(childNode, otherSubGraph.SavedBounds[otherNode]);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + "\n" + ex.StackTrace);
            }
        }
Esempio n. 13
0
        private void addChildren <TList, T>(ContainerNodeBase containerBaseNode, IList <TList> children, bool recursive)
            where T : class, TList
        {
            foreach (GoObject child in Enumerable.Where <GoObject>(containerBaseNode, child => ConversionExtensions.IsAnImplementationOf <T>(child)))
            {
                addUnique(children, child as T);
            }

            if (recursive)
            {
                foreach (GoObject child in Enumerable.Where <GoObject>(containerBaseNode, child => ConversionExtensions.IsAnImplementationOf <ContainerNodeBase>(child)))
                {
                    addChildren <TList, T>(child as ContainerNodeBase, children, recursive);
                }
            }
        }
Esempio n. 14
0
 public static TypeConverter GetTypeConverter(Type type)
 {
     return(ConversionExtensions.GetTypeConverter(type));
 }
Esempio n. 15
0
 public void It_should_return_mapped_card_type_if_issue_has_matching_label()
 {
     ConversionExtensions.CalculateLeanKitCardType(_mapping, "Roger")
     .Id.ShouldEqual(_testBoard.CardTypes.FirstOrDefault(x => x.Name == "Willy").Id);
 }
Esempio n. 16
0
 public void It_should_default_to_normal()
 {
     ConversionExtensions.CalculateLeanKitPriority(null).ShouldEqual(1);
     ConversionExtensions.CalculateLeanKitPriority("").ShouldEqual(1);
 }
        protected override IEnumerable <BosuHitObject> ConvertHitObject(HitObject obj, IBeatmap beatmap, CancellationToken cancellationToken)
        {
            List <BosuHitObject> hitObjects = new List <BosuHitObject>();

            var originalPosition = (obj as IHasPosition)?.Position ?? Vector2.Zero;
            var comboData        = obj as IHasCombo;

            bool newCombo = comboData?.NewCombo ?? false;

            if (newCombo)
            {
                index = 0;
            }
            else
            {
                index++;
            }

            switch (obj)
            {
            case IHasPathWithRepeats curve:

                double spanDuration = curve.Duration / (curve.RepeatCount + 1);
                bool   isBuzz       = spanDuration < 75 && curve.RepeatCount > 0;

                hitObjects.AddRange(ConversionExtensions.GenerateSliderBody(obj.StartTime, curve, originalPosition));

                if (isBuzz)
                {
                    hitObjects.AddRange(ConversionExtensions.ConvertBuzzSlider(obj, originalPosition, beatmap, curve, spanDuration));
                }
                else
                {
                    hitObjects.AddRange(ConversionExtensions.ConvertDefaultSlider(obj, originalPosition, beatmap, curve, spanDuration));
                }

                break;

            case IHasDuration endTime:
                hitObjects.AddRange(ConversionExtensions.ConvertSpinner(obj.StartTime, endTime, beatmap.ControlPointInfo.TimingPointAt(obj.StartTime).BeatLength));
                break;

            default:

                if (newCombo)
                {
                    hitObjects.AddRange(ConversionExtensions.ConvertImpactCircle(obj.StartTime, originalPosition));
                }
                else
                {
                    hitObjects.AddRange(ConversionExtensions.ConvertDefaultCircle(obj.StartTime, originalPosition, index));
                }

                break;
            }

            bool first = true;

            foreach (var h in hitObjects)
            {
                if (h is Cherry c)
                {
                    c.NewCombo    = first && newCombo;
                    c.ComboOffset = comboData?.ComboOffset ?? 0;
                }

                if (first)
                {
                    first = false;
                }
            }

            return(hitObjects);
        }
Esempio n. 18
0
 public void It_should_map_priority_of_3_to_normal()
 {
     ConversionExtensions.CalculateLeanKitPriority("3").ShouldEqual(1);
 }
Esempio n. 19
0
 public TypeConversionTests()
 {
     ConversionExtensions.RegisterAllCustomTypeConverters();
 }
Esempio n. 20
0
 public void It_should_map_priority_of_1_to_critical()
 {
     ConversionExtensions.CalculateLeanKitPriority("1").ShouldEqual(3);
 }
Esempio n. 21
0
 public RavenQueryBuilder(ILoggerFactory loggerFactory)
 {
     _loggerFactory = loggerFactory;
     //TODO: Better logging and IOC handling
     ConversionExtensions.Add(new StringConversionExtensions(_loggerFactory.CreateLogger <StringConversionExtensions>()));
 }