static void Main()
    { 
        Dictionary<byte, byte> studentHeight = new Dictionary<byte, byte>();
        int n = int.Parse(Console.ReadLine());

        string numbers = Console.ReadLine(); // We have sequence of numbers on one line
        string[] tokens = numbers.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

        for (int i = 0; i < n; i++)
        {
            byte height = byte.Parse(tokens[i]);

            if (!studentHeight.ContainsKey(height))
                studentHeight.Add(height, 1);
            else
                studentHeight[height]++;
        }

        int combinations = 0;
        for (int i = 0; i < studentHeight.Count; i++)
        {
            if (studentHeight.ElementAt(i).Value > 1)
            {
                combinations += (int)CalculateCombinations(studentHeight.ElementAt(i).Value);
            }
        }
        Console.WriteLine(combinations);
    }
Example #2
0
        public static Dictionary<string, int> GetShortestLevenshtein(string givenWord, List<string> words)
        {
            Dictionary<string, int> dists = new Dictionary<string, int>();

            foreach (string word in words) {
                dists.Add(word, LevenshteinDistance(givenWord, word));
            }

            dists = dists.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

            var shortestElement = dists.ElementAt(1);
            int shortestDist = shortestElement.Value;

            for (int i = dists.Count - 1; i > 0; i--) {
                var item = dists.ElementAt(i);

                if (item.Value != shortestDist) {
                    dists.Remove(item.Key);
                }
            }

            /* Remove givenWord from the output */
            dists.Remove(dists.ElementAt(0).Key);

            return dists;
        }
Example #3
0
        public MenuOptions(string title, Dictionary<string, Action<MenuOptionAction>> optionsToActions, int backActionOptionIndex)
        {
            if (backActionOptionIndex >= optionsToActions.Count || backActionOptionIndex < 0)
                throw new ArgumentOutOfRangeException("backActionOptionIndex", "The back action index must be between 0 and the size of the options array");

            finalize(title, optionsToActions, optionsToActions.ElementAt(backActionOptionIndex).Key, optionsToActions.ElementAt(backActionOptionIndex).Value);
        }
Example #4
0
        static void Main(string[] args)
        {
            Dictionary<int, int> deck = new Dictionary<int, int>()
            {
                {2, 0}, {3, 0},
                {4, 0}, {5, 0}, {6, 0},
                {7, 0}, {8, 0}, {9, 0}, {10, 0},
                {11, 0}, {12, 0}, {13, 0}, {14, 0}

            };

            Random rand = new Random();

            for (int i = 0; i < 5; i++)
            {
            Another:
                int rnd = rand.Next(2, 14);
                int currentValue = deck.ElementAt(rnd).Value + 1;
                if((deck.ElementAt(rnd).Value > 4))
                {
                    goto Another;
                } else
                {
                    deck[rnd]++;
                }
            }

            foreach (var item in deck.Where(x => x.Value > 0))
            {

            }
        }
Example #5
0
        public override Exceptional Execute(AGraphDSSharp myAGraphDSSharp, ref String myCurrentPath, Dictionary<String, List<AbstractCLIOption>> myOptions, String myInputString)
        {
            if (myAGraphDSSharp == null)
                return new Exceptional(new GraphDSError("myAGraphDSSharp must not be null!"));

            var _Content        = myOptions.ElementAt(1).Value[0].Option;
            var _FileLocation   = new ObjectLocation(ObjectLocation.ParseString(myCurrentPath), myOptions.ElementAt(2).Value[0].Option);

            if (myAGraphDSSharp.ObjectExists(_FileLocation).Value != Trinary.TRUE)
            {

                try
                {
                    AFSObject _FileObject = new FileObject() { ObjectLocation = _FileLocation, ObjectData = Encoding.UTF8.GetBytes(_Content)};
                    myAGraphDSSharp.StoreFSObject(_FileObject, true);
                }
                catch (Exception e)
                {
                    WriteLine(e.Message);
                }

            }

            else
            {

                if (myAGraphDSSharp.ObjectStreamExists(_FileLocation, FSConstants.INLINEDATA).Value)
                {

                }

            }

            return Exceptional.OK;
        }
