示例#1
0
        public static PageMeta Parse(IEnumerable<string> lines)
        {
            var meta = new PageMeta();
            foreach (var line in lines.TakeWhile(line => line.StartsWith(MD_META_PREFIX)))
            {
                var metaType = new string(line.Skip(MD_META_PREFIX.Length).TakeWhile(c => c != ' ').ToArray());
                var content = new string(line.Skip(metaType.Length + 3).ToArray());

                switch (metaType)
                {
                    case "title":
                        meta.Title = content;
                        break;
                    case "date":
                        DateTimeOffset articleDate;
                        if (DateTimeOffset.TryParse(content, out articleDate))
                        {
                            meta.Date = articleDate;
                        }
                        break;
                }
            }

            return meta;
        }
示例#2
0
 static List<DataSample> GetIncidentsReverse(IEnumerable<DataSample> samples, int sessionNumber, int maxTotalIncidents)
 {
     return IncidentsSupport.FindIncidents(
         samples.TakeWhile(data => data.Telemetry.SessionNum == sessionNumber && data.Telemetry.RaceLaps > 0),
         d => iRacing.Replay.MoveToPrevIncident(),
         maxTotalIncidents);
 }
示例#3
0
 static List<DataSample> GetIncidentsForward(IEnumerable<DataSample> samples, int maxTotalIncidents)
 {
     return IncidentsSupport.FindIncidents(
         samples.TakeWhile(data => data.Telemetry.SessionState != SessionState.CoolDown),
         d => iRacing.Replay.MoveToNextIncident(),
         maxTotalIncidents);
 }
示例#4
0
 public Arguments(IEnumerable<string> args, IEnumerable<Option> options)
 {
     if (args == null)
         throw new ArgumentNullException("args");
     Switches = new Dictionary<string, bool?>(StringComparer.CurrentCultureIgnoreCase);
     Variables = new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase);
     Parameters = args;
     Options = options;
     foreach (var argument in Parameters.TakeWhile(item => item.StartsWith("-") &&
                                                   item.Length > 1)) {
         var name = argument.TrimStart('-');
         int colon = name.IndexOf(':');
         if (colon > 0) {
             var value = name.Substring(colon + 1);
             name = name.Substring(0, colon - 1);
             name = GetOptionName(name);
             Variables[name] = value;
         } else {
             name = GetOptionName(name);
             bool? value = null;
             if (name.EndsWith("+")) {
                 name = argument.Substring(0, name.Length - 1);
                 value = true;
             } else if (name.EndsWith("-")) {
                 name = name.Substring(0, name.Length - 1);
                 value = false;
             }
             Switches[name] = value;
         }
     }
     Parameters = Parameters.Skip(Switches.Count + Variables.Count);
 }
示例#5
0
        private ParserContext HandleAction(IEnumerable<string> parts)
        {
            var actionParts = parts.TakeWhile(s => !s.StartsWith("@")).TakeWhile(s => !s.Equals("@@"));

            CurrentParserContext.ContextContent = String.Join(" ", actionParts);

            return CurrentParserContext;
        }
示例#6
0
        static List<DataSample> GetIncidentsForward(IEnumerable<DataSample> samples, int sampleScanSettle, int maxTotalIncidents)
        {
            TraceDebug.WriteLine("Scanning for incidents forwards from start");

            return IncidentsSupport.FindIncidents(
                samples.TakeWhile(data => data.Telemetry.SessionState != SessionState.CoolDown),
                sampleScanSettle,
                maxTotalIncidents);
        }
示例#7
0
 public Result<IEnumerable<Token>, Error> Preprocess(
     IEnumerable<string> arguments,
     Func<IEnumerable<string>, Result<IEnumerable<Token>, Error>> tokenizer)
 {
     if (arguments.Any(arg => arg.EqualsOrdinal("--")))
     {
         var tokenizerResult = tokenizer(arguments.TakeWhile(arg => !arg.EqualsOrdinal("--")));
         var values = arguments.SkipWhile(arg => !arg.EqualsOrdinal("--")).Skip(1).Select(Token.Value);
         return tokenizerResult.Map(tokens => tokens.Concat(values));
     }
     if (arguments.Any(arg => arg.EqualsOrdinal("//")))
     {
         var tokenizerResult = tokenizer(arguments.TakeWhile(arg => !arg.EqualsOrdinal("--")));
         var values = arguments.SkipWhile(arg => !arg.EqualsOrdinal("//")).Skip(1).Select(Token.Value);
         return tokenizerResult.Map(tokens => tokens.Concat(values));
     }
     return tokenizer(arguments);
 }
