public static string FindPositionPart(IList<string> parts, int cursorPosition, out int foundPartsIndex, out int cursorInPartPosition)
        {
            cursorInPartPosition = 0;
              var partsComplete = parts.Aggregate(String.Empty, (aggr, s) => aggr + s);
              for (int i = 0; i < parts.Count(); i++) {
            var partsLower = parts.Take(i).Aggregate(String.Empty, (aggr, s) => aggr + s);
            var partsUpper = parts.Take(i + 1).Aggregate(String.Empty, (aggr, s) => aggr + s);

            var b = partsLower.Length;
            var t = partsUpper.Length;

            if ((cursorPosition >= b && cursorPosition < t) || partsUpper == partsComplete) {
              if (parts[i] == WorkDayParser.itemSeparator.ToString() || parts[i] == WorkDayParser.hourProjectInfoSeparator.ToString()) {
            // cursor left of separator
            foundPartsIndex = i - 1;
            var prevPart = parts.ElementAt(foundPartsIndex);
            // find out where in the found part the cursor is, need to use prevpart an its length
            cursorInPartPosition = prevPart.Length;
            return prevPart;
              } else {
            // find out where in the found part the cursor is
            cursorInPartPosition = cursorPosition - b;
            foundPartsIndex = i;
            return parts.ElementAt(i);
              }
            }
              }
              // not found
              foundPartsIndex = -1;
              return String.Empty;
        }
Exemple #2
1
        public Span Handle(IList<Token> tokens, Options options)
        {
            RepeaterMonthName month = null;
            int day = 0;
            IList<Token> remainingTokens = null;
            if (tokens.Count > 3)
            {
                month = tokens[2].GetTag<RepeaterMonthName>();
                day = tokens[3].GetTag<ScalarDay>().Value;
                remainingTokens = tokens.Take(2).ToList();
            }
            else
            {
                month = tokens[1].GetTag<RepeaterMonthName>();
                day = tokens[2].GetTag<ScalarDay>().Value;
                remainingTokens = tokens.Take(1).ToList();
            }

            var now = options.Clock();
            if (Time.IsMonthOverflow(now.Year, (int)month.Value, day))
            {
                return null;
            }
            return Utils.HandleMD(month, day, remainingTokens, options);
        }
        public static string GetFormation(IList<PlayerGameweekPerformance> performances)
        {
            var defenders = performances.Take(11).Count(p => p.Position == Position.Defender);
            var midfielders = performances.Take(11).Count(p => p.Position == Position.Midfielder);
            var forwards = performances.Take(11).Count(p => p.Position == Position.Forward);

            return string.Format("{0}-{1}-{2}", defenders, midfielders, forwards);
        }
 private void ParseRealization(IList<Double> realization)
 {
     Double repeatedValue = realization.Last(); // last value it's the same as cycle start value
     Int32 cycleStartIndex = realization.IndexOf(repeatedValue);
     Appendix = realization.Take(cycleStartIndex).ToList();
     Cycle = realization.Skip(cycleStartIndex).Take(realization.Count - cycleStartIndex - 1).ToList();
 }