Example #6
0
    public void activeSongList(string pack)
    {
        packSelected = pack;
        songList = LoadManager.Instance.ListSong()[pack];
        startnumber = 0;
        currentstartnumber = 0;
        camerasong.transform.position = posBaseCameraSong;

        for(int i=0; i < songList.Count; i++)
        {
            var key = songCubePack.ElementAt(i).Key;
            if(!key.activeInHierarchy)
            {
                key.SetActive(i <= numberToDisplay);
            }
            var songChecked = songList.ElementAt(i).Value.First().Value;
            songCubePack[key] = songChecked.title + ";" + songChecked.subtitle + ";" + songList.ElementAt(i).Key;
            if(packLocked == packSelected && gs.songSelected != null && ((gs.songSelected.First().Value.title + ";" + gs.songSelected.First().Value.subtitle) == (songChecked.title + ";" + songChecked.subtitle)))
            {
                key.transform.FindChild("Selection").gameObject.SetActive(true);
            }else
            {
                key.transform.FindChild("Selection").gameObject.SetActive(false);

            }
        }
        for(int i=songList.Count; i < songCubePack.Count; i++)
        {
            var key = songCubePack.ElementAt(i).Key;
            if(key.activeInHierarchy) key.SetActive(false);
            songCubePack[key] = "";
        }
    }
        public void CreateTypeActions(string actionsmoid, string typeid, string typeidname)
        {
            Dictionary<string, string> StageActions = new Dictionary<string, string>();
            StageActions.Add("Assign Task", "cm.task__create.form");
            StageActions.Add("Send Message", "cm.sendmessage.form");
            StageActions.Add("Log Conversation", "cm.logconversation.form");
            StageActions.Add("Attach Document", "cm.logconversation.form");
            StageActions.Add("Edit Priority", "cm.logconversation.form");

            for (int i = 0; i < StageActions.Count; i++)
            {
                SourceCode.SmartObjects.Client.SmartObject smoTypAction = Client.GetSmartObject(new Guid(actionsmoid));

                smoTypAction.Properties["Name"].Value = StageActions.ElementAt(i).Key;
                smoTypAction.Properties["Description"].Value = StageActions.ElementAt(i).Key;
                smoTypAction.Properties["Sort_Order"].Value = StageActions.ElementAt(i).Key;
                smoTypAction.Properties["Action_Form"].Value = StageActions.ElementAt(i).Value;
                smoTypAction.Properties["Is_Important"].Value = "false";
                smoTypAction.Properties["Created_On"].Value = DateTime.Now.ToString();
                smoTypAction.Properties["Created_By"].Value = "denallix\\administrator";
                smoTypAction.Properties["Modified_On"].Value = DateTime.Now.ToString();
                smoTypAction.Properties["Modified_By"].Value = "denallix\\administrator";
                smoTypAction.Properties["Is_Active"].Value = "true";
                smoTypAction.Properties["Is_Deleted"].Value = "false";
                smoTypAction.Properties["Sort_Order"].Value = i.ToString();

                smoTypAction.Properties[typeidname].Value = typeid;

                smoTypAction.MethodToExecute = "Create";

                SourceCode.SmartObjects.Client.SmartObject result = Client.ExecuteScalar(smoTypAction);
            }
        }
        public static async Task<string> Post(Uri url, Dictionary<string, string> keyValue)
        {
            try
            {
                using (var client = new HttpClient(
                    new HttpClientHandler
                    {
                        AutomaticDecompression = DecompressionMethods.GZip
                                                 | DecompressionMethods.Deflate
                    }))
                {
                    client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");

                    var arr = new KeyValuePair<string, string>[keyValue.Count];
                    for (int i = 0; i < keyValue.Count; i++)
                    {
                        arr[i] = new KeyValuePair<string, string>(keyValue.ElementAt(i).Key, keyValue.ElementAt(i).Value);
                    }

                    var credentials = new FormUrlEncodedContent(arr);

                    var res = await client.PostAsync(url, credentials);
                    return await res.Content.ReadAsStringAsync();

                }
            }
            catch (Exception ex)
            {

            }
            return null;
        }
        //To get all items by running this on all tickers.
        public static void GetAllFRItemFromNASDAQ(string[] tickers, string reportType)
        {
            string periodType = "Annual";
            string numPeriods = "10";
            string reportParam = FinancialReportsConfig.params_NASDAQ[reportType];
            string periodParam = FinancialReportsConfig.params_NASDAQ[periodType];
            var keys = (Dictionary<string, int>)FinancialReportsConfig.mappings_NASDAQ[reportType];

            List<string[]> list = new List<string[]>();
            list.Add(new string[] { "ticker", "not in key", "previous key", "next key", "number" });
            foreach (string ticker in tickers)
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                try
                {
                    WebData webData = new WebData(string.Format(Constants.NASDAQFinancialReportingURL, reportParam, periodParam, numPeriods, ticker));
                    data = webData.ReadNASDAQFRHtmlTable().ElementAt(1);
                }
                catch
                {
                }
                data.Each((d, i) =>
                {
                    int nexti = i + 1 == data.Count ? i : i + 1;
                    if (!keys.ContainsKey(d.Key))
                        list.Add(new string[] { ticker, d.Key, data.ElementAt(i - 1).Key, data.ElementAt(nexti).Key, i.ToString() });
                }
                );

                //list.Add(new string[]{"","","","",""});
            }

            Excel.Worksheet ws = ExcelUtil.Worksheet("Test_" + reportType);
            ws.Range("A2").Resize(list.Count, list[0].Length).Formula = ExcelUtil.To2DArray(list);
        }
        internal void update(Dictionary<string, string> dictionary)
        {
            //Lock for enumeration thread safety
            lock (slidegen.cstlist)
            {
                if (dictionary != null)
                {
                    for (int i = 0; i < dictionary.Count; i++)
                    {
                        if (slidegen.cstlist.ContainsKey(dictionary.ElementAt(i).Key))
                        {
                            slidegen.cstlist[dictionary.ElementAt(i).Key] = dictionary.ElementAt(i).Value;
                            if(dictionary.ElementAt(i).Key =="CURRENTARTIST")
                                slidegen.cstlist["ARTIST"] = dictionary.ElementAt(i).Value;
                            if (dictionary.ElementAt(i).Key == "CURRENTTITLE")
                                slidegen.cstlist["TITLE"] = dictionary.ElementAt(i).Value;
                        }
                        else
                        {
                            slidegen.cstlist.Add(dictionary.ElementAt(i).Key, dictionary.ElementAt(i).Value);

                            if (dictionary.ElementAt(i).Key == "CURRENTARTIST")
                                slidegen.cstlist.Add("ARTIST", dictionary.ElementAt(i).Value);
                            if (dictionary.ElementAt(i).Key == "CURRENTTITLE")
                                slidegen.cstlist.Add("TITLE", dictionary.ElementAt(i).Value);
                        }
                    }
                }
            }
        }
