示例#1
0
        public void IllegalAsciiArt1()
        {
            List <string> results = new List <string>();

            StartPoint <int>       s      = Helpers.GetStartpointCounter(1, 15);
            TaskNode <int, string> filter = Helpers.GetFilter();
            EndPoint <string>      n      = Helpers.GetEndpoint(results);

            try
            {
                Flow flow = Flow.FromAsciiArt(@"
   a----->b->c
     <--
",
                                              new Dictionary <char, TaskNode>()
                {
                    { 'a', s },
                    { 'b', filter },
                    { 'c', n }
                }
                                              );
            }
            catch (InvalidOperationException)
            {
                return;
            }
            Assert.Fail("loose arrows should throw exception");
        }
示例#2
0
        public void ThreeStepWithFilter()
        {
            List <string>    results = new List <string>();
            StartPoint <int> s       = Helpers.GetStartpointCounter(1, 100);
            // pass only numbers divisible by three with no 2 in them
            // Output in
            TaskNode <int, string> filter = Helpers.GetFilter();

            filter.ItemProcessed += new EventHandler <TaskNode.ItemEventArgs>(EndItemProcessed);

            EndPoint <string> n = Helpers.GetEndpoint(results);

            Flow flow = Helpers.ConnectStartFilterEnd(s, filter, n);

            flow.Start();
            flow.RunToCompletion();

            Assert.Contains(flow.Status, new List <RunStatus>()
            {
                RunStatus.Stopped, RunStatus.Stopping
            });

            Assert.AreEqual(27, results.Count);
            Assert.AreEqual(results.Count, n.ItemsProcessed);
            Assert.AreEqual(1, s.ItemsProcessed);
            Console.WriteLine(flow.GetStateSnapshot());
            Assert.Greater(s.TotalSecondsProcessing, 0);
            Assert.Greater(filter.TotalSecondsProcessing, 0);
            Assert.Greater(filter.TotalSecondsBlocked, 0);

            // Each node works with one thread, so order is maintained, so:
            Assert.AreEqual('3', results[0][0]);
        }
示例#3
0
        public void LegalAsciiArtParallel()
        {
            List <string> results1 = new List <string>();
            List <string> results2 = new List <string>();

            StartPoint <int>       s1      = Helpers.GetStartpointCounter(1, 15);
            StartPoint <int>       s2      = Helpers.GetStartpointCounter(5, 35);
            TaskNode <int, string> filter1 = Helpers.GetFilter();
            TaskNode <int, string> filter2 = Helpers.GetFilter();
            EndPoint <string>      n1      = Helpers.GetEndpoint(results1);
            EndPoint <string>      n2      = Helpers.GetEndpoint(results2);

            n2.ThreadNumber = 3;

            Flow flow = Flow.FromAsciiArt(@"
a-->b->c
d->e--->f
",
                                          new Dictionary <char, TaskNode>()
            {
                { 'a', s1 },
                { 'b', filter1 },
                { 'c', n1 },
                { 'd', s2 },
                { 'e', filter2 },
                { 'f', n2 }
            }
                                          );

            flow.Start();
            flow.RunToCompletion();

            Assert.AreEqual(4, results1.Count);
            Assert.AreEqual(6, results2.Count);
        }
示例#4
0
        public void StartingAndStopping()
        {
            StartPoint <int> s = Helpers.GetStartpointCounter(1, 15);
            // pass only numbers divisible by three with no 2 in them
            // Output in
            TaskNode <int, string> filter = Helpers.GetFilter();

            filter.ThreadNumber = 2;

            Collector <string> collect = new Collector <string>();

            filter.ItemProcessed += new EventHandler <TaskNode.ItemEventArgs>(StopFlowItemProcessed);
            Flow flow = Flow.FromAsciiArt("c->d--->e", s, filter, collect);

            flow.Start();
            // Flow will be stopped from evnt handler
            // Give it time to do it wrong:
            Thread.Sleep(100);
            Assert.Greater(collect.Items.Count, 0);
            Assert.Less(collect.Items.Count, 4);
            flow.RunToCompletion();
            try
            {
                Console.WriteLine(flow.Status);
                //flow.Start();
                //Assert.Fail("An exception should be thrown when starting a stopped flow");
            }
            catch (InvalidOperationException)
            {
                //noop
            }
        }
示例#5
0
 public RUTaskNode(WFTEditor wftEditor, TaskNode selectedTaskNode, string operateType)
 {
     this.mainWindow      = wftEditor;
     this.currentTaskNode = selectedTaskNode;
     this.operate         = operateType;
     this.associateLines  = wftEditor.viewPanel.shapeData.FindAssociatedLine(selectedTaskNode);
 }
