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

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

            while (stack.Any())
            {
                node = stack.Peek();
                if (node != null)
                {
                    stack.Push(node);
                    node = node.Left;
                }
                else
                {
                    var item = stack.Peek();
                    if (item.Right != null && !visited.Contains(item.Right))
                    {
                        node = item.Right;
                    }
                    else
                    {
                        System.Console.Write(node.Data + " ");
                        visited.Add(item);
                        stack.Pop();
                    }
                }
            }
        }
Exemplo n.º 2
0
            /**
             * The pop implementation
             */
            public void Pop()
            {
                postPopEvent();

                /**
                 * If the stack is not empty show the top element of the stack
                 */
                if (0 < mStack.Count)
                {
                    MoSync.Util.RunActionOnMainThreadSync(() =>
                    {
                        mAddChildDelegate = delegate()
                        {
                            if (mPage.Children.Count > 0)
                            {
                                mPage.Children.RemoveAt(mPage.Children.Count - 1);
                            }
                            mPage.Children.Add((mStack.Peek() as Screen).View);
                            Grid.SetColumn(mPage.Children[mPage.Children.Count - 1] as Grid, 0);
                            Grid.SetRow(mPage.Children[mPage.Children.Count - 1] as Grid, 0);

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

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

            //将本次事务处理的资源管理器压入资源栈中
            depentran.EnlistVolatile(source, EnlistmentOptions.None);
            _tranStack.Push(depentran);
            _resourceStack.Push(source);
            //切换环境事务场景
            Transaction.Current = depentran;
            if (NextEvent != null)
            {
                if (NextEvent.GetInvocationList().Length > 0)
                {
                    NextEvent(Transaction.Current);
                }
            }
        }
Exemplo n.º 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();
        }
Exemplo n.º 5
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.
        }
    }
        public static double integrate(func f, System.Collections.Generic.IReadOnlyList <double> init_ticks, double eps1)
        {
            var points = new System.Collections.Generic.Stack <Point>();
            var areas  = new System.Collections.Generic.List <double>();

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

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

            while (points.Count > 1)
            {
                //Console.WriteLine(points.Count);
                right = points.Pop();
                var left = points.Peek();
                var mid  = Integration.midpoint(ref left, ref right, f);
                if (Math.Abs(left.f + right.f - mid.f * 2.0) <= eps)
                {
                    areas.Add((left.f + right.f + mid.f * 2.0) * (right.x - left.x) / 4.0);
                }
                else
                {
                    points.Push(mid);
                    points.Push(right);
                }
            }
            areas.Sort(delegate(double x, double y){
                return(Math.Abs(x).CompareTo(Math.Abs(y)));
            });
            return(areas.Sum());
        }
Exemplo n.º 7
0
        private CalendarItem getCalendarItem(string clndr_data)
        {
            CalendarItem returnvalue;

            System.Collections.Generic.Stack <CalendarItem> stack1 = new System.Collections.Generic.Stack <CalendarItem>();


            long level = 0;

            long[] currentlevel       = new long[20];
            System.IO.StringReader sr = new System.IO.StringReader(clndr_data.Replace("(", "\n(").Replace(")", "\n)").Replace(" ", ""));
            string aline = sr.ReadLine();

            aline = sr.ReadLine();
            System.IO.StringWriter sw = new System.IO.StringWriter();
            System.Collections.Generic.List <CalendarItem> adam = new List <CalendarItem>();
            while (aline != null)
            {
                if (aline.StartsWith("("))
                {
                    string       name = aline.Replace("(", "");
                    CalendarItem pci  = stack1.Count > 0? stack1.Peek() as CalendarItem:null;
                    CalendarItem ci   = new CalendarItem(level++, name, pci);
                    adam.Add(ci);
                    if (stack1.Count > 0)
                    {
                        stack1.Peek().addItem(ci);
                    }
                    stack1.Push(ci);
                    sw.WriteLine(ci.Name + "," + level.ToString() + "," + aline);
                }
                else if (aline == ")")
                {
                    if (stack1.Count > 1)
                    {
                        stack1.Pop();
                    }
                }


                aline = sr.ReadLine();
            }
            returnvalue = stack1.Pop();
            returnvalue.Adam.AddRange(adam);
            return(returnvalue);
        }
Exemplo n.º 8
0
 /// <remarks>Returns the current statement in the abstract syntax tree being compiled.  Will return null if no statement is on the statement stack.</remarks>
 public Statement CurrentStatement()
 {
     if (_statementStack.Count > 0)
     {
         return(_statementStack.Peek());
     }
     return(null);
 }
Exemplo n.º 9
0
        static TextTpl ResourceLoader(string input)
        {
            var tp = new TextTpl();

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

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

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

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

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

            if (startIndex < input.Length)
            {
                var pt = new TextTpl();
                pt.Text     = input.Substring(startIndex);
                pt.Children = new List <TextTpl>();
                tp.Children.Add(pt);
            }
            if (stack.Count > 1)
            {
                tp.Text = "未配置正确请求标签,请检查";
            }
            return(tp);
        }
Exemplo n.º 10
0
        public int Peek()
        {
            if (Isempty())
            {
                throw new InvalidOperationException();
            }

            MoveStack1ToStack2();

            return(stack2.Peek());
        }
Exemplo n.º 11
0
        public virtual Gen::IEnumerable <Gen::Stack <HTMLElement> > EnumerateSelectRoute(HTMLElement parent)
        {
            int m = simpleEnums.Length;

            if (m == 0)
            {
                yield break;
            }
            System.Collections.IEnumerator[] @enum  = new System.Collections.IEnumerator[m];
            /*☆*/ Gen::Stack <HTMLElement>   estack = new System.Collections.Generic.Stack <HTMLElement>();

            /*☆*/ estack.Push(parent);
            bool move; int i = 0, imax = m - 1;

            @enum[0] = this.simpleEnums[0].Enumerate(estack.Peek()).GetEnumerator();
            while (i >= 0)
            {
                try{ move = @enum[i].MoveNext(); }catch (System.Exception exc) {
                    __dll__.log.WriteError(exc, "HTML 要素の列挙中にエラーが発生しました。(列挙に使用している Selector は " + this.ToString() + " )");
                    yield break;
                }
                if (move)
                {
                    /*☆*/ estack.Push((HTMLElement)@enum[i].Current);
                    if (i == imax)
                    {
                        /*☆*/ yield return((Gen::Stack <HTMLElement>)((System.ICloneable)estack).Clone());;
                        /*☆*/ estack.Pop();
                    }
                    else
                    {
                        @enum[++i] = simpleEnums[i].Enumerate(estack.Peek()).GetEnumerator();
                    }
                }
                else
                {
                    i--;
                    /*☆*/ estack.Pop();
                }
            }
        }
Exemplo n.º 12
0
 public int Peek()
 {
     if (Empty())
     {
         throw new InvalidOperationException("queue empty");
     }
     else
     {
         MoveStack1toStack2();
         return(s2.Peek());
     }
 }
Exemplo n.º 13
0
 private void LoadFiles(string path)
 {
     listViewFiles.Items.Clear();
     if (_roots.Count > 0)
     {
         ListViewItem    item = new ListViewItem("..");
         SkydriveContent sc   = new SkydriveContent();
         sc.Type         = "folder";
         sc.ParentId     = _roots.Peek();
         item.Tag        = sc;
         item.ImageIndex = 1;
         listViewFiles.Items.Add(item);
     }
     comboBoxFileName.Items.Clear();
     foreach (SkydriveContent f in _api.GetFiles(path))
     {
         if (f.IsFile || f.IsFolder)
         {
             ListViewItem item = new ListViewItem(f.Name);
             item.SubItems.Add(f.UpdatedTime.ToShortDateString() + " " + f.UpdatedTime.ToShortTimeString());
             item.SubItems.Add(FormatBytesToDisplayFileSize(f.Size));
             item.Tag = f;
             if (f.IsFile)
             {
                 item.ImageIndex = 0;
                 comboBoxFileName.Items.Add(f.Name);
             }
             else
             {
                 item.ImageIndex = 1;
             }
             listViewFiles.Items.Add(item);
         }
     }
     if (listViewFiles.Items.Count > 0)
     {
         listViewFiles.Items[0].Selected = true;
     }
 }
Exemplo n.º 14
0
        private bool OnUpdatesTimeout()
        {
            lock (updates)
            {
                foreach (ListTupple update in updates)
                {
                    if (update == null)
                    {
                        stack.Pop();
                    }
                    else
                    {
                        Source source = (Source)update[0];
                        string label  = (string)update[1];
                        object tag    = update[2];
                        object link   = update[3];

                        GtkProofBox linkBox = null;

                        if (link != null)
                        {
                            linkBox = new GtkProofBox(tags[link]);
                            label   = label + " ->";
                        }

                        TreeIter iter;

                        if (stack.Count == 0)
                        {
                            iter = store.AppendValues(label, source, linkBox);
                        }
                        else
                        {
                            iter = store.AppendValues(stack.Peek(), label, source, linkBox);
                        }

                        stack.Push(iter);

                        if (tag != null)
                        {
                            TreePath path = store.GetPath(iter);
                            tags[tag] = path;
                        }
                    }
                }

                updates.Clear();
            }

            return(true);
        }
        /// <summary>
        /// Given a string of opening and closing parentheses, check whether it’s balanced. We have 3 types of parentheses: round brackets: (), square brackets: [], and curly brackets: {}. Assume that the string doesn’t contain any other character than these, no spaces words or numbers. As a reminder, balanced parentheses require every opening parenthesis to be closed in the reverse order opened. For example ‘([])’ is balanced but ‘([)]’ is not. You can assume the input string has no spaces.
        /// </summary>
        /// <param name="inputStr"></param>
        /// <returns></returns>
        public static bool AreParenthesesBalanced(string inputStr)
        {
            //if the number is odd, directly return false
            if (inputStr.Length % 2 != 0)
            {
                return(false);
            }

            System.Collections.Generic.Stack <char> stack = new System.Collections.Generic.Stack <char>();
            HashSet <char> leftBrackets = new HashSet <char>("([{");

            foreach (char c in inputStr)
            {
                if (leftBrackets.Contains(c))
                {
                    stack.Push(c);                           //if current char is a left bracket, then push the it into the stack
                }
                else //if a right bracket
                {
                    if (stack.Count == 0)
                    {
                        return(false);                  //make sure the first item should not be the right bracket, otherwise directly return false. Without this check, the loop will iterate the end, which is unnecessary.
                    }
                    char paired;
                    switch (c)
                    {
                    case ')': paired = '('; break;

                    case ']': paired = '['; break;

                    case '}': paired = '{'; break;

                    default: return(false);
                    }
                    if (stack.Peek() == paired)
                    {
                        stack.Pop();                         // if matches, then pop stack
                    }
                    else
                    {
                        return(false); //if not match, return false
                    }
                }
            }

            return(stack.Count == 0); //stack should be empty if passed the checking.
        }
Exemplo n.º 16
0
    public void OnUndo()
    {
        if (undoStack.Count == 1)        // undo stack only have base canvas image
        {
            return;
        }

        CanvasSnapshot previousCanvas = undoStack.Pop();
        CanvasSnapshot currentCanvas  = undoStack.Peek();

        this.texture = Instantiate(currentCanvas.CanvasTex) as Texture2D; // make clone of texture to perform deep copy
        redoStack.Push(previousCanvas);                                   // there is no need to deep copy. b/c previousCanvas is popped.

        setTextureToMypaint(currentCanvas.CanvasBuf);
        //TODO set timer

        this.texture.Apply(false);
    }
Exemplo n.º 17
0
        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>();
            double total_area = 0;
            double comp       = 0;

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

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

            while (points.Count > 0)
            {
                //Console.WriteLine(points.Count);
                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);
                    double area = (left.f + right.f + mid.f * 2.0) * (right.x - left.x) / 4.0;
                    (total_area, comp) = neumaier_sum(total_area, area, comp);

                    right = points.Pop();
                }
                else
                {
                    points.Push(mid);
                }
            }
            return(total_area + comp);
        }
