public IEnumerable<ValidationError> Validate(IList<Benchmark> benchmarks)
        {
#if CORE
            yield break; // todo: implement when it becomes possible
#else
            foreach (var group in benchmarks.GroupBy(benchmark => benchmark.Target.Type.Assembly()))
            {
                foreach (var referencedAssemblyName in group.Key.GetReferencedAssemblies())
                {
                    var referencedAssembly = Assembly.Load(referencedAssemblyName);

                    if (IsJITOptimizationDisabled(referencedAssembly))
                    {
                        yield return new ValidationError(
                            TreatsWarningsAsErrors,
                            $"Assembly {group.Key} which defines benchmarks references non-optimized {referencedAssemblyName.Name}");
                    }
                }

                if (IsJITOptimizationDisabled(group.Key))
                {
                    yield return new ValidationError(
                        TreatsWarningsAsErrors,
                        $"Assembly {group.Key} which defines benchmarks is non-optimized");
                }
            }
#endif
        }
 protected internal IEnumerable<IGrouping<CardFigure, Card>> GetSets(IList<Card> cards, int cardsInSet)
 {
     // broke my original linq up so it can be debugged.  This is a good idea? or bad idea?  Then put it back together
     return cards
               .GroupBy<Card, CardFigure>(key => key.Figure)
               .Where<IGrouping<CardFigure, Card>>(group => group.Count<Card>() == cardsInSet);
 }
 private void GenerateDateRangeCollection()
 {
     _dayForecastCollection = new List<DayForecast>();
     _startDateDaysInMonth = DateTime.DaysInMonth(_startDate.Year, _startDate.Month);
     _endDateDaysInMonth = DateTime.DaysInMonth(_endDate.Year, _endDate.Month);
     _monthDifference = Microsoft.VisualBasic.DateAndTime.DateDiff(Microsoft.VisualBasic.DateInterval.Month, _startDate, _endDate);
     ProcessDayForecastCollection(_startDateDaysInMonth, _startDate, _dayForecastCollection);
     for (int i = 1; i < _monthDifference; i++)
     {
         DateTime inbetweenDt = _startDate.AddMonths(i);
         var inbetweenDtDaysInMonth = DateTime.DaysInMonth(inbetweenDt.Year, inbetweenDt.Month);
         ProcessDayForecastCollection(inbetweenDtDaysInMonth, inbetweenDt, _dayForecastCollection);
     }
     List<DayForecast> weekItem = new List<DayForecast>();
     _weekDayForecastCollection = new List<List<DayForecast>>();
     foreach(var df in _dayForecastCollection)
     {
         weekItem.Add(df);
         if (df.FullDayOfTheWeek == _dayForecastConfiguration.DayEndOfWeek)
         {
             _weekDayForecastCollection.Add(weekItem);
             weekItem = new List<DayForecast>();
         }
     }
     _week = _dayForecastCollection.GroupBy(d => d.FullDayOfTheWeek).Select(gd => gd.Key).ToList();
     //here
 }
 public DesignTimeCompilationException(IList<DiagnosticMessage> compileResponseErrors)
     : base(string.Join(Environment.NewLine, compileResponseErrors.Select(e => e.FormattedMessage)))
 {
     CompilationFailures = compileResponseErrors.GroupBy(g => g.SourceFilePath, StringComparer.OrdinalIgnoreCase)
                                                .Select(g => new CompilationFailure(g.Key, g))
                                                .ToArray();
 }
Пример #5
1
        public MainWindow()
        {
            InitializeComponent();
            Loaded += (sender, e) => ClearValue(SizeToContentProperty);

            _allControllerViewModels =
                (from type in GetType().Assembly.GetTypes()
                 where !type.IsInterface && typeof(IController).IsAssignableFrom(type)
                 let viewModel = new ControllerViewModel((IController)Activator.CreateInstance(type))
                 orderby viewModel.SortIndex, viewModel.Library, viewModel.Description
                 select viewModel).ToList();
            _allControllerViewModels.First().IsChecked = true;
            ControllerGroups.ItemsSource = _allControllerViewModels.GroupBy(viewModel => viewModel.Library);

            _allResolutionViewModels = new[] {
                new ResolutionViewModel(800, 600, 50, 42),
                new ResolutionViewModel(1024, 768, 64, 54),
                new ResolutionViewModel(1280, 1024, 80, 73),
                new ResolutionViewModel(1440, 900, 90, 64),
            };
            _allResolutionViewModels.Last(
                res => res.Width <= SystemParameters.PrimaryScreenWidth &&
                res.Height <= SystemParameters.PrimaryScreenHeight).IsChecked = true;
            Resolutions.ItemsSource = _allResolutionViewModels;

            RunResults.ItemsSource = _runResults;
        }
        public IList<AcceptedUserComment> AddComments(string type, string clientToken, IList<UserComment> userComments)
        {
            if (userComments == null || userComments.Count == 0)
                return null;

            var acceptedComments = new List<AcceptedUserComment>();
            var commentsForEvents = userComments.GroupBy(x=>x.eventId);
            foreach (var eventGroup in commentsForEvents)
            {
                var userInfo = GetUserEventInfo(eventGroup.Key);
                var dddEvent = eventsService.GetServerEventData(eventGroup.Key);
                var eventDetail = eventsService.GetEventDetail(dddEvent);

                if (dddEvent.IsActive)
                {
                    var accepted = addComments(type, eventGroup.Key, eventDetail, userInfo != null ? userInfo.UserName : "", userInfo != null ? userInfo.UserToken : null, clientToken, eventGroup.ToList());
                    acceptedComments.AddRange(accepted);
                }
                else
                {
                    //We don't want the client to keep sending the same message, so respond that it is accepted (even though it's not)
                    var accepted = eventGroup.Select(x => new AcceptedUserComment
                    {
                        eventId = x.eventId,
                        id = x.id,
                        sessionId = x.sessionId
                    });

                    return accepted.ToList();
                }
            }

            return acceptedComments;
        }
        public void SetUp()
        {
            _listaGruppi = new List<SferaAziendeDTO>
            {
                new SferaAziendeDTO {Codice = "AZI01", Gruppo = "GR1", Id = 1},
                new SferaAziendeDTO {Codice = "AZI02", Gruppo = "GR1", Id = 2},
                new SferaAziendeDTO {Codice = "AZI03", Gruppo = "GR2", Id = 3},
                new SferaAziendeDTO {Codice = "AZI04", Gruppo = "GR2", Id = 4},
                new SferaAziendeDTO {Codice = "AZI05", Gruppo = "GR3", Id = 5},
                new SferaAziendeDTO {Codice = "AZI06", Gruppo = "GR3", Id = 6},
                new SferaAziendeDTO {Codice = "AZI07", Gruppo = "GR4", Id = 7},
                new SferaAziendeDTO {Codice = "AZI08", Gruppo = "GR4", Id = 8}
            };

            _aziendaService = MockRepository.GenerateStub<IAziendaService>();
            _aziendaService.Stub(x => x.GetAllGruppi()).Return(_listaGruppi.GroupBy(item => item.Gruppo).ToList());

            _richiestaImportazioneDocumentiBolletteService = MockRepository.GenerateMock<IRichiestaImportazioneDocumentiBolletteService>();
            _importazioneDocumentiBolletteService = MockRepository.GenerateMock<IImportazioneDocumentiBolletteService>();

            _windsorContainer = MockRepository.GenerateStub<IWindsorContainer>();
            _windsorContainer.Stub(x => x.Resolve<IRichiestaImportazioneDocumentiBolletteService>()).Return(_richiestaImportazioneDocumentiBolletteService);
            _windsorContainer.Stub(x => x.Resolve<IImportazioneDocumentiBolletteService>()).Return(_importazioneDocumentiBolletteService);

            _iocContainerService = MockRepository.GenerateStub<IIocContainerService>();
            _iocContainerService.Stub(x => x.GetContainerFromKey(Arg<string>.Is.Anything)).Return(_windsorContainer);

            _utenzaRicezioneDocumentoJob = new UtenzaRicezioneDocumentoJob(_aziendaService, _iocContainerService);
        }
