private List<string> GetLinksAsJs(
            List<MarriageSon> marriageSons, 
            List<Marriage> marriages,
            Dictionary<long, Tuple<int, string>> personsJsNodes,
            Dictionary<long, Tuple<int, string>> marriageJsNodes)
        {
            var linksAsJs = new List<string>();
            foreach(var marriageSon in marriageSons)
            {
                var marriage = marriages.Where(x => x.id.Equals(marriageSon.marriage_id)).FirstOrDefault();

                var marriageJsId = marriageJsNodes.Where(x => x.Key.Equals(marriage.id)).Select(x => x.Value.Item1).FirstOrDefault();
                var sonJsId = personsJsNodes.Where(x => x.Key.Equals(marriageSon.son_id)).Select(x => x.Value.Item1).FirstOrDefault();
                var husbandJsId = personsJsNodes.Where(x => x.Key.Equals(marriage.husband_id)).Select(x => x.Value.Item1).FirstOrDefault();
                var wifeJsId = personsJsNodes.Where(x => x.Key.Equals(marriage.wife_id)).Select(x => x.Value.Item1).FirstOrDefault();

                var jsText2 = string.Format("{{\"source\": {0}, \"target\": {1}}}",
                    husbandJsId,
                    marriageJsId);
                var jsText3 = string.Format("{{\"source\": {0}, \"target\": {1}}}",
                    wifeJsId,
                    marriageJsId);
                var jsText1 = string.Format("{{\"source\": {0}, \"target\": {1}}}",
                    marriageJsId,
                    sonJsId);

                linksAsJs.AddRange(new string[] { jsText1, jsText2, jsText3 });
            }
            return linksAsJs;
        }
Example #2
0
        public void ChangeMealeUnitAttack(Model M, Dictionary<int, Units> team)
        {
            int pos0 = 0;
            int pos1 = 0;
            int pos2 = 0;

            if (M.CurrentUnitAttack == 5)
            {
                string tostr = M.CanAttack[4].ToString();
                char[] pos = tostr.ToCharArray();
                try
                {
                    int.TryParse(pos[0].ToString(), out pos0);
                    int.TryParse(pos[1].ToString(), out pos1);
                    int.TryParse(pos[2].ToString(), out pos2);
                }
                catch (Exception e) { }
                var Target = team.Where(z => z.Value.Live == true)
                    .Where(y => y.Key == pos0 || y.Key == pos1 || y.Key == pos2)
                    .OrderBy(x => x.Value.HP)
                    .FirstOrDefault();
                M.PositionUnitOfAttack = Target.Key;
            }
            else if (M.CurrentUnitAttack == 4)
            {
                string tostr = M.CanAttack[3].ToString();
                char[] pos = tostr.ToCharArray();
                try
                {
                    int.TryParse(pos[0].ToString(), out pos0);
                    int.TryParse(pos[1].ToString(), out pos1);

                }
                catch (Exception e) { }

                var Target = team.Where(z => z.Value.Live == true)
                    .Where(y => y.Key == pos0 || y.Key == pos1)
                    .OrderBy(x => x.Value.HP)
                    .FirstOrDefault();
                M.PositionUnitOfAttack = Target.Key;
            }
            else
            {
                string tostr = M.CanAttack[5].ToString();
                char[] pos = tostr.ToCharArray();
                try
                {
                    int.TryParse(pos[0].ToString(), out pos0);
                    int.TryParse(pos[1].ToString(), out pos1);

                }
                catch (Exception e) { }

                var Target = team.Where(z => z.Value.Live == true)
                    .Where(y => y.Key == pos0 || y.Key == pos1)
                    .OrderBy(x => x.Value.HP)
                    .FirstOrDefault();
                M.PositionUnitOfAttack = Target.Key;
            }
        }
Example #3
0
        public static Dictionary<string, double> ProcessIntSequence(List<int> seq, int order, bool normalize)
        {
            var ans = new Dictionary<string, double>();

            for (int i = 0; i < seq.Count - order; i++)
            {
                string nextkey = "v" + string.Join("_", seq.Skip(i).Take(order).Select(s => s.ToString()).ToArray());

                if (ans.ContainsKey(nextkey))
                {
                    if (normalize)
                        ans[nextkey] += (double)100 / (double)seq.Count;
                    else
                        ans[nextkey]++;
                }
                else
                {
                    if (normalize)
                        ans.Add(nextkey, (double)100 / (double)seq.Count);
                    else
                        ans.Add(nextkey, 1);
                }
            }

            if (normalize)
                ans = ans.Where(p => p.Value >= 200 / (double)seq.Count).ToDictionary(p => p.Key, p => p.Value);
            else
                ans = ans.Where(p => p.Value >= 2).ToDictionary(p => p.Key, p => p.Value);

            return ans;
        }