Example #11
0
        static void Main(string[] args)
        {
            // Write a program that finds the most frequent number in an array.
            // Example: {4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3} -> 4 (5 times)

            int[] arr = { 4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3 };
            Dictionary<int, int> frequencyMeter = new Dictionary<int, int>();

            for (int i = 0; i < arr.Length; i++)
            {
                if (frequencyMeter.ContainsKey(arr[i]))
                {
                    frequencyMeter[arr[i]]++;
                }
                else
                {
                    frequencyMeter.Add(arr[i], 1);
                }
            }

            int maxOccurences = frequencyMeter.ElementAt(0).Value;
            int number = frequencyMeter.ElementAt(0).Key;
            foreach (KeyValuePair<int, int> pair in frequencyMeter)
            {
                if (pair.Value > maxOccurences)
                {
                    maxOccurences = pair.Value;
                    number = pair.Key;
                }
            }

            Console.WriteLine("{0} ({1} times)", number, maxOccurences);
        }
Example #12
0
        public MainPage()
        {
            Game game;
            game = new Game();
            TTskProvider tprov = new TTskProvider(game);
            tprov.tskBad(tprov.encodeTask('f'));
            tprov.tskBad(tprov.encodeTask('g'));
            tprov.tskBad(tprov.encodeTask('g'));
            tprov.tskBad(tprov.encodeTask('g'));
            tprov.tskBad(tprov.encodeTask('h'));

            tprov.tskGood(tprov.encodeTask('h'),true);

            TRandom rand = new TRandom("0123456789", null,0);
            Dictionary<Char, int> dic = new Dictionary<Char, int>();
            rand.count = 6;
            rand.only.Add(2);
            rand.only.Add(1);
            rand.only.Add(5);

            rand.freq[2] = 1;
            rand.freq[4] = 2;
            Char c;
            String res = "";
            string res1 = "";
            for (int i = 0; i < rand.count; i++) dic.Add(rand.charAt(i), 0);
            for (int i = 0; i < 800; i++) { res += (c = rand.getVal()); dic[c]++; }
            for (int i = 0; i < dic.Count; i++)res1 += " " + dic.ElementAt(i).Key + '='+dic.ElementAt(i).Value.ToString() + ' ';
            InitializeComponent();
        }
 public IEnumerator PlayCutscene(Dictionary<Transform, Vector3> _ship_gridPos_Table)
 {
     this.ship_gridPos_Table = _ship_gridPos_Table;
     yield return StartCoroutine(PreCutscene());
     foreach (var ship_gridPos in ship_gridPos_Table)
     {
         Transform shipTrans = ship_gridPos.Key;
         int hangarIndex = Random.Range(0, hangars.Length);
         shipTrans.position = hangars[hangarIndex].position;
         shipTrans.rotation = hangars[hangarIndex].rotation;
     }
     for (int i = 0; i < ship_gridPos_Table.Count; i++)
     {
         if (skipCutscene) yield break;
         Transform shipTrans = ship_gridPos_Table.ElementAt(i).Key;
         Vector3 destination = ship_gridPos_Table.ElementAt(i).Value;
         yield return StartCoroutine(ExitHangar(shipTrans));
         if (skipCutscene) yield break;
         yield return StartCoroutine(FlyToGridPos(shipTrans, destination));
         if (skipCutscene) yield break;
         //swing back to mothership until last ship
         if (!skipCutscene && i < ship_gridPos_Table.Count - 1)
         {
             yield return StartCoroutine(CameraDirector.Instance.MoveAndRotate(camMotherShipPos, camMotherShipRot, 1.0f));
         }
         shipTrans.position = destination;
         shipTrans.rotation = Quaternion.identity;
     }
     PostCutscene();
 }
    static void Main(string[] args)
    {
        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine("Knapsack Problem Solution :)");
        Console.WriteLine();
        Console.ResetColor();

        // Checking input size of the knapsack.
        string consoleInputKnapsackSize = default(string);
        int knapsackSize = default(int);
        ValidateTheInputKnapsackSize(ref consoleInputKnapsackSize, ref knapsackSize);

        // Checking input count of products.
        string consoleInputProductsCount = default(string);
        int productsCount = default(int);
        ValidateTheInputProductsCount(ref consoleInputProductsCount, ref productsCount);

        Console.WriteLine();
        Console.WriteLine("Example for product adding...");
        Console.WriteLine("beer–3-2 => name=beer – weight=3 - cost=2");
        Console.WriteLine();

        // In this dictionary will be added to all products.
        Dictionary<string, List<int>> allProducts = new Dictionary<string, List<int>>();

        // This for loop will get all inputed products from console.
        GetAllInputedProductsFromConsole(productsCount, allProducts);

        // Verify that only one product is added and return it as a result.
        if (allProducts.Count == 1)
        {
            string firstProductName = allProducts.ElementAt(0).Key;
            int firstProductWeight = allProducts.ElementAt(0).Value[0];
            int firstProductCost = allProducts.ElementAt(0).Value[1];

            Console.WriteLine("Best solution is: Name=" + firstProductName + 
                " - Weight=" + firstProductWeight + " - Cost=" + firstProductCost);

            return;
        }

        // Arrays for dynamic programming solution of the problem.
        int[,] valuesArray = new int[productsCount + 1, knapsackSize + 1];
        int[,] keepArray = new int[productsCount + 1, knapsackSize + 1];

        InputTheProductsDataIntoArrays(allProducts, valuesArray, keepArray);

        List<string> bestSolutionItems = new List<string>();

        FindBestSolutionItems(knapsackSize, allProducts, keepArray, bestSolutionItems);

        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine();
        Console.Write("Best choice is: ");
        Console.WriteLine(string.Join(", ", bestSolutionItems));
        Console.ResetColor();

        Console.ReadLine();
    }
