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);
        }
Example #2
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();
                    }
                }
            }
        }
Example #3
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;
                }
            }
        }
Example #4
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();
        }
Example #5
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);
        }
Example #6
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());
        }
        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);
        }
Example #8
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);
                }
            }
        }
Example #9
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;
            }
        }
Example #10
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);
        }
        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());
        }
Example #12
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);
        }
Example #13
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));
        }
Example #14
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);
            }
        }
Example #15
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);
        }
Example #16
0
 public void Wykonaj(Photo.Zdjecie z, System.Collections.Generic.Stack <object> Argumenty)
 {
     if (z.Zaznaczenie.IsEmpty)
     {
         Photo.BitmapFilter.GaussianBlur(z.Duze, 4);
     }
     else
     {
         if (z.Zaznaczenie.Width < 0)
         {
             z.Zaznaczenie.X     += z.Zaznaczenie.Width;
             z.Zaznaczenie.Width *= -1;
         }
         if (z.Zaznaczenie.Height < 0)
         {
             z.Zaznaczenie.Y      += z.Zaznaczenie.Height;
             z.Zaznaczenie.Height *= -1;
         }
         Bitmap   blured = new Bitmap(Math.Abs(z.Zaznaczenie.Width), Math.Abs(z.Zaznaczenie.Height), z.Duze.PixelFormat);
         Graphics g      = Graphics.FromImage(blured);
         g.DrawImage(z.Duze, new Rectangle(0, 0, blured.Width, blured.Height), z.Zaznaczenie, GraphicsUnit.Pixel);
         g.Dispose();
         Photo.BitmapFilter.GaussianBlur(blured, 4);
         g = Graphics.FromImage(z.Duze);
         g.DrawImage(blured, z.Zaznaczenie);
         g.Dispose();
     }
 }
Example #17
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);
 }
Example #18
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);
        }
Example #19
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);
        }
Example #20
0
    //-------------------------------------------------------------------------------------------------------------------------------------------------
    // Método virtual sobrescrito, que faz a validação conforme as regras da pilha intermediária

    public override bool Validate(System.Collections.Generic.Stack <GameObject> externalStack)
    {
        // Referencias das carta
        Card externalCard = externalStack.Peek().GetComponent <Card>();// Referência da carta da pilha externa.

        // Caso não haja cartas na pilha, checará:
        if (externalStack.Count == 0 && externalCard.Value == 13)                           // Checa se a pilha está vazia, caso positivo, só aceita reis.
        {
            return(true);
        }

        Card internalCard = stack.Peek().GetComponent <Card>();                              // Referência da carta da pilha interna.

        // Caso haja cartas na pilha, checará:
        bool condition1 = (isBlack(internalCard.Suit) != isBlack(externalCard.Suit));       // Compara as cores entre as cartas, e valida se as cores forem opostas
        bool condition2 = (internalCard.Value == (externalCard.Value + 1));                 // Compara se o valor da carta a ser recebida é é uma unidade inferior e valida caso positivo
        bool condition3 = internalCard.Value > 1;                                           // Compara se a carta a ser recebida é maior do que ás, e valida se for positivo

        if (condition1 && condition2 && condition3)                                         // Checa se todas as condições fora atendidas
        {
            return(true);
        }
        else
        {
            return(false);                                                                   // Caso contrário, retorna falso.
        }
    }
Example #21
0
        public MainWindow()
        {
            InitializeComponent();
            InitializeMenu();

            history = new Stack<string>();
            ApplicationSettings settings = ObjectPool.Instance.Resolve<ApplicationSettings>();
            settings.ConfigurationLoaded += settings_ConfigurationLoaded;
            if (!firstLoaded)
            {
                firstLoaded = true; 
                if (settings.General.LaunchMinimized)
                    this.WindowState = WindowState.Minimized;

                if (settings.General.ShowTaskbarIcon)
                    this.ShowInTaskbar = true;
                else
                    this.ShowInTaskbar = false;

                ObjectPool.Instance.Register<Window>().ImplementedBy(this);
            }
            var theme = ThemeManager.DetectAppStyle(Application.Current);
            var appTheme = ThemeManager.GetAppTheme("BaseLight");
            if (theme != null)
                ThemeManager.ChangeAppStyle(Application.Current, theme.Item2, appTheme);
            else
            {
                var accent = ThemeManager.Accents.First(x => x.Name == "Blue");
                ThemeManager.ChangeAppStyle(Application.Current, accent, appTheme);
            }
                

            Current = this; 
        }
Example #22
0
        public MainWindow()
        {
            InitializeComponent();
            InitializeMenu();
            history = new Stack <string>();
            ApplicationSettings settings = ObjectPool.Instance.Resolve <ApplicationSettings>();

            settings.ConfigurationLoaded += settings_ConfigurationLoaded;
            if (!firstLoaded)
            {
                firstLoaded = true;


                if (settings.General.LaunchMinimized)
                {
                    this.WindowState = WindowState.Minimized;
                }

                if (settings.General.ShowTaskbarIcon)
                {
                    this.ShowInTaskbar = true;
                }
                else
                {
                    this.ShowInTaskbar = false;
                }

                ObjectPool.Instance.Register <Window>().ImplementedBy(this);
            }
        }
