Exemplo n.º 1
1
 public static void Main(String[] args) {
   FooBar fb = new FooBar();
   IList<int> list = new LinkedList<int>();
   list.AddAll(new int[] { 2, 3, 5, 7, 11 });
   list.Map<double>(fb).Apply(Console.WriteLine);
   list.Apply(fb);
 }
Exemplo n.º 2
0
        /*
         * This is the central method of the whole Dataflow engine as it executes the patches.
         *
         * A breath first search over the entire graph is done, starting from the rootSet.
         * All patches that have no connected inlets are part of the rootSet.
         *
         * The algorith is the follow
         *
         * 1) push all elements from the root set into the execution queue
         *
         * 2) dequeue a patch from the execution queue
         * 3) if execution criteria is met execute it *1
         * 4) propagate the values of all changed outlets and add the receiving patches to the discovered set *2 *3
         * 5) goto to step 2 if the execution queue is not empty
         * 6) move all elements from the discovered set to the execution queue
         * 7) goto step 2 if the execution queue is not empty
         * 8) finish the frame
         *
         * *1 right now the only criteria is 'execute allways'
         * *2 outlet values propagation and patch enqueuing are done from first to last outlet.
         * *3 order of discovery is maintained during execution.
         */
        public void StepFrame()
        {
            LinkedList <IPatchContainer>       executionQueue = new LinkedList <IPatchContainer> ();
            HashedLinkedList <IPatchContainer> discoveredSet  = new HashedLinkedList <IPatchContainer> ();

            executionQueue.AddAll(this.rootSet);

            do
            {
                while (executionQueue.Count > 0)
                {
                    IPatchContainer patch = executionQueue.RemoveFirst();
                    patch.ExecutePatch();
                    foreach (IOutlet outlet in patch.Outlets)
                    {
                        outlet.PropagateChanges(discoveredSet);
                    }
                }
                if (discoveredSet.Count > 0)
                {
                    executionQueue.AddAll(discoveredSet);
                    discoveredSet.Clear();
                }
            } while (executionQueue.Count > 0);
        }
 public override IList<Variable> apply(IList<Variable> input)
 {
     var list = new LinkedList<Variable>();
     list.AddAll(input);
     //list.Add(0, );
     list.Insert(0, input[input.Count - 1]);
     return list;
 }
        private ICollection <DataNode> Route0(ShardingRule shardingRule, TableRule tableRule, List <IRouteValue> databaseShardingValues, List <IRouteValue> tableShardingValues)
        {
            ICollection <String>   routedDataSources = RouteDataSources(shardingRule, tableRule, databaseShardingValues);
            ICollection <DataNode> result            = new LinkedList <DataNode>();

            foreach (var routedDataSource in routedDataSources)
            {
                result.AddAll(RouteTables(shardingRule, tableRule, routedDataSource, tableShardingValues));
            }
            return(result);
        }
        private ICollection <DataNode> RouteByMixedConditionsWithCondition(ShardingRule shardingRule, TableRule tableRule)
        {
            ICollection <DataNode> result = new LinkedList <DataNode>();

            foreach (var condition in ShardingConditions.Conditions)
            {
                ICollection <DataNode> dataNodes = Route0(shardingRule, tableRule, GetDatabaseShardingValues(shardingRule, tableRule, condition), GetTableShardingValues(shardingRule, tableRule, condition));
                result.AddAll(dataNodes);
                OriginalDataNodes.Add(dataNodes);
            }
            return(result);
        }
Exemplo n.º 6
0
        private List <T> GetGroupResults <T>(ICollection <T> firstResults, ICollection <Task <ICollection <T> > > restFutures)
        {
            var result = new LinkedList <T>(firstResults);
            var rs     = Task.WhenAll(restFutures).GetAwaiter().GetResult();

            foreach (var r in rs)
            {
                result.AddAll(r);
            }

            return(result.ToList());
        }
Exemplo n.º 7
0
        private List <R> SerialExecute <T, R>(ICollection <InputGroup <T> > inputGroups,
                                              IGroupedCallback <T, R> firstCallback, IGroupedCallback <T, R> callback)
        {
            ICollection <R> result =
                new LinkedList <R>(SyncExecute(inputGroups.First(), null == firstCallback ? callback : firstCallback));
            var loopInputGroups = inputGroups.Skip(1);

            foreach (var inputGroup in loopInputGroups)
            {
                result.AddAll(SyncExecute(inputGroup, callback));
            }

            return(result.ToList());
        }