示例#6
0
        public void KeepOrder2()
        {
            List <int>          results = new List <int>();
            Random              r       = new Random();
            StartPoint <int>    s       = Helpers.GetStartpointCounter(1, 50);
            TaskNode <int, int> process = new TaskNode <int, int>(
                (int input, IWritableQueue <int> output) =>
            {
                int sleeptime = r.Next(50);
                Thread.Sleep(sleeptime);
                output.Send(input);
            }
                )
            {
                ThreadNumber = 5, KeepOrder = true
            };
            Collector <int> n = new Collector <int>();
            Flow            f = Flow.FromAsciiArt("c<----b<---0a", new Dictionary <char, TaskNode>()
            {
                { 'a', s }, { 'b', process }, { 'c', n }
            });

            f.Start();
            f.RunToCompletion();
            int vorig = 0;

            foreach (var item in n.Items)
            {
                Assert.AreEqual(vorig + 1, item);
                vorig = item;
            }
        }
        public override void ExecuteRecursive(TaskExecutionNode node)
        {
            //Debugger.Break();

            var assemblyProviders = new IAssemblyTaskProvider[]
            {
                new MsTestAssemblyTaskProvider(),
                new NUnitAssemblyTaskProvider(),
                new XUnitAssemblyTaskProvider()
            };
            var classProviders = new IClassTaskProvider[]
            {
                new MsTestClassTaskProvider(),
                new NUnitClassTaskProvider(),
                new XUnitClassTaskProvider()
            };
            var methodProviders = new IMethodTaskProvider[]
            {
                new MsTestMethodTaskProvider(),
                new NUnitMethodTaskProvider(),
                new XUnitMethodTaskProvider()
            };

            var taskEnvironment = new TaskEnvironment(Server, assemblyProviders, classProviders, methodProviders);
            var taskNode = new TaskNode(node, taskEnvironment);

            foreach (var silverlightTaskNode in taskNode.GetSilverlightTasks())
            {
                silverlightTaskNode.Execute(Execute);
            }
        }
示例#8
0
 public static void ReorganizeFiveTasks(TaskNode T0, TaskNode T1, TaskNode T2, TaskNode T3, TaskNode T4)
 {
     // Remove connections
     T0.removeConnection(Direction.Right);
     T1.removeConnection(Direction.Left);
     T1.removeConnection(Direction.Right);
     T2.removeConnection(Direction.Left);
     T2.removeConnection(Direction.Right);
     T3.removeConnection(Direction.Left);
     T3.removeConnection(Direction.Right);
     T4.removeConnection(Direction.Left);
     // Modify nodes
     T0.setAsTerminal();
     T1.setAsTerminal();
     T2.setAsTerminal();
     T3.setAsTerminal();
     // Reorganize connections
     T0.setConnection(Direction.Up, T1);
     T0.setConnection(Direction.Down, T3);
     T1.setConnection(Direction.Down, T0);
     T1.setConnection(Direction.Right, T2);
     T2.setConnection(Direction.Left, T1);
     T3.setConnection(Direction.Up, T0);
     T3.setConnection(Direction.Right, T4);
     T4.setConnection(Direction.Left, T4);
 }
示例#9
0
        /// <summary>
        ///   Generates a collection of active task nodes under this task. Used for debugging only.
        /// </summary>
        /// <param name="agentData"> Agent data. </param>
        /// <param name="taskNode"> Task node this task is located in. </param>
        /// <param name="activeTasks"> Collection of active task nodes. </param>
        public override void GetActiveTasks(
            IAgentData agentData, TaskNode taskNode, ref ICollection <TaskNode> activeTasks)
        {
            Data data = agentData.CurrentTaskData as Data;

            if (data == null)
            {
                throw new ArgumentException(string.Format("Expected parallel data for task '{0}'.", this.Name));
            }

            // Check if selector has an active child.
            if (data.RunningChildren.Count == 0)
            {
                return;
            }

            // Add task to active tasks and collect active tasks of active child.
            ++agentData.CurrentDeciderLevel;
            foreach (int childIdx in data.RunningChildren)
            {
                TaskNode childTaskNode = taskNode.CreateChildNode(this.Children[childIdx], childIdx);
                activeTasks.Add(childTaskNode);

                agentData.CurrentTaskData = data.ChildrenData[childIdx];
                this.Children[childIdx].GetActiveTasks(agentData, childTaskNode, ref activeTasks);
            }

            --agentData.CurrentDeciderLevel;
        }
示例#10
0
        internal static TaskNode <int, string> GetFilter()
        {
            TaskNode <int, string> filter = new TaskNode <int, string>(
                (int i, IWritableQueue <string> word) =>
            {
                if (i % 3 != 0)
                {
                    return;
                }
                string formattedNumber = i.ToString("###.00", CultureInfo.InvariantCulture);
                if (formattedNumber.Contains("2"))
                {
                    return;
                }
                if (i == 3)
                {
                    Thread.Sleep(100);
                }
                word.Send(formattedNumber);
            }

                );

            return(filter);
        }
示例#11
0
        /// <summary>Removes the waiter task from the linked list.</summary>
        /// <param name="task">The task to remove.</param>
        /// <returns>true if the waiter was in the list; otherwise, false.</returns>
        private bool RemoveAsyncWaiter(TaskNode task)
        {
            Debug.Assert(task != null, "Expected non-null task");
            Debug.Assert(m_lock.IsAcquired, "Requires the lock be held");

            // Is the task in the list?  To be in the list, either it's the head or it has a predecessor that's in the list.
            bool wasInList = m_asyncHead == task || task.Prev != null;

            // Remove it from the linked list
            if (task.Next != null)
            {
                task.Next.Prev = task.Prev;
            }
            if (task.Prev != null)
            {
                task.Prev.Next = task.Next;
            }
            if (m_asyncHead == task)
            {
                m_asyncHead = task.Next;
            }
            if (m_asyncTail == task)
            {
                m_asyncTail = task.Prev;
            }
            Debug.Assert((m_asyncHead == null) == (m_asyncTail == null), "Head is null iff tail is null");

            // Make sure not to leak
            task.Next = task.Prev = null;

            // Return whether the task was in the list
            return(wasInList);
        }