Example #23
0
        public void Enqueue(int inputValue)
        {
            if (Queue == null)
            {
                Queue = new System.Collections.Generic.Stack <int>();
            }

            Queue.Push(inputValue);
        }
Example #24
0
        public void IterativeStack(System.Collections.Generic.Stack <int> s)
        {
            var v = s.Pop();

            if (s.Count > 0)
            {
                IterativeStack(s, v);
            }
        }
Example #25
0
 public void Init()
 {
     //Inicializacion de las variables del interprete
     mp = 0;
     ip = 0;
     m = new byte[9999];
     pila = new Stack<int>();
     opers=new Regex("[\\+\\-\\.\\,\\<\\>\\[\\]]");
 }
Example #26
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);
        }
Example #27
0
        public static System.Collections.Generic.Stack <T> ToStack <T> (this LinkedList <T> list)
        {
            var stack = new System.Collections.Generic.Stack <T> ();

            foreach (var item in list)
            {
                stack.Push(item);
            }
            return(stack);
        }
Example #28
0
        static void Main(string[] args)
        {
            System.Collections.Generic.Stack <int> stack =
                new System.Collections.Generic.Stack <int>();

            PopulateStack(ref stack);
            PrintToConsole(ref stack);
            PullFromStack(ref stack);
            PrintToConsole(ref stack);
        }
Example #29
0
        /// <summary>
        /// Creates a writer to translate an incoming XSL stylesheet into a data structure.
        /// </summary>
        public XmlStylesheetWriter(Stylesheet stylesheet)
        {
            // Initialize the object;
            this.stylesheet = stylesheet;

            // This determines how to handle each of the incoming tokens parsed out of the XML stream.
            this.tokenHandlerDictionary = new Dictionary <Token, TokenHandler>();

            // This stack holds the current state of parsing the XSL language elements.  It is needed to build a tree of these
            // structures that is roughly the same as the incoming XSL document.  The stack structure is required because the
            // parsing can recursively dig down into the data structures, the unwind back up the tree before reading more child
            // elements.  The stack structure keeps track of how far down into the tree the parsing has gone.
            this.nodeStack = new Stack <Node>();
            this.nodeStack.Push(new RootNode());

            // This will create a lexical analyzer for the XSL Stylesheets and installs handlers for each of the tokens read from
            // the XML stream as it parses the stylesheet.
            this.lexicon = new Lexicon();
            this.tokenHandlerDictionary.Add(Token.Alignment, new TokenHandler(ParseAlignment));
            this.tokenHandlerDictionary.Add(Token.Animation, new TokenHandler(ParseAnimation));
            this.tokenHandlerDictionary.Add(Token.ApplyTemplate, new TokenHandler(ParseApplyTemplate));
            this.tokenHandlerDictionary.Add(Token.Attribute, new TokenHandler(ParseAttribute));
            this.tokenHandlerDictionary.Add(Token.Border, new TokenHandler(ParseBorder));
            this.tokenHandlerDictionary.Add(Token.Borders, new TokenHandler(ParseBorders));
            this.tokenHandlerDictionary.Add(Token.Cell, new TokenHandler(ParseCell));
            this.tokenHandlerDictionary.Add(Token.Choose, new TokenHandler(ParseChoose));
            this.tokenHandlerDictionary.Add(Token.Column, new TokenHandler(ParseColumn));
            this.tokenHandlerDictionary.Add(Token.Columns, new TokenHandler(ParseColumns));
            this.tokenHandlerDictionary.Add(Token.Constraint, new TokenHandler(ParseConstraint));
            this.tokenHandlerDictionary.Add(Token.Constraints, new TokenHandler(ParseConstraints));
            this.tokenHandlerDictionary.Add(Token.ColumnReference, new TokenHandler(ParseColumnReference));
            this.tokenHandlerDictionary.Add(Token.Delete, new TokenHandler(ParseDelete));
            this.tokenHandlerDictionary.Add(Token.View, new TokenHandler(ParseView));
            this.tokenHandlerDictionary.Add(Token.Font, new TokenHandler(ParseFont));
            this.tokenHandlerDictionary.Add(Token.Fragment, new TokenHandler(ParseFragment));
            this.tokenHandlerDictionary.Add(Token.If, new TokenHandler(ParseIf));
            this.tokenHandlerDictionary.Add(Token.Insert, new TokenHandler(ParseInsert));
            this.tokenHandlerDictionary.Add(Token.Interior, new TokenHandler(ParseInterior));
            this.tokenHandlerDictionary.Add(Token.NumberFormat, new TokenHandler(ParseNumberFormat));
            this.tokenHandlerDictionary.Add(Token.Otherwise, new TokenHandler(ParseOtherwise));
            this.tokenHandlerDictionary.Add(Token.Protection, new TokenHandler(ParseProtection));
            this.tokenHandlerDictionary.Add(Token.Row, new TokenHandler(ParseRow));
            this.tokenHandlerDictionary.Add(Token.Style, new TokenHandler(ParseStyle));
            this.tokenHandlerDictionary.Add(Token.Styles, new TokenHandler(ParseStyles));
            this.tokenHandlerDictionary.Add(Token.Stylesheet, new TokenHandler(ParseStylesheet));
            this.tokenHandlerDictionary.Add(Token.Table, new TokenHandler(ParseTable));
            this.tokenHandlerDictionary.Add(Token.Template, new TokenHandler(ParseTemplate));
            this.tokenHandlerDictionary.Add(Token.Update, new TokenHandler(ParseUpdate));
            this.tokenHandlerDictionary.Add(Token.ValueOf, new TokenHandler(ParseValueOf));
            this.tokenHandlerDictionary.Add(Token.Variable, new TokenHandler(ParseVariable));
            this.tokenHandlerDictionary.Add(Token.Sort, new TokenHandler(ParseSort));
            this.tokenHandlerDictionary.Add(Token.SortColumn, new TokenHandler(ParseSortColumn));
            this.tokenHandlerDictionary.Add(Token.When, new TokenHandler(ParseWhen));
            this.tokenHandlerDictionary.Add(Token.Document, new TokenHandler(ParseDocument));
        }