Example #15
0
        public void OnTick(object sender, EventArgs e)
        {
            if (!Main.IsOnServer()) return;

            const int npcThreshold = 5000; // 5 second timeout
            const int playerThreshold = 60000; // 60 second timeout

            Dictionary<long, SyncPed> localOpps = null;
            lock (Main.Opponents) localOpps = new Dictionary<long, SyncPed>(Main.Opponents);
            for (int i = localOpps.Count - 1; i >= 0; i--)
            {
                if (DateTime.Now.Subtract(localOpps.ElementAt(i).Value.LastUpdateReceived).TotalMilliseconds > playerThreshold)
                {
                    var key = localOpps.ElementAt(i).Key;
                    localOpps[key].Clear();
                    localOpps.Remove(key);
                }
            }

            Dictionary<string, SyncPed> localNpcs = null;
            lock (Main.Npcs) localNpcs = new Dictionary<string, SyncPed>(Main.Npcs);
            for (int i = localNpcs.Count - 1; i >= 0; i--)
            {
                if (DateTime.Now.Subtract(localNpcs.ElementAt(i).Value.LastUpdateReceived).TotalMilliseconds > npcThreshold)
                {
                    var key = localNpcs.ElementAt(i).Key;
                    localNpcs[key].Clear();
                    localNpcs.Remove(key);
                }
            }

            lock (Main.Opponents) foreach (KeyValuePair<long, SyncPed> opp in new Dictionary<long, SyncPed>(Main.Opponents)) if (!localOpps.ContainsKey(opp.Key)) Main.Opponents.Remove(opp.Key);

            lock (Main.Npcs) foreach (KeyValuePair<string, SyncPed> npc in new Dictionary<string, SyncPed>(Main.Npcs)) if (!localNpcs.ContainsKey(npc.Key)) Main.Npcs.Remove(npc.Key);

            for (int i = 0; i < localOpps.Count; i++) localOpps.ElementAt(i).Value.DisplayLocally();

            for (int i = 0; i < localNpcs.Count; i++) localNpcs.ElementAt(i).Value.DisplayLocally();

            if (Main.SendNpcs)
            {
                var list = new List<int>(localNpcs.Where(pair => pair.Value.Character != null).Select(pair => pair.Value.Character.Handle));
                list.AddRange(localOpps.Where(pair => pair.Value.Character != null).Select(pair => pair.Value.Character.Handle));
                list.Add(Game.Player.Character.Handle);

                foreach (Ped ped in World.GetAllPeds()
                    .OrderBy(p => (p.Position - Game.Player.Character.Position).Length())
                    .Take(Main.PlayerSettings.MaxStreamedNpcs == 0 ? 10 : Main.PlayerSettings.MaxStreamedNpcs))
                {
                    if (!list.Contains(ped.Handle))
                    {
                        Main.SendPedData(ped);
                    }
                }
            }

            Main.SendPlayerData();
        }
