Clear() public method

public Clear ( ) : void
return void
Exemplo n.º 1
0
    public void PurgeNavigationStack()
    {
        if (navigationStacks.ContainsKey(SceneManager.GetActiveScene().name) == false)
        {
            navigationStack.Clear();
        }
        else
        {
            navigationStack.Clear();

            navigationStacks.Remove(SceneManager.GetActiveScene().name);
        }
    }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            // Declare stack collection
            Stack myStack = new Stack();

            // Push elements onto the stack
            myStack.Push("item 1");
            myStack.Push("item 2");
            myStack.Push("item 3");

            // Display number of items
            Console.WriteLine("{0} Items on the stack", myStack.Count);

            // Have a peek at the item on top
            Console.WriteLine("{0}", myStack.Peek());

            // Pop off an element
            myStack.Pop(); // gets top value

            // Have a peek at the item on top
            Console.WriteLine("{0}", myStack.Peek());

            // Clear stack
            myStack.Clear();

            // Display number of items
            Console.WriteLine("{0} Items on the stack", myStack.Count);

            Console.ReadLine();
        }
Exemplo n.º 3
0
            public override void execute3(RunTimeValueBase thisObj,FunctionDefine functionDefine,SLOT returnSlot,SourceToken token,StackFrame stackframe,out bool success)
            {
                System.Collections.Stack stack =
                    (System.Collections.Stack)((LinkObj <object>)((ASBinCode.rtData.rtObjectBase)thisObj).value).value;

                try
                {
                    stack.Clear();
                    returnSlot.setValue(ASBinCode.rtData.rtUndefined.undefined);
                    success = true;
                }
                //catch (KeyNotFoundException)
                //{
                //    success = false;
                //    stackframe.throwAneException(token, arraylist.ToString() + "没有链接到脚本");
                //}
                catch (ArgumentException a)
                {
                    success = false;
                    stackframe.throwAneException(token,a.Message);
                }
                catch (IndexOutOfRangeException i)
                {
                    success = false;
                    stackframe.throwAneException(token,i.Message);
                }
            }
Exemplo n.º 4
0
    static void Main(string[] args)
    {
        short diamonds;
        int   N = Int32.Parse(Console.ReadLine());

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

        for (int i = 0; i < N; i++)
        {
            diamonds = 0;

            foreach (char c in Console.ReadLine())
            {
                if (c == '<')
                {
                    stack.Push(c);
                }
                else if (c == '>' && stack.Count > 0)
                {
                    stack.Pop();
                    diamonds++;
                }
            }

            stack.Clear();

            Console.WriteLine(diamonds);
        }
    }
Exemplo n.º 5
0
        public void LoadXml(string xml)
        {
            root = null;
#if CF_1_0
			stack = new Stack ();
#else
            stack.Clear();
#endif
            Parse(new StringReader(xml), this);
        }
