Beispiel #1
0
        /// <summary>
        /// input newClientContent is a string representation of a json array of records, each of which is a nsg flow log hierarchy
        /// output is a List of SplunkEventMessage, up to a max # of bytes or 450 elements
        /// </summary>
        /// <param name="newClientContent"></param>
        /// <param name="errorRecordBinder"></param>
        /// <param name="log"></param>
        /// <returns></returns>
        static IEnumerable <List <SplunkEventMessage> > denormalizedSplunkEvents(string newClientContent, Binder errorRecordBinder, ILogger log)
        {
            var outgoingSplunkList = ListPool <SplunkEventMessage> .Allocate();

            outgoingSplunkList.Capacity = 450;
            var sizeOfListItems = 0;

            try
            {
                NSGFlowLogRecords logs = JsonConvert.DeserializeObject <NSGFlowLogRecords>(newClientContent);

                foreach (var record in logs.records)
                {
                    float version = record.properties.Version;

                    foreach (var outerFlow in record.properties.flows)
                    {
                        foreach (var innerFlow in outerFlow.flows)
                        {
                            foreach (var flowTuple in innerFlow.flowTuples)
                            {
                                var tuple = new NSGFlowLogTuple(flowTuple, version);

                                var denormalizedRecord = new DenormalizedRecord(
                                    record.properties.Version,
                                    record.time,
                                    record.category,
                                    record.operationName,
                                    record.resourceId,
                                    outerFlow.rule,
                                    innerFlow.mac,
                                    tuple);

                                var splunkEventMessage = new SplunkEventMessage(denormalizedRecord);
                                var sizeOfObject       = splunkEventMessage.GetSizeOfObject();

                                if (sizeOfListItems + sizeOfObject > MAXTRANSMISSIONSIZE + 20 || outgoingSplunkList.Count == 450)
                                {
                                    yield return(outgoingSplunkList);

                                    outgoingSplunkList.Clear();
                                    sizeOfListItems = 0;
                                }
                                outgoingSplunkList.Add(splunkEventMessage);

                                sizeOfListItems += sizeOfObject;
                            }
                        }
                    }
                }
                if (sizeOfListItems > 0)
                {
                    yield return(outgoingSplunkList);
                }
            }
            finally
            {
                ListPool <SplunkEventMessage> .Free(outgoingSplunkList);
            }
        }
Beispiel #2
0
        /// <summary>
        /// Generates layer of nodes.
        /// </summary>
        public void GenerateBranches()
        {
            if (HandState.Count > 0)
            {
                var tempList = ListPool <Card> .Obtain();

                for (int i = 0; i < HandState.Count; ++i)
                {
                    for (int j = 0; j < HandState.Count; ++j)
                    {
                        if (i != j)
                        {
                            tempList.Add(HandState[j]);
                        }
                    }


                    var childNode = Pool <Node> .Obtain();

                    childNode.SetHandState(tempList);
                    childNode.CardPlayed = HandState[i];
                    Children.Add(childNode);
                    tempList.Clear();
                }
                ListPool <Card> .Free(tempList);
            }
        }
        /// <summary>
        /// beräknar rörelsen som ändrar rörelsevektorn för att ta hänsyn till eventuella
        /// kollisioner som kommer att inträffa vid rörelse
        /// </summary>
        /// <returns><c>true</c> Om Rörelsen Blev Uträknad <c>false</c> Om Inte.</returns>
        /// <param name="rörelse"> Rörelse.</param>
        /// <param name="kollitionsResultat"> Kollitions Resultat.</param>
        public bool BeräknaRörelse(ref Vector2 rörelse, out CollisionResult kollitionsResultat)
        {
            kollitionsResultat = new CollisionResult();

            // ingen kolliderare? Strunta i det och förflytta dig bara
            if (Entity.GetComponent <Collider>() == null || TriggerHjälpare == null)
            {
                return(false);
            }

            // 1. flytta alla icke-trigger Kollisioner och få närmaste kollision
            List <Collider> kolliders = Entity.GetComponents <Collider>();

            for (int i = 0; i < kolliders.Count; i++)
            {
                Collider kollider = kolliders[i];

                // hoppa över triggers för tillfället.
                //vi kommer tillbaka till de när vi förflyttar oss.
                if (kollider.IsTrigger)
                {
                    continue;
                }

                // hämta allt som vi kan kollidera med vid den nya positionen
                RectangleF gränser = kollider.Bounds;
                gränser.X += rörelse.X;
                gränser.Y += rörelse.Y;
                Grannar    = Physics.BoxcastBroadphaseExcludingSelf(kollider, ref gränser, kollider.CollidesWithLayers);

                foreach (Collider granne in Grannar)
                {
                    // hoppa över triggers för tillfället.
                    //vi kommer tillbaka till de när vi förflyttar oss.
                    if (granne.IsTrigger)
                    {
                        continue;
                    }

                    if (kollider.CollidesWith(granne, rörelse, out CollisionResult InternKollitionsResultat))
                    {
                        // vid träff. dra vi undan våran rörelse
                        rörelse -= InternKollitionsResultat.MinimumTranslationVector;

                        // Om vi träffar flera objekt, kolla bara med den första för att förenkla.
                        if (InternKollitionsResultat.Collider != null)
                        {
                            kollitionsResultat = InternKollitionsResultat;
                        }
                    }
                }
            }

            ListPool <Collider> .Free(kolliders);

            return(kollitionsResultat.Collider != null);
        }
