public void RunTests(IEnumerable<TestCase> tests, IRunContext runContext, IFrameworkHandle frameworkHandle)
        {
            //Debugger.Launch();

            frameworkHandle.SendMessage(TestMessageLevel.Informational, Strings.EXECUTOR_STARTING);

            int executedSpecCount = 0;

            Settings settings = GetSettings(runContext);

            string currentAsssembly = string.Empty;
            try
            {

                foreach (IGrouping<string, TestCase> grouping in tests.GroupBy(x => x.Source)) {
                    currentAsssembly = grouping.Key;
                    frameworkHandle.SendMessage(TestMessageLevel.Informational, string.Format(Strings.EXECUTOR_EXECUTINGIN, currentAsssembly));

                    List<VisualStudioTestIdentifier> testsToRun = grouping.Select(test => test.ToVisualStudioTestIdentifier()).ToList();

                    this.executor.RunAssemblySpecifications(currentAsssembly, testsToRun, settings, uri, frameworkHandle);
                    executedSpecCount += grouping.Count();
                }

                frameworkHandle.SendMessage(TestMessageLevel.Informational, String.Format(Strings.EXECUTOR_COMPLETE, executedSpecCount, tests.GroupBy(x => x.Source).Count()));
            } catch (Exception ex)
            {
                frameworkHandle.SendMessage(TestMessageLevel.Error, string.Format(Strings.EXECUTOR_ERROR, currentAsssembly, ex.Message));
            }
            finally
            {
            }
        }
    public override void SetUp ()
    {
      base.SetUp();

      _keySelector = ExpressionHelper.CreateLambdaExpression<int, short> (i => (short) i);
      _elementSelector = ExpressionHelper.CreateLambdaExpression<int, string> (i => i.ToString());
      _resultSelectorWithElementSelector = 
          ExpressionHelper.CreateLambdaExpression<short, IEnumerable<string>, Tuple<short, int>> ((key, group) => Tuple.Create (key, group.Count()));

      _sourceEnumerable = ExpressionHelper.CreateIntQueryable();

      var methodCallExpressionWithElementSelector = (MethodCallExpression) ExpressionHelper.MakeExpression (
          () => _sourceEnumerable.GroupBy (
              i => (short) i,
              i => i.ToString(),
              (key, group) => Tuple.Create (key, group.Count())));
      _parseInfoWithElementSelector = new MethodCallExpressionParseInfo ("g", SourceNode, methodCallExpressionWithElementSelector);
      _nodeWithElementSelector = new GroupByWithResultSelectorExpressionNode (
          _parseInfoWithElementSelector,
          _keySelector,
          _elementSelector,
          _resultSelectorWithElementSelector);

      var methodCallExpressionWithoutElementSelector = (MethodCallExpression) ExpressionHelper.MakeExpression (
          () => _sourceEnumerable.GroupBy (
              i => (short) i,
              (key, group) => Tuple.Create (key, group.Count())));
      _resultSelectorWithoutElementSelector = 
          ExpressionHelper.CreateLambdaExpression<short, IEnumerable<int>, Tuple<short, int>> ((key, group) => Tuple.Create (key, group.Count()));
      _nodeWithoutElementSelector = new GroupByWithResultSelectorExpressionNode (
          new MethodCallExpressionParseInfo ("g", SourceNode, methodCallExpressionWithoutElementSelector),
          _keySelector,
          _resultSelectorWithoutElementSelector,
          null);
    }
        private SinkSettings(string name, IEnumerable<EventSourceSettings> eventSources)
        {
            Guard.ArgumentNotNullOrEmpty(name, "name");
            Guard.ArgumentLowerOrEqualThan<int>(200, name.Length, "name.Length");
            Guard.ArgumentNotNull(eventSources, "eventSources");

            // Do not allow an empty source list
            if (eventSources.Count() == 0)
            {
                throw new ConfigurationException(string.Format(CultureInfo.CurrentCulture, Properties.Resources.NoEventSourcesError, name));
            }

            // Validate duplicate sources by name
            var duplicateByName = eventSources.GroupBy(l => l.Name).FirstOrDefault(g => g.Count() > 1);
            if (duplicateByName != null)
            {
                throw new ConfigurationException(string.Format(CultureInfo.CurrentCulture, Properties.Resources.DuplicateEventSourceNameError, duplicateByName.First().Name, name));
            }

            // Validate duplicate sources by id
            var duplicateById = eventSources.GroupBy(l => l.EventSourceId).FirstOrDefault(g => g.Count() > 1);
            if (duplicateById != null)
            {
                throw new ConfigurationException(string.Format(CultureInfo.CurrentCulture, Properties.Resources.DuplicateEventSourceIdError, duplicateById.First().Name, name));
            }

            this.Name = name;
            this.EventSources = eventSources;
        }
 public static void PrintSeatLayout(IEnumerable<Seat> e)
 {
     Console.Clear();
     var seats = e.GroupBy(x => x.Number);
     Console.Write("\t");
     foreach (var seat in seats)
     {
         if (seat.Key < 10)
             Console.Write(" " + seat.Key + "  ");
         else
         {
             Console.Write(" " + seat.Key + " ");
         }
     }
     Console.Write("\n");
     var rows = e.GroupBy(x => x.Row);
     foreach (var row in rows)
     {
         Console.Write("R {0}:\t", row.Key);
         foreach (var seat in row)
         {
             string booked = seat.IsBooked ? "X" : " ";
             Console.Write("[" + booked + "] ");
         }
         Console.Write("\n");
     }
 }
        public Models.AssessmentScoringResult CalculateScore(IEnumerable<Models.AssessmentScoringItem> assessmentItems)
        {
            var result = new Models.AssessmentScoringResult();

            if (assessmentItems == null)
            {
                result.DimensionResults = new List<Models.DimensionResult>();
            }

            result.TotalUserCount = assessmentItems.GroupBy(i => i.UserId).Count();

            var groupByDimension = assessmentItems.GroupBy(i => i.DimensionId);

            var dimensionResults = groupByDimension.Select(i => new Models.DimensionResult()
            {
                DimensionId = i.Key,
                ResponseCount = i.Count(),
                Levels = i.GroupBy(j => j.Level)
                .Select(k => new Models.LevelResult()
                {
                    Level = k.Key,
                    ResponseCount = k.Count(x=>x.CapabilityAchieved),
                    TargetCapabilityCount = GetCapabilityCountForLevel(i.Key, k.Key),
                    LevelAchieved = k.Count(x => x.CapabilityAchieved) == result.TotalUserCount * GetCapabilityCountForLevel(i.Key, k.Key)
                })
            });

            result.DimensionResults = dimensionResults;

            AddMissingDimensionsAndLevels(result);

            return result;
        }
