Exemple #1
0
 /// <summary>
 /// Gets the first instance of a set of brackets in a string.
 /// </summary>
 /// <param name="html">The string in which the brackets should be located.</param>
 /// <param name="brackets">The type of brackets to look for.</param>
 /// <param name="CutBrackets">true, if the brackets should be removed from the return value; otherwise, false.</param>
 /// <returns>A <see cref="String"/> containing the brackets and their content.</returns>
 public static string CutToBrackets(this string html, Brackets brackets, bool CutBrackets)
 {
     switch (brackets)
     {
         case Brackets.Round:
             return cutToBrackets(html, '(', ')', CutBrackets);
         case Brackets.Square:
             return cutToBrackets(html, '[', ']', CutBrackets);
         case Brackets.Curly:
             return cutToBrackets(html, '{', '}', CutBrackets);
         case Brackets.Angle:
             return cutToBrackets(html, '\u3008', '\u3009', CutBrackets);
         case Brackets.Inequality:
             return cutToBrackets(html, '(', ')', CutBrackets);
         default:
             throw new ArgumentOutOfRangeException("brackets", "Unknown value '" + brackets.ToString() + "' for parameter 'brackets'.");
     }
 }
        /// <summary>
        /// Adds a Bracket object to the list of Brackets.
        /// If the list already contains this Bracket, an exception is thrown.
        /// </summary>
        /// <param name="_bracket">Bracket to add</param>
        public void AddBracket(IBracket _bracket)
        {
            if (null == _bracket)
            {
                throw new ArgumentNullException("_bracket");
            }
            if (null == Brackets)
            {
                throw new NullReferenceException
                          ("Bracket list is null; this shouldn't happen...");
            }
            if (Brackets.Contains(_bracket))
            {
                throw new DuplicateObjectException
                          ("Tournament already contains this Bracket!");
            }

            Brackets.Add(_bracket);
        }
Exemple #3
0
        private static void CreateFunctions()
        {
            Functions    = new List <Function>();
            Constants    = new List <Constant>();
            MainFunction = new MainFunction();
            for (int i = 0; i < Data.Code.Lines.Length; i++)
            {
                Word[] words = Data.Code[i];
                if (words.Length == 0)
                {
                    continue;
                }
                if (Split.IsTag(words[0].Text))
                {
                    continue;
                }
                if (words[0].Text == "")
                {
                    continue;
                }
                if (Word.Contains(words, Data.FUNCTION))
                {
                    int end = Brackets.GetCloseCurveBracketIndex(Data.Code.Lines, i + 1);
                    Functions.Add(new Function(i, end, words));
                    i = end;
                }
                else
                {
                    int end = MainFunctionEnd(i);
                    MainFunction.AddLines(i, end);
                    i = end;
                }
            }

            List <Function> onlyOutputtingFunctions = GetFunctionsThatAreOnlyForOutput();

            foreach (Function function in Functions)
            {
                function.DefineIsOnlyForOutputting(ref onlyOutputtingFunctions);
            }
        }
Exemple #4
0
        public static List <int> CASE_And_DEFAULT_LinesIndexesOf_SWITCH_Block(CodeBlock SWITCH_Block)
        {
            List <int> list = new List <int>();

            for (int i = SWITCH_Block.StartLine + 1; i <= SWITCH_Block.EndLine; i++)
            {
                if (Data.Code[i].Length == 0)
                {
                    continue;
                }
                if (Data.Code[i][0].Text == Data.SWITCH.Text)
                {
                    i = Brackets.GetCloseCurveBracketIndex(Data.Code.Lines, i + 1);
                }
                if (Data.Code[i][0].Text == Data.CASE.Text || Data.Code[i][0].Text == Data.DEFAULT.Text)
                {
                    list.Add(i);
                }
            }
            return(list);
        }
Exemple #5
0
        /// <inheritdoc/>
        public override string[] GetExpressions()
        {
            List <string> expressions = new List <string>();

            expressions.AddRange(base.GetExpressions());

            if (AllowExpressions && !String.IsNullOrEmpty(Brackets))
            {
                string[] brackets = Brackets.Split(new char[] { ',' });
                // collect expressions found in the text
                expressions.AddRange(CodeUtils.GetExpressions(Text, brackets[0], brackets[1]));
            }

            // add highlight conditions
            foreach (HighlightCondition condition in Highlight)
            {
                expressions.Add(condition.Expression);
            }

            return(expressions.ToArray());
        }
Exemple #6
0
        public IEnumerable <Token <R> > ReadToScopeClose(R open, R close, Brackets bracketPairs)
        {
            SkipSpace();
            _stack.Clear();
            Token <R> token = null;

            while (!End)
            {
                token = ReadToken();
                if (bracketPairs.ContainsOpening(token.ID) || open == token.ID) // Allows nesting
                {
                    _stack.Push(token);
                }
                else if (bracketPairs.ContainsClosing(token.ID) || token.ID == close) // Allows nesting
                {
                    // Since this method assumes that the first opening bracket was already read, an empty _stack indicates main scope closure.
                    if (!_stack.Any() && token.ID == close)
                    {
                        yield break;
                    }

                    var lastOpening = _stack.Pop();

                    if (!bracketPairs.Contains(lastOpening.ID, token.ID))
                    {
                        throw new RantException(_source, token,
                                                "Invalid closure '"
                                                + lastOpening.Value
                                                + " ... "
                                                + token.Value
                                                + "' - expected '"
                                                + RantLexer.Rules.GetSymbolForId(bracketPairs.GetClosing(lastOpening.ID))
                                                + "'");
                    }
                }
                yield return(token);
            }
            throw new RantException(_source, null, "Unexpected end of file - expected '" + RantLexer.Rules.GetSymbolForId(close) + "'.");
        }