Beispiel #4
0
        /// <summary>
        /// caculates the movement modifying the motion vector to take into account any collisions that will
        /// occur when moving
        /// </summary>
        /// <returns><c>true</c>, if movement was calculated, <c>false</c> otherwise.</returns>
        /// <param name="motion">Motion.</param>
        /// <param name="collisionResult">Collision result.</param>
        public bool CalculateMovement(ref Vector2 motion, out CollisionResult collisionResult)
        {
            collisionResult = new CollisionResult();

            // no collider? just move and forget about it
            if (Entity.GetComponent <Collider>() == null || _triggerHelper == null)
            {
                return(false);
            }

            // 1. move all non-trigger Colliders and get closest collision
            var colliders = Entity.GetComponents <Collider>();

            for (var i = 0; i < colliders.Count; i++)
            {
                var collider = colliders[i];

                // skip triggers for now. we will revisit them after we move.
                if (collider.IsTrigger)
                {
                    continue;
                }

                // fetch anything that we might collide with at our new position
                var bounds = collider.Bounds;
                bounds.X += motion.X;
                bounds.Y += motion.Y;
                var neighbors =
                    Physics.BoxcastBroadphaseExcludingSelf(collider, ref bounds, collider.CollidesWithLayers);

                foreach (var neighbor in neighbors)
                {
                    // skip triggers for now. we will revisit them after we move.
                    if (neighbor.IsTrigger)
                    {
                        continue;
                    }

                    if (collider.CollidesWith(neighbor, motion, out CollisionResult _InternalcollisionResult))
                    {
                        // hit. back off our motion
                        //motion -= _InternalcollisionResult.MinimumTranslationVector;

                        // If we hit multiple objects, only take on the first for simplicity sake.
                        if (_InternalcollisionResult.Collider != null)
                        {
                            collisionResult = _InternalcollisionResult;
                        }
                    }
                }
            }

            ListPool <Collider> .Free(colliders);

            return(collisionResult.Collider != null);
        }
Beispiel #5
0
        /// <summary>
        /// Calculates the movement modifying the motion vector to take into account any collisions that will
        /// occur when moving. This version is modified to output through a given collection to show every
        /// collision that occured.
        /// </summary>
        /// <returns>The amount of collisions that occured.</returns>
        /// <param name="motion">Motion.</param>
        /// <param name="collisionResult">Collision result.</param>
        public int AdvancedCalculateMovement(ref Vector2 motion, ICollection <CollisionResult> collisionResults)
        {
            int Collisions = 0;

            // no collider? just move and forget about it
            if (Entity.GetComponent <Collider>() == null || _triggerHelper == null)
            {
                return(Collisions);
            }

            // 1. move all non-trigger Colliders and get closest collision
            var colliders = Entity.GetComponents <Collider>();

            for (var i = 0; i < colliders.Count; i++)
            {
                var collider = colliders[i];

                // skip triggers for now. we will revisit them after we move.
                if (collider.IsTrigger)
                {
                    continue;
                }

                // fetch anything that we might collide with at our new position
                var bounds = collider.Bounds;
                bounds.X += motion.X;
                bounds.Y += motion.Y;
                var neighbors =
                    Physics.BoxcastBroadphaseExcludingSelf(collider, ref bounds, collider.CollidesWithLayers);

                foreach (var neighbor in neighbors)
                {
                    // skip triggers for now. we will revisit them after we move.
                    if (neighbor.IsTrigger)
                    {
                        continue;
                    }

                    if (collider.CollidesWith(neighbor, motion, out CollisionResult _InternalcollisionResult))
                    {
                        // hit. back off our motion
                        motion -= _InternalcollisionResult.MinimumTranslationVector;
                        collisionResults.Add(_InternalcollisionResult);

                        Collisions++;
                    }
                }
            }

            ListPool <Collider> .Free(colliders);

            return(Collisions);
        }
