Пример #1
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, ' ');
    }
Пример #2
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);
        }
Пример #3
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;
 }
Пример #4
0
 private void FillStack_Click(object sender, EventArgs e)
 {
     for (int i = 0; i < 2; i++)
     {
         stackCollection.Push(_last++);
     }
 }
Пример #5
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;
 }
Пример #6
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;
 }
Пример #7
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);
            }
Пример #8
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);
        }
Пример #9
0
 public static void DrillDownAqbSqlContext(
     ActiveQueryBuilder.Core.SQLContext sc
     , System.Data.DataTable tbl
     , string dataStoreName
     )
 {
     ActiveQueryBuilder.Core.MetadataList items = sc.MetadataContainer.Items;
     //
     System.Collections.Generic.Stack <StackItem> stack = new System.Collections.Generic.Stack <StackItem>( );
     stack.Push(new StackItem {
         list = items, index = 0, parentID = -1, grandParentID = -1
     });
     do
     {
         StackItem si = stack.Pop( );
         ActiveQueryBuilder.Core.MetadataList actualMIList = si.list;
         int actualIndex    = si.index;
         int actualParentID = si.grandParentID; // IMPORTANT!!!
         for ( ; actualIndex < actualMIList.Count; actualIndex++)
         {
             System.Data.DataRow row = tbl.NewRow( );
             row["DataStoreName"] = dataStoreName;
             ExtractMetadataItem(row, actualMIList[actualIndex], actualParentID, tbl);
             tbl.Rows.Add(row);
             if (actualMIList[actualIndex].Items.Count > 0) // branch...
             {
                 int count = tbl.Rows.Count;
                 System.Data.DataRowCollection rows = tbl.Rows;
                 int parentId = (int)rows[count - 1]["ID"];
                 // Push the "next" Item...
                 stack.Push(new StackItem
                 {
                     list          = actualMIList,
                     index         = actualIndex + 1,
                     parentID      = parentId,
                     grandParentID = actualParentID
                 });
                 // Reset the loop to process the "actual" Item...
                 actualParentID = parentId;
                 actualMIList   = actualMIList[actualIndex].Items;
                 actualIndex    = -1;
             }
         } // for(;;)...
     } while(stack.Count > 0);
 }
Пример #10
0
 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;
 }
Пример #11
0
        /** 更新。
         */
        public static void Main(string a_label = nameof(Test_20))
        {
            UnityEngine.Debug.Log("----- " + a_label + " -----");

            try{
                System.Collections.Generic.Stack <int> t_item_from = new System.Collections.Generic.Stack <int>();
                {
                    t_item_from.Push(1);
                    t_item_from.Push(2);
                    t_item_from.Push(3);
                }

                //オブジェクト ==> JSONITEM。
                                #if (FEE_JSON)
                Fee.JsonItem.JsonItem t_jsonitem = Fee.JsonItem.Convert.ObjectToJsonItem <System.Collections.Generic.Stack <int> >(t_item_from);
                                #endif

                //JSONITEM ==> JSON文字列。
                                #if (FEE_JSON)
                string t_jsonstring = t_jsonitem.ConvertToJsonString();
                                #else
                string t_jsonstring = UnityEngine.JsonUtility.ToJson(t_item_from);
                                #endif

                //JSON文字列 ==> オブジェクト。
                                #if (FEE_JSON)
                System.Collections.Generic.Stack <int> t_item_to = Fee.JsonItem.Convert.JsonStringToObject <System.Collections.Generic.Stack <int> >(t_jsonstring);
                                #else
                System.Collections.Generic.Stack <int> t_item_to = UnityEngine.JsonUtility.FromJson <System.Collections.Generic.Stack <int> >(t_jsonstring);
                                #endif

                //ログ。
                UnityEngine.Debug.Log(a_label + " : " + t_jsonstring);

                //チェック。
                if (Check(t_item_from, t_item_to) == false)
                {
                    UnityEngine.Debug.LogError("mismatch");
                }
            }catch (System.Exception t_exception) {
                UnityEngine.Debug.LogError(a_label + " : exception : " + t_exception.Message);
            }
        }
Пример #12
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();
 }
Пример #13
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;
 }
Пример #14
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));
             }
         }
     }
 }
Пример #15
0
        private void Awake()
        {
            _hash = 1;

            _unusedCommandBufferIndices = new System.Collections.Generic.Stack <ushort>(bufferSize);
            for (ushort i = 0; i < bufferSize; i++)
            {
                _unusedCommandBufferIndices.Push(i);
            }

            _commandBuffer = new ActiveTimer[bufferSize];
        }