Exemple #7
0
        public static List <Employee> ContractorPayrollDemo()
        {
            Dictionary <string, decimal[]> taxBrackets = Brackets.Table();

            List <Employee> employees = new List <Employee>();

            for (int i = 0; i < 10; i++)
            {
                string  idNumber, state;
                decimal hoursWorked, hourlyRate;

                do
                {
                    Console.WriteLine("\nPlease enter ID:");
                    idNumber = Console.ReadLine();
                }while (!int.TryParse(idNumber, out _));

                do
                {
                    Console.WriteLine("\nPlease enter state:");
                    state = Console.ReadLine();
                }while (!taxBrackets.ContainsKey(state));

                do
                {
                    Console.WriteLine("\nPlease enter number of hours worked:");
                }while (!decimal.TryParse(Console.ReadLine(), out hoursWorked));

                do
                {
                    Console.WriteLine("\nPlease enter hourly rate:");
                }while (!decimal.TryParse(Console.ReadLine(), out hourlyRate));

                employees.Add(new Employee(idNumber, hoursWorked, hourlyRate, state));
            }

            return(employees);
        }
Exemple #8
0
        /// <summary>
        /// Locates the first instance of a set of brackets in a string.
        /// </summary>
        /// <param name="html">The string in which the brackets should be located.</param>
        /// <param name="brackets">The type of brackets to look for.</param>
        /// <param name="includeBrackets">true, if the brackets should be included in the return value; otherwise, false.</param>
        /// <returns>A <see cref="StringIndex"/> determining the position of the first and last bracket within the string.</returns>
        public static StringIndex FindBrackets(this string html, Brackets brackets, bool includeBrackets)
        {
            switch (brackets)
            {
            case Brackets.Round:
                return(findBrackets(html, '(', ')', includeBrackets));

            case Brackets.Square:
                return(findBrackets(html, '[', ']', includeBrackets));

            case Brackets.Curly:
                return(findBrackets(html, '{', '}', includeBrackets));

            case Brackets.Angle:
                return(findBrackets(html, '\u3008', '\u3009', includeBrackets));

            case Brackets.Inequality:
                return(findBrackets(html, '(', ')', includeBrackets));

            default:
                throw new ArgumentOutOfRangeException("brackets", "Unknown value '" + brackets.ToString() + "' for parameter 'brackets'.");
            }
        }
        public StringParser CutToBrackets(Brackets brackets, bool CutBrackets)
        {
            switch (brackets)
            {
            case Brackets.Round:
                return(CutToBrackets('(', ')', CutBrackets));

            case Brackets.Square:
                return(CutToBrackets('[', ']', CutBrackets));

            case Brackets.Curly:
                return(CutToBrackets('{', '}', CutBrackets));

            case Brackets.Angle:
                return(CutToBrackets('\u3008', '\u3009', CutBrackets));

            case Brackets.Inequality:
                return(CutToBrackets('(', ')', CutBrackets));

            default:
                throw new ArgumentOutOfRangeException("brackets", "Unknown value '" + brackets.ToString() + "' for parameter 'brackets'.");
            }
        }
        private void TabulateSwitch(ref int i, string startOffset)
        {
            int start = i;
            int end   = Brackets.GetCloseCurveBracketIndex(lines, start);

            for (i = i + 1; i < end; i++)
            {
                string trimmedCurrent  = Line.TrimmedLine(lines[i]);
                string trimmedPrevious = Line.TrimmedLine(lines[i - 1]);
                if (Line.Is_SWITCH_Label(trimmedCurrent))
                {
                    lines[i] = startOffset + trimmedCurrent;
                }
                else if (Line.Is_SWITCH_Label(trimmedPrevious))
                {
                    lines[i] = startOffset + "\t" + trimmedCurrent;
                }
                else
                {
                    TabulateLine(ref i);
                }
            }
        }
Exemple #11
0
        /// <inheritdoc/>
        public override void GetData()
        {
            base.GetData();

            // process expressions
            if (AllowExpressions)
            {
                if (!String.IsNullOrEmpty(Brackets))
                {
                    string[]     brackets = Brackets.Split(new char[] { ',' });
                    FindTextArgs args     = new FindTextArgs();
                    args.Text         = new FastString(Text);
                    args.OpenBracket  = brackets[0];
                    args.CloseBracket = brackets[1];
                    int expressionIndex = 0;

                    while (args.StartIndex < args.Text.Length)
                    {
                        string expression = CodeUtils.GetExpression(args, false);
                        if (expression == "")
                        {
                            break;
                        }

                        string formattedValue = CalcAndFormatExpression(expression, expressionIndex);
                        args.Text        = args.Text.Remove(args.StartIndex, args.EndIndex - args.StartIndex);
                        args.Text        = args.Text.Insert(args.StartIndex, formattedValue);
                        args.StartIndex += formattedValue.Length;
                        expressionIndex++;
                    }
                    Text = args.Text.ToString();
                }
            }

            // process highlight
            Variant varValue = new Variant(Value);
        }
        protected virtual Decimal FindWithholding(decimal withheldWages)
        {
            decimal sum = 0.00m;

            foreach (var bracket in Brackets)
            {
                if (withheldWages > bracket.Amount && bracket != Brackets.Last())
                {
                    sum           += bracket.Amount * bracket.Percentage;
                    withheldWages -= bracket.Amount;
                }
                else if (bracket == Brackets.Last())
                {
                    sum += bracket.Percentage * withheldWages;
                }
                else
                {
                    sum += bracket.Percentage * withheldWages;
                    break;
                }
            }

            return(sum);
        }