Beispiel #6
0
        /// <summary>
        /// gets optimized drawing points with extra points in curves and less in straight lines with any transforms present applied
        /// </summary>
        /// <returns>The optimized drawing points.</returns>
        /// <param name="distanceTolerance">Distance tolerance.</param>
        public Vector2[] GetOptimizedTransformedDrawingPoints(float distanceTolerance = 2f)
        {
            var pointList = GetOptimizedDrawingPoints(distanceTolerance);
            var points    = pointList.ToArray();

            ListPool <Vector2> .Free(pointList);

            var mat = GetCombinedMatrix();

            Vector2Ext.Transform(points, ref mat, points);

            return(points);
        }
        private static async Task <ImmutableArray <ClassifiedSpan> > GetClassifiedSpansAsync(
            Document document, TextSpan narrowSpan, TextSpan widenedSpan, CancellationToken cancellationToken)
        {
            var classificationService = document.GetLanguageService <IEditorClassificationService>();

            if (classificationService == null)
            {
                // For languages that don't expose a classification service, we show the entire
                // item as plain text. Break the text into three spans so that we can properly
                // highlight the 'narrow-span' later on when we display the item.
                return(ImmutableArray.Create(
                           new ClassifiedSpan(ClassificationTypeNames.Text, TextSpan.FromBounds(widenedSpan.Start, narrowSpan.Start)),
                           new ClassifiedSpan(ClassificationTypeNames.Text, narrowSpan),
                           new ClassifiedSpan(ClassificationTypeNames.Text, TextSpan.FromBounds(narrowSpan.End, widenedSpan.End))));
            }

            // Call out to the individual language to classify the chunk of text around the
            // reference. We'll get both the syntactic and semantic spans for this region.
            // Because the semantic tags may override the semantic ones (for example,
            // "DateTime" might be syntactically an identifier, but semantically a struct
            // name), we'll do a later merging step to get the final correct list of
            // classifications.  For tagging, normally the editor handles this.  But as
            // we're producing the list of Inlines ourselves, we have to handles this here.
            var syntaxSpans = ListPool <ClassifiedSpan> .Allocate();

            var semanticSpans = ListPool <ClassifiedSpan> .Allocate();

            try
            {
                var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);

                await classificationService.AddSyntacticClassificationsAsync(
                    document, widenedSpan, syntaxSpans, cancellationToken).ConfigureAwait(false);

                await classificationService.AddSemanticClassificationsAsync(
                    document, widenedSpan, semanticSpans, cancellationToken).ConfigureAwait(false);

                var classifiedSpans = MergeClassifiedSpans(
                    syntaxSpans, semanticSpans, widenedSpan, sourceText);
                return(classifiedSpans);
            }
            finally
            {
                ListPool <ClassifiedSpan> .Free(syntaxSpans);

                ListPool <ClassifiedSpan> .Free(semanticSpans);
            }
        }
Beispiel #8
0
        /// <summary>
        /// 清理小球
        /// </summary>
        /// <param name="isWin"></param>
        private void ClearBalls(bool isWin)
        {
            BonusList.ForEach(x => BrickMgrM.LoaderManager.ReleaseObject(x.gameObject));
            var tempList = ListPool <BallEntity> .Allocate();

            foreach (var item in BallsSet)
            {
                tempList.Add(item);
            }
            foreach (var item in tempList)
            {
                BrickMgrM.LoaderManager.ReleaseObject(item.gameObject);
                // BrickMgrM.PoolModule.GetPool<BallEntity>().Return(item);
            }
            ListPool <BallEntity> .Free(tempList);
        }
Beispiel #9
0
        public override void PassCards(int roundNumber, Player otherPlayer)
        {
            var tempList = ListPool <Card> .Obtain();

            for (int i = 0; i < 3; ++i)
            {
                var randomIdx  = _random.Next(0, Hand.Count - 1);
                var randomCard = Hand[randomIdx];
                Hand.RemoveAt(randomIdx);
                tempList.Add(randomCard);
            }

            otherPlayer.QueueRecieveCards(tempList);

            ListPool <Card> .Free(tempList);
        }
Beispiel #10
0
        public override void PassCards(int roundNumber, Player otherPlayer)
        {
            var tempList = ListPool <Card> .Obtain();

            Hand.Sort();

            for (int i = Hand.Count - 1, j = 0; j < 3; ++j, --i)
            {
                tempList.Add(Hand[i]);
                Hand.RemoveAt(i);
            }

            otherPlayer.QueueRecieveCards(tempList);

            ListPool <Card> .Free(tempList);
        }
            private async Task <ClassifiedSpansAndHighlightSpan> GetTaggedTextForReferenceAsync(
                Document document, TextSpan referenceSpan, TextSpan widenedSpan)
            {
                var classificationService = document.GetLanguageService <IEditorClassificationService>();

                if (classificationService == null)
                {
                    return(new ClassifiedSpansAndHighlightSpan(ImmutableArray <ClassifiedSpan> .Empty, new TextSpan()));
                }

                // Call out to the individual language to classify the chunk of text around the
                // reference. We'll get both the syntactic and semantic spans for this region.
                // Because the semantic tags may override the semantic ones (for example,
                // "DateTime" might be syntactically an identifier, but semantically a struct
                // name), we'll do a later merging step to get the final correct list of
                // classifications.  For tagging, normally the editor handles this.  But as
                // we're producing the list of Inlines ourselves, we have to handles this here.
                var syntaxSpans = ListPool <ClassifiedSpan> .Allocate();

                var semanticSpans = ListPool <ClassifiedSpan> .Allocate();

                try
                {
                    var sourceText = await document.GetTextAsync(CancellationToken).ConfigureAwait(false);

                    await classificationService.AddSyntacticClassificationsAsync(
                        document, widenedSpan, syntaxSpans, CancellationToken).ConfigureAwait(false);

                    await classificationService.AddSemanticClassificationsAsync(
                        document, widenedSpan, semanticSpans, CancellationToken).ConfigureAwait(false);

                    var classifiedSpans = MergeClassifiedSpans(
                        syntaxSpans, semanticSpans, widenedSpan, sourceText);

                    var highlightSpan = new TextSpan(
                        start: referenceSpan.Start - widenedSpan.Start,
                        length: referenceSpan.Length);

                    return(new ClassifiedSpansAndHighlightSpan(classifiedSpans, highlightSpan));
                }
                finally
                {
                    ListPool <ClassifiedSpan> .Free(syntaxSpans);

                    ListPool <ClassifiedSpan> .Free(semanticSpans);
                }
            }