示例#6
0
        public static void groupjoin(IEnumerable<Employee> em, IEnumerable<Employee> en)
        {
            var query = from n in em join t in en on n.Department equals t.Department into samedepart select new { n.Department, samedepart };
            var query2 = em.GroupJoin(en, m => m.Department, n => n.Department, (n, dep) => new { n.Department, dep });

            var query3 = em.GroupBy(e => e.Department).Select(d => new { d.Key, size = d.Count() });
            var query31 = em.GroupBy((e)=> e.Department).Select(d => new { d.Key, ordered= from x in d orderby x.LastName select x });
        }
示例#7
0
        public async Task <ICollection <SummarisedActual> > Summarise(
            IEnumerable <SummarisedActual> inputSummarisedActuals,
            ISummarisationMessage summarisationMessage,
            ICollection <FcsContractAllocation> fcsContractAllocations,
            CancellationToken cancellationToken)
        {
            var providerActuals = _summarisationService.Summarise(fcsContractAllocations, inputSummarisedActuals.ToList()).ToList();

            var groupedActuals = inputSummarisedActuals?
                                 .GroupBy(x => x.OrganisationId, StringComparer.OrdinalIgnoreCase)
                                 .Select(sa => new
            {
                OrganisationId    = sa.Key,
                SummarisedActuals = sa.ToList()
            }).ToList();

            foreach (var group in groupedActuals)
            {
                _logger.LogInfo($"Summarisation Wrapper: Funding Data Removed Rule OrgId: {group.OrganisationId} Start");

                var actualsToCarry = await _providerFundingDataRemovedService.FundingDataRemovedAsync(group.OrganisationId, group.SummarisedActuals, summarisationMessage, cancellationToken);

                providerActuals.AddRange(actualsToCarry);

                _logger.LogInfo($"Summarisation Wrapper: Funding Data Removed  Rule OrgId: {group.OrganisationId} End");
            }

            return(providerActuals);
        }
示例#8
0
 OrderByTotalSleepTime(IEnumerable <Shift> shifts)
 {
     return(shifts?.
            GroupBy(s => s.EmployeeID)?.
            Select(sg => (employeeID: sg.Key, minutesSlept: sg.ToList()))?.
            OrderByDescending(gs => gs.minutesSlept.Sum(g => g.MinutesSlept)));
 }
        HashSet<string> SelectDestinationsForEachEndpoint(IDistributionPolicy distributionPolicy, IEnumerable<Subscriber> subscribers)
        {
            //Make sure we are sending only one to each transport destination. Might happen when there are multiple routing information sources.
            var addresses = new HashSet<string>();
            var destinationsByEndpoint = subscribers
                .GroupBy(d => d.Endpoint, d => d);

            foreach (var group in destinationsByEndpoint)
            {
                if (group.Key == null) //Routing targets that do not specify endpoint name
                {
                    //Send a message to each target as we have no idea which endpoint they represent
                    foreach (var subscriber in group)
                    {
                        addresses.Add(subscriber.TransportAddress);
                    }
                }
                else
                {
                    var subscriber = distributionPolicy.GetDistributionStrategy(group.First().Endpoint, DistributionStrategyScope.Publish).SelectReceiver(group.Select(s => s.TransportAddress).ToArray());
                    addresses.Add(subscriber);
                }
            }

            return addresses;
        }
 public static void CheckKeyUniqueness(IEnumerable<ConceptApplication> appliedConcepts, string errorContext)
 {
     var firstError = appliedConcepts.GroupBy(pca => pca.GetConceptApplicationKey()).Where(g => g.Count() > 1).FirstOrDefault();
     if (firstError != null)
         throw new FrameworkException(String.Format("More than one concept application with same key {2} ('{0}') loaded in repository. Concept application IDs: {1}.",
             firstError.Key, string.Join(", ", firstError.Select(ca => SqlUtility.QuoteGuid(ca.Id))), errorContext));
 }
        public DependencySetsViewModel(IEnumerable<PackageDependency> packageDependencies)
        {
            try
            {
                DependencySets = new Dictionary<string, IEnumerable<DependencyViewModel>>();

                var dependencySets = packageDependencies
                    .GroupBy(d => d.TargetFramework)
                    .OrderBy(ds => ds.Key);

                OnlyHasAllFrameworks = dependencySets.Count() == 1 && dependencySets.First().Key == null;

                foreach (var dependencySet in dependencySets)
                {
                    var targetFramework = dependencySet.Key == null
                                              ? "All Frameworks"
                                              : NuGetFramework.Parse(dependencySet.Key).ToFriendlyName();

                    if (!DependencySets.ContainsKey(targetFramework))
                    {
                        DependencySets.Add(targetFramework,
                            dependencySet.Select(d => d.Id == null ? null : new DependencyViewModel(d.Id, d.VersionSpec)));
                    }
                }
            }
            catch (Exception e)
            {
                DependencySets = null;
                QuietLog.LogHandledException(e);
                // Just set Dependency Sets to null but still render the package.
            }
        }