Exemple #13
0
    // Use this for initialization
    void Start()
    {
        #region Defining Private Fields
        // Defines Camera, fpscontroller, and InteractionBehavior for roomba and player objects
        playerCam = player.GetComponentInChildren <Camera>();
        roombaCam = roomba.GetComponentInChildren <Camera>();

        playerController = player.GetComponent <CustomRigidbodyFPSController>();
        roombaController = roomba.GetComponent <CustomRigidbodyFPSController>();

        playerInteractionBehavior = player.GetComponentInChildren <InteractWithSelectedObject>();
        roombaInteractionBehavior = roomba.GetComponentInChildren <InteractWithSelectedObject>();

        playerDetectInteractionBehavior = player.GetComponentInChildren <DetectInteractableObject>();
        roombaDetectInteractionBehavior = roomba.GetComponentInChildren <DetectInteractableObject>();

        playerCanvas = player.GetComponentInChildren <Canvas>();
        roombaCanvas = roomba.GetComponentInChildren <Canvas>();

        playerBrackets = player.GetComponentInChildren <Brackets>();
        roombaBrackets = roomba.GetComponentInChildren <Brackets>();

        swapEnabled = false;
        #endregion

        // Sets the Roomba and player as active or inactive
        if (roombaIsActive)
        {
            ActivateRoomba();
        }
        else // Sets roomba to inactive, player inactive
        {
            DeactivateRoomba();
        }
        swapCanvas.enabled = false;
    }
Exemple #14
0
        public static ITimeable Build(List <Token> tokens)
        {
            if (Brackets.ContainsIndependentBracketsPairs(tokens, BracketsType.Normal))
            {
                return(null);
            }

            List <Token> tokensCopy = tokens.Select(t => t.Clone()).ToList();

            string name = tokensCopy[0].GetContent().ToLower();

            tokensCopy.RemoveAt(tokensCopy.Count - 1);
            tokensCopy.RemoveAt(0);
            tokensCopy.RemoveAt(0);

            List <Argument> args = ArgumentsExtractor.GetArguments(tokensCopy);

            if (name.Equals("date"))
            {
                return(BuildNumNumNum(name, args));
            }
            else if (name.Equals("newyear") || name.Equals("christmas") || name.Equals("easter"))
            {
                return(BuildNum(name, args));
            }
            else if (name.Equals("access") || name.Equals("creation") || name.Equals("modification"))
            {
                return(BuildStr(name, args));
            }
            else if (name.Equals("tomorrow") || name.Equals("yesterday") || name.Equals("today"))
            {
                return(BuildWithArgs023(name, args));
            }

            return(null);
        }
Exemple #15
0
 /// <summary>
 /// Locates the first instance of a set of brackets in a string. 
 /// Searching for '(' and ')' in "(hello (code) world)" would return "hello (code) world".
 /// </summary>
 /// <param name="html">The string in which the brackets should be located.</param>
 /// <param name="brackets">The type of brackets to look for.</param>
 /// <returns>A <see cref="StringIndex"/> determining the position of the first and last bracket within the string.</returns>
 public static StringIndex FindBrackets(this string html, Brackets brackets)
 {
     return FindBrackets(html, brackets, true);
 }
Exemple #16
0
 /// <summary>
 /// Gets the first instance of a set of brackets in a string. 
 /// Searching for '(' and ')' in "(hello (code) world)" would return "hello (code) world".
 /// </summary>
 /// <param name="html">The string in which the brackets should be located.</param>
 /// <param name="brackets">The type of brackets to look for.</param>
 /// <returns>A <see cref="String"/> containing the content inside the brackets.</returns>
 public static string CutToBrackets(this string html, Brackets brackets)
 {
     return CutToBrackets(html, brackets, false);
 }
Exemple #17
0
        static void Main(string[] args)
        {
            Console.WriteLine($"BinaryGap is {BinaryGap.Solution(9)}");
            Console.WriteLine($"BinaryGap is {BinaryGap.Solution(529)}");
            Console.WriteLine($"BinaryGap is {BinaryGap.Solution(20)}");
            Console.WriteLine($"BinaryGap is {BinaryGap.Solution(15)}");
            Console.WriteLine($"BinaryGap is {BinaryGap.Solution(32)}");
            Console.WriteLine($"BinaryGap is {BinaryGap.Solution(1041)}");
            Console.WriteLine(Environment.NewLine);

            var result = CyclicRotation.Solution(new[] { 1, 2, 3, 4 }, 2);

            Console.WriteLine($"CyclicRotation: {string.Join('-', result)}");
            Console.WriteLine(Environment.NewLine);

            Console.WriteLine($"OddOccurrencesInArray: {OddOccurrencesInArray.Solution(new[] {1, 1, 2, 2, 3, 4, 4})}");
            Console.WriteLine(Environment.NewLine);

            Console.WriteLine($"FrogJmp: {FrogJmp.Solution(10, 85, 30)}");
            Console.WriteLine(Environment.NewLine);

            Console.WriteLine($"PermMissingElem: {PermMissingElem.Solution(new[] {6, 7, 8, 1, 2, 4, 5})}");
            Console.WriteLine(Environment.NewLine);

            Console.WriteLine($"TapeEquilibrium: {TapeEquilibrium.Solution(new[] {3,1,2,4,3})}");
            Console.WriteLine(Environment.NewLine);

            Console.WriteLine($"FrogRiverOne: {FrogRiverOne.Solution(5,new[] {1,3,1,4,2,3,6,5,4})}");
            Console.WriteLine(Environment.NewLine);

            var maxCounter = MaxCounters.Solution(5, new[] { 3, 4, 4, 6, 1, 4, 4 });

            Console.WriteLine($"MaxCounters: {string.Join('-', maxCounter)}");
            Console.WriteLine(Environment.NewLine);

            Console.WriteLine($"MissingInteger: {MissingInteger.Solution(new []{1, 3, 6, 4, 1, 2})}");
            Console.WriteLine(Environment.NewLine);

            Console.WriteLine($"PermCheck: {PermCheck.Solution(new []{4,1,3,2})}");
            Console.WriteLine($"PermCheck: {PermCheck.Solution(new []{4,1,3})}");
            Console.WriteLine(Environment.NewLine);

            Console.WriteLine($"CountDiv: {CountDiv.Solution(11, 345, 17)}");
            Console.WriteLine(Environment.NewLine);

            Console.WriteLine($"PassingCars: {PassingCars.Solution(new []{0,1,0,1,1})}");
            Console.WriteLine(Environment.NewLine);

            // Console.WriteLine($"MinAvgTwoSlice: {MinAvgTwoSlice.Solution(new []{4,2,2,5,1,5,8})}");
            // Console.WriteLine(Environment.NewLine);
            //
            Console.WriteLine($"MaxProductOfThree: {MaxProductOfThree.Solution(new []{-3,1,2,-2,5,6})}");
            Console.WriteLine(Environment.NewLine);

            Console.WriteLine($"Triangle: {Triangle.Solution(new []{10,2,5,1,8,20})}");
            Console.WriteLine($"Triangle: {Triangle.Solution(new []{10,50,5,1})}");
            Console.WriteLine(Environment.NewLine);

            Console.WriteLine($"Brackets: {Brackets.Solution("{[()()]}")}");
            Console.WriteLine($"Brackets: {Brackets.Solution("([)()]")}");
            Console.WriteLine(Environment.NewLine);
        }
