public IBindingNodeBuilder <TParent> Clone() { return(new BindingNodeBuilder <TParent, TNode>( _targetSelector, _subNodes?.ToDictionary(x => x.Key, x => x.Value.Clone()), _bindingActions.ToDictionary(x => x.Key, x => new List <int>(x.Value)), _collectionNode?.Clone())); }
/// <summary> /// Initializes a new instance of the <see cref="Craswell.WebRepositories.Tangerine.TangerineConfiguration"/> class. /// </summary> /// <param name="webSiteAddress">Web site address.</param> /// <param name="acn">The account client number.</param> /// <param name="pin">The client pin.</param> /// <param name="securityQuestions">The client security questions.</param> public TangerineConfiguration( Uri webSiteAddress, string acn, string pin, IDictionary<string, string> securityQuestions) { if (string.IsNullOrEmpty(acn)) { throw new ArgumentNullException("acn"); } if (string.IsNullOrEmpty(pin)) { throw new ArgumentNullException("pin"); } if (webSiteAddress == null) { throw new ArgumentNullException("webSiteAddress"); } if (securityQuestions == null) { throw new ArgumentNullException("securityQuestions"); } this.acn = acn; this.pin = pin; this.webSiteAddress = webSiteAddress; this.securityQuestions = securityQuestions .ToDictionary(d => d.Key, d => d.Value); }
public BinaryDecisionTreeParentNode( bool isLeaf, string decisionFeatureName, IDictionary<IDecisionTreeLink, IDecisionTreeNode> linksToChildren, object decisionValue, bool isSplitValueNumeric) : base(isLeaf, decisionFeatureName, linksToChildren) { IsValueNumeric = isSplitValueNumeric; DecisionValue = decisionValue; TestResultsWithChildren = linksToChildren.ToDictionary( kvp => kvp.Key as IBinaryDecisionTreeLink, kvp => kvp.Value); foreach (var link in linksToChildren) { var binaryTreeLink = link.Key as IBinaryDecisionTreeLink; if (binaryTreeLink != null) { if (!binaryTreeLink.LogicalTestResult) { LeftChild = link.Value; LeftChildLink = binaryTreeLink; } else { RightChild = link.Value; RightChildLink = binaryTreeLink; } } } }
/// <inheritdoc /> protected override async Task <T> CreateExportableCIAsync <T>() { var exportable = await base.CreateExportableCIAsync <T>(); if (exportable is ExportableCompetitionCI competition) { competition.BookingStatus = _bookingStatus; competition.Venue = _venue != null ? await _venue.ExportAsync() : null; competition.Conditions = _conditions != null ? await _conditions.ExportAsync() : null; competition.Competitors = Competitors?.Select(c => c.ToString()).ToList(); competition.ReferenceId = _referenceId?.ReferenceIds?.ToDictionary(r => r.Key, r => r.Value); competition.CompetitorsQualifiers = _competitorsQualifiers?.ToDictionary(q => q.Key.ToString(), q => q.Value); competition.CompetitorsReferences = _competitorsReferences?.ToDictionary(r => r.Key.ToString(), r => (IDictionary <string, string>)r.Value.ReferenceIds.ToDictionary(v => v.Key, v => v.Value)); competition.CompetitorsVirtual = _competitorsVirtual.IsNullOrEmpty() ? null : _competitorsVirtual.Select(s => s.ToString()).ToList(); competition.LiveOdds = _liveOdds; competition.SportEventType = _sportEventType; competition.StageType = _stageType; } return(exportable); }
public IDictionary<string,Parameter> GetParameters(IDictionary<string, object> dictionary) { if (dynamicRaml == null) return new Dictionary<string, Parameter>(); return dictionary.ToDictionary(kv => kv.Key, kv => (new ParameterBuilder()).Build((IDictionary<string, object>)kv.Value)); }
protected override async Task <T> CreateExportableCIAsync <T>() { var exportable = await base.CreateExportableCIAsync <T>(); var info = exportable as ExportableTournamentInfoCI; info.CategoryId = _categoryId?.ToString(); info.TournamentCoverage = _tournamentCoverage != null ? await _tournamentCoverage.ExportAsync().ConfigureAwait(false) : null; info.Competitors = _competitors?.Select(s => s.ToString()); info.CurrentSeasonInfo = _currentSeasonInfo != null ? await _currentSeasonInfo.ExportAsync().ConfigureAwait(false) : null; var groupsTasks = _groups?.Select(async g => await g.ExportAsync().ConfigureAwait(false)); info.Groups = groupsTasks != null ? await Task.WhenAll(groupsTasks) : null; info.ScheduleUrns = _scheduleUrns?.Select(s => s.ToString()).ToList(); info.Round = _round != null ? await _round.ExportAsync().ConfigureAwait(false) : null; info.Year = _year; info.TournamentInfoBasic = _tournamentInfoBasic != null ? await _tournamentInfoBasic.ExportAsync().ConfigureAwait(false) : null; info.ReferenceId = _referenceId?.ReferenceIds?.ToDictionary(r => r.Key, r => r.Value); info.SeasonCoverage = _seasonCoverage != null ? await _seasonCoverage.ExportAsync().ConfigureAwait(false) : null; info.Seasons = _seasons?.Select(s => s.ToString()).ToList(); info.LoadedSeasons = new List <CultureInfo>(_loadedSeasons ?? new List <CultureInfo>()); info.LoadedSchedules = new List <CultureInfo>(_loadedSchedules ?? new List <CultureInfo>()); info.CompetitorsReferences = _competitorsReferences?.ToDictionary(r => r.Key.ToString(), r => (IDictionary <string, string>)r.Value.ReferenceIds.ToDictionary(v => v.Key, v => v.Value)); info.ExhibitionGames = _exhibitionGames; return(exportable); }
static IDictionary<string, IOptionApplier> BuildOptionDictionary( IDictionary<string, IDictionary<string, JToken>> jsonOptions, IReadOnlyList<IOption> supportedOptions) { return jsonOptions.ToDictionary( o => o.Key, o => (IOptionApplier)new JsonOptionApplier(o.Key, o.Value, supportedOptions)); }
public IObjectFacade[] GetChoices(IObjectFacade target, IDictionary <string, object> parameterNameValues) { var oneToOneFeature = WrappedSpec as IOneToOneFeatureSpec; var pnv = parameterNameValues?.ToDictionary(kvp => kvp.Key, kvp => framework.GetNakedObject(kvp.Value)); return(oneToOneFeature?.GetChoices(((ObjectFacade)target).WrappedNakedObject, pnv).Select(no => ObjectFacade.Wrap(no, FrameworkFacade, framework)).Cast <IObjectFacade>().ToArray()); }
IMockNetworkWithReturn IMockNetworkWithExpectation.Returning(HttpStatusCode statusCode, string responseContent, IDictionary<string, string> responseHeaders) { _statusCode = statusCode; _responseContent = responseContent; _responseHeaders = responseHeaders.ToDictionary(kvp => kvp.Key.ToLowerInvariant(), kvp => kvp.Value); return this; }
/// <summary> /// Initializes a new instance of the <see cref="RequestMessage"/> class. /// </summary> /// <param name="url">The original url.</param> /// <param name="method">The HTTP method.</param> /// <param name="clientIP">The client IP Address.</param> /// <param name="body">The body.</param> /// <param name="headers">The headers.</param> /// <param name="cookies">The cookies.</param> public RequestMessage([NotNull] Uri url, [NotNull] string method, [NotNull] string clientIP, [CanBeNull] BodyData body = null, [CanBeNull] IDictionary <string, string[]> headers = null, [CanBeNull] IDictionary <string, string> cookies = null) { Check.NotNull(url, nameof(url)); Check.NotNull(method, nameof(method)); Check.NotNull(clientIP, nameof(clientIP)); Url = url.ToString(); Protocol = url.Scheme; Host = url.Host; Port = url.Port; Origin = $"{url.Scheme}://{url.Host}:{url.Port}"; Path = WebUtility.UrlDecode(url.AbsolutePath); PathSegments = Path.Split('/').Skip(1).ToArray(); Method = method.ToLower(); ClientIP = clientIP; Body = body?.BodyAsString; BodyEncoding = body?.Encoding; BodyAsJson = body?.BodyAsJson; BodyAsBytes = body?.BodyAsBytes; Headers = headers?.ToDictionary(header => header.Key, header => new WireMockList <string>(header.Value)); Cookies = cookies; RawQuery = WebUtility.UrlDecode(url.Query); Query = ParseQuery(RawQuery); }
/// <summary> /// Initializes a new instance of the <see cref="RequestMessage"/> class. /// </summary> /// <param name="urlDetails">The original url details.</param> /// <param name="method">The HTTP method.</param> /// <param name="clientIP">The client IP Address.</param> /// <param name="bodyData">The BodyData.</param> /// <param name="headers">The headers.</param> /// <param name="cookies">The cookies.</param> public RequestMessage([NotNull] UrlDetails urlDetails, [NotNull] string method, [NotNull] string clientIP, [CanBeNull] BodyData bodyData = null, [CanBeNull] IDictionary <string, string[]> headers = null, [CanBeNull] IDictionary <string, string> cookies = null) { Check.NotNull(urlDetails, nameof(urlDetails)); Check.NotNull(method, nameof(method)); Check.NotNull(clientIP, nameof(clientIP)); AbsoluteUrl = urlDetails.AbsoluteUrl.ToString(); Url = urlDetails.Url.ToString(); Protocol = urlDetails.Url.Scheme; Host = urlDetails.Url.Host; Port = urlDetails.Url.Port; Origin = $"{Protocol}://{Host}:{Port}"; AbsolutePath = WebUtility.UrlDecode(urlDetails.AbsoluteUrl.AbsolutePath); Path = WebUtility.UrlDecode(urlDetails.Url.AbsolutePath); PathSegments = Path.Split('/').Skip(1).ToArray(); AbsolutePathSegments = AbsolutePath.Split('/').Skip(1).ToArray(); Method = method; ClientIP = clientIP; BodyData = bodyData; // Convenience getters for e.g. Handlebars Body = BodyData?.BodyAsString; BodyAsJson = BodyData?.BodyAsJson; BodyAsBytes = BodyData?.BodyAsBytes; DetectedBodyType = BodyData?.DetectedBodyType.ToString(); DetectedBodyTypeFromContentType = BodyData?.DetectedBodyTypeFromContentType.ToString(); Headers = headers?.ToDictionary(header => header.Key, header => new WireMockList <string>(header.Value)); Cookies = cookies; RawQuery = WebUtility.UrlDecode(urlDetails.Url.Query); Query = QueryStringParser.Parse(RawQuery); }
public static async Task<IDictionary<string, int>> EnsureClientDimensionsExist(SqlConnection connection, IDictionary<string, Tuple<int, ClientDimension>> recognizedUserAgents) { var results = new Dictionary<string, int>(); var command = connection.CreateCommand(); command.CommandText = "[dbo].[EnsureClientDimensionsExist]"; command.CommandType = CommandType.StoredProcedure; command.CommandTimeout = _defaultCommandTimeout; var parameterValue = ClientDimensionTableType.CreateDataTable(recognizedUserAgents.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Item2)); var parameter = command.Parameters.AddWithValue("clients", parameterValue); parameter.SqlDbType = SqlDbType.Structured; parameter.TypeName = "[dbo].[ClientDimensionTableType]"; using (var dataReader = await command.ExecuteReaderAsync()) { while (await dataReader.ReadAsync()) { var clientDimensionId = dataReader.GetInt32(0); var userAgent = dataReader.GetString(1); results.Add(userAgent, clientDimensionId); } } return results; }
private IDictionary <string, object> SwapRowAliases( [CanBeNull] IDictionary <string, object> fieldValues) { return(fieldValues?.ToDictionary(pair => SwapRowAliases(pair.Key), pair => pair.Value, StringComparer.OrdinalIgnoreCase)); }
public OverrideValueProvider(IValueProvider originalValueProvider, IDictionary<string, string> values) { OriginalValueProvider = originalValueProvider; HardcodedValues = values.ToDictionary( x => x.Key, x => new ValueProviderResult(x.Value, x.Value, System.Globalization.CultureInfo.InvariantCulture)); }
public Request(string url, string verb, string body, IDictionary<string, string> headers) { _url = url; _headers = headers.ToDictionary(kv => kv.Key.ToLower(), kv => kv.Value.ToLower()); _verb = verb.ToLower(); _body = body==null ? "" : body.Trim(); }
private short[,] BuildTextureMap(IDictionary<TextureGroup, byte> textureGroupIds, IDictionary<Tuple<byte, byte>, TextureGroupTransition> textureTansitionLookup, byte[,] textureGroupMap) { var idsToTextureGroups = textureGroupIds.ToDictionary(item => item.Value, item => item.Key); return null; }
private IDictionary <TResultKey, TResultValue> ConvertIDictionaryToDbType <TSourceKey, TSourceValue, TResultKey, TResultValue>(IDictionary <TSourceKey, TSourceValue> map) { var keyConverter = TryFindToDbConverter <TSourceKey, TResultKey>(); var valueConverter = TryFindToDbConverter <TSourceValue, TResultValue>(); return(map?.ToDictionary(kv => keyConverter(kv.Key), kv => valueConverter(kv.Value))); }
public static IDictionary <string, MultiformatMessageString> ConvertToMultiformatMessageStringsDictionary(this IDictionary <string, string> v1MessageStringsDictionary) { return(v1MessageStringsDictionary?.ToDictionary( keyValuePair => keyValuePair.Key, keyValuePair => new MultiformatMessageString { Text = keyValuePair.Value })); }
public ImperativeCodeModel( IEnumerable <AbstractMember> topLevelMembers, IDictionary <object, AbstractMember> membersByBindings = null) { _topLevelMembers = new HashSet <AbstractMember>(topLevelMembers); _membersByBndings = ( membersByBindings?.ToDictionary(kvp => kvp.Key, kvp => kvp.Value) ?? new Dictionary <object, AbstractMember>()); }
public static IDictionary <TTargetKey, TTargetValue> Map <TSourceKey, TTargetKey, TSourceValue, TTargetValue>( IDictionary <TSourceKey, TSourceValue> dictionary, Func <TSourceKey, TTargetKey> mapKeyFunction, Func <TSourceValue, TTargetValue> mapValueFunction) where TSourceValue : class where TTargetValue : class { return(dictionary?.ToDictionary(entry => mapKeyFunction(entry.Key), entry => mapValueFunction(entry.Value))); }
public ObjectSubclassingController(IDictionary<Type, Action> actions) { mutex = new ReaderWriterLockSlim(); registeredSubclasses = new Dictionary<String, ObjectSubclassInfo>(); registerActions = actions.ToDictionary(p => GetClassName(p.Key), p => p.Value); // Register the ParseObject subclass, so we get access to the ACL, // objectId, and other ParseFieldName properties. RegisterSubclass(typeof(ParseObject)); }
/// <summary> /// Initializes a new instance of the <see cref="BlobContentHashListResponse"/> class. /// </summary> public BlobContentHashListResponse( BlobContentHashListWithCacheMetadata contentHashListWithCacheMetadata, IDictionary <BlobIdentifier, ExpirableUri> blobIdsToUris) { ContentHashListWithCacheMetadata = contentHashListWithCacheMetadata; BlobDownloadUris = blobIdsToUris?.ToDictionary( blobId => blobId.Key.ValueString, blobKvp => blobKvp.Value.NotNullUri); }
/// <summary> /// Updates multiple sets of key value pairs in a given category and collection. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='category'> /// The category /// </param> /// <param name='collection'> /// The collection /// </param> /// <param name='model'> /// A <see cref="Dictionary{TKey, TValue}"/> containing the keys to update the metadata and keywords for /// </param> /// <param name="strategy"> /// The bulk update strategy /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BulkUpdateAsync(this IMetadata operations, string category, string collection, IDictionary <string, MetadataModel> model = default, BulkUpdateStrategy strategy = BulkUpdateStrategy.UpdateMatchedOnly, CancellationToken cancellationToken = default) { await operations.RefitClient.BulkUpdate(category, collection, model?.ToDictionary(x => x.Key, x => x.Value.ToChestContract()), strategy); }
public static IReadOnlyDictionary <ThumbnailSize, Thumbnail> Clone(this IDictionary <ThumbnailSize, Thumbnail> thumbnails) { var t = thumbnails?.ToDictionary(kv => kv.Key, kv => kv.Value); if (t == null) { return(null); } return(new ReadOnlyDictionary <ThumbnailSize, Thumbnail>(t)); }
static RedisExtensions() { getCommand = new Dictionary<string,Type>{ {"AddCustomerCommand", typeof(AddCustomerCommand)}, {"AddOrderCommand" , typeof(AddOrderCommand)}, {"AddProductCommand" , typeof(AddProductCommand)}, {"AddProductToOrder" , typeof(AddProductToOrder)}, }; getName = getCommand.ToDictionary(kv => kv.Value, kv => kv.Key); }
private static IDictionary <string, object> ToDynamicODataEntry(IDictionary <string, object> entry, ITypeCache typeCache) { return(entry?.ToDictionary( x => x.Key, y => y.Value is IDictionary <string, object> ?new DynamicODataEntry(y.Value as IDictionary <string, object>, typeCache) : y.Value is IEnumerable <object> ?ToDynamicODataEntry(y.Value as IEnumerable <object>, typeCache) : y.Value)); }
/// <summary> /// Save temp data dictionary to the specified <see cref="HttpContext" /> object. /// </summary> /// <param name="context">The <see cref="HttpContext" /> object.</param> /// <param name="values">The temp data dictionary to be saving.</param> public override void SaveTempData(HttpContext context, IDictionary<string, object> values) { if (values == null) { base.SaveTempData(context, null); return; } var newDic = values.ToDictionary(item => item.Key, item => ObjectSerializer.Serialize(item.Value)); base.SaveTempData(context, newDic); }
public IEnumerable<string> InvokeMethod(Models.Method method, IDictionary<string, object> form) { using (var build = Build()) { return build .Controller(method.ClassName) .Action(method.Name) .Parameters(form.ToDictionary(p => p.Key, p => p.Value != null ? p.Value.ToString() : (string)null)) .Invoke(); } }
private static IDictionary<string, object> ToDynamicODataEntry(IDictionary<string, object> entry) { return entry == null ? null : entry.ToDictionary( x => x.Key, y => y.Value is IDictionary<string, object> ? new DynamicODataEntry(y.Value as IDictionary<string, object>) : y.Value is IEnumerable<object> ? ToDynamicODataEntry(y.Value as IEnumerable<object>) : y.Value); }
static ODataQueryPartTypeExtensions() { var fields = Enum.GetNames(typeof (ODataQueryPartType)) .Select(typeof (ODataQueryPartType).GetField) .ToList(); TypeToParameterNames = fields .Where(x => x.GetCustomAttributes<UrlParameterAttribute>().Any()) .ToDictionary(key => (ODataQueryPartType)key.GetValue(null), value => value.GetCustomAttributes<UrlParameterAttribute>().Single().Name); ParameterNameToType = TypeToParameterNames.ToDictionary(key => key.Value, value => value.Key); }
public static ChangeLocation Create(Uri loc, DateTime lastmod, ChangeTypes change, ChangeFrequencies?changeFrequency = null, IDictionary <string, string> properties = null) { return(new ChangeLocation { Url = loc, LastModified = lastmod, Metadata = new ResourceSyncMetadata { Change = change.ToString(), Properties = properties?.ToDictionary(kvp => kvp.Key, kvp => kvp.Value) }, ChangeFrequency = changeFrequency, Priority = 1 }); }
private string Publish(GitHubClient client, IDictionary<string, string> content) { var response = client.Execute<GitHub.Gist>(new RestRequest("/gists", Method.POST) { RequestFormat = DataFormat.Json } .AddBody(new GitHub.Gist { IsPublic = true, Files = content.ToDictionary(_ => _.Key, _ => new GistFile { Content = _.Value }) })); if ((response.ResponseStatus == ResponseStatus.Error) //|| !response.StatusCode.InRange(HttpStatusCode.OK, HttpStatusCode.Ambiguous - 1) ) { //Logger.LogMessage("Gist error: {0}", response.ErrorMessage ?? string.Format("{0:D} {1}", response.StatusCode, response.StatusDescription)); return null; } return response.Data != null ? response.Data.HtmlUrl : null; }
/// <summary> /// GridCell constructor. /// </summary> /// <param name="latitude">Latitude of this grid cell.</param> /// <param name="longitude">Longitude of this grid cell.</param> /// <param name="cohorts">List of cohorts in this grid cell.</param> /// <param name="stocks">List of stocks in this grid cell.</param> /// <param name="environment">Environmental data for this grid cell.</param> public GridCell( double latitude, double longitude, IEnumerable<IEnumerable<Cohort>> cohorts, IEnumerable<IEnumerable<Stock>> stocks, IDictionary<string, double[]> environment) { this.Latitude = latitude; this.Longitude = longitude; this.Cohorts = cohorts.Select(cs => cs.ToArray()).ToArray(); this.Stocks = stocks.Select(ss => ss.ToArray()).ToArray(); this.Environment = new SortedList<string, double[]>(environment.ToDictionary(kv => kv.Key, kv => kv.Value.ToArray())); }
public static IDictionary <string, IEnumerable <string> > ReplacePlaceholders( this IDictionary <string, IEnumerable <string> > inp, IDictionary <string, KeyValuePair <string, string> > placeholders) { foreach (var placeholder in placeholders.Values) { inp = inp?.ToDictionary( kvp => kvp.Key, kvp => kvp.Value.Select(v => v.Replace(placeholder.Key, Uri.EscapeDataString(placeholder.Value)))); } return(inp); }
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) { return dictionary.ToDictionary(item => item.Key, item => { var d = (item.Value as Dictionary<string, object>); var range = new ApiRange { Min = Convert.ToDouble(d["min"]), Max = Convert.ToDouble(d["max"]) }; return range; }); }
public static IEnumerable<VirtualPathData> LookupVirtualPaths( HttpContextBase httpContext, IEnumerable<RouteDescriptor> routeDescriptors, string areaName, IDictionary<string, string> routeValues) { var routeValueDictionary = new RouteValueDictionary(routeValues.ToDictionary(kv => RemoveDash(kv.Key), kv => (object)kv.Value)); var virtualPathDatas = routeDescriptors.Where(r2 => r2.Route.GetAreaName() == areaName) .Invoke(r2 => r2.Route.GetVirtualPath(httpContext.Request.RequestContext, routeValueDictionary), NullLogger.Instance) .Where(vp => vp != null) .ToArray(); return virtualPathDatas; }
private MetricEvent( DateTime collectionStarted, DateTime collectionCompleted, TimeSpan totalLatency, TimeSpan listJobsLatency, IDictionary<string, JobMetrics> jobStats) { this.collectionStarted = collectionStarted; this.collectionCompleted = collectionCompleted; this.totalLatency = totalLatency; this.listJobsLatency = listJobsLatency; this.jobMetrics = new Dictionary<string, JobMetrics>(jobStats); this.latency = new Latency(totalLatency, listJobsLatency, jobStats.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ListTasksLatency)); }
/// <summary> /// Returns an evaluation context that contains bindings for 'standard library' functions, for instance ID and randomness functions, /// and bindings for the given properties (which have been parsed into properly typed values). /// </summary> public static EvaluationContext ContextFromProperties(IDictionary <string, string> properties, double id, Random random, IDictionary <string, object> globals) { var evaluationContext = new EvaluationContext( properties?.ToDictionary( kv => kv.Key, kv => PropertyExtensions.ParseProperty(kv.Value)), _globalsContext); var instanceFunctions = new InstanceFunctions(id, random, globals); NativeUtils.RegisterInstanceMethods(evaluationContext, instanceFunctions); return(evaluationContext); }
public MockIdentityManagementService(IDictionary <string, IEnumerable <ITeamFoundationIdentity> > accountMappings) { _accountNameMappings = accountMappings?.ToDictionary(k => k.Key, e => e.Value.ToArray()) ?? new Dictionary <string, ITeamFoundationIdentity[]>(StringComparer.OrdinalIgnoreCase); _descriptorMappings = new Dictionary <IIdentityDescriptor, ITeamFoundationIdentity>(new IIdentityDescriptorComparer()); foreach (var accounts in _accountNameMappings.Values) { foreach (var account in accounts) { _descriptorMappings.Add(account.Descriptor, account); } } }
public Runner( SimpleSubquery <TResult> owner, IConnection connection, string id, string after, IDictionary <string, object> variables, IList result) { this.owner = owner; this.connection = connection; this.variables = variables?.ToDictionary(x => x.Key, x => x.Value) ?? new Dictionary <string, object>(); this.variables["__id"] = id; this.variables["__after"] = after; finalResult = result; }
static TraditionalTextHarmonicKeyConverter() { TradtionalKeys = new Dictionary<HarmonicKey, string> { {HarmonicKey.Key1A, "A-Flat Minor"}, {HarmonicKey.Key1B, "B Major"}, {HarmonicKey.Key2A, "E-Flat Minor"}, {HarmonicKey.Key2B, "F-Sharp Major"}, {HarmonicKey.Key3A, "B-Flat Minor"}, {HarmonicKey.Key3B, "D-Flat Major"}, {HarmonicKey.Key4A, "F Minor"}, {HarmonicKey.Key4B, "A-Flat Major"}, {HarmonicKey.Key5A, "C Minor"}, {HarmonicKey.Key5B, "E-Flat Major"}, {HarmonicKey.Key6A, "G Minor"}, {HarmonicKey.Key6B, "B-Flat Major"}, {HarmonicKey.Key7A, "D Minor"}, {HarmonicKey.Key7B, "F Major"}, {HarmonicKey.Key8A, "A Minor"}, {HarmonicKey.Key8B, "C Major"}, {HarmonicKey.Key9A, "E Minor"}, {HarmonicKey.Key9B, "G Major"}, {HarmonicKey.Key10A, "B Minor"}, {HarmonicKey.Key10B, "D Major"}, {HarmonicKey.Key11A, "F-Sharp Minor"}, {HarmonicKey.Key11B, "A Major"}, {HarmonicKey.Key12A, "D-Flat Minor"}, {HarmonicKey.Key12B, "E Major"} }; KeyCodes = TradtionalKeys .ToDictionary(k => k.Value, v => v.Key, StringComparer.CurrentCultureIgnoreCase); // Enharmonic equivalents (only one way so we can read them) KeyCodes.Add("G-Sharp Minor", HarmonicKey.Key1A); KeyCodes.Add("D-Sharp Minor", HarmonicKey.Key2A); KeyCodes.Add("G-Flat Major", HarmonicKey.Key2B); KeyCodes.Add("A-Sharp Minor", HarmonicKey.Key3A); KeyCodes.Add("C-Sharp Major", HarmonicKey.Key3B); KeyCodes.Add("G-Sharp Major", HarmonicKey.Key4B); KeyCodes.Add("D-Sharp Major", HarmonicKey.Key5B); KeyCodes.Add("A-Sharp Major", HarmonicKey.Key6B); KeyCodes.Add("G-Flat Minor", HarmonicKey.Key11A); KeyCodes.Add("C-Sharp Minor", HarmonicKey.Key12A); }
/// <summary> /// Renders the macro with the specified alias, passing in the specified parameters. /// </summary> private async Task <IHtmlEncodedString> RenderMacroAsync(IPublishedContent content, string alias, IDictionary <string, object>?parameters) { if (content == null) { throw new ArgumentNullException(nameof(content)); } // TODO: We are doing at ToLower here because for some insane reason the UpdateMacroModel method looks for a lower case match. the whole macro concept needs to be rewritten. // NOTE: the value could have HTML encoded values, so we need to deal with that var macroProps = parameters?.ToDictionary( x => x.Key.ToLowerInvariant(), i => i.Value is string?WebUtility.HtmlDecode(i.Value.ToString()) : i.Value); var html = (await _macroRenderer.RenderAsync(alias, content, macroProps)).Text; return(new HtmlEncodedString(html !)); }
public new object CreateElementInstance(Type baseType, IDictionary<string, object> fieldValues, IEnumerable<IExecutionContext> executionContexts) { if (!typeof(IItemWrapper).IsAssignableFrom(baseType)) return base.CreateElementInstance(baseType, fieldValues, executionContexts); Guid groupID; Guid templateID; if (fieldValues.ContainsKey("_group") && fieldValues.ContainsKey("_template") && (Guid.TryParse(fieldValues["_group"].ToString(), out groupID) && Guid.TryParse(fieldValues["_template"].ToString(), out templateID))) { return Global.SpawnProvider.FromItem(groupID, templateID, baseType, fieldValues.ToDictionary(k => k.Key, v => v.Value)); } return base.CreateElementInstance(baseType, fieldValues, executionContexts); }
static FilterExpressionOperatorEnumExtensions() { var fields = Enum.GetNames(typeof (FilterExpressionOperator)) .Select(typeof (FilterExpressionOperator).GetField) .ToList(); FilterExpressionOperatorToDotNetExpressionType = fields .Where(x => x.GetCustomAttributes<DotNetOperatorAttribute>().Any()) .ToDictionary(key => (FilterExpressionOperator)key.GetValue(null), value => value.GetCustomAttributes<DotNetOperatorAttribute>().Single().ExpressionType); FilterExpressionOperatorToODataQueryOperatorString = fields .Where(x => x.GetCustomAttributes<FilterOperatorAttribute>().Any()) .ToDictionary(key => (FilterExpressionOperator)key.GetValue(null), value => value.GetCustomAttributes<FilterOperatorAttribute>().Single().Value); DotNetExpressionTypeToFilterExpressionOperator = FilterExpressionOperatorToDotNetExpressionType.ToDictionary(key => key.Value, value => value.Key); ODataQueryOperatorStringToFilterExpressionOperator = FilterExpressionOperatorToODataQueryOperatorString.ToDictionary(key => key.Value, value => value.Key); }
protected override async Task <T> CreateExportableCIAsync <T>() { var exportable = await base.CreateExportableCIAsync <T>(); var competition = exportable as ExportableCompetitionCI; competition.BookingStatus = _bookingStatus; competition.Venue = _venue != null ? await _venue.ExportAsync() : null; competition.Conditions = _conditions != null ? await _conditions.ExportAsync() : null; competition.Competitors = Competitors?.Select(c => c.ToString()).ToList(); competition.ReferenceId = _referenceId?.ReferenceIds?.ToDictionary(r => r.Key, r => r.Value); competition.CompetitorsQualifiers = _competitorsQualifiers?.ToDictionary(q => q.Key.ToString(), q => q.Value); competition.CompetitorsReferences = _competitorsReferences?.ToDictionary(r => r.Key.ToString(), r => (IDictionary <string, string>)r.Value.ReferenceIds.ToDictionary(v => v.Key, v => v.Value)); return(exportable); }
public void SaveTempData(ControllerContext controllerContext, IDictionary<string, object> values) { using (var db = new MongoDbContext(_connectionString)) { if (values != null) { var sessionId = controllerContext.HttpContext.Request.UserHostAddress; if (!string.IsNullOrEmpty(sessionId)) { db.TempData.Insert(new TempData() { Data = values.ToDictionary(k => k.Key, v => v.Value), SessionId = sessionId }); } } } }
/// <summary> /// Returns an evaluation context that contains bindings for 'standard library' functions, for instance ID and randomness functions, /// and bindings for the given properties (which have been parsed into properly typed values). /// </summary> public static EvaluationContext ContextFromProperties( IDictionary <string, string> properties, double id, double sequenceNumber, Random random, IDictionary <string, object> globals, ILogger logger, EvaluationContext parentContext = null) { var typedProperties = properties?.ToDictionary( kv => kv.Key, kv => PropertyExtensions.ParseProperty(kv.Value)); var evaluationContext = new EvaluationContext(typedProperties, parentContext ?? _globalsContext); var instanceFunctions = new InstanceFunctions(id, sequenceNumber, random, typedProperties, globals, logger); NativeUtils.RegisterInstanceMethods(evaluationContext, instanceFunctions); return(evaluationContext); }
public void Register(StandardComponents standardComponents) { _masterMainBus = new InMemoryBus("manager input bus"); _masterInputQueue = new QueuedHandler(_masterMainBus, "Projections Master"); _masterOutputBus = new InMemoryBus("ProjectionManagerAndCoreCoordinatorOutput"); var projectionsStandardComponents = new ProjectionsStandardComponents( _projectionWorkerThreadCount, _runProjections, _masterOutputBus, _masterInputQueue, _masterMainBus); CreateAwakerService(standardComponents); _coreQueues = ProjectionCoreWorkersNode.CreateCoreWorkers(standardComponents, projectionsStandardComponents); _queueMap = _coreQueues.ToDictionary(v => v.Key, v => (IPublisher)v.Value); ProjectionManagerNode.CreateManagerService(standardComponents, projectionsStandardComponents, _queueMap); }
/// <summary> /// Initializes a new instance of the <see cref="ResolvedRouteInfo" /> class. /// </summary> /// <param name="controller">Resolved controller type for the current route.</param> /// <param name="action">Resolved action name for the current route.</param> /// <param name="actionArguments">Resolved dictionary of the action arguments for the current route.</param> /// <param name="httpMessageHandler">Resolved HttpMessageHandler for the current route.</param> /// <param name="modelState">Resolved model state validation for the current route.</param> public ResolvedRouteInfo( Type controller, string action, IDictionary<string, object> actionArguments, HttpMessageHandler httpMessageHandler, ModelStateDictionary modelState) { this.IsResolved = true; this.Controller = controller; this.Action = action; this.HttpMessageHandler = httpMessageHandler; this.ModelState = modelState; this.ActionArguments = actionArguments.ToDictionary( a => a.Key, a => new MethodArgumentInfo { Name = a.Key, Type = a.Value != null ? a.Value.GetType() : null, Value = a.Value }); }
public Request(string path, string query, string verb, string body, IDictionary<string, string> headers) { if (!string.IsNullOrEmpty(query)) { if (query.StartsWith("?")) query = query.Substring(1); _params = query.Split('&') .Aggregate(new Dictionary<string, List<string>>(), (dict, term) => { var key = term.Split('=')[0]; if (!dict.ContainsKey(key)) dict.Add(key, new List<string>()); dict[key].Add(term.Split('=')[1]); return dict; }); } _path = path; _headers = headers.ToDictionary(kv => kv.Key.ToLower(), kv => kv.Value.ToLower()); _verb = verb.ToLower(); _body = body==null ? "" : body.Trim(); }
/// <inheritdoc/> public async Task <WorkflowInstance> StartWorkflowInstanceAsync( string workflowId, string workflowPartitionKey = null, string instanceId = null, string instancePartitionKey = null, IDictionary <string, string> context = null) { // We need to clone the original context here in case it's modified by any of the code which creates the // workflow instance. var originalSuppliedContext = context?.ToDictionary(x => x.Key, x => x.Value); WorkflowInstance newInstance = await Retriable.RetryAsync(() => this.CreateWorkflowInstanceAsync(workflowId, workflowPartitionKey, instanceId, instancePartitionKey, context)).ConfigureAwait(false); // We publish the CloudEvent outside the Retry block because: // a) we only want to publish the event once the instance is created, and // b) we don't want a failure in CloudEvent publishing to cause a retry // of the whole process. The ICloudEventPublisher implementation is expected // to provide its own retry mechanism. Workflow workflow = await this.workflowStore.GetWorkflowAsync(newInstance.WorkflowId).ConfigureAwait(false); var workflowEventData = new WorkflowInstanceCreationCloudEventData(newInstance.Id) { NewContext = newInstance.Context, NewState = newInstance.StateId, NewStatus = newInstance.Status, SuppliedContext = originalSuppliedContext, WorkflowId = newInstance.WorkflowId, }; await this.cloudEventPublisher.PublishWorkflowEventDataAsync( this.cloudEventSource, WorkflowEventTypes.InstanceCreated, newInstance.Id, workflowEventData.ContentType, workflowEventData, workflow.WorkflowEventSubscriptions).ConfigureAwait(false); return(newInstance); }
// Solve using Dynamic Programming public static int SolveDp(IDictionary<int, int> snakes, IDictionary<int, int> ladders) { // Reverse keys and values ladders = ladders.ToDictionary(l => l.Value, l => l.Key); var minPath = new int[N + 1]; for (int i = 2; i <= D + 1; i++) { minPath[i] = 1; } for (int i = D + 2; i <= N; i++) { var shortestPath = GetMinPath(i, minPath, ladders, snakes); // Terminate this test case and return -1 if (shortestPath == -1) { return -1; } minPath[i] = shortestPath; // If this square has a snake head, we need to go to the tail and // update the shortest path for all squares up to the current one if (snakes.ContainsKey(i)) { var y = snakes[i]; minPath[y] = Math.Min(minPath[y], minPath[i]); for (var j = y + 1; j <= i; j++) { minPath[j] = GetMinPath(j, minPath, ladders, snakes); } } } return minPath[N]; }
public static Dictionary <string, object> ToFlattenedDictionaryOfPublicMembers(this object objSource, string strParentPropertyKey = "", IDictionary <string, object> dicParentPropertyValue = null) { Dictionary <string, object> dicReturn = dicParentPropertyValue?.ToDictionary(x => x.Key, y => y.Value) ?? new Dictionary <string, object>(); foreach (KeyValuePair <string, object> objItem in objSource.ToDictionaryOfPublicMembers()) { string strKey = string.IsNullOrEmpty(strParentPropertyKey) ? objItem.Key : $"{strParentPropertyKey}.{objItem.Key}"; if (objItem.Value.IsAnonymousType()) { foreach (KeyValuePair <string, object> objInnerItem in objItem.Value .ToFlattenedDictionaryOfPublicMembers(strKey, dicReturn)) { dicReturn.Add(objInnerItem.Key, objInnerItem.Value); } } else { dicReturn.Add(strKey, objItem.Value); } } return(dicReturn); }
static FunctionEnumExtensions() { var fields = Enum.GetNames(typeof (Function)) .Select(typeof (Function).GetField) .ToList(); FunctionToDotNetMethodName = fields .Where(x => x.GetCustomAttributes<DotNetMethodAttribute>().Any()) .ToDictionary(key => (Function)key.GetValue(null), value => value.GetCustomAttributes<DotNetMethodAttribute>().Single().Name); FunctionToODataQueryMethodName = fields .Where(x => x.GetCustomAttributes<FilterMethodAttribute>().Any()) .ToDictionary(key => (Function)key.GetValue(null), value => value.GetCustomAttributes<FilterMethodAttribute>().Single().Name); FunctionArity = fields .Where(x => x.GetCustomAttributes<FilterMethodAttribute>().Any()) .ToDictionary(key => (Function)key.GetValue(null), value => value.GetCustomAttributes<ArityAttribute>().Single().Arity); DotNetMethodNameToFunction = FunctionToDotNetMethodName.ToDictionary(key => key.Value, value => value.Key); ODataQueryMethodNameToFunction = FunctionToODataQueryMethodName.ToDictionary(key => key.Value, value => value.Key); }
public static FormulaGenerationArguments CreateRandom(Random random, Bounds<int> dimensionCountBounds, Bounds<int> minimalDepthBounds, Bounds leafProbabilityBounds, Bounds constantProbabilityBounds, Bounds constantBounds, IDictionary<Operator, Bounds> operatorAndMaxProbabilityBoundsMap, Operator[] obligatoryOperators, Bounds unaryVsBinaryOperatorsProbabilityBounds) { Dictionary<Operator, double> operatorAndProbabilityMap = operatorAndMaxProbabilityBoundsMap.ToDictionary(e => e.Key, e => random.Next(e.Value)); Operator[] unaryOperators = operatorAndMaxProbabilityBoundsMap.Keys.Where(op => op.Arity == 1).ToArray(); Operator[] binaryOperators = operatorAndMaxProbabilityBoundsMap.Keys.Where(op => op.Arity == 2).ToArray(); int unaryOperatorsToDeleteCount = random.Next(new Bounds<int>(0, unaryOperators.Length - 1)); int binaryOperatorsToDeleteCount = random.Next(new Bounds<int>(0, binaryOperators.Length - 1)); var unaryOperatorsToDelete = random.TakeDistinct(unaryOperators, unaryOperatorsToDeleteCount).Where(op => obligatoryOperators.All(o => o != op)); var binaryOperatorsToDelete = random.TakeDistinct(binaryOperators, binaryOperatorsToDeleteCount).Where(op => obligatoryOperators.All(o => o != op)); var operatorsToDelete = unaryOperatorsToDelete.Concat(binaryOperatorsToDelete); foreach (var op in operatorsToDelete) { operatorAndProbabilityMap.Remove(op); } double ubp = random.Next(unaryVsBinaryOperatorsProbabilityBounds); double ups = operatorAndProbabilityMap.Where(e => e.Key.Arity == 1).Sum(e => e.Value); double bps = operatorAndProbabilityMap.Where(e => e.Key.Arity == 2).Sum(e => e.Value); double correctionCoef = ubp / (1 - ubp) * bps / ups; operatorAndProbabilityMap.Select(e => e.Key).Where(op => op.Arity == 1).ToArray(). ForEach(op => operatorAndProbabilityMap[op] *= correctionCoef); return new FormulaGenerationArguments { DimensionsCount = random.Next(dimensionCountBounds), MinimalDepth = random.Next(minimalDepthBounds), LeafProbability = random.Next(leafProbabilityBounds), ConstantProbability = random.Next(constantProbabilityBounds), OperatorAndProbabilityMap = operatorAndProbabilityMap, CreateConstant = () => { double c = Math.Round(random.Next(constantBounds), 2); return Math.Abs(c - 0) < 0.01 ? 0.01 : c; } }; }
/********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="position">The tile position to edit, relative to the top-left corner.</param> /// <param name="layer">The map layer name to edit.</param> /// <param name="setIndex">The tilesheet index to apply, the string <c>false</c> to remove it, or null to leave it as-is.</param> /// <param name="setTilesheet">The tilesheet ID to set.</param> /// <param name="setProperties">The tile properties to set.</param> /// <param name="remove">Whether to remove the current tile and all its properties.</param> public EditMapPatchTile(TokenPosition position, IManagedTokenString layer, IManagedTokenString setIndex, IManagedTokenString setTilesheet, IDictionary <IManagedTokenString, IManagedTokenString> setProperties, IManagedTokenString remove) { this.Position = position; this.Layer = layer; this.SetIndex = setIndex; this.SetTilesheet = setTilesheet; this.SetProperties = setProperties?.ToDictionary(p => (ITokenString)p.Key, p => (ITokenString)p.Value); this.Remove = remove; this.Contextuals = new AggregateContextual() .Add(position) .Add(layer) .Add(setIndex) .Add(setTilesheet) .Add(remove); if (setProperties != null) { foreach (var pair in setProperties) { this.Contextuals.Add(pair.Key).Add(pair.Value); } } }
public ResponseMetaData( string serviceName, Guid correlationId, ServiceResult serviceResult, long durationMs, DateTimeOffset?responseCreated = null, IDictionary <int, string> errorCodes = null, IDictionary <string, string[]> validationErrors = null, string publicMessage = "", string exceptionMessage = "", Dictionary <string, ResponseMetaData> dependencies = null ) { ServiceName = serviceName; CorrelationId = correlationId; Result = serviceResult; DurationMs = durationMs; PublicMessage = string.IsNullOrWhiteSpace(publicMessage) ? null : publicMessage.Trim(); ExceptionMessage = string.IsNullOrWhiteSpace(exceptionMessage) ? null : exceptionMessage.Trim(); Dependencies = dependencies; ErrorCodes = errorCodes?.ToDictionary(k => k.Key.ToString(), v => v.Value); ValidationErrors = validationErrors; ResponseCreated = responseCreated ?? ServiceClock.CurrentTime(); }
public Task <int> SetAllAsync <T>(IDictionary <string, T> values, TimeSpan?expiresIn = null) { return(UnscopedCache.SetAllAsync(values?.ToDictionary(kvp => GetScopedCacheKey(kvp.Key), kvp => kvp.Value), expiresIn)); }
public Task UnlinkEntryAsync(ODataExpression expression, IDictionary <string, object> linkedEntryKey, CancellationToken cancellationToken) { return(_client.UnlinkEntryAsync(_command, expression.AsString(_session), linkedEntryKey?.ToDictionary(), cancellationToken)); }
private static IDictionary <string, string> ConvertToV1MessageStringsDictionary(IDictionary <string, MultiformatMessageString> v2MessageStringsDictionary) { return(v2MessageStringsDictionary?.ToDictionary( keyValuePair => keyValuePair.Key, keyValuePair => keyValuePair.Value.Text)); }