Example #4
0
 static void Main()
 {
     Console.SetIn(File.OpenText("TextFile1.txt"));
     int n = int.Parse(Console.ReadLine());
     string move1 = Console.ReadLine();
     string move2 = Console.ReadLine();
     Dictionary<int, Turn> Turns = new Dictionary<int, Turn>();
     for (int i = 1; i <= n; i++)
     {
         Turns.Add(i, new Turn() { Number = i} );
     }
     int lastNumber = 0;
     int count = 0;
     int multiplayer = 1;
     while (Turns.Where(t => !t.Value.IsCaptured).ToList().Count > 0)
     {
         var newTurns = Turns.Where(t => !t.Value.IsCaptured).ToList();
         count = newTurns.Count;
         for (int i = 0; i < count; i++)
         {
             lastNumber = newTurns[i].Value.Number;
             Turns[i].IsCaptured = true;
             i += multiplayer;
         }
         multiplayer++;
     }
     Console.WriteLine(lastNumber);
     Console.WriteLine(MakeMoves(move1));
     Console.WriteLine(MakeMoves(move2));
     //work :)
     //Console.WriteLine("bounded");
     //Console.WriteLine("bounded");
 }
        public static IDictionary<Version, ChangeLogVersionDetails> GetChangeLog(Version fromVersion, Version toVersion, XDocument changeLogContent)
        {
            var changeLog = new Dictionary<Version, ChangeLogVersionDetails>();

            foreach (var changeVersion in changeLogContent.Descendants("Version"))
            {
                var changeLogItem = BuildChangeLogItem(changeVersion);
                if (!changeLog.ContainsKey(changeLogItem.Key))
                {
                    changeLog.Add(changeLogItem.Key, changeLogItem.Value);
                }
            }

            if (fromVersion < toVersion && changeLog.Any(x => x.Key > fromVersion && x.Key <= toVersion))
            {
                return changeLog.Where(x => x.Key > fromVersion && x.Key <= toVersion).OrderByDescending(detail => detail.Key).ToDictionary(detail => detail.Key, detail => detail.Value);
            }

            if (fromVersion < toVersion && changeLog.Any() && toVersion > changeLog.Keys.Max())
            {
                return changeLog.Where(x => x.Key == changeLog.Keys.Max()).ToDictionary(detail => detail.Key, detail => detail.Value);
            }

            if (fromVersion < toVersion && toVersion.Revision > 0 && changeLog.Any() && toVersion < changeLog.Keys.Max())
            {
                var versionWithoutRevision = new Version(toVersion.Major, toVersion.Minor, toVersion.Build);
                return changeLog.Where(x => x.Key > versionWithoutRevision).ToDictionary(detail => detail.Key, detail => detail.Value);
            }

            return changeLog.OrderByDescending(detail => detail.Key).ToDictionary(detail => detail.Key, detail => detail.Value);
        }
Example #6
0
        public Diff GetDiff(Dictionary<string, PriceItem> newProds, Dictionary<string, PriceItem> oldProds)
        {
            oldProds = oldProds ?? new Dictionary<string, PriceItem>();

            var diff = new Diff 
            { 
                NewItems = newProds.Where(kvp => !oldProds.ContainsKey(kvp.Key)).ToDictionary(key => key.Key, value => value.Value),
                DeletedItems = oldProds.Where(kvp => !newProds.ContainsKey(kvp.Key)).ToDictionary(key => key.Key, value => value.Value),
                UpdatedItems = newProds.Where(kvp => oldProds.ContainsKey(kvp.Key)).ToDictionary(key => key.Key, value => value.Value)
            };

            var toRemove = new List<string>();
            foreach (var item in diff.UpdatedItems.Values)
            {
                var oldItem = oldProds[item.Reference];
                if (item.WholesalePrice == oldItem.WholesalePrice && item.Active == oldItem.Active && !SameBalance(item, oldItem))
                {
                    toRemove.Add(item.Reference);
                }
            }

            foreach (var reference in toRemove)
            {
                diff.UpdatedItems.Remove(reference);
            }

            return diff;
        }
Example #7
0
 public List<Coin> ReturnCache()
 {
     List<Coin> for_return = new List<Coin>();
     //Получаем список всех доступных монет
     Dictionary<Coin, int> avail_coins = new Dictionary<Coin, int>();
     foreach(var item in GetSorted())
     {
         avail_coins.Add(new Coin(item.Key), item.Value);
     }
     //Массив всех доступных номиналов
     int[] values = avail_coins.Where(p => p.Value > 0).OrderByDescending(p => p.Key.Info.Price).Select(p => p.Key.Info.Price).ToArray();
     int i = 0;
     while (_money_cache > 0 && i<values.Length)
     {
         //Сколько нам нужно монет данного номинала
         int need_coins = (int)Math.Floor((double)_money_cache / values[i]);
         //Сколько у нас их есть
         int have_coins=avail_coins.Where(p=>p.Key.Info.Price==values[i]).Select(p=>p.Value).First();
         //Если у нас есть такое кол-во данных монет то возвращаем его, иначе отдаем что есть
         if(need_coins>have_coins)
         {
             need_coins = have_coins;
         }
         List<Coin> ret_coins=_GetCoins(values[i], need_coins);
         for_return.AddRange(ret_coins);
         _money_cache -= VMWallet.GetSum(ret_coins);
         i++;
     }
     return for_return;
 }