Beispiel #12
0
        /// <summary>
        /// 每帧最多生成50个小球
        /// </summary>
        /// <returns></returns>
        private IEnumerator MultiplyAsync()
        {
            var tempList = ListPool <BallEntity> .Allocate();

            var counter = 0;

            foreach (var item in BrickMgrM.EntityModule.BallsSet)
            {
                tempList.Add(item);
            }
            yield return(null);

            foreach (var ball in tempList)
            {
                if (BrickMgrM.EntityModule.BallsSet.Count > 500)
                {
                    yield break;
                }
                if (ball.gameObject.activeInHierarchy == true)
                {
                    var zFloat = Random.Range(-80, 45);
                    ball.Init(ball.transform.position, new Vector3(0, 0, zFloat));

                    BrickMgrM.PoolModule.GetPool <BallEntity>()
                    .RentAsync()
                    .Subscribe(x =>
                    {
                        zFloat = Random.Range(-45, 80);
                        x.Init(ball.transform.position, new Vector3(0, 0, zFloat));
                    });
                    BrickMgrM.PoolModule.GetPool <BallEntity>()
                    .RentAsync()
                    .Subscribe(x =>
                    {
                        zFloat = Random.Range(110, 340);
                        x.Init(ball.transform.position, new Vector3(0, 0, zFloat));
                    });
                    counter++;
                }
                if (counter > 50)
                {
                    counter = 0;
                    yield return(null);
                }
            }
            ListPool <BallEntity> .Free(tempList);
        }
Beispiel #13
0
        void IPoolable.Free()
        {
            disposed = true;

            foreach (var inputConnection in inputConnections)
            {
                ListPool <UnitPortPreservation> .Free(inputConnection.Value);
            }

            foreach (var outputConnection in outputConnections)
            {
                ListPool <UnitPortPreservation> .Free(outputConnection.Value);
            }

            defaultValues.Clear();
            inputConnections.Clear();
            outputConnections.Clear();
        }
Beispiel #14
0
        public Player GetWinner()
        {
            var tempList = ListPool <Card> .Obtain();

            foreach (var card in OrderedCards)
            {
                if (card.Suit == LeadSuit)
                {
                    tempList.Add(card);
                }
            }

            tempList.Sort();
            var winner = Cards[tempList[tempList.Count - 1]];

            ListPool <Card> .Free(tempList);

            return(winner);
        }
Beispiel #15
0
        void DestroyBody()
        {
            for (var i = 0; i < _joints.Count; i++)
            {
                _joints[i].DestroyJoint();
            }
            _joints.Clear();

            var collisionShapes = Entity.GetComponents <FSCollisionShape>();

            for (var i = 0; i < collisionShapes.Count; i++)
            {
                collisionShapes[i].DestroyFixture();
            }
            ListPool <FSCollisionShape> .Free(collisionShapes);

            Body.World.RemoveBody(Body);
            Body = null;
        }
Beispiel #16
0
        private void CreateBody()
        {
            if (Body != null)
            {
                return;
            }

            FSWorld world = Entity.Scene.GetOrCreateSceneComponent <FSWorld>();

            Body = new Body(world, Transform.Position * FSConvert.DisplayToSim, Transform.Rotation, _bodyDef.BodyType,
                            this)
            {
                LinearVelocity  = _bodyDef.LinearVelocity,
                AngularVelocity = _bodyDef.AngularVelocity,
                LinearDamping   = _bodyDef.LinearDamping,
                AngularDamping  = _bodyDef.AngularDamping,

                IsBullet          = _bodyDef.IsBullet,
                IsSleepingAllowed = _bodyDef.IsSleepingAllowed,
                IsAwake           = _bodyDef.IsAwake,
                Enabled           = Enabled,
                FixedRotation     = _bodyDef.FixedRotation,
                IgnoreGravity     = _bodyDef.IgnoreGravity,
                Mass    = _bodyDef.Mass,
                Inertia = _bodyDef.Inertia
            };

            List <FSCollisionShape> collisionShapes = Entity.GetComponents <FSCollisionShape>();

            for (int i = 0; i < collisionShapes.Count; i++)
            {
                collisionShapes[i].CreateFixture();
            }

            ListPool <FSCollisionShape> .Free(collisionShapes);

            for (int i = 0; i < _joints.Count; i++)
            {
                _joints[i].CreateJoint();
            }
        }