Exemplo n.º 8
0
        public static void Main(string[] args)
        {
            var count = args.Length > 0 ? int.Parse(args[0]) : 10;
            var arr   = RandomInts(count);
            // int[] arr = { 2, 5, 1, 8, 11, 22, 4, 5 };
            // qwsort(arr);
            // Print(arr);
            IList <int> list = new LinkedList <int>();

            list.AddAll(arr);
            var t = new Timer();

            QwSort(list);
            Console.WriteLine("Time = {0} sec", t.Check());
            Console.WriteLine(list[0]);
            Print(list);
        }
Exemplo n.º 9
0
        /**
         * /// Internal routine used to generate all paths starting at a given node.
         *
         * /// @param path
         * /// @param n
         * /// @return a list of lists of Nodes
         */
        protected LinkedList <String> AllPathsFrom(String path, Node n)
        {
            var p = path + ' ' + n.Word;
            var l = new LinkedList <String>();

            if (n == TerminalNode)
            {
                l.Add(p);
            }
            else
            {
                foreach (var e in n.LeavingEdges)
                {
                    l.AddAll(AllPathsFrom(p, e.ToNode));
                }
            }
            return(l);
        }
Exemplo n.º 10
0
            /// <summary>
            ///     检索的分词
            /// </summary>
            /// <returns></returns>
            private List<Term> Result()
            {
                var result = new LinkedList<Term>();
                var length = Graph.Terms.Length - 1;
                for (var i = 0; i < length; i++)
                {
                    if (Graph.Terms[i] != null)
                    {
                        result.Add(Graph.Terms[i]);
                    }
                }

                var last = new LinkedList<Term>();
                foreach (var term in result)
                {
                    if (term.Name.Length >= 3)
                    {
                        var gwi = new GetWordsImpl(term.Name);
                        string temp;
                        while ((temp = gwi.AllWords()) != null)
                        {
                            if (temp.Length < term.Name.Length && temp.Length > 1)
                            {
                                last.Add(new Term(temp, gwi.Offe + term.Offe, TermNatures.Null));
                            }
                        }
                    }
                }

                result.AddAll(last);

                ToAnalysis.SetRealName(Graph, result);
                return result;
            }
Exemplo n.º 11
0
        public void Update(UpdateArgs args)
        {
            // See if we have a new category
            if (currentCategory == null)
            {
                // Create a category and force the first credit to show
                ChooseCategory();
                Debug("Starting category: {0}", currentCategory);
                newSeconds = 0;
            }

            // If we don't have a category, we are done
            if (currentCategory == null)
            {
                Game.GameMode = new MainMenuMode();
                return;
            }

            // Update any of the displayed ones
            LinkedList<CreditsLine> tmpList = new LinkedList<CreditsLine>();
            tmpList.AddAll(displayed);

            foreach (CreditsLine cl in tmpList)
            {
                // Add the time
                cl.SecondsDisplayed += args.SecondsSinceLastUpdate;

                // If we exceeded the life, kill it
                if (cl.SecondsDisplayed > cl.SecondsToLive)
                {
                    displayed.Remove(cl);
                    sprites.Remove(cl.Sprite);
                    Debug("Removing credit line: {0}", cl.Name);
                }
            }

            // If the displayed and pending list are empty, then we
            // are done
            if (displayed.Count == 0 && pending.Count == 0)
            {
                Debug("Finished category: {0}", currentCategory);
                currentCategory = null;
                return;
            }

            // See if we are showing a new one
            newSeconds -= args.SecondsSinceLastUpdate;

            if (slots > 0 && newSeconds <= 0 && pending.Count > 0)
            {
                // Reset the counter
                newSeconds = 0.2;

                // See if we have too many
                if (displayed.Count <= slots)
                {
                    // Pick a random location for this
                    int kill = slots * 2;

                    while (true)
                    {
                        // Check the kill
                        if (kill-- < 0)
                            break;

                        // Set up some variables
                        int row = Entropy.Next(0, slots);
                        float y = row * CreditsLine.FontSize + FontSize * 2;
                        bool found = false;

                        foreach (CreditsLine cl0 in displayed)
                        {
                            if (cl0.Point.Y == y)
                            {
                                found = true;
                                break;
                            }
                        }

                        // If we found something, try again
                        if (found)
                            continue;

                        // Add a new one
                        CreditsLine cl = pending.RemoveFirst();
                        displayed.Add(cl);
                        cl.Point = new PointF(
                            Entropy.NextFloat(sprites.Size.Width
                                - cl.Sprite.Size.Width - 160) + 80,
                            y);
                        sprites.Add(cl.Sprite);
                        break;
                    }
                }
            }

            // Update the sprites
            sprites.Update(args);
        }
