Пример #1
0
        public void RollbackTransaction()
        {
            System.Data.SqlClient.SqlTransaction rollbackTransaction;

            try {
                SetLastException(null);

                if (sqlTransactions.Count > 0)
                {
                    rollbackTransaction = (System.Data.SqlClient.SqlTransaction)(sqlTransactions.Pop());

                    rollbackTransaction.Rollback();
                }
            } // end try

            catch (System.Data.SqlClient.SqlException SqlException) {
                SetLastException(SqlException);

                throw;
            } // end catch (SqlException)

            catch (Exception UnhandledException) {
                SetLastException(UnhandledException);

                throw;
            } // end catch (Exception)

            finally {
                OnDemandClose();
            } // end finally

            return;
        }
Пример #2
0
        private void uiCommandManager1_CommandClick(object sender, Janus.Windows.UI.CommandBars.CommandEventArgs e)
        {
            try
            {
                if (e.Command.Key == "cmdBack")
                {
                    SeriesStack.Pop();                     // remove current series;
                    int SeriesId = (int)SeriesStack.Pop(); //return previous series
                    BackButtonSelected           = true;
                    seriesBindingSource.Position = seriesBindingSource.Find("SeriesId", SeriesId);
                }
                //if (e.Command.Key == "cmdMailConnectors")
                //    InitDiagram();
                //if (e.Command.Key == "cmdHideBF")
                //    InitDiagram();
                //if(e.Command.Key == "cmdImage")
                //{

                //        saveFileDialog1.Filter = "BMP files (*.bmp)|*.bmp|All files (*.*)|*.*";
                //        saveFileDialog1.FileName =  this.CurrentSeries().SeriesDescEng + ".bmp";
                //        if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                //        {
                //            string saveas = saveFileDialog1.FileName;
                //            diagram.SaveAsImg(saveas);
                //        }

                //}
            }
            catch (Exception x)
            {
                UIHelper.HandleUIException(x);
            }
        }
Пример #3
0
 /* Returns the node on the top of the stack, and remove it from the
  * stack.  */
 internal Node popNode()
 {
     if (--sp < mk)
     {
         mk = ((System.Int32)marks.Pop());
     }
     return((Node)nodes.Pop());
 }
Пример #4
0
        public int solution(int[] A)
        {
            candidate dominator = new candidate()
            {
                dominator = -1, index = -1
            };
            candidate first;
            candidate second;

            int count = 0;

            System.Collections.Stack st = new System.Collections.Stack();

            for (int i = 0; i < A.Length; i++)
            {
                st.Push(new candidate()
                {
                    dominator = A[i], index = i
                });

                if (st.Count > 1)
                {
                    first  = (candidate)st.Pop();
                    second = (candidate)st.Pop();

                    if (first.dominator == second.dominator)
                    {
                        st.Push(second);
                        st.Push(first);
                    }
                }
            }

            if (st.Count > 0)
            {
                dominator = (candidate)st.Pop();
                for (int i = 0; i < A.Length; i++)
                {
                    if (A[i] == dominator.dominator)
                    {
                        count++;
                    }
                }

                if (count <= A.Length / 2)
                {
                    return(-1);
                }
            }
            else
            {
                return(-1);
            }

            return(dominator.index);
        }
Пример #5
0
        private result getLeader(int[] B, int sIndex, int eIndex)
        {
            int    candidate = 0;
            int    count     = 0;
            int    Length    = eIndex - sIndex + 1;
            int    first     = 0;
            int    second    = 0;
            result r         = new result()
            {
                hasLeader = false, leader = 0, count = 0
            };

            System.Collections.Stack st = new System.Collections.Stack();

            for (int i = sIndex; i <= eIndex; i++)
            {
                st.Push(B[i]);

                if (st.Count > 1)
                {
                    first  = (int)st.Pop();
                    second = (int)st.Pop();
                    if (first == second)
                    {
                        st.Push(second);
                        st.Push(first);
                    }
                }
            }

            if (st.Count > 0)
            {
                candidate = (int)st.Pop();

                for (int i = sIndex; i <= eIndex; i++)
                {
                    if (B[i] == candidate)
                    {
                        count++;
                    }
                }

                if (count > Length / 2)
                {
                    r.hasLeader = true;
                    r.leader    = candidate;
                    r.count     = count;
                }
            }

            return(r);
        }
Пример #6
0
        public void RemoveKey(string key)
        {
            if (!Exists(key))
            {
                return;
            }
            var route = new Stack <TrieNode>();
            var node  = Root;

            foreach (var letter in key)
            {
                route.Push(node);
                node = node.Next(letter);
            }
            node.IsTerminal = false;
            foreach (var letter in key)
            {
                var parentNode = route.Pop();
                if (parentNode.Next(key[route.Count]).IsTerminal ||
                    parentNode.Next(key[route.Count]).Edges.Count > 0)
                {
                    return;
                }
                parentNode.Edges.Remove(key[route.Count]);
            }
        }
        // <summary>
        /// 十进制转换为十六进制
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        public static string toHexString(this string x)
        {
            if (string.IsNullOrEmpty(x))
            {
                return("0");
            }



            string z = null;
            int    X = Convert.ToInt32(x);

            System.Collections.Stack a = new System.Collections.Stack();
            int i = 0;

            while (X > 0)
            {
                a.Push(Convert.ToString(X % 16));
                X = X / 16;
                i++;
            }
            while (a.Count != 0)
            {
                z += ToHex(Convert.ToString(a.Pop()));
            }
            if (string.IsNullOrEmpty(z))
            {
                z = "0";
            }
            return(z);
        }
Пример #8
0
        // LIFO (Last In, First Out)
        public Stack()
        {
            Console.WriteLine("=> Stack");

            System.Collections.Stack numbers = new System.Collections.Stack();

            foreach (int number in new int[] { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21 })
            {
                numbers.Push(number);
                Console.WriteLine("Number: {0} has been pushed on the stack.", number); // entra na pilha
            }

            Console.Write("Iterator: ");

            foreach (int number in numbers)
            {
                Console.Write("{0} ", number);
            }

            // Peek method reads without remove it

            // for (int i = 0; i < numbers.Count; i++)
            //     Console.Write("{0}:{1} ", i, (int)numbers.Peek());

            Console.WriteLine();

            while (numbers.Count > 0)
            {
                int number = (int)numbers.Pop();
                Console.WriteLine("Number: {0} has been popped of the stack.", number); // saiu da pilha
            }

            Console.WriteLine();
        }
Пример #9
0
        //Brute force solution 100% correct
        public int solution(int[] H)
        {
            System.Collections.Stack st = new System.Collections.Stack();

            int b;
            int counter    = 0;
            int wallHeight = 0;

            for (int i = 0; i < H.Length; i++)
            {
                while (wallHeight > H[i] && st.Count > 0)
                {
                    b           = (int)st.Pop();;
                    wallHeight -= b;
                }

                if (wallHeight < H[i])
                {
                    counter++;
                    b           = H[i] - wallHeight;
                    wallHeight += b;
                    st.Push(b);
                }
            }

            return(counter);
        }
Пример #10
0
        //brute force 100% correct
        public int solution(int[] A, int[] B)
        {
            System.Collections.Stack st = new System.Collections.Stack();
            int count = 0;

            for (int i = 0; i < A.Length; i++)
            {
                if (B[i] == 1)
                {
                    st.Push(i);
                }
                else
                {
                    while (st.Count > 0)
                    {
                        if (A[(int)st.Peek()] < A[i])
                        {
                            st.Pop();
                        }
                        else
                        {
                            break;
                        }
                    }
                    if (st.Count == 0)
                    {
                        count++;
                    }
                }
            }


            return(count + st.Count);
        }
Пример #11
0
        /// <summary>
        /// takes an string as an input and checks if the parenthesis are valid or not
        /// Result is displayed as text in console
        /// </summary>
        /// <param name="input">Input String</param>
        public static void ValidataParenthesis(string input)
        {
            System.Collections.Stack s = new System.Collections.Stack();
            Dictionary <char, char>  parenthesisPair = new Dictionary <char, char>();

            parenthesisPair.Add('}', '{');
            parenthesisPair.Add(')', '(');
            parenthesisPair.Add(']', '[');
            char temp;

            foreach (char x in input)
            {
                if (x == '(' || x == '{' || x == '[')
                {
                    s.Push(x);
                }
                else if (x == '}' || x == ')' || x == ']')
                {
                    temp = Convert.ToChar(s.Pop());
                    if (parenthesisPair[x] != temp)
                    {
                        Console.WriteLine("Doesn't Match");
                        return;
                    }
                }
            }
            if (s.Count > 0)
            {
                Console.WriteLine("Doesn't Match");
                return;
            }
            Console.WriteLine("Valid Parenthesis");
        }
Пример #12
0
        public virtual TokenStream pop()
        {
            TokenStream stream = (TokenStream)streamStack.Pop();

            select(stream);
            return(stream);
        }