Exemplo n.º 18
0
        static int[] parseString(string[,] parseTable, Grammar grammar, string str, string[,] parseInputTable)
        {
            int[] ret = new int[2];
            //parseInputTable= new string[30,4];
            Stack <int>    stack       = new System.Collections.Generic.Stack <int>();
            Stack <string> symbol      = new System.Collections.Generic.Stack <string>();
            int            inp_pointer = 0;

            Console.WriteLine();
            stack.Push(0);
            Production[] x     = grammar.PrecedenceGroups[0].Productions;
            string[]     token = grammar.Tokens;
            Console.WriteLine("Stack\tSymbol\tInput\tAction");
            parseInputTable[0, 0] = "Stack";
            parseInputTable[0, 1] = "Symbol";
            parseInputTable[0, 2] = "Input";
            parseInputTable[0, 3] = "Action";
            int l = 0;

            while (true)
            {
                // Console.WriteLine(++l);
                //input parsing
                l++;
                if (stack.Count != 0)
                {
                    string temp;
                    temp = print(stack);
                    if (stack.Count > 2)
                    {
                        temp += stack.Peek();
                        Console.Write(stack.Peek());
                    }
                    parseInputTable[l, 0] = temp;
                }
                else
                {
                    Console.Write("");
                }
                Console.Write("\t");
                if (symbol.Count != 0)
                {
                    string temp;
                    temp = print(symbol);
                    if (symbol.Count > 2)
                    {
                        Console.Write(symbol.Peek());
                        temp += symbol.Peek();
                    }
                    parseInputTable[l, 1] = temp;
                }
                else
                {
                    Console.Write("");
                }
                Console.Write("\t");
                Console.Write(str.Substring(inp_pointer, str.Length - inp_pointer));
                parseInputTable[l, 2] = str.Substring(inp_pointer, str.Length - inp_pointer);

                string value = parseTable[stack.Peek() + 1, getIndex(token, str, inp_pointer)];
                if (stack.Peek() == 0 && symbol.Count != 0 && symbol.Peek() == "S" && str[inp_pointer] == '$')
                {
                    Console.WriteLine("\n Input parsed!!");
                    ret[0] = 1;
                    ret[1] = l;
                    return(ret);
                    //break;
                }

                else if (value.Contains("S"))
                {
                    int state = Int32.Parse(value[2].ToString());
                    stack.Push(state);

                    symbol.Push(str[inp_pointer].ToString());
                    inp_pointer++;
                    Console.WriteLine("\tShift " + state);
                    parseInputTable[l, 3] = "\tShift " + state;
                }
                else if (value.Contains("R"))
                {
                    int prod_no = Int32.Parse(value[2].ToString());
                    for (int i = 0; i < x[prod_no].Right.Length; i++)
                    {
                        symbol.Pop();
                        stack.Pop();
                    }
                    int token_inserted = x[prod_no].Left;
                    symbol.Push(token[token_inserted]);
                    //Console.WriteLine(stack.Peek() + "\t" + symbol.Peek() + "\t" + str.Substring(inp_pointer, str.Length - inp_pointer));

                    if (stack.Peek() == 0 && symbol.Count != 0 && symbol.Peek() == "S" && str[inp_pointer] == '$')
                    {
                        Console.WriteLine("\n Input parsed!!");
                        ret[0] = 1;
                        ret[1] = l;
                        return(ret);
                        // break;
                    }
                    string temp           = parseTable[stack.Peek() + 1, token_inserted + 2];
                    int    state_inserted = Int32.Parse(temp[2].ToString());
                    stack.Push(state_inserted);
                    Console.WriteLine("\tReduce " + prod_no);
                    parseInputTable[l, 3] = "\tReduce " + prod_no;
                }
                else
                {
                    Console.WriteLine("\nParse error!");
                    ret[0] = -1;
                    ret[1] = l;
                    return(ret);
                    //break;
                }
            }
        }
        private static SelectionCriterion _ParseCriterion(String s)
        {
            if (s == null)
            {
                return(null);
            }

            // inject spaces after open paren and before close paren, etc
            s = NormalizeCriteriaExpression(s);

            // no spaces in the criteria is shorthand for filename glob
            if (s.IndexOf(" ") == -1)
            {
                s = "name = " + s;
            }

            // 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++)
            {
                string tok1 = tokens[i].ToLower();
                switch (tok1)
                {
                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(), true);
                    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 (FormatException)
                    {
                        try
                        {
                            t = DateTime.ParseExact(tokens[i + 2], "yyyy/MM/dd-HH:mm:ss", null);
                        }
                        catch (FormatException)
                        {
                            try
                            {
                                t = DateTime.ParseExact(tokens[i + 2], "yyyy/MM/dd", null);
                            }
                            catch (FormatException)
                            {
                                try
                                {
                                    t = DateTime.ParseExact(tokens[i + 2], "MM/dd/yyyy", null);
                                }
                                catch (FormatException)
                                {
                                    t = DateTime.ParseExact(tokens[i + 2], "yyyy-MM-dd", null);
                                }
                            }
                        }
                    }
                    t       = DateTime.SpecifyKind(t, DateTimeKind.Local).ToUniversalTime();
                    current = new TimeCriterion
                    {
                        Which    = (WhichTime)Enum.Parse(typeof(WhichTime), tokens[i], true),
                        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("'") && m.EndsWith("'"))
                    {
                        // trim off leading and trailing single quotes and
                        // revert the control characters to spaces.
                        m = m.Substring(1, m.Length - 2)
                            .Replace("\u0006", " ");
                    }

                    // if (m.StartsWith("'"))
                    //     m = m.Replace("\u0006", " ");

                    //Fix for Unix -> NormalizeCriteriaExpression replaces all slashes with backslashes
                    if (Path.DirectorySeparatorChar == '/')
                    {
                        m = m.Replace('\\', Path.DirectorySeparatorChar);
                    }

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

                case "attrs":
                case "attributes":
                case "type":
                {
                    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 = (tok1 == "type")
                                ? (SelectionCriterion) new TypeCriterion
                    {
                        AttributeString = tokens[i + 2],
                        Operator        = c
                    }
                                : (SelectionCriterion) new AttributesCriterion
                    {
                        AttributeString = tokens[i + 2],
                        Operator        = c
                    };
                    i += 2;
                    stateStack.Push(ParseState.CriterionDone);
                }
                break;

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

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

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

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

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

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

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

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

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

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

            SelectionCriterion current = null;

            LogicalConjunction pendingConjunction = LogicalConjunction.NONE;

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

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

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

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

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

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

                        stateStack.Push(ParseState.OpenParen);
                        break;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            return current;
        }
Exemplo n.º 21
0
 public IValue Peek()
 {
     return(_stack.Peek());
 }
Exemplo n.º 22
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
                {
                    // 是操作数
                    // 直接输出
                    output.Add(item);
                }
            }

            // 遍历结束,输出栈中全部剩余
            while (opr.Count > 0)
            {
                output.Add(opr.Pop());
            }

            return(output);
        }