Exemplo n.º 6
0
 static public int Clear(IntPtr l)
 {
     try {
         System.Collections.Stack self = (System.Collections.Stack)checkSelf(l);
         self.Clear();
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Exemplo n.º 7
0
        /// <summary>
        /// Sets the enumerator to its initial position, which is before
        /// the first element in the random access list.
        /// </summary>
        public void Reset()
        {
            index          = -1;
            currentTopNode = head;
            treeStack.Clear();

            //  If the list is not empty.
            if (count > 0)
            {
                // Push the first node in the list onto the stack.
                treeStack.Push(head.Root);
            }
        }
 static int Clear(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 1);
         System.Collections.Stack obj = (System.Collections.Stack)ToLua.CheckObject(L, 1, typeof(System.Collections.Stack));
         obj.Clear();
         return(0);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
Exemplo n.º 9
0
    public static void ClearResetsNumberOfElementsToZero()
    {
        int iNumElementsAdded = 2;
        Stack stack = new Stack();

        for (int i = 0; i < iNumElementsAdded; i++)
        {
            stack.Push(new Object());
        }

        stack.Clear();

        Assert.Equal(0, stack.Count);
    }
Exemplo n.º 10
0
        /// <summary>
        /// Sets the enumerator to its initial position, which is before
        /// the first element in the AVL tree.
        /// </summary>
        public void Reset()
        {
            index = 0;

            nodeStack.Clear();

            IAvlNode currentNode = root;

            // Push nodes on to the stack to get to the first item.
            while (currentNode != AvlNode.NullNode)
            {
                nodeStack.Push(currentNode);
                currentNode = currentNode.LeftChild;
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// 计算条件组合表达式结果
        /// </summary>
        /// <param name="strConditionExpression">条件组合表达式</param>
        /// <returns></returns>
        public static bool CalculateApproveFlowStepConditionExpression(string strConditionExpression)
        {
            //1.处理表达式字符串
            //1.1.全部转换为小写
            strConditionExpression = strConditionExpression.ToLower();

            //1.2.将and和or转换为&和|
            strConditionExpression = strConditionExpression.Replace("and", "&");
            strConditionExpression = strConditionExpression.Replace("or", "|");

            //1.3.删除空格字符
            strConditionExpression = strConditionExpression.Replace(" ", "");

            //2.将中缀表达式转换成后缀表达式
            strConditionExpression = TransformPostFix(strConditionExpression);

            //3.运算后缀表达式
            Stack stack = new Stack();
            string[] arrayString = strConditionExpression.Split('$');
            foreach (string str in arrayString)
            {
                if (str == "true" || str == "false")
                {
                    stack.Push(Convert.ToBoolean(str));
                }
                else
                {
                    try
                    {
                        bool bRight = (bool)stack.Pop();
                        bool bLeft = (bool)stack.Pop();

                        switch (str)
                        {
                            case "&": stack.Push(bLeft && bRight); break;
                            case "|": stack.Push(bLeft || bRight); break;
                        }
                    }
                    catch (InvalidOperationException e)
                    {
                        stack.Clear();
                        throw new Exception(e.Message);
                    }
                }
            }
            return (bool)stack.Pop();
        }
Exemplo n.º 12
0
        static void Main(string[] args)
        {
            Stack myStack = new Stack();

            myStack.Push("item 1");
            myStack.Push("item 2");
            myStack.Push("item 3");
            Console.WriteLine("{0} Items on the stack", myStack.Count);

            //Have a peek at the top item
            Console.WriteLine("{0}", myStack.Peek());

            myStack.Pop();
            Console.WriteLine("{0}", myStack.Peek());

            myStack.Clear();
            Console.WriteLine("{0} Items on the stack", myStack.Count);

            Console.ReadLine();
        }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            Stack myStack = new Stack();

            myStack.Push("item 1");
            myStack.Push("item 2");
            myStack.Push("item 3");
            Console.WriteLine("{0} Items on the stack", myStack.Count);

            // Have a peek at the top item
            Console.WriteLine("{0}", myStack.Peek());

            myStack.Pop(); // pops "item 3" off the top
            // now "item 2" is the top item
            Console.WriteLine("{0}", myStack.Peek());

            myStack.Clear(); // get rid of everything
            Console.WriteLine("{0} Items on the stack", myStack.Count);

            Console.ReadLine();
        }
        /**
         * Recursively parses the token array.  Recursion is used in order
         * to evaluate parentheses and function arguments
         *
         * @param iterator an iterator of tokens
         * @return the root node of the current parse stack
         * @exception FormulaException if an error occurs
         */
        private ParseItem parseCurrent(IEnumerator<ParseItem> iterator)
        {
            Stack<ParseItem> stack = new Stack<ParseItem>();
            Stack<Operator> operators = new Stack<Operator>();
            Stack<ParseItem> args = null; // we usually don't need this

            bool parenthesesClosed = false;
            ParseItem lastParseItem = null;

            while (!parenthesesClosed && iterator.MoveNext())
                {
                ParseItem pi = iterator.Current;
                if (pi == null)
                    break;

                pi.setParseContext(parseContext);

                if (pi is Operand)
                    handleOperand((Operand)pi, stack);
                else if (pi is StringFunction)
                    handleFunction((StringFunction)pi, iterator, stack);
                else if (pi is Operator)
                    {
                    Operator op = (Operator)pi;

                    // See if the operator is a binary or unary operator
                    // It is a unary operator either if the stack is empty, or if
                    // the last thing off the stack was another operator
                    if (op is StringOperator)
                        {
                        StringOperator sop = (StringOperator)op;
                        if (stack.Count == 0 || lastParseItem is Operator)
                            op = sop.getUnaryOperator();
                        else
                            op = sop.getBinaryOperator();
                        }

                    if (operators.Count == 0)
                        {
                        // nothing much going on, so do nothing for the time being
                        operators.Push(op);
                        }
                    else
                        {
                        Operator op2 = operators.Peek();

                        // If the last  operator has a higher precedence then add this to
                        // the operator stack and wait
                        if (op2.getPrecedence() < op2.getPrecedence())
                            operators.Push(op2);
                        else if (op2.getPrecedence() == op2.getPrecedence() && op2 is UnaryOperator)
                            {
                            // The operators are of equal precedence, but because it is a
                            // unary operator the operand isn't available yet, so put it on
                            // the stack
                            operators.Push(op2);
                            }
                        else
                            {
                            // The operator is of a lower precedence so we can sort out
                            // some of the items on the stack
                            operators.Pop(); // remove the operator from the stack
                            op2.getOperands(stack);
                            stack.Push(op2);
                            operators.Push(op2);
                            }
                        }
                    }
                else if (pi is ArgumentSeparator)
                    {
                    // Clean up any remaining items on this stack
                    while (operators.Count > 0)
                        {
                        Operator o = operators.Pop();
                        o.getOperands(stack);
                        stack.Push(o);
                        }

                    // Add it to the argument stack.  Create the argument stack
                    // if necessary.  Items will be stored on the argument stack in
                    // reverse order
                    if (args == null)
                        args = new Stack<ParseItem>();

                    args.Push(stack.Pop());
                    stack.Clear();
                    }
                else if (pi is OpenParentheses)
                    {
                    ParseItem pi2 = parseCurrent(iterator);
                    Parenthesis p = new Parenthesis();
                    pi2.setParent(p);
                    p.add(pi2);
                    stack.Push(p);
                    }
                else if (pi is CloseParentheses)
                    parenthesesClosed = true;

                lastParseItem = pi;
                }

            while (operators.Count > 0)
                {
                Operator o = operators.Pop();
                o.getOperands(stack);
                stack.Push(o);
                }

            ParseItem rt = (stack.Count > 0) ? (ParseItem)stack.Pop() : null;

            // if the argument stack is not null, then add it to that stack
            // as well for good measure
            if (args != null && rt != null)
                args.Push(rt);

            arguments = args;

            if (stack.Count > 0 || operators.Count > 0)
                {
                //logger.warn("Formula " + formula + " has a non-empty parse stack");
                }

            return rt;
        }
        protected async Task CompileTokenFile(CancellationToken cancellationToken) {
            try {
                await TaskEx.Run(() => {
                    _languageRoot = new CodeTypeDeclarationRoot() { Project = _document.Project };
                    CodeTypeDeclarationEx initialparent = _languageRoot;


                    cancellationToken.ThrowIfCancellationRequested();

                    _dependingOnSave = this.DependingOn;

                    #region Clean Up

                    _document.Project.Solution.ErrorService.ClearAllErrorsFrom(_document, Errors.ErrorSource.ASTParser);
                    _codeRangeManager.Clear();

                    #endregion

                    #region Merge DependingOn Members

                    if(_dependingOnSave == null) {
                        // merge super base members
                        _languageRoot.Members.AddRange(_root.Members);
                        firstAfterNull = true;
                    } else {

                        //if(!_project.IsInUpdate) {
                        //    if(firstAfterNull) {
                        //        ignoreDependingOnce = true;
                        //        _dependingOnSave.CompileTokenFileAsync();
                        //        firstAfterNull = false;
                        //    }
                        //    _dependingOnSave.WaitUntilUpdated(200);
                        //}
                        
                        _languageRoot.Members.AddRange(_dependingOnSave.GetRootTypeSnapshot().Members);
                    }

                    #endregion

                    var codeLineMap = _document.SegmentService.GetCodeSegmentLinesMap();
                    CodeTypeDeclaration parent = initialparent;
                    Stack<CodeSegment> paramstack = new Stack<CodeSegment>();
                    int linecnt = 0;
                    if(codeLineMap.Keys.Any())
                        linecnt = codeLineMap.Keys.Max();

                    CodeTokenLine line;

                    Stack<CodeTypeDeclarationEx> parentHirarchy = new Stack<CodeTypeDeclarationEx>();
                    int bcc = 0;
                    parentHirarchy.Push(initialparent);

                    cancellationToken.ThrowIfCancellationRequested();

                    #region Parse

                    for(int i = 0; i <= linecnt; i++) {

                        cancellationToken.ThrowIfCancellationRequested();

                        if(codeLineMap.ContainsKey(i))
                            line = codeLineMap[i];
                        else
                            continue;

                        // is class definition?:

                        #region Parse Class Definition

                        var classkeywordSegment = line.CodeSegments[0].ThisOrNextOmit(whitespacetokenNewLines);
                        if(classkeywordSegment != null && classkeywordSegment.Token == Token.KeyWord && classkeywordSegment.TokenString.Equals("class", StringComparison.CurrentCultureIgnoreCase)) {
                            var classNameSegment = classkeywordSegment.FindNextOnSameLine(Token.Identifier);
                            if(classNameSegment != null) {

                                var next = classNameSegment.NextOmit(whitespacetokenNewLines);
                                if(next != null) {
                                    CodeTypeDeclarationEx thisparent = parentHirarchy.Any() ? parentHirarchy.Peek() : _languageRoot;
                                    CodeTypeReferenceEx basecls = null;
                                    CodeSegment refBaseClass = null;
                                    if(next.Token == Token.KeyWord && next.TokenString.Equals("extends", StringComparison.InvariantCultureIgnoreCase)) {
                                        refBaseClass = next.NextOmit(whitespacetokenNewLines);

                                        if(refBaseClass != null) {
                                            if(refBaseClass.Token == Token.Identifier) {
                                                refBaseClass.CodeDOMObject = basecls = new CodeTypeReferenceEx(_document, refBaseClass.TokenString, thisparent);
                                                next = refBaseClass.NextOmit(whitespacetokenNewLines);
                                            } else {
                                                RegisterError(_document, next.Next, "Expected: Class Name Identifier");
                                                next = next.NextOmit(whitespacetokenNewLines);
                                            }
                                        } else {
                                            if(next.Next != null && next.Next.Token != Token.BlockOpen) {
                                                RegisterError(_document, next.Next, "Expected: Class Name Identifier");
                                                next = next.NextOmit(whitespacetokenNewLines);
                                            }
                                        }
                                    }

                                    if(next != null) {
                                        if(next.Token == Token.BlockOpen) {

                                            #region Add Class Declaration

                                            CodeSegment classBodyStart = next;

                                            var type = new CodeTypeDeclarationEx(_document, classNameSegment.TokenString)
                                            {
                                                IsClass = true,
                                                LinePragma = CreatePragma(classNameSegment, _document.FilePath),
                                                CodeDocumentItem = _document
                                            };
                                            classNameSegment.CodeDOMObject = type;


                                            // check if this type was alread defined in this scope
                                            if(thisparent.GetInheritedMembers().Contains(type)) {
                                                RegisterError(_document, classNameSegment, "oh my dear, this class already exisits in the current scope!");
                                            } else {

                                                #region Check & Resolve Baseclass

                                                if(basecls != null) {
                                                    //check if we have a circual interhance tree
                                                    var baseclassImpl = basecls.ResolveTypeDeclarationCache();
                                                    if(baseclassImpl != null && baseclassImpl.IsSubclassOf(new CodeTypeReferenceEx(_document, classNameSegment.TokenString, thisparent))) {
                                                        //circular dependency detected!!
                                                        RegisterError(_document, refBaseClass, "Woops you just produced a circular dependency in your inheritance tree!");
                                                    } else {
                                                        if(basecls != null)
                                                            type.BaseTypes.Add(basecls);
                                                        else
                                                            type.BaseTypes.Add(new CodeTypeReferenceEx(_document, "Object", thisparent) { ResolvedTypeDeclaration = _superBase });
                                                    }
                                                }

                                                #endregion


                                                // extract class documentation Comment
                                                var comment = ExtractComment(classkeywordSegment);
                                                if(comment != null)
                                                    type.Comments.Add(comment);


                                                // Add it to the CodeDOM Tree
                                                thisparent.Members.Add(type);
                                                type.Parent = thisparent;
                                            }

                                            // Create a CodeRange Item
                                            int startOffset = classBodyStart.Range.Offset;
                                            var classBodyEnd = classBodyStart.FindClosingBracked(true);
                                            if(classBodyEnd != null) {
                                                int length = (classBodyEnd.Range.Offset - startOffset);
                                                _codeRangeManager.Add(new CodeRange(new SimpleSegment(startOffset, length), type));
                                            } else {
                                                RegisterError(_document, classBodyStart, "Expected: " + Token.BlockClosed);
                                            }

                                            parentHirarchy.Push(type);
                                            bcc++;

                                            i = classBodyStart.LineNumber; // jumt to:  class Foo { * <---|
                                            continue;

                                            #endregion

                                        } else {
                                            RegisterError(_document, next, "Expected: " + Token.BlockOpen);
                                            i = (next.Next != null) ? next.Next.LineNumber : next.LineNumber;
                                        }
                                    }
                                }
                            }
                        }

                        #endregion

                        // adjust some asumptions the tokenizer has made

                        if(parentHirarchy.Count > 1) {
                            // if we are in a class body, we can't have a traditional command invoke
                            foreach(var s in line.CodeSegments)
                                if(s.Token == Token.TraditionalCommandInvoke) {
                                    s.Token = Token.Identifier;
                                    break;
                                }
                        }


                        // is method definition?:

                        #region Analyze for Method Definition

                        var methodSegment = line.CodeSegments[0].ThisOrNextOmit(whitespacetokenNewLines);
                        if(methodSegment != null && methodSegment.Token == Token.Identifier) {
                            var methodSignatureStart = methodSegment.Next;
                            if(methodSignatureStart != null && methodSignatureStart.Token == Token.LiteralBracketOpen) {
                                var methodSignatureEnd = methodSignatureStart.FindClosingBracked(false);
                                if(methodSignatureEnd != null) {
                                    var startMethodBody = methodSignatureEnd.NextOmit(whitespacetokenNewLinesComments);
                                    if(startMethodBody != null && startMethodBody.Token == Token.BlockOpen) {
                                        // jup we have a method definition here.
                                        // Method body starts at startMethodBody


                                        CodeTypeDeclarationEx thisparent = parentHirarchy.Any() ? parentHirarchy.Peek() : _languageRoot;
                                        bool hasDeclarationError = false;

                                        #region Generate Method Definition DOM

                                        var method = new CodeMemberMethodExAHK(_document)
                                        {
                                            Name = methodSegment.TokenString,
                                            LinePragma = CreatePragma(methodSegment, _document.FilePath),
                                            CodeDocumentItem = _document,
                                            ReturnType = new CodeTypeReferenceEx(_document, typeof(object))
                                        };
                                        methodSegment.CodeDOMObject = method;

                                        //check if this method is not already defined elsewere in current scope

                                        var equalmethods = from m in thisparent.Members.Cast<CodeTypeMember>()
                                                           let meth = m as CodeMemberMethodExAHK
                                                           where meth != null && !meth.IsBuildInType && meth.Equals(method)
                                                           select meth;


                                        if(equalmethods.Any()) {
                                            RegisterError(_document, methodSegment,
                                                string.Format("The Methodename '{0}' is already used in the current scope!", method.Name));
                                            hasDeclarationError = true;
                                        } else {


                                            // extract Method Comment
                                            var comment = ExtractComment(methodSegment);
                                            if(comment != null)
                                                method.Comments.Add(comment);

                                            // extract method params
                                            paramstack.Clear();
                                            CodeSegment previous = methodSignatureStart;

                                            // get method params:
                                            while(true) {
                                                var current = previous.Next;
                                                if(current.Token == Token.Identifier || current.Token == Token.KeyWord) {
                                                    paramstack.Push(current);
                                                } else if(current.Token == Token.ParameterDelemiter || current.Token == Token.LiteralBracketClosed) {
                                                    // end of param reached:
                                                    if(paramstack.Count == 1) {
                                                        // thread one param as the untyped argument, type of Object
                                                        method.Parameters.Add(new CodeParameterDeclarationExpressionEx(typeof(object), paramstack.Pop().TokenString)
                                                            {
                                                                Direction = FieldDirection.In
                                                            });
                                                    } else if(paramstack.Count == 2) {

                                                        CodeParameterDeclarationExpressionEx param;

                                                        var second = paramstack.Pop();
                                                        var first = paramstack.Pop();

                                                        //handle byref ->
                                                        if(first.Token == Token.KeyWord && first.TokenString.Equals(BY_REF, StringComparison.InvariantCultureIgnoreCase)) {
                                                            param = new CodeParameterDeclarationExpressionEx(typeof(object), second.TokenString);
                                                            param.Direction = FieldDirection.Ref;
                                                        } else {
                                                            param = new CodeParameterDeclarationExpressionEx(
                                                                new CodeTypeReferenceEx(_document, first.TokenString, thisparent),
                                                                paramstack.Pop().TokenString);
                                                        }

                                                        // thread two param as the type and argument
                                                        method.Parameters.Add(param);
                                                    }
                                                    if(current.Token == Token.LiteralBracketClosed)
                                                        break;
                                                } else if(current.Token == Token.NewLine){
                                                    break;
                                                }
                                                previous = current;
                                            }
                                        }
                                        #endregion

                                        // Method body ends at
                                        var endMethodBody = startMethodBody.FindClosingBracked(true);
                                        if(endMethodBody != null) {

                                            // get method statements
                                            method.Statements.AddRange(
                                                CollectAllCodeStatements(cancellationToken, thisparent, codeLineMap, startMethodBody.LineNumber + 1, endMethodBody.LineNumber));


                                            // add it to the code DOM Tree
                                            if(!hasDeclarationError) {
                                                thisparent.Members.Add(method);
                                                method.DefiningType = thisparent;
                                            }


                                            // Create a CodeRange Item
                                            int startOffset = startMethodBody.Range.Offset;
                                            int length = (endMethodBody.Range.Offset - startOffset);

                                            _codeRangeManager.Add(new CodeRange(new SimpleSegment(startOffset, length), method));

                                            // move the scanpointer to the method end:
                                            i = endMethodBody.LineNumber;
                                            continue;
                                        } else {
                                            RegisterError(_document, startMethodBody, "Missing: " + Token.BlockClosed);


                                        }
                                    }
                                }
                            }
                        }

                        #endregion


                        // is class property / field

                        #region Parse Class Properties / Fields

                        if(parentHirarchy.Count > 1) {
                            // we must be in a class to have method properties
                            // extract keywords & Identifiers untill we reach
                            // any otherToken - omit whitespaces 

                            List<CodeSegment> declarationStack = new List<CodeSegment>();

                            CodeSegment current = line.CodeSegments[0].ThisOrNextOmit(whitespacetokens);

                            while(current != null) {
                                if(current.Token == Token.WhiteSpace) {
                                    //ignore white spaces
                                } else if(current.Token == Token.Identifier || current.Token == Token.KeyWord) {
                                    declarationStack.Add(current);
                                } else {
                                    break;
                                }
                                current = current.Next;
                            }

                            switch(declarationStack.Count) {


                                case 0:
                                    break;
                                case 1:
                                    // instance field definition
                                    if(declarationStack[0].Token == Token.Identifier) {

                                        // this is an untyped instance class field declaration

                                        var propertyType = new CodeTypeReference(typeof(object));
                                        var memberprop = new CodeMemberPropertyEx(_document)
                                        {
                                            Name = declarationStack[0].TokenString,
                                            Attributes = MemberAttributes.Public,
                                            Type = propertyType,
                                            LinePragma = CreatePragma(declarationStack[0], _document.FilePath)
                                        };
                                        declarationStack[0].CodeDOMObject = memberprop;
                                        parentHirarchy.Peek().Members.Add(memberprop);

                                    } else {
                                        RegisterError(_document, declarationStack[0], string.Format("Unexpected Token: {0}", declarationStack[0].Token));
                                    }

                                    break;

                                case 2:
                                    // we have two members in the decalration stack
                                    // expected token flows
                                    // keyword - identifier:  static Field, int Field
                                    // identifier - identifier: Car myTypedCarField

                                    // for the time beeing, AHK just supports static Field

                                    if(declarationStack[0].Token == Token.KeyWord
                                        && declarationStack[0].TokenString.Equals(MODIFIER_STATIC, StringComparison.InvariantCultureIgnoreCase)) {

                                        if(declarationStack[1].Token == Token.Identifier) {

                                            // this is an untyped static class field declaration

                                            var propertyType = new CodeTypeReference(typeof(object));
                                            var memberprop = new CodeMemberPropertyEx(_document)
                                            {
                                                Name = declarationStack[1].TokenString,
                                                Attributes = MemberAttributes.Public | MemberAttributes.Static,
                                                Type = propertyType,
                                                LinePragma = CreatePragma(declarationStack[1], _document.FilePath)
                                            };
                                            declarationStack[1].CodeDOMObject = memberprop;
                                            parentHirarchy.Peek().Members.Add(memberprop);
                                            

                                        } else {
                                            RegisterError(_document, declarationStack[0], string.Format("Expected: {0}", Token.Identifier));

                                        }

                                    } else {
                                        RegisterError(_document, declarationStack[0], string.Format("Unexpected '{0}' in Class Body", declarationStack[0].TokenString));
                                    }
                                    break;

                                default:
                                    for(int ci = 0; ci < declarationStack.Count; ci++) {
                                        RegisterError(_document, declarationStack[ci], string.Format("To much declaration Members", declarationStack[0].Token));
                                    }
                                    break;

                            }

                        }

                        #endregion


                        #region Parse Remaining Tokens

                        if(codeLineMap.ContainsKey(i)) {
                            var lineBlock = codeLineMap[i];
                            CodeTypeDeclarationEx thisparent = parentHirarchy.Any() ? parentHirarchy.Peek() : _languageRoot;

                            foreach(var segment in lineBlock.CodeSegments) {

                                cancellationToken.ThrowIfCancellationRequested();

                                if(segment.Token == Token.BlockOpen) {
                                    bcc++;
                                } else if(segment.Token == Token.BlockClosed) {
                                    bcc--;
                                    if(parentHirarchy.Count - 2 == bcc) {
                                        if(parentHirarchy.Any())
                                            parentHirarchy.Pop();
                                    }
                                }
                            }
                            _autoexec.Statements.AddRange(
                                            CollectAllCodeStatements(cancellationToken, thisparent, codeLineMap, i, i));

                        } else
                            continue;

                        #endregion
                    }

                    #endregion

                    AnalyzeAST(cancellationToken);

                    lock(_rootLanguageSnapshotLOCK) {
                        _rootLanguageSnapshot = _languageRoot;
                    }
                });
            } catch(OperationCanceledException) {
                throw;
            }
        }
Exemplo n.º 16
0
        private void _Compile(string relativeSourceFile, bool pass2)
        {
            bool error = false;
            Stream bamlStream = null;
            XamlParser xamlParser = null;

            try
            {
                DefinitionNSPrefix = DEFINITION_PREFIX;
                IsCodeNeeded = false;

                _ccRoot = null;
                _hasLocalEvent = false;
                _codeContexts = new Stack();
                _parserContext = new ParserContext();
                _parserContext.XamlTypeMapper = _typeMapper;
                _hasEmittedEventSetterDeclaration = false;

                bamlStream = new MemoryStream();
                BamlRecordWriter bamlWriter = new BamlRecordWriter(bamlStream, _parserContext, true);
                bamlWriter.DebugBamlStream = XamlDebuggingInformation;

                xamlParser = new ParserExtension(this, _parserContext, bamlWriter, SourceFileInfo.Stream, pass2);

                xamlParser.ParserHooks = ParserHooks;

                try
                {
                    xamlParser.Parse();
                }
                finally
                {
                    _typeMapper.ResetMapper();
                }
            }
            catch (XamlParseException e)
            {
                OnError(e);
                error = true;
            }
            // All exceptions including NullRef & SEH need to be caught by the markupcompiler
            // since it is an app and not a component.
#pragma warning suppress 6500
            catch (Exception e)
            {
                OnError(e);
                error = true;
            }
            finally
            {
                if (!error &&
                    xamlParser.BamlRecordWriter == null &&
                    IsBamlNeeded)
                {
                    if (_pendingLocalFiles == null)
                    {
                        _pendingLocalFiles = new ArrayList(10);
                    }

                    _pendingLocalFiles.Add(relativeSourceFile);
                }

                if (_codeContexts != null)
                {
                    _codeContexts.Clear();
                    _codeContexts = null;
                }


                if (SourceFileInfo != null)
                {
                    SourceFileInfo.CloseStream();
                }

                if (bamlStream != null)
                {
                    bamlStream.Close();
                    bamlStream = null;
                }
            }
        }
Exemplo n.º 17
0
        private void ConvertFile2HTML()
        {
            Application.UseWaitCursor = true;
            toolStripStatusLabel1.Text = "Converting to HTML ... Please Wait";
            this.Refresh();
            string strContent = "";

            string[] strLines;

            stkIDs = new System.Collections.Stack();
            stkIDs.Clear();

            strContent = rtbContent.Text;
            strLines = strContent.Split('\n');
            long i = strLines.Length;

            toolStripProgressBar1.Maximum = Convert.ToInt32(i) + 1;
            toolStripProgressBar1.Minimum = 1;
            toolStripProgressBar1.Value = 1;
            toolStripStatusLabel1.Text = "Creating TOC ... Please Wait";
            this.Refresh();

            //strIDPrefix

            //string strIDPrefix = "images/978-1-933988-54-2-text_img_";

            #region Variable Decl

            long lnPart = 0;
            long lnChapter = 0;
            long lnAppendix = 0;
            long lnPreface = 0;
            long lnSect1 = 0;
            long lnSect2 = 0;
            long lnSect3 = 0;
            long lnSidebar = 0;
            long lnFigure = 0;
            long lnTable = 0;
            long lnOrderedList = 0;
            long lnExample = 0;

            bool blAppendix = false;
            bool blSidebar = false;
            bool blitemizedlist = false;
            bool blorderedlist = false;
            bool blSectionStart = false;
            bool blblockquote = false;
            bool blCopyrightPage = false;
            //bool blTable = false;
            bool blNote = false;
            bool blNoteStart = false;
            bool blProgramListingStart = false;
            bool blExampleStart = false;
            bool blTipStart = false;

            string strChapterNumber = "";
            string strCurrentFileName = "";
            string strTempID = "";
            string strTempID2 = "";
            string strTempID3 = "";
            string strTempID4 = "";
            string strTempID5 = "";
            string strTempID6 = "";
            string strTempID7 = "";
            #endregion

            #region Looping Through Lines

            #region Content

            strContent = rtbContent.Text;
            strLines = strContent.Split('\n');
            i = strLines.Length;
            string[] strContentsFile = new string[i];
            string[] strBrfContentsFile = new string[i];
            //string strCtTitle = "";
            //string strCtID = "";
            int intCtIndex = 0;
            int intBfCtIndex = 0;

            for (int j = 0; j < i; j++)
            {
                if (strLines[j].StartsWith("<chapter ") || strLines[j].StartsWith("<part ") || strLines[j].StartsWith("<preface ") || strLines[j].StartsWith("<sect1 ") || strLines[j].StartsWith("<sect2 ") || strLines[j].StartsWith("<appendix "))
                {
                    if (strLines[j].IndexOf("label=") >= 0)
                    {
                        strChapterNumber = Regex.Replace(strLines[j], "^(.*) label=\"([^\"]+)\"(.*)$", "$2") + " ";
                    }
                    else
                    {
                        strChapterNumber = "";
                    }

                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID7 = Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2");
                    }
                    else
                    {
                        strTempID7 = "";
                    }

                    j++;
                    if (strLines[j].StartsWith("<title>"))
                    {
                        strTempID6 = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "$1");
                    }

                    j++;

                    if (strLines[j].StartsWith("<title>"))
                    {
                        strTempID6 = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "$1");
                    }

                    strContentsFile[intCtIndex] = "<link linkend=\"" + strTempID7 + "\">" + strChapterNumber + strTempID6 + "</link><br/>";
                    intCtIndex++;
                }

                toolStripProgressBar1.Value = j + 1;

            }

            string strXML1 = "<split filename=\"toc.xhtml\">\n" +
                        "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n" +
                        "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n" +
                        "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
                        "<head>\n" +
                        "<title>Contents</title>\n" +
                        "<link href=\"bv_ebook_style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n" +
                        "<link rel=\"stylesheet\" type=\"application/vnd.adobe-page-template+xml\" href=\"page-template.xpgt\"/>\n" +
                        "</head>\n" +
                        "<body>\n" +
                        "<div>\n<a id=\"toc\"></a>\n";

            //rtbContent.Text = strXML1 + string.Join("\n", strContentsFile, 0, intCtIndex) + "\n</div>\n</body>\n</html>\n</split>\n" + rtbContent.Text;

            #endregion

            #region Breif_contents
            toolStripStatusLabel1.Text = "Creating Breif Contents ... Please Wait";
            toolStripProgressBar1.Value = 1;

            for (int j = 0; j < i; j++)
            {
                if (strLines[j].StartsWith("<chapter ")) //strLines[j].StartsWith("<part ") || strLines[j].StartsWith("<preface ") || strLines[j].StartsWith("<appendix ")
                {
                    if (strLines[j].IndexOf("label=") >= 0)
                    {
                        strChapterNumber = Regex.Replace(strLines[j], "^(.*) label=\"([^\"]+)\"(.*)$", "$2") + " " + "<img src=\"" + strIDPrefix + "015.jpg\" width=\"5\" height=\"5\" alt=\"icon014\"/> ";
                    }
                    else
                    {
                        strChapterNumber = "<img src=\"" + strIDPrefix + "015.jpg\" width=\"5\" height=\"5\" alt=\"icon014\"/> ";
                    }

                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID7 = Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2");
                    }
                    else
                    {
                        strTempID7 = "";
                    }

                    j++;
                    if (strLines[j].StartsWith("<title>"))
                    {
                        strTempID6 = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "$1");
                    }

                    j++;

                    if (strLines[j].StartsWith("<title>"))
                    {
                        strTempID6 = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "$1");
                    }

                    strBrfContentsFile[intBfCtIndex] = "<link linkend=\"" + strTempID7 + "\">" + strChapterNumber + strTempID6 + "</link><br/>";
                    intBfCtIndex++;
                }

                if (strLines[j].StartsWith("<part "))
                {
                    if (strLines[j].IndexOf("label=") >= 0)
                    {
                        strChapterNumber = "<b>P<small>ART</small> " + Regex.Replace(strLines[j], "^(.*) label=\"([^\"]+)\"(.*)$", "$2") + " " + "<img src=\"" + strIDPrefix + "015.jpg\" width=\"5\" height=\"5\" alt=\"icon014\"/> ";
                    }
                    else
                    {
                        strChapterNumber = "<img src=\"" + strIDPrefix + "015.jpg\" width=\"5\" height=\"5\" alt=\"icon014\"/> ";
                    }

                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID7 = Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2");
                    }
                    else
                    {
                        strTempID7 = "";
                    }

                    j++;
                    if (strLines[j].StartsWith("<title>"))
                    {
                        strTempID6 = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "$1");
                    }

                    j++;

                    if (strLines[j].StartsWith("<title>"))
                    {
                        strTempID6 = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "$1").ToUpper().Insert(1, "<small>") + "</small></b>";
                    }

                    strBrfContentsFile[intBfCtIndex] = "<br/>\n<link linkend=\"" + strTempID7 + "\">" + strChapterNumber + strTempID6 + "</link><br/><br/>";
                    intBfCtIndex++;
                }

                toolStripProgressBar1.Value = j + 1;

            }

            string strXML2 = "<split filename=\"brief_contents.xhtml\">\n" +
                        "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n" +
                        "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n" +
                        "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
                        "<head>\n" +
                        "<title>Brief Contents</title>\n" +
                        "<link href=\"bv_ebook_style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n" +
                        "<link rel=\"stylesheet\" type=\"application/vnd.adobe-page-template+xml\" href=\"page-template.xpgt\"/>\n" +
                        "</head>\n" +
                        "<body>\n" +
                        "<div>\n<a id=\"brief_contents\"></a>\n<h2 class=\"chaptertitle\">brief contents</h2>\n";

            rtbContent.Text = strXML1 + string.Join("\n", strContentsFile, 0, intCtIndex) + "\n</div>\n</body>\n</html>\n</split>\n" + strXML2 + string.Join("\n", strBrfContentsFile, 0, intBfCtIndex) + "\n</div>\n</body>\n</html>\n</split>\n" + rtbContent.Text;

            #endregion

            this.Refresh();

            strContent = rtbContent.Text;
            strLines = strContent.Split('\n');
            i = strLines.Length;
            toolStripStatusLabel1.Text = "Converting to HTML ... Please Wait";
            toolStripProgressBar1.Maximum = Convert.ToInt32(i) + 1;
            toolStripProgressBar1.Minimum = 1;
            toolStripProgressBar1.Value = 1;
            //Creating IDs
            for (int j = 0; j < i; j++)
            {

                #region Chapters

                if (strLines[j].StartsWith("<chapter ")) // || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                {
                    lnChapter++;
                    blSectionStart = true;
                    strChapterNumber = Regex.Replace(strLines[j], "^(.*) label=\"([^\"]*)\"(.*)$", "$2");

                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID7 = Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2");
                    }
                    else
                    {
                        strTempID7 = "";
                    }

                    strCurrentFileName = "chap" + lnChapter.ToString("00") + ".xhtml";

                    strLines[j] = "<split filename=\"chap" + lnChapter.ToString("00") + ".xhtml\">\n" +
                            "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n" +
                            "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n" +
                            "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
                            "<head>\n" +
                            "<title>Chapter " + strChapterNumber + "</title>\n" +
                            "<link href=\"bv_ebook_style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n" +
                            "<link rel=\"stylesheet\" type=\"application/vnd.adobe-page-template+xml\" href=\"page-template.xpgt\"/>\n" +
                            "</head>\n" +
                            "<body>\n" +
                            "<div>\n" +
                            "<a id=\"" + strTempID7 + "\"></a>";

                    j++;

                    //MessageBox.Show(strLines[j]);

                    strLines[j] = GeneralReplace(strLines[j]);

                    //<a id=\"page_3\"></a><h2 class=\"chaptertitle\">1<br/>SOA essentials</h2>";

                    j++;
                    //MessageBox.Show(strLines[j]);
                    if (strLines[j].StartsWith("<title>")) // || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                    {
                        strLines[j] = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "<h2 class=\"chaptertitle\">" + strChapterNumber + "<br/>$1</h2>");
                        //MessageBox.Show(strLines[j]);
                    }
                    //<title>SOA essentials</title>
                    //<h2 class="chaptertitle">1<br/>SOA essentials</h2>
                    //MessageBox.Show(strLines[j]);

                }

                #endregion

                #region Prefaces

                if (strLines[j].StartsWith("<preface ")) // || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                {
                    lnPreface++;
                    blSectionStart = true;
                    strChapterNumber = Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2");

                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID7 = Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2");
                    }
                    else
                    {
                        strTempID7 = "";
                    }

                    strCurrentFileName = "pref" + lnPreface.ToString("00") + ".xhtml";
                    strLines[j] = "<split filename=\"pref" + lnPreface.ToString("00") + ".xhtml\">\n" +
                            "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n" +
                            "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n" +
                            "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
                            "<head>";

                    j = j + 2;

                    if (strLines[j].StartsWith("<title>")) // || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                    {
                        strLines[j - 2] = strLines[j - 2] + strLines[j] + "\n<link href=\"bv_ebook_style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n" +
                            "<link rel=\"stylesheet\" type=\"application/vnd.adobe-page-template+xml\" href=\"page-template.xpgt\"/>\n" +
                            "</head>\n" +
                            "<body>\n" +
                            "<div>\n" +
                            "<a id=\"" + strTempID7 + "\"></a>";
                        //MessageBox.Show(strLines[j]);
                        if (strLines[j].IndexOf("copyright", StringComparison.InvariantCultureIgnoreCase) > 0)
                        {
                            blCopyrightPage = true;
                        }

                    }
                    strLines[j] = "";
                    j = j - 1;

                    //MessageBox.Show(strLines[j]);

                    strLines[j - 1] = strLines[j - 1] + GeneralReplace(strLines[j]);
                    strLines[j] = "";

                    //<a id=\"page_3\"></a><h2 class=\"chaptertitle\">1<br/>SOA essentials</h2>";

                    j = j + 2;
                    //MessageBox.Show(strLines[j]);

                    //<title>SOA essentials</title>
                    //<h2 class="chaptertitle">1<br/>SOA essentials</h2>
                    //MessageBox.Show(strLines[j]);

                }

                #endregion

                #region Closing Chapter, Part and Preface etc..

                if (strLines[j].StartsWith("</chapter>") || strLines[j].StartsWith("</partintro>") || strLines[j].StartsWith("</preface>") || strLines[j].StartsWith("</appendix>"))
                {
                    blCopyrightPage = false;
                    strLines[j] = "</div>\n</body>\n</html>\n</split>";

                    if (strLines[j].StartsWith("</appendix>"))
                    {
                        blAppendix = false;
                    }

                }

                if (strLines[j].StartsWith("<partintro>"))
                {
                    strLines[j] = "";
                }

                #endregion

                #region Part

                if (strLines[j].StartsWith("<part ")) // || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                {
                    lnPart++;
                    blSectionStart = true;
                    //MessageBox.Show(strLines[j]);
                    strChapterNumber = Regex.Replace(strLines[j], "^(.*) label=\"([^\"]*)\"(.*)$", "$2");

                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID7 = Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2");
                    }
                    else
                    {
                        strTempID7 = "";
                    }

                    //MessageBox.Show(strChapterNumber);
                    strCurrentFileName = "part" + lnPart.ToString("00") + ".xhtml";
                    strLines[j] = "<split filename=\"part" + lnPart.ToString("00") + ".xhtml\">\n" +
                            "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n" +
                            "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n" +
                            "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
                            "<head>\n" +
                            "<title>Part " + strChapterNumber + "</title>\n" +
                            "<link href=\"bv_ebook_style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n" +
                            "<link rel=\"stylesheet\" type=\"application/vnd.adobe-page-template+xml\" href=\"page-template.xpgt\"/>\n" +
                            "</head>\n" +
                            "<body>\n" +
                            "<div>\n" +
                            "<a id=\"" + strTempID7 + "\"></a>";

                    //MessageBox.Show(strLines[j]);
                    j++;

                    //MessageBox.Show(strLines[j]);

                    strLines[j] = GeneralReplace(strLines[j]);

                    //<a id=\"page_3\"></a><h2 class=\"chaptertitle\">1<br/>SOA essentials</h2>";
                    //MessageBox.Show(strLines[j]);
                    j++;
                    //MessageBox.Show(strLines[j]);
                    if (strLines[j].StartsWith("<title>")) // || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                    {
                        strLines[j] = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "<h2 class=\"chaptertitle\">Part " + strChapterNumber + "<br/>$1</h2>");
                        //MessageBox.Show(strLines[j]);
                    }
                    //<title>SOA essentials</title>
                    //<h2 class="chaptertitle">1<br/>SOA essentials</h2>
                    //MessageBox.Show(strLines[j]);

                }
                #endregion

                #region Appendix

                if (strLines[j].StartsWith("<appendix "))
                {
                    lnAppendix++;
                    blAppendix = true;
                    blSectionStart = true;
                    if (strLines[j].IndexOf(" label=") > 0)
                    {
                        strChapterNumber = Regex.Replace(strLines[j], "^(.*) label=\"([^\"]*)\"(.*)$", "$2");
                    }
                    else
                    {
                        strChapterNumber = "";
                    }

                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID7 = Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2");
                    }
                    else
                    {
                        strTempID7 = "";
                    }

                    strCurrentFileName = "appe" + lnAppendix.ToString("00") + ".xhtml";
                    strLines[j] = "<split filename=\"appe" + lnAppendix.ToString("00") + ".xhtml\">\n" +
                            "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n" +
                            "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n" +
                            "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
                            "<head>";

                    j = j + 2;

                    if (strLines[j].StartsWith("<title>")) // || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                    {
                        strLines[j - 2] = strLines[j - 2] + strLines[j] + "\n<link href=\"bv_ebook_style.css\" rel=\"stylesheet\" type=\"text/css\"/>\n" +
                            "<link rel=\"stylesheet\" type=\"application/vnd.adobe-page-template+xml\" href=\"page-template.xpgt\"/>\n" +
                            "</head>\n" +
                            "<body>\n" +
                            "<div>\n" +
                            "<a id=\"" + strTempID7 + "\"></a>";

                    }
                    //strLines[j] = "";
                    j = j - 1;

                    strLines[j] = strLines[j] + GeneralReplace(strLines[j]);
                    //strLines[j] = "";
                    j++;
                    if (strLines[j].StartsWith("<title>")) // || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                    {
                        strLines[j] = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "<h2 class=\"chaptertitle\">" + strChapterNumber + "<br/>$1</h2>");
                        //MessageBox.Show(strLines[j]);
                    }
                    else
                    {
                        strLines[j] = "";
                    }

                    j++;
                    //j = j + 2;

                }

                #endregion

                #region Sect1

                if (strLines[j].StartsWith("<sect1 "))
                {
                    lnSect1++;
                    blSectionStart = true;
                    //MessageBox.Show(strLines[j]);
                    if (strLines[j].IndexOf(" label=") > 0)
                    {
                        strChapterNumber = Regex.Replace(strLines[j], "^(.*) label=\"([^\"]*)\"(.*)$", "$2") + "&#x00A0;&#x00A0;&#x00A0; ";
                    }
                    else
                    {
                        strChapterNumber = "";
                    }

                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID = " id=\"" + Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2") + "\"";
                    }
                    else
                    {
                        strTempID = "";
                    }

                    //MessageBox.Show(strChapterNumber);

                    strLines[j] = ""; //"<a id=\"chapter_" + lnChapter.ToString() + "\"></a>";

                    j++;

                    strLines[j] = GeneralReplace(strLines[j]);
                    //MessageBox.Show(strLines[j]);

                    j++;
                    //MessageBox.Show(strLines[j]);
                    if (strLines[j].StartsWith("<title>")) // || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                    {
                        strLines[j] = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "<p class=\"subhead\"" + strTempID + ">" + strChapterNumber + "$1</p>");
                        //MessageBox.Show(strLines[j]);
                    }

                }
                #endregion

                #region Sect2

                if (strLines[j].StartsWith("<sect2 ")) // || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                {
                    lnSect2++;
                    blSectionStart = true;
                    //MessageBox.Show(strLines[j]);
                    if (strLines[j].IndexOf(" label=") > 0)
                    {
                        strChapterNumber = Regex.Replace(strLines[j], "^(.*) label=\"([^\"]*)\"(.*)$", "$2") + "&#x00A0;&#x00A0;&#x00A0; ";
                    }
                    else
                    {
                        strChapterNumber = "";
                    }
                    //MessageBox.Show(strChapterNumber);
                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID = " id=\"" + Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2") + "\"";
                    }
                    else
                    {
                        strTempID = "";
                    }

                    strLines[j] = ""; //"<a id=\"chapter_" + lnChapter.ToString() + "\"></a>";

                    j++;

                    strLines[j] = GeneralReplace(strLines[j]);
                    //MessageBox.Show(strLines[j]);

                    j++;
                    //MessageBox.Show(strLines[j]);
                    if (strLines[j].StartsWith("<title>")) // || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                    {
                        strLines[j] = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "<p class=\"subhead1\"" + strTempID + ">" + strChapterNumber + "$1</p>");
                        //MessageBox.Show(strLines[j]);
                    }

                }

                #endregion

                #region Sect3

                if (strLines[j].StartsWith("<sect3 ")) // || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                {
                    lnSect3++;
                    blSectionStart = true;
                    //MessageBox.Show(strLines[j]);
                    if (strLines[j].IndexOf(" label=") > 0)
                    {
                        strChapterNumber = Regex.Replace(strLines[j], "^(.*) label=\"([^\"]*)\"(.*)$", "$2") + "&#x00A0;&#x00A0;&#x00A0; ";
                    }
                    else
                    {
                        strChapterNumber = "";
                    }
                    //MessageBox.Show(strChapterNumber);
                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID = " id=\"" + Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2") + "\"";
                    }
                    else
                    {
                        strTempID = "";
                    }

                    strLines[j] = ""; //"<a id=\"chapter_" + lnChapter.ToString() + "\"></a>";

                    j++;

                    strLines[j] = GeneralReplace(strLines[j]);
                    //MessageBox.Show(strLines[j]);

                    j++;
                    //MessageBox.Show(strLines[j]);
                    if (strLines[j].StartsWith("<title>")) // || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                    {
                        strLines[j] = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "<p class=\"subhead1\"" + strTempID + ">" + strChapterNumber + "$1</p>");
                        //MessageBox.Show(strLines[j]);
                    }

                }

                #endregion

                #region Sidebar

                if (strLines[j].StartsWith("<sidebar "))
                {
                    lnSidebar++;
                    blSidebar = true;
                    strLines[j] = "";
                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID = " id=\"" + Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2") + "\"";
                    }
                    else
                    {
                        strTempID = "";
                    }
                    j++;

                    if (strLines[j].StartsWith("<title>"))
                    {
                        strLines[j] = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "<p class=\"box-title\"" + strTempID + ">$1</p>");

                    }

                }

                if (strLines[j].StartsWith("</sidebar>"))
                {
                    strLines[j] = "";
                    blSidebar = false;
                    blSectionStart = true;
                }

                #endregion

                #region Note

                if (strLines[j].StartsWith("<note>"))
                {
                    strLines[j] = "";
                    blNote = true;
                    blNoteStart = true;
                }

                if (strLines[j].StartsWith("</note>"))
                {
                    strLines[j] = "";
                    blNote = false;
                    blSectionStart = true;
                }

                #endregion

                #region Programlisting

                if (strLines[j].StartsWith("<programlisting>"))
                {
                    blProgramListingStart = true;
                    strLines[j] = strLines[j].Replace("<programlisting>", "<p class=\"script\"><code>");
                    if (strLines[j].EndsWith(">") == false)
                    {
                        strLines[j] = strLines[j] + "<br/>";
                    }

                }

                //<programlisting>
                if (strLines[j].EndsWith("</programlisting>"))
                {
                    blProgramListingStart = false;
                    strLines[j] = strLines[j].Replace("</programlisting>", "</code></p>");
                    blSectionStart = true;
                }

                if (strLines[j].StartsWith("<") == false)
                {
                    if (blProgramListingStart == true)
                    {
                        strLines[j] = strLines[j] + "<br/>";

                        if (strLines[j].StartsWith(" ") == true)
                        {
                            // MessageBox.Show("[" + strLines[j].ToString() + "]");
                            strLines[j] = Regex.Replace(strLines[j], "([ ][ ])", "&#x00A0;&#x00A0;");
                            strLines[j] = Regex.Replace(strLines[j], "(&#x00A0;[ ])", "&#x00A0;&#x00A0;");
                            strLines[j] = Regex.Replace(strLines[j], "^([ ])(.*)$", "&#x00A0;$2");
                            // MessageBox.Show("[" + strLines[j].ToString() + "]");
                        }
                    }
                }

                #endregion

                #region Para

                if (strLines[j].StartsWith("<para>"))
                {
                    //Table
                    strLines[j] = Regex.Replace(strLines[j], "^<para>(.*)</para></entry>$", "<p class=\"body-text\">$1</p></td>");

                    if (strLines[j].IndexOf("<emphasis role=\"strong\">") > 0)
                    {

                        strLines[j] = Regex.Replace(strLines[j], "^<para>(.*)<emphasis role=\"strong\">(.*)</emphasis></para>$", "<p class=\"subhead2\">$1$2</p>");
                    }

                    if (blSidebar == true)
                    {
                        strLines[j] = Regex.Replace(strLines[j], "^<para>(.*)$", "<p class=\"box-para\">$1");
                    }
                    else
                    {
                        if (blblockquote == true)
                        {
                            strLines[j] = Regex.Replace(strLines[j], "^<para>(.*)$", "<p class=\"blockquote\">$1");
                        }
                        else
                        {

                            if (blNote == true)
                            {
                                if (blNoteStart == true)
                                {
                                    strLines[j] = Regex.Replace(strLines[j], "^<para>(.*)$", "<p class=\"hanging-note\"><small><b>NOTE</b></small> $1");
                                    blNoteStart = false;
                                }
                                else
                                {
                                    strLines[j] = Regex.Replace(strLines[j], "^<para>(.*)$", "<p class=\"hanging-note\">$1");
                                }

                            }
                            else
                            {

                                if (blCopyrightPage == true)
                                {

                                    strLines[j] = Regex.Replace(strLines[j], "^<para>(.*)$", "<p class=\"copyright\">$1");

                                }
                                else
                                {
                                    if (blTipStart == true)
                                    {

                                        strLines[j] = Regex.Replace(strLines[j], "^<para>(.*)$", "<p class=\"hanging-tip\"><small><b>TIP</b></small>&#x00A0;&#x00A0;&#x00A0;&#x00A0;&#x00A0;&#x00A0;$1");

                                    }
                                    else
                                    {

                                        if (blAppendix == true)
                                        {
                                            strLines[j] = Regex.Replace(strLines[j], "^<para>(.*)$", "<p class=\"hanging-indent\">$1");
                                        }
                                        else
                                        {
                                            if (blSectionStart == true)
                                            {

                                                strLines[j] = Regex.Replace(strLines[j], "^<para>(.*)$", "<p class=\"body-text\">$1");
                                            }
                                            else
                                            {

                                                strLines[j] = Regex.Replace(strLines[j], "^<para>(.*)$", "<p class=\"indent\">$1");

                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    blSectionStart = false;
                }

                #endregion

                #region Itemizedlist

                if (strLines[j].StartsWith("<itemizedlist mark=\"squf\">"))
                {
                    //strLines[j] = "";
                    strLines[j] = "<ul>";
                    blitemizedlist = true;
                }

                if (strLines[j].StartsWith("</itemizedlist>"))
                {
                    //strLines[j] = "";
                    strLines[j] = "</ul>";
                    blitemizedlist = false;
                    blSectionStart = true;
                }
                #endregion

                #region Orderedlist

                if (strLines[j].StartsWith("<orderedlist numeration=\"arabic\">"))
                {
                    //strLines[j] = "";
                    strLines[j] = "<ol>";
                    lnOrderedList = 0;
                    blorderedlist = true;
                }

                if (strLines[j].StartsWith("</orderedlist>"))
                {
                    //strLines[j] = "";
                    strLines[j] = "</ol>";
                    lnOrderedList = 0;
                    blorderedlist = false;
                    blSectionStart = true;
                }
                #endregion

                #region Blockquote

                if (strLines[j].StartsWith("<blockquote>"))
                {
                    strLines[j] = "";
                    blblockquote = true;
                }

                if (strLines[j].IndexOf("</blockquote>") > 0)
                {
                    strLines[j] = strLines[j].Replace("</blockquote>", "");
                    blblockquote = false;
                    blSectionStart = true;

                }

                if (strLines[j].StartsWith("</blockquote>"))
                {
                    strLines[j] = "";
                    blblockquote = false;
                    blSectionStart = true;
                }

                #endregion

                #region Closing Sect, Figure
                //</example>

                if (strLines[j].StartsWith("</sect") || strLines[j].StartsWith("</figure>"))
                {
                    strLines[j] = "";
                    blSectionStart = true;
                }

                #endregion

                #region Closing example
                //</example>

                if (strLines[j].StartsWith("</example>"))
                {
                    strLines[j] = "";
                    blExampleStart = false;
                    blSectionStart = true;
                }

                #endregion

                #region ListItem

                if (strLines[j].StartsWith("<listitem><para>"))
                {

                    if (blitemizedlist == true)
                    {
                        //Old
                        //strLines[j] = Regex.Replace(strLines[j], "^<listitem><para>(.*)</para></listitem>$", "<p class=\"hanging-list\"><img src=\"" + strIDPrefix + "015.jpg\" width=\"5\" height=\"5\" alt=\"icon014\"/> $1</p>");
                        strLines[j] = Regex.Replace(strLines[j], "^<listitem><para>(.*)</para></listitem>$", "<li><p>$1</p></li>");

                    }
                    else
                    {
                        if (blorderedlist == true)
                        {
                            lnOrderedList++;
                            //Old
                            //strLines[j] = Regex.Replace(strLines[j], "^<listitem><para>(.*)</para></listitem>$", "<p class=\"hanging-numberlist\">" + lnOrderedList.ToString() + " $1</p>");
                            strLines[j] = Regex.Replace(strLines[j], "^<listitem><para>(.*)</para></listitem>$", "<li><p>$1</p></li>");

                        }
                    }

                }

                #endregion

                #region Figure

                if (strLines[j].StartsWith("<figure "))
                {
                    lnFigure++;
                    if (strLines[j].IndexOf(" label=") > 0)
                    {
                        strChapterNumber = "Figure " + Regex.Replace(strLines[j], "^(.*) label=\"([^\"]*)\"(.*)$", "$2") + "&#x00A0;&#x00A0;&#x00A0; ";
                    }
                    else
                    {
                        strChapterNumber = "";
                    }

                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID = Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2");
                    }
                    else
                    {
                        strTempID = "";
                    }

                    strLines[j] = "";

                    j++;
                    strTempID2 = "";
                    if (strLines[j].StartsWith("<title>"))
                    {
                        strTempID2 = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "<p class=\"figure-caption\"><b>" + strChapterNumber + "$1</b></p>");
                        strLines[j] = "";
                    }

                    j++;

                    if (strLines[j].StartsWith("<graphic"))
                    {
                        //File Name
                        strTempID3 = Regex.Replace(strLines[j], "^(.*) fileref=\"([^\"]*)\"(.*)$", "$2");
                        //Width
                        strTempID4 = Regex.Replace(strLines[j], "^(.*) width=\"([^\"]*)\"(.*)$", "$2");
                        //height
                        strTempID5 = Regex.Replace(strLines[j], "^(.*) depth=\"([^\"]*)\"(.*)$", "$2");

                        //strLines[j] = "<p class=\"figure-image\" id=\"" + strTempID + "\"><img src=\"" + strIDPrefix + strTempID3 + ".jpg\" width=\"" + strTempID4 + "\" height=\"" + strTempID5 + "\" alt=\"fig" + lnFigure.ToString("000") + "\"/></p>\n" + strTempID2;
                        strLines[j] = "<p class=\"figure-image\" id=\"" + strTempID + "\"><img src=\"" + strTempID3 + "\" width=\"" + strTempID4 + "\" height=\"" + strTempID5 + "\" alt=\"" + strTempID3 + "\"/></p>\n" + strTempID2;

                    }

                }
                #endregion

                #region Example

                if (strLines[j].StartsWith("<example "))
                {
                    lnExample++;
                    blExampleStart = true;
                    if (strLines[j].IndexOf(" label=") > 0 && strLines[j].IndexOf(" role=") > 0)
                    {
                        strTempID6 = Regex.Replace(strLines[j], "^(.*) role=\"([^\"]*)\"(.*)$", "$2");
                        strChapterNumber = strTempID6 + " " + Regex.Replace(strLines[j], "^(.*) label=\"([^\"]*)\"(.*)$", "$2") + "&#x00A0;&#x00A0;&#x00A0; ";
                    }
                    else
                    {
                        strChapterNumber = "";
                    }

                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID = " id=\"" + Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2") + "\"";
                    }
                    else
                    {
                        strTempID = "";
                    }

                    strLines[j] = "";

                    j++;
                    strTempID2 = "";
                    if (strLines[j].StartsWith("<title>"))
                    {
                        strLines[j] = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "<p class=\"listing-script\"" + strTempID + "><b>" + strChapterNumber + "$1</b></p>");
                        //strLines[j] = "";
                    }

                    j++;

                }

                if (blExampleStart == true)
                {
                    if (strLines[j].StartsWith("<programlisting") == false && strLines[j].StartsWith("<") == true)
                    {
                        //strLines[j] = "<p class=\"script\">" + strLines[j] + "</p>";

                    }
                    else
                    {
                        strLines[j] = strLines[j].Replace("<programlisting>", "<p class=\"script\"><code>");
                        blProgramListingStart = true;
                    }
                }

                #endregion

                #region Tip

                if (strLines[j].StartsWith("<tip>"))
                {
                    blTipStart = true;
                    strLines[j] = "";

                }

                if (strLines[j].StartsWith("</tip>"))
                {
                    blTipStart = false;
                    strLines[j] = "";

                }

                #endregion

                #region Table

                if (strLines[j].StartsWith("<table "))
                {
                    lnTable++;
                    strChapterNumber = "";
                    if (strLines[j].IndexOf(" label=") > 0)
                    {
                        strChapterNumber = "Table " + Regex.Replace(strLines[j], "^(.*) label=\"([^\"]*)\"(.*)$", "$2") + "&#x00A0;&#x00A0;&#x00A0; ";
                    }
                    else
                    {
                        strChapterNumber = "";
                    }

                    if (strLines[j].IndexOf(" id=") > 0)
                    {
                        strTempID = Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$2");
                    }
                    else
                    {
                        strTempID = "";
                    }

                    strLines[j] = "";

                    j++;
                    strTempID2 = "";
                    if (strLines[j].StartsWith("<title>"))
                    {
                        strTempID2 = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "$1");
                        strLines[j] = "<table id=\"" + strTempID + "\" cellpadding=\"2\" cellspacing=\"0\">\n<p class=\"table-caption\"><b>" + strChapterNumber + strTempID2 + "</b></p>";
                    }
                    else
                    {
                        j--;
                        strLines[j] = "<table id=\"" + strTempID + "\" cellpadding=\"2\" cellspacing=\"0\">";

                    }

                }

                if (strLines[j].StartsWith("<row>"))
                {
                    strLines[j] = "<tr>";
                }
                if (strLines[j].StartsWith("</row>"))
                {
                    strLines[j] = "</tr>";
                }

                if (strLines[j].StartsWith("<entry"))
                {
                    strLines[j] = Regex.Replace(strLines[j], "^<entry(.*)><para>(.*)</para></entry>$", "<td$1>$2</td>");
                    strLines[j] = Regex.Replace(strLines[j], "^<entry(.*)><para>(.*)</para>$", "<td$1><p>$2</p>");
                    strLines[j] = Regex.Replace(strLines[j], "^<entry(.*)><para>(.*)$", "<td$1>$2");

                    //MessageBox.Show(strLines[j]);
                }

                if (strLines[j].StartsWith("<tgroup") || strLines[j].StartsWith("<colspec") || strLines[j].StartsWith("<thead>") || strLines[j].StartsWith("</thead>") || strLines[j].StartsWith("<tbody>") || strLines[j].StartsWith("</tbody>") || strLines[j].StartsWith("</tgroup>"))
                {
                    strLines[j] = "";
                    blSectionStart = true;
                }

                #endregion

                #region Remove Index

                if (strLines[j].IndexOf("<indexterm ") > 0 && strLines[j].LastIndexOf("</indexterm>") > 0)
                {
                    //MessageBox.Show(strLines[j] + strLines[j].IndexOf("<indexterm ").ToString());
                    strLines[j] = strLines[j].Remove(strLines[j].IndexOf("<indexterm "), (strLines[j].LastIndexOf("</indexterm>") - strLines[j].IndexOf("<indexterm ") + 12));
                    //MessageBox.Show(strLines[j]);
                }

                #endregion

                #region Some General Replacings
                //</para></entry>

                strLines[j] = strLines[j].Replace("</para></entry>", "</td>");
                strLines[j] = strLines[j].Replace("</programlisting>", "</code></p>");
                strLines[j] = strLines[j].Replace("<programlisting>", "<p class=\"script\"><code>");
                strLines[j] = strLines[j].Replace("</entry>", "</td>");
                strLines[j] = strLines[j].Replace("<p class=\"script\"><br/></p>", "<br/>");
                //Replace all general things
                strLines[j] = strLines[j].Replace("</para>", "</p>");
                //strLines[j] = strLines[j].Replace("<p class=\"script\"><p class=\"script\"><code>",
                strLines[j] = strLines[j].Replace("<listitem><para>", "<li><p>");
                strLines[j] = strLines[j].Replace("</para></listitem>", "</p></li>");
                strLines[j] = strLines[j].Replace("<listitem>", "<li>");
                strLines[j] = strLines[j].Replace("</listitem>", "</li>");
                strLines[j] = strLines[j].Replace("<entry", "<td");
                strLines[j] = strLines[j].Replace("<td align=\"center\" valign=\"bottom\">", "<td>");
                //
                if (strLines[j].IndexOf("<literal>") > 0)
                {
                    //MessageBox.Show(strLines[j]);
                    strLines[j] = Regex.Replace(strLines[j], "<literal>([^<]+)</literal>", "<code>$1</code>", RegexOptions.RightToLeft);
                    //MessageBox.Show(strLines[j]);
                }

                if (strLines[j].IndexOf("<emphasis>") > 0)
                {
                    //MessageBox.Show(strLines[j]);
                    strLines[j] = Regex.Replace(strLines[j], "<emphasis>([^<]+)</emphasis>", "<i>$1</i>", RegexOptions.RightToLeft);
                    //MessageBox.Show(strLines[j]);
                }

                if (strLines[j].IndexOf("<informalfigure>") >= 0)
                {
                    //MessageBox.Show(strLines[j]);
                    //strLines[j] = Regex.Replace(strLines[j], "<informalfigure><graphic fileref=\"figs/([^<> ]+).png\"/></informalfigure>", "<img src=\"images/$1.png\" alt=\"$1\"/>", RegexOptions.RightToLeft);
                    strLines[j] = Regex.Replace(strLines[j], "<informalfigure><graphic fileref=\"([^<> ]+)\"/></informalfigure>", "<img src=\"$1\" alt=\"$1\"/>", RegexOptions.RightToLeft);
                    //MessageBox.Show(strLines[j]);
                }

                if (strLines[j].IndexOf("<informalfigure>") < 0 && strLines[j].IndexOf("<graphic") >= 0)
                {
                    //MessageBox.Show(strLines[j]);
                    //strLines[j] = Regex.Replace(strLines[j], "<graphic fileref=\"figs/([^<> ]+).png\"/>", "<img src=\"" + strIDPrefix + "/$1.png\" alt=\"$1\"/>", RegexOptions.RightToLeft);
                    strLines[j] = Regex.Replace(strLines[j], "<graphic fileref=\"([^<> ]+)\"/>", "<img src=\"$1\" alt=\"$1\"/>", RegexOptions.RightToLeft);
                    //MessageBox.Show(strLines[j]);
                }

                if (strLines[j].IndexOf("<systemitem role=\"url\">") >= 0)
                {
                    //MessageBox.Show(strLines[j]);
                    strLines[j] = Regex.Replace(strLines[j], "<systemitem role=\"url\">([^<>]+)</systemitem>", "<a href=\"$1\">$1</a>", RegexOptions.RightToLeft);
                    //MessageBox.Show(strLines[j]);
                }

                if (strLines[j].IndexOf("<systemitem role=\"httpurl\">") >= 0)
                {
                    //MessageBox.Show(strLines[j]);
                    strLines[j] = Regex.Replace(strLines[j], "<systemitem role=\"httpurl\">([^<>]+)</systemitem>", "<a href=\"http://$1\">$1</a>", RegexOptions.RightToLeft);
                    //MessageBox.Show(strLines[j]);
                }

                #endregion

                toolStripProgressBar1.Value = j + 1;

            }

            #endregion

            this.Refresh();

            rtbContent.Text = string.Join("\n", strLines);
            toolStripProgressBar1.Value = toolStripProgressBar1.Maximum;
            //toolStripStatusLabel1.Text = "Ready";
            Application.UseWaitCursor = false;

            //IDLinking();
            IDLinkingVer2();
        }