示例#12
0
        /// <summary>Creates a new task and stores it into the async waiters list.</summary>
        /// <returns>The created task.</returns>
        private TaskNode CreateAndAddAsyncWaiter()
        {
            Debug.Assert(m_lock.IsAcquired, "Requires the lock be held");

            // Create the task
            var task = new TaskNode();

            // Add it to the linked list
            if (m_asyncHead == null)
            {
                Debug.Assert(m_asyncTail == null, "If head is null, so too should be tail");
                m_asyncHead = task;
                m_asyncTail = task;
            }
            else
            {
                Debug.Assert(m_asyncTail != null, "If head is not null, neither should be tail");
                m_asyncTail.Next = task;
                task.Prev        = m_asyncTail;
                m_asyncTail      = task;
            }

            // Hand it back
            return(task);
        }
示例#13
0
 public void AssignTask(TaskNode task, int currentTime)
 {
     currentTask = task;
     if (task != null)
     {
         task.UpdateEST();
         TaskList.Add(task);
         if (currentTime + task.SimulatedExecutionTime < task.EarliestStartTime + task.SimulatedExecutionTime)
         {
             FinishTime = task.EarliestStartTime + task.SimulatedExecutionTime;
         }
         else
         {
             FinishTime = currentTime + task.SimulatedExecutionTime;
             foreach (var item in task.ChildNodes)
             {
                 if (item.EarliestStartTime < currentTime + task.SimulatedExecutionTime)
                 {
                     item.UpdateEST();
                 }
             }
         }
         task.FinishTime = FinishTime;
     }
 }
示例#14
0
            public void Backpropagate(int score)
            {
                int      currentPlayerID = Game.CurrentPlayer.PlayerId;
                TaskNode node            = this;


                while (node.Parent != null)
                {
                    if (node.Parent.Game.CurrentPlayer.PlayerId == currentPlayerID)
                    {
                        node.UpdateScore(score);
                    }
                    else
                    {
                        if (score == 0)
                        {
                            node.UpdateScore(1);
                        }
                        else
                        {
                            node.UpdateScore(0);
                        }
                    }
                    node = node.Parent;
                }
                node.TotNumVisits++;
            }
示例#15
0
 public BranchWorker(int workerId, int finishTime, List <TaskNode> taskList, TaskNode currentTask)
 {
     this.WorkerId    = workerId;
     this.FinishTime  = finishTime;
     this.TaskList    = taskList;
     this.currentTask = currentTask;
 }
示例#16
0
        public TestOracle(TaskNode goalTaskNode, MessageUnitList messages)
        {
            // define task operator only one time
            if (mapOperator == null)
            {
                MapTaskOperators();
            }

            // Must be a goal node & has child nodes
            if (goalTaskNode.Type == NODE_TYPE.GOAL &&
                goalTaskNode.HasChildNodes)
            {
                // initialize
                _goalTaskNode = goalTaskNode;
                //_taskNodeList = goalTaskNode.ChildNodes;
                _messages = messages;

                // Add all task nodes
                this.Clear();

                foreach (TaskNode tNode in goalTaskNode.ChildNodes)
                {
                    this.Add(tNode);
                }
            }
            else
            {
                throw new ApplicationException("Test oracle must take a goal type task node which contains child nodes.");
            }
        }
示例#17
0
            public TaskNode SelectNode()
            {
                //Console.WriteLine("---------Selection--------");



                if (PossibleActions.Count == 0 && Children.Count > 0)                //有子節點的狀況,且第一層都建完
                {
                    double   candidateScore = Double.MinValue;
                    TaskNode candidate      = null;

                    foreach (TaskNode child in Children)
                    {
                        double childScore = child.UCB1Score();
                        if (childScore > candidateScore)
                        {
                            candidateScore = childScore;
                            candidate      = child;
                        }
                    }

                    return(candidate.SelectNode());
                }

                return(this);                //沒有子節點
            }
示例#18
0
            public void Backpropagate(int score)
            {
                //Console.WriteLine("---------Back---------");
                int      currentPlayerID = Game.CurrentPlayer.PlayerId;
                TaskNode node            = this;

                // While the node has a parent, backpropagate the result of the simulation up the game tree
                while (node.Parent != null)
                {
                    if (node.Parent.Game.CurrentPlayer.PlayerId == currentPlayerID)
                    {
                        node.UpdateScore(score);
                    }
                    else
                    {
                        if (score == 0)
                        {
                            node.UpdateScore(1);
                        }
                        else
                        {
                            node.UpdateScore(0);
                        }
                    }
                    node = node.Parent;
                }
                node.TotNumVisits++;
            }