示例#8
0
 public static StatePair<IEnumerable<Token>> PreprocessDashDash(
     IEnumerable<string> arguments,
     Func<IEnumerable<string>, StatePair<IEnumerable<Token>>> tokenizer)
 {
     if (arguments.Any(arg => arg.EqualsOrdinal("--")))
     {
         var tokenizerResult = tokenizer(arguments.TakeWhile(arg => !arg.EqualsOrdinal("--")));
         var values = arguments.SkipWhile(arg => !arg.EqualsOrdinal("--")).Skip(1).Select(Token.Value);
         return tokenizerResult.MapValue(tokens => tokens.Concat(values));
     }
     return tokenizer(arguments);
 }
 public static DigitSequence Produce(IEnumerable<Symbol> symbols,
 	out IEnumerable<Symbol> symbolsToProcess)
 {
     // digit-sequence = 1*decimal-digit
     IEnumerable<Symbol> digits = symbols.TakeWhile(s =>
         s is DecimalDigit);
     if (digits.Any())
     {
         symbolsToProcess = symbols.Skip(digits.Count());
         return new DigitSequence(digits);
     }
     symbolsToProcess = null;
     return null;
 }
        /// <summary>
        /// Creates a new instance.
        /// </summary>
        /// <param name="parseContext">Parse context</param>
        /// <param name="applicationCommand">Application command</param>
        /// <param name="subConfigurations">Command configurations</param>
        internal AggregatedRuntimeCommand(ParseContext parseContext,
                                          IRuntimeCommand applicationCommand,
                                          IEnumerable <ICommandLineConfiguration>?subConfigurations)
        {
            // Get the matched sub configuration
            var command = subConfigurations?
                          .TakeWhile(_ => parseContext.Reset())
                          .Select(config => config.GetRuntimeCommand())
                          .FirstOrDefault(runtimeCommand => parseContext.TryTakeTemplate(runtimeCommand.Template !, 0));

            if (command != null)
            {
                _runtimeCommands.Add(command);
            }

            _runtimeCommands.Add(applicationCommand);
        }
示例#11
0
 public static Expression Produce(IEnumerable<Symbol> symbols)
 {
     // expression = *whitespace nospace-expression *whitespace
     int numSpaceBefore = symbols.TakeWhile(s => s is WhiteSpace).Count();
     int numSpaceAfter = symbols.Reverse()
         .TakeWhile(s => s is WhiteSpace).Count();
     IEnumerable<Symbol> noSpaceSymbolList = symbols
         .Skip(numSpaceBefore)
         .SkipLast(numSpaceAfter)
         .ToList();
     NoSpaceExpression n = NoSpaceExpression.Produce(noSpaceSymbolList);
     if (null == n)
     {
         return null;
     }
     return new Expression(WhiteSpace.CreateWhiteSpace(numSpaceBefore),
                           n, WhiteSpace.CreateWhiteSpace(numSpaceAfter));
 }
示例#12
0
        public static void ProcessCommits(this IBot bot, string repositoryName ,string lastCommit, IEnumerable<dynamic> commits)
        {
            // find new commits since
            var groupedCommits = commits.TakeWhile(c => c.commit.tree.sha != lastCommit).GroupBy(c => c.committer.login);

            // create string to send as message
            var sb = new StringBuilder();
            sb.AppendFormat("github: there are new commits in the {0} repository\r\n", repositoryName);
            foreach (var committer in groupedCommits)
            {
                sb.AppendFormat("{0} had {1} commits\r\n", committer.Key, committer.Count());
            }

            // split into rows and send to rooms
            var rows = sb.ToString().Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var row in rows)
                bot.SayToAllRooms(row);
        }
示例#13
0
        public static Expression Produce(IEnumerable<Symbol> symbols)
        {
            // expression = *whitespace nospace-expression *whitespace

            var whiteSpaceBefore = symbols.TakeWhile(s => s is WhiteSpace)
                                          .Count();
            var whiteSpaceAfter = symbols.Reverse()
                                         .TakeWhile(s => s is WhiteSpace)
                                         .Count();
            var noSpaceSymbolList = symbols.Skip(whiteSpaceBefore)
                                           .SkipLast(whiteSpaceAfter)
                                           .ToList();  // ToList is vital here!
            var nospaceExpression = NospaceExpression.Produce(noSpaceSymbolList);
            return nospaceExpression == null
                       ? null
                       : new Expression(
                             Enumerable.Repeat(new WhiteSpace(), whiteSpaceBefore),
                             nospaceExpression,
                             Enumerable.Repeat(new WhiteSpace(), whiteSpaceAfter));
        }
示例#14
0
        private static String ParseString(ref IEnumerable<byte> data)
        {
            byte[] sname = data
                        .TakeWhile<byte>(b => b != TK_VAR_SECTION)
                        .ToArray<byte>();

            data = data.Skip<byte>(sname.Length + 1);

            return Encoding.UTF8.GetString(sname);
        }