Beispiel #17
0
        /// <summary>
        /// checks to see if the Fixture with motion applied (delta movement vector) collides with any collider. If it does, true will be
        /// returned and result will be populated with collision data. motion will be set to the maximum distance the Body can travel
        /// before colliding.
        /// </summary>
        /// <returns><c>true</c>, if with any was collidesed, <c>false</c> otherwise.</returns>
        /// <param name="self">Fixture a.</param>
        /// <param name="motion">the delta movement in Nez pixel coordinates</param>
        /// <param name="result">Result.</param>
        public static bool CollidesWithAnyFixtures(this Fixture self, ref Vector2 motion, out FSCollisionResult result)
        {
            result  = new FSCollisionResult();
            motion *= FSConvert.DisplayToSim;
            AABB        aabb;
            FSTransform xf;
            var         didCollide = false;

            self.Body.GetTransform(out xf);
            xf.P += motion;
            self.Shape.ComputeAABB(out aabb, ref xf, 0);

            var neighbors = ListPool <Fixture> .Obtain();

            self.Body.World.QueryAABB(ref aabb, neighbors);
            if (neighbors.Count > 1)
            {
                // handle collisions with all but ourself
                for (var i = 0; i < neighbors.Count; i++)
                {
                    if (neighbors[i].FixtureId == self.FixtureId)
                    {
                        continue;
                    }

                    if (FSCollisions.CollideFixtures(self, ref motion, neighbors[i], out result))
                    {
                        // if we have a collision, adjust the transform to account for it
                        xf.P += result.MinimumTranslationVector;
                    }
                }
            }

            ListPool <Fixture> .Free(neighbors);

            motion *= FSConvert.SimToDisplay;

            return(didCollide);
        }
Beispiel #18
0
        /// <summary>
        /// gets optimized drawing points with extra points in curves and less in straight lines. Returns a pooled list that should be returned to the ListPool when done.
        /// </summary>
        /// <returns>The optimized drawing points.</returns>
        /// <param name="distanceTolerance">Distance tolerance.</param>
        public List <Vector2> GetOptimizedDrawingPoints(float distanceTolerance = 2f)
        {
            Insist.IsTrue(IsPathCubicBezier(), "SvgPath is not a cubic bezier");

            var points = ListPool <Vector2> .Obtain();

            for (var i = 1; i < Segments.Count; i++)
            {
                var cub = Segments[i] as SvgCubicCurveSegment;
                var pts = Bezier.GetOptimizedDrawingPoints(cub.Start, cub.FirstCtrlPoint, cub.SecondCtrlPoint, cub.End, distanceTolerance);

                // as long as this isnt the first segment, we can remove the first drawing point since it will be identical to the last one
                if (i != 1)
                {
                    pts.RemoveAt(0);
                }
                points.AddRange(pts);
                ListPool <Vector2> .Free(pts);
            }

            return(points);
        }
