Example #1
0
        private void CriarIndice()
        {
            List<INDICE> indices = new List<INDICE>();
            Dictionary<VOCABULARIO,int> dicIndice = new Dictionary<VOCABULARIO,int>();
            foreach (var termo in Termos)
            {
                VOCABULARIO voc = new VOCABULARIO();
                //vai criar um termo na base caso não exista e retornar com seu ID
                voc = _vocabularioRepositorio.GetVocabularioByTermo(termo);

                if (dicIndice.ContainsKey(voc))
                {
                    //existe então adiciona mais um na frequencia do termo no documento
                    dicIndice[voc]++;
                }
                else
                {
                    //caso contrario será um
                    dicIndice[voc] = 1;
                }
            }

            //implementa a lista de indices para o bulkInsert no banco já ordenada pela frequencia
            foreach (var iDic in dicIndice.OrderByDescending(d =>d.Value))
            {
                INDICE indice = new INDICE();
                indice.IND_DOCUMENTO = Documento.DOC_ID;
                indice.IND_VOCABULARIO = iDic.Key.VOC_ID;
                indice.IND_FREQUENCIA = iDic.Value;
                indices.Add(indice);
            }

            _indiceRepositorio.InsereBulkIndice(indices);
        }
		//Sort list by frequency 
		public static List<int> sortArray(int[] arr){ //Time:O(nlogn), Space:O(n)
			//Handle edge case
			if (arr.Length == 0)
				return null;

			Dictionary<int, Element> dt = new Dictionary<int, Element> ();
			for (int i = 0; i < arr.Length; i++) { //put all info into dt, Time: O(n)
				if (dt.ContainsKey (arr [i])) {
					dt [arr [i]].occurence++;
				} else {
					Element temp = new Element (1, i);
					dt.Add (arr [i], temp);
				}
			}

			//sort object in dt by occurence in descending order then by firstIndex in ascending order
			//use QuickSort, time: O(nlogn)
			List<KeyValuePair<int, Element>> sortedList = dt.OrderByDescending (o => o.Value.occurence).
														ThenBy (o => o.Value.firstIndex).ToList ();
				
			//Convert the sortedList to a result list
			List<int> result = new List<int> ();
			foreach (KeyValuePair<int, Element> kp in sortedList) {
				for (int i = 0; i < kp.Value.occurence; i++)
					result.Add (kp.Key);
			}
			return result;
		}
Example #3
0
        internal EventCategory(int categoryID)
        {
            this.categoryID = categoryID;

            this.events = new Dictionary<RoomData, int>();
            this.orderedEventRooms = events.OrderByDescending(t => t.Value);
            this.addQueue = new Queue();
            this.removeQueue = new Queue();
            this.updateQueue = new Queue();
        }
 public static void PrintResults(string methodName, Dictionary<string, double> reports)
 {
     Console.WriteLine("Results for {0} method in milliseconds:", methodName);
     var results = reports.OrderByDescending(x => x.Value);
     int index = 1;
     foreach (var res in results)
     {
         Console.WriteLine("{0}.{1} - {2}", index++, res.Key, res.Value);
     }
     Console.WriteLine();
 }
Example #5
0
        public RoomCategory(int categoryID, string caption)
        {
            this.categoryID = categoryID;
            this.caption = caption;

            this.activeRooms = new Dictionary<RoomData, int>();
            this.orderedRooms = activeRooms.OrderByDescending(t => t.Value).Take(0);

            this.addActiveRoomQueue = new Queue();
            this.updateActiveRoomQueue = new Queue();
            this.removeActiveRoomQueue = new Queue();
        }
Example #6
0
        public EventManager()
        {
            this.eventCategories = new Dictionary<int, EventCategory>();
            this.events = new Dictionary<RoomData, int>();
            this.orderedEventRooms = events.OrderByDescending(t => t.Value);
            this.addQueue = new Queue();
            this.removeQueue = new Queue();
            this.updateQueue = new Queue();

            for (int i = 0; i < 30; i++)
            {
                eventCategories.Add(i, new EventCategory(i));
            }
        }
Example #7
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="EventManager" /> class.
        /// </summary>
        public EventManager()
        {
            _eventCategories = new Dictionary<int, EventCategory>();
            _events = new Dictionary<RoomData, uint>();

            _orderedEventRooms = _events.OrderByDescending(t => t.Value);

            _addQueue = new Queue();
            _removeQueue = new Queue();
            _updateQueue = new Queue();

            for (int i = 0; i < 30; i++)
                _eventCategories.Add(i, new EventCategory(i));
        }
Example #8
0
        public void SaveData(Dictionary<string, int> dict, int len)
        {
            ArrayList list = new ArrayList();
            FileStream fs = new FileStream(string.Format("result_{0}word.txt", len), FileMode.OpenOrCreate, FileAccess.Write);
            fs.SetLength(0);
            StreamWriter write = new StreamWriter(fs);

            List<KeyValuePair<string ,int>> data = dict.OrderByDescending(x => x.Value).ToList();
            foreach (KeyValuePair<string, int> kv in data)
            {
                write.WriteLine(kv.Key + " " + kv.Value);
            }
            write.Close();
            fs.Close();
        }
        private Dictionary<String, int> SortScores(string[] scores, int count)
        {
            string[] split;

            Dictionary<String, int> scoreDic = new Dictionary<string,int>();
            Dictionary<String, int> tempDic = new Dictionary<string, int>();

            for (int i = 0; i < count ; i++)
            {
                split = scores[i].Split(' ');
                scoreDic.Add(split[0] + i.ToString(), int.Parse(split[1]));
            }

            tempDic = scoreDic.OrderByDescending(x => x.Value).ToDictionary(pair => pair.Key, pair => pair.Value);
            return (Dictionary<String, int>)tempDic;
        }
        public static string Process(Index index, string[] query)
        {
            _index = index;

            // initialize the rank dictionary
            Dictionary<int, double> rank = new Dictionary<int, double>();
            foreach (KeyValuePair<int, string> document in _index.documents)
                rank.Add(document.Key, 0.0);

            // rank the terms in the query
            Dictionary<string, double> queryWeight = new Dictionary<string, double>();

            int weight = 1;
            foreach (string term in query.Reverse())
            {
                queryWeight.Add(term, weight);
                // weight++;
            }

            // loop through all of the terms in the index
            foreach (KeyValuePair<int, string> term in _index.terms)
            {
                // only process the terms that are being queried
                if (query.Contains(term.Value) == true)
                {
                    // loop though all of the documents in the index
                    foreach (KeyValuePair<int, string> document in _index.documents)
                    {
                        int frequency = Occurrences(document.Value, term.Value);

                        // only process the documents that contain this term
                        if (frequency > 0)
                            rank[document.Key] = rank[document.Key] + ComputeWeight(document.Key, term.Key, frequency, queryWeight[term.Value]);
                    }
                }
            }

            // calculate the results
            StringBuilder sb = new StringBuilder();
            foreach (KeyValuePair<int, double> result in rank.OrderByDescending(z => z.Value))
            {
                sb.AppendLine(result.Key.ToString() + " " + result.Value.ToString());
            }

            return sb.ToString();
        }
Example #11
0
        public override IEnumerable GetDistribution(Release[] releases)
        {
            Dictionary<string, int> result = new Dictionary<string, int>();

            foreach (Release release in releases)
            {
                if (!string.IsNullOrEmpty(release.Genre))
                {
                    if (!result.ContainsKey(release.Genre))
                    {
                        result[release.Genre] = 0;
                    }

                    ++result[release.Genre];
                }
            }

            var allItems = result.OrderByDescending(i => i.Value);
            var topItems = allItems.Take(6);
            var otherItems = allItems.Skip(6);
            int otherItemsSum = otherItems.Sum(i => i.Value);

            foreach (var topItem in topItems)
            {
                yield return new Item()
                {
                    Key = topItem.Key + " (" + topItem.Value + ")",
                    Value = topItem.Value,
                    Genres = new string[] { topItem.Key },
                };
            }

            if (otherItemsSum != 0)
            {
                yield return new Item()
                {
                    Key = "Other (" + otherItemsSum + ")",
                    Value = otherItemsSum,
                    Genres = otherItems.Select(i => i.Key).ToArray()
                };
            }
        }
Example #12
0
        static void Main(string[] args)
        {
            foreach (String name in Directory.GetFiles(_picturesDirectory, "*.jpg"))
                _knownNames.Add(name);

            Dictionary<DateTime, string> nameDic = new Dictionary<DateTime, string>();
            foreach (String name in _knownNames)
                nameDic.Add(Directory.GetCreationTime(name), name);

            var lastime = nameDic.Count() > 0 ? nameDic.Last().Key : DateTime.Now;

            StreamReader r = new StreamReader(_picturesDirectory +  "\\list.txt");
            String line;
            while ((line = r.ReadLine()) != null)
            {
                nameDic.Add(lastime, line);
                lastime = lastime.AddSeconds(1);
            }

            foreach (var item in nameDic.OrderByDescending(x=>x.Key))
                FindFollowers(
                    String.Format("https://api.twitter.com/1/followers/ids.json?screen_name=@{0}", Path.GetFileNameWithoutExtension(item.Value)));
        }
        private void BuildDetailedStatsByCapReport(StringBuilder sb, string capName)
        {
            sb.AppendFormat("Capability name {0}\n", capName);

            ConsoleDisplayTable cdt = new ConsoleDisplayTable();
            cdt.AddColumn("User Name", 34);
            cdt.AddColumn("Req Received", 12);
            cdt.AddColumn("Req Handled", 12);
            cdt.Indent = 2;

            Dictionary<string, int> receivedStats = new Dictionary<string, int>();
            Dictionary<string, int> handledStats = new Dictionary<string, int>();

            m_scene.ForEachScenePresence(
                sp =>
                {
                    Caps caps = m_scene.CapsModule.GetCapsForUser(sp.UUID);

                    if (caps == null)
                        return;

                    Dictionary<string, IRequestHandler> capsHandlers = caps.CapsHandlers.GetCapsHandlers();

                    IRequestHandler reqHandler;
                    if (capsHandlers.TryGetValue(capName, out reqHandler))
                    {
                        receivedStats[sp.Name] = reqHandler.RequestsReceived;
                        handledStats[sp.Name] = reqHandler.RequestsHandled;
                    }        
                    else 
                    {
                        PollServiceEventArgs pollHandler = null;
                        if (caps.TryGetPollHandler(capName, out pollHandler))
                        {
                            receivedStats[sp.Name] = pollHandler.RequestsReceived;
                            handledStats[sp.Name] = pollHandler.RequestsHandled;
                        }
                    }
                }
            );

            foreach (KeyValuePair<string, int> kvp in receivedStats.OrderByDescending(kp => kp.Value))
            {
                cdt.AddRow(kvp.Key, kvp.Value, handledStats[kvp.Key]);
            }

            sb.Append(cdt.ToString());
        }
Example #14
0
        private DataTable _sortTable()
        {
            int intTempIndex = -1;
            string[] astrSort = _strSort.Split(' ');

            if (astrSort.Length != 2)
            {
                throw new Exception("Sort clause in unsupported format: " + _strSort);
            }
            for (int i = 0; i < this.baseTable.Columns.Count; i++)
            {
                if (this.baseTable.Columns[i].ColumnName.Equals(astrSort[0], StringComparison.CurrentCultureIgnoreCase))
                {
                    intTempIndex = i;
                    break;
                }
            }
            if (-1 == intTempIndex)
            {
                throw new Exception("Column name not found: " + astrSort[0]);
            }

            DataTable dtReturn = _dupeTableNoData();

            switch (this.baseTable.Columns[intTempIndex].DataType.ToString())
            {
                case "System.Int32":
                case "System.String":
                case "System.Decimal":
                case "System.DateTime":
                    Dictionary<int, IComparable> dictRowNumThenIntValue = new Dictionary<int, IComparable>();
                    for (int i=0; i < this.baseTable.Rows.Count; i++)
                    {
                        dictRowNumThenIntValue.Add(i, (IComparable)this.baseTable.Rows[i][intTempIndex]);
                    }

                    if (astrSort[1].Equals("DESC", StringComparison.CurrentCultureIgnoreCase))
                        foreach (KeyValuePair<int, IComparable> rowNumThenValue in dictRowNumThenIntValue.OrderByDescending(entry => entry.Value))
                            dtReturn.Rows.Add(_copyRow(dtReturn.NewRow(), dtReturn.Columns, rowNumThenValue.Key));
                    else if (astrSort[1].Equals("ASC", StringComparison.CurrentCultureIgnoreCase))
                        foreach (KeyValuePair<int, IComparable> rowNumThenValue in dictRowNumThenIntValue.OrderBy(entry => entry.Value))
                            dtReturn.Rows.Add(_copyRow(dtReturn.NewRow(), dtReturn.Columns, rowNumThenValue.Key));
                    break;

                default:
                    throw new NotImplementedException(
                        string.Format(
                            "Uncaptured data type ({0}) for datatable sort: {1}",
                            this.baseTable.Columns[intTempIndex].DataType.ToString(),
                             dtReturn.Columns[intTempIndex].ColumnName
                        )
                    );
            }

            return dtReturn;
        }