Example #16
0
 /// <summary>
 /// 生成CheckBox并设置相关属性事件
 /// </summary>
 /// <param name="dic"></param>
 /// <param name="num"></param>
 /// <param name="j"></param>
 /// <param name="i"></param>
 public void InitCheckBox(Dictionary<string,int> dic,int num,int j,int i,bool check = true)
 {
     CheckBox chk = new CheckBox();
     chk.Text = dic.ElementAt(j - 1).Key;
     chk.Tag = dic.ElementAt(j - 1).Value;
     chk.Checked = check;
     chk.Width = 150;
     chk.Click += new EventHandler(CheckBoxChanged);
     chk.Location = new Point(57 + (num * 210), 10 + (i * 30));
     this.panel1.Controls.Add(chk);
 }
        public static void ToNetMsg(Dictionary<long, F3_NetServerInfo> servers, ref NetOutgoingMessage netMsg)
        {
            netMsg.Write((byte)NetDataType.eDATA_REQUEST_SERVER_LIST);

            StringBuilder sb = new StringBuilder();
            JsonWriter writer = new JsonWriter(sb);

            writer.WriteObjectStart();
            writer.WritePropertyName("servers");
            writer.WriteArrayStart();

            for (int i = 0; i < servers.Count; i++)
            {
                F3_NetServerInfo info = servers.ElementAt(i).Value;
                writer.WriteObjectStart();

                writer.WritePropertyName("UUID");
                writer.Write(servers.ElementAt(i).Key);

                writer.WritePropertyName("serverName");
                writer.Write(info.m_serverName);

                writer.WritePropertyName("type");
                writer.Write((int)info.m_serverType);

                writer.WritePropertyName("internal_ip");
                writer.Write(info.m_serverInternalAdress.Address.ToString());

                writer.WritePropertyName("internal_port");
                writer.Write(info.m_serverInternalAdress.Port);

                writer.WritePropertyName("external_ip");
                writer.Write(info.m_serverExternalAdress.Address.ToString());

                writer.WritePropertyName("external_port");
                writer.Write(info.m_serverExternalAdress.Port);

                writer.WritePropertyName("maxPlayers");
                writer.Write(info.m_maxPlayers);

                writer.WritePropertyName("currentPlayers");
                writer.Write(info.m_currentNbPlayers);

                writer.WritePropertyName("token");
                writer.Write(info.m_NATtoken);

                writer.WriteObjectEnd();
            }

            writer.WriteArrayEnd();
            writer.WriteObjectEnd();

            netMsg.Write(sb.ToString());
        }
		public MongoClient Connexion(Dictionary<string, int> listAdressPort) {
			string conn = "mongodb://";

			for (int i = 0; i < listAdressPort.Keys.Count; i++) {
				conn += listAdressPort.ElementAt(i).Key + ":" + listAdressPort.ElementAt(i).Value;
				if (i != listAdressPort.Keys.Count - 1)
					conn += ',';
			}
			conn += "/";

			return new MongoClient(conn);
		}
    static void SolveTask1()
    {
        int[] points = Console.ReadLine().Split(',').Select(ch => int.Parse(ch)).ToArray();
        Dictionary<int, int> occurs = new Dictionary<int, int>();

        for (int i = 0; i < points.Length; i++)
            if (!occurs.ContainsKey(points[i]) && points[i] <= 21) occurs.Add(points[i], 1);
            else if (points[i] <= 21) occurs[points[i]]++;

        occurs = occurs.OrderByDescending(i => i.Key).ToDictionary(k => k.Key, k => k.Value);

        Console.WriteLine(occurs.ElementAt(0).Value == 1 ? Array.IndexOf(points, occurs.ElementAt(0).Key) : -1);
    }