示例#15
0
文件: Poker.cs 项目: middas/Poker
        private static bool CheckStraight(IEnumerable<Card> cards, List<Card> bestCards)
        {
            bool isStraight = CheckAceHighStraight(cards);

            if (!isStraight)
            {
                int count = 1; //set to 1 to include the first card

                var list = cards.OrderByDescending(c => c.NumberValue).DistinctBy(c => c.NumberValue).ToList();
                for (int i = 0; i < list.Count; i++)
                {
                    if (i + 1 >= list.Count)
                    {
                        break;
                    }

                    if (list[i].NumberValue - list[i + 1].NumberValue == 1)
                    {
                        count++;
                    }
                    else
                    {
                        count = 1;
                    }

                    if (count >= 5)
                    {
                        isStraight = true;

                        i++;

                        while (bestCards.Count < 5)
                        {
                            bestCards.Add(list[i]);
                            i--;
                        }

                        break;
                    }
                }

                if (isStraight && cards.ContainsProperty(c => c.Number == "A"))
                {
                    cards.Where(c => c.Number == "A").ToList().ForEach(c => c.Points = 1);
                }
            }
            else
            {
                bestCards.AddRange(cards.TakeWhile(c =>
                    c.Number == "A" || c.Number == "K" || c.Number == "Q" || c.Number == "J" ||
                    c.Number == "10"));
                bestCards = bestCards.DistinctBy(c => c.Number).ToList();
            }

            return isStraight;
        }
示例#16
0
 public static IEnumerable <T> TakeUntil <T>(this IEnumerable <T> enumerable, Func <T, bool> condition)
 {
     return(enumerable.TakeWhile(x => !condition(x)));
 }
示例#17
0
 private static string Str(this IEnumerable <char> cs) => string.Concat(cs.TakeWhile(char.IsLetter));
示例#18
0
 private static IEnumerable<int> FindTheAnswer(IEnumerable<int> numbers)
 {
     return numbers.TakeWhile(x => x != 42);
 }
 public static IEnumerable <TItem> TakeUntilItemExclusive <TItem>(this IEnumerable <TItem> list, TItem item)
 {
     return(list.TakeWhile(it => !it.Equals(item)));
 }
 public static T GetPrevious <T>(this IEnumerable <T> list, T current, Func <T, T, bool> comparison)
 {
     return(list.TakeWhile(x => !comparison(x, current)).LastOrDefault());
 }
示例#21
0
 private static IEnumerable <char> LeadingNulls(IEnumerable <byte> input)
 {
     return(Enumerable.Range(0, input.TakeWhile(b => b == 0x00).Count()).Select(_ => '0'));
 }
示例#22
0
 private static IEnumerable <byte> LeadingZeros(IEnumerable <char> input)
 {
     return(Enumerable.Range(0, input.TakeWhile(b => b == '0').Count()).Select(_ => (byte)0x00));
 }
示例#23
0
    public static int IndexOf <T>(this IEnumerable <T> enumerable, T item, EqualityComparer <T> comparer)
    {
        int index = enumerable.TakeWhile(x => comparer.Equals(x, item)).Count();

        return(index == enumerable.Count() ? -1 : index);
    }
示例#24
0
 /// <summary>
 ///     Continues processing items in a collection until the end condition is true.
 /// </summary>
 public static IEnumerable <T> TakeUntil <T>(this IEnumerable <T> source, Predicate <T> endCondition)
 {
     return(source.TakeWhile(item => !endCondition(item)));
 }