Example #15
0
        private Dictionary<object, object> initXValues(ResultPage page, List<ResultCell[]> XDimensions)
        {
            Dictionary<object, object> result = new Dictionary<object, object>();
            bool hasNVD3Pie = Model.Elements.Exists(i => i.SerieDefinition == SerieDefinition.NVD3Serie && i.Nvd3Serie == NVD3SerieDefinition.PieChart && i.PivotPosition == PivotPosition.Data);
            bool orderAsc = true;
            foreach (var dimensions in XDimensions)
            {
                //One value -> set the raw value, several values -> concat the display value
                if (dimensions.Length == 1)
                {

                    if (!dimensions[0].Element.IsEnum && dimensions[0].Element.AxisUseValues && !hasNVD3Pie)
                    {
                        result.Add(dimensions, dimensions[0].Value);
                    }
                    else
                    {
                        result.Add(dimensions, dimensions[0].ValueNoHTML);
                    }
                }
                else result.Add(dimensions, Helper.ConcatCellValues(dimensions, ","));

                if (dimensions.Length > 0 && dimensions[0].Element.SortOrder.Contains(SortOrderConverter.kAutomaticDescSortKeyword)) orderAsc = false;
            }

            return orderAsc ? result.OrderBy(i => i.Value).ToDictionary(i => i.Key, i => i.Value) : result.OrderByDescending(i => i.Value).ToDictionary(i => i.Key, i => i.Value);
        }
Example #16
0
 public static Dictionary<string, double> GetTableRootProbability(IList<HtmlNode> nodes, bool haschild)
 {
     var dict = new Dictionary<string, double>();
     GetTableRootProbability(nodes, dict, haschild);
     dict = dict.OrderByDescending(d => d.Value).ToDictionary(d => d.Key, d => d.Value);
     return dict;
 }
Example #17
0
 private void setLengths(List<Artifact> allArtifacts)
 {
     Dictionary<Artifact, int> descLengths = new Dictionary<Artifact, int>();
     foreach (Artifact a in allArtifacts)
     {
         int len = a.Function.Length + a.CanadianSignificance.Length + a.TechSignificance.Length;
         if(len > 0)
             descLengths.Add(a, len);
     }
     descLengths = descLengths.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
     //descLengths = descLengths.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
     descLengthsList = descLengths.ToList();
 }
Example #18
0
 void ShowRecordsInTable()
 {
     if (CheckFileExist(ratingFilePath))
     {
         rating = new Dictionary<string, int>();
         var file = File.ReadAllLines(ratingFilePath, Encoding.UTF8);
         for (int i = 0; i < file.Length; i++)
         {
             string[] temp = file[i].Split(';');
             rating.Add(temp[0], Convert.ToInt16(temp[1]));
         }
         int n = 0;
         foreach (var line in rating.OrderByDescending(kvp => kvp.Value))
         {
             n++;
             app.dataTopPlayesTable.Rows.Add(n, line.Key, line.Value);
         }
         app.dataTopPlayesTable.AllowUserToResizeRows = false;
         app.dataTopPlayesTable.AllowUserToAddRows = false;
         app.dataTopPlayesTable.RowCount = 10;
     }
 }
Example #19
0
        public void Shuffle()
        {
            if (CardList.Count > 0)
            {
                if (Convert.ToBoolean(AppConfig.GetValue("UseNewShuffle")))
                {
                    string notes = Environment.NewLine + Environment.NewLine + "洗牌";
                    int N = CardList.Count;
                    notes += N.ToString() + "张:" + Environment.NewLine;
                    List<int> IntList = new List<int>(N);
                    for (int i = 0; i < N; i++)
                    {
                        IntList.Add(i);
                    }
                    Random rnd = new Random();
                    List<Card> CardListTemp1 = new List<Card>(N);
                    List<Card> CardListTemp2 = new List<Card>(N);
                    Dictionary<string, int> UnitNameDict = new Dictionary<string, int>();
                    foreach (Card card in CardList)
                    {
                        notes += card.CardName + Environment.NewLine;
                        if (UnitNameDict.Keys.Contains<string>(card.UnitName))
                        {
                            UnitNameDict[card.UnitName]++;
                        }
                        else
                        {
                            UnitNameDict.Add(card.UnitName, 1);
                        }
                    }
                    for (int i = 0; i < N; i++)
                    {
                        CardListTemp1.Add(null);
                    }
                    foreach (KeyValuePair<string, int> pair in UnitNameDict.OrderByDescending(pair => pair.Value))
                    {
                        List<int> IntListTemp = new List<int>();
                        IntListTemp.AddRange(IntList);
                        notes += "插入" + pair.Value.ToString() + "张" + pair.Key + Environment.NewLine;
                        int divides = IntList.Count / pair.Value;
                        int remain = IntList.Count % pair.Value;
                        for (int i = 0; i < pair.Value; i++)
                        {
                            int number;
                            int StartPos = 0;
                            int EndPos = 0;
                            if (remain != 0)
                            {
                                if (i == 0)
                                {
                                    StartPos = 0;
                                    EndPos = divides;
                                }
                                else if (i < remain)
                                {
                                    StartPos = i * (divides + 1);
                                    EndPos = StartPos + divides;
                                }
                                else if (i == remain)
                                {
                                    StartPos = remain * (divides + 1);
                                    EndPos = StartPos + divides - 1;
                                }
                                else
                                {
                                    StartPos = i * divides + remain;
                                    EndPos = StartPos + divides - 1;
                                }
                            }
                            else
                            {
                                StartPos = i * divides;
                                EndPos = (i + 1) * divides - 1;
                            }

                            number = rnd.Next(StartPos, EndPos + 1);
                            notes += "(" + StartPos.ToString() + "~" + EndPos.ToString() + ") => " + number.ToString() + " => ";
                            int cardtomovenumber = 0;
                            foreach (Card card in CardList)
                            {
                                if (card.UnitName == pair.Key)
                                {
                                    cardtomovenumber = CardList.IndexOf(card);
                                    break;
                                }
                            }
                            int cardnumbernew = IntList[number];
                            notes += cardnumbernew.ToString() + Environment.NewLine;
                            CardListTemp1.RemoveAt(cardnumbernew);
                            CardListTemp1.Insert(cardnumbernew, CardList[cardtomovenumber]);
                            IntListTemp.Remove(cardnumbernew);
                            CardList.RemoveAt(cardtomovenumber);
                        }
                        IntList = IntListTemp;
                    }
                    notes += Environment.NewLine + "平均分配后:" + Environment.NewLine;
                    foreach (Card card in CardListTemp1)
                    {
                        notes += card.CardName + Environment.NewLine;
                    }
                    int ShuffleTime = rnd.Next(5, 11);
                    notes += Environment.NewLine + "切洗" + ShuffleTime.ToString() + "次:" + Environment.NewLine;
                    for (int i = 0; i < ShuffleTime; i++)
                    {
                        CardListTemp2 = new List<Card>();
                        notes += "第" + (i + 1).ToString() + "次," + Environment.NewLine;
                        int StartPos = rnd.Next(CardListTemp1.Count);
                        int EndPos = rnd.Next(StartPos, CardListTemp1.Count);
                        for (int j = StartPos; j <= EndPos; j++)
                        {
                            CardListTemp2.Add(CardListTemp1[j]);
                        }
                        for (int j = 0; j < StartPos; j++)
                        {
                            CardListTemp2.Add(CardListTemp1[j]);
                        }
                        for (int j = EndPos + 1; j < CardListTemp1.Count; j++)
                        {
                            CardListTemp2.Add(CardListTemp1[j]);
                        }
                        notes += "将第" + (StartPos + 1).ToString() + "~" + (EndPos + 1).ToString() + "张卡抽出,置于最顶端后:" + Environment.NewLine;
                        foreach (Card card in CardListTemp2)
                        {
                            notes += card.CardName + Environment.NewLine;
                        }
                        CardListTemp1 = CardListTemp2;
                    }
                    CardList = CardListTemp1;
                    //using (StreamWriter writer = File.AppendText("ShuffleNotes.txt"))
                    //{
                    //    writer.Write(notes);
                    //}
                }
                else
                {
                    int N = CardList.Count;
                    int[] array = new int[N];
                    for (int i = 0; i < N; i++)
                    {
                        array[i] = i;
                    }
                    Random rnd = new Random();
                    for (int j = 0; j < N; j++)
                    {
                        int pos = rnd.Next(j, N);
                        int temp = array[pos];
                        array[pos] = array[j];
                        array[j] = temp;
                    }
                    List<Card> CardList_temp = new List<Card>();
                    for (int i = 0; i < N; i++)
                    {
                        CardList_temp.Add(CardList[array[i]]);
                    }
                    CardList = CardList_temp;
                }
            }
        }
		//get the k most repeating element in the array
		public static List<int> findTopK(int[] arr, int k){ //Time:O(nlogn) Space:O(n)
			//handle edge case
			if (k == 0 || arr.Length < k)
				return null;


			Dictionary<int,int> dt = new Dictionary<int, int> ();
			for (int i = 0; i < arr.Length; i++) { //put frequency info into dt
				if (dt.ContainsKey (arr [i]))
					dt [arr [i]]++;
				else
					dt.Add (arr [i], 1);
			}

			//convert dt to list, then sort the list
			List<KeyValuePair<int,int>> list= dt.OrderByDescending (o => o.Value).ToList ();
			List<int> result = new List<int> ();
			for (int i = 0; i < k; i++)
				result.Add (list [i].Key);
			return result;
		}