示例#12
0
 public static IEnumerable <TSource> DistinctBy <TSource, TKey>(this IEnumerable <TSource> source, Func <TSource, TKey> keySelector)
 {
     return
         (source
          ?.GroupBy(keySelector)
          .Select(grp => grp.First()));
 }
        private void ValidateOperators(IEnumerable<IOperator> operatorList)
        {
            var codes = operatorList.Select(op => op.Code).ToList();
            var duplicateCodes = operatorList.Count() != operatorList.Distinct().Count();

            if (duplicateCodes) {
                var groupedCodes = operatorList.GroupBy(x => x.Code);
                var moreThanOneCodeGroups = groupedCodes.Where(x => x.Count() > 1);

                var sb = new StringBuilder();
                sb.AppendLine("Operators contain duplicate codes:");

                foreach (var group in moreThanOneCodeGroups) {
                    var groupString = string.Format("\\tThe code {0} is present {1} times in operators {2}", group.Key, group.Count(), string.Join(", ", group.Select(x => x.GetType().Name)));
                    sb.AppendLine(groupString);
                }

                throw new ArgumentException(sb.ToString());
            }

            if (codes.Any(x => string.IsNullOrWhiteSpace(x))) {
                var whitespaceCodes = operatorList.Where(x => string.IsNullOrWhiteSpace(x.Code));

                var sb = new StringBuilder();
                sb.AppendLine("Operators contain empty codes:");

                foreach (var op in whitespaceCodes) {
                    var groupString = string.Format("\\tThe code of {0} is empty", op.GetType().Name);
                    sb.AppendLine(groupString);
                }

                throw new ArgumentException(sb.ToString());
            }
        }
示例#14
0
        /// <summary>
        /// 创建PartDrawingDto
        /// </summary>
        public static List <PartDrawingDto> Create(IEnumerable <PartItemDoc> sourceData)
        {
            /*
             * return sourceData?
             *  .GroupBy(item => new { item.PartNumber, item.PartVersion, item.PartName })
             *  .Select(grp => new PartDrawingDto
             *  {
             *      PartNumber = grp.Key.PartNumber,
             *      PartVersion = grp.Key.PartVersion,
             *      PartName = grp.Key.PartName,
             *      //文档版本
             *      Versions = buildVersionList(grp)
             *  })
             *  .OrderBy(d => d.PartNumber)
             *  .ThenBy(d => d.PartVersion)
             *  .ToList();
             */

            return(sourceData?
                   .GroupBy(item => new { item.PartNumber, item.PartVersion, item.PartName })
                   .Select(grp => new PartDrawingDto
            {
                PartNumber = grp.Key.PartNumber,
                PartVersion = grp.Key.PartVersion,
                PartName = grp.Key.PartName,
                //文档项
                PartDocs = buildDocList(grp)
            })
                   .OrderBy(d => d.PartNumber)
                   .ThenBy(d => d.PartVersion)
                   .ToList());
        }
        async Task IEventProcessor.ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> messages)
        {
            var partitionedMessages = messages.GroupBy(data => data.PartitionKey).ToDictionary(datas => datas.Key, datas => datas.ToList());

            //For each partition spawn a Task which will sequentially iterate over its own block
            //Wait for all Tasks to complete, before proceeding.
            await Task.WhenAll(partitionedMessages.Select(partition => Task.Run(async () =>
            {
                var block = partition.Value;
                foreach (var eventData in block)
                {
                    try
                    {
                        var data = Encoding.UTF8.GetString(eventData.GetBytes());

                        System.Console.WriteLine(DateTime.Now + ":Message received.  Partition: '{0}', Data: '{1}', Partition Key: '{2}'", context.Lease.PartitionId, data, eventData.PartitionKey);
                    }
                    catch (Exception e)
                    {
                        //do something with your logs..
                    }
                }
            })));

            //Call checkpoint every 5 minutes, so that worker can resume processing from the 5 minutes back if it restarts.
            if (checkpointStopWatch.Elapsed > TimeSpan.FromMinutes(5))
            {
                await context.CheckpointAsync();
                checkpointStopWatch.Restart();
            }
        }
 public NamespacePropertyProvider(
     IEnumerable<KeyValuePair<string, IPropertyProvider>> elements)
 {
     foreach (var grouping in elements.GroupBy(l => l.Key, l => l.Value)) {
         items.Add(grouping.Key, (IPropertyProviderExtension) PropertyProvider.Compose(grouping));
     }
 }
示例#17
0
 public void LoadTextureItems(IEnumerable<TextureItem> items)
 {
     foreach (var g in items.GroupBy(x => x.Package))
     {
         g.Key.LoadTextures(g);
     }
 }
示例#18
0
 public void Add(IEnumerable<TemporaryIdentifier> temporaryIdentifiers)
 {
     foreach (var identifier in temporaryIdentifiers.GroupBy(t => t.Context))
     {
         identifiers.Add(identifier.Key, identifier.Select(grouping => grouping.Identifier).ToArray());
     }
 }