Example #20
0
        public void AddNewPollHandler(Dictionary<string, Dictionary<string, Dictionary<string, CityDetails>>> Areas,
            Dictionary<string, Dictionary<string, SubsectionDetails>> sections,
            List<string> keywords)
        {
            string to_string = "";
            for (int i = 0; i < keywords.Count; i++)
            {
                to_string += keywords[i];
                if (i + 1 != keywords.Count)
                    to_string += ", ";
            }
            int index = poll_handlers_.Count;
            //poll_handlers_.Insert(index, new PollHandler(this, Areas, keywords, sections, to_string));
            //poll_handlers_[index].Start();

            TreeNode keyword_node = this.trFilters.Nodes.Add(to_string);

            //Add the sections.
            TreeNode sections_node = keyword_node.Nodes.Add("Sections");
            for (int sections_counter = 0; sections_counter < sections.Count; sections_counter++)
            {
                string section_name = sections.ElementAt(sections_counter).Key;
                Dictionary<string, SubsectionDetails> subsections = sections.ElementAt(sections_counter).Value;
                TreeNode current_section_node = sections_node.Nodes.Add(section_name);
                for (int subsections_counter = 0; subsections_counter < subsections.Count; subsections_counter++)
                {
                    string subsection_name = subsections.ElementAt(subsections_counter).Key;
                    current_section_node.Nodes.Add(subsection_name);
                }
            }
            //Add the areas
            TreeNode areas_node = keyword_node.Nodes.Add("Areas");
            for (int country_counter = 0; country_counter < Areas.Count; country_counter++)
            {
                Dictionary<string, Dictionary<string, CityDetails>> state_map = Areas.ElementAt(country_counter).Value;
                string country_name = Areas.ElementAt(country_counter).Key;
                TreeNode country_node = areas_node.Nodes.Add(country_name);
                for (int state_counter = 0; state_counter < state_map.Count; state_counter++)
                {
                    Dictionary<string, CityDetails> city_map = state_map.ElementAt(state_counter).Value;
                    string state_name = state_map.ElementAt(state_counter).Key;
                    TreeNode state_node = country_node.Nodes.Add(state_name);
                    for (int city_counter = 0; city_counter < city_map.Count; city_counter++)
                    {
                        string city_name = city_map.ElementAt(city_counter).Key;
                        state_node.Nodes.Add(city_name);
                    }
                }
            }
        }