Example #21
0
        private void UpdateSuggestions()
        {
            Match m;

            suggestions.Clear();
            HaveSuggestions = false;

            if (string.IsNullOrEmpty(LastSelectedCulture))
            {
                AddDummySuggestion();
                return;
            }
            if (!LoadedCultureNames.Contains(LastSelectedCulture))
            {
                AddDummySuggestion();
                return;
            }
            SuggestionsCulture = CultureInfoName(new CultureInfo(LastSelectedCulture), false);
            //if (lastSelectedCulture == primaryCulture) return;

            TextKeyViewModel tk = selectedTextKeys != null && selectedTextKeys.Count > 0 ? selectedTextKeys[0] : null;
            if (tk == null || tk.CultureTextVMs.Count < 1)
            {
                AddDummySuggestion();
                return;
            }

            // The text we're finding translation suggestions for
            string refText = tk.CultureTextVMs[0].Text;
            string origRefText = refText;
            if (refText == null)
            {
                AddDummySuggestion();
                return;
            }

            //// Find the most common words to filter them out
            //Dictionary<string, int> wordCount = new Dictionary<string, int>();
            //foreach (var kvp in TextKeys)
            //{
            //    string otherBaseText = kvp.Value.CultureTextVMs[0].Text;
            //    if (string.IsNullOrEmpty(otherBaseText)) continue;

            //    // Remove all placeholders and key references
            //    string otherText = Regex.Replace(otherBaseText, @"(?<!\{)\{[^{]*?\}", "");

            //    // Extract all words
            //    m = Regex.Match(otherText, @"(\w{2,})");
            //    while (m.Success)
            //    {
            //        string lcWord = m.Groups[1].Value.ToLowerInvariant();

            //        int count;
            //        if (wordCount.TryGetValue(lcWord, out count))
            //        {
            //            wordCount[lcWord] = count + 1;
            //        }
            //        else
            //        {
            //            wordCount[lcWord] = 1;
            //        }

            //        m = m.NextMatch();
            //    }
            //}

            //HashSet<string> commonWords = new HashSet<string>();
            //if (wordCount.Count > 0)
            //{
            //    int maxCount = wordCount.Select(kvp => kvp.Value).Max();
            //    foreach (var kvp in wordCount.OrderByDescending(kvp => kvp.Value))
            //    {
            //        if (commonWords.Count < (int) (wordCount.Count * 0.05) ||
            //            kvp.Value >= (int) (maxCount * 0.8))
            //        {
            //            commonWords.Add(kvp.Key);
            //        }
            //    }
            //}

            //commonWords.Clear();
            //commonWords.Add("all");
            //commonWords.Add("also");
            //commonWords.Add("an");
            //commonWords.Add("and");
            //commonWords.Add("are");
            //commonWords.Add("as");
            //commonWords.Add("at");
            //commonWords.Add("be");
            //commonWords.Add("but");
            //commonWords.Add("by");
            //commonWords.Add("can");
            //commonWords.Add("cannot");
            //commonWords.Add("do");
            //commonWords.Add("don");
            //commonWords.Add("each");
            //commonWords.Add("for");
            //commonWords.Add("from");
            //commonWords.Add("have");
            //commonWords.Add("if");
            //commonWords.Add("in");
            //commonWords.Add("into");
            //commonWords.Add("is");
            //commonWords.Add("it");
            //commonWords.Add("its");
            //commonWords.Add("may");
            //commonWords.Add("must");
            //commonWords.Add("no");
            //commonWords.Add("not");
            //commonWords.Add("of");
            //commonWords.Add("on");
            //commonWords.Add("please");
            //commonWords.Add("that");
            //commonWords.Add("the");
            //commonWords.Add("there");
            //commonWords.Add("this");
            //commonWords.Add("those");
            //commonWords.Add("to");
            //commonWords.Add("were");
            //commonWords.Add("will");
            //commonWords.Add("with");
            //commonWords.Add("would");
            //commonWords.Add("you");
            //commonWords.Add("your");

            HashSet<string> commonWords;
            if (LastSelectedCulture.StartsWith("de"))
            {
                // GERMAN STOPWORDS
                // Zusammmengetragen von Marco Götze, Steffen Geyer
                // Last update: 2011-01-15
                // Source: http://solariz.de/649/deutsche-stopwords.htm
                // Via: http://en.wikipedia.org/wiki/Stop_words
                commonWords = new HashSet<string>(new string[]
                {
                    "ab", "aber", "abgerufen", "abgerufene", "abgerufener", "abgerufenes", "acht", "ähnlich", "alle", "allein", "allem",
                    "allen", "aller", "allerdings", "allerlei", "alles", "allgemein", "allmählich", "allzu", "als", "alsbald", "also",
                    "am", "an", "ander", "andere", "anderem", "anderen", "anderer", "andererseits", "anderes", "anderm", "andern",
                    "andernfalls", "anders", "anerkannt", "anerkannte", "anerkannter", "anerkanntes", "anfangen", "anfing", "angefangen",
                    "angesetze", "angesetzt", "angesetzten", "angesetzter", "ansetzen", "anstatt", "arbeiten", "auch", "auf", "aufgehört",
                    "aufgrund", "aufhören", "aufhörte", "aufzusuchen", "aus", "ausdrücken", "ausdrückt", "ausdrückte", "ausgenommen",
                    "außen", "ausser", "außer", "ausserdem", "außerdem", "außerhalb", "author", "autor", "bald", "bearbeite",
                    "bearbeiten", "bearbeitete", "bearbeiteten", "bedarf", "bedürfen", "bedurfte", "befragen", "befragte", "befragten",
                    "befragter", "begann", "beginnen", "begonnen", "behalten", "behielt", "bei", "beide", "beiden", "beiderlei", "beides",
                    "beim", "beinahe", "beitragen", "beitrugen", "bekannt", "bekannte", "bekannter", "bekennen", "benutzt", "bereits",
                    "berichten", "berichtet", "berichtete", "berichteten", "besonders", "besser", "bestehen", "besteht", "beträchtlich",
                    "bevor", "bezüglich", "bietet", "bin", "bis", "bis", "bisher", "bislang", "bist", "bleiben", "blieb", "bloß", "bloss",
                    "böden", "brachte", "brachten", "brauchen", "braucht", "bräuchte", "bringen", "bsp", "bzw", "ca", "da", "dabei",
                    "dadurch", "dafür", "dagegen", "daher", "dahin", "damals", "damit", "danach", "daneben", "dank", "danke", "danken",
                    "dann", "dannen", "daran", "darauf", "daraus", "darf", "darfst", "darin", "darüber", "darüberhinaus", "darum",
                    "darunter", "das", "daß", "dass", "dasselbe", "davon", "davor", "dazu", "dein", "deine", "deinem", "deinen", "deiner",
                    "deines", "dem", "demnach", "demselben", "den", "denen", "denn", "dennoch", "denselben", "der", "derart", "derartig",
                    "derem", "deren", "derer", "derjenige", "derjenigen", "derselbe", "derselben", "derzeit", "des", "deshalb",
                    "desselben", "dessen", "desto", "deswegen", "dich", "die", "diejenige", "dies", "diese", "dieselbe", "dieselben",
                    "diesem", "diesen", "dieser", "dieses", "diesseits", "dinge", "dir", "direkt", "direkte", "direkten", "direkter",
                    "doch", "doppelt", "dort", "dorther", "dorthin", "drauf", "drei", "dreißig", "drin", "dritte", "drüber", "drunter",
                    "du", "dunklen", "durch", "durchaus", "dürfen", "durfte", "dürfte", "durften", "eben", "ebenfalls", "ebenso", "ehe",
                    "eher", "eigenen", "eigenes", "eigentlich", "ein", "einbaün", "eine", "einem", "einen", "einer", "einerseits",
                    "eines", "einfach", "einführen", "einführte", "einführten", "eingesetzt", "einig", "einige", "einigem", "einigen",
                    "einiger", "einigermaßen", "einiges", "einmal", "eins", "einseitig", "einseitige", "einseitigen", "einseitiger",
                    "einst", "einstmals", "einzig", "ende", "entsprechend", "entweder", "er", "ergänze", "ergänzen", "ergänzte",
                    "ergänzten", "erhält", "erhalten", "erhielt", "erhielten", "erneut", "eröffne", "eröffnen", "eröffnet", "eröffnete",
                    "eröffnetes", "erst", "erste", "ersten", "erster", "es", "etc", "etliche", "etwa", "etwas", "euch", "euer", "eure",
                    "eurem", "euren", "eurer", "eures", "fall", "falls", "fand", "fast", "ferner", "finden", "findest", "findet",
                    "folgende", "folgenden", "folgender", "folgendes", "folglich", "fordern", "fordert", "forderte", "forderten",
                    "fortsetzen", "fortsetzt", "fortsetzte", "fortsetzten", "fragte", "frau", "frei", "freie", "freier", "freies", "fuer",
                    "fünf", "für", "gab", "gängig", "gängige", "gängigen", "gängiger", "gängiges", "ganz", "ganze", "ganzem", "ganzen",
                    "ganzer", "ganzes", "gänzlich", "gar", "gbr", "geb", "geben", "geblieben", "gebracht", "gedurft", "geehrt", "geehrte",
                    "geehrten", "geehrter", "gefallen", "gefälligst", "gefällt", "gefiel", "gegeben", "gegen", "gehabt", "gehen", "geht",
                    "gekommen", "gekonnt", "gemacht", "gemäss", "gemocht", "genommen", "genug", "gern", "gesagt", "gesehen", "gestern",
                    "gestrige", "getan", "geteilt", "geteilte", "getragen", "gewesen", "gewissermaßen", "gewollt", "geworden", "ggf",
                    "gib", "gibt", "gleich", "gleichwohl", "gleichzeitig", "glücklicherweise", "gmbh", "gratulieren", "gratuliert",
                    "gratulierte", "gute", "guten", "hab", "habe", "haben", "haette", "halb", "hallo", "hast", "hat", "hätt", "hatte",
                    "hätte", "hatten", "hätten", "hattest", "hattet", "heraus", "herein", "heute", "heutige", "hier", "hiermit",
                    "hiesige", "hin", "hinein", "hinten", "hinter", "hinterher", "hoch", "höchstens", "hundert", "ich", "igitt", "ihm",
                    "ihn", "ihnen", "ihr", "ihre", "ihrem", "ihren", "ihrer", "ihres", "im", "immer", "immerhin", "important", "in",
                    "indem", "indessen", "info", "infolge", "innen", "innerhalb", "ins", "insofern", "inzwischen", "irgend", "irgendeine",
                    "irgendwas", "irgendwen", "irgendwer", "irgendwie", "irgendwo", "ist", "ja", "jährig", "jährige", "jährigen",
                    "jähriges", "je", "jede", "jedem", "jeden", "jedenfalls", "jeder", "jederlei", "jedes", "jedoch", "jemand", "jene",
                    "jenem", "jenen", "jener", "jenes", "jenseits", "jetzt", "kam", "kann", "kannst", "kaum", "kein", "keine", "keinem",
                    "keinen", "keiner", "keinerlei", "keines", "keines", "keineswegs", "klar", "klare", "klaren", "klares", "klein",
                    "kleinen", "kleiner", "kleines", "koennen", "koennt", "koennte", "koennten", "komme", "kommen", "kommt", "konkret",
                    "konkrete", "konkreten", "konkreter", "konkretes", "könn", "können", "könnt", "konnte", "könnte", "konnten",
                    "könnten", "künftig", "lag", "lagen", "langsam", "längst", "längstens", "lassen", "laut", "lediglich", "leer",
                    "legen", "legte", "legten", "leicht", "leider", "lesen", "letze", "letzten", "letztendlich", "letztens", "letztes",
                    "letztlich", "lichten", "liegt", "liest", "links", "mache", "machen", "machst", "macht", "machte", "machten", "mag",
                    "magst", "mal", "man", "manche", "manchem", "manchen", "mancher", "mancherorts", "manches", "manchmal", "mann",
                    "margin", "mehr", "mehrere", "mein", "meine", "meinem", "meinen", "meiner", "meines", "meist", "meiste", "meisten",
                    "meta", "mich", "mindestens", "mir", "mit", "mithin", "mochte", "möchte", "möchten", "möchtest", "mögen", "möglich",
                    "mögliche", "möglichen", "möglicher", "möglicherweise", "morgen", "morgige", "muessen", "muesst", "muesste", "muss",
                    "muß", "müssen", "mußt", "musst", "müßt", "musste", "müßte", "müsste", "mussten", "müssten", "nach", "nachdem",
                    "nacher", "nachhinein", "nächste", "nacht", "nahm", "nämlich", "natürlich", "neben", "nebenan", "nehmen", "nein",
                    "neu", "neue", "neuem", "neuen", "neuer", "neues", "neun", "nicht", "nichts", "nie", "niemals", "niemand", "nimm",
                    "nimmer", "nimmt", "nirgends", "nirgendwo", "noch", "nötigenfalls", "nun", "nur", "nutzen", "nutzt", "nützt",
                    "nutzung", "ob", "oben", "oberhalb", "obgleich", "obschon", "obwohl", "oder", "oft", "ohne", "per", "pfui",
                    "plötzlich", "pro", "reagiere", "reagieren", "reagiert", "reagierte", "rechts", "regelmäßig", "rief", "rund", "sage",
                    "sagen", "sagt", "sagte", "sagten", "sagtest", "sämtliche", "sang", "sangen", "schätzen", "schätzt", "schätzte",
                    "schätzten", "schlechter", "schließlich", "schnell", "schon", "schreibe", "schreiben", "schreibens", "schreiber",
                    "schwierig", "sechs", "sect", "sehe", "sehen", "sehr", "sehrwohl", "seht", "sei", "seid", "sein", "seine", "seinem",
                    "seinen", "seiner", "seines", "seit", "seitdem", "seite", "seiten", "seither", "selber", "selbst", "senke", "senken",
                    "senkt", "senkte", "senkten", "setzen", "setzt", "setzte", "setzten", "sich", "sicher", "sicherlich", "sie", "sieben",
                    "siebte", "siehe", "sieht", "sind", "singen", "singt", "so", "sobald", "sodaß", "soeben", "sofern", "sofort", "sog",
                    "sogar", "solange", "solc hen", "solch", "solche", "solchem", "solchen", "solcher", "solches", "soll", "sollen",
                    "sollst", "sollt", "sollte", "sollten", "solltest", "somit", "sondern", "sonst", "sonstwo", "sooft", "soviel",
                    "soweit", "sowie", "sowohl", "später", "spielen", "startet", "startete", "starteten", "statt", "stattdessen", "steht",
                    "steige", "steigen", "steigt", "stets", "stieg", "stiegen", "such", "suchen", "tages", "tat", "tät", "tatsächlich",
                    "tatsächlichen", "tatsächlicher", "tatsächliches", "tausend", "teile", "teilen", "teilte", "teilten", "titel",
                    "total", "trage", "tragen", "trägt", "trotzdem", "trug", "tun", "tust", "tut", "txt", "übel", "über", "überall",
                    "überallhin", "überdies", "übermorgen", "übrig", "übrigens", "ueber", "um", "umso", "unbedingt", "und", "ungefähr",
                    "unmöglich", "unmögliche", "unmöglichen", "unmöglicher", "unnötig", "uns", "unse", "unsem", "unsen", "unser", "unser",
                    "unsere", "unserem", "unseren", "unserer", "unseres", "unserm", "unses", "unten", "unter", "unterbrach",
                    "unterbrechen", "unterhalb", "unwichtig", "usw", "vergangen", "vergangene", "vergangener", "vergangenes", "vermag",
                    "vermögen", "vermutlich", "veröffentlichen", "veröffentlicher", "veröffentlicht", "veröffentlichte",
                    "veröffentlichten", "veröffentlichtes", "verrate", "verraten", "verriet", "verrieten", "version", "versorge",
                    "versorgen", "versorgt", "versorgte", "versorgten", "versorgtes", "viel", "viele", "vielen", "vieler", "vieles",
                    "vielleicht", "vielmals", "vier", "völlig", "vollständig", "vom", "von", "vor", "voran", "vorbei", "vorgestern",
                    "vorher", "vorne", "vorüber", "wachen", "waere", "während", "während", "währenddessen", "wann", "war", "wär", "wäre",
                    "waren", "wären", "warst", "warum", "was", "weder", "weg", "wegen", "weil", "weiß", "weiter", "weitere", "weiterem",
                    "weiteren", "weiterer", "weiteres", "weiterhin", "welche", "welchem", "welchen", "welcher", "welches", "wem", "wen",
                    "wenig", "wenige", "weniger", "wenigstens", "wenn", "wenngleich", "wer", "werde", "werden", "werdet", "weshalb",
                    "wessen", "wichtig", "wie", "wieder", "wieso", "wieviel", "wiewohl", "will", "willst", "wir", "wird", "wirklich",
                    "wirst", "wo", "wodurch", "wogegen", "woher", "wohin", "wohingegen", "wohl", "wohlweislich", "wolle", "wollen",
                    "wollt", "wollte", "wollten", "wolltest", "wolltet", "womit", "woraufhin", "woraus", "worin", "wurde", "würde",
                    "wurden", "würden", "zahlreich", "zehn", "zeitweise", "ziehen", "zieht", "zog", "zogen", "zu", "zudem", "zuerst",
                    "zufolge", "zugleich", "zuletzt", "zum", "zumal", "zur", "zurück", "zusammen", "zuviel", "zwanzig", "zwar", "zwei",
                    "zwischen", "zwölf"
                });
            }
            else if (LastSelectedCulture.StartsWith("en"))
            {
                // English stop words
                // Source: http://norm.al/2009/04/14/list-of-english-stop-words/ (MySQL fulltext, from 2009-10-03)
                // Via: http://en.wikipedia.org/wiki/Stop_words
                commonWords = new HashSet<string>(new string[]
                {
                    "able", "about", "above", "according", "accordingly", "across", "actually", "after", "afterwards", "again", "against",
                    "ain", "all", "allow", "allows", "almost", "alone", "along", "already", "also", "although", "always", "am", "among",
                    "amongst", "an", "and", "another", "any", "anybody", "anyhow", "anyone", "anything", "anyway", "anyways", "anywhere",
                    "apart", "appear", "appreciate", "appropriate", "are", "aren", "around", "as", "aside", "ask", "asking", "associated",
                    "at", "available", "away", "awfully", "be", "became", "because", "become", "becomes", "becoming", "been", "before",
                    "beforehand", "behind", "being", "believe", "below", "beside", "besides", "best", "better", "between", "beyond",
                    "both", "brief", "but", "by", "mon", "came", "can", "cannot", "cause", "causes", "certain", "certainly", "changes",
                    "clearly", "co", "com", "come", "comes", "concerning", "consequently", "consider", "considering", "contain",
                    "containing", "contains", "corresponding", "could", "couldn", "course", "currently", "definitely", "described",
                    "despite", "did", "didn", "different", "do", "does", "doesn", "doing", "don", "done", "down", "downwards", "during",
                    "each", "edu", "eg", "eight", "either", "else", "elsewhere", "enough", "entirely", "especially", "et", "etc", "even",
                    "ever", "every", "everybody", "everyone", "everything", "everywhere", "ex", "exactly", "example", "except", "far",
                    "few", "fifth", "first", "five", "followed", "following", "follows", "for", "former", "formerly", "forth", "four",
                    "from", "further", "furthermore", "get", "gets", "getting", "given", "gives", "go", "goes", "going", "gone", "got",
                    "gotten", "greetings", "had", "hadn", "happens", "hardly", "has", "hasn", "have", "haven", "having", "he", "hello",
                    "help", "hence", "her", "here", "hereafter", "hereby", "herein", "hereupon", "hers", "herself", "hi", "him",
                    "himself", "his", "hither", "hopefully", "how", "howbeit", "however", "if", "ignored", "immediate", "in", "inasmuch",
                    "inc", "indeed", "indicate", "indicated", "indicates", "inner", "insofar", "instead", "into", "inward", "is", "isn",
                    "it", "its", "itself", "just", "keep", "keeps", "kept", "know", "knows", "known", "last", "lately", "later", "latter",
                    "latterly", "least", "less", "lest", "let", "like", "liked", "likely", "little", "ll", "look", "looking", "looks",
                    "ltd", "mainly", "many", "may", "maybe", "me", "mean", "meanwhile", "merely", "might", "more", "moreover", "most",
                    "mostly", "much", "must", "my", "myself", "name", "namely", "nd", "near", "nearly", "necessary", "need", "needs",
                    "neither", "never", "nevertheless", "new", "next", "nine", "no", "nobody", "non", "none", "noone", "nor", "normally",
                    "not", "nothing", "novel", "now", "nowhere", "obviously", "of", "off", "often", "oh", "ok", "okay", "old", "on",
                    "once", "one", "ones", "only", "onto", "or", "other", "others", "otherwise", "ought", "our", "ours", "ourselves",
                    "out", "outside", "over", "overall", "own", "particular", "particularly", "per", "perhaps", "placed", "please",
                    "plus", "possible", "presumably", "probably", "provides", "que", "quite", "qv", "rather", "rd", "re", "really",
                    "reasonably", "regarding", "regardless", "regards", "relatively", "respectively", "right", "said", "same", "saw",
                    "say", "saying", "says", "second", "secondly", "see", "seeing", "seem", "seemed", "seeming", "seems", "seen", "self",
                    "selves", "sensible", "sent", "serious", "seriously", "seven", "several", "shall", "she", "should", "shouldn",
                    "since", "six", "so", "some", "somebody", "somehow", "someone", "something", "sometime", "sometimes", "somewhat",
                    "somewhere", "soon", "sorry", "specified", "specify", "specifying", "still", "sub", "such", "sup", "sure", "take",
                    "taken", "tell", "tends", "th", "than", "thank", "thanks", "thanx", "that", "thats", "the", "their", "theirs", "them",
                    "themselves", "then", "thence", "there", "thereafter", "thereby", "therefore", "therein", "theres", "thereupon",
                    "these", "they", "think", "third", "this", "thorough", "thoroughly", "those", "though", "three", "through",
                    "throughout", "thru", "thus", "to", "together", "too", "took", "toward", "towards", "tried", "tries", "truly", "try",
                    "trying", "twice", "two", "un", "under", "unfortunately", "unless", "unlikely", "until", "unto", "up", "upon", "us",
                    "use", "used", "useful", "uses", "using", "usually", "value", "various", "ve", "very", "via", "viz", "vs", "want",
                    "wants", "was", "wasn", "way", "we", "welcome", "well", "went", "were", "weren", "what", "whatever", "when", "whence",
                    "whenever", "where", "whereafter", "whereas", "whereby", "wherein", "whereupon", "wherever", "whether", "which",
                    "while", "whither", "who", "whoever", "whole", "whom", "whose", "why", "will", "willing", "wish", "with", "within",
                    "without", "won", "wonder", "would", "would", "wouldn", "yes", "yet", "you", "your", "yours", "yourself",
                    "yourselves", "zero"
                });
            }
            else
            {
                commonWords = new HashSet<string>();
            }

            // Remove all placeholders and key references
            refText = Regex.Replace(refText, @"(?<!\{)\{[^{]*?\}", "");

            // Extract all words
            List<string> refWords = new List<string>();
            m = Regex.Match(refText, @"(\w{2,})");
            while (m.Success)
            {
                if (!commonWords.Contains(m.Groups[1].Value.ToLowerInvariant()))   // Skip common words
                    refWords.Add(m.Groups[1].Value);
                m = m.NextMatch();
            }

            // Find other text keys that contain these words in their primary culture text
            Dictionary<TextKeyViewModel, float> otherKeys = new Dictionary<TextKeyViewModel, float>();
            foreach (var kvp in TextKeys)
            {
                if (kvp.Value.TextKey == tk.TextKey) continue;   // Skip currently selected item
                if (kvp.Value.TextKey.StartsWith("Tx:")) continue;   // Skip system keys

                float score = 0;
                bool isExactMatch = false;
                string otherBaseText = kvp.Value.CultureTextVMs[0].Text;
                string otherTranslatedText = kvp.Value.CultureTextVMs.First(ct => ct.CultureName == LastSelectedCulture).Text;

                if (string.IsNullOrEmpty(otherBaseText)) continue;
                if (string.IsNullOrEmpty(otherTranslatedText)) continue;

                if (otherBaseText == origRefText)
                {
                    // Both keys' primary translation matches exactly
                    isExactMatch = true;
                }

                // Remove all placeholders and key references
                string otherText = Regex.Replace(otherBaseText, @"(?<!\{)\{[^{]*?\}", "");

                // Extract all words
                List<string> otherWords = new List<string>();
                m = Regex.Match(otherText, @"(\w{2,})");
                while (m.Success)
                {
                    if (!commonWords.Contains(m.Groups[1].Value.ToLowerInvariant()))   // Skip common words
                        otherWords.Add(m.Groups[1].Value);
                    m = m.NextMatch();
                }

                // Increase score by 1 for each case-insensitively matching word
                foreach (string word in refWords)
                {
                    if (otherWords.Any(w => string.Equals(w, word, StringComparison.InvariantCultureIgnoreCase)))
                        score += 1;
                }
                // Increase score by 2 for each case-sensitively matching word
                foreach (string word in refWords)
                {
                    if (otherWords.Any(w => string.Equals(w, word, StringComparison.InvariantCulture)))
                        score += 2;
                }

                // Divide by the square root of the number of relevant words. (Using the square
                // root to reduce the effect for very long texts.)
                if (otherWords.Count > 0)
                {
                    score /= (float) Math.Sqrt(otherWords.Count);
                }
                else
                {
                    // There are no significant words in the other text
                    score = 0;
                }

                if (isExactMatch)
                {
                    score = 100000;
                }

                // Accept every text key with a threshold score
                if (score >= 0.5f)
                {
                    otherKeys.Add(kvp.Value, score);
                }
            }

            // Sort all matches by their score
            foreach (var kvp in otherKeys.OrderByDescending(kvp => kvp.Value))
            {
                try
                {
                    SuggestionViewModel suggestion = new SuggestionViewModel(this);
                    suggestion.TextKey = kvp.Key.TextKey;
                    suggestion.BaseText = kvp.Key.CultureTextVMs[0].Text;
                    if (LastSelectedCulture != PrimaryCulture)
                        suggestion.TranslatedText = kvp.Key.CultureTextVMs.First(ct => ct.CultureName == LastSelectedCulture).Text;
                    suggestion.IsExactMatch = kvp.Value >= 100000;
                    suggestion.ScoreNum = kvp.Value;
                    if (suggestion.IsExactMatch)
                        suggestion.Score = Tx.T("suggestions.exact match");
                    else
                        suggestion.Score = kvp.Value.ToString("0.00");
                    suggestions.Add(suggestion);
                }
                catch
                {
                    // Something's missing (probably a LINQ-related exception), ignore that item
                }
            }

            if (suggestions.Count == 0)
            {
                AddDummySuggestion();
            }
            else
            {
                HaveSuggestions = true;
            }
        }