Example #8
0
 public void SaveReport(DateTime sessionStart, DateTime sessionEnd, string path, Dictionary<MouseMessage, ulong> mouseUsage, Dictionary<string, ulong> keyboardUsage, Dictionary<string, ulong> windowUsage, ulong mouseMoveLength)
 {
     XDocument xDoc = new XDocument(new XDeclaration("1.0", "", ""),
         new XElement("StatistiksReport",
             new XAttribute("SessionStart", sessionStart.ToString("yyyyMMddHHmmss")),
             new XAttribute("SessionEnd", sessionEnd.ToString("yyyyMMddHHmmss")),
             new XElement("KeyboardEvents",
                 from x in keyboardUsage.Where(x => ((int)x.Key[0]).IsValidXmlChar())
                 select new XElement("Event",
                     new XAttribute("Key", x.Key),
                     new XAttribute("Count", x.Value))),
             new XElement("MouseEvents",
                 from x in mouseUsage.Where(x => x.Key == MouseMessage.WM_LBUTTONUP || x.Key == MouseMessage.WM_RBUTTONUP) // only left or right mouse button events
                 select new XElement("Event",
                     new XAttribute("Code", x.Key.ToString()),
                     new XAttribute("Count", x.Value))),
             new XElement("MouseMetr",
                 from x in mouseUsage.Where(x => x.Key == MouseMessage.WM_MOUSEMOVE)
                 select new XElement("Event",
                     new XAttribute("Code", "Length"),
                     new XAttribute("Count", mouseMoveLength))),
             new XElement("WindowsEvents",
                 from x in windowUsage
                 select new XElement("Event",
                     new XAttribute("ExeName", x.Key.Split('\\').Last()),
                     new XAttribute("ExePath", x.Key),
                     new XAttribute("Count", x.Value)))));
     xDoc.Save(path);
 }
Example #9
0
        public void Handle()
        {
            LogHelper.Info<RefreshGroupsHandler>("Refresh started");

            // 1) get the groups from db
            var groups = _repo.GetAll();

            // 2) get the users for each group from db
            var usersPerGroup = _repo.GetAllUsers();

            // 3) query the users in ad for each group (step 1)
            var adGroupedUsers = new Dictionary<int, IEnumerable<EasyADUser>>();
            foreach (var group in groups)
            {
                adGroupedUsers.Add(group.Id, _groupManager.GetUsersInGroup(group.Name));
            }

            var adUsers = GetUniqueAdUsers(adGroupedUsers);
            var backofficeUsers = GetUniqueBackofficeUsers(usersPerGroup).ToList();

            var deleteUsers = backofficeUsers.Select(u => u.Username).Except(adUsers.Select(u => u.Login)).ToList();
            var newUsers = adUsers.Select(u => u.Login).Except(backofficeUsers.Select(u => u.Username)).ToList();

            // Delete the users that aren't any group anymore
            foreach (var name in deleteUsers)
            {
                LogHelper.Info<RefreshGroupsHandler>(string.Format("Removing user '{0}' from backoffice", name));
                var user = backofficeUsers.First(u => u.Username == name);
                _userService.Delete(user, deletePermanently: false);
                _repo.DeleteUser(user.Id);

                backofficeUsers.Remove(user);
            }

            // Create the users that aren't in the backoffice yet
            foreach (var name in newUsers)
            {
                LogHelper.Debug<RefreshGroupsHandler>(string.Format("Creating user '{0}' in backoffice", name));
                var user = adUsers.First(u => u.Login == name);
                var firstGroup = groups.Single(g => g.Id == adGroupedUsers.First(a => a.Value.Contains(user)).Key);
                var backofficeUser = _userService.CreateUserWithIdentity(user.Login, user.Email, _userService.GetUserTypeById(firstGroup.UserType));

                backofficeUser.Name = user.DisplayName;
                backofficeUsers.Add(backofficeUser);
            }

            // Update the current users
            foreach (var user in backofficeUsers)
            {
                var userGroupIds = adGroupedUsers.Where(g => g.Value.Any(u => u.Login == user.Username)).Select(g => g.Key).ToList();
                _repo.SetGroupsForUser(user.Id, userGroupIds);

                var groupsUserIsIn = adGroupedUsers.Where(a => a.Value.Any(u => u.Login == user.Username)).Select(kvp => groups.First(g => g.Id == kvp.Key));
                ConfigureUserRights(user, groupsUserIsIn);
            }

            LogHelper.Info<RefreshGroupsHandler>("Refresh completed");
        }