Пример #8
1
        private void OnReferenceLocationsChanged(object sender, IList<InlineRenameLocation> renameLocations)
        {
            int totalFilesCount = renameLocations.GroupBy(s => s.Document).Count();
            int totalSpansCount = renameLocations.Count;

            UpdateSearchText(totalSpansCount, totalFilesCount);
        }
Пример #9
1
 public static int GetPowerScores(IList<string> powerPhrases)
 {
     return powerPhrases
         .GroupBy(e => e)
         .Select(e => new {PowerPhrase = e.Key, Amount = e.Count()})
         .Aggregate(0, (sum, info) => sum + GetPowerScore(info.PowerPhrase, info.Amount));
 }
        public IEnumerable<ValidationError> Validate(IList<Benchmark> benchmarks)
        {
            var errors = new List<ValidationError>();

            foreach (var typeGroup in benchmarks.GroupBy(benchmark => benchmark.Target.Type))
            {
                object benchmarkTypeInstance = null;
                if (!TryCreateBenchmarkTypeInstance(typeGroup.Key, typeGroup, errors, out benchmarkTypeInstance))
                {
                    continue;
                }

                if (!TryToSetParamsFields(benchmarkTypeInstance, typeGroup, errors))
                {
                    continue;
                }

                if (!TryToSetParamsProperties(benchmarkTypeInstance, typeGroup, errors))
                {
                    continue;
                }


                if (!TryToCallSetup(benchmarkTypeInstance, typeGroup, errors))
                {
                    continue;
                }

                ExecuteBenchmarks(benchmarkTypeInstance, typeGroup, errors);
            }

            return errors;
        }
Пример #11
1
        IList<ReceiptItem> MergeReceiptItems(IList<BoughtProduct> boughtProducts)
        {
            string[] barcodes = boughtProducts.Select(bp => bp.Barcode).Distinct().ToArray();
            Dictionary<string, Product> boughtProductSet = m_productRepository
                .GetByBarcodes(barcodes)
                .ToDictionary(p => p.Barcode, p => p);
            Dictionary<string,int> boughtDictionary = boughtProducts.GroupBy(bp => bp.Barcode)
                .ToDictionary(g => g.Key, g => g.Sum(bp => bp.Amount));
            var buyTwoGetOne = new BuyTwoGetOne(m_promotionRepository, m_productRepository);
            Dictionary<string, decimal> boughtProductPromoted = buyTwoGetOne.GetPromoted(boughtDictionary);

            return boughtProducts
                .GroupBy(bp => bp.Barcode)
                .Select(g => new ReceiptItem(boughtProductSet[g.Key], g.Sum(bp => bp.Amount),boughtProductPromoted[g.Key]))
                .ToArray();
        }
Пример #12
1
        /// <summary>
        /// Sort the items by their priority and their index they currently exist in the collection
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        public static IList<IClientDependencyFile> SortItems(IList<IClientDependencyFile> files)
        {
            //first check if each item's order is the same, if this is the case we'll make sure that we order them 
            //by the way they were defined
            if (!files.Any()) return files;

            var firstPriority = files.First().Priority;

            if (files.Any(x => x.Priority != firstPriority))
            {
                var sortedOutput = new List<IClientDependencyFile>();
                //ok they are not the same so we'll need to sort them by priority and by how they've been entered
                var groups = files.GroupBy(x => x.Priority).OrderBy(x => x.Key);
                foreach (var currentPriority in groups)
                {
                    //for this priority group, we'll need to prioritize them by how they are found in the files array
                    sortedOutput.AddRange(currentPriority.OrderBy(files.IndexOf));
                }
                return sortedOutput;
            }

            //they are all the same so we can really just return the original list since it will already be in the 
            //order that they were added.
            return files;
        } 
        public DashboardViewModel(IEnumerable<WebSite> websites, IList<SyncStatus> syncStatuses)
        {
            Instances = syncStatuses.GroupBy(s => s.RoleInstanceId)
                .Select(s => new InstanceViewModel {Name = s.Key, IsOnline = s.First().IsOnline})
                .ToList();

            Sites = websites.Select(w => new SiteViewModel
            {
                Id = w.Id,
                Name = w.Name,
                SyncStatus = Instances.ToDictionary(
                    i => i.Name,
                    i => syncStatuses
                        .Where(s => s.SiteName.Equals(w.Name, StringComparison.InvariantCultureIgnoreCase)
                            && s.RoleInstanceId.Equals(i.Name, StringComparison.InvariantCultureIgnoreCase)
                        )
                        .Select(s =>
                            new SiteSyncViewModel
                            {
                                SyncError = s.LastError != null ? s.LastError.Message : null,
                                SyncStatus = s.Status.ToString(),
                                SyncTime = s.SyncTimestamp
                            }
                        )
                        .FirstOrDefault() ?? new SiteSyncViewModel{SyncStatus = "NotDeployed"}
                )
            });
        }
Пример #14
1
        //Get aggregates i.e WinPercentage and AverageBet for each customer in provided list of bets
        public IList<Customer> GetCustomersStatistics(IList<Bet> settledBets)
        {
            var customers = new List<Customer>();

            customers = settledBets.GroupBy(b => b.CustomerCode)
                        .Select(group => new Customer(group.Key, (group.Count(g => g.Win > 0) * 100) / group.Count(), Math.Round(group.Average(g => g.Stake), 2))).ToList();
            return customers.OrderByDescending(o=>o.WinPercentage).ToList();
        }