Пример #13
0
        /// <summary> Pop the next operation off the stack and build a non-terminal node
        /// around it, poping the next two items from the expression stack
        /// as its children
        /// </summary>
        private void  popOperation()
        {
            Operator op = (Operator)m_opStack.Pop();

            /* dispose of stack place holder ops (e.g.. OPEN_PAREN and OPEN_BRACKET) */
            if (op.precedence < 0)
            {
                return;
            }

            if (IndirectionOperatorAllowed)
            {
                /*
                 * Special case to support trailing dot syntax (e.g. a.b. )
                 * If DotOp and nothing on stack then we convert to
                 * an indirection op
                 */
                if (op == Operator.DIRECT_SELECT && m_expStack.Count < 2)
                {
                    op = Operator.INDIRECTION;
                }
            }

            // create operation and set its nodes
            NonTerminalExp node = op.createExpNode();

            node.RightChild = (ValueExp)m_expStack.Pop();

            if (!(node is SingleArgumentExp))
            {
                node.LeftChild = (ValueExp)m_expStack.Pop();
            }

            m_expStack.Push(node);
        }
Пример #14
0
        public int solution(String S)
        {
            // 100%

            if (S.Length % 2 != 0)
            {
                return(0);
            }

            System.Collections.Stack stack = new System.Collections.Stack();
            var array = S.ToArray();

            for (int i = 0; i < S.Length; i++)
            {
                if (array[i] == '(')
                {
                    stack.Push(array[i]);
                }
                else
                {
                    var compare = stack.Count == 0 ? '@' : (char)stack.Pop();
                    if (compare != '(')
                    {
                        return(0);
                    }
                }
            }

            return(stack.Count == 0 ? 1 : 0);
        }
Пример #15
0
        public int stackLeader(int[] A)
        {
            int leader    = -1;
            int candidate = 0;
            int count     = 0;
            int first     = 0;
            int second    = 0;

            System.Collections.Stack st = new System.Collections.Stack();

            for (int i = 0; i < A.Length; i++)
            {
                st.Push(A[i]);

                if (st.Count > 1)
                {
                    first  = (int)st.Pop();
                    second = (int)st.Pop();

                    if (first == second)
                    {
                        st.Push(second);
                        st.Push(first);
                    }
                }
            }

            if (st.Count > 0)
            {
                candidate = (int)st.Pop();

                for (int i = 0; i < A.Length; i++)
                {
                    if (A[i] == candidate)
                    {
                        count++;
                    }
                }

                if (count > A.Length / 2)
                {
                    leader = candidate;
                }
            }

            return(leader);
        }
Пример #16
0
        static void Main(string[] args)
        {
            System.Collections.ArrayList lst1 = new System.Collections.ArrayList();
            lst1.Add("a");
            lst1.Add("b");
            lst1.Insert(1, "c");
            foreach (var item in lst1)
            {
                Console.WriteLine(item);
            }
            for (int i = 0; i < lst1.Count; i++)
            {
                Console.WriteLine(lst1[i]);
            }

            System.Collections.Hashtable lst2 = new System.Collections.Hashtable();
            lst2.Add("123", "anders");
            lst2.Add("124", "lene");
            Console.WriteLine(lst2["124"]);

            //System.Collections.Queue
            System.Collections.Stack s = new System.Collections.Stack();
            s.Push("1");
            s.Push("2");
            s.Push("3");
            var o = s.Pop();

            Garage g = new Garage();

            g.SætBilIGarage(new Bil()
            {
                Mærke = "Volvo"
            });
            g.SætBilIGarage(new Bil()
            {
                Mærke = "BMW"
            });


            System.Collections.Generic.List <string> lst3 = new List <string>();
            lst3.Add("1");
            string r = lst3[0];

            System.Collections.Generic.List <Bil> lst4 = new List <Bil>();
            lst4.Add(new Bil());

            System.Collections.Generic.Queue <int>              lst5 = new Queue <int>();
            System.Collections.Generic.Stack <string>           lst6 = new Stack <string>();
            System.Collections.Generic.Dictionary <string, int> lst7 = new Dictionary <string, int>();
            lst7.Add("123", 5);
            lst7.Add("125", 6);

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

            lst8.Add(3);
            lst8.Add(6);
            lst8.Add(6);
            Test2(lst8.ToArray());
        }
Пример #17
0
 /// <summary>
 /// Pop current root; back to adding to old root
 /// </summary>
 /// <param name="s"></param>
 public override void traceOut(string s)                                         // throws TokenStreamException
 {
     if (inputState.guessing > 0)
     {
         return;
     }
     mostRecentParseTreeRoot = (ParseTreeRule)currentParseTreeRoot.Pop();
 }
Пример #18
0
        /// <summary>
        /// internal.
        /// </summary>
        internal static void Pop()
        {
            MeshCreatorItem M = S.Pop() as MeshCreatorItem;

            //MeshContainer M = S.Pop() as MeshContainer;
            //MeshCreator.MeshListCurrent = M;
            M.Reset();
        }
Пример #19
0
 public FAMIX.Entity PopContext()
 {
     if (stack.Count == 2)
     {
         var a = "";
     }
     return(stack.Pop() as FAMIX.Entity);
 }
Пример #20
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private boolean step() throws LexicalError, SyntaticError, SemanticError
    private bool step()
    {
        if (currentToken == null)
        {
            int pos = 0;
            if (previousToken != null)
            {
                pos = previousToken.Position + previousToken.Lexeme.Length;
            }

            currentToken = new Token(Constants_Fields.DOLLAR, "$", pos);
        }

        int x = ((int?)stack.Pop()).Value;
        int a = currentToken.Id;

        if (x == Constants_Fields.EPSILON)
        {
            return(false);
        }
        else if (isTerminal(x))
        {
            if (x == a)
            {
                if (stack.Count == 0)
                {
                    return(true);
                }
                else
                {
                    previousToken = currentToken;
                    currentToken  = scanner.nextToken();
                    return(false);
                }
            }
            else
            {
                throw new SyntaticError(ParserConstants_Fields.PARSER_ERROR[x], currentToken.Position);
            }
        }
        else if (isNonTerminal(x))
        {
            if (pushProduction(x, a))
            {
                return(false);
            }
            else
            {
                throw new SyntaticError(ParserConstants_Fields.PARSER_ERROR[x], currentToken.Position);
            }
        }
        else         // isSemanticAction(x)
        {
            semanticAnalyser.executeAction(x - ParserConstants_Fields.FIRST_SEMANTIC_ACTION, previousToken);
            return(false);
        }
    }
Пример #21
0
 public object GetData()
 {
     if (HasData())
     {
         return(_data.Pop());
     }
     else
     {
         return(null);
     }
 }
Пример #22
0
 public object GetReturnData()
 {
     if (HasReturnData())
     {
         return(_returnData.Pop());
     }
     else
     {
         return(null);
     }
 }
Пример #23
0
 public void UndoClearHistory()
 {
     while (UndoStack.Count > 0)
     {
         string s    = (string)UndoStack.Pop();
         string xtmp = System.IO.Path.ChangeExtension(s, ".shx");
         string ddbf = System.IO.Path.ChangeExtension(s, ".dbf");
         if (System.IO.File.Exists(s))
         {
             System.IO.File.Delete(s);
         }
         if (System.IO.File.Exists(xtmp))
         {
             System.IO.File.Delete(xtmp);
         }
         if (System.IO.File.Exists(ddbf))
         {
             System.IO.File.Delete(ddbf);
         }
     }
     UpdateUndoButtons();
 }
Пример #24
0
        /// <summary> The front-end has finished so we pop the
        /// stack until it empty
        /// </summary>
        private ValueExp done()
        {
            while (m_opStack.Count > 0)
            {
                popOperation();
            }

            /* should only have one entry on the expression stack */
            ValueExp tree = (ValueExp)m_expStack.Pop();

            if (m_expStack.Count != 0 || m_opStack.Count != 0)
            {
                /* clear the stacks */
                m_expStack.Clear();

                m_opStack.Clear();

                throw new IncompleteExpressionException();
            }

            return(tree);
        }
        public override Tag CreateTag(TagData tagData, CompositeTagData compositeTagData)
        {
            string formUrl = ExtractFormLocn(compositeTagData.StartTag, tagData.UrlBeingParsed);

            if (formUrl != null && formUrl.Length > 0)
            {
                compositeTagData.StartTag["ACTION"] = formUrl;
            }
            if (!(stack.Count == 0) && (this == stack.Peek()))
            {
                stack.Pop();
            }
            return(new FormTag(tagData, compositeTagData));
        }
Пример #26
0
        static void Main(string[] args)
        {
            System.Collections.Stack stack = new System.Collections.Stack();
            stack.Push(1);
            stack.Push(2);
            stack.Push(3);

            Console.WriteLine("1 in stack:{0}", stack.Contains(1));
            Console.WriteLine("Remove 1:{0}", stack.Pop());
            Console.WriteLine("Peek1:{0}", stack.Peek());

            object[] numArray = stack.ToArray();
            Console.WriteLine(string.Join(", ", numArray));
        }