Example #10
0
        static public IDnaDataReader CreateMockedIDnaDataReader(MockRepository mocks, List<TestDatabaseRow> testRowData)
        {
            IDnaDataReader reader = mocks.DynamicMock<IDnaDataReader>();

            if (testRowData != null)
            {
                Dictionary<string, Queue<RowQueueItem>> queuedData = new Dictionary<string, Queue<RowQueueItem>>();

                reader.Stub(x => x.HasRows).Return(true).WhenCalled(x => x.ReturnValue = queuedData.Where(y => y.Value.Count() > 0).Count() > 0);

                bool firstread = true;
                reader.Stub(x => x.Read()).Return(true).WhenCalled(x =>
                {
                    if (!firstread)
                    {
                        // Find the non-empty queues
                        var nq = queuedData.Where(n => n.Value.Count() > 0);

                        // Find the min value of Row in all the RowQueueItems
                        var min = nq.Min(q => q.Value.Min(n => n.Row));

                        // Get all queues that contain a RowQueueItem with Row == min
                        // These are the queues that contain column values for the current
                        // row that need dequeuing
                        var queues = nq.Where(q => q.Value.Min(n => n.Row) == min);

                        foreach (var qd in queues)
                            qd.Value.Dequeue();
                    }
                    firstread = false;
                    // If we still have at least 1 non-empty queue, return true
                    x.ReturnValue = queuedData.Where(y => y.Value.Count() > 0).Count() >= 1;
                });

                int row = 1;
                foreach (TestDatabaseRow o in testRowData)
                {
                    foreach (KeyValuePair<string, object> kv in o.paramAndValues)
                    {
                        string keyName = kv.Key;
                        object objectValue = kv.Value;

                        if (!queuedData.ContainsKey(keyName))
                        {
                            queuedData.Add(keyName, new Queue<RowQueueItem>());
                        }

                        queuedData[keyName].Enqueue(new RowQueueItem { Row = row, ObjectValue = objectValue });
                    }
                    row++;
                }

                QueueValuesToDataReaderCalls(reader, queuedData);
            }

            return reader;
        }
 public Contour GetSingleContour()
 {
     if (Contours.Count == 0){
         throw new Exception("Контуры отсутствуют");
     }
     if (!AllContoursAreCompleted){
         throw new Exception("Все контуры должны быть замкнуты!");
     }
     var boundingBoxes = new Dictionary<int, BoundingBox>();
     for (int i=0; i<Contours.Count; i++){
         boundingBoxes.Add(i, Contours[i].GetBoundingBox());
     }
     var largestBox = boundingBoxes.FirstOrDefault(x => boundingBoxes.Where(y => y.Key != x.Key).All(y => x.Value.Contains(y.Value)));
     var restBoxes = boundingBoxes.Where(x => x.Key != largestBox.Key).ToArray();
     if (largestBox.Value == null) {
         throw new Exception("Контуры не образуют единой области. Дальнейшие вычисления невозможны");
     }
     if (restBoxes.Any(x => restBoxes.Where(y => y.Key != x.Key).Any(y => x.Value.Contains(y.Value)))){
         throw new Exception("Вложенность дырок недопустима. Дальнейшие вычисления невозможны");
     }
     var largestContour = Contours[largestBox.Key];
     largestContour.OrientCounterclockwise();
     for (int i = 0; i < Contours.Count; i++ ){
         if (i != largestBox.Key){
             var contour = Contours[i];
             contour.OrientClockwise();
             var nearestPoints = largestContour.ToDictionary(x => x,
                 x => contour.ToDictionary(y => y, y => Math.Sqrt(Math.Pow(x.X - y.X, 2) + Math.Pow(x.Y - y.Y, 2))).OrderBy(r => r.Value).First()).
                 OrderBy(r => r.Value.Value).First();
             int largeContourPointIndex = nearestPoints.Key.Index;
             int contourPointIndex = nearestPoints.Value.Key.Index;
             for (int j = 0; j < contour.Count - contourPointIndex + 1; j++){
                 Point pt = contour[contourPointIndex - 1 + j].Clone();
                 pt.Index = largeContourPointIndex + 1 + j;
                 largestContour.Insert(pt.Index - 1, pt);
             }
             for (int j = 0; j < contourPointIndex; j++){
                 Point pt = contour[j].Clone();
                 pt.Index = largeContourPointIndex + contour.Count - contourPointIndex + j + 2;
                 largestContour.Insert(pt.Index - 1, pt);
             }
             Point self = largestContour[largeContourPointIndex - 1].Clone();
             int offset = self.Index + contour.Count + 2;
             self.Index = offset;
             largestContour.Insert(self.Index - 1, self);
             for (int j = offset; j < largestContour.Count; j++){
                 largestContour[j].Index = j + 1;
             }
         }
     }
     largestContour.Index = 1;
     Contours.Clear();
     Contours.Add(largestContour);
     return largestContour;
 }