Exemple #18
0
 public StringIndex FindBrackets(Brackets brackets, bool includeBrackets)
 {
     switch (brackets)
     {
         case Brackets.Round:
             return FindBrackets('(', ')', includeBrackets);
         case Brackets.Square:
             return FindBrackets('[', ']', includeBrackets);
         case Brackets.Curly:
             return FindBrackets('{', '}', includeBrackets);
         case Brackets.Angle:
             return FindBrackets('\u3008', '\u3009', includeBrackets);
         case Brackets.Inequality:
             return FindBrackets('(', ')', includeBrackets);
         default:
             throw new ArgumentOutOfRangeException("brackets", "Unknown value '" + brackets.ToString() + "' for parameter 'brackets'.");
     }
 }
Exemple #19
0
        public static IRightValue Parse(ISyntaxNode parent, ref string Input)
        {
            string temp = Input;

            System.Text.RegularExpressions.Regex endRegEx      = new System.Text.RegularExpressions.Regex("^\\s*$");
            System.Text.RegularExpressions.Regex bracketsRegEx = new System.Text.RegularExpressions.Regex("^\\s*\\)\\s*");
            System.Text.RegularExpressions.Regex commaRegEx    = new System.Text.RegularExpressions.Regex("^\\s*,\\s*");

            IRightValue highestNode = null;

            while ((!endRegEx.IsMatch(Input)) && (!bracketsRegEx.IsMatch(Input)) && (!commaRegEx.IsMatch(Input)))
            {
                IntegerConstant iconst = TryParse <IntegerConstant>(parent, ref Input);
                if (iconst != null)
                {
                    if (highestNode != null)                     // Function calls can only be the first one.
                    {
                        throw new SyntaxException("Syntax error: Invalid rvalue before integer constant.");
                    }
                    highestNode = iconst;
                    continue;
                }

                FloatingConstant fconst = TryParse <FloatingConstant>(parent, ref Input);
                if (fconst != null)
                {
                    if (highestNode != null)                     // Function calls can only be the first one.
                    {
                        throw new SyntaxException("Syntax error: Invalid rvalue before floating constant.");
                    }
                    highestNode = fconst;
                    continue;
                }

                FunctionCall fcall = TryParse <FunctionCall>(parent, ref Input);
                if (fcall != null)
                {
                    if (highestNode != null)                     // Function calls can only be the first one.
                    {
                        throw new SyntaxException("Syntax error: Invalid rvalue before function call.");
                    }
                    highestNode = fcall;
                    continue;
                }


                //string tmp = Input;
                IBinaryOperator binop = IBinaryOperator.Parse(parent, ref Input, highestNode);
                if (binop != null)
                {
                    //	Input = tmp;

                    if (highestNode == null)                     // Function calls can only be the first one.
                    {
                        throw new SyntaxException("Syntax error: Missing first operand for binary operator.");
                    }
                    highestNode = binop;
                    continue;
                }

                IUnaryOperator unop = IUnaryOperator.Parse(parent, ref Input, highestNode);
                if (unop != null)
                {
                    if ((unop.Position == OperatorPosition.Postfix) && (highestNode == null))                     // Function calls can only be the first one.
                    {
                        throw new SyntaxException("Syntax error: Missing first operand for unary operator.");
                    }
                    highestNode = unop;
                    continue;
                }

                Brackets backets = TryParse <Brackets>(parent, ref Input);
                if (backets != null)
                {
                    if (highestNode != null)                     // Function calls can only be the first one.
                    {
                        throw new SyntaxException("Syntax error: Invalid rvalue before brackets.");
                    }
                    highestNode = backets;
                    continue;
                }

                //	InfixOperator iopp = TryParse<InfixOperator>(ref Input, delegate(ref string i) { return new InfixOperator(parent, ref i, highestNode); });
                //	if (iopp != null)
                //		highestNode = fcall;

                // Well, if nothing got parsed, then it's a invalid expression
                throw new SyntaxException("Syntax error: Invalid token \"" + Input + "\"");
            }

            if ((highestNode is IOperator) &&
                ((highestNode as IOperator).SecondaryOperand is IOperator) &&
                (highestNode.Priority < (highestNode as IOperator).SecondaryOperand.Priority))
            {
                IOperator higher = (highestNode as IOperator);
                IOperator lower  = (IOperator)higher.SecondaryOperand;

                higher.SecondaryOperand = lower.PrimaryOperand;
                lower.PrimaryOperand    = higher;
                higher = lower;

                highestNode = higher;
            }


            return(highestNode);
        }