Пример #16
0
        private async Task DeleteNoInterlock(bool GetNextImage = false)
        {
            if (ImageIdxListDeletePtr == -1 || ImageIdxList[ImageIdxListDeletePtr] == -1)
            {
                return;
            }
            var  fileName = ImageList[ImageIdxList[ImageIdxListDeletePtr]].FullName;
            bool result   = true;

            if (!IsUserjgentile)
            {
                result = MessageBox.Show("Confirm delete: " + fileName, "Confirm delete image.", MessageBoxButton.YesNo) == MessageBoxResult.Yes;
            }
            if (result)
            {
                try
                {
                    if (memStream != null)
                    {
                        memStream.Dispose();
                    }
                    memStream           = null;
                    displayPhoto        = null;
                    ImageControl.Source = null;
                    RecyclingBin.MoveHere(fileName);
                    if (!File.Exists(fileName))
                    {
                        DeletedFiles.Push(fileName);
                        ImageIdxList[ImageIdxListDeletePtr] = -1;
                        ImagesNotNull--;
                        ImageIdxListDeletePtr = -1;
                        topTextBoxClass.messageDisplayStart("Deleted: " + fileName, 5);
                    }
                    else
                    {
                        MessageBox.Show("Error: Could not delete image.");
                    }
                }
                catch
                {
                    MessageBox.Show("Exception: Could not delete image.");
                }
            }
            if (ImagesNotNull <= 0)
            {
                ImageListReady = false;
            }
            if (GetNextImage)
            {
                await DisplayGetNextImageWithoutCheck(1);
            }
        }
Пример #17
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;
            }
Пример #18
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;
        }
Пример #19
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;
        }
Пример #20
0
 /// <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;
 }
Пример #21
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;
        }