示例#25
0
        private void LoadMenuFlyoutItem(IList <MenuFlyoutItemBase> MenuItemsList, IEnumerable <Win32ContextMenuItem> menuFlyoutItems, string menuHandle, bool showIcons = true, int itemsBeforeOverflow = int.MaxValue)
        {
            var items_count    = 0; // Separators do not count for reaching the overflow threshold
            var menu_items     = menuFlyoutItems.TakeWhile(x => x.Type == MenuItemType.MFT_SEPARATOR || ++items_count <= itemsBeforeOverflow).ToList();
            var overflow_items = menuFlyoutItems.Except(menu_items).ToList();

            if (overflow_items.Where(x => x.Type != MenuItemType.MFT_SEPARATOR).Any())
            {
                var menuLayoutSubItem = new MenuFlyoutSubItem()
                {
                    Text = "ContextMenuMoreItemsLabel".GetLocalized(),
                    Tag  = ((Win32ContextMenuItem)null, menuHandle),
                    Icon = new FontIcon()
                    {
                        FontFamily = App.Current.Resources["FluentUIGlyphs"] as Windows.UI.Xaml.Media.FontFamily,
                        Glyph      = "\xEAD0"
                    }
                };
                LoadMenuFlyoutItem(menuLayoutSubItem.Items, overflow_items, menuHandle, false);
                MenuItemsList.Insert(0, menuLayoutSubItem);
            }
            foreach (var menuFlyoutItem in menu_items
                     .SkipWhile(x => x.Type == MenuItemType.MFT_SEPARATOR)  // Remove leading seperators
                     .Reverse()
                     .SkipWhile(x => x.Type == MenuItemType.MFT_SEPARATOR)) // Remove trailing separators
            {
                if ((menuFlyoutItem.Type == MenuItemType.MFT_SEPARATOR) && (MenuItemsList.FirstOrDefault() is MenuFlyoutSeparator))
                {
                    // Avoid duplicate separators
                    continue;
                }

                BitmapImage image = null;
                if (showIcons)
                {
                    image = new BitmapImage();
                    if (!string.IsNullOrEmpty(menuFlyoutItem.IconBase64))
                    {
                        byte[] bitmapData = Convert.FromBase64String(menuFlyoutItem.IconBase64);
                        using (var ms = new MemoryStream(bitmapData))
                        {
#pragma warning disable CS4014
                            image.SetSourceAsync(ms.AsRandomAccessStream());
#pragma warning restore CS4014
                        }
                    }
                }

                if (menuFlyoutItem.Type == MenuItemType.MFT_SEPARATOR)
                {
                    var menuLayoutItem = new MenuFlyoutSeparator()
                    {
                        Tag = (menuFlyoutItem, menuHandle)
                    };
                    MenuItemsList.Insert(0, menuLayoutItem);
                }
                else if (menuFlyoutItem.SubItems.Where(x => x.Type != MenuItemType.MFT_SEPARATOR).Any() &&
                         !string.IsNullOrEmpty(menuFlyoutItem.Label))
                {
                    var menuLayoutSubItem = new MenuFlyoutSubItem()
                    {
                        Text = menuFlyoutItem.Label.Replace("&", ""),
                        Tag  = (menuFlyoutItem, menuHandle),
                    };
                    LoadMenuFlyoutItem(menuLayoutSubItem.Items, menuFlyoutItem.SubItems, menuHandle, false);
                    MenuItemsList.Insert(0, menuLayoutSubItem);
                }
                else if (!string.IsNullOrEmpty(menuFlyoutItem.Label))
                {
                    var menuLayoutItem = new MenuFlyoutItemWithImage()
                    {
                        Text       = menuFlyoutItem.Label.Replace("&", ""),
                        Tag        = (menuFlyoutItem, menuHandle),
                        BitmapIcon = image
                    };
                    menuLayoutItem.Click += MenuLayoutItem_Click;
                    MenuItemsList.Insert(0, menuLayoutItem);
                }
            }
        }
示例#26
0
        /// <summary>
        /// Creates an asynchronous Task object that executes the given critical phase and optional phases in a background thread
        /// and invokes all other callbacks on the UI thread.
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <param name="beforeStart">Invoked on UI thread</param>
        /// <param name="criticalPhase">First phase to run.  Must succeed (by returning <c>true</c> and not throwing an exception) for the optional phases to run.  Invoked on the background thread.</param>
        /// <param name="optionalPhases">Collection of phases that can fail (by throwing an exception) without preventing subsequent phases from running.  Invoked on the background thread.</param>
        /// <param name="fail">Called if the operation is canceled or the critical phase throws an exception.  Invoked on the UI thread.</param>
        /// <param name="succeed">Called if the operation completes successfully without being canceled.  Invoked on the UI thread.</param>
        /// <returns>
        /// Task object that returns <c>false</c> if the operation was canceled by the user or
        /// the critical phase threw an exception; otherwise <c>true</c>.
        /// </returns>
        private Task<bool> CreateStageTask(CancellationToken cancellationToken, TaskStartedEventHandler beforeStart, CriticalPhase criticalPhase, IEnumerable<OptionalPhase> optionalPhases, ExceptionEventHandler fail, TaskSucceededEventHandler succeed)
        {
            var canContinue = CreateCanContinueFunc(cancellationToken);
            return new TaskBuilder()
                .OnThread(_callbackScheduler)
                .CancelWith(cancellationToken)
                .BeforeStart(beforeStart)
                .Fail(fail)
                .DoWork(delegate(IThreadInvoker invoker, CancellationToken token)
                    {
                        cancellationToken.Register(() => Logger.Warn("User canceled current operation"));

                        if (criticalPhase())
                        {
                            foreach (var phase in optionalPhases.TakeWhile(phase => canContinue()))
                            {
                                phase();
                            }

                            if (canContinue())
                            {
                                invoker.InvokeOnUIThreadAsync(_ => succeed());
                                return;
                            }
                        }

                        // TODO: How should we handle exceptions here?
                        // The rest of the code assumes exceptions are being handled by the plugin runner.
                        invoker.InvokeOnUIThreadAsync(_ => fail(new ExceptionEventArgs()));
                    })
                .Build()
            ;
        }