示例#19
0
        public void ThreeStepWithMultilineAsciiArt()
        {
            List <string> results = new List <string>();

            StartPoint <int>       s      = Helpers.GetStartpointCounter(1, 15);
            TaskNode <int, string> filter = Helpers.GetFilter();
            EndPoint <string>      n      = Helpers.GetEndpoint(results);

            Flow flow = Flow.FromAsciiArt(@"
   a
   |
   V 
   b
   |  
   +->c",
                                          new Dictionary <char, TaskNode>()
            {
                { 'a', s },
                { 'b', filter },
                { 'c', n }
            }
                                          );

            flow.Start();
            flow.RunToCompletion();
            Assert.AreEqual(4, results.Count);

            string outputArt = flow.GetStateSnapshot().ToStringAsciiArt();

            Assert.IsFalse(string.IsNullOrEmpty(outputArt));
            Console.WriteLine(outputArt);
        }
示例#20
0
        public void ThreeStepWithInputPoint()
        {
            List <string>          results = new List <string>();
            InputPoint <int>       s       = new InputPoint <int>();
            TaskNode <int, string> filter  = Helpers.GetFilter();

            EndPoint <string> n = Helpers.GetEndpoint(results);

            Flow flow = Helpers.ConnectStartFilterEnd(s, filter, n);

            flow.Start();
            s.Send(1, 2, 3, 4, 5, 6, 7, 8);
            s.Send(new int[] { 9, 10, 11, 12, 13, 14, 15 });
            flow.RunToCompletion();
            Assert.AreEqual(4, results.Count);
            Assert.AreEqual(15, filter.ItemsProcessed);
            Assert.AreEqual(RunStatus.Running, n.Status);

            s.CloseEntrance();
            flow.RunToCompletion();
            // at this point, the flow and some nodes may still be running or stopping,
            // the data items have left the flow, but the nodes can still be in the process of stopping
            Assert.Contains(n.Status, new List <RunStatus>()
            {
                RunStatus.Running, RunStatus.Stopping, RunStatus.Stopped
            });

            // after a small wait, everything should be in the Stopped status
            Thread.Sleep(100);
            Assert.AreEqual(RunStatus.Stopped, n.Status);
        }
示例#21
0
        public override void ExecuteRecursive(TaskExecutionNode node)
        {
            //Debugger.Break();

            var assemblyProviders = new IAssemblyTaskProvider[]
            {
                new MsTestAssemblyTaskProvider(),
                new NUnitAssemblyTaskProvider(),
                new XUnitAssemblyTaskProvider()
            };
            var classProviders = new IClassTaskProvider[]
            {
                new MsTestClassTaskProvider(),
                new NUnitClassTaskProvider(),
                new XUnitClassTaskProvider()
            };
            var methodProviders = new IMethodTaskProvider[]
            {
                new MsTestMethodTaskProvider(),
                new NUnitMethodTaskProvider(),
                new XUnitMethodTaskProvider()
            };

            var taskEnvironment = new TaskEnvironment(Server, assemblyProviders, classProviders, methodProviders);
            var taskNode        = new TaskNode(node, taskEnvironment);

            foreach (var silverlightTaskNode in taskNode.GetSilverlightTasks())
            {
                silverlightTaskNode.Execute(Execute);
            }
        }
示例#22
0
 /// <summary>
 ///   Gets the active tasks of the passed child. Does no index range checking.
 /// </summary>
 /// <param name="childIdx"> Child index. Has to be in correct range. </param>
 /// <param name="agentData"> Agent data. </param>
 /// <param name="childTaskNode"> Task node of child. </param>
 /// <param name="activeTasks"> Collection of active tasks. </param>
 protected void GetActiveChildTasks(
     int childIdx, IAgentData agentData, TaskNode childTaskNode, ref ICollection <TaskNode> activeTasks)
 {
     ++agentData.CurrentDeciderLevel;
     this.children[childIdx].GetActiveTasks(agentData, childTaskNode, ref activeTasks);
     --agentData.CurrentDeciderLevel;
 }
示例#23
0
    public static List <TaskNode> GetTaskNodes(int projectID)
    {
        var             result = Database.GetProjectTasks(projectID);
        List <task>     tasks  = result.ToList();
        List <TaskNode> nodes  = new List <TaskNode>();
        TaskNode        tempNode;
        bool            added;

        // get rootnodes from tasks
        for (int i = 0; i < tasks.Count; i++)
        {
            if (tasks.ElementAt(i).task_id == null)
            {
                tempNode = new TaskNode(tasks.ElementAt(i).id.ToString(), tasks.ElementAt(i).name);
                nodes.Add(tempNode);
                tasks.RemoveAt(i);
                i--;
            }
        }


        // arrange rest of the list into nodetrees
        while (tasks.Count > 0)
        {
            int initialCount = tasks.Count;
            for (int i = 0; i < tasks.Count; i++)
            {
                for (int x = 0; x < nodes.Count; x++)
                {
                    System.Diagnostics.Debug.WriteLine("i:" + i + "x:" + x);
                    System.Diagnostics.Debug.WriteLine("tasks.Count:" + tasks.Count);
                    tempNode = new TaskNode(tasks.ElementAt(i).id.ToString(), tasks.ElementAt(i).name, tasks.ElementAt(i).task_id.ToString());
                    added    = nodes.ElementAt(x).TryAddToParent(tempNode);
                    if (added)
                    {
                        tasks.RemoveAt(i);
                        if (i == tasks.Count)
                        {
                            i--;
                        }
                        if (tasks.Count == 0)
                        {
                            break;
                        }
                    }
                }
                if (tasks.Count == 0)
                {
                    break;
                }
            }
            // make sure the loop is not infinite
            if (tasks.Count == initialCount)
            {
                throw new ApplicationException("GetTaskNodes can not arrange tasks into nodes");
            }
        }

        return(nodes);
    }