Пример #15
1
		public SearchRootNode(string title, IList<SearchResultMatch> results)
		{
			this.Title = title;
			this.results = results.Select(r => new SearchResultNode(r)).ToArray();
			
			fileCount = results.GroupBy(r => r.FileName).Count();
			this.Children = this.results;
			this.IsExpanded = true;
		}
Пример #16
1
        public static int? FindMajorant(IList<int> numbers)
        {
            int minimumOccurencesRequired = (numbers.Count / 2) + 1;

            return numbers
                .GroupBy(x => x)
                .Where(g => g.Count() >= minimumOccurencesRequired)
                .Select(g => (int?)g.Key)
                .SingleOrDefault();
        }
Пример #17
1
        private void CategoryFiller(IList<Project> projects, Func<Project, string> projectPropertySelector, IList<CategoryValue> list)
        {
            var summary = projects.GroupBy(projectPropertySelector).Select(g => new { Key = g.Key, Count = g.Count() });
              var total = summary.Sum(t => t.Count);

              foreach (var t in summary)
              {
            list.Add(new CategoryValue() { Value = t.Key, Count = t.Count, Ratio = (decimal)t.Count / (decimal)total });
              }
        }
Пример #18
0
 IList<ReceiptItem> MergeReceiptItems(IList<BoughtProduct> boughtProducts)
 {
     string[] barcodes = boughtProducts.Select(bp => bp.Barcode).Distinct().ToArray();
     Dictionary<string, Product> boughtProductSet = m_repository
         .GetByBarcodes(barcodes)
         .ToDictionary(p => p.Barcode, p => p);
     return boughtProducts
         .GroupBy(bp => bp.Barcode)
         .Select(g => new ReceiptItem(boughtProductSet[g.Key], g.Sum(bp => bp.Amount)))
         .ToArray();
 }
Пример #19
0
 /// <summary>
 ///     Mapping list of timeslot models into list of date models
 /// </summary>
 /// <param name="timeSlots">List of timeslot models</param>
 /// <returns>List of date models</returns>
 public static IList<EventModel.DatesModel> MapToDatesModel(IList<TimeSlot> timeSlots)
 {
     return timeSlots.GroupBy(ts => ts.DateTime.Date, ts => ts)
         .Select(
             tsGrp =>
                 new EventModel.DatesModel()
                 {
                     Date = tsGrp.Key.Date,
                     Times = tsGrp.Select(ts => new EventModel.TimeModel(ts.Id, ts.DateTime.ToString("HH:mm:ss"))).ToList()
                 }).ToList();
 }
 internal override IList<GuoKuItem> GetSpecialItems(IList<CaiWuItem> caiWus, IList<GuoKuItem> guoKus)
 {
     //按凭证号与总金额分组
     var caiWuGroup = caiWus.GroupBy(c => c.GetNumber()).Select(g => new NumberGroupItem { Number = g.Key, Total = g.Sum(i => i.CreditAmount) }).ToList();
     var guoKuGroup = guoKus.GroupBy(c => c.GetNumber()).Select(g => new NumberGroupItem { Number = g.Key, Total = g.Sum(i => i.Amount) }).ToList();
     //比较凭证号与总金额
     var numberAndAmountAreEqual = caiWuGroup.Intersect(guoKuGroup, new NumberGroupItemEqualityComparer()).ToList();
     //根据凭证号与总金额比较结果,取出记录
     var result = guoKus.Where(c => numberAndAmountAreEqual.Select(n => n.Number).Contains(c.GetNumber())).ToList();
     return result;
 }
		private void CheckForDuplicates(IList<Category> newCategories)
		{
			var duplicateCategories = newCategories
				.GroupBy(x => x.Name)
				.Where(x => x.Count() > 1)
				.Select(x => x.Key).ToArray();

			if (duplicateCategories.Length > 0)
				throw new DuplicateCategoryException(duplicateCategories);

		}
        static public PackageEntity BuildPackageXML(IList<IDeployableItem> items)
        {
            var response = items.GroupBy(g => g.Type)
              .Select(s => new PackageTypeEntity
              {
                  Name = s.Key.ToString(),
                  Members = s.Select(sm => sm.FileNameWithoutExtension).ToArray()
              })
              .ToArray();

            return new PackageEntity { Version = "29.0", Types = response };
        }
Пример #23
0
        private static void ValidatePlayerRanks(IList<PlayerRank> playerRanks)
        {
            if (playerRanks.Count > FIBONACCI_N_PLUS_2.Count)
            {
                throw new ArgumentException(EXCEPTION_MESSAGE_CANNOT_EXCEED_MAX_PLAYERS);
            }

            if (playerRanks.GroupBy(x => x.PlayerId).Count(y => y.Count() > 1) > 0)
            {
                throw new ArgumentException(string.Format(EXCEPTION_MESSAGE_DUPLICATE_PLAYER));
            }
        }
 private List<EnrichedData> GetDataWithCleanedDistance(IList<EnrichedData> input)
 {
     var byIds = input.GroupBy(rd => rd.DeviceIdentifier);
     var values = byIds.Select(
         gr =>
         {
             var id = gr.Key;
             var distance = Median(gr.Select(ed => ed.Distance));
             return new EnrichedData(id, distance);
         }).ToList();
     Log.Debug(beaconScanning, $"Found {values.Count} devices");
     return values;
 }
Пример #25
0
        public static IEnumerable<string> GetResourcesForCulture(string cultureName, IList<string> resources)
        {
            var resourcesByCultureName = resources
                .GroupBy(GetResourceCultureName, StringComparer.OrdinalIgnoreCase);

            if (string.Equals(cultureName, "neutral", StringComparison.OrdinalIgnoreCase))
            {
                cultureName = string.Empty;
            }

            return resourcesByCultureName
                .SingleOrDefault(grouping => string.Equals(grouping.Key, cultureName, StringComparison.OrdinalIgnoreCase));
        }
        /// <summary>
        /// 取国库数据
        /// 金额与记录数与财务相等
        /// </summary>
        /// <returns></returns>
        internal override IList<GuoKuItem> GetSpecialItems(IList<CaiWuItem> caiWus, IList<GuoKuItem> guoKus)
        {
            //按金额与记录数分组
            var caiWuGroup = caiWus.GroupBy(c => c.CreditAmount).Select(g => new AmountGroupItem { Amount = g.Key, Count = g.Count() }).ToList();
            var guoKuGroup = guoKus.GroupBy(c => c.Amount).Select(g => new AmountGroupItem { Amount = g.Key, Count = g.Count() }).ToList();

            //交集,取金额与记录数相等的数据项
            var amountAndCountAreEqual = caiWuGroup.Intersect(guoKuGroup, new AmountCountEqualityComparer()).ToList();
            //取国库对应数据
            var result = guoKus.Where(c => amountAndCountAreEqual.Select(a => a.Amount).Contains(c.Amount)).ToList();

            //返回
            return result;
        }
        public IList <IGrouping <string, Base64Image> > GetDuplicateImageGroups(IList <Base64Image> images)
        {
            var groupedImages = images
                                ?.GroupBy(i => i.Base64)
                                ?.ToList() ?? new List <IGrouping <string, Base64Image> >();

            Console.WriteLine($"Found {groupedImages.Count()} groups of images.");

            var duplicateImageGroups = groupedImages.Where(grp => grp.Count() > 1);

            Console.WriteLine($"Found {duplicateImageGroups.Count()} images with 2 or more copies");

            return(duplicateImageGroups?.ToList() ?? new List <IGrouping <string, Base64Image> >());
        }
