static void Main(string[] args) { Console.WriteLine("String :"); string text = Console.ReadLine(); List<string> checkedWords = new List<string>(); string[] words = text.Split(new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries); Dictionary<string, int> count = new Dictionary<string, int>(); for (int i = 0; i < words.Length; i++) { string word = words[i]; if (!checkedWords.Contains(word)) { count.Add(word, words.Count(x => x == word)); checkedWords.Add(word); } } List<KeyValuePair<string, int>> sorted = count.ToList(); sorted.Sort((x, y) => { return y.Value.CompareTo(x.Value); }); foreach (var item in sorted) { Console.WriteLine("{0} - {1}", item.Key, item.Value); } }
static void Main(string[] args) { Dictionary<char, int> symbols = new Dictionary<char, int>(); string text = Console.ReadLine(); for (int i = 0; i < text.Length; i++) { char currentChar = Convert.ToChar(text[i]); if (!symbols.ContainsKey(text[i])) { symbols[currentChar] = 0; } symbols[currentChar]++; } var orderedSymbols = symbols.ToList(); orderedSymbols.Sort(delegate(KeyValue<char, int> c1, KeyValue<char, int> c2) { return c1.Key.CompareTo(c2.Key); }); foreach (var symbol in orderedSymbols) { Console.WriteLine(symbol + " time/s"); } }
private void Form1_Load_1(object sender, EventArgs e) { var source = new Dictionary<string, uint>(); source.Add("F1", 0x70); source.Add("F2", 0x71); source.Add("F3", 0x72); source.Add("F4", 0x73); source.Add("F5", 0x74); source.Add("F6", 0x75); source.Add("F7", 0x76); source.Add("F8", 0x77); source.Add("F9", 0x78); source.Add("F10", 0x79); source.Add("F11", 0x80); source.Add("F12", 0x81); this.mana_hotkey.DataSource = source.ToList(); this.mana_hotkey.DisplayMember = "Key"; this.mana_hotkey.ValueMember = "Value"; this.light_heal_hotkey.DataSource = source.ToList(); this.light_heal_hotkey.DisplayMember = "Key"; this.light_heal_hotkey.ValueMember = "Value"; this.intense_heal_hotkey.DataSource = source.ToList(); this.intense_heal_hotkey.DisplayMember = "Key"; this.intense_heal_hotkey.ValueMember = "Value"; }
public AdoNetEventStoreConfiguration(string connectionString, string tableName, params KeyValuePair <Expression <Func <EventDescriptor, object> >, string>[] tableFieldRegistrations) : this(connectionString, tableName, new NullKeyGenerator <Guid>(), tableFieldRegistrations?.ToList() .Select(x => new KeyValuePair <string, string>(Utils.GetPropertyNameFromExpression(x.Key), x.Value)).ToArray()) { }
public void Connect(User user) { _callback = OperationContext.Current.GetCallbackChannel <IMessageServiceCallback>(); if (_callback != null) { _clients.Add(user.UserId, _callback); _activeUsers.Add(user); _clients?.ToList().ForEach(client => client.Value.UsersConnected(_activeUsers)); } }
/// <summary> /// Merges the values. /// </summary> /// <param name="configValues">The config values.</param> /// <param name="recipient">The recipient.</param> /// <returns></returns> protected Dictionary<string, object> MergeValues( Dictionary<string, object> configValues, CommunicationRecipient recipient ) { Dictionary<string, object> mergeValues = new Dictionary<string, object>(); configValues.ToList().ForEach( v => mergeValues.Add( v.Key, v.Value ) ); if ( recipient != null ) { if ( recipient.Person != null ) { mergeValues.Add( "Person", recipient.Person ); } // Add any additional merge fields created through a report foreach ( var mergeField in recipient.AdditionalMergeValues ) { if ( !mergeValues.ContainsKey( mergeField.Key ) ) { mergeValues.Add( mergeField.Key, mergeField.Value ); } } } return mergeValues; }
public IronPythonComposablePart(IronPythonTypeWrapper typeWrapper, IEnumerable<Type> exports, IEnumerable<KeyValuePair<string, IronPythonImportDefinition>> imports) { _typeWrapper = typeWrapper; _instance = typeWrapper.Activator(); _exports = new List<ExportDefinition>(exports.Count()); _imports = new Dictionary<string, ImportDefinition>(imports.Count()); foreach (var export in exports) { var metadata = new Dictionary<string, object>() { {"ExportTypeIdentity", AttributedModelServices.GetTypeIdentity(export)} }; var contractName = AttributedModelServices.GetContractName(export); _exports.Add(new ExportDefinition(contractName, metadata)); } foreach (var import in imports) { var contractName = AttributedModelServices.GetContractName(import.Value.Type); var metadata = new Dictionary<string, Type>(); _imports[import.Key] = new IronPythonContractBasedImportDefinition( import.Key, contractName, AttributedModelServices.GetTypeIdentity(import.Value.Type), metadata.ToList(), import.Value.Cardinality, import.Value.IsRecomposable, import.Value.IsPrerequisite, CreationPolicy.Any); } }
private static string BuildBody(Dictionary <string, object> parameters, ContentType contentType) { StringBuilder bodyBuilder = new StringBuilder(); switch (contentType) { case ContentType.Form: { var paramList = parameters?.ToList() ?? new List <KeyValuePair <string, object> >(); for (int i = 0; i < paramList.Count; i++) { var theParamter = paramList[i]; string key = theParamter.Key; string value = theParamter.Value?.ToString(); string head = string.Empty; if (i != 0) { head = "&"; } bodyBuilder.Append($@"{head}{key}={value}"); } }; break; case ContentType.Json: { bodyBuilder.Append(JsonConvert.SerializeObject(parameters)); }; break; default: break; } return(bodyBuilder.ToString()); }
public static string HttpPost(string uri, Dictionary<string, string> parameters, List<KeyValuePair<string, string>> sensitiveStrings = null) { var asList = parameters.ToList(); return HttpPost(uri, asList, sensitiveStrings); }
private async Task <T> HandleSoapRequest <T>(string content, RequestType type, Dictionary <string, string> headers = null) { var client = clientFactory.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Post, config.Url); request.Content = new StringContent(content); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/soap+xml"); headers?.ToList() .ForEach(header => request.Content.Headers.Add(header.Key, header.Value)); var response = await client.SendAsync(request, GetCancellationToken()); var xmlData = ParseMtomString(await response.Content.ReadAsStringAsync(), type); var serializer = new XmlSerializer(typeof(T)); if (type == RequestType.Query) { xmlData = XElement.Parse(HttpUtility.HtmlDecode(xmlData.FirstNode.ToString())); } return((T)serializer.Deserialize(type == RequestType.Query ? xmlData.FirstNode.CreateReader() : xmlData.CreateReader())); }
private void _convertIntermediateResultsToFinal(BaseSentenceAlgorithmData result, int parentId, Dictionary<int, PredicatePartsStageHelperObject> intermediateResult, BaseSentenceAlgorithmData sourceData, int rootId, string rootType) { _recursionLevel++; var currentResults = intermediateResult.ToList().FindAll(x => x.Value.Parent == parentId); if (currentResults.Count > 0) { foreach (var currentResult in currentResults) { var currentSentenceElement = result.Sentence.Elements.Find(x => x.Id == currentResult.Key); if (_recursionLevel == 1) { rootId = currentResult.Key; rootType = sourceData.HelperData.GetRowByGUID(currentSentenceElement.GUID).Field<string>(HelperDataPredicateCorrectionSourceType.Name); } var predicatePartType = currentResult.Value.Type.ToString(); result.HelperData.AddOrUpdateCustomRow(currentSentenceElement.GUID, currentSentenceElement.Id, currentSentenceElement.Order, rootId, currentResult.Value.Parent, predicatePartType, currentResult.Value.Level, rootType); var newParentID = currentResult.Key; _convertIntermediateResultsToFinal(result, newParentID, intermediateResult, sourceData, rootId, rootType); _recursionLevel--; } } }
static void Main() { string text = String.Empty; using (StreamReader sr = new StreamReader(@"..\..\TextFile.txt")) { text = sr.ReadToEnd().ToLower(); } var matches = Regex.Matches(text, @"\w+"); Dictionary<string, int> occurances = new Dictionary<string, int>(); foreach (var word in matches) { string keyWord = word.ToString(); if (!occurances.Keys.Contains(keyWord)) { occurances.Add(keyWord, 1); } else { occurances[keyWord]++; } } List<KeyValuePair<string, int>> pairs = occurances.ToList(); pairs.Sort((x, y) => x.Value.CompareTo(y.Value)); foreach (var pair in pairs) { Console.WriteLine("{0} -> {1}", pair.Key, pair.Value); } }
private IList<KeyValuePair<string, string>> GetProductList() { Dictionary<string, string> dicProductList = new Dictionary<string, string>(); //橡膠 dicProductList.Add("JRU-橡膠", "81"); //黃金 dicProductList.Add("JAU-黃金", "11"); //小黃金 dicProductList.Add("JAM-小黃金", "16"); //白銀 dicProductList.Add("JSV-白銀", "12"); //白金 dicProductList.Add("JPL-//白金", "13"); //小白金 dicProductList.Add("JPM-小白金", "17"); //鈀金 dicProductList.Add("JPA-鈀金", "14"); //汽油 dicProductList.Add("JGL-汽油", "31"); //燃油 dicProductList.Add("JKE-燃油", "32"); //原油 dicProductList.Add("JCO-原油", "33"); return dicProductList.ToList(); }
private Dictionary<string, double> weightVector; //Implemented as a map since it is simpler #endregion Fields #region Constructors public AveragedPerceptron(string category, List<Dictionary<string, int>> docsOfCategory, List<Dictionary<string, int>> docsNotOfCat, double learningRate, int iterations, double bias, ISet<string> vocabulary) { if (learningRate <= 0 || learningRate >= 1) throw new ArgumentOutOfRangeException("0 < learningRate < 1 must be satisfied"); this.category = category; this.learningRate = learningRate; this.bias = bias; int trainingSize = docsNotOfCat.Count + docsOfCategory.Count; //Initialize the weightvectors weightVector = new Dictionary<string, double>(); foreach (var word in vocabulary) { weightVector.Add(word, 0); } averageWeightVector = new Dictionary<string, double>(weightVector); for (int i = 0; i < iterations; i++) { //Learn from training data foreach (var doc in docsOfCategory) { this.Learn(true, doc, i, iterations, trainingSize); } foreach (var doc in docsNotOfCat) { this.Learn(false, doc, i, iterations, trainingSize); } } List<KeyValuePair<string, double>> weightList = weightVector.ToList(); weightList.Sort((firstPair, nextPair) => { return firstPair.Value.CompareTo(nextPair.Value); }); }
public static JsonArray GetPoiInformation(Location userLocation, int numberOfPlaces) { if (userLocation == null) return null; var pois = new List<JsonObject> (); for (int i = 0; i < numberOfPlaces; i++) { var loc = GetRandomLatLonNearby (userLocation.Latitude, userLocation.Longitude); var p = new Dictionary<string, JsonValue>(){ { "id", i.ToString() }, { "name", "POI#" + i.ToString() }, { "description", "This is the description of POI#" + i.ToString() }, { "latitude", loc[0] }, { "longitude", loc[1] }, { "altitude", 100f } }; pois.Add (new JsonObject (p.ToList())); } var vals = from p in pois select (JsonValue)p; return new JsonArray (vals); }
static void ShowBeautyNumber(string line) { line = line.ToLower(); string pattern = "[^a-z]"; string replacement = ""; Regex rgx = new Regex(pattern); string resultStr = rgx.Replace(line, replacement); Dictionary<char, int> myMap = new Dictionary<char, int>(); foreach(char ch in resultStr){ if(!myMap.ContainsKey(ch)){ myMap.Add(ch,0); } myMap[ch] += 1; } List<KeyValuePair<char, int>> myList = myMap.ToList(); myList.Sort((firstPair,nextPair) =>{ return -firstPair.Value.CompareTo(nextPair.Value); }); int beauty = 26; int result = 0; foreach(KeyValuePair<char, int> itm in myList){ result += itm.Value*beauty; beauty--; } Console.WriteLine(result); }
public void NewValidationRulesShouldBeInTheRuleSetExceptBaselinedExceptionRules() { var validationRules = new Dictionary<object, string>(); var items = typeof(ValidationRules).GetFields().Select(f=> new KeyValuePair<object, string>(f.GetValue(null), f.Name)); foreach (var item in items) { validationRules.Add(item.Key, item.Value); } var unFoundValidationRules = new List<object>(); foreach(var ruleSet in ValidationRuleSet.GetEdmModelRuleSet(new Version(4, 0))) { if (validationRules.ContainsKey(ruleSet)) { validationRules.Remove(ruleSet); } else { unFoundValidationRules.Add(validationRules); } } unFoundValidationRules.Should().HaveCount(0); // The 4 remaining rules are deprecated: // ComplexTypeMustContainProperties // OnlyEntityTypesCanBeOpen // ComplexTypeInvalidPolymorphicComplexType // ComplexTypeInvalidAbstractComplexType validationRules.ToList().Should().HaveCount(4); }
public VertexProgramStrategy(string graphComputer = null, int?workers = null, string persist = null, string result = null, ITraversal vertices = null, ITraversal edges = null, Dictionary <string, dynamic> configuration = null) { if (graphComputer != null) { Configuration["graphComputer"] = graphComputer; } if (workers != null) { Configuration["workers"] = workers; } if (persist != null) { Configuration["persist"] = persist; } if (result != null) { Configuration["result"] = result; } if (vertices != null) { Configuration["vertices"] = vertices; } if (edges != null) { Configuration["edges"] = edges; } configuration?.ToList().ForEach(x => Configuration[x.Key] = x.Value); }
static void Main(string[] args) { var matches = GetWords(); Dictionary<string, int> wordOccurance = new Dictionary<string, int>(); foreach (var word in matches) { string strWord = word.ToString(); if (wordOccurance.ContainsKey(strWord)) { wordOccurance[strWord] += 1; } else { wordOccurance.Add(strWord, 1); } } List<KeyValuePair<string, int>> wordPairs = wordOccurance.ToList(); wordPairs.Sort((x, y) => x.Value.CompareTo(y.Value)); foreach (var entry in wordPairs) { Console.WriteLine("{0}: {1}", entry.Key, entry.Value); } }
public List<KeyValuePair<string, double>> RankedResults() { List<Document> documents = new List<Document>(); HashSet<string> dataSet = new HashSet<string>(); foreach (var result in results) { Document d = new Document(result); documents.Add(d); foreach (var term in d.tokens()){ dataSet.Add(term); } } //Build Document Vectors Dictionary<string, Vector> documentVectors = new Dictionary<string, Vector>(); foreach (var document in documents) { documentVectors.Add(document.ToString(), new Vector(dataSet, document)); } //Build Query Vector Query query = new Query(queryString); Vector queryVector = new Vector(dataSet, query); Dictionary<string, double> relevance = new Dictionary<string, double>(); foreach (var documentVector in documentVectors) { relevance.Add(documentVector.Key, Vector.GetSimilarityScore(queryVector, documentVector.Value)); } //Sort result by most relevant List<KeyValuePair<string, double>> myList = relevance.ToList(); return myList; }
public static void Main() { string text = @"C# is not C++, not PHP and not Delphi! Write a program that extracts from a given text all palindromes, e.g. ""ABBA"", ""lamal"", ""exe""."; //Console.WriteLine("Please enter your text:"); //string text = Console.ReadLine(); string regex = @"[A-Z]+"; Dictionary<string, int> wordOccurrences = new Dictionary<string, int>(); MatchCollection matches = Regex.Matches(text, regex, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); foreach (Match match in matches) { if (wordOccurrences.ContainsKey(match.Value)) { wordOccurrences[match.Value]++; } else { wordOccurrences.Add(match.Value, 1); } } // var sortedDictionary = (from entry in wordOccurrences orderby entry.Key ascending select entry).ToDictionary(pair => pair.Key, pair => pair.Value); List<KeyValuePair<string, int>> sortedDictionary = wordOccurrences.ToList(); sortedDictionary.Sort((x, y) => x.Key.CompareTo(y.Key)); foreach (KeyValuePair<string, int> wordEntry in sortedDictionary) { Console.WriteLine("{0}: {1}", wordEntry.Key, wordEntry.Value); } }
public override String run(CommandInfo cmdInfo, Bot bot) { String output = "Here are the items you have duplicates of:"; dynamic json = Util.CreateSteamRequest(String.Format("http://api.steampowered.com/ITFItems_440/GetPlayerItems/v0001/?key=" + bot.apiKey + "&SteamID={0}&format=json",cmdInfo.getSteamid().ConvertToUInt64()),"GET"); int limit = cmdInfo.getArg(0, 2); Dictionary<int, MutableInt> freq = new Dictionary<int, MutableInt>(); foreach (dynamic i in json.result.items.item) { int defindex = i.defindex; if (freq.ContainsKey(defindex)) { freq[defindex].increment(); } else { freq.Add(defindex, new MutableInt()); } } List<KeyValuePair<int, MutableInt>> myList = freq.ToList(); myList.Sort((firstPair,nextPair) => { return firstPair.Value.CompareTo(nextPair.Value); } ); foreach (KeyValuePair<int, MutableInt> entry in myList) { if (entry.Value.get() < limit) { break; } ItemInfo itemInfo = Util.getItemInfo(entry.Key); output += "\n" + itemInfo.getName() + " x" + entry.Value.get(); } return output; }
public override Dictionary<string, double> SuggestNItems(Dictionary<string, SuggestorCollection> collections, SuggestorCollection compareCollection, int n) { if (compareCollection.CollectionLines.Count == 0) return null; Dictionary<string, double> itemAggregation = new Dictionary<string, double>(); // Find top similar collections Dictionary<SuggestorCollection, double> topCollections = SuggestNCollections(collections.Values.ToList(), compareCollection, n); foreach (SuggestorCollection collection in topCollections.Keys) { foreach (string itemNo in collection.CollectionLines.Keys) { if (compareCollection.CollectionLines.ContainsKey(itemNo)) continue; // Ignore items that are already in basket if (!(itemAggregation.ContainsKey(itemNo))) itemAggregation.Add(itemNo, 1); itemAggregation[itemNo]++; //itemAggregation[itemNo] += topInvoices[invoice] * 1.0; } } List<KeyValuePair<string, double>> itemAggregationList = itemAggregation.ToList(); // Sort dictionary by value itemAggregationList.Sort((firstPair, nextPair) => { return firstPair.Value.CompareTo(nextPair.Value); }); itemAggregationList.Reverse(); itemAggregation = itemAggregationList.ToDictionary(pair => pair.Key, pair => pair.Value); return itemAggregation; }
public void CreateFlowWithAssignId(Guid flowId, string flowName, User originator, string title, Dictionary<string, string> args = null, string comment = null) { var trans = TransactionManager.BeginTransaction(); try { var flow = new Flow(); flow.FlowStatus = FlowStatus.Instance; var flowType = _flowTypeRepository.GetByTypeName(flowName); if (flowType == null) throw new Exception(string.Format("{0}的流程类型不存在", flowName)); flow.FlowType = flowType; flow.Id = flowId; flow.Title = title; args = args ?? new Dictionary<string, string>(); args.ToList().ForEach(o => flow.FlowDataFields.Add(new FlowDataField { Name = o.Key, Value = o.Value })); flow.RecordDescription.CreateBy(originator); flow.UserOfFlowAdmin = originator; var history = new FlowHistory() { Comment = comment, Action = "提交流程", Stage = "发起流程" }; history.RecordDescription.CreateBy(originator); flow.FlowHistories.Add(history); _flowRepository.Save(flow); trans.Commit(); } catch (Exception) { trans.Rollback(); throw; } }
public static ControlKeyStates ToControlKeyState( this Console.ConsoleControlKeyStates state ) { var map = new Dictionary<Console.ConsoleControlKeyStates, ControlKeyStates> { {ConsoleControlKeyStates.CapsLockOn, ControlKeyStates.CapsLockOn}, {ConsoleControlKeyStates.EnhancedKey, ControlKeyStates.EnhancedKey}, {ConsoleControlKeyStates.LeftAltPressed, ControlKeyStates.LeftAltPressed}, {ConsoleControlKeyStates.LeftCtrlPressed, ControlKeyStates.LeftCtrlPressed}, {ConsoleControlKeyStates.NumLockOn, ControlKeyStates.NumLockOn}, {ConsoleControlKeyStates.RightAltPressed, ControlKeyStates.RightAltPressed}, {ConsoleControlKeyStates.RightCtrlPressed, ControlKeyStates.RightCtrlPressed}, {ConsoleControlKeyStates.ScrollLockOn, ControlKeyStates.ScrollLockOn}, {ConsoleControlKeyStates.ShiftPressed, ControlKeyStates.ShiftPressed}, }; ControlKeyStates controlKeyState = 0; map.ToList().ForEach(pair => { if (0 != (pair.Key & state)) { controlKeyState |= pair.Value; } }); return controlKeyState; }
/// <summary> /// Json Çıktısı Olarak AppData İçindeki İlleri Servisten Yayınlıyoruz /// </summary> /// <param name="context"></param> public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/json"; Dictionary<int,string> iller = new Dictionary<int, string>(); using (StreamReader stramreader = new StreamReader(context.Server.MapPath("App_Data\\veri.txt"))) { while (stramreader.Peek()>=0) { try { string[] satir = stramreader.ReadLine().ToString().Split(' '); iller.Add(int.Parse(satir[0].Trim()), satir[1]); } catch (Exception) { } } } context.Response.Write(JsonConvert.SerializeObject(iller.ToList())); }
public void WithArguments(Dictionary<string, object> args) { if (args == null) return; Arguments = args.ToList(); }
public List<KeyValuePair<int, float>> Ensenble(List<IList<Tuple<int, float>>> list) { var novaList = new Dictionary<int, float>(); //Vamos criar uma nova lista com o score junto foreach (IList<Tuple<int, float>> aLista in list) { foreach (Tuple<int, float> item in aLista) { if (novaList.ContainsKey(item.Item1)) { if (novaList[item.Item1] < item.Item2) { novaList[item.Item1] = item.Item2; } } else { novaList.Add(item.Item1, item.Item2); } } } List<KeyValuePair<int, float>> listRetorno = novaList.ToList(); listRetorno.Sort((firstPair, nextPair) => { return nextPair.Value.CompareTo(firstPair.Value); }); return listRetorno; }
protected void btnSubmit_Click(object sender, EventArgs e) { tableColumns = (Dictionary<string, List<DB.Column>>)Session["tableColumns"]; if (null == tableColumns) return; var dbo = new DB.DBCalls(); tableColumns.ToList().ForEach(table => { var query = "alter table [" + client + "].[" + table.Key + "] add "; table.Value.ForEach(column => { query += "[" + column.ColumnName + "] " + column.DataType.ToString(); if ((column.DataType == System.Data.SqlDbType.VarChar) || (column.DataType == System.Data.SqlDbType.NVarChar) || (column.DataType == System.Data.SqlDbType.Char) || (column.DataType == System.Data.SqlDbType.Char) || (column.DataType == System.Data.SqlDbType.NChar)) { query += "(" + column.Length.ToString() + ")"; } query += (column.IsNullable) ? " null " : " not null "; query += (string.IsNullOrEmpty(column.DefaultValue)) ? "" : " default '" + column.DefaultValue + "'"; query += ", "; }); query = query.Remove(query.LastIndexOf(","), 2); try { dbo.ExecuteString(query); } catch (System.Data.SqlClient.SqlException sqlE) { } }); }
/// <summary> /// 构建完全Url /// </summary> /// <param name="url">Url</param> /// <param name="parameters">参数</param> /// <returns></returns> public static string BuildGetFullUrl(string url, Dictionary <string, object> parameters = null) { StringBuilder paramBuilder = new StringBuilder(); var paramList = new List <KeyValuePair <string, object> >(); paramList = parameters?.ToList(); for (int i = 0; i < paramList.Count; i++) { var theParamter = paramList[i]; string key = theParamter.Key; string value = theParamter.Value.ToString(); string head = string.Empty; if (i == 0 && !UrlHaveParam(url)) { head = "?"; } else { head = "&"; } paramBuilder.Append($@"{head}{key}={value}"); } return(url + paramBuilder.ToString()); }
void onBonusesLoaded(Dictionary<long, string> difficultyIds) { List<KeyValuePair<long, string>> list = difficultyIds.ToList(); list.Sort((first, second) => first.Key.CompareTo(second.Key)); foreach (KeyValuePair<long, string> pair in list) addButton(pair); }
static void Main(string[] args) { Console.Write("Enter array size: "); int size = int.Parse(Console.ReadLine()); int[] array = new int[size]; Console.WriteLine(); for (int i = 0; i < size; i++) { Console.Write("Enter array[{0}]: ", i); array[i] = int.Parse(Console.ReadLine()); } Dictionary<int, int> occurences = new Dictionary<int, int>(); for(int i = 0; i < size; i ++) { if(occurences.ContainsKey(array[i])) { occurences[array[i]]++; } else { occurences.Add(array[i], 1); } } List<KeyValuePair<int, int>> sorted = occurences.ToList(); sorted.Sort((x, y) => x.Value.CompareTo(y.Value)); Console.WriteLine("The most frequent number is {0} -> {1} times", sorted.Last().Key, sorted.Last().Value); Console.ReadLine(); }
public static void SetExtractOutput(DependencyObject dependencyObject, Dictionary<string, string> list) { MainWindow mainWindow = MainContext.GetMainWindow(dependencyObject); LayoutAnchorable documentPane = mainWindow.MainDockingManager.Layout.Descendents() .OfType<LayoutAnchorable>() .FirstOrDefault(c => c.ContentId == "OutputContent"); if (documentPane != null) { if (documentPane.IsAutoHidden) { documentPane.ToggleAutoHide(); } var content = documentPane.Content as OutputPageUserControl; if (content != null) { LayoutDocumentPane panes = content.OutputDockingManager.Layout.Descendents().OfType<LayoutDocumentPane>().FirstOrDefault(); for (; panes.ChildrenCount > 0; ) { LayoutContent pane = panes.Children[0]; pane.Close(); } foreach (var pair in list.ToList()) { var outputContentUserControl = new OutputContentUserControl(); outputContentUserControl.ContentTextEditor.Text = pair.Value; UtilityManager.CreateTab(content.OutputDockingManager, outputContentUserControl, pair.Key); } } } }
public static bool Send(string modelName, Dictionary <string, string> toDictionary, Dictionary <string, string> ccDictionary, Dictionary <string, string> bccDictionary, string subject, string body, string[] file, MemoryStream msFile) { if (!BaseHelper.IsEmail) { return(true); } string sendMsg; bool result = SendMailBll.Send2(toDictionary, ccDictionary, bccDictionary, subject, body, file, msFile, out sendMsg); ccDictionary?.ToList().ForEach(c => toDictionary.Add(c.Key, c.Value)); new EmailLog().AddEntity(new Entity.EmailLog { ModelName = modelName, To = string.Join(",", (toDictionary.ToList()).Select(c => c.Key + ";")), Subject = subject, Body = body, CreateTime = DateTime.Now, SendResult = result, Message = sendMsg }); return(result); }
/// <inheritdoc/> public ISmsSendResult SendSms(ISms sms) { try { if (!sms?.IsValid(_smsServiceConfig) ?? true) { throw new Exception("Invalid SMS request."); } var paramDict = new Dictionary <string, string>(); paramDict.Add(_smsServiceConfig.MessageMask, sms.Message); paramDict.Add(_smsServiceConfig.RecepientMask, sms.Recepient); _smsServiceConfig?.RequestParameters?.ToList()?.ForEach(x => paramDict?.Add(x.Key, x.Value)); HttpWebRequest request = null; string postData = null; byte[] postBytes = null; switch (_smsServiceConfig.RequestContentType) { case RequestContentType.FormData: NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(string.Empty); paramDict?.ToList()?.ForEach(x => outgoingQueryString.Add(x.Key, x.Value)); postData = outgoingQueryString?.ToString(); postBytes = _smsServiceConfig.Encoding.GetBytes(postData); request = (HttpWebRequest)WebRequest.Create(_smsServiceConfig.BaseUrl); request.ContentType = "application/form-data"; break; case RequestContentType.JSON: postData = JsonConvert.SerializeObject(paramDict); postBytes = _smsServiceConfig.Encoding.GetBytes(postData); request = (HttpWebRequest)WebRequest.Create(_smsServiceConfig.BaseUrl); request.ContentType = "application/json"; break; default: //Handles Enums.RequestContentType.URL too string @params = String.Join("&&", paramDict?.Select(x => $"{x.Key}={x.Value}")?.ToArray()); string url = _smsServiceConfig.BaseUrl + '?' + @params; request = (HttpWebRequest)WebRequest.Create(url); break; } request.Method = _smsServiceConfig.RequestMethod.Method; if (postBytes != null) { using (var stream = request.GetRequestStream()) { stream.Write(postBytes, 0, postBytes.Length); } } HttpWebResponse response = request.GetResponse() as HttpWebResponse; return(new SmsSendResult(sms.Recepient, response.StatusCode, response.GetResponseStream())); } catch (Exception e) { return(new SmsSendResult(sms.Recepient, e.Message)); } }
static void Main(string[] args) { WriteHeader("Jedan objekat, klasika"); var myCat = new Cat("Garfield"); myCat.Walk(); myCat.Talk(); WriteHeader("Jedan objekat, oneliner"); new Cat("Garfield").Walk().Talk(); WriteHeader("Više objekata (znamo tip u compile time)"); var animals = new List<Animal> { new Cat("Garfield"), new Dog("Locko"), new Dog("Pajko") }; foreach (var animal in animals) { animal.Walk(); animal.Talk(); } WriteHeader("Više objekata, tip se određuje u runtime"); var animalsNameType = new Dictionary<string, string> { {"Garfield", "Cat"}, {"Locko", "Dog"}, {"Pajko", "Dog"} }; foreach (var pair in animalsNameType) { var animal = AnimalFactory.Create(pair.Value, pair.Key); animal.Walk(); animal.Talk(); } WriteHeader("Više objekata, tip se određuje u runtime, oneliner"); animalsNameType.ToList().ForEach( pair => AnimalFactory.Create(pair.Value, pair.Key) .Walk() .Talk() ); Console.Read(); }
private static void WriteAnswer(Dictionary<City, int> liderCities) { using (var stream = Console.Out) { foreach (var res in liderCities.ToList().SortByNameCity()) stream.WriteLine("{0} {1}", res.Key.Name, res.Value); } }
private Dictionary <string, string> MergeWithOriginalHeaders(Dictionary <string, string> optionalHeaders) { var headers = new Dictionary <string, string>(); TransportMessage?.Headers.ToList().ForEach(x => headers.Add(x.Key, x.Value)); optionalHeaders?.ToList().ForEach(x => headers[x.Key] = x.Value); return(headers); }
public static List<string> FindDuplicateFeeds(List<Dictionary<string,string>> list_dict_str) { var feedurls = new Dictionary<string, int>(); foreach (var dict in list_dict_str) feedurls.IncrementOrAdd(dict["feedurl"]); var dupes = feedurls.ToList().FindAll(x => Convert.ToInt16(x.Value) > 1); return dupes.Select(x => x.Key).ToList(); }
public static IServiceProvider GetMigrationExampleServiceProvider( SupportedDatabaseTypes databaseType = SupportedDatabaseTypes.Postgres, Dictionary <string, string> additionalOverrideConfig = null) { var overrideConfig = OverrideConfig.GetInMemoryOverrideConfig(databaseType); additionalOverrideConfig?.ToList().ForEach(x => overrideConfig[x.Key] = x.Value); return(MigrationBuilder.BuildMigration(databaseType, overrideConfig)); }
/// <summary> /// Saves the session configuration. /// </summary> /// <param name="name">The session configuration name.</param> /// <param name="uri">The session configuration uri.</param> /// <param name="appData">The session configuration data as a dictionary.</param> /// <returns>A <see cref="SessionConfig"/> object set with the saved configuration data.</returns> public static SessionConfig Save(string name, string uri, Dictionary <string, string> appData) { ValidateName(name); ValidateUri(uri); SessionConfig sessionConfig = new SessionConfig(name, uri); appData?.ToList().ForEach(i => sessionConfig.SetAppData(i.Key, i.Value)); return(Save(sessionConfig)); }
public TestRunner(string testExePath, ITestOutputHelper _outputHelper = null, bool redirectError = false, bool redirectInput = false, Dictionary <string, string> envVars = null) { startInfo = new ProcessStartInfo(CommonHelper.HostExe, testExePath); startInfo.UseShellExecute = false; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = redirectError; startInfo.RedirectStandardInput = redirectInput; envVars?.ToList().ForEach(item => startInfo.Environment.Add(item.Key, item.Value)); outputHelper = _outputHelper; }
public static IServiceProvider GetNServiceBusServiceProvider(Dictionary <string, string> additionalOverrideConfig = null) { var overrideConfig = OverrideConfig.GetOverrideConfig(); additionalOverrideConfig?.ToList().ForEach(x => overrideConfig[x.Key] = x.Value); var provider = new ServiceCollection() .ConfigureWithNServiceBusHost(overrideConfig) .BuildServiceProvider(); return(provider); }
private void InitTaskBuilderMock(Dictionary <string, object> expectedConfig = null) { Dictionary <string, object> expectedEntries = new Dictionary <string, object> { { "CopyFromPath", Source }, { "CopyToPath", Target } }; expectedConfig?.ToList().ForEach(pair => expectedEntries.Add(pair.Key, pair.Value)); _taskBuilderMock = new TaskBuilderMock(expectedEntries); }
public static IServiceProvider GetMigrationServiceProvider(Dictionary <string, string> additionalOverrideConfig = null) { var overrideConfig = OverrideConfig.GetOverrideConfig(); additionalOverrideConfig?.ToList().ForEach(x => overrideConfig[x.Key] = x.Value); var provider = new ServiceCollection() .ConfigureWithSafeRebusMessageHandlerMigration(overrideConfig) .BuildServiceProvider(); return(provider); }
public static IConfiguration GetDefaultConfiguration(SupportedDatabaseTypes databaseType = DefaultDatabaseType, Dictionary <string, string> additionalOverrideConfig = null) { var overrideConfig = GetOverrideConfig(databaseType); additionalOverrideConfig?.ToList().ForEach(x => overrideConfig[x.Key] = x.Value); var configuration = ConfigBuilderExtensions.GetDefaultConfiguration(overrideConfig); return(configuration); }
public void Connect(User user) { _callBack = OperationContext.Current.GetCallbackChannel <IMessaseServiceCallBack>(); if (_callBack != null) { _clients.Add(user.UserID, _callBack); Users.Add(user); _clients?.ToList().ForEach(c => c.Value.UserConnected(Users)); Console.WriteLine($"{user.Name} just connected"); } }
public void Connect(User user) { callback = OperationContext.Current.GetCallbackChannel <IServiceCallback>(); if (callback != null) { clients.Add(user.UserId, callback); users.Add(user); clients?.ToList().ForEach(client => client.Value.UserConnected(users)); Debug.WriteLine($"{user.Name} just connected"); } }
public XmlNode ToXML() { var xml = Fetch.Xml.CreateElement(name); AddXMLProperties(xml); if (IncludeUnknown) { unknowsAttributes?.ToList().ForEach(u => xml.AddAttribute(u.Key, u.Value)); // More works is needed... // unknowsNodes?.ToList().ForEach(u => xml.AppendChild(u.Value.CloneNode(true))); } return(xml); }
private async Task <HttpResponseMessage> ExecuteEndpoint(Api api, Endpoint endpoint, Dictionary <string, string> parameters = null, byte[] body = null) { var path = endpoint.Path; parameters?.ToList().ForEach(p => path = path.Replace($"%{p.Key}%", p.Value)); var request = $"{api.BaseUrl}/{path}" .WithApiEndpoint(api, endpoint) .WithHeaders(api.Headers) .WithHeaders(endpoint.Headers); switch (api.Authentication.Type) { case AuthenticationType.Basic: request = request.WithBasicAuth(api.Authentication.BasicUsername, api.Authentication.BasicPassword); break; case AuthenticationType.Bearer: request = request.WithOAuthBearerToken(api.Authentication.Token); break; case AuthenticationType.Header: request = request.WithHeader(api.Authentication.HeaderName, api.Authentication.Token); break; } _logger.LogInformation("Request path: {0}", request.Url); _logger.LogDebug("Body {0}", body); switch (endpoint.Method) { case RequestMethod.Get: return(await request.GetAsync()); case RequestMethod.Post: return(await request.PostAsync(new ByteArrayContent(body))); case RequestMethod.Put: return(await request.PutAsync(new ByteArrayContent(body))); case RequestMethod.Delete: return(await request.DeleteAsync()); case RequestMethod.Patch: return(await request.PatchAsync(new ByteArrayContent(body))); default: throw new ArgumentOutOfRangeException(); } }
/// <summary> /// Creates a HttpClient object for every endpoint /// </summary> /// <param name="url">The URL to the end point</param> /// <param name="customHeaders">Any custom headers that needs to be added to the HttpClient</param> /// <param name="timeOutInMilliseconds">Http time in milliseconds, will be default to 100,000ms (10s)</param> /// <returns>The HttpClient instance</returns> public static HttpClient GetOrCreateClient(string url, Dictionary <string, string> customHeaders = null, int timeOutInMilliseconds = 10000) { var uri = new Uri(url); var client = new HttpClient() { BaseAddress = uri, MaxResponseContentBufferSize = int.MaxValue, Timeout = TimeSpan.FromMilliseconds(timeOutInMilliseconds), }; customHeaders?.ToList().ForEach(h => client.AddOrUpdateHeader(h.Key, h.Value)); return(client); }
public void Dispose() { _analyzerLogsCollection?.CompleteAdding(); _outputHandlers?.ToList().ForEach(aoh => aoh.Value?.Dispose()); _ruleHandlers?.ToList().ForEach(rh => rh.Value?.Dispose()); _outputHandlers?.Clear(); _ruleHandlers?.Clear(); _scheduleHandlers?.Clear(); }
/// <summary> /// Registers the library helper. /// </summary> /// <param name="jarFile">The jar file.</param> /// <param name="config">The configuration.</param> /// <param name="registration">The registration.</param> /// <returns></returns> private ExecutionResult RegisterLibraryHelper(string jarFile, IConfigurationReader config, Dictionary <string, JniMetadata> registration) { var r = registration?.ToList(); var libraryId = Guid.NewGuid(); var retval = ExecutionResult.Empty; var c = (CustomConfigReader)config.Configuration; var assembly = Path.GetFileName(jarFile).Replace(".jar", ".dll"); var assemblyLocation = $@"{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}\Proxies\{assembly}"; // If connection is closed then we'll open it if (_dataContext.Database.Connection.State == System.Data.ConnectionState.Closed) { _dataContext.Database.Connection.Open(); } using (var transaction = _dataContext.Database.Connection.BeginTransaction()) { // We first register our proxy assembly _dataContext.DynamicLibrary.Add(new DynamicLibrary() { AssemblyName = assembly, IsHostingEnabled = true, JarFileLocation = jarFile, AssemblyLocation = assemblyLocation, JarFileName = Path.GetFileName(jarFile), LibraryId = libraryId.ToString(), RegisteredDate = EpochTime }); try { r?.ForEach(_ => ProvisionTablesAtRegistration(_, jarFile, assembly, c, libraryId)); _dataContext.SaveChanges(); transaction.Commit(); retval.IsSuccess = true; } catch { transaction.Rollback(); retval.IsSuccess = false; } finally { _dataContext.Database.Connection.Close(); } } return(retval); }
protected (CalamariResult result, IVariables variables) RunScript(string scriptName, Dictionary <string, string> additionalVariables = null, Dictionary <string, string> additionalParameters = null, string sensitiveVariablesPassword = null, IEnumerable <string> extensions = null) { var variablesFile = Path.GetTempFileName(); var variables = new CalamariVariables(); variables.Set(ScriptVariables.ScriptFileName, scriptName); variables.Set(ScriptVariables.ScriptBody, File.ReadAllText(GetFixtureResource("Scripts", scriptName))); variables.Set(ScriptVariables.Syntax, scriptName.ToScriptType().ToString()); additionalVariables?.ToList().ForEach(v => variables[v.Key] = v.Value); using (new TemporaryFile(variablesFile)) { var cmdBase = Calamari() .Action("run-script"); if (sensitiveVariablesPassword == null) { variables.Save(variablesFile); cmdBase = cmdBase.Argument("variables", variablesFile); } else { variables.SaveEncrypted(sensitiveVariablesPassword, variablesFile); cmdBase = cmdBase.Argument("sensitiveVariables", variablesFile) .Argument("sensitiveVariablesPassword", sensitiveVariablesPassword); } if (extensions != null) { cmdBase.Argument("extensions", string.Join(",", extensions)); } cmdBase = (additionalParameters ?? new Dictionary <string, string>()).Aggregate(cmdBase, (cmd, param) => cmd.Argument(param.Key, param.Value)); var output = Invoke(cmdBase, variables); return(output, variables); } }
/// <summary> /// Assembles the 6502 asm provided into raw bytes. /// </summary> /// <param name="origin">The address this code will run at. e.g. 0x8000. Must be between 0 and 0xFFFF.</param> /// <param name="name">A human-readable reference, e.g. a subroutine name.</param> /// <param name="asm">the 6502 asm source, including newline characters.</param> /// <example> /// var newBytes = InlineAssembler.assemble(0x8000, "FixTheThing", @" /// LDA $30 /// JMP $8044 /// "); /// </example> /// <exception cref="AssemblyError">if something goes wrong.</exception> public byte[] Assemble(int origin, string name, string asm, Dictionary <string, int> variables = null, Dictionary <string, int> labels = null) { if (origin < 0 || origin > 0xFFFF) { throw new ArgumentOutOfRangeException(nameof(origin)); } // it is very important for caseSensitive to be false here. it interprets even instructions as case-sensitive with it on. var options = new AssemblyOptions(); var controller = new PatchController(this, options); controller.AddAssembler(new Asm6502(controller)); // have to do this every pass because each one clears everything out every time... controller.OnBeginningOfPass += delegate(object sender, EventArgs e) { // load up the symbol table variables?.ToList().ForEach(pair => controller.Symbols.Variables.SetSymbol(pair.Key, pair.Value, isStrict: false)); labels?.ToList().ForEach(pair => controller.Symbols.Labels.SetSymbol(pair.Key, pair.Value, isStrict: false)); // set PC controller.Output.SetPC(origin); }; var result = controller.Assemble(name, asm); if (ShowWarningsInConsole) { controller.Log.DumpAll(); } else if (controller.Log.HasErrors) { controller.Log.DumpErrors(); } if (result is null) { throw new AssemblyError($"Unable to assemble {name} at {origin}; see console output for details"); } return(result); }
public void Conectarse(Jugador jugador) { if (!BuscarClientePorNombre(jugador.nickName)) { callBackActual = OperationContext.Current.GetCallbackChannel <ILoginServiceCallback>(); if (callBackActual != null) { clientes.Add(jugador, callBackActual); jugadores.Add(jugador); clientes?.ToList().ForEach(c => c.Value.UsuariosConectados(jugadores)); foreach (Jugador c in jugadores) { Console.WriteLine(c.nickName); } Console.WriteLine($"{jugador.nickName} se ha conectado"); } } }
public static CSOMOperation CreateTerm(this CSOMOperation operation, string name , Guid?guid = null, int lcid = 1033, IEnumerable <Tuple <string, int> > descriptions = null , Dictionary <string, string> customProperties = null, Dictionary <string, string> localProperties = null) { var op = operation.TaxonomyOperation; op.LastTerm = op.LastTermSet.CreateTerm(name, lcid, guid ?? Guid.NewGuid()); if (descriptions != null) { foreach (var description in descriptions) { op.LastTerm.SetDescription(description.Item1, description.Item2); } } customProperties?.ToList().ForEach(x => op.LastTerm.SetCustomProperty(x.Key, x.Value)); localProperties?.ToList().ForEach(x => op.LastTerm.SetLocalCustomProperty(x.Key, x.Value)); return(operation); }
public static async Task <HttpResponseMessage> PutObjectAsync <TRequest, TResponse>(this HttpClient client, string url, TRequest content, TraceWriter log, Dictionary <string, string> customHeaders = null) where TResponse : new() { try { var serialisedPayload = typeof(TRequest) == typeof(string) ? content as string : JsonConvert.SerializeObject(content, CamelCaseSettings); var httpContent = new StringContent(serialisedPayload); customHeaders?.ToList().ForEach(h => httpContent.Headers.AddOrUpdateHeader(h.Key, h.Value)); var response = await client.PutAsync(url, httpContent); return(response); } catch (Exception ex) { log.Error($"Could not send post requst to {url} with error {ex.Message}"); throw; } }
/// <summary> /// 请求数据 /// 注:若使用证书,推荐使用X509Certificate2的pkcs12证书 /// </summary> /// <param name="method">请求方法</param> /// <param name="url">URL地址</param> /// <param name="paramters">参数</param> /// <param name="headers">请求头信息</param> /// <param name="contentType">请求数据类型</param> /// <param name="cerFile">证书</param> /// <returns></returns> public static string RequestData(HttpMethod method, string url, Dictionary <string, object> paramters = null, Dictionary <string, string> headers = null, ContentType contentType = ContentType.Form, X509Certificate cerFile = null) { if (string.IsNullOrEmpty(url)) { throw new Exception("请求地址不能为NULL或空!"); } string newUrl = url; if (method == HttpMethod.Get) { StringBuilder paramBuilder = new StringBuilder(); var paramList = new List <KeyValuePair <string, object> >(); paramList = paramters?.ToList() ?? new List <KeyValuePair <string, object> >(); for (int i = 0; i < paramList.Count; i++) { var theParamter = paramList[i]; string key = theParamter.Key; string value = theParamter.Value.ToString(); string head = string.Empty; if (i == 0 && !UrlHaveParam(url)) { head = "?"; } else { head = "&"; } paramBuilder.Append($@"{head}{key}={value}"); } newUrl = url + paramBuilder.ToString(); } string body = BuildBody(paramters, contentType); return(RequestData(method.ToString().ToUpper(), newUrl, body, GetContentTypeStr(contentType), headers, cerFile)); }
private static Dictionary <string, object> GenerateValues <T>(T row, NpgsqlTypeProjection <T> typeProjection, Dictionary <string, object> valueOverrides, IEnumerable <string> excludeColumns = null) { var values = typeProjection.TypePropertyProjections.ToDictionary( tpp => tpp.ColumnName, tpp => { switch (tpp.GetPropertyValue(row)) { case string valueStr: return(valueStr.Replace("\u0000", "")); case object value: return(value); } return(null); } ); valueOverrides?.ToList().ForEach(kvp => { if (values.ContainsKey(kvp.Key)) { values[kvp.Key] = kvp.Value; } else { values.Add(kvp.Key, kvp.Value); } }); if (excludeColumns != null) { foreach (var excludedColumn in excludeColumns) { values.Remove(excludedColumn); } } return(values); }