示例#27
0
 public static IEnumerable <T> RemoveWhile <T>(this IEnumerable <T> enumerable, Func <T, bool> predicate) => enumerable.Skip(enumerable.TakeWhile(predicate).Count());
        private IEnumerable<IFormulaToken> CompleteOperatorBackwards(IEnumerable<IFormulaToken> tokens, IFormulaOperator operatorToken)
        {
            var operatorOrder = operatorToken.Order;
            return tokens
                .TakeWhile(token => !(token is FormulaTokenParameterSeparator))
                .WithContext()
                .TakeWhile(context =>
                {
                    var nextToken = context[0];
                    var token = context[1];
                    if (token == null) return false;
                    var operatorToken2 = token as IFormulaOperator;

                    var expectValue = nextToken == null || nextToken is FormulaNodeInfixOperator;
                    if (expectValue)
                    {
                        // missing value of operator
                        return operatorToken2 == null;
                    }

                    // operator fully completed
                    return operatorToken2 != null && operatorOrder < operatorToken2.Order;
                }).Select(context => context[1]);
        }
 public static T GetPrevious <T>(this IEnumerable <T> list, T current)
 {
     return(list.TakeWhile(x => !x.Equals(current)).LastOrDefault());
 }
 public static IEnumerable <TItem> TakeUntilItemInclusive <TItem>(this IEnumerable <TItem> list, TItem item) where TItem : class
 {
     return(list.TakeWhile(it => !it.Equals(item)).Append(item));
 }
        private IEnumerable<IFormulaToken> CompleteOperatorForward(IEnumerable<IFormulaToken> tokens, IFormulaOperator operatorToken)
        {
            var operatorOrder = operatorToken.Order;
            return tokens
                .TakeWhile(token => !(token is FormulaTokenParameterSeparator))
                .WithContext()
                .TakeWhile(context =>
                {
                    var previousToken = context[0];
                    var token = context[1];
                    if (token == null) return false;
                    var infixOperatorToken = token as FormulaNodeInfixOperator;

                    var expectValue = previousToken == null || previousToken is IFormulaOperator;
                    if (expectValue)
                    {
                        // missing value of operator
                        return infixOperatorToken == null;
                    }

                    // operator fully completed
                    return infixOperatorToken != null && infixOperatorToken.Order > operatorOrder;
                }).Select(context => context[1]);
        }
        public static void PopulateWithRatings(this List<IUser> users, IEnumerable<IRating> ratings, bool combineDuplicateArtists = false)
        {
            foreach (var rating in ratings.TakeWhile(rating => rating.UserIndex < users.Count))
                users[rating.UserIndex].Ratings.Add(rating);

            if (combineDuplicateArtists)
                users.CombineDuplicateArtists();
        }
示例#33
0
 protected Element(IEnumerable<char> tag)
 {
     IndentLevel = tag.TakeWhile(x => x == ' ').Count();
 }
 private static IEnumerable<string> CreateSegment(IEnumerable<string> current, IEnumerable<string> previous)
 {
     return current.TakeWhile((step, index) => step == previous.ElementAtOrDefault(index)).ToArray();
 }