Beispiel #19
0
        //private readonly string mssKey = "82069A88-26BD-4902-9CA6-7AE324193FE3:X";
        //private readonly string nssKey = "0EECCFF2-8CAE-4D65-935F-15E1AF31709B:X" ;

        public bool GetShapeFunctions(Element targetElement, out Polynomial[] nss, out Polynomial[] mss)
        {
            nss = null;
            mss = null;

            var mssKey = "7AE324193FE3:X" + this.Direction;
            var nssKey = "15E1AF31709B:X" + this.Direction;


            var sb = new StringBuilder();

            var bar = targetElement as BarElement;

            var n = bar.NodeCount;


            List <Condition> cnds = null;

            {
                var xis = new Func <int, double>(i =>
                {
                    var delta = 2.0 / (n - 1);

                    return(-1 + delta * i);
                });

                bar.TryGetCache(mssKey, out mss);
                bar.TryGetCache(nssKey, out nss);

                if (nss != null && mss != null)
                {
                    //return true;

                    cnds = GetShapeFunctionConditions(bar);

                    var flag = true;

                    foreach (var cnd in cnds)
                    {
                        var pn = (cnd.Type == Condition.FunctionType.N) ? nss[cnd.NodeNumber] : mss[cnd.NodeNumber];

                        var epsilon = (pn.EvaluateDerivative(cnd.Xi, cnd.DifferentialDegree) - cnd.RightSide);

                        if (epsilon < 0)
                        {
                            epsilon *= -1;
                        }

                        if (epsilon > 1e-10)
                        {
                            flag = false;
                            break;
                        }
                    }

                    if (flag)
                    {
                        CondsListPool.Free(cnds);
                        return(true);
                    }
                    else
                    {
                        mss = nss = null;
                    }
                }

                if (cnds == null)
                {
                    cnds = GetShapeFunctionConditions(bar);
                }
            }


            var grpd = cnds.GroupBy(i => Tuple.Create(i.NodeNumber, i.Type)).ToArray();

            CondsListPool.Free(cnds);

            mss = new Polynomial[n];
            nss = new Polynomial[n];

            foreach (var grp in grpd)
            {
                var nodeNum   = grp.Key.Item1;
                var tp        = grp.Key.Item2;
                var condCount = grp.Count();

                var mtx =
                    bar.MatrixPool.Allocate(condCount, condCount);
                //new Matrix(condCount, condCount);

                var rightSide =
                    bar.MatrixPool.Allocate(condCount, 1);
                //new Matrix(condCount, 1);

                var arr = grp.ToArray();

                for (var i = 0; i < arr.Length; i++)
                {
                    var itm = arr[i];

                    mtx.SetRow(i, Diff(itm.Xi, condCount - 1, itm.DifferentialDegree));

                    rightSide.SetRow(i, itm.RightSide);
                }

                Polynomial pl;

                if (arr.Length != 0)
                {
                    //var cfs = mtx.Inverse2() * rightSide;
                    var cfs = mtx.Solve(rightSide.CoreArray);//.Inverse2() * rightSide;

                    pl = new Polynomial(cfs);
                }
                else
                {
                    pl = new Polynomial();
                }

                //bar.ReturnMatrixToPool(rightSide, mtx);

                if (tp == Condition.FunctionType.M)
                {
                    mss[nodeNum] = pl;
                }

                if (tp == Condition.FunctionType.N)
                {
                    nss[nodeNum] = pl;
                }

                mtx.ReturnToPool();
                rightSide.ReturnToPool();
            }

            for (var i = 0; i < n; i++)
            {
                if (nss[i] == null)
                {
                    nss[i] = new Polynomial();
                }

                if (mss[i] == null)
                {
                    mss[i] = new Polynomial();
                }
            }

            {
                bar.SetCache(nssKey, nss);
                bar.SetCache(mssKey, mss);
            }


            return(true);
        }
Beispiel #20
0
        /* from: http://theory.stanford.edu/~amitp/GameProgramming/ImplementationNotes.html
         * OPEN = priority queue containing START
         * CLOSED = empty set
         * while lowest rank in OPEN is not the GOAL:
         * current = remove lowest rank item from OPEN
         * add current to CLOSED
         * for neighbors of current:
         *  cost = g(current) + movementcost(current, neighbor)
         *  if neighbor in OPEN and cost less than g(neighbor):
         *    remove neighbor from OPEN, because new path is better
         *  if neighbor in CLOSED and cost less than g(neighbor): **
         *    remove neighbor from CLOSED
         *  if neighbor not in OPEN and neighbor not in CLOSED:
         *    set g(neighbor) to cost
         *    add neighbor to OPEN
         *    set priority queue rank to g(neighbor) + h(neighbor)
         *    set neighbor's parent to current
         */

        /// <summary>
        /// Make a plan of actions that will reach desired world state
        /// </summary>
        /// <param name="ap">Ap.</param>
        /// <param name="start">Start.</param>
        /// <param name="goal">Goal.</param>
        /// <param name="storage">Storage.</param>
        public static Stack <Action> Plan(ActionPlanner ap, WorldState start, WorldState goal,
                                          List <AStarNode> selectedNodes = null)
        {
            storage.Clear();

            var currentNode = Pool <AStarNode> .Obtain();

            currentNode.WorldState                = start;
            currentNode.ParentWorldState          = start;
            currentNode.CostSoFar                 = 0;                                                 // g
            currentNode.HeuristicCost             = CalculateHeuristic(start, goal);                   // h
            currentNode.CostSoFarAndHeuristicCost = currentNode.CostSoFar + currentNode.HeuristicCost; // f
            currentNode.Depth = 1;

            storage.AddToOpenList(currentNode);

            while (true)
            {
                // nothing left open so we failed to find a path
                if (!storage.HasOpened())
                {
                    storage.Clear();
                    return(null);
                }

                currentNode = storage.RemoveCheapestOpenNode();

                storage.AddToClosedList(currentNode);

                // all done. we reached our goal
                if (goal.Equals(currentNode.WorldState))
                {
                    var plan = ReconstructPlan(currentNode, selectedNodes);
                    storage.Clear();
                    return(plan);
                }

                var neighbors = ap.GetPossibleTransitions(currentNode.WorldState);
                for (var i = 0; i < neighbors.Count; i++)
                {
                    var cur    = neighbors[i];
                    var opened = storage.FindOpened(cur);
                    var closed = storage.FindClosed(cur);
                    var cost   = currentNode.CostSoFar + cur.CostSoFar;

                    // if neighbor in OPEN and cost less than g(neighbor):
                    if (opened != null && cost < opened.CostSoFar)
                    {
                        // remove neighbor from OPEN, because new path is better
                        storage.RemoveOpened(opened);
                        opened = null;
                    }

                    // if neighbor in CLOSED and cost less than g(neighbor):
                    if (closed != null && cost < closed.CostSoFar)
                    {
                        // remove neighbor from CLOSED
                        storage.RemoveClosed(closed);
                    }

                    // if neighbor not in OPEN and neighbor not in CLOSED:
                    if (opened == null && closed == null)
                    {
                        var nb = Pool <AStarNode> .Obtain();

                        nb.WorldState                = cur.WorldState;
                        nb.CostSoFar                 = cost;
                        nb.HeuristicCost             = CalculateHeuristic(cur.WorldState, goal);
                        nb.CostSoFarAndHeuristicCost = nb.CostSoFar + nb.HeuristicCost;
                        nb.Action           = cur.Action;
                        nb.ParentWorldState = currentNode.WorldState;
                        nb.Parent           = currentNode;
                        nb.Depth            = currentNode.Depth + 1;
                        storage.AddToOpenList(nb);
                    }
                }

                // done with neighbors so release it back to the pool
                ListPool <AStarNode> .Free(neighbors);
            }
        }