Пример #22
0
        /// <summary>
        /// Virtual. Plots a time graph with a filtered set of data.
        /// </summary>
        /// <param name="subSet">Filtered set of data.</param>
        /// <param name="panel">The panel.</param>
        protected override void DrawFilteredTimeGraph(IEnumerable subSet, PanelWrapper panel)
        {
            base.DrawFilteredTimeGraph(subSet, panel);

            // Maintain the previous and current point plotted for the virtual method call
            GraphPoint prevPoint = new GraphPoint();
            GraphPoint currPoint = new GraphPoint();

            System.Collections.Generic.Stack<FrameworkElement> dataPointStack =
                new System.Collections.Generic.Stack<FrameworkElement>();

            System.Collections.Generic.Stack<FrameworkElement> dataPointLabelStack =
                new System.Collections.Generic.Stack<FrameworkElement>();

            CollisionDetectionManager collisionManager = GraphBase.GetCollisionDetectionManager(this.DynamicPlotLayer);

            foreach (object o in subSet)
            {
                if (panel.AbortLayout)
                {
                    break;
                }

                GraphPoint gp = this.GetBoundGraphPoint(o);
                if (null == gp)
                {
                    return;
                }

                gp.X1Pixel = this.GetXForDate(gp.X1);
                gp.Y1Pixel = this.GetYForValue(gp.Y1);

                if (!Double.IsNaN(gp.Y2))
                {
                    gp.Y2Pixel = this.GetYForValue(gp.Y2);
                }

                currPoint = gp;

                // process the plotted data marker
                this.ProcessPlottedDataMarker(prevPoint, currPoint);

                if (!this.Minimized)
                {
                    if (!double.IsNaN(gp.Y1) && currPoint.X1Pixel >= 0 && currPoint.X1Pixel < this.DynamicMainLayerViewport.ActualWidth)
                    {
                        FrameworkElement marker = this.GetPlottedDataMarker(gp);
                        double left = Canvas.GetLeft(marker);
#if !SILVERLIGHT
                    // For WPF should snap to grid if requested
                    bool snap = GraphBase.GetSnapToPixels(marker);
                    if (marker.SnapsToDevicePixels != snap)
                    {
                        marker.SnapsToDevicePixels = snap;
                    }
#endif

                        if (left < 0 || (left + marker.Width) > this.DynamicMainLayerViewport.ActualWidth)
                        {
                            this.CurrentWorkingPanel.SeamedElementCollection.Add(marker);
                        }

                        this.DynamicPlotLayer.Children.Add(marker);
                        dataPointStack.Push(marker);

                        FrameworkElement labelElement = null;
                        if (null != this.LabelTemplate)
                        {
                            labelElement = this.LabelTemplate.LoadContent() as FrameworkElement;
                            labelElement.DataContext = gp;
                            dataPointLabelStack.Push(labelElement);
                        }

                        if (null != labelElement)
                        {
                            double offsetValueX = GraphBase.GetXOffset(labelElement);
                            double offsetValueY = GraphBase.GetYOffset(labelElement);

                            // define the label position
                            double labelY = currPoint.Y1Pixel;
                            if (!double.IsNaN(gp.Y2) && gp.Y1 < gp.Y2)
                            {
                                labelY = currPoint.Y2Pixel;
                            }

                            double markerOffset = Math.Abs(GraphBase.GetYOffset(marker)) + 2;
                            Canvas.SetTop(labelElement, (labelY - markerOffset) + offsetValueY);
                            Canvas.SetLeft(labelElement, currPoint.X1Pixel + offsetValueX);
                            labelElement.Visibility = this.ShowDataPointLabels;
                            this.DynamicPlotLayer.Children.Add(labelElement);
                            GraphBase.SetDataPointLabel(marker, labelElement);
                            panel.LabelElements.Add(labelElement);

                            marker.MouseEnter += new MouseEventHandler(this.DataPointMarker_MouseEnter);
                            marker.MouseLeave += new MouseEventHandler(this.DataPointMarker_MouseLeave);
                        }
                    }
                }

                prevPoint = currPoint;
            }

            if (!panel.AbortLayout && this.DetectCollisions)
            {
                Collision previousCollision = null;

                // get the last items in the collection for the data context
                object[] lastItems = this.GetLastDataPoints();
                object lastObject = lastItems[1];
                object secondLastObject = lastItems[0];

                byte lastItemsCheck = 0;

                while (dataPointStack.Count > 0)
                {
                    FrameworkElement ele = dataPointStack.Pop();
                    FrameworkElement labelEle = GraphBase.GetDataPointLabel(ele);

                    if (lastItemsCheck < 2 && null != labelEle && null != labelEle.DataContext)
                    {
                        // this is the last item on the page.
                        // we plot back to front to check if things overlap.
                        ++lastItemsCheck;
                        object gp = ((GraphPoint)labelEle.DataContext).DataContext;
                        if (lastObject == gp)
                        {
                            // this is the last item in the series.
                            GraphBase.SetLastItem(ele, true);
                            labelEle.Visibility = Visibility.Visible;
                            labelEle.RenderTransform = this.LabelTransform;
                        }

                        if (secondLastObject == gp)
                        {
                            // this is the second last item in the series.
                            GraphBase.SetSecondToLast(ele, true);
                            labelEle.Visibility = Visibility.Visible;
                        }
                    }

                    FrameworkElement clashElement = collisionManager.RegisterAndTestIfMarkerOverlaps(ele);

                    if (null != clashElement)
                    {
                        previousCollision = new Collision(clashElement, ele, true);
                        this.CurrentWorkingPanel.CollisionCollection.Add(previousCollision);

                        GraphBase.SetDataPointOverlapProperty(ele, true);
                        GraphBase.SetDataPointOverlapProperty(labelEle, true);
                        labelEle.Visibility = Visibility.Collapsed;

                        GraphBase.SetDataPointOverlapProperty(clashElement, true);
                        FrameworkElement clashElementLabel = GraphBase.GetDataPointLabel(clashElement);
                        GraphBase.SetDataPointOverlapProperty(clashElementLabel, true);
                        clashElementLabel.Visibility = Visibility.Collapsed;
                    }
                    else
                    {
                        // this marker does not overlap
                        previousCollision = null;
                    }
                }

                while (dataPointLabelStack.Count > 0)
                {
                    FrameworkElement ele2 = dataPointLabelStack.Pop();
                    if (collisionManager.RegisterAndTestIfLabelOverlaps(ele2))
                    {
                        GraphBase.SetDataPointOverlapProperty(ele2, true);
                        ele2.Visibility = Visibility.Collapsed;
                    }
                }

                PanelWrapper otherPanel = null;

                // we get panel 2 then panel 1 when getting both panels.
                double markerOffsetToUse = 0;

                // perform seam detection
                // panel1 is to the left of panel2
                if (this.CurrentWorkingPanel == this.Panel1)
                {
                    // panel2 markers must be incremented by the width of the layer.
                    otherPanel = this.Panel2;
                    markerOffsetToUse = this.Panel1.Width;
                }
                else
                {
                    // panel1 markers must be decremented by the width of the plot layer.
                    // if we are renewing both panels, then do not do collisions detections on seams for
                    if (true != this.RenewingBothPanels)
                    {
                        otherPanel = this.Panel1;
                        markerOffsetToUse = this.Panel2.Width * -1;
                    }
                }

                // this gets run if we are renewing a panel, but if renewing both, only for panel 1
                if (null != otherPanel)
                {
                    LookThroughAdjacentPanelForOverlap(this.CurrentWorkingPanel, otherPanel, markerOffsetToUse);
                }

                double lastCollisionPosition = -1;

                foreach (Collision collision in this.CurrentWorkingPanel.CollisionCollection)
                {
                    if (null != this.CollisionTemplate)
                    {
                        FrameworkElement collisionIcon = this.CollisionTemplate.LoadContent() as FrameworkElement;
                        double theXOffset = GraphBase.GetXOffset(collisionIcon);
                        double theYOffset = GraphBase.GetYOffset(collisionIcon);
                        if (null != collisionIcon)
                        {
                            double localxPosition = Canvas.GetLeft(collision.ClusterStartElement) + theXOffset;
                            double localyPosition = Canvas.GetTop(collision.ClusterStartElement) + theYOffset;

                            if (lastCollisionPosition == -1 || localxPosition < lastCollisionPosition - 46)
                            {
                                lastCollisionPosition = localxPosition;

                                Canvas.SetLeft(collisionIcon, localxPosition);
                                Canvas.SetTop(collisionIcon, localyPosition);

                                if (true == collision.ClusterShowingIcon)
                                {
                                    this.DynamicPlotLayer.Children.Add(collisionIcon);
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #23
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);
        }
Пример #24
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;
        }
Пример #25
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;
                    }

                }
            }
        }
Пример #26
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);
    }