Example #21
0
        private List<Fork> GetForks(SportType sportType, Dictionary<GameInfo, List<Game>> gameLists)
        {
            var forks = new List<Fork>();

            for (var i = 0; i < gameLists.Count; i++)
            {
                forks.AddRange(this.Searcher.SearchForks(
                        gameLists.ElementAt(i).Key,
                        gameLists.ElementAt(i).Value,
                        sportType));
            }

            return forks;
        }
        /*
         * AdditionalProperties
         *
         * Constructor for AdditionalProperties form.  Enables user to
         * add/delete/modify properties of a current entity.
         *
         * Dictionary<string, string> props: list of current properties the
         *                                   selected entity owns
         */
        public AdditionalProperties(Dictionary<string, string> props)
        {
            InitializeComponent();

            Properties = new Dictionary<string, string>();
            if (props.Count > 0)
                for (var i = 0; i < props.Count; i++)
                {

                    var name = props.ElementAt(i).Key;
                    var value = props.ElementAt(i).Value;
                    Properties.Add(name, value);
                    lb_properties.Items.Add(name + "/" + value);
                }
        }
 /// <summary>
 /// 执行一段 C# 代码并返回结果。
 /// </summary>
 /// <param name="codeBody">方法体。</param>
 /// <param name="parameters">参数(名称,值)。</param>
 /// <returns>方法的返回值。</returns>
 public static object RunCode(string codeBody, Dictionary<string, object> parameters)
 {
     using (CSharpCodeProvider provider = new CSharpCodeProvider())
     {
         CompilerParameters parameter = new CompilerParameters();
         parameter.GenerateExecutable = false;
         parameter.GenerateInMemory = true;
         StringBuilder sb = new StringBuilder(); // 生成方法参数代码。
         List<object> methodParameters = new List<object>(); // 调用方法时的参数对象列表。
         for (int i = 0; i < parameters.Count; i++)
         {
             var temp = parameters.ElementAt(i);
             sb.Append(temp.Value.GetType().FullName + " " + temp.Key);
             methodParameters.Add(temp.Value);
             if (i != parameters.Count - 1)
             {
                 sb.Append(",");
             }
         }
         string source = @"using System;namespace NameSpace{public class Class{public static object Method(" +
                         sb.ToString() + @"){" + codeBody + @"}}}"; // 最终代码段。
         CompilerResults result = provider.CompileAssemblyFromSource(parameter, source); // 编译代码。
         if (result.Errors.Count > 0)
         {
             throw new Exception("代码错误");
         }
         else
         {
             Assembly assembly = result.CompiledAssembly; // 获得编译成功的程序集。
             Type type = assembly.GetType("NameSpace.Class");
             return type.GetMethod("Method").Invoke(null, methodParameters.ToArray()); // 执行方法。
         }
     }
 }
    static void Main()
    {
        string text = Console.ReadLine();
        string[] words = text.Split(' ', '.');
        Dictionary<string, int> wordsCount = new Dictionary<string, int>();

        foreach (string word in words)
        {
            if (wordsCount.ContainsKey(word) == false)
            {
                int count = word.Length;
                wordsCount.Add(word, count);
            }
        }
        string maxKey = wordsCount.ElementAt(0).Key;
        int maxValue = int.MinValue;
        foreach (string word in wordsCount.Keys)
        {
            if (wordsCount[word] > maxValue)
            {
                maxKey = word;
                maxValue = wordsCount[word];
            }
        }
        // second way:
        // string maxKey = wordsCount.Aggregate((l, r) => l.Value > r.Value ? l : r).Key;
        Console.WriteLine(maxKey);
    }
Example #25
0
 public static void Rename(Dictionary<string, string> file_to_new_file)
 {
     var file_to_new_file_copy = new Dictionary<string, string>(file_to_new_file);
     while (file_to_new_file_copy.Count > 0)
     {
         var kvp = file_to_new_file_copy.ElementAt(0);
         Action<string> recursive_rename_delegate = null;
         recursive_rename_delegate = file =>
         {
             if (File.Exists(file_to_new_file_copy[file]))
             {
                 if (file_to_new_file_copy[file] == kvp.Key)
                 {
                     string temp_file = Path.Combine(Path.GetDirectoryName(file) ?? string.Empty, Path.GetRandomFileName());
                     File.Move(file, temp_file);
                     file_to_new_file_copy[temp_file] = file_to_new_file_copy[file];
                     file_to_new_file_copy.Remove(file);
                     return;
                 }
                 else
                 {
                     recursive_rename_delegate(file_to_new_file_copy[file]);
                 }
             }
             File.Move(file, file_to_new_file_copy[file]);
             file_to_new_file_copy.Remove(file);
         };
         recursive_rename_delegate(kvp.Key);
     }
 }
 public BoolMatrix InitializeInterations(int length, int nComponents, int nInteractions, IRandom random) {
   Dictionary<int, int> bitInteractionCounts = new Dictionary<int, int>();
   for (int i = 0; i < length; i++) {
     int count = nInteractions * 2 * i / length;
     if (count > 0)
       bitInteractionCounts[i] = count;
   }
   List<BinaryVector> components = new List<BinaryVector>();
   while (bitInteractionCounts.Count > 0) {
     BinaryVector component = new BinaryVector(length);
     for (int i = 0; i < nInteractions; i++) {
       while (bitInteractionCounts.Count > 0) {
         int bit = bitInteractionCounts.ElementAt(random.Next(bitInteractionCounts.Count)).Key;
         if (bitInteractionCounts[bit]-- <= 0)
           bitInteractionCounts.Remove(bit);
         if (!component[bit]) {
           component[bit] = true;
           break;
         }
       }
     }
     components.Add(component);
   }
   BoolMatrix m = new BoolMatrix(length, components.Count);
   foreach (var c in components.Select((v, j) => new { v, j })) {
     for (int i = 0; i < c.v.Length; i++) {
       m[i, c.j] = c.v[i];
     }
   }
   return m;
 }