Beispiel #21
0
 public override void Unload()
 {
     base.Unload();
     ListPool <ECEntity> .Free(EmittedEntities);
 }
Beispiel #22
0
 public static void Free <T>(this List <T> list)
 {
     ListPool <T> .Free(list);
 }
Beispiel #23
0
        public override void PassCards(int roundNumber, Player otherPlayer)
        {
            var  mod         = roundNumber % 4;
            bool hasLeadCard = false;

            ResetSuitTrackers();
            foreach (var card in Hand)
            {
                IncrementSuitCount(Suit.Clubs);
                if (card.CardRank == 2 && card.Suit == Suit.Clubs)
                {
                    hasLeadCard = true;

                    IncrementSuitScore(Suit.Clubs, 5);
                }
                else if (card.CardRank == Card.QUEEN && card.Suit == Suit.Spades)
                {
                    var queenScore = mod == 1 ? 1 : Card.QUEEN;
                    IncrementSuitScore(Suit.Clubs, queenScore);
                }
                else
                {
                    IncrementSuitScore(card.Suit, card.CardRank);
                }
            }

            var maxSuit = GetMaxScoreSuit();

            var tempList = ListPool <Card> .Obtain();

            Hand.Sort();

            int jLimit = 3;

            if (hasLeadCard)
            {
                jLimit = 2;
                var leadCard = Hand.First(c => c.CardRank == 2 && c.Suit == Suit.Clubs);
                tempList.Add(leadCard);
                Hand.Remove(leadCard);
            }

            for (int i = Hand.Count - 1, j = 0; i >= 0 && j < jLimit; --i)
            {
                var card = Hand[i];
                if (card.Suit == maxSuit)
                {
                    tempList.Add(card);
                    ++j;
                    Hand.RemoveAt(i);
                }
            }

            if (tempList.Count < 3)
            {
                for (int i = Hand.Count - 1; tempList.Count < 3; --i)
                {
                    tempList.Add(Hand[i]);
                    Hand.RemoveAt(i);
                }
            }


            otherPlayer.QueueRecieveCards(tempList);
            ListPool <Card> .Free(tempList);
        }