Example #12
0
 /// <summary>
 /// Sort the collection in the proper manner.
 /// </summary>
 internal static Dictionary<string, ListDictionary> SortCollection(Dictionary<string, ListDictionary> collection, string treeLevel, string sortLevel)
 {
     switch (sortLevel)
     {
         case "Alphabet":
             return collection
                 .OrderBy(kvp => kvp.Key)
                 .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
         case "Effort":
             return collection
                 .OrderByDescending(kvp => kvp.Value["effort"])
                 .ThenBy(kvp => kvp.Key) // Sort alphabetically if there is a tie.
                 .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
         case "Priority":
             return collection
                 .OrderByDescending(kvp => kvp.Value["priority"])
                 .ThenBy(kvp => kvp.Key) // Sort alphabetically if there is a tie.
                 .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
         case "Product":
             var missingTeamString = SimpleWorkItem.GetMissingString("Team");
             var missingTeamCollection = collection.Where(kvp => kvp.Key == missingTeamString); // Reference the 'NO TEAM' grouping.
             return collection
                 .Where(kvp => kvp.Key != missingTeamString) // Exclude 'NO TEAM' from sorting.
                 .OrderBy(kvp => kvp.Key != "Atlas")
                 .ThenBy(kvp => kvp.Key != "Anubis")
                 .ThenBy(kvp => kvp.Key != "Proteus")
                 .ThenBy(kvp => kvp.Key != "Shiva")
                 .ThenBy(kvp => kvp.Key != "Janus")
                 .ThenBy(kvp => kvp.Key != "Phoenix")
                 .ThenBy(kvp => kvp.Key != "Brahma")
                 .ThenBy(kvp => kvp.Key != "Loki")
                 .ThenBy(kvp => kvp.Key != "Heimdall")
                 .ThenBy(kvp => kvp.Key != "Vulcan")
                 .ThenBy(kvp => kvp.Key != "Athena")
                 .ThenBy(kvp => kvp.Key != "Ra")
                 .ThenBy(kvp => kvp.Key) // Any unmentioned teams above will be sorted alphabetically.
                 .Concat(missingTeamCollection) // Attach 'NO TEAM' back on.
                 .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
         case "Date":
             const string futureString = "Future";
             var missingString = SimpleWorkItem.GetMissingString(treeLevel);
             var futureCollection = collection.Where(kvp => kvp.Key == futureString); // Reference the Future grouping.
             var missingCollection = collection.Where(kvp => kvp.Key == missingString); // Reference the missing grouping.
             return collection
                 .Where(kvp => kvp.Key != futureString && kvp.Key != missingString) // Exclude Future and missing from sorting.
                 .OrderBy(kvp => kvp.Key.Split('\\').ElementAtOrDefault(0, "Z")) // Sort by Year, using "Z" to place it last if it's missing.
                 .ThenBy(kvp => kvp.Key.Split('\\').ElementAtOrDefault(1, "Z")) // Sort by Quarter, using "Z" to place it last if it's missing.
                 .ThenBy(kvp => kvp.Key.Split('\\').ElementAtOrDefault(2, "Z")) // Sort by Sprint, using "Z" to place it last if it's missing.
                 .Concat(futureCollection) // Attach Future back on.
                 .Concat(missingCollection) // Attach missing back on.
                 .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
         default:
             throw new Exception("Sorting type: " + sortLevel + ", is not supported.");
     }
 }
