public void UnionDefaultEqualityComparer_SameKeyDifferentValues_Throws() { var first = new Dictionary<int, int> { { 2, 3 }, { 3, 5 }, { 6, 4 } }; var second = new SortedList<int, int> { { 3, 2 }, { 6, 4 } }; var actual = first.Union(second, EqualityComparer<KeyValuePair<int, int>>.Default); }
static void ARPScan(ScanOptions options) { Dictionary<IPAddress, List<ArpEntry>> results = new Dictionary<IPAddress, List<ArpEntry>>(); IEnumerable<string> targets; if (options.FromFile) { List<string> targetList = new List<string>(); foreach (string filename in options.StringSeq) { using (System.IO.TextReader r = System.IO.File.OpenText(filename)) { string s = String.Empty; while ((s = r.ReadLine()) != null) { string[] separators = options.separator == "" ? new string[] { System.Globalization.CultureInfo.CurrentUICulture.TextInfo.ListSeparator } : new string[] { options.separator }; string[] lineElts = s.Split(separators, StringSplitOptions.RemoveEmptyEntries); if(lineElts.Length == 1) //IP only { targetList.Add(lineElts[0]); } else if (lineElts.Length == 2) //Target name,IP { targetList.Add(lineElts[1]); } } } } targets = targetList; } else { targets = options.StringSeq; } foreach (string target in targets) { Dictionary<IPAddress, List<ArpEntry>> scanresult = ScanTarget(target, options); results = results.Union(scanresult).ToDictionary(k => k.Key, v => v.Value); } if (options.OutputFileName != "") { OutputToCSV(results, options); } else { foreach (IPAddress ipaddr in results.Keys) { foreach (ArpEntry entry in results[ipaddr]) Console.WriteLine("On {0}, IP {1} : MAC {2}", ipaddr, entry.ipEntry.AddressList[0], entry.physAddress); } Console.ReadLine(); } }
public void UnionNoEqualityComparer_SameKeyInSecondDict_TakesDuplicateKeyValuePair() { var first = new Dictionary<int, int> { { 2, 3 }, { 3, 5 }, { 6, 4 } }; var second = new SortedList<int, int> { { 3, 2 }, { 4, 7 } }; var expected = 4; var actual = first.Union(second).Count; Assert.AreEqual(expected, actual); }
public Dictionary<string, object> Insert(string tableName, Dictionary<string, object> row) { var allRows = _getTable(tableName); var keys = _getKeys(tableName, row, allRows); var prepedRow = row.Union(keys); var toWrite = allRows.And(prepedRow); _writeTable(tableName, toWrite); return keys; }
public IDictionary<TestCase, int> ReadTestDurations(IEnumerable<TestCase> testcases) { IDictionary<string, List<TestCase>> groupedTestcases = testcases.GroupByExecutable(); var durations = new Dictionary<TestCase, int>(); foreach (string executable in groupedTestcases.Keys) { durations = durations.Union(ReadTestDurations(executable, groupedTestcases[executable])).ToDictionary(kvp => kvp.Key, kvp => kvp.Value); } return durations; }
public MatrixPetriNet(string id, Dictionary<int, string> placeNames, Dictionary<int, string> transitionNames, Dictionary<int, List<InArc>> inArcs, Dictionary<int, List<OutArc>> outArcs, Dictionary<int, int> transitionOrdering) : this(id, placeNames, transitionNames, inArcs, outArcs) { var x = transitionNames.Select(t => t.Key).Except(transitionOrdering.Select(t => t.Key)); var y = transitionOrdering.Union(x.ToDictionary(t => t, t => 0)); // baseline priority level TransitionPriorities = y.ToDictionary(a => a.Key, a => a.Value); }
public static void LoadAffixes(string languageCode) { string json = File.ReadAllText(string.Format(@"data\affixes.{0}.json", languageCode)); affixMatches = JsonConvert.DeserializeObject<Dictionary<string, string>>(json); json = File.ReadAllText(string.Format(@"data\strings.{0}.json", languageCode)); var strings = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, string>>>(json); ItemQualities = strings["ItemQualities"]; WeaponTypes = strings["WeaponTypes"]; OffHandTypes = strings["OffHandTypes"]; FollowerTypes = strings["FollowerTypes"]; CommonTypes = strings["CommonTypes"]; ItemTypes = WeaponTypes.Union(OffHandTypes).Union(CommonTypes).ToDictionary(a => a.Key, b => b.Value); }
static AuditActionMapper() { actions = new Dictionary<MessageAction, MessageMaps>(); actions = actions .Union(LoginActionsMapper.GetMaps()) .Union(ProjectsActionsMapper.GetMaps()) .Union(CrmActionMapper.GetMaps()) .Union(PeopleActionMapper.GetMaps()) .Union(DocumentsActionMapper.GetMaps()) .Union(SettingsActionsMapper.GetMaps()) .ToDictionary(x => x.Key, x => x.Value); }
/// <summary> /// Inserts the row if it doesn't exist, update the row(s) if they do /// </summary> /// <param name="readWrite"></param> /// <param name="tablename"></param> /// <param name="dataFields"></param> /// <param name="keyFields"></param> /// <param name="trans"></param> public static void Ensure(this IReadWrite readWrite, string tablename, Dictionary<string, object> dataFields, Dictionary<string, object> keyFields) { // See if the keyFields exist // If so, update them, otherwise insert them var existing = readWrite.Read(tablename, keyFields); if (existing.Any()) readWrite.Update(tablename, dataFields, keyFields); else { var newRow = dataFields.Union(keyFields); var newKeys = readWrite.Insert(tablename, newRow); } }
public async Task<ActionResult> GetCustomVariablesAsync() { var meta = await AppUsers.GetCurrentAsync().ConfigureAwait(true); var model = new Dictionary<string, string>(); var iType = typeof(ICustomJavascriptVariable); var members = iType.GetTypeMembers<ICustomJavascriptVariable>(); foreach (var member in members) { var items = await member.GetAsync(this.Tenant, meta.OfficeId).ConfigureAwait(true); model = model.Union(items).ToDictionary(k => k.Key, v => v.Value); } return this.Ok(model); }
public IReadOnlyCollection<RCompletion> GetEntries(RCompletionContext context) { List<RCompletion> completions = new List<RCompletion>(); ImageSource functionGlyph = GlyphService.GetGlyph(StandardGlyphGroup.GlyphGroupValueType, StandardGlyphItem.GlyphItemPublic); // Safety checks FunctionCall funcCall = context.AstRoot.GetNodeOfTypeFromPosition<FunctionCall>(context.Position); if (funcCall == null || funcCall.OpenBrace == null || funcCall.Arguments == null) { return completions; } if (context.Position < funcCall.OpenBrace.End || context.Position >= funcCall.SignatureEnd) { return completions; } // Retrieve parameter positions from the current text buffer snapshot ParameterInfo parametersInfo = SignatureHelp.GetParametersInfoFromBuffer(context.AstRoot, context.TextBuffer.CurrentSnapshot, context.Position); if (parametersInfo == null) { return completions; } // Get collection of function signatures from documentation (parsed RD file) IFunctionInfo functionInfo = FunctionIndex.GetFunctionInfo(parametersInfo.FunctionName, o => { }, context.Session.TextView); if (functionInfo == null) { return completions; } // Collect parameter names from all signatures IEnumerable<KeyValuePair<string, IArgumentInfo>> arguments = new Dictionary<string, IArgumentInfo>(); foreach (ISignatureInfo signature in functionInfo.Signatures) { var args = signature.Arguments.ToDictionary(x => x.Name); arguments = arguments.Union(args); } // Add names of arguments that are not yet specified to the completion // list with '=' sign so user can tell them from function names. IEnumerable<string> declaredArguments = funcCall.Arguments.Where(x => x is NamedArgument).Select(x => ((NamedArgument)x).Name); IEnumerable<KeyValuePair<string, IArgumentInfo>> possibleArguments = arguments.Where(x => x.Key != "..." && !declaredArguments.Contains(x.Key)); foreach (KeyValuePair<string, IArgumentInfo> arg in possibleArguments) { string displayText = arg.Key + " ="; string insertionText = arg.Key + " = "; completions.Add(new RCompletion(displayText, insertionText, arg.Value.Description, functionGlyph)); } return completions; }
public void Generate__GeneratedProperly() { // Prepare expected results var joinedModels = new Dictionary<string, string> { { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.CustomerFirstName), "Customer.FirstName" }, { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.CustomerLastName), "Customer.LastName" }, { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.CustomerFingersCount), "Customer.FingersCount" }, { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.CustomerHairLength), "Customer.HairLength" }, { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.CustomerPreviousSurgeryDate), "Customer.PreviousSurgeryDate" }, { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.CustomerType), "Customer.Type" }, }; var components = new Dictionary<string, string> { { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.PaymentInfoOrderedDate), "PaymentInfo.OrderedDate" }, { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.PaymentInfoState), "PaymentInfo.State" }, { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.PaymentInfoDouble), "PaymentInfo.Double" }, { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.PaymentInfoExternalPaymentId), "PaymentInfo.ExternalPaymentId" }, { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.PaymentInfoNumber), "PaymentInfo.Number" }, }; var simpleProps = new Dictionary<string, string> { { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.Id), "Id" }, { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.Type), "Type" }, { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.OrderDate), "OrderDate" }, { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.TotalPrice), "TotalPrice" }, { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.Note), "Note" }, { ObjectHelper.GetPropertyName<OrderGridModel>(v => v.ItemsCount), "ItemsCount" }, }; var allProps = joinedModels.Union(components).Union(simpleProps).ToDictionary(x => x.Key, x => x.Value); // ACT var modelDescription = GetTestModelDescription(); var map = ViewModelToPersistenceModelPropertyNamesMapsGenerator.Generate(typeof(OrderGridModel), modelDescription); // ASSERT map.Should(Be.Not.Null); map.AllProperties.Count.Should(Be.EqualTo(17)); map.AllProperties.Should(Be.EquivalentTo(allProps)); }
protected void Page_Init(object sender, EventArgs e) { changeableOptions = new Dictionary<CheckBox, OptionView>() { { cbNotasAndQuarterlyReportsByPost, new OptionView { Category = SendableDocumentCategories.NotasAndQuarterlyReports, Option = SendingOptions.ByPost } }, { cbNotasAndQuarterlyReportsByEmail, new OptionView { Category = SendableDocumentCategories.NotasAndQuarterlyReports, Option = SendingOptions.ByEmail } } }; nonChangeableOptions = new Dictionary<CheckBox, OptionView>() { { cbYearlyReportsByPost, new OptionView { Category = SendableDocumentCategories.YearlyReports, Option = SendingOptions.ByPost } }, { cbYearlyReportsByEmail, new OptionView { Category = SendableDocumentCategories.YearlyReports, Option = SendingOptions.ByEmail } } }; allOptions = changeableOptions.Union(nonChangeableOptions).ToDictionary(pair => pair.Key, pair => pair.Value); }
public static MultiSelectList GetPossibleValues( this PropertyValue propertyValue, bool addChooseItem = true) { if (propertyValue.Property.IsForeignKey) { var options = new Dictionary<string, string>(); if (addChooseItem) { options.Add(String.Empty, IlaroAdminResources.Choose); } options = options.Union(propertyValue.PossibleValues).ToDictionary(x => x.Key, x => x.Value); return propertyValue.Property.TypeInfo.IsCollection ? new MultiSelectList(options, "Key", "Value", propertyValue.Values) : new SelectList(options, "Key", "Value", propertyValue.AsString); } else { var options = addChooseItem ? propertyValue.Property.TypeInfo.EnumType.GetOptions(String.Empty, IlaroAdminResources.Choose) : propertyValue.Property.TypeInfo.EnumType.GetOptions(); if (propertyValue.Property.TypeInfo.IsEnum) { return new SelectList( options, "Key", "Value", propertyValue.AsObject); } return new SelectList(options, "Key", "Value", propertyValue.AsString); } }
public IReadOnlyCollection<RCompletion> GetEntries(RCompletionContext context) { List<RCompletion> completions = new List<RCompletion>(); FunctionCall funcCall; ImageSource functionGlyph = _glyphService.GetGlyphThreadSafe(StandardGlyphGroup.GlyphGroupValueType, StandardGlyphItem.GlyphItemPublic); // Safety checks if (!ShouldProvideCompletions(context, out funcCall)) { return completions; } // Get collection of function signatures from documentation (parsed RD file) IFunctionInfo functionInfo = GetFunctionInfo(context); if (functionInfo == null) { return completions; } // Collect parameter names from all signatures IEnumerable<KeyValuePair<string, IArgumentInfo>> arguments = new Dictionary<string, IArgumentInfo>(); foreach (ISignatureInfo signature in functionInfo.Signatures) { var args = signature.Arguments.ToDictionary(x => x.Name); arguments = arguments.Union(args); } // Add names of arguments that are not yet specified to the completion // list with '=' sign so user can tell them from function names. IEnumerable<string> declaredArguments = funcCall.Arguments.Where(x => x is NamedArgument).Select(x => ((NamedArgument)x).Name); var possibleArguments = arguments.Where(x => !x.Key.EqualsOrdinal("...") && !declaredArguments.Contains(x.Key, StringComparer.OrdinalIgnoreCase)); foreach (var arg in possibleArguments) { string displayText = arg.Key + " ="; string insertionText = arg.Key + " = "; completions.Add(new RCompletion(displayText, insertionText, arg.Value.Description, functionGlyph)); } return completions; }
private Dictionary<SiloAddress, ConsistentRingProvider> Combine(Dictionary<SiloAddress, ConsistentRingProvider> set1, Dictionary<SiloAddress, ConsistentRingProvider> set2) { // tell set1 about every node in set2 foreach (ConsistentRingProvider crp in set1.Values) { foreach (ConsistentRingProvider other in set2.Values) { if (!crp.MyAddress.Equals(other.MyAddress)) { other.AddServer(crp.MyAddress); } } } // tell set2 about every node in set1 ... even if set1 and set2 overlap, ConsistentRingProvider should be able to handle foreach (ConsistentRingProvider crp in set2.Values) { foreach (ConsistentRingProvider other in set1.Values) { if (!crp.MyAddress.Equals(other.MyAddress)) { other.AddServer(crp.MyAddress); } } } // tell set2 about every node in set2 ... note that set1 already knows about nodes in set1 foreach (ConsistentRingProvider crp in set2.Values) { foreach (ConsistentRingProvider other in set2.Values) { if (!crp.MyAddress.Equals(other.MyAddress)) { other.AddServer(crp.MyAddress); } } } // merge the sets return set1.Union(set2).ToDictionary(pair => pair.Key, pair => pair.Value); }
public string CreateHtmlText(string testHtmlTemplate, Dictionary<string, string> frameworkReplacements) { var testJsReplacement = new StringBuilder(); var testFrameworkDependencies = new StringBuilder(); var codeCoverageDependencies = new StringBuilder(); var referenceJsReplacement = new StringBuilder(); var referenceCssReplacement = new StringBuilder(); var referenceHtmlTemplateReplacement = new StringBuilder(); BuildReferenceHtml(testFrameworkDependencies, referenceCssReplacement, testJsReplacement, referenceJsReplacement, referenceHtmlTemplateReplacement, codeCoverageDependencies); string amdTestFilePathArrayString = ""; string amdModuleMap = ""; if (chutzpahTestSettings.TestHarnessReferenceMode == TestHarnessReferenceMode.AMD) { amdTestFilePathArrayString = BuildAmdTestFileArrayString(); amdModuleMap = BuildModuleMapForGeneratedFiles(); } var amdBasePathUrl = ""; if (!string.IsNullOrEmpty(chutzpahTestSettings.AMDBasePath)) { amdBasePathUrl = FileProbe.GenerateFileUrl(chutzpahTestSettings.AMDBasePath); } else if (!string.IsNullOrEmpty(chutzpahTestSettings.AMDBaseUrl)) { amdBasePathUrl = FileProbe.GenerateFileUrl(chutzpahTestSettings.AMDBaseUrl); } var replacements = new Dictionary<string, string> { {"TestFrameworkDependencies", testFrameworkDependencies.ToString()}, {"CodeCoverageDependencies", codeCoverageDependencies.ToString()}, {"TestJSFile", testJsReplacement.ToString()}, {"ReferencedJSFiles", referenceJsReplacement.ToString()}, {"ReferencedCSSFiles", referenceCssReplacement.ToString()}, {"TestHtmlTemplateFiles", referenceHtmlTemplateReplacement.ToString()}, {"AMDTestPath", amdTestFilePathArrayString}, {"AMDModuleMap", amdModuleMap}, {"AMDBasePath", amdBasePathUrl } }; var testHtmlStringBuilder = new StringBuilder(testHtmlTemplate); foreach (var replacement in replacements.Union(frameworkReplacements)) { testHtmlStringBuilder.Replace("@@" + replacement.Key + "@@", replacement.Value); } return testHtmlStringBuilder.ToString(); }
public MultiSelectList GetPossibleValues(bool addChooseItem = true) { if (IsForeignKey) { var options = new Dictionary<string, string>(); if (addChooseItem) { options.Add(String.Empty, IlaroAdminResources.Choose); } options = options.Union(Value.PossibleValues).ToDictionary(x => x.Key, x => x.Value); return TypeInfo.IsCollection ? new MultiSelectList(options, "Key", "Value", Value.Values) : new SelectList(options, "Key", "Value", Value); } else { var options = addChooseItem ? TypeInfo.EnumType.GetOptions(String.Empty, IlaroAdminResources.Choose) : TypeInfo.EnumType.GetOptions(); if (Value != null && Value.GetType().IsEnum) { return new SelectList( options, "Key", "Value", Convert.ToInt32(Value)); } return new SelectList(options, "Key", "Value", Value); } }
/// <summary> /// Does an insert and returns the keys of the row just inserted /// </summary> /// <param name="tableName"></param> /// <param name="dataFields"></param> /// <param name="transaction"></param> /// <returns></returns> public Dictionary<string, object> Insert(string tableName, Dictionary<string, object> dataFields, ITransaction transaction = null) { //Retrieve the AutoNumbered key name if there is one var autoNumberKeyName = Analyzer.GetAutoNumberKey(tableName); //Retrieve all of the primary keys to be sure they are all set, except we don't want the autonumbered key since the DB will set it var requiredKeys = Analyzer.GetPrimaryKeys(tableName).Except(autoNumberKeyName); //Check that all of the required keys are actually set var invalid = requiredKeys.Where(key => dataFields[key] == null); if (invalid.Any()) throw new KeyNotSetException(tableName, invalid); // Keep in mind that GetFields might return an empty list, which means that it doesn't know var dbFields = Analyzer.GetFields(tableName).Or(dataFields.Keys); // Take out the autonumber keys, and take out any supplied data fields // that aren't actually fields in the DB var fieldNames = dataFields.Keys.Except(autoNumberKeyName) .Intersect(dbFields); var sql = "INSERT INTO " + tableName + " (" + fieldNames.Join(", ") + ") VALUES (" + fieldNames.Select(x => "@" + x).Join(", ") + ")\n"; sql += "SELECT SCOPE_IDENTITY()"; var autoKey = sqlInsert(sql, transaction, dataFields); if (autoNumberKeyName != null && autoKey == null) throw new ThisSadlyHappenedException("The SQL ran beautifully, but you were expecting an autogenerated number and you did not get it"); if (autoNumberKeyName != null) { var autoKeyDict = new Dictionary<string, object>() { { autoNumberKeyName, autoKey } }; dataFields = dataFields.Union(autoKeyDict); } return dataFields.WhereKeys(key => Analyzer.GetPrimaryKeys(tableName).Contains(key)); }
protected FaceAPI call_method(string method, Dictionary<string, string> param) { // Remember keys for removal List<string> keys = new List<string>(); foreach (KeyValuePair<string, string> s in param) { if (String.IsNullOrWhiteSpace(s.Value)) { keys.Add(s.Key); } else { if (s.Key == "_file" && s.Value == "@") { keys.Add(s.Key); } } } foreach (string s in keys) { param.Remove(s); } Dictionary<string, string> authParams = new Dictionary<string, string>(); if (!String.IsNullOrWhiteSpace(this.apiKey)) { authParams.Add("api_key", this.apiKey); } if (!String.IsNullOrWhiteSpace(this.apiSecret)) { authParams.Add("api_secret", this.apiSecret); } if (userAuth.Count > 0) { authParams.Add("user_auth", getUserAuthString(this.userAuth)); } if (!String.IsNullOrWhiteSpace(this.password)) { authParams.Add("password", this.password); } Dictionary<String, String> paramMerge = new Dictionary<String, String>(); paramMerge = authParams.Union(param).ToDictionary(pair => pair.Key, pair => pair.Value); string request = method + "." + this.format; return this.post_method(request, paramMerge); }
Dictionary<string, string> CreateExpectedConfigDictionary(Dictionary<string, string> config, string url, WebHookContentType contentType, string secret) { return config.Union(new Dictionary<string, string> { { "url", url }, { "content_type", contentType.ToString().ToLowerInvariant() }, { "secret", secret }, { "insecure_ssl", "False" } }).ToDictionary(k => k.Key, v => v.Value); }
protected FaceApi CallMethod(string method, Dictionary<string, string> param) { // Remember keys for removal var keys = new List<string>(); foreach (var s in param) { if (String.IsNullOrWhiteSpace(s.Value)) { keys.Add(s.Key); } else { if (s.Key == "_file" && s.Value == "@") { keys.Add(s.Key); } } } foreach (string s in keys) { param.Remove(s); } var authParams = new Dictionary<string, string>(); if (!String.IsNullOrWhiteSpace(this._apiKey)) { authParams.Add("api_key", this._apiKey); } if (!String.IsNullOrWhiteSpace(this._apiSecret)) { authParams.Add("api_secret", this._apiSecret); } if (_userAuth.Count > 0) { authParams.Add("user_auth", getUserAuthString(this._userAuth)); } if (!String.IsNullOrWhiteSpace(_password)) { authParams.Add("password", _password); } var paramMerge = authParams.Union(param).ToDictionary(pair => pair.Key, pair => pair.Value); var request = method + "." + _format; return PostMethod(request, paramMerge); }
public FeatureCollectionResult ImportFeed(SyndicationFeed feed) { if (feed == null) throw new ArgumentNullException("feed"); FeatureCollectionResult fc = new FeatureCollectionResult(); NameValueCollection namespaces = null; XmlNamespaceManager xnsm = null; string prefix = ""; if (options.KeepNamespaces) { // Initialize namespaces namespaces = new NameValueCollection(); namespaces.Set("", "http://geojson.org/ns#"); namespaces.Set("atom", "http://www.w3.org/2005/Atom"); XmlReader reader = feed.ElementExtensions.GetReaderAtElementExtensions(); xnsm = new XmlNamespaceManager(reader.NameTable); foreach (var names in xnsm.GetNamespacesInScope(XmlNamespaceScope.All)) { namespaces.Set(names.Key, names.Value); } fc.Properties.Add("@namespaces", namespaces); prefix = "atom:"; } // Import Feed if (feed != null) { if ((feed.Authors != null) && (feed.Authors.Count > 0)) { object[] authors = new object[feed.Authors.Count]; fc.Properties.Add(prefix + "authors", authors); for (int i = 0; i < feed.Authors.Count; i++) { Dictionary<string,object> author = new Dictionary<string, object>(); author.Add(prefix + "name", feed.Authors[i].Name); author.Add(prefix + "email", feed.Authors[i].Email); author.Add(prefix + "uri", feed.Authors[i].Uri); author = author.Concat(util.ImportAttributeExtensions(feed.Authors[i].AttributeExtensions, namespaces, xnsm)).ToDictionary(x => x.Key, x => x.Value); author = author.Concat(util.ImportElementExtensions(feed.Authors[i].ElementExtensions, namespaces)).ToDictionary(x => x.Key, x => x.Value); authors[i] = author; } } if (feed.BaseUri != null) { fc.Properties.Add(prefix + "uri", feed.BaseUri.ToString()); } if ((feed.Categories != null) && (feed.Categories.Count > 0)) { object[] categories = new object[feed.Categories.Count]; fc.Properties.Add(prefix + "categories", categories); for (int i = 0; i < feed.Categories.Count; i++) { Dictionary<string,object> category = new Dictionary<string, object>(); category.Add(prefix + "name", feed.Categories[i].Name); category.Add(prefix + "label", feed.Categories[i].Label); category.Add(prefix + "scheme", feed.Categories[i].Scheme); category = category.Union(util.ImportAttributeExtensions(feed.Categories[i].AttributeExtensions, namespaces, xnsm)).ToDictionary(x => x.Key, x => x.Value); category = category.Union(util.ImportElementExtensions(feed.Categories[i].ElementExtensions, namespaces)).ToDictionary(x => x.Key, x => x.Value); categories[i] = category; } } if ((feed.Contributors != null) && (feed.Contributors.Count > 0)) { object[] contributors = new object[feed.Contributors.Count]; fc.Properties.Add(prefix + "categories", contributors); for (int i = 0; i < feed.Contributors.Count; i++) { Dictionary<string,object> contributor = new Dictionary<string, object>(); contributor.Add(prefix + "name", feed.Contributors[i].Name); contributor.Add(prefix + "email", feed.Contributors[i].Email); contributor.Add(prefix + "uri", feed.Contributors[i].Uri); contributor = contributor.Union(util.ImportAttributeExtensions(feed.Contributors[i].AttributeExtensions, namespaces, xnsm)).ToDictionary(x => x.Key, x => x.Value); contributor = contributor.Union(util.ImportElementExtensions(feed.Contributors[i].ElementExtensions, namespaces)).ToDictionary(x => x.Key, x => x.Value); contributors[i] = contributor; } } if (feed.Copyright != null) { fc.Properties.Add(prefix + "rights", feed.Copyright.Text); } if (feed.Description != null) { fc.Properties.Add(prefix + "content", feed.Description.Text); } if (feed.Generator != null) { fc.Properties.Add(prefix + "generator", feed.Generator); } fc.Properties.Add(prefix + "id", feed.Id); if (feed.ImageUrl != null) fc.Properties.Add(prefix + "logo", feed.ImageUrl.ToString()); if (feed.Language != null) fc.Properties.Add(prefix + "language", feed.Language); if (feed.LastUpdatedTime != null) fc.Properties.Add(prefix + "updated", feed.LastUpdatedTime); if ((feed.Links != null) && (feed.Links.Count > 0)) { fc.Links = feed.Links; } if (feed.Title != null) fc.Properties.Add(prefix + "title", feed.Title); if (feed.Items != null) { foreach (var item in feed.Items) { fc.FeatureResults.Add(ImportItem(item)); } } return fc; } return null; }
public async Task<Dictionary<byte, byte>> GetAnswers() { return await Task.Run(() => { var answers = new Dictionary<byte, byte>(); foreach (var d in Drivers) { answers = answers.Union(d.Answers).ToDictionary(x => x.Key, x => x.Value); } return answers; }); }
private static string GetSignature(string url, string method, string nonce, string timestamp, string token, string tokenSecret, Dictionary<string, object> parameters) { var dict = new Dictionary<string, object>(); dict.Add("oauth_consumer_key", ConsumerKey); dict.Add("oauth_nonce", nonce.ToString()); dict.Add("oauth_signature_method", "HMAC-SHA1"); dict.Add("oauth_timestamp", timestamp); dict.Add("oauth_token", token); dict.Add("oauth_version", "1.0"); var sigBase = new StringBuilder(); var first = true; foreach (var d in (parameters == null ? dict : dict.Union(parameters)).OrderBy(p => p.Key)) { if (!first) { sigBase.Append("&"); } first = false; if (d.Key.StartsWith("data")) { sigBase.Append(d.Key); } else { UrlEncode(sigBase, d.Key); } sigBase.Append("="); if (d.Value is byte[]) { EncodeSigStream(sigBase, (byte[])d.Value); } else { UrlEncode(sigBase, d.Value.ToString()); } } String SigBaseString = method.ToUpper() + "&"; SigBaseString += UrlEncode(url) + "&" + UrlEncode(sigBase.ToString(), false); var keyMaterial = Encoding.UTF8.GetBytes(ConsumerSecret + "&" + tokenSecret); var HmacSha1Provider = new System.Security.Cryptography.HMACSHA1 { Key = keyMaterial }; return Convert.ToBase64String(HmacSha1Provider.ComputeHash(Encoding.UTF8.GetBytes(SigBaseString))); }
public string CreateHtmlText(string testHtmlTemplate, Dictionary<string, string> frameworkReplacements) { var testJsReplacement = new StringBuilder(); var testFrameworkDependencies = new StringBuilder(); var codeCoverageDependencies = new StringBuilder(); var referenceJsReplacement = new StringBuilder(); var referenceCssReplacement = new StringBuilder(); var referenceHtmlTemplateReplacement = new StringBuilder(); BuildReferenceHtml(testFrameworkDependencies, referenceCssReplacement, testJsReplacement, referenceJsReplacement, referenceHtmlTemplateReplacement, codeCoverageDependencies); var replacements = new Dictionary<string, string> { {"TestFrameworkDependencies", testFrameworkDependencies.ToString()}, {"CodeCoverageDependencies", codeCoverageDependencies.ToString()}, {"TestJSFile", testJsReplacement.ToString()}, {"ReferencedJSFiles", referenceJsReplacement.ToString()}, {"ReferencedCSSFiles", referenceCssReplacement.ToString()}, {"TestHtmlTemplateFiles", referenceHtmlTemplateReplacement.ToString()}, {"AMDTestPath", amdModulePath} }; var testHtmlStringBuilder = new StringBuilder(testHtmlTemplate); foreach (var replacement in replacements.Union(frameworkReplacements)) { testHtmlStringBuilder.Replace("@@" + replacement.Key + "@@", replacement.Value); } return testHtmlStringBuilder.ToString(); }
public ActionResult ManagePointItems() { PointSettings pointSettings = pointSettingsManger.Get(); pageResourceManager.InsertTitlePart("积分规则"); IEnumerable<PointCategory> pointCategories = pointService.GetPointCategories(); ViewData["traPoint"] = pointCategories.FirstOrDefault(n => n.CategoryKey.Equals("TradePoints")).CategoryName; ViewData["expPoint"] = pointCategories.FirstOrDefault(n => n.CategoryKey.Equals("ExperiencePoints")).CategoryName; ViewData["prePoint"] = pointCategories.FirstOrDefault(n => n.CategoryKey.Equals("ReputationPoints")).CategoryName; ViewData["TransactionTax"] = pointSettings.TransactionTax; ViewData["PointCategories"] = pointService.GetPointCategories(); ViewData["UserIntegratedPointRuleText"] = pointSettings.UserIntegratedPointRuleText; IEnumerable<PointItem> pointItems = pointService.GetPointItems(null); Dictionary<int, string> applicationDictionary = new Dictionary<int, string> { { 0, "通用" } }; ViewData["Applications"] = applicationDictionary.Union(applicationService.GetAll().ToDictionary(m => m.ApplicationId, n => n.Config.ApplicationName)); return View(pointItems); }
public void Union() { var dict = new Dictionary<int, int>() { { 1, 1 }, { 2, 2 }, { 3, 3 } }; var dictCopy = new Dictionary<int, int>() { { 1, 17 }, { 4, 4 }, { 5, 5 } }; var dictOther = new Dictionary<int, int>() { { 1, 17 }, { 2, 2 }, { 3, 3 }, { 4, 4 }, { 5, 5 } }; Assert.AreEqual(dictOther, dict.Union(dictCopy)); }
public AuthorizationManager(IAuthorizationConfiguration authorizationConfiguration) { defaultAuthorizer = authorizationConfiguration.DefaultAuthorizer; if (defaultAuthorizer == null) { throw new InitialisationException("Default Authorizer cannot be null"); } var isVisibleDict = new Dictionary<Type, Func<object, IPrincipal, object, string, bool>>() { {defaultAuthorizer, DelegateUtils.CreateTypeAuthorizerDelegate(defaultAuthorizer.GetMethod("IsVisible"))} }; var isEditableDict = new Dictionary<Type, Func<object, IPrincipal, object, string, bool>>() { {defaultAuthorizer, DelegateUtils.CreateTypeAuthorizerDelegate(defaultAuthorizer.GetMethod("IsEditable"))} }; if (authorizationConfiguration.NamespaceAuthorizers.Any()) { namespaceAuthorizers = authorizationConfiguration.NamespaceAuthorizers.OrderByDescending(x => x.Key.Length).ToImmutableDictionary(); } if (authorizationConfiguration.TypeAuthorizers.Any()) { if (authorizationConfiguration.TypeAuthorizers.Values.Any(t => typeof(ITypeAuthorizer<object>).IsAssignableFrom(t))) { throw new InitialisationException("Only Default Authorizer can be ITypeAuthorizer<object>"); } typeAuthorizers = authorizationConfiguration.TypeAuthorizers.ToImmutableDictionary(); isVisibleDelegates = isVisibleDict.Union(authorizationConfiguration.TypeAuthorizers.Values.ToDictionary(type => type, type => DelegateUtils.CreateTypeAuthorizerDelegate(type.GetMethod("IsVisible")))).ToImmutableDictionary(); isEditableDelegates = isEditableDict.Union(authorizationConfiguration.TypeAuthorizers.Values.ToDictionary(type => type, type => DelegateUtils.CreateTypeAuthorizerDelegate(type.GetMethod("IsEditable")))).ToImmutableDictionary(); } else { // default authorizer must be the only TypeAuthorizer isVisibleDelegates = isVisibleDict.ToImmutableDictionary(); isEditableDelegates = isEditableDict.ToImmutableDictionary(); } }
protected void InternalBuildSmoothBondSeries(KnownCurve knownCurve, SmoothBondCurveCalculationParams parameters, bool buildCMT = true) { if (mConstituentsOnly) { return; } var curve = SObjectManager.Instance().LoadSObject<DiscountCurve>(new Moniker { Close = parameters.Close, Source = parameters.Source, Type = "DiscountCurve", Date = ValueDate, Name = KnownCurveHelpers.GetKnownCurveCode(knownCurve) }); if (curve == null) { SLog.log.ErrorFormat("Unable to load curve {0} for smooth series construction.", knownCurve.ToString()); return; } // delete the old data else might have residual stuff saved that confuses things { SLog.log.Debug("Deleting any previous data from the database..."); foreach (var ending in new[] { string.Empty, "%" }) SObjectManager.Instance().DeleteCachedObject( monikerDate_: ValueDate, monikerSource_: parameters.Source, likeMonikerName_: string.Format("{0}%{1}{2}", parameters.Country, parameters.CurveName, ending)); } SLog.log.DebugFormat("Building {0} smooth curve over {1} on {2}", parameters.Country, parameters.CurveName, ValueDate); IEnumerable<KeyValuePair<string, AnySObject>> allObjects = new Dictionary<string, AnySObject>(); Dictionary<string, Dictionary<int, RateCurve>> cmtGlobal = new Dictionary<string, Dictionary<int, RateCurve>>(); foreach (var maturity in parameters.Maturities) { try { var smoothCurves = new SmoothBondCurveCalculator(ValueDate, new SmoothBondCurveParameters { SpotDelay = parameters.SpotDelay, SettleDelay = parameters.SettleDelay, HolidayCenter = parameters.HolidayCenter, Close = parameters.Close, Source = parameters.Source, CurveStart = parameters.CurveStart, CurveStep = parameters.CurveStep, YieldLambda = parameters.YieldLambdas[maturity], SpreadLambda = parameters.SpreadLambdas[maturity], TrueSpreadLambda = parameters.TrueSpreadLambdas[maturity], CurveName = parameters.CurveName, Markets = parameters.Markets, Currency = parameters.Currency, Country = parameters.Country, AnalyticsCountry = parameters.AnalyticsCountry, Maturity = maturity, SwapCurveType = parameters.SwapCurveType, TermDrift = parameters.BondTermDrift, ShouldIncludeDelegate = parameters.ShouldIncludeBondInTargetMaturityDelegate, }, curve).Calculate(); if (smoothCurves.ContainsKey("Yield")) { var yieldMoniker = RateCurve.CreateSmoothCurveMoniker(ValueDate, "yield", parameters.Country, maturity, parameters.Close, parameters.Source, parameters.CurveName); SObjectManager.Instance().SaveSObject(yieldMoniker, smoothCurves["Yield"]); } if (smoothCurves.ContainsKey("Spread")) { var spreadMoniker = RateCurve.CreateSmoothCurveMoniker(ValueDate, "spread", parameters.Country, maturity, parameters.Close, parameters.Source, parameters.CurveName); SObjectManager.Instance().SaveSObject(spreadMoniker, smoothCurves["Spread"]); } if (smoothCurves.ContainsKey("MMS")) { var mmsMoniker = RateCurve.CreateSmoothCurveMoniker(ValueDate, "mms", parameters.Country, maturity, parameters.Close, parameters.Source, parameters.CurveName); SObjectManager.Instance().SaveSObject(mmsMoniker, smoothCurves["MMS"]); } if (smoothCurves.ContainsKey("TrueSpread")) { var trueSpreadMoniker = RateCurve.CreateSmoothCurveMoniker(ValueDate, "truespread", parameters.Country, maturity, parameters.Close, parameters.Source, parameters.CurveName); SObjectManager.Instance().SaveSObject(trueSpreadMoniker, smoothCurves["TrueSpread"]); } foreach (var kvp in smoothCurves) { if (Moniker.IsMoniker(kvp.Key)) { SObjectManager.Instance().SaveSObject(Moniker.FromString(kvp.Key), kvp.Value); } } if (buildCMT) { var bsObjects = new CMTBondSpreadCalculator(ValueDate, new CMTBondSpreadParameters { Close = parameters.Close, CurveName = parameters.CurveName, Country = parameters.Country, Maturity = maturity, Source = parameters.Source, Maturities = parameters.Maturities }, smoothCurves, ref cmtGlobal).Calculate(); foreach (var bso in bsObjects) { SObjectManager.Instance().SaveSObject(Moniker.FromString(bso.Key), bso.Value); } allObjects = allObjects.Union(bsObjects.AsEnumerable()); } } catch (Exception ex) { SLog.log.Error("Error calculating smooth series", ex); } } if (buildCMT) { try { foreach (var curveType in cmtGlobal.Keys) foreach (var series in cmtGlobal[curveType].Keys) { var moniker = RateCurve.CreateBondSeriesCurveMoniker(ValueDate, curveType, parameters.Country, series, parameters.Close, parameters.Source, parameters.CurveName); SObjectManager.Instance().SaveSObject(moniker, cmtGlobal[curveType][series]); } } catch (Exception ex) { SLog.log.Error("Error saving cmt rate curves", ex); } } }