Exemplo n.º 18
0
        private void ConvertFootNote()
        {
            Application.UseWaitCursor = true;
            toolStripStatusLabel1.Text = "Converting Footnotes ... Please Wait";
            this.Refresh();
            string strContent = "";

            string[] strLines;

            stkIDs = new System.Collections.Stack();
            stkIDs.Clear();

            strContent = rtbContent.Text;
            strLines = strContent.Split('\n');
            long i = strLines.Length;

            toolStripProgressBar1.Maximum = Convert.ToInt32(i) + 1;
            toolStripProgressBar1.Minimum = 1;
            toolStripProgressBar1.Value = 1;
            this.Refresh();

            //bool blNoteStart = false;
            string strFn = "";
            long lnBibNo = 0;

            MatchCollection mc;

            #region First Loop

            //Creating IDs
            for (int j = 0; j < i; j++)
            {

                if (strLines[j].StartsWith("<note"))
                {

                    //blNoteStart = true;
                    strLines[j] = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                        "<!DOCTYPE noteGroup PUBLIC \"-//OXFORD//DTD OXCHAPML//EN\" \"OxChapML.dtd\">\n" +
                        "<!-- [DTD] OxChapML, v2.5 -->\n" +
                        "<!-- [TCI] Oxford Scholarship Online Text Capture Instructions, v1.2 -->\n" +
                        "<!-- [TCI] OUP Bibliographic reference capture, v1.15 -->\n" +
                        "<noteGroup>";

                }

                if (strLines[j].StartsWith("</note>"))
                {
                    //blNoteStart = false;

                    strLines[j] = "</noteGroup>";
                }

                if (strLines[j].StartsWith("<fn"))
                {

                    strFn = Regex.Replace(strLines[j], "^<fn([0-9]+)>(.*)", "$1");

                    mc = Regex.Matches(strLines[j], "</bibn>", RegexOptions.RightToLeft);
                    int intFirstBibStart = 0;
                    int intFirstBibEnd = 0;
                    string strBIB = "";

                    foreach (Match singleMc in mc)
                    {
                        lnBibNo++;
                        intFirstBibStart = strLines[j].IndexOf("<bibn>");
                        intFirstBibEnd = strLines[j].IndexOf("</bibn>");
                        //MessageBox.Show(strLines[j]);
                        strBIB = strLines[j].Substring(intFirstBibStart, (intFirstBibEnd - intFirstBibStart) + 7);
                        //MessageBox.Show(strBIB);
                        strLines[j] = strLines[j].Remove(intFirstBibStart, (intFirstBibEnd - intFirstBibStart) + 7);
                        //MessageBox.Show(strLines[j]);
                        strLines[j] = strLines[j].Insert(intFirstBibStart, ConvertSingleBibn(strBIB, lnBibNo.ToString()));
                        //MessageBox.Show(strLines[j]);

                    }

                    strLines[j] = Regex.Replace(strLines[j], "^<fn([0-9]+)>(.*)</fn>$", "<note id=\"" + strIDPrefix + "-note-$1\" type=\"footnote\"><p><enumerator><sup>$1</sup></enumerator> $2</p></note>");

                }

                toolStripProgressBar1.Value = toolStripProgressBar1.Value + 1;

            }

            #endregion

            this.Refresh();

            rtbContent.Text = string.Join("\n", strLines);
            toolStripStatusLabel1.Text = "Ready";
            Application.UseWaitCursor = false;
        }