Example #13
0
        static void Main(string[] args)
        {
            Dictionary<string, Car> cars = new Dictionary<string, Car>();

            int n = int.Parse(Console.ReadLine());
            for (int i = 0; i < n; i++)
            {
                var input = Console.ReadLine().Split();

                var model = input[0];
                var engineSpeed = long.Parse(input[1]);
                var enginePower = long.Parse(input[2]);
                var cargoWeight = long.Parse(input[3]);
                var cargoType = input[4];
                var tier1P = double.Parse(input[5]);
                var tier1A = int.Parse(input[6]);
                var tier2P = double.Parse(input[7]);
                var tier2A = int.Parse(input[8]);
                var tier3P = double.Parse(input[9]);
                var tier3A = int.Parse(input[10]);
                var tier4P = double.Parse(input[11]);
                var tier4A = int.Parse(input[12]);

                var engine = new Engine(engineSpeed, enginePower);
                var cargo = new Cargo(cargoWeight, cargoType);

                var tierOne = new Tier(tier1P, tier1A);
                var tierTwo = new Tier(tier2P, tier2A);
                var tierThree = new Tier(tier3P, tier3A);
                var tierFour = new Tier(tier4P, tier4A);
                List<Tier> tiers = new List<Tier> { tierOne, tierTwo, tierThree, tierFour };
                var car = new Car(model, engine, cargo, tiers);
                cars[car.Model] = car;
            }

            var type = Console.ReadLine();
            if (type == "fragile")
            {
                var result = cars.Where(x => x.Value.Tiers.Exists(y => y.TirePressure < 1d));
                foreach (var car in result)
                {
                    Console.WriteLine(car.Key);
                }
            }
            else
            {
                var result = cars.Where(x => x.Value.Engine.EnginePower > 250);
                foreach (var car in result)
                {
                    Console.WriteLine(car.Key);
                }
            }
        }
        /// <summary>
        /// Inits the viewmodel with the specified sys info, and setups the default categories.
        /// </summary>
        /// <param name="sysInfo">The sys info.</param>
        /// <param name="attachedFiles">path to the attachment</param>
        /// <author>Jurie.smit</author>
        /// <datetime>2013/01/14-09:19 AM</datetime>
        private void Init(SystemInfoTO sysInfo, Dictionary<string, string> attachedFiles)
        {
            Comment = null;

            ServerLogAttachmentPath = attachedFiles.Where(f => f.Key.Equals("ServerLog", StringComparison.CurrentCulture)).Select(v => v.Value).SingleOrDefault();
            StudioLogAttachmentPath = attachedFiles.Where(f => f.Key.Equals("StudioLog", StringComparison.CurrentCulture)).Select(v => v.Value).SingleOrDefault();
            
            Comment = GenerateDefaultComment(sysInfo);
            SetCaretPosition();
            Categories.AddRange(new List<string> { "General", "Compliment", "Feature request", "Bug", "Feedback" });
            if(attachedFiles.Count > 0) SelectedCategory = "Feedback";
        }
        public ActionResult Parts(int id = 0, int page = 1, int per_page = 10)
        {
            if (id > 0) {
                APICategory category = new APICategory();

                category = CURTAPI.GetCategory(id);
                ViewBag.category = category;

                List<APIPart> parts = CURTAPI.GetCategoryParts(id, page, per_page);

                Dictionary<string, List<APIPart>> ordered_parts = new Dictionary<string, List<APIPart>>();
                foreach (APIPart part in parts) {
                    APIColorCode color_code = CURTAPI.GetColorCode(part.partID);
                    part.colorCode = color_code.code;
                    if (part.pClass.Length > 0) {
                        if (ordered_parts.Keys.Contains(part.pClass)) { // Already added to dictionary
                            List<APIPart> existing_parts = ordered_parts.Where(x => x.Key == part.pClass).Select(x => x.Value).FirstOrDefault<List<APIPart>>();
                            existing_parts.Add(part);
                            ordered_parts[part.pClass] = existing_parts;
                        } else { // New Color Code
                            List<APIPart> new_parts = new List<APIPart>();
                            new_parts.Add(part);
                            ordered_parts.Add(part.pClass, new_parts);
                        }
                    } else {
                        if (ordered_parts.Keys.Contains(category.catTitle.Trim())) { // Already added to dictionary
                            List<APIPart> existing_parts = ordered_parts.Where(x => x.Key == category.catTitle.Trim()).Select(x => x.Value).FirstOrDefault<List<APIPart>>();
                            existing_parts.Add(part);
                            ordered_parts[category.catTitle.Trim()] = existing_parts;
                        } else { // New Color Code
                            List<APIPart> new_parts = new List<APIPart>();
                            new_parts.Add(part);
                            ordered_parts.Add(category.catTitle.Trim(), new_parts);
                        }
                    }
                }
                ViewBag.parts = ordered_parts;

                // We need to figure out if there are going to be more parts to display
                int more_count = CURTAPI.GetCategoryParts(id, page + 1, per_page).Count;
                ViewBag.more_count = more_count;

                ViewBag.page = page;
                ViewBag.per_page = per_page;

                return View();
            } else {
                return RedirectToAction("Index", "Index");
            }
        }
        private Dictionary<string, List<Session>> CondenseNumerics(Dictionary<string, List<Session>> dictionary)
        {
            var numerics = dictionary.Where(kv => kv.Key.AsInt() > 0);
            var sessionList = new List<Session>();
            sessionList = numerics.Aggregate(sessionList, (current, kv) => current.Concat(kv.Value).ToList());

            var finalDictionary = dictionary.Where(kv => kv.Key.AsInt() == int.MinValue)
                .ToDictionary(kv => kv.Key, kv => kv.Value);

            if (sessionList.Count > 0)
                finalDictionary.Add("#", sessionList);

            return finalDictionary;
        }
        public void CaptureReader_Can_Read_Back_A_Stream_That_Was_Written_By_A_CaptureWriter()
        {
            var writeOperations = 100;
            var ms = new ConcurrentStream(new MemoryStream());

            var sat = new Dictionary<Guid, short>();
            sat.Add(Guid.NewGuid(), 24);
            sat.Add(Guid.NewGuid(), 25);
            sat.Add(Guid.NewGuid(), 26);

            var stateResolver = new Mock<IStateResolver>();
            stateResolver.SetupGet(s => s.AllocationTable).Returns(sat);
            stateResolver.Setup(s => s.IsAllocated(It.IsAny<Guid>())).Returns<Guid>(g => sat.ContainsKey(g));
            stateResolver.Setup(s => s.GetAllocatedId(It.IsAny<Guid>())).Returns<Guid>(g => sat[g]);

            //write operations
            var captureWriter = new CaptureWriter(ms, stateResolver.Object);

            for (int i = 0; i < writeOperations; i++)
            {
                var timestamp = DateTime.UtcNow;
                var randomData = new byte[1024];
                new Random().NextBytes(randomData);

                var randomSat = (short)new Random().Next(24, 26);

                var captureState = new Mock<ICaptureState>();
                captureState.Setup(c => c.Data).Returns(randomData);
                captureState.Setup(c => c.Guid).Returns(sat.Where(f => f.Value == randomSat).First().Key);
                captureState.Setup(c => c.Timestamp).Returns(timestamp);

                captureWriter.Write(captureState.Object);
            }

            //rewind the stream to the beginning
            ms.Position = 0;

            //read operations
            var readStateResolver = new StateResolver();
            readStateResolver.Add(new SimpleStateController { Guid = sat.Where(f => f.Value == 24).First().Key });
            readStateResolver.Add(new SimpleStateController { Guid = sat.Where(f => f.Value == 25).First().Key });
            readStateResolver.Add(new SimpleStateController { Guid = sat.Where(f => f.Value == 26).First().Key });

            var captureReader = new CaptureReader(ms, readStateResolver);

            while (captureReader.Position < captureReader.Count)
            {
                captureReader.Read();
            }
        }
Example #18
0
        static void Main(string[] args)
        {
            Dictionary<char, int> FrequenciesChars = new Dictionary<char, int>();
            FrequenciesChars.Add('a', 100);  
            FrequenciesChars.Add('b', 50);  
            FrequenciesChars.Add('c', 25);
            FrequenciesChars.Add('d', 15);  
            FrequenciesChars.Add('e', 5);

            int Million = 10000000;
            int TwoMillions = Million * 2;

            Random Randomizer = new Random();

            char[] Output = new char[TwoMillions];

            int RandomFreq = 0;
            for (int i = 0; i < TwoMillions; i++)
            {
                RandomFreq = Randomizer.Next(1, 100);
                var From = FrequenciesChars.Where(g => g.Value <= RandomFreq).OrderByDescending(g => g.Value).FirstOrDefault();
                var To = FrequenciesChars.Where(g => g.Value > RandomFreq).OrderBy(g => g.Value).FirstOrDefault();

                int FromDiff = RandomFreq - From.Value;
                int ToDiff = To.Value - RandomFreq;

                char Selected = ' ';
                if (ToDiff < FromDiff)
                {
                    Selected = To.Key;
                }
                else
                {
                    Selected = From.Key;
                }

                Output[i] = Selected;
            }

            using (var OutputStream = System.IO.File.Open("output.txt", System.IO.FileMode.Append, System.IO.FileAccess.Write))
            {
                var StreamWriter = new StreamWriter(OutputStream);
                StreamWriter.Write(Output);
                StreamWriter.Flush();
            }
            
            Console.WriteLine(Output);
            Console.ReadKey();
        }
