Example #1
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 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"}
                )
            });
        }
 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
 }
Example #4
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();
        }
        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;
        }
Example #6
1
        private void OnReferenceLocationsChanged(object sender, IList<InlineRenameLocation> renameLocations)
        {
            int totalFilesCount = renameLocations.GroupBy(s => s.Document).Count();
            int totalSpansCount = renameLocations.Count;

            UpdateSearchText(totalSpansCount, totalFilesCount);
        }
        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 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;
        }
 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);
 }
        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
        }
        /// <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 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);
        }
 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();
 }
        //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();
        }
Example #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;
		}
        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();
        }
Example #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 });
              }
        }
 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);

		}
Example #20
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();
 }
 /// <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();
 }
        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 };
        }
Example #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));
            }
        }
Example #24
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));
        }
 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;
 }
        /// <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<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	    
        }
 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}");
         }
     }
 }
Example #29
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;
        }
        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);
                }
            }
        }