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"; }
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); }); }
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); }
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 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(); }
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 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 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); } }
/// <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 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); } }
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); }
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) { } }); }
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 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; }
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 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; } }
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); } }
public void WithArguments(Dictionary<string, object> args) { if (args == null) return; Arguments = args.ToList(); }
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); }
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(); }
/// <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 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 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; }
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); } }
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(); }