示例#35
0
 private static int GetIndexOfTab(TabInfo objTab, IEnumerable<TabInfo> tabs)
 {
     return Null.NullInteger + tabs.TakeWhile(tab => tab.TabID != objTab.TabID).Count();
 }
        /// <summary>
        /// sToPop is a member of block, and can be or is the first statement. We see if we can pop it up
        /// a level, and then start a scan for an equivalent statement, marching up the list. If we
        /// find an equivalent statement, we will perform the combination and removal.
        /// </summary>
        /// <param name="block">The block of statements that holds sToPop</param>
        /// <param name="sToPop">The statement to try to up level.</param>
        /// <param name="previousStatements">Statements before this one in this block. This block might not actually contain this statement, in which case we must have this!</param>
        /// <param name="followingStatements">Statements after this one in this block. This block might not actually contain this statement, in which case we must have this!</param>
        /// <returns>True if something was done to the statement, false if we aborted for whatever reason.</returns>
        private static bool FindEquivalentAboveAndCombine(IStatementCompound block, IStatement sToPop,
            IEnumerable<IStatement> previousStatements = null,
            IEnumerable<IStatement> followingStatements = null,
            IStatement betweenStatement = null
            )
        {
            // Can we combine these guys? This is when one sits in the other.
            if (!(block is IStatementLoop) && block.TryCombineStatement(sToPop, new BlockRenamer(sToPop.Parent.FindBookingParent(), block.FindBookingParent())))
            {
                sToPop.FindCompoundParent().Remove(sToPop);
                return false;
            }


            // If we can't get data flow information about a statement, then we can't do anything.
            var sInfo = sToPop as ICMStatementInfo;
            if (sInfo == null)
            {
                return false;
            }

            // For this next step we need to fetch the list of statements above us. Either it has
            // been supplied to us, or we will have to generate it.
            if (previousStatements == null)
            {
                previousStatements = block.Statements.TakeWhile(s => s != sInfo).Reverse();
                followingStatements = block.Statements.SkipWhile(s => s != sInfo).Skip(1);
                betweenStatement = sToPop;
            }

            // Make sure we can get the statement to the top of the block. As we move it
            // forward, we want to also see if we can combine it in a straight-up way
            // with each statement as we go by it.
            bool madeItToTheFront = true;
            foreach (var prevStatement in previousStatements)
            {
                if (MakeStatmentsEquivalent(prevStatement, sToPop))
                {
                    return true;
                }
                if (!StatementCommutes(prevStatement, sToPop))
                {
                    madeItToTheFront = false;
                }
            }

            // Next, lets see if there isn't a statement *after* this one that we can combine it with. However,
            // to do this, we have to move the statements *after* forward previous to this one. So a little painful.
            // No need to do this if we working at the level of the statement: this ground will automatically be covered
            // later in the loop.
            if (betweenStatement != sToPop && betweenStatement is ICMCompoundStatementInfo)
            {
                foreach (var followStatement in followingStatements)
                {
                    if (followStatement is ICMStatementInfo)
                    {
                        // Can we commute this statement from where it is to before the statement we are working on?
                        if (StatementCommutes(followStatement, followingStatements.TakeWhile(f => f != followStatement).Reverse()))
                        {
                            // Next is the tricky part. We are now sitting one down from the block that contains
                            // the sToPop statement. Can we move it up above the block? If the statements are the same,
                            // then we know it is ok to move it pass all the contents of the block (otherwise we would not be here).
                            // But what if it is an if statement, and the if statement depends on something in sToPop? Then
                            // we can't move it.
                            var betweenAsBlock = betweenStatement as ICMCompoundStatementInfo;
                            if (betweenAsBlock.CommutesWithGatingExpressions(followStatement as ICMStatementInfo))
                            {
                                if (MakeStatmentsEquivalent(followStatement, sToPop))
                                {
                                    // To keep continuity and unitarity, this follow statement now has to be moved before the betweenStatement!
                                    var parent = followStatement.Parent as IStatementCompound;
                                    parent.Remove(followStatement);
                                    parent.AddBefore(followStatement, betweenStatement);
                                    return true;
                                }
                            }
                        }
                    }
                }
            }

            // Now the only option left is to pop it up one level. We can do that only if we were able to
            // shift the statement all the way to the front.
            if (!madeItToTheFront)
            {
                return false;
            }

            // The statement can be moved to the top of the block, and isn't the same as
            // anything else we passed. Can we pull it out one level?
            // The key to answering this is: are all the variables it needs defined at the next
            // level up? And if not, are the missing ones simply declared down here and need to be moved up?
            var nParent = block.Parent.FindBookingParent();
            if (nParent == null)
            {
                return false;
            }

            var sDependent = sInfo.DependentVariables;
            var availAtParent = nParent.AllDeclaredVariables.Select(n => n.RawValue).Intersect(sDependent);
            IEnumerable<string> declaredInBlock = Enumerable.Empty<string>();
            if (block is IBookingStatementBlock)
            {
                declaredInBlock = (block as IBookingStatementBlock).DeclaredVariables.Select(np => np.RawValue).Intersect(sDependent);
            }
            if ((availAtParent.Count() + declaredInBlock.Count()) != sDependent.Count())
            {
                return false;
            }

            // If this there is a variable declared in the block internally, then we can't lift it up and out.
            // Also make sure that we can lift it past if there is a gating expression.
            if (block is ICMCompoundStatementInfo)
            {
                var compoundInfo = block as ICMCompoundStatementInfo;
                if (compoundInfo.InternalResultVarialbes.Select(p => p.RawValue).Intersect(sDependent).Any())
                {
                    return false;
                }
                if (!compoundInfo.CommutesWithGatingExpressions(sInfo))
                {
                    return false;
                }
            }

            // If we are going to try to lift past a loop, we have to make sure the statement is idempotent.
            if (block is IStatementLoop && !StatementIdempotent(sToPop))
            {
                return false;
            }

            // And the next figure out where we are in the list of statements.
            var nPrevStatements = nParent.Statements.TakeWhile(ps => ps != block).Reverse();
            var nFollowStatements = nParent.Statements.SkipWhile(ps => ps != block).Skip(1);

            // And repeat one level up with some tail recursion!
            var statementMoved = FindEquivalentAboveAndCombine(nParent, sToPop, nPrevStatements, nFollowStatements, block);

            // There is one other thing to try. If we couldn't move it above us (e.g. statementMoved is false), it could be
            // we can leave the statement here, rather than in its original location.
            if (!statementMoved)
            {
                var parentsToBlock = sToPop
                    .WalkParents(false)
                    .TakeWhile(s => s != block)
                    .Concat(new IStatementCompound[] { block }).ToArray();

                // If no lifting out of some statement between us and the statement, then don't do it.
                var parentsNotOK = parentsToBlock
                    .Where(s => s is ICMCompoundStatementInfo)
                    .Cast<ICMCompoundStatementInfo>()
                    .Where(s => !s.AllowNormalBubbleUp);
                if (parentsNotOK.Any())
                {
                    return false;
                }

                // The next thing we have to double check is that we can do the lifting, and nothing we are going to
                // lift is going to impact some variable.
                var dependents = sInfo.DependentVariables;
                var dependentAffected = parentsToBlock
                    .Select(p => p.CheckForVariableAsInternalResult(dependents))
                    .Where(t => t);
                if (dependentAffected.Any())
                {
                    return false;
                }

                return MoveStatement(sToPop, block);
            }

            return statementMoved;
        }