Exemplo n.º 23
0
 public T Peek() => stack.Peek();
Exemplo n.º 24
0
	// Update is called once per frame
	void Update ()
	{
		if(inEditMode && Input.GetMouseButtonUp(0))
		{
			Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
			RaycastHit hitInfo;
			if(Physics.Raycast(ray,out hitInfo))
			{
				if(hitInfo.collider.gameObject.tag == "gridPanel")
				{
					triangleNode node = findOutlineNode(hitInfo.collider.gameObject.transform.parent.gameObject);
					if(node != null && GetComponent<HandleUI>().IsAdding())
					{
						string c = GetComponent<HandleUI>().GetColourString();
						Vector2 realCoords = getRealCoords(node.x, node.y);
						if(grid[(int)realCoords.x,(int)realCoords.y] == null)
						{
							createTriangleOnGrid(node.x, node.y, c);
						}
					}
				}
				else if(hitInfo.collider.gameObject.tag == "Triangle")
				{
					triangleNode node = getNode(hitInfo.collider.gameObject);
					if(node != null && !GetComponent<HandleUI>().IsAdding()
					   && !(node.x == 0 && node.y == 0))
					{
						Vector2 realCoords = getRealCoords(node.x, node.y);
						grid[(int)realCoords.x,(int)realCoords.y] = null;
						Destroy(hitInfo.collider.gameObject);
					}
				}
			}
		}

		GameObject[] triangles = GameObject.FindGameObjectsWithTag("Triangle");
		GameObject gObject = GameObject.FindGameObjectWithTag("Queue");

		queue queueScript = gObject.GetComponent<queue>();

		if(GlobalFlags.updateControlPoints)			
		{
			updateAllAttractionPoints();
			GlobalFlags.updateControlPoints = false;

			//if all triangles are atatched to grid, let the player fire again
			if(allTrianglesStatic())
			{
				GlobalFlags.trianglesStatic = true;
				if (queueScript.trisLeftInQueue() == 0 && triangles.Length != 1) {
					if(GlobalFlags.getMusicVolume() > 0.1f)
					{
						music.audio.volume = 0.1f;
					}
					music.setSeStartTime(Time.time, 2);
					music.playSoundEffect("gameOver");
					Application.LoadLevel("EndGameMenu");
				}
			}
		}

		if(!inEditMode)
		{
			GameObject[] queueTriangles = GameObject.FindGameObjectsWithTag("QueueTriangle");
			GlobalFlags.setQueueBonusTotal(queueTriangles.Length * GlobalFlags.getQueueBounus());

			//decrement delay time
			if(((elapsedChainDelay > 0 && elapsedChainDelay != float.MaxValue)) && (chainedClusters.Count == 0 || (chainedClusters.Count > 0 && !chainedClusters.Peek().skipDelay)))
			{
				elapsedChainDelay -= Time.deltaTime;
			}
			else if (elapsedChainDelay != float.MaxValue)
			{
				elapsedChainDelay = float.MaxValue;
			
				//if clusters left to deal with, color them and chain more
				if(chainedClusters.Count > 0)
				{
					GlobalFlags.incrementMultiplier();
					CheckForGreaterTriangle(chainedClusters.Pop());
					startChainDelay();
				
				}
				else if(chainedClusters.Count == 0)
				{
		
					foreach (triangleNode n in grid)
					{
						if(n != null && n.delayedDestroy && n.triangleObject.GetComponent<TriangleColour>().GetColour() != Color.black)
						{
							Destroy(n.triangleObject);
							deleteNode(n.x, n.y);
						}
						else if(n != null) // if it is black, set to not deleted
						{
							n.delayedDestroy = false;
						}
					}
					
					//Remove any triangles stranded by this action
					dettatchStranded();
					
					GlobalFlags.updateControlPoints = true;
						
					GlobalFlags.resetMultiplier();	
				}		
			}
			else
			{
				if(triangles.Length == 1)
				{
					if(GlobalFlags.getMusicVolume() > 0.1f)
					{
						music.audio.volume = 0.1f;
					}
					music.setSeStartTime(Time.time, 6);
					music.playSoundEffect("machoMadness");
					if (!GlobalFlags.infiniteRandomMode){ 
						GlobalFlags.setScore(GlobalFlags.getScore() + GlobalFlags.getQueueBounusTotal());
					}
					else {
						GlobalFlags.setScore(GlobalFlags.getScore());
					}
					Application.LoadLevel("PostGameMenu");
				}
			}
		}
	}