Exemple #20
0
        public void AddingAccountToAccountsAddsAccountToList()
        {
            Brackets brackets = new Brackets("()()");

            Assert.AreEqual(brackets.ValidationBracket(), true);
        }
Exemple #21
0
        public static IListable Build(List <Token> tokens)
        {
            // try to build Stringable
            IStringable ist = StringableBuilder.Build(tokens);

            if (!ist.IsNull())
            {
                return(ist as IListable);
            }

            // remove first and last bracket if it is there
            while (tokens[0].GetTokenType().Equals(TokenType.BracketOn) && tokens[tokens.Count - 1].GetTokenType().Equals(TokenType.BracketOff) &&
                   !Brackets.ContainsIndependentBracketsPairs(tokens, BracketsType.Normal))
            {
                List <Token> tokensCopy = tokens.Select(t => t.Clone()).ToList();
                tokensCopy.RemoveAt(tokens.Count - 1);
                tokensCopy.RemoveAt(0);
                tokens = tokensCopy;
            }

            // try to build 'empty list'
            if (tokens.Count == 2 && tokens[0].GetTokenType().Equals(TokenType.Variable) && tokens[1].GetTokenType().Equals(TokenType.Variable) &&
                tokens[0].GetContent().ToLower().Equals("empty") && tokens[1].GetContent().ToLower().Equals("list"))
            {
                return(new EmptyList());
            }

            // try to build small arrow function
            if (tokens.Where(t => t.GetTokenType().Equals(TokenType.SmallArrow)).Count() == 1)
            {
                IListable smallArrow = BuildSmallArrowFunction(tokens);
                if (!smallArrow.IsNull())
                {
                    return(smallArrow);
                }
            }

            string str = tokens[0].GetContent();

            // try to build list variable reference - just one word and it is a name
            if (tokens.Count == 1 && tokens[0].GetTokenType().Equals(TokenType.Variable) && InterVariables.GetInstance().Contains(str, InterVarType.List))
            {
                return(new ListVariableRefer(str));
            }

            // try to build list expression
            if (InterVariables.GetInstance().Contains(str, InterVarType.List))
            {
                IListable listEx = BuildListExpression(tokens, str);
                if (!listEx.IsNull())
                {
                    return(listEx);
                }
            }

            // try to build list ternary
            if (TernaryBuilder.IsPossibleTernary(tokens))
            {
                IListable ilist = TernaryBuilder.BuildListTernary(tokens);
                if (!ilist.IsNull())
                {
                    return(ilist);
                }
            }

            // try to build listed lists/strings: many Listables/Stringables divided by commas
            if (TokenGroups.ContainsTokenOutsideBrackets(tokens, TokenType.Comma))
            {
                IListable listed = BuildListed(tokens);
                if (!listed.IsNull())
                {
                    return(listed);
                }
            }

            throw new SyntaxErrorException("ERROR! Unknown error in code syntax.");
        }
 /// <summary>
 /// Creates a new Round Robin "Group Stage," and adds it to the bracketlist.
 /// This is just a wrapper method that calls the bracket ctor
 /// and adds the resulting Bracket object to the list.
 /// </summary>
 /// <param name="_playerList">List of Players</param>
 /// <param name="_numGroups">How many groups to divide Players into</param>
 /// <param name="_maxGamesPerMatch">Max games, applied to every Match</param>
 /// <param name="_maxRounds">Limit of rounds to generate (0 = full round robin)</param>
 public void AddRRGroupStage(List <IPlayer> _playerList, int _numGroups = 2, int _maxGamesPerMatch = 1, int _maxRounds = 0)
 {
     Brackets.Add(new RoundRobinGroups(_playerList, _numGroups, _maxGamesPerMatch, _maxRounds));
 }
 /// <summary>
 /// Creates a new Swiss-style Bracket, and adds it to the bracketlist.
 /// This is just a wrapper method that calls the bracket ctor
 /// and adds the resulting Bracket object to the list.
 /// </summary>
 /// <param name="_playerList">List of Players</param>
 /// <param name="_pairingMethod">Method for matchup pairing: Slide, Fold, or Adjacent</param>
 /// <param name="_maxGamesPerMatch">Max games, applied to every Match</param>
 /// <param name="_numRounds">Limit of rounds to generate (0 = full Swiss)</param>
 public void AddSwissBracket(List <IPlayer> _playerList, PairingMethod _pairingMethod = PairingMethod.Slide, int _maxGamesPerMatch = 1, int _numRounds = 0)
 {
     Brackets.Add(new SwissBracket(_playerList, _pairingMethod, _maxGamesPerMatch, _numRounds));
 }
Exemple #24
0
 public void FillNested(Brackets exp)
 {
     _nested = exp;
 }
 /// <summary>
 /// Перевірка на символи
 /// </summary>
 /// <param name="bracket">Дужка</param>
 /// <param name="c">Символ</param>
 /// <returns></returns>
 public static bool IsEquals(this Brackets bracket, char c)
 {
     return((int)bracket == c);
 }