Exemplo n.º 19
0
 private void stateTravers(StateNode tra)
 {
     StateLawNode lawNode=tra.laws.Head;
     Stack lawExists=new Stack();
     while(lawNode!=null)
     {
         LawsNode law=parsHead.findLaw(lawNode.data.lawNum);
         if(law!=null)
         {
             PartsNode part=law.parts[lawNode.data.dotPos];
             if(part!=null)
             {
                 if(!part.item.isTerminal )
                 {
                     if(!lawExists.Contains(part.item.name))
                     {
                         Stack lawNumbers = new Stack();
                         lawNumbers.Clear();
                         law.parts.Parent.Parent.NonTerminals.findLaws(part.item.name,lawNumbers);
                         while(lawNumbers.Count != 0)
                             tra.laws.add(0,(int)lawNumbers.Pop());
                         lawExists.Push(part.item.name);
                     }
                 }
             }
         }
         lawNode=lawNode.next;
     }
 }
Exemplo n.º 20
0
  /**
   * this event runs when someone clicks on online user list
   * need to add code to get file size and rating and
   * CATEGORY
   */
 private void clearStack(Stack<string> st)
 {
     st.Clear();
 }
Exemplo n.º 21
0
        /**
        * Breaks up the given `template` string into a tree of tokens. If the `tags`
        * argument is given here it must be an array with two string values: the
        * opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of
        * course, the default is to use mustaches (i.e. mustache.tags).
        *
        * A token is an array with at least 4 elements. The first element is the
        * mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag
        * did not contain a symbol (i.e. {{myValue}}) this element is "Name". For
        * all text that appears outside a symbol this element is "text".
        *
        * The second element of a token is its "Value". For mustache tags this is
        * whatever else was inside the tag besides the opening symbol. For text tokens
        * this is the text itself.
        *
        * The third and fourth elements of the token are the Start and End indices,
        * respectively, of the token in the original template.
        *
        * Tokens that are the root node of a subtree contain two more elements: 1) an
        * array of tokens in the subtree and 2) the index in the original template at
        * which the closing tag for that section begins.
        */
        private static List<Token> ParseTemplate(string template, Tags tags = null)
        {
            if (!template.Any())
                return new List<Token>();

            var sections = new Stack<Token>(); // Stack to hold section tokens
            var tokens = new List<Token>(); // Buffer to hold the tokens
            var spaces = new Stack<int>(); // Indices of whitespace tokens on the current line
            var hasTag = false; // Is there a {{tag}} on the current line?
            var nonSpace = false; // Is there a non-space char on the current line?

            // Strips all whitespace tokens array for the current line
            // if there was a {{#tag}} on it and otherwise only space.
            Action stripSpace = () =>
            {
                if (hasTag && !nonSpace)
                {
                    while (spaces.Any())
                        tokens.RemoveAt(spaces.Pop());
                }
                else
                {
                    spaces.Clear();
                }

                hasTag = false;
                nonSpace = false;
            };

            // TODO: this `= null` is to avoid "Use of unassigned local variable" C# compiler error.
            Regex openingTagRe = null;
            Regex closingTagRe = null;
            Regex closingCurlyRe = null;
            Action<Tags> compileTags = delegate(Tags tagsToCompile)
            {
                openingTagRe = new Regex(Regex.Escape(tagsToCompile.Opener) + "\\s*");
                closingTagRe = new Regex("\\s*" + Regex.Escape(tagsToCompile.Closer));
                closingCurlyRe = new Regex("\\s*" + Regex.Escape('}' + tagsToCompile.Closer));
            };

            if (tags == null)
                compileTags(MustacheTags);
            else
                compileTags(tags);

            //var Start, Type, Value, chr, token, openSection;
            var scanner = new Scanner(template);
            Token openSection = null;
            while (!scanner.Eos())
            {
                var start = scanner._pos;
                var value = scanner.ScanUntil(openingTagRe);
                var valueLength = value.Length;
                if (valueLength > 0)
                {
                    for (var i = 0; i < valueLength; ++i)
                    {
                        string chr = "" + value[i];

                        if (IsWhitespace(chr))
                        {
                            spaces.Push(tokens.Count);
                        }
                        else
                        {
                            nonSpace = true;
                        }

                        tokens.Add(new Token {Type = "text", Value = chr, Start = start, End = start + 1});
                        start += 1;

                        // Check for whitespace on the current line.
                        if (chr == "\n")
                            stripSpace();
                    }
                }

                // Match the opening tag.
                if (!scanner.Scan(openingTagRe).Any())
                    break;

                hasTag = true;

                // Get the tag Type.
                var scanTag = scanner.Scan(_tagRe);
                string type;
                if (!scanTag.Any())
                    type = "Name";
                else
                    type = scanTag;

                scanner.Scan(_whiteRe);

                // Get the tag Value.
                switch (type)
                {
                    case "=":
                        value = scanner.ScanUntil(_equalsRe);
                        scanner.Scan(_equalsRe);
                        scanner.ScanUntil(closingTagRe);
                        break;
                    case "{":
                        value = scanner.ScanUntil(closingCurlyRe);
                        scanner.Scan(_curlyRe);
                        scanner.ScanUntil(closingTagRe);
                        type = "&";
                        break;
                    default:
                        value = scanner.ScanUntil(closingTagRe);
                        break;
                }

                // Match the closing tag.
                if (!scanner.Scan(closingTagRe).Any())
                    throw new Exception("Unclosed tag at " + scanner._pos);
                var arr = value.Split('|');
                string format = null;
                if (arr.Length == 2)
                {
                    value = arr[0];
                    format = arr[1];
                }

                var token = new Token {Type = type, Value = value, Format = format, Start = start, End = scanner._pos};
                tokens.Add(token);
                switch (type)
                {
                    case "#":
                    case "^":
                        sections.Push(token);
                        break;
                    case "/":
                        // Check section nesting.
                        openSection = sections.Pop();

                        if (openSection == null)
                            throw new Exception("Unopened section \"" + value + "\" at " + start);

                        if (openSection.Value != value)
                            throw new Exception("Unclosed section \"" + openSection.Value + "\" at " + start);
                        break;
                    case "Name":
                    case "{":
                    case "&":
                        nonSpace = true;
                        break;
                    case "=":
                        // Set the tags for the next time around.
                        var newTags = _spaceRe.Split(value, 2);
                        compileTags(new Tags {Opener = newTags[0], Closer = newTags[1]});
                        break;
                }
            }

            // Make sure there are no open sections when we're done.
            if (sections.Any())
            {
                openSection = sections.Pop();
                throw new Exception("Unclosed section \"" + openSection.Value + "\" at " + scanner._pos);
            }

            return NestTokens(SquashTokens(tokens));
        }
Exemplo n.º 22
0
		private TokenList ParseInfix (TokenList partial) {
			TokenList output = new TokenList ();
			Stack stack = new Stack ();
			bool last_was_operand = false;

			int length = partial.Count;
			for (int i = length - 1; i >= 0; i--) {
				Token token = partial[i];
				if (token.Type == TokenType.Word) {
					ExtendList (output, stack);
					output.Add (token);
					stack.Clear ();
				} else if (token.Type == TokenType.Infix) {
					if (stack.Count == 0) {
						stack.Push (token);
					} else {
						Token prev = (Token) stack.Pop ();
						if (Weight (prev) <= Weight (token)) {
							stack.Push (token);
							stack.Push (prev);
						} else {
							output.Add (prev);
							stack.Push (token);
						}
					}
					last_was_operand = false;
				} else {
					if (token.Type == TokenType.PlaceholderGroup) {
						token.Val = ParseInfix ((TokenList) token.Val);
					}

					if (i > 0) {
						Token peek = partial[i - 1];
						if (peek.Type == TokenType.Minus) {
							output.Add (token);
							output.Add (peek);
							last_was_operand = true;
							i--;
							continue;
						}
					}
					
					if (last_was_operand) {
						ExtendList (output, stack);
						stack.Clear ();
					}
					output.Add (token);
					last_was_operand = true;
				}
			}

			ExtendList (output, stack);
			output.Reverse ();
			return output;
		}
Exemplo n.º 23
0
    static void Main()
    {
        System.Collections.Stack OperatorStack = new System.Collections.Stack();
        List <string>            Output        = new List <string>();
        string OutputStr;
        int    loops;
        string Express = "";
        string Letter;

        loops = int.Parse(Console.ReadLine());

        for (int i = 0; i != loops - 1; i++)
        {
            Express = Console.ReadLine();

            foreach (char c in Express)
            {
                Letter = c.ToString();

                switch (Letter)
                {
                case "a":
                case "b":
                case "c":
                case "d":
                case "e":
                case "f":
                case "g":
                case "h":
                case "i":
                case "j":
                case "k":
                case "l":
                case "m":
                case "n":
                case "o":
                case "p":
                case "q":
                case "r":
                case "s":
                case "t":
                case "u":
                case "v":
                case "w":
                case "x":
                case "y":
                case "z":

                    Output.Add(Letter);
                    break;

                case "+":
                case "-":
                case "*":
                case "/":
                case "^":

                    while (OperatorStack.Peek().ToString() == "+" | OperatorStack.Peek().ToString() == "-" | OperatorStack.Peek().ToString() == "+" | OperatorStack.Peek().ToString() == "+")
                    {
                    }


                    OperatorStack.Push(Letter);
                    break;

                case "(":

                    OperatorStack.Push(Letter);
                    break;

                case ")":

                    while (OperatorStack.Peek().ToString() != "(")
                    {
                        Output.Add(OperatorStack.Pop().ToString());
                    }
                    OperatorStack.Pop();
                    break;
                }
            }

            if (OperatorStack.Count != 0)
            {
                while (OperatorStack.Peek() != null)
                {
                    Output.Add(OperatorStack.Pop().ToString());
                }
            }

            OutputStr = string.Join("", Output.ToArray());
            Console.WriteLine(OutputStr);
            Output.Clear();
            OperatorStack.Clear();
        }
    }
Exemplo n.º 24
0
        private void ConvertFileNewID()
        {
            Application.UseWaitCursor = true;
            toolStripStatusLabel1.Text = "Creating IDs... Please Wait";
            this.Refresh();
            string strContent = "";

            string[] strLines;

            stkIDs = new System.Collections.Stack();
            stkIDs.Clear();

            strContent = rtbContent.Text;
            strLines = strContent.Split('\n');
            long i = strLines.Length;

            toolStripProgressBar1.Maximum = Convert.ToInt32(i);
            toolStripProgressBar1.Minimum = 1;
            toolStripProgressBar1.Value = 1;
            this.Refresh();

            string strID = "";

            #region First Loop

            //Creating IDs
            for (int j = 0; j < i; j++)
            {

                if (strLines[j].StartsWith("<preface") || strLines[j].StartsWith("<chapter") || strLines[j].StartsWith("<sect") || strLines[j].StartsWith("<figure") || strLines[j].StartsWith("<table") || strLines[j].StartsWith("<sidebar") || strLines[j].StartsWith("<example") || strLines[j].StartsWith("<appendix") || strLines[j].StartsWith("<part") || strLines[j].StartsWith("<glossary")) // || strLines[j].StartsWith("<preface")
                {
                    //MessageBox.Show(strLines[j]);
                    strLines[j] = Regex.Replace(strLines[j], "^(.*) id=\"([^\"]*)\"(.*)$", "$1$3");
                    //MessageBox.Show(strLines[j]);
                    strLines[j] = strLines[j].Insert(strLines[j].LastIndexOf(">"), " id=\"****\"");
                    //MessageBox.Show(strLines[j]);

                }

                toolStripProgressBar1.Increment(1);
                if (strLines[j].StartsWith("<title>"))
                {
                    strID = CreateID(Regex.Replace(strLines[j], "<title>(.*)</title>", "$1"));

                    if (strLines[j - 1].IndexOf("id=\"*") >= 0)
                    {

                        /*if (strLines[j - 1].StartsWith("<preface"))
                        {
                            strLines[j - 1] = strLines[j - 1].Insert(strLines[j - 1].IndexOf("id=") + 4, "preface").Replace("*", "");
                        }
                        else
                        {
                        */
                        strLines[j - 1] = strLines[j - 1].Insert(strLines[j - 1].IndexOf("id=") + 4, strID).Replace("*", "");
                        //}
                    }
                    else
                    {
                        if (strLines[j - 2].IndexOf("id=\"*") >= 0)
                        {
                            /*
                            if (strLines[j - 2].StartsWith("<preface"))
                            {
                                strLines[j - 2] = strLines[j - 2].Insert(strLines[j - 2].IndexOf("id=") + 4, "preface").Replace("*", "");
                            }
                            else
                            {
                             */
                            strLines[j - 2] = strLines[j - 2].Insert(strLines[j - 2].IndexOf("id=") + 4, strID).Replace("*", "");
                            //}
                        }
                    }

                }

            }

            #endregion

            this.Refresh();

            rtbContent.Text = string.Join("\n", strLines);
            toolStripStatusLabel1.Text = "Ready";
            Application.UseWaitCursor = false;
        }
Exemplo n.º 25
0
        public void UpdatePathfinding(Address playerPosition)
        {
            if (pathPlane == null) return;

            foreach (Cell c in path)
                pathTexture.SetPixel(c.x, c.y, emptyColor);

            if (path.Count > 0 && path.Peek().address.Equals(playerPosition))
                path.Pop();
            else
            {
                try
                {
                    //Debug.Log("done a pathfinding");
                    path = algorithm.GetFastestPath(map.cellsOnMap[playerPosition.x, playerPosition.y], map.cellsOnMap[targetX, targetY]);
                }
                catch (System.Exception)
                {
                    path.Clear();
                }

            }

            foreach (Cell c in path)
                pathTexture.SetPixel(c.x, c.y, pathColor);

            pathTexture.Apply();
            pathPlane.GetComponent<Renderer>().material.SetTexture("_MainTex", pathTexture);

            lastPlayerPosition = playerPosition;
        }
Exemplo n.º 26
0
        private void createOPFAuto(string strPath)
        {
            //fbdSplit.ShowDialog();
            string strSavePath = strPath;
            System.Collections.Stack stkImgs;
            stkImgs = new System.Collections.Stack();
            stkImgs.Clear();
            MatchCollection mc;

            if (strSavePath.Length > 2)
            {

                try
                {

                    Application.UseWaitCursor = true;
                    toolStripStatusLabel1.Text = "Creating .OPF File... Please Wait";
                    this.Refresh();
                    string strContent = "";

                    string[] strLines;

                    strContent = rtbContent.Text;
                    strLines = strContent.Split('\n');
                    long i = strLines.Length;

                    toolStripProgressBar1.Maximum = Convert.ToInt32(i) + 1;
                    toolStripProgressBar1.Minimum = 1;
                    toolStripProgressBar1.Value = 1;
                    this.Refresh();

                    StreamWriter swFiles;
                    string strFileNames = "";
                    string strChapterTitle = "";
                    //bool blSplitStart = false;
                    bool blIdFound = false;
                    bool blSrcFound = false;
                    bool blTitleFound = false;
                    bool blATitleFound = false;
                    string strWrite = "";

                    string strIdFound = "";
                    string strSrcFound = "";
                    string strTitleFound = "";
                    string strATitleFound = "";
                    long lnImgIDCount = 1;

                    swFiles = new StreamWriter(strSavePath + "\\content.opf");

                    swFiles.WriteLine("<?xml version=\"1.0\"?>\n" +
                        "<package version=\"2.0\" xmlns=\"http://www.idpf.org/2007/opf\"\n" +
                        "         unique-identifier=\"isbn\">\n" +
                        " <metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n" +
                        "           xmlns:opf=\"http://www.idpf.org/2007/opf\">\n" +
                        "   <dc:title>***Book Name***</dc:title> \n" +
                        "   <dc:creator>***Author Name***</dc:creator>\n" +
                        "   <dc:language>en-US</dc:language> \n" +
                        "   <dc:rights>***Copyright***</dc:rights>\n" +
                        "   <dc:publisher>***Publisher***</dc:publisher>\n" +
                        "   <dc:identifier id=\"isbn\">****</dc:identifier>\n" +
                        "   <meta name=\"cover\" content=\"cover-image\"/>  \n" +
                        " </metadata>\n" +
                        " <manifest>\n" +
                        "\n" +
                        "<!-- Images -->\n");

                    for (int j = 0; j < i; j++)
                    {

                        mc = Regex.Matches(strLines[j], "<img src=\"([^\"]+)\"");

                        foreach (Match singleMc in mc)
                        {

                            if (stkImgs.Contains(singleMc.Result("$1")) == false)
                            {
                                stkImgs.Push(singleMc.Result("$1"));
                                swFiles.WriteLine("  <item href=\"" + singleMc.Result("$1") + "\" id=\"img_" + lnImgIDCount.ToString() + "\" media-type=\"image/jpeg\"/>");
                                lnImgIDCount++;
                            }

                        }

                        toolStripProgressBar1.Value = j + 1;

                    }

                    swFiles.WriteLine("<!-- NCX -->\n" +
                        "\n" +
                        "<item id=\"ncx\" href=\"toc.ncx\" media-type=\"application/x-dtbncx+xml\"/>\n" +
                        "\n" +
                        " <!-- CSS Style Sheets -->\n" +
                        "\n" +
                        "<item id=\"style_bv\" href=\"bv_ebook_style.css\" media-type=\"text/css\"/>\n" +
                        "<item id=\"style_basic\" href=\"stylesheet.css\" media-type=\"text/css\"/>\n" +
                        "<item id=\"pagetemplate\" href=\"page-template.xpgt\" media-type=\"application/vnd.adobe-page-template+xml\"/>\n" +
                        "<!-- Content Documents -->\n" +
                        "\n");

                    string strIDRef = " <spine toc=\"ncx\">";

                    for (int j = 0; j < i; j++)
                    {

                        if (strLines[j].StartsWith("<split"))
                        {
                            strFileNames = Regex.Replace(strLines[j], "^<split filename=\"([^<>]+)\">$", "$1");
                            //blSplitStart = true;
                            //swFiles.WriteLine("      <content src=\"" + strFileNames + "\"/>");
                            blSrcFound = true;
                            strSrcFound = strFileNames;

                        }

                        if (strLines[j].StartsWith("<div>") == true)
                        {
                            j++;
                            if (strLines[j].StartsWith("<a id=") == true)
                            {
                                strChapterTitle = Regex.Replace(strLines[j], "^<a id=\"([^<]*)\"></a>(.*)$", "$1");
                                //swFiles.WriteLine("    <navPoint class=\"chapter\" id=\"" + strChapterTitle + "\" playOrder=\"1\">");
                                blIdFound = true;
                                strIdFound = strChapterTitle;

                            }

                        }

                        if (strLines[j].StartsWith("</split"))
                        {
                            strWrite = "";
                            if (blIdFound == true)
                            {

                                if (blSrcFound == true)
                                {
                                    strWrite = "  <item id=\"" + strIdFound + "\" href=\"" + strSrcFound + "\" media-type=\"application/xhtml+xml\"/>";
                                    swFiles.WriteLine(strWrite);

                                    strIDRef = strIDRef + "\n" + "  <itemref idref=\"" + strIdFound + "\" linear=\"yes\" />";

                                }

                            }

                            blIdFound = false;
                            blSrcFound = false;
                            blTitleFound = false;
                            blATitleFound = false;

                            strIdFound = "";
                            strSrcFound = "";
                            strTitleFound = "";
                            strATitleFound = "";

                            //blSplitStart = false;
                        }

                        toolStripProgressBar1.Value = j + 1;

                    }

                    swFiles.WriteLine("  </manifest>\n");

                    swFiles.WriteLine(strIDRef);

                    swFiles.WriteLine("<guide>");

                    for (int j = 0; j < i; j++)
                    {

                        if (strLines[j].StartsWith("<split"))
                        {
                            strFileNames = Regex.Replace(strLines[j], "^<split filename=\"([^<>]+)\">$", "$1");
                            //blSplitStart = true;
                            //swFiles.WriteLine("      <content src=\"" + strFileNames + "\"/>");
                            blSrcFound = true;
                            strSrcFound = strFileNames;

                        }

                        if (strLines[j].StartsWith("<head>") == true)
                        {
                            j++;
                            if (strLines[j].StartsWith("<title>") == true)
                            {
                                strChapterTitle = Regex.Replace(strLines[j], "^<title>(.*)</title>$", "$1");
                                //swFiles.WriteLine("        <text>" + strChapterTitle + "</text>");
                                blTitleFound = true;
                                strTitleFound = strChapterTitle;
                            }

                        }

                        if (strLines[j].StartsWith("<h2 class=\"chaptertitle\">") == true)
                        {

                            strChapterTitle = Regex.Replace(strLines[j], "^<h2 class=\"chaptertitle\">(.*)</h2>$", "$1");
                            strChapterTitle = RemoveTag(strChapterTitle);
                            blATitleFound = true;
                            strATitleFound = strChapterTitle;

                        }

                        if (strLines[j].StartsWith("<div>") == true)
                        {
                            j++;
                            if (strLines[j].StartsWith("<a id=") == true)
                            {
                                strChapterTitle = Regex.Replace(strLines[j], "^<a id=\"([^<]*)\"></a>(.*)$", "$1");
                                //swFiles.WriteLine("    <navPoint class=\"chapter\" id=\"" + strChapterTitle + "\" playOrder=\"1\">");
                                blIdFound = true;
                                strIdFound = strChapterTitle;

                            }

                        }

                        if (strLines[j].StartsWith("</split"))
                        {
                            strWrite = "";
                            if (blIdFound == true)
                            {
                                strWrite = strIdFound;
                                if (blATitleFound == true)
                                {
                                    //strATitleFound
                                }
                                else
                                {
                                    if (blTitleFound == true)
                                    {
                                        strATitleFound = strTitleFound;
                                    }

                                }

                                strWrite = "<reference type=\"text\"\n" +
                                "		   title=\"" + strATitleFound + "\"\n" +
                                "          href=\"" + strSrcFound + "\"/>";

                                swFiles.WriteLine(strWrite);
                            }

                            blIdFound = false;
                            blSrcFound = false;
                            blTitleFound = false;
                            blATitleFound = false;

                            strIdFound = "";
                            strSrcFound = "";
                            strTitleFound = "";
                            strATitleFound = "";

                            //blSplitStart = false;
                        }

                        toolStripProgressBar1.Value = j + 1;

                    }

                    swFiles.WriteLine("</guide>\n</package>");

                    swFiles.Flush();
                    swFiles.Close();

                    this.Refresh();

                    rtbContent.Text = string.Join("\n", strLines);
                    toolStripProgressBar1.Value = toolStripProgressBar1.Maximum;

                    toolStripStatusLabel1.Text = "Ready";
                    Application.UseWaitCursor = false;
                }
                catch
                {
                    MessageBox.Show("Unexpected Error", "ERR", MessageBoxButtons.OK);

                }
            }
        }