Example #30
0
        /// <summary>
        /// Creates a writer to translate an incoming XSL stylesheet into a data structure.
        /// </summary>
        public XmlDataTransformWriter(DataTransform dataTransform)
        {
            // Initialize the object;
            this.dataTransform = dataTransform;

            // This determines how to handle each of the incoming tokens parsed out of the XML stream.
            this.tokenHandlerDictionary = new Dictionary <Token, TokenHandler>();

            // This stack holds the current state of parsing the XSL language elements.  It is needed to build a tree of these
            // structures that is roughly the same as the incoming XSL document.  The stack structure is required because the
            // parsing can recursively dig down into the data structures, the unwind back up the tree before reading more child
            // elements.  The stack structure keeps track of how far down into the tree the parsing has gone.
            this.nodeStack = new Stack <Node>();
            this.nodeStack.Push(new RootNode());

            // This will create a lexical analyzer for the XSL DataTransforms and installs handlers for each of the tokens read from
            // the XML stream as it parses the stylesheet.
            this.lexicon = new Lexicon();
            this.tokenHandlerDictionary.Add(Token.Animation, new TokenHandler(ParseAnimation));
            this.tokenHandlerDictionary.Add(Token.ApplyTemplate, new TokenHandler(ParseApplyTemplate));
            this.tokenHandlerDictionary.Add(Token.BottomBorder, new TokenHandler(ParseBottomBorder));
            this.tokenHandlerDictionary.Add(Token.LeftBorder, new TokenHandler(ParseLeftBorder));
            this.tokenHandlerDictionary.Add(Token.RightBorder, new TokenHandler(ParseRightBorder));
            this.tokenHandlerDictionary.Add(Token.TopBorder, new TokenHandler(ParseTopBorder));
            this.tokenHandlerDictionary.Add(Token.Tile, new TokenHandler(ParseTile));
            this.tokenHandlerDictionary.Add(Token.Column, new TokenHandler(ParseColumn));
            this.tokenHandlerDictionary.Add(Token.Columns, new TokenHandler(ParseColumns));
            this.tokenHandlerDictionary.Add(Token.ColumnReference, new TokenHandler(ParseColumnReference));
            this.tokenHandlerDictionary.Add(Token.Data, new TokenHandler(ParseData));
            this.tokenHandlerDictionary.Add(Token.DataTransform, new TokenHandler(ParseDataTransform));
            this.tokenHandlerDictionary.Add(Token.View, new TokenHandler(ParseView));
            this.tokenHandlerDictionary.Add(Token.Filter, new TokenHandler(ParseFilter));
            this.tokenHandlerDictionary.Add(Token.Font, new TokenHandler(ParseFont));
            this.tokenHandlerDictionary.Add(Token.FontBrush, new TokenHandler(ParseFontBrush));
            this.tokenHandlerDictionary.Add(Token.Image, new TokenHandler(ParseImage));
            this.tokenHandlerDictionary.Add(Token.InteriorBrush, new TokenHandler(ParseInteriorBrush));
            this.tokenHandlerDictionary.Add(Token.Locks, new TokenHandler(ParseLocks));
            this.tokenHandlerDictionary.Add(Token.Lock, new TokenHandler(ParseLock));
            this.tokenHandlerDictionary.Add(Token.NumberFormat, new TokenHandler(ParseNumberFormat));
            this.tokenHandlerDictionary.Add(Token.Protection, new TokenHandler(ParseProtection));
            this.tokenHandlerDictionary.Add(Token.Row, new TokenHandler(ParseRow));
            this.tokenHandlerDictionary.Add(Token.Style, new TokenHandler(ParseStyle));
            this.tokenHandlerDictionary.Add(Token.StyleId, new TokenHandler(ParseStyleId));
            this.tokenHandlerDictionary.Add(Token.Styles, new TokenHandler(ParseStyles));
            this.tokenHandlerDictionary.Add(Token.Template, new TokenHandler(ParseTemplate));
            this.tokenHandlerDictionary.Add(Token.Scale, new TokenHandler(ParseScale));
            this.tokenHandlerDictionary.Add(Token.Split, new TokenHandler(ParseSplit));
            this.tokenHandlerDictionary.Add(Token.Scratch, new TokenHandler(ParseScratch));
            this.tokenHandlerDictionary.Add(Token.StringFormat, new TokenHandler(ParseStringFormat));
            this.tokenHandlerDictionary.Add(Token.Sort, new TokenHandler(ParseSort));
            this.tokenHandlerDictionary.Add(Token.SortColumn, new TokenHandler(ParseSortColumn));
            this.tokenHandlerDictionary.Add(Token.Source, new TokenHandler(ParseSource));
            this.tokenHandlerDictionary.Add(Token.Variable, new TokenHandler(ParseVariable));
        }