示例#19
0
 /// <summary>
 /// Проверить, что все хабы идут в правильной последовательности
 /// </summary>
 public static string ValidateSequenceHub(IEnumerable<DeliveryModel> deliveries)
 {
     if (deliveries == null)
     {
         throw new ArgumentNullException("deliveries", @"Null reference.");
     }
     if (!deliveries.Any())
     {
         throw new ArgumentException(@"Deliveries not contains any item.", "deliveries");
     }
     if (deliveries.GroupBy(x => x.CaseNumber).Count() != 1)
     {
         throw new ArgumentException(
             @"Deliveries contains more than one case. It is necessary to pass a list with onle one case.", "deliveries");
     }
     var previousEventType = EventType.UnknownType;
     for (int i = 0; i < deliveries.Count(); i++)
     {
         var delivery = deliveries.ElementAt(i);
         if (i == 0 && delivery.EventTypeEnum != EventType.ActualTruckDeparture)
         {
             return string.Format("{0}. {1} {2}", delivery.CaseNumber, "First place must be",
                 EventType.ActualTruckDeparture.GetDescription());
         }
         if (delivery.EventTypeEnum == previousEventType)
         {
             return string.Format("{0}. Previous and current event type is same \"{1}\".", delivery.CaseNumber,
                 delivery.EventTypeEnum);
         }
         previousEventType = delivery.EventTypeEnum;
     }
     return string.Empty;
 }
        public void Process(IEnumerable<BasicSerializedDeliveryEventArgs<FileMessage>> operations)
        {
            _logger.Trace("[Start]: Start file batch processing.");

            var groupedOperations = operations.GroupBy(p => p.Body.FileName);

            IList<Task> processingOperations = new List<Task>();

            foreach (var groupedOperation in groupedOperations)
            {
                var operationBatch = new OperationBatch(groupedOperation.Key, groupedOperation.ToList());
                IFileOperationProcessor fileOperationProcessor = _fileOperationProcessorFactory.Invoke(_fileTransferManager);

                var processingOperation = fileOperationProcessor.ProcessBatch(operationBatch);
                processingOperations.Add(processingOperation);
            }

            try
            {
                Task.WaitAll(processingOperations.ToArray());
            }
            catch (AggregateException ex)
            {
                for (int i = 0; i < ex.InnerExceptions.Count; ++i)
                {
                    _logger.Error(ex.InnerExceptions[i]);
                }
            }
            finally
            {
                _logger.Trace("[End]: End file batch processing.");
            }
        }
 private static IEnumerable<object> Reduce(IEnumerable<dynamic> source)
 {
     foreach (var events in source
         .GroupBy(@event => @event.ShoppingCartId))
     {
         var cart = new ShoppingCart { Id = events.Key };
         foreach (var @event in events.OrderBy(x => x.Timestamp))
         {
             switch ((string)@event.Type)
             {
                 case "Create":
                     cart.Customer = new ShoppingCartCustomer
                     {
                         Id = @event.CustomerId,
                         Name = @event.CustomerName
                     };
                     break;
                 case "Add":
                     cart.AddToCart(@event.ProductId, @event.ProductName, (decimal)@event.Price);
                     break;
                 case "Remove":
                     cart.RemoveFromCart(@event.ProductId);
                     break;
             }
         }
         yield return new
         {
             ShoppingCartId = cart.Id,
             Aggregate = RavenJObject.FromObject(cart)
         };
     }
 }
示例#22
0
        protected Line ChildElement(Unit left = default(Unit),
            Unit top = default(Unit),
            Unit innerHeight = default(Unit),
            bool breakable = false,
            bool followLineHeight = false,
            Unit border = default(Unit),
            bool keepWithNextLine = false,
            Behaviors behavior = null,
            IEnumerable<Line> children = null)
        {
            LayoutedElement element;
            if (children == null)
            {
                element = new LayoutedElement(new TestSpecification(), Children.Empty);
            }
            else
            {
                element = new LayoutedElement(new TestSpecification(), new Children(children.GroupBy(x => x.Top).SelectMany(x => x)));
            }

            element.Left = left;
            element.ForcedInnerHeight = innerHeight;
            element.Specification.FollowLineHeight = followLineHeight;
            element.Specification.Breakable = breakable;
            element.Specification.Margins = new Margins { Bottom = border, Left = border, Right = border, Top = border };
            element.Specification.Behavior = behavior ?? new NullBehavior();

            return new Line(top, keepWithNextLine, element);
        }
示例#23
0
 /// <summary>
 /// For each PID chooses the last reported process.
 /// </summary>
 protected IReadOnlyList <ReportedProcess> CoalesceProcesses(IEnumerable <ReportedProcess> processes)
 {
     return(processes?
            .GroupBy(p => p.ProcessId)
            .Select(grp => grp.Last())
            .ToList());
 }
            /// <summary>
            /// Erzeugt eine neue Verwaltung.
            /// </summary>
            /// <param name="definition">Die Definition der Aufzeichnung.</param>
            /// <param name="exceptions">Alle Ausnahmen zur Aufzeichnung.</param>
            /// <exception cref="ArgumentNullException">Es wurde keine Aufzeichnung angegeben.</exception>
            public _Schedule( IScheduleDefinition definition, IEnumerable<PlanException> exceptions = null )
            {
                // Validate
                if (definition == null)
                    throw new ArgumentNullException( "plan" );

                // Remember
                Definition = definition;

                // Default
                if (exceptions == null)
                    exceptions = Enumerable.Empty<PlanException>();

                // Validate exceptions
                foreach (var exception in exceptions)
                    if (exception.ExceptionDate.TimeOfDay != TimeSpan.Zero)
                        throw new ArgumentException( string.Format( Properties.SchedulerResources.Exception_NotAPureDate, exception.ExceptionDate ), "exceptions" );

                // Cross validate
                foreach (var exception in exceptions.GroupBy( e => e.ExceptionDate ))
                    if (exception.Count() > 1)
                        throw new ArgumentException( string.Format( Properties.SchedulerResources.Exception_DuplicateDate, exception.Key ), "exceptions" );

                // Order plan
                m_Exceptions = exceptions.ToDictionary( e => e.ExceptionDate );
            }
        public override async Task<IEnumerable<UIPackageMetadata>> GetMetadata(IEnumerable<PackageIdentity> packages, CancellationToken token)
        {
            List<UIPackageMetadata> results = new List<UIPackageMetadata>();

            foreach (var group in packages.GroupBy(e => e.Id, StringComparer.OrdinalIgnoreCase))
            {
                if (group.Count() == 1)
                {
                    // optimization for a single package
                    var package = group.Single();

                    IPackage result = V2Client.FindPackage(package.Id, SemanticVersion.Parse(package.Version.ToString()));

                    if (result != null)
                    {
                        results.Add(GetVisualStudioUIPackageMetadata(result));
                    }
                }
                else
                {
                    // batch mode
                    var foundPackages = V2Client.FindPackagesById(group.Key)
                        .Where(p => group.Any(e => VersionComparer.VersionRelease.Equals(e.Version, NuGetVersion.Parse(p.Version.ToString()))))
                        .Select(p => GetVisualStudioUIPackageMetadata(p));

                    results.AddRange(foundPackages);
                }
            }

            return results;
        }
 void ValidateMigrations(IEnumerable<Type> migrations)
 {
     if (migrations.GroupBy(m => m.Namespace).Count() > 1)
     {
         throw new PageTypeBuilderException();
     }
 }
 private static bool IsPossibleSqlNPlus1(IEnumerable<PetaTuning> list)
 {
     return list
         .GroupBy(x => x.Sql)
         .Where(x => x.Count() > 2)
         .Any();
 }