Exemple #5
1
        /// <summary>
        /// Returns a Faro shuffled list.
        /// The initial list is split in half. A new list is created by alternately adding each item from the half-lists to it.
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static IList<string> FaroShuffle(IList<string> list)
        {
            if (list.Count == 0)
                return list;

            var items = list.Count;

            //First half needs to greater by 1, or equal to the second half for this to work right
            int firstHalfSize;
            if (list.Count % 2 == 0)
                firstHalfSize = list.Count / 2;
            else
                firstHalfSize = list.Count / 2 + 1;

            //Split in two halfs
            IList<string> firstHalf = list.Take(firstHalfSize).ToList();
            IList<string> secondHalf = list.Skip(firstHalfSize).Take(list.Count - firstHalfSize).ToList();

            IList<string> result = new List<string>();

            for (int i = 0, skip = 0; i < items; i = i + 2, skip++)
            {
                var item = firstHalf.Skip(skip).FirstOrDefault();
                if (item != null)
                    result.Add(item);
                item = secondHalf.Skip(skip).FirstOrDefault();
                if (item != null)
                    result.Add(item);
            }

            return result;
        }
        private static IList<ulong> GetFibLikeSequence(IList<ulong> seedSequence, int length)
        {
            IList<ulong> sequence = new List<ulong>();

            int count = seedSequence.Count();

            if (length <= count)
            {
                sequence = seedSequence.Take((int)length).ToList();
            }
            else
            {
                sequence = seedSequence;

                for (int i = count; i < length; i++)
                {
                    ulong num = 0;

                    for (int j = 0; j < count; j++)
                    {
                        num += sequence[sequence.Count - 1 - j];
                    }

                    sequence.Add(num);
                }
            }

            return sequence;
        }
        public IEnumerable<PageLinksValidationResult> ValidateLinks(IList<DocumentationPage> pages)
        {
            var results = new ConcurrentBag<PageLinksValidationResult>();

            var p = new List<DocumentationPage>[2];

            var half = pages.Count / 2;
            p[0] = pages.Take(half).ToList();
            p[1] = pages.Skip(half).ToList();

            Parallel.For(
                0,
                2,
                i =>
                {
                    using (var client = new HttpClient())
                    {
                        var pagesToCheck = p[i];
                        foreach (var page in pagesToCheck)
                            results.Add(ValidatePageLinks(client, page, pages));
                    }
                });

            return results;
        }
        public FromImportCompletionAnalysis(IList<ClassificationSpan> tokens, ITrackingSpan span, ITextBuffer textBuffer, CompletionOptions options)
            : base(span, textBuffer, options)
        {
            Debug.Assert(tokens[0].Span.GetText() == "from");

            int beforeImportToken = tokens
                .TakeWhile(tok => !(tok.ClassificationType.IsOfType(PredefinedClassificationTypeNames.Keyword) && tok.Span.GetText() == "import"))
                .Count();

            bool lastIsDot = tokens.Last().ClassificationType.IsOfType(JPredefinedClassificationTypeNames.Dot);
            _modulesOnly = beforeImportToken == tokens.Count;
            _noCompletions = !_modulesOnly && lastIsDot;
            _includeStar = beforeImportToken == tokens.Count - 1;

            if (beforeImportToken >= 2) {
                // If there are at least two tokens ('from' <name>) before the
                // 'import' token, use completions from that package.
                if (beforeImportToken < tokens.Count || lastIsDot) {
                    _namespace = tokens
                        .Take(beforeImportToken)
                        .Where(tok => tok.ClassificationType.IsOfType(PredefinedClassificationTypeNames.Identifier))
                        .Select(tok => tok.Span.GetText())
                        .ToArray();
                } else {
                    _importKeywordOnly = true;
                }
            }
        }
 public override MatchResult Match(IList<Pattern> left, IEnumerable<Pattern> collected = null)
 {
     var coll = collected ?? new List<Pattern>();
     var sresult = SingleMatch(left);
     var match = sresult.Match;
     if (match == null)
     {
         return new MatchResult(false, left, coll);
     }
     var left_ = new List<Pattern>();
     left_.AddRange(left.Take(sresult.Position));
     left_.AddRange(left.Skip(sresult.Position + 1));
     var sameName = coll.Where(a => a.Name == Name).ToList();
     if (Value != null && (Value.IsList || Value.IsOfTypeInt))
     {
         var increment = new ValueObject(1);
         if (!Value.IsOfTypeInt)
         {
             increment = match.Value.IsString ? new ValueObject(new [] {match.Value})  : match.Value;
         }
         if (sameName.Count == 0) 
         {
             match.Value = increment;
             var res = new List<Pattern>(coll) {match};
             return new MatchResult(true, left_, res);
         }
         sameName[0].Value.Add(increment);
         return new MatchResult(true, left_, coll);
     }
     var resColl = new List<Pattern>();
     resColl.AddRange(coll);
     resColl.Add(match);
     return new MatchResult(true, left_, resColl);
 }
        public void Execute(IList<IRecord> records, IList<IWorkItemTarget> targets)
        {
            String body = TemplateEngine.EvaluateTemplate(records, _body);
            String subject = TemplateEngine.EvaluateTemplate(records.Take(1).ToList(), _subject);
            String[] recipient = targets.Select(x => x.Evaluate(records[0])).ToArray();

            ((SmtpDeliverySystem)DeliverySystem).SendEmail(recipient, subject, body);
        }
 private static void UpdateSearchResults(IList<SearchResult> searchResults, XPathWorkbench workbench)
 {
     foreach(var searchResult in searchResults.Take(XPathWorkbench.MaxSearchResultCount))
     {
         workbench.SearchResults.Add(searchResult);
     }
     workbench.UpdateSearchResultText(searchResults);
 }
 private IList<TripleExponentialEntry> BuildFirstSeason(IList<SeasonalIndex> seasonalIndices)
 {
     return seasonalIndices.Take(_periodsPerSeason).Select(i => new TripleExponentialEntry
         {
             Ft = 0,
             Tt = 0,
             St = i.PeriodSeasonalComponent,
             Forecast = 0
         }).ToList();
 }
        private static IEnumerable<double> ForecastSeries(IList<double> series, IEnumerable<IEnumerable<int>> indices, IEnumerable<int> radiuses, int period, int startForecastingFrom)
        {
            var indicesList = indices.Select(x => x.ToList()).ToList();
            var radiusesList = radiuses.ToList();

            var trainingSeries = series.Take(startForecastingFrom).ToList();
            foreach (var value in series.Skip(startForecastingFrom))
            {
                trainingSeries.Add(value);
                yield return Forecast(trainingSeries, indicesList, radiusesList, period);
            }
        }
 private static void ReplaceAnonymousType(
     IList<SymbolDisplayPart> list,
     INamedTypeSymbol anonymousType,
     IEnumerable<SymbolDisplayPart> parts)
 {
     var index = list.IndexOf(p => anonymousType.Equals(p.Symbol));
     if (index >= 0)
     {
         var result = list.Take(index).Concat(parts).Concat(list.Skip(index + 1)).ToList();
         list.Clear();
         list.AddRange(result);
     }
 }
        public Grid Build(IList<IPanelItem> items)
        {
            var grid = new Grid();

            var i = 1;

            while (!items.IsNullOrEmpty())
            {
                grid.Blocks.Add(GenerateBlock(items.Take(i)));

                items = items.Skip(i).ToList();

                if (items.IsNullOrEmpty())
                    break;

                i = i == 1 ? 4 : 1;

                grid.Blocks.Add(GenerateBlock(items.Take(i)));

                items = items.Skip(i).ToList();
            }

            return grid;
        }
Exemple #16
0
        private static IList <ulong> GetFibLikeSequence(IList <ulong> seedSequence, int length)
        {
            IList <ulong> sequence = new List <ulong>();

            int count = seedSequence.Count();

            if (length <= count)
            {
                sequence = seedSequence.Take((int)length).ToList();
            }
            else
            {
                sequence = seedSequence;

                for (int i = count; i < length; i++)
                {
                    ulong num = 0;

                    for (int j = 0; j < count; j++)
                    {
                        num += sequence[sequence.Count - 1 - j];
                    }

                    sequence.Add(num);
                }
            }

            return(sequence);
        }