Example #31
0
        public override bool Test(HTMLElement elem, System.Collections.Generic.Stack <string> stack)
        {
            this.var = null;
            bool r = base.Test(elem);

            if (this.var != null)
            {
                stack.Push(this.var);
            }
            return(r);
        }
Example #32
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;
                    }
                }
            }
        }
 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++;
     }
 }
Example #34
0
        public MainWindow()
        {
            InitializeComponent();
            InitializeMenu();
            history = new Stack<string>();
            ApplicationSettings settings = ObjectPool.Instance.Resolve<ApplicationSettings>();
            settings.ConfigurationLoaded += settings_ConfigurationLoaded;
            if (!firstLoaded)
            {
                firstLoaded = true;
                 

                if (settings.General.LaunchMinimized)
                    this.WindowState = WindowState.Minimized;                    

                if (settings.General.ShowTaskbarIcon)
                    this.ShowInTaskbar = true;
                else
                    this.ShowInTaskbar = false;

                ObjectPool.Instance.Register<Window>().ImplementedBy(this);
            } 
        }
Example #35
0
 public static void InitializeThreads()
 {
     // Initialize the threading locks
     int nLocks = CRYPTO_num_locks();
     lock_objects = new List<object>(nLocks);
     for (int i = 0; i < nLocks; i++)
     {
         object obj = new object();
         lock_objects.Add(obj);
     }
     // Initialize the internal thread id stack
     threadIDs = new System.Collections.Generic.Stack<uint>();
     // Initialize the delegate for the locking callback
     CRYPTO_locking_callback_delegate = new CRYPTO_locking_callback(LockingCallback);
     CRYPTO_set_locking_callback(CRYPTO_locking_callback_delegate);
     // Initialze the thread id callback
     CRYPTO_id_callback_delegate = new CRYPTO_id_callback(ThreadIDCallback);
     CRYPTO_set_id_callback(CRYPTO_id_callback_delegate);
 }
Example #36
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;
        }
Example #37
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();
        }
        private void InitHelpers()
        {
            addToProgram = true;
            lastCompiledAssign = null;

            isOperatorUnaryPrefix = false;
            isCompilingAssignmentTarget = false;
            isSelectorsFirstCompile = true;
            isCurrentCompiledTheMainProgram = true;

            lazyEvaluationJumpStack = new System.Collections.Generic.Stack<Jump>();
            jumpStack = new System.Collections.Generic.Stack<Jump>();

            conditionCount = 0;
            lineLengthList = SourceInfoUtils.FindLineLengths(Source);

            currentGlobalVariableInfo = null;
            currentUserDefinedFunctionInfo = null;
        }
        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;
        }
Example #40
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;
        }
Example #41
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();
        }