示例#28
0
 public HomepageViewModel(IEnumerable<BlogEntryForList> blogList, string title, BlogArchive blogArchive, IEnumerable<TagCloudViewModel> tagCloud)
 {
     BlogList = blogList.GroupBy(b => b.PostedAt.Date, b => new BlogItemViewModel(b)).OrderByDescending(l => l.Key);
     Title = title;
     BlogArchive = blogArchive;
     TagCloud = tagCloud;
 }
示例#29
0
        public Measurement Aggregate(IEnumerable<Measurement> measurements)
        {
            var highValue = measurements.GroupBy(m => m.HighValue)
                .OrderByDescending(g => g.Count())
                .Select(g => g.Key).FirstOrDefault();

            var lowValue = measurements.GroupBy(m => m.LowValue)
                .OrderByDescending(g => g.Count())
                .Select(g => g.Key).FirstOrDefault();

            return new Measurement()
                       {
                           HighValue = highValue,
                           LowValue = lowValue
                       };
        }
        public IDictionary <string, Dictionary <int, Dictionary <string, IEnumerable <PeriodisedValue> > > > PeriodiseIlr(IEnumerable <string> conRefNumbers, IEnumerable <FM70PeriodisedValues> fm70Data)
        {
            var contractsFromIlr = fm70Data.Select(x => x.ConRefNumber).Distinct().ToList();

            return(conRefNumbers.Contains(NotApplicable) || !contractsFromIlr.Any(x => conRefNumbers.Contains(x)) ?
                   new Dictionary <string, Dictionary <int, Dictionary <string, IEnumerable <PeriodisedValue> > > >(StringComparer.OrdinalIgnoreCase)
            {
                { NotApplicable, new Dictionary <int, Dictionary <string, IEnumerable <PeriodisedValue> > >() }
            } :

                   fm70Data?
                   .GroupBy(x => conRefNumbers.Contains(x.ConRefNumber)?x.ConRefNumber : NotApplicable)
                   .ToDictionary(
                       cr => cr.Key,
                       crv => crv.Select(x => x)
                       .GroupBy(x => x.FundingYear)
                       .ToDictionary(
                           fy => fy.Key,
                           fyv => fyv.Select(x => x)
                           .GroupBy(x => x.DeliverableCode)
                           .ToDictionary(
                               dc => dc.Key,
                               dcv => MapIlrPeriodisedValues(crv.Key, dcv.Key, dcv.ToList()),
                               StringComparer.OrdinalIgnoreCase))));
        }
示例#31
0
        private void WriteDocuments(IEnumerable<IMember> members)
        {
            var config = new TemplateServiceConfiguration
            {
                BaseTemplateType = typeof (MarkdownTemplateBase<>)
            };
            string template = getTemplate();
            // You can use the @inherits directive instead (this is the fallback if no @inherits is found).
            var types = members.GroupBy(m => m.TypeName);
            using (var razorService = RazorEngineService.Create(config))
            {
                foreach (var typeMembers in types)
                {
                    var result = razorService.RunCompile(template, "type", typeof(DocumentModel), new DocumentModel
                        {
                            TypeName = typeMembers.Key,
                            Members = typeMembers
                        });

                    CreateDocument((typeMembers.First() as MemberBase)?.AssemblyName ?? "UnknownAssembly",
                        typeMembers.Key,
                        result);
                }
            }
        }
        protected override Chart[] HandleResults(IEnumerable<RequestDataResults> results)
        {
            var charts = new List<Chart>();
            var query = results.GroupBy(r => r.Request);
            query.ToList().ForEach(group =>
            {
                int pos = group.Key.LastIndexOf('?');
                string name = group.Key;
                if (pos != -1)
                {
                    int count = charts.Count(c => c.Request == group.Key);
                    name = group.Key.Substring(0, pos);
                    if (count > 0)
                    {
                        name += count;
                    }

                }
                var stream = new MemoryStream();
                var trendChartBuilder = new TrendChartBuilder();
                trendChartBuilder.Generate(stream, group.ToList());
                charts.Add(new Chart { Data = stream.GetBuffer(), Name = name, Request = group.Key});
            });
            return charts.ToArray();
        }
        /// <summary>
        /// Extracts the metrics from the given <see cref="XElement">XElements</see>.
        /// </summary>
        /// <param name="methods">The methods.</param>
        /// <param name="class">The class.</param>
        private static void SetMethodMetrics(IEnumerable<XElement> methods, Class @class)
        {
            foreach (var methodGroup in methods.GroupBy(m => m.Element("Name").Value))
            {
                var method = methodGroup.First();

                // Exclude properties and lambda expressions
                if (method.Attribute("skippedDueTo") != null
                    || method.HasAttributeWithValue("isGetter", "true")
                    || method.HasAttributeWithValue("isSetter", "true")
                    || Regex.IsMatch(methodGroup.Key, "::<.+>.+__"))
                {
                    continue;
                }

                var metrics = new[]
                {
                    new Metric(
                        "Cyclomatic Complexity",
                        methodGroup.Max(m => int.Parse(m.Attribute("cyclomaticComplexity").Value, CultureInfo.InvariantCulture))),
                    new Metric(
                        "Sequence Coverage",
                        methodGroup.Max(m => decimal.Parse(m.Attribute("sequenceCoverage").Value, CultureInfo.InvariantCulture))),
                    new Metric(
                        "Branch Coverage",
                        methodGroup.Max(m => decimal.Parse(m.Attribute("branchCoverage").Value, CultureInfo.InvariantCulture)))
                };

                @class.AddMethodMetric(new MethodMetric(methodGroup.Key, metrics));
            }
        }
        public override HandRanking Handle(IEnumerable<Card> hand)
        {
            if (!hand.GroupBy(x => x.Suit.Value).Any(grp => grp.Count() == 5))
            {
                return next.Handle(hand);
            }

            var valueArray = hand.Select(c => (int)c.Value).ToArray();
            Array.Sort(valueArray);

            CanHandle = true;

            if(valueArray[0] < (int)CardValue.Ten)
                return next.Handle(hand);

            for (int i = 0; i < valueArray.Length - 1; i++)
            {
                if ((valueArray[i] + 1) != valueArray[i + 1])
                {
                    CanHandle = false;
                    return next.Handle(hand);
                }
            }
            return HandRanking.RoyalFlush;
        }