Example #22
0
 public List<Dictionary<int, int>> GetLotteryDataMaxFrequency(List<LotteryBaseInfo> baseInfoList)
 {
     List<Dictionary<int, int>> maxList = new List<Dictionary<int, int>>();
     Dictionary<int, int> maxRedDict = new Dictionary<int, int>();
     Dictionary<int, int> maxBlueDict = new Dictionary<int, int>();
     Dictionary<int, int> redDict = new Dictionary<int, int>();
     Dictionary<int, int> blueDict = new Dictionary<int, int>();
     if (baseInfoList != null)
     {
         foreach (var baseinfo in baseInfoList)
         {
             if (baseinfo.DetailInfo.result != null)
             {
                 ArrayList result = (ArrayList)baseinfo.DetailInfo.result["result"];
                 foreach (var i in result)
                 {
                     Dictionary<string, object> ballDict = (Dictionary<string, object>)i;
                     string ballColor = ballDict["key"].ToString();
                     ArrayList ballData = (ArrayList)ballDict["data"];
                     if (ballColor == "red")
                     {
                         foreach (var num in ballData)
                         {
                             if (redDict.Keys.Contains(int.Parse(num.ToString())))
                             {
                                 redDict[int.Parse(num.ToString())] += 1;
                             }
                             else
                             {
                                 redDict[int.Parse(num.ToString())] = 1;
                             }
                         }
                     }
                     if (ballColor == "blue")
                     {
                         foreach (var num in ballData)
                         {
                             if (blueDict.Keys.Contains(int.Parse(num.ToString())))
                             {
                                 blueDict[int.Parse(num.ToString())] += 1;
                             }
                             else
                             {
                                 blueDict[int.Parse(num.ToString())] = 1;
                             }
                         }
                     }
                 }
             }
         }
         maxRedDict = redDict.OrderByDescending(p=>p.Value).Take(6).OrderBy(p=>p.Key).ToDictionary(p=>p.Key,p=>p.Value);
         maxBlueDict = blueDict.OrderByDescending(p => p.Value).Take(1).OrderBy(p => p.Key).ToDictionary(p => p.Key, p => p.Value);
     }
     maxList.Add(maxRedDict);
     maxList.Add(maxBlueDict);
     return maxList;
 }
        private void BuildSummaryStatsByCapReport(StringBuilder sb)
        {
            ConsoleDisplayTable cdt = new ConsoleDisplayTable();
            cdt.AddColumn("Name", 34);
            cdt.AddColumn("Req Received", 12);
            cdt.AddColumn("Req Handled", 12);
            cdt.Indent = 2;

            Dictionary<string, int> receivedStats = new Dictionary<string, int>();
            Dictionary<string, int> handledStats = new Dictionary<string, int>();

            m_scene.ForEachScenePresence(
                sp =>
                {
                    Caps caps = m_scene.CapsModule.GetCapsForUser(sp.UUID);

                    if (caps == null)
                        return;            

                    foreach (IRequestHandler reqHandler in caps.CapsHandlers.GetCapsHandlers().Values)
                    {
                        string reqName = reqHandler.Name ?? "";

                        if (!receivedStats.ContainsKey(reqName))
                        {
                            receivedStats[reqName] = reqHandler.RequestsReceived;
                            handledStats[reqName] = reqHandler.RequestsHandled;
                        }
                        else
                        {
                            receivedStats[reqName] += reqHandler.RequestsReceived;
                            handledStats[reqName] += reqHandler.RequestsHandled;
                        }
                    }

                    foreach (KeyValuePair<string, PollServiceEventArgs> kvp in caps.GetPollHandlers())
                    {
                        string name = kvp.Key;
                        PollServiceEventArgs pollHandler = kvp.Value;

                        if (!receivedStats.ContainsKey(name))
                        {
                            receivedStats[name] = pollHandler.RequestsReceived;
                            handledStats[name] = pollHandler.RequestsHandled;
                        }
                            else
                        {
                            receivedStats[name] += pollHandler.RequestsReceived;
                            handledStats[name] += pollHandler.RequestsHandled;
                        }
                    }
                }
            );
                    
            foreach (KeyValuePair<string, int> kvp in receivedStats.OrderByDescending(kp => kp.Value))
                cdt.AddRow(kvp.Key, kvp.Value, handledStats[kvp.Key]);

            sb.Append(cdt.ToString());
        }
        // The engineLoop thread executes RunEngine() function. This thread waits until a signal is received
        // (frameReady.WaitOne()). In this case, the signal means that the copy of frame bytes is ready.
        // Since the engineLoop thread is not the UI thread (the thread which manages the interface), 
        // it cannot modify objects belonging to the interface. A Dispatcher object (the last line of the function) 
        // is necessary for updating the interface.
        private void RunEngine()
        {
            while (kinect.frameReady.WaitOne())
            {
                content = engine.Process(imageIntPr + 1, fWidth, fHeight, 1U, kinect.pixelFeed, lineFeed, 0, "GRAYSCALE");

                if (content == null) return;

                Canvas_Shore.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                new Action(delegate()
                {
                    Canvas_Shore.Children.Clear();
                }));


                List<Subject> sh = new List<Subject>() { };

                for (uint i = 0; i < content.GetObjectCount(); i++)
                {
                    try
                    {
                        ShoreNetObject sObj = content.GetObject(i);
                        if (sObj.GetShoreType() == "Face")
                        {
                            bool present = false;
                            System.Windows.Point middleEyes = new System.Windows.Point((sObj.GetMarkerOf("LeftEye").GetX() + sObj.GetMarkerOf("RightEye").GetX()) / 2, sObj.GetMarkerOf("LeftEye").GetY());

                            sceneSubjectsCopy = sceneSubjects.ToList();

                            for (int j = 0; j < sceneSubjectsCopy.Count; j++)
                            {
                                if (sceneSubjectsCopy[j].normalizedspincenter_xy != null)
                                {
                                    //calcolo lo spine
                                    double zeta = sceneSubjectsCopy[j].spincenter_xyz[2];

                                    System.Windows.Point spinInCanvas = new System.Windows.Point();
                                    if (sceneSubjectsCopy[j].trackedState)
                                        spinInCanvas = new System.Windows.Point((int)(sceneSubjectsCopy[j].normalizedspincenter_xy[0] * kinect.sensor.DepthStream.FrameWidth),
                                            (int)(kinect.sensor.DepthStream.FrameHeight - (sceneSubjectsCopy[j].normalizedspincenter_xy[1] * kinect.sensor.DepthStream.FrameHeight)));
                                    else
                                        spinInCanvas = new System.Windows.Point((int)(sceneSubjectsCopy[j].normalizedspincenter_xy[0] * kinect.sensor.ColorStream.FrameWidth),
                                            (int)(kinect.sensor.ColorStream.FrameHeight - (sceneSubjectsCopy[j].normalizedspincenter_xy[1] * kinect.sensor.ColorStream.FrameHeight)));




                                    double ErrorX = spinInCanvas.X - middleEyes.X; 

                                    if (Math.Abs(ErrorX) < DeltaErrorX)
                                    {
                                        try
                                        {
                                            sceneSubjects[j].gender = (sObj.GetAttributeOf("Gender") == "Female") ?  "Female" :"Male";
                                            sceneSubjects[j].age = (int)sObj.GetRatingOf("Age"); 
                                            sceneSubjects[j].happiness_ratio = sObj.GetRatingOf("Happy"); 
                                            sceneSubjects[j].surprise_ratio = sObj.GetRatingOf("Surprised"); 
                                            sceneSubjects[j].anger_ratio = sObj.GetRatingOf("Angry"); 
                                            sceneSubjects[j].sadness_ratio =sObj.GetRatingOf("Sad");  
                                            sceneSubjects[j].uptime = sObj.GetRatingOf("Uptime");
                                            sceneSubjects[j].middleeyes_xy = new List<float>() { (float)middleEyes.X, (float)middleEyes.Y };

                                            present = true;
                                        }
                                        catch (Exception e)
                                        {
                                            Console.WriteLine("Shore Error" + e.Message);
                                        }
                                        
                                        break;
                                    }
                                }
                            }

                            if (!present)
                            {
                            
                                Subject newSub = new Subject();
                                newSub.idKinect = 0;
                                newSub.angle = 0;
                                newSub.gender = (sObj.GetAttributeOf("Gender") == "Female") ? "Female" : "Male";
                                newSub.age = (int)sObj.GetRatingOf("Age");
                                newSub.happiness_ratio = sObj.GetRatingOf("Happy");
                                newSub.surprise_ratio = sObj.GetRatingOf("Surprised");
                                newSub.anger_ratio = sObj.GetRatingOf("Angry");
                                newSub.sadness_ratio = sObj.GetRatingOf("Sad");
                                newSub.uptime = sObj.GetRatingOf("Uptime");
                                newSub.middleeyes_xy = new List<float>() { (float)middleEyes.X, (float)middleEyes.Y };

                                newSub.normalizedspincenter_xy = new List<float>() { };
                                newSub.spincenter_xyz = new List<float>() { };
                                newSub.lefthand_xyz = new List<float>(){ };
                                newSub.righthand_xyz = new List<float>() { };
                                newSub.head_xyz = new List<float>() { };
                                newSub.leftwrist_xyz = new List<float>(){ };
                                newSub.rightwrist_xyz = new List<float>() { };
                                newSub.leftelbow_xyz = new List<float>() { };
                                newSub.rightelbow_xyz = new List<float>() { };
                                newSub.leftshoulder_xyz = new List<float>() { };
                                newSub.rightshoulder_xyz = new List<float>() { };

                                sh.Add(newSub);


                            }

                            #region draw in canvas

                            Dictionary<string, float> expRatio = new Dictionary<string, float>() 
                            {
                                { "Angry", sObj.GetRatingOf("Angry") },
                                { "Happy", sObj.GetRatingOf("Happy") },
                                { "Sad", sObj.GetRatingOf("Sad") },
                                { "Surprised", sObj.GetRatingOf("Surprised") }
                            };
                            float ratioVal = (float)Math.Round((decimal)expRatio.Values.Max(), 1);
                            string ratioName = expRatio.OrderByDescending(kvp => kvp.Value).First().Key;

                            // Draw subject information: Gender, age +/- deviation, expression, expression rate
                            StringBuilder sb = new StringBuilder();
                            sb.AppendLine(sObj.GetAttributeOf("Gender"));
                            sb.AppendLine("Age: " + sObj.GetRatingOf("Age") + " +/- " + sObj.GetRatingOf("AgeDeviation"));
                            sb.AppendLine(ratioName + ": " + ratioVal + "%");
                            
                          
                           

                           
                            double width = Math.Abs(sObj.GetRegion().GetLeft() - sObj.GetRegion().GetRight());
                            double height = Math.Abs(sObj.GetRegion().GetTop() - sObj.GetRegion().GetBottom());
                            double left = sObj.GetRegion().GetLeft();
                            double top = sObj.GetRegion().GetTop();
                            double bottom =  sObj.GetRegion().GetBottom();
                            string gender = sObj.GetAttributeOf("Gender");

                            Canvas_Shore.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                            new Action(delegate()
                            {
                                Rectangle rect = new Rectangle();
                                rect.Width = width;
                                rect.Height = height;
                                rect.StrokeThickness = 2;
                                rect.Stroke = (gender == "Female") ? Brushes.Fuchsia : Brushes.Cyan;
                                rect.Margin = new Thickness(left, top, 0, 0); //draw the rectangle

                                Label lab = new Label
                                {
                                    Foreground = (gender == "Female") ? Brushes.Fuchsia : Brushes.Cyan,
                                    FontSize = 12,
                                    FontWeight = FontWeights.Bold,
                                    Content = sb.ToString(),
                                    Opacity = 1,
                                    Margin = new Thickness(left,bottom, 0, 0) //draw under the rectangle
                                };


                                    Canvas_Shore.Children.Add(rect);
                                    Canvas_Shore.Children.Add(lab);

                              
                            }));
                            #endregion
                        }
                    }
                    catch(Exception e) 
                    {
                        Console.WriteLine("error shore" + e.Message);

                    }
                }

                sceneSubjectsShore = sh;
               
            }
        }
        /// <summary>
        /// Determine popularity of classes for the selection process using the lists
        /// </summary>
        public void verifyPopularity()
        {
            AllClasses = new Dictionary<String, int>();

            ThirdClasses = new Dictionary<String, int>();
            SecondClasses = new Dictionary<String, int>();
            FirstClasses = new Dictionary<String, int>();

            foreach(Presenter currentPresenter in presenterList)
            {
                AllClasses.Add(currentPresenter.PresenterTitle, 0);

                #region Loop over all requests and populate dictionaries
                foreach (Request currentRequest in requestList)
                {
                    string presenterName = currentPresenter.PresenterTitle;
                    if (currentRequest.RequestOne.Equals(presenterName) || currentRequest.RequestTwo.Equals(presenterName) || currentRequest.RequestThree.Equals(presenterName) || currentRequest.RequestFour.Equals(presenterName) || currentRequest.RequestFive.Equals(presenterName))
                    {
                        if (AllClasses.ContainsKey(presenterName))
                        {
                            int currentCount = AllClasses[presenterName];
                            ++currentCount;
                            AllClasses[presenterName] = currentCount;
                        }
                        else
                        {
                            AllClasses.Add(presenterName, 1);
                        }
                    }

                    if (currentRequest.RequestThree.Equals(presenterName) )
                    {
                        if (ThirdClasses.ContainsKey(presenterName))
                        {
                            int currentCount = ThirdClasses[presenterName];
                            ++currentCount;
                            ThirdClasses[presenterName] = currentCount;
                        }
                        else
                        {
                            ThirdClasses.Add(presenterName, 1);
                        }
                    }

                    if (currentRequest.RequestTwo.Equals(presenterName) )
                    {
                        if (SecondClasses.ContainsKey(presenterName))
                        {
                            int currentCount = SecondClasses[presenterName];
                            ++currentCount;
                            SecondClasses[presenterName] = currentCount;
                        }
                        else
                        {
                            SecondClasses.Add(presenterName, 1);
                        }
                    }

                    if (currentRequest.RequestOne.Equals(presenterName))
                    {
                        if (FirstClasses.ContainsKey(presenterName))
                        {
                            int currentCount = FirstClasses[presenterName];
                            ++currentCount;
                            FirstClasses[presenterName] = currentCount;
                        }
                        else
                        {
                            FirstClasses.Add(presenterName, 1);
                        }
                    }
                }
            #endregion
            }

            AllClasses = AllClasses.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
            ThirdClasses = ThirdClasses.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
            SecondClasses = SecondClasses.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
            FirstClasses = FirstClasses.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
        }
