private Dictionary<char, int> TenMostFrequentChar(string value) { var charDictionary = new Dictionary<char, int>(); foreach (var x in value) { if (charDictionary.ContainsKey(x)) { charDictionary[x] = charDictionary[x] + 1; } else { charDictionary.Add(x, 1); } } //This will order the Dictionary by the values charDictionary = charDictionary.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value); if (charDictionary.Count < 10) { return charDictionary; } else { return charDictionary.Take(10).ToDictionary(x => x.Key, x => x.Value); } }
public static List<Recette> SelectBestRecettes(List<Recette> recettes, List<Product> products, int limit = 3) { List<Tuple<int, List<string>>> lesMotsDesProduits = products.Select(o => new Tuple<int, List<string>>(o.ID, o.Libelle.Split(' ').ToList())).ToList(); List<Tuple<int, List<List<string>>>> lesMotsDesRecettes = recettes.Select(o => new Tuple<int, List<List<string>>>(o.ID, o.Ingrédients.Select(i => i.Split(' ').ToList()).ToList())).ToList(); lesMotsDesProduits.ForEach(o => o.Item2.RemoveAll(i => uselessWords.Contains(i))); lesMotsDesRecettes.ForEach(o => o.Item2.ForEach(l => l.RemoveAll(s => uselessWords.Contains(s)))); Dictionary<int, int> classementRecette = new Dictionary<int, int>(); foreach (Tuple<int, List<List<string>>> recette in lesMotsDesRecettes) { foreach (List<string> ingredient in recette.Item2) { if (!classementRecette.ContainsKey(recette.Item1)) { classementRecette[recette.Item1] = 0; } classementRecette[recette.Item1] += lesMotsDesProduits.Sum(o => o.Item2.Where(i => ingredient.Contains(i)).Count()); } } classementRecette = classementRecette.OrderBy(o => o.Value).ToDictionary(o => o.Key, i => i.Value); return classementRecette.Values.All(o => o == 0) ? null : classementRecette.Take(limit).Select(r => recettes.Where(o => o.ID == r.Key && r.Value > 0).First()).ToList(); }
public Bitmap CreateCloud(Config config, Dictionary<string, int> words) { var bitmap = new Bitmap(config.ConfigModel.Width, config.ConfigModel.Height); using (var graphics = Graphics.FromImage(bitmap)) { float height = 0; graphics.Clear(Color.FromName(config.ConfigModel.Background)); var sum = words.Take(config.ConfigModel.Count).Sum(x => x.Value); foreach (var word in words.Take(config.ConfigModel.Count)) { var wordHeight = (bitmap.Height/sum)*word.Value; DrawWord(word, graphics, wordHeight, height, config); height += wordHeight; } } return bitmap; }
private void SplitByRack(Dictionary<int, int> smpPlasmaSlices) { int totalSliceCnt = smpPlasmaSlices.Count; while (smpPlasmaSlices.Any()) { int remaining = smpPlasmaSlices.Count; int splitted = totalSliceCnt - remaining; var tmpPlasmaSlices = smpPlasmaSlices.Take(Math.Min(remaining, 16)).ToDictionary(x => x.Key, x => x.Value); allRackSmpPlasmaSlices.Add(tmpPlasmaSlices); var tmpPackageInfos = CreatePackInfo(tmpPlasmaSlices); allPackageExpectedInfos.Add(new Dictionary<Point, string>(tmpPackageInfos)); allPackageScannedInfos.Add(new Dictionary<Point, string>()); smpPlasmaSlices = smpPlasmaSlices.Except(tmpPlasmaSlices).ToDictionary(x => x.Key, x => x.Value); } ChangeRackIndex(0); }
/// <summary> /// CSVのデータからマップデータを作成する /// </summary> /// <param name="data"></param> /// <param name="num"></param> public void FittingMap(Dictionary <string, List <string> > data, int num) { //CSVデータからマップの部分のみ切り取り Dictionary <string, List <string> > tmp_data = data.Take(num).ToDictionary(k => k.Key, k => k.Value); //マップデータの作成 foreach (var v in tmp_data) { allMap.Add(new MapData( v.Key, int.Parse(v.Value[0]), data[v.Value[1]].ToArray() ) ); } }
void ScoreTableUpdate() { if (highScores.Count == 0) { return; } int num = highScores.Count; if (highScores.Count >= 5) { num = 5; } highScores = highScores.OrderByDescending(x => x.Value).ToDictionary(X => X.Key, X => X.Value); highScores = highScores.Take(num).ToDictionary(X => X.Key, X => X.Value); }
private static bool ParseArgs(IEnumerable <string> args, out FileSystemInfo map, out IDictionary <AntProxy, AppDomain> ants, bool checkSubFolder = true) { map = null; var antList = new Dictionary <AntProxy, AppDomain>(); var debug = false; foreach (var a in args) { if (a.Equals("debug", StringComparison.InvariantCultureIgnoreCase)) { debug = true; continue; } if (!File.Exists(a)) { if (checkSubFolder && Directory.Exists(a)) { ParseArgs(Directory.GetFiles(a), out var subMap, out var subAnts, false); map = subMap; foreach (var v in subAnts) { antList.Add(v.Key, v.Value); } } continue; } var info = new FileInfo(a); if (AntLoader.ValidExtension(info.Extension)) { var ant = AntLoader.Load(info.FullName, out var domain); if (ant == null) { continue; } antList.Add(ant, domain); } else if (info.Extension.Equals(".bmp", StringComparison.InvariantCultureIgnoreCase)) { map = info; } } ants = antList.Take(8).ToDictionary(x => x.Key, y => y.Value); return(debug); }
public async Task Start() { await Crawl(webpages[0]); try { Console.WriteLine(); Console.WriteLine("En total se visitaron: {0} pagina(s)", webPagesVisited); Console.WriteLine(); //Distict keywords by key and count, and then order by count. wordCounter = wordCounter.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value); //Save wordcounter in a file using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"WebCrawler.txt")) { file.WriteLine("Word \t\t\t | Occurrences"); foreach (var line in wordCounter) { file.WriteLine(line.Key + " \t\t\t\t " + wordCounter[line.Key]); } } //print Top 50 keyword to console. Console.WriteLine("================================================================================"); Console.WriteLine("|| Top 50 words. If you want to see the full wordcounter, open ||"); Console.WriteLine("|| ConsoleApp1/bin/Debug/netcoreapp2.1/WebCrawler.txtWebCrawler.txt ||"); Console.WriteLine("================================================================================"); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("================================================================================"); Console.WriteLine("|| Word \t\t\t | No. of Occurrences \t\t\t||"); Console.WriteLine("================================================================================"); foreach (var aux in wordCounter.Take(50)) { Console.WriteLine("{0} \t\t\t\t {1}", aux.Key, wordCounter[aux.Key]); } } catch (HttpRequestException e) { Console.WriteLine("\nException Caught!"); Console.WriteLine("Message :{0} ", e.Message); } }
//输入单词进行词频统计分析 private void button1_Click(object sender, EventArgs e) { if (textBox7.TextLength != 0 && textBox9.TextLength != 0) { if (click == true && textBox5.TextLength == 0) { sumchar = wordCount.characSum(textBox1.Text.ToString()); al = wordCount.Splitwords(textBox1.Text.ToString()); //textBox8.AppendText(al.Capacity.ToString()); int i = 0; while (i <= (al.Count - CZcount)) { var result = al.GetRange(i, CZcount); foreach (var n in result) { textBox8.AppendText(n.ToString() + " "); } textBox8.AppendText("\r\n"); i++; } sumword = wordCount.Sumword(al); nary = wordCount.countWords(al); textBox3.AppendText(sumchar.ToString()); textBox4.AppendText(sumword.ToString()); foreach (var pair in nary.Take(ZDYcount)) { textBox2.AppendText(pair.Key + ":" + pair.Value); textBox2.AppendText("\r\n"); } } else if (textBox1.TextLength == 0 && click == true) { MessageBox.Show("已导入"); } else { MessageBox.Show("请点击自定义"); } } else { MessageBox.Show("请输入两个需要的数字"); } }
public static string GetWhere(string columna, string operacion, string valor) { var opciones = new Dictionary <string, string> { { "eq", "=" }, { "ne", "<>" }, { "lt", "<" }, { "le", "<=" }, { "gt", ">" }, { "ge", ">=" }, { "bw", "LIKE" }, { "bn", "NOT LIKE" }, { "in", "LIKE" }, { "ni", "NOT LIKE" }, { "ew", "LIKE" }, { "en", "NOT LIKE" }, { "cn", "LIKE" }, { "nc", "NOT LIKE" } }; if (string.IsNullOrEmpty(operacion)) { return(string.Empty); } else { if (operacion.Equals("bw") || operacion.Equals("bn")) { valor = valor + "%"; } if (operacion.Equals("ew") || operacion.Equals("en")) { valor = "%" + valor; } if (operacion.Equals("cn") || operacion.Equals("nc") || operacion.Equals("in") || operacion.Equals("ni")) { valor = "%" + valor + "%"; } if (opciones.Take(6).ToDictionary(p => p.Key, p => p.Value).ContainsKey(operacion)) { return(string.IsNullOrEmpty(valor) ? string.Empty : (columna + " ") + opciones[operacion] + " " + valor); } return(columna + " " + opciones[operacion] + " '" + valor + "'"); } }
public static string[] BestPredictWord(int topNumberOfPredictWords, string[] allWords) { int topWord = topNumberOfPredictWords; string[] keys = new string[topWord]; Dictionary <string, int> wordCount = WordsCount(allWords); int count = 0; foreach (KeyValuePair <string, int> word in wordCount.Take(topWord)) { keys[count] = word.Key; count++; } //IEnumerable<KeyValuePair<string,int>> test = wordCount.Take(5); return(keys); }
private async Task <Dictionary <string, decimal> > GetCashFlowByMonth() { try { var allTransactions = await _transactionService.GetAllTransactionsAsync(); var transactionsByMonth = allTransactions .Select(t => new { t.Date.Year, t.Date.Month, t.Amount, t.Type }) .GroupBy(t => new { t.Year, t.Month }, (key, group) => new { year = key.Year, month = key.Month, cashflow = group.Sum(k => k.Type == TransactionTypesEnum.Expense ? -1 * k.Amount : k.Amount) }).ToList(); var transactionsByMonthDict = new Dictionary <DateTime, decimal>(); foreach (var item in transactionsByMonth) { var date = new DateTime(item.year, item.month, 1); var amount = item.cashflow; transactionsByMonthDict.Add(date, amount); } foreach (var pair in transactionsByMonthDict.Where(pair => transactionsByMonthDict.ContainsKey(pair.Key) == false)) { transactionsByMonthDict.Add(pair.Key, 0m); } var oneYearAgo = DateTime.Today.AddYears(-1); var index = new DateTime(oneYearAgo.Year, oneYearAgo.Month, 1); for (DateTime i = index; i <= DateTime.Today; i = i.AddMonths(1)) { if (!transactionsByMonthDict.ContainsKey(i)) { transactionsByMonthDict.Add(i, 0m); } } return(transactionsByMonthDict.Take(12).OrderBy(t => t.Key.Year).ThenBy(t => t.Key.Month) .ToDictionary(t => $"{ConvertMonthIntToString(t.Key.Month)} {t.Key.Year}", t => t.Value)); } catch (Exception e) { throw; } }
private IList <MixinMemberResolvedResult> FilterOutCollisions( Dictionary <IType, List <MixinMemberResolvedResult> > allMixinMembers, IType currentMixin, IList <MixinMemberResolvedResult> currentMixinMembers) { //if there is only one mixin, then we don't have to worry //about collisions if (allMixinMembers.Keys.Count == 1) { return(currentMixinMembers); } //if currentMixin is the first mixin then we don't have to //worry about collisions. The other mixins will need to prevent //the collision. if (allMixinMembers.Keys.First().Equals(currentMixin)) { return(currentMixinMembers); } //Where is the currentMixin in the line //of all mixins var indexOfCurrentMixin = allMixinMembers.Keys.IndexOf(x => x.Equals(currentMixin)); var mixinsAheadInLineMembers = allMixinMembers .Take(indexOfCurrentMixin) .SelectMany(x => x.Value) .ToList(); for (var currentMixinMemberIndex = 0; currentMixinMemberIndex < currentMixinMembers.Count(); currentMixinMemberIndex++) { var currentMixinMethodUnderTest = currentMixinMembers[currentMixinMemberIndex]; if (mixinsAheadInLineMembers.Any(x => x.Member.EqualsMember(currentMixinMethodUnderTest.Member))) { currentMixinMembers[currentMixinMemberIndex] = ResolveCollision(currentMixin, currentMixinMethodUnderTest); } } //Remove any member where ResolveCollision set the resolution to null return(currentMixinMembers.Where(x => null != x).ToList()); }
private static void PrintAllItems(Dictionary <string, long> itemValues) { var rareItems = itemValues.Take(3).OrderByDescending(x => x.Value).ThenBy(x => x.Key).ToList(); var junkItems = itemValues.Skip(3).OrderBy(x => x.Key).ToList(); foreach (var rareItem in rareItems) { Console.WriteLine($"{rareItem.Key}: {rareItem.Value}"); } foreach (var item in junkItems) { Console.WriteLine($"{item.Key}: {item.Value}"); } }
private Dictionary <string, int> FindUnorderedMatches(string prefix, int max = 0) { Dictionary <string, int> matches = new Dictionary <string, int>(); foreach (var word in words) { if (word.Key.StartsWith(prefix)) { matches.Add(word.Key, word.Value); } } if (max > 0 && matches.Count > max) { return(matches.Take(max) as Dictionary <string, int>); } return(matches); }
private void SplitByRack(Dictionary <int, int> smpPlasmaSlices) { int totalSliceCnt = smpPlasmaSlices.Count; while (smpPlasmaSlices.Any()) { int remaining = smpPlasmaSlices.Count; int splitted = totalSliceCnt - remaining; var tmpPlasmaSlices = smpPlasmaSlices.Take(Math.Min(remaining, 16)).ToDictionary(x => x.Key, x => x.Value); allRackSmpPlasmaSlices.Add(tmpPlasmaSlices); var tmpPackageInfos = CreatePackInfo(tmpPlasmaSlices); allPackageExpectedInfos.Add(new Dictionary <Point, string>(tmpPackageInfos)); allPackageScannedInfos.Add(new Dictionary <Point, string>()); smpPlasmaSlices = smpPlasmaSlices.Except(tmpPlasmaSlices).ToDictionary(x => x.Key, x => x.Value); } ChangeRackIndex(0); }
private static SubmitContext GetSubmitContext(int numberOfFields, int numberOfMatchingFields, string boolOperator) { var fieldNamesAndValues = new Dictionary <string, string>(); for (int i = 0; i < numberOfFields; i++) { fieldNamesAndValues.Add(GetTestString(), GetTestString()); } var filter = new FiltersModel() { Excluded = GetSearchTreeNodeModel(boolOperator, fieldNamesAndValues) }; var submitContext = GetSubmitContext(filter); return(AddOrUpdateCoreMetadata(submitContext, fieldNamesAndValues.Take(numberOfMatchingFields))); }
static void Main(string[] args) { Dictionary <int, string> products = new Dictionary <int, string>() { { 1, "Product 1" }, { 2, "Product 2" }, { 3, "Product 3" }, { -1, "Product 3" } }; Dictionary <int, string> orderedProducts = products.OrderBy(pair => pair.Value) .ThenBy(pair => pair.Key) //here first we order by Value then secondly by Key .ToDictionary(pair => pair.Key, pair => pair.Value); Console.WriteLine(string.Join("\n", products.Take(2))); // We take only the first 2 elements -> Key-Value -pairs Console.WriteLine(); // using the method take( we take only the fiorst two elements from the list , from the Dictionary..) Console.WriteLine(string.Join("\n", orderedProducts)); }
private WallSection GetWallSection(float value) { int i = wallSectionTemplatePairs.Count; foreach (var pair in wallSectionTemplatePairs) { if (pair.Key.SpawnChance >= value && pair.Key.SpawnChance > 0f) { var valuablePairs = wallSectionTemplatePairs.Take(i).Where(p => p.Value.HasAvailableItems && p.Key.MinNormalizedDifficulty <= DifficultyController.Singleton.NormalizedDifficulty && p.Key.SpawnChance > 0f); return(valuablePairs.Count() > 2 ? valuablePairs.ElementAt(Random.Range(2, valuablePairs.Count())).Value.GetItem() : wallSectionTemplatePairs[defaultSectionTemplate].GetItem()); } i--; } return(wallSectionTemplatePairs[defaultSectionTemplate].GetItem()); }
// generates output text using the keys/values of ChangeInCoins private string GenerateOutput() { string output = String.Format("Total change: £{0:N}. The most efficient way to provide this is with ", TotalChange); // creates a dictionary only containing the key/values that we actually want to print (the ones where value != 0) Dictionary <string, int> ChangeToBePrinted = new Dictionary <string, int>(); foreach (KeyValuePair <string, int> denomination in ChangeInCoins.Where(x => x.Value != 0)) { ChangeToBePrinted.Add(denomination.Key, denomination.Value); } //comma separates all but the last denomination to be printed foreach (KeyValuePair <string, int> denomination in ChangeToBePrinted.Take(ChangeToBePrinted.Count - 1)) { if (denomination.Value == 1) { output += String.Format("a {0}, ", denomination.Key); } else { output += String.Format("{0} {1}s, ", NumberToWords(denomination.Value), denomination.Key); } } // removes final ", " and replaces with "and " if there's more than one denomination to list if (ChangeToBePrinted.Count > 1) { output = output.Remove(output.Length - 2); output += " and "; } // adds last key/value to the list, "and" separated, with final full stop if (ChangeToBePrinted.LastOrDefault().Value == 1) { output += String.Format("a {0}.", ChangeToBePrinted.LastOrDefault().Key); } else { output += String.Format("{0} {1}s.", NumberToWords(ChangeToBePrinted.LastOrDefault().Value), ChangeToBePrinted.LastOrDefault().Key); } return(output); }
public bool MatchTwoPlayer(out Tuple <Player, Deck> playerDeckPair1, out Tuple <Player, Deck> playerDeckPair2) { if (WaitingPlayerCount >= 2) { Tuple <Player, Deck>[] players = waitingPlayerDictionary.Take(2).Select(x => x.Value).ToArray(); playerDeckPair1 = players[0]; playerDeckPair2 = players[1]; waitingPlayerDictionary.Remove(playerDeckPair1.Item1.PlayerID); waitingPlayerDictionary.Remove(playerDeckPair2.Item1.PlayerID); onWaitingPlayerCountUpdated?.Invoke(WaitingPlayerCount); return(true); } else { playerDeckPair1 = null; playerDeckPair2 = null; return(false); } }
/// <summary> /// The form report. /// </summary> /// <param name="periodInHours"> /// The period in hours. /// </param> /// <param name="reportOptions"> /// The report options. /// </param> /// <returns> /// The <see cref="AvailabilityData"/>. /// </returns> public AvailabilityData FormReport(int periodInHours, ReportOptions reportOptions) { // this is a stub // it should request real repository with data var data = new AvailabilityData(); data.PeriodType = reportOptions.PeriodType; if (data.PeriodType == AvailabilityData.PeriodTypeEnum.Day) { data.Statistics = availabilityByHours.GroupBy(i => i.Key.Date).Take(periodInHours / 24).Select(j => Math.Round(j.Average(g => g.Value), 2)).ToArray(); } else { data.Statistics = availabilityByHours.Take(periodInHours).Select(i => i.Value).ToArray(); } return(data); }
/// <summary> /// 加密方法 /// </summary> /// <param name="Source">待加密的串</param> /// <returns>经过加密的串</returns> public string Encrypto(string source) { lock (_cache) { if (_cache.ContainsKey(source)) { return(_cache[source]); } byte[] bytIn = UTF8Encoding.UTF8.GetBytes(source); MemoryStream ms = new MemoryStream(); mobjCryptoService.Key = GetLegalKey(); mobjCryptoService.IV = GetLegalIV(); ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor(); CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write); cs.Write(bytIn, 0, bytIn.Length); cs.FlushFinalBlock(); ms.Close(); byte[] bytOut = ms.ToArray(); string reval = Convert.ToBase64String(bytOut); lock (_cacheLock) { if (_cache.Count > _maxCacheNum) { foreach (var it in _cache.Take(_maxCacheNum / 5)) { _cache.Remove(it.Key); } } _cache.Add(source, reval); } return(reval);; } }
/// <summary> /// Reconstruct time series component from the signal matrix /// </summary> /// <param name="xs">number of signal matrix</param> /// <returns></returns> public double[] Reconstruct(int signalCounts = -1) { double[] tsCumulative = null; IEnumerable <KeyValuePair <int, double[, ]> > sM = _Xs; if (signalCounts > 0) { sM = _Xs.Take(signalCounts); } //initi ts tsCumulative = MatrixEx.Zeros(_ts.Count()); foreach (var sMat in sM) { var retVal = diagonalAveraging(sMat.Value); tsCumulative = tsCumulative.Add(retVal); } return(tsCumulative); }
public static void zad2() { string path = Console.ReadLine(); try { readPath(path); //partWord("+-The'dad%thE9dad#$-+dad's the".ToLower()); wordsMap = wordsMap.OrderByDescending(obj => obj.Value).ToDictionary(obj => obj.Key, obj => obj.Value); foreach (var pair in wordsMap) { Console.WriteLine("Word: {0}, Frequency: {1}", pair.Key, pair.Value); } Console.WriteLine(); foreach (var pair in wordsMap.Take(10)) { Console.WriteLine("Word: {0}, Frequency: {1}", pair.Key, pair.Value); } } catch (IOException e) { Console.WriteLine("The file could not be read:"); Console.WriteLine(e.Message); } catch (ArgumentException e) { Console.WriteLine("Empty path provided:"); Console.WriteLine(e.Message); } catch (UnauthorizedAccessException e) { Console.WriteLine("Unsufficent privilages to open file:"); Console.WriteLine(e.Message); } }
public Dictionary <string, int> GetTotalJogosLoja() { Dictionary <string, int> total = new Dictionary <string, int>(); Dictionary <string, int> resposta = new Dictionary <string, int>(); var query = db.game_platform. Where(gp => gp.id_status == 1). GroupBy(gp => gp.store.name). Select(g => new { loja = g.Key, total = g.Count() }). OrderByDescending(g => g.total); foreach (var gp in query) { if (gp.loja != null) { total.Add(gp.loja, gp.total); } } resposta = total.Take(14).ToDictionary(x => x.Key, x => x.Value); return(resposta); }
public Dictionary <string, int> GetTotalJogosAno() { Dictionary <string, int> total = new Dictionary <string, int>(); Dictionary <string, int> resposta = new Dictionary <string, int>(); var query = db.game_platform. Where(gp => gp.id_status == 1). GroupBy(gp => gp.release_date.Value.Year). Select(g => new { ano = (int?)g.Key, total = g.Count() }). OrderByDescending(g => g.total); foreach (var gp in query) { if (gp.ano != null) { total.Add(gp.ano.ToString(), gp.total); } } resposta = total.Take(14).ToDictionary(x => x.Key, x => x.Value); return(resposta); }
public void TestEnumerator() { var reactiveList = new Dictionary <int, string> { { 1, "first" }, { 2, "second" }, { 3, "third" }, { 4, "fourth" } }.ToReactive(); var sumFirstTwo = Reactive.Expression(() => reactiveList.Take(2).Sum(kv => kv.Key)); var counter = 0; sumFirstTwo.Subscribe(getValue => ReactiveManagerTest.Const(getValue, () => counter++)); var expectation = 1; reactiveList[3] = "fifth"; Assert.AreEqual(expectation, counter); reactiveList.Add(6, "sixth"); Assert.AreEqual(expectation, counter); reactiveList[1] = "seventh"; Assert.AreEqual(++expectation, counter); reactiveList.Clear(); Assert.AreEqual(++expectation, counter); }
private static void Print(Dictionary <string, long> itemValue) { var rareMaterials = itemValue .Take(3) .OrderByDescending(x => x.Value) .ThenBy(x => x.Key) .ToArray(); var junkMaterials = itemValue.Skip(3).OrderBy(x => x.Key); foreach (var rare in rareMaterials) { Console.WriteLine($"{rare.Key}: {rare.Value}"); } foreach (var junk in junkMaterials) { Console.WriteLine($"{junk.Key}: {junk.Value}"); } }
public void ArrayElementsAccessTest() { var mapping = "ARRAY_TEST_MAPPING_1"; var accessDict = new Dictionary <string, object> { { "ByteElements[10]", (byte)0x05 }, { "ByteElements[5]", (byte)0x06 }, { "ByteElements[1]", (byte)0x07 }, { "CharElements[10]", 'a' }, { "CharElements[5]", 'b' }, { "CharElements[1]", 'c' }, { "IntElements[10]", 10 }, { "IntElements[5]", 20 }, { "IntElements[1]", 30 }, }; Test(mapping, accessDict.Take(3).ToDictionary(kvp => kvp.Key, kvp => kvp.Value), default(byte)); Test(mapping, accessDict.Skip(3).Take(3).ToDictionary(kvp => kvp.Key, kvp => kvp.Value), default(char)); Test(mapping, accessDict.Skip(6).Take(3).ToDictionary(kvp => kvp.Key, kvp => kvp.Value), default(int)); }
protected void Page_Load(object sender, EventArgs e) { string userInput = "!@#$";//使用者輸入的文字 Dictionary <Func <string, bool>, Action> d = new Dictionary <Func <string, bool>, Action>() { { (a) => { return(a.Equals("蘋果")); }, () => { Response.Write("Apple"); } }, { (a) => { return(a.Equals("香蕉")); }, () => { Response.Write("Banana"); } }, { (a) => { return(a.Equals("櫻桃")); }, () => { Response.Write("Cherry"); } } }; //條件都不符合的情況,抓出前三筆條件判斷都是false的話... d.Add( (a) => { return(d.Take(3).All(x => x.Key.Equals(userInput) == false)); }, () => { Response.Write("字串都不符合條件"); } ); //挑選出Key回傳值為true的Method來執行 d.Where(x => x.Key(userInput) == true).FirstOrDefault().Value.Invoke(); }
private void CrossValidationTeachAndClassificate(Dictionary <double[], bool> testVectors, int groupsNumber) { int vectorsInGroup = (int)((double)testVectors.Count / groupsNumber); for (int i = 0; i < groupsNumber; i++) { var testVectorsFrom = i * vectorsInGroup; var testVectorsTo = (i * vectorsInGroup) + vectorsInGroup; var teachingVectors = testVectors.Skip(testVectorsFrom).Take(vectorsInGroup).ToDictionary(x => x.Key, x => x.Value); var checkVectors = testVectors.Take(testVectorsFrom).ToDictionary(x => x.Key, x => x.Value); foreach (var element in testVectors.Skip(testVectorsTo)) { checkVectors.Add(element.Key, element.Value); } _classificator.Teach(teachingVectors); Classificate(checkVectors); } }
public void SetInitialSliderState(ConcurrentDictionary <string, LightState> Lights) { foreach (KeyValuePair <string, LightState> pair in Lights) { lightDict.Add(pair.Key, pair.Value.LampName); } RGB newRGB = new RGB(); LightsCombo.ItemsSource = lightDict; LightsCombo.DisplayMemberPath = "Value"; LightsCombo.SelectedValuePath = "Key"; var firstKey = lightDict.Take(1).Select(d => d.Key).First(); LightsCombo.SelectedIndex = 0; slHue.Value = Lights[firstKey].HueState.Hue; slSat.Value = Lights[firstKey].HueState.Sat; slBri.Value = Lights[firstKey].HueState.Bri; var isOn = Lights[firstKey].HueState.On; if (!isOn) { slBri.IsEnabled = false; slHue.IsEnabled = false; slSat.IsEnabled = false; StatusLbl.Visibility = Visibility.Visible; LightOff.IsChecked = false; } else { slBri.IsEnabled = true; slHue.IsEnabled = true; slSat.IsEnabled = true; StatusLbl.Visibility = Visibility.Hidden; LightOff.IsChecked = true; } newRGB = Helpers.RgbHelper.GetRGB(slHue.Value, slSat.Value, slBri.Value); ColorPreview.IsEnabled = false; ColorPreview.Background = new SolidColorBrush(Color.FromRgb(Convert.ToByte(newRGB.R), Convert.ToByte(newRGB.G), Convert.ToByte(newRGB.B))); OnLoad = false; }
private string LoadSongs(string path, int category) { // read the index file from disk StreamReader sr = new StreamReader(path); string lyrics = sr.ReadToEnd(); // parse the index file for songs and rank Dictionary<int, double> songs = new Dictionary<int, double>(); foreach (string line in lyrics.Split('\n')) { try { songs.Add(Convert.ToInt32(line.Split(' ')[0]), Convert.ToDouble(line.Split(' ')[1])); } catch (Exception ex) { continue; } } // initialize web client WebClient client = new WebClient(); // build the results output string output = ""; foreach (KeyValuePair<int, double> song in songs.Take(5)) { // download song information and album art from MusixMatch string response = client.DownloadString("http://api.musixmatch.com/ws/1.1/track.get?track_id=" + song.Key + "&apikey=" + apiKey); var track = Json.Decode(response).message.body.track; string albumCover = track.album_coverart_350x350 == "" ? track.album_coverart_100x100 : track.album_coverart_350x350; // append the raw HTML content output += "<div class='span2'><a href='view.aspx?id=" + track.track_id + "&category=" + category + "'><img class='img-polaroid' width='150' height='150' style='width: 150px; height: 150px;' src='" + albumCover + "'></a><h4><a href='view.aspx?id=" + track.track_id + "&category=" + category + "'>" + track.track_name + "</a></h4><p>by " + track.artist_name + "</p></div>\n"; } // return the rendered results return output; }
private void btnCalculate_Click(object sender, EventArgs e) { string textEntered = txtRTB.Text.Trim(); string[] words = textEntered.Replace("\n", " ").Replace(" ", " ").Split(); Dictionary <string, int> distinctWords = new Dictionary <string, int>(); foreach (string word in words) { if (distinctWords.ContainsKey(word.ToLower())) { distinctWords[word.ToLower()] += 1; } else { distinctWords.Add(word.ToLower(), 1); } } distinctWords = distinctWords.OrderByDescending(word => word.Value).ToDictionary(word => word.Key, word => word.Value); Dictionary <string, int> topThreeWords = distinctWords.Take(3).ToDictionary(count => count.Key, count => count.Value); StringBuilder str = new StringBuilder(); foreach (KeyValuePair <string, int> word in distinctWords) { str.AppendFormat("{0} - {1}\n", word.Key, word.Value); } txtRTB.Text = str.ToString(); str.Clear(); str.Append("Las palabras mas escritas fueron: \n\n"); foreach (KeyValuePair <string, int> word in topThreeWords) { str.AppendFormat("{0} - {1}\n", word.Key, word.Value); } MessageBox.Show(str.ToString()); }
private void PrintRequests(string type, Dictionary<string, int> sortedDict, int sum) { m_log.InfoFormat("[INFO]:"); m_log.InfoFormat("[INFO]: {0,25}", type); foreach (KeyValuePair<string, int> kvp in sortedDict.Take(12)) m_log.InfoFormat("[INFO]: {0,25} {1,-6}", kvp.Key, kvp.Value); m_log.InfoFormat("[INFO]: {0,25}", "..."); m_log.InfoFormat("[INFO]: {0,25} {1,-6}", "Total", sum); }
/// <summary> /// Vrátí součet rozdílů očekávaných a nalezených procentuálních výskytů znaků /// </summary> /// <param name="text"></param> /// <param name="occurrence"></param> /// <returns></returns> private static double SumSimilarity(string text, Dictionary<string, double> occurrence) { Dictionary<string, double> standardLettersOccurrence = occurrence.Take(6).ToDictionary(x => x.Key, x => x.Value); Dictionary<string, double> inTextLettersOcc = TextAnalysis.GetOccurrence(text, occurrence.Keys.Take(1).ToArray()[0].Length); double sum = 0; foreach (KeyValuePair<string, double> occ in standardLettersOccurrence) { if (inTextLettersOcc.ContainsKey(occ.Key)) { sum += Math.Abs(occ.Value - inTextLettersOcc[occ.Key]); } else { sum += 10; } } return sum; }
public void UpsertDocuments(Dictionary<string, string> docsToUpsert) { while (docsToUpsert.Any()) { var upsertBatch = docsToUpsert.Take (32).ToList (); upsertBatch.ForEach (b => docsToUpsert.Remove (b.Key)); var upsertCommand = new StringBuilder (); foreach (var kvp in upsertBatch) { var segments = kvp.Key.Split ('_'); string environment = segments [0]; string type = segments [1]; upsertCommand.AppendFormat ("exec UpsertDocument @id='{0}', @index='{1}', @type='{2}', @doc='{3}'", kvp.Key, environment, type, kvp.Value.Replace ("'", "''")); } string sqlText = upsertCommand.ToString (); using (var _loadConnection = new SqlConnection(Common.TargetConnectionString)) { _loadConnection.Open (); using (var upsertCmd = new SqlCommand(sqlText, _loadConnection)) { try { upsertCmd.ExecuteNonQuery (); } catch (SqlException sex) { Console.WriteLine ("SqlException: {0}", sex.Message); foreach (var d in upsertBatch) { // requeue these docs for upsert docsToUpsert.Add (d.Key, d.Value); } } } } } }
//serach bar action for ajax send public ActionResult SearchActionMethod(string word) { Dictionary<string[], int> words = new Dictionary<string[], int>(); foreach (var item in client.GetProducts()) { if (item.Name.ToUpper().Contains(word.ToUpper()) && word != String.Empty) { words.Add(new string[] { "pro", item.Name }, item.Id); } } foreach (var item in client.GetShipping_Companys()) { if (item.Company_Name.ToUpper().Contains(word.ToUpper()) && word != String.Empty) { words.Add(new string[] { "com", item.Company_Name }, item.Id); } } foreach (var item in client.SubCategories()) { if (item.Name.ToUpper().Contains(word.ToUpper()) && word != String.Empty) { words.Add(new string[] { "sub", item.Name }, item.Id); } } //foreach (var item in client.GetProducts()) //{ // if (item.Name.ToUpper().Contains(word.ToUpper()) && word != String.Empty) // { // words.Add("",item.Name); // } //} foreach (var item in client.GetCategories()) { if (item.Name.ToUpper().Contains(word.ToUpper()) && word != String.Empty) { words.Add(new string[] { "cat", item.Name }, item.Id); } } //client.GetCategories(); return Json(words.Take(7), JsonRequestBehavior.AllowGet); }
private void WriteInsertColumns(Dictionary<string, string> exampleRow, string fieldSeparator, Dictionary<string, int> maxFieldWidths, out Dictionary<string, string> fieldFormats) { fieldFormats = new Dictionary<string, string>(); foreach (var field in exampleRow.Take(exampleRow.Count - 1)) { var fieldName = field.Key; var fieldFormat = GetFieldFormat(fieldName, maxFieldWidths); fieldFormats.Add(fieldName, fieldFormat); _tt.Write(fieldFormat + fieldSeparator, fieldName); } var lastField = exampleRow.Last(); var lastFieldName = lastField.Key; var lastFieldFormat = GetFieldFormat(lastFieldName, maxFieldWidths); fieldFormats.Add(lastFieldName, lastFieldFormat); _tt.Write(lastFieldFormat + new string(' ', fieldSeparator.Length), lastFieldName); }
/// <summary> /// /// </summary> /// <param name="req"></param> public SearchResponse SearchDocumentSpace(SearchRequest req) { SearchResponse resp = new SearchResponse(); try { if (req == null || String.IsNullOrEmpty(req.DocumentSpace) || String.IsNullOrEmpty(req.SearchWords)) return resp; resp.DocumentSpace = req.DocumentSpace; Dictionary<int, Document> dmnts = new Dictionary<int, Document>(); Action repack = () => { //Repacking dmnts into resp if (req.IncludeDocuments) { foreach (var el in dmnts) { resp.Documents.Add(el.Value); } } else { foreach (var el in dmnts) { resp.DocumentsInternalIds.Add(el.Key); } } }; System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); using (var tran = DBreezeEngine.GetTransaction()) { var mt = tran.SelectTable<int>(DocumentsStorageTablesPrefix + "m", 1, 0); var docSpaceId = mt.Select<string, long>(req.DocumentSpace).Value; if (docSpaceId == 0) return resp; //Not found document space var Words = this.PrepareSearchKeyWords(req.SearchWords); string docTable = DocumentsStorageTablesPrefix + "d" + docSpaceId.ToString(); var vt = tran.SelectTable<int>(docTable, 3, 0); //Version table Key var dt = tran.SelectTable<int>(docTable, 1, 0); //Document table Key dt.ValuesLazyLoadingIsOn = !req.IncludeDocuments; DBreeze.DataTypes.Row<int, byte[]> docRow = null; Document doc = null; //byte[] btDoc = null; int qOutput = 0; //----------------------------------------------------------------- ONE/MULTIPLE WORDS SEARCH then one word is supplied, using AND/OR LOGIC #region "Multiple Words" int j = -1; List<byte[]> foundArrays = new List<byte[]>(); List<byte[]> oneWordFoundArrays = new List<byte[]>(); //WAH2 wh = null; var tbOneWordWAH = tran.SelectTable<int>(DocumentsStorageTablesPrefix + "s" + docSpaceId.ToString(), 2, 0); tbOneWordWAH.ValuesLazyLoadingIsOn = false; resp.UniqueWordsInDataSpace = (int)tbOneWordWAH.Count(); bool anyWordFound = false; int totalFoundWords = 0; Dictionary<string, WordInDoc> words = new Dictionary<string, WordInDoc>(); int foundOrigin = 1; Dictionary<string, WordInDoc> perWord = new Dictionary<string, WordInDoc>(); Dictionary<string, WordInDoc> firstHighOccuranceWord = new Dictionary<string, WordInDoc>(); //Currently we ignore these words and do nothing with them List<string> highOccuranceWordParts = new List<string>(); foreach (var word in Words.Take(10)) //Maximum 10 words for search { anyWordFound = false; totalFoundWords = 0; perWord = new Dictionary<string, WordInDoc>(); foreach (var row1 in tbOneWordWAH.SelectForwardStartsWith<string, byte[]>(word)) { anyWordFound = true; totalFoundWords++; if (Words.Count() == 1 && totalFoundWords > req.Quantity) { //In case if only one search word, then we don't need to make any comparation break; } else if (totalFoundWords >= req.MaximalExcludingOccuranceOfTheSearchPattern) //Found lots of words with such mask inside { //Too much found docs have this word-part inside, better to enhance search if (firstHighOccuranceWord.Count() == 0) { //Only first HighOccurance word part come to the list. It can be used later in case if all search words are of HighOccurance (then we will visualize only this one) firstHighOccuranceWord = perWord.ToDictionary(r => r.Key, r => r.Value); } //Clearing repack element perWord.Clear(); //Adding word into List of High-Occurance word-part highOccuranceWordParts.Add(word); break; } perWord.Add(row1.Key, new WordInDoc() { BlockId = row1.Value.Substring(0,4).To_Int32_BigEndian(), NumberInBlock = row1.Value.Substring(4, 4).To_Int32_BigEndian(), foundOrigin = foundOrigin }); } //Repacking occurances foreach (var pw in perWord) words.Add(pw.Key, pw.Value); foundOrigin++; if ( req.SearchLogicType == SearchRequest.eSearchLogicType.AND && !anyWordFound ) { //Non of words found corresponding to AND logic sw.Stop(); resp.SearchDurationMs = sw.ElapsedMilliseconds; return resp; } } if (words.Count() == 0) { //In case of multiple search words and each of them of HighOccurance. //We will form result only from the first HighOccurance list //Repacking occurances foreach (var pw in firstHighOccuranceWord.Take(req.Quantity)) words.Add(pw.Key, pw.Value); //In this case highOccuranceWordParts must be cleared, because the returning result is very approximate highOccuranceWordParts.Clear(); } //Here we must start get data from blocks //Nested table with blocks var tbBlocks = tran.SelectTable<int>(DocumentsStorageTablesPrefix + "s" + docSpaceId.ToString(), 10, 0); tbBlocks.ValuesLazyLoadingIsOn = false; Dictionary<int,byte[]> block=null; byte[] btBlock=null; int currentBlockId = 0; //DBreeze.Diagnostic.SpeedStatistic.StartCounter("LoadBlocks"); foreach (var wrd in words.OrderBy(r=>r.Value.BlockId)) { if (currentBlockId != wrd.Value.BlockId) { currentBlockId = wrd.Value.BlockId; //DBreeze.Diagnostic.SpeedStatistic.StartCounter("SelectBlocks"); btBlock = tbBlocks.Select<int, byte[]>(wrd.Value.BlockId).Value; //DBreeze.Diagnostic.SpeedStatistic.StopCounter("SelectBlocks"); btBlock = btBlock.Substring(4, btBlock.Substring(0, 4).To_Int32_BigEndian()); //DBreeze.Diagnostic.SpeedStatistic.StartCounter("DecomDeserBlocks"); btBlock = btBlock.DecompressGZip(); block = btBlock.DeserializeProtobuf<Dictionary<int, byte[]>>(); //DBreeze.Diagnostic.SpeedStatistic.StopCounter("DecomDeserBlocks"); } wrd.Value.wah = new WAH2(block[wrd.Value.NumberInBlock]); } //DBreeze.Diagnostic.SpeedStatistic.PrintOut("LoadBlocks", true); //DBreeze.Diagnostic.SpeedStatistic.PrintOut("SelectBlocks", true); //DBreeze.Diagnostic.SpeedStatistic.PrintOut("DecomDeserBlocks", true); foundOrigin = 0; foreach (var wrd in words.OrderBy(r => r.Value.foundOrigin)) { //Console.WriteLine(wrd.Value.foundOrigin); if (foundOrigin != wrd.Value.foundOrigin) { if (oneWordFoundArrays.Count() > 0) { j++; foundArrays.Add(WAH2.MergeAllUncompressedIntoOne(oneWordFoundArrays)); oneWordFoundArrays = new List<byte[]>(); } foundOrigin = wrd.Value.foundOrigin; } else { } oneWordFoundArrays.Add(wrd.Value.wah.GetUncompressedByteArray()); } //The last if (oneWordFoundArrays.Count() > 0) { j++; foundArrays.Add(WAH2.MergeAllUncompressedIntoOne(oneWordFoundArrays)); oneWordFoundArrays = new List<byte[]>(); } ////////// final results if (j >= 0) { var q = WAH2.TextSearch_OR_logic(foundArrays, req.Quantity); if (req.SearchLogicType == SearchRequest.eSearchLogicType.AND) q = WAH2.TextSearch_AND_logic(foundArrays).Take(req.Quantity); foreach (var el in q) { //Getting document docRow = dt.Select<int, byte[]>((int)el); if (docRow.Exists) { if (!dmnts.ContainsKey((int)el)) { if (highOccuranceWordParts.Count() > 0) { //We got some noisy word-parts of high occurance together with strongly found words. //We must be sure that these word parts are also inside of returned docs doc = this.RetrieveDocument(req.IncludeDocumentsContent, true, dt, docRow); if (doc != null) { //Checking doc.Searchables must have all word parts from the occurance in case of AND if (req.SearchLogicType == SearchRequest.eSearchLogicType.AND) { if (String.IsNullOrEmpty(doc.Searchables)) continue; if (!highOccuranceWordParts.All(doc.Searchables.ToLower().Contains)) continue; } if (req.IncludeDocuments) { if (!req.IncludeDocumentsSearchanbles) doc.Searchables = String.Empty; dmnts.Add((int)el, doc); } else { dmnts.Add((int)el, null); } } else continue; } else { if (req.IncludeDocuments) { doc = this.RetrieveDocument(req.IncludeDocumentsContent, req.IncludeDocumentsSearchanbles, dt, docRow); if (doc == null) //If doc is deleted, while search was in progress and we received its id in the list continue; dmnts.Add((int)el, doc); } else { dmnts.Add((int)el, null); } } qOutput++; } } if (qOutput > req.Quantity) break; } } #endregion }//eo using //Repacking dmnts into resp repack(); sw.Stop(); resp.SearchDurationMs = sw.ElapsedMilliseconds; } catch (Exception ex) { throw ThrowException("SearchDocumentSpace", ex.ToString()); } return resp; }
public ulong S_1(Dictionary<ulong, int> guesses) { ulong start = 1; ulong stop = 10; while(stop<guesses.First().Key) { start *= 10; stop *= 10; } var poss = new List<ulong>(); foreach (var g in guesses.Take(1)) { ulong guess = g.Key; int correct = g.Value; for (ulong i = start; i < guess; i++) { ulong diff = guess - i; int count = 0; while (diff > 0) { if (diff%10 == 0) { count++; if (count > correct) { //continue to for loop diff = 0; } } diff /= 10; } if (count == correct) poss.Add(i); } for (ulong i = guess + 1; i < stop; i++) { ulong diff = i - guess; int count = 0; while (diff > 0) { if (diff%10 == 0) { count++; if (count > correct) { //continue to for loop diff = 0; } } diff /= 10; } if (count == correct) poss.Add(i); } } foreach (var g in guesses.Skip(1)) { ulong guess = g.Key; int correct = g.Value; foreach (var p in poss) { ulong diff = p > guess ? p - guess : guess - p; int count = 0; while (diff > 0) { if (diff%10 == 0) { count++; if (count > correct) { //continue to for loop diff = 0; } } diff /= 10; } if (count != correct) poss.Remove(p); } } Debug.Assert(poss.Count==1); return poss.Single(); }
private string FormatLastInsertRecord(Dictionary<string, string> row, Dictionary<string, string> fieldFormats, string prefixFormat, string fieldSeparator) { var sb = new StringBuilder(); sb.AppendFormat(prefixFormat, "SELECT"); foreach (var field in row.Take(row.Count - 1)) { var fieldName = field.Key; sb.AppendFormat(fieldFormats[fieldName] + fieldSeparator, field.Value); } var lastField = row.Last(); var lastFieldName = lastField.Key; sb.AppendFormat(fieldFormats[lastFieldName] + new string(' ', fieldSeparator.Length), lastField.Value); return sb.ToString(); }
public static List<FeedResultItem> GetFeeds(FeedApiFilter filter) { var filterOffset = filter.Offset; var filterLimit = filter.Max > 0 && filter.Max < 1000 ? filter.Max : 1000; var feeds = new Dictionary<string, List<FeedResultItem>>(); var tryCount = 0; List<FeedResultItem> feedsIteration; do { feedsIteration = GetFeedsInternal(filter); foreach (var feed in feedsIteration) { if (feeds.ContainsKey(feed.GroupId)) { feeds[feed.GroupId].Add(feed); } else { feeds[feed.GroupId] = new List<FeedResultItem> { feed }; } } filter.Offset += feedsIteration.Count; } while (feeds.Count < filterLimit && feedsIteration.Count == filterLimit && tryCount++ < 5); filter.Offset = filterOffset; return feeds.Take(filterLimit).SelectMany(group => group.Value).ToList(); }
protected void Page_Load(object sender, EventArgs e) { var shapePageReference = new Rock.Web.PageReference(GetAttributeValue("SHAPEAssessmentPage")); var discPageReference = new Rock.Web.PageReference(GetAttributeValue("DISCAssessmentPage")); if (!string.IsNullOrWhiteSpace(PageParameter("FormId"))) { //Load the person based on the FormId var personInUrl = PageParameter("FormId"); SelectedPerson = GetPersonFromForm(personInUrl); PersonEncodedKey = SelectedPerson.UrlEncodedKey; } else if (!string.IsNullOrWhiteSpace(PageParameter("PersonId"))) { //Load the person based on the PersonId SelectedPerson = GetPersonFromId(PageParameter("PersonId")); PersonEncodedKey = SelectedPerson.UrlEncodedKey; } else if (CurrentPerson != null) { //Load the person based on the currently logged in person SelectedPerson = CurrentPerson; PersonEncodedKey = SelectedPerson.UrlEncodedKey; } else { //Show Error Message nbNoPerson.Visible = true; Response.Redirect(shapePageReference.BuildUrl(), true); return; } // Load the attributes AttributeValueService attributeValueService = new AttributeValueService(rockContext); DefinedValueService definedValueService = new DefinedValueService(rockContext); string spiritualGift1 = ""; string spiritualGift2 = ""; string spiritualGift3 = ""; string spiritualGift4 = ""; string heartCategories = ""; string heartCauses = ""; string heartPassion = ""; string ability1 = ""; string ability2 = ""; string people = ""; string places = ""; string events = ""; var spiritualGift1AttributeValue = attributeValueService .Queryable() .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift1" && a.EntityId == SelectedPerson.Id); // Redirect if they haven't taken the Assessment if (spiritualGift1AttributeValue == null) { Response.Redirect(shapePageReference.BuildUrl(), true); } else { var spiritualGift2AttributeValue = attributeValueService .Queryable() .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift2" && a.EntityId == SelectedPerson.Id); var spiritualGift3AttributeValue = attributeValueService .Queryable() .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift3" && a.EntityId == SelectedPerson.Id); var spiritualGift4AttributeValue = attributeValueService .Queryable() .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift4" && a.EntityId == SelectedPerson.Id); var ability1AttributeValue = attributeValueService .Queryable().FirstOrDefault(a => a.Attribute.Key == "Ability1" && a.EntityId == SelectedPerson.Id); var ability2AttributeValue = attributeValueService .Queryable().FirstOrDefault(a => a.Attribute.Key == "Ability2" && a.EntityId == SelectedPerson.Id); var peopleAttributeValue = attributeValueService .Queryable() .FirstOrDefault(a => a.Attribute.Key == "SHAPEPeople" && a.EntityId == SelectedPerson.Id); var placesAttributeValue = attributeValueService .Queryable() .FirstOrDefault(a => a.Attribute.Key == "SHAPEPlaces" && a.EntityId == SelectedPerson.Id); var eventsAttributeValue = attributeValueService .Queryable() .FirstOrDefault(a => a.Attribute.Key == "SHAPEEvents" && a.EntityId == SelectedPerson.Id); var heartCategoriesAttributeValue = attributeValueService .Queryable() .FirstOrDefault(a => a.Attribute.Key == "HeartCategories" && a.EntityId == SelectedPerson.Id); var heartCausesAttributeValue = attributeValueService .Queryable() .FirstOrDefault(a => a.Attribute.Key == "HeartCauses" && a.EntityId == SelectedPerson.Id); var heartPassionAttributeValue = attributeValueService .Queryable() .FirstOrDefault(a => a.Attribute.Key == "HeartPassion" && a.EntityId == SelectedPerson.Id); if (spiritualGift1AttributeValue.Value != null) spiritualGift1 = spiritualGift1AttributeValue.Value; if (spiritualGift2AttributeValue.Value != null) spiritualGift2 = spiritualGift2AttributeValue.Value; if (spiritualGift3AttributeValue.Value != null) spiritualGift3 = spiritualGift3AttributeValue.Value; if (spiritualGift4AttributeValue.Value != null) spiritualGift4 = spiritualGift4AttributeValue.Value; if (heartCategoriesAttributeValue.Value != null) heartCategories = heartCategoriesAttributeValue.Value; if (heartCausesAttributeValue.Value != null) heartCauses = heartCausesAttributeValue.Value; if (heartPassionAttributeValue.Value != null) heartPassion = heartPassionAttributeValue.Value; if (ability1AttributeValue.Value != null) ability1 = ability1AttributeValue.Value; if (ability2AttributeValue.Value != null) ability2 = ability2AttributeValue.Value; if (peopleAttributeValue.Value != null) people = peopleAttributeValue.Value; if (placesAttributeValue.Value != null) places = placesAttributeValue.Value; if (eventsAttributeValue.Value != null) events = eventsAttributeValue.Value; string spiritualGift1Guid; string spiritualGift2Guid; string spiritualGift3Guid; string spiritualGift4Guid; string ability1Guid; string ability2Guid; // Check to see if there are already values saved as an ID. If so, convert them to GUID if (spiritualGift1.ToString().Length < 5) { if (spiritualGift1 != null) SpiritualGift1 = Int32.Parse(spiritualGift1); if (spiritualGift2 != null) SpiritualGift2 = Int32.Parse(spiritualGift2); if (spiritualGift3 != null) SpiritualGift3 = Int32.Parse(spiritualGift3); if (spiritualGift4 != null) SpiritualGift4 = Int32.Parse(spiritualGift4); if (ability1 != null) Ability1 = Int32.Parse(ability1); if (ability2 != null) Ability2 = Int32.Parse(ability2); var intsOfGifts = definedValueService.GetByIds(new List<int> { SpiritualGift1, SpiritualGift2, SpiritualGift3, SpiritualGift4, Ability1, Ability2 }); spiritualGift1Guid = intsOfGifts.ToList()[SpiritualGift1].Guid.ToString(); spiritualGift2Guid = intsOfGifts.ToList()[SpiritualGift2].Guid.ToString(); spiritualGift3Guid = intsOfGifts.ToList()[SpiritualGift3].Guid.ToString(); spiritualGift4Guid = intsOfGifts.ToList()[SpiritualGift4].Guid.ToString(); ability1Guid = intsOfGifts.ToList()[Ability1].Guid.ToString(); ability2Guid = intsOfGifts.ToList()[Ability2].Guid.ToString(); } else { spiritualGift1Guid = spiritualGift1; spiritualGift2Guid = spiritualGift2; spiritualGift3Guid = spiritualGift3; spiritualGift4Guid = spiritualGift4; ability1Guid = ability1; ability2Guid = ability2; } // Get all of the data about the assiciated gifts and ability categories var shapeGift1Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(spiritualGift1Guid) }).FirstOrDefault(); var shapeGift2Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(spiritualGift2Guid) }).FirstOrDefault(); var shapeGift3Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(spiritualGift3Guid) }).FirstOrDefault(); var shapeGift4Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(spiritualGift4Guid) }).FirstOrDefault(); var ability1Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(ability1Guid) }).FirstOrDefault(); var ability2Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(ability2Guid) }).FirstOrDefault(); shapeGift1Object.LoadAttributes(); shapeGift2Object.LoadAttributes(); shapeGift3Object.LoadAttributes(); shapeGift4Object.LoadAttributes(); ability1Object.LoadAttributes(); ability2Object.LoadAttributes(); // Get heart choices Values from Guids string heartCategoriesString = ""; if (!heartCategories.IsNullOrWhiteSpace()) { string[] heartCategoryArray = heartCategories.Split(','); foreach (string category in heartCategoryArray) { var definedValueObject = definedValueService.Queryable().FirstOrDefault(a => a.Guid == new Guid(category)); if (category.Equals(heartCategoryArray.Last())) { heartCategoriesString += definedValueObject.Value; } else { heartCategoriesString += definedValueObject.Value + ", "; } } } // Get Volunteer Opportunities string gift1AssociatedVolunteerOpportunities = shapeGift1Object.GetAttributeValue("AssociatedVolunteerOpportunities"); string gift2AssociatedVolunteerOpportunities = shapeGift2Object.GetAttributeValue("AssociatedVolunteerOpportunities"); string gift3AssociatedVolunteerOpportunities = shapeGift3Object.GetAttributeValue("AssociatedVolunteerOpportunities"); string gift4AssociatedVolunteerOpportunities = shapeGift4Object.GetAttributeValue("AssociatedVolunteerOpportunities"); string allAssociatedVolunteerOpportunities = gift1AssociatedVolunteerOpportunities + "," + gift2AssociatedVolunteerOpportunities + "," + gift3AssociatedVolunteerOpportunities + "," + gift4AssociatedVolunteerOpportunities; if (allAssociatedVolunteerOpportunities != ",,,") { List<int> associatedVolunteerOpportunitiesList = allAssociatedVolunteerOpportunities.Split(',').Select(t => int.Parse(t)).ToList(); Dictionary<int, int> VolunteerOpportunities = new Dictionary<int, int>(); var i = 0; var q = from x in associatedVolunteerOpportunitiesList group x by x into g let count = g.Count() orderby count descending select new { Value = g.Key, Count = count }; foreach (var x in q) { VolunteerOpportunities.Add(i, x.Value); i++; } ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService(rockContext); List<ConnectionOpportunity> connectionOpportunityList = new List<ConnectionOpportunity>(); foreach (KeyValuePair<int, int> entry in VolunteerOpportunities.Take(4)) { var connection = connectionOpportunityService.GetByIds(new List<int> { entry.Value }).FirstOrDefault(); // Only display connection if it is marked Active if (connection.IsActive == true) { connectionOpportunityList.Add(connection); } } rpVolunteerOpportunities.DataSource = connectionOpportunityList; rpVolunteerOpportunities.DataBind(); } //Get DISC Info DiscService.AssessmentResults savedScores = DiscService.LoadSavedAssessmentResults(SelectedPerson); if (!string.IsNullOrWhiteSpace(savedScores.PersonalityType)) { ShowResults(savedScores); DISCResults.Visible = true; NoDISCResults.Visible = false; } else { discPageReference.Parameters = new System.Collections.Generic.Dictionary<string, string>(); discPageReference.Parameters.Add("rckipid", SelectedPerson.UrlEncodedKey); Response.Redirect(discPageReference.BuildUrl(), true); } // Build the UI lbPersonName.Text = SelectedPerson.FullName; lbGift1Title.Text = shapeGift1Object.Value; lbGift1BodyHTML.Text = shapeGift1Object.GetAttributeValue("HTMLDescription"); lbGift2Title.Text = shapeGift2Object.Value; lbGift2BodyHTML.Text = shapeGift2Object.GetAttributeValue("HTMLDescription"); lbGift3Title.Text = shapeGift3Object.Value; lbGift3BodyHTML.Text = shapeGift3Object.GetAttributeValue("HTMLDescription"); lbGift4Title.Text = shapeGift4Object.Value; lbGift4BodyHTML.Text = shapeGift4Object.GetAttributeValue("HTMLDescription"); lbAbility1Title.Text = ability1Object.Value; lbAbility1BodyHTML.Text = ability1Object.GetAttributeValue("HTMLDescription"); lbAbility2Title.Text = ability2Object.Value; lbAbility2BodyHTML.Text = ability2Object.GetAttributeValue("HTMLDescription"); lbPeople.Text = people; lbPlaces.Text = places; lbEvents.Text = events; lbHeartCategories.Text = heartCategoriesString; lbHeartCauses.Text = heartCauses; lbHeartPassion.Text = heartPassion; if (spiritualGift1AttributeValue.ModifiedDateTime != null) { lbAssessmentDate.Text = spiritualGift1AttributeValue.ModifiedDateTime.Value.ToShortDateString(); } else { lbAssessmentDate.Text = spiritualGift1AttributeValue.CreatedDateTime.Value.ToShortDateString(); } // Show create account panel if this person doesn't have an account if (SelectedPerson.Users.Count == 0) { pnlAccount.Visible = true; } } }
public void Iterate() { Dictionary<Particle, Rank> ranks = new Dictionary<Particle, Rank>(); // Determine how strongly each Particle is being pulled in the four cardinal directions for (int x = 0; x < Size; ++x) { for (int y = 0; y < Size; ++y) { Particle p = _lattice[x, y]; if (p == null) continue; Rank r = getParticleRank(p); ranks.Add(p, r); } } // Compute the energy of the system in this Iteration _energy = ranks.Sum(r => Math.Abs(r.Value.Pulls[r.Value.MaxDirection])); // Sort the particles by the max magnitude of all their pull directions ranks = ranks.OrderBy(r => r.Value.Pulls[r.Value.MaxDirection]) .ToDictionary(r => r.Key, r => r.Value); // Process the Particles of highest rank (and any in their way) until all have been processed do { KeyValuePair<Particle, Rank> pair = ranks.Take(1).Single(); processRank(pair.Key, pair.Value, ref ranks); } while (ranks.Count > 0); }