Exemple #26
0
 /// <summary>
 /// Gets the first instance of a set of brackets in a string.
 /// Searching for '(' and ')' in "(hello (code) world)" would return "hello (code) world".
 /// </summary>
 /// <param name="html">The string in which the brackets should be located.</param>
 /// <param name="brackets">The type of brackets to look for.</param>
 /// <returns>A <see cref="String"/> containing the content inside the brackets.</returns>
 public static string CutToBrackets(this string html, Brackets brackets)
 {
     return(CutToBrackets(html, brackets, false));
 }
Exemple #27
0
        public IEnumerable <IEnumerable <Token <R> > > ReadMultiItemScope(R open, R close, R separator, Brackets bracketPairs)
        {
            SkipSpace();
            _stack.Clear();

            // Assumes first bracket was already read.
            _stack.Push(new Token <R>(open, RantLexer.Rules.GetSymbolForId(open)));

            int       start = _pos;
            Token <R> token = null;

            while (!End)
            {
                // Peek but don't consume - this saves some calculations later on.
                token = PeekToken();

                // Opening bracket
                if (bracketPairs.ContainsOpening(token.ID) || open == token.ID) // Previous bracket allows nesting
                {
                    _stack.Push(token);
                }

                // Closing bracket
                else if (bracketPairs.ContainsClosing(token.ID) || close == token.ID) // Previous bracket allows nesting
                {
                    var lastOpening = _stack.Pop();

                    // Handle invalid closures
                    if (!bracketPairs.Contains(lastOpening.ID, token.ID)) // Not in main pair
                    {
                        throw new RantException(_source, token,
                                                "Invalid closure '"
                                                + lastOpening.Value
                                                + " ... "
                                                + token.Value
                                                + "' - expected '"
                                                + RantLexer.Rules.GetSymbolForId(bracketPairs.GetClosing(lastOpening.ID))
                                                + "'");
                    }

                    // If the _stack is empty, this is the last item. Stop the iterator.
                    if (!_stack.Any())
                    {
                        yield return(_tokens
                                     .SkipWhile((t, i) => i < start)        // Cut to start of section
                                     .TakeWhile((t, i) => i < _pos - start) // Cut to end of section
                                     .SkipWhile(t => t.ID == R.Whitespace)  // Remove leading whitespace
                                     .Reverse()                             // Reverse to trim end
                                     .SkipWhile(t => t.ID == R.Whitespace)  // Remove trailing whitespace
                                     .Reverse()                             // Reverse back
                                     .ToArray());

                        _pos++;
                        yield break;
                    }
                }

                // Separator
                else if (token.ID == separator && _stack.Count == 1)
                {
                    yield return(_tokens
                                 .SkipWhile((t, i) => i < start)        // Cut to start of section
                                 .TakeWhile((t, i) => i < _pos - start) // Cut to end of section
                                 .SkipWhile(t => t.ID == R.Whitespace)  // Remove leading whitespace
                                 .Reverse()                             // Reverse to trim end
                                 .SkipWhile(t => t.ID == R.Whitespace)  // Remove trailing whitespace
                                 .Reverse()                             // Reverse back
                                 .ToArray());

                    _pos++;
                    start = _pos;
                    continue;
                }

                // Move to next position
                _pos++;
            }
            throw new RantException(_source, null, "Unexpected end of file - expected '" + RantLexer.Rules.GetSymbolForId(close) + "'.");
        }
Exemple #28
0
 public StringParser CutToBrackets(Brackets brackets)
 {
     return CutToBrackets(brackets, false);
 }
Exemple #29
0
 public static bool IsNotBracketed(this string text, Brackets brackets)
 {
     return(text.IsNotBracketed(brackets.Opening, brackets.Closing));
 }
Exemple #30
0
 public StringIndex FirdBrackets(Brackets brackets)
 {
     return FindBrackets(brackets, true);
 }
        public void ShouldWork(string input, int expectedResult)
        {
            var result = Brackets.IsNested(input);

            Assert.Equal(expectedResult, result);
        }
Exemple #32
0
 public void Parse(ExpressionParserHelper parseHelper)
 {
     if (parseHelper.At(BRACKETS_OPEN))
     {
         var token = parseHelper.Current;
         parseHelper.Expect(BRACKETS_OPEN);
         var brackets = new Brackets(_functionArgument, _arguments) {Token = token};
         parseHelper.Push(brackets);
         parseHelper.ParseExpression();
     }
     else
     {
         parseHelper.Reduce(TYPE);
         var nested = parseHelper.Pop();
         parseHelper.Expect(nameof(BracketsParser), BRACKETS_CLOSE, BRACKETS_COMMA);
         var brackets = ((Brackets) parseHelper.Top);
         brackets.FillNext(nested);
         if (parseHelper.At(BRACKETS_CLOSE) && brackets.PartOfFunction)
         {
             FunctionParser.FillArguments(parseHelper);
         }
     }
 }
 internal string GetTextWithBrackets(string text)
 {
     string[] brackets = Brackets.Split(new char[] { ',' });
     return(brackets[0] + text + brackets[1]);
 }
Exemple #34
0
 public void FillNested(Brackets exp)
 {
     _nested = exp;
 }
