public CloudApiCatalogLookup(DotNetCatalog catalog) { _builtBy = catalog.BuiltBy; // we want to recreate the fast look-up data structures. _apiMapping = catalog.Apis.AsParallel() .ToDictionary(key => key.DocId, value => value.Targets.ToDictionary(innerkey => innerkey.Identifier, innervalue => innervalue.Version, StringComparer.OrdinalIgnoreCase)); _apiMetadata = catalog.Apis.AsParallel() .Where(api => api.Metadata != null) .ToDictionary( key => key.DocId, value => value.Metadata.ToDictionary( innerKey => innerKey.MetadataKey, innerValue => innerValue.Value, StringComparer.Ordinal), StringComparer.Ordinal); _publicTargets = catalog.SupportedTargets .Where(sp => sp.IsReleased) .Select(sp => sp.DisplayName) .ToList(); _latestTargetVersion = catalog.SupportedTargets .GroupBy(sp => sp.DisplayName.Identifier) .ToDictionary(key => key.Key, value => value.OrderByDescending(p => p.DisplayName.Version).First().DisplayName, StringComparer.OrdinalIgnoreCase); _allTargets = catalog.SupportedTargets; _frameworkAssemblies = new HashSet<string>(catalog.FrameworkAssemblyIdenties, StringComparer.OrdinalIgnoreCase); _docIdToApi = catalog.Apis.ToDictionary(key => key.DocId, key => new ApiDefinition { DocId = key.DocId, Name = key.Name, ReturnType = key.Type, FullName = key.FullName, Parent = key.Parent }); }
public ToolBarButton(UIElement inputBindingOwner, Codon codon, object caller, bool createCommand, IReadOnlyCollection<ICondition> conditions) { ToolTipService.SetShowOnDisabled(this, true); this.codon = codon; this.caller = caller; if (createCommand) this.Command = CommandWrapper.CreateCommand(codon, conditions); else this.Command = CommandWrapper.CreateLazyCommand(codon, conditions); this.CommandParameter = caller; this.Content = ToolBarService.CreateToolBarItemContent(codon); this.conditions = conditions; if (codon.Properties.Contains("name")) { this.Name = codon.Properties["name"]; } if (!string.IsNullOrEmpty(codon.Properties["shortcut"])) { KeyGesture kg = MenuService.ParseShortcut(codon.Properties["shortcut"]); MenuCommand.AddGestureToInputBindingOwner(inputBindingOwner, kg, this.Command, GetFeatureName()); this.inputGestureText = MenuService.GetDisplayStringForShortcut(kg); } UpdateText(); SetResourceReference(FrameworkElement.StyleProperty, ToolBar.ButtonStyleKey); }
private void Handle(IReadOnlyCollection<IAggregateCommand> commands) { var aggregateRootTypes = commands.Select(x => x.AggregateRootType).ToArray(); var actors = _aggregateActorFactory.Create(aggregateRootTypes); // TODO: Can agreggate actors be executed in parallel? See https://github.com/2gis/nuclear-river/issues/76 foreach (var actor in actors) { var actorName = actor.GetType().GetFriendlyName(); using (var transaction = new TransactionScope( TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted, Timeout = TimeSpan.Zero })) { using (Probe.Create($"ETL2 {actorName}")) { actor.ExecuteCommands(commands); } transaction.Complete(); } } _telemetryPublisher.Publish<StatisticsProcessedOperationCountIdentity>(commands.Count); }
private void Handle(IReadOnlyCollection<FactOperation> operations) { _tracer.Debug("Handing fact operations started"); var result = _factsReplicator.Replicate(operations); _telemetryPublisher.Publish<ErmProcessedOperationCountIdentity>(operations.Count); var statistics = result.OfType<RecalculateStatisticsOperation>().ToArray(); var aggregates = result.OfType<AggregateOperation>().ToArray(); // We always need to use different transaction scope to operate with operation sender because it has its own store using (var pushTransaction = new TransactionScope(TransactionScopeOption.RequiresNew, new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted, Timeout = TimeSpan.Zero })) { _tracer.Debug("Pushing events for statistics recalculation"); _statisticsSender.Push(statistics); _telemetryPublisher.Publish<StatisticsEnqueuedOperationCountIdentity>(statistics.Length); _tracer.Debug("Pushing events for aggregates recalculation"); _aggregateSender.Push(aggregates); _telemetryPublisher.Publish<AggregateEnqueuedOperationCountIdentity>(aggregates.Length); pushTransaction.Complete(); } _tracer.Debug("Handing fact operations finished"); }
public AllCommittedEventsPage( GlobalPosition nextGlobalPosition, IReadOnlyCollection<ICommittedDomainEvent> committedDomainEvents) { NextGlobalPosition = nextGlobalPosition; CommittedDomainEvents = committedDomainEvents; }
public MusicFile(Func<string, Task<MusicMetadata>> loadMetadata, string fileName) { this.loadMetadataCompletionSource = new TaskCompletionSource<MusicMetadata>(); this.loadMetadata = loadMetadata; this.fileName = fileName; this.sharedMusicFiles = new MusicFile[0]; }
public static CardValuationType CalculateRisk(Card leftCard, Card rightCard, IReadOnlyCollection<Card> communityCard) { List<Card> cards = new List<Card>(communityCard); cards.Add(leftCard); cards.Add(rightCard); var handRankType = Helpers.GetHandRank(cards); switch (handRankType) { case HandRankType.Pair: return CardValuationType.Risky; case HandRankType.TwoPairs: return CardValuationType.Recommended; case HandRankType.ThreeOfAKind: case HandRankType.Straight: return CardValuationType.VeryRecommended; case HandRankType.Flush: case HandRankType.FullHouse: case HandRankType.FourOfAKind: return CardValuationType.VeryPowerful; case HandRankType.StraightFlush: return CardValuationType.AllIn; default: return CardValuationType.Unplayable; } }
public static void RegisterHandlersWithAutofac(ContainerBuilder containerBuilder, IReadOnlyCollection<MessageRegistration> registrations) { var handlers = registrations.Select(x => x.Handler).Distinct(); var piplelineHandlers = registrations.Select(x => x.Pipeline).Distinct().SelectMany(x => x).Distinct(); RegisterLeafHandlers(containerBuilder, handlers); RegisterPipelineHandlers(containerBuilder, piplelineHandlers); foreach (var registration in registrations) { if (registration.Dependancies.Any()) { foreach (var dependancy in registration.Dependancies) { containerBuilder.RegisterType(dependancy).AsSelf(); } } if (registration.ScopedDependancies.Any()) { foreach (var dependancy in registration.ScopedDependancies) { containerBuilder.RegisterType(dependancy).AsSelf().AsImplementedInterfaces().InstancePerLifetimeScope(); } } } }
public IndexCollection(IReadOnlyCollection<Index> latest, IndexCollection previous, FileInfo info, Encoding encoding) { Info = info; Encoding = encoding; Count = latest.Select(idx => idx.LineCount).Sum(); Indicies = latest.ToArray(); Diff = Count - (previous?.Count ?? 0); //need to check whether if (previous == null) { ChangedReason = LinesChangedReason.Loaded; TailInfo = new TailInfo(latest.Max(idx => idx.End)); } else { var mostRecent = latest.OrderByDescending(l => l.TimeStamp).First(); ChangedReason = mostRecent.Type == IndexType.Tail ? LinesChangedReason.Tailed : LinesChangedReason.Paged; TailInfo = new TailInfo(previous.Indicies.Max(idx => idx.End)); } }
public async Task PublishAsync(IReadOnlyCollection<RabbitMqMessage> rabbitMqMessages, CancellationToken cancellationToken) { var uri = _configuration.Uri; IRabbitConnection rabbitConnection = null; try { rabbitConnection = await GetRabbitMqConnectionAsync(uri, cancellationToken).ConfigureAwait(false); await _transientFaultHandler.TryAsync( c => rabbitConnection.WithModelAsync(m => PublishAsync(m, rabbitMqMessages), c), Label.Named("rabbitmq-publish"), cancellationToken) .ConfigureAwait(false); } catch (OperationCanceledException) { throw; } catch (Exception e) { if (rabbitConnection != null) { using (await _asyncLock.WaitAsync(CancellationToken.None).ConfigureAwait(false)) { rabbitConnection.Dispose(); _connections.Remove(uri); } } _log.Error(e, "Failed to publish domain events to RabbitMQ"); throw; } }
public static IContainer ConfigureContainer(this IAppBuilder app, HttpConfiguration config, IReadOnlyCollection<Assembly> applicationAssemblies, IEnumerable<Module> dependencyModules, WebOption webOption) { var builder = new ContainerBuilder(); foreach (var module in dependencyModules) builder.RegisterModule(module); var assemblies = applicationAssemblies.ToArray(); ConfigureContainer(builder, webOption, assemblies); if (webOption.UseApi) builder.RegisterWebApiFilterProvider(config); var container = builder.Build(); if (webOption.UseApi) config.DependencyResolver = new AutofacWebApiDependencyResolver(container); if (webOption.UseMvc) DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); app.UseAutofacMiddleware(container); if (webOption.UseApi) app.UseAutofacWebApi(config); return container; }
public ToolbarItemDescriptor(object parameter, Codon codon, IList subItems, IReadOnlyCollection<ICondition> conditions) { this.Parameter = parameter; this.Codon = codon; this.SubItems = subItems; this.Conditions = conditions; }
private static void SetToCache(UserToken userToken, EntityToken entityToken, IReadOnlyCollection<PermissionType> permissionTypes, object cachingKey) { // Using RequestLifetimeCache and there for no thread locking /MRJ Dictionary<UserToken, Dictionary<EntityToken, IReadOnlyCollection<PermissionType>>> permissionTypeCache; if (RequestLifetimeCache.HasKey(cachingKey)) { permissionTypeCache = RequestLifetimeCache.TryGet<Dictionary<UserToken, Dictionary<EntityToken, IReadOnlyCollection<PermissionType>>>>(cachingKey); } else { permissionTypeCache = new Dictionary<UserToken, Dictionary<EntityToken, IReadOnlyCollection<PermissionType>>>(); RequestLifetimeCache.Add(cachingKey, permissionTypeCache); } Dictionary<EntityToken, IReadOnlyCollection<PermissionType>> entityTokenPermissionTypes; if (!permissionTypeCache.TryGetValue(userToken, out entityTokenPermissionTypes)) { entityTokenPermissionTypes = new Dictionary<EntityToken, IReadOnlyCollection<PermissionType>>(); permissionTypeCache.Add(userToken, entityTokenPermissionTypes); } if (!entityTokenPermissionTypes.ContainsKey(entityToken)) { entityTokenPermissionTypes.Add(entityToken, permissionTypes); } else { entityTokenPermissionTypes[entityToken] = entityTokenPermissionTypes[entityToken].Concat(permissionTypes).Distinct().ToList(); } }
internal ExecutionPlan( IEnumerable<IPluginInfo> pluginsToStart, IEnumerable<IPluginInfo> pluginsToStop, IReadOnlyCollection<IPluginInfo> pluginsToDisable ) { Debug.Assert( pluginsToStart != null && pluginsToStop != null && pluginsToDisable != null ); PluginsToStart = pluginsToStart.ToReadOnlyCollection(); PluginsToStop = pluginsToStop.ToReadOnlyCollection(); PluginsToDisable = pluginsToDisable; }
public void CreateStores(IReadOnlyCollection<DataTypeDescriptor> dataTypeDescriptors) { var dataTypes = DataTypeTypesManager.GetDataTypes(dataTypeDescriptors); var storesToCreate = new List<GeneratedTypesInfo>(); foreach (var dataTypeDescriptor in dataTypeDescriptors) { Type interfaceType = dataTypes[dataTypeDescriptor.DataTypeId]; storesToCreate.Add(BuildGeneratedTypesInfo(dataTypeDescriptor, interfaceType)); } CompileMissingTypes(storesToCreate); foreach (var storeToCreate in storesToCreate) { var dataTypeDescriptor = storeToCreate.DataTypeDescriptor; InterfaceConfigurationManipulator.AddNew(_dataProviderContext.ProviderName, dataTypeDescriptor); var xmlDataTypeStoreCreator = new XmlDataTypeStoreCreator(_fileStoreDirectory); XmlDataTypeStore xmlDateTypeStore = xmlDataTypeStoreCreator.CreateStoreResult( dataTypeDescriptor, storeToCreate.DataProviderHelperClass, storeToCreate.DataIdClass, null); Type interfaceType = storeToCreate.InterfaceType; AddDataTypeStore(dataTypeDescriptor, interfaceType, xmlDateTypeStore); } }
public Music(Key key = null, Time time = null, string tune = null, IReadOnlyCollection<Attribution> sources = null) { Tune = tune; Key = key; Time = time; Sources = sources; }
/// <exclude /> public IndexAttribute(string fieldName, IndexDirection indexDirection) { _fields = new List<Tuple<string, IndexDirection>> { new Tuple<string, IndexDirection>(fieldName, indexDirection) }; }
void matchIntoAnagrams(IReadOnlyCollection<char> source, string lexiconWord, ICollection<Anagram> anagrams) { if (lexiconWord.Length < MIN_WORD_LENGTH) return; if (lexiconWord.Length > source.Count) return; var unused = source.ToList(); var used = new List<char>(); foreach (var letter in lexiconWord) { if (!unused.Move(letter, used)) if (!unused.Move(WILDCARD, used)) break; } if (used.Count != lexiconWord.Length) return; var points = getTotalPoints(used); var anagram = new Anagram(lexiconWord, points); anagrams.Add(anagram); }
public static ObservableViewModel CombineViewModels(IViewModelServiceProvider serviceProvider, NodeContainer nodeContainer, IReadOnlyCollection<ObservableViewModel> viewModels) { if (viewModels == null) throw new ArgumentNullException(nameof(viewModels)); var combinedViewModel = new ObservableViewModel(serviceProvider, nodeContainer, viewModels.SelectMany(x => x.Dirtiables)); var rootNodes = new List<ObservableModelNode>(); foreach (var viewModel in viewModels) { if (!(viewModel.RootNode is SingleObservableNode)) throw new ArgumentException(@"The view models to combine must contains SingleObservableNode.", nameof(viewModels)); viewModel.parent = combinedViewModel; var rootNode = (ObservableModelNode)viewModel.RootNode; rootNodes.Add(rootNode); } if (rootNodes.Count < 2) throw new ArgumentException(@"Called CombineViewModels with a collection of view models that is either empty or containt just a single item.", nameof(viewModels)); // Find best match for the root node type var rootNodeType = rootNodes.First().Root.Type; if (rootNodes.Skip(1).Any(x => x.Type != rootNodeType)) rootNodeType = typeof(object); CombinedObservableNode rootCombinedNode = CombinedObservableNode.Create(combinedViewModel, "Root", null, rootNodeType, rootNodes, null); rootCombinedNode.Initialize(); combinedViewModel.RootNode = rootCombinedNode; return combinedViewModel; }
public async override void OnNavigatedTo(NavigatedToEventArgs e, Dictionary<string, object> viewModelState) { var categoryId = Convert.ToInt32(e.Parameter); string errorMessage = string.Empty; try { var category = await _productCatalogRepository.GetCategoryAsync(categoryId); Title = category.Title; var products = await _productCatalogRepository.GetProductsAsync(categoryId); Items = new ReadOnlyCollection<ProductViewModel>(products .Select(product => new ProductViewModel(product)) .ToList()); } catch (Exception ex) { errorMessage = string.Format(CultureInfo.CurrentCulture, _resourceLoader.GetString("GeneralServiceErrorMessage"), Environment.NewLine, ex.Message); } if (!string.IsNullOrWhiteSpace(errorMessage)) { await _alertMessageService.ShowAsync(errorMessage, _resourceLoader.GetString("ErrorServiceUnreachable")); } }
/// <summary> /// Performs the validation. /// </summary> /// <param name="validations">The validations.</param> /// <param name="validationProcess">The validation process for an item.</param> /// <returns>The result of the action.</returns> public static ActionResult PerformValidation(IReadOnlyCollection<ItemValidation> validations, Func<ItemValidation, ValidationItemResult, bool> validationProcess) { var itemResult = new ValidationItemResult(); var result = new ValidationResult(validations) { IsValid = true }; result.CheckedItems.Add(itemResult); foreach (var validation in validations) { var successful = validationProcess(validation, itemResult); if (!successful) { result.IsValid = false; } } if (!result.IsValid) { return ActionResult.Failure(new ElementExecuteException( "Value comparison(s) failed. See details for validation results.{0}{1}", Environment.NewLine, result.GetComparisonTableByRule())); } return ActionResult.Successful(); }
// TODO: Use Assembly Discovery.. void SetupContainer(Func<ISteamApi> steamApi) { _assemblies = new[] {Assembly.GetExecutingAssembly()}; _container = new Container(); _container.Options.DefaultScopedLifestyle = new ExecutionContextScopeLifestyle(); _container.RegisterSingleton<ICheatImpl, CheatImpl>(); _container.RegisterSingleton<IExceptionHandler, UnhandledExceptionHandler>(); _container.RegisterSingleton<IActionDispatcher>( () => new ActionDispatcher(_container.GetInstance<IMediator>(), null)); BootstrapperBridge.RegisterMessageBus(_container); _container.RegisterSingleton<IMessageBusProxy, MessageBusProxy>(); _container.RegisterSingleton<ISteamHelper>(SteamHelper.Create()); _container.RegisterPlugins<IHandleExceptionPlugin>(_assemblies, Lifestyle.Singleton); _container.RegisterSingleton<SteamSession.SteamSessionFactory>(); _container.RegisterSingleton<ISteamSessionFactory>(_container.GetInstance<SteamSession.SteamSessionFactory>); _container.RegisterSingleton<ISteamSessionLocator>(_container.GetInstance<SteamSession.SteamSessionFactory>); _container.RegisterSingleton<IServiceMessenger, ServiceMessenger>(); _container.RegisterSingleton<ISteamDownloader, SteamDownloader>(); _container.RegisterSingleton<Api.Services.ISteamApi, SteamApi>(); _container.RegisterSingleton(steamApi); _container.RegisterSingleton<IEventStorage, EventStorage>(); _container.RegisterSingleton<ISafeCallFactory, SafeCallFactory>(); _container.RegisterValidation(_assemblies); _container.RegisterMediator(_assemblies); _container.RegisterDecorator<IMediator, MediatorLoggingDecorator>(); _container.Register<IRequestScope, RequestScope>(Lifestyle.Scoped); _container.RegisterSingleton<IRequestScopeLocator, RequestScopeService>(); }
public Agent(Random randomNumberGenerator, int maxOrderQuantity, string name,IReadOnlyCollection<BitArray> allTimingChromosomes, double initialPropensity, double recency, double experimentation, double temperature, string group) { _random = randomNumberGenerator; _maxOrderQuantity = maxOrderQuantity; _name = name; _initialPropensity = initialPropensity; _recency = recency; _experimentation = experimentation; _temperature = temperature; _group = @group; CurrentProfit = 0; _learningLog = new List<ChromosomeLearning>(); foreach (var chromosome in allTimingChromosomes) { _learningLog.Add(new ChromosomeLearning() { Probability = 1d/allTimingChromosomes.Count, Propensity = initialPropensity, TimingChromosome = chromosome }); } TimingChromosome = _learningLog.OrderBy(l => l.Probability*_random.NextDouble()).First().TimingChromosome; }
public CollectionChangeOperation(IList list, NotifyCollectionChangedEventArgs args, IEnumerable<IDirtiable> dirtiables) : this(list, args.Action, dirtiables) { switch (args.Action) { case NotifyCollectionChangedAction.Add: items = args.NewItems.Cast<object>().ToArray(); index = args.NewStartingIndex; break; case NotifyCollectionChangedAction.Move: // Intentionally ignored, move in collection are not tracked return; case NotifyCollectionChangedAction.Remove: items = args.OldItems.Cast<object>().ToArray(); index = args.OldStartingIndex; break; case NotifyCollectionChangedAction.Replace: items = args.OldItems.Cast<object>().ToArray(); index = args.OldStartingIndex; break; case NotifyCollectionChangedAction.Reset: throw new NotSupportedException("Reset is not supported by the undo stack."); default: items = new object[] { }; index = -1; break; } }
internal SharedResource() { sharedResourceIdentifier = SharedResourceIdentifier.Create(); directlyConnectedSharedSharedResources = new List<SharedResource> { this }; mustRecalculateConnectedSharedResources = true; connectedSharedResourcesCache = GetConnectedSharedResources(); }
protected virtual void VisitNodeAttributes(IReadOnlyCollection<IXamlAttribute> attributes) { foreach (var attribute in attributes) { VisitNodeAttribute(attribute); } }
public CollectionChangeOperation(IList list, NotifyCollectionChangedAction actionToUndo, IReadOnlyCollection<object> items, int index, IEnumerable<IDirtiable> dirtiables) : this(list, actionToUndo, dirtiables) { if (items == null) throw new ArgumentNullException(nameof(items)); this.items = items; this.index = index; }
internal static string[] SerializeArguments(IReadOnlyCollection<object> arguments) { var serializedArguments = new List<string>(arguments.Count); foreach (var argument in arguments) { string value = null; if (argument != null) { if (argument is DateTime) { value = ((DateTime)argument).ToString("o", CultureInfo.InvariantCulture); } else { value = JobHelper.ToJson(argument); } } // Logic, related to optional parameters and their default values, // can be skipped, because it is impossible to omit them in // lambda-expressions (leads to a compile-time error). serializedArguments.Add(value); } return serializedArguments.ToArray(); }
protected virtual void VisitNodeChildren(IReadOnlyCollection<IXamlNode> children) { foreach (var child in children) { VisitNode(child); } }
public static Generator ToHTML5(this Element self, IReadOnlyCollection<ITag> inners, Generator generator) { var tags = new Generator(generator.Indention + 1); inners.ForEach(x => x.ToHTML5(tags)); var annotations = String.Concat(self.Annotations.Select(x => x.ToHTML5())); var isText = inners.Count == 1 && inners.Single() is Text; if (!inners.Any()) { if (self.Name.ToLower() == "script") generator.Write("<{0}{1}></{0}>", self.Name, annotations); else generator.Write("<{0}{1} />", self.Name, annotations); } else if (isText) { generator.Write("<{0}{1}>{2}</{0}>", self.Name, annotations, tags.Generate().Trim()); } else { generator.Write("<{0}{1}>{2}", self.Name, annotations, tags.Generate()); generator.Write("</{0}>", self.Name); } return generator; }
/// <summary> /// Reflects given assembly for PeachPie compiler specifics - compiled scripts, references to other assemblies, declared functions and classes. /// Scripts and declarations are loaded into application context (static). /// </summary> /// <param name="assembly">PeachPie compiler generated assembly.</param> /// <remarks>Not thread safe.</remarks> public static void AddScriptReference(Assembly assembly) { if (assembly == null) { throw new ArgumentNullException(nameof(assembly)); } if (assembly.GetType(ScriptInfo.ScriptTypeName) == null || !s_processedAssemblies.Add(assembly)) { // nothing to reflect return; } ProcessedAssemblies = s_processedAssemblies.ToArray(); // remember the assembly for class map: s_assClassMap.AddPhpAssemblyNoLock(assembly); // reflect the module for imported symbols: var module = assembly.ManifestModule; // PhpPackageReferenceAttribute foreach (var r in module.GetCustomAttributes <PhpPackageReferenceAttribute>()) { if (r.ScriptType != null) // always true { AddScriptReference(r.ScriptType.Assembly); } } // ImportPhpTypeAttribute foreach (var t in module.GetCustomAttributes <ImportPhpTypeAttribute>()) { TypesTable.DeclareAppType(PhpTypeInfoExtension.GetPhpTypeInfo(t.ImportedType)); } // ImportPhpFunctionsAttribute foreach (var t in module.GetCustomAttributes <ImportPhpFunctionsAttribute>()) { if (ExtensionsAppContext.ExtensionsTable.VisitFunctionsContainer(t.ContainerType, out var attr)) { foreach (var m in t.ContainerType.GetMethods()) { if (m.IsPublic && m.IsStatic && !m.IsPhpHidden()) { ExtensionsAppContext.ExtensionsTable.AddRoutine(attr, RoutinesTable.DeclareAppRoutine(m.Name, m)); } } } } // ImportPhpConstantsAttribute foreach (var t in module.GetCustomAttributes <ImportPhpConstantsAttribute>()) { if (!s_processedConstantsContainers.Add(t.ContainerType)) { // already visited before continue; } // var extensionName = t.ContainerType.GetCustomAttribute <PhpExtensionAttribute>(false)?.FirstExtensionOrDefault; // reflect constants defined in the container foreach (var m in t.ContainerType.GetMembers(BindingFlags.Static | BindingFlags.Public)) { if (m is FieldInfo fi && !fi.IsPhpHidden()) { Debug.Assert(fi.IsStatic && fi.IsPublic); if (fi.IsInitOnly || fi.IsLiteral) { // constant ConstsMap.DefineAppConstant(fi.Name, PhpValue.FromClr(fi.GetValue(null)), false, extensionName); } else { // static field ConstsMap.DefineAppConstant(fi.Name, new Func <PhpValue>(() => PhpValue.FromClr(fi.GetValue(null))), false, extensionName); } }
public BootstrapTask(IServiceCollection services, IConfiguration connectionStrings, IReadOnlyCollection <string> allowedUserPropertyKeys, PathResolver pathResolver) { Ensure.NotNull(services, "services"); Ensure.NotNull(connectionStrings, "connectionStrings"); Ensure.NotNull(allowedUserPropertyKeys, "allowedUserPropertyKeys"); Ensure.NotNull(pathResolver, "pathResolver"); this.services = services; this.connectionStrings = connectionStrings; this.allowedUserPropertyKeys = allowedUserPropertyKeys; this.pathResolver = pathResolver; }
private static bool IsMatrix(IReadOnlyCollection <string> dna) => dna.All(s => s.Length == dna.Count);
private static int NumberOfSequencesInRows(IReadOnlyCollection <string> matrix) { return(matrix.Select((t, y) => LineContainsConsecutiveChars(matrix, 0, y, (i, j) => i < matrix.Count, 1, incrementY: 0)).Sum()); }
private static int NumberOfSequencesInColumns(IReadOnlyCollection <string> matrix) { return(matrix.Select((t, x) => LineContainsConsecutiveChars(matrix, x, 0, (i, j) => j < matrix.Count, 0)).Sum()); }
private static int ObliqueLineFromRightToLeft(IReadOnlyCollection <string> matrix, int initialX, int initialY) { return(LineContainsConsecutiveChars(matrix, initialX, initialY, (i, j) => i >= 0 && j < matrix.Count, -1)); }
public void AddNotifications(IReadOnlyCollection<Notification> notifications) { _notifications.AddRange(notifications); }
public static void Main() { string url = "https://dotnetbrowser-support.teamdev.com/docs/guides/gs/printing.html"; string pdfFilePath = Path.GetFullPath("result.pdf"); EngineOptions engineOptions = new EngineOptions.Builder { RenderingMode = RenderingMode.OffScreen, GpuDisabled = true }.Build(); using (IEngine engine = EngineFactory.Create(engineOptions)) { using (IBrowser browser = engine.CreateBrowser()) { // #docfragment "PrintToPdf" // Resize browser to the required dimension. browser.Size = new Size(1024, 768); // Load the required web page and wait until it is loaded completely. Console.WriteLine($"Loading {url}"); browser.Navigation.LoadUrl(url).Wait(); // Configure print handlers. browser.RequestPrintHandler = new Handler <RequestPrintParameters, RequestPrintResponse >(p => RequestPrintResponse.Print()); TaskCompletionSource <string> printCompletedTcs = new TaskCompletionSource <string>(); browser.PrintHtmlContentHandler = new Handler <PrintHtmlContentParameters, PrintHtmlContentResponse >(p => { try { // Get the print job for the built-in PDF printer. PdfPrinter <PdfPrinter.IHtmlSettings> pdfPrinter = p.Printers.Pdf; IPrintJob <PdfPrinter.IHtmlSettings> printJob = pdfPrinter.PrintJob; // Apply the necessary print settings. printJob.Settings.Apply(s => { IReadOnlyCollection <PaperSize> paperSizes = pdfPrinter.Capabilities.PaperSizes; s.PaperSize = paperSizes.First(size => size.Name.Contains("A4")); s.PrintingHeaderFooterEnabled = true; // Specify the path to save the result. s.PdfFilePath = pdfFilePath; }); string browserUrl = p.Browser.Url; printJob.PrintCompleted += (sender, args) => { // Set the task result when the printing is completed. printCompletedTcs.TrySetResult(browserUrl); }; // Tell Chromium to use the built-in PDF printer // for printing. return(PrintHtmlContentResponse.Print(pdfPrinter)); } catch (Exception e) { printCompletedTcs.TrySetException(e); throw; } }); // Initiate printing and wait until it is completed. Console.WriteLine("URL loaded. Initiate printing"); browser.MainFrame.Print(); string printedUrl = printCompletedTcs.Task.Result; Console.WriteLine($"Printing completed for the URL: {printedUrl}"); // #enddocfragment "PrintToPdf" } } Console.WriteLine("Press any key to terminate..."); Console.ReadKey(); }
private async Task DoStateChangesTransactionallyAsync(string actorType, string actorId, IReadOnlyCollection<ActorStateChange> stateChanges, CancellationToken cancellationToken = default) { // Transactional state update request body: /* [ { "operation": "upsert", "request": { "key": "key1", "value": "myData" } }, { "operation": "delete", "request": { "key": "key2" } } ] */ using var stream = new MemoryStream(); using var writer = new Utf8JsonWriter(stream); writer.WriteStartArray(); foreach (var stateChange in stateChanges) { writer.WriteStartObject(); var operation = this.GetDaprStateOperation(stateChange.ChangeKind); writer.WriteString("operation", operation); // write the requestProperty writer.WritePropertyName("request"); writer.WriteStartObject(); // start object for request property switch (stateChange.ChangeKind) { case StateChangeKind.Remove: writer.WriteString("key", stateChange.StateName); break; case StateChangeKind.Add: case StateChangeKind.Update: writer.WriteString("key", stateChange.StateName); // perform default json serialization if custom serializer was not provided. if (this.actorStateSerializer != null) { var buffer = this.actorStateSerializer.Serialize(stateChange.Type, stateChange.Value); writer.WriteBase64String("value", buffer); } else { writer.WritePropertyName("value"); JsonSerializer.Serialize(writer, stateChange.Value, stateChange.Type, jsonSerializerOptions); } break; default: break; } writer.WriteEndObject(); // end object for request property writer.WriteEndObject(); } writer.WriteEndArray(); await writer.FlushAsync(); var content = Encoding.UTF8.GetString(stream.ToArray()); await this.daprInteractor.SaveStateTransactionallyAsync(actorType, actorId, content, cancellationToken); }
public Task <string> ProcessArrayOfByteArray(IReadOnlyCollection <byte[]> file, CrossContext ctx, CancellationToken token) { return(Task.FromResult(Tools.Json.Serializer.Serialize(file.Select(x => Encoding.UTF8.GetString(x))))); }
public BestServer(IReadOnlyCollection <Server> servers) { Ensure.NotNull(servers, nameof(servers)); _servers = servers; }
/// <summary> /// Adds a <see cref="JoinableTaskDependentData"/> instance as one that is relevant to the async operation. /// </summary> /// <param name="parentTaskOrCollection">The current joinableTask or collection contains to add a dependency.</param> /// <param name="joinChild">The <see cref="IJoinableTaskDependent"/> to join as a child.</param> internal static JoinableTaskCollection.JoinRelease AddDependency(IJoinableTaskDependent parentTaskOrCollection, IJoinableTaskDependent joinChild) { Requires.NotNull(parentTaskOrCollection, nameof(parentTaskOrCollection)); Requires.NotNull(joinChild, nameof(joinChild)); if (parentTaskOrCollection == joinChild) { // Joining oneself would be pointless. return(default(JoinableTaskCollection.JoinRelease)); } using (parentTaskOrCollection.JoinableTaskContext.NoMessagePumpSynchronizationContext.Apply()) { List <AsyncManualResetEvent>?eventsNeedNotify = null; lock (parentTaskOrCollection.JoinableTaskContext.SyncContextLock) { var joinableTask = joinChild as JoinableTask; if (joinableTask?.IsCompleted == true) { return(default(JoinableTaskCollection.JoinRelease)); } ref JoinableTaskDependentData data = ref parentTaskOrCollection.GetJoinableTaskDependentData(); if (data.childDependentNodes is null) { data.childDependentNodes = new WeakKeyDictionary <IJoinableTaskDependent, int>(capacity: 2); } if (data.childDependentNodes.TryGetValue(joinChild, out int refCount) && !parentTaskOrCollection.NeedRefCountChildDependencies) { return(default(JoinableTaskCollection.JoinRelease)); } data.childDependentNodes[joinChild] = ++refCount; if (refCount == 1) { // This constitutes a significant change, so we should apply synchronous task tracking to the new child. joinChild.OnAddedToDependency(parentTaskOrCollection); IReadOnlyCollection <PendingNotification>?tasksNeedNotify = AddDependingSynchronousTaskToChild(parentTaskOrCollection, joinChild); if (tasksNeedNotify.Count > 0) { eventsNeedNotify = new List <AsyncManualResetEvent>(tasksNeedNotify.Count); foreach (PendingNotification taskToNotify in tasksNeedNotify) { AsyncManualResetEvent?notifyEvent = taskToNotify.SynchronousTask.RegisterPendingEventsForSynchrousTask(taskToNotify.TaskHasPendingMessages, taskToNotify.NewPendingMessagesCount); if (notifyEvent is object) { eventsNeedNotify.Add(notifyEvent); } } } parentTaskOrCollection.OnDependencyAdded(joinChild); } } // We explicitly do this outside our lock. if (eventsNeedNotify is object) { foreach (AsyncManualResetEvent?queueEvent in eventsNeedNotify) { queueEvent.PulseAll(); } } return(new JoinableTaskCollection.JoinRelease(parentTaskOrCollection, joinChild)); }
public static Row[] ApplyColorToCharacters(IReadOnlyCollection <FormatSpan> highlights, IReadOnlyList <WrappedLine> lines, SelectionSpan?selection, AnsiColor?selectedTextBackground) { var selectionStart = new ConsoleCoordinate(int.MaxValue, int.MaxValue); //invalid var selectionEnd = new ConsoleCoordinate(int.MaxValue, int.MaxValue); //invalid if (selection.TryGet(out var selectionValue)) { selectionStart = selectionValue.Start; selectionEnd = selectionValue.End; } bool selectionHighlight = false; var highlightsLookup = highlights .ToLookup(h => h.Start) .ToDictionary(h => h.Key, conflictingHighlights => conflictingHighlights.OrderByDescending(h => h.Length).First()); var highlightedRows = new Row[lines.Count]; FormatSpan?currentHighlight = null; for (int lineIndex = 0; lineIndex < lines.Count; lineIndex++) { WrappedLine line = lines[lineIndex]; int lineFullWidthCharacterOffset = 0; var cells = Cell.FromText(line.Content); for (int cellIndex = 0; cellIndex < cells.Count; cellIndex++) { var cell = cells[cellIndex]; if (cell.IsContinuationOfPreviousCharacter) { lineFullWidthCharacterOffset++; } // syntax highlight wrapped lines if (currentHighlight.TryGet(out var previousLineHighlight) && cellIndex == 0) { currentHighlight = HighlightSpan(previousLineHighlight, cells, cellIndex, previousLineHighlight.Start - line.StartIndex); } // get current syntaxt highlight start int characterPosition = line.StartIndex + cellIndex - lineFullWidthCharacterOffset; currentHighlight ??= highlightsLookup.TryGetValue(characterPosition, out var lookupHighlight) ? lookupHighlight : null; // syntax highlight based on start if (currentHighlight.TryGet(out var highlight) && highlight.Contains(characterPosition)) { currentHighlight = HighlightSpan(highlight, cells, cellIndex, cellIndex); } // if there's text selected, invert colors to represent the highlight of the selected text. if (selectionStart.Equals(lineIndex, cellIndex - lineFullWidthCharacterOffset)) //start is inclusive { selectionHighlight = true; } if (selectionEnd.Equals(lineIndex, cellIndex - lineFullWidthCharacterOffset)) //end is exclusive { selectionHighlight = false; } if (selectionHighlight) { if (selectedTextBackground.TryGet(out var background)) { cell.Formatting = cell.Formatting with { Background = background }; } else { cell.Formatting = new ConsoleFormat { Inverted = true }; } } } highlightedRows[lineIndex] = new Row(cells); } return(highlightedRows); }
public async Task SaveStateAsync(string actorType, string actorId, IReadOnlyCollection<ActorStateChange> stateChanges, CancellationToken cancellationToken = default) { await this.DoStateChangesTransactionallyAsync(actorType, actorId, stateChanges, cancellationToken); }
public GameHistory(IReadOnlyCollection <BoardState> states, IReadOnlyCollection <Turn> turns) { States = states; Turns = turns; }
internal TemplateResolutionResult(string userInputLanguage, IReadOnlyCollection <ITemplateMatchInfo> coreMatchedTemplates) { _hasUserInputLanguage = !string.IsNullOrEmpty(userInputLanguage); _coreMatchedTemplates = coreMatchedTemplates; }
public abstract void AssignRelationship(IReadOnlyCollection <PatreonData> includes);
/// <summary> /// This is just an extra function used by <see cref="Prompt.RenderAnsiOutput"/> that highlights arbitrary text. It's /// not used for drawing input during normal functioning of the prompt. /// </summary> public static Row[] ApplyColorToCharacters(IReadOnlyCollection <FormatSpan> highlights, string text, int textWidth) { var wrapped = WordWrapping.WrapEditableCharacters(new StringBuilder(text), 0, textWidth); return(ApplyColorToCharacters(highlights, wrapped.WrappedLines, selection: null, selectedTextBackground: null)); }
/// <summary> /// Creates a computed index on this data member within the JSON data storage /// </summary> /// <param name="expressions"></param> /// <param name="configure"></param> /// <returns></returns> public DocumentMappingExpression <T> Index(IReadOnlyCollection <Expression <Func <T, object> > > expressions, Action <ComputedIndex> configure = null) { alter = m => m.Index(expressions, configure); return(this); }
/// <summary> /// ソースコレクションを指定してインスタンスを新規作成します /// ソースコレクションの要素数がキャパシティとなります /// </summary> /// <param name="source">ソースコレクション</param> /// <param name="mode">キャパを超えて要素を追加しようとしたときの挙動</param> public FixedCapacityQueue(IReadOnlyCollection <T> source, CapacityOverQueueBehaviour behaviour = CapacityOverQueueBehaviour.ThrowException) : this(new Queue <T>(source), source.Count, behaviour) { }
/// <summary> /// Create a sprite image from a list of images and the CSS to render each image. /// </summary> /// <param name="images">The list of images to include in the sprite.</param> /// <param name="spriteSettings">The settings to use when creating the sprite.</param> public void CreateSprite(IReadOnlyCollection<ISpriteImage> images, SpriteSettings spriteSettings) { CreateSprite(images, DefaultPlaceholderImages, spriteSettings); }
internal IReadOnlyCollection <IPipelineEvent> GetEventsOrdered() { IReadOnlyCollection <IPipelineEvent> readonlyList = Events.Values.OrderBy(p => p.Order).ToList(); return(readonlyList); }
public TraitGroup(Name name, IReadOnlyCollection <Trait> traits) { Traits = traits; Name = name; }
/// <summary> /// Create a sprite image from a list of images and the CSS to render each image. /// </summary> /// <param name="images">The list of images to include in the sprite.</param> /// <param name="placeholderImages">The list of custom placeholder images.</param> /// <param name="spriteSettings">The settings to use when creating the sprite.</param> public void CreateSprite(IReadOnlyCollection<ISpriteImage> images, IReadOnlyCollection<ISpriteImage> placeholderImages, SpriteSettings spriteSettings) { if (images == null) { throw new ArgumentNullException(nameof(images)); } if (images.GroupBy(x => x.Key).Any(x => x.Skip(1).Any())) { throw new ArgumentException("The list of keys must be unique.", nameof(images)); } if (placeholderImages == null || !placeholderImages.Any()) { placeholderImages = DefaultPlaceholderImages; } if (placeholderImages.GroupBy(x => x.Key).Any(x => x.Skip(1).Any())) { throw new ArgumentException("The list of keys must be unique.", nameof(placeholderImages)); } if (spriteSettings == null) { throw new ArgumentNullException(nameof(spriteSettings)); } var spritePlaceholderImages = new List<SpritePlaceholderImage>(); using (var spriteImages = new MagickImageCollection()) { var css = new StringBuilder(); var nextSpriteImageTop = 0; foreach (ISpriteImage image in images) { var hasImageBeenAddedToSprite = false; int selectedImageHeight; int selectedImageTop; int selectedImageWidth; var selectedHoverImageHeight = 0; var selectedHoverImageTop = 0; var selectedHoverImageWidth = 0; MagickImage imageForSprite = ImageToMagickImage(image); if (imageForSprite != null) { spriteImages.Add(imageForSprite); hasImageBeenAddedToSprite = true; selectedImageTop = nextSpriteImageTop; selectedImageHeight = imageForSprite.Height; selectedImageWidth = imageForSprite.Width; } else { string selectedPlaceholderImageKey = placeholderImages.Any(x => x.Key == image.PlaceholderImageKey) ? image.PlaceholderImageKey : placeholderImages.First().Key; ISpriteImage selectedPlaceholderImage = placeholderImages.FirstOrDefault(x => x.Key == selectedPlaceholderImageKey); imageForSprite = ImageToMagickImage(selectedPlaceholderImage); SpritePlaceholderImage spritePlaceholderImage = spritePlaceholderImages.FirstOrDefault(x => x.Key == selectedPlaceholderImageKey && x.Width == imageForSprite.Width && x.Height == imageForSprite.Height); if (spritePlaceholderImage == null) { spritePlaceholderImage = new SpritePlaceholderImage(selectedPlaceholderImageKey, nextSpriteImageTop, imageForSprite.Height, imageForSprite.Width); spritePlaceholderImages.Add(spritePlaceholderImage); spriteImages.Add(imageForSprite); hasImageBeenAddedToSprite = true; } selectedImageTop = spritePlaceholderImage.Top; selectedImageHeight = spritePlaceholderImage.Height; selectedImageWidth = spritePlaceholderImage.Width; } string selectedImageTopText = selectedImageTop != 0 ? $"-{selectedImageTop}px" : "0"; css.Append($"#{image.Key}{{height:{selectedImageHeight}px;width:{selectedImageWidth}px;background:url('{spriteSettings.SpriteUrl}') 0 {selectedImageTopText};}}"); if (hasImageBeenAddedToSprite) { nextSpriteImageTop += selectedImageHeight; } if (image.HoverImage != null) { MagickImage hoverImageForSprite = ImageToMagickImage(image.HoverImage, imageForSprite); if (hoverImageForSprite != null) { spriteImages.Add(hoverImageForSprite); hasImageBeenAddedToSprite = true; selectedHoverImageTop = nextSpriteImageTop; selectedHoverImageHeight = hoverImageForSprite.Height; selectedHoverImageWidth = hoverImageForSprite.Width; } string selectedHoverImageTopText = selectedHoverImageTop != 0 ? $"-{selectedHoverImageTop}px" : "0"; css.Append($"#{image.Key}:hover{{height:{selectedHoverImageHeight}px;width:{selectedHoverImageWidth}px;background:url('{spriteSettings.SpriteUrl}') 0 {selectedHoverImageTopText};}}"); if (hasImageBeenAddedToSprite) { nextSpriteImageTop += selectedHoverImageHeight; } } } _imageProcessor.CreateSprite(spriteImages, spriteSettings.SpriteFilename); _cssProcessor.CreateCss(css.ToString(), spriteSettings.CssFilename); } }
public static IEnumerable <ContainerRegisterFunction> ResolveIndexerFunctions(IReadOnlyCollection <string> searchNodes) { yield return(ContainerRegisterFunction.Service <IElasticClient, ElasticClient>(() => { var nodes = searchNodes.Select(n => new Uri(n)).ToArray(); var pool = new StaticConnectionPool(nodes); var settings = new ConnectionSettings(pool); var client = new ElasticClient(settings); return client; })); }
public GitDeleteBranchCmd(IReadOnlyCollection <IGitRef> branches, bool force) { _branches = branches ?? throw new ArgumentNullException(nameof(branches)); _force = force; }
private NumberArgument[] MapToOriginalValues <T>(IReadOnlyCollection <T> elements, IDictionary <T, Queue <NumberArgument> > map) { return(elements.Select(element => map[element].Dequeue()).ToArray()); }
public static void StackToMax(IReadOnlyCollection <Item> itemSet) => StackToMax(itemSet.ToArray());
private static void UpdateNamesByGemeentenamen(MunicipalityLatestItem syndicationItem, IReadOnlyCollection <GeografischeNaam> gemeentenamen) { if (gemeentenamen == null || !gemeentenamen.Any()) { return; } foreach (var naam in gemeentenamen) { switch (naam.Taal) { default: case Taal.NL: syndicationItem.NameDutch = naam.Spelling; syndicationItem.NameDutchSearch = naam.Spelling.RemoveDiacritics(); break; case Taal.FR: syndicationItem.NameFrench = naam.Spelling; syndicationItem.NameFrenchSearch = naam.Spelling.RemoveDiacritics(); break; case Taal.DE: syndicationItem.NameGerman = naam.Spelling; syndicationItem.NameGermanSearch = naam.Spelling.RemoveDiacritics(); break; case Taal.EN: syndicationItem.NameEnglish = naam.Spelling; syndicationItem.NameEnglishSearch = naam.Spelling.RemoveDiacritics(); break; } } }
public bool ConditionMet(IReadOnlyCollection <ILearner> learners, IReadOnlyCollection <ILearnerDestinationAndProgression> learnerDestinationAndProgressions) { return((learners?.Count() ?? 0) == 0 && (learnerDestinationAndProgressions?.Count() ?? 0) == 0); }