Exemplo n.º 25
0
        public void Format(string input, TextWriter output, HtmlFormatterOptions options)
        {
            bool makeXhtml = options.MakeXhtml;
            int maxLineLength = options.MaxLineLength;
            string indentString = new string(options.IndentChar, options.IndentSize);
            char[] chars = input.ToCharArray();
            System.Collections.Generic.Stack<FormatInfo> formatInfoStack = new System.Collections.Generic.Stack<FormatInfo>();
            System.Collections.Generic.Stack<HtmlWriter> writerStack = new System.Collections.Generic.Stack<HtmlWriter>();
            FormatInfo curTagFormatInfo = null;
            FormatInfo prevTokenFormatInfo = null;
            string s = string.Empty;
            bool flag2 = false;
            bool hasNoEndTag = false;
            bool flag4 = false;
            HtmlWriter writer = new HtmlWriter(output, indentString, maxLineLength);
            writerStack.Push(writer);
            Token curToken = HtmlTokenizer.GetFirstToken(chars);
            Token prevToken = curToken;
            while (curToken != null)
            {
                string text;
                string tagName;
                TagInfo tagInfo;
                writer = (HtmlWriter) writerStack.Peek();
                switch (curToken.Type)
                {
                    case Token.Whitespace:
                        if (curToken.Text.Length > 0)
                        {
                            writer.Write(' ');
                        }
                        goto Label_Get_Next_Token;

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

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

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

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

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

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

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

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

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

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

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

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

                    default:
                        goto Label_Get_Next_Token;
                }

                text = curToken.Text;

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

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

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

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

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

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

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

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

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

            Label_Get_Next_Token:
                prevToken = curToken;
                curToken = HtmlTokenizer.GetNextToken(curToken);
            }
            if (s.Length > 0)
            {
                writer.Write(s);
            }
            while (writerStack.Count > 1)
            {
                HtmlWriter writer8 = (HtmlWriter) writerStack.Pop();
                writer = (HtmlWriter) writerStack.Peek();
                writer.Write(writer8.Content);
            }
            writer.Flush();
        }