Exemple #17
0
        static DmdMethodBase AddTypeArguments(DmdMethodBase method, IList <DmdType> typeAndMethodGenArgs)
        {
            var declType = method.ReflectedType;

            if (declType.IsConstructedGenericType)
            {
                return(null);
            }
            int typeGenArgs   = declType.GetGenericArguments().Count;
            int methodGenArgs = method.GetGenericArguments().Count;

            if (typeGenArgs + methodGenArgs != typeAndMethodGenArgs.Count)
            {
                return(null);
            }

            if (typeGenArgs != 0)
            {
                var type = declType.MakeGenericType(typeAndMethodGenArgs.Take(typeGenArgs).ToArray());
                method = type.GetMethod(method.Module, method.MetadataToken, throwOnError: true);
            }
            if (methodGenArgs != 0)
            {
                method = ((DmdMethodInfo)method).MakeGenericMethod(typeAndMethodGenArgs.Skip(typeGenArgs).ToArray());
            }

            return(method);
        }
        public IList <Task> GetAllTasks(long projectId, int limit, String startingAfter)
        {
            IList <Task> tasks = GetAllTasks(projectId);

            if (!String.IsNullOrEmpty(startingAfter))
            {
                while ((tasks.Count > 0) && (tasks.First().ExternalId != startingAfter))
                {
                    tasks.RemoveAt(0);
                }

                if (tasks.Count > 0)
                {
                    tasks.RemoveAt(0);
                }
            }

            if (tasks.Count <= limit)
            {
                return(tasks);
            }
            else
            {
                return(tasks.Take(limit).ToList());
            }
        }
        public static int AssertResults <T>(
            IList <T> expected,
            IList <T> actual,
            bool assertOrder,
            Action <IList <T>, IList <T> > asserter = null)
        {
            Assert.Equal(expected.Count, actual.Count);

            if (asserter != null)
            {
                asserter(expected, actual);
            }
            else
            {
                if (assertOrder)
                {
                    Assert.Equal(expected, actual);
                }
                else
                {
                    foreach (var expectedItem in expected)
                    {
                        Assert.True(
                            actual.Contains(expectedItem),
                            string.Format(
                                "\r\nExpected item: [{0}] not found in results: [{1}]...",
                                expectedItem,
                                string.Join(", ", actual.Take(10))));
                    }
                }
            }
            return(actual.Count);
        }
Exemple #20
0
        //Вычисляем CRC-сумму
        public IList <bool> GetCRC(IList <bool> message = default)
        {
            //Полином
            bool[] polynome = Message.Polynome.Skip(1).ToArray();
            //Сбалансированное сообщение
            IList <bool> balancedMessage = message == default ? Message.BalanceMessage : message;
            //Степень полинома
            int polynomDegree = Message.GetPolynomialDegree();
            //Имитируем регистр, заполняем его первыми W элементами сообщения
            Queue <bool> register = new Queue <bool>(balancedMessage.Take(polynomDegree));

            for (int i = polynomDegree; i < balancedMessage.Count; i++)
            {
                if (register.Dequeue())
                {
                    register.Enqueue(balancedMessage[i]);
                    IList <bool> tempRegister = new List <bool>(register);
                    for (int k = 0; k < register.Count; k++)
                    {
                        tempRegister[k] ^= polynome[k];
                    }
                    register = new Queue <bool>(tempRegister);
                }
                else
                {
                    register.Enqueue(balancedMessage[i]);
                }
            }

            return(register.ToList());
        }
        public static IList <TResult> RunInParallel <TResult>(IList <Closure <TResult> > closures)
        {
            IList <TResult> results = new List <TResult>();

            if (closures == null || closures.Count == 0)
            {
                return(results);
            }
            if (closures.Count > 1)
            {
                var remainingClosures = closures.Skip(1);
                var tasks             = remainingClosures.Select(c => Task.Run(() => c())).ToArray();
                var firstClosure      = closures.Take(1).First();
                var firstResult       = firstClosure();
                results.Add(firstResult);
                Task.WaitAll(tasks);
                tasks.ForEach(t => results.Add(t.Result));
            }
            else
            {
                var result = closures.First()();
                results.Add(result);
            }
            return(results);
        }
Exemple #22
0
            private static IList <Expression> ChainConcatenations(IList <Expression> /*!*/ expressions)
            {
                //return expressions;

                List <Expression> newExpressions = null;

                ConcatEx expr;

                for (int index = 0; index < expressions.Count; index++)
                {
                    if ((expr = expressions[index] as ConcatEx) != null)
                    {
                        if (newExpressions == null)
                        {
                            newExpressions = new List <Expression>(index);
                            newExpressions.AddRange(expressions.Take(index)); // initial list of expressions (that were not ConcatEx)
                        }

                        newExpressions.AddRange(expr.Expressions);
                    }
                    else if (newExpressions != null)
                    {
                        newExpressions.Add(expressions[index]);
                    }
                }

                // something was chained ?? or not
                return((IList <Expression>)newExpressions ?? expressions);
            }
Exemple #23
0
        public IEnumerable <PageLinksValidationResult> ValidateLinks(IList <DocumentationPage> pages)
        {
            var results = new ConcurrentBag <PageLinksValidationResult>();

            var p = new List <DocumentationPage> [2];

            var half = pages.Count / 2;

            p[0] = pages.Take(half).ToList();
            p[1] = pages.Skip(half).ToList();

            Parallel.For(
                0,
                2,
                i =>
            {
                using (var client = new HttpClient())
                {
                    var pagesToCheck = p[i];
                    foreach (var page in pagesToCheck)
                    {
                        results.Add(ValidatePageLinks(client, page, pages));
                    }
                }
            });

            return(results);
        }
Exemple #24
0
        private Expression BuildExpressionInternal(IList <NodeItem> nodeItems)
        {
            var min = nodeItems.Max(n => n.Kind);

            NodeItem lowest = nodeItems.FirstOrDefault(n => n.Kind == min);

            if (lowest.Kind == NodeKind.SubExpression)
            {
                nodeItems = lowest.NodeItems;
                min       = nodeItems.Max(n => n.Kind);
                lowest    = nodeItems.SingleOrDefault(n => n.Kind == min);
            }

            var index            = nodeItems.IndexOf(lowest);
            var previousSiblings = nodeItems.Take(index).ToList();
            var nextSiblings     = nodeItems.Skip(index + 1).ToList();

            var result = BuildExpressionFrom(lowest, previousSiblings, nextSiblings);

            if (_forcedOutputType != null && _forcedOutputType != result.Type)
            {
                result = Expression.Convert(result, _forcedOutputType);
            }

            return(result);
        }
Exemple #25
0
        public IList <double> Calculate(IList <double> values)
        {
            var i = 0;

            foreach (var val in values)
            {
                var avg = avgAcum.ElementAtOrDefault(i);
                if (avg < val)
                {
                    avg = val;
                }
                else if (avg > 0)
                {
                    avg -= avg / 20;
                }

                if (avgAcum.Count > i)
                {
                    avgAcum[i] = avg;
                }
                else
                {
                    avgAcum.Add(avg);
                }

                i++;
            }

            if (avgAcum.Count > values.Count)
            {
                avgAcum = avgAcum.Take(values.Count).ToList();
            }

            return(avgAcum);
        }