Пример #28
0
 private WeekSchedule ToWeekSchedule(IList <Exercise> exercises)
 => new WeekSchedule
 {
     ScheduleByDay = exercises
                     ?.GroupBy(e => e.DayOfWeek)
                     .ToDictionary(
         gd => (DayOfWeek)gd.Key,
         gd => new DaySchedule
     {
         ExerciseByLessonNumber = gd.GroupBy(e => e.ExerciseNumber)
                                  .ToDictionary(gn => gn.Key, gn => gn.ToList())
     }
         )
 };
        public IList<InventoryItemBase> Sort(IList<InventoryItemBase> items)
        {
            // Group them by ID, this will exceed stack limit.
            var test = items.GroupBy(o => o.ID).
                Select(o => new { item = o.First(), newStackSize = o.Sum(i => i.currentStackSize) }). // Get the items so we can re-assemble the items.
                ToList();
        
            // Move the items to a manageable array, still exceeding stack limits.
            var sortedList = new List<InventoryItemBase>(test.Count);
        
            for (int i = 0; i < test.Count; i++)
            {
                //sortedList.Add(test[i].item);
                var item = test[i].item;

                item.currentStackSize = (uint)test[i].newStackSize;

                // Keep going until the stack is divided into parts of maxStackSizes
                uint currentStackSize = item.currentStackSize;
                while (currentStackSize > item.maxStackSize)
                {
                    //// The old item becomes the max stack size, the remainder is pushed to the next index,
                    //// in the next loop, maxStackSize will be removed of that, and on and on until the stack is no longer to large.
                    var a = GameObject.Instantiate<InventoryItemBase>(item); // Copy the item
                    a.currentStackSize = item.maxStackSize;
                    sortedList.Add(a);

                    currentStackSize -= item.maxStackSize;
                }
                if(currentStackSize > 0)
                {
                    // Got 1 pile left
                    var a = GameObject.Instantiate<InventoryItemBase>(item); // Copy the item
                    a.currentStackSize = currentStackSize;
                    sortedList.Add(a);
                }
            }

            // Because the sorter creates copies we can remove the old
            test.ForEach(o => Object.Destroy(o.item.gameObject));
        

            // Orders by category.ID but can easilly be switched to anything else.
            // Simply change o => o.category.ID to any object variable to sort by.
            // For example: o => o.buyPrice will sort items based on the buying price.
            // Another examlpe: o => o.name will sort items on an alphabetical order.
            // If you want to go wild you can chain OrderBy's this allows you to filter on the first category first (for example category), then rarity. (check uncommented line below)
            return sortedList.OrderBy(o => o.GetType().Name).ThenBy(o => o.category.ID).ThenBy(o => o.name).ToArray(); // Order by and return
            //return sortedList.OrderBy(o => o.category.ID).ThenBy(o => o.rarity.ID).ToArray(); // Order by and return	    
        }
Пример #30
0
 public IEnumerable<ValidationError> Validate(IList<Benchmark> benchmarks)
 {
     foreach (var groupByType in benchmarks.GroupBy(benchmark => benchmark.Target.Type))
     {
         var allMethods = groupByType.Key.GetAllMethods();
         var count = allMethods.Count(method => method.GetCustomAttributes<BenchmarkAttribute>(false)
                                                      .Any(benchmarkAttribute => benchmarkAttribute.Baseline));
         if (count > 1)
         {
             yield return new ValidationError(
                 TreatsWarningsAsErrors,
                 $"Only 1 [Benchmark] in a class can have \"Baseline = true\" applied to it, class {groupByType.Key.Name} has {count}");
         }
     }
 }
Пример #31
0
        public static string UpdatePattern(IList<ChatUserMention> mentions)
        {
            _customCachedPattern = string.Format(CustomMentionPattern, String.Join("|",
                mentions.GroupBy(g => g.UserKey)
                        .Select(p => string.Format(GroupFormat, p.First().User.Name,
                            String.Join("|",
                                p.Select(j => j.String)
                                    .Concat(new [] { p.First().User.Name })
                            )
                        ))
            ));

            _customCachedPatternMentions = mentions.Select(p => p.Key).ToArray();
            return _customCachedPattern;
        }
Пример #32
0
        public void AddValidationErrors(ControllerBase controller, IList<Tuple<string, string>> errors)
        {
            var groupedErrors = errors.GroupBy(x => x.Item1 ?? string.Empty);
            foreach (var error in groupedErrors)
            {
                var state = controller.ViewData.ModelState[error.Key];

                if (state != null && state.Errors.Count > 0) continue;

                foreach (var message in error)
                {
                    controller.ViewData.ModelState.AddModelError(
                        error.Key,
                        message.Item2);
                }
            }
        }
        public IList <string> CalculateWorstSellers(IList <Sale> sales)
        {
            if (!sales.Any())
            {
                return(new List <string>());
            }
            var salesBySalesman = sales
                                  .GroupBy(sale => sale.Salesman)
                                  .Select(group => new
            {
                Salesman = group.Key,
                Total    = group.Sum(sale => sale.Total)
            }).ToList();

            var minTotal = salesBySalesman.Min(x => x.Total);

            return(salesBySalesman
                   .Where(sale => sale.Total.Equals(minTotal))
                   .Select(sale => sale.Salesman).ToList());
        }
        /// <summary>
        /// Groups identical products together by increasing their quantity.
        /// </summary>
        /// <param name="products">The list of products to group.</param>
        public static IList <ProcessOrderProduct> GroupDuplicates(this IList <ProcessOrderProduct> products)
        {
            products.CheckNotNull(nameof(products));
            if (!products.Any())
            {
                return(products);
            }

            var grouped = products.GroupBy(x => new { x.Name, x.Price })
                          .Select(x => new ProcessOrderProduct()
            {
                Name     = x.Key.Name,
                Price    = x.Key.Price,
                Quantity = x.Sum(x => x.Quantity)
            }).ToList();

            products.Clear();
            products.AddRange(grouped);
            return(products);
        }