Example #19
0
        public string GetBestPool(Dictionary<string, PoolServer> pools, string currentPool, int advancedSeconds)
        {
            string best = null;

            if (currentPool != "")
            {
                if (_currentRouletteDelay++ < MaxRouletteDelay)
                {
                    return currentPool;
                }
                else
                {
                    _currentRouletteDelay = 0;
                }
            }

            var sharePropPools = pools
                .Where(pool => pool.Value.Type == PoolType.Prop && pool.Value.CurrentShare < _difficulty * Threshold)
                .ToDictionary(pool => pool.Key, pool => _difficulty / pool.Value.CurrentShare);

            if (sharePropPools.Count == 0)
            {
                sharePropPools = pools
                    .Where(pool => pool.Value.Type == PoolType.PropEarlyHop && pool.Value.CurrentShare * 4.0 < _difficulty * Threshold)
                    .ToDictionary(pool => pool.Key, pool => _difficulty / pool.Value.CurrentShare);
            }

            if (sharePropPools.Count == 0)
            {
                sharePropPools = pools
                    .Where(pool => pool.Value.Type == PoolType.Score && pool.Value.CurrentShare * 4.0 < _difficulty * Threshold)
                    .ToDictionary(pool => pool.Key, pool => _difficulty / pool.Value.CurrentShare);
            }

            if (sharePropPools.Count == 0)
            {
                sharePropPools = pools
                    .Where(pool => pool.Value.Type == PoolType.Pplns && pool.Value.CurrentShare * 4.0 < _difficulty * Threshold)
                    .ToDictionary(pool => pool.Key, pool => _difficulty / pool.Value.CurrentShare);
            }

            if (sharePropPools.Count > 0)
            {
                best = _rnd.Roulette(sharePropPools);
            }

            return best ?? (best = "smpps");
        }
		public static Entity GetHeroEntity(bool forPlayer, Dictionary<int, Entity> entities, int id)
		{
			if(!forPlayer)
				id = (id % 2) + 1;
			var heros = entities.Where(x => IsHero(x.Value)).Select(x => x.Value).ToList();
			return heros.FirstOrDefault(x => x.GetTag(CONTROLLER) == id);
		}
Example #21
0
        public long Solve()
        {
            var result = new Dictionary<long, int> { { 1, 1 } };

            for (var i = 2L; i <= Limit; i++)
            {
                var n = i;
                var row = new List<long>();

                while (!result.ContainsKey(n))
                {
                    row.Add(n);

                    n = GetNext(n);
                }

                var lenght = result[n];

                var count = 0;
                foreach (var r in row)
                {
                    result.Add(r, lenght + row.Count - count);
                    count++;
                }
            }

            return result.Where(t => t.Key <= Limit).OrderByDescending(t => t.Value).First().Key;
        }
        static void Main(string[] args)
        {
            var input = Console.ReadLine().ToLower().Split();

            var elements = new Dictionary<string, int>();

            for (int i = 0; i < input.Length; i++)
            {
                var currentElement = input[i];
                if (!elements.ContainsKey(currentElement))
                {
                    elements[currentElement] = 0;
                }

                elements[currentElement]++;
            }

            var resultElements = elements.Where(x => x.Value % 2 != 0);
            var result = new List<string>();

            foreach (var element in resultElements)
            {
                result.Add(element.Key);
            }

            Console.WriteLine(string.Join(", ", result));
        }
Example #23
0
        /// <summary>
        /// TODO: input Namespace list instead; 
        /// TODO: Save to ...yml.map
        /// </summary>
        /// <param name="allMembers"></param>
        /// <returns></returns>
        public static MetadataModel ResolveMetadata(
            Dictionary<string, MetadataItem> allMembers,
            Dictionary<string, ReferenceItem> allReferences,
            string apiFolder,
            bool preserveRawInlineComments,
            IEnumerable<string> externalReferencePackages)
        {
            MetadataModel viewModel = new MetadataModel();
            viewModel.TocYamlViewModel = new MetadataItem()
            {
                Type = MemberType.Toc,
                Items = allMembers.Where(s => s.Value.Type == MemberType.Namespace).Select(s => s.Value).ToList(),
            };
            viewModel.Members = new List<MetadataItem>();
            ResolverContext context = new ResolverContext
            {
                ApiFolder = apiFolder,
                References = allReferences,
                PreserveRawInlineComments = preserveRawInlineComments,
            };

            ExecutePipeline(viewModel, context);

            return viewModel;
        }