Exemplo n.º 27
0
 private void Cleanup()
 {
     line = 1;
     column = 0;
     handler = null;
     reader = null;
     #if CF_1_0
     elementNames = new Stack ();
     xmlSpaces = new Stack ();
     #else
     elementNames.Clear();
     xmlSpaces.Clear();
     #endif
     attributes.Clear();
     buffer.Length = 0;
     xmlSpace = null;
     isWhitespace = false;
 }
Exemplo n.º 28
0
        /// <summary>
        /// Measure one line of tooltip text calcuating formatting
        /// </summary>
        /// <param name="g"></param>
        /// <param name="txt"></param>
        /// <returns></returns>
        protected virtual Size MeasureToolTipString( Graphics g, string txt )
        {
            Size sizeText;
              int maxHeight = 0;
              int totalWidht = 0;

              string  tempString = txt;
              Stack   stack = new Stack();

              ToolTipStringFormatter frmtString = new ToolTipStringFormatter( this );

              stack.Push( frmtString.Clone() );

              do
              {
            Match   mt = m_regex.Match( tempString );

            if( mt.Success == true )
            {
              string pretext  = mt.Groups[1].Value;
              string formatId = mt.Groups[2].Value;
              string text     = mt.Groups[3].Value;

              tempString = tempString.Remove( 0, mt.Groups[0].Value.Length );
              frmtString.CopyFrom( (ToolTipStringFormatter)stack.Peek() );

              sizeText = MeasureStringByFormat( g, frmtString, pretext );
              maxHeight = Math.Max( maxHeight, sizeText.Height );
              totalWidht += sizeText.Width;

              DetectFormatting( ref frmtString, formatId );

              if( IsStringWithFormat( text ) )
              {
            stack.Push( frmtString.Clone() );
            tempString = text + "</stack>" + tempString;
            continue;
              }
              else
              {
            int pos = text.IndexOf( "</stack>" );
            int left = pos + "</stack>".Length;

            if( pos != -1 )
            {
              tempString = text.Substring( left, text.Length - left ) + tempString;
              text = text.Substring( 0, pos );
            }

            sizeText = MeasureStringByFormat( g, frmtString, text );
            maxHeight = Math.Max( maxHeight, sizeText.Height );
            totalWidht += sizeText.Width;

            if( pos != -1 ) stack.Pop();
              }
            }
            else
            {
              int pos = 0;

              while( -1 != ( pos = tempString.IndexOf( "</stack>" ) ) )
              {
            int left = pos + "</stack>".Length;
            string text = tempString.Substring( 0, pos );

            tempString = tempString.Substring( left, tempString.Length - left );

            sizeText = MeasureStringByFormat( g, (ToolTipStringFormatter)stack.Peek(), text );
            maxHeight = Math.Max( maxHeight, sizeText.Height );
            totalWidht += sizeText.Width;

            stack.Pop();
              }

              sizeText = MeasureStringByFormat( g, (ToolTipStringFormatter)stack.Peek(), tempString );
              maxHeight = Math.Max( maxHeight, sizeText.Height );
              totalWidht += sizeText.Width;
              tempString = "";
            }

            if( tempString.Length == 0 ) break;
              }
              while( true );

              stack.Clear();

              return new Size( totalWidht, maxHeight );
        }
Exemplo n.º 29
0
        private void stateTravers(int stateNumber)
        {
            StateNode node=this.first;
            Stack lawExist=new Stack();
            while(node!=null)
            {
                if(node.StateNumber == stateNumber)
                {
                    StateLawNode lawNode=node.laws.Head;
                    while(lawNode!=null)
                    {
                        LawsNode law=parsHead.findLaw(lawNode.data.lawNum);
                        if(law!=null)
                        {
                            PartsNode part=law.parts[lawNode.data.dotPos];
                            if(part!=null)
                            {
                                if(!part.item.isTerminal)
                                {
                                    Stack lawNumbers = new Stack();
                                    lawNumbers.Clear();
                                    law.parts.Parent.Parent.NonTerminals.findLaws(part.item.name,lawNumbers);
                                    while(lawNumbers.Count != 0)
                                    {

                                        this.addStateLaw(node.StateNumber,0,(int)lawNumbers.Pop());
                                    }
                                }
                            }
                        }
                        lawNode=lawNode.next;
                    }
                    return;
                }
                node=node.next;
            }
        }
Exemplo n.º 30
0
	private void ClearActionStack (Stack stack)
	{
		foreach (EditAction action in stack)
			action.Destroy ();
		
		stack.Clear ();
	}
Exemplo n.º 31
0
        public List<StageCell> FindShortestPath(StageCell fromCell, StageCell toCell)
        {
            // Reset all cell's traversal point
            for (int c=0; c<mNumberOfColumns; c++) {
                for (int r=0; r<mNumberOfRows; r++) {
                    mCells[c, r].TraversalPoint = int.MaxValue;
                }
            }

            Stack<StageCell> cellStack = new Stack<StageCell>();
            fromCell.TraversalPoint = 0;
            cellStack.Push(fromCell);

            // 1. Fill Traversal point until toCell found!
            while (cellStack.Count > 0) {
                StageCell cell = cellStack.Pop();

                int v = cell.TraversalPoint + 1;

                if (cell.North != null) {
                    if (cell.North.TraversalPoint > v) {
                        cell.North.TraversalPoint = v;
                        if (cell.North != toCell) {
                            cellStack.Push(cell.North);
                        }
                    }
                }

                if (cell.East != null) {
                    if (cell.East.TraversalPoint > v) {
                        cell.East.TraversalPoint = v;
                        if (cell.East != toCell) {
                            cellStack.Push(cell.East);
                        }
                    }
                }

                if (cell.South != null) {
                    if (cell.South.TraversalPoint > v) {
                        cell.South.TraversalPoint = v;
                        if (cell.South != toCell) {
                            cellStack.Push(cell.South);
                        }
                    }
                }

                if (cell.West != null) {
                    if (cell.West.TraversalPoint > v) {
                        cell.West.TraversalPoint = v;
                        if (cell.West != toCell) {
                            cellStack.Push(cell.West);
                        }
                    }
                }
            }

            // 2. We won't use cell stack anymore
            cellStack.Clear();
            cellStack = null;

            // 3. Traverse back
            List<StageCell> path = new List<StageCell>();
            StageCell traverseBackCell = toCell;
            path.Add(traverseBackCell);

            while (traverseBackCell != fromCell) {

                StageCell[] neightbourCells = new StageCell[] {
                    traverseBackCell.North,
                    traverseBackCell.East,
                    traverseBackCell.South,
                    traverseBackCell.West
                };

                StageCell minTraversePointCell = null;
                int minTraversePoint = int.MaxValue;
                for (int i=0; i<neightbourCells.Length; i++) {
                    if (neightbourCells[i] == null) {
                        continue;
                    }
                    if (neightbourCells[i].TraversalPoint < minTraversePoint) {
                        minTraversePoint = neightbourCells[i].TraversalPoint;
                        minTraversePointCell = neightbourCells[i];
                    }
                }

                traverseBackCell = minTraversePointCell;
                path.Add(traverseBackCell);
            }

            path.Reverse();
            return path;
        }
Exemplo n.º 32
0
		public void GetListTest ()
		{
			ListSource lsource = new ListSource (true);
			Stack stack = new Stack ();
			stack.Push (3);

			Assert.IsTrue (ListBindingHelper.GetList (lsource) is SimpleItem [], "#A1");
			Assert.AreEqual ("NonList", ListBindingHelper.GetList ("NonList"), "#A2");
			Assert.AreEqual (null, ListBindingHelper.GetList (null), "#A3");
			Assert.AreEqual (stack, ListBindingHelper.GetList (stack), "#A4"); // IEnumerable

			Assert.IsTrue (ListBindingHelper.GetList (lsource, String.Empty) is SimpleItem [], "#B1");
			Assert.AreEqual ("NonList", ListBindingHelper.GetList ("NonList", String.Empty), "#B2");
			Assert.AreEqual (null, ListBindingHelper.GetList (null, "DontExist"), "#B3");
			Assert.IsTrue (ListBindingHelper.GetList (lsource, null) is SimpleItem [], "#B4");

			ListContainer list_container = new ListContainer ();
			Assert.AreEqual (new object [0], ListBindingHelper.GetList (list_container, "List"), "#C1");

			// Even if IListSource.ContainsListCollection is false, we return the result of GetList ()
			lsource = new ListSource (false);
			Assert.IsTrue (ListBindingHelper.GetList (lsource) is SimpleItem [], "#D1");

			// DataMember is not if IList type
			Assert.AreEqual (new SimpleItem (), ListBindingHelper.GetList (list_container, "NonList"), "#E1");

			// List (IEnumerable)
			stack.Clear ();
			stack.Push (new SimpleItem (3));
			stack.Push (new SimpleItem (7));
			object obj = ListBindingHelper.GetList (stack, "Value");
			Assert.IsTrue (obj != null, "#F1");
			Assert.IsTrue (obj is int, "#F2");
			Assert.AreEqual (7, (int) obj, "#F3");

			// ListSource returning an IEnumerable,
			// which in turn retrieves dataMember
			obj = ListBindingHelper.GetList (lsource, "Value");
			Assert.IsTrue (obj != null, "#G1");
			Assert.IsTrue (obj is int, "#G2");
			Assert.AreEqual (0, (int)obj, "#G3");

			// Empty IEnumerable - valid property for list item type
			// Since it's empty, it needs to check whether the datamember is
			// a valid value, and thus we need the datasource to also be IList
			// Then we need a parameterized IEnumerable, which returns null.
			// *Observation: if it is empty and it doesn't implement IList,
			// it doesn't have a way to get the properties, and will throw an exc
			StringCollection str_coll = new StringCollection ();
			obj = ListBindingHelper.GetList (str_coll, "Length");
			Assert.IsNull (obj, "#H1");

			// IEnumerable that returns instances of ICustomTypeDescriptor
			// Use DataTable as source, which returns, when enumerating,
			// instances of DataRowView, which in turn implement ICustomTypeDescriptor
			DataTable table = new DataTable ();
			table.Columns.Add ("Id", typeof (int));
			table.Rows.Add (666);
			object l = ListBindingHelper.GetList (table, "Id");
			Assert.AreEqual (666, l, "#J1");

			try {
				ListBindingHelper.GetList (list_container, "DontExist");
				Assert.Fail ("#EXC1");
			} catch (ArgumentException) {
			}

			// Empty IEnumerable not implementing IList
			// Don't have a way to know whether at least datamember is valid or not.
			try {
				stack.Clear ();
				obj = ListBindingHelper.GetList (stack, "Value");
				Assert.Fail ("#EXC3");
			} catch (ArgumentException) {
			}

		}
Exemplo n.º 33
0
            public DICTData( byte[] data, INDEXData String, bool isPrivate )
            {
                uint cursor = 0;
                Stack operandStack = new Stack();
                m_String = String;
                ROS = null;

                while( cursor < data.Length )
                {
                    uint advance = 1;
                    if ( data[cursor] >= 32 && data[cursor] <= 246 )
                    {
                        operandStack.Push( (data[cursor]-139) );
                    }
                    else if ( data[cursor] >= 247 && data[cursor] <= 250 )
                    {
                        operandStack.Push( ((data[cursor]-247)*256+data[cursor+1]+108) );
                        advance = 2;
                    }
                    else if ( data[cursor] >= 251 && data[cursor] <= 254 )
                    {
                        operandStack.Push( (-(data[cursor]-251)*256-data[cursor+1]-108) );
                        advance = 2;
                    }
                    else if ( data[cursor] == 28 )
                    {
                        operandStack.Push( (data[cursor+1]<<8|data[cursor+2]) );
                        advance = 3;
                    }
                    else if ( data[cursor] == 29 )
                    {
                        operandStack.Push( (data[cursor+1]<<24|data[cursor+2]<<16|data[cursor+3]<<8|data[cursor+4]) );
                        advance = 5;
                    }
                    else if ( data[cursor] == 30 )
                    {
                        string realstr = "";
                        while ( (data[cursor+advance] & 0x0f) != 0x0f )
                        {
                            int[] x = { data[cursor+advance] >> 4, data[cursor+advance] & 0x0f };
                            for (int i = 0; i < 2 ; i++)
                            {
                                switch(x[i])
                                {
                                    case 10:
                                        realstr += ".";
                                        break;
                                    case 11:
                                        realstr += "E";
                                        break;
                                    case 12:
                                        realstr += "E-";
                                        break;
                                    case 14:
                                        realstr += "-";
                                        break;
                                    case 15:
                                        /* do nothing */
                                        break;
                                    case 13:
                                        throw new ArgumentOutOfRangeException("Invalid Nibble encountered at pos "
                                                                              + cursor );
                                        break;
                                    default:
                                        /* 0 - 9, hopefully! */
                                        realstr += x[i].ToString("d1");
                                        break;
                                }
                            }
                            advance ++;
                        }
                        /* the last half byte */
                        int y = data[cursor+advance] >> 4 ;
                        switch(y)
                        {
                            case 10:
                                realstr += ".";
                                break;
                            case 11:
                                realstr += "E";
                                break;
                            case 12:
                                realstr += "E-";
                                break;
                            case 14:
                                realstr += "-";
                                break;
                            case 15:
                                /* do nothing */
                                break;
                            case 13:
                                throw new ArgumentOutOfRangeException("Invalid Nibble encountered at pos "
                                                                      + cursor );
                                break;
                            default:
                                /* 0 - 9, hopefully! */
                                realstr += y.ToString("d1");
                                break;
                        }
                        operandStack.Push(realstr);
                        advance ++;
                    }
                    else if ( !isPrivate && data[cursor] >= 0 && data[cursor] <= 21 )
                    {
                        string op = "";
                        switch(data[cursor])
                        {
                            case 0x00:
                                int sidversion = (int) operandStack.Pop();
                                op = "version";
                                break;
                            case 0x01:
                                int sidNotice = (int) operandStack.Pop();
                                op = "Notice";
                                break;
                            case 0x02:
                                sidFullName = (int) operandStack.Pop();
                                op = "FullName";
                                break;
                            case 0x03:
                                int sidFamilyName = (int) operandStack.Pop();
                                op = "FamilyName";
                                break;
                            case 0x04:
                                int sidWeight = (int) operandStack.Pop();
                                op = "Weight";
                                break;
                            case 0x05:
                                operandStack.Pop();
                                operandStack.Pop();
                                operandStack.Pop();
                                operandStack.Pop();
                                op = "FontBBox";
                                break;
                            case 0x0d:
                                operandStack.Pop();
                                op = "UniqueID";
                                break;
                            case 0x0e:
                                operandStack.Clear();
                                op = "XUID";
                                break;
                            case 0x0f:
                                offsetCharset = (int) operandStack.Pop();
                                op = "charset";
                                break;
                            case 0x10:
                                offsetEncoding = (int) operandStack.Pop();
                                op = "Encoding";
                                break;
                            case 0x11:
                                offsetCharStrings = (int) operandStack.Pop();
                                op = "CharStrings";
                                break;
                            case 0x12:
                                offsetPrivate = (int) operandStack.Pop();
                                sizePrivate   = (int) operandStack.Pop();
                                op = "Private";
                                break;
                            case 0x0c:
                                switch(data[cursor+1])
                                {
                                    case 0x00:
                                        int sidCopyright = (int) operandStack.Pop();
                                        op = "Copyright";
                                        break;
                                    case 0x01:
                                        operandStack.Pop();
                                        op = "isFixedPitch";
                                        break;
                                    case 0x02:
                                        operandStack.Pop();
                                        op = "ItalicAngle";
                                        break;
                                    case 0x03:
                                        operandStack.Pop();
                                        op = "UnderlinePosition";
                                        break;
                                    case 0x04:
                                        operandStack.Pop();
                                        op = "UnderlineThickness";
                                        break;
                                    case 0x05:
                                        operandStack.Pop();
                                        op = "PaintType";
                                        break;
                                    case 0x06:
                                        int CharstringType = (int) operandStack.Pop();
                                        if ( CharstringType != 2 )
                                            throw new ArgumentOutOfRangeException("Invalid CharstringType:" + CharstringType );
                                        op = "CharstringType";
                                        break;
                                    case 0x07:
                                        operandStack.Clear();
                                        op = "FontMatrix";
                                        break;
                                    case 0x08:
                                        operandStack.Pop();
                                        op = "StrokeWidth";
                                        break;
                                    case 0x14:
                                        operandStack.Pop();
                                        op = "SyntheticBase";
                                        break;
                                    case 0x15:
                                        operandStack.Pop();
                                        op = "PostScript";
                                        break;
                                    case 0x16:
                                        operandStack.Pop();
                                        op = "BaseFontName";
                                        break;
                                    case 0x17:
                                        operandStack.Clear();
                                        op = "BaseFontBlend";
                                        break;
                                    case 0x1e:
                                        op = "ROS";
                                        int supplement  = (int) operandStack.Pop();
                                        int sidOrdering = (int) operandStack.Pop();
                                        int sidRegistry = (int) operandStack.Pop();
                                        ROS = m_String.StringForID(sidRegistry) + " " + m_String.StringForID(sidOrdering) + " " + supplement;
                                        break;
                                    case 0x1f:
                                        object oCIDFontVersion = operandStack.Pop();
                                        op = "CIDFontVersion";
                                        break;
                                    case 0x20:
                                        operandStack.Pop();
                                        op = "CIDFontRevision";
                                        break;
                                    case 0x21:
                                        operandStack.Pop();
                                        op = "CIDFontType";
                                        break;
                                    case 0x22:
                                        operandStack.Pop();
                                        op = "CIDCount";
                                        break;
                                    case 0x23:
                                        operandStack.Pop();
                                        op = "UIDBase";
                                        break;
                                    case 0x24:
                                        offsetFDArray  = (int) operandStack.Pop();
                                        op = "FDArray";
                                        break;
                                    case 0x25:
                                        offsetFDSelect = (int) operandStack.Pop();
                                        op = "FDSelect";
                                        break;
                                    case 0x26:
                                        sidFontName = (int) operandStack.Pop();
                                        op = "FontName";
                                        break;
                                    default:
                                        operandStack.Clear();
                                        op = "<2-byte>+0x" + data[cursor+1].ToString("x2");
                                        throw new ArgumentOutOfRangeException("Invalid <2-byte> op:"
                                                                              + data[cursor+1].ToString("x2") + " at pos " + cursor );
                                }
                                advance = 2;
                                break;

                            default:
                                operandStack.Clear();
                                op = "0x" + data[cursor].ToString("x2");
                                throw new ArgumentOutOfRangeException("Invalid op:"
                                                                      + data[cursor].ToString("x2") + " at pos " + cursor );
                        }
                    }
                    else if ( isPrivate && data[cursor] >= 0 && data[cursor] <= 21 )
                    {
                        string op = "";
                        switch(data[cursor])
                        {
                            case 0x06:
                                operandStack.Clear();
                                op = "BlueValues";
                                break;
                            case 0x07:
                                operandStack.Clear();
                                op = "OtherBlues";
                                break;
                            case 0x08:
                                operandStack.Clear();
                                op = "FamilyBlues";
                                break;
                            case 0x09:
                                operandStack.Clear();
                                op = "FamilyOtherBlues";
                                break;
                            case 0x0a:
                                operandStack.Pop();
                                op = "StdHW";
                                break;
                            case 0x0b:
                                operandStack.Pop();
                                op = "StdVW";
                                break;
                            case 0x13:
                                Subrs = (int) operandStack.Pop();
                                op = "Subrs";
                                break;
                            case 0x14:
                                operandStack.Pop();
                                op = "defaultWidthX";
                                break;
                            case 0x15:
                                operandStack.Pop();
                                op = "nominalWidthX";
                                break;
                            case 0x0c:
                                switch(data[cursor+1])
                                {
                                    case 0x09:
                                        operandStack.Pop();
                                        op = "BlueScale";
                                        break;
                                    case 0x0a:
                                        operandStack.Pop();
                                        op = "BlueShift";
                                        break;
                                    case 0x0b:
                                        operandStack.Pop();
                                        op = "BlueFuzz";
                                        break;
                                    case 0x0c:
                                        operandStack.Clear();
                                        op = "StemSnapH";
                                        break;
                                    case 0x0d:
                                        operandStack.Clear();
                                        op = "StemSnapV";
                                        break;
                                    case 0x0e:
                                        operandStack.Pop();
                                        op = "ForceBold";
                                        break;
                                    case 0x11:
                                        operandStack.Pop();
                                        op = "LanguageGroup";
                                        break;
                                    case 0x12:
                                        operandStack.Pop();
                                        op = "ExpansionFactor";
                                        break;
                                    case 0x13:
                                        operandStack.Pop();
                                        op = "initialRandomSeed";
                                        break;
                                    default:
                                        operandStack.Clear();
                                        op = "<2-byte>+0x" + data[cursor+1].ToString("x2");
                                        throw new ArgumentOutOfRangeException("Invalid <2-byte> op:"
                                                                              + data[cursor+1].ToString("x2") + " at pos " + cursor );
                                }
                                advance = 2;
                                break;
                            default:
                                operandStack.Clear();
                                op = "0x" + data[cursor].ToString("x2");
                                throw new ArgumentOutOfRangeException("Invalid op:"
                                                                      + data[cursor].ToString("x2") + " at pos " + cursor );
                        }
                    }
                    else
                    {
                        throw new ArgumentOutOfRangeException("Reserved Byte encountered:"
                                                              + data[cursor].ToString("x2") + " at pos " + cursor );
                    }
                    cursor += advance;
                }
                if (cursor != data.Length)
                    throw new ArgumentOutOfRangeException( "operand stack ends unexpectedly, cursor not equal to data length:"
                                                           + cursor + "!=" + data.Length );
                if (operandStack.Count != 0)
                    throw new ArgumentOutOfRangeException( "operand stack not empty:"
                                                           + operandStack.Count );
            }