Пример #35
0
        protected override Dictionary <Product, IEnumerable <string> > GetValues(List <Product> objs)
        {
            ProductVariant          productVariantAlias = null;
            OptionValueData         data   = null;
            IList <OptionValueData> values = _session.QueryOver <ProductOptionValue>()
                                             .JoinAlias(value => value.ProductVariant, () => productVariantAlias)
                                             .SelectList(builder => builder
                                                         .Select(value => value.Value).WithAlias(() => data.Value)
                                                         .Select(value => value.ProductOption.Id).WithAlias(() => data.OptionId)
                                                         .Select(() => productVariantAlias.Product.Id).WithAlias(() => data.ProductId)
                                                         ).TransformUsing(Transformers.AliasToBean <OptionValueData>())
                                             .List <OptionValueData>();

            Dictionary <int, IEnumerable <string> > dictionary =
                values.GroupBy(valueData => valueData.ProductId)
                .ToDictionary(datas => datas.Key, datas => datas.Select(valueData => valueData.TermValue));

            return(objs.ToDictionary(product => product,
                                     product => dictionary.ContainsKey(product.Id) ? dictionary[product.Id] : Enumerable.Empty <string>()));
        }
Пример #36
0
        public static IList <StudentAttendanceSummary> Create(IList <StudentSectionAbsenceSummary> studentSectionAttendances, IList <Student> students, IList <ClassDetails> classes)
        {
            var stSectionAttsDic = studentSectionAttendances.GroupBy(x => x.StudentId).ToDictionary(x => x.Key, x => x.ToList());
            var res = new List <StudentAttendanceSummary>();

            foreach (var stSectionAtts in stSectionAttsDic)
            {
                var student = students.FirstOrDefault(x => x.Id == stSectionAtts.Key);
                if (student == null)
                {
                    continue;
                }
                res.Add(new StudentAttendanceSummary
                {
                    Student = student,
                    ClassAttendanceSummaries = StudentClassAttendanceSummary.Create(stSectionAtts.Value, classes)
                });
            }
            return(res);
        }
Пример #37
0
        private async Task <IEnumerable <JobDefinition> > SupersedeJobs(IList <Job> createdJobs, IEnumerable <JobDefinition> jobDefinitions)
        {
            IEnumerable <IGrouping <string, Job> > jobDefinitionGroups = createdJobs
                                                                         .GroupBy(j => j.JobDefinitionId);

            IEnumerable <JobDefinition> jobDefinitionsToSupersede = jobDefinitions
                                                                    .GroupBy(x => x.Id)
                                                                    .Select(x => x.First(y => y.Id == x.Key));

            foreach (IGrouping <string, Job> jobDefinitionKvp in jobDefinitionGroups)
            {
                Job jobToSupersedeOthers = jobDefinitionKvp.First();

                JobDefinition jobDefinition = jobDefinitionsToSupersede.First(m => m.Id == jobToSupersedeOthers.JobDefinitionId);

                await CheckForSupersededAndCancelOtherJobs(jobToSupersedeOthers, jobDefinition);
            }

            return(jobDefinitionsToSupersede);
        }
Пример #38
0
        /// <summary>
        /// Gets selected address attributes
        /// </summary>
        /// <param name="attributes">Attributes</param>
        /// <returns>Selected address attributes</returns>
        public virtual async Task <IList <AddressAttribute> > ParseAddressAttributes(IList <CustomAttribute> customAttributes)
        {
            var result = new List <AddressAttribute>();

            if (!customAttributes.Any())
            {
                return(result);
            }

            foreach (var customAttribute in customAttributes.GroupBy(x => x.Key))
            {
                var attribute = await _addressAttributeService.GetAddressAttributeById(customAttribute.Key);

                if (attribute != null)
                {
                    result.Add(attribute);
                }
            }
            return(result);
        }
Пример #39
0
        private async Task <User> GetRolesAndClaimsAsync(ApplicationUser appUser)
        {
            IList <string> roles = await userManager.GetRolesAsync(appUser);

            IList <Claim> claims = await userManager.GetClaimsAsync(appUser);

            User user = new User
            {
                Id       = appUser.Id,
                Username = appUser.UserName,
                Email    = appUser.Email,
                Roles    = roles.ToArray(),
                Claims   = claims.GroupBy(x => x.Type.ToString())
                           .Select(g => (key: g.Key, values: g.Select(k => k.Value).ToArray()))
                           .ToDictionary(k => k.key, k => k.values)
            };

            return(user);
        }
    }
        private static void SetDownloadDependencies(IObjectWriter writer, IList <DownloadDependency> downloadDependencies)
        {
            if (!downloadDependencies.Any())
            {
                return;
            }

            writer.WriteArrayStart("downloadDependencies");

            foreach (var dependency in downloadDependencies.GroupBy(dep => dep.Name).OrderBy(dep => dep.Key))
            {
                var version = string.Join(";", dependency.Select(dep => dep.VersionRange).OrderBy(dep => dep.MinVersion).Select(dep => dep.ToNormalizedString()));

                writer.WriteObjectStart();
                SetValue(writer, "name", dependency.Key);
                SetValue(writer, "version", version);
                writer.WriteObjectEnd();
            }
            writer.WriteArrayEnd();
        }
Пример #41
0
        private bool ValidateFiles(string directoryPath, IList <MigrationInfo> target)
        {
            _logger.LogInformation("Validate migrations directory: \"{DirectoryPath}\"", directoryPath);

            var directory = new DirectoryInfo(directoryPath);

            bool success = true;

            foreach (var file in directory.GetFiles(Pattern))
            {
                var info = ValidateFileName(file);

                if (info == null)
                {
                    success = false;
                    continue;
                }

                target.Add(info);
            }

            var duplicateTimestamps = target.GroupBy(x => x.Timestamp).Where(x => x.Count() > 1).Select(x => x.Key).ToArray();

            if (duplicateTimestamps.Any())
            {
                foreach (var timestamp in duplicateTimestamps)
                {
                    _logger.LogWarning("Duplicate timestamp: {Timestamp}", timestamp);
                }

                _logger.LogError("Duplicate timestamps found. Please fix. Exit");
                return(false);
            }

            if (!success)
            {
                _logger.LogError("Some files does not match suggested migration file pattern \"YYYYMMDDNN - migration name\". Exit");
            }

            return(success);
        }