示例#37
0
 private static void WriteParts(IEnumerable<string> parts, IDataWriter dataWriter)
 {
     foreach (var part in parts.TakeWhile(part => part.Length != 0))
     {
         dataWriter.WriteByte((byte)part.Length);
         dataWriter.WriteString(part);
     }
     dataWriter.WriteByte(0);
 }
示例#38
0
        private static string GetVzzualResponseWithMultipartRequest(HttpClient client, string relativeUrl, IEnumerable<KeyValuePair<string, string>> headers, IEnumerable<KeyValuePair<string, string>> files, out HttpStatusCode statusCode)
        {
            if (client == null) throw new ArgumentNullException("client");
            if (string.IsNullOrEmpty(relativeUrl)) throw new ArgumentNullException("relativeUrl");

            using (var requestContent = new MultipartFormDataContent())
            {
                if (files != null)
                {
                    foreach (var keyValuePair in files.TakeWhile(keyValuePair => keyValuePair.Value.Any()))
                    {
                        //Read file
                        var fileBytes = File.ReadAllBytes(keyValuePair.Value);

                        //Add file to request
                        var fileContent = new ByteArrayContent(fileBytes);
                        fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                            {
                                Name = keyValuePair.Key,
                                FileName = Path.GetFileName(keyValuePair.Value)
                            };
                        requestContent.Add(fileContent);
                    }
                }

                //Add headers
                if (headers != null)
                {
                    foreach (var keyValuePair in headers.TakeWhile(keyValuePair => keyValuePair.Value.Any()))
                    {
                        requestContent.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
                    }
                }

                using (var responseMessage = client.PostAsync(relativeUrl, requestContent).Result)
                {
                    statusCode = responseMessage.StatusCode;

                    return responseMessage.Content.ReadAsStringAsync().Result;
                }
            }
        }
 /// <summary>
 /// Returns elements from a sequence until a specified condition is true.
 /// </summary>
 /// <typeparam name="T">The type of the elements of <paramref name="source"/>.</typeparam>
 /// <param name="source">A sequence to return elements from.</param>
 /// <param name="predicate">A function to test each element for a condition.</param>
 /// <returns>An <see cref="IEnumerable{T}"/> that contains the elements from the input sequence that occur before the first element at which the test passes.</returns>
 /// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="predicate"/> is <see langword="null"/>.</exception>
 public static IEnumerable <T> TakeUntil <T>(this IEnumerable <T> source, Func <T, bool> predicate)
 {
     return(source.TakeWhile(x => !predicate(x)));
 }
示例#40
0
 //takewhile
 public static IEnumerable <TSource> q <TSource>(this IEnumerable <TSource> input, Func <TSource, Boolean> predicate) => input.TakeWhile(predicate);
        /// <summary>
        /// See if we can move the statement to the front of the line.
        /// </summary>
        /// <param name="statementToMove"></param>
        /// <param name="statements"></param>
        /// <returns></returns>
        private static bool MoveFirst(IStatement statementToMove, IEnumerable<IStatement> statements)
        {
            // Walk backwards through previous statements
            var prevStatements = statements.TakeWhile(s => s != statementToMove).Reverse();

            // See if we can move.
            foreach (var s in prevStatements)
            {
                if (!StatementCommutes(s, statementToMove))
                {
                    return false;
                }
            }

            // If we can commute everywhere, then we are done!
            return true;
        }