Пример #27
0
        static void Main(string[] args)
        {
            System.Collections.Stack stack = new System.Collections.Stack();
            stack.Push("Fine");
            stack.Push("Does");
            stack.Push("Boy");
            stack.Push("Good");
            stack.Push("Every");

            Console.WriteLine("Peek returns {0}", stack.Peek());
            while (stack.Count > 0)
            {
                Console.WriteLine(stack.Pop());
            }
        }
Пример #28
0
 public Cargo RemoveCargo(Cargo item) // compares given Cargo object with last item in storage and returns it if their variables match
 {
     if (!CompareCargo(item, getLastCargoItem()))
     {
         Console.WriteLine("{0} Does not exist in {1}'s inventory", item.Description, Name);
         return(null);
     }
     else
     {
         Storage.Pop();
         Available += item.Size;
         Console.WriteLine("{0} removed from {1}'s inventory", item.Description, Name);
         return(item);
     }
 }
Пример #29
0
 private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
 {
     try
     {
         while (true)
         {
             QuickBallon q = (QuickBallon)_balloonStack.Pop();
             taskIcon.ShowBalloonTip(q.delay, q.title, q.body, ToolTipIcon.Info);
             System.Threading.Thread.Sleep(q.delay);
         }
     }
     catch
     {
     }
 }
Пример #30
0
        static void Main(string[] args)
        {
            System.Collections.Stack stack = new System.Collections.Stack();

            for (int i = 0; i < 800000; i++)
            {
                stack.Push(i);
            }

            while (stack.Count > 0)
            {
                Console.WriteLine(stack.Pop());
            }

            Console.ReadLine();
        }
Пример #31
0
        public override void execute(StackFrame frame)
        {
            Object obj = frame.popOperand();

            System.Collections.Stack temp = new System.Collections.Stack();
            for (int i = 0; i < depth; i++){
                temp.Push(frame.popOperand());
            }
            frame.pushOperand(obj); // insert at depth depth

            while (temp.Count > 0){
                frame.pushOperand(temp.Pop());
            }

            frame.pushOperand(obj); // put the duplicated one back on top
        }
Пример #32
0
        public static bool verifyPopFromPush(double[] push, double[] pop)
        {
            int index_push = 0;
            int index_pop = 0;
            System.Collections.Stack s = new System.Collections.Stack();

            while (true)
            {
                while (s.Count == 0 || pop[index_pop] != (double)s.Peek())
                {
                    if (index_push > push.Length - 1)
                    {
                        break;
                    }
                    s.Push(push[index_push]);
                    index_push++;

                }

                if ((double)s.Pop() != pop[index_pop])
                {
                    break;
                }
                index_pop++;
                if (index_pop > pop.Length - 1)
                {
                    break;
                }

            }

            if (index_push == push.Length && index_pop == pop.Length && s.Count == 0)
            {
                return true;
            }

            return false;
        }
Пример #33
0
        void NotifyWork()
        {
            NotifyEventObject notifyObj;
             System.Collections.Stack stack = new System.Collections.Stack();
             while (true)
             {

             try
             {

                         if (notifyQueue.Count == 0)
                         {
                             lock (notifyQueue)
                             {
                                 System.Threading.Monitor.Wait(notifyQueue);
                             }
                         }
                         else
                         {
                             stack.Clear();
                             notifyObj = (NotifyEventObject)notifyQueue.Dequeue();
                             foreach (ClientConnection cn in clientStreamArray)
                             {
                                 try
                                 {

                                     if (cn.IsConnected)
                                     {
                                         cn.DoNotify((NotifyEventObject)notifyObj);
                                         // cnt++;
                                     }
                                     else
                                     {
                                         Console.WriteLine("client dead");
                                         stack.Push(cn);
                                     }

                                 }
                                 catch (Exception ex)
                                 {
                                     Console.WriteLine("client dead" + ex.Message);
                                     stack.Push(cn);

                                     //clientStreamArray.Remove(stream);
                                 }
                             }
                             while (stack.Count > 0)
                             {
                                 ClientConnection cc = (ClientConnection)stack.Pop();
                                 clientStreamArray.Remove(cc);
                                 cc.Dispose();
                             }

                     }

                 //lock (clientStreamArray)
                 //{

                 //}
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.Message + ex.StackTrace);
             }

             }
        }
        /// <summary>
        /// load rtf
        /// </summary>
        /// <param name="reader">RTF text reader</param>
        public void Load( RTFReader reader )
        {
            myNodes.Clear();
            System.Collections.Stack groups = new System.Collections.Stack();
            RTFNodeGroup NewGroup = null ;
            RTFNode NewNode = null;
            while( reader.ReadToken() != null )
            {
                if( reader.TokenType == RTFTokenType.GroupStart )
                {
                    // begin group
                    if( NewGroup == null)
                    {
                        NewGroup = this ;
                    }
                    else
                    {
                        NewGroup = new RTFNodeGroup();
                        NewGroup.OwnerDocument = this ;
                    }
                    if( NewGroup != this )
                    {
                        RTFNodeGroup g = ( RTFNodeGroup ) groups.Peek();
                        g.AppendChild( NewGroup );
                    }
                    groups.Push( NewGroup );
                }
                else if( reader.TokenType == RTFTokenType.GroupEnd )
                {
                    // end group
                    NewGroup = ( RTFNodeGroup ) groups.Pop();
                    NewGroup.MergeText();
                    if (NewGroup.FirstNode is RTFNode)
                    {
                        switch (NewGroup.Keyword)
                        {
                            case RTFConsts._fonttbl:
                                // read font table
                                ReadFontTable(NewGroup);
                                break;
                            case RTFConsts._colortbl:
                                // read color table
                                ReadColorTable(NewGroup);
                                break;
                            case RTFConsts._info :
                                // read document information
                                ReadDocumentInfo(NewGroup);
                                break;
                        }
                    }
                    if (groups.Count > 0)
                    {
                        NewGroup = (RTFNodeGroup)groups.Peek();
                    }
                    else
                    {
                        break;
                    }
                    //NewGroup.MergeText();
                }
                else
                {
                    // read content

                    NewNode = new RTFNode( reader.CurrentToken );
                    NewNode.OwnerDocument = this ;
                    NewGroup.AppendChild( NewNode );
                    if (NewNode.Keyword == RTFConsts._f )
                    {
                        RTFFont font = this.FontTable[NewNode.Parameter];
                        if (font != null)
                        {
                            myFontChartset = font.Encoding;
                        }
                        else
                        {
                            myFontChartset = null;
                        }
                        //myFontChartset = RTFFont.GetRTFEncoding( NewNode.Parameter );
                    }
                    else if (NewNode.Keyword == RTFConsts._af)
                    {
                        RTFFont font = this.FontTable[NewNode.Parameter];
                        if (font != null)
                        {
                            myAssociateFontChartset = font.Encoding;
                        }
                        else
                        {
                            myAssociateFontChartset = null;
                        }
                    }
                }
            }// while( reader.ReadToken() != null )
            while( groups.Count > 0 )
            {
                NewGroup = ( RTFNodeGroup ) groups.Pop();
                NewGroup.MergeText();
            }
            //this.UpdateInformation();
        }
Пример #35
0
        /// <summary>
        /// Reverse Polish Notation
        /// �����沨�����ʽ.����.
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        private static string BuildingRPN(string s)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder(s);
            System.Collections.Stack sk = new System.Collections.Stack();
            System.Text.StringBuilder re = new System.Text.StringBuilder();
            char c = ' ';
            //sb.Replace(" ","");//һ��ʼ,��ֻȥ���˿ո�.�����Ҳ��벻֧�ֺ����ͳ������˵��ȫOUT��.
            for (int i = 0; i < sb.Length; i++)
            {
                c = sb[i];
                if (char.IsDigit(c))//���ֵ�ȻҪ��.
                    re.Append(c);
                //if(char.IsWhiteSpace(c)||char.IsLetter(c))//����ǿհ�,��ô��Ҫ.������ĸҲ��Ҫ.
                //continue;
                switch (c)//����������ַ�...�г���Ҫ,û���г��IJ�Ҫ.
                {
                    case '+':
                    case '-':
                    case '*':
                    case '/':
                    case '%':
                    case '^':
                    case '!':
                    case '(':
                    case ')':
                    case '.':
                        re.Append(c);
                        break;
                    default:
                        continue;
                }
            }
            sb = new System.Text.StringBuilder(re.ToString());
            #region �Ը��Ž���Ԥת�崦��.���ű䵥Ŀ�������.
            for (int i = 0; i < sb.Length - 1; i++)
                if (sb[i] == '-' && (i == 0 || sb[i - 1] == '('))
                    sb[i] = '!';//�ַ�ת��.
            #endregion
            #region ����׺���ʽ��Ϊ��׺���ʽ.

            re = new System.Text.StringBuilder();
            for (int i = 0; i < sb.Length; i++)
            {
                if (char.IsDigit(sb[i]) || sb[i] == '.')//�������ֵ.
                {
                    re.Append(sb[i]);//�����׺ʽ
                }
                else if (sb[i] == '+'
                 || sb[i] == '-'
                 || sb[i] == '*'
                 || sb[i] == '/'
                 || sb[i] == '%'
                 || sb[i] == '^'
                 || sb[i] == '!')//.
                {
                    #region ���������
                    while (sk.Count > 0) //ջ��Ϊ��ʱ
                    {
                        c = (char)sk.Pop(); //��ջ�еIJ���������.
                        if (c == '(') //�������������.ͣ.
                        {
                            sk.Push(c); //��������������ѹ��.��Ϊ����������Ҫ����ƥ��.
                            break; //�ж�.
                        }
                        else
                        {
                            if (Power(c) < Power(sb[i]))//������ȼ����ϴεĸ�,��ѹջ.
                            {
                                sk.Push(c);
                                break;
                            }
                            else
                            {
                                re.Append(' ');
                                re.Append(c);
                            }
                            //�������������,��ô�������������׺ʽ��.
                        }
                    }
                    sk.Push(sb[i]); //���²�������ջ.
                    re.Append(' ');
                    #endregion
                }
                else if (sb[i] == '(')//�������ȼ�����
                {
                    sk.Push('(');
                    re.Append(' ');
                }
                else if (sb[i] == ')')//�������ȼ��µ�
                {
                    while (sk.Count > 0) //ջ��Ϊ��ʱ
                    {
                        c = (char)sk.Pop(); //pop Operator
                        if (c != '(')
                        {
                            re.Append(' ');
                            re.Append(c);//����ո���Ҫ��Ϊ�˷�ֹ����ɵ��������ٲ�����������.
                            re.Append(' ');
                        }
                        else
                            break;
                    }
                }
                else
                    re.Append(sb[i]);
            }
            while (sk.Count > 0)//�������һ����ջ��.
            {
                re.Append(' ');
                re.Append(sk.Pop());
            }
            #endregion

            re.Append(' ');
            return FormatSpace(re.ToString());//���������һ�α��ʽ��ʽ��.������Ǻ�׺ʽ��.
        }