Exemplo n.º 12
0
        public ParkingSpaceObstacle(World world, Vector2 position, float rotation)
        {
            Vector2[] vertices = new Vector2[8];
            vertices[0] = new Vector2(-3.5f, 1.5f);
            vertices[1] = new Vector2(3.5f, 1.5f);
            vertices[2] = new Vector2(3.5f, -1.5f);
            vertices[3] = new Vector2(-3.5f, -1.5f);
            vertices[4] = new Vector2(-3.5f, -1.45f);
            vertices[5] = new Vector2(3.45f, -1.45f);
            vertices[6] = new Vector2(3.45f, 1.45f);
            vertices[7] = new Vector2(-3.45f, 1.45f);

            for (int i = 0; i < 8; i++)
                vertices[i] *= 10;

            LinkedList<Vertices> vertexSet = new LinkedList<Vertices>();
            vertexSet.AddAll(EarclipDecomposer.ConvexPartition(new Vertices(vertices)));

            foreach (Vertices v in vertexSet)
            {
                Body b = BodyFactory.CreatePolygon(world, v, 1f, position);
                b.BodyType = BodyType.Static;
                b.Rotation = rotation;

                Bodies.Add(b);
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Updates the prayer viewport to show/include/remove the
        /// top-down views to fit the current view.
        /// </summary>
        private void UpdatePrayers()
        {
            // Build up a list of ones to remove
            LinkedList<Prayer> oldKeys = new LinkedList<Prayer>();
            oldKeys.AddAll(prayerViews.Keys);

            // Loop through the prayers
            float x = Padding;

            foreach (Prayer prayer in Game.State.Prayers)
            {
                // Ignore invisible prayers
                if (!prayer.IsAccepted)
                    continue;

                // See if we have the view
                if (!prayerViews.Contains(prayer))
                {
                    // We need to create the top-down view
                    TopDownViewport tdv = new TopDownViewport(prayer.Board);
                    tdv.BlockFilter = FilterConstruction;

                    // Set the value
                    prayerViews[prayer] = tdv;
                    prayerViewport.Add(tdv);
                }
                else
                {
                    // Remove this from the to-remove (old) list
                    oldKeys.Remove(prayer);
                }

                // Change the location of the viewport
                TopDownViewport v = prayerViews[prayer];
                v.Point = new PointF(x, Padding);

                // Adjust the size based on how close the mouse is to
                // viewport.
                float size = 8;
                float left = Math.Abs(mousePoint.X - v.Point.X);
                float right =
                    Math.Abs(mousePoint.X - (v.Point.X + v.Size.Width));

                // Average these two to get the midpoint
                float average = (left + right) / 2;

                // Only make a different if we are with 64 of it
                if (average <= 64)
                {
                    float ratio = (64 - average) / 64;
                    size += ratio * 8;
                }

                v.BlockHeight = v.BlockWidth = size;

                // Update the new x coordinate
                v.Size = v.Extents.Size;
                x += Padding + v.Size.Width;
            }

            // Anything left in the old list needs to be removed
            foreach (Prayer prayer in oldKeys)
            {
                // Get the viewport
                TopDownViewport ov = prayerViews[prayer];
                prayerViewport.Remove(ov);
                prayerViews.Remove(prayer);
            }
        }
Exemplo n.º 14
0
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(backgroundLight ? LIGHT : DARK);

            Matrix p = camera.Projection;
            Matrix v = camera.View;

            if (cameraView == 2)
            {
                float orientation = controller != null && controller.InReverse ? car.Pose.Orientation + MathHelper.Pi : car.Pose.Orientation;
                Vector2 position = Car.GetCenterPosition(car.Pose);
                Vector2 headingVector = new Vector2((float)Math.Cos(orientation), (float)Math.Sin(orientation));
                float offset = 14f;
                float height = 10f;
                v = Matrix.CreateLookAt(new Vector3(position + -offset * headingVector, height), new Vector3(position + offset * headingVector, 0f), Vector3.UnitZ);
            }
            else if (cameraView == 3)
            {
                float or = car.Pose.Orientation + MathHelper.ToRadians(120f);
                Vector2 headingVector = new Vector2((float)Math.Cos(or), (float)Math.Sin(or));
                v = Matrix.CreateLookAt(new Vector3(car.Pose.Position + -10f * headingVector, 5f), new Vector3(Car.GetCenterPosition(car.Pose), 0f), Vector3.UnitZ);
            }
            else if (cameraView == 4)
            {
                float or = goalPose.Orientation;
                Vector2 headingVector = new Vector2((float)Math.Cos(or), (float)Math.Sin(or));
                v = Matrix.CreateLookAt(new Vector3(goalPose.Position + 10f * headingVector, 20f), new Vector3(Car.GetCenterPosition(car.Pose), 0f), Vector3.UnitZ);
            }
            else if (cameraView == 5)
            {
                v = Matrix.CreateLookAt(new Vector3(Car.GetCenterPosition(car.Pose), 20f), new Vector3(Car.GetCenterPosition(car.Pose), 0f), Vector3.UnitY);
                if (rotateCar)
                    v *= Matrix.CreateRotationZ(-car.Body.Rotation + MathHelper.PiOver2);
            }

            if (gridDone && (drawGrid || drawVoro || drawHeur))
            {
                basicEffect.World = Matrix.Identity;
                basicEffect.View = v;
                basicEffect.Projection = p;
                spriteBatch.Begin(0, null, SamplerState.PointClamp, DepthStencilState.DepthRead, RasterizerState.CullNone, basicEffect);

                if (drawHeur)
                    HybridAStar.Draw(spriteBatch);
                else
                    grid.Draw(spriteBatch, drawVoro);

                spriteBatch.End();
            }

            debug.BeginCustomDraw(ref p, ref v);

            debug.DrawSolidCircle(Car.GetFrontAxlePosition(car.Pose), 0.2f, Color.Green);

            if ((pathSearching && watchSearch || pathSearchingDone && drawSearch) && HybridAStar.Expanded != null && HybridAStar.Expanded.Count > 0)
            {
                LinkedList<HybridAStar.Node> expanded = new LinkedList<HybridAStar.Node>();
                lock (HybridAStar.Expanded)
                {
                    expanded.AddAll(HybridAStar.Expanded);
                }

                float pathLength = expanded.Last.f;
                foreach (HybridAStar.Node n in expanded)
                {
                    if (pathDone && n.rsIndex >= 0)
                    {
                        for (int i = n.rsIndex; i < poses.Count - 1; i++)
                            debug.DrawSegment(poses[i].Position, poses[i + 1].Position, Color.Purple, 0.02f);
                    }
                    else if (n.from != null)
                    {
                        Color color;
                        if (n.cell.rev == 0)
                            color = Color.Lerp(Color.Orange, Color.Green, n.g / pathLength);
                        else
                            color = Color.Lerp(Color.Blue, Color.Cyan, n.g / pathLength);

                        debug.DrawSegment(n.from.pose.Position, n.pose.Position, color, 0.02f);
                    }
                }
            }

            if (pathDone)
            {
                if (drawPath)
                {
                    for (int i = 0; i < poses.Count - 1; i++)
                    {
                        Color c = poses[i].Gear == Gear.Forward ? Color.Blue : Color.Red;
                        debug.DrawSegment(poses[i].Position, poses[i + 1].Position, c, 0.04f);
                        debug.DrawPoint(poses[i].Position, 0.1f, c * 0.5f);
                    }
                }
            }

            if (pathSearchingDone && !pathSmoothDone && (drawSmoothedPath || drawController))
                Smoother.Draw(debug);

            if (pathSmoothDone)
            {
                if (drawFrontPath && controller.FrontPath != null)
                {
                    int num = controller.FrontPath.Count;
                    for (int i = 0; i < num - 1; i++)
                    {
                        if (controller.FrontPath[i].Gear == Gear.Forward)
                            debug.DrawSegment(controller.FrontPath[i].Position, controller.FrontPath[i + 1].Position, Color.DarkOrange);
                        else
                            debug.DrawSegment(controller.ReverseFrontPath[i].Position, controller.ReverseFrontPath[i + 1].Position, Color.Cyan);
                    }
                }

                if (drawSmoothedPath)
                {
                    for (int i = 0; i < smoothedPath.Count - 1; i++)
                    {
                        debug.DrawSegment(smoothedPath[i].Position, smoothedPath[i + 1].Position, smoothedPath[i].Gear == Gear.Forward ? Color.DarkGreen : Color.Red, 0.04f);
                        //if (Smoother.UnsafeIndices != null && Smoother.UnsafeIndices.Contains(i))
                            //debug.DrawCircle(smoothedPath[i].Position, 0.2f, Color.Orange);
                    }
                }

                if (drawController)
                    controller.Draw(debug);
            }

            if (drawStart)
                startPose.DrawPose(debug, new Color(0f, 1f, 0f, 0.9f), 1.1f);
            if (drawGoal)
                goalPose.DrawPose(debug, new Color(1f, 0f, 0f, 0.9f), 1.1f);

            if (drawCurrent)
            {
                if (pathSmoothDone && controller.State != StanleyFSMController.ControllerState.MissionComplete)
                {
                    debug.DrawCircle(controller.ClosestPoint, 0.1f, controller.InReverse ? Color.Aqua : Color.Orange);
                    if (controller.InReverse) debug.DrawCircle(controller.FakeFrontAxle, 0.2f, Color.Aqua);
                }

                car.Pose.DrawPose(debug, 0.2f, Color.Red);
            }

            debug.EndCustomDraw();

            if (drawDebugData)
                debug.RenderDebugData(ref p, ref v);

            if (drawCar)
                car.Draw(v, p);

            if (showDebugInfo)
            {
                string info = String.Format("Speed: {0:0.0}", Math.Round(car.SpeedMPH, 1));
                if (pathSmoothDone)
                {
                    info += String.Format("\nGas: {0:0.00}", Math.Round(currentControls.Gas * 100f, 2));
                    info += String.Format("\nBrake: {0:0.00}", Math.Round(currentControls.Brake * 100f, 2));
                    info += String.Format("\nCTE: {0:0.0000}", Math.Round(controller.CrossTrackError, 4));
                    info += "\n" + controller.State.ToString();
                    info += "\n" + controller.DebugInfo;
                }
                spriteBatch.Begin();
                spriteBatch.DrawString(font, info, new Vector2(8, 4), !backgroundLight ? LIGHT : DARK);
                spriteBatch.End();
            }

            if (showDashboard)
                dashboard.Draw(gameTime);

            base.Draw(gameTime);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Random grabs or drops a block on the board.
        /// </summary>
        private void ChangeBoard(UpdateArgs args)
        {
            // Loop through the blocks to see if they are too high. If
            // they are, remove them.
            LinkedList<Block> tmpBlocks = new LinkedList<Block>();
            tmpBlocks.AddAll(blocks);

            foreach (Block b in tmpBlocks)
            {
                if (b.BottomPosition > 10)
                {
                    stacks[b].Remove(b);
                    blocks.Remove(b);
                    stacks.Remove(b);
                }
            }

            // Decrement the counter for the timeout
            secondsUntilChange -= args.SecondsSinceLastUpdate;

            if (secondsUntilChange > 0)
                // We aren't changing anything
                return;

            // Reset it
            secondsUntilChange = Entropy.NextDouble() * 2;

            // Pick a random coordinate
            int x = Entropy.Next(0, BoardColumns);
            int y = Entropy.Next(0, BoardRows);
            BlockStack stack = board[x, y];

            // Make sure we aren't already doing something here
            foreach (Block b in blocks)
                if (stacks[b] == stack)
                    // Don't bother this time
                    return;

            // We have a stack, decide if we are going to drop or grab
            // something from the stack.
            bool drop = Entropy.Next(0, 2) == 0;

            if (stack.Count > 5)
                // Don't go over 5 high
                drop = false;

            if (stack.Count == 1)
                // Don't go below 1 high
                drop = true;

            // Figure out what to do
            if (drop)
            {
                // Create a new block
                Block nb = new Block(RandomBlock());
                nb.BottomPosition = 10;
                nb.Vector = Constants.DroppedVector;
                nb.Mass = Constants.BlockMass;
                nb.IsMoving = true;
                nb.CastsShadows = true;
                nb.Height = 1;
                stack.Add(nb);
            }
            else
            {
                // Grab the top block
                Block tb = stack.TopBlock;
                tb.Vector = -Constants.DroppedVector;
                tb.Mass = 0;
                tb.IsMoving = true;
            }
        }