public static double integrate(func f, System.Collections.Generic.IReadOnlyList <double> init_ticks, double eps1)
        {
            var points = new System.Collections.Generic.Stack <Point>();
            var areas  = new System.Collections.Generic.List <double>();

            foreach (var x in init_ticks)
            {
                points.Push(new Point(x, f(x)));
            }

            var    full_width = init_ticks.Last() - init_ticks.First();
            Point  right;
            double eps = eps1 * 4.0 / full_width;

            while (points.Count > 1)
            {
                //Console.WriteLine(points.Count);
                right = points.Pop();
                var left = points.Peek();
                var mid  = Integration.midpoint(ref left, ref right, f);
                if (Math.Abs(left.f + right.f - mid.f * 2.0) <= eps)
                {
                    areas.Add((left.f + right.f + mid.f * 2.0) * (right.x - left.x) / 4.0);
                }
                else
                {
                    points.Push(mid);
                    points.Push(right);
                }
            }
            areas.Sort(delegate(double x, double y){
                return(Math.Abs(x).CompareTo(Math.Abs(y)));
            });
            return(areas.Sum());
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            int  x   = 5;
            var  st  = new System.Collections.Generic.Stack <int>();
            bool dir = true;

            st.Push(x);
            while (st.Count > 0)
            {
                x = st.Peek();
                st.Pop();
                if ((x > 0) && (dir))
                {
                    st.Push(x);
                    st.Push(x - 1);
                }
                else
                {
                    dir = false;
                }
                if (x != 0)
                {
                    Console.WriteLine(x);
                }
            }
            Console.ReadKey();
            Console.WriteLine();
            f(3);
            Console.ReadKey();
        }
Exemplo n.º 3
0
        public void IEnumerableTest()
        {
            System.Collections.Generic.Stack <int> s =
                new System.Collections.Generic.Stack <int>();
            s.Push(1);
            s.Push(2);

            List <int> items = new List <int>();

            // Uses IEnumerable.GetEnumerator() to return an enumerator instance
            // to use with `foreach`.
            foreach (int i in s)
            {
                items.Add(i);
            }

            // The above code compiles into...

            // using (System.Collections.Generic.Stack<int>.Enumerator enumerator = s.GetEnumerator()) {
            //     while (enumerator.MoveNext())
            //     {
            //         items.Add(enumerator.Current);
            //     }
            // }

            Assert.Equal(new List <int> {
                2, 1
            }, items);
        }
Exemplo n.º 4
0
        //Performs DFS to find node with value
        //returns node with given value
        //returns null if value was not found in graph
        public static GraphNode <T> Search <T>(GraphNode <T> begining, T value)
        {
            System.Collections.Generic.Stack <GraphNode <T> > stack = new System.Collections.Generic.Stack <GraphNode <T> >();
            HashSet <GraphNode <T> > visited = new HashSet <GraphNode <T> >();

            stack.Push(begining);

            while (stack.Count != 0)
            {
                GraphNode <T> node = stack.Pop();

                if (node.Value.Equals(value))
                {
                    return(node);
                }


                if (!visited.Contains(node))
                {
                    visited.Add(node);
                    foreach (GraphNode <T> n in node.Neighbours)
                    {
                        stack.Push(n);
                    }
                }
            }

            return(null);
        }
Exemplo n.º 5
0
        public string DepthFirstSearch(int startValue)
        {
            bool[] visited = new bool[vertices];
            System.Collections.Generic.Stack <GraphNode> stack = new System.Collections.Generic.Stack <GraphNode>();
            StringBuilder sb = new StringBuilder();

            int index = startValue;

            stack.Push(adjLists[index]);

            while (stack.Count > 0)
            {
                var graphNode = stack.Pop();

                index = graphNode.value;
                if (!visited[index])
                {
                    sb.Append(graphNode.value + " ");
                    visited[index] = true;
                }

                for (int i = 0; i < graphNode.Edges.Count; i++)
                {
                    int adjIndex = graphNode.Edges[i];
                    if (!visited[adjIndex])
                    {
                        stack.Push(adjLists[adjIndex]);
                    }
                }
            }

            return(sb.ToString());
        }
Exemplo n.º 6
0
        private Path BuildPath(Node toNode, Dictionary <Node, Node> previousNodes)
        {
            //we will add "toNode" & nodes from "PreviousNodes" to stack
            // and then pop Nodes from stack
            // so we can have the nodes & build the path from "fromNode" to "ToNode" in correct order.
            var stack = new System.Collections.Generic.Stack <Node>();

            stack.Push(toNode);

            previousNodes.TryGetValue(toNode, out var previous);
            while (previous != null)
            {
                stack.Push(previous);
                previous = previousNodes.ContainsKey(previous) ? previousNodes[previous] : null;
            }

            var path = new Path();

            while (stack.Count > 0)
            {
                path.AddNode(stack.Pop().Label);
            }

            return(path);
        }