Пример #42
0
        private void CreateTimelineForPackets <T>(IList <T> packets, int interval, Func <T, string> selector, Func <T, double> timestamp)
        {
            var paths = packets.Select(selector).ToHashSet();

            var startTime = timestamp(packets.First());
            var points    = packets.GroupBy(p => (int)Math.Floor((timestamp(p) - startTime) / interval));
            var timeTable = new DataTable();

            timeTable.Columns.Add("Time", typeof(string));
            foreach (var path in paths)
            {
                var col = new DataColumn(String.IsNullOrWhiteSpace(path) ? "<empty>" : path, typeof(int));
                col.DefaultValue = 0;
                timeTable.Columns.Add(col);
            }
            var lastPoint = 0;

            foreach (var point in points)
            {
                for (int i = lastPoint + 1; i < point.Key; i++)
                {   // add empty rows
                    timeTable.Rows.Add(i);
                }
                lastPoint = point.Key;

                var row  = timeTable.NewRow();
                var data = point.GroupBy(selector).Select(x => (Key: x.Key, Count: x.Count()));
                row["Time"] = point.Key;
                foreach (var item in data)
                {
                    var key = String.IsNullOrWhiteSpace(item.Key) ? "<empty>" : item.Key;
                    row[key] = item.Count;
                }
                timeTable.Rows.Add(row);
            }

            Console.WriteLine("Timeline:");
            ConsoleTableBuilder.From(timeTable)
            .WithFormat(ConsoleTableBuilderFormat.MarkDown)
            .ExportAndWriteLine();
        }
Пример #43
0
        private ICollection <PlanTrackNumber> GetPlanTrackNumberByPredictData(string lotteryId, IList <PredictDataDto> data)
        {
            var planTrackNumbers = new List <PlanTrackNumber>();

            var finalLotteryData = _lotteryDataAppService.GetFinalLotteryData(LotteryInfo.Id);

            var cacheKey = string.Format(RedisKeyConstants.LOTTERY_PLANTRACK_DETAIL_KEY,
                                         LotteryInfo.Id, _userMemberRank == MemberRank.Ordinary ?
                                         LotteryConstants.SystemUser : _lotterySession.UserId, finalLotteryData.Period);

            _cacheManager.Remove(cacheKey);

            data.GroupBy(p => p.NormConfigId).ForEach(item =>
            {
                var planInfo             = _normConfigQueryService.GetNormPlanInfoByNormId(item.Key, lotteryId);
                var newestPredictDataDto = item.OrderByDescending(p => p.StartPeriod).First();
                var normConfig           = _normConfigQueryService.GetUserNormConfig(item.Key);
                var planTrackNumber      = new PlanTrackNumber()
                {
                    NormId                = normConfig.Id,
                    Sort                  = normConfig.Sort,
                    PlanId                = planInfo.Id,
                    PlanName              = planInfo.PlanName,
                    EndPeriod             = newestPredictDataDto.EndPeriod,
                    StartPeriod           = newestPredictDataDto.StartPeriod,
                    MinorCycle            = newestPredictDataDto.MinorCycle,
                    PredictData           = newestPredictDataDto.PredictedData,
                    CurrentPredictPeriod  = newestPredictDataDto.CurrentPredictPeriod,
                    PredictType           = planInfo.DsType,
                    HistoryPredictResults = GetHistoryPredictResults(item.OrderByDescending(p => p.StartPeriod), item.Key, normConfig.LookupPeriodCount, planInfo.PlanNormTable),
                };
                var rightCount               = planTrackNumber.HistoryPredictResults.Count(p => p == 0);
                var totleCount               = planTrackNumber.HistoryPredictResults.Count(p => p != 2);
                var currentScore             = Math.Round((double)rightCount / totleCount, 2);
                planTrackNumber.CurrentScore = currentScore;
                WritePlanTrackNumbers(item, planInfo, currentScore);
                planTrackNumbers.Add(planTrackNumber);
            });

            return(planTrackNumbers.OrderBy(p => p.Sort).ToList());
        }
Пример #44
0
        private async Task <IList <Price> > GetMergedPriceByPriceList(IList <CsvPrice> pricesWithPriceListIds)
        {
            if (!pricesWithPriceListIds.Any())
            {
                return(new List <Price>());
            }

            var existentPrices = new List <Price>();

            var dictionary = pricesWithPriceListIds.GroupBy(x => x.PricelistId).ToDictionary(g => g.Key, g => g.ToArray());

            foreach (var priceListId in dictionary.Keys)
            {
                var criteria = new PricesSearchCriteria
                {
                    PriceListId = priceListId,
                    ProductIds  = dictionary[priceListId].Select(x => x.ProductId).ToArray(),
                    Take        = int.MaxValue,
                };

                var searchResult = await _pricingSearchService.SearchPricesAsync(criteria);

                existentPrices.AddRange(searchResult.Results);
            }

            var result = new List <Price>();

            foreach (var price in pricesWithPriceListIds)
            {
                var existPrice = existentPrices.FirstOrDefault(x => x.ProductId.EqualsInvariant(price.ProductId) && x.PricelistId.EqualsInvariant(price.PricelistId));

                if (existPrice != null)
                {
                    price.MergeFrom(existPrice);
                }

                result.Add(price);
            }

            return(result);
        }
Пример #45
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            IDataParser         dataparser    = new DataParser();
            IList <SalesEntity> salesEntities = dataparser.JsonParse <SalesEntity>(@"C:\Users\benasm\salesValid.json").ToList();
            ISalesInsight       salesInsight  = new SalesInsight();

            salesInsight.LogRegisterStateChange(salesEntities);

            DateTime startDateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            var departmentsHourlyAggregated = salesEntities.GroupBy(saleEntity => new
            {
                saleEntity.StoreNumber,
                saleEntity.Department,
                DateWithHour = new DateTime(startDateTime.AddMilliseconds(saleEntity.OrderTime).Year,
                                            startDateTime.AddMilliseconds(saleEntity.OrderTime).Month,
                                            startDateTime.AddMilliseconds(saleEntity.OrderTime).Day,
                                            startDateTime.AddMilliseconds(saleEntity.OrderTime).Hour, 0, 0)
            }).Select(groupedData => new DepartmentHourlyAggregateEntity()
            {
                StoreNumber  = groupedData.Key.StoreNumber,
                Department   = groupedData.Key.Department,
                DateWithHour = groupedData.Key.DateWithHour,
                TotalAmount  = groupedData.Sum(d => d.Amount)
            }).ToList();
            var storeHourlyAggregated = departmentsHourlyAggregated.GroupBy(departmentsHourlyAggregate => new
            {
                departmentsHourlyAggregate.StoreNumber,
                departmentsHourlyAggregate.DateWithHour
            }).Select(groupedData => new StoreHourlyAggregateEntity()
            {
                StoreNumber  = groupedData.Key.StoreNumber,
                DateWithHour = groupedData.Key.DateWithHour,
                TotalAmount  = groupedData.Sum(d => d.TotalAmount)
            }).OrderBy(d => d.DateWithHour).ToList();

            salesInsight.LogDepartmentSaleDecrease(departmentsHourlyAggregated, storeHourlyAggregated);
            salesInsight.LogHighestRelativePercentIncrease(departmentsHourlyAggregated, storeHourlyAggregated);
            Console.Write("Press any key to close");
            Console.Read();
        }