Пример #36
0
 /// <summary>
 /// �����沨�����ʽ����.
 /// </summary>
 /// <param name="s"></param>
 /// <returns></returns>
 public static string ComputeRPN(string s)
 {
     string S = BuildingRPN(s);
     string tmp = "";
     System.Collections.Stack sk = new System.Collections.Stack();
     char c = ' ';
     System.Text.StringBuilder Operand = new System.Text.StringBuilder();
     double x, y;
     for (int i = 0; i < S.Length; i++)
     {
         c = S[i];
         if (char.IsDigit(c) || c == '.')
         {//����ֵ�ռ�.
             Operand.Append(c);
         }
         else if (c == ' ' && Operand.Length > 0)
         {
             #region ������ת��
             try
             {
                 tmp = Operand.ToString();
                 if (tmp.StartsWith("-"))//������ת��һ��ҪС��...������ֱ��֧��.
                 {//�����ҵ��㷨�������֧������Զ���ᱻִ��.
                     sk.Push(-((double)Convert.ToDouble(tmp.Substring(1, tmp.Length - 1))));
                 }
                 else
                 {
                     sk.Push(Convert.ToDouble(tmp));
                 }
             }
             catch
             {
                 return "�����쳣����ֵ.";
             }
             Operand = new System.Text.StringBuilder();
             #endregion
         }
         else if (c == '+'//���������.˫Ŀ���㴦��.
          || c == '-'
          || c == '*'
          || c == '/'
          || c == '%'
          || c == '^')
         {
             #region ˫Ŀ����
             if (sk.Count > 0)/*�������ı��ʽ����û�а��������.���Ǹ������ǿմ�.������߼�����������.*/
             {
                 y = (double)sk.Pop();
             }
             else
             {
                 sk.Push(0);
                 break;
             }
             if (sk.Count > 0)
                 x = (double)sk.Pop();
             else
             {
                 sk.Push(y);
                 break;
             }
             switch (c)
             {
                 case '+':
                     sk.Push(x + y);
                     break;
                 case '-':
                     sk.Push(x - y);
                     break;
                 case '*':
                     sk.Push(x * y);
                     break;
                 case '/':
                     sk.Push(x / y);
                     break;
                 case '%':
                     sk.Push(x % y);
                     break;
                 case '^':
                     sk.Push(System.Math.Pow(x, y));
                     break;
             }
             #endregion
         }
         else if (c == '!')//��Ŀȡ��.)
         {
             sk.Push(-((double)sk.Pop()));
         }
     }
     if (sk.Count != 1)
         throw new Exception(String.Format("����ʧ��(sk.Count={0}): {1}", sk.Count, s));
     return sk.Pop().ToString();
 }
        public static void MostrarColeccionesNoGenerics()
        {
            Console.Clear();
            Console.WriteLine("******************************");
            Console.WriteLine("*****Pilas No Genéricas*******");
            Console.WriteLine("******************************");
            Console.ReadLine();

            //DECLARO E INSTANCIO UNA COLECCION DE TIPO LIFO
            System.Collections.Stack pila = new System.Collections.Stack();

            pila.Push(1);
            pila.Push(2);
            pila.Push(3);
            pila.Push(4);

            Console.WriteLine("Agrego elementos a la pila...");
            Console.WriteLine("Utilizo pila.Push()");
            Console.WriteLine("Orden de los elementos: 1 - 2 - 3 - 4");
            Console.ReadLine();

            Console.WriteLine("Muestro el primer elemento de la pila...");
            Console.WriteLine("Utilizo pila.Peek()");
            Console.ReadLine();

            Console.WriteLine(pila.Peek());
            Console.ReadLine();

            Console.WriteLine("Muestro todos los elementos de la pila...");
            Console.WriteLine("Recorro con un foreach. No saco los elementos de la pila.");
            Console.ReadLine();

            foreach (int elemento in pila)
            {
                Console.WriteLine(elemento);
            }

            Console.ReadLine();

            Console.WriteLine("Desapilo todos los elementos de la pila...");
            Console.WriteLine("Utilizo pila.Pop(). Recorro con un for");
            Console.ReadLine();

            int cantidad = pila.Count;

            for (int i = 0; i < cantidad; i++)
            {
                Console.WriteLine("Elemento {0} = {1}", i, pila.Pop());
            }

            Console.ReadLine();

            Console.WriteLine("Cantidad de elementos en la pila = {0}", pila.Count);
            Console.ReadLine();

            Console.Clear();
            Console.WriteLine("******************************");
            Console.WriteLine("****Colas No Genéricas********");
            Console.WriteLine("******************************");
            Console.ReadLine();

            System.Collections.Queue cola = new System.Collections.Queue();

            cola.Enqueue(1);
            cola.Enqueue(2);
            cola.Enqueue(3);
            cola.Enqueue(4);

            Console.WriteLine("Agrego elementos a la cola...");
            Console.WriteLine("Utilizo pila.Enqueue()");
            Console.WriteLine("Orden de los elementos: 1 - 2 - 3 - 4");
            Console.ReadLine();

            Console.WriteLine("Muestro el primer elemento de la cola...");
            Console.WriteLine("Utilizo cola.Peek()");
            Console.ReadLine();

            Console.WriteLine(cola.Peek());
            Console.ReadLine();

            Console.WriteLine("Muestro todos los elementos de la cola...");
            Console.WriteLine("Recorro con un foreach");
            Console.ReadLine();

            foreach (int elemento in cola)
            {
                Console.WriteLine(elemento);
            }

            Console.ReadLine();

            Console.WriteLine("Saco todos los elementos de la cola...");
            Console.WriteLine("Utilizo cola.Dequeue(). Recorro con un for");
            Console.ReadLine();

            cantidad = cola.Count;

            for (int i = 0; i < cantidad; i++)
            {
                Console.WriteLine("Elemento {0} = {1}", i, cola.Dequeue());
            }

            Console.ReadLine();

            Console.WriteLine("Cantidad de elementos en la cola = {0}", cola.Count);
            Console.ReadLine();

            Console.Clear();
            Console.WriteLine("******************************");
            Console.WriteLine("******Listas Dinamicas********");
            Console.WriteLine("******************************");
            Console.ReadLine();

            System.Collections.ArrayList vec = new System.Collections.ArrayList();

            vec.Add(1);
            vec.Add(4);
            vec.Add(3);
            vec.Add(2);

            Console.WriteLine("Agrego elementos al ArrayList...");
            Console.WriteLine("Utilizo vec.Add()");
            Console.WriteLine("Orden de los elementos: 1 - 4 - 3 - 2");
            Console.ReadLine();

            Console.WriteLine("Muestro todos los elementos del ArrayList...");
            Console.WriteLine("Recorro con un foreach");
            Console.ReadLine();

            foreach (int elemento in vec)
            {
                Console.WriteLine(elemento);
            }

            Console.ReadLine();

            Console.WriteLine("Ordeno los elementos del ArrayList...");
            Console.WriteLine("Utilizo vec.Sort(). Recorro con un for");
            Console.ReadLine();

            vec.Sort();

            cantidad = vec.Count;

            for (int i = 0; i < cantidad; i++)
            {
                Console.WriteLine("Elemento {0} = {1}", i, vec[i]);
            }

            Console.ReadLine();

            Console.WriteLine("Ordeno los elementos del ArrayList...");
            Console.WriteLine("Utilizo vec.Reverse(). Recorro con un for");
            Console.ReadLine();

            vec.Reverse();

            cantidad = vec.Count;

            for (int i = 0; i < cantidad; i++)
            {
                Console.WriteLine("Elemento {0} = {1}", i, vec[i]);
            }

            Console.ReadLine();

            Console.Clear();
            Console.WriteLine("******************************");
            Console.WriteLine("*********HashTable************");
            Console.WriteLine("******************************");
            Console.ReadLine();

            System.Collections.Hashtable ht = new System.Collections.Hashtable();

            ht.Add(1, "valor 1");
            ht.Add(4, "valor 4");
            ht.Add(3, "valor 3");
            ht.Add(2, "valor 2");

            Console.WriteLine("Agrego elementos al HashTable...");
            Console.WriteLine("Utilizo vec.Add()");
            Console.WriteLine("Orden de los elementos: 1 - 4 - 3 - 2");
            Console.ReadLine();

            Console.WriteLine("Muestro todos los elementos del HashTable...");
            Console.WriteLine("Recorro con un for");
            Console.ReadLine();

            cantidad = ht.Count;

            for (int i = 1; i <= cantidad; i++)
            {
                Console.WriteLine("Elemento {0} = {1}", i, ht[i]);
            }

            Console.ReadLine();
        }