Exemple #35
0
 /// <summary>
 /// Locates the first instance of a set of brackets in a string.
 /// Searching for '(' and ')' in "(hello (code) world)" would return "hello (code) world".
 /// </summary>
 /// <param name="html">The string in which the brackets should be located.</param>
 /// <param name="brackets">The type of brackets to look for.</param>
 /// <returns>A <see cref="StringIndex"/> determining the position of the first and last bracket within the string.</returns>
 public static StringIndex FindBrackets(this string html, Brackets brackets)
 {
     return(FindBrackets(html, brackets, true));
 }
        public static IBoolable Build(List <Token> tokens)
        {
            /// INITIAL CHECKING

            // check is is empty
            if (tokens.Count == 0)
            {
                throw new SyntaxErrorException("ERROR! Variable declaration is empty.");
            }

            // check if contains not allowed tokens
            Token wwtok = TokenGroups.WrongTokenInExpression(tokens);

            if (!wwtok.GetTokenType().Equals(TokenType.Null))
            {
                return(null);
            }

            // check brackets
            if (!Brackets.CheckCorrectness(tokens))
            {
                return(null);
            }

            // remove first and last bracket if it is there
            while (tokens[0].GetTokenType().Equals(TokenType.BracketOn) && tokens[tokens.Count - 1].GetTokenType().Equals(TokenType.BracketOff) &&
                   !Brackets.ContainsIndependentBracketsPairs(tokens, BracketsType.Normal))
            {
                List <Token> tokensCopy = tokens.Select(t => t.Clone()).ToList();
                tokensCopy.RemoveAt(tokens.Count - 1);
                tokensCopy.RemoveAt(0);
                tokens = tokensCopy;
            }

            // check is is empty again after removing brackets
            if (tokens.Count == 0)
            {
                throw new SyntaxErrorException("ERROR! Variable declaration is empty.");
            }

            /// BOOL BUILDING

            // try to build simple one-element Boolable
            if (tokens.Count == 1)
            {
                if (tokens[0].GetTokenType().Equals(TokenType.Variable))
                {
                    string str = tokens[0].GetContent();
                    if (InterVariables.GetInstance().Contains(str, InterVarType.Bool))
                    {
                        return(new BoolVariableRefer(str));
                    }
                    else
                    {
                        return(null);
                    }
                }
                if (tokens[0].GetTokenType().Equals(TokenType.BoolConstant))
                {
                    if (tokens[0].GetContent().Equals("true"))
                    {
                        return(new BoolConstant(true));
                    }
                    else
                    {
                        return(new BoolConstant(false));
                    }
                }
            }

            // try to build IN function
            if (TokenGroups.ContainsTokenOutsideBrackets(tokens, TokenType.In))
            {
                IBoolable iboo = BuildIn(tokens);
                if (!iboo.IsNull())
                {
                    return(iboo);
                }
            }

            // try to build LIKE function
            if (TokenGroups.ContainsTokenOutsideBrackets(tokens, TokenType.Like))
            {
                IBoolable iboo = BuildLike(tokens);
                if (!iboo.IsNull())
                {
                    return(iboo);
                }
            }

            // try to build BETWEEN function
            if (TokenGroups.ContainsTokenOutsideBrackets(tokens, TokenType.And) &&
                TokenGroups.ContainsTokenOutsideBrackets(tokens, TokenType.Between))
            {
                IBoolable iboo = BuildBetween(tokens);
                if (!iboo.IsNull())
                {
                    return(iboo);
                }
            }

            // try to build time comparison IS AFTER/IS BEFORE
            if (ContainsOneTimeComparingToken(tokens))
            {
                IBoolable iboo = BuildTimeComparison(tokens);
                if (!iboo.IsNull())
                {
                    return(iboo);
                }
            }

            // try to build comparison = != > < >= <=
            if (ContainsOneComparingToken(tokens))
            {
                IBoolable iboo = BuildComparison(tokens);
                if (!iboo.IsNull())
                {
                    return(iboo);
                }
            }

            // try to build bool ternary
            if (TernaryBuilder.IsPossibleTernary(tokens))
            {
                IBoolable iboo = TernaryBuilder.BuildBoolTernary(tokens);
                if (!iboo.IsNull())
                {
                    return(iboo);
                }
            }

            // try to build bool function
            if (Functions.IsPossibleFunction(tokens))
            {
                IBoolable iboo = BoolFunction.Build(tokens);
                if (!iboo.IsNull())
                {
                    return(iboo);
                }
            }

            // try to build expression: many elements with operators or, and, xor, not
            if (ContainsLogicTokens(tokens))
            {
                return(BuildExpression(tokens));
            }
            else
            {
                return(null);
            }
        }