示例#24
0
        public TaskSetTransferModel Get(Guid Id)
        {
            var unmapped = dataProvider.Get(Id);
            var mapped   = new TaskSetTransferModel
            {
                Id    = unmapped.Id,
                Tasks = new List <TaskNode>()
            };

            foreach (var item in unmapped.Tasks)
            {
                var mappedItem = new TaskNode
                {
                    AssignedUser = item.AssignedUser,
                    EstimatedCompletionTimespan = item.EstimatedCompletionTimespan,
                    OutNeighbors = new List <Guid>(item.OutNeighbors),
                    InNeighbors  = new List <Guid>(item.InNeighbors),
                    ParentId     = item.ParentId,
                    TaskGraphId  = item.TaskGraphId,
                    WorkspaceId  = item.WorkspaceId,
                    IsRoot       = item.IsRoot,
                    Data         = new TaskData
                    {
                        CurrentStatus = item.Task.CurrentStatus,
                        Description   = item.Task.Description,
                        Id            = item.Task.Id,
                        Name          = item.Task.Name
                    }
                };
                mapped.Tasks.Add(mappedItem);
            }

            return(mapped);
        }
示例#25
0
        /// <summary>Performs the asynchronous wait.</summary>
        /// <param name="asyncWaiter">The asynchronous waiter.</param>
        /// <param name="millisecondsTimeout">The timeout.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The task to return to the caller.</returns>
        private async Task <bool> WaitUntilCountOrTimeoutAsync(TaskNode asyncWaiter, int millisecondsTimeout, CancellationToken cancellationToken)
        {
            Debug.Assert(asyncWaiter != null, "Waiter should have been constructed");
            Debug.Assert(Monitor.IsEntered(m_lockObjAndDisposed), "Requires the lock be held");

            if (millisecondsTimeout != Timeout.Infinite)
            {
                // Wait until either the task is completed, cancellation is requested, or the timeout occurs.
                // We need to ensure that the Task.Delay task is appropriately cleaned up if the await
                // completes due to the asyncWaiter completing, so we use our own token that we can explicitly
                // cancel, and we chain the caller's supplied token into it.
                using (var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
                {
                    if (asyncWaiter == await Task.WhenAny(asyncWaiter, Task.Delay(millisecondsTimeout, cts.Token)).ConfigureAwait(false))
                    {
                        cts.Cancel(); // ensure that the Task.Delay task is cleaned up
                        return(true); // successfully acquired
                    }
                }
            }
            else // millisecondsTimeout == Timeout.Infinite
            {
                // Wait until either the task is completed or cancellation is requested.
                var cancellationTask = new Task(null, TaskCreationOptions.RunContinuationsAsynchronously, promiseStyle: true);
                using (cancellationToken.UnsafeRegister(static s => ((Task)s !).TrySetResult(), cancellationTask))
示例#26
0
        public IHttpActionResult PutTaskNode(int id, TaskNode taskNode)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != taskNode.TaskNodeId)
            {
                return(BadRequest());
            }

            db.Entry(taskNode).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TaskNodeExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
示例#27
0
 public RUTaskNode(WFTEditor wftEditor, TaskNode selectedTaskNode, Point moveBaseOriginal, Point moveBaseFinal)
 {
     this.mainWindow       = wftEditor;
     this.currentTaskNode  = selectedTaskNode;
     this.operate          = "OP_Move";
     this.moveBaseOriginal = moveBaseOriginal;
     this.moveBaseFinal    = moveBaseFinal;
 }
示例#28
0
            } = 0;                                                                  //勝利次數

            public TaskNode(TaskNode parent, PlayerTask action, POGame.POGame game) //TaskNode建構子
            {
                Game            = game;
                Parent          = parent;
                Action          = action;
                PossibleActions = Game.CurrentPlayer.Options();
                Children        = new List <TaskNode>();
            }
示例#29
0
 public static void ReorganizeSixTasks(TaskNode T0, TaskNode T1, TaskNode T2, TaskNode T3, TaskNode T4, TaskNode T5)
 {
     // Remove connections
     T0.removeConnection(Direction.Right);
     T1.removeConnection(Direction.Left);
     T1.removeConnection(Direction.Right);
     T2.removeConnection(Direction.Left);
     T2.removeConnection(Direction.Right);
     T3.removeConnection(Direction.Left);
     T3.removeConnection(Direction.Right);
     T4.removeConnection(Direction.Left);
     T4.removeConnection(Direction.Right);
     T5.removeConnection(Direction.Left);
     // Two ways of reorganizing six tasks with 50% chance each
     if (Random.Range(0.0f, 1.0f) > 0.5f)
     {
         // Modify nodes
         T0.setAsTerminal();
         T1.setAsTerminal();
         T2.setAsTerminal();
         T3.setAsTerminal();
         T4.setAsTerminal();
         // Reorganize connections
         T0.setConnection(Direction.Up, T1);
         T0.setConnection(Direction.Down, T4);
         T1.setConnection(Direction.Down, T0);
         T1.setConnection(Direction.Right, T2);
         T2.setConnection(Direction.Left, T1);
         T2.setConnection(Direction.Right, T3);
         T3.setConnection(Direction.Left, T2);
         T4.setConnection(Direction.Up, T0);
         T4.setConnection(Direction.Right, T5);
         T5.setConnection(Direction.Left, T4);
     }
     else
     {
         // Modify nodes
         T0.setAsTerminal();
         T1.setAsTerminal();
         T3.setAsTerminal();
         // Add new nodes
         FarTaskNode T2new = new FarTaskNode();
         FarTaskNode T4new = new FarTaskNode();
         // Reorganize connections
         T0.setConnection(Direction.Up, T1);
         T0.setConnection(Direction.Down, T3);
         T1.setConnection(Direction.Down, T0);
         T1.setConnection(Direction.Right, T2new);
         T2new.setConnection(Direction.Left, T1);
         T2new.setConnection(Direction.Down, T4new);
         T3.setConnection(Direction.Up, T0);
         T3.setConnection(Direction.Right, T4new);
         T4new.setConnection(Direction.Up, T2new);
         T4new.setConnection(Direction.Right, T5);
         T5.setConnection(Direction.Left, T4new);
     }
 }
示例#30
0
 void StopTask(object data)
 {
     taskNode = null;
     if (isStop)
     {
         return;
     }
     isStop = true;
 }
示例#31
0
        public override int PostTask(TaskNode taskNode, int delay = 0)
        {
            if (taskPump == null)
            {
                return(-1);
            }

            return(taskPump.PostTask(taskNode, delay));
        }
示例#32
0
文件: Helpers.cs 项目: Teun/BatchFlow
 internal static Flow ConnectStartFilterEnd(TaskNode s, TaskNode filter, TaskNode n)
 {
     Flow flow = new Flow();
     flow.AddNode(s);
     flow.AddNode(filter);
     flow.AddNode(n);
     flow.ConnectNodes(s, filter, 0);
     flow.ConnectNodes(filter, n, 0);
     flow.Error += new EventHandler<Flow.ErrorEventArgs>(flow_Error);
     return flow;
 }
 private void AddChildTaskNodeRoleName(List<string> roleNames, TaskNode tn)
 {
     if (tn.Children.Count > 0)
     {
         foreach (TaskNode node in tn.Children)
         {
             roleNames.Add(node.Name);
             this.AddChildTaskNodeRoleName(roleNames, node);
         }
     }
 }
        public override void ExecuteRecursive(TaskExecutionNode node)
        {
            //Debugger.Break();

            var assemblyTaskProviders = UnitTestTaskProviderFactory.GetAssemblyTaskProviders();
            var classTaskProviders = UnitTestTaskProviderFactory.GetClassTaskProviders();
            var methodTaskProviders = UnitTestTaskProviderFactory.GetMethodTaskProviders();

            var taskEnvironment = new TaskEnvironment(Server, assemblyTaskProviders, classTaskProviders, methodTaskProviders);
            var taskNode = new TaskNode(node, taskEnvironment);

            foreach (var silverlightTaskNode in taskNode.GetSilverlightTasks())
            {
                silverlightTaskNode.Execute(Execute);
            }
        }
示例#35
0
文件: Helpers.cs 项目: Teun/BatchFlow
        internal static TaskNode<int, string> GetFilter()
        {
            TaskNode<int, string> filter = new TaskNode<int, string>(
                (int i, IWritableQueue<string> word) =>
                {
                    if (i % 3 != 0) return;
                    string formattedNumber = i.ToString("###.00", CultureInfo.InvariantCulture);
                    if (formattedNumber.Contains("2")) return;
                    if (i == 3) Thread.Sleep(100);
                    word.Send(formattedNumber);
                }

                );

            return filter;
        }
示例#36
0
        public void StopRightInTheMiddle()
        {
            InputPoint<int> inp = new InputPoint<int>();
            TaskNode<int,int> process = new TaskNode<int, int>(
                    (input, output) => output.Send(input)
                        );
            process.ThreadNumber = 2;
            process.KeepOrder = true;
            Collector<int> coll = new Collector<int>();

            Flow flow = Flow.FromAsciiArt("a->b->c",
                inp,
                process,
                coll
                );
            coll.ItemProcessed += (o,a) =>
                {
                    if ((int)a.Item == 0)
                    {
                        flow.Stop();
                    }
                    var state = flow.GetStateSnapshot();
                    Console.WriteLine(state.ToStringAsciiArt());
                };

            flow.Start();
            for (int i = 1; i < 100; i++)
            {
                inp.Send(i);
            }
            inp.Send(0);
            inp.Send(1);
            inp.Send(1);
            inp.Send(1);
            inp.Send(1);
            inp.Send(1);
            inp.Send(1);
            //for (int i = 1; i < 1000; i++)
            //{
            //    inp.Send(i);
            //}
            flow.RunToCompletion();
            Assert.AreEqual(coll.Items.Count,100);
        }
示例#37
0
 public TaskTreeNode(TaskNode taskNode)
 {
     this.taskNode = taskNode;
     base.Text = taskNode.Name;
     if (!string.IsNullOrEmpty(taskNode.ContextmenuAddinTreePath))
     {
         this.ContextmenuAddinTreePath = taskNode.ContextmenuAddinTreePath;
     }
     if (!string.IsNullOrEmpty(taskNode.Icon))
     {
         base.SetIcon(taskNode.Icon);
     }
     lock (assemblys)
     {
         if (LoggingService.IsDebugEnabled)
         {
             LoggingService.DebugFormatted("任务节点的程序集是:{0}", new object[] { taskNode.Assembly });
         }
         if (!string.IsNullOrEmpty(taskNode.Assembly))
         {
             if (!assemblys.ContainsKey(taskNode.Assembly))
             {
                 this.assembly = Assembly.Load(taskNode.Assembly);
                 assemblys.Add(taskNode.Assembly, this.assembly);
                 if (LoggingService.IsDebugEnabled)
                 {
                     LoggingService.DebugFormatted("加载了组件:{0}", new object[] { taskNode.Assembly });
                 }
             }
             else
             {
                 this.assembly = assemblys[taskNode.Assembly];
             }
         }
     }
     if (!(((taskNode.Children.Count <= 0) && !this.EnableAddChild) && string.IsNullOrEmpty(taskNode.LoadChildrenCommand)))
     {
         base.Nodes.Add(new TreeNode("Loading"));
     }
 }
示例#38
0
 public void KeepOrder2()
 {
     List<int> results = new List<int>();
     Random r = new Random();
     StartPoint<int> s = Helpers.GetStartpointCounter(1, 50);
     TaskNode<int, int> process = new TaskNode<int, int>(
         (int input, IWritableQueue<int> output) =>
         {
             int sleeptime = r.Next(50);
             Thread.Sleep(sleeptime);
             output.Send(input);
         }
         ) { ThreadNumber = 5, KeepOrder = true };
     Collector<int> n = new Collector<int>();
     Flow f = Flow.FromAsciiArt("c<----b<---0a", new Dictionary<char, TaskNode>() { { 'a', s }, { 'b', process }, { 'c', n } });
     f.Start();
     f.RunToCompletion();
     int vorig = 0;
     foreach (var item in n.Items)
     {
         Assert.AreEqual(vorig + 1, item);
         vorig = item;
     }
 }
示例#39
0
文件: Flow.cs 项目: Teun/BatchFlow
 /// <summary>
 /// 
 /// </summary>
 /// <param name="publisher"></param>
 /// <param name="reader"></param>
 /// <param name="streamNumber"></param>
 public BoundedBlockingQueue ConnectNodes(TaskNode publisher, TaskNode reader, int streamNumber, int queueSize)
 {
     if(! reader.InType.IsAssignableFrom(publisher.OutTypes[streamNumber]))
     {
         throw new InvalidOperationException(String.Format("The in-stream of the reader ({1}) cannot be assigned from the publisher of type ({0})", publisher.OutTypes[streamNumber].Name, reader.InType.Name));
     }
     Type bbOfT = typeof(BoundedBlockingQueue<>).MakeGenericType(new Type[] { reader.InType });
     BoundedBlockingQueue stream = (BoundedBlockingQueue)Activator.CreateInstance(bbOfT, queueSize);
     publisher.ConnectOutStream(stream, streamNumber, reader.InType);
     reader.ConnectInStream(stream);
     if (String.IsNullOrEmpty(stream.Name)) stream.Name = String.Format("from '{0}' to '{1}'", publisher.Name, reader.Name);
     _streams.Add(stream);
     stream.OwningFlow = this;
     return stream;
 }
示例#40
0
文件: Flow.cs 项目: Teun/BatchFlow
 public BoundedBlockingQueue ConnectNodes(TaskNode publisher, TaskNode reader, int streamNumber)
 {
     return ConnectNodes(publisher, reader, streamNumber, DefaultStreamSize);
 }
示例#41
0
文件: Flow.cs 项目: Teun/BatchFlow
 public void ConnectNodeByJoin(TaskNode start, TaskNode end, int outNr)
 {
     if (end.StreamIn == null)
     {
         throw new InvalidOperationException("Use ConnectNodeByJoin only after connecting the main connection");
     }
     start.ConnectOutStream((IWritableQueue)end.StreamIn, outNr, end.InType);
 }
示例#42
0
文件: Flow.cs 项目: Teun/BatchFlow
 /// <summary>
 /// Add a node to the flow. Nodes may only be included once per flow
 /// </summary>
 /// <param name="newNode"></param>
 public void AddNode(TaskNode newNode, Position position)
 {
     _nodes.Add(newNode);
     if(String.IsNullOrEmpty(newNode.Name )) newNode.Name = "node " + _nodes.Count.ToString();
     newNode.OwningFlow = this;
     newNode.Position = position;
 }
示例#43
0
文件: Flow.cs 项目: Teun/BatchFlow
 public void AddNode(TaskNode newNode)
 {
     AddNode(newNode, Position.Origin);
 }
示例#44
0
 public AssemblyTask(TaskNode node, IAssemblyTaskProvider assemblyTaskProvider)
 {
     Node = node;
     AssemblyTaskProvider = assemblyTaskProvider;
 }
示例#45
0
 public ClassTask(TaskNode node, IClassTaskProvider classTaskProvider)
 {
     Node = node;
     ClassTaskProvider = classTaskProvider;
 }
示例#46
0
 void EndItemProcessed(object sender, TaskNode.ItemEventArgs e)
 {
 }
示例#47
0
文件: Flow.cs 项目: Teun/BatchFlow
 internal void OnError(TaskNode node, Exception exc, object item, ref bool stopProcessing)
 {
     if (Error != null)
     {
         ErrorEventArgs args = new ErrorEventArgs() { Error = exc, ProcessedItem=item, StopProcessing = stopProcessing, Node = node };
         Error(this, args);
         stopProcessing = args.StopProcessing;
     }
     else
     {
         stopProcessing = true;
     }
     if (stopProcessing) _stoppingException = exc;
 }
示例#48
0
 public SilverlightTask(TaskNode node)
 {
     Node = node;
 }
示例#49
0
 void StopFlowItemProcessed(object sender, TaskNode.ItemEventArgs e)
 {
     i++;
     if (i == 3) ((TaskNode)sender).OwningFlow.Stop();
 }
示例#50
0
 public void KeepOrder3()
 {
     List<int> results = new List<int>();
     Random r = new Random();
     StartPoint<int> s = Helpers.GetStartpointCounter(1, 50);
     TaskNode<int, int, int> process = new TaskNode<int, int, int>(
         (input, output1, output2) =>
         {
             int sleeptime = r.Next(50);
             Thread.Sleep(sleeptime);
             if (input % 2 == 0)
             {
                 output1.Send(input);
             }
             else
             {
                 output2.Send(input);
             }
         }
         ) { ThreadNumber = 2, KeepOrder = true };
     Collector<int> n = new Collector<int>();
     Collector<int> n2 = new Collector<int>();
     Flow f = Flow.FromAsciiArt(@"
     a-->b0-->c
     1
     |
     V
     d
     ", new Dictionary<char, TaskNode>() { { 'a', s }, { 'b', process }, { 'c', n }, {'d', n2} });
     f.Start();
     f.RunToCompletion();
     int vorig = 0;
     foreach (var item in n.Items)
     {
         Assert.AreEqual(vorig + 2, item);
         vorig = item;
     }
     vorig = -1;
     foreach (var item in n2.Items)
     {
         Assert.AreEqual(vorig + 2, item);
         vorig = item;
     }
 }
        private void ExecuteSilverlightTasks(TaskExecutionNode node)
        {
            var assemblyTaskProviders = UnitTestTaskProviderFactory.GetAssemblyTaskProviders();
            var classTaskProviders = UnitTestTaskProviderFactory.GetClassTaskProviders();
            var methodTaskProviders = UnitTestTaskProviderFactory.GetMethodTaskProviders();

            var taskEnvironment = new TaskEnvironment(Server, assemblyTaskProviders, classTaskProviders, methodTaskProviders);
            var taskNode = new TaskNode(node, taskEnvironment);

            foreach (var silverlightTaskNode in taskNode.GetSilverlightTasks())
            {
                silverlightTaskNode.Execute(Execute);
            }
        }
示例#52
0
        public void ThreeStepWithMultilineAsciiArt()
        {
            List<string> results1 = new List<string>();
            List<string> results2 = new List<string>();

            StartPoint<int> s = Helpers.GetStartpointCounter(1, 50);
            TaskNode<int, string, string> splitter =
                new TaskNode<int, string, string>(
                    (int i, IWritableQueue<string> o1, IWritableQueue<string> o2) =>
                    {
                        if (i % 3 == 0 || i % 4 == 0 || i % 5 == 0)
                        {
                            // divisible by 3, 4 or 5, go to stream 1
                            o1.Send(i.ToString(CultureInfo.InvariantCulture));
                        }else{
                            // if not, send i and i+1 to stream 2
                            o2.Send(i.ToString());
                            o2.Send((i + 1).ToString(CultureInfo.InvariantCulture));
                        }
                    }
                    );
            EndPoint<string> end1 = Helpers.GetEndpoint(results1);
            EndPoint<string> end2 = Helpers.GetEndpoint(results2);

            Flow flow = Flow.FromAsciiArt(@"
            s--+
               |
               V
               t0->n
               1
               |
               +---->m
            ",
                new Dictionary<char, TaskNode>()
                {
                    {'s', s},
                    {'t', splitter},
                    {'n', end1},
                    {'m', end2}
                }
                );

            flow.Start();
            flow.RunToCompletion();
            Assert.AreEqual(29, results1.Count);
            Assert.AreEqual("50", results1[28]);
            Assert.AreEqual(42, results2.Count);
        }
示例#53
0
 public MethodTask(TaskNode node, IMethodTaskProvider methodTaskProvider)
 {
     Node = node;
     MethodTaskProvider = methodTaskProvider;
 }
示例#54
0
 public static bool IfAuthNode(TaskNode tn)
 {
     SmPrincipal smPrincipal = SecurityUtil.GetSmPrincipal();
     SmIdentity identity = (SmIdentity) smPrincipal.Identity;
     return (((identity.AdminLevel == AdminLevelType.Admin) || (identity.AdminLevel == AdminLevelType.AdminDef)) || smPrincipal.IsInRole(tn.Name));
 }