Beispiel #24
0
        public override Card GetPlayCard(int trickNumber, Trick currentTrick)
        {
            if (this.ShouldLead() && trickNumber == 1)
            {
                return(Hand.First(c => c.CardRank == 2 && c.Suit == Suit.Clubs));
            }


            if (currentTrick.Count == 0)
            {
                if (CanLeadHearts || HandIsAllHeartsAndQueenOfSpades())    //|| Hand.All( c => c.Suit == Suit.Hearts ) )
                {
                    if (this.HasQueenOfSpades())
                    {
                        foreach (Card card in Hand)
                        {
                            if ((card.Suit == Suit.Spades && card.CardRank == Card.QUEEN))
                            {
                                return(card);
                            }
                        }
                    }
                    else
                    {
                        return(Hand[_random.Next(0, Hand.Count)]);
                    }
                }
                else //Play a random card that is NOT a heart
                {
                    var tempList = ListPool <Card> .Obtain();

                    foreach (Card card in Hand)
                    {
                        if (card.Suit != Suit.Hearts)
                        {
                            tempList.Add(card);
                        }
                    }

                    var returnCard = tempList[_random.Next(0, tempList.Count)];
                    ListPool <Card> .Free(tempList);

                    return(returnCard);
                }
            }

            if (this.HasSuit(currentTrick.LeadSuit))
            {
                var tempList = ListPool <Card> .Obtain();

                foreach (Card card in Hand)
                {
                    if (card.Suit == currentTrick.LeadSuit)
                    {
                        tempList.Add(card);
                    }
                }

                var returnCard = tempList[_random.Next(0, tempList.Count)];
                ListPool <Card> .Free(tempList);

                return(returnCard);
            }
            else
            {
                return(Hand[_random.Next(0, Hand.Count)]);
            }
        }
        static IEnumerable <List <DenormalizedRecord> > denormalizedRecords(string newClientContent, Binder errorRecordBinder, ILogger log)
        {
            var outgoingList = ListPool <DenormalizedRecord> .Allocate();

            outgoingList.Capacity = 450;
            var sizeOfListItems = 0;

            try
            {
                NSGFlowLogRecords logs = JsonConvert.DeserializeObject <NSGFlowLogRecords>(newClientContent);

                foreach (var record in logs.records)
                {
                    float version = record.properties.Version;

                    foreach (var outerFlow in record.properties.flows)
                    {
                        foreach (var innerFlow in outerFlow.flows)
                        {
                            foreach (var flowTuple in innerFlow.flowTuples)
                            {
                                var tuple = new NSGFlowLogTuple(flowTuple, version);

                                var denormalizedRecord = new DenormalizedRecord(
                                    record.properties.Version,
                                    record.time,
                                    record.category,
                                    record.operationName,
                                    record.resourceId,
                                    outerFlow.rule,
                                    innerFlow.mac,
                                    tuple);

                                var sizeOfDenormalizedRecord = denormalizedRecord.GetSizeOfJSONObject();

                                //for Event hub binding fork  -- start
                                // Event hub basic message size is 256KB and the 'if' statement below ensures that list does not exceed size this size for Eventhub

                                string outputBinding = Util.GetEnvironmentVariable("outputBinding");

                                if (outputBinding == "eventhub")
                                {
                                    if (sizeOfListItems > 120) // this will chunk below 256KB : this is ideal sample message size. Feel free to go maximum till 150 : smaller values will create lot of outbound connections.
                                    {
                                        yield return(outgoingList);

                                        outgoingList.Clear();
                                        sizeOfListItems = 0;
                                    }
                                    outgoingList.Add(denormalizedRecord);
                                    sizeOfListItems += 1;
                                }

                                //for Event hub binding fork  -- end
                                //other output bindings

                                else if (sizeOfListItems + sizeOfDenormalizedRecord > MAXTRANSMISSIONSIZE + 20)
                                {
                                    yield return(outgoingList);

                                    outgoingList.Clear();
                                    sizeOfListItems = 0;
                                }
                                outgoingList.Add(denormalizedRecord);
                                sizeOfListItems += sizeOfDenormalizedRecord;
                            }
                        }
                    }
                }
                if (sizeOfListItems > 0)
                {
                    yield return(outgoingList);
                }
            }
            finally
            {
                ListPool <DenormalizedRecord> .Free(outgoingList);
            }
        }
Beispiel #26
0
 public void Recycle()
 {
     ListPool <ObjectType, PoolIdentifier> .Free(this);
 }
Beispiel #27
0
        static IEnumerable <List <DenormalizedRecord> > denormalizedRecords(string newClientContent, Binder errorRecordBinder, ILogger log)
        {
            var outgoingList = ListPool <DenormalizedRecord> .Allocate();

            outgoingList.Capacity = 450;
            var sizeOfListItems = 0;

            try
            {
                NSGFlowLogRecords logs = JsonConvert.DeserializeObject <NSGFlowLogRecords>(newClientContent);

                foreach (var record in logs.records)
                {
                    float version = record.properties.Version;

                    foreach (var outerFlow in record.properties.flows)
                    {
                        foreach (var innerFlow in outerFlow.flows)
                        {
                            foreach (var flowTuple in innerFlow.flowTuples)
                            {
                                var tuple = new NSGFlowLogTuple(flowTuple, version);

                                var denormalizedRecord = new DenormalizedRecord(
                                    record.properties.Version,
                                    record.time,
                                    record.category,
                                    record.operationName,
                                    record.resourceId,
                                    outerFlow.rule,
                                    innerFlow.mac,
                                    tuple);

                                var sizeOfDenormalizedRecord = denormalizedRecord.GetSizeOfJSONObject();
                                //new-code-start
                                //if (sizeOfDenormalizedRecord > 120) // this will chunk below 256KB
                                if (sizeOfListItems > 120)
                                {
                                    yield return(outgoingList);

                                    outgoingList.Clear();
                                    sizeOfListItems = 0;
                                }
                                //new-code-end

/*
 *                              if (sizeOfListItems + sizeOfDenormalizedRecord > MAXTRANSMISSIONSIZE + 20)
 *                              {
 *                                  yield return outgoingList;
 *                                  outgoingList.Clear();
 *                                  sizeOfListItems = 0;
 *                              }
 */
                                outgoingList.Add(denormalizedRecord);
                                //sizeOfListItems += sizeOfDenormalizedRecord;
                                sizeOfListItems += 1;
                            }
                        }
                    }
                }
                if (sizeOfListItems > 0)
                {
                    yield return(outgoingList);
                }
            }
            finally
            {
                ListPool <DenormalizedRecord> .Free(outgoingList);
            }
        }