Example #24
0
        private string FromDictionaryToUrlEncoded(Dictionary<string, string> dictionary, string url)
        {
            var dic = dictionary.Where(x => !string.IsNullOrEmpty(x.Value));

            var kvs = dic.Select(kvp => $"{kvp.Key}={string.Join("&", kvp.Value)}");
            return string.Concat(url, "?", string.Join("&", kvs));
        }
Example #25
0
        private string FromDictionaryToJson(Dictionary<string, string> dictionary)
        {
            var dic = dictionary.Where(x => !string.IsNullOrEmpty(x.Value));

            var kvs = dic.Select(kvp => string.Format("\"{0}\":\"{1}\"", kvp.Key, string.Join(",", kvp.Value)));
            return string.Concat("{", string.Join(",", kvs), "}");
        }
Example #26
0
        public void CreateModels(IEnumerable<OvhApi> apis)
        {
            Dictionary<string,ModelType> modelsByNamespace = new Dictionary<string, ModelType>();
            foreach (var ovhApi in apis)
            {
                foreach (var model in ovhApi.Models)
                {
                    string fullTypeName = Util.GetType(model.Key);

                    if (modelsByNamespace.ContainsKey(fullTypeName))
                        continue;

                    modelsByNamespace.Add(fullTypeName, new ModelType(model.Value));
                }
            }

            foreach (var st in modelsByNamespace)
            {
                string modelNamespace = Util.GetNamespace(st.Value.Model);

                if (modelsByNamespace.ContainsKey(modelNamespace))
                {
                    modelsByNamespace[modelNamespace].AddChild(st.Value);
                }
            }

            foreach (var type in modelsByNamespace.Where(x => x.Value.Parent == null))
            {
                CodeNamespace ns = new CodeNamespace(Util.GetNamespace(type.Value.Model));
                ns.Types.Add(CreateType(type.Value));
                _code.Namespaces.Add(ns);
            }
        }
		/// <summary>
		/// Turns all the properties into a semi-colon separated string.
		/// </summary>
		/// <returns>
		/// Returns semi-colon separated string of properties.
		/// </returns>
		public override string ToString()
		{
			var b =
				new Dictionary<string, object>
				{
					{"Server", Server},
					{"Port", Port},
					{"Userid", UserId},
					{"Password", Password},
					{"Protocol", Protocol},
					{"SSL", Ssl},
					{"Pooling", Pooling},
					{"MinPoolSize", MinPoolSize},
					{"MaxPoolSize", MaxPoolSize},
					{"Timeout", Timeout},
					{"SslMode", SslMode},
					{"Database", Database}
				};

			var buff =
				string.Join(
					";",
					b.Where(kvp => kvp.Value != null)
						.Select(
							kvp =>
							string.Format(
								"{0}={1}",
								kvp.Key,
								Convert(kvp.Value)))
						.ToArray());

			return buff.ToString();
		}
Example #28
0
        public Response Speak()
        {
            Dictionary<Rule, int> acceptDict = new Dictionary<Rule, int>();

            foreach (Rule rule in _ruleDb)
            {
                if (!rule.CanMatch())
                    continue;

                bool match = true;
                foreach (Criterion criterion in rule.Criteria)
                {
                    if (!_factDict.ContainsKey(criterion.Lhs) || !criterion.Compare(_factDict[criterion.Lhs] as IComparable))
                    {
                        match = false;
                        break;
                    }
                }
                if (match)
                    acceptDict.Add(rule, rule.Criteria.Count);
            }
            if (acceptDict.Count == 0)
                return new Response("NullResponse", "NO RESPONSE");

            // Of all the matched rules, find the one(s) that match the most criteria
            int maxScore = acceptDict.Max(kvp => kvp.Value);
            List<Rule> acceptList = acceptDict.Where(kvp => kvp.Value == maxScore).Select(kvp => kvp.Key).ToList();

            // Of all the matched rules of maximum criteria, return a random one
            Rule matchedRule = acceptList.RandomItem();
            matchedRule.Match();
            Response response = matchedRule.Response;
            response.Match();
            return response;
        }
Example #29
0
 public Dictionary<string, int> GetSortedWords(Dictionary<string, int> words, Dictionary<string, int> bannedWords)
 {
     return words
         .Where(x => !bannedWords.ContainsKey(x.Key))
         .OrderByDescending(x => x.Value)
         .ToDictionary(pair => pair.Key, pair => pair.Value);
 }
Example #30
0
        private static bool DoDepthFirstSearchingAux(Dictionary<string, int> existingRoutes, ref int runningWeight, string fromToKey, string requestedRoute)
        {
            // Concept: the minute you have entered this function, you have gone from...to.  (See fromToKey.)  So update recordkeeping now.
            runningWeight += existingRoutes[fromToKey];

            if (YouHaveReachedYourDestination(requestedRoute))
                return true;

            var nextLocation = requestedRoute.Substring(1);
            var possibleRoutes = existingRoutes.Where(r => r.Key == nextLocation.Substring(0, 2));

            if (!possibleRoutes.Any())
                return false;

            foreach (var route in possibleRoutes)
            {
                var savedWeight = runningWeight;
                if (DoDepthFirstSearchingAux(existingRoutes, ref runningWeight, route.Key, nextLocation))
                {
                    return true;
                }
                runningWeight = savedWeight;
            }

            return false;
        }