Example #42
0
 // TODO: Handle default values in the comprehension
 // Q{U i in enumerable, P(i); T(i)}
 public override Expression VisitQuantifier(Quantifier quantifier) {
   if (quantifier == null) return null;
   Comprehension comprehension = quantifier.Comprehension;
   if (comprehension == null) return null;
   Block block = new Block(new StatementList());
   block.HasLocals = true;
   #region Create local to act as accumulator for the quantifier
   Local b = null;
   switch (quantifier.QuantifierType){
     case NodeType.Forall:
       b = new Local(Identifier.Empty,SystemTypes.Boolean,block);
       break;
     case NodeType.Exists:
       b = new Local(Identifier.Empty,SystemTypes.Boolean,block);
       break;
     case NodeType.ExistsUnique:
     case NodeType.Count:
     case NodeType.Max:
     case NodeType.Min:
     case NodeType.Product:
     case NodeType.Sum:
       b = new Local(Identifier.Empty,SystemTypes.Int32,block);
       break;
     default:
       Debug.Assert(false);
       return null;
   }
   #endregion Create local to act as accumulator for the quantifier
   
   if (comprehension.IsDisplay){
     #region Display: Generate a separate if-statement for each element
     Block endBlock = new Block(new StatementList());
     for(int i = 0, n = comprehension.Elements == null ? 0 : comprehension.Elements.Count; i < n; i++){
       #region assign the value of the term to b
       Statement updateB = null;
       switch (quantifier.QuantifierType){
         case NodeType.Forall:
           updateB = new AssignmentStatement(b,comprehension.Elements[i]);
           break;
         case NodeType.Exists:
           updateB = new AssignmentStatement(b,comprehension.Elements[i]);
           break;
         case NodeType.ExistsUnique:
         case NodeType.Count:
           // b := b + (T(i) ? 1 : 0)
           updateB = new AssignmentStatement(b,
             new BinaryExpression(b,
             new TernaryExpression(comprehension.Elements[i], Literal.Int32One, Literal.Int32Zero, NodeType.Conditional, SystemTypes.Int32),
             NodeType.Add));
           break;
         case NodeType.Product:
           // b := b * T(i)
           updateB = new AssignmentStatement(b, new BinaryExpression(b, comprehension.Elements[i], NodeType.Mul));
           break;
         case NodeType.Sum:
           // b := b + T(i)
           updateB = new AssignmentStatement(b, new BinaryExpression(b, comprehension.Elements[i], NodeType.Add));
           break;
         case NodeType.Max:
           // b := b < T(i) ? T(i) : b
           updateB = new AssignmentStatement(b,
             new TernaryExpression(new BinaryExpression(b, comprehension.Elements[i], NodeType.Lt, SystemTypes.Boolean),
             comprehension.Elements[i], b, NodeType.Conditional, SystemTypes.Int32));
           break;
         case NodeType.Min:
           // b := b > T(i) ? T(i) : b
           updateB = new AssignmentStatement(b,
             new TernaryExpression(new BinaryExpression(b, comprehension.Elements[i], NodeType.Gt, SystemTypes.Boolean),
             comprehension.Elements[i], b, NodeType.Conditional, SystemTypes.Int32));
           break;
         default:
           Debug.Assert(false);
           return null;
       }
       block.Statements.Add(updateB);
       #endregion assign the value of the term to b
       #region Test to see if loop should terminate early
       Expression condition = null;
       switch (quantifier.QuantifierType){
         case NodeType.Forall:
           condition = new UnaryExpression(b, NodeType.LogicalNot, SystemTypes.Boolean);
           block.Statements.Add(new Branch(condition, endBlock));
           break;
         case NodeType.Exists:
           condition = b;
           block.Statements.Add(new Branch(condition, endBlock));
           break;
         case NodeType.ExistsUnique:
           condition = new BinaryExpression(b,Literal.Int32One,NodeType.Gt,SystemTypes.Boolean);
           break;
         case NodeType.Count:
         case NodeType.Max:
         case NodeType.Min:
         case NodeType.Product:
         case NodeType.Sum:
           condition = Literal.False; // no short-circuit!! Need to evaluate all of the terms!
           break;
         default:
           Debug.Assert(false);
           return null;
       }
       #endregion Test to see if loop should terminate early
     }
     block.Statements.Add(endBlock);
     #endregion Display: Generate a separate if-statement for each element
   }else {
     #region "True" comprehension
     #region assign the value of the term to the accumulator
     Statement updateB = null;
     switch (quantifier.QuantifierType){
       case NodeType.Forall:
         // b := T(i);
         updateB = new AssignmentStatement(b,comprehension.Elements[0]);
         break;
       case NodeType.Exists:
         // b := T(i);
         updateB = new AssignmentStatement(b,comprehension.Elements[0]);
         break;
       case NodeType.ExistsUnique:
       case NodeType.Count:
         // b := b + T(i) ? 1 : 0; // TODO: is it better to try and generate "b += ..."?
         updateB = new AssignmentStatement(b,
           new BinaryExpression(b,
           new TernaryExpression(comprehension.Elements[0],Literal.Int32One,Literal.Int32Zero,NodeType.Conditional,SystemTypes.Int32),
           NodeType.Add));
         break;
       case NodeType.Product:
         // b := b * T(i)
         updateB = new AssignmentStatement(b,
           new BinaryExpression(b, comprehension.Elements[0], NodeType.Mul));
         break;
       case NodeType.Sum:
         // b := b + T(i)
         updateB = new AssignmentStatement(b,
           new BinaryExpression(b, comprehension.Elements[0], NodeType.Add));
         break;
       case NodeType.Max:
         // b := b < T(i) ? T(i) : b
         updateB = new AssignmentStatement(b,
           new TernaryExpression(new BinaryExpression(b, comprehension.Elements[0], NodeType.Lt, SystemTypes.Boolean),
           comprehension.Elements[0], b, NodeType.Conditional, SystemTypes.Int32));
         break;
       case NodeType.Min:
         // b := b > T(i) ? T(i) : b
         updateB = new AssignmentStatement(b,
           new TernaryExpression(new BinaryExpression(b, comprehension.Elements[0], NodeType.Gt, SystemTypes.Boolean),
           comprehension.Elements[0], b, NodeType.Conditional, SystemTypes.Int32));
         break;
       default:
         Debug.Assert(false);
         return null;
     }
     block.Statements.Add(updateB);
     #endregion assign the value of the term to the accumulator
     #region Generate the "foreach" and "if P(x)" parts
     for (int i = comprehension.BindingsAndFilters.Count - 1; i >= 0; i--) {
       ComprehensionBinding binding = comprehension.BindingsAndFilters[i] as ComprehensionBinding ;
       if (binding != null){
         #region Test to see if loop should terminate early
         Expression condition = null;
         switch (quantifier.QuantifierType){
           case NodeType.Forall:
             condition = new UnaryExpression(b,NodeType.LogicalNot,SystemTypes.Boolean);
             break;
           case NodeType.Exists:
             condition = b;
             break;
           case NodeType.ExistsUnique:
             condition = new BinaryExpression(b,Literal.Int32One,NodeType.Gt,SystemTypes.Boolean);
             break;
           case NodeType.Count:
           case NodeType.Max:
           case NodeType.Min:
           case NodeType.Product:
           case NodeType.Sum:
             condition = Literal.False; // no short-circuit!! Need to evaluate all of the terms!
             break;
           default:
             Debug.Assert(false);
             return null;
         }
         block.Statements.Add(new If(condition,new Block(new StatementList(new Exit())),null));
         #endregion Test to see if loop should terminate early
         #region Wrap everything so far into a loop (either for or foreach)
         Expression forEachTargetVariable = binding.TargetVariable;
         if (binding.AsTargetVariableType != null){
           Local l = new Local(Identifier.For("SS$dummyForEachVar"),binding.SourceEnumerable.Type,block);
           forEachTargetVariable = l;
           Block b2 = new Block(new StatementList(2));
           b2.Statements.Add(new AssignmentStatement(binding.TargetVariable,
             new BinaryExpression(l,new MemberBinding(null,binding.AsTargetVariableType),NodeType.Isinst,binding.AsTargetVariableType)));
           b2.Statements.Add(new If(new BinaryExpression(binding.TargetVariable,new Literal(null,SystemTypes.Type),NodeType.Ne),
             block,null));
           block = b2;
         }
         if (binding.SourceEnumerable== null) 
           return null;
         CollectionEnumerator ce = binding.SourceEnumerable as CollectionEnumerator;
         UnaryExpression u = ce == null ? null : ce.Collection as UnaryExpression;
         BinaryExpression be = u == null ? null : u.Operand as BinaryExpression;
         if (be != null && be.NodeType == NodeType.Range){
           // implement Range with a for-loop
           AssignmentStatement init = new AssignmentStatement(forEachTargetVariable,be.Operand1);
           AssignmentStatement incr = new AssignmentStatement(forEachTargetVariable,
             new BinaryExpression(forEachTargetVariable,new Literal(1,SystemTypes.Int32),NodeType.Add,SystemTypes.Int32));
           Expression cond = new BinaryExpression(forEachTargetVariable,be.Operand2,NodeType.Le,SystemTypes.Boolean);
           #region Add loop invariant "be.Operand1 <= forEachTargetVariable"
           Block invariantBlock = new Block(new StatementList());
           Assertion assertion = new Assertion(new BinaryExpression(be.Operand1, forEachTargetVariable, NodeType.Le, SystemTypes.Boolean));
           assertion.SourceContext = be.SourceContext;
           foreach (Statement s in this.SerializeAssertion(this.currentModule, assertion.Condition, "For loop index must be at least first operand of range.", assertion.SourceContext, "LoopInvariant")) {
             invariantBlock.Statements.Add(s);
           }
           // need to put the generated invariants in the for-loop's condition because that's where VisitFor
           // puts any user-declared invariants.
           invariantBlock.Statements.Add(new ExpressionStatement(cond, cond.SourceContext));
           cond = new BlockExpression(invariantBlock, SystemTypes.Boolean);
           #endregion
           For forloop = new For(new StatementList(init),cond,new StatementList(incr),block);
           block = new Block(new StatementList(forloop));
         }else{
           // Just use the source enumerable as an IEnumerable in a foreach loop
           ForEach fe = new ForEach(binding.SourceEnumerable.Type,forEachTargetVariable,binding.SourceEnumerable,block);
           fe.ScopeForTemporaryVariables = binding.ScopeForTemporaryVariables;
           block = new Block(new StatementList(fe));
         }
         #endregion Wrap everything so far into a loop (either for or foreach)
       }else{ // it's a filter
         block = new Block(new StatementList(new If(comprehension.BindingsAndFilters[i],block,null)));
       }
     }
     #endregion
     #endregion
   }
   #region Choose initial value for accumulator
   Literal initialValue = null;
   switch (quantifier.QuantifierType){
     case NodeType.Forall:
       initialValue = Literal.True;
       break;
     case NodeType.Exists:
       initialValue = Literal.False;
       break;
     case NodeType.ExistsUnique:
     case NodeType.Count:
     case NodeType.Sum:
       initialValue = Literal.Int32Zero;
       break;
     case NodeType.Product:
       initialValue = Literal.Int32One;
       break;
     case NodeType.Max:
       initialValue = new Literal(Int32.MinValue, SystemTypes.Int32);
       break;
     case NodeType.Min:
       initialValue = new Literal(Int32.MaxValue, SystemTypes.Int32);
       break;
     default:
       Debug.Assert(false);
       return null;
   }
   #endregion Choose initial value for accumulator
   #region Set the return value of the quantifier
   Expression valueToReturn = null;
   switch (quantifier.QuantifierType){
     case NodeType.Forall:
       valueToReturn = b;
       break;
     case NodeType.Exists:
       valueToReturn = b;
       break;
     case NodeType.ExistsUnique:
       valueToReturn = new BinaryExpression(b,Literal.Int32One,NodeType.Eq,SystemTypes.Boolean);
       break;
     case NodeType.Count:
     case NodeType.Max:
     case NodeType.Min:
     case NodeType.Product:
     case NodeType.Sum:
       valueToReturn = b;
       break;
     default:
       Debug.Assert(false);
       return null;
   }
   #endregion Set the boolean to return as the value of the quantifier
   BlockExpression returnBlock = new BlockExpression(
     new Block(new StatementList(
     new AssignmentStatement(b,initialValue),
     block,
     new ExpressionStatement(valueToReturn))),
     SystemTypes.Boolean,comprehension.SourceContext);
   if (this.quantifiedVarStack == null) this.quantifiedVarStack = new System.Collections.Generic.Stack<ExpressionList>();
   this.quantifiedVarStack.Push(comprehension.BindingsAndFilters);
   Expression result = this.VisitBlockExpression(returnBlock);
   this.quantifiedVarStack.Pop();
   return result;
 }