Пример #38
0
		/// <summary>
		/// Insert the newKey into this B-tree, 
		/// </summary>
		/// <param name="newKey"></param>
		/// <returns></returns>
		public bool Insert(IKey newKey)
		{
			//find the leaf where the newKey should be in
			BNode n = m_top;
			System.Collections.Stack visited = new System.Collections.Stack();
			int pos = -1;
			while (!n.Leaf)
			{
				IKey temp = n.SearchKey(newKey, ref pos);
				if (temp == null)
				{
					uint nextNodeId = n.GetChildAt(pos);
					visited.Push(n);
					
					n = (BNode)m_sgManager.GetSegment(nextNodeId, m_nodeFactory, m_keyFactory);
				}
				else
					return false;
			}
			
			//now BNode n is the leaf where insert should happen
			IKey t_temp = n.SearchKey(newKey, ref pos);
			if (t_temp == null)
			{
				//not exists, go ahead to insert the new key
				if (!n.IsFull)
				{
					n.InsertAtLeaf(newKey, pos);

					return true;
				}
				else
				{
					//split needed for this node
					BNode right = new BNode();
					m_sgManager.GetNewSegment(right);
					IKey median = null;
					n.SplitAtLeaf(newKey, pos,  ref median, ref right); //this split is at leaf

					bool finished = false;					
					//now n holds the left half of the items, 
					//right holds the right half items, median is the middle key

					while (!finished)
					{			
						//parent is node middle key will be inserted
						BNode parent = (visited.Count >0 ? (BNode)visited.Pop() : null);

						if (parent == null)
						{
							//new top node is needed
							BNode new_top = new BNode();
							m_sgManager.GetNewSegment(new_top);
							new_top.SetOrder(m_top.Order);
							new_top.Leaf = false;
							new_top.InsertFirstKey(median, n.SegmentID, right.SegmentID);

							this.m_top_sid = new_top.SegmentID;

							return true;
						}
						else
						{
							IKey tt = parent.SearchKey(median, ref pos);
							if (tt != null)
								return false;

							if (!parent.IsFull)
							{
								parent.InsertAtInternal(median, pos, right.SegmentID);
								return true;
							}
							else
							{
								//parent is full again
								BNode newRight = new BNode();
								m_sgManager.GetNewSegment(newRight);
								newRight.SetOrder(parent.Order);
								newRight.Leaf = parent.Leaf;
								//this split will insert median into the parent, then split and new middle key is newMedian
								IKey newMedian;
								parent.SplitAtInternal(median, pos, right.SegmentID, out newMedian, newRight);

								n = parent;
								median = newMedian;
								right = newRight;
							}

						}

					}


				}
			}
			else
				return false;

			return false;
		}