Exemple #26
0
        public override void Prepare(
            IList <IGenome> sampleGenomes,
            GenomeProductionSession thisSession,
            GenomeProductionSession totalSession,
            int totalNbToSelect)
        {
            base.Prepare(
                sampleGenomes,
                thisSession,
                totalSession,
                totalNbToSelect);

            var samplesCount = ComputeParticipantsCount(sampleGenomes.Count());
            var candidates   = sampleGenomes.Take(samplesCount).ToList();

            var minFitness = candidates.Min(x => x.Fitness);

            if (minFitness < 0)
            {
                minFitness *= -1;
            }
            else
            {
                minFitness = 0;
            }

            genomeAndFitn = candidates.ToDictionary(
                x => x,
                x => x.Fitness + minFitness + float.Epsilon);

            usedSetsOfGenomes = new List <IGenome[]>();
        }
Exemple #27
0
        public static IEnumerable <T> OuterSegments <T>(this IList <T> source, int segmentIndexStart, int segmentIndexEnd)
        {
            var firstOuterSegment  = source.Take(segmentIndexStart);
            var secondOuterSegment = source.Skip(segmentIndexEnd + 1).Take(source.Count - segmentIndexEnd);

            return(firstOuterSegment.Concat(secondOuterSegment));
        }
        private static IList <string> GetSubquestions(IList <string> lines)
        {
            var index = 0;

            // Remove empty lines.
            lines = lines.Where(line => !string.IsNullOrEmpty(line)).ToList();

            char lastChar;

            do
            {
                lastChar = lines[index].TrimEnd().LastOrDefault();
                index++;
            }while (index < lines.Count && !TextParseZhTw.SuffixSet.Contains(lastChar));

            if (index >= lines.Count - 1)
            {
                return(new[] { string.Join(" ", lines.Select(TextParseZhTw.TrimEnding)) });
            }

            var questions = new List <string> {
                string.Join(" ", lines.Take(index + 1).Select(TextParseZhTw.TrimEnding))
            };

            questions.AddRange(lines.Skip(index + 1).Select(TextParseZhTw.TrimEnding));
            return(questions);
        }
Exemple #29
0
        public KAABBTree(IList <Triangle2d> mesh)
        {
            _boxes = new AxisAlignedBox2d[NumberOfAlignment];
            for (var i = 0; i < NumberOfAlignment; ++i)
            {
                var i1 = i;
                _boxes[i] = mesh.Select(tra => tra.Rotate(Alignment[i1])).GetBBox();
            }

            var alignmentToSplitBy = Random.Next(NumberOfAlignment);

            mesh = (_boxes[alignmentToSplitBy].Height > _boxes[alignmentToSplitBy].Width ?
                    mesh.OrderBy(tra => (Alignment[alignmentToSplitBy] * tra.V0).y)
                : mesh.OrderBy(tra => (Alignment[alignmentToSplitBy] * tra.V0).x)).ToList();
            if (mesh.Count != 1)
            {
                _isALeef = false;
                var midIndex = mesh.Count / 2;
                _left  = new KAABBTree(mesh.Take(midIndex).ToList());
                _right = new KAABBTree(mesh.Skip(midIndex).Take(mesh.Count - midIndex).ToList());
            }
            else
            {
                _isALeef = true;
                _mesh    = mesh.First();
            }
        }
Exemple #30
0
    public static TList BinaryFind <TList>(this IList <TList> list, Func <TList, int> comparer)
    {
        if (!list.Any())
        {
            return(default(TList));
        }
        int   pivot           = list.Count() / 2;
        TList pivotVal        = list[pivot];
        int   conditionResult = condition(pivotVal);

        if (conditionResult == 0)
        {
            return(pivotVal);
        }
        else
        {
            if (conditionResult < 0)
            {
                return(BinaryFind <TList, TSearchArg>(list.Take(pivot).ToList(), condition));
            }
            else
            {
                return(BinaryFind <TList, TSearchArg>(list.Skip(pivot).ToList(), condition));
            }
        }
    }