Exemplo n.º 34
0
        private static Hashtable analyzeSingleStory(string fileName, StoryData inputStory, Hashtable sampleStoryData)
        {
            Hashtable currentStoryStats = new Hashtable();

            #region FILE_NAME
            currentStoryStats[FILE_NAME] = System.IO.Path.GetFileName(fileName);
            #endregion

            #region STORY_COUNT_PLOTFRAGS
            currentStoryStats[STORY_COUNT_PLOTFRAGS] = 0.0;
            foreach(AuthorGoal g in inputStory.AuthorGoals)
            {
                currentStoryStats[STORY_COUNT_PLOTFRAGS] = (double)currentStoryStats[STORY_COUNT_PLOTFRAGS] + (double)g.PlotFragments.Count;
            }

            #endregion

            #region STORY_COUNT_GOALS
            currentStoryStats[STORY_COUNT_GOALS] = (double)inputStory.AuthorGoals.Count;
            #endregion

            #region STORY_AVG_PLOTFRAGS_PER_GOAL

            if((double)currentStoryStats[STORY_COUNT_GOALS] > 0.0 )
            {
                currentStoryStats[STORY_AVG_PLOTFRAGS_PER_GOAL] = (double)currentStoryStats[STORY_COUNT_PLOTFRAGS] / (double)currentStoryStats[STORY_COUNT_GOALS];
            }
            else
            {
                currentStoryStats[STORY_AVG_PLOTFRAGS_PER_GOAL] = 0.0;
            }

            #endregion

            #region STORY_AVG_SUBGOALS_PER_GOAL

            if ((double)currentStoryStats[STORY_COUNT_GOALS] > 0.0)
            {

                currentStoryStats[STORY_AVG_SUBGOALS_PER_GOAL] = 0.0;

                foreach (AuthorGoal g in inputStory.AuthorGoals)
                {
                    foreach (PlotFragment f in g.PlotFragments)
                    {
                        foreach (Action a in f.Actions)
                        {
                            if (a is ActionSubgoal)
                            {
                                currentStoryStats[STORY_AVG_SUBGOALS_PER_GOAL] = (double)currentStoryStats[STORY_AVG_SUBGOALS_PER_GOAL] + 1.0;
                            }

                        }

                    }

                }
                //Calculate average by dividing total number of subgoal actions in entire story by number of author goals
                currentStoryStats[STORY_AVG_SUBGOALS_PER_GOAL] = (double)currentStoryStats[STORY_AVG_SUBGOALS_PER_GOAL] / (double)currentStoryStats[STORY_COUNT_GOALS];

            }
            else
            {
                currentStoryStats[STORY_AVG_SUBGOALS_PER_GOAL] = 0.0;
            }

            #endregion

            #region STORY_COUNT_CHARACTERS
            currentStoryStats[STORY_COUNT_CHARACTERS] = (double)inputStory.Characters.Count;
            #endregion

            #region STORY_COUNT_CHARACTER_TRAITS
            if ((double)currentStoryStats[STORY_COUNT_CHARACTERS] > 0.0)
            {
                currentStoryStats[STORY_COUNT_CHARACTER_TRAITS] = (double)inputStory.Characters[0].Traits.Count;
            }
            else
            {
                currentStoryStats[STORY_COUNT_CHARACTER_TRAITS] = 0.0;
            }
            #endregion

            #region STORY_COUNT_CHARACTER_RELATIONSHIPS
            if ((double)currentStoryStats[STORY_COUNT_CHARACTERS] > 0.0)
            {
                currentStoryStats[STORY_COUNT_CHARACTER_RELATIONSHIPS] = (double)inputStory.Characters[0].Relationships.Count;
            }
            else
            {
                currentStoryStats[STORY_COUNT_CHARACTER_RELATIONSHIPS] = 0.0;
            }
            #endregion

            #region STORY_COUNT_ENVIRONMENTS
            currentStoryStats[STORY_COUNT_ENVIRONMENTS] = (double)inputStory.Environments.Count;
            #endregion

            #region STORY_COUNT_ENVIRONMENT_TRAITS
            if ((double)currentStoryStats[STORY_COUNT_ENVIRONMENTS] > 0.0)
            {
                currentStoryStats[STORY_COUNT_ENVIRONMENT_TRAITS] = (double)inputStory.Environments[0].Traits.Count;
            }
            else
            {
                currentStoryStats[STORY_COUNT_ENVIRONMENT_TRAITS] = 0.0;
            }
            #endregion

            #region STORY_COUNT_ENVIRONMENT_RELATIONSHIPS
            if ((double)currentStoryStats[STORY_COUNT_ENVIRONMENTS] > 0.0)
            {
                currentStoryStats[STORY_COUNT_ENVIRONMENT_RELATIONSHIPS] = (double)inputStory.Environments[0].Relationships.Count;
            }
            else
            {
                currentStoryStats[STORY_COUNT_ENVIRONMENT_RELATIONSHIPS] = 0.0;
            }
            #endregion

            #region STORY_COUNT_PLOTPOINTS
            currentStoryStats[STORY_COUNT_PLOTPOINTS] = (double)inputStory.PlotPointTypes.Count;
            #endregion

            #region STORY_COUNT_PLOTPOINT_TRAITS
            if ((double)currentStoryStats[STORY_COUNT_PLOTPOINTS] > 0.0)
            {
                currentStoryStats[STORY_COUNT_PLOTPOINT_TRAITS] = (double)inputStory.PlotPointTypes[0].Traits.Count;
            }
            else
            {
                currentStoryStats[STORY_COUNT_PLOTPOINT_TRAITS] = 0.0;
            }
            #endregion

            #region STORY_INTERACTIVE_ACTIONS
            currentStoryStats[STORY_INTERACTIVE_ACTIONS] = (double)inputStory.Interactions.Count;
            #endregion

            #region STORY_DEEPEST_GOALFRAG_TREE_PATH
            ArrayList pathDepths = new ArrayList(10);

            Hashtable goalTable = new Hashtable(inputStory.AuthorGoals.Count);
            Stack goalStack = new Stack();
            foreach(AuthorGoal g in inputStory.AuthorGoals)
            {
                goalTable.Add(g.Id, g);
            }
            foreach (AuthorGoal g in inputStory.AuthorGoals)
            {

                measureGoalDepth(inputStory, goalStack, goalTable, g, pathDepths, 1);
                goalStack.Clear();

            }

            int totalPathDepth = 0;
            int deepestPathDepth = 0;
            foreach(int pathDepth in pathDepths)
            {
                totalPathDepth += pathDepth;
                deepestPathDepth = pathDepth > deepestPathDepth ? pathDepth : deepestPathDepth;

            }

            currentStoryStats[STORY_DEEPEST_GOALFRAG_TREE_PATH] = (double)deepestPathDepth;
            #endregion

            #region STORY_AVG_DEPTH_GOALFRAG_TREE_PATH

            if (pathDepths.Count > 0)
            {
                currentStoryStats[STORY_AVG_DEPTH_GOALFRAG_TREE_PATH] = (double)totalPathDepth /(double)pathDepths.Count;
            }
            else
            {
                currentStoryStats[STORY_AVG_DEPTH_GOALFRAG_TREE_PATH] = 0.0;
            }

            #endregion

            #region PLOTFRAG_COUNT_PARAMETERS
            currentStoryStats[PLOTFRAG_COUNT_PARAMETERS] = 0.0;
            foreach (AuthorGoal g in inputStory.AuthorGoals)
            {
                currentStoryStats[PLOTFRAG_COUNT_PARAMETERS] = (double)currentStoryStats[PLOTFRAG_COUNT_PARAMETERS] + (double)g.Parameters.Count;
            }
            #endregion

            #region PLOTFRAG_AVG_PARAMETERS
            if ((double)currentStoryStats[STORY_COUNT_GOALS] > 0.0)
            {
                currentStoryStats[PLOTFRAG_AVG_PARAMETERS] = (double)currentStoryStats[PLOTFRAG_COUNT_PARAMETERS] / (double)currentStoryStats[STORY_COUNT_GOALS];
            }
            else
            {
                currentStoryStats[PLOTFRAG_AVG_PARAMETERS] = 0.0;
            }
            #endregion

            #region PRECOND_COUNT_PRECONDS
            currentStoryStats[PRECOND_COUNT_PRECONDS] = 0.0;
            foreach (AuthorGoal g in inputStory.AuthorGoals)
            {
                foreach(PlotFragment f in g.PlotFragments)
                {
                    currentStoryStats[PRECOND_COUNT_PRECONDS] = (double)currentStoryStats[PRECOND_COUNT_PRECONDS] + (double)f.PrecStatements.Count;
                }

            }
            #endregion

            #region PRECOND_AVG_PRECONDS
            if ((double)currentStoryStats[STORY_COUNT_PLOTFRAGS] > 0.0)
            {
                currentStoryStats[PRECOND_AVG_PRECONDS] = (double)currentStoryStats[PRECOND_COUNT_PRECONDS] / (double)currentStoryStats[STORY_COUNT_PLOTFRAGS];
            }
            else
            {
                currentStoryStats[PRECOND_AVG_PRECONDS] = 0.0;
            }
            #endregion

            #region PRECOND_COUNT_CONSTRAINTS
            currentStoryStats[PRECOND_COUNT_CONSTRAINTS] = 0.0;
            foreach (AuthorGoal g in inputStory.AuthorGoals)
            {
                foreach (PlotFragment f in g.PlotFragments)
                {
                    foreach(PreconditionStatement p in f.PrecStatements)
                    {
                        currentStoryStats[PRECOND_COUNT_CONSTRAINTS] = (double)currentStoryStats[PRECOND_COUNT_CONSTRAINTS] + (double)p.Constraints.Count;
                    }

                }

            }
            #endregion

            #region PRECOND_AVG_CONSTRAINTS
            if ((double)currentStoryStats[PRECOND_COUNT_PRECONDS] > 0.0)
            {
                currentStoryStats[PRECOND_AVG_CONSTRAINTS] = (double)currentStoryStats[PRECOND_COUNT_CONSTRAINTS] / (double)currentStoryStats[PRECOND_COUNT_PRECONDS];
            }
            else
            {
                currentStoryStats[PRECOND_AVG_CONSTRAINTS] = 0.0;
            }
            #endregion

            #region PRECOND_COUNT_TOTAL_VAR_BINDINGS
            currentStoryStats[PRECOND_COUNT_TOTAL_VAR_BINDINGS] = 0.0;
            foreach (AuthorGoal g in inputStory.AuthorGoals)
            {
                foreach (PlotFragment f in g.PlotFragments)
                {
                    foreach (PreconditionStatement p in f.PrecStatements)
                    {
                        if(p.SaveMatchedObject)
                        {
                            currentStoryStats[PRECOND_COUNT_TOTAL_VAR_BINDINGS] = (double)currentStoryStats[PRECOND_COUNT_TOTAL_VAR_BINDINGS] + 1.0;

                        }
                        foreach (Constraint c in p.Constraints)
                        {
                            if(c.ContainsSavedVariable)
                            {
                                currentStoryStats[PRECOND_COUNT_TOTAL_VAR_BINDINGS] = (double)currentStoryStats[PRECOND_COUNT_TOTAL_VAR_BINDINGS] + 1.0;
                            }
                        }

                    }

                }

            }
            #endregion

            #region PRECOND_AVG_VAR_BINDINGS_PER_PLOTFRAG
            if ((double)currentStoryStats[STORY_COUNT_PLOTFRAGS] > 0.0)
            {
                currentStoryStats[PRECOND_AVG_VAR_BINDINGS_PER_PLOTFRAG] = (double)currentStoryStats[PRECOND_COUNT_TOTAL_VAR_BINDINGS] / (double)currentStoryStats[STORY_COUNT_PLOTFRAGS];
            }
            else
            {
                currentStoryStats[PRECOND_AVG_VAR_BINDINGS_PER_PLOTFRAG] = 0.0;
            }
            #endregion

            #region PRECOND_COUNT_NEGATION
            currentStoryStats[PRECOND_COUNT_NEGATION] = 0.0;
            foreach (AuthorGoal g in inputStory.AuthorGoals)
            {
                foreach (PlotFragment f in g.PlotFragments)
                {
                    foreach (PreconditionStatement p in f.PrecStatements)
                    {
                        if(!p.ObjectExists)
                        {
                            currentStoryStats[PRECOND_COUNT_NEGATION] = (double)currentStoryStats[PRECOND_COUNT_NEGATION] + 1.0;
                        }

                    }

                }

            }
            #endregion

            #region PRECOND_COUNT_TOTAL_VAR_REFERENCES
            currentStoryStats[PRECOND_COUNT_TOTAL_VAR_REFERENCES] = 0.0;
            foreach (AuthorGoal g in inputStory.AuthorGoals)
            {
                foreach (PlotFragment f in g.PlotFragments)
                {
                    foreach (PreconditionStatement p in f.PrecStatements)
                    {
                        foreach (Constraint c in p.Constraints)
                        {
                            if(c.ComparisonValue.ValueIsBoundToVariable)
                            {
                                currentStoryStats[PRECOND_COUNT_TOTAL_VAR_REFERENCES] = (double)currentStoryStats[PRECOND_COUNT_TOTAL_VAR_REFERENCES] + 1.0;
                            }
                        }

                    }

                }

            }
            #endregion

            #region PRECOND_AVG_VAR_REFERENCES_PER_PLOTFRAG
            if ((double)currentStoryStats[STORY_COUNT_PLOTFRAGS] > 0.0)
            {
                currentStoryStats[PRECOND_AVG_VAR_REFERENCES_PER_PLOTFRAG] = (double)currentStoryStats[PRECOND_COUNT_TOTAL_VAR_REFERENCES] / (double)currentStoryStats[STORY_COUNT_PLOTFRAGS];
            }
            else
            {
                currentStoryStats[PRECOND_AVG_VAR_REFERENCES_PER_PLOTFRAG] = 0.0;
            }
            #endregion

            #region PRECOND_COUNT_NEGATION
            currentStoryStats[PRECOND_COUNT_NEGATION] = 0.0;
            foreach (AuthorGoal g in inputStory.AuthorGoals)
            {
                foreach (PlotFragment f in g.PlotFragments)
                {
                    foreach (PreconditionStatement p in f.PrecStatements)
                    {
                        if(!p.ObjectExists)
                        {
                            currentStoryStats[PRECOND_COUNT_NEGATION] = (double)currentStoryStats[PRECOND_COUNT_NEGATION] + 1.0;
                        }

                    }

                }

            }
            #endregion

            #region PRECOND_AVG_NEGATION
            if ((double)currentStoryStats[STORY_COUNT_PLOTFRAGS] > 0.0)
            {
                currentStoryStats[PRECOND_AVG_NEGATION] = (double)currentStoryStats[PRECOND_COUNT_NEGATION] / (double)currentStoryStats[STORY_COUNT_PLOTFRAGS];
            }
            else
            {
                currentStoryStats[PRECOND_AVG_NEGATION] = 0.0;
            }
            #endregion

            #region ACTION_TOTAL_ACTIONS
            currentStoryStats[ACTION_TOTAL_ACTIONS] = 0.0;
            foreach (AuthorGoal g in inputStory.AuthorGoals)
            {
                foreach (PlotFragment f in g.PlotFragments)
                {
                    currentStoryStats[ACTION_TOTAL_ACTIONS] = (double)currentStoryStats[ACTION_TOTAL_ACTIONS] + (double)f.Actions.Count;
                }

            }
            #endregion

            #region ACTION_AVG_ACTIONS
            if ((double)currentStoryStats[STORY_COUNT_PLOTFRAGS] > 0.0)
            {
                currentStoryStats[ACTION_AVG_ACTIONS] = (double)currentStoryStats[ACTION_TOTAL_ACTIONS] / (double)currentStoryStats[STORY_COUNT_PLOTFRAGS];
            }
            else
            {
                currentStoryStats[ACTION_AVG_ACTIONS] = 0.0;
            }
            #endregion

            #region ACTION_COUNT_VAR_REFERENCES
            currentStoryStats[ACTION_COUNT_VAR_REFERENCES] = 0.0;
            foreach (AuthorGoal g in inputStory.AuthorGoals)
            {
                foreach (PlotFragment f in g.PlotFragments)
                {
                    foreach (Action a in f.Actions)
                    {
                        if(a is ActionCalculation)
                        {

                            if( ((ActionCalculation)a).ParamLeft.ValueIsBoundToVariable)
                            {
                                currentStoryStats[ACTION_COUNT_VAR_REFERENCES] = (double)currentStoryStats[ACTION_COUNT_VAR_REFERENCES] + 1.0;
                            }
                            if (((ActionCalculation)a).ParamRight.ValueIsBoundToVariable)
                            {
                                currentStoryStats[ACTION_COUNT_VAR_REFERENCES] = (double)currentStoryStats[ACTION_COUNT_VAR_REFERENCES] + 1.0;
                            }
                        }
                        else if (a is ActionEditObject)
                        {
                            if (((ActionEditObject)a).Mode == ObjectEditingMode.RelationshipTarget && ((ActionEditObject)a).NewTarget.ValueIsBoundToVariable)
                            {
                                currentStoryStats[ACTION_COUNT_VAR_REFERENCES] = (double)currentStoryStats[ACTION_COUNT_VAR_REFERENCES] + 1.0;
                            }
                            else if (((ActionEditObject)a).NewValue.ValueIsBoundToVariable)
                            {
                                currentStoryStats[ACTION_COUNT_VAR_REFERENCES] = (double)currentStoryStats[ACTION_COUNT_VAR_REFERENCES] + 1.0;
                            }
                        }
                        else if (a is ActionTextOutput)
                        {
                            Regex varMatcher = new Regex("(?:[^<])[^<]*(?=>(?!>))", RegexOptions.Compiled | RegexOptions.IgnoreCase);

                            MatchCollection varMatches = varMatcher.Matches(((ActionTextOutput)a).TextOutput);
                            if(varMatches.Count > 0)
                            {
                                currentStoryStats[ACTION_COUNT_VAR_REFERENCES] = (double)currentStoryStats[ACTION_COUNT_VAR_REFERENCES] + (double)varMatches.Count;
                            }
                        }
                        else if (a is ActionSubgoal)
                        {
                            foreach(Parameter p in ((ActionSubgoal)a).ParametersToPass)
                            {
                                if(p.ValueIsBoundToVariable)
                                {
                                    currentStoryStats[ACTION_COUNT_VAR_REFERENCES] = (double)currentStoryStats[ACTION_COUNT_VAR_REFERENCES] + 1.0;
                                }
                            }
                        }

                    }

                }

            }
            #endregion

            #region ACTION_AVG_VAR_REFERENCES
            if ((double)currentStoryStats[STORY_COUNT_PLOTFRAGS] > 0.0)
            {
                currentStoryStats[ACTION_AVG_VAR_REFERENCES] = (double)currentStoryStats[ACTION_COUNT_VAR_REFERENCES] / (double)currentStoryStats[STORY_COUNT_PLOTFRAGS];
            }
            else
            {
                currentStoryStats[ACTION_AVG_VAR_REFERENCES] = 0.0;
            }
            #endregion

            #region ACTION_COUNT_VAR_BINDINGS
            currentStoryStats[ACTION_COUNT_VAR_BINDINGS] = 0.0;
            foreach (AuthorGoal g in inputStory.AuthorGoals)
            {
                foreach (PlotFragment f in g.PlotFragments)
                {
                    foreach (Action a in f.Actions)
                    {
                        if(a is ActionCalculation)
                        {

                            currentStoryStats[ACTION_COUNT_VAR_BINDINGS] = (double)currentStoryStats[ACTION_COUNT_VAR_BINDINGS] + 1.0;

                        }
                        else if (a is ActionCreateCharacter)
                        {
                            currentStoryStats[ACTION_COUNT_VAR_BINDINGS] = (double)currentStoryStats[ACTION_COUNT_VAR_BINDINGS] + 1.0;

                        }
                        else if (a is ActionCreateEnvironment)
                        {
                            currentStoryStats[ACTION_COUNT_VAR_BINDINGS] = (double)currentStoryStats[ACTION_COUNT_VAR_BINDINGS] + 1.0;

                        }
                        else if (a is ActionCreatePlotPoint)
                        {
                            currentStoryStats[ACTION_COUNT_VAR_BINDINGS] = (double)currentStoryStats[ACTION_COUNT_VAR_BINDINGS] + 1.0;

                        }
                    }

                }

            }
            #endregion

            #region ACTION_AVG_VAR_BINDINGS_PER_PLOTFRAG
            if ((double)currentStoryStats[STORY_COUNT_PLOTFRAGS] > 0.0)
            {
                currentStoryStats[ACTION_AVG_VAR_BINDINGS_PER_PLOTFRAG] = (double)currentStoryStats[ACTION_COUNT_VAR_BINDINGS] / (double)currentStoryStats[STORY_COUNT_PLOTFRAGS];
            }
            else
            {
                currentStoryStats[ACTION_AVG_VAR_BINDINGS_PER_PLOTFRAG] = 0.0;
            }
            #endregion

            #region ACTION_COUNT_TEXT_OUTPUTS
            currentStoryStats[ACTION_COUNT_TEXT_OUTPUTS] = 0.0;
            foreach (AuthorGoal g in inputStory.AuthorGoals)
            {
                foreach (PlotFragment f in g.PlotFragments)
                {
                    foreach (Action a in f.Actions)
                    {
                        if(a is ActionTextOutput)
                        {
                            currentStoryStats[ACTION_COUNT_TEXT_OUTPUTS] = (double)currentStoryStats[ACTION_COUNT_TEXT_OUTPUTS] + 1.0;
                        }
                    }

                }

            }
            #endregion

            #region ACTION_AVG_TEXT_OUTPUTS
            if ((double)currentStoryStats[STORY_COUNT_PLOTFRAGS] > 0.0)
            {
                currentStoryStats[ACTION_AVG_TEXT_OUTPUTS] = (double)currentStoryStats[ACTION_COUNT_TEXT_OUTPUTS] / (double)currentStoryStats[STORY_COUNT_PLOTFRAGS];
            }
            else
            {
                currentStoryStats[ACTION_AVG_TEXT_OUTPUTS] = 0.0;
            }
            #endregion

            #region ACTION_AVG_TEXT_OUTPUT_VARS and ACTION_COUNT_TEXT_OUTPUT_VARS

            currentStoryStats[ACTION_AVG_TEXT_OUTPUT_VARS] = 0.0;
            foreach (AuthorGoal g in inputStory.AuthorGoals)
            {
                foreach (PlotFragment f in g.PlotFragments)
                {
                    foreach (Action a in f.Actions)
                    {
                       if (a is ActionTextOutput)
                        {
                            Regex varMatcher = new Regex("(?:[^<])[^<]*(?=>(?!>))", RegexOptions.Compiled | RegexOptions.IgnoreCase);

                            MatchCollection varMatches = varMatcher.Matches(((ActionTextOutput)a).TextOutput);
                            if (varMatches.Count > 0)
                            {
                                currentStoryStats[ACTION_AVG_TEXT_OUTPUT_VARS] = (double)currentStoryStats[ACTION_AVG_TEXT_OUTPUT_VARS] + (double)varMatches.Count;
                            }
                        }

                    }

                }

            }

            //Store the total count of variable references before we caculate the average
            currentStoryStats[ACTION_COUNT_TEXT_OUTPUT_VARS] = (double)currentStoryStats[ACTION_AVG_TEXT_OUTPUT_VARS];

            //Calculate average per text output
            if ((double)currentStoryStats[ACTION_COUNT_TEXT_OUTPUTS] > 0.0)
            {
                currentStoryStats[ACTION_AVG_TEXT_OUTPUT_VARS] = (double)currentStoryStats[ACTION_AVG_TEXT_OUTPUT_VARS] / (double)currentStoryStats[ACTION_COUNT_TEXT_OUTPUTS];
            }
            else
            {
                currentStoryStats[ACTION_AVG_TEXT_OUTPUT_VARS] = 0.0;
            }
            #endregion

            #region ACTION_AVG_TEXT_OUTPUT_LENGTH
            currentStoryStats[ACTION_AVG_TEXT_OUTPUT_LENGTH] = 0.0;
            foreach (AuthorGoal g in inputStory.AuthorGoals)
            {
                foreach (PlotFragment f in g.PlotFragments)
                {
                    foreach (Action a in f.Actions)
                    {
                        if (a is ActionTextOutput)
                        {
                            //Add up total number of characters
                            currentStoryStats[ACTION_AVG_TEXT_OUTPUT_LENGTH] = (double)currentStoryStats[ACTION_AVG_TEXT_OUTPUT_LENGTH] + (double)((ActionTextOutput)a).TextOutput.Length;
                        }
                    }

                }

            }
            //Divide out total number of text output actions to get average char count
            currentStoryStats[ACTION_AVG_TEXT_OUTPUT_LENGTH] = (double)currentStoryStats[ACTION_AVG_TEXT_OUTPUT_LENGTH] / (double)currentStoryStats[ACTION_COUNT_TEXT_OUTPUTS];
            #endregion

            #region ACTION_COUNT_CHAR_ADDS
            currentStoryStats[ACTION_COUNT_CHAR_ADDS] = 0.0;
            foreach (AuthorGoal g in inputStory.AuthorGoals)
            {
                foreach (PlotFragment f in g.PlotFragments)
                {
                    foreach (Action a in f.Actions)
                    {
                        if (a is ActionCreateCharacter)
                        {
                            currentStoryStats[ACTION_COUNT_CHAR_ADDS] = (double)currentStoryStats[ACTION_COUNT_CHAR_ADDS] + 1.0;
                        }
                    }

                }

            }

            #endregion

            #region ACTION_AVG_CHAR_ADDS
            if ((double)currentStoryStats[STORY_COUNT_PLOTFRAGS] > 0.0)
            {
                currentStoryStats[ACTION_AVG_CHAR_ADDS] = (double)currentStoryStats[ACTION_COUNT_CHAR_ADDS] / (double)currentStoryStats[STORY_COUNT_PLOTFRAGS];
            }
            else
            {
                currentStoryStats[ACTION_AVG_CHAR_ADDS] = 0.0;
            }
            #endregion

            #region ACTION_COUNT_CHAR_DELETES
            currentStoryStats[ACTION_COUNT_CHAR_DELETES] = 0.0;
            foreach (AuthorGoal g in inputStory.AuthorGoals)
            {
                foreach (PlotFragment f in g.PlotFragments)
                {
                    foreach (Action a in f.Actions)
                    {
                        if (a is ActionDeleteEntity && ((ActionDeleteEntity)a).TypeId == inputStory.CharTypeId)
                        {
                            currentStoryStats[ACTION_COUNT_CHAR_DELETES] = (double)currentStoryStats[ACTION_COUNT_CHAR_DELETES] + 1.0;
                        }
                    }

                }

            }
            #endregion

            #region ACTION_AVG_CHAR_DELETES
            if ((double)currentStoryStats[STORY_COUNT_PLOTFRAGS] > 0.0)
            {
                currentStoryStats[ACTION_AVG_CHAR_DELETES] = (double)currentStoryStats[ACTION_COUNT_CHAR_DELETES] / (double)currentStoryStats[STORY_COUNT_PLOTFRAGS];
            }
            else
            {
                currentStoryStats[ACTION_AVG_CHAR_DELETES] = 0.0;
            }
            #endregion

            #region ACTION_COUNT_CHAR_EDITS
            currentStoryStats[ACTION_COUNT_CHAR_EDITS] = 0.0;
            foreach (AuthorGoal g in inputStory.AuthorGoals)
            {
                foreach (PlotFragment f in g.PlotFragments)
                {
                    foreach (Action a in f.Actions)
                    {
                        if (a is ActionEditObject && ((ActionEditObject)a).ObjectTypeId == inputStory.CharTypeId)
                        {
                            currentStoryStats[ACTION_COUNT_CHAR_EDITS] = (double)currentStoryStats[ACTION_COUNT_CHAR_EDITS] + 1.0;
                        }
                    }

                }

            }
            #endregion

            #region ACTION_AVG_CHAR_EDITS
             if ((double)currentStoryStats[STORY_COUNT_PLOTFRAGS] > 0.0)
            {
                currentStoryStats[ACTION_AVG_CHAR_EDITS] = (double)currentStoryStats[ACTION_COUNT_CHAR_EDITS] / (double)currentStoryStats[STORY_COUNT_PLOTFRAGS];
            }
            else
            {
                currentStoryStats[ACTION_AVG_CHAR_EDITS] = 0.0;
            }

            #endregion

             #region ACTION_COUNT_ENV_ADDS
             currentStoryStats[ACTION_COUNT_ENV_ADDS] = 0.0;
             foreach (AuthorGoal g in inputStory.AuthorGoals)
             {
                 foreach (PlotFragment f in g.PlotFragments)
                 {
                     foreach (Action a in f.Actions)
                     {
                         if (a is ActionCreateEnvironment)
                         {
                             currentStoryStats[ACTION_COUNT_ENV_ADDS] = (double)currentStoryStats[ACTION_COUNT_ENV_ADDS] + 1.0;
                         }
                     }

                 }

             }

             #endregion

             #region ACTION_AVG_ENV_ADDS
             if ((double)currentStoryStats[STORY_COUNT_PLOTFRAGS] > 0.0)
             {
                 currentStoryStats[ACTION_AVG_ENV_ADDS] = (double)currentStoryStats[ACTION_COUNT_ENV_ADDS] / (double)currentStoryStats[STORY_COUNT_PLOTFRAGS];
             }
             else
             {
                 currentStoryStats[ACTION_AVG_ENV_ADDS] = 0.0;
             }
             #endregion

             #region ACTION_COUNT_ENV_DELETES
             currentStoryStats[ACTION_COUNT_ENV_DELETES] = 0.0;
             foreach (AuthorGoal g in inputStory.AuthorGoals)
             {
                 foreach (PlotFragment f in g.PlotFragments)
                 {
                     foreach (Action a in f.Actions)
                     {
                         if (a is ActionDeleteEntity && ((ActionDeleteEntity)a).TypeId == inputStory.EnvTypeId)
                         {
                             currentStoryStats[ACTION_COUNT_ENV_DELETES] = (double)currentStoryStats[ACTION_COUNT_ENV_DELETES] + 1.0;
                         }
                     }

                 }

             }
             #endregion

             #region ACTION_AVG_ENV_DELETES
             if ((double)currentStoryStats[STORY_COUNT_PLOTFRAGS] > 0.0)
             {
                 currentStoryStats[ACTION_AVG_CHAR_DELETES] = (double)currentStoryStats[ACTION_COUNT_ENV_DELETES] / (double)currentStoryStats[STORY_COUNT_PLOTFRAGS];
             }
             else
             {
                 currentStoryStats[ACTION_AVG_ENV_DELETES] = 0.0;
             }
             #endregion

            #region ACTION_COUNT_ENV_EDITS
            currentStoryStats[ACTION_COUNT_ENV_EDITS] = 0.0;
            foreach (AuthorGoal g in inputStory.AuthorGoals)
            {
                foreach (PlotFragment f in g.PlotFragments)
                {
                    foreach (Action a in f.Actions)
                    {
                        if (a is ActionEditObject && ((ActionEditObject)a).ObjectTypeId == inputStory.EnvTypeId)
                        {
                            currentStoryStats[ACTION_COUNT_ENV_EDITS] = (double)currentStoryStats[ACTION_COUNT_ENV_EDITS] + 1.0;
                        }
                    }

                }

            }
            #endregion

            #region ACTION_AVG_ENV_EDITS
            if ((double)currentStoryStats[STORY_COUNT_PLOTFRAGS] > 0.0)
            {
                currentStoryStats[ACTION_AVG_ENV_EDITS] = (double)currentStoryStats[ACTION_COUNT_ENV_EDITS] / (double)currentStoryStats[STORY_COUNT_PLOTFRAGS];
            }
            else
            {
                currentStoryStats[ACTION_AVG_ENV_EDITS] = 0.0;
            }
            #endregion

            #region ACTION_COUNT_PP_ADDS
            currentStoryStats[ACTION_COUNT_PP_ADDS] = 0.0;
            foreach (AuthorGoal g in inputStory.AuthorGoals)
            {
                foreach (PlotFragment f in g.PlotFragments)
                {
                    foreach (Action a in f.Actions)
                    {
                        if (a is ActionCreatePlotPoint)
                        {
                            currentStoryStats[ACTION_COUNT_PP_ADDS] = (double)currentStoryStats[ACTION_COUNT_PP_ADDS] + 1.0;
                        }
                    }

                }

            }

            #endregion

            #region ACTION_AVG_PP_ADDS
            if ((double)currentStoryStats[STORY_COUNT_PLOTFRAGS] > 0.0)
            {
                currentStoryStats[ACTION_AVG_PP_ADDS] = (double)currentStoryStats[ACTION_COUNT_PP_ADDS] / (double)currentStoryStats[STORY_COUNT_PLOTFRAGS];
            }
            else
            {
                currentStoryStats[ACTION_AVG_PP_ADDS] = 0.0;
            }
            #endregion

            #region ACTION_COUNT_PP_DELETES
            currentStoryStats[ACTION_COUNT_PP_DELETES] = 0.0;
            foreach (AuthorGoal g in inputStory.AuthorGoals)
            {
                foreach (PlotFragment f in g.PlotFragments)
                {
                    foreach (Action a in f.Actions)
                    {
                        if (a is ActionDeleteEntity && ((ActionDeleteEntity)a).TypeId != inputStory.EnvTypeId && ((ActionDeleteEntity)a).TypeId != inputStory.CharTypeId)
                        {
                            currentStoryStats[ACTION_COUNT_PP_DELETES] = (double)currentStoryStats[ACTION_COUNT_PP_DELETES] + 1.0;
                        }
                    }

                }

            }
            #endregion

            #region ACTION_AVG_PP_DELETES
            if ((double)currentStoryStats[STORY_COUNT_PLOTFRAGS] > 0.0)
            {
                currentStoryStats[ACTION_AVG_PP_DELETES] = (double)currentStoryStats[ACTION_COUNT_PP_DELETES] / (double)currentStoryStats[STORY_COUNT_PLOTFRAGS];
            }
            else
            {
                currentStoryStats[ACTION_AVG_PP_DELETES] = 0.0;
            }
            #endregion

            #region ACTION_COUNT_PP_EDITS
            currentStoryStats[ACTION_COUNT_PP_EDITS] = 0.0;
            foreach (AuthorGoal g in inputStory.AuthorGoals)
            {
                foreach (PlotFragment f in g.PlotFragments)
                {
                    foreach (Action a in f.Actions)
                    {
                        if (a is ActionEditObject && ((ActionEditObject)a).ObjectTypeId != inputStory.EnvTypeId && ((ActionEditObject)a).ObjectTypeId != inputStory.CharTypeId)
                        {
                            currentStoryStats[ACTION_COUNT_PP_EDITS] = (double)currentStoryStats[ACTION_COUNT_PP_EDITS] + 1.0;

                        }
                    }

                }

            }
            #endregion

            #region ACTION_AVG_PP_EDITS
            if ((double)currentStoryStats[STORY_COUNT_PLOTFRAGS] > 0.0)
            {
                currentStoryStats[ACTION_AVG_PP_EDITS] = (double)currentStoryStats[ACTION_COUNT_PP_EDITS] / (double)currentStoryStats[STORY_COUNT_PLOTFRAGS];
            }
            else
            {
                currentStoryStats[ACTION_AVG_PP_EDITS] = 0.0;
            }
            #endregion

            #region ACTION_COUNT_SUBGOALS
            currentStoryStats[ACTION_COUNT_SUBGOALS] = 0.0;
            foreach (AuthorGoal g in inputStory.AuthorGoals)
            {
                foreach (PlotFragment f in g.PlotFragments)
                {
                    foreach (Action a in f.Actions)
                    {
                        if (a is ActionSubgoal)
                        {
                            currentStoryStats[ACTION_COUNT_SUBGOALS] = (double)currentStoryStats[ACTION_COUNT_SUBGOALS] + 1.0;

                        }
                    }

                }

            }
            #endregion

            #region ACTION_AVG_SUBGOALS
            if ((double)currentStoryStats[STORY_COUNT_PLOTFRAGS] > 0.0)
            {
                currentStoryStats[ACTION_AVG_SUBGOALS] = (double)currentStoryStats[ACTION_COUNT_SUBGOALS] / (double)currentStoryStats[STORY_COUNT_PLOTFRAGS];
            }
            else
            {
                currentStoryStats[ACTION_AVG_SUBGOALS] = 0.0;
            }
            #endregion

            #region ACTION_COUNT_CALCS
            currentStoryStats[ACTION_COUNT_CALCS] = 0.0;
            foreach (AuthorGoal g in inputStory.AuthorGoals)
            {
                foreach (PlotFragment f in g.PlotFragments)
                {
                    foreach (Action a in f.Actions)
                    {
                        if (a is ActionCalculation)
                        {
                            currentStoryStats[ACTION_COUNT_CALCS] = (double)currentStoryStats[ACTION_COUNT_CALCS] + 1.0;

                        }
                    }

                }

            }
            #endregion

            #region ACTION_AVG_CALCS
            if ((double)currentStoryStats[STORY_COUNT_PLOTFRAGS] > 0.0)
            {
                currentStoryStats[ACTION_AVG_CALCS] = (double)currentStoryStats[ACTION_COUNT_CALCS] / (double)currentStoryStats[STORY_COUNT_PLOTFRAGS];
            }
            else
            {
                currentStoryStats[ACTION_AVG_CALCS] = 0.0;
            }
            #endregion

            #region ACTION_AVG_ACTIONS_BETWEEN_SUBGOALS
            currentStoryStats[ACTION_AVG_ACTIONS_BETWEEN_SUBGOALS] = 0.0;
            int gapCount = 0;
            foreach (AuthorGoal g in inputStory.AuthorGoals)
            {
                foreach (PlotFragment f in g.PlotFragments)
                {
                    int numSubgoalsLeft = 0;
                    int numSubgoals = 0;
                    foreach (Action a in f.Actions)
                    {
                        if(a is ActionSubgoal)
                        {
                            numSubgoals++;
                            numSubgoalsLeft++;
                        }
                    }
                    if(numSubgoals > 1) //Gap between subgoals exists, therefore perform count
                    {
                        foreach (Action a in f.Actions)
                        {
                            if (a is ActionSubgoal)
                            {

                                numSubgoalsLeft--; //Decrement remain subgoal count
                                if(numSubgoalsLeft > 0) //If there is at least one subgoal left, then we are beginning a gap section
                                {
                                    gapCount++;
                                }

                            }
                            else if ((numSubgoals > numSubgoalsLeft) && (numSubgoalsLeft > 0))
                            //We are located after first subgoal, and there are still subgoals left, therefore we are currently inside a gap between subgoals,
                            //and should increment the total gap size by one unit
                            {
                                currentStoryStats[ACTION_AVG_ACTIONS_BETWEEN_SUBGOALS] = (double)currentStoryStats[ACTION_AVG_ACTIONS_BETWEEN_SUBGOALS] + 1.0;
                            }
                        }
                    }

                }

            }
            if(gapCount > 0) //Calculate average gap size between subgoals by dividing total gap size of all gaps by number of gaps
            {
                currentStoryStats[ACTION_AVG_ACTIONS_BETWEEN_SUBGOALS] = (double)currentStoryStats[ACTION_AVG_ACTIONS_BETWEEN_SUBGOALS] / (double)gapCount;
            }
            else
            {
                currentStoryStats[ACTION_AVG_ACTIONS_BETWEEN_SUBGOALS] = 0.0;
            }
            #endregion

            #region PLOTFRAG_COUNT_VAR_REFERENCES
            currentStoryStats[PLOTFRAG_COUNT_VAR_REFERENCES] = (double)currentStoryStats[ACTION_COUNT_VAR_REFERENCES] + (double)currentStoryStats[PRECOND_COUNT_TOTAL_VAR_REFERENCES];
            #endregion

            #region PLOTFRAG_AVG_VAR_REFERENCES
            if ((double)currentStoryStats[STORY_COUNT_PLOTFRAGS] > 0.0)
            {
                currentStoryStats[PLOTFRAG_AVG_VAR_REFERENCES] = (double)currentStoryStats[PLOTFRAG_COUNT_VAR_REFERENCES] / (double)currentStoryStats[STORY_COUNT_PLOTFRAGS];
            }
            else
            {
                currentStoryStats[PLOTFRAG_AVG_VAR_REFERENCES] = 0.0;
            }
            #endregion

            #region PLOTFRAG_COUNT_VAR_BINDINGS
            currentStoryStats[PLOTFRAG_COUNT_VAR_BINDINGS] = (double)currentStoryStats[ACTION_COUNT_VAR_BINDINGS] + (double)currentStoryStats[PRECOND_COUNT_TOTAL_VAR_BINDINGS];
            #endregion

            #region PLOTFRAG_AVG_VAR_BINDINGS
            if ((double)currentStoryStats[STORY_COUNT_PLOTFRAGS] > 0.0)
            {
                currentStoryStats[PLOTFRAG_AVG_VAR_BINDINGS] = (double)currentStoryStats[PLOTFRAG_COUNT_VAR_BINDINGS] / (double)currentStoryStats[STORY_COUNT_PLOTFRAGS];
            }
            else
            {
                currentStoryStats[PLOTFRAG_AVG_VAR_BINDINGS] = 0.0;
            }
            #endregion

            #region SAMPLE SIMILARITY
            if (sampleStoryData == null)
            {
                //We are analyzing the sample story itself
                currentStoryStats[SAMPLE_SIMILARITY] = 0.0;
            }
            else
            {
                int totalStats = 0;
                double distanceSummation = 0.0;

                //Compute generalized euclidean distance for N dimensions, where N = the number of statistical values
                foreach (DictionaryEntry statElement in currentStoryStats)
                {
                    if (!statElement.Key.Equals(SAMPLE_SIMILARITY) && !statElement.Key.Equals(FILE_NAME))
                    {
                        totalStats++;
                        distanceSummation += Math.Pow(
                                                Math.Abs(
                                                    ((double)sampleStoryData[statElement.Key]) - ((double)statElement.Value)
                                                ),
                                             2.0);

                    }
                }
                currentStoryStats[SAMPLE_SIMILARITY] = Math.Sqrt(distanceSummation);

            }
            #endregion

            #region GRADING_POINTS

            gradeStory(currentStoryStats, inputStory);

            #endregion

            return currentStoryStats;
        }