Exemplo n.º 26
0
        /// <summary>
        /// �����ʽת��Ϊ��׺���ʽ
        /// </summary>
        /// <param name="expression">�ı����ʽ</param>
        /// <returns>ת����ĺ�׺���ʽ</returns>
        internal static List<IOperatorOrOperand> ConvertInfixToPostfix(string expression)
        {
            // Ԥ������׺���ʽ
            List<IOperatorOrOperand> infix = SplitExpression(expression);
            // �����ջ
            System.Collections.Generic.Stack<OperatorBase> opr = new System.Collections.Generic.Stack<OperatorBase>();
            // ��׺���ʽ���
            List<IOperatorOrOperand> output = new List<IOperatorOrOperand>();

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

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

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

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

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

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

            return output;
        }
Exemplo n.º 27
0
        /// <summary>
        /// Add event data
        /// </summary>
        /// <param name="progressEvent"></param>
        /// <returns></returns>
        public ProgressItem AddEventData(Autodesk.Revit.DB.Events.ProgressChangedEventArgs progressEvent)
        {
            ProgressItem currentProgressItem = null;


            switch (progressEvent.Stage)
            {
            case ProgressStage.Started:
            {
                ProgressItem pi = new ProgressItem(progressEvent.Caption, progressEvent.LowerRange, progressEvent.UpperRange, progressEvent.Position, progressEvent.Stage);
                m_itemStack.Push(pi);
                currentProgressItem = pi;
                break;
            }

            case ProgressStage.PositionChanged:
            {
                ProgressItem pi = m_itemStack.Peek();
                if (pi.Name != progressEvent.Caption)
                {
                    Debug.WriteLine("Name not matching?");
                }
                pi.Position         = progressEvent.Position;
                pi.Stage            = progressEvent.Stage;
                currentProgressItem = pi;
                break;
            }

            case ProgressStage.RangeChanged:
            {
                ProgressItem pi = m_itemStack.Peek();
                pi.Upper            = progressEvent.UpperRange;
                pi.Stage            = progressEvent.Stage;
                currentProgressItem = pi;
                break;
            }

            case ProgressStage.Finished:
            {
                ProgressItem pi = m_itemStack.Pop();
                pi.IsDone           = true;
                pi.Stage            = progressEvent.Stage;
                currentProgressItem = pi;
                break;
            }

            case ProgressStage.CaptionChanged:
            {
                ProgressItem pi = m_itemStack.Peek();
                pi.Name  = progressEvent.Caption;
                pi.Stage = progressEvent.Stage;
                Debug.WriteLine("Caption Change at top.");
                currentProgressItem = pi;
                break;
            }

            case ProgressStage.Unchanged:
            {
                Debug.WriteLine("Idle.");
                currentProgressItem = new ProgressItem(progressEvent.Caption, progressEvent.LowerRange, progressEvent.UpperRange, progressEvent.Position, progressEvent.Stage);
                break;
            }


            default:
                throw new Exception("Unknown stage.");
            }


            if (m_itemStack.Count == 0)
            {
                Debug.WriteLine("Stack empty");
            }
            else
            {
                Debug.WriteLine(this.ToString());
            }

            return(currentProgressItem);
        }