Example #26
0
        public static IEnumerable<List<CrawlItem>> SearchPropertiesSmart(this HtmlDocument doc2,
            ICollection<CrawlItem> existItems = null, bool isAttrEnabled = false)
        {
            if (existItems == null)
                existItems = new List<CrawlItem>();
            var shortv = "";
            if (existItems.Count > 1)
            {
                shortv =
                    XPath.GetMaxCompareXPath(existItems.Select(d => new XPath(d.XPath)).ToList()).ToString();
                yield return GetDiffNodes(doc2, shortv, isAttrEnabled, existItems);
            }
            else if (existItems.Count == 1)
            {
                var realPath = new XPath(existItems.First().XPath);
                var array =
                    realPath.SelectAll(d => true)
                        .Select(d => new XPath(realPath.Take(d)).ToString()).ToList();
                var dict = new Dictionary<string, double>();
                foreach (var item in array)
                {
                    GetTableRootProbability(
                        doc2.DocumentNode.SelectSingleNode(item)
                            .ChildNodes.Where(d2 => d2.Name.Contains("#") == false)
                            .ToList(), dict, false);
                }

                foreach (
                    var  item in
                        dict.OrderByDescending(d => d.Value))
                {
                    shortv = item.Key;
                    yield return GetDiffNodes(doc2, shortv, isAttrEnabled, existItems);
                }
            }
            else
            {
                var dict = new Dictionary<string, double>();
                GetTableRootProbability(
                    doc2.DocumentNode.ChildNodes.Where(d => d.Name.Contains("#") == false).ToList(), dict, true);
                IEnumerable<KeyValuePair<string, double>> p = dict.OrderByDescending(d => d.Value);
                foreach (var keyValuePair in p)
                {
                    var items = GetDiffNodes(doc2, keyValuePair.Key, isAttrEnabled, existItems);
                    if (items.Count > 1)
                        yield return items;
                }
            }
        }