Exemple #37
0
        public static ITimeable Build(List <Token> tokens)
        {
            // remove first and last bracket if it is there
            while (tokens[0].GetTokenType().Equals(TokenType.BracketOn) && tokens[tokens.Count - 1].GetTokenType().Equals(TokenType.BracketOff) &&
                   !Brackets.ContainsIndependentBracketsPairs(tokens, BracketsType.Normal))
            {
                List <Token> tokensCopy = tokens.Select(t => t.Clone()).ToList();
                tokensCopy.RemoveAt(tokens.Count - 1);
                tokensCopy.RemoveAt(0);
                tokens = tokensCopy;
            }

            // try to build simple one-token Timeable
            if (tokens.Count == 1)
            {
                if (tokens[0].GetTokenType().Equals(TokenType.Variable))
                {
                    string str = tokens[0].GetContent();
                    if (InterVariables.GetInstance().Contains(str, InterVarType.Time))
                    {
                        return(new TimeVariableRefer(str));
                    }
                }
            }

            //try to build time function
            if (Functions.IsPossibleFunction(tokens))
            {
                ITimeable itim = TimeFunction.Build(tokens);
                if (!itim.IsNull())
                {
                    return(itim);
                }
            }

            // try to build time ternary
            if (TernaryBuilder.IsPossibleTernary(tokens))
            {
                ITimeable itim = TernaryBuilder.BuildTimeTernary(tokens);
                if (!itim.IsNull())
                {
                    return(itim);
                }
            }

            // try to build relative time expression
            if (tokens.Where(t => IsTimeDirection(t)).Count() > 0)
            {
                ITimeable itim = BuildRelativeTime(tokens);
                if (!itim.IsNull())
                {
                    return(itim);
                }
            }

            if (HasOneComma(tokens))
            {
                // try to build Timeable from date and clock
                ITimeable itim = BuildFromDateAndClock(tokens);
                if (!itim.IsNull())
                {
                    return(itim);
                }
            }
            else
            {
                // try to build Timeable from date only
                if (ContainMonth(tokens))
                {
                    ITimeable itim = BuildFromDate(tokens);
                    if (!itim.IsNull())
                    {
                        return(itim);
                    }
                }

                // try to build Timeable from clock only
                if (ContainSemicolons(tokens))
                {
                    ITimeable itim = BuildFromClock(tokens);
                    if (!itim.IsNull())
                    {
                        return(itim);
                    }
                }
            }

            return(null);
        }
        private static IBoolable BuildExpression(List <Token> tokens)
        {
            // turn list of tokens into list of BoolExpressionElements
            // they are in usual infix notation
            // when this is done, their order is changed to Reverse Polish Notation
            // meanwhile check, if it all can be represented as simple one negated IBoolable
            // finally build BoolExpression

            List <IBoolExpressionElement> infixList = new List <IBoolExpressionElement>();
            List <Token> currentTokens   = new List <Token>();
            bool         readingFunction = false;
            Token        previousToken   = new Token(TokenType.Null);

            // first, merge many tokens into fewer number of IBoolables
            foreach (Token tok in tokens)
            {
                bool actionDone = false;

                if (TokenGroups.IsLogicSign(tok.GetTokenType()))
                {
                    if (readingFunction)
                    {
                        if (Brackets.AllBracketsClosed(currentTokens))
                        {
                            IBoolable ibo = BoolableBuilder.Build(currentTokens);
                            if (!ibo.IsNull())
                            {
                                infixList.Add(ibo);
                            }
                            else
                            {
                                return(null);
                            }
                            currentTokens.Clear();
                            readingFunction = false;
                            infixList.Add(new BoolExpressionOperator(GetBEOT(tok.GetTokenType())));
                        }
                        else
                        {
                            currentTokens.Add(tok);
                        }
                    }
                    else
                    {
                        if (currentTokens.Count > 0)
                        {
                            IBoolable ibo = BoolableBuilder.Build(currentTokens);
                            if (!ibo.IsNull())
                            {
                                infixList.Add(ibo);
                            }
                            else
                            {
                                return(null);
                            }
                            currentTokens.Clear();
                        }
                        infixList.Add(new BoolExpressionOperator(GetBEOT(tok.GetTokenType())));
                    }
                    actionDone = true;
                }

                if (tok.GetTokenType().Equals(TokenType.BracketOn))
                {
                    if (readingFunction)
                    {
                        currentTokens.Add(tok);
                    }
                    else
                    {
                        if (currentTokens.Count == 1 && previousToken.GetTokenType().Equals(TokenType.Variable))
                        {
                            currentTokens.Add(tok);
                            readingFunction = true;
                        }
                        else
                        {
                            if (currentTokens.Count > 0)
                            {
                                IBoolable ibo = BoolableBuilder.Build(currentTokens);
                                if (!ibo.IsNull())
                                {
                                    infixList.Add(ibo);
                                }
                                else
                                {
                                    return(null);
                                }
                                currentTokens.Clear();
                            }
                            infixList.Add(new BoolExpressionOperator(BoolExpressionOperatorType.BracketOn));
                        }
                    }
                    actionDone = true;
                }

                if (tok.GetTokenType().Equals(TokenType.BracketOff))
                {
                    if (readingFunction)
                    {
                        if (Brackets.AllBracketsClosed(currentTokens))
                        {
                            IBoolable ibo = BoolableBuilder.Build(currentTokens);
                            if (!ibo.IsNull())
                            {
                                infixList.Add(ibo);
                            }
                            else
                            {
                                return(null);
                            }
                            currentTokens.Clear();

                            readingFunction = false;
                            infixList.Add(new BoolExpressionOperator(BoolExpressionOperatorType.BracketOff));
                        }
                        else
                        {
                            currentTokens.Add(tok);
                        }
                    }
                    else
                    {
                        if (currentTokens.Count > 0)
                        {
                            IBoolable ibo = BoolableBuilder.Build(currentTokens);
                            if (!ibo.IsNull())
                            {
                                infixList.Add(ibo);
                            }
                            else
                            {
                                return(null);
                            }
                            currentTokens.Clear();
                        }
                        infixList.Add(new BoolExpressionOperator(BoolExpressionOperatorType.BracketOff));
                    }
                    actionDone = true;
                }

                if (!actionDone)
                {
                    currentTokens.Add(tok);
                }

                previousToken = tok;
            }

            if (currentTokens.Count > 0)
            {
                IBoolable ibo = BoolableBuilder.Build(currentTokens);
                if (!ibo.IsNull())
                {
                    infixList.Add(ibo);
                }
                else
                {
                    return(null);
                }
            }

            // try to build negation of one boolable
            if (infixList.Count == 2 && (infixList[0] is BoolExpressionOperator) && (infixList[1] is IBoolable) &&
                (infixList[0] as BoolExpressionOperator).GetOperatorType().Equals(BoolExpressionOperatorType.Not))
            {
                return(new NegatedBoolable(infixList[1] as IBoolable));
            }

            // check if value of infixlist can be computed (check order of elements)
            if (!CheckExpressionComputability(infixList))
            {
                throw new SyntaxErrorException("ERROR! Wrong syntax of logic expression.");
            }

            // if everything is right, finally build BoolExpression in RPN
            return(new BoolExpression(ReversePolishNotation(infixList)));
        }