示例#35
0
        public void RunTests(IEnumerable<TestCase> tests, IRunContext runContext, IFrameworkHandle frameworkHandle)
        {
            this.frameworkHandle = frameworkHandle;

            var testLogger = new TestLogger(frameworkHandle);

            testLogger.SendMainMessage("Execution started");

            foreach (var group in tests.GroupBy(t => t.Source))
            {
                testLogger.SendInformationalMessage(String.Format("Running selected: '{0}'", group.Key));

                try
                {
                    using (var sandbox = new Sandbox<Executor>(group.Key))
                    {
                        var assemblyDirectory = new DirectoryInfo(Path.GetDirectoryName(group.Key));
                        Directory.SetCurrentDirectory(assemblyDirectory.FullName);
                        sandbox.Content.Execute(this, group.Select(t => t.FullyQualifiedName).ToArray());
                    }
                }
                catch (Exception ex)
                {
                    testLogger.SendErrorMessage(ex, String.Format("Exception found while executing tests in group '{0}'", group.Key));

                    // just go on with the next
                }
            }

            testLogger.SendMainMessage("Execution finished");
        }
 public override bool CanHandle(IEnumerable<RequestDataResults> results)
 {
     var query = results.GroupBy(x => x.Date.ToShortDateString());
     if (query.Count() > 1)
         return true;
     return false;
 }
示例#37
0
        public GameService(
            IListener listener,
            ILogger <GameService> logger,
            GameState state,
            PacketProcessExecutor packetProcessExecutor,
            IEnumerable <ILoopTask> loopTasks,
            IDbConnection dbConnection,
            DatabaseOptions dbOptions
            )
        {
            _logger    = logger;
            _loopTasks = loopTasks?
                         .GroupBy(x => x.Order)
                         .OrderBy(x => x.Key)
                         .Select(x => new Tuple <int, ILoopTask[]>(x.Key, x.ToArray()))
                         .ToArray() ?? throw new ArgumentNullException(nameof(LoopTasks));

            _state    = state ?? throw new ArgumentNullException(nameof(state));
            _listener = listener ?? throw new ArgumentNullException(nameof(listener));
            _packetProcessExecutor = packetProcessExecutor ?? throw new ArgumentNullException(nameof(packetProcessExecutor));
            _db        = dbConnection ?? throw new ArgumentNullException(nameof(dbConnection));
            _dbOptions = dbOptions ?? throw new ArgumentNullException(nameof(dbOptions));

            _listener.OnClientConnect    += Listener_OnClientConnect;
            _listener.OnClientData       += Listener_OnClientData;
            _listener.OnClientDisconnect += Listener_OnClientDisconnect;
        }
示例#38
0
 OrderBySleepMinuteFrequency(IEnumerable <Shift> shifts)
 {
     return(shifts?.
            GroupBy(s => s.EmployeeID)?.
            Select(sg => (employeeID: sg.Key,
                          freq: SleepCountsByMinute(sg.ToList()).Max(out int id),
                          min: id))?.
            OrderByDescending(t => t.freq));
 }
        public decimal Calculate(IEnumerable <IProduct> products)
        {
            var groupedProducts = products?.GroupBy(m => m.Name).ToList();

            return((groupedProducts != null &&
                    packageProductNames.All(m => groupedProducts.Any(p => p.Key == m)))
                                ? discountAmount * groupedProducts.Select(m => m.Count()).Min()
                                 : 0);
        }
示例#40
0
        public StyleItemLookup(IEnumerable <TItem> items, IDirectory <TValue> parent)
        {
            Parent = parent;

            var list = items?
                       .GroupBy(i => i.Name)
                       .ToDictionary(g => g.Key, g => g.First().Value);

            _dictionary = list ?? new Dictionary <string, TValue>();
        }
 private IEnumerable <FM70PeriodisedValuesYearly> GroupFm70DataIntoYears(IEnumerable <FM70PeriodisedValues> fm70Data)
 {
     return(fm70Data?
            .GroupBy(x => x.FundingYear)
            .Select(x => new FM70PeriodisedValuesYearly
     {
         FundingYear = x.Key,
         Fm70PeriodisedValues = x.Select(pv => pv).ToList()
     }) ?? Enumerable.Empty <FM70PeriodisedValuesYearly>());
 }
示例#42
0
 IList <ApiHeader> getHeaders(IEnumerable <KeyValuePair <string, string> > globalHeaders)
 {
     return(globalHeaders?
            .GroupBy(_ => _.Key)
            .Select(_ => new ApiHeader
     {
         Name = _.Key,
         Values = _.Select(__ => __.Value).Where(__ => __ != null).ToArray(),
     })
            .ToList());
 }
        public List <UploadRowErrorViewModel> MapErrors(IEnumerable <UploadError> errors)
        {
            var result = errors
                         ?.GroupBy(m => m.Row)
                         .Select(MapError)
                         .Where(m => m != null)
                         .OrderBy(m => m.RowNumber)
                         ?.ToList();

            return(result);
        }
示例#44
0
        public static IEnumerable <T> Duplicates <T, K>(this IEnumerable <T> enumerable, Func <T, K> groupByFunc)
        {
            if (groupByFunc == null)
            {
                throw new ArgumentNullException(nameof(groupByFunc));
            }

            return(enumerable?.GroupBy(groupByFunc)
                   .Where(x => x.Count() > 1)
                   .SelectMany(x => x.AsEnumerable())
                   ?? throw new ArgumentNullException(nameof(enumerable)));
        }
示例#45
0
        public static IEnumerable <IEnumerable <T> > GroupByHash <T, TProperty>(this IEnumerable <T> items,
                                                                                params Func <T, TProperty>[] properties)
        {
            if (properties == default)
            {
                throw new ArgumentNullException(nameof(properties));
            }

            var result = items?
                         .GroupBy(s => properties.GetSequenceHash(p => p(s))).ToArray();

            return(result ?? Enumerable.Empty <IEnumerable <T> >());
        }