Exemplo n.º 35
0
        public Match Match(IList searchList, int searchIndex, int searchLength)
        {
            char searchingChar;
            int searchingGroups;
            bool searchingEscaped;
            bool searchingCondition;
            char searchingNextChar;
            char searchingPreviousChar;

            int patternIndex = 0;
            byte patternSymbol = symbol_Char;
            int patternLength = this.patternChars.Length;
            char patternChar = this.patternChars[patternIndex];

            bool escaped = false;
            bool comparing = false;
            bool startAnchored = false;
            int repetitions = 0;
            int minRepetitions = 1;
            int maxRepetitions = 1;
            ArrayList classChars = new ArrayList();

            Match match;
            Group group;
            Stack groupStack = new Stack();
            ArrayList groupList = new ArrayList();

            match = new Match() { index = searchIndex, patternBeginIndex = patternIndex, success = true };

            group = match;
            groupList.Add(group);

            //Check if searchList is byte list.
            if (searchList[searchIndex] is byte)
                searchList = new CharByteList(searchList);

            searchLength += searchIndex;

            while (true)
            {
                while (patternIndex < patternLength)
                {
                    if (escaped)
                    {
                        escaped = false;
                        comparing = true;

                        switch (patternChar)
                        {
                            case char_d:
                                patternSymbol = symbol_Digit;
                                break;
                            case char_w:
                                patternSymbol = symbol_WordCharacter;
                                break;
                            case char_s:
                                patternChar = char_Space;
                                patternSymbol = symbol_Char;
                                break;
                            case char_r:
                                patternChar = char_CarriageReturn;
                                patternSymbol = symbol_Char;
                                break;
                            case char_n:
                                patternChar = char_LineFeed;
                                patternSymbol = symbol_Char;
                                break;
                            case char_t:
                                patternChar = char_Tab;
                                patternSymbol = symbol_Char;
                                break;
                            default:
                                patternSymbol = symbol_Char;
                                break;
                        }
                    }
                    else
                    {
                        switch (patternChar)
                        {
                            case char_BackSlash:
                                escaped = true;
                                break;
                            case char_CircumflexAccent:
                                startAnchored = true;
                                break;
                            case char_VerticalLine:
                                if (group.success)
                                {
                                    searchingGroups = 0;
                                    searchingEscaped = false;

                                    //Search group end.
                                    while (patternIndex < patternLength)
                                    {
                                        searchingNextChar = this.patternChars[patternIndex];

                                        if (searchingEscaped)
                                        {
                                            searchingEscaped = false;
                                        }
                                        else if (searchingNextChar == char_BackSlash)
                                        {
                                            searchingEscaped = true;
                                        }
                                        else if (searchingNextChar == char_LeftParenthesis)
                                        {
                                            searchingGroups++;

                                            //Add empty group.
                                            groupList.Add(new Group() { success = false });
                                        }
                                        else if (searchingNextChar == char_RightParenthesis)
                                        {
                                            searchingGroups--;

                                            if (searchingGroups < 0)
                                                break;
                                        }

                                        patternIndex++;
                                    }

                                    patternIndex--;
                                }
                                else
                                {
                                    //Start alternative search.
                                    group.success = true;

                                    searchIndex = group.index;
                                }
                                break;
                            case char_LeftParenthesis:
                                //Push the parent group on the stack.
                                groupStack.Push(group);

                                //Initializze the child group.
                                group = new Group() { index = searchIndex, patternBeginIndex = patternIndex, success = true };
                                groupList.Add(group);
                                break;
                            case char_RightParenthesis:
                                //Check if repetitions are evalueted.
                                if (group.repetitions == 0)
                                {
                                    //Evaluate repetitions.
                                    if (patternIndex + 1 < patternLength)
                                    {
                                        searchingNextChar = this.patternChars[patternIndex + 1];

                                        switch (searchingNextChar)
                                        {
                                            case char_Asterisk:
                                                patternIndex++;

                                                group.minRepetitions = 0;
                                                group.maxRepetitions = Int32.MaxValue;
                                                break;
                                            case char_PlusSign:
                                                patternIndex++;

                                                group.minRepetitions = 1;
                                                group.maxRepetitions = Int32.MaxValue;

                                                group.patternEndIndex = patternIndex + 1;
                                                break;
                                            case char_LeftCurlyBracket:
                                                group.minRepetitions = 0;
                                                group.maxRepetitions = 0;

                                                searchingCondition = false;

                                                patternIndex += 2;

                                                while (patternIndex < patternLength)
                                                {
                                                    searchingNextChar = this.patternChars[patternIndex];

                                                    if (searchingNextChar >= char_0 && searchingNextChar <= char_9)
                                                    {
                                                        if (searchingCondition)
                                                        {
                                                            group.maxRepetitions = maxRepetitions * 10 + (searchingNextChar - 0x30);
                                                        }
                                                        else
                                                        {
                                                            group.minRepetitions = minRepetitions * 10 + (searchingNextChar - 0x30);
                                                        }
                                                    }
                                                    else if (searchingNextChar == char_Comma)
                                                    {
                                                        searchingCondition = true;
                                                    }
                                                    else if (searchingNextChar == char_RightCurlyBracket)
                                                    {
                                                        break;
                                                    }

                                                    patternIndex++;
                                                }

                                                if (group.maxRepetitions == 0)
                                                    group.maxRepetitions = Int32.MaxValue;
                                                break;
                                        }
                                    }

                                    group.patternEndIndex = patternIndex;
                                }

                                if (group.success)
                                {
                                    group.repetitions++;
                                    group.captureList.Add(new Capture() { index = group.index + group.length, length = searchIndex - group.index - group.length });
                                    group.length = searchIndex - group.index;

                                    //Check if repetitions are completed.
                                    if (group.repetitions < group.maxRepetitions)
                                    {
                                        patternIndex = group.patternBeginIndex;
                                    }
                                    else
                                    {
                                        patternIndex = group.patternEndIndex;

                                        group.captures = new Capture[group.captureList.Count];
                                        group.captureList.CopyTo(group.captures);
                                        group.captureList = null;

                                        //Pop parent group.
                                        group = (Group)groupStack.Pop();
                                    }
                                }
                                //Check if minRepetitions are completed.
                                else if (group.repetitions >= group.minRepetitions)
                                {
                                    patternIndex = group.patternEndIndex;

                                    group.success = true;
                                    group.captures = new Capture[group.captureList.Count];
                                    group.captureList.CopyTo(group.captures);
                                    group.captureList = null;

                                    //Pop parent group.
                                    group = (Group)groupStack.Pop();
                                }
                                else
                                {
                                    patternIndex = group.patternEndIndex;

                                    //Pop parent group.
                                    group = (Group)groupStack.Pop();
                                    group.success = false;
                                }
                                break;
                            case char_LeftSquareBracket:
                                searchingEscaped = false;
                                searchingCondition = false;
                                searchingPreviousChar = (char)0;

                                classChars.Clear();

                                patternIndex++;

                                //Check if the class is negated.
                                if (this.patternChars[patternIndex] == char_CircumflexAccent)
                                {
                                    patternSymbol = symbol_NegatedClass;

                                    patternIndex++;
                                }
                                else
                                {
                                    patternSymbol = symbol_Class;
                                }

                                //Read class chars.
                                while (patternIndex < patternLength)
                                {
                                    searchingNextChar = this.patternChars[patternIndex];

                                    if (searchingEscaped)
                                    {
                                        searchingEscaped = false;

                                        if (searchingNextChar == char_d)
                                        {
                                            for (char symbolRangeByte = char_0; symbolRangeByte <= char_9; symbolRangeByte++)
                                                classChars.Add((char)symbolRangeByte);
                                        }
                                        else if (searchingNextChar == char_w)
                                        {
                                            for (char symbolRangeByte = char_0; symbolRangeByte <= char_9; symbolRangeByte++)
                                                classChars.Add((char)symbolRangeByte);

                                            for (char symbolRangeByte = char_A; symbolRangeByte <= char_Z; symbolRangeByte++)
                                                classChars.Add((char)symbolRangeByte);

                                            for (char symbolRangeByte = char_a; symbolRangeByte <= char_z; symbolRangeByte++)
                                                classChars.Add((char)symbolRangeByte);
                                        }
                                        else if (searchingNextChar == char_s)
                                        {
                                            classChars.Add(char_Space);
                                        }
                                        else if (searchingNextChar == char_r)
                                        {
                                            classChars.Add(char_CarriageReturn);
                                        }
                                        else if (searchingNextChar == char_n)
                                        {
                                            classChars.Add(char_LineFeed);
                                        }
                                        else
                                        {
                                            classChars.Add(searchingNextChar);
                                        }
                                    }
                                    else if (searchingNextChar == char_BackSlash)
                                    {
                                        searchingEscaped = true;
                                    }
                                    else if (searchingNextChar == char_MinusSign)
                                    {
                                        searchingPreviousChar = (char)classChars[classChars.Count - 1];
                                        searchingCondition = true;
                                    }
                                    else if (searchingNextChar == char_RightSquareBracket)
                                    {
                                        comparing = true;

                                        break;
                                    }
                                    else if (searchingCondition)
                                    {
                                        for (byte symbolRangeByte = (byte)(searchingPreviousChar + 1); symbolRangeByte <= searchingNextChar; symbolRangeByte++)
                                            classChars.Add((char)symbolRangeByte);

                                        searchingCondition = false;
                                    }
                                    else
                                    {
                                        classChars.Add(searchingNextChar);
                                    }

                                    patternIndex++;
                                }
                                break;
                            default:
                                patternSymbol = symbol_Char;
                                comparing = true;
                                break;
                        }
                    }

                    if (comparing)
                    {
                        comparing = false;

                        repetitions = 0;
                        minRepetitions = 1;
                        maxRepetitions = 1;

                        //Evaluate repetitions.
                        if (patternIndex + 1 < patternLength)
                        {
                            searchingNextChar = this.patternChars[patternIndex + 1];

                            switch (searchingNextChar)
                            {
                                case char_LeftCurlyBracket:
                                    minRepetitions = 0;
                                    maxRepetitions = 0;

                                    searchingCondition = false;

                                    patternIndex += 2;

                                    while (patternIndex < patternLength)
                                    {
                                        searchingNextChar = this.patternChars[patternIndex];

                                        if (searchingNextChar >= char_0 && searchingNextChar <= char_9)
                                        {
                                            if (searchingCondition)
                                            {
                                                maxRepetitions = maxRepetitions * 10 + (searchingNextChar - 0x30);
                                            }
                                            else
                                            {
                                                minRepetitions = minRepetitions * 10 + (searchingNextChar - 0x30);
                                            }
                                        }
                                        else if (searchingNextChar == char_Comma)
                                        {
                                            searchingCondition = true;
                                        }
                                        else if (searchingNextChar == char_RightCurlyBracket)
                                        {
                                            break;
                                        }

                                        patternIndex++;
                                    }

                                    if (maxRepetitions == 0)
                                        maxRepetitions = Int32.MaxValue;
                                    break;
                                case char_Asterisk:
                                    patternIndex++;

                                    minRepetitions = 0;
                                    maxRepetitions = Int32.MaxValue;
                                    break;
                                case char_PlusSign:
                                    patternIndex++;

                                    minRepetitions = 1;
                                    maxRepetitions = Int32.MaxValue;
                                    break;
                            }
                        }

                        //Check if repetitions are completed.
                        while (repetitions < maxRepetitions)
                        {
                            //Check symbol index.
                            if (searchIndex >= searchLength)
                            {
                                group.success = false;
                            }
                            else
                            {
                                searchingChar = (char)searchList[searchIndex];

                                //Check symbol matching.
                                switch (patternSymbol)
                                {
                                    case symbol_Class:
                                        group.success = classChars.IndexOf(searchingChar) != -1;
                                        break;
                                    case symbol_NegatedClass:
                                        group.success = classChars.IndexOf(searchingChar) == -1;
                                        break;
                                    case symbol_Digit:
                                        group.success = searchingChar >= char_0 && searchingChar <= char_9;
                                        break;
                                    case symbol_WordCharacter:
                                        group.success = (searchingChar >= char_0 && searchingChar <= char_9) || (searchingChar >= char_a && searchingChar <= char_z) || (searchingChar >= char_a && searchingChar <= char_z);
                                        break;
                                    default:
                                        group.success = searchingChar == patternChar;
                                        break;
                                }
                            }

                            if (group.success)
                            {
                                repetitions++;

                                searchIndex++;
                            }
                            //Check if minRepetitions are completed.
                            else if (repetitions >= minRepetitions)
                            {
                                group.success = true;

                                break;
                            }
                            else
                            {
                                break;
                            }
                        }
                    }

                    patternIndex++;

                    if (patternIndex >= patternLength)
                        break;

                    patternChar = this.patternChars[patternIndex];

                    if (!group.success)
                    {
                        if (groupStack.Count == 0 && startAnchored)
                            break;

                        //Search group alternative or end.
                        searchingGroups = 0;
                        searchingEscaped = false;

                        while (patternIndex < patternLength)
                        {
                            searchingNextChar = this.patternChars[patternIndex];

                            if (searchingEscaped)
                            {
                                searchingEscaped = false;
                            }
                            else if (searchingNextChar == char_BackSlash)
                            {
                                searchingEscaped = true;
                            }
                            else if (searchingNextChar == char_LeftParenthesis)
                            {
                                searchingGroups++;
                            }
                            else if (searchingNextChar == char_RightParenthesis)
                            {
                                searchingGroups--;

                                if (searchingGroups < 0)
                                    break;
                            }
                            else if (searchingGroups == 0 && searchingNextChar == char_VerticalLine)
                            {
                                break;
                            }

                            patternIndex++;
                        }

                        if (patternIndex >= patternLength)
                            break;

                        patternChar = this.patternChars[patternIndex];
                    }
                }

                if (match.success && patternIndex >= patternLength)
                {
                    match.length = searchIndex - match.index;
                    match.captures = new Capture[] { new Capture() { index = match.index, length = match.length } };

                    match.groups = new Group[groupList.Count];
                    groupList.CopyTo(match.groups);

                    return match;
                }
                else if (match.index + 1 < searchLength && !startAnchored)
                {
                    escaped = false;
                    comparing = false;
                    startAnchored = false;

                    match.index++;
                    match.success = true;

                    group = match;
                    groupList.Clear();
                    groupList.Add(group);
                    groupStack.Clear();

                    searchIndex = match.index;

                    patternIndex = 0;

                    patternChar = this.patternChars[patternIndex];
                }
                else
                {
                    match.index = 0;

                    break;
                }
            }

            return match;
        }