Пример #46
0
        // <summary>
        // Validates the specified enumeration type as a whole.
        // </summary>
        internal override void Validate()
        {
            base.Validate();

            var enumUnderlyingType = UnderlyingType as ScalarType;

            if (enumUnderlyingType == null ||
                !Helper.IsSupportedEnumUnderlyingType(enumUnderlyingType.TypeKind))
            {
                AddError(
                    ErrorCode.InvalidEnumUnderlyingType,
                    EdmSchemaErrorSeverity.Error,
                    Strings.InvalidEnumUnderlyingType);
            }
            else
            {
                Debug.Assert(!_enumMembers.Any(m => !m.Value.HasValue), "member values should have been fixed up already.");

                // Check for underflows and overflows
                var invalidEnumMembers = _enumMembers
                                         .Where(m => !Helper.IsEnumMemberValueInRange(enumUnderlyingType.TypeKind, (long)m.Value));

                foreach (var invalidEnumMember in invalidEnumMembers)
                {
                    invalidEnumMember.AddError(
                        ErrorCode.EnumMemberValueOutOfItsUnderylingTypeRange,
                        EdmSchemaErrorSeverity.Error,
                        Strings.EnumMemberValueOutOfItsUnderylingTypeRange(
                            invalidEnumMember.Value, invalidEnumMember.Name, UnderlyingType.Name));
                }
            }

            // Check for duplicate enumeration members.
            if (_enumMembers.GroupBy(o => o.Name).Where(g => g.Count() > 1).Any())
            {
                AddError(
                    ErrorCode.DuplicateEnumMember,
                    EdmSchemaErrorSeverity.Error,
                    Strings.DuplicateEnumMember);
            }
        }
Пример #47
0
        private List <MinuteBarRequestKeyDto> DeduplicateKeys(IList <MinuteBarRequestKeyDto> filteredKeys)
        {
            var deduplicatedKeys = new List <MinuteBarRequestKeyDto>();

            var grps = filteredKeys.GroupBy(x => x.Figi);

            foreach (var grp in grps)
            {
                var dedupe = grp.GroupBy(x => x.Date.Date).Select(x => x.FirstOrDefault()).Where(x => x != null)
                             .ToList();

                if (!dedupe.Any())
                {
                    continue;
                }

                deduplicatedKeys.AddRange(dedupe);
            }

            return(deduplicatedKeys);
        }
        public async Task <ActionResult> ViewSalesData()
        {
            try
            {
                HttpPostedFileBase salesDataFile = Request.Files.Count > 0 ? Request.Files[0] : null;
                IList <string>     csvData       = CSVHelper.ReadCSVFile(salesDataFile);

                if (csvData == null)
                {
                    ViewBag.Errors = new[] { "Unable to read CSV file." };
                }
                IList <VehicleDetail> vehicleDetails = CSVHelper.ConvertToModel(csvData);
                ViewBag.MostSoldVehicle = vehicleDetails.GroupBy(vd => vd.Vehicle).GetHighesCountGroup();
                return(View("Results", vehicleDetails));
            }
            catch (Exception ex)
            {
                Response.StatusCode = 500;
                return(View("Error"));
            }
        }
Пример #49
0
        public static List <FoodChargeCheckDTO> ToExtendedList(this IList <FoodChargeCheck> pLstObjCheckList)
        {
            return(pLstObjCheckList.GroupBy(x => new { SellerId = x.SellerId, SellerCode = x.Seller.Code, SellerName = x.Seller.Name }).Select(y => new FoodChargeCheckDTO()
            {
                SellerId = y.Key.SellerId,
                SellerCode = y.Key.SellerCode,
                SellerName = y.Key.SellerName,

                Lines = y.Select(z => new FoodChargeCheckLineDTO()
                {
                    Id = z.Id,
                    BatchNumber = z.BatchNumber,
                    BatchDate = z.BatchDate,
                    ExpirationDate = z.ExpirationDate,
                    FoodCharge = z.FoodCharge,
                    FoodDeliveries = z.FoodDeliveries,
                    AlfalfaDeliveries = z.AlfalfaDeliveries,
                    ApplyFoodCharge = z.ApplyFoodCharge
                }).ToList()
            }).ToList());
        }
        public override SKSize Measure(IList <HierarchicalNode> elements, SKSize availableSize)
        {
            heightByLevel.Clear();
            float maxWidth  = 0;
            float maxHeight = 0;
            List <HierarchicalNode> allreadyPassed = new List <HierarchicalNode>();

            foreach (var group in elements.GroupBy(n => n.Level))
            {
                maxWidth = Measure(group.Key, group, maxWidth, availableSize, allreadyPassed);
                float maxHeightByLevel = 0;
                foreach (var element in group)
                {
                    maxHeightByLevel = Math.Max(maxHeightByLevel, element.DesiredSize.Height);
                }
                heightByLevel.Add(group.Key, maxHeightByLevel);
                maxHeight += maxHeightByLevel + VerticalSpacing;
            }
            totalSize = new SKSize(maxWidth - HorizontalSpacing, maxHeight - VerticalSpacing);
            return(totalSize);
        }
Пример #51
0
        public static IList <GridData> CleanupRawData(this FileReaderResult rawData)
        {
            IList <GridData> cleanupColumn = rawData.Data;

            if (rawData.Titles != null && rawData.Titles.Any() && !rawData.Titles.All(ttl => String.IsNullOrEmpty(ttl)))
            {
                cleanupColumn = rawData
                                .Titles
                                .Select((ttl, idx) => new { Ordinal = idx + 1, Item = ttl })
                                .Where(ttl => !String.IsNullOrEmpty(ttl.Item))
                                .Join(rawData.Data, o => o.Ordinal, i => i.Column, (o, i) => i)
                                .ToList();
            }

            return(cleanupColumn
                   .GroupBy(prm => prm.Row)
                   .Select(grp => grp.Select(item => item))
                   .Where(grd => !grd.Aggregate(true, (p, n) => p && String.IsNullOrEmpty(n.CellValue)))
                   .SelectMany(grd => grd)
                   .ToList());
        }
Пример #52
0
        public void AddOrUpdateSessionData(string clientToken, IList <PocketDDD.Models.UserSessionData> sessionData)
        {
            if (sessionData == null || sessionData.Count == 0)
            {
                return;
            }

            var sessionDataForEvents = sessionData.GroupBy(x => x.eventId);

            foreach (var eventGroup in sessionDataForEvents)
            {
                var userInfo    = GetUserEventInfo(eventGroup.Key);
                var dddEvent    = eventsService.GetServerEventData(eventGroup.Key);
                var eventDetail = eventsService.GetEventDetail(dddEvent);

                if (dddEvent.IsActive)
                {
                    addOrUpdateSessionData(eventGroup.Key, eventDetail, userInfo != null ? userInfo.UserName : "", userInfo != null ? userInfo.UserToken : null, clientToken, eventGroup.ToList());
                }
            }
        }
        public void TestCodeCoverageSelection()
        {
            this.RunContext.IsDataCollectionEnabled = true;

            this.Executor.RunTests(
                new VSTestCase[] { CreateTestCase("Test1", DefaultSource), CreateTestCase("Test2", DefaultSource) },
                this.RunContext,
                this.FrameworkHandle
                );

            IList <MockBoostTestRunner> runners = this.RunnerFactory.ProvisionedRunners.OfType <MockBoostTestRunner>().ToList();

            Assert.That(runners.GroupBy(runner => runner.Source).Count(), Is.EqualTo(1));

            MockBoostTestRunner testRunner = runners.FirstOrDefault(runner => runner.RunCount == 1);

            Assert.That(testRunner, Is.Not.Null);

            // All selected tests are executed
            Assert.That(testRunner.Args.First().Tests.Count, Is.EqualTo(2));
        }