示例#46
0
        /// <summary>
        /// Redirects the client to the specified file.
        /// </summary>
        public void ReturnFile(Stream stream, string fileName, string mimeType, IEnumerable <KeyValuePair <string, string> > additionalHeaders = null)
        {
            var returnedFileStorage = Configuration.ServiceLocator.GetService <IReturnedFileStorage>();
            var metadata            = new ReturnedFileMetadata()
            {
                FileName          = fileName,
                MimeType          = mimeType,
                AdditionalHeaders = additionalHeaders?.GroupBy(k => k.Key, k => k.Value)?.ToDictionary(k => k.Key, k => k.ToArray())
            };

            var generatedFileId = returnedFileStorage.StoreFile(stream, metadata).Result;

            RedirectToUrl("~/dotvvmReturnedFile?id=" + generatedFileId);
        }
        public ICollection <CatsByOwnerGender> Map(IEnumerable <Person> people) =>
        people?.GroupBy(person => person.Gender, StringComparer.OrdinalIgnoreCase)
        .Select(genderGroup => new CatsByOwnerGender
        {
            OwnerGender = genderGroup.Key.Capitalize(),

            CatNames = genderGroup
                       .Where(p => p.Pets != null)
                       .SelectMany(p => p.Pets
                                   .Where(pet => CatType.Equals(pet.Type, StringComparison.OrdinalIgnoreCase))
                                   .Select(pet => pet.Name))
                       .OrderBy(name => name)
                       .ToArray()
        }).ToArray();
示例#48
0
 private static IEnumerable <PullRequestSummary> Map(IEnumerable <Models.AzureDevops.GitPullRequest> pullRequests)
 {
     return(pullRequests?
            .GroupBy(c => c?.createdBy?.displayName)
            .Select(g => new PullRequestSummary
     {
         AuthorName = g.Key,
         TotalCount = g.Count(),
         LastActivity = g.Max(c => DateTime.Parse(c.creationDate)),
         AbandonedCount = g.Count(c => string.Equals("abandoned", c.status, StringComparison.CurrentCultureIgnoreCase)),
         ActiveCount = g.Count(c => string.Equals("active", c.status, StringComparison.CurrentCultureIgnoreCase)),
         CompletedCount = g.Count(c => string.Equals("completed", c.status, StringComparison.CurrentCultureIgnoreCase)),
     })
            .OrderByDescending(c => c.LastActivity));
 }
        /// <summary>
        /// Redirects the client to the specified file.
        /// </summary>
        public static void ReturnFile(this IDotvvmRequestContext context, Stream stream, string fileName, string mimeType, IEnumerable <KeyValuePair <string, string> > additionalHeaders = null)
        {
            var returnedFileStorage = context.Services.GetService <IReturnedFileStorage>();
            var metadata            = new ReturnedFileMetadata()
            {
                FileName          = fileName,
                MimeType          = mimeType,
                AdditionalHeaders = additionalHeaders?.GroupBy(k => k.Key, k => k.Value)?.ToDictionary(k => k.Key, k => k.ToArray())
            };

            var generatedFileId = returnedFileStorage.StoreFile(stream, metadata).Result;

            context.SetRedirectResponse(context.TranslateVirtualPath("~/dotvvmReturnedFile?id=" + generatedFileId));
            throw new DotvvmInterruptRequestExecutionException(InterruptReason.ReturnFile, fileName);
        }
示例#50
0
        public WordList(
            IEnumerable <string>?values,
            IEnumerable <WordSequence>?sequences,
            StringComparison?comparison = null)
        {
            Comparer   = StringComparer.FromComparison(comparison ?? DefaultComparison);
            Comparison = comparison ?? DefaultComparison;

            Values = values?.ToImmutableHashSet(Comparer) ?? ImmutableHashSet <string> .Empty;

            Sequences = sequences?
                        .GroupBy(f => f.First, Comparer)
                        .ToImmutableDictionary(f => f.Key, f => f.ToImmutableArray(), Comparer)
                        ?? ImmutableDictionary <string, ImmutableArray <WordSequence> > .Empty;
        }
 public BuilderContext(
     IEnumerable <ImageMeta> imageMetas,
     BuildContext context)
 {
     inline             = new Stack <TextSpan>();
     rows               = new List <List <Container> >();
     cells              = new List <Container>();
     positionRecords    = new List <PositionRecord>();
     useNotifyContainer = false;
     this.imageMetas    = imageMetas?
                          .GroupBy(item => item.name)
                          .Select(group => group.ToArray().First())
                          .ToDictionary(
         meta => meta.name,
         meta => meta);
     spanRecognizers = new List <TapGestureRecognizer>();
     useRecognizer   = false;
     this.context    = context;
 }
示例#52
0
        private static IEnumerable <DisciplineResults> GroupResultsByDiscipline(IEnumerable <Result> results)
        {
            return(results?
                   .GroupBy(pair => pair.Discipline)
                   .Select(pairs =>
            {
                var discipline = pairs.Key;

                discipline.Description = null;

                return new DisciplineResults
                {
                    Discipline = discipline,
                    Results = pairs.Select(result =>
                    {
                        result.Discipline = null;
                        return result;
                    })
                };
            }));
        }