Exemplo n.º 36
0
        /// <summary>
        /// Draw one line of tooltip text with formatting
        /// </summary>
        /// <param name="g"></param>
        /// <param name="pntStart"></param>
        /// <param name="txt"></param>
        protected virtual void DrawToolTipString( Graphics g, Point pntStart, string txt )
        {
            string  tempString = txt;
              Stack   stack = new Stack();

              ToolTipStringFormatter frmtString = new ToolTipStringFormatter( this );

              stack.Push( frmtString.Clone() );

              do
              {
            Match   mt = m_regex.Match( tempString );

            if( mt.Success == true )
            {
              string pretext  = mt.Groups[1].Value;
              string formatId = mt.Groups[2].Value;
              string text     = mt.Groups[3].Value;

              tempString = tempString.Remove( 0, mt.Groups[0].Value.Length );
              frmtString.CopyFrom( (ToolTipStringFormatter)stack.Peek() );

              DrawStringByFormat( g, ref pntStart, frmtString, pretext );
              DetectFormatting( ref frmtString, formatId );

              if( IsStringWithFormat( text ) )
              {
            stack.Push( frmtString.Clone() );
            tempString = text + "</stack>" + tempString;
            continue;
              }
              else
              {
            int pos = text.IndexOf( "</stack>" );
            int left = pos + "</stack>".Length;

            if( pos != -1 )
            {
              tempString = text.Substring( left, text.Length - left ) + tempString;
              text = text.Substring( 0, pos );
            }

            DrawStringByFormat( g, ref pntStart, frmtString, text );

            if( pos != -1 ) stack.Pop();
              }
            }
            else
            {
              int pos = 0;

              while( -1 != ( pos = tempString.IndexOf( "</stack>" ) ) )
              {
            int left = pos + "</stack>".Length;
            string text = tempString.Substring( 0, pos );

            tempString = tempString.Substring( left, tempString.Length - left );

            DrawStringByFormat( g, ref pntStart, (ToolTipStringFormatter)stack.Peek(), text );
            stack.Pop();
              }

              DrawStringByFormat( g, ref pntStart, (ToolTipStringFormatter)stack.Peek(), tempString );
              tempString = "";
            }

            if( tempString.Length == 0 ) break;
              }
              while( true );

              stack.Clear();
        }
Exemplo n.º 37
0
        private void getSubEntities()
        {
            uint length;
            List<int> clusters = fat.getClusterTail(FirstClusterOfFile);
            int numberOfBytesPerCluster = fat.SectorsPerCluster * fat.BytesPerSector;
            byte[] buffer = new byte[clusters.Count() * numberOfBytesPerCluster];
            subDirectories.Clear();
            subFiles.Clear();
            for (int i = 0; i < clusters.Count(); i++)
            {
                byte[] temp = IO.read(fat.HandleFile, clusters[i], fat.ClusterSize, fat);
                for (int j = 0; j < temp.Length; j++)
                {
                    buffer[i * numberOfBytesPerCluster + j] = temp[j];
                }
            }

            Stack<byte[]> longName = new Stack<byte[]>();
            for (int i = 0; i < buffer.Length; i += 32)
            {
                if (buffer[i] == 0)
                {
                    //no more entity beyond
                    break;
                }
                else if (buffer[i + 11] == 0x0f)
                {
                    longName.Push(buffer.ToList().GetRange(i, 32).ToArray());
                }
                else
                {
                    Entity temp = new Entity(buffer.ToList().GetRange(i, 32).ToArray(), fat, clusters[(i + 1) / numberOfBytesPerCluster], this);
                    string tempName = null;
                    for (; longName.Count != 0; )
                    {
                        var x = longName.Pop();
                        tempName += Encoding.Unicode.GetString(x.ToList().GetRange(1, 10).ToArray()) +
                                    Encoding.Unicode.GetString(x.ToList().GetRange(14, 12).ToArray()) +
                                    Encoding.Unicode.GetString(x.ToList().GetRange(28, 4).ToArray());
                    }
                    temp.LongName = tempName != null ? tempName.Split('\0')[0] : null;
                    if (temp.Attribute.IsDirectory)
                    {
                        Directory di = new Directory(buffer.ToList().GetRange(i, 32).ToArray(), fat, clusters[(i + 1) / numberOfBytesPerCluster], this);
                        di.LongName = tempName != null ? tempName.Split('\0')[0] : null;
                        subDirectories.Add(di);
                    }
                    else
                    {
                        File fi = new File(buffer.ToList().GetRange(i, 32).ToArray(), fat, clusters[(i + 1) / numberOfBytesPerCluster], this);
                        fi.LongName = tempName != null ? tempName.Split('\0')[0] : null;
                        subFiles.Add(fi);
                    }
                    longName.Clear();
                }
            }
        }
Exemplo n.º 38
0
        /// <summary>
        /// Alternate entry point for starting the parser.
        /// </summary>
        /// <param name="emitHandT">Indicates if the emitter should be told to emit headers
        /// and trailers before and after emitting the iCalendar body</param>
        public void Parse(bool emitHandT)
        {
            stack = new Stack();
            linenumber = 0;
            attributes = new Stack();  // a stack of key-value pairs (implemented as a stack of DitionaryEntry)

            if (emitHandT)
            {
                emitter.doIntro();
            }

            // each time through the loop will get a single (maybe folded) line
            while (true)
            {
                // check for termination condition
                if (scanner.isEOF())
                {
                    // end of file - do cleanup and go
                    break;
                }

                // empty the attribute stack and the iprop value...
                attributes.Clear();
                iprop = null;
                id = null;

                //FIXME: linenumber doesn't really keep track of actual line numbers because
                //       it is not aware of folded lines...
                linenumber++;

                //DEBUG: emit line number
                //emitter.emit( linenumber + ". " );

                if (!parseID())
                {
                    continue;
                }

                // we now have to parse a set of attributes (semi-colon separated) or
                // a value (delimited by a colon)
                Token sep = scanner.GetNextToken(ScannerState.ParseSimple);
                if (sep == null || sep.TokenVal == TokenValue.Error)
                {
                    // some kind of error - skip rest of line and continue
                    reportError(scanner, " expecting : or ; after id - found nothing.");
                    continue;
                }
                else if (sep.TokenVal == TokenValue.SemiColon)
                {
                    if (!parseAttributes(scanner))
                    {
                        continue;
                    }

                    // now we have to parse the value
                    sep = scanner.GetNextToken(ScannerState.ParseSimple);
                    if (!parseValue())
                    {
                        continue;
                    }
                }
                else if (sep.TokenVal == TokenValue.Colon)
                {
                    if (!parseValue())
                    {
                        continue;
                    }
                }
                else
                {
                    reportError(scanner, "expecting : or ; after id - found: " + sep.TokenText);
                    continue;
                }

                // now sploosh out the attributes (if any) and finish the ID tag
                while (attributes.Count > 0)
                {
                    DictionaryEntry entry = (DictionaryEntry)attributes.Pop();
                    Token key = (Token)entry.Key;
                    Token val = (Token)entry.Value;
                    emitter.doAttribute(key, val);
                }

                emitter.doEnd(id);
            }

            if (emitHandT)
            {
                emitter.doOutro();
            }
        }
Exemplo n.º 39
0
 public static void PrepareDraw()
 {
     Stack.Clear();
     //CellNextX = CellNextY = 0;
 }