Example #27
0
        public StandardMenu(int bW, int bH, int xO, int yO, int w, int h)
            : base(bW, bH, xO, yO, w, h)
        {
            // Set up commands
            go = new Go(ConsoleKey.G);
            examine = new Examine(ConsoleKey.E);

            // Link console keys to their assigned commands
            commandKeys = new Dictionary<ConsoleKey, Commands.Command>();

            commandKeys.Add(go.KeyBinding, go);
            commandKeys.Add(examine.KeyBinding, examine);

            // Set screen positions from commands, then populate
            // the menuSlots dictionary
            // This approach seems awkward and ugly.
            // Consider for major refactor.
            menuSlots = new Dictionary<Command, Coordinate>();

            textOrigin = new Coordinate(xO + 1, yO + 1);

            int yOffset = 0;

            for (int i = 0; i < commandKeys.Count; i++)
            {
                Command currentCommand = commandKeys.ElementAt(i).Value;

                menuSlots.Add(currentCommand,
                    new Coordinate(textOrigin.xCoordinate,
                    textOrigin.yCoordinate + yOffset));

                yOffset++;
            }
        }
	Dictionary<string, Dictionary<string, string>> locDictionary;	// Collection of language dictionaries.

	void Awake()
	{
		// Register this script as the singleton instance.
		Instance = this;

		// Read the localization string data file.
		locDictionary = CSVReader.Read("Localization");
		var first = locDictionary.ElementAt(0).Value;
		if (first.Count <= 0)
		{
			Debug.Log("Invalid localization file. No language found!");
			return;
		}

		// Get the list of available languages.
		languages = new List<string>();
		foreach (string k in first.Keys)
		{
			languages.Add(k);
		}

		// If we don't have a language selected, default to the first language in our list.
		if (currentLanguage == null || currentLanguage.Length == 0)
		{
			currentLanguage = languages.First();
		}
	}
        private static string GetQueryString(Dictionary<string, string> values)
        {
            string toReturn = string.Empty;

            if (values.Count == 0)
            {
                return toReturn;
            }

            toReturn = "?";

            for (int i = 0; i < values.Count; i++)
            {
                var element = values.ElementAt(i);
                var key = System.Net.WebUtility.UrlEncode (element.Key);
                var value = System.Net.WebUtility.UrlEncode (element.Value);
                var stringArgument = string.Format ("{0}={1}", key, value);

                //not the last
                if(i != values.Count-1)
                {
                    stringArgument += "&";
                }

                toReturn += stringArgument;
            }

            return toReturn;
        }
Example #30
0
        /*
        static public Boolean CheckCoolDown(String name, out int timeLeft)
        {
            timeLeft = 0;
            DockingCooldownItem item = null;
            var list = PluginDocking.CooldownList.FindAll(n => n.name.ToLower() == name.ToLower()); // Change to FirstOrDefault
            foreach (DockingCooldownItem i in list)
            {
                item = i;
                break;
            }

            if (item != null)
            {
                timeLeft = (int)(20.0 - (DateTime.Now - item.startTime).TotalSeconds);
                if (timeLeft <= 0)
                {
                    PluginDocking.CooldownList.Remove(item);
                    item = null;
                }
            }

            return item != null;
        }
         */
        public static bool CheckForIntersection(Dictionary<String, List<IMyCubeBlock>> testList, List<IMyCubeBlock> beaconList, out int intersectElement)
        {
            Boolean intersects = false;
            intersectElement = 0;
            OrientedBoundingBoxD targetTestBounding = Entity.GetBoundingBox(beaconList);
            if (testList.Count > 0)
            {
                for (int r = 0; r < testList.Count; r++)
                {
                    List<IMyCubeBlock> beaconTestList = (List<IMyCubeBlock>)testList.ElementAt(r).Value;
                    if (beaconTestList.Count != 4)
                        continue;

                    OrientedBoundingBoxD testBounding = Entity.GetBoundingBox(beaconTestList);
                    if (testBounding.Contains(ref targetTestBounding) != ContainmentType.Disjoint)
                    {
                        intersectElement = r;
                        intersects = true;
                        break;
                    }
                }
            }

            return intersects;
        }