public FactoryClass(IConstructorArgList argList, IList<IFactoryMethod> methods) { m_argList = argList; Methods = methods; foreach (var definition in methods.SelectMany(m => m.ConstructorArgs)) argList.Add(definition); }
public SchemaScope(JTokenType tokenType, IList<JsonSchemaModel> schemas) { _tokenType = tokenType; _schemas = schemas; _requiredProperties = schemas.SelectMany<JsonSchemaModel, string>(GetRequiredProperties).Distinct().ToDictionary(p => p, p => false); }
/// <summary> /// Searches for lunch menu URLs through all search engines with given query strings. /// </summary> /// <param name="queries">Query-strings to search with.</param> public IList<string> SearchForLunchMenuURLs(IList<string> queries) { return queries.SelectMany(SearchForLunchMenuURLs) .AsParallel() .Distinct(new UrlComparer()) .ToList(); }
private void ColoriseDupFilesWithDifferentPaths(ref IList<ProjectModel> projects) { // If there's a different version reference between 2 or more projects then flag this. // Example: ProjectA has EF 4.3.1. ProjectB has EF 5.0. We need to flag this in the UI. var children = projects.SelectMany(p => p.Children); children.Where(c => c.ItemType != "ProjectReference") .ToList() .ForEach(c => { if (c.IsConflicting) return; var similar = children.Where(x => x.Filename.Equals(c.Filename, StringComparison.CurrentCultureIgnoreCase) && !x.ItemLocation.Replace(@"..\", "").Equals(c.ItemLocation.Replace(@"..\", ""), StringComparison.CurrentCultureIgnoreCase)).ToList(); if (similar.Any()) { int i = _r.Next(_pairedColors.Count - 1); Color color = _pairedColors.Skip(i).First(); c.SimilarRefences = similar.ToList(); c.Color = color; c.IsConflicting = true; similar.ForEach(x => { x.Color = color; x.IsConflicting = true; }); } }); }
//todo: Link content to a content cache similar to openwraps package cache. Use same mechanism? public ContentLocator() { var environment = ServiceLocator.GetService<IEnvironment>(); var packageManager = ServiceLocator.GetService<IPackageManager>(); var baseDirectory = LocalFileSystem.Instance.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory); contentRoot = baseDirectory.GetDirectory("Content"); contentRoot.MustExist(); foreach (var scopedDescriptor in environment.ScopedDescriptors) { var files = packageManager.GetProjectExports<ContentFolderExport>(scopedDescriptor.Value.Value, environment.ProjectRepository, environment.ExecutionEnvironment); contentPathSources = files.SelectMany(x => x).Distinct().Select(x => x.Directory).ToList(); foreach ( var pathSource in contentPathSources.SelectMany(contentPathSource => contentPathSource.Directories())) { pathSource.LinkTo(contentRoot.GetDirectory(pathSource.Name).MustExist().Path.FullPath); } } }
public IList<Type> ExtractIntegrationJobTypesFromAssemblies(IList<Assembly> assembliesWithJobs) { return assembliesWithJobs .SelectMany(x => x.GetTypes()) .Where(x => typeof(IIntegrationJob).IsAssignableFrom(x) && x.IsClass) .ToList(); }
public IList<CatalogDto> GetUsersCatalogs(IList<long> userIds) { var userCatalogIds = userIds .SelectMany(x => Call<IList<long>>("get-user-catalogs", new { UserId = x })) .Distinct().ToArray(); return Get(userCatalogIds); }
private static List<byte> Escape(IList<byte> p) { return p.SelectMany(q => q == 0x7E ? new byte[] { 0x7d, 0x02 } : (q == 0x7D ? new byte[] { 0x7D, 0x01 } : new[] { q }) ).ToList(); }
/// <summary> /// Mapping list of date models into list of timeslot models /// </summary> /// <param name="dates">List of date models</param> /// <returns>List of timeslot models</returns> public static IList<TimeSlot> MapToTimeSlot(IList<EventModel.DatesModel> dates) { return dates.SelectMany(d => d.Times.Select(time => new TimeSlot() { Id = time.Id.GetValueOrDefault(), DateTime = d.Date.Add(TimeSpan.Parse(time.Time)) }).ToList()).ToList(); }
public ValidatedContractBlock(IList<ValidatedStatement> validatedContractBlock) { Contract.Requires(validatedContractBlock != null); _validatedContractBlock = validatedContractBlock; _contractBlock = validatedContractBlock.Select(x => x.ProcessedStatement).ToList(); _validationResults = validatedContractBlock.SelectMany(x => x.ValidationResults).ToList(); }
private IList<ISymbol> GenerateMembers( IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> unimplementedMembers, CancellationToken cancellationToken) { return unimplementedMembers.SelectMany(t => t.Item2) .Select(m => GenerateMember(m, cancellationToken)) .WhereNotNull() .ToList(); }
public bool UpdateValues(IList<AFValues> valsList) { IList<AFValue> valsToWrite = new List<AFValue>(); valsToWrite = valsList.SelectMany(i => i).ToList(); AFErrors<AFValue> errors = AFListData.UpdateValues(valsToWrite, AFUpdateOption.Replace); return (errors == null) ? true : false; }
public double GetPointsPerMinute(IList<Player> players, bool? homeFixtures) { var fixtures = players.SelectMany(p => p.PastFixtures).ToList(); if(homeFixtures.HasValue) { fixtures = fixtures.Where(pf => pf.Home == homeFixtures).ToList(); } var totalMinutes = fixtures.Sum(f => f.MinutesPlayed); var totalPoints = fixtures.Sum(f => f.TotalPointsScored); return totalPoints/(double)totalMinutes; }
public SchemaScope(JTokenType tokenType, IList<JsonSchemaModel> schemas) { _tokenType = tokenType; _schemas = schemas; _requiredProperties = schemas.SelectMany<JsonSchemaModel, string>(GetRequiredProperties).Distinct().ToDictionary(p => p, p => false); if (tokenType == JTokenType.Array && schemas.Any(s => s.UniqueItems)) { IsUniqueArray = true; UniqueArrayItems = new List<JToken>(); } }
public Game(IList<Team> teams, Contract contract, IEnumerable<Card> deck, ILogger logger) { _logger = logger; Contract = contract; Teams = teams; _numberOfPlayers = teams.SelectMany(t => t.Players).Count(); Declarer = Contract.Team.Players.First(); // TODO: This probably isn't right! Dummy = Contract.Team.Players.Last(); // TODO: This probably isn't right! Deal(deck, Declarer); //TODO: This Probably isn't right! }
public async Task CreateNextEvents(IList <int> sourceIds, IList <EventSourceType> eventSourceTypes, int?delay, long?previousEventId, int?hourId) { var nextTasks = sourceIds?.SelectMany(id => eventSourceTypes.Select(eventType => new Event { SourceId = id, SourceType = eventType, PreviousEventId = previousEventId, Delay = delay, HourId = hourId })).ToList() ?? eventSourceTypes.Select(eventType => new Event { SourceType = eventType, PreviousEventId = previousEventId, Delay = delay, HourId = hourId }).ToList(); await SetInitialHourIdForEvents(nextTasks); if (nextTasks.Any()) { await this.eventRepository.CreateAsync(nextTasks); } }
private async Task <IList <DetailsByEntityModel> > GetDetailsForEntities(Guid memoryBookUniverseId, params Guid[] entityIds) { IList <DetailReadModel> details = await this.detailQueryManager.GetDetailsByEntity(memoryBookUniverseId, entityIds).ConfigureAwait(false); return(details?.SelectMany(x => x.EntityIds.Select(entityId => new { EntityId = entityId, Detail = x })) .GroupBy(x => x.EntityId) .Select(x => new DetailsByEntityModel { EntityId = x.Key, Details = x.Select(p => p.Detail).ToList() }).ToList()); }
public PersistentTaskController(ChannelGraph graph, ILogger logger, ITaskMonitoringSource factory, IList<IPersistentTaskSource> sources) { _graph = graph; _logger = logger; _factory = factory; sources.Each(x => _sources[x.Protocol] = x); _agents.OnMissing = uri => { var persistentTask = FindTask(uri); return persistentTask == null ? null : _factory.BuildAgentFor(persistentTask); }; _permanentTasks = sources.SelectMany(x => x.PermanentTasks()).ToArray(); }
public List<JsonPostResponse> Convert(IList<Post> posts, string username) { var list = posts.SelectMany(post => new List<JsonPostResponse>{ Convert(post, username) }); return list.ToList<JsonPostResponse>(); //List<JsonPostResponse> convertedPosts = new List<JsonPostResponse>(); //foreach (Post post in posts) //{ // convertedPosts.Add(Convert(post, username)); //} //return convertedPosts; }
public Dictionary<TimeSpan, List<CollectedSugar>> CollectByHour(Meal meal, IList<ReplacementItem> replacementItems) { this.meal = meal; IEnumerable<Tuple<Sugar, ReplacementItem>> sugarTuples = replacementItems .SelectMany(replacementItem => replacementItem.Pattern.After, (replacementItem, sugar) => new Tuple<Sugar, ReplacementItem>(sugar, replacementItem)); var collectedSugars = sugarTuples.Select(tuple => new CollectedSugar { Collected = GetSugarCopyWithRelativeTime(tuple), Source = tuple.Item2 }); var groupped = collectedSugars .GroupBy(collectedSugar => new TimeSpan(collectedSugar.Collected.DateTime.Hour, 0, 0)); return groupped.ToDictionary(groupping => groupping.Key + TimeSpan.FromMinutes(Math.Round( groupping.Average(collectedSugar => collectedSugar.Collected.DateTime.Minute))), groupping => groupping.ToList()); }
public DbReader(DbConnection conn, IEnumerable<IReadOnlyItem> items) { _conn = conn; _items = items.ToList(); _type = items.Select(i => i.Type().Value).FirstOrDefault(); _count = _items.Count; GetMetadata(); foreach (var rel in _items.SelectMany(i => i.Relationships()) .OrderBy(i => i.Type().Value)) { _items.Add(rel); }; }
public virtual TeamStrength CalculateLastSeasonForm(IList<Player> players, int seasonEndYear) { var seasonRecords = players.SelectMany(p => p.PastSeasons.Where(ps => ps.SeasonEndYear == seasonEndYear)).ToList(); var totalMinutes = seasonRecords.Sum(s => s.MinutesPlayed); var totalPoints = seasonRecords.Sum(s => s.TotalPointsScored); return new TeamStrength { SamplePlayers = players.Count, TotalMinutes = totalMinutes, TotalPointsScored = totalPoints, PointsPerMinute = totalPoints/(double)totalMinutes, }; }
public static DoughnutChart GetAverageGameDurationPriceDoughnut(IList<DetailedStatistics> detailedStatistics) { var allReports = detailedStatistics.SelectMany(s => s.Reports).ToList(); var averageDuration = allReports.Sum(r => r.ElapsedTime) / allReports.Count(); var averageGameDirationDoughnut = new DoughnutChart(); averageGameDirationDoughnut.Data = new List<SimpleData>() { new SimpleData() { Value = averageDuration, Label = "Среднее время одной игры", Color = Colors.Blue } }; averageGameDirationDoughnut.ChartConfiguration.Responsive = true; return averageGameDirationDoughnut; }
public HBaseRowData(IList<TRowResult> rowResult) { Key = rowResult[0].Row; Columns = new Dictionary<byte[], IList<IHBaseCellData>>(); foreach (var column in rowResult.SelectMany(r => r.Columns)) { if (Columns.ContainsKey(column.Key)) { Columns[column.Key].Add(new HBaseCellData(column.Value)); } else { Columns.Add(column.Key, new List<IHBaseCellData> { new HBaseCellData(column.Value) }); } } }
public static DoughnutChart GetAverageGamePriceDoughnut(IList<DetailedStatistics> detailedStatistics) { var allReports = detailedStatistics.SelectMany(s => s.Reports).ToList(); var averagePrice = allReports.Sum(r => r.Cost) / allReports.Count(); var averageGamePriceDoughnut = new DoughnutChart(); averageGamePriceDoughnut.Data = new List<SimpleData>() { new SimpleData() { Value = averagePrice, Label = "Средняя цена за игру", Color = Colors.Blue } }; averageGamePriceDoughnut.ChartConfiguration.Responsive = true; return averageGamePriceDoughnut; }
internal GraphPattern BuildGraphPattern(INamespaceMapper prefixes) { var graphPattern = CreateGraphPattern(); foreach (var triplePattern in _triplePatterns.SelectMany(getTriplePatterns => getTriplePatterns(prefixes))) { AddTriplePattern(graphPattern, triplePattern); } foreach (var graphPatternBuilder in _childGraphPatternBuilders) { graphPattern.AddGraphPattern(graphPatternBuilder.BuildGraphPattern(prefixes)); } foreach (var buildFilter in _filterBuilders) { graphPattern.AddFilter(new UnaryExpressionFilter(buildFilter(prefixes))); } return(graphPattern); }
void model_Changed(IList<IChange> changes) { notifyIcon.Icon = GetIcon(changes.Count); int countOfDistinctFilesTouched = changes.SelectMany(change => change.Files) .Select(path => path.Path).Distinct().Count(); if (!changes.Any(log => log.IsRelevant)) { return; } IChange latestChange = changes[changes.Count - 1]; string title = latestChange.User + "'s checked in" + sizeOf(latestChange.Files.Count) + "."; string text = latestChange.Message + "\r\nYou have " + SayPlural(changes.Count, " pending change") + ", touching " + SayPlural(countOfDistinctFilesTouched, " file") + "."; notifyIcon.ShowBalloonTip(10*1000, title, text, BalloonTipIcon.Info); }
public void ActOnPeoplePresent(ICollection <Person> people) { lock (_mutex) _tick = false; var state = new Dictionary <IDevice, Tuple <double, bool> >(); foreach (var device in _scenarios.SelectMany(scenario => scenario.Devices)) { state[device] = new Tuple <double, bool>(-1, false); } foreach (var person in people) { foreach (var scenario in _scenarios) { if (scenario.Zone.InZone(person)) { var priority = scenario.Priority * 1000 + (100 - Distance(scenario.Zone, person)); foreach (var device in scenario.Devices) { if (state[device].Item1 < priority) { state.Remove(device); state[device] = new Tuple <double, bool>(priority, true); } } } } } foreach (var kvp in state) { if (kvp.Value.Item2) { kvp.Key.Restore(); } else { kvp.Key.Off(); } } }
static void ConfigureDataGrid(IList <DataGrid> grids) { grids.ForEach( a => { //a.CanUserAddRows = true; a.CanUserDeleteRows = true; a.CanUserReorderColumns = true; a.CanUserResizeColumns = true; a.CanUserResizeRows = true; a.CanUserSortColumns = true; a.GridLinesVisibility = DataGridGridLinesVisibility.None; a.MouseUp += (_, __) => { a.BeginEdit(); }; }); grids.SelectMany(a => a.Columns) .ForEach( a => { if (!string.IsNullOrWhiteSpace(a.SortMemberPath)) { return; } var sortClipboard = (string)a.GetValue(SortingClipboard.SortAndClipboardPathProperty); if (sortClipboard != null) { a.SortMemberPath = sortClipboard; } else if (a.Header != null && a.Header is string) { a.SortMemberPath = (a.Header as string).Replace(" ", string.Empty); } if (a.SortMemberPath != null) { a.ClipboardContentBinding = new Binding(a.SortMemberPath); } }); }
public IList <Product> GetRewardProducts(IList <IIndividualReward> rewards, IList <Product> productsInShoppingCart) { IList <Product> rewardProducts = null; if (rewards != null) { rewardProducts = rewards.SelectMany(r => r.GetActiveRewardProducts(productsInShoppingCart)).ToList(); // Specialized logic - If both New Style Ambassador and Ongoing Style Ambassador rewards are active (will be the first 30 days a Style Ambassador joins), // remove any duplicate reward products the New Style Ambassador reward offers that the Ongoing Style Ambassador reward also offers. if (rewards.Any(r => r is NewStyleAmbassadorHalfOffReward)) /*&& (rewards.Any(r => r is NewProductsLaunchReward) || rewards.Any(r => r is OngoingStyleAmbassadorHalfOffReward)))*/ { IList <string> rewardItemCodes = rewardProducts.Where(p => p.EligibleDiscounts.Any(d => d.DiscountType == DiscountType.SAHalfOffOngoing) || p.EligibleDiscounts.Any(d => d.DiscountType == DiscountType.NewProductsLaunchReward)).Select(p => p.ItemCode).ToList(); rewardProducts = rewardProducts.Where(p => !(p.EligibleDiscounts.Any(d => d.DiscountType == DiscountType.SAHalfOff) && rewardItemCodes.Contains(p.ItemCode))).ToList(); } } return(rewardProducts); }
private protected IReadOnlyList <PackageReference> GetTransitivePackageReferences(NuGetFramework targetFramework, Dictionary <string, ProjectInstalledPackage> installedPackages, Dictionary <string, ProjectInstalledPackage> transitivePackages, IList <LockFileTarget> targets) { // If the assets files has not been updated, return the cached transitive packages if (targets == null) { return(transitivePackages .Select(package => new PackageReference(package.Value.InstalledPackage, targetFramework)) .ToList()); } else { return(targets .SelectMany(target => target.Libraries) .Where(library => library.Type == LibraryType.Package) .SelectMany(library => GetPackageReferenceUtility.UpdateTransitiveDependencies(library, targetFramework, targets, installedPackages, transitivePackages)) .Select(packageIdentity => new PackageReference(packageIdentity, targetFramework)) .ToList()); } }
public void Initialize(int sourceControlVersionId) { this.entities = new AspNetDeployEntities(); this.sourceControlVersion = this.entities.SourceControlVersion .Include("Properties") .Include("SourceControl.Properties") .First(svc => svc.Id == sourceControlVersionId); this.existingProjects = this.entities.Project .Include("ProjectVersions") .Where(p => p.SourceControlId == sourceControlVersion.SourceControlId) .ToList(); this.existingProjectVersions = existingProjects .SelectMany(p => p.ProjectVersions) .Where(pv => pv.SourceControlVersionId == sourceControlVersion.Id) .ToList(); }
private Wait RoutineBranch(Creature user, IList <Tile> tileRay) { var lightning = SpriteLoader.Instance.AddSprite("content/lightning"); var startTile = tileRay.First(); var endTile = tileRay.Last(); new LightningSpark(user.World, lightning, startTile.VisualTarget, endTile.VisualTarget, 5); //new Arc(user.World, lightning, () => startTile.VisualTarget, () => endTile.VisualTarget, Vector2.Zero, Vector2.Zero, 1, 20); var creatures = tileRay.SelectMany(t => t.Creatures).Distinct(); var waits = new List <Wait>(); foreach (var targetCreature in creatures.Where(c => !SameCreatureType(user, c))) { var wait = user.Attack(targetCreature, SkillUtil.SafeNormalize(targetCreature.VisualTarget - user.VisualTarget), BeamAttack); waits.Add(wait); } return(new WaitAll(waits)); }
/// <summary> /// Tries to decode the original data from all <see cref="Slice"/>s previously given to /// <see cref="Remember"/>. /// </summary> /// <remarks> /// Decoding the original data is akin to solving a set of linear equations. Each <see cref="Slice"/> /// represents one more equation. So enough <see cref="Slice"/>s have to be given to <see cref="Remember"/> /// in order to be able to solve them. /// </remarks> public bool TrySolve(out byte[] solution) { var solved = false; foreach (var step in GaussianEliminationHelpers.Solve( _coefficientsList, _numCoefficients)) { switch (step.Operation) { case Operation.Complete: solved = true; break; case Operation.Swap: Swap( step.From, step.To, _solutionsList); break; case Operation.Xor: Xor( step.From, step.To, _solutionsList); break; default: throw new NotImplementedException(); } } solution = solved ? _solutionsList .SelectMany(x => x.GetBytes(_sliceSize)) .Take(_totalLength) .ToArray() : null; return(solved); }
private static void InitPlugins(IList <Assembly> plugins) { Plugins = plugins; _pluginNamespaces = plugins.SelectMany(p => p.GetExportedTypes()).Select(t => new AssemblyNamespace { Assembly = t.Assembly, Namespace = t.Namespace }).Distinct().ToList(); try { if (!File.Exists(WrapperDllPath)) { (new FileInfo(WrapperDllPath)).Directory.Create(); OutputWrapperDll(); } else { // Check if WrapperDll is of same version as the TabularEditor.exe and same Compatibility Level. If not, output a new one: var wrapperVersion = FileVersionInfo.GetVersionInfo(WrapperDllPath); var currentVersion = Assembly.GetAssembly(typeof(TabularModelHandler)).GetName().Version; if (wrapperVersion.FileVersion != currentVersion.ToString()) { OutputWrapperDll(); } } if (File.Exists(CustomActionsJsonPath)) { Console.WriteLine("Loading custom actions from: " + CustomActionsJsonPath); var actions = CustomActionsJson.LoadFromJson(CustomActionsJsonPath); actions.SaveToJson(@"C:\TE\testactions.json"); CompileCustomActions(actions); } else { ScriptEngineStatus = "File not found: " + CustomActionsJsonPath; } } catch (Exception ex) { Debug.WriteLine(ex.Message); ScriptEngineStatus = "Error: " + ex.Message; } }
private ItemUpdateType UpdateGenres(TItemType item, IList <BaseItem> children) { var updateType = ItemUpdateType.None; if (!item.LockedFields.Contains(MetadataFields.Genres)) { var currentList = item.Genres.ToList(); item.Genres = children.SelectMany(i => i.Genres) .Distinct(StringComparer.OrdinalIgnoreCase) .ToList(); if (currentList.Count != item.Genres.Count || !currentList.OrderBy(i => i).SequenceEqual(item.Genres.OrderBy(i => i), StringComparer.OrdinalIgnoreCase)) { updateType = updateType | ItemUpdateType.MetadataEdit; } } return(updateType); }
private IReadOnlyCollection <Type> ProcessConverter(IList <RegisteredJsonConverter> registeredConverters, bool checkForAlreadyRegistered = true) { var handledTypes = registeredConverters.SelectMany(_ => _.HandledTypes).ToList(); if (checkForAlreadyRegistered && this.RegisteredTypeToDetailsMap.Keys.Intersect(handledTypes).Any()) { throw new DuplicateRegistrationException( Invariant($"Trying to register one or more types via {nameof(this.ConvertersToRegister)} processing, but one is already registered."), handledTypes); } this.RegisteredConverters.AddRange(registeredConverters); this.TypesWithConverters.AddRange(handledTypes); this.TypesWithStringConverters.AddRange( registeredConverters .Where(_ => _.OutputKind == RegisteredJsonConverterOutputKind.String) .SelectMany(_ => _.HandledTypes).Distinct()); return(handledTypes); }
public IEnumerable <ValidationResult> Validate() { if (_hosts.Count == 0) { yield return(this.Failure("Host", "At least one host must be defined")); } if (string.IsNullOrWhiteSpace(_settings.QueueName)) { yield return(this.Failure("Bus", "The bus queue name must not be null or empty")); } foreach (ValidationResult result in _transportBuilderConfigurators.SelectMany(x => x.Validate())) { yield return(result); } foreach (ValidationResult result in _consumePipeSpecification.Validate()) { yield return(result); } }
public void Save(UPath savePath) { // 1. Create file system for archive var archiveFileSystem = FileSystemFactory.CreateAfiFileSystem(ArchiveState, UPath.Root, _archiveStateInfo.StreamManager); // 2. Save PVB and PBIs var distinctPointMappings = _pointMappings.SelectMany(x => x).Batch(6).Select(x => x.OrderBy(y => y.v).ThenBy(y => y.u)).SelectMany(x => x).Distinct().ToArray(); SavePvb(archiveFileSystem, distinctPointMappings); SavePbis(archiveFileSystem, _pointMappings, distinctPointMappings); // 3. Save images foreach (var stateInfo in _imageStateInfos) { _pluginManager.SaveFile(stateInfo); } // 3. Save original archive _pluginManager.SaveFile(_archiveStateInfo, savePath); }
public SearchResults Process(IList <IList <Cell> > input) { var cummulativeComponents = new List <Component>(); var cummulativeInformation = new List <Information>(); foreach (var cell in input.SelectMany(row => row)) { var components = detectors.SelectMany(detector => FindComponents(detector, cell)).ToList(); var information = inspectors.SelectMany(inspector => inspector.Inspect(components)); cummulativeComponents.AddRange(components); cummulativeInformation.AddRange(information); } var verifiedInformation = verifiers.SelectMany(func => func(cummulativeInformation)); cummulativeInformation.AddRange(verifiedInformation); return(new SearchResults(input, cummulativeComponents, cummulativeInformation)); }
/// <summary> /// Build a battle's initial state. /// </summary> /// <param name="distribution">Represent a stubbed distribution of cards. /// By Player, we have a list of CardStack(a list of cards list). /// </param> /// <param name="source"></param> /// <returns></returns> public static Game BuildGame(IList <List <Card> > distribution, IEnumerable <Player> source) { var numberOfJoueurs = distribution.Count; var playersCollection = source.ToArray(); for (int i = 0; i < numberOfJoueurs; i++) { playersCollection[i].CardStack = new CardStack(distribution[i]); } IDistributeCards cardsDistributor = Substitute.For <IDistributeCards>(); cardsDistributor.DistributedCardsSize.Returns(distribution.SelectMany(x => x).Count()); cardsDistributor.Distribute().Returns(playersCollection.ToList()); var game = new Game(cardsDistributor); return(game); }
private static IList <UnspentTxOut> FilterTransactionPoolTransactions(IList <UnspentTxOut> unspentTxOuts, IList <Transaction> transactionPool) { IList <TxIn> txIns = transactionPool .SelectMany(tx => tx.TxIns) .ToList(); IList <UnspentTxOut> removable = new List <UnspentTxOut>(); foreach (UnspentTxOut unspentTxOut in unspentTxOuts) { TxIn txIn = txIns.FirstOrDefault(aTxIn => aTxIn.TxOutIndex == unspentTxOut.TxOutIndex && aTxIn.TxOutId == unspentTxOut.TxOutId); if (txIn != null) { removable.Add(unspentTxOut); } } return(unspentTxOuts.Except(removable).ToList()); }
private async Task <IList <NetworkModel> > GetNetworkModelsAsync(IList <Network> networks) { List <Guid> accessIds = networks.SelectMany(n => new[] { n.ReadAccessId, n.WriteAccessId }).ToList(); List <NetworkUserAccess> userAccesses = await Context.NetworkUserAccesses .Include(nameof(NetworkUserAccess.User)) .Where(n => accessIds.Contains(n.NetworkAccessId)) .ToListAsync(); ILookup <Guid, NetworkUserAccess> userAccessesMapping = userAccesses.ToLookup(a => a.NetworkAccessId); return(networks .Select(n => new NetworkModel( n, n.ReadAccess, userAccessesMapping[n.ReadAccessId].ToList(), n.WriteAccess, userAccessesMapping[n.WriteAccessId].ToList())) .ToList()); }
private void dropSearchStockSearchBy_onItemSelected(object sender, EventArgs e) { IList <Item> searchItems = userController.GetItems(false); switch (dropSearchStockSearchBy.selectedIndex) { case 1: searchItems = searchItems .Where(x => x.Stocks.Any(y => y.CompanyName.ToLower().Contains(txtSearchStock.Text.ToLower()))).ToList(); break; default: searchItems = searchItems .Where(x => x.Name.ToLower().Contains(txtSearchStock.Text.ToLower())).ToList(); break; } Stocks = searchItems.SelectMany(x => x.Stocks).ToList(); ListUtil.InitializeListView(mlvSearchStock, Stocks, searchItems); }
/// <summary> /// Initializes ListView details with garbage properties by item's garbages list /// </summary> /// <param name="mlv">ListView Object</param> /// <param name="garbages">Garbage List</param> /// <param name="items">Item List</param> public static void InitializeListView(MaterialSkin.Controls.MaterialListView mlv, IList <Garbage> garbages, IList <Item> items) { mlv.Items.Clear(); int counter = 1; Item item; Stock stock; foreach (var garbage in garbages) { item = items.First(x => x.Id.Equals(garbage.Item_Id)); stock = items.SelectMany(x => x.Stocks).First(x => x.Id.Equals(garbage.Stock_Id)); ListViewItem listViewItem = new ListViewItem(counter++.ToString()); listViewItem.SubItems.Add(item.Name); listViewItem.SubItems.Add(stock.CompanyName); listViewItem.SubItems.Add(garbage.Quantity.ToString()); listViewItem.SubItems.Add(garbage.CreatedAt.ToShortDateString()); mlv.Items.Add(listViewItem); } }
private ItemUpdateType UpdateStudios(TItemType item, IList <BaseItem> children) { var updateType = ItemUpdateType.None; if (!item.LockedFields.Contains(MetadataField.Studios)) { var currentList = item.Studios; item.Studios = children.SelectMany(i => i.Studios) .Distinct(StringComparer.OrdinalIgnoreCase) .ToArray(); if (currentList.Length != item.Studios.Length || !currentList.OrderBy(i => i).SequenceEqual(item.Studios.OrderBy(i => i), StringComparer.OrdinalIgnoreCase)) { updateType |= ItemUpdateType.MetadataEdit; } } return(updateType); }
/// <inheritdoc/> public List <ResourceAccessSubmission> BuildResourceAccessSubmissions(IOpenApiContext context, AccessCheckOperationDescriptor[] requests, Dictionary <string, string> pathToResourceUriMap) { // Get the list of roles for the user. IList <string> roles = context.CurrentPrincipal .Claims .Where(c => c.Type == "roles") .Select(c => c.Value) .ToList(); // Now translate the set of requested evaluations into a set of requests for the claims service. This is built // from the cartesian product of the roles and requests lists. var submissions = roles.SelectMany(role => requests.Select(request => new ResourceAccessSubmission { ClaimPermissionsId = role, ResourceAccessType = request.Method, ResourceUri = pathToResourceUriMap[request.Path], })).ToList(); return(submissions); }
public void Initialize(IList <FilterHtmlGenerator.Filter> intializeFilters, params string[] joinFilterNames) { var filtersDic = intializeFilters.Union(intializeFilters.SelectMany(f => f.AllChildren)) .Where(r => r.FilterName != null) .ToDictionary(r => r.FilterName); foreach (var filterName in joinFilterNames) { var filter = (BaseFilterParameter <TTable>)filtersDic[filterName]; filter.Container = this; filter.IsJournalFilter = true; this.filters.Add(filterName, filter); this.filterItems.Add(filterName, new List <FilterItem>()); } this.GetChildsFromJournal = this.filters.Values.First().GetChildsFromJournal; this.AddFilter(intializeFilters); }
private Source GetSource <T>(string name, IList <T> data, Func <T, IEnumerable <float> > func) { var source = new Source { Id = name, Name = name }; var sourceArray = new Float_Array { Id = $"{name}-array", Count = (ulong)data.Count * 3, Value = string.Join(" ", data.SelectMany(func).Select(v => v.ToString(CultureInfo.InvariantCulture))) }; source.Float_Array = sourceArray; source.Technique_Common = new SourceTechnique_Common { Accessor = new Accessor { Source = $"#{name}-array", Count = (ulong)data.Count, Stride = 3 } }; source.Technique_Common.Accessor.Param.Add(new Param() { Name = "X", Type = "float" }); source.Technique_Common.Accessor.Param.Add(new Param() { Name = "Y", Type = "float" }); source.Technique_Common.Accessor.Param.Add(new Param() { Name = "Z", Type = "float" }); return(source); }
internal override Task ResolveView(ResolveViewArgs resolveViewArgs) { if (resolveViewArgs.Success == true) { return(Task.CompletedTask); } // build list of path patterns. var name = resolveViewArgs.Name.Replace('/', '.').Replace('\\', '.'); var paths = ViewExtensions.Select(ext => $"{name}{ext}"); foreach (var search in SearchPaths.SelectMany(_ => _.Prefixes.Select(prefix => new { prefix = prefix, assembly = _.Assembly }))) { // search every path pattern. foreach (var path in paths) { var absolutePath = string.IsNullOrWhiteSpace(search.prefix) ? path : $"{search.prefix.TrimEnd('.')}.{path}"; var info = search.assembly.GetManifestResourceInfo(absolutePath); if (info == null) { continue; } // resolve mime type. if (RoutableOptions.TryGetMimeType(Path.GetExtension(path), out var mimeType) == false) { mimeType = DefaultMimeType; } // construct response. resolveViewArgs.MimeType = mimeType; resolveViewArgs.LastModified = DateTime.MinValue; // embedded resources will not ever change. resolveViewArgs.GetStream = () => Task.FromResult(search.assembly.GetManifestResourceStream(absolutePath)); resolveViewArgs.Success = true; return(Task.CompletedTask); } } // no matches. return(Task.CompletedTask); }
public async Task <IList <ProductOrder> > CreateAsync(IList <ProductWithCharmsOrderDto> productsWithCharmsOrder) { var productsIds = productsWithCharmsOrder.Select(s => s.ProductId).Distinct().ToList(); var charmsIds = productsWithCharmsOrder.SelectMany(s => s.Charms).Select(s => s.CharmId).ToList(); var products = await productQueryService.GetRawByIdsAsync(productsIds); var charms = await charmQueryService.GetRawByIdsAsync(charmsIds); var enabledDiscounts = await productCategoryDiscountQueryService.GetRawActiveAsync(); var productsWithDiscounts = productCategoryDiscountQueryService.ApplyDiscountsToProducts(products, enabledDiscounts); var productOrders = new List <ProductOrder>(); foreach (var productWithCharmsOrder in productsWithCharmsOrder) { var productOrder = new ProductOrder(productWithCharmsOrder.Amount, productWithCharmsOrder.Comment, productWithCharmsOrder.Size, productWithCharmsOrder.Color); var productWithDiscount = productsWithDiscounts.First(x => x.Product.Id == productWithCharmsOrder.ProductId); productOrder.AddProduct(productWithDiscount.Product); productOrder.SetGraver(productWithCharmsOrder.Graver); var finalPrice = productWithDiscount.Product.Price; if (productWithCharmsOrder.HaveCharms) { var result = productOrderHelper.ApplyCharmsToProductOrder(productOrder, productWithCharmsOrder, charms, finalPrice); finalPrice = result.FinalPrice; } if (productWithDiscount.ProductCategoryDiscount != null) { productOrder.AddProductCategoryDiscount(productWithDiscount.ProductCategoryDiscount); var discountValue = finalPrice * (productWithDiscount.ProductCategoryDiscount.PercentValue / 100.0M); finalPrice -= discountValue; } productOrder.SetCurrentProductPrice(productWithDiscount.Product.Price); productOrder.SetFinalPrice(finalPrice); productOrders.Add(productOrder); } return(productOrders); }
public ActionResult Create(BillCreateCommand billCreateCommand, User currentUser) { if (!ModelState.IsValid) { IList <UserGroupMembership> userGroupMemberships = UserGroupService.FindMembershipsByUser(PageRequest.All, currentUser, new List <UserGroupMembershipType> { UserGroupMembershipType.Administrator, UserGroupMembershipType.Member }).ToList(); IList <UserGroup> userGroups = userGroupMemberships.Select(membership => membership.UserGroup).Distinct().ToList(); IList <UserGroupMembership> members = userGroups.SelectMany( userGroup => UserGroupService.FindMembershipsByGroups(PageRequest.All, new List <UserGroup> { userGroup }, new List <UserGroupMembershipType> { UserGroupMembershipType.Administrator, UserGroupMembershipType.Member })) .ToList(); return(View("Create", new BillCreateViewModel(userGroupMemberships, members, billCreateCommand))); } UserGroupMembership creditor = UserGroupService.FindMembershipsByUserAndGroup(currentUser, billCreateCommand.UserGroup); Bill bill = BillService.Create(billCreateCommand.UserGroup, billCreateCommand.BillDto, creditor, billCreateCommand.UserGroupDebitors.Values.ToList(), billCreateCommand.GuestDebitors.Values.ToList(), billCreateCommand.CreatedFromPeanut, currentUser); string billUrl = Url.Action("Show", "Bill", new { bill = bill.BusinessId }, Request.Url.Scheme); ; NotificationService.SendBillReceivedNotification(bill, billUrl); return(RedirectToAction("Show", new { bill = bill.BusinessId })); }
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"); } }
public static List <DataPoint> GetDataPoints(List <int> harmonics, bool useAverage, IList <MeasurementParent> measurements) { List <DataPoint> dataPoints = new List <DataPoint>(); foreach (var h in harmonics) { var harmonicMeasures = measurements.SelectMany(x => x.Measurements).Where(x => x.Harmonic == h).ToList(); if (useAverage) { var value = harmonicMeasures.Sum(x => x.Average); dataPoints.Add(new DataPoint(h, value)); } else { var value = harmonicMeasures.Sum(x => x.Max); dataPoints.Add(new DataPoint(h, value)); } } return(dataPoints); }
public static MapperConfiguration ConfigureAutomapper(IList<Type> types) { var profiles = types.SelectMany(t => t.GetInterfaces(), (t, i) => new { t, i }) .Where( type => typeof(Profile).IsAssignableFrom(type.t) && !type.t.IsAbstract && !type.t.IsInterface) .Select(type => (Profile)Activator.CreateInstance(type.t)); var config = new MapperConfiguration(cfg => { foreach (var profile in profiles) { cfg.AddProfile(profile); } }); return config; }
private static void Export2Mht( IServiceProvider provider, IList<IMsg> msgs, Stream fs, ProgressDelegate pd) { var encoding = Encoding.UTF8; using (var sw = new StreamWriter(fs, Encoding.Default)) { sw.Write( _mhtHeader, DateTime.Now.ToString("ddd, d MMM yyyy h:m:s zz00", CultureInfo.InvariantCulture), encoding.HeaderName); sw.Flush(); var htmlText = BuildHTMLPage(provider, msgs, pd, true, Encoding.UTF8); var page = encoding.GetBytes(htmlText); fs.Write(page, 0, page.Length); var usedSmileFiles = msgs .SelectMany(msg => TextFormatter.GetSmileFiles(msg.Body)) .Distinct(); const string prefix = @"ForumImages\"; foreach (var smileName in usedSmileFiles) { var smileImage = provider .GetRequiredService<IStyleImageManager>() .GetImage(prefix + smileName, StyleImageType.ConstSize); var ifi = ImageFormatInfo.FromImageFormat(smileImage.RawFormat); sw.Write(_mhtContentImageHeader, ifi.MimeType, smileName, ifi.Extension); using (var ms = new MemoryStream()) { smileImage.Save(ms, smileImage.RawFormat); sw.Write(Convert.ToBase64String(ms.ToArray(), Base64FormattingOptions.InsertLineBreaks)); } } sw.Write(_mhtFooter); } }
private void ApplyResult(ParametersInfo info, IList<RemapAlarmResult> result) { _reporter.Report(result.SelectMany(r => r.Notifications)); _dispatcherService.Invoke(() => ApplyStatus(info, result)); ApplyCurrentQueries(info, result); ApplyHistoryQueries(info, result); }
private void ApplyHistoryQueries(ParametersInfo info, IList<RemapAlarmResult> result) { for (var i = 0; i < result.Count; i++) { var p = info.Parameters[i]; var r = result[i]; var alarmCategory = _categories[p.Item1.CategoryId]; foreach (var a in r.History.SelectMany(alarms => alarms)) { var alarmInfo = alarmCategory.GetAlarmInfo(a.AlarmId); a.SetAlarmInfo(alarmInfo.Item1, alarmInfo.Item2, alarmCategory); } var callbacks = p.Item3; for (var j = 0; j < callbacks.Length; j++) { var callback = callbacks[j]; var alarms = r.History[info.CommonCurrentInfo.Count + j]; callback(alarms); } } for (var i = 0; i < info.CommonHistoryInfo.Count; i++) { var historyInfo = info.CommonHistoryInfo[i]; var i1 = i; var alarms = result.SelectMany(r => r.History[i1]); switch (historyInfo.Item2) { case CriteriaType.DownFromInfinity: case CriteriaType.DownFrom: case CriteriaType.DownFromOrEqual: alarms = alarms.OrderByDescending(a => a.StartTime).ThenByDescending(a => a.UserId).Take(historyInfo.Item3); break; case CriteriaType.UpFromInfinity: case CriteriaType.UpFrom: case CriteriaType.UpFromOrEqual: alarms = alarms.OrderBy(a => a.StartTime).ThenBy(a => a.UserId).Take(historyInfo.Item3).Reverse(); break; } var callback = historyInfo.Item1; var alarmsArray = alarms.ToArray(); callback(alarmsArray); } }
/// <summary> /// Decides what information from a ChromatogramGroupInfo should be thrown away. /// ChromatogramGroupInfo's can have the the retention time range shortened, and certain /// transitions discarded. /// </summary> private MinimizedChromGroup MinimizeChromGroup(Settings settings, ChromatogramGroupInfo chromatogramGroupInfo, IList<TransitionGroupDocNode> transitionGroups) { var fileIndexes = new List<int>(); for (int fileIndex = 0; fileIndex < Document.Settings.MeasuredResults.Chromatograms.Count; fileIndex++) { var chromatogramSet = Document.Settings.MeasuredResults.Chromatograms[fileIndex]; if (chromatogramSet.MSDataFilePaths.Any(path=>Equals(path, chromatogramGroupInfo.FilePath))) { fileIndexes.Add(fileIndex); } } var chromatograms = chromatogramGroupInfo.TransitionPointSets.ToArray(); Assume.IsTrue(Equals(chromatogramGroupInfo.NumTransitions, chromatograms.Length)); var keptTransitionIndexes = new List<int>(); double minRetentionTime = Double.MaxValue; double maxRetentionTime = -Double.MaxValue; for (int i = 0; i < chromatograms.Length; i++) { var chromatogram = chromatograms[i]; var matchingTransitions = new List<TransitionDocNode>(); foreach (var transitionDocNode in transitionGroups.SelectMany(tg => tg.Transitions)) { if (0!=ChromKey.CompareTolerant((float) chromatogram.ProductMz, (float) transitionDocNode.Mz, _tolerance)) { continue; } matchingTransitions.Add(transitionDocNode); foreach (var fileIndex in fileIndexes) { var chromatogramSet = transitionDocNode.Results[fileIndex]; if (chromatogramSet == null) { continue; } foreach (var transitionChromInfo in chromatogramSet) { if (transitionChromInfo.IsEmpty) { continue; } minRetentionTime = Math.Min(minRetentionTime, transitionChromInfo.StartRetentionTime); maxRetentionTime = Math.Max(maxRetentionTime, transitionChromInfo.EndRetentionTime); } } } bool kept = !settings.DiscardUnmatchedChromatograms || matchingTransitions.Count > 0; if (kept) { keptTransitionIndexes.Add(i); } } var result = new MinimizedChromGroup(chromatogramGroupInfo.Header) { RetainedTransitionIndexes = keptTransitionIndexes, }; if (settings.NoiseTimeRange.HasValue && minRetentionTime < maxRetentionTime) { if (null == chromatogramGroupInfo.Times) { // Chromatogram was unreadable. result.RetainedTransitionIndexes.Clear(); } else { result.SetStartEndTime(chromatogramGroupInfo.Times, (float)(minRetentionTime - settings.NoiseTimeRange), (float)(maxRetentionTime + settings.NoiseTimeRange)); } } return result; }
private void HandleFunctionOrPredicate(CommonTree tree, CommonTree name, IList<CommonTree> parameters, CommonTree returnSpec, ImageSource glyph) { if (tree == null || name == null) return; var navigationType = EditorNavigationTypeRegistryService.GetEditorNavigationType(PredefinedEditorNavigationTypes.Members); var startToken = _tokens[tree.TokenStartIndex]; var stopToken = _tokens[tree.TokenStopIndex]; Span span = new Span(startToken.StartIndex, stopToken.StopIndex - startToken.StartIndex + 1); SnapshotSpan ruleSpan = new SnapshotSpan(Snapshot, span); SnapshotSpan ruleSeek = new SnapshotSpan(Snapshot, new Span(name.Token.StartIndex, 0)); string functionDisplayName = (name.Type == DOT) ? GetNameText((CommonTree)name.Children[1]) : GetNameText(name); string thisType = (name.Type == DOT) ? GetNameText((CommonTree)name.Children[0]) : null; IEnumerable<string> thisParam = !string.IsNullOrEmpty(thisType) ? Enumerable.Repeat(string.Format("this : {0}", thisType), 1) : Enumerable.Empty<string>(); IList<string> parameterText = thisParam.Concat(parameters != null ? parameters.SelectMany(GetParameterText) : new string[0]).ToArray(); string returnText = returnSpec != null ? string.Format(" : {0}", GetNameText(returnSpec)) : string.Empty; string displayName = string.Format("{0} {1}[{2}]{3}", tree.Text, functionDisplayName, string.Join(", ", parameterText), returnText); _targets.Add(new EditorNavigationTarget(displayName, navigationType, ruleSpan, ruleSeek, glyph)); }