Пример #39
0
        private static long SearchForInterestFiles(DirectoryInfo dSrcDir, Dictionary<string, FileInfo> src, string stExtensions)
        {
            try
            {
                DateTime cacheDate = DateTime.MinValue;

                Dictionary<string, string> srcCache = new Dictionary<string, string>();

                System.Collections.Stack stackDirs = new System.Collections.Stack();

                string stCachePath = Path.Combine(@".\", dSrcDir.FullName.Replace('\\', '_').Replace(':', '_'));

                int cursorLeft = 0;
                if (File.Exists(stCachePath))
                {
                    Console.Write(String.Format(Resources.readCache, dSrcDir.FullName) + " ");
                    cursorLeft = Console.CursorLeft;

                    FileInfo f = new FileInfo(stCachePath);

                    StreamReader inputlist = File.OpenText(stCachePath);

                    string line = null;

                    while ((line = inputlist.ReadLine()) != null)
                    {
                        if (line.Contains("|"))
                        {
                            string[] split = line.Split('|');
                            srcCache.Add(split[1], split[0]);
                        }
                    }

                    inputlist.Close();

                    if (srcCache.Count > 0)
                        cacheDate = f.LastWriteTimeUtc;
                }
                else
                    Console.WriteLine(String.Format(Resources.warnNocache, dSrcDir.FullName));

                StreamWriter sw = new StreamWriter(stCachePath);

                long TotalInterestSize = 0;

                stackDirs.Push(dSrcDir);
                int schonIndex = 0;

                Stack<FileInfo> staHashToCompute = new Stack<FileInfo>();
                while (stackDirs.Count > 0)
                {
                    DirectoryInfo currentDir = (DirectoryInfo)stackDirs.Pop();

                    //Process .\files
                    foreach (FileInfo fileInfo in currentDir.GetFiles())
                    {
                        if (stExtensions.Contains(fileInfo.Extension))
                        {
                            string hash;
                            if ((fileInfo.LastWriteTimeUtc < cacheDate) && srcCache.ContainsKey(fileInfo.FullName))
                            {
                                hash = srcCache[fileInfo.FullName];
                                AddInSrc(src, fileInfo, hash, sw);
                            }
                            else
                                staHashToCompute.Push(fileInfo);

                            TotalInterestSize += fileInfo.Length;

                            {
                                ++schonIndex;
                                Console.CursorLeft = cursorLeft;
                                Console.Write(_stSchon[schonIndex % _stSchon.Length].ToString());
                            }
                        }
                    }

                    //Process Subdirectories
                    foreach (DirectoryInfo diNext in currentDir.GetDirectories())
                        stackDirs.Push(diNext);
                }

                //Process not cached hashs
                Console.WriteLine();
                if (staHashToCompute.Count > 10)
                    Console.Write(String.Format(Resources.hashToDo, staHashToCompute.Count) + " ");
                cursorLeft = Console.CursorLeft;

                int done = 0;
                foreach (FileInfo fi in staHashToCompute)
                {
                    ++done;
                    Console.CursorLeft = cursorLeft;
                    Console.Write(_stSchon[done % _stSchon.Length].ToString());
                    if (staHashToCompute.Count > 10)
                        if (done % (staHashToCompute.Count / 10) == 0)
                            Console.Write(" " + String.Format(Resources.hashWIP, done, staHashToCompute.Count));

                    string hash = Hash.GetSAH1HashFromFile(fi.FullName);
                    AddInSrc(src, fi, hash, sw);
                }
                sw.Close();

                Console.WriteLine();
                return TotalInterestSize;
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #40
0
        private DateTime AddMissedEvents(DateTime latestTimeStamp)
        {
            DateTime retDateTime = DateTime.MinValue;
            string dateTimeWMI = convertToWMIDateTime(latestTimeStamp);
            CLogger.WriteLog(ELogLevel.DEBUG, "Querying Win32_NTLogEvent");

            string queryStr = @"SELECT * from Win32_NTLogEvent where LogFile = 'Security' and Category =" +
                            EVENT_CATEGORY.ToString() +
                            "and (EventCode=" + OBJ_OPEN_EVENT.ToString() + " OR EventCode= " + OBJ_DELETE_EVENT.ToString() +
                            " OR EventCode=" + OBJ_ACCESS_EVENT.ToString() +") and TimeGenerated > '" + dateTimeWMI + "'";

            SelectQuery query = new SelectQuery(queryStr);

            ManagementObjectSearcher eventLogSearcher = new ManagementObjectSearcher(query);
            CLogger.WriteLog(ELogLevel.DEBUG, "Created new MgmtObjSearcher");

            System.Collections.Stack stack = new System.Collections.Stack();

            foreach (ManagementObject eventLogEntry in eventLogSearcher.Get())
            {
                /* On Win Server 2008, the items are provided by WMI in desc order of timestamps
                 * Hence we add the events to a stack and process it later by popping off elements
                 */
                if (osInfo.Version.Major == OS_VER_WIN_SERVER_2008)
                {
                    stack.Push(eventLogEntry);
                }
                else
                {
                    //CLogger.WriteLog(ELogLevel.DEBUG, "Looping through entries in eventLog");
                    EventEntry e = processManagementObject(eventLogEntry);
                    if (e != null)
                    {
                        CLogger.WriteLog(ELogLevel.DEBUG, "Looping through entries in eventLog , timestamp : "
                                    + e.timestamp.ToString());
                        retDateTime = e.timestamp;  // should not we compare timestamp
                        ProcessEventLogEventEntry(e);
                    }
                }
            }
            while (stack.Count != 0)
            {
                ManagementObject eventLogEntry = (ManagementObject)stack.Pop();
                EventEntry e = processManagementObject(eventLogEntry);
                if (e != null)
                {
                    CLogger.WriteLog(ELogLevel.DEBUG, "Looping through entries in eventLog , timestamp : "
                                + e.timestamp.ToString());
                    retDateTime = e.timestamp;  // should not we compare timestamp
                    ProcessEventLogEventEntry(e);
                }
            }

            CLogger.WriteLog(ELogLevel.DEBUG, "Returning from Missed events");
            return retDateTime;
        }
Пример #41
0
		/// <summary>
		/// Remove the key from the tree.
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public bool Delete(IKey key)
		{
			int pos = -1;
			System.Collections.Stack visited = new System.Collections.Stack();
			System.Collections.Stack viaLinks = new System.Collections.Stack();
			
			//find the node which contains the key
			BNode n = FindNode(m_top, key, ref pos, visited, viaLinks);
			if (n == null)
			{
				return false;
			}
			else
			{
				if (n.Leaf)
				{
					n.RemoveAtLeaf(key, pos);
				}
				else
				{
					visited.Push(n);
					uint nextNodeId = n.GetChildAt(pos+1);
					viaLinks.Push(pos+1);
					BNode t_node = (BNode)m_sgManager.GetSegment(nextNodeId, m_nodeFactory, m_keyFactory);
					//find the leaf most leaf in its right sub-tree
					while (!t_node.Leaf)
					{
						visited.Push(t_node);
						nextNodeId = t_node.GetChildAt(0);
						viaLinks.Push(0);
						t_node = (BNode)m_sgManager.GetSegment(nextNodeId, m_nodeFactory, m_keyFactory);
					}
					Debug.Assert(t_node.Leaf);

					IKey successor = t_node.GetKeyAt(0);
                    
					//replace the key&data in n with the successor
					n.ReplaceKeyDataWSuccessor(key, successor, pos);

					//remove successor from the leaf node
					t_node.RemoveAtLeaf(successor, 0);

					n = t_node;
				}
			}

			//now n is the leaf node where the real deletion happens
			//visited keep all the parents visited so far, viaLinks keeps which links we followed
			while (n.IsUnderflow && n.SegmentID != m_top_sid)
			{

				BNode parent = (BNode)visited.Pop();
				//get left/right brother
				int followed = (int)viaLinks.Pop();
				BNode left = (followed>0? (BNode)m_sgManager.GetSegment(parent.GetChildAt(followed-1), m_nodeFactory, m_keyFactory) : null);
				BNode right = (followed<parent.KeyNums ? (BNode)m_sgManager.GetSegment(parent.GetChildAt(followed+1), m_nodeFactory, m_keyFactory) : null);

				Debug.Assert(left != null || right != null);

				bool combined = false;
				//try combin with right first
				if (right != null && right.KeyNums == right.ReqMinimum)
				{
					//combine with the right
					parent.CombineChildren(followed, n, right);
					Debug.Assert(right.KeyNums == 0);
					Debug.Assert(n.KeyNums > n.ReqMinimum);
					m_sgManager.FreeSegment(right);

					combined = true;

					if (parent.KeyNums == 0)
					{
						Debug.Assert(parent.Leaf == false);
						Debug.Assert(parent.SegmentID == this.m_top_sid);
						//tree will shrink
						this.m_top_sid = n.SegmentID;
						m_sgManager.FreeSegment(parent);
						break;
					}

				}
				else if (left != null && left.KeyNums == left.ReqMinimum)
				{
					//combine with the left
					parent.CombineChildren(followed-1, left, n);
					Debug.Assert(n.KeyNums == 0);
					Debug.Assert(left.KeyNums > left.ReqMinimum);
					m_sgManager.FreeSegment(n);

					combined = true;

					if (parent.KeyNums == 0)
					{
						Debug.Assert(parent.Leaf == false);
						Debug.Assert(parent.SegmentID == this.m_top_sid);
						//tree will shrink
						this.m_top_sid = left.SegmentID;
						m_sgManager.FreeSegment(parent);
						break;
					}

				}
				if (!combined)
				{
					//try redistrubute if combine is not possible
					if (right != null && right.KeyNums > right.ReqMinimum)
					{
						//redistribute one entry from right node
						parent.RedistributeRight2Left(followed, n, right);

					}
					else if (left != null &&  left.KeyNums > left.ReqMinimum)
					{
						//redistribute with left
						parent.RedistributeLeft2Right(followed-1, left, n);
					}

				}

				else
					n = parent;

			}

			return true;
		}
Пример #42
0
    protected void Interpret(Graphics g)
    {
      this._isMeasureInSync = false; // if structure is changed, the measure is out of sync

      char[] searchchars = new Char[] { '\\', '\r', '\n', ')' };

      // Modification of StringFormat is necessary to avoid 
      // too big spaces between successive words
      StringFormat strfmt = (StringFormat)StringFormat.GenericTypographic.Clone();
      strfmt.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces;

      strfmt.LineAlignment = StringAlignment.Far;
      strfmt.Alignment = StringAlignment.Near;

      // next statement is necessary to have a consistent string length both
      // on 0 degree rotated text and rotated text
      // without this statement, the text is fitted to the pixel grid, which
      // leads to "steps" during scaling
      g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

      MeasureFont(g, _font, out _cyBaseLineSpace, out _cyBaseAscent, out _cyBaseDescent);

      System.Collections.Stack itemstack = new System.Collections.Stack();

      Font currFont = (Font)_font.Clone();


      if(null!=_cachedTextLines)
        _cachedTextLines.Clear(); // delete old contents 
      else
        _cachedTextLines = new TextLine.TextLineCollection();


      TextLine currTextLine = new TextLine();
        
      // create a new text line first
      _cachedTextLines.Add(currTextLine);
      int currTxtIdx = 0;

      TextItem currTextItem = new TextItem(currFont);
      //      TextItem firstItem = currTextItem; // preserve the first item
      


      currTextLine.Add(currTextItem);


      while(currTxtIdx<_text.Length)
      {

        // search for the first occurence of a backslash
        int bi = _text.IndexOfAny(searchchars,currTxtIdx);

        if(bi<0) // nothing was found
        {
          // move the rest of the text to the current item
          currTextItem.Text += _text.Substring(currTxtIdx,_text.Length-currTxtIdx);
          currTxtIdx = _text.Length;
        }
        else // something was found
        {
          // first finish the current item by moving the text from
          // currTxtIdx to (bi-1) to the current text item
          currTextItem.Text += _text.Substring(currTxtIdx,bi-currTxtIdx);
          
          if('\r'==_text[bi]) // carriage return character : simply ignore it
          {
            // simply ignore this character, since we search for \n
            currTxtIdx=bi+1;
          }
          else if('\n'==_text[bi]) // newline character : create a new line
          {
            currTxtIdx = bi+1;
            // create a new line
            currTextLine = new TextLine();
            _cachedTextLines.Add(currTextLine);
            // create also a new text item
            currTextItem = new TextItem(currTextItem,null);
            currTextLine.Add(currTextItem);
          }
          else if('\\'==_text[bi]) // backslash : look what comes after
          {
            if(bi+1<_text.Length && (')'==_text[bi+1] || '\\'==_text[bi+1])) // if a closing brace or a backslash, take these as chars
            {
              currTextItem.Text += _text[bi+1];
              currTxtIdx = bi+2;
            }
              // if the backslash not followed by a symbol and than a (, 
            else if(bi+3<_text.Length && !char.IsSeparator(_text,bi+1) && '('==_text[bi+2])
            {
              switch(_text[bi+1])
              {
                case 'b':
                case 'B':
                {
                  itemstack.Push(currTextItem);
                  currTextItem = new TextItem(currTextItem, new Font(currTextItem.Font.FontFamily,currTextItem.Font.Size,currTextItem.Font.Style | FontStyle.Bold, GraphicsUnit.World));
                  currTextLine.Add(currTextItem);
                  currTxtIdx = bi+3;
                }
                  break; // bold
                case 'i':
                case 'I':
                {
                  itemstack.Push(currTextItem);
                  currTextItem = new TextItem(currTextItem, new Font(currTextItem.Font.FontFamily,currTextItem.Font.Size,currTextItem.Font.Style | FontStyle.Italic, GraphicsUnit.World));
                  currTextLine.Add(currTextItem);
                  currTxtIdx = bi+3;
                }
                  break; // italic
                case 'u':
                case 'U':
                {
                  itemstack.Push(currTextItem);
                  currTextItem = new TextItem(currTextItem, new Font(currTextItem.Font.FontFamily,currTextItem.Font.Size,currTextItem.Font.Style | FontStyle.Underline, GraphicsUnit.World));
                  currTextLine.Add(currTextItem);
                  currTxtIdx = bi+3;
                }
                  break; // underlined
                case 's':
                case 'S': // strikeout
                {
                  itemstack.Push(currTextItem);
                  currTextItem = new TextItem(currTextItem, new Font(currTextItem.Font.FontFamily,currTextItem.Font.Size,currTextItem.Font.Style | FontStyle.Strikeout, GraphicsUnit.World));
                  currTextLine.Add(currTextItem);
                  currTxtIdx = bi+3;
                }
                  break; // end strikeout
                case 'g':
                case 'G':
                {
                  itemstack.Push(currTextItem);
                  currTextItem = new TextItem(currTextItem, new Font("Symbol",currTextItem.Font.Size,currTextItem.Font.Style, GraphicsUnit.World));
                  currTextLine.Add(currTextItem);
                  currTxtIdx = bi+3;
                }
                  break; // underlined
                case '+':
                case '-':
                {
                  itemstack.Push(currTextItem);
                  // measure the current font size
                  float cyLineSpace,cyAscent,cyDescent;
                  MeasureFont(g,currTextItem.Font,out cyLineSpace, out cyAscent, out cyDescent);
                  
                  currTextItem = new TextItem(currTextItem, new Font(currTextItem.Font.FontFamily,0.65f*currTextItem.Font.Size,currTextItem.Font.Style, GraphicsUnit.World));
                  currTextLine.Add(currTextItem);
                  currTextItem.m_SubIndex += ('+'==_text[bi+1] ? 1 : -1);


                  if('-'==_text[bi+1]) 
                    currTextItem.m_yShift += 0.15f*cyAscent; // Carefull: plus (+) means shift down
                  else
                    currTextItem.m_yShift -= 0.35f*cyAscent; // be carefull: minus (-) means shift up
                  
                  currTxtIdx = bi+3;
                }
                  break; // underlined
                case 'l': // Plot Curve Symbol
                case 'L':
                {
                  // parse the arguments
                  // either in the Form 
                  // \L(PlotCurveNumber) or
                  // \L(LayerNumber, PlotCurveNumber) or
                  // \L(LayerNumber, PlotCurveNumber, DataPointNumber)


                  // find the corresponding closing brace
                  int closingbracepos = _text.IndexOf(")",bi+1);
                  if(closingbracepos<0) // no brace found, so threat this as normal text
                  {
                    currTextItem.Text += _text.Substring(bi,3);
                    currTxtIdx += 3;
                    continue;
                  }
                  // count the commas between here and the closing brace to get
                  // the number of arguments
                  int parsepos=bi+3;
                  int[] arg = new int[3];
                  int args;
                  for(args=0;args<3 && parsepos<closingbracepos;args++)
                  {
                    int commapos = _text.IndexOf(",",parsepos,closingbracepos-parsepos);
                    int endpos = commapos>0 ? commapos : closingbracepos; // the end of this argument
                    try { arg[args]=System.Convert.ToInt32(_text.Substring(parsepos,endpos-parsepos)); }
                    catch(Exception) { break; }
                    parsepos = endpos+1;
                  }
                  if(args==0) // if not successfully parsed at least one number
                  {
                    currTextItem.Text += _text.Substring(bi,3);
                    currTxtIdx += 3;
                    continue;   // handle it as if it where normal text
                  }

                  // itemstack.Push(currTextItem); // here we don't need to put the item on the stack, since we pared until the closing brace
                  currTextItem = new TextItem(currTextItem,null);
                  currTextLine.Add(currTextItem);
                  currTextItem.SetAsSymbol(args,arg);

                  currTextItem = new TextItem(currTextItem,null); // create a normal text item behind the symbol item
                  currTextLine.Add(currTextItem); // to have room for the following text
                  currTxtIdx = closingbracepos+1;
                }
                  break; // curve symbol
                case '%': // Plot Curve Name
                {
                  // parse the arguments
                  // either in the Form 
                  // \%(PlotCurveNumber) or
                  // \%(LayerNumber, PlotCurveNumber) or
                  Match match;
                  int layerNumber=-1;
                  int plotNumber=-1;
                  string plotLabelStyle=null;
                  bool   plotLabelStyleIsPropColName=false;
                  if((match = _regexIntArgument.Match(_text,bi+2)).Success)
                  {
                    plotNumber = int.Parse(match.Result("${argone}"));
                  }
                  else if((match = _regexIntIntArgument.Match(_text,bi+2)).Success)
                  {
                    layerNumber = int.Parse(match.Result("${argone}"));
                    plotNumber =  int.Parse(match.Result("${argtwo}"));
                  }
                  else if((match = _regexIntQstrgArgument.Match(_text,bi+2)).Success)
                  {
                    plotNumber     = int.Parse(match.Result("${argone}"));
                    plotLabelStyle =  match.Result("${argtwo}");
                    plotLabelStyleIsPropColName=true;
                  }
                  else if((match = _regexIntStrgArgument.Match(_text,bi+2)).Success)
                  {
                    plotNumber     = int.Parse(match.Result("${argone}"));
                    plotLabelStyle =  match.Result("${argtwo}");
                  }
                  else if((match = _regexIntIntStrgArgument.Match(_text,bi+2)).Success)
                  {
                    layerNumber = int.Parse(match.Result("${argone}"));
                    plotNumber =  int.Parse(match.Result("${argtwo}"));
                    plotLabelStyle = match.Result("${argthree}");
                  }
                  else if((match = _regexIntIntQstrgArgument.Match(_text,bi+2)).Success)
                  {
                    layerNumber = int.Parse(match.Result("${argone}"));
                    plotNumber =  int.Parse(match.Result("${argtwo}"));
                    plotLabelStyle = match.Result("${argthree}");
                    plotLabelStyleIsPropColName=true;
                  }
      
                  if(match.Success)
                  {
                    itemstack.Push(currTextItem);
                    currTextItem = new TextItem(currTextItem,null);
                    currTextLine.Add(currTextItem);
                    currTextItem.SetAsPlotCurveName(layerNumber,plotNumber,plotLabelStyle,plotLabelStyleIsPropColName);

                    currTextItem = new TextItem(currTextItem,null); // create a normal text item behind the symbol item
                    currTextLine.Add(currTextItem); // to have room for the following text
                    currTxtIdx = bi+2+match.Length;
                  }
                  else
                  {
                    currTextItem.Text += _text.Substring(bi,2);
                    currTxtIdx += 3;
                    continue;   // handle it as if it where normal text
                  }
                }
                  break; // percent symbol
                default:
                  // take the sequence as it is
                  currTextItem.Text += _text.Substring(bi,3);
                  currTxtIdx = bi+3;
                  break;
              } // end of switch
            }
            else // if no formatting and also no closing brace or backslash, take it as it is
            {
              currTextItem.Text += _text[bi];
              currTxtIdx = bi+1;
            }
          } // end if it was a backslash
          else if(')'==_text[bi]) // closing brace
          {
            // the formating is finished, we can return to the formating of the previous section
            if(itemstack.Count>0)
            {
              TextItem preservedprevious = (TextItem)itemstack.Pop();
              currTextItem = new TextItem(preservedprevious,null);
              currTextLine.Add(currTextItem);
              currTxtIdx = bi+1;
            }
            else // if the stack is empty, take the brace as it is, and use the default style
            {
              currTextItem.Text += _text[bi];
              currTxtIdx = bi+1;
            }

          }
        }

      } // end of while loop

      this._isStructureInSync=true; // now the text was interpreted
    }
Пример #43
0
        /// <summary>
        /// Emulates the behavior of a SAX parser, it realizes the callback events of the parser.
        /// </summary>
        private void DoParsing()
        {
            System.Collections.Hashtable prefixes = new System.Collections.Hashtable();
            System.Collections.Stack stackNameSpace = new System.Collections.Stack();
            locator = new XmlSaxLocatorImpl();
            try
            {
                UpdateLocatorData(this.locator, (System.Xml.XmlTextReader)(this.reader));
                if (this.callBackHandler != null)
                    this.callBackHandler.setDocumentLocator(locator);
                if (this.callBackHandler != null)
                    this.callBackHandler.startDocument();
                while (this.reader.Read())
                {
                    UpdateLocatorData(this.locator, (System.Xml.XmlTextReader)(this.reader));
                    switch (this.reader.NodeType)
                    {
                        case System.Xml.XmlNodeType.Element:
                            bool Empty = reader.IsEmptyElement;
                            System.String namespaceURI = "";
                            System.String localName = "";
                            if (this.namespaceAllowed)
                            {
                                namespaceURI = reader.NamespaceURI;
                                localName = reader.LocalName;
                            }
                            System.String name = reader.Name;
                            SaxAttributesSupport attributes = new SaxAttributesSupport();
                            if (reader.HasAttributes)
                            {
                                for (int i = 0; i < reader.AttributeCount; i++)
                                {
                                    reader.MoveToAttribute(i);
                                    System.String prefixName = (reader.Name.IndexOf(":") > 0) ? reader.Name.Substring(reader.Name.IndexOf(":") + 1, reader.Name.Length - reader.Name.IndexOf(":") - 1) : "";
                                    System.String prefix = (reader.Name.IndexOf(":") > 0) ? reader.Name.Substring(0, reader.Name.IndexOf(":")) : reader.Name;
                                    bool IsXmlns = prefix.ToLower().Equals("xmlns");
                                    if (this.namespaceAllowed)
                                    {
                                        if (!IsXmlns)
                                            attributes.Add(reader.NamespaceURI, reader.LocalName, reader.Name, "" + reader.NodeType, reader.Value);
                                    }
                                    else
                                        attributes.Add("", "", reader.Name, "" + reader.NodeType, reader.Value);
                                    if (IsXmlns)
                                    {
                                        System.String namespaceTemp = "";
                                        namespaceTemp = (namespaceURI.Length == 0) ? reader.Value : namespaceURI;
                                        if (this.namespaceAllowed && !prefixes.ContainsKey(namespaceTemp) && namespaceTemp.Length > 0)
                                        {
                                            stackNameSpace.Push(name);
                                            System.Collections.Stack namespaceStack = new System.Collections.Stack();
                                            namespaceStack.Push(prefixName);
                                            prefixes.Add(namespaceURI, namespaceStack);
                                            if (this.callBackHandler != null)
                                                ((IXmlSaxContentHandler)this.callBackHandler).startPrefixMapping(prefixName, namespaceTemp);
                                        }
                                        else
                                        {
                                            if (this.namespaceAllowed && namespaceTemp.Length > 0 && !((System.Collections.Stack)prefixes[namespaceTemp]).Contains(reader.Name))
                                            {
                                                ((System.Collections.Stack)prefixes[namespaceURI]).Push(prefixName);
                                                if (this.callBackHandler != null)
                                                    ((IXmlSaxContentHandler)this.callBackHandler).startPrefixMapping(prefixName, reader.Value);
                                            }
                                        }
                                    }
                                }
                            }
                            if (this.callBackHandler != null)
                                this.callBackHandler.startElement(namespaceURI, localName, name, attributes);
                            if (Empty)
                            {
                                if (this.NamespaceAllowed)
                                {
                                    if (this.callBackHandler != null)
                                        this.callBackHandler.endElement(namespaceURI, localName, name);
                                }
                                else
                                    if (this.callBackHandler != null)
                                        this.callBackHandler.endElement("", "", name);
                            }
                            break;

                        case System.Xml.XmlNodeType.EndElement:
                            if (this.namespaceAllowed)
                            {
                                if (this.callBackHandler != null)
                                    this.callBackHandler.endElement(reader.NamespaceURI, reader.LocalName, reader.Name);
                            }
                            else
                                if (this.callBackHandler != null)
                                    this.callBackHandler.endElement("", "", reader.Name);
                            if (this.namespaceAllowed && prefixes.ContainsKey(reader.NamespaceURI) && ((System.Collections.Stack)stackNameSpace).Contains(reader.Name))
                            {
                                stackNameSpace.Pop();
                                System.Collections.Stack namespaceStack = (System.Collections.Stack)prefixes[reader.NamespaceURI];
                                while (namespaceStack.Count > 0)
                                {
                                    System.String tempString = (System.String)namespaceStack.Pop();
                                    if (this.callBackHandler != null)
                                        ((IXmlSaxContentHandler)this.callBackHandler).endPrefixMapping(tempString);
                                }
                                prefixes.Remove(reader.NamespaceURI);
                            }
                            break;

                        case System.Xml.XmlNodeType.Text:
                            if (this.callBackHandler != null)
                                this.callBackHandler.characters(reader.Value.ToCharArray(), 0, reader.Value.Length);
                            break;

                        case System.Xml.XmlNodeType.Whitespace:
                            if (this.callBackHandler != null)
                                this.callBackHandler.ignorableWhitespace(reader.Value.ToCharArray(), 0, reader.Value.Length);
                            break;

                        case System.Xml.XmlNodeType.ProcessingInstruction:
                            if (this.callBackHandler != null)
                                this.callBackHandler.processingInstruction(reader.Name, reader.Value);
                            break;

                        case System.Xml.XmlNodeType.Comment:
                            if (this.lexical != null)
                                this.lexical.comment(reader.Value.ToCharArray(), 0, reader.Value.Length);
                            break;

                        case System.Xml.XmlNodeType.CDATA:
                            if (this.lexical != null)
                            {
                                lexical.startCDATA();
                                if (this.callBackHandler != null)
                                    this.callBackHandler.characters(this.reader.Value.ToCharArray(), 0, this.reader.Value.ToCharArray().Length);
                                lexical.endCDATA();
                            }
                            break;

                        case System.Xml.XmlNodeType.DocumentType:
                            if (this.lexical != null)
                            {
                                System.String lname = this.reader.Name;
                                System.String systemId = null;
                                if (this.reader.AttributeCount > 0)
                                    systemId = this.reader.GetAttribute(0);
                                this.lexical.startDTD(lname, null, systemId);
                                this.lexical.startEntity("[dtd]");
                                this.lexical.endEntity("[dtd]");
                                this.lexical.endDTD();
                            }
                            break;
                    }
                }
                if (this.callBackHandler != null)
                    this.callBackHandler.endDocument();
            }
            catch (System.Xml.XmlException e)
            {
                throw e;
            }
        }
Пример #44
0
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Images();

            // Load the source PDF file
            Document doc = new Document(dataDir+ "ImageInformation.pdf");

            // Define the default resolution for image
            int defaultResolution = 72;
            System.Collections.Stack graphicsState = new System.Collections.Stack();
            // Define array list object which will hold image names
            System.Collections.ArrayList imageNames = new System.Collections.ArrayList(doc.Pages[1].Resources.Images.Names);
            // Insert an object to stack
            graphicsState.Push(new System.Drawing.Drawing2D.Matrix(1, 0, 0, 1, 0, 0));

            // Get all the operators on first page of document
            foreach (Operator op in doc.Pages[1].Contents)
            {
                // Use GSave/GRestore operators to revert the transformations back to previously set
                Operator.GSave opSaveState = op as Operator.GSave;
                Operator.GRestore opRestoreState = op as Operator.GRestore;
                // Instantiate ConcatenateMatrix object as it defines current transformation matrix.
                Operator.ConcatenateMatrix opCtm = op as Operator.ConcatenateMatrix;
                // Create Do operator which draws objects from resources. It draws Form objects and Image objects
                Operator.Do opDo = op as Operator.Do;

                if (opSaveState != null)
                {
                    // Save previous state and push current state to the top of the stack
                    graphicsState.Push(((System.Drawing.Drawing2D.Matrix)graphicsState.Peek()).Clone());
                }
                else if (opRestoreState != null)
                {
                    // Throw away current state and restore previous one
                    graphicsState.Pop();
                }
                else if (opCtm != null)
                {
                    System.Drawing.Drawing2D.Matrix cm = new System.Drawing.Drawing2D.Matrix(
                       (float)opCtm.Matrix.A,
                       (float)opCtm.Matrix.B,
                       (float)opCtm.Matrix.C,
                       (float)opCtm.Matrix.D,
                       (float)opCtm.Matrix.E,
                       (float)opCtm.Matrix.F);

                    // Multiply current matrix with the state matrix
                    ((System.Drawing.Drawing2D.Matrix)graphicsState.Peek()).Multiply(cm);

                    continue;
                }
                else if (opDo != null)
                {
                    // In case this is an image drawing operator
                    if (imageNames.Contains(opDo.Name))
                    {
                        System.Drawing.Drawing2D.Matrix lastCTM = (System.Drawing.Drawing2D.Matrix)graphicsState.Peek();
                        // Create XImage object to hold images of first pdf page
                        XImage image = doc.Pages[1].Resources.Images[opDo.Name];

                        // Get image dimensions
                        double scaledWidth = Math.Sqrt(Math.Pow(lastCTM.Elements[0], 2) + Math.Pow(lastCTM.Elements[1], 2));
                        double scaledHeight = Math.Sqrt(Math.Pow(lastCTM.Elements[2], 2) + Math.Pow(lastCTM.Elements[3], 2));
                        // Get Height and Width information of image
                        double originalWidth = image.Width;
                        double originalHeight = image.Height;

                        // Compute resolution based on above information
                        double resHorizontal = originalWidth * defaultResolution / scaledWidth;
                        double resVertical = originalHeight * defaultResolution / scaledHeight;

                        // Display Dimension and Resolution information of each image
                        Console.Out.WriteLine(
                                string.Format(dataDir + "image {0} ({1:.##}:{2:.##}): res {3:.##} x {4:.##}",
                                             opDo.Name, scaledWidth, scaledHeight, resHorizontal,
                                             resVertical));
                    }
                }
            }
            
            
        }