public static void ChapterMain()
        {
            System.Collections.Generic.Stack <int> stack =
                new System.Collections.Generic.Stack <int>();
            System.Collections.Generic.Stack <int> .Enumerator enumerator;
            IDisposable disposable;

            enumerator = stack.GetEnumerator();
            try
            {
                int number;
                while (enumerator.MoveNext())
                {
                    number = enumerator.Current;
                    Console.WriteLine(number);
                }
            }
            finally
            {
                // Explicit cast used for IEnumerator<T>.
                disposable = (IDisposable)enumerator;
                disposable.Dispose();

                // IEnumerator will use the as operator unless IDisposable
                // support is known at compile time.
                // disposable = (enumerator as IDisposable);
                // if (disposable != null)
                // {
                //     disposable.Dispose();
                // }
            }
        }
예제 #2
0
        /// <summary>
        ///		扫描目录
        /// </summary>
        /// <param name="DirName">路径</param>
        public void ScanDirectory(String DirName)
        {
            try
            {
                DirectoryInfo RDirInfo = new DirectoryInfo(DirName);
                if (!RDirInfo.Exists)
                {
                    return;
                }
            }
            catch (Exception)
            {
                return;
            }

            System.Collections.Generic.Stack <string> DirStack = new System.Collections.Generic.Stack <string>();
            DirStack.Push(DirName);

            while (DirStack.Count > 0)
            {
                DirectoryInfo DirInfo = new DirectoryInfo(DirStack.Pop());
                foreach (DirectoryInfo DirChildInfo in DirInfo.GetDirectories())
                {
                    DirStack.Push(DirChildInfo.FullName);
                }
                foreach (FileInfo FileChildInfo in DirInfo.GetFiles())
                {
                    if (FileChildInfo.Name.EndsWith(".exe") && !RuleListBox.Items.Contains(FileChildInfo.Name))
                    {
                        RuleListBox.Items.Add(FileChildInfo.Name);
                    }
                }
            }
        }
예제 #3
0
            public static bool IsValid(string s)
            {
                if (s.Length % 2 == 1)
                {
                    return(false);
                }
                var stacks = new System.Collections.Generic.Stack <char>();
                var hash   = new System.Collections.Hashtable();

                hash.Add(')', '(');
                hash.Add(']', '[');
                hash.Add('}', '{');
                var chars = s.ToCharArray();

                foreach (var c in chars)
                {
                    if (hash.ContainsKey(c))
                    {
                        if (stacks.Count == 0 || (char)hash[c] != stacks.Peek())
                        {
                            return(false);
                        }
                        stacks.Pop();
                    }
                    else
                    {
                        stacks.Push(c);
                    }
                }
                if (stacks.Count != 0)
                {
                    return(false);
                }
                return(true);
            }
예제 #4
0
 public static bool verifyPalindromeIterate(LinkedNode head)
 {
     System.Collections.Generic.Stack<double> stack = new System.Collections.Generic.Stack<double>();
     LinkedNode SlowRunner = head;
     LinkedNode FastRunner = head;
     while (FastRunner != null && FastRunner.Next != null)
     {
         stack.Push(SlowRunner.Data);
         FastRunner = FastRunner.Next.Next;
         SlowRunner = SlowRunner.Next;
     }
     SlowRunner = SlowRunner.Next;
     while (SlowRunner!=null)
     {
         if (stack.Pop() == SlowRunner.Data)
         {
             SlowRunner = SlowRunner.Next;
         }
         else
         {
             return false;
         }
     }
     return true;
 }
        public static void Main()
        {
            System.Collections.Generic.Stack<int> stack =
                new System.Collections.Generic.Stack<int>();
            System.Collections.Generic.Stack<int>.Enumerator enumerator;
            IDisposable disposable;

            enumerator = stack.GetEnumerator();
            try
            {
                int number;
                while(enumerator.MoveNext())
                {
                    number = enumerator.Current;
                    Console.WriteLine(number);
                }
            }
            finally
            {
                // Explicit cast used for IEnumerator<T>.
                disposable = (IDisposable)enumerator;
                disposable.Dispose();

                // IEnumerator will use the as operator unless IDisposable
                // support is known at compile time.
                // disposable = (enumerator as IDisposable);
                // if (disposable != null)
                // {
                //     disposable.Dispose();
                // }
            }
        }
예제 #6
0
        } // End Function StringifyException

        public virtual void LogException(
            string origin
            , int level
            , System.Exception exception
            , System.Data.Common.DbCommand cmd
            , string logMessage)
        {
            System.Collections.Generic.Stack <System.Exception> stack = GetExceptionStack(exception);


            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            int sequence = 0;

            while (stack.Count > 0)
            {
                sequence++;

                System.Exception ex            = stack.Pop();
                string           exceptionText = StringifyException(ex);
                sb.AppendLine(exceptionText);
            } // Whend

            string text = sb.ToString();

            sb.Length = 0;
            sb        = null;

            // SendMail(text);
        } // End Function LogException
예제 #7
0
        public static bool verifyPalindromeIterate(LinkedNode head)
        {
            System.Collections.Generic.Stack <double> stack = new System.Collections.Generic.Stack <double>();
            LinkedNode SlowRunner = head;
            LinkedNode FastRunner = head;

            while (FastRunner != null && FastRunner.Next != null)
            {
                stack.Push(SlowRunner.Data);
                FastRunner = FastRunner.Next.Next;
                SlowRunner = SlowRunner.Next;
            }
            SlowRunner = SlowRunner.Next;
            while (SlowRunner != null)
            {
                if (stack.Pop() == SlowRunner.Data)
                {
                    SlowRunner = SlowRunner.Next;
                }
                else
                {
                    return(false);
                }
            }
            return(true);
        }