示例#42
0
        /// <summary>
        /// Calculates the prime factors of the current instance.
        /// </summary>
        /// <param name="i">The current instance.</param>
        /// <param name="primes">An array of primes.</param>
        /// <returns>The prime factors of the current instance.</returns>
        public static IEnumerable<int> PrimeFactors(this int i, IEnumerable<int> primes)
        {
            Contract.Requires(i >= 0);

            if (i <= 1) yield break;

            foreach (int prime in primes.TakeWhile(p => p <= i))
            {
                while (i % prime == 0)
                {
                    yield return prime;
                    i /= prime;
                }

                if (i == 1) yield break;
            }
        }
        public static NoSpaceExpression Produce(IEnumerable<Symbol> symbols)
        {
            // nospace-expression = open-parenthesis expression close-parenthesis
            //         / numerical-constant
            //         / prefix-operator expression
            //         / expression infix-operator expression
            if (!symbols.Any())
            {
                return null;
            }

            // expression, infix-operator, expression
            var z = symbols.Rollup(0,
                (t, d) => {
                    if (t is OpenParenthesis)
                    {
                        return d + 1;
                    }
                    if (t is ClosedParenthesis)
                    {
                        return d - 1;
                    }
                    return d;
                }
            );
            var symbolsWithIndex = symbols.Select((s, i) => new
                {
                    Symbol = s,
                    Index = i,
                });
            var z2 = symbolsWithIndex.Zip(z, (v1, v2) => new
                {
                    SymbolWithIndex = v1,
                    Depth = v2,
                });
            var operatorList = z2.Where(x =>
                x.Depth == 0 &&
                x.SymbolWithIndex.Index != 0 &&
                InfixOperator.Produce(x.SymbolWithIndex.Symbol) != null
            ).ToList();
            if (operatorList.Any())
            {
                int minPrecedence = operatorList.Select(o2 =>
                    OperatorPrecedence[o2.SymbolWithIndex.Symbol.ToString()]
                ).Min();
                var op = operatorList.Last(o2 =>
                    OperatorPrecedence[o2.SymbolWithIndex.Symbol.ToString()] ==
                        minPrecedence
                );
                if (op != null)
                {
                    var expressionTokenList1 = symbols.TakeWhile(t =>
                        t != op.SymbolWithIndex.Symbol);
                    Expression e1 = Expression.Produce(expressionTokenList1);
                    if (e1 == null)
                    {
                        throw new ParserException("Invalid expression");
                    }
                    var expressionTokenList2 = symbols.SkipWhile(t =>
                        t != op.SymbolWithIndex.Symbol).Skip(1);
                    Expression e2 = Expression.Produce(expressionTokenList2);
                    if (e2 == null)
                    {
                        throw new ParserException("Invalid expression");
                    }
                    InfixOperator io = new InfixOperator(op.SymbolWithIndex.Symbol);
                    return new NoSpaceExpression(e1, io, e2);
                }
            }
            if (symbols.First() is OpenParenthesis &&
                symbols.Last() is ClosedParenthesis)
            {
                Expression e = Expression.Produce(symbols.Skip(1).SkipLast(1));
                if (e != null)
                {
                    return new NoSpaceExpression(new OpenParenthesis(), e,
                        new ClosedParenthesis());
                }
            }
            NumericalConstant n = NumericalConstant.Produce(symbols);
            if (n != null)
            {
                return new NoSpaceExpression(n);
            }
            PrefixOperator p = PrefixOperator.Produce(symbols.FirstOrDefault());
            if (p != null)
            {
                Expression e = Expression.Produce(symbols.Skip(1));
                if (e != null)
                {
                    return new NoSpaceExpression(p, e);
                }
            }
            return null;
        }
示例#44
0
 private static List<short> UploadBinaryFiles(IEnumerable<Tuple<FileFormat, byte[]>> files, int fileCountLimit)
 {
     var uploadImages = new List<short>();
     foreach (var file in files.TakeWhile(file => uploadImages.Count < fileCountLimit)) {
         uploadImages.Add(UploadImage(default(int), file.Item1, file.Item2));
     }
     return uploadImages;
 }
示例#45
0
 protected IEnumerable<string[]> SplitByBoundary(IEnumerable<string> texts, params string[] separators)
 {
     Func<string, bool> predicate = t => separators.Contains(t) == false;
     while (texts.Any())
     {
         var bound = texts.TakeWhile(predicate).ToArray();
         yield return bound;
         texts = texts.SkipWhile(predicate).Skip(1);
     }
 }
示例#46
0
 public Solver(IEnumerable <string> input)
 {
     rulesInput = input.TakeWhile(s => !string.IsNullOrEmpty(s)).ToList();
     wordsInput = input.SkipWhile(s => !string.IsNullOrEmpty(s)).Skip(1).ToList();
 }