Exemple #31
0
        private bool MatchesConstraint(TKey key)
        {
            switch (_type)
            {
            case CombineOperator.And:
            {
                return(_sourceCaches.All(s => s.Lookup(key).HasValue));
            }

            case CombineOperator.Or:
            {
                return(_sourceCaches.Any(s => s.Lookup(key).HasValue));
            }

            case CombineOperator.Xor:
            {
                return(_sourceCaches.Count(s => s.Lookup(key).HasValue) == 1);
            }

            case CombineOperator.Except:
            {
                bool first  = _sourceCaches.Take(1).Any(s => s.Lookup(key).HasValue);
                bool others = _sourceCaches.Skip(1).Any(s => s.Lookup(key).HasValue);
                return(first && !others);
            }

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        public static async Task UpdateDashboard(IList <ThingsDeviceModel> sensors)
        {
            using (HttpClient client = new HttpClient())
            {
                var query = new UpdateDashboardMutation
                {
                    Dashboard = new DataCakeDashboard
                    {
                        Widgets = sensors.Take(1).Select(sensor => new DataCakeSensor {
                            Title = sensor.DeviceId
                        })
                                  .ToList()
                    }
                }.ToString().Replace("\n", "");

                var encodedQuery = query; //System.Net.WebUtility.UrlEncode(query);

                //TODO: touch SensorRegister.Core/Secrets.cs
                client.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("token", Secrets.DataCakeApiToken);

                var result = await client.PostAsync(
                    "https://api.datacake.co/graphql?query=" + encodedQuery, new StringContent(encodedQuery));

                var s = await result.Content.ReadAsStringAsync();

                if (!result.IsSuccessStatusCode)
                {
                    throw new Exception(s);
                }
            }
        }
Exemple #33
0
    /// <summary>
    /// Gets the count of the number of messages that completely match rule 0.
    /// </summary>
    /// <param name="input">The input of rules and messages to get the count for.</param>
    /// <param name="applyFix">Whether to apply the fix to the rules.</param>
    /// <returns>
    /// The number of messages that completely match rule 0.
    /// </returns>
    public static int GetMatchCount(IList <string> input, bool applyFix)
    {
        int delimiter = input.IndexOf(string.Empty);

        var rules    = ParseRules(input.Take(delimiter), delimiter);
        var messages = input.Skip(delimiter + 1);

        if (applyFix)
        {
            string rule31 = rules["31"];
            string rule42 = rules["42"];

            //// "N: a | a N" => "N: (a)+" => "8: 42 | 42 8" => "8: (42)+"
            string rule8 = $"(" + rule42 + ")+";

            // See https://www.regular-expressions.info/balancing.html
            string rule11 = $"(?:(?'X'{rule42})+(?'-X'{rule31})+)+(?(X)(?!))";

            rules["0"]  = rule8 + rule11;
            rules["8"]  = rule8;
            rules["11"] = rule11;
        }

        string pattern = $"^{rules["0"]}$";

        return(messages.Count((p) => Regex.IsMatch(p, pattern)));
Exemple #34
0
        private bool AddWordBackward(IList <ushort> reply)
        {
            int o = Order;

            if (reply.Count < o)
            {
                o = reply.Count;
            }

            IEnumerable <ushort> backward = reply.Take(o).Reverse();
            Node *n = this.Find(ModelContext.Backward, backward);

            if (n == null || n->branch < 1)
            {
                return(false);
            }
            ushort t = GetNextToken(n);

            if (_dict[t] is TerminateSymbol || (_dict[t] is PunctuationSymbol && ((PunctuationSymbol)_dict[t]).IsTerminating))
            {
                return(false);
            }
            reply.Insert(0, t);
            return(true);
        }
Exemple #35
0
 private void CachePhotos(IList <PhotoDto> photos)
 {
     foreach (var id in photos.Take(10).Select(x => x.Id))
     {
         _photosService.GetPhoto(Priority.Speculative, id);
     }
 }
Exemple #36
0
        /// <summary>
        /// Computes an exponential moving average
        /// </summary>
        /// <param name="prices">Prices for which the average should be computed</param>
        /// <param name="terms">A period in days</param>
        /// <returns>Values of the exponential moving average</returns>
        public static IList <IndicatorValue> ExpotentialMovingAverage(IList <Price> prices, int terms)
        {
            if (prices == null || prices.Count < terms || terms < 1 || !CheckDates(prices.Select(price => price.Date).ToList()))
            {
                throw new IndicatorArgumentException();
            }
            IList <IndicatorValue> averages = new List <IndicatorValue>();
            var ema = SimpleMovingAverage(prices.Take(terms).ToList());

            averages.Add(ema);
            var alpha = 2.0m / (terms + 1);
            var p     = 1 - alpha;

            for (var i = terms; i < prices.Count; i++)
            {
                var nextEma = new IndicatorValue
                {
                    Date  = prices[i].Date,
                    Value = prices[i].ClosePrice * alpha + ema.Value * p
                };
                ema = nextEma;
                averages.Add(ema);
            }
            return(averages);
        }
Exemple #37
0
        private void BindList()
        {
            //国内
            Query q = new Query();

            q.OrderBy("Views desc");
            q.Append("NewsType='" + NewsType.国内新闻 + "'");
            IList <New> alist1     = bn.GetNewsTitleList(q).Take(13).ToList();
            New         toparticle = alist1.Take(1).FirstOrDefault();

            lttitle.Text       = Utils.CutString(toparticle.Title, 50);
            ltsummary.Text     = Utils.CutString(toparticle.summary, 170);
            hfaid.Value        = Utils.ObjectToStr(toparticle.NewsID);
            rplist1.DataSource = alist1.Skip(1).ToList();
            rplist1.DataBind();

            //国外
            Query q2 = new Query();

            q2.OrderBy("Views desc");
            q2.Append("NewsType='" + NewsType.国际会议 + "'");
            IList <New> alist2      = bn.GetNewsTitleList(q2).Take(13).ToList();
            New         toparticle2 = alist2.Take(1).FirstOrDefault();

            lttitle2.Text      = Utils.CutString(toparticle2.Title, 50);
            ltsummary2.Text    = Utils.CutString(toparticle2.summary, 170);
            hfaid2.Value       = Utils.ObjectToStr(toparticle2.NewsID);
            rplist2.DataSource = alist2.Skip(1).ToList();
            rplist2.DataBind();
        }
Exemple #38
0
            /// <summary>
            /// Gets the context to use when building the inner text of the tag.
            /// </summary>
            /// <param name="writer">The text writer passed</param>
            /// <param name="keyScope">The current scope.</param>
            /// <param name="arguments">The arguments passed to the tag.</param>
            /// <returns>The scope to use when building the inner text of the tag.</returns>
            public override IEnumerable <NestedContext> GetChildContext(
                TextWriter writer,
                Scope keyScope,
                Dictionary <string, object> arguments,
                Scope contextScope)
            {
                object    value      = arguments[collectionParameter];
                int       limit      = int.Parse(arguments["limit"].ToString());
                IList <T> enumerable = value as IList <T>;

                if (enumerable == null)
                {
                    yield break;
                }

                enumerable = enumerable.Take(limit).ToList();

                int index = 0;

                foreach (object item in enumerable)
                {
                    NestedContext childContext = new NestedContext()
                    {
                        KeyScope     = keyScope.CreateChildScope(item),
                        Writer       = writer,
                        ContextScope = contextScope.CreateChildScope(),
                    };
                    //childContext.ContextScope.Set("index", index);
                    yield return(childContext);

                    ++index;
                }
            }
        public IList <Vector2Int> GetFirstLongestNaturalLine(IList <Vector2Int> jumpPoints, Func <Vector2Int, bool> isWalkable)
        {
            if (jumpPoints.Count == 1)
            {
                return(jumpPoints);
            }
            IList <Vector2Int> naturalJumpPoints = GetNaturalJumpPoints(jumpPoints);

            if (naturalJumpPoints.Count == 2)
            {
                return(_bresenhamLineCreator.GetBresenhamLine(jumpPoints[0].x, jumpPoints[0].y, jumpPoints[1].x, jumpPoints[1].y, -1, isWalkable, false));
            }
            IList <Vector2Int> firstThreeNaturalJumpPoints = naturalJumpPoints.Take(3).ToList();
            Vector2Int         firstJumpPoint      = firstThreeNaturalJumpPoints[0];
            Vector2Int         rangeCheckBeginning = firstThreeNaturalJumpPoints[1];
            Vector2Int         rangeCheckEnd       = firstThreeNaturalJumpPoints[2];
            IList <Vector2Int> rangeToCheck        =     // note that it's going from range end to range beginning
                                                     _bresenhamLineCreator.GetBresenhamLine(rangeCheckEnd.x, rangeCheckEnd.y, rangeCheckBeginning.x, rangeCheckBeginning.y, -1,
                                                                                            position => true);
            IList <Vector2Int> naturalWay = null;

            foreach (Vector2Int checkedPosition in rangeToCheck)
            {
                IList <Vector2Int> bresenhamLineToChecked =
                    _bresenhamLineCreator.GetBresenhamLine(firstJumpPoint.x, firstJumpPoint.y, checkedPosition.x, checkedPosition.y, -1, isWalkable, false);
                bool clearWayToThirdExists = bresenhamLineToChecked.Any() && bresenhamLineToChecked.Last() == checkedPosition;
                if (clearWayToThirdExists)
                {
                    naturalWay = bresenhamLineToChecked;
                    break;
                }
            }
            return(naturalWay);
        }
 private void AppendTag(StringBuilder result)
 {
     if (_tags.Any())
     {
         if (_tags.Count > 1)
         {
             foreach (var tag in _tags.Take(_tags.Count - 1))
             {
                 result.Append("_" + tag.GetType().Name);
             }
         }
         var lastTag         = _tags.Last();
         var descriptionType = lastTag.GetType();
         if (_attribute != null)
         {
             descriptionType = _attribute.DeclaringType;
         }
         var description = descriptionType.Name;
         if (lastTag is IInstanceTagDocumentation)
         {
             description = lastTag.TagName;
         }
         result.Append("_" + description);
         AppendProperty(result);
     }
 }
        public static void ValidateTupleReturnType(MethodInfo method)
        {
            if (method.ReturnsTuple())
            {
                Type returnType = method.ReturnType;
                Type tupleType  = TaskExtensions.UnwrapReturnType(returnType);

                if (!tupleType.IsValidTupleType())
                {
                    ThrowHelper.MethodReturnsInvalidValueTuple(method);
                }

                if (method.ReturnParameter.IsDefined(typeof(TupleElementNamesAttribute)))
                {
                    int tupleLength = tupleType.GetValueTupleLength();

                    TupleElementNamesAttribute attribute =
                        method.ReturnParameter.GetCustomAttribute <TupleElementNamesAttribute>();

                    IList <string> transformNames = attribute.TransformNames;

                    List <string> tupleNames =
                        transformNames.Take(tupleLength).ToList();

                    ValidateTupleReturnType(method, tupleNames);
                    ValidateTupleReturnTypeWithOutRefParameters(method, tupleNames);
                }
            }
        }
Exemple #42
0
        public IList <SourceDTO> GetSourcesToIndex(IStatelessSession session, int startSourceId, int num, string prefix)
        {
            // get list of sources to index
            IList <SourceDTO> dtos = this.GetAllSourceDTOs(session, true, false);

            // filter for path prefix
            if (!string.IsNullOrEmpty(prefix))
            {
                dtos = dtos.Where(x => !string.IsNullOrEmpty(x.SourcePath) && x.SourcePath.StartsWith(prefix, StringComparison.InvariantCultureIgnoreCase)).ToList();
            }

            // filtering out non-text media files
            dtos = dtos.Where(x => !MIMEAssistant.GetMIMEType(x.SourceName).StartsWith("image") &&
                              !MIMEAssistant.GetMIMEType(x.SourceName).StartsWith("audio") &&
                              !MIMEAssistant.GetMIMEType(x.SourceName).StartsWith("video"))
                   .Where(x => !Source.IGNORED_FILE_EXTENSIONS.Contains(x.FileExtension))
                   .Where(x => x.SourceID > startSourceId)
                   .OrderBy(x => x.SourceID)
                   .ToList();

            log.Info("Found " + dtos.Count + " sources to index, starting from SourceID=" + startSourceId + " with prefix=" + prefix + "."
                     + (num > 0 ? " Taking " + num + "." : string.Empty));

            if (num > 0)
            {
                dtos = dtos.Take(num).ToList();
            }

            return(dtos);
        }
        /// <summary>
        /// Creates the comma seperated list with at least one 'bad value': a value which cannot represent a number.
        /// The number of valid items in the list will be preserved.
        /// </summary>
        /// <typeparam name="T">Type of entries in the list.</typeparam>
        /// <param name="list">The list to convert and corrupt.</param>
        /// <returns>A string representing the list, but with at least one non-numeric entry.</returns>
        private static String CreateCommaSeperatedListWithBadValue <T>(IList <T> list)
        {
            String listString = CreateListOfIds(list);
            int    breakpoint = Random.Next(0, list.Count());

            return(CreateListOfIds(list.Take(breakpoint)) + ",NaN," + CreateListOfIds(list.Skip(breakpoint)));
        }
Exemple #44
0
        private static int AssertResults <T>(
            IList <T> l2oItems,
            IList <T> efItems,
            bool assertOrder,
            Action <IList <T>, IList <T> > asserter = null)
        {
            Assert.Equal(l2oItems.Count, efItems.Count);

            if (asserter != null)
            {
                asserter(l2oItems, efItems);
            }
            else
            {
                if (assertOrder)
                {
                    Assert.Equal(l2oItems, efItems);
                }
                else
                {
                    foreach (var l2oItem in l2oItems)
                    {
                        Assert.True(
                            efItems.Contains(l2oItem),
                            string.Format(
                                "\r\nL2o item: [{0}] not found in EF results: [{1}]...",
                                l2oItem,
                                string.Join(", ", efItems.Take(10))));
                    }
                }
            }

            return(l2oItems.Count);
        }
Exemple #45
0
 public void PrintTop10()
 {
     foreach (var company in list.Take(20))
     {
         Console.WriteLine("\n" + company.Symbol + " " + company.Name + " " + company.Sector + " " + company.SummaryQuote);
     }
 }
 public DataTable DataManagementPlansToDataTable(IList<Project> projects, string listSeparator = CsvHelper.ListSeparator)
 {
     var dataTable = new DataTable();
     dataTable.AddDmpColumns(projects.Take(1).Single().DataManagementPlan);
     foreach (var project in projects)
     {
         var dataRow = dataTable.NewRow();
         dataRow.AddDmpValues(project.DataManagementPlan, project.Parties, listSeparator);
         dataTable.Rows.Add(dataRow);
     }
     return dataTable;
 }
 public DataTable DataCollectionsToDataTable(IList<DataCollection> dataCollections, string listSeparator = ListSeparator)
 {
     var dataTable = new DataTable();
     dataTable.AddDataCollectionColumns(dataCollections.Take(1).Single());
     foreach (var dataCollection in dataCollections)
     {
         var dataRow = dataTable.NewRow();
         dataRow.AddDataCollectionValues(dataCollection, listSeparator);
         dataTable.Rows.Add(dataRow);
     }
     return dataTable;
 }
Exemple #48
0
        public override IJsValue Construct(IList<IJsValue> arguments)
        {
            if (arguments.Count == 0)
            {
                return Construct(Environment, "", new string[0], null);
            }

            var script = arguments[arguments.Count - 1].ToString();
            var names = arguments.Take(arguments.Count - 1).Select(a => a.ToString()).ToArray();
            var body = Environment.Context.ParseScript(script);
            return Construct(Environment, "", names, body);
        }
        /// <summary>
        /// Creates the foo bars.
        /// </summary>
        /// <param name="foos">The foos.</param>
        /// <param name="bars">The bars.</param>
        /// <returns></returns>
	    public static IList<FooBar> CreateFooBars(IList<Foo> foos, IList<Bar> bars)
	    {
	        var trimmedBars = bars;

            if (bars.Count > foos.Count)
	        {
	            trimmedBars = bars.Take(foos.Count).ToList();
	        }

	        var fooBarDictionary = Enumerable.Range(0, foos.Count).ToDictionary(i => foos[i], i => trimmedBars[i]);

	        return (from pair in fooBarDictionary let foo = pair.Key let bar = pair.Value select new FooBar(foo, bar, RandomValueProvider.RandomString(10, false))).ToList();
	    }
		public static IReturnType[] InferTypeArguments(IMethod method, IList<IReturnType> arguments, out bool success)
		{
			TypeInference ti = new TypeInference();
			Log("Doing type inference for " + new CSharpAmbience().Convert(method));
			Log(" with arguments = ", arguments);
			ti.typeParameters = method.TypeParameters.Select(tp => new TP(tp)).ToList();
			ti.parameterTypes = method.Parameters.Select(p => p.ReturnType).Take(arguments.Count).ToList();
			ti.arguments = arguments.Take(ti.parameterTypes.Count).ToArray();
			ti.PhaseOne();
			success = ti.PhaseTwo();
			IReturnType[] result = ti.typeParameters.Select(tp => tp.FixedTo).ToArray();
			Log("Type inference for " + method.DotNetName + " " + (success ? "succeeded" : "failed") + ": ", result);
			return result;
		}
 private static IEnumerable<Tuple<int, IList<int>>> GetAllSequences(IList<int> numbers)
 {
     var sequences = new List<Tuple<int, IList<int>>>();
     for (int i = 0; i < numbers.Count; i++)
     {
         IList<int> list = numbers.Skip(i).ToList();
         sequences.Add(Tuple.Create(list.Sum(), list));
     }
     for (int i = numbers.Count - 1; i > 0; i--)
     {
         IList<int> list = numbers.Take(i).ToArray();
         sequences.Add(Tuple.Create(list.Sum(), list));
     }
     return sequences;
 }
        public static void AssertValidDependencies(IList<IAnalyzedSourceFile> dependencies)
        {
            foreach (var index in Enumerable.Range(0, dependencies.Count))
            {
                var source = dependencies[index];
                var previousProvides = GetProvides(dependencies.Take(index));

                foreach (var require in source.Required)
                {
                    Assert.True(previousProvides.Contains(require), 
                        string.Format("Namespace '{0}' is not provided before being required by '{1}': [{2}]", 
                            require, source.Path, string.Join(", ", dependencies.Select(x => x.Path))));
                }
            }
        }
Exemple #53
0
        private static IEnumerable<KeyValuePair<string, IDictionary<string, IList<IClassGenerationParameters>>>> SortMainNameSpaces(IList<IClassGenerationParameters> classes)
        {
            var mainNamespaces = classes.Select(x => x.MainNamespaceName).Distinct().OrderBy(x => x).ToList();

            var mappings = new Dictionary<string, IDictionary<string, IList<IClassGenerationParameters>>>(mainNamespaces.Count);

            foreach (var mainNamespace in mainNamespaces)
            {
                var ns = mainNamespace;
                var classesInNamespace = classes.Take(x => x.MainNamespaceName.Equals(ns, StringComparison.Ordinal)).ToList();
                var sortedSubNamespaces = SortSubNamespaces(classesInNamespace);

                mappings.Add(mainNamespace, sortedSubNamespaces);
            }

            return mappings;
        }
        public void GenerateInquiriesList()
        {
            Clock.FreezedTime = new DateTime(2012, 7, 19);
            var team = Builder<Team>.CreateNew().Build();

            tags = new List<Tag>
            {
                new Tag
                {
                    Id = 1,
                    Name = "tag1",
                    Owner = team
                },
                new Tag
                {
                    Id = 2,
                    Name = "tag2",
                    Owner = team
                }
            };

            inquiries = Builder<Inquiry>.CreateListOfSize(40)
                .All()
                .With(x => x.Client = Builder<Person>.CreateNew().Build())
                .With(x => x.Assignee = Builder<Person>.CreateNew().Build())
                .With(x => x.Source = Builder<MailMessage>.CreateNew().Build())
                .With(x => x.Tags = new List<Tag>())
                .TheFirst(10)
                .With(x => x.ReferenceDate = null)
                .With(x => x.Tags = tags.Take(1).ToList())
                .TheNext(10)
                .With(x => x.ReferenceDate = GetRandom.DateTime(February.The15th, February.The28th))
                .With(x => x.Tags = tags.Skip(1).Take(1).ToList())
                .TheNext(1)
                .With(x => x.ReferenceDate = new DateTime(Clock.Now.Year, 3, 1))
                .TheNext(9)
                .With(x => x.ReferenceDate = GetRandom.DateTime(March.The1st, March.The31st))
                .TheNext(10)
                .With(x => x.ReferenceDate = GetRandom.DateTime(
                    Clock.Now.GetStartOfBusinessWeek(), Clock.Now.GetEndOfBusinessWeek()))
                .Build();

            tags[0].Inquiries = inquiries.Take(10).ToList();
            tags[1].Inquiries = inquiries.Skip(10).Take(10).ToList();
        }
Exemple #55
0
        public int find(int itemToFind, IList<int> collection)
        {
            if(!collection.Any())
                return -1;

            var foundIndex = 0;
            switch(itemToFind.CompareTo(collection[collection.Count / 2]))
            {
                case 0:
                    return collection.Count/2;
                case 1:
                    foundIndex = binary_chopper.find(itemToFind, collection.Skip(collection.Count/2 + 1).ToList());
                    return foundIndex != -1 ? foundIndex + collection.Count / 2 + 1 : -1;
                case -1:
                    foundIndex = binary_chopper.find(itemToFind, collection.Take(collection.Count/2).ToList());
                    return foundIndex != -1 ? foundIndex : -1;
            }

            throw new Exception();
        }
 public void Add(IList<SkinnedVertex> v, bool generateNormals)
 {
     if (v.Count < 3) throw new EngineException("Trying to build a face with less than 3 vertices.");
     if (v.Count >= 4)
     {
         Add(v.Take(3).ToList(), generateNormals);
         Add(v.Skip(2).Concat(new[] {v[0]}).ToList(), generateNormals);
         return;
     }
     for (var i = 0; i < v.Count; i++ )
     {
         var vert = v[i];
         if (generateNormals)
         {
             var temp = (i + v.Count - 1) % v.Count;
             var left = v[temp].Position - v[i].Position;
             var right = v[(i + 1) % v.Count].Position - v[i].Position;
             vert.Normal = Vector3.Normalize(Vector3.Cross(left, right));
         }
         if (!vertindex.ContainsKey(vert.Position)) vertindex.Add(vert.Position, new LinkedList<int>());
         var found = false;
         foreach (var index in vertindex[vert.Position])
         {
             if (Equals(vertices[index], vert))
             {
                 found = true;
                 indices[i] = index;
                 break;
             }
         }
         if (found) continue;
         indices[i] = vertices.Count;
         vertindex[vert.Position].AddLast(vertices.Count);
         vertices.Add(vert);
     }
     submeshes.Last().Count++;
     triangles.Add(new Vector3i(indices));
 }
        public IExpressionTree Build(IList<Token> tokens)
        {
            if (tokens.Count == 0)
                return null;

            if (IsExpressionASingleValue(tokens))
            {
                // ���� ��������� ������� �� ������������� ��������, �� ������������ ���� ������ � ���� ���������.
                return new ExpressionTree(tokens[0], null);
            }

            // ���������� �������� ������������ ��������, �� �������� ��������� ����������� �� ��� �����.
            var index = GetIndexOfOperatorWithLowestPrecedence(tokens);

            if (index != -1)
            {
                var leftchild = Build(tokens.Take(index).ToList());
                var rightchild = Build(tokens.Skip(index + 1).ToList());

                var children = new List<IExpressionTree>();
                if (leftchild != null)
                    children.Add(leftchild);
                if (rightchild != null)
                    children.Add(rightchild);

                return new ExpressionTree(tokens[index], children);
            }

            // ���� �� ��������� � �������, �� ���������� ��������� ��, ��� ������
            if (IsExpressionInBrackets(tokens))
            {

                return Build(tokens.Skip(1).Take(tokens.Count - 2).ToList());
            }

            throw new Exception("Can't parse: " + String.Join("", tokens.Select(t => t.ToString())));
        }
 public Expression Mutate(IList<Expression> operands)
 {
     var bindings = new List<MemberBinding>();
     int operandIndex = MemberInitExpression.NewExpression.Arguments.Count();
     NewExpression newNewExpression;
     if (MemberInitExpression.NewExpression.Constructor != null)
     {
         newNewExpression = Expression.New(MemberInitExpression.NewExpression.Constructor,
                                           operands.Take(operandIndex));
     }
     else
     {
         newNewExpression = Expression.New(MemberInitExpression.NewExpression.Type);
     }
     foreach (var memberBinding in MemberInitExpression.Bindings)
     {
         var memberBindingMutator = MemberBindingMutatorFactory.GetMutator(memberBinding);
         int operandsCount = memberBindingMutator.Operands.Count();
         var subOperands = operands.Skip(operandIndex).Take(operandsCount).ToList();
         bindings.Add(memberBindingMutator.Mutate(subOperands));
         operandIndex += operandsCount;
     }
     return Expression.MemberInit(newNewExpression, bindings);
 }
        private IList<PlayerGameweekPerformance> SelectScoringPerformances(IList<PlayerGameweekPerformance> playerGameweekPerformances)
        {
            //start with the first 11 and replace players where we can if they don't play this gameweek
            var scoringPerformances = playerGameweekPerformances.Take(11).ToList();
            var subs = playerGameweekPerformances.Skip(11).ToList();

            //iterate through players and replace where neccessary)
            for (var i = 0; i < 11; i++)
            {
                var performance = scoringPerformances.ElementAt(i);
                if(performance.MinutesPlayed == 0)
                {
                    var sub = FindSubPerformance(scoringPerformances, subs, performance.Position);
                    if(sub != null)
                    {
                        scoringPerformances.RemoveAt(i);
                        scoringPerformances.Insert(i, sub);
                        subs.Remove(sub);

                        _logger.Log(Tag.Result, string.Concat(sub.PlayerName, " subbed in for ", performance.PlayerName), true);
                    } else
                    {
                        _logger.Log(Tag.Result, string.Concat("No sub found for ", performance.PlayerName), true);
                    }
                }
            }

            return scoringPerformances;
        }
Exemple #60
0
 private static int GetProb(IList<double> prob)
 {
     int result = 0;
     int n = (int)(prob.Sum() * 1000);
     Random r = new Random();
     double x = (float)r.Next(0, n) / 1000;
     for (int i = 0; i < prob.Count(); i++)
     {
         double pre = prob.Take(i).Sum();
         double next = prob.Take(i + 1).Sum();
         if (x >= pre && x < next)
         {
             result = i;
             break;
         }
     }
     return result;
 }