Exemplo n.º 28
0
            internal ListNode MergeTwoLists(ListNode l1, ListNode l2)
            {
                System.Collections.Generic.Stack <ListNode> nodestack = new System.Collections.Generic.Stack <ListNode>();

                while (l1 != null || l2 != null)
                {
                    int?firstValue  = null;
                    int?secondValue = null;

                    if (l1 != null)
                    {
                        firstValue = l1.val;
                        Console.WriteLine($"{firstValue}");
                    }

                    if (l2 != null)
                    {
                        secondValue = l2.val;
                        Console.WriteLine($"{secondValue}");
                    }

                    ListNode newnode = null;
                    if (firstValue.HasValue && secondValue.HasValue)
                    {
                        if (firstValue.Value > secondValue.Value)
                        {
                            newnode = new ListNode(secondValue.Value);

                            if (l2.next != null)
                            {
                                l2 = l2.next;
                            }
                            else
                            {
                                l2 = null;
                            }
                        }
                        else if (firstValue.Value < secondValue.Value)
                        {
                            newnode = new ListNode(firstValue.Value);

                            if (l1.next != null)
                            {
                                l1 = l1.next;
                            }
                            else
                            {
                                l1 = null;
                            }
                        }
                        else
                        {
                            newnode = new ListNode(firstValue.Value);

                            if (nodestack.Count == 0)
                            {
                                nodestack.Push(newnode);
                                Console.WriteLine($"Empty Stack: Node with value: {newnode.val} is added in the Stack");
                            }
                            else
                            {
                                nodestack.Peek().next = newnode;
                                nodestack.Push(newnode);
                                Console.WriteLine($"Node with value: {newnode.val} is added in the Stack");
                            }

                            newnode = new ListNode(secondValue.Value);

                            if (l1.next != null)
                            {
                                l1 = l1.next;
                            }
                            else
                            {
                                l1 = null;
                            }

                            if (l2.next != null)
                            {
                                l2 = l2.next;
                            }
                            else
                            {
                                l2 = null;
                            }
                        }
                    }
                    else if (firstValue.HasValue && !secondValue.HasValue)
                    {
                        newnode = new ListNode(firstValue.Value);
                        if (l1.next != null)
                        {
                            l1 = l1.next;
                        }
                        else
                        {
                            l1 = null;
                        }
                    }
                    else if (!firstValue.HasValue && secondValue.HasValue)
                    {
                        newnode = new ListNode(secondValue.Value);
                        if (l2.next != null)
                        {
                            l2 = l2.next;
                        }
                        else
                        {
                            l2 = null;
                        }
                    }

                    if (nodestack.Count == 0)
                    {
                        nodestack.Push(newnode);
                        Console.WriteLine($"Empty Stack: Node with value: {newnode.val} is added in the Stack");
                    }
                    else
                    {
                        nodestack.Peek().next = newnode;
                        nodestack.Push(newnode);
                        Console.WriteLine($"Node with value: {newnode.val} is added in the Stack");
                    }
                }
                Console.WriteLine($"Stack count: {nodestack.Count}");

                if (nodestack.Count > 0)
                {
                    while (nodestack.Count != 1)
                    {
                        nodestack.Pop();
                    }
                }

                if (nodestack.Count == 1)
                {
                    return(nodestack.Pop());
                }
                else
                {
                    return(null);
                }
            }