示例#53
0
        public static IDictionary <TKey, IEnumerable <T> > AsDictionary <T, TKey>(this IEnumerable <T> items, Func <T, TKey> keyGetter)
        {
            if (keyGetter == default)
            {
                throw new ArgumentNullException(nameof(keyGetter));
            }

            var result = new Dictionary <TKey, IEnumerable <T> >();

            var keyGroups = items?
                            .GroupBy(s => keyGetter.Invoke(s)).ToArray();

            foreach (var keyGroup in keyGroups.IfAny())
            {
                result.Add(
                    key: keyGroup.Key,
                    value: keyGroup);
            }

            return(result);
        }
    /// <summary>
    /// Redirects the client to the specified file.
    /// </summary>
    public static void ReturnFile(this IDotvvmRequestContext context, Stream stream, string fileName, string mimeType, IEnumerable <KeyValuePair <string, string> > additionalHeaders = null)
    {
        var returnedFileStorage = context.Services.GetService <IReturnedFileStorage>();

        if (returnedFileStorage == null)
        {
            throw new DotvvmFileStorageMissingException($"Unable to resolve service for type '{typeof(IReturnedFileStorage).Name}'. " +
                                                        $"Visit https://www.dotvvm.com/docs/tutorials/advanced-returning-files for more details!");
        }

        var metadata = new ReturnedFileMetadata()
        {
            FileName          = fileName,
            MimeType          = mimeType,
            AdditionalHeaders = additionalHeaders?.GroupBy(k => k.Key, k => k.Value)?.ToDictionary(k => k.Key, k => k.ToArray())
        };

        var generatedFileId = returnedFileStorage.StoreFile(stream, metadata).Result;

        context.SetRedirectResponse(context.TranslateVirtualPath("~/dotvvmReturnedFile?id=" + generatedFileId));
        throw new DotvvmInterruptRequestExecutionException(InterruptReason.ReturnFile, fileName);
    }
示例#55
0
        public static IEnumerable <IDebugState> BuildTree(IEnumerable <IDebugState> source)
        {
            var groups = source?.GroupBy(i => i.ParentID) ?? new List <IGrouping <Guid?, IDebugState> >();

            if (!groups.Any())
            {
                return(new List <IDebugState>());
            }
            var roots = groups.First(g => !g.Key.HasValue).ToList();

            roots = roots.Where(state => state.StateType != StateType.Duration).ToList();
            if (roots.Any())
            {
                var dict = groups.Where(g => g.Key.HasValue).ToDictionary(g => g.Key.Value, g => g.ToList());
                for (var i = 0; i < roots.Count(); i++)
                {
                    AddChildren(roots[i], dict);
                }
            }
            var debugStates = roots?.DistinctBy(state => new { state.ID, state.StateType, state.Children }).ToList();

            return(debugStates);
        }
示例#56
0
        /// <summary>
        /// Generates a class diagram.
        /// <para>If <paramref name="accessFilter"/> is specified,
        /// contents that do not correspond to the filter are not described.</para>
        /// </summary>
        /// <param name="title">Title of class diagram</param>
        /// <param name="classInfoList">Classes to be included in a class diagram</param>
        /// <param name="relations">Relations to be included in a class diagram</param>
        /// <param name="accessFilter">Access level filter</param>
        /// <param name="excludedClasses">A collection of class names not to be written to a class diagram</param>
        /// <returns>Class diagram text written in PlantUML</returns>
        public static string Generate(string title, IEnumerable <ClassInfo> classInfoList, IEnumerable <Relation> relations, Modifier accessFilter = Modifiers.AllAccessLevels, IEnumerable <string> excludedClasses = null)
        {
            var writer = new CodeWriter(NewLine);

            WriteHeader(writer, title);

            var groups = classInfoList?.GroupBy(cls => cls.Package)
                         ?? Enumerable.Empty <IGrouping <string, ClassInfo> >();

            foreach (var group in groups.OrderBy(g => g.Key))
            {
                writer.Write($"package {group.Key} {{").NewLine().NewLine();
                writer.IncreaseIndent();

                foreach (var cls in group.OrderBy(c => c.Name))
                {
                    WriteClassAndUpdateExcludedClasses(writer, cls, accessFilter, ref excludedClasses);
                }

                writer.DecreaseIndent();
                writer.Write("}").NewLine().NewLine();
            }

            foreach (var relation in relations ?? Enumerable.Empty <Relation>())
            {
                // Does not draw self relation
                if (relation.Class1 == relation.Class2)
                {
                    continue;
                }

                WriteRelation(writer, relation, excludedClasses);
            }

            WriteFooter(writer);
            return(writer.ToString());
        }
示例#57
0
        private static IEnumerable <ContributorSummary> Map(IEnumerable <Models.AzureDevops.GitCommitRef> commits)
        {
            //For Git commits, author vs committer here is a good explanation:
            //https://stackoverflow.com/questions/18750808/difference-between-author-and-committer-in-git



            // Email addresses and names can be inconsistent. (ex: [email protected] and [email protected] can both be there but are the same person)
            var nameByEmail = commits.ToLookup(c => c?.author?.email ?? "unknown")
                              .ToDictionary(g => g?.Key ?? "unknown", g => g?.FirstOrDefault()?.author?.name ?? "unknown");

            return(commits?
                   .GroupBy(c => nameByEmail[c.author.email])
                   .Select(g => new ContributorSummary
            {
                AuthorName = g.Key,
                CommitCount = g.Count(),
                LastActivity = g.Max(c => c?.author?.date?.Date),
                Additions = g.Sum(c => c.changeCounts?.Add),
                Edits = g.Sum(c => c.changeCounts?.Edit),
                Deletions = g.Sum(c => c.changeCounts?.Delete),
            })
                   .OrderByDescending(c => c.LastActivity));
        }
 /// <summary>
 /// Returns new collection where elements have unique property value.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="source">Source collection.</param>
 /// <param name="selector">Selector for a property.</param>
 /// <returns></returns>
 public static IEnumerable <T> DistinctBy <T>(this IEnumerable <T> source, Func <T, object> selector)
 => source?.GroupBy(selector).DefaultIfEmpty().Where(g => g != null).Select(g => g.FirstOrDefault());
示例#59
0
        public static IEnumerable <TestListModel> ToTaskList(IEnumerable <UserTestModel> model)
        {
            var taskListModels = model?.GroupBy(c => c.UnitName).Select(TestListModel.From);

            return(taskListModels);
        }
示例#60
0
 /// <summary>
 /// Returns  Occurence of words in a list
 /// </summary>
 public static IDictionary <string, int> OccurenceOfwords(IEnumerable <string> words)
 {
     return(words?.GroupBy(word => word).ToDictionary(g => g.Key, g => g.Count()));
 }