Example #27
0
        /// <summary>
        /// Gets the most popular entries for the blog by the number of page views
        /// </summary>
        /// <param name="blogItem">The blog to find the most popular pages for</param>
        /// <param name="maxCount">The maximum number of entries to return</param>
        /// <returns>An array of EntryItem classes</returns>
        public virtual EntryItem[] GetPopularEntriesByView(Item blogItem, int maxCount)
        {
            if (AnalyticsEnabled())
            {
                var blogEntries = GetBlogEntries(blogItem);
                var entryIds = (from entry in blogEntries select entry.ID).ToArray();

                if (entryIds.Any())
                {
                    var views = new Dictionary<ID, long>();

                    foreach (var id in entryIds)
                    {
                        var itemViews = GetItemViews(id);

                        if (itemViews > 0)
                            views.Add(id, itemViews);
                    }

                    var ids = views.OrderByDescending(x => x.Value).Take(maxCount).Select(x => x.Key).ToArray();

                    return (from id in ids select blogEntries.First(i => i.ID == id)).ToArray();
                }
            }
            else
            {
                Logger.Warn("Sitecore.Analytics must be enabled to get popular entries by view.", this);
            }
            return new EntryItem[0];
        }
        public StringBuilder FillSectionData(string contents, string json)
        {
            var sectionMatches = SectionRegex.Matches(contents);
            var sections = new Dictionary<string, SectionData>();

            foreach (Match match in sectionMatches)
            {
                // extract the matched sections into variables 
                var sectionData = match.Value.Split(':');
                var operation = sectionData[1];
                var name = sectionData[2].TrimEnd('#', '-', '>');

                if (!sections.ContainsKey(name))
                    sections.Add(name, new SectionData() { NameLength = name.Length });

                switch (operation)
                {
                    case "start":
                        sections[name].Start = match.Index + match.Length;
                        break;
                    case "stop":
                        sections[name].Stop = match.Index;
                        sections[name].Contents = contents.Substring(sections[name].Start, sections[name].Stop - sections[name].Start).Trim(' ', '\n', '\t', '\r');
                        break;
                }
            }

            // find the master for this template
            // ###master            
            // todo:
            // return an HTML error describing the missing
            var masterMatch = MasterRegex.Match(contents, 0);
            if (!masterMatch.Success)
                return new StringBuilder(contents, contents.Length * 2);

            var removal = sections.Values.OrderByDescending(_ => _.Stop);
            foreach (SectionData sd in removal)
            {
                // <!--####section:start:####-->
                // <!--####section:stop:####-->
                int start = sd.Start - sd.NameLength - 29;
                int stop = sd.Stop + sd.NameLength + 28;
                contents = contents.Remove(start, stop - start);
            }


            // remove the master tag from the render pipeline
            contents = contents.Remove(masterMatch.Index, masterMatch.Length);

            // this logic is only needed if there is a master template with sections
            // any content not in a section will be automatically assumed as the 
            // "content" section and appended to it (if it was already created)
            if (!sections.ContainsKey("contents"))
            {
                sections.Add("contents", new SectionData { });
                sections["contents"].Contents = contents.Trim(' ', '\n', '\t', '\r');
            }

            var masterPath = masterMatch.Value.Split(':')[1].TrimEnd('#');
            string master = _template.Render(masterPath, json);

            // recycle variable for efficiency
            sectionMatches = SectionRegex.Matches(master);

            // foreach section in the master, 
            // replace the section with the contents from the template
            // if the sections don't exist then leave them because there
            // might be default content

            var masterSections = new Dictionary<string, SectionData>();
            foreach (Match match in sectionMatches)
            {
                // extract the matched sections into variables
                var sectionData = match.Value.Split(':');
                var operation = sectionData[1];
                var name = sectionData[2].TrimEnd('#', '-', '>');

                if (!masterSections.ContainsKey(name))
                    masterSections.Add(name, new SectionData() { NameLength = name.Length });

                switch (operation)
                {
                    case "start":
                        masterSections[name].Start = match.Index + match.Length;
                        break;
                    case "stop":
                        masterSections[name].Stop = match.Index;
                        break;
                }
            }

            // use a pesamistic estimate for the length of the string builder (considering we might get donuts later
            var sb = new StringBuilder(master, (master.Length + sections.Sum(_ => _.Value.Contents.Length)) * 2);

            var replacement = masterSections.OrderByDescending(_ => _.Value.Stop);
            foreach (KeyValuePair<string, SectionData> kvp in replacement)
            {
                if (sections.ContainsKey(kvp.Key))
                {
                    sb.Remove(masterSections[kvp.Key].Start, masterSections[kvp.Key].Stop - masterSections[kvp.Key].Start);
                    sb.Insert(masterSections[kvp.Key].Start, "\n" + sections[kvp.Key].Contents + "\n");
                }
            }

            return sb;
        }
        private void RunResearchPlanner()
        {
            if (string.IsNullOrEmpty(this.empire.ResearchTopic))
            {
                //Added by McShooterz: random tech is less random, selects techs based on priority
                //Check for needs of empire
                        // Ship ship;
                        // int researchneeded = 0;

                        //if( ResourceManager.ShipsDict.TryGetValue(this.BestCombatShip, out ship))
                        //{
                        //    ship.shipData.TechScore / this.empire.Research
                        //}
                bool cybernetic = this.empire.data.Traits.Cybernetic > 0;
                bool atWar = false;
                bool highTaxes = false;
                bool lowResearch = false;
                bool lowincome = false;
                if (this.empire.GetRelations().Where(war => !war.Key.isFaction && ( war.Value.AtWar || war.Value.PreparingForWar)).Count() > 0)
                    atWar = true;
                if (this.empire.data.TaxRate >= .50f )
                    highTaxes = true;
                if (this.empire.GetPlanets().Sum(research => research.NetResearchPerTurn) < this.empire.GetPlanets().Count / 3)
                    lowResearch = true;
                int economics = 10-(int)(this.empire.Money / (this.empire.GrossTaxes +1));
                    //(int)(this.empire.data.TaxRate * 10 + this.empire.Money < this.empire.GrossTaxes?5:0);
                int needsFood =0;
                foreach(Planet hunger in this.empire.GetPlanets())
                {
                    if (cybernetic ? hunger.ProductionHere <1 : hunger.FoodHere <1)
                        needsFood++;

                }

                needsFood = needsFood>0 ? needsFood /this.empire.GetPlanets().Count :0;
                needsFood *= 10;
                //float moneyNeeded = this.empire.canBuildFrigates ? 25 : 0;
                //moneyNeeded = this.empire.canBuildCruisers ? 50 : moneyNeeded;
                //moneyNeeded = this.empire.canBuildCapitals ? 100 : moneyNeeded;
                //float money = this.empire.EstimateIncomeAtTaxRate(.5f) + this.empire.GetTotalShipMaintenance();
                //if (money < moneyNeeded)
                //{
                //    lowincome = true;
                //}
                switch (this.res_strat)
                {
                    case GSAI.ResearchStrategy.Random:
                    {

                        if (true)
                        {
                            Dictionary<string, int> priority = new Dictionary<string, int>();

                            priority.Add("SHIPTECH", HelperFunctions.GetRandomIndex(this.empire.getResStrat().MilitaryPriority + 4+ (atWar ? 6 : 2)));

                            priority.Add("Research", HelperFunctions.GetRandomIndex(this.empire.getResStrat().ResearchPriority +4+ (lowResearch ? 4 : 0)));
                            priority.Add("Colonization", HelperFunctions.GetRandomIndex(this.empire.getResStrat().ExpansionPriority + 4 +(!cybernetic?needsFood:0)));
                            priority.Add("Economic", HelperFunctions.GetRandomIndex(this.empire.getResStrat().ExpansionPriority +4+ (economics) ));
                            priority.Add("Industry", HelperFunctions.GetRandomIndex(this.empire.getResStrat().IndustryPriority + 4+ (cybernetic?needsFood:0)));
                            priority.Add("General", HelperFunctions.GetRandomIndex(4));
                            priority.Add("GroundCombat", HelperFunctions.GetRandomIndex(this.empire.getResStrat().MilitaryPriority +4+ (atWar ? 4 : 0)));

                            string sendToScript = "";
                            int max = 0;
                            foreach (KeyValuePair<string, int> pWeighted in priority.OrderByDescending(pri => pri.Value))
                            {
                                if (max > 3)
                                    break;
                                if (pWeighted.Value < 3 && !string.IsNullOrEmpty(sendToScript))
                                    continue;
                                //if (!string.IsNullOrEmpty(sendToScript))
                                sendToScript += ":";
                                if (pWeighted.Key == "SHIPTECH")
                                {
                                    sendToScript += "ShipWeapons:ShipDefense:ShipGeneral:ShipHull";
                                    max += 4;

                                }
                                else
                                {
                                    sendToScript += pWeighted.Key;
                                    max++;
                                }

                            }
                            if (ScriptedResearch("CHEAPEST", "TECH", "TECH"+sendToScript))
                                return;

                        }

                        //changed by gremlin exclude module tech that we dont have any ships that use it.
                        ConcurrentBag<Technology> AvailableTechs = new ConcurrentBag<Technology>();
                        //foreach (KeyValuePair<string, Ship_Game.Technology> Technology in ResourceManager.TechTree)

                        Parallel.ForEach(ResourceManager.TechTree, Technology =>
                        {
                            TechEntry tech = null;// new TechEntry();
                            bool techexists = this.empire.GetTDict().TryGetValue(Technology.Key, out tech);
                            if (!techexists || tech == null)
                                //continue;
                                return;
                            Technology technology = tech.GetTech();
                            if (tech.Unlocked
                                || !this.empire.HavePreReq(Technology.Key)
                                || (Technology.Value.Secret && !tech.Discovered)
                                || technology.BuildingsUnlocked.Where(winsgame => ResourceManager.BuildingsDict[winsgame.Name].WinsGame == true).Count() > 0
                                || !tech.shipDesignsCanuseThis
                                || (tech.shipDesignsCanuseThis && technology.ModulesUnlocked.Count > 0 && technology.HullsUnlocked.Count == 0
                                && !this.empire.WeCanUseThisNow(tech.GetTech())))
                            {
                                //continue;
                                return;
                            }
                            AvailableTechs.Add(Technology.Value);
                        });
                        if (AvailableTechs.Count == 0)
                            break;
                        foreach(Technology tech in AvailableTechs.OrderBy(tech => tech.Cost))
                        {
                            switch (tech.TechnologyType)
                            {
                                //case TechnologyType.ShipHull:
                                //    {
                                //        //Always research when able
                                //        this.empire.ResearchTopic = tech.UID;
                                //        break;
                                //    }
                                //case TechnologyType.ShipGeneral:
                                //    {
                                //        if (HelperFunctions.GetRandomIndex(4) == 3)
                                //            this.empire.ResearchTopic = tech.UID;
                                //        break;
                                //    }
                                //case TechnologyType.ShipWeapons:
                                //    {
                                //        if(atWar || HelperFunctions.GetRandomIndex(this.empire.getResStrat().MilitaryPriority + 4) > 2)
                                //            this.empire.ResearchTopic = tech.UID;
                                //        break;
                                //    }
                                //case TechnologyType.ShipDefense:
                                //    {
                                //        if (atWar || HelperFunctions.GetRandomIndex(this.empire.getResStrat().MilitaryPriority + 4) > 2)
                                //            this.empire.ResearchTopic = tech.UID;
                                //        break;
                                //    }
                                case TechnologyType.GroundCombat:
                                    {
                                        if (atWar || HelperFunctions.GetRandomIndex(this.empire.getResStrat().MilitaryPriority + 4) > 2)
                                            this.empire.ResearchTopic = tech.UID;
                                        break;
                                    }
                                case TechnologyType.Economic:
                                    {
                                        if (highTaxes || HelperFunctions.GetRandomIndex(this.empire.getResStrat().ExpansionPriority + 4) > 2)
                                            this.empire.ResearchTopic = tech.UID;
                                        break;
                                    }
                                case TechnologyType.Research:
                                    {
                                        if (lowResearch || HelperFunctions.GetRandomIndex(this.empire.getResStrat().ResearchPriority + 4) > 2)
                                            this.empire.ResearchTopic = tech.UID;
                                        break;
                                    }
                                case TechnologyType.Industry:
                                    {
                                        if (HelperFunctions.GetRandomIndex(this.empire.getResStrat().IndustryPriority + 4) > 2)
                                            this.empire.ResearchTopic = tech.UID;
                                        break;
                                    }
                                case TechnologyType.Colonization:
                                    {
                                        if (HelperFunctions.GetRandomIndex(this.empire.getResStrat().ExpansionPriority + 4) > 2)
                                            this.empire.ResearchTopic = tech.UID;
                                        break;
                                    }
                                default:
                                    {
                                        break;
                                    }
                            }
                            if (!string.IsNullOrEmpty(this.empire.ResearchTopic))
                                break;
                        }
                        if (string.IsNullOrEmpty(this.empire.ResearchTopic))
                            this.empire.ResearchTopic = AvailableTechs.OrderBy(tech => tech.Cost).First().UID;
                        break;
                    }
                    case GSAI.ResearchStrategy.Scripted:
                    {
                        int loopcount = 0;
                    Start:
                        if (this.empire.getResStrat() != null && ScriptIndex < this.empire.getResStrat().TechPath.Count &&loopcount < this.empire.getResStrat().TechPath.Count)
                        {

                        string scriptentry = this.empire.getResStrat().TechPath[ScriptIndex].id;
                            string scriptCommand = this.empire.GetTDict().ContainsKey(scriptentry) ?  scriptentry:scriptentry.Split(':')[0];
                            switch (scriptCommand)
                            {

                                case  "SCRIPT":
                                    {

                                        string modifier ="";
                                        string[] script =scriptentry.Split(':');

                                        if(script.Count() >2)
                                        {
                                            modifier = script[2];

                                        }
                                        ScriptIndex++;
                                        if (ScriptedResearch("CHEAPEST",script[1], modifier))
                                            return;
                                        loopcount++;
                                        goto Start;
                                    }
                                case "LOOP":
                                        {
                                            ScriptIndex=int.Parse(this.empire.getResStrat().TechPath[ScriptIndex].id.Split(':')[1]);
                                            loopcount++;
                                            goto Start;
                                        }
                                case "CHEAPEST":
                                        {
                                        string modifier ="";
                                        string[] script =scriptentry.Split(':');

                                        if(script.Count() ==1)
                                        {
                                            this.res_strat = GSAI.ResearchStrategy.Random;
                                            this.RunResearchPlanner();
                                            this.res_strat = GSAI.ResearchStrategy.Scripted;
                                            ScriptIndex++;
                                            return;

                                        }
                                        string[] modifiers = new string[script.Count()-1];
                                        for(int i=1; i <script.Count();i++)
                                        {
                                            modifiers[i-1] =script[i];
                                        }
                                            modifier =String.Join(":",modifiers);
                                            ScriptIndex++;
                                            if (ScriptedResearch(scriptCommand, script[1], modifier))
                                            return;
                                        loopcount++;
                                        goto Start;

                                        }
                                case "EXPENSIVE":
                                        {
                                            string modifier = "";
                                            string[] script = scriptentry.Split(':');

                                            if (script.Count() == 1)
                                            {
                                                this.res_strat = GSAI.ResearchStrategy.Random;
                                                this.RunResearchPlanner();
                                                this.res_strat = GSAI.ResearchStrategy.Scripted;
                                                ScriptIndex++;
                                                return;

                                            }
                                            string[] modifiers = new string[script.Count() - 1];
                                            for (int i = 1; i < script.Count(); i++)
                                            {
                                                modifiers[i - 1] = script[i];
                                            }
                                            modifier = String.Join(":", modifiers);
                                            ScriptIndex++;
                                            if (ScriptedResearch(scriptCommand,script[1], modifier))
                                                return;
                                            loopcount++;
                                            goto Start;

                                        }
                                case "IFWAR":
                                        {
                                            if (atWar)
                                            {
                                                 ScriptIndex=int.Parse(this.empire.getResStrat().TechPath[ScriptIndex].id.Split(':')[1]);
                                                 loopcount++;
                                            goto Start;

                                            }
                                            ScriptIndex++;

                                            goto Start;

                                        }
                                case "IFHIGHTAX":
                                        {
                                            if (highTaxes)
                                            {
                                                ScriptIndex=int.Parse(this.empire.getResStrat().TechPath[ScriptIndex].id.Split(':')[1]);
                                                loopcount++;
                                            goto Start;
                                            }
                                            ScriptIndex++;

                                            goto  Start;
                                        }
                                case "IFPEACE":
                                        {
                                            if (!atWar)
                                            {
                                                ScriptIndex = int.Parse(this.empire.getResStrat().TechPath[ScriptIndex].id.Split(':')[1]);
                                                loopcount++;
                                                goto Start;
                                            }
                                            ScriptIndex++;

                                            goto Start;
                                        }
                                case "IFCYBERNETIC":
                                        {
                                            if(this.empire.data.Traits.Cybernetic>0 )//&& !this.empire.GetBDict()["Biospheres"])//==true)//this.empire.GetTDict().Where(biosphereTech=> biosphereTech.Value.GetTech().BuildingsUnlocked.Where(biosphere=> ResourceManager.BuildingsDict[biosphere.Name].Name=="Biospheres").Count() >0).Count() >0)
                                            {
                                                ScriptIndex = int.Parse(this.empire.getResStrat().TechPath[ScriptIndex].id.Split(':')[1]);
                                                loopcount++;
                                                goto Start;

                                            }
                                            ScriptIndex++;
                                            goto Start;
                                        }
                                case "IFLOWRESEARCH":
                                        {
                                            if (lowResearch)
                                            {
                                                ScriptIndex = int.Parse(this.empire.getResStrat().TechPath[ScriptIndex].id.Split(':')[1]);
                                                loopcount++;
                                                goto Start;

                                            }
                                            ScriptIndex++;
                                            goto Start;

                                        }
                                case "IFNOTLOWRESEARCH":
                                        {
                                            if (!lowResearch)
                                            {
                                                ScriptIndex = int.Parse(this.empire.getResStrat().TechPath[ScriptIndex].id.Split(':')[1]);
                                                loopcount++;
                                                goto Start;

                                            }
                                            ScriptIndex++;
                                            goto Start;

                                        }
                                case "IFLOWINCOME":
                                        {
                                            if (lowincome)
                                            {
                                                ScriptIndex = int.Parse(this.empire.getResStrat().TechPath[ScriptIndex].id.Split(':')[1]);
                                                loopcount++;
                                                goto Start;

                                            }
                                            ScriptIndex++;
                                            goto Start;

                                        }
                                case "IFNOTLOWINCOME":
                                        {
                                            if (!lowincome)
                                            {
                                                ScriptIndex = int.Parse(this.empire.getResStrat().TechPath[ScriptIndex].id.Split(':')[1]);
                                                loopcount++;
                                                goto Start;

                                            }
                                            ScriptIndex++;
                                            goto Start;

                                        }
                                case "RANDOM":
                                        {
                                            this.res_strat = GSAI.ResearchStrategy.Random;
                                            this.RunResearchPlanner();
                                            this.res_strat = GSAI.ResearchStrategy.Scripted;
                                            ScriptIndex++;
                                            return;
                                        }
                                default:
                                    {

                                        TechEntry defaulttech;
                                        if(this.empire.GetTDict().TryGetValue(scriptentry, out defaulttech))
                                        {
                                            if (defaulttech.Unlocked)

                                            {
                                                ScriptIndex++;
                                                goto Start;
                                            }
                                            if ( !defaulttech.Unlocked && this.empire.HavePreReq(defaulttech.UID))
                                            {
                                                this.empire.ResearchTopic = defaulttech.UID;
                                                ScriptIndex++;
                                                if (!string.IsNullOrEmpty(scriptentry))
                                                    return;
                                            }
                                        }
                                        else
                                        {
                                            System.Diagnostics.Debug.WriteLine("TechNotFound");
                                            System.Diagnostics.Debug.WriteLine(scriptentry);
                                        }

                                        foreach (EconomicResearchStrategy.Tech tech in this.empire.getResStrat().TechPath)
                                        {

                                            if (!this.empire.GetTDict().ContainsKey(tech.id) || this.empire.GetTDict()[tech.id].Unlocked || !this.empire.HavePreReq(tech.id))
                                            {

                                                    continue;
                                            }

                                            int X = GlobalStats.ScriptedTechWithin;
                                            List<TechEntry> unresearched = new List<TechEntry>();
                                            unresearched = this.empire.GetTDict().Values.Where(filter => !filter.Unlocked && filter.shipDesignsCanuseThis && (!filter.GetTech().Secret || !filter.Discovered) && this.empire.HavePreReq(filter.UID) && filter.GetTech().Cost > 0).OrderBy(cost => cost.GetTech().Cost).ToList();
                                            //foreach (TechEntry tech2 in unresearched)//this.empire.GetTDict().Values.Where(filter => !filter.Unlocked && !filter.GetTech().Secret&& filter.Discovered  && filter.GetTech().Cost > 0).OrderBy(cost => cost.GetTech().Cost))
                                            //{
                                            //    X--;
                                            //    if (tech2.UID == tech.id || tech2.GetTech().Cost >= ResourceManager.TechTree[tech.id].Cost * .25F)
                                            //        break;
                                            //    if (X <= 0)
                                            //    {
                                            //        this.res_strat = GSAI.ResearchStrategy.Random;
                                            //        this.RunResearchPlanner();
                                            //        this.res_strat = GSAI.ResearchStrategy.Scripted;
                                            //        ScriptIndex++;
                                            //        return;
                                            //    }

                                            //}

                                                this.empire.ResearchTopic = tech.id;
                                                ScriptIndex++;
                                            if(!string.IsNullOrEmpty(tech.id))
                                                    return;

                                        }
                                        this.res_strat = GSAI.ResearchStrategy.Random;
                                        ScriptIndex++;
                                        return;
                                    }
                            }
                        }
                        if (string.IsNullOrEmpty(this.empire.ResearchTopic))
                        {
                            this.res_strat = GSAI.ResearchStrategy.Random;
                        }
                            return;

                    }
                    default:
                    {
                        return;
                    }
                }
            }
        }
	    /// <summary>
        /// Retrieve all Buggs matching the search criteria.
	    /// </summary>
	    /// <returns></returns>
        private ReportsViewModel GetResults(string branchName, DateTime startDate, DateTime endDate, int BuggIDToBeAddedToJira)
	    {
	        // It would be great to have a CSV export of this as well with buggs ID being the key I can then use to join them :)
	        // 
	        // Enumerate JIRA projects if needed.
	        // https://jira.ol.epicgames.net//rest/api/2/project
	        var JC = JiraConnection.Get();
	        var JiraComponents = JC.GetNameToComponents();
	        var JiraVersions = JC.GetNameToVersions();

	        using (FAutoScopedLogTimer LogTimer = new FAutoScopedLogTimer(this.GetType().ToString()))
	        {
	            string AnonumousGroup = "Anonymous";
	            //List<String> Users = FRepository.Get().GetUserNamesFromGroupName( AnonumousGroup );
	            int AnonymousGroupID = _unitOfWork.UserGroupRepository.First(data => data.Name == "Anonymous").Id;
	            List<int> AnonumousIDs =
                    _unitOfWork.UserGroupRepository.First(data => data.Name == "Anonymous").Users.Select(data => data.Id).ToList();
	            int AnonymousID = AnonumousIDs.First();

	            var CrashesQuery = _unitOfWork.CrashRepository.ListAll().Where(data => data.TimeOfCrash > startDate && data.TimeOfCrash <= endDate)
	                // Only crashes and asserts
	                .Where(Crash => Crash.CrashType == 1 || Crash.CrashType == 2)
	                // Only anonymous user
	                .Where(Crash => Crash.UserNameId.Value == AnonymousID);

	            // Filter by BranchName
	            if (!string.IsNullOrEmpty(branchName))
	            {
	                CrashesQuery =
	                    (
	                        from CrashDetail in CrashesQuery
	                        where CrashDetail.Branch.Equals(branchName)
	                        select CrashDetail
	                        );
	            }

	            var crashes = CrashesQuery.Select(data => new
	            {
                    ID = data.Id,
                    TimeOfCrash = data.TimeOfCrash.Value,
	                //UserID = Crash.UserNameId.Value, 
                    BuildVersion = data.BuildVersion,
                    JIRA = data.Jira,
                    Platform = data.PlatformName,
                    FixCL = data.FixedChangeList,
                    BuiltFromCL = data.ChangeListVersion,
                    Pattern = data.Pattern,
                    MachineID = data.ComputerName,
                    Branch = data.Branch,
                    Description = data.Description,
                    RawCallStack = data.RawCallStack,
	            }).ToList();
                var numCrashes = CrashesQuery.Count();

	            /*
                // Build patterns for crashes where patters is null.
                var CrashesWithoutPattern = FRepository.Get().Crashes
                    .FilterByDate( FRepository.Get().Crashes.ListAll(), startDate, endDate.AddDays( 1 ) )
                    // Only crashes and asserts
                    .Where( Crash => Crash.Pattern == null || Crash.Pattern == "" )
                    .Select( Crash => Crash )
                    .ToList();

                foreach( var Crash in CrashesWithoutPattern )
                {
                    Crash.BuildPattern();
                }
                */

	            // Total # of ALL (Anonymous) crashes in timeframe
	            int TotalAnonymousCrashes = numCrashes;

	            // Total # of UNIQUE (Anonymous) crashes in timeframe
	            HashSet<string> UniquePatterns = new HashSet<string>();
	            HashSet<string> UniqueMachines = new HashSet<string>();
	            Dictionary<string, int> PatternToCount = new Dictionary<string, int>();

	            //List<int> CrashesWithoutPattern = new List<int>();
	            //List<DateTime> CrashesWithoutPatternDT = new List<DateTime>();

	            foreach (var Crash in crashes)
	            {
	                if (string.IsNullOrEmpty(Crash.Pattern))
	                {
	                    //CrashesWithoutPattern.Add( Crash.ID );
	                    //CrashesWithoutPatternDT.Add( Crash.TimeOfCrash );
	                    continue;
	                }

	                UniquePatterns.Add(Crash.Pattern);
	                UniqueMachines.Add(Crash.MachineID);

	                bool bAdd = !PatternToCount.ContainsKey(Crash.Pattern);
	                if (bAdd)
	                {
	                    PatternToCount.Add(Crash.Pattern, 1);
	                }
	                else
	                {
	                    PatternToCount[Crash.Pattern]++;
	                }
	            }
	            var PatternToCountOrdered = PatternToCount.OrderByDescending(X => X.Value).ToList();
	            const int NumTopRecords = 200;
	            var PatternAndCount = PatternToCountOrdered.Take(NumTopRecords).ToDictionary(X => X.Key, Y => Y.Value);

	            int TotalUniqueAnonymousCrashes = UniquePatterns.Count;

	            // Total # of AFFECTED USERS (Anonymous) in timeframe
	            int TotalAffectedUsers = UniqueMachines.Count;

	            var RealBuggs = _unitOfWork.BuggRepository.ListAll().Where(Bugg => PatternAndCount.Keys.Contains(Bugg.Pattern));

	            // Build search string.
	            HashSet<string> FoundJiras = new HashSet<string>();
	            Dictionary<string, List<Bugg>> JiraIDtoBugg = new Dictionary<string, List<Bugg>>();

	            List<Bugg> Buggs = new List<Bugg>(NumTopRecords);
	            foreach (var Top in PatternAndCount)
	            {
	                Bugg NewBugg = RealBuggs.FirstOrDefault(X => X.Pattern == Top.Key);
	                if (NewBugg != null)
	                {
	                    using (
	                        FAutoScopedLogTimer TopTimer =
	                            new FAutoScopedLogTimer(string.Format("{0}:{1}", Buggs.Count + 1, NewBugg.Id)))
	                    {
	                        var CrashesForBugg = crashes.Where(Crash => Crash.Pattern == Top.Key).ToList();

	                        // Convert anonymous to full type;
	                        var FullCrashesForBugg = new List<Crash>(CrashesForBugg.Count);
	                        foreach (var Anon in CrashesForBugg)
	                        {
	                            FullCrashesForBugg.Add(new Crash()
	                            {
	                                Id = Anon.ID,
	                                TimeOfCrash = Anon.TimeOfCrash,
	                                BuildVersion = Anon.BuildVersion,
	                                Jira = Anon.JIRA,
	                                PlatformName = Anon.Platform,
	                                FixedChangeList = Anon.FixCL,
	                                ChangeListVersion = Anon.BuiltFromCL,
	                                Pattern = Anon.Pattern,
	                                ComputerName = Anon.MachineID,
	                                Branch = Anon.Branch,
	                                Description = Anon.Description,
	                                RawCallStack = Anon.RawCallStack,
	                            });
	                        }

	                        NewBugg.PrepareBuggForJira(FullCrashesForBugg);

	                        // Verify valid JiraID, this may be still a TTP 
	                        if (!string.IsNullOrEmpty(NewBugg.TTPID))
	                        {
	                            int TTPID = 0;
	                            int.TryParse(NewBugg.TTPID, out TTPID);

	                            if (TTPID == 0)
	                            {
	                                AddBuggJiraMapping(NewBugg, ref FoundJiras, ref JiraIDtoBugg);
	                            }
	                        }

	                        Buggs.Add(NewBugg);
	                    }
	                }
	                else
	                {
	                    FLogger.Global.WriteEvent("Bugg for pattern " + Top.Key + " not found");
	                }
	            }

	            if (BuggIDToBeAddedToJira > 0)
	            {
                    var Bugg = Buggs.Where(X => X.Id == BuggIDToBeAddedToJira).FirstOrDefault();
                    if (Bugg != null)
                    {
                        Bugg.CopyToJira();
                        AddBuggJiraMapping(Bugg, ref FoundJiras, ref JiraIDtoBugg);
                    }
	            }

	            if (JC.CanBeUsed())
	            {
	                var BuggsCopy = new List<Bugg>(Buggs);

	                HashSet<string> InvalidJiras = new HashSet<string>();

	                // Simple verification of JIRA
	                foreach (var Value in FoundJiras)
	                {
	                    if (Value.Length < 3 || !Value.Contains('-'))
	                    {
	                        InvalidJiras.Add(Value);
	                    }
	                }

	                foreach (var InvalidJira in InvalidJiras)
	                {
	                    FoundJiras.Remove(InvalidJira);
	                }

	                // Grab the data form JIRA.
	                string JiraSearchQuery = string.Join(" OR ", FoundJiras);

	                using (FAutoScopedLogTimer JiraResultsTimer = new FAutoScopedLogTimer("JiraResults"))
	                {
	                    bool bInvalid = false;
	                    var JiraResults = new Dictionary<string, Dictionary<string, object>>();
	                    try
	                    {
	                        if (!string.IsNullOrWhiteSpace(JiraSearchQuery))
	                        {
	                            JiraResults = JC.SearchJiraTickets(
	                                JiraSearchQuery,
	                                new string[]
	                                {
	                                    "key", // string
	                                    "summary", // string
	                                    "components", // System.Collections.ArrayList, Dictionary<string,object>, name
	                                    "resolution",
	                                    // System.Collections.Generic.Dictionary`2[System.String,System.Object], name
	                                    "fixVersions", // System.Collections.ArrayList, Dictionary<string,object>, name
	                                    "customfield_11200" // string
	                                });
	                        }
	                    }
	                    catch (System.Exception)
	                    {
	                        bInvalid = true;
	                    }

	                    // Invalid records have been found, find the broken using the slow path.
	                    if (bInvalid)
	                    {
	                        foreach (var Query in FoundJiras)
	                        {
	                            try
	                            {
	                                var TempResult = JC.SearchJiraTickets(
	                                    Query,
	                                    new string[]
	                                    {
	                                        "key", // string
	                                        "summary", // string
	                                        "components", // System.Collections.ArrayList, Dictionary<string,object>, name
	                                        "resolution",
	                                        // System.Collections.Generic.Dictionary`2[System.String,System.Object], name
	                                        "fixVersions", // System.Collections.ArrayList, Dictionary<string,object>, name
	                                        "customfield_11200" // string
	                                    });

	                                foreach (var Temp in TempResult)
	                                {
	                                    JiraResults.Add(Temp.Key, Temp.Value);
	                                }
	                            }
	                            catch (System.Exception)
	                            {

	                            }
	                        }
	                    }

	                    // Jira Key, Summary, Components, Resolution, Fix version, Fix changelist
	                    foreach (var Jira in JiraResults)
	                    {
	                        string JiraID = Jira.Key;

	                        string Summary = (string) Jira.Value["summary"];

	                        string ComponentsText = "";
	                        System.Collections.ArrayList Components =
	                            (System.Collections.ArrayList) Jira.Value["components"];
	                        foreach (Dictionary<string, object> Component in Components)
	                        {
	                            ComponentsText += (string) Component["name"];
	                            ComponentsText += " ";
	                        }

	                        Dictionary<string, object> ResolutionFields =
	                            (Dictionary<string, object>) Jira.Value["resolution"];
	                        string Resolution = ResolutionFields != null ? (string) ResolutionFields["name"] : "";

	                        string FixVersionsText = "";
	                        System.Collections.ArrayList FixVersions =
	                            (System.Collections.ArrayList) Jira.Value["fixVersions"];
	                        foreach (Dictionary<string, object> FixVersion in FixVersions)
	                        {
	                            FixVersionsText += (string) FixVersion["name"];
	                            FixVersionsText += " ";
	                        }

	                        int FixCL = Jira.Value["customfield_11200"] != null
	                            ? (int) (decimal) Jira.Value["customfield_11200"]
	                            : 0;

	                        List<Bugg> BuggsForJira;
	                        JiraIDtoBugg.TryGetValue(JiraID, out BuggsForJira);

	                        //var BuggsForJira = JiraIDtoBugg[JiraID];

	                        if (BuggsForJira != null)
	                        {
	                            foreach (Bugg Bugg in BuggsForJira)
	                            {
	                                Bugg.JiraSummary = Summary;
	                                Bugg.JiraComponentsText = ComponentsText;
	                                Bugg.JiraResolution = Resolution;
	                                Bugg.JiraFixVersionsText = FixVersionsText;
	                                if (FixCL != 0)
	                                {
	                                    Bugg.JiraFixCL = FixCL.ToString();
	                                }

	                                BuggsCopy.Remove(Bugg);
	                            }
	                        }
	                    }
	                }

	                // If there are buggs, we need to update the summary to indicate an error.
	                // Usually caused when bugg's project has changed.
	                foreach (var Bugg in BuggsCopy.Where(b => !string.IsNullOrEmpty(b.TTPID)))
	                {
	                    Bugg.JiraSummary = "JIRA MISMATCH";
	                    Bugg.JiraComponentsText = "JIRA MISMATCH";
	                    Bugg.JiraResolution = "JIRA MISMATCH";
	                    Bugg.JiraFixVersionsText = "JIRA MISMATCH";
	                    Bugg.JiraFixCL = "JIRA MISMATCH";
	                }
	            }

	            Buggs = Buggs.OrderByDescending(b => b.CrashesInTimeFrameGroup).ToList();

	            return new ReportsViewModel
	            {
	                Buggs = Buggs,
                    BranchName = branchName,
	                BranchNames = _unitOfWork.CrashRepository.GetBranchesAsListItems(),
	                DateFrom = (long) (startDate - CrashesViewModel.Epoch).TotalMilliseconds,
	                DateTo = (long) (endDate - CrashesViewModel.Epoch).TotalMilliseconds,
	                TotalAffectedUsers = TotalAffectedUsers,
	                TotalAnonymousCrashes = TotalAnonymousCrashes,
	                TotalUniqueAnonymousCrashes = TotalUniqueAnonymousCrashes
	            };
	        }
	    }