Exemplo n.º 7
0
        public List <T> PreOrderIterative(Node root)
        {
            if (root == null)
            {
                return(null);
            }

            // Root Left Right
            System.Collections.Generic.Stack <Node> stack = new System.Collections.Generic.Stack <Node>();
            stack.Push(root);

            List <T> res = new List <T>();

            while (stack.Count > 0)
            {
                Node node = stack.Pop();
                res.Add(node.Value);

                if (node.Right != null)
                {
                    stack.Push(node.Right);
                }

                if (node.Left != null)
                {
                    stack.Push(node.Left);
                }
            }

            return(res);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Takes a starting point to find all vertices that can be reached by the starting vertex. Return all reacheable vertice from the start vertex.
        /// </summary>
        /// <param name="start"></param>
        /// <returns></returns>
        public IEnumerable <Vertex <T> > DFS_Visit(T start)
        {
            var startVert = GetVertex(start);
            // To make sure the depth-first search algorithm doesn't re-visit vertices, the visited HashSet keeps track of vertices already visited.
            var visited = new HashSet <Vertex <T> >();
            //A Stack, keeps track of vertices found but not yet visited.
            var stack = new System.Collections.Generic.Stack <Vertex <T> >();

            //Initially stack contains the starting vertex.
            stack.Push(startVert);

            while (stack.Count != 0)
            {
                // The next vertex is popped from stack.
                var currentVert = stack.Pop();
                // If it has already been visited, it is discarded and the next vertex is popped from stack(continue). If it has not been visited, it is added to the set of visited vertices
                if (!visited.Add(currentVert))
                {
                    continue;
                }

                //its unvisited neighbors are added to stack.
                var unvisitNbr = currentVert.GetConnections().Where(n => !visited.Contains(n));
                //visit order is from left to right, if not care about the order remoce Reverse()
                foreach (var next in unvisitNbr.Reverse())
                {
                    stack.Push(next);
                }
            }

            return(visited);
        }
Exemplo n.º 9
0
        /// <summary>
        /// trace back path from destination to source using parent map
        /// </summary>
        /// <param name="graph"></param>
        /// <param name="parentMap"></param>
        /// <param name="source"></param>
        /// <param name="destination"></param>
        /// <returns></returns>
        private ShortestPathResult <T, W> tracePath(WeightedDiGraph <T, W> graph, System.Collections.Generic.Dictionary <T, T> parentMap, T source, T destination)
        {
            //trace the path
            var pathStack = new System.Collections.Generic.Stack <T>();

            pathStack.Push(destination);

            var currentV = destination;

            while (!Equals(currentV, default(T)) && !Equals(parentMap[currentV], default(T)))
            {
                pathStack.Push(parentMap[currentV]);
                currentV = parentMap[currentV];
            }

            //return result
            var resultPath   = new List <T>();
            var resultLength = operators.DefaultValue;

            while (pathStack.Count > 0)
            {
                resultPath.Add(pathStack.Pop());
            }

            for (int i = 0; i < resultPath.Count - 1; i++)
            {
                resultLength = operators.Sum(resultLength,
                                             graph.Vertices[resultPath[i]].OutEdges[graph.Vertices[resultPath[i + 1]]]);
            }

            return(new ShortestPathResult <T, W>(resultPath, resultLength));
        }
        public HashSet <T> DFT <T>(Graph <T> graph, T start)
        {
            var visited = new HashSet <T>();

            if (!graph.Nodes.ContainsKey(start))
            {
                return(visited);
            }

            var stack = new System.Collections.Generic.Stack <T>();

            stack.Push(start);

            while (stack.Count > 0)
            {
                var vertex = stack.Pop();

                if (visited.Contains(vertex))
                {
                    continue;
                }

                visited.Add(vertex);

                foreach (var neighbor in graph.Nodes[vertex])
                {
                    if (!visited.Contains(neighbor.Key))
                    {
                        stack.Push(neighbor.Key);
                    }
                }
            }

            return(visited);
        }
Exemplo n.º 11
0
        static TextTpl ResourceLoader(string input)
        {
            var tp = new TextTpl();

            tp.Children = new List <TextTpl>();
            var stack = new System.Collections.Generic.Stack <TextTpl>();

            stack.Push(tp);
            MatchCollection matchs     = resourceName.Matches(input);
            int             startIndex = 0;

            foreach (Match match in matchs)
            {
                Group group = match.Groups["resourceName"];
                if (group != null)
                {
                    string resourceName = group.Value.Trim();

                    if (resourceName.StartsWith("publish", StringComparison.CurrentCultureIgnoreCase))
                    {
                        var p  = stack.Peek();
                        var pt = new TextTpl();
                        pt.Text     = input.Substring(startIndex, match.Index - startIndex);
                        pt.Children = new List <TextTpl>();
                        p.Children.Add(pt);
                        var tpl = new TextTpl();
                        tpl.IsBegin  = true;
                        tpl.Key      = resourceName.Substring(7).Trim();
                        tpl.Children = new List <TextTpl>();
                        p.Children.Add(tpl);

                        stack.Push(tpl);
                    }
                    else if (resourceName.StartsWith("end", StringComparison.CurrentCultureIgnoreCase))
                    {
                        var resText = input.Substring(startIndex, match.Index - startIndex);
                        var p       = stack.Pop();
                        p.Text = resText;
                    }
                    startIndex = match.Index + match.Length;
                }
            }

            if (startIndex < input.Length)
            {
                var pt = new TextTpl();
                pt.Text     = input.Substring(startIndex);
                pt.Children = new List <TextTpl>();
                tp.Children.Add(pt);
            }
            if (stack.Count > 1)
            {
                tp.Text = "未配置正确请求标签,请检查";
            }
            return(tp);
        }
Exemplo n.º 12
0
        private void btnSettings_Click(object sender, RoutedEventArgs e)
        {
            HomeNavigation selector = ViewLocator.Instance.Get <HomeNavigation>();

            this.transitionContentHome.Content = selector.Templates["Settings"];

            if (history.FirstOrDefault() != "about")
            {
                this.transitionContentHome.AbortTransition();
            }

            history.Push("settings");
        }
Exemplo n.º 13
0
        //non recursive
        public IEnumerator <T> InOrderTraversal()
        {
            if (_head != null)

            {
                // Store the nodes we've skipped in this stack (avoids recursion).
                var stack = new System.Collections.Generic.Stack <BinaryTreeNode <T> >();

                BinaryTreeNode <T> current = _head;

                // When removing recursion, we need to keep track of whether
                // we should be going to the left node or the right nodes next.
                bool goLeftNext = true;

                // Start by pushing Head onto the stack.
                stack.Push(current);

                while (stack.Count > 0)
                {
                    // If we're heading left...
                    if (goLeftNext)
                    {
                        // Push everything but the left-most node to the stack.
                        // // We'll yield the left-most after this block.
                        while (current.Left != null)
                        {
                            stack.Push(current);
                            current = current.Left;
                        }
                    }
                    // Inorder is left->yield->right.
                    yield return(current.Data);

                    // If we can go right, do so.
                    if (current.Right != null)
                    {
                        current = current.Right;
                        // Once we've gone right once, we need to start
                        // going left again.
                        goLeftNext = true;
                    }
                    else
                    {
                        // If we can't go right, then we need to pop off the parent node
                        // so we can process it and then go to its right node.
                        current    = stack.Pop();
                        goLeftNext = false;
                    }
                }
            }
        }
Exemplo n.º 14
0
        private static System.ComponentModel.BindingList <DataModel.MetadataItem> BuildBindingList(
            ActiveQueryBuilder.Core.SQLContext sc
            )
        {
            System.ComponentModel.BindingList <DataModel.MetadataItem> list = new System.ComponentModel.BindingList <DataModel.MetadataItem>( );
            using (var sqlContext = new ActiveQueryBuilder.Core.SQLContext( ))
            {
                sqlContext.Assign(sc);
                //sqlContext.MetadataContainer.LoadingOptions.LoadDefaultDatabaseOnly = false;
                //sqlContext.MetadataContainer.LoadingOptions.LoadSystemObjects = false;

                using (ActiveQueryBuilder.Core.MetadataList miList = new ActiveQueryBuilder.Core.MetadataList(sqlContext.MetadataContainer))
                {
                    miList.Load(ActiveQueryBuilder.Core.MetadataType.All, true);
                    System.Collections.Generic.Stack <StackItem> stack = new System.Collections.Generic.Stack <StackItem>( );
                    stack.Push(new StackItem {
                        list = miList, index = 0, parentID = -1, grandParentID = -1
                    });
                    do
                    {
                        StackItem si = stack.Pop( );
                        ActiveQueryBuilder.Core.MetadataList actualMIList = si.list;
                        int actualIndex    = si.index;
                        int actualParentID = si.grandParentID; // IMPORTANT!!!
                        {
                            for ( ; actualIndex < actualMIList.Count; actualIndex++)
                            {
                                ExtractMetadataItem(list, actualMIList[actualIndex], actualParentID);
                                if (actualMIList[actualIndex].Items.Count > 0) // branch...
                                {
                                    // Push the "next" Item...
                                    stack.Push(new StackItem
                                    {
                                        list          = actualMIList,
                                        index         = actualIndex + 1,
                                        parentID      = list[list.Count - 1].ID,
                                        grandParentID = actualParentID
                                    });
                                    // Reset the loop to process the "actual" Item...
                                    actualParentID = list[list.Count - 1].ID;
                                    actualMIList   = actualMIList[actualIndex].Items;
                                    actualIndex    = -1;
                                }
                            } // for(;;)...
                        }
                    } while(stack.Count > 0);
                } // using()...
            }     // using()...
            return(list);
        }         // buildBindingList(...)
Exemplo n.º 15
0
        public void IterativeStack(System.Collections.Generic.Stack <int> s, int a)
        {
            var v = s.Pop();

            if (s.Count > 0)
            {
                IterativeStack(s, a);
            }
            else
            {
                s.Push(a);
            }
            s.Push(v);
        }
Exemplo n.º 16
0
    private static void chkStack動作()
    {
        Gen::Stack <int> st = new System.Collections.Generic.Stack <int>();

        st.Push(0);
        st.Push(1);
        st.Push(2);
        st.Push(3);

        PrintStack(st);

        Gen::Stack <int> st2 = new System.Collections.Generic.Stack <int>(st.ToArray());

        PrintStack(st2);
    }
Exemplo n.º 17
0
        public static string Decode(string input)
        {
            string result = null;

            System.Collections.Generic.Stack <int>  integerstack = new System.Collections.Generic.Stack <int>();
            System.Collections.Generic.Stack <char> charstack    = new System.Collections.Generic.Stack <char>();

            for (int i = 0; i < input.Length; i++)
            {
                if (char.IsDigit(input[i]))
                {
                    integerstack.Push(input[i]);
                }
                else if (input[i] == '[')
                {
                    charstack.Push('[');
                }
                else if (input[i] == ']')
                {
                    //charstack.pop();
                }

                return(result);
            }
            return(null);
        }
Exemplo n.º 18
0
        /// <summary>
        /// 先需遍历
        /// 先根节点,然后左节点,后右节点
        /// </summary>
        public void Preorder()
        {
            if (tree == null)
            {
                return;
            }

            System.Collections.Generic.Stack <Tree> stack = new System.Collections.Generic.Stack <Tree>();
            Tree node = tree;

            while (node != null || stack.Any())
            {
                if (node != null)
                {
                    stack.Push(node);
                    System.Console.Write(node.Data + " ");
                    node = node.Left;
                }
                else
                {
                    var item = stack.Pop();
                    node = item.Right;
                }
            }
        }
Exemplo n.º 19
0
 private static bool DoOps(string str)
 {
     System.Collections.Generic.Dictionary <char, char> cache = new System.Collections.Generic.Dictionary <char, char>()
     {
         { '(', ')' }, { '[', ']' }, { '{', '}' },
     };
     System.Collections.Generic.Stack <char> ts = new System.Collections.Generic.Stack <char>();
     for (int i = 0; i < str.Length; i++)
     {
         if (cache.ContainsKey(str[i]))
         {
             ts.Push(cache[str[i]]);
         }
         else
         {
             if (ts.Count > 0)
             {
                 var top = ts.Pop();
                 if (top != str[i])
                 {
                     return(false);
                 }
             }
             else
             {
                 return(false);
             }
         }
     }
     if (ts.Count > 0)
     {
         return(false);
     }
     return(true);
 }
Exemplo n.º 20
0
        static void Main(string[] args)
        {
            int    M        = int.Parse(args[0]);
            string filePath = args[1];

            int N = 12;

            string[]    lines = File.ReadAllLines(filePath);
            MinPQ <int> pq    = new MinPQ <int>(lines.Length);

            foreach (var line in lines)
            {
                int el = int.Parse(line);
                pq.insert(el);

                if (pq.size() > M)
                {
                    pq.delMin();
                }
            }

            System.Collections.Generic.Stack <int> stack = new System.Collections.Generic.Stack <int>();

            while (!pq.isEmpty())
            {
                stack.Push(pq.delMin());
            }

            foreach (var i in stack)
            {
                Console.WriteLine(i);
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// 开始下一步操作
        /// </summary>
        /// <typeparam name="S">IEnlistmentNotification接口实现</typeparam>
        /// <param name="level">IsolationLevel事务的隔离级别(对全局事务处理设置)</param>
        /// <param name="source">下一步操作的自定义数据管理器</param>
        public void Next <S>(IsolationLevel level, S source)
            where S : class, IEnlistmentNotification, new()
        {
            Transaction tran = _tranStack.Peek();//获取事务栈的顶端事务

            if (tran == null)
            {
                tran = Transaction.Current;//主事务
            }
            DependentTransaction depentran = tran.DependentClone(DependentCloneOption.BlockCommitUntilComplete);

            //将本次事务处理的资源管理器压入资源栈中
            depentran.EnlistVolatile(source, EnlistmentOptions.None);
            _tranStack.Push(depentran);
            _resourceStack.Push(source);
            //切换环境事务场景
            Transaction.Current = depentran;
            if (NextEvent != null)
            {
                if (NextEvent.GetInvocationList().Length > 0)
                {
                    NextEvent(Transaction.Current);
                }
            }
        }
Exemplo n.º 22
0
        public void PushScenario(string it)
        {
            // reset counter too
            counter = 0;

            scenario.Push(it);
        }
Exemplo n.º 23
0
        /// <summary>Pushes the current view to the top of the history stack and updates the Navigation UI</summary>
        private void NavigateAdd()
        {
            var item = new NavigateItem();

            item.ViewMode = _currentViewMode;
            switch (item.ViewMode)
            {
            case ViewMode.ViewSource:
                // don't reference the current source, we don't want to lose memory from the GC
//					item.Argument = CurrentSource;
                break;

            case ViewMode.ViewType:
                item.Argument = _viewList.CurrentObject as ResourceType;
                break;

            case ViewMode.ViewName:
                item.Argument = _viewList.CurrentObject as ResourceName;
                break;

            case ViewMode.ViewLangData:
                item.Argument = _viewData.CurrentData.Lang;
                break;
            }

            _history.Push(item);

            NavigateUpdateUI();
        }
Exemplo n.º 24
0
        private void EnumerateConversation(System.Collections.Generic.Stack <MailItem> st, object item, Outlook.Conversation conversation)
        {
            Outlook.SimpleItems items =
                conversation.GetChildren(item);
            if (items.Count > 0)
            {
                foreach (object myItem in items)
                {
                    // In this example, enumerate only MailItem type.
                    // Other types such as PostItem or MeetingItem
                    // can appear in the conversation.
                    if (myItem is Outlook.MailItem)
                    {
                        Outlook.MailItem mailItem = myItem as Outlook.MailItem;
                        Outlook.Folder   inFolder = mailItem.Parent as Outlook.Folder;

                        string msg = mailItem.Subject + " in folder [" + inFolder.Name + "] EntryId [" + (mailItem.EntryID.ToString() ?? "NONE") + "]";
                        _logger.Debug(msg);
                        _logger.Debug(mailItem.Sender);
                        _logger.Debug(mailItem.ReceivedByEntryID);

                        if (mailItem.EntryID != null && (mailItem.Sender != null || mailItem.ReceivedByEntryID != null))
                        {
                            st.Push(mailItem);
                        }
                    }
                    // Continue recursion.
                    EnumerateConversation(st, myItem, conversation);
                }
            }
        }
Exemplo n.º 25
0
        public int Dequeue()
        {
            if ((Queue == null) || (Queue.Count == 0))
            {
                throw new NullReferenceException();
            }

            if (Queue.Count == 1)
            {
                return(Queue.Pop());
            }

            var reversedQueue = new System.Collections.Generic.Stack <int>();

            while ((Queue.Count != 0) && (Queue != null))
            {
                reversedQueue.Push(Queue.Pop());
            }

            var poppedValue = reversedQueue.Pop();

            while ((reversedQueue.Count != 0) && (reversedQueue != null))
            {
                Queue.Push(reversedQueue.Pop());
            }



            return(poppedValue);
        }
Exemplo n.º 26
0
        public void FromTreeToLinkedList()
        {
            if (this.root == null)
            {
                return;
            }

            System.Collections.Generic.Stack <TreeNode> stack = new System.Collections.Generic.Stack <TreeNode>();
            TreeNode ptr = root;


            while (ptr != null || stack.Count > 0)
            {
                if (ptr.right != null)
                {
                    stack.Push(ptr.right);
                }

                if (ptr.left != null)
                {
                    ptr.right = ptr.left;
                    ptr.left  = null;
                }
                else if (stack.Count > 0)
                {
                    TreeNode tmp = stack.Pop();
                    ptr.right = tmp;
                }


                ptr = ptr.right;
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// 后序遍历
        /// 先左节点,然后右节点,后根节点
        /// </summary>
        public void PostOrderNo()
        {
            if (tree == null)
            {
                return;
            }
            HashSet <Tree> visited = new HashSet <Tree>();

            System.Collections.Generic.Stack <Tree> stack = new System.Collections.Generic.Stack <Tree>();
            Tree node = tree;

            while (stack.Any())
            {
                node = stack.Peek();
                if (node != null)
                {
                    stack.Push(node);
                    node = node.Left;
                }
                else
                {
                    var item = stack.Peek();
                    if (item.Right != null && !visited.Contains(item.Right))
                    {
                        node = item.Right;
                    }
                    else
                    {
                        System.Console.Write(node.Data + " ");
                        visited.Add(item);
                        stack.Pop();
                    }
                }
            }
        }
Exemplo n.º 28
0
    public void OnCanvasUp()
    {
        mypaint_draw_end();

        //TODO limit maximum number of undo

        //Do deep copy
        Texture2D deepCopiedTex = Instantiate(texture) as Texture2D;

        short[] deepCopidedBuf = buffer.Clone() as short[];

        //push current canvas image to undo stack
        undoStack.Push(new CanvasSnapshot(deepCopiedTex, deepCopidedBuf));

        //clear redo stack
        redoStack.Clear();
    }
Exemplo n.º 29
0
        /// <summary>
        /// 计算表达式的值
        /// </summary>
        /// <param name="expression">文本表达式</param>
        /// <returns>计算结果</returns>
        public static double Calculate(string expression)
        {
            // 预处理后缀表达式
            List <IOperatorOrOperand> postfix = Expressions.ConvertInfixToPostfix(expression);

            // 操作数栈
            System.Collections.Generic.Stack <double> data = new System.Collections.Generic.Stack <double>();

            // 遍历
            foreach (IOperatorOrOperand item in postfix)
            {
                if (item.IsOperator)
                {
                    // 运算符
                    OperatorBase opr = item as OperatorBase;

                    // 从操作数栈中取出操作数
                    if (data.Count < opr.OperandCount)
                    {
                        throw new InvalidCastException("无效的表达式。缺少运算符或出现多余的操作数。");
                    }
                    double[] operands = new double[opr.OperandCount];
                    for (int i = opr.OperandCount - 1; i >= 0; i--)
                    {
                        operands[i] = data.Pop();
                    }

                    // 计算并将结果压回栈中
                    data.Push(opr.Calculate(operands));
                }
                else
                {
                    // 操作数
                    // 压入操作数栈
                    data.Push(((OperandInfo)item).Value);
                }
            }

            // 取最后结果
            if (data.Count != 1)
            {
                throw new InvalidCastException("无效的表达式。缺少运算符或出现多余的操作数。");
            }
            return(data.Pop());
        }
Exemplo n.º 30
0
        public static string DepthFirstSearch(Node root)
        {
            Console.WriteLine("\nDEPTH FIRST");
            var stack  = new System.Collections.Generic.Stack <Node>();
            var result = "";

            stack.Push(root);
            while (stack.Count > 0)
            {
                var current = stack.Pop();
                result += current.Visit();
                foreach (var neighbor in current.Neighbors.Where(x => !x.Visited))
                {
                    stack.Push(neighbor);
                }
            }
            return(result);
        }
 private static void checkSequenceValid(string inputString)
 {
     System.Collections.Generic.Stack<char> brackets = new System.Collections.Generic.Stack<char>();
     for (int i = 0; i < inputString.Length; i++)
     {
         if (inputString[i] == '(')
         {
             brackets.Push(inputString[i]);
         }
         else if (inputString[i] == ')')
         {
             if (brackets.Count <= 0)
             {
                 return;
             }
             brackets.Pop();
         }
     }
     if (brackets.Count == 0)
     {
         numberOfSequence++;
     }
 }
Exemplo n.º 32
0
        public void Format(string input, TextWriter output, HtmlFormatterOptions options)
        {
            bool makeXhtml = options.MakeXhtml;
            int maxLineLength = options.MaxLineLength;
            string indentString = new string(options.IndentChar, options.IndentSize);
            char[] chars = input.ToCharArray();
            System.Collections.Generic.Stack<FormatInfo> formatInfoStack = new System.Collections.Generic.Stack<FormatInfo>();
            System.Collections.Generic.Stack<HtmlWriter> writerStack = new System.Collections.Generic.Stack<HtmlWriter>();
            FormatInfo curTagFormatInfo = null;
            FormatInfo prevTokenFormatInfo = null;
            string s = string.Empty;
            bool flag2 = false;
            bool hasNoEndTag = false;
            bool flag4 = false;
            HtmlWriter writer = new HtmlWriter(output, indentString, maxLineLength);
            writerStack.Push(writer);
            Token curToken = HtmlTokenizer.GetFirstToken(chars);
            Token prevToken = curToken;
            while (curToken != null)
            {
                string text;
                string tagName;
                TagInfo tagInfo;
                writer = (HtmlWriter) writerStack.Peek();
                switch (curToken.Type)
                {
                    case Token.Whitespace:
                        if (curToken.Text.Length > 0)
                        {
                            writer.Write(' ');
                        }
                        goto Label_Get_Next_Token;

                    case Token.TagName:
                    case Token.Comment:
                    case Token.InlineServerScript:
                        hasNoEndTag = false;
                        if (curToken.Type != Token.Comment)
                        {
                            goto Label_Token_TagName_Or_InlineServerScript;
                        }

                        tagName = curToken.Text;
                        tagInfo = new TagInfo(curToken.Text, commentTag);
                        goto Label_Process_Comment;

                    case Token.AttrName:
                        if (!makeXhtml)
                        {
                            goto Label_0164;
                        }
                        text = string.Empty;
                        if (curTagFormatInfo.tagInfo.IsXml)
                        {
                            break;
                        }
                        text = curToken.Text.ToLower();
                        goto Label_0127;

                    case Token.AttrVal:
                        if ((!makeXhtml || (prevToken.Type == 13)) || (prevToken.Type == 14))
                        {
                            goto Label_0227;
                        }
                        writer.Write('"');
                        writer.Write(curToken.Text.Replace("\"", "&quot;"));
                        writer.Write('"');
                        goto Label_Get_Next_Token;

                    case Token.TextToken:
                    case Token.ClientScriptBlock:
                    case Token.Style:
                    case Token.ServerScriptBlock:
                        s = s + curToken.Text;
                        goto Label_Get_Next_Token;

                    case Token.SelfTerminating:
                        curTagFormatInfo.isEndTag = true;
                        if (!curTagFormatInfo.tagInfo.NoEndTag)
                        {
                            formatInfoStack.Pop();
                            if (curTagFormatInfo.tagInfo.IsXml)
                            {
                                HtmlWriter writer2 = (HtmlWriter) writerStack.Pop();
                                writer = (HtmlWriter) writerStack.Peek();
                                writer.Write(writer2.Content);
                            }
                        }
                        if ((prevToken.Type == Token.Whitespace) && (prevToken.Text.Length > 0))
                        {
                            writer.Write("/>");
                        }
                        else
                        {
                            writer.Write(" />");
                        }
                        goto Label_Get_Next_Token;

                    case Token.Error:
                        if (prevToken.Type == Token.OpenBracket)
                        {
                            writer.Write('<');
                        }
                        writer.Write(curToken.Text);
                        goto Label_Get_Next_Token;

                    case Token.CloseBracket:
                        if (!makeXhtml)
                        {
                            goto Label_027A;
                        }
                        if (!flag4)
                        {
                            goto Label_Process_CloseBracket; // proc CloseBracket
                        }
                        flag4 = false;
                        goto Label_Get_Next_Token;

                    case Token.DoubleQuote:
                        writer.Write('"');
                        goto Label_Get_Next_Token;

                    case Token.SingleQuote:
                        writer.Write('\'');
                        goto Label_Get_Next_Token;

                    case Token.EqualsChar:
                        writer.Write('=');
                        goto Label_Get_Next_Token;

                    case Token.XmlDirective:
                        writer.WriteLineIfNotOnNewLine();
                        writer.Write('<');
                        writer.Write(curToken.Text);
                        writer.Write('>');
                        writer.WriteLineIfNotOnNewLine();
                        curTagFormatInfo = new FormatInfo(directiveTag, false);
                        flag4 = true;
                        goto Label_Get_Next_Token;

                    default:
                        goto Label_Get_Next_Token;
                }

                text = curToken.Text;

            Label_0127:
                writer.Write(text);
                if (HtmlTokenizer.GetNextToken(curToken).Type != 15)
                {
                    writer.Write("=\"" + text + "\"");
                }
                goto Label_Get_Next_Token;

            Label_0164:
                if (!curTagFormatInfo.tagInfo.IsXml)
                {
                    if (options.AttributeCasing == HtmlFormatterCase.UpperCase)
                    {
                        writer.Write(curToken.Text.ToUpper());
                    }
                    else if (options.AttributeCasing == HtmlFormatterCase.LowerCase)
                    {
                        writer.Write(curToken.Text.ToLower());
                    }
                    else
                    {
                        writer.Write(curToken.Text);
                    }
                }
                else
                {
                    writer.Write(curToken.Text);
                }
                goto Label_Get_Next_Token;

            Label_0227:
                writer.Write(curToken.Text);
                goto Label_Get_Next_Token;

            Label_Process_CloseBracket: // write closebucket
                if (hasNoEndTag && !curTagFormatInfo.tagInfo.IsComment) // flag3 = NoEndTag
                {
                    writer.Write(" />");
                }
                else
                {
                    writer.Write('>');
                }
                goto Label_Get_Next_Token;

            Label_027A:
                writer.Write('>');
                goto Label_Get_Next_Token;

            Label_Token_TagName_Or_InlineServerScript:
                if (curToken.Type == Token.InlineServerScript)
                {
                    string newTagName = curToken.Text.Trim().Substring(1);
                    tagName = newTagName;
                    if (newTagName.StartsWith("%@"))
                    {
                        tagInfo = new TagInfo(newTagName, directiveTag);
                    }
                    else
                    {
                        tagInfo = new TagInfo(newTagName, otherServerSideScriptTag);
                    }
                }
                else
                {
                    tagName = curToken.Text;
                    tagInfo = tagTable[tagName] as TagInfo;
                    if (tagInfo == null)
                    {
                        if (tagName.IndexOf(':') > -1)
                        {
                            tagInfo = new TagInfo(tagName, unknownXmlTag);
                        }
                        else if (writer is XmlWriter)
                        {
                            tagInfo = new TagInfo(tagName, nestedXmlTag);
                        }
                        else
                        {
                            tagInfo = new TagInfo(tagName, unknownHtmlTag);
                        }
                    }
                    else if ((options.ElementCasing == HtmlFormatterCase.LowerCase) || makeXhtml)
                    {
                        tagName = tagInfo.TagName;
                    }
                    else if (options.ElementCasing == HtmlFormatterCase.UpperCase)
                    {
                        tagName = tagInfo.TagName.ToUpper();
                    }
                }

            Label_Process_Comment:
                if (curTagFormatInfo == null)
                {
                    curTagFormatInfo = new FormatInfo(tagInfo, false);
                    curTagFormatInfo.indent = 0;
                    formatInfoStack.Push(curTagFormatInfo);
                    writer.Write(s);
                    if (tagInfo.IsXml)
                    {
                        HtmlWriter writer3 = new XmlWriter(writer.Indent, tagInfo.TagName, indentString, maxLineLength);
                        writerStack.Push(writer3);
                        writer = writer3;
                    }
                    if (prevToken.Type == Token.ForwardSlash)
                    {
                        writer.Write("</");
                    }
                    else
                    {
                        writer.Write('<');
                    }
                    writer.Write(tagName);
                    s = string.Empty;
                }
                else
                {
                    WhiteSpaceType followingWhiteSpaceType;
                    prevTokenFormatInfo = new FormatInfo(tagInfo, prevToken.Type == Token.ForwardSlash);
                    followingWhiteSpaceType = curTagFormatInfo.isEndTag ? curTagFormatInfo.tagInfo.FollowingWhiteSpaceType : curTagFormatInfo.tagInfo.InnerWhiteSpaceType;
                    bool isInline = curTagFormatInfo.tagInfo.IsInline;
                    bool flag6 = false;
                    bool flag7 = false;
                    if (writer is XmlWriter)
                    {
                        XmlWriter writer4 = (XmlWriter) writer;
                        if (writer4.IsUnknownXml)
                        {
                            flag7 = ((curTagFormatInfo.isBeginTag && (curTagFormatInfo.tagInfo.TagName.ToLower() == writer4.TagName.ToLower())) || (prevTokenFormatInfo.isEndTag && (prevTokenFormatInfo.tagInfo.TagName.ToLower() == writer4.TagName.ToLower()))) && !FormattedTextWriter.IsWhiteSpace(s);
                        }
                        if (curTagFormatInfo.isBeginTag)
                        {
                            if (FormattedTextWriter.IsWhiteSpace(s))
                            {
                                if ((writer4.IsUnknownXml && prevTokenFormatInfo.isEndTag) && (curTagFormatInfo.tagInfo.TagName.ToLower() == prevTokenFormatInfo.tagInfo.TagName.ToLower()))
                                {
                                    isInline = true;
                                    flag6 = true;
                                    s = "";
                                }
                            }
                            else if (!writer4.IsUnknownXml)
                            {
                                writer4.ContainsText = true;
                            }
                        }
                    }
                    bool frontWhiteSpace = true;
                    if (curTagFormatInfo.isBeginTag && curTagFormatInfo.tagInfo.PreserveContent)
                    {
                        writer.Write(s);
                    }
                    else
                    {
                        switch (followingWhiteSpaceType)
                        {
                            case WhiteSpaceType.NotSignificant:
                                if (!isInline && !flag7)
                                {
                                    writer.WriteLineIfNotOnNewLine();
                                    frontWhiteSpace = false;
                                }
                                break;

                            case WhiteSpaceType.Significant:
                                if ((FormattedTextWriter.HasFrontWhiteSpace(s) && !isInline) && !flag7)
                                {
                                    writer.WriteLineIfNotOnNewLine();
                                    frontWhiteSpace = false;
                                }
                                break;

                            default:
                                if (((followingWhiteSpaceType == WhiteSpaceType.CarryThrough) && (flag2 || FormattedTextWriter.HasFrontWhiteSpace(s))) && (!isInline && !flag7))
                                {
                                    writer.WriteLineIfNotOnNewLine();
                                    frontWhiteSpace = false;
                                }
                                break;
                        }
                        if ((curTagFormatInfo.isBeginTag && !curTagFormatInfo.tagInfo.NoIndent) && !isInline)
                        {
                            writer.Indent++;
                        }
                        if (flag7)
                        {
                            writer.Write(s);
                        }
                        else
                        {
                            writer.WriteLiteral(s, frontWhiteSpace);
                        }
                    }
                    if (prevTokenFormatInfo.isEndTag)
                    {
                        if (!prevTokenFormatInfo.tagInfo.NoEndTag)
                        {
                            //ArrayList list = new ArrayList();
                            List<FormatInfo> formatInfoList = new List<FormatInfo>();
                            FormatInfo info4 = null;
                            bool flag9 = false;
                            bool flag10 = false;
                            if ((prevTokenFormatInfo.tagInfo.Flags & FormattingFlags.AllowPartialTags) != FormattingFlags.None)
                            {
                                flag10 = true;
                            }
                            if (formatInfoStack.Count > 0)
                            {
                                info4 = (FormatInfo) formatInfoStack.Pop();
                                formatInfoList.Add(info4);
                                while ((formatInfoStack.Count > 0) && (info4.tagInfo.TagName.ToLower() != prevTokenFormatInfo.tagInfo.TagName.ToLower()))
                                {
                                    if ((info4.tagInfo.Flags & FormattingFlags.AllowPartialTags) != FormattingFlags.None)
                                    {
                                        flag10 = true;
                                        break;
                                    }
                                    info4 = (FormatInfo) formatInfoStack.Pop();
                                    formatInfoList.Add(info4);
                                }
                                if (info4.tagInfo.TagName.ToLower() != prevTokenFormatInfo.tagInfo.TagName.ToLower())
                                {
                                    for (int i = formatInfoList.Count - 1; i >= 0; i--)
                                    {
                                        formatInfoStack.Push(formatInfoList[i]);
                                    }
                                }
                                else
                                {
                                    flag9 = true;
                                    for (int j = 0; j < (formatInfoList.Count - 1); j++)
                                    {
                                        FormatInfo info5 = (FormatInfo) formatInfoList[j];
                                        if (info5.tagInfo.IsXml && (writerStack.Count > 1))
                                        {
                                            HtmlWriter writer5 = (HtmlWriter) writerStack.Pop();
                                            writer = (HtmlWriter) writerStack.Peek();
                                            writer.Write(writer5.Content);
                                        }
                                        if (!info5.tagInfo.NoEndTag)
                                        {
                                            writer.WriteLineIfNotOnNewLine();
                                            writer.Indent = info5.indent;
                                            if (makeXhtml && !flag10)
                                            {
                                                writer.Write("</" + info5.tagInfo.TagName + ">");
                                            }
                                        }
                                    }
                                    writer.Indent = info4.indent;
                                }
                            }
                            if (flag9 || flag10)
                            {
                                if ((((!flag6 && !flag7) && (!prevTokenFormatInfo.tagInfo.IsInline && !prevTokenFormatInfo.tagInfo.PreserveContent)) && ((FormattedTextWriter.IsWhiteSpace(s) || FormattedTextWriter.HasBackWhiteSpace(s)) || (prevTokenFormatInfo.tagInfo.FollowingWhiteSpaceType == WhiteSpaceType.NotSignificant))) && (!(prevTokenFormatInfo.tagInfo is TDTagInfo) || FormattedTextWriter.HasBackWhiteSpace(s)))
                                {
                                    writer.WriteLineIfNotOnNewLine();
                                }
                                writer.Write("</");
                                writer.Write(tagName);
                            }
                            else
                            {
                                flag4 = true;
                            }
                            if (prevTokenFormatInfo.tagInfo.IsXml && (writerStack.Count > 1))
                            {
                                HtmlWriter writer6 = (HtmlWriter) writerStack.Pop();
                                writer = (HtmlWriter) writerStack.Peek();
                                writer.Write(writer6.Content);
                            }
                        }
                        else
                        {
                            flag4 = true;
                        }
                    }
                    // prevTokenFormatInfo.isEndTag == false
                    else
                    {
                        bool flag11 = false;
                        while (!flag11 && (formatInfoStack.Count > 0))
                        {
                            FormatInfo info6 = (FormatInfo) formatInfoStack.Peek();
                            if (!info6.tagInfo.CanContainTag(prevTokenFormatInfo.tagInfo))
                            {
                                formatInfoStack.Pop();
                                writer.Indent = info6.indent;
                                if (makeXhtml)
                                {
                                    if (!info6.tagInfo.IsInline)
                                    {
                                        writer.WriteLineIfNotOnNewLine();
                                    }
                                    writer.Write("</" + info6.tagInfo.TagName + ">");
                                }
                            }
                            flag11 = true;
                        }
                        prevTokenFormatInfo.indent = writer.Indent;
                        if (((!flag7 && !prevTokenFormatInfo.tagInfo.IsInline) && !prevTokenFormatInfo.tagInfo.PreserveContent) && ((FormattedTextWriter.IsWhiteSpace(s) || FormattedTextWriter.HasBackWhiteSpace(s)) || ((s.Length == 0) && ((curTagFormatInfo.isBeginTag && (curTagFormatInfo.tagInfo.InnerWhiteSpaceType == WhiteSpaceType.NotSignificant)) || (curTagFormatInfo.isEndTag && (curTagFormatInfo.tagInfo.FollowingWhiteSpaceType == WhiteSpaceType.NotSignificant))))))
                        {
                            writer.WriteLineIfNotOnNewLine();
                        }
                        if (!prevTokenFormatInfo.tagInfo.NoEndTag)
                        {
                            formatInfoStack.Push(prevTokenFormatInfo);
                        }
                        else
                        {
                            hasNoEndTag = true;
                        }
                        if (prevTokenFormatInfo.tagInfo.IsXml)
                        {
                            HtmlWriter writer7 = new XmlWriter(writer.Indent, prevTokenFormatInfo.tagInfo.TagName, indentString, maxLineLength);
                            writerStack.Push(writer7);
                            writer = writer7;
                        }
                        writer.Write('<');
                        writer.Write(tagName);
                    }
                    flag2 = FormattedTextWriter.HasBackWhiteSpace(s);
                    s = string.Empty;
                    curTagFormatInfo = prevTokenFormatInfo;
                }

            Label_Get_Next_Token:
                prevToken = curToken;
                curToken = HtmlTokenizer.GetNextToken(curToken);
            }
            if (s.Length > 0)
            {
                writer.Write(s);
            }
            while (writerStack.Count > 1)
            {
                HtmlWriter writer8 = (HtmlWriter) writerStack.Pop();
                writer = (HtmlWriter) writerStack.Peek();
                writer.Write(writer8.Content);
            }
            writer.Flush();
        }
Exemplo n.º 33
0
        public double calc(int amount, string fromUnit, string toUnit)
        {
            var from = (Units) Enum.Parse(typeof (Units), fromUnit.Replace("in", "inch"));
            var to = (Units) Enum.Parse(typeof (Units), toUnit.Replace("in", "inch"));

            var dgraf = new Graf<Units>();

            var ftVertex = new Vertex<Units>(Units.ft);
            var inVertex = new Vertex<Units>(Units.inch);
            var ydVertex = new Vertex<Units>(Units.yd);
            var miVertex = new Vertex<Units>(Units.mi);

            ftVertex.AddDirectedEdge(12, inVertex);
            inVertex.AddDirectedEdge(1D / 12, ftVertex);

            ydVertex.AddDirectedEdge(3, ftVertex);
            ftVertex.AddDirectedEdge(1D / 3, ydVertex);

            miVertex.AddDirectedEdge(1760, ydVertex);
            ydVertex.AddDirectedEdge(1D / 1760, miVertex);

            dgraf.AddVertex(ftVertex);
            dgraf.AddVertex(inVertex);
            dgraf.AddVertex(ydVertex);
            dgraf.AddVertex(miVertex);

            var source = dgraf.Vertexes.FirstOrDefault(vertex => vertex.Key == from);
            var target = dgraf.Vertexes.FirstOrDefault(vertex => vertex.Key == to);

            var vertexPath = dgraf.GetBreadthPath(source, target).ToList();

            var edgePath = new System.Collections.Generic.Stack<Edge<Units>>();
            if (target.Color != Vertex<Units>.VertexColor.Black)
                return 0;

            var currentVertex = target;
            while (currentVertex != null && currentVertex != source && currentVertex.Parent != null)
            {
                var currentEdge = currentVertex.Parent.Edges.FirstOrDefault(edge => edge.Target == currentVertex);
                edgePath.Push(currentEdge);
                currentVertex = currentVertex.Parent;
            }

            if (source == target)
                return amount;
            if (!edgePath.Any())
                return 0;

            double res = amount;
            double weigth = 1;
            foreach (var pathEdge in edgePath)
                    weigth *= pathEdge.Weigth;
            return res * weigth;
        }
Exemplo n.º 34
0
        private void switchBaseMapLayer(TiledMapServiceLayer baseMapLayer, Envelope newExtent, List<Layer> oldBasemapLayers)
        {
            if (Map == null)
                return;

            // 1. Save the operational layers (We assume a single base layer)
            System.Collections.Generic.Stack<Layer> layers = new System.Collections.Generic.Stack<Layer>();
            for (int i = Map.Layers.Count - 1; i >= 0; i--)
            {
                Layer l = Map.Layers[i];
                if (oldBasemapLayers.Contains(l))
                    continue;

                Map.Layers.RemoveAt(i);
                layers.Push(l);
            }

            // 2. Clear the layers collection
            Map.Layers.Clear();

            // 3. Set the extent
            bool spatialReferenceUnchanged = Map.SpatialReference.Equals(newExtent.SpatialReference);
            Map.Extent = newExtent;

            // 4a. Set layer id if this is not set
            if (string.IsNullOrEmpty(baseMapLayer.ID) || (!string.IsNullOrEmpty(baseMapLayer.ID) && Map.Layers[baseMapLayer.ID] != null))
                baseMapLayer.ID = Guid.NewGuid().ToString("N");

            // 4. Add the new base map
            Map.Layers.Add(baseMapLayer);

            // 5. Re-add the operational layers         
            while (layers.Count > 0)
            {
                Layer layer = layers.Pop();
                if (!spatialReferenceUnchanged)
                {
                    //reproject graphics layers that are not feature layers 
                    // Feature layers support reprojection
                    if (layer is GraphicsLayer && !(layer is FeatureLayer))
                    {
                        GraphicsLayer graphicsLayer = layer as GraphicsLayer;
                        if (graphicsLayer.Graphics.Count > 0)
                        {
                            GeometryServiceOperationHelper helper = new GeometryServiceOperationHelper(
                                                                                                        new ConfigurationStoreHelper().GetGeometryServiceUrl(ConfigurationStore));
                            helper.ProjectGraphicsCompleted += (o, e) =>
                            {
                                GraphicsLayer targetLayer = e.UserState as GraphicsLayer;
                                if (targetLayer != null)
                                {
                                    targetLayer.Graphics.Clear();
                                    foreach (Graphic graphic in e.Graphics)
                                        targetLayer.Graphics.Add(graphic);
                                }
                            };
                            helper.ProjectGraphics(graphicsLayer.Graphics, newExtent.SpatialReference, graphicsLayer);
                        }

                        // update the map spatial reference on custom layers
                        ICustomGraphicsLayer customGraphicsLayer = layer as ICustomGraphicsLayer;
                        if (customGraphicsLayer != null)
                            customGraphicsLayer.MapSpatialReference = Map.SpatialReference;
                        else
                        {
                            HeatMapLayerBase heatMapLayer = layer as HeatMapLayerBase;
                            if (heatMapLayer != null)
                                heatMapLayer.MapSpatialReference = Map.SpatialReference;
                        }
                    }
                    else
                    {
                        HeatMapLayerBase heatMapLayer = layer as HeatMapLayerBase;
                        if (heatMapLayer != null && heatMapLayer.HeatMapPoints.Count > 0)
                        {
                            GeometryServiceOperationHelper helper = new GeometryServiceOperationHelper(new ConfigurationStoreHelper().GetGeometryServiceUrl(ConfigurationStore));
                            helper.ProjectPointsCompleted += (o, e) =>
                            {
                                PointCollection points = new PointCollection();

                                foreach (MapPoint item in e.Points)
                                {
                                    if (item != null)
                                        points.Add(item);
                                }

                                heatMapLayer.HeatMapPoints = points;
                                heatMapLayer.MapSpatialReference = points[0].SpatialReference;
                                heatMapLayer.Refresh();
                            };
                            helper.ProjectPoints(heatMapLayer.HeatMapPoints, newExtent.SpatialReference);
                        }
                    }
                }
                Map.Layers.Add(layer);
            }
        }
Exemplo n.º 35
0
        /// <summary>
        /// ������ʽ��ֵ
        /// </summary>
        /// <param name="expression">�ı����ʽ</param>
        /// <returns>������</returns>
        public static double Calculate(string expression)
        {
            // Ԥ�����׺���ʽ
            List<IOperatorOrOperand> postfix = Expressions.ConvertInfixToPostfix(expression);
            // ������ջ
            System.Collections.Generic.Stack<double> data = new System.Collections.Generic.Stack<double>();

            // ����
            foreach (IOperatorOrOperand item in postfix)
            {
                if (item.IsOperator)
                {
                    // �����
                    OperatorBase opr = item as OperatorBase;

                    // �Ӳ�����ջ��ȡ��������
                    if (data.Count < opr.OperandCount)
                    {
                        throw new InvalidCastException("��Ч�ı��ʽ��ȱ�����������ֶ���IJ�������");
                    }
                    double[] operands = new double[opr.OperandCount];
                    for (int i = opr.OperandCount - 1; i >= 0; i--)
                    {
                        operands[i] = data.Pop();
                    }

                    // ���㲢�����ѹ��ջ��
                    data.Push(opr.Calculate(operands));
                }
                else
                {
                    // ������
                    // ѹ�������ջ
                    data.Push(((OperandInfo)item).Value);
                }
            }

            // ȡ�����
            if (data.Count != 1)
            {
                throw new InvalidCastException("��Ч�ı��ʽ��ȱ�����������ֶ���IJ�������");
            }
            return data.Pop();
        }
Exemplo n.º 36
0
        /// <summary>
        /// �����ʽת��Ϊ��׺���ʽ
        /// </summary>
        /// <param name="expression">�ı����ʽ</param>
        /// <returns>ת����ĺ�׺���ʽ</returns>
        internal static List<IOperatorOrOperand> ConvertInfixToPostfix(string expression)
        {
            // Ԥ������׺���ʽ
            List<IOperatorOrOperand> infix = SplitExpression(expression);
            // �����ջ
            System.Collections.Generic.Stack<OperatorBase> opr = new System.Collections.Generic.Stack<OperatorBase>();
            // ��׺���ʽ���
            List<IOperatorOrOperand> output = new List<IOperatorOrOperand>();

            // ����
            foreach (IOperatorOrOperand item in infix)
            {
                if (item.IsOperator)
                {
                    // �������
                    if (item.GetType() == typeof(OperatorCloseBracket))
                    {
                        // ������

                        // �����������ֱ������������Ϊֹ
                        while (opr.Peek().GetType() != typeof(OperatorOpenBracket))
                        {
                            output.Add(opr.Pop());
                            if (opr.Count == 0)
                            {
                                // ���Ų����
                                throw new InvalidCastException("�������Ų�ƥ�䡣");
                            }
                        }

                        // ����������
                        opr.Pop();
                    }
                    else
                    {
                        // ���������
                        OperatorBase thisopr = item as OperatorBase;

                        // �������ȼ��߻���ȵ������
                        int thisPriority = thisopr.Priority;
                        while (opr.Count > 0)
                        {
                            OperatorBase topopr = opr.Peek();
                            if(topopr.GetType() != typeof(OperatorOpenBracket))
                            {
                                // ���ջ���������Ϊ������
                                if (topopr.Priority > thisopr.Priority)
                                {
                                    // ���ջ���е���������ȼ����ڵ�ǰ������������������ջ
                                    output.Add(opr.Pop());
                                }
                                else if (topopr.Priority == thisopr.Priority)
                                {
                                    // ���ջ���е���������ȼ��뵱ǰ��������
                                    if (topopr.Direction == OperatingDirection.LeftToRight)
                                    {
                                        // ���ջ�����������Է���Ϊ�������ң������������ջ
                                        output.Add(opr.Pop());
                                    }
                                    else
                                    {
                                        // ����Ǵ���������ֹ��ջ
                                        break;
                                    }
                                }
                                else
                                {
                                    // ��ֹ��ջ
                                    break;
                                }
                            }
                            else
                            {
                                // ��ֹ��ջ
                                break;
                            }
                        }

                        // ����ǰ�����ѹ��ջ��
                        opr.Push(thisopr);
                    }
                }
                else
                {
                    // �Dz�����
                    // ֱ�����
                    output.Add(item);
                }
            }

            // �������������ջ��ȫ��ʣ��
            while (opr.Count > 0)
            {
                output.Add(opr.Pop());
            }

            return output;
        }
Exemplo n.º 37
0
        private SelectionCriterion _ParseCriterion(String s)
        {
            if (s == null) return null;

            // shorthand for filename glob
            if (s.IndexOf(" ") == -1)
                s = "name = " + s;

            // inject spaces after open paren and before close paren
            string[] prPairs = { @"\((\S)", "( $1", @"(\S)\)", "$1 )", };
            for (int i = 0; i + 1 < prPairs.Length; i += 2)
            {
                Regex rgx = new Regex(prPairs[i]);
                s = rgx.Replace(s, prPairs[i + 1]);
            }

            // split the expression into tokens
            string[] tokens = s.Trim().Split(' ', '\t');

            if (tokens.Length < 3) throw new ArgumentException(s);

            SelectionCriterion current = null;

            LogicalConjunction pendingConjunction = LogicalConjunction.NONE;

            ParseState state;
            var stateStack = new System.Collections.Generic.Stack<ParseState>();
            var critStack = new System.Collections.Generic.Stack<SelectionCriterion>();
            stateStack.Push(ParseState.Start);

            for (int i = 0; i < tokens.Length; i++)
            {
                switch (tokens[i].ToLower())
                {
                    case "and":
                    case "xor":
                    case "or":
                        state = stateStack.Peek();
                        if (state != ParseState.CriterionDone)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        if (tokens.Length <= i + 3)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        pendingConjunction = (LogicalConjunction)Enum.Parse(typeof(LogicalConjunction), tokens[i].ToUpper());
                        current = new CompoundCriterion { Left = current, Right = null, Conjunction = pendingConjunction };
                        stateStack.Push(state);
                        stateStack.Push(ParseState.ConjunctionPending);
                        critStack.Push(current);
                        break;

                    case "(":
                        state = stateStack.Peek();
                        if (state != ParseState.Start && state != ParseState.ConjunctionPending && state != ParseState.OpenParen)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        if (tokens.Length <= i + 4)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        stateStack.Push(ParseState.OpenParen);
                        break;

                    case ")":
                        state = stateStack.Pop();
                        if (stateStack.Peek() != ParseState.OpenParen)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        stateStack.Pop();
                        stateStack.Push(ParseState.CriterionDone);
                        break;

                    case "atime":
                    case "ctime":
                    case "mtime":
                        if (tokens.Length <= i + 2)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        DateTime t;
                        try
                        {
                            t = DateTime.ParseExact(tokens[i + 2], "yyyy-MM-dd-HH:mm:ss", null);
                        }
                        catch
                        {
                            t = DateTime.ParseExact(tokens[i + 2], "yyyy-MM-dd", null);
                        }
                        current = new TimeCriterion
                        {
                            Which = (WhichTime)Enum.Parse(typeof(WhichTime), tokens[i]),
                            Operator = (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1]),
                            Time = t
                        };
                        i += 2;
                        stateStack.Push(ParseState.CriterionDone);
                        break;

                    case "length":
                    case "size":
                        if (tokens.Length <= i + 2)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        Int64 sz = 0;
                        string v = tokens[i + 2];
                        if (v.ToUpper().EndsWith("K"))
                            sz = Int64.Parse(v.Substring(0, v.Length - 1)) * 1024;
                        else if (v.ToUpper().EndsWith("KB"))
                            sz = Int64.Parse(v.Substring(0, v.Length - 2)) * 1024;
                        else if (v.ToUpper().EndsWith("M"))
                            sz = Int64.Parse(v.Substring(0, v.Length - 1)) * 1024 * 1024;
                        else if (v.ToUpper().EndsWith("MB"))
                            sz = Int64.Parse(v.Substring(0, v.Length - 2)) * 1024 * 1024;
                        else if (v.ToUpper().EndsWith("G"))
                            sz = Int64.Parse(v.Substring(0, v.Length - 1)) * 1024 * 1024 * 1024;
                        else if (v.ToUpper().EndsWith("GB"))
                            sz = Int64.Parse(v.Substring(0, v.Length - 2)) * 1024 * 1024 * 1024;
                        else sz = Int64.Parse(tokens[i + 2]);

                        current = new SizeCriterion
                        {
                            Size = sz,
                            Operator = (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1])
                        };
                        i += 2;
                        stateStack.Push(ParseState.CriterionDone);
                        break;

                    case "filename":
                    case "name":
                        {
                            if (tokens.Length <= i + 2)
                                throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                            ComparisonOperator c =
                                (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1]);

                            if (c != ComparisonOperator.NotEqualTo && c != ComparisonOperator.EqualTo)
                                throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                            string m = tokens[i + 2];
                            // handle single-quoted filespecs (used to include spaces in filename patterns)
                            if (m.StartsWith("'"))
                            {
                                int ix = i;
                                if (!m.EndsWith("'"))
                                {
                                    do
                                    {
                                        i++;
                                        if (tokens.Length <= i + 2)
                                            throw new ArgumentException(String.Join(" ", tokens, ix, tokens.Length - ix));
                                        m += " " + tokens[i + 2];
                                    } while (!tokens[i + 2].EndsWith("'"));
                                }
                                // trim off leading and trailing single quotes
                                m = m.Substring(1, m.Length - 2);
                            }

                            current = new NameCriterion
                            {
                                MatchingFileSpec = m,
                                Operator = c
                            };
                            i += 2;
                            stateStack.Push(ParseState.CriterionDone);
                        }
                        break;

                    case "attributes":
                        {
                            if (tokens.Length <= i + 2)
                                throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                            ComparisonOperator c =
                                (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1]);

                            if (c != ComparisonOperator.NotEqualTo && c != ComparisonOperator.EqualTo)
                                throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                            current = new AttributesCriterion
                            {
                                AttributeString = tokens[i + 2],
                                Operator = c
                            };
                            i += 2;
                            stateStack.Push(ParseState.CriterionDone);
                        }
                        break;

                    case "":
                        // NOP
                        stateStack.Push(ParseState.Whitespace);
                        break;

                    default:
                        throw new ArgumentException("'" + tokens[i] + "'");
                }

                state = stateStack.Peek();
                if (state == ParseState.CriterionDone)
                {
                    stateStack.Pop();
                    if (stateStack.Peek() == ParseState.ConjunctionPending)
                    {
                        while (stateStack.Peek() == ParseState.ConjunctionPending)
                        {
                            var cc = critStack.Pop() as CompoundCriterion;
                            cc.Right = current;
                            current = cc; // mark the parent as current (walk up the tree)
                            stateStack.Pop();   // the conjunction is no longer pending

                            state = stateStack.Pop();
                            if (state != ParseState.CriterionDone)
                                throw new ArgumentException();
                        }
                    }
                    else stateStack.Push(ParseState.CriterionDone);  // not sure?
                }

                if (state == ParseState.Whitespace)
                    stateStack.Pop();
            }

            return current;
        }
Exemplo n.º 38
0
        public override void Visit(ConditionalBranchNode node)
        {
            // AddCommand( new PushState() );

            node.ConditionalBranchCondition.Accept(this);

            RelativeJumpIfFalse falseConditionJump = new RelativeJumpIfFalse(0);
            AddCommand(falseConditionJump);
            jumpStack.Push(falseConditionJump);

            // IfCore
            node.ConditionalBranchCore.Accept(this);

            // This will jump to the end of the IfStatement
            RelativeJump toEndJump = new RelativeJump(0);
            AddCommand(toEndJump);

            // Pop all Break command from the jumpStack
            System.Collections.Generic.Stack<Jump> tempBreakStack = new System.Collections.Generic.Stack<Jump>();

            while (jumpStack.Count != 0 && jumpStack.Peek().GetType() == (new Break()).GetType() )
                tempBreakStack.Push(jumpStack.Pop());

            SetUpTopJumpInJumpStack(0);

            // Push all Break back to the jumpStack
            while (tempBreakStack.Count != 0) jumpStack.Push(tempBreakStack.Pop());

            // Push the falseConditionJump to set up PC later
            jumpStack.Push(toEndJump);
            conditionCount++;

            // AddCommand( new PopState() );
        }
Exemplo n.º 39
0
        private int? DoSmartIndent(ITextSnapshotLine line) {
            if (line.LineNumber == 0) {
                return null;
            }
            int? indentation = GetLeadingWhiteSpace(line.GetText());
            var classifications = EnumerateClassificationsInReverse(
                _classifier,
                line.Snapshot.GetLineFromLineNumber(line.LineNumber - 1).End
            );

            if (classifications.MoveNext()) {
                var starting = classifications.Current;

                // first check to see if we're in an unterminated multiline token
                if (starting != null) {
                    if (starting.Tag.ClassificationType.Classification == "comment" &&
                        starting.Span.GetText().StartsWith("/*") &&
                        (!starting.Span.GetText().EndsWith("*/") || starting.Span.End.GetContainingLine() == line)) {
                        // smart indent in comment, dont indent
                        return null;
                    } else if (starting.Tag.ClassificationType.Classification == "string") {
                        var text = starting.Span.GetText();
                        if (!text.EndsWith("\"") && !text.EndsWith("'")) {
                            // smart indent in multiline string, no indent
                            return null;
                        }
                    }
                }

                // walk backwards and collect all of the possible tokens that could
                // be useful here...
                var tokenStack = new System.Collections.Generic.Stack<ITagSpan<ClassificationTag>>();
                tokenStack.Push(null);  // end with an implicit newline
                bool endAtNextNull = false;

                do {
                    var token = classifications.Current;
                    tokenStack.Push(token);
                    if (token == null && endAtNextNull) {
                        break;
                    } else if (token != null &&
                        token.Span.GetText() == "{") {
                        endAtNextNull = true;
                    }
                } while (classifications.MoveNext());

                var indentStack = new System.Collections.Generic.Stack<LineInfo>();
                var current = LineInfo.Empty;

                while (tokenStack.Count > 0) {
                    var token = tokenStack.Pop();
                    bool didDedent = false;
                    if (token == null) {
                        current.NeedsUpdate = true;
                    } else if (IsOpenGrouping(token)) {
                        if (current.WasIndentKeyword && token.Span.GetText() == "{") {
                            // the indentation statement is followed by braces, go ahead
                            // and remove the level of indentation now
                            current.WasIndentKeyword = false;
                            current.Indentation -= _editorOptions.GetTabSize();
                        }
                        indentStack.Push(current);
                        var start = token.Span.Start;
                        current = new LineInfo {
                            Indentation = GetLeadingWhiteSpace(start.GetContainingLine().GetText()) + _editorOptions.GetTabSize()
                        };
                    } else if (_indentKeywords.Contains(token.Span.GetText()) && !current.WasDoKeyword) {
                        // if (foo) 
                        //      console.log('hi')
                        // We should indent here
                        var start = token.Span.Start;
                        int dedentTo = GetLeadingWhiteSpace(start.GetContainingLine().GetText());
                        if (current.DedentTo != null && token.Span.GetText() != "if") {
                            // https://nodejstools.codeplex.com/workitem/1176
                            // if (true)
                            //     while (true)
                            //         ;
                            //
                            // We should dedent to the if (true)
                            // But for:
                            // if (true)
                            //     if (true)
                            //          ;
                            // We still want to dedent to our current level for the else
                            dedentTo = current.DedentTo.Value;
                        }
                        current = new LineInfo {
                            Indentation = GetLeadingWhiteSpace(start.GetContainingLine().GetText()) + _editorOptions.GetTabSize(),
                            DedentTo = dedentTo,
                            WasIndentKeyword = true,
                            WasDoKeyword = token.Span.GetText() == "do"
                        };
                    } else if (IsCloseGrouping(token)) {
                        if (indentStack.Count > 0) {
                            current = indentStack.Pop();
                        } else {
                            current = new LineInfo {
                                Indentation = GetLeadingWhiteSpace(token.Span.Start.GetContainingLine().GetText())
                            };
                        }
                    } else if (IsMultilineStringOrComment(token)) {
                        while (token != null && tokenStack.Count > 0) {
                            token = tokenStack.Pop();
                        }
                    } else if (current.WasIndentKeyword) {
                        // we've encountered a token after the opening of the indented
                        // statement, go ahead and decrement our indentation level now.
                        current = new LineInfo {
                            Indentation = current.DedentTo,
                            DedentTo = current.DedentTo - _editorOptions.GetTabSize(),
                            WasDoKeyword = current.WasDoKeyword
                        };
                        didDedent = true;
                    } else if (current.NeedsUpdate) {
                        var line2 = token.Span.Start.GetContainingLine();
                        current = new LineInfo {
                            Indentation = GetLeadingWhiteSpace(line2.GetText())
                        };
                    }

                    if (!didDedent && token != null && _dedentKeywords.Contains(token.Span.GetText())) {     // dedent after some statements
                        current.ShouldDedentAfter = true;
                    }
                }

                return current.Indentation -
                    (current.ShouldDedentAfter ? _editorOptions.GetTabSize() : 0);
            }

            return null;
        }