예제 #8
0
        public bool IsValid(string s)
        {
            var map = new System.Collections.Generic.Dictionary <char, char>()
            {
                { '(', ')' },
                { '[', ']' },
                { '{', '}' }
            };

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

            foreach (char c in s)
            {
                if (map.ContainsKey(c)) // is opening bracket
                {
                    stack.Push(c);
                }
                else // is closing bracket
                {
                    if (stack.Count == 0 || // and there was not opening braket
                        map[stack.Pop()] != c) // and opening bracket does not match
                    {
                        return(false);
                    }
                }
            }

            return(stack.Count == 0);
        }
예제 #9
0
        static int _m_FloodFill(RealStatePtr L)
        {
            try {
                ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);


                PF.GraphNode gen_to_be_invoked = (PF.GraphNode)translator.FastGetCSObj(L, 1);



                {
                    System.Collections.Generic.Stack <PF.GraphNode> _stack = (System.Collections.Generic.Stack <PF.GraphNode>)translator.GetObject(L, 2, typeof(System.Collections.Generic.Stack <PF.GraphNode>));
                    uint _region = LuaAPI.xlua_touint(L, 3);

                    gen_to_be_invoked.FloodFill(
                        _stack,
                        _region);



                    return(0);
                }
            } catch (System.Exception gen_e) {
                return(LuaAPI.luaL_error(L, "c# exception:" + gen_e));
            }
        }
        /// <summary>
        /// 前序遍历,也叫先根遍历,先序遍历
        /// <para>根左右</para>
        /// </summary>
        /// <param name="action"></param>
        public void Preorder(Action <T> action)
        {
            if (action == null)
            {
                throw new ArgumentNullException(nameof(action));
            }

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

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

            while (stack.Count != 0)
            {
                var current = stack.Pop();
                action(current.Data);

                //栈是后进先出,所以先使用的左节点要后入栈
                if (current.Right != null)
                {
                    stack.Push(current.Right);
                }
                if (current.Left != null)
                {
                    stack.Push(current.Left);
                }
            }
        }
예제 #11
0
 public int solution(string S)
 {
     var stack = new System.Collections.Generic.Stack<char>();
     foreach (var s in S)
     {
         if (-1 == "{[(".IndexOf(s))
         {
             if (stack.Count == 0)
                 return 0;
             var z = stack.Pop();
             switch (s)
             {
                 case '}':
                     if (z != '{')
                         return 0;
                     break;
                 case ']':
                     if (z != '[')
                         return 0;
                     break;
                 case ')':
                     if (z != '(')
                         return 0;
                     break;
             }
         }
         else
         {
             stack.Push(s);
         }
     }
     return (stack.Count == 0) ? 1 : 0;
 }
예제 #12
0
        /** タッチリスト更新。
         *
         *      タッチアップされたアイテムはa_listから削除する。
         *
         */
        public static void UpdateTouchList <TYPE>(System.Collections.Generic.Dictionary <TYPE, Fee.Input.Touch_Phase> a_list)
            where TYPE : Touch_Phase_Key_Base
        {
            System.Collections.Generic.Stack <TYPE> t_delete_keylist = null;

            foreach (System.Collections.Generic.KeyValuePair <TYPE, Fee.Input.Touch_Phase> t_pair in a_list)
            {
                if (t_pair.Value.update == false)
                {
                    if (t_delete_keylist == null)
                    {
                        t_delete_keylist = new System.Collections.Generic.Stack <TYPE>();
                    }
                    t_delete_keylist.Push(t_pair.Key);
                }
                else
                {
                    //更新。
                    t_pair.Key.OnUpdate();
                }
            }

            //リストから削除。
            if (t_delete_keylist != null)
            {
                while (t_delete_keylist.Count > 0)
                {
                    TYPE t_key = t_delete_keylist.Pop();
                    a_list.Remove(t_key);
                    t_key.OnRemove();
                }
            }
        }
예제 #13
0
 public int solution(int[] A, int[] B)
 {
     var ret = 0;
     var up = new System.Collections.Generic.Stack<int>();
     for (int i = A.Length - 1; i >= 0; i--)
     {
         if (B[i] == 1)
         {
             while (up.Count > 0)
             {
                 var fishSize = up.Peek();
                 if (A[i] > fishSize)
                     up.Pop(); // remove one from stack
                 else
                     break; // downFish was eaten, break circle
             }
             if (up.Count == 0)
                 ret++; // downFish ate all upFishes
         }
         else
         {
             up.Push(A[i]);
         }
     }
     while (up.Count > 0)
     {
         var fishSize = up.Pop();
         ret++;
     }
     return ret;
 }
예제 #14
0
 public XmlStylesheetReader(Stylesheet stylesheet)
 {
     // Initialize the object.
     this.stylesheet          = stylesheet;
     this.lexicon             = new Lexicon();
     this.xmlNamespaceManager = new XmlNamespaceManager(new NameTable());
     this.stateStack          = new System.Collections.Generic.Stack <NodeState>();
 }
    public void ReplaceNavigationPath(System.Collections.Generic.Stack <HexCellBehaviour> newPath)
    {
        var index     = GameComponentsLookup.NavigationPath;
        var component = CreateComponent <NavigationPathComponent>(index);

        component.path = newPath;
        ReplaceComponent(index, component);
    }
예제 #16
0
        private void OnDestroy()
        {
            _commandBuffer = null;

            _unusedCommandBufferIndices = null;

            _hash = 1;
        }
예제 #17
0
        /// <devdoc>
        /// Creates a new WizardForm with a given service provider.
        /// </devdoc>
        public WizardForm(IServiceProvider serviceProvider)
            : base(serviceProvider)
        {
            _panelHistory = new System.Collections.Generic.Stack <WizardPanel>();

            InitializeComponent();
            InitializeUI();
        }
예제 #18
0
 /// <summary>
 /// Muestra los Valores de un Stack generio de tipo Class Punto
 /// </summary>
 /// <param name="puntos">Nombre de la Instacia de la Class Punto</param>
 /// <param name="salto">Tipo de Salto deciado</param>
 public void Show(System.Collections.Generic.Stack <Punto> puntos, int salto = 1)
 {
     foreach (Punto p in puntos)
     {
         System.Console.Write("->{0}\n", p);
     }
     LineasEsp.Salto(salto);
 }