Example #43
0
 public DependentSubExpSeeker(System.Collections.Generic.Dictionary<string,bool> quantifiedVars) {
   this.quantifiedVars = quantifiedVars;
   trace = new System.Collections.Generic.Stack<Expression>();
   dependents = new System.Collections.Generic.Dictionary<Expression,bool>();
 }
Example #44
0
 public PrefixHolder()
 {
   this.prefix = new System.Text.StringBuilder();
   this.lengths = new System.Collections.Generic.Stack<int>();
 }
Example #45
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);
            }
        }
Example #46
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;
        }
        private void ParseAndSetSpecifiedText(string text)
        {
            // Clear the collection of Inlines
            SelectAll();
            this.Selection.Text = "";
            // Wrap the input in a <div> (so even plain text becomes valid XML)
            using (var stringReader = new StringReader(string.Concat("<div>", text, "</div>")))
            {
                DocTree RootElement = new DocTree(new Span(), 0, 0) { FontSize = 10 };
                DocTree currentElement = RootElement;
                // Read the input
                using (var xmlReader = XmlReader.Create(stringReader))
                {
                    // State variables
                    var bold = 0;
                    var italic = 0;
                    var underline = 0;
                    var td = 0;
                    var tr = 0;
                    Stack<double> fontSize = new Stack<double>();
                    fontSize.Push(10);
                    System.Collections.Generic.Stack<TextElement> elementTree = new System.Collections.Generic.Stack<TextElement>();
                    string link = null;
                    var lastElement = elementP;
                    // Read the entire XML DOM...
                    while (xmlReader.Read())
                    {
                        var nameUpper = xmlReader.Name.ToUpper();
                        switch (xmlReader.NodeType)
                        {
                            case XmlNodeType.Element:
                                // Handle the begin element
                                switch (nameUpper)
                                {
                                    case "H1":
                                        fontSize.Push(24);
                                        break;
                                    case "H2":
                                        fontSize.Push(18);
                                        break;
                                    case "H3":
                                        fontSize.Push(14);
                                        break;
                                    case "H4":
                                        fontSize.Push(12);
                                        break;
                                    case elementA:
                                        link = "";
                                        // Look for the HREF attribute (can't use .MoveToAttribute because it's case-sensitive)
                                        if (xmlReader.MoveToFirstAttribute())
                                        {
                                            do
                                            {
                                                if ("HREF" == xmlReader.Name.ToUpper())
                                                {
                                                    // Store the link target
                                                    link = xmlReader.Value;
                                                    break;
                                                }
                                            } while (xmlReader.MoveToNextAttribute());
                                        }
                                        break;
                                    case elementB:
                                    case elementSTRONG: bold++; break;
                                    case elementI:
                                    case elementEM: italic++; break;
                                    case elementU: underline++; break;
                                    case elementBR:
                                        currentElement.Children.Add(new DocTree(new LineBreak(), tr, td));
                                        break;
                                    //Selection.Insert(new LineBreak() ); break;
                                    case elementTR:
                                        tr++; td = 0; break;
                                    case elementTD:
                                        td++; break;
                                    case "TH":
                                        td++;
                                        bold++;
                                        break;
                                    case elementTABLE:
                                        DocTree p = new DocTree(new Table(), tr, td);
                                        currentElement.Children.Add(p);
                                        tr = 0; td = 0;
                                        currentElement = p;
                                        break;
                                    case elementP:
                                        DocTree p2 = new DocTree(new InlineParaGraph(), tr, td);
                                        currentElement.Children.Add(p2);
                                        currentElement = p2;
                                        break;
                                    case elementImage:
                                        var img = new InlineUIContainer()
                                        {
                                            Child = new Image()
                                            {
                                                Source = new System.Windows.Media.Imaging.BitmapImage(
                                                    new System.Uri(xmlReader.GetAttribute("src"), System.UriKind.Absolute)
                                                ),
                                                Stretch = Stretch.None //This should be improved to read image size if set
                                            }
                                        };
                                        currentElement.Children.Add(new DocTree(img, tr, td));
                                        break;
                                }
                                lastElement = nameUpper;
                                break;
                            case XmlNodeType.EndElement:
                                // Handle the end element
                                switch (nameUpper)
                                {
                                    case elementA: link = null; break;
                                    case elementB:
                                    case elementSTRONG: bold--; break;
                                    case elementI:
                                    case elementEM: italic--; break;
                                    case elementU: underline--; break;
                                    case "H1":
                                    case "H2":
                                    case "H3":
                                    case "H4":
                                        fontSize.Pop();
                                        break;
                                    case elementTR:
                                        td = 0; break;
                                    case elementTD:
                                        break;
                                    case "TH":
                                        bold--;
                                        break;
                                    case elementTABLE:
                                        tr = 0; td = 0;
                                        currentElement = currentElement.Parent ?? RootElement;
                                        break;
                                    case elementP:
                                        currentElement = currentElement.Parent ?? RootElement;
                                        //Selection.Insert(elementTree.Pop());
                                        //Selection.Insert(new LineBreak());
                                        //Selection.Insert(new LineBreak());
                                        break;
                                }
                                lastElement = nameUpper;
                                break;
                            case XmlNodeType.Text:
                            case XmlNodeType.Whitespace:
                                // Create a Run for the visible text
                                // Collapse contiguous whitespace per HTML behavior
                                StringBuilder builder = new StringBuilder(xmlReader.Value.Length);
                                var last = '\0';
                                foreach (char c in xmlReader.Value.Replace('\n', ' '))
                                {
                                    if ((' ' != last) || (' ' != c))
                                    {
                                        builder.Append(c);
                                    }
                                    last = c;
                                }
                                // Trim leading whitespace if following a <P> or <BR> element per HTML behavior
                                var builderString = builder.ToString();
                                if ((elementP == lastElement) || (elementBR == lastElement))
                                {
                                    builderString = builderString.TrimStart();
                                }
                                // If any text remains to display...
                                if (0 < builderString.Length)
                                {
                                    // Create a Run to display it
                                    Run run = new Run
                                    {
                                        Text = builderString,
                                        FontSize = currentElement.FontSize
                                    };

                                    // Style the Run appropriately
                                    if (0 < bold) run.FontWeight = FontWeights.Bold;
                                    if (0 < italic) run.FontStyle = FontStyles.Italic;
                                    if (0 < underline) run.TextDecorations = System.Windows.TextDecorations.Underline;
                                    if (fontSize.Count > 0) run.FontSize = fontSize.Peek();
                                    if (null != link)
                                    {
                                        // Links get styled and display their HREF since Run doesn't support MouseLeftButton* events
                                        run.TextDecorations = System.Windows.TextDecorations.Underline;
                                        run.Foreground = HyperlinkColor ?? new SolidColorBrush { Color = Color.FromArgb(255, 177, 211, 250) };
                                        Hyperlink hlink = new Hyperlink()
                                        {
                                            NavigateUri = new System.Uri(link, System.UriKind.RelativeOrAbsolute),
                                            TargetName = "_blank"
                                        };
                                        hlink.Inlines.Add(run);
                                        currentElement.Children.Add(new DocTree(hlink, tr, td));
                                    }
                                    else
                                        // Add the Run to the collection
                                        currentElement.Children.Add(new DocTree(run, tr, td));
                                    lastElement = null;
                                }
                                break;
                        }
                    }

                }
                Span s = new Span();
                DocTreeToTextElement(RootElement, s.Inlines);
                Selection.Insert(s);
            }
        }
        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() );
        }