Пример #54
0
        private EstatisticaAdocante GerarEstatisticasUsamAdocante(IList <Inscricao> inscricoes)
        {
            var grupo       = inscricoes.GroupBy(x => x.Pessoa.UsaAdocanteDiariamente);
            var estatistica = new EstatisticaAdocante();

            foreach (var item in grupo)
            {
                if (item.Key)
                {
                    estatistica.Usam          = item.Count();
                    estatistica.UsamPresentes = item.Count(x => x.ConfirmadoNoEvento);
                }
                else
                {
                    estatistica.NaoUsam          = item.Count();
                    estatistica.NaoUsamPresentes = item.Count(x => x.ConfirmadoNoEvento);
                }
            }

            return(estatistica);
        }
Пример #55
0
        public static IList <StudentGradingByTypeStatsViewData> Create(IList <ClassAnnouncement> announcements
                                                                       , IList <StudentAnnouncementDetails> studentAnnouncements, IList <ClaimInfo> claims)
        {
            var res = new List <StudentGradingByTypeStatsViewData>();

            announcements = announcements.Where(x => x.ClassAnnouncementTypeRef.HasValue).ToList();
            var dicbyType = announcements.GroupBy(x => x.ClassAnnouncementTypeRef).ToDictionary(x => x.Key, x => x.ToList());

            foreach (var typeAnns in dicbyType)
            {
                var ann = typeAnns.Value.First();
                Trace.Assert(ann.ClassAnnouncementTypeRef.HasValue);
                res.Add(new StudentGradingByTypeStatsViewData
                {
                    ClassAnnouncementTypeId   = ann.ClassAnnouncementTypeRef.Value,
                    ClassAnnouncementTypeName = ann.ClassAnnouncementTypeName,
                    StudentGradingStats       = StudentGradingStatsViewData.Create(typeAnns.Value, studentAnnouncements, claims)
                });
            }
            return(res);
        }
Пример #56
0
        public List <BLL_ContractTypes> Transform(IList <grs_VGrsContractType> contractType)
        {
            List <BLL_ContractTypes> data = new List <BLL_ContractTypes>();

            if (contractType.Count > 0)
            {
                contractType.GroupBy(a => a.RowId).ToList().ForEach((sContract) =>
                {
                    var contractGroupData = sContract.ToList();
                    contractGroupData.ForEach((summary) =>
                    {
                        data.Add(new BLL_ContractTypes()
                        {
                            name = Convert.ToString(summary.AssumedName), value = Convert.ToString(summary.Code), group = Convert.ToString(summary.Exposuretype), isActive = (Convert.ToBoolean(summary.AssumedFlag) && Convert.ToBoolean(summary.Active))
                        });
                    });
                });
                return(data.ToList());
            }
            return(null);
        }
Пример #57
0
        private EstatisticaSexo GerarEstatisticasSexo(IList <Inscricao> inscricoes)
        {
            var inscricoesPorSexo = inscricoes.GroupBy(x => x.Pessoa.Sexo);
            var estatistica       = new EstatisticaSexo();

            foreach (var sexo in inscricoesPorSexo)
            {
                if (sexo.Key == SexoPessoa.Feminino)
                {
                    estatistica.Mulheres          = sexo.Count();
                    estatistica.MulheresPresentes = sexo.Count(x => x.ConfirmadoNoEvento);
                }
                else if (sexo.Key == SexoPessoa.Masculino)
                {
                    estatistica.Homens          = sexo.Count();
                    estatistica.HomensPresentes = sexo.Count(x => x.ConfirmadoNoEvento);
                }
            }

            return(estatistica);
        }
Пример #58
0
        protected override void DoStart()
        {
            _parameterMetaDataList = _flatParameterMetaDataRepository.All().ToList();

            _parameterMetaDataList.Each(parameterMetaData =>
            {
                parameterMetaData.ParentContainerPath = _flatContainerRepository.ContainerPathFrom(parameterMetaData.ContainerId).ToString();
                //Use clone here to ensure that we are not modifying the reference stored in the repository
                var valueOrigin = _valueOriginRepository.FindBy(parameterMetaData.ValueOriginId).Clone();
                parameterMetaData.ValueOrigin = valueOrigin;

                //update only if available in db
                parameterMetaData.ContainerCriteria = containerCriteriaFor(parameterMetaData.ContainerId, parameterMetaData.ParameterName);
            });

            //now cache the parameter meta data by container path
            foreach (var parameterValueMetaDataGroup in _parameterMetaDataList.GroupBy(x => x.ParentContainerPath))
            {
                _parameterMetaDataCacheByContainer.Add(parameterValueMetaDataGroup.Key, new List <TParameterMetaData>(parameterValueMetaDataGroup));
            }
        }
Пример #59
0
        void Validate(IList <VisualStateGroup> groups)
        {
            // If we have 1 group, no need to worry about duplicate group names
            if (groups.Count > 1)
            {
                if (groups.GroupBy(vsg => vsg.Name).Any(g => g.Count() > 1))
                {
                    throw new InvalidOperationException("VisualStateGroup Names must be unique");
                }
            }

            // State names must be unique within this group list, so pull in all
            // the states in all the groups, group them by name, and see if we have
            // and duplicates
            if (groups.SelectMany(group => group.States)
                .GroupBy(state => state.Name)
                .Any(g => g.Count() > 1))
            {
                throw new InvalidOperationException("VisualState Names must be unique");
            }
        }
Пример #60
0
        private EstatisticaDiabeticos GerarEstatisticasDiabeticos(IList <Inscricao> inscricoes)
        {
            var grupo       = inscricoes.GroupBy(x => x.Pessoa.EhDiabetico);
            var estatistica = new EstatisticaDiabeticos();

            foreach (var item in grupo)
            {
                if (item.Key)
                {
                    estatistica.Sao          = item.Count();
                    estatistica.SaoPresentes = item.Count(x => x.ConfirmadoNoEvento);
                }
                else
                {
                    estatistica.NaoSao          = item.Count();
                    estatistica.NaoSaoPresentes = item.Count(x => x.ConfirmadoNoEvento);
                }
            }

            return(estatistica);
        }