예제 #19
0
        /// <devdoc>
        /// Creates a new WizardForm with a given service provider.
        /// </devdoc>
        public WizardForm(IServiceProvider serviceProvider)
            : base(serviceProvider)
        {
            _panelHistory = new System.Collections.Generic.Stack<WizardPanel>();

            InitializeComponent();
            InitializeUI();
        }
예제 #20
0
        public static void TestStack()
        {
            System.Collections.Generic.Stack <string> stack = new System.Collections.Generic.Stack <string>();
            string isEmpty = stack.Peek();

            stack.Push("abc");
            string abc = stack.Pop();
        }
예제 #21
0
 public DataTransformReader(DataTransform dataTransform)
 {
     // Initialize the object.
     this.dataTransform       = dataTransform;
     this.lexicon             = new Lexicon();
     this.xmlNamespaceManager = new XmlNamespaceManager(new NameTable());
     this.stateStack          = new System.Collections.Generic.Stack <NodeState>();
 }
예제 #22
0
        public List <List <int> > ZigzagLevelOrder(Tree <int> .Node Root)
        {
            /*
             * have 2 stacks
             * while both are not empty.
             * go through one stack and put to the other and visa varsa
             */

            System.Collections.Generic.Stack <Tree <int> .Node> stackL = new System.Collections.Generic.Stack <Tree <int> .Node>();
            System.Collections.Generic.Stack <Tree <int> .Node> stackR = new System.Collections.Generic.Stack <Tree <int> .Node>();

            stackL.Push(Root);

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

            while (stackL.Count > 0 || stackR.Count > 0)
            {
                List <int> level     = new List <int>();
                var        stackFrom = stackL.Count > 0 ? stackL : stackR;
                var        stackTo   = stackL.Count > 0 ? stackR : stackL;
                bool       left      = stackFrom == stackL;

                while (stackFrom.Count > 0)
                {
                    var node = stackFrom.Pop();
                    level.Add(node.Value);

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

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

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

                res.Add(level);
            }

            return(res);
        }
예제 #23
0
        static void Main(string[] args)
        {
            System.Collections.Generic.Stack <Punto> puntosStack =
                new System.Collections.Generic.Stack <Punto>();

            // Stack
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Stack");
            Console.ForegroundColor = ConsoleColor.DarkGray;

            // Añadiendo nuevos datos
            puntosStack.Push(new Punto(3, 4));
            puntosStack.Push(new Punto(5, 7));
            puntosStack.Push(new Punto(9, 6));
            puntosStack.Push(new Punto(1, 4));
            Coleccion coleccion = new Coleccion();

            coleccion.Show(puntosStack);

            // Hacemos un peek
            Console.Write("Peek {0}\n", puntosStack.Peek());

            coleccion.Show(puntosStack);

            // Hacemos dos pop
            Console.Write("Pop {0}\n", puntosStack.Pop());
            Console.Write("Pop {0}\n", puntosStack.Pop());

            coleccion.Show(puntosStack);

            // Queue
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Queue");
            Console.ForegroundColor = ConsoleColor.White;

            System.Collections.Generic.Queue <Punto> puntosQueue =
                new System.Collections.Generic.Queue <Punto>();

            // Añadiendo nuevos datos
            puntosQueue.Enqueue(new Punto(5, 4));
            puntosQueue.Enqueue(new Punto(4, 7));
            puntosQueue.Enqueue(new Punto(1, 6));
            puntosQueue.Enqueue(new Punto(7, 4));

            coleccion.Show(puntosQueue);

            // Hacemos un Peek
            Console.Write("Peek {0}\n", puntosQueue.Peek());

            // Hacemos dequeue
            Console.Write("Dequeue {0}\n", puntosQueue.Dequeue());
            Console.Write("Dequeue {0}\n", puntosQueue.Dequeue());
            Console.Write("Dequeue {0}\n", puntosQueue.Dequeue());
            coleccion.Show(puntosQueue);
            Console.Write("Dequeue {0}\n", puntosQueue.Dequeue());
            coleccion.Show(puntosQueue);
            Console.ReadKey();
        }
예제 #24
0
        public void BroadcastMessage()
        {
            lock (SocketService._broadcastLock)
            {
                this._isThreading = true;

                Fleck.IWebSocketConnection[] connections;
                System.Collections.Generic.Stack <Fleck.IWebSocketConnection> unavailable = null;

                this._connections.CopyTo(connections = new Fleck.IWebSocketConnection[this._connections.Count], 0);

                BufferItem item;
                while (this._broadcastBuffer.Count > 0)
                {
                    item = this._broadcastBuffer.Dequeue();

                    if (DateTime.UtcNow.Subtract(item.TimeStamp).Milliseconds > 10000)
                    {
                        continue;
                    }

                    if (item.Message != null && item.Message.Length > 0)
                    {
                        foreach (Fleck.IWebSocketConnection client in connections)
                        {
                            if (client.IsAvailable == true)
                            {
                                if (client.ConnectionInfo.Path.Equals("/Listener") == true)
                                {
                                    if (item.ConnectionId.Equals(client.ConnectionInfo.Id) == false)
                                    {
                                        client.Send(item.Message);
                                    }
                                }
                            }
                            else
                            {
                                unavailable = new Stack <Fleck.IWebSocketConnection>();
                                unavailable.Push(client);
                            }
                        }
                    }
                }

                if (unavailable != null)
                {
                    while (unavailable.Count != 0)
                    {
                        this._connections.Remove(unavailable.Pop());
                    }
                }

                this._broadcastTimestamp = DateTime.UtcNow;

                this._isThreading = false;
            }
        }
예제 #25
0
 public static void reverseStack(System.Collections.Generic.Stack <int> s)
 {
     if (s.Count != 0)
     {
         int data = s.Pop();
         reverseStack(s);
         addStackToBack(s, data);
     }
 }
예제 #26
0
 /** constructor
  */
 public PoolList(int a_capacity)
 {
     //pool_list
     this.pool_list = new System.Collections.Generic.Stack <T>();
     for (int ii = 0; ii < a_capacity; ii++)
     {
         this.pool_list.Push(CreateInstance());
     }
 }
        static StackObject *Ctor_0(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *__ret = ILIntepreter.Minus(__esp, 0);

            var result_of_this_method = new System.Collections.Generic.Stack <ILRuntime.Runtime.Intepreter.ILTypeInstance>();

            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
예제 #28
0
        private void VisitInternal(System.Collections.Generic.Stack <TypeVisit> stack, System.Collections.Generic.ISet <Type> visitedSet)
        {
            var type = stack.CurrentType();

            if (configuration.AvoidMultipleVisits && visitedSet.Contains(type))
            {
                return;
            }
            else
            {
                visitedSet.Add(type);
            }

            if (!configuration.TypeCanBeVisited(type))
            {
                return;
            }

            Action(stack);

            if (configuration.VisitInheritedTypes)
            {
                foreach (var(inheritedType, stackEntry) in type.GetInheritedTypes())
                {
                    VisitInternalWithStackWrapping(inheritedType, stack, visitedSet, stackEntry);
                }
            }

            if (configuration.VisitEncompassingTypes)
            {
                foreach (var(encompassingType, stackEntry) in type.GetEncompassingTypes())
                {
                    VisitInternalWithStackWrapping(encompassingType, stack, visitedSet, stackEntry);
                }
            }


            if (configuration.VisitAssignableTypesOf(type))
            {
                var assignableTypes = type.GetAssignableTypes(AppDomain.CurrentDomain);
                foreach (var(assignableType, stackEntry) in assignableTypes)
                {
                    VisitInternalWithStackWrapping(assignableType, stack, visitedSet, stackEntry);
                }
            }

            foreach (var(propertyType, stackEntry) in
                     type
                     .GetProperties()
                     .Where(x => configuration.PropertyCanBeVisited(x))
                     .Select(x => (type: x.PropertyType, stackEntry: (TypeVisit) new PropertyTypeVisit(x.PropertyType, x.Name)))
                     )
            {
                VisitInternalWithStackWrapping(propertyType, stack, visitedSet, stackEntry);
            }
        }
예제 #29
0
 private void VisitInternalWithStackWrapping(
     Type type,
     System.Collections.Generic.Stack <TypeVisit> stack,
     System.Collections.Generic.ISet <Type> visitedSet,
     TypeVisit typeVisit)
 {
     stack.Push(typeVisit);
     VisitInternal(stack, visitedSet);
     stack.Pop();
 }
예제 #30
0
	// Use this for initialization
	void Start () {

        sharedState = this;
        Config c = new Config();

        // starting economy
        currentEconomy = new Economy(c.initialEconomy);

        // factories to start with
        factories = new System.Collections.Generic.Stack<Factory>();
	}
예제 #31
0
            private int[] low;                                // najnizszy numer prefiksowy wierzcholka osiagalnego z danego przez krawedz powrotną (czyli nie nalezaca do drzewa DFS)

            internal TarjanHelper(IGraph g)
            {
                this.g = g;
                int n = g.VerticesCount;

                s       = new System.Collections.Generic.Stack <int>();
                visited = new bool[n];
                pref    = new int[n];
                id      = new int[n];
                low     = new int[n];
            }
예제 #32
0
 public StatementVisitor(Statement entryPoint)
 {
     programStack = new System.Collections.Generic.Stack<System.Collections.Generic.Queue<Statement>>();
     programStack.Push(new System.Collections.Generic.Queue<Statement>());
     programStack.Peek ().Enqueue(entryPoint);
     TimeControl.OnStartCycle += OnStartCycle;
     TimeControl.OnTelegraph += OnTelegraph;
     TimeControl.OnStart += OnStartAction;
     TimeControl.OnStop += OnStopAction;
     TimeControl.OnEndCycle += OnEndCycle;
 }
예제 #33
0
        public void Dispose()
        {
            if (nodeStack != null)
            {
                Debug.Warn.If(nodeStack.Count == 0, "Closing a XML stream while stack still in use: depth = {0}", nodeStack.Count);
            }
            node      = null;
            nodeStack = null;

            owner = null;
        }
예제 #34
0
        static public System.Collections.Generic.IEnumerator <string> RecursiveFileEnumerator(string startDirectory)
        {
            var remaining_dirs = new System.Collections.Generic.Stack <string>();

            remaining_dirs.Push(startDirectory);

            while (true)
            {
                var directory = remaining_dirs.Pop();
            }
        }
예제 #35
0
        public static System.Collections.Generic.Stack <System.Exception> GetExceptionStack(System.Exception exceptionChain)
        {
            System.Collections.Generic.Stack <System.Exception> stack = new System.Collections.Generic.Stack <System.Exception>();

            while (exceptionChain != null)
            {
                stack.Push(exceptionChain);
                exceptionChain = exceptionChain.InnerException;
            } // Whend

            return(stack);
        } // End Function GetExceptionStack
예제 #36
0
        // This is de facto behind the 4.8/EnableDpiMessaging/ToolStrip HighDpi quirks.
        internal override void ToolStrip_RescaleConstants(int oldDpi, int newDpi)
        {
            RescaleConstantsInternal(newDpi);

            // Traversing the tree of DropDownMenuItems non-recursively to set new
            // Font (where necessary because not inherited from parent), DeviceDpi and reset the scaling.
            var itemsStack = new System.Collections.Generic.Stack <ToolStripDropDownItem>();

            itemsStack.Push(this);
            while (itemsStack.Count > 0)
            {
                var item = itemsStack.Pop();

                if (item.dropDown != null)
                {
                    // The following does not get set, since dropDown has no parent/is not part of the
                    // controls collection, so this gets never called through the normal inheritance chain.
                    item.dropDown.deviceDpi = newDpi;
                    item.dropDown.ResetScaling(newDpi);

                    foreach (ToolStripItem childItem in item.DropDown.Items)
                    {
                        if (childItem == null)
                        {
                            continue;
                        }

                        // Checking if font was inherited from parent.
                        Font local = childItem.Font;
                        if (!local.Equals(childItem.OwnerItem?.Font))
                        {
                            var factor = (float)newDpi / oldDpi;
                            childItem.Font = new Font(local.FontFamily, local.Size * factor, local.Style,
                                                      local.Unit, local.GdiCharSet, local.GdiVerticalFont);
                        }

                        childItem.DeviceDpi = newDpi;

                        if (typeof(ToolStripDropDownItem).IsAssignableFrom(childItem.GetType()))
                        {
                            if (((ToolStripDropDownItem)childItem).dropDown != null)
                            {
                                itemsStack.Push((ToolStripDropDownItem)childItem);
                            }
                        }
                    }
                }
            }

            // It's important to call the base class method only AFTER we processed all DropDown items,
            // because we need the new DPI in place, before a Font change triggers new layout calc.
            base.ToolStrip_RescaleConstants(oldDpi, newDpi);
        }
예제 #37
0
 /// <summary>
 /// Saves the current stream cursor so a new one can be specified,
 /// but then later restored to the saved cursor
 /// </summary>
 public void SaveCursor()
 {
     if (nodeStack == null)
     {
         nodeStack = new System.Collections.Generic.Stack <XmlNode>();
     }
     if (nodeStack.Count > 0)
     {
         Debug.Warn.If(nodeStack.Peek() != node, "Saving the cursor more than once! {0} in {1}", node, owner);
     }
     nodeStack.Push(node);
 }
        public static void Main()
        {
            System.Collections.Generic.Stack<int> stack =
                new System.Collections.Generic.Stack<int>();
            int number;
            // ...

            // This code is conceptual, not the actual code.
            while(stack.Pop() != -1) //this is actually not the right logic, but the point is the while, not stack
            {
                number = stack.Peek();
                Console.WriteLine(number);
            }
        }
예제 #39
0
    //Evaluating RPN
    public static void evalu(string output)
    {
        int num1 = 0;
            int num2 = 0;
            System.Collections.Generic.Stack<int> myStack = new System.Collections.Generic.Stack<int>();
            foreach (char token in output)
            {
                if (Char.IsNumber(token) == true)
                {
                    myStack.Push(int.Parse(token.ToString()));
                }
                if (token == '+' || token == '-' || token == '*' || token == '/')
                {
                    if (token == '+')
                    {
                        num1 = myStack.Peek();
                        myStack.Pop();
                        num2 = myStack.Peek();
                        myStack.Pop();
                        myStack.Push(num1 + num2);
                    }

                    if (token == '-')
                    {
                        num1 = myStack.Peek();
                        myStack.Pop();
                        num2 = myStack.Peek();
                        myStack.Pop();
                        myStack.Push(num2 - num1);
                    }
                    if (token == '*')
                    {
                        num1 = myStack.Peek();
                        myStack.Pop();
                        num2 = myStack.Peek();
                        myStack.Pop();
                        myStack.Push(num1 * num2);
                    }
                    if (token == '/')
                    {
                        num1 = myStack.Peek();
                        myStack.Pop();
                        num2 = myStack.Peek();
                        myStack.Pop();
                        myStack.Push(num1 / num2);
                    }
                }
            }
        PrintValues(myStack, ' ');
    }
        public static void Main()
        {
            System.Collections.Generic.Stack<int> stack =
                new System.Collections.Generic.Stack<int>();
            int number;

            using(
                System.Collections.Generic.Stack<int>.Enumerator
                    enumerator = stack.GetEnumerator())
            {
                while(enumerator.MoveNext())
                {
                    number = enumerator.Current;
                    Console.WriteLine(number);
                }
            }
        }
예제 #41
0
파일: Extensions.cs 프로젝트: keyvank/i3dml
 public static System.Collections.Generic.List<i3DML.ObjectModel.Light> GetWorldLights(this i3DML.ObjectModel.World w)
 {
     var ret = new System.Collections.Generic.List<i3DML.ObjectModel.Light>();
     var stack = new System.Collections.Generic.Stack<i3DML.ObjectModel.PlaceBase>();
     stack.Push(w);
     while (stack.Count > 0)
     {
         i3DML.ObjectModel.PlaceBase p = stack.Pop();
         for (int i = 0; i < p.Length; i++)
         {
             if (p[i] is i3DML.ObjectModel.Light)
                 ret.Add(p[i] as i3DML.ObjectModel.Light);
             if (p[i] is i3DML.ObjectModel.PlaceBase)
                 stack.Push(p[i] as i3DML.ObjectModel.PlaceBase);
         }
     }
     return ret;
 }
        public static void Main()
        {
            System.Collections.Generic.Stack<int> stack =
                new System.Collections.Generic.Stack<int>();
            int number;
            System.Collections.Generic.Stack<int>.Enumerator
              enumerator;

            // ...

            // If IEnumerable<T> is implemented explicitly, 
            // then a cast is required.
            // ((IEnumerable<int>)stack).GetEnumerator();
            enumerator = stack.GetEnumerator();
            while(enumerator.MoveNext())
            {
                number = enumerator.Current;
                Console.WriteLine(number);
            }
        }
예제 #43
0
 /// <summary>
 /// Executes a quicksort algorithm given the value and swap methods.
 /// </summary>
 public static void Sort(Func<long, long> value, Action<long, long> swap, long left, long right)
 {
     if (left < right)
     {
         var stack = new System.Collections.Generic.Stack<Pair>();
         stack.Push(new Pair(left, right));
         while (stack.Count > 0)
         {
             var pair = stack.Pop();
             var pivot = QuickSort.Partition(value, swap, pair.Left, pair.Right);
             if (pair.Left < pivot)
             {
                 stack.Push(new Pair(pair.Left, pivot - 1));
             }
             if (pivot < pair.Right)
             {
                 stack.Push(new Pair(pivot + 1, pair.Right));
             }
         }
     }
 }
예제 #44
0
            public int solution(int[] H)
            {
                var blockCount = 0;
                var stack = new System.Collections.Generic.Stack<Tuple<int, int>>();

                foreach (var h in H)
                {
                    var lastBlockBottom = 0;
                    var lastBlockTop = 0;
                    if (stack.Count != 0)
                    {
                        var lastBlock = stack.Peek();
                        lastBlockBottom = lastBlock.Item1;
                        lastBlockTop = lastBlock.Item2;
                    }
                    if (h > lastBlockTop)
                    {
                        stack.Push(new Tuple<int, int>(lastBlockTop, h));
                    }
                    else if (h < lastBlockTop)
                    {
                        stack.Pop();
                        blockCount++;

                        while (h < lastBlockBottom)
                        {
                            var lastBlock = stack.Pop();
                            blockCount++;
                            lastBlockBottom = lastBlock.Item1;
                        }
                        if (h > lastBlockBottom)
                        {
                            stack.Push(new Tuple<int, int>(lastBlockBottom, h));
                        }
                    }
                }

                return blockCount + stack.Count;
            }
예제 #45
0
        //revision:clear 12/2/2012
        public static bool validatePushPop(double[] pop)
        {
            int i = 0, length = pop.Length;
            bool[] positioned = new bool[1 + length];
            System.Collections.Generic.Stack<int> s = new System.Collections.Generic.Stack<int>();
            while (i < length)
            {
                if (s.Count == 0 || s.Peek() != pop[i])
                {
                    int n = 1; bool f = true;
                    while (n <= pop[i])
                    {
                        if (!positioned[n])
                        {
                            f = false;
                            s.Push(n);
                            positioned[n] = true;
                        }
                        n++;
                    }
                    if (f)
                    {
                        return false;
                    }
                }
                else if (s.Count != 0 && s.Peek() == pop[i])
                {
                    s.Pop();
                    i++;
                }
                else
                {
                    return false;
                }

            }

            return true;
        }
예제 #46
0
        public EnvironmentGraphics(VapeTeam.Psimulex.Core.ICommandContext environment)
        {
            panel = new StackPanel();
            panel.SnapsToDevicePixels = true;
            states = new System.Collections.Generic.Stack<StateGraphics>();
            //			depthListeners = new List<IDepthChangedListener>();
            env = environment;

            Content = panel;

            //environment.VariableCreated += new VariableEventHandler(environment_VariableCreated);
            //environment.VariableDeleted += new VariableEventHandler(environment_VariableDeleted);

            environment.CallStack.Pushed += environment_StatePushed;
            environment.CallStack.Popped += environment_StatePopped;

            environment.VariableCreated += environment_VariableCreated;

            //environment.StatePushed += new EventHandler(environment_StatePushed);
            //environment.StatePopped += new EventHandler(environment_StatePopped);

            PushState();
        }
            public static void Scenario()
            {
                var stack = default(System.Collections.Generic.Stack<int>);

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

                "When pushing 1 onto the stack"
                    .When(() => stack.Push(1));

                "Then the first item in the stack should be 1"
                    .Then(() => stack.Pop().Should().Be(1))
                    .InIsolation();

                "And the first item in the stack should be 1"
                    .And(() => stack.Pop().Should().Be(1))
                    .InIsolation();

                "And the stack should contain some items"
                    .And(() => stack.Should().NotBeEmpty());

                "But the stack should not contain more than one item"
                    .But(() => stack.Count.Should().BeLessOrEqualTo(1));
            }
예제 #48
0
파일: Drawable.cs 프로젝트: keyvank/i3dml
 /// <summary>
 /// Find an element with a specified name by looking to the descendants of this element.
 /// </summary>
 /// <param name="Name">Name of the element we are looking for</param>
 /// <returns>The found element</returns>
 public Drawable FindElement(string Name)
 {
     if (this.Name == Name)
         return this;
     var plcs=new System.Collections.Generic.Stack<PlaceBase>();
     if (this is PlaceBase)
         plcs.Push(this as PlaceBase);
     while (plcs.Count != 0)
     {
         PlaceBase pop=plcs.Pop();
         if (pop.Name == Name)
             return pop;
         for (int i = 0; i < pop.Length; i++)
         {
             if (pop[i] is PlaceBase)
                 plcs.Push(pop[i] as PlaceBase);
             else if (pop[i].Name == Name)
                 return pop[i];
         }
     }
     return null;
 }
예제 #49
0
    public void compute_expression(string expr)
    {
        System.Collections.Generic.Stack<char> myStack = new System.Collections.Generic.Stack<char>();
        string output = "";
        // Rewriting the string into Reverse Polish Notation(RPN) format
        foreach(char token in expr)
        {
             //Read a token.
            //If the token is a number, then add it to the output queue.
            if (Char.IsNumber(token) == true)
            {
                output = output + ' ' +token;
            }
            if(token == '+' || token == '-')
            {
                if (myStack.Count() != 0)
                {
                        while(myStack.Peek() == '*' || myStack.Peek() == '/' || myStack.Peek() == '-')
                        {
                            if (myStack.Count() != 0)
                            {
                                output = output + ' ' + myStack.Peek();
                                myStack.Pop();
                            }
                            if (myStack.Count() == 0)
                            {
                                break;
                            }
                        }
                }
                myStack.Push(token);
            }
            if(token == '(')
            {
                myStack.Push(token);
            }

            if (token == ')')
            {
                if (myStack.Count() != 0)
                {
                    while (myStack.Peek() != '(')
                    {
                        if (myStack.Count() != 0)
                        {
                            output = output + ' ' + myStack.Peek();
                            myStack.Pop();
                        }
                    }
                myStack.Pop();
                }
            }
        }
           while(myStack.Count() != 0)
           {
               output = output + " " + myStack.Peek();
               myStack.Pop();
           }
        //Done RPN
           //Now we need to Evaluate the RPN
           evalu(output);
    }
예제 #50
0
 /**
  * The constructor
  */
 public StackScreen()
     : base()
 {
     mStack = new System.Collections.Generic.Stack<IScreen>();
 }
예제 #51
0
 /**
  * The constructor
  */
 public StackScreen()
     : base()
 {
     mStack = new System.Collections.Generic.Stack<IScreen>();
     mApplicationBarItemsIndexes = new Dictionary<Object, int>();
 }
예제 #52
0
        public static void interateBinaryTreeEx(TreeAndGraph.BinaryTreeNode head, Order o)
        {
            TreeAndGraph.BinaryTreeNode btn = head;
            if (o == Order.Post)
            {
                System.Collections.Generic.Stack<TreeAndGraph.BinaryTreeNode> s
                    = new System.Collections.Generic.Stack<TreeAndGraph.BinaryTreeNode>();
                s.Push(btn);
                TreeAndGraph.BinaryTreeNode cur = null;
                TreeAndGraph.BinaryTreeNode pre = null;
                while (s.Count != 0)
                {
                    cur = s.Peek();
                    if ((cur.LeftNode == null && cur.RightNode == null) || (pre != null && (pre == cur.LeftNode || pre == cur.RightNode)))
                    {
                        System.Console.WriteLine("XPost:"+cur.Data);
                        s.Pop();
                        pre = cur;
                    }
                    else
                    {
                        if (cur.RightNode != null)
                        {
                            s.Push(cur.RightNode);
                        }
                        if (cur.LeftNode != null)
                        {
                            s.Push(cur.LeftNode);
                        }
                    }
                }
            }
            if (o == Order.Pre)
            {
                System.Collections.Generic.Stack<TreeAndGraph.BinaryTreeNode> s
                    = new System.Collections.Generic.Stack<TreeAndGraph.BinaryTreeNode>();

                while (btn != null || s.Count != 0)
                {
                    while (btn != null)
                    {
                        s.Push(btn);
                        System.Console.WriteLine("XPre:" + btn.Data);
                        btn = btn.LeftNode;
                    }
                    if (s.Count != 0)
                    {
                        btn = s.Pop().RightNode;
                    }
                }
            }
            if (o == Order.Mid)
            {
                System.Collections.Generic.Stack<TreeAndGraph.BinaryTreeNode> s
                     = new System.Collections.Generic.Stack<TreeAndGraph.BinaryTreeNode>();
                while (btn != null || s.Count != 0)
                {
                    while (btn != null)
                    {
                        s.Push(btn);
                        btn = btn.LeftNode;
                    }
                    if (s.Count != 0)
                    {
                        btn = s.Pop();
                        System.Console.WriteLine("XMid:" + btn.Data);
                        btn = btn.RightNode;
                    }

                }
            }
        }
예제 #53
0
        private JsonReader(System.IO.TextReader reader, bool owned)
        {
            if (reader == null)
                throw new System.ArgumentNullException("reader");

            _parserInString = false;
            _parserReturn = false;

            _readStarted = false;
            _automatonStack = new System.Collections.Generic.Stack<int>();
            _automatonStack.Push((int) ParserToken.End);
            _automatonStack.Push((int) ParserToken.Text);

            _lexer = new Lexer(reader);

            EndOfInput = false;
            EndOfJson = false;

            _reader = reader;
            _readerIsOwned = owned;
        }
            public void PushSubOperation(IRadicalYieldInstruction op)
            {
                if (op == null) throw new System.ArgumentNullException("op");

                if (_stack == null) _stack = new System.Collections.Generic.Stack<IRadicalYieldInstruction>();
                _stack.Push(op);
            }
예제 #55
0
        //private static string strDatFilNam;//程序配置数据文件名
        static GlobalVar()
        {
            g_ErrInfos = new System.Collections.Generic.Stack<ErrorInfo>();
            PROGRAM_ROOT_PATH = System.Windows.Forms.Application.StartupPath;
            strCfgFilNam = @"\config.db";

            //strDatFilNam = @"\datas.db";
            //将密钥定入代码中是不安全的,但明文中没有第三信息,只为忽悠
            strSecurityKey = "kener";
        }
예제 #56
0
 static KeyboardHook()
 {
     longHolder = new System.Collections.Generic.Stack<LongKeyData>(10);
 }
예제 #57
0
        /// <summary>
        /// カバーフローを初期化する。
        /// </summary>
        private void Initialize()
        {
            _coverImages = new System.Collections.Generic.Dictionary<int, CoverImage>();
            _onscreenCovers = new System.Collections.Generic.Dictionary<int, ItemView>();
            _offscreenCovers = new System.Collections.Generic.Stack<ItemView>();
            #if false
            // デフォルト画像の作成
            _defaultImage = new CoverImage(_dataSource.RequestDefaultImage(this));
            #endif
            // スクロールビューの作成
            _scrollView = new MonoTouch.UIKit.UIScrollView(Frame)
            {
                UserInteractionEnabled = false,
                MultipleTouchEnabled = false,
                AutoresizingMask = MonoTouch.UIKit.UIViewAutoresizing.FlexibleHeight | MonoTouch.UIKit.UIViewAutoresizing.FlexibleWidth
            };
            AddSubview(_scrollView);

            MultipleTouchEnabled = false;
            UserInteractionEnabled = true;
            AutosizesSubviews = true;

            //Layer.Position = new System.Drawing.PointF((float)(Frame.Size.Width / 2), (float)(Frame.Height / 2));
            Layer.Position = new System.Drawing.PointF((float)(Frame.Left + Frame.Size.Width / 2), (float)(Frame.Top + Frame.Height / 2));

            // Initialize the visible and selected cover range.
            _lowerVisibleCover = _upperVisibleCover = -1;
            _selectedCoverView = null;

            // Set up transforms
            UpdateTransforms();

            // Set some perspective
            var sublayerTransform = MonoTouch.CoreAnimation.CATransform3D.Identity;
            sublayerTransform.m34 = -0.01f;
            _scrollView.Layer.SublayerTransform = sublayerTransform;

            Bounds = Frame;
        }
예제 #58
0
        private static int CalculateIndentation(string baseline, ITextSnapshotLine line, IEditorOptions options, IClassifier classifier, ITextView textView) {
            int indentation = GetIndentation(baseline, options.GetTabSize());
            int tabSize = options.GetIndentSize();
            var tokens = classifier.GetClassificationSpans(line.Extent);
            if (tokens.Count > 0 && !IsUnterminatedStringToken(tokens[tokens.Count - 1])) {
                int tokenIndex = tokens.Count - 1;

                while (tokenIndex >= 0 &&
                    (tokens[tokenIndex].ClassificationType.IsOfType(PredefinedClassificationTypeNames.Comment) ||
                    tokens[tokenIndex].ClassificationType.IsOfType(PredefinedClassificationTypeNames.WhiteSpace))) {
                    tokenIndex--;
                }

                if (tokenIndex < 0) {
                    return indentation;
                }

                if (ReverseExpressionParser.IsExplicitLineJoin(tokens[tokenIndex])) {
                    // explicit line continuation, we indent 1 level for the continued line unless
                    // we're already indented because of multiple line continuation characters.

                    indentation = GetIndentation(line.GetText(), options.GetTabSize());
                    var joinedLine = tokens[tokenIndex].Span.Start.GetContainingLine();
                    if (joinedLine.LineNumber > 0) {
                        var prevLineSpans = classifier.GetClassificationSpans(tokens[tokenIndex].Span.Snapshot.GetLineFromLineNumber(joinedLine.LineNumber - 1).Extent);
                        if (prevLineSpans.Count == 0 || !ReverseExpressionParser.IsExplicitLineJoin(prevLineSpans[prevLineSpans.Count - 1])) {
                            indentation += tabSize;
                        }
                    } else {
                        indentation += tabSize;
                    }

                    return indentation;
                }

                string sline = tokens[tokenIndex].Span.GetText();
                var lastChar = sline.Length == 0 ? '\0' : sline[sline.Length - 1];

                // use the expression parser to figure out if we're in a grouping...
                var spans = textView.BufferGraph.MapDownToFirstMatch(
                    tokens[tokenIndex].Span,
                    SpanTrackingMode.EdgePositive,
                    PythonContentTypePrediciate
                );
                if (spans.Count == 0) {
                    return indentation;
                }
                
                var revParser = new ReverseExpressionParser(
                        spans[0].Snapshot,
                        spans[0].Snapshot.TextBuffer,
                        spans[0].Snapshot.CreateTrackingSpan(
                            spans[0].Span,
                            SpanTrackingMode.EdgePositive
                        )
                    );

                var tokenStack = new System.Collections.Generic.Stack<ClassificationSpan>();
                tokenStack.Push(null);  // end with an implicit newline
                bool endAtNextNull = false;

                foreach (var token in revParser) {
                    tokenStack.Push(token);
                    if (token == null && endAtNextNull) {
                        break;
                    } else if (token != null &&
                       token.ClassificationType == revParser.Classifier.Provider.Keyword &&
                       PythonKeywords.IsOnlyStatementKeyword(token.Span.GetText())) {
                        endAtNextNull = true;
                    }
                }

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

                while (tokenStack.Count > 0) {
                    var token = tokenStack.Pop();
                    if (token == null) {
                        current.NeedsUpdate = true;
                    } else if (token.IsOpenGrouping()) {
                        indentStack.Push(current);
                        var start = token.Span.Start;
                        var line2 = start.GetContainingLine();
                        var next = tokenStack.Count > 0 ? tokenStack.Peek() : null;
                        if (next != null && next.Span.End <= line2.End) {
                            current = new LineInfo {
                                Indentation = start.Position - line2.Start.Position + 1
                            };
                        } else {
                            current = new LineInfo {
                                Indentation = GetIndentation(line2.GetText(), tabSize) + tabSize
                            };
                        }
                    } else if (token.IsCloseGrouping()) {
                        if (indentStack.Count > 0) {
                            current = indentStack.Pop();
                        } else {
                            current.NeedsUpdate = true;
                        }
                    } else if (ReverseExpressionParser.IsExplicitLineJoin(token)) {
                        while (token != null && tokenStack.Count > 0) {
                            token = tokenStack.Pop();
                        }
                    } else if (current.NeedsUpdate == true) {
                        var line2 = token.Span.Start.GetContainingLine();
                        current = new LineInfo {
                            Indentation = GetIndentation(line2.GetText(), tabSize)
                        };
                    }

                    if (token != null && ShouldDedentAfterKeyword(token)) {     // dedent after some statements
                        current.ShouldDedentAfter = true;
                    }

                    if (token != null && token.Span.GetText() == ":" &&         // indent after a colon
                        indentStack.Count == 0) {                               // except in a grouping
                        current.ShouldIndentAfter = true;
                        // If the colon isn't at the end of the line, cancel it out.
                        // If the following is a ShouldDedentAfterKeyword, only one dedent will occur.
                        current.ShouldDedentAfter = (tokenStack.Count != 0 && tokenStack.Peek() != null);
                    }
                }

                indentation = current.Indentation +
                    (current.ShouldIndentAfter ? tabSize : 0) -
                    (current.ShouldDedentAfter ? tabSize : 0);
            }

            // Map indentation back to the view's text buffer.
            int offset = 0;
            var viewLineStart = textView.BufferGraph.MapUpToSnapshot(line.Start, PointTrackingMode.Positive, PositionAffinity.Successor, textView.TextSnapshot);
            if (viewLineStart.HasValue) {
                offset = viewLineStart.Value.Position - viewLineStart.Value.GetContainingLine().Start.Position;
            }

            return offset + indentation;
        }
예제 #59
0
        private void Init()
        {
            _hasReachedEnd = false;
            _indentation = 0;
            _indentValue = 4;
            _prettyPrint = false;
            _validate = true;

            _ctxStack = new System.Collections.Generic.Stack<WriterContext>();
            _context = new WriterContext();
            _ctxStack.Push(_context);
        }
예제 #60
0
        private static SelectionCriterion _ParseCriterion(String s)
        {
            if (s == null) return null;

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

            // 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("'"))
                            {
                                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 "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;
        }