Ejemplo n.º 1
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);
        }
Ejemplo n.º 2
0
        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;
        }
Ejemplo n.º 3
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;
        }
 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();
 }
        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);
                        }
                    }
                }
            }
        }
Ejemplo n.º 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] = "";
        }
    }
Ejemplo n.º 7
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))
            {

            }
        }
Ejemplo n.º 8
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();
        }
Ejemplo n.º 9
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);
        }
Ejemplo n.º 10
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;
        }
Ejemplo n.º 11
0
    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);
    }
        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);
            }
        }
        //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);
        }
    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();
    }
Ejemplo n.º 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();
        }
        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());
        }
Ejemplo n.º 17
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);
 }
Ejemplo n.º 18
0
		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);
		}
Ejemplo n.º 19
0
    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);
    }
Ejemplo n.º 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);
                    }
                }
            }
        }
Ejemplo n.º 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;
        }
Ejemplo n.º 22
0
        /*
         * 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);
                }
        }
Ejemplo n.º 23
0
 private void UpdateAdminClients()
 {
     UsingClients.Clear();
     for (int i = 0; i < Admins.Count; i++)
     {
         try
         {
             Admins?.ElementAt(i).Value?.Callback?.UpdateClients(UsingClients, Clients);
         }
         catch
         {
             Admins.Remove(Admins?.ElementAt(i).Key);
         }
     }
 }
Ejemplo n.º 24
0
    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);
    }
 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;
 }
 /// <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()); // 执行方法。
         }
     }
 }
Ejemplo n.º 27
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);
     }
 }
Ejemplo n.º 28
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++;
            }
        }
Ejemplo n.º 29
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;
        }
        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;
        }
	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();
		}
	}
Ejemplo n.º 32
0
        public static void Main(string[] args)
        {
            List <Customer>             customers = new List <Customer>();
            Dictionary <String, double> menu      = new Dictionary <String, double>();
            int    amount  = int.Parse(Console.ReadLine());
            String command = "";

            for (int i = 0; i < amount; i++)
            {
                String[] input = Console.ReadLine().Split('-');
                // add menu item
                if (!menu.ContainsKey(input[0]))
                {
                    menu.Add(input[0], double.Parse(input[1]));
                } // replace existent item price
                else
                {
                    menu[input[0]] = double.Parse(input[1]);
                }
            }
            command = Console.ReadLine();
            while (command != "end of clients")
            {
                String[] input             = command.Split('-');
                String   clientName        = input[0];
                String[] clientOrder       = input[1].Split(',');
                String   clientOrderName   = clientOrder[0];
                int      clientOrderAmount = int.Parse(clientOrder[1]);
                // check customer for existence
                bool hasCustomer = false;
                for (int i = 0; i < customers.Count; i++)
                {
                    if (customers[i].name == clientName)
                    {
                        hasCustomer = true; break;
                    }
                }
                // add customer and ignore duplicate item in menu
                if (!hasCustomer && menu.ContainsKey(clientOrderName))
                {
                    Customer newCustomer = new Customer();
                    newCustomer.name = clientName;
                    newCustomer.order.Add(clientOrderName, clientOrderAmount);
                    customers.Add(newCustomer);
                }
                command = Console.ReadLine();
            }
            double totalBill = 0;

            // calculate customer bill
            for (int c = 0; c < customers.Count; c++)
            {
                for (int m = 0; m < menu.Count; m++)
                {
                    double tempBill = 0;
                    for (int o = 0; o < customers[c].order.Count; o++)
                    {
                        if (menu.ElementAt(m).Key == customers[c].order.ElementAt(o).Key)
                        {
                            tempBill += customers[c].order.ElementAt(o).Value *menu.ElementAt(m).Value;
                        }
                        break;
                    }
                    customers[c].bill += tempBill;
                }
                totalBill += customers[c].bill;
            }

            // sort cunstomers list
            customers = customers.OrderBy(a => a.name).ToList();

            // print result
            for (int c = 0; c < customers.Count; c++)
            {
                Console.WriteLine(customers[c].name);
                for (int o = 0; o < customers[c].order.Count; o++)
                {
                    Console.WriteLine("-- {0} - {1}", customers[c].order.ElementAt(o).Key,
                                      customers[c].order.ElementAt(o).Value);
                }
                Console.WriteLine("Bill: {0:f2}", customers[c].bill);
            }
            Console.WriteLine("Total bill: {0:f2}", totalBill);
        }
Ejemplo n.º 33
0
        private void NextPage()
        {
            if (currentPage >= totalPages - 1)
            {
                return;
            }

            currentPage++;
            if (pages.ElementAt(currentPage).Value.ElementAt(0) != null)
            {
                CurrentSeason     = pages.ElementAt(currentPage).Value.ElementAt(0).VirtualSeason.ToString();
                CurrentPageToShow = pages.ElementAt(currentPage).Value.ElementAt(0).VirtualDay.ToString();
            }
            Update();
            OnPropertyChanged("CurrentPageToShow");
            OnPropertyChanged("PrevPageToShow");
            OnPropertyChanged("NextPageToShow");
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Init Worksheet
        /// </summary>
        private void InitWorksheet()
        {
            WorksheetAttribute classAttribue = _RecordModelType.GetCustomAttribute(typeof(WorksheetAttribute)) as WorksheetAttribute;

            if (classAttribue != null)
            {
                _Worksheet.Name = classAttribue.Title;
            }
            else
            {
                _Worksheet.Name = _RecordModelType.Name;
            }

            PropertyInfo[] properties = _RecordModelType.GetProperties();
            Dictionary <PropertyInfo, ColumnHeaderAttribute> ColHeaderAttributeDict = new Dictionary <PropertyInfo, ColumnHeaderAttribute>();

            foreach (PropertyInfo property in properties)
            {
                ColumnHeaderAttribute headerAttribute = property.GetCustomAttribute(typeof(ColumnHeaderAttribute)) as ColumnHeaderAttribute;
                if (headerAttribute != null && headerAttribute.IsVisible) //filter invisible item
                {
                    ColHeaderAttributeDict.Add(property, headerAttribute);
                }
            }
            if (ColHeaderAttributeDict.Count < 1)
            {
#if DEBUG
                Console.WriteLine("InitWorksheet Failed: HeaderAttributes.Count is 0.");
#endif
                return;
            }
            ColHeaderAttributeDict = ColHeaderAttributeDict.OrderBy(one => one.Value.Index).ToDictionary(one => one.Key, one => one.Value); // order by index
            // Re-Set Index
            for (int i = 0; i < ColHeaderAttributeDict.Keys.Count; i++)
            {
                var key = ColHeaderAttributeDict.Keys.ElementAt(i);
                ColHeaderAttributeDict[key].Index = i;
            }


            _Worksheet.Columns = ColHeaderAttributeDict.Count;


            RangePosition rangePosition = new RangePosition();

            rangePosition.Cols = 1;
            rangePosition.Row  = 0;
            rangePosition.Rows = _Worksheet.RowCount;

            for (int i = 0; i < properties.Count(); i++)
            {
                PropertyInfo property  = properties[i];
                var          attribute = property.GetCustomAttribute(typeof(FormatAttributeBase));
                if (attribute == null)
                {
                    continue;
                }
                IFormatArgs formatArgs = attribute as IFormatArgs;
                if (formatArgs != null)
                {
                    ColumnHeaderAttribute headerAttribute = (from key in ColHeaderAttributeDict.Keys
                                                             where key.Equals(property)
                                                             select ColHeaderAttributeDict[property]).FirstOrDefault();

                    if (headerAttribute != null && headerAttribute.IsVisible)
                    {
                        rangePosition.Col = headerAttribute.Index;
                        //not work correctly
                        switch (formatArgs.CellDataFormatFlag)
                        {
                        case CellDataFormatFlag.General:
                            break;

                        case CellDataFormatFlag.Number:
                        {
                            NumberFormatAttribute numberFormatAttribute          = formatArgs as NumberFormatAttribute;
                            NumberDataFormatter.NumberFormatArgs numberFormatter = new NumberDataFormatter.NumberFormatArgs();
                            if (numberFormatAttribute.DecimalPlaces != short.MaxValue)
                            {
                                numberFormatter.DecimalPlaces = numberFormatAttribute.DecimalPlaces;
                            }
                            numberFormatter.NegativeStyle         = numberFormatAttribute.NegativeStyle;
                            numberFormatter.UseSeparator          = numberFormatAttribute.UseSeparator;
                            numberFormatter.CustomNegativePrefix  = numberFormatAttribute.CustomNegativePrefix;
                            numberFormatter.CustomNegativePostfix = numberFormatAttribute.CustomNegativePostfix;
                            _Worksheet.SetRangeDataFormat(rangePosition, CellDataFormatFlag.Number, numberFormatter);
                            //_ReoGridControl.DoAction(new SetRangeDataFormatAction(rangePosition, CellDataFormatFlag.Number, numberFormatter));
                            break;
                        }

                        case CellDataFormatFlag.DateTime:
                        {
                            DateTimeFormatAttribute dateTimeFormatAttribute             = formatArgs as DateTimeFormatAttribute;
                            DateTimeDataFormatter.DateTimeFormatArgs dateTimeFormatArgs = new DateTimeDataFormatter.DateTimeFormatArgs();
                            dateTimeFormatArgs.Format      = dateTimeFormatAttribute.Format;
                            dateTimeFormatArgs.CultureName = dateTimeFormatAttribute.CultureName;
                            _Worksheet.SetRangeDataFormat(rangePosition, CellDataFormatFlag.DateTime, dateTimeFormatArgs);
                            break;
                        }

                        case CellDataFormatFlag.Percent:
                            break;

                        case CellDataFormatFlag.Currency:
                            break;

                        case CellDataFormatFlag.Text:
                            break;

                        case CellDataFormatFlag.Custom:
                            break;

                        default:
                            break;
                        }
                    }
                }
            }

            _ColumnWidthList = new List <int>();
            _RowHeightList   = new List <int>();

            for (int i = 0; i < ColHeaderAttributeDict.Count; i++)
            {
                ColumnHeaderAttribute headerAttribute = ColHeaderAttributeDict.ElementAt(i).Value;

                if (string.IsNullOrEmpty(headerAttribute.Text))
                {
                    _Worksheet.ColumnHeaders[i].Text = ColHeaderAttributeDict.ElementAt(i).Key.Name;
                }
                else
                {
                    _Worksheet.ColumnHeaders[i].Text = headerAttribute.Text;
                }
                if (headerAttribute.Width <= 0)
                {
                    _Worksheet.ColumnHeaders[i].IsAutoWidth = true;
                }
                else
                {
                    _Worksheet.ColumnHeaders[i].Width = (ushort)headerAttribute.Width;
                }
                _Worksheet.ColumnHeaders[i].IsVisible = true;
                _Worksheet.ColumnHeaders[i].Tag       = ColHeaderAttributeDict.ElementAt(i).Key; // Tag stores PropertyInfo of Model
                _ColumnWidthList.Add(_Worksheet.ColumnHeaders[i].Width);                         // store column width
            }

            //stroe row height
            for (int i = 0; i < _Worksheet.Rows; i++)
            {
                _RowHeightList.Add(_Worksheet.RowHeaders[i].Height);
            }

            // load data
            LoadRecords();


            _Worksheet.BeforeCellEdit   += Worksheet_BeforeCellEdit;
            _Worksheet.CellDataChanged  += Worksheet_CellDataChanged;
            _Worksheet.RangeDataChanged += Worksheet_RangeDataChanged;
            _Worksheet.AfterPaste       += Worksheet_AfterPaste;

            _Worksheet.RowsHeightChanged   += Worksheet_RowsHeightChanged;
            _Worksheet.ColumnsWidthChanged += Worksheet_ColumnsWidthChanged;
        }
        public void Medley()
        {
            string keys = "AAAAAAABCDEFGabcdefg";

            Random rand = new Random();

            for (int capacity = 0; capacity < HybridDictionary <string, string> .MaxListSize + 2; capacity++)
            {
                var dict   = new HybridDictionary <string, string>(capacity, StringComparer.OrdinalIgnoreCase);
                var shadow = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

                for (int i = 0; i < 2000; i++)
                {
                    switch (rand.Next(10 + 1))
                    {
                    case 0:
                        // Set something
                        if (shadow.Count < HybridDictionary <string, string> .MaxListSize + 2)   // Don't bother exploring above here
                        {
                            string key   = new String(keys[rand.Next(keys.Length)], 1);
                            string value = rand.Next(10).ToString();
                            dict[key]   = value;
                            shadow[key] = value.ToString();
                            AssertDictionariesIdentical(dict, shadow);
                        }

                        break;

                    case 1:
                        // Remove something existing
                        if (shadow.Count > 0)
                        {
                            var entry = shadow.ElementAt(rand.Next(shadow.Count - 1)).Key;
                            Assert.Equal(dict.Remove(entry), shadow.Remove(entry));
                            AssertDictionariesIdentical(dict, shadow);
                        }

                        break;

                    case 2:
                        // Remove something nonexistent
                        AssertBothOrNeitherThrew <bool>(delegate() { return(dict.Remove("ZZ")); }, delegate() { return(shadow.Remove("ZZ")); });
                        AssertDictionariesIdentical(dict, shadow);
                        break;

                    case 3:
                        // Look up something existing
                        if (shadow.Count > 0)
                        {
                            var entry2 = shadow.ElementAt(rand.Next(shadow.Count - 1)).Key;
                            Assert.Equal(dict[entry2], shadow[entry2]);
                            AssertDictionariesIdentical(dict, shadow);
                        }

                        break;

                    case 4:
                        // Look up something non existing
                        AssertBothOrNeitherThrew <string>(delegate() { return(dict["ZZ"]); }, delegate() { return(shadow["ZZ"]); });
                        AssertDictionariesIdentical(dict, shadow);
                        break;

                    case 5:
                        // Try look up something existing
                        if (shadow.Count > 0)
                        {
                            var    entry2 = shadow.ElementAt(rand.Next(shadow.Count - 1)).Key;
                            string value1;
                            string value2;
                            Assert.Equal(dict.TryGetValue(entry2, out value1), shadow.TryGetValue(entry2, out value2));
                            Assert.Equal(value1, value2);
                            AssertDictionariesIdentical(dict, shadow);
                        }

                        break;

                    case 6:
                        // Try look up something non existing
                        string value3;
                        string value4;
                        Assert.Equal(dict.TryGetValue("ZZ", out value3), shadow.TryGetValue("ZZ", out value4));
                        AssertDictionariesIdentical(dict, shadow);
                        break;

                    case 7:
                        dict.Clear();
                        shadow.Clear();
                        break;

                    case 8:
                        // Add something existing key same value
                        if (shadow.Count > 0)
                        {
                            var entry = shadow.ElementAt(rand.Next(shadow.Count - 1));
                            AssertBothOrNeitherThrew(delegate() { dict.Add(entry.Key, entry.Value); }, delegate() { shadow.Add(entry.Key, entry.Value); });
                            AssertDictionariesIdentical(dict, shadow);
                        }

                        break;

                    case 9:
                        // Add something existing key different value
                        if (shadow.Count > 0)
                        {
                            var    key   = shadow.ElementAt(rand.Next(shadow.Count - 1)).Key;
                            string value = rand.Next(10).ToString();
                            AssertBothOrNeitherThrew(delegate() { dict.Add(key, value); }, delegate() { shadow.Add(key, value); });
                            AssertDictionariesIdentical(dict, shadow);
                        }

                        break;

                    case 10:
                        // Add something non existing
                        string key2   = new String(keys[rand.Next(keys.Length)], 1);
                        string value5 = rand.Next(10).ToString();
                        AssertBothOrNeitherThrew(delegate() { dict.Add(key2, value5); }, delegate() { shadow.Add(key2, value5); });
                        AssertDictionariesIdentical(dict, shadow);
                        break;
                    }
                }

                dict.Clear();
                Assert.Equal(0, dict.Count);
            }
        }
Ejemplo n.º 36
0
        private void buildButton_Click(object sender, EventArgs e)
        {
            if (originalObject == null)
            {
                MessageBox.Show("Объект не был сгенерирован", "Ошибка");
                return;
            }

            double x1, x2, delta;
            int    n;

            try
            {
                n  = Convert.ToInt32(nTextBox.Text);
                x1 = Convert.ToDouble(x1TextBox.Text);
                x2 = Convert.ToDouble(x2TextBox.Text);
            }
            catch (FormatException)
            {
                MessageBox.Show("Введены некорректные данные.", "Ошибка ввода");
                return;
            }

            delta = Math.Abs(x1 - x2) / n;

            types  = new List <ModelBuilding.CoreType>();
            models = new List <Dictionary <double, double> >();

            if (rectCheckBox.Checked)
            {
                types.Add(ModelBuilding.CoreType.Recatangle);
            }
            if (triCheckBox.Checked)
            {
                types.Add(ModelBuilding.CoreType.Triangle);
            }
            if (parCheckBox.Checked)
            {
                types.Add(ModelBuilding.CoreType.Parabola);
            }
            if (cubeCheckBox.Checked)
            {
                types.Add(ModelBuilding.CoreType.Cube);
            }

            foreach (var type in types)
            {
                ModelBuilding modelBuilding = new ModelBuilding(delta, type);
                GoldenRatio   goldenRatio   = new GoldenRatio(originalObject, modelBuilding);
                var           model         = new Dictionary <double, double>();

                modelBuilding.B = goldenRatio.FindMin(0.00001, 0, 0.9);

                double coreXN, reg, temp = 0;
                int    tempIndL = 0, tempIndJ = 0;
                bool   flag = false;
                for (int i = 0; i < originalObject.Count; i++)
                {
                    coreXN = 0; reg = 0;
                    flag   = false;

                    for (int l = tempIndL; l < originalObject.Count; l++)
                    {
                        temp = modelBuilding.CoreFunction(originalObject.ElementAt(i).Key, originalObject.ElementAt(l).Key);
                        if (temp != 0 && !flag)
                        {
                            flag     = true;
                            tempIndL = l;
                            coreXN  += temp;
                        }
                        else if (temp != 0)
                        {
                            coreXN += temp;
                        }
                        else if (temp == 0 && flag)
                        {
                            break;
                        }
                    }

                    flag = false;

                    for (int j = tempIndJ; j < originalObject.Count; j++)
                    {
                        temp = modelBuilding.CoreFunction(originalObject.ElementAt(i).Key, originalObject.ElementAt(j).Key);

                        if (temp != 0 && !flag)
                        {
                            flag     = true;
                            tempIndJ = j;
                            reg     += (temp / coreXN) * originalObject.ElementAt(j).Value;
                        }
                        else if (temp != 0)
                        {
                            reg += (temp / coreXN) * originalObject.ElementAt(j).Value;
                        }
                        else if (temp == 0 && flag)
                        {
                            break;
                        }
                    }

                    model.Add(originalObject.ElementAt(i).Key, reg);
                }

                models.Add(model);
            }
        }
Ejemplo n.º 37
0
 public override KeyValuePair <string, string[]> this[int position]
 {
     get { return(items.ElementAt(position)); }
 }
Ejemplo n.º 38
0
        private void PlaceShipRandomly(int shipLength)
        {
            bool   notValidPlace = true;
            Random rnd           = new Random();

            while (notValidPlace)
            {
                int xRand = rnd.Next(0, 10);
                int yRand = rnd.Next(0, 10);

                if (!Grid[xRand, yRand].Equals('S'))
                {
                    Dictionary <string, Boolean> directions = new Dictionary <string, bool>();
                    directions.Add("Right", true);
                    directions.Add("Top", true);
                    directions.Add("Left", true);
                    directions.Add("Bottom", true);



                    for (int i = 1; i < shipLength; i++)
                    {
                        // right
                        if (xRand + i > 9)
                        {
                            directions["Right"] = false;
                        }

                        else if (Grid[xRand + i, yRand].Equals('S'))
                        {
                            directions["Right"] = false;
                        }

                        // top
                        if (yRand - i < 0)
                        {
                            directions["Top"] = false;
                        }
                        else if (Grid[xRand, yRand - i].Equals('S'))
                        {
                            directions["Top"] = false;
                        }
                        // left
                        if (xRand - i < 0)
                        {
                            directions["Left"] = false;
                        }
                        else if (Grid[xRand - i, yRand].Equals('S'))
                        {
                            directions["Left"] = false;
                        }

                        // bottom
                        if (yRand + i > 9)
                        {
                            directions["Bottom"] = false;
                        }

                        else if ((Grid[xRand, yRand + i].Equals('S')))
                        {
                            directions["Bottom"] = false;
                        }
                    }


                    // place ships in random direction
                    Random rand = new Random();

                    bool placed = false;

                    while (placed == false)
                    {
                        int r = rand.Next(0, directions.Count);

                        if (directions.ElementAt(r).Value == true)
                        {
                            for (int i = 0; i < shipLength; i++)
                            {
                                if (directions.ElementAt(r).Key == "Right")
                                {
                                    SetGrid(xRand + i, yRand);
                                }

                                else if (directions.ElementAt(r).Key == "Top")
                                {
                                    SetGrid(xRand, yRand - i);
                                }

                                else if (directions.ElementAt(r).Key == "Left")
                                {
                                    SetGrid(xRand - i, yRand);
                                }

                                else
                                {
                                    SetGrid(xRand, yRand + i);
                                }
                            }

                            placed        = true;
                            notValidPlace = false;
                        }

                        directions.Remove(directions.ElementAt(r).Key);

                        if (directions.Count == 0)
                        {
                            break;
                        }
                    }
                }
            }
        }
Ejemplo n.º 39
0
        /// <summary>
        /// POST: api/Messages
        /// Receive a message from a user and reply to it
        /// </summary>
        //public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
        //{
        //    if (activity.Type == ActivityTypes.Message)
        //    {
        //        ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
        //        // calculate something for us to return
        //        int length = (activity.Text ?? string.Empty).Length;

        //        // return our reply to the user
        //        Activity reply = activity.CreateReply($"You sent {activity.Text} which was {length} characters");
        //        await connector.Conversations.ReplyToActivityAsync(reply);
        //    }
        //    else
        //    {
        //        HandleSystemMessage(activity);
        //    }
        //    var response = Request.CreateResponse(HttpStatusCode.OK);
        //    return response;
        //}
        public virtual async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            //Emotion API を使う準備: emotionApiKey にサブスクリプションキーを入れてください
            ConnectorClient connector     = new ConnectorClient(new Uri(activity.ServiceUrl));
            const string    emotionApiKey = "";

            //Emotion API を Call する EmotionServiceClient を生成
            EmotionServiceClient emotionServiceClient = new EmotionServiceClient(emotionApiKey);

            Emotion[] emotionResult = null;

            //入力値(URL) を元に Emotion API を Call
            try
            {
                emotionResult = await emotionServiceClient.RecognizeAsync(activity.Text);
            }
            catch (Exception e)
            {
                emotionResult = null;
            }

            //デフォルトの返答 (初回、または写真判定ができなかったとき))
            Activity reply = activity.CreateReply("顔の表情を判定します。写真のURLを送ってね。");

            //Call 結果を元に 返答を作成
            if (emotionResult != null)
            {
                //表情スコアを取得
                Scores emotionScores = emotionResult[0].Scores;

                //取得したスコアを KeyValuePair に代入、スコア数値の大きい順に並び替える
                IEnumerable <KeyValuePair <string, float> > emotionList = new Dictionary <string, float>()
                {
                    { "怒ってる", emotionScores.Anger },
                    { "軽蔑してる", emotionScores.Contempt },
                    { "うんざりしてる", emotionScores.Disgust },
                    { "怖がってる", emotionScores.Fear },
                    { "楽しい", emotionScores.Happiness },
                    { "特になし", emotionScores.Neutral },
                    { "悲しい", emotionScores.Sadness },
                    { "驚いてる", emotionScores.Surprise }
                }
                .OrderByDescending(kv => kv.Value)
                .ThenBy(kv => kv.Key)
                .ToList();

                KeyValuePair <string, float> topEmotion = emotionList.ElementAt(0);
                string topEmotionKey   = topEmotion.Key;
                float  topEmotionScore = topEmotion.Value;

                reply = activity.CreateReply
                        (
                    "顔の表情を判定しました。"
                    + (int)(topEmotionScore * 100) + "% " + topEmotionKey + "顔だと思うよ。"
                        );
            }

            await connector.Conversations.ReplyToActivityAsync(reply);

            return(new HttpResponseMessage(System.Net.HttpStatusCode.Accepted));
        }
Ejemplo n.º 40
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "")
            {
                return;
            }
            dictionary.Clear();
            char_range_from_to.Clear();
            for (int i = 0; i < textBox1.Text.Length; i++)
            {
                if (dictionary.ContainsKey(textBox1.Text[i].ToString()))
                {
                    dictionary[textBox1.Text[i].ToString()]++;
                }
                else
                {
                    dictionary[textBox1.Text[i].ToString()] = 1;
                }
            }


            //claculate probability
            List <Tuple <String, Double> > prob = new List <Tuple <String, Double> >();

            for (int i = 0; i < dictionary.Count; i++)
            {
                prob.Add(Tuple.Create(dictionary.ElementAt(i).Key, (double)(dictionary.ElementAt(i).Value) / textBox1.Text.Length));
            }

            //claculate acumilative
            List <double> acum = new List <double>();

            acum.Add(prob[0].Item2);
            for (int i = 1; i < prob.Count; i++)
            {
                acum.Add(prob[i].Item2 + acum[i - 1]);
            }

            //range   sym      from      to
            List <Tuple <string, Double, Double> > range = new List <Tuple <string, Double, Double> >();

            range.Add(Tuple.Create(dictionary.ElementAt(0).Key, (Double)0, acum[0]));
            for (int i = 1; i < acum.Count; i++)
            {
                range.Add(Tuple.Create(dictionary.ElementAt(i).Key, acum[i - 1], acum[i]));
            }

            //add chars to dictionary

            for (int i = 0; i < range.Count; i++)
            {
                char_range_from_to[range[i].Item1] = Tuple.Create(range[i].Item2, range[i].Item3);
            }
            result.Clear();
            arith_metod(0, 0, 1);



            dataGridView1.Columns.Clear();
            dataGridView1.Rows.Clear();

            dataGridView2.Columns.Clear();
            dataGridView2.Rows.Clear();



            try
            {
                dataGridView1.RowCount    = char_range_from_to.Count;
                dataGridView1.ColumnCount = 4;


                dataGridView1.Columns[0].HeaderText = "Sympole";
                dataGridView1.Columns[1].HeaderText = "From";
                dataGridView1.Columns[2].HeaderText = "To";
                dataGridView1.Columns[3].HeaderText = "Range";


                for (int i = 0; i < result.Count; i++)
                {
                    dataGridView1.Rows[i].Cells[0].Value = char_range_from_to.ElementAt(i).Key.ToString();
                    dataGridView1.Rows[i].Cells[1].Value = char_range_from_to.ElementAt(i).Value.Item1;
                    dataGridView1.Rows[i].Cells[2].Value = char_range_from_to.ElementAt(i).Value.Item2;
                    dataGridView1.Rows[i].Cells[3].Value = char_range_from_to.ElementAt(i).Value.Item2 - char_range_from_to.ElementAt(i).Value.Item1;
                }
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message.ToString());
            }



            try
            {
                dataGridView2.RowCount    = result.Count;
                dataGridView2.ColumnCount = result[0].Count;


                dataGridView2.Columns[0].HeaderText = "Sympole";
                dataGridView2.Columns[1].HeaderText = "From";
                dataGridView2.Columns[2].HeaderText = "To";
                dataGridView2.Columns[2].HeaderText = "Range";


                for (int i = 0; i < result.Count; i++)
                {
                    for (int j = 0; j < result[0].Count; j++)
                    {
                        dataGridView2.Rows[i].Cells[j].Value = result[i][j];
                    }
                }
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message.ToString());
            }
        }
Ejemplo n.º 41
0
        void DrawPlayMenuScreen(RenderTexture buffer)
        {
            spr.Texture  = levelSelectBgTexture;
            spr.Position = new Vector2f(0, 0);
            spr.Color    = new Color(255, 255, 255, 255);
            buffer.Draw(spr);

            txt.DisplayedString = "Back to main menu";

            txt.Font          = TextureMan.Font;
            txt.CharacterSize = 8;
            txt.Color         = new Color(226, 149, 37);
            txt.Position      = new Vector2f(30, 10);

            buffer.Draw(txt);

            if (Cheater)
            {
                txt.DisplayedString = "Please don't cheat :)";
                txt.Position        = new Vector2f(180, 10);

                buffer.Draw(txt);
            }

            int pos = 20;

            foreach (KeyValuePair <string, string> level in levels)
            {
                txt.DisplayedString = level.Key;
                txt.Position        = new Vector2f(30, pos);

                if (!levelCompleted[level.Value])
                {
                    txt.Color = new Color(226, 149, 37);
                }
                else
                {
                    txt.Color = new Color(255, 255, 255);
                }

                buffer.Draw(txt);

                pos += 10;
            }

            txt.Color           = new Color(226, 149, 37);
            txt.DisplayedString = ">";
            txt.Position        = new Vector2f(20, menuOption * 10 + 10);
            buffer.Draw(txt);

            if (menuOption > 0)
            {
                if (levelCompleted.ElementAt(menuOption - 1).Value == true)
                {
                    txt.Color = new Color(255, 255, 255);

                    txt.DisplayedString = "Level Completed";
                    txt.Position        = new Vector2f(190, 50);
                    buffer.Draw(txt);

                    txt.DisplayedString = "Best time: " + levelBestTime.ElementAt(menuOption - 1).Value.ToString(@"mm\:ss\.ff");
                    txt.Position        = new Vector2f(190, 60);
                    buffer.Draw(txt);
                }
            }
        }
Ejemplo n.º 42
0
        void IntegrationGUI()
        {
            EditorGUILayout.LabelField("Social Platforms:", EditorStyles.boldLabel);

            ReadSocialIntegrationState(socialIntegrationState);

            EditorGUI.BeginChangeCheck();

            Dictionary <string, bool?> .KeyCollection keys = socialIntegrationState.Keys;
            for (int i = 0; i < keys.Count; i++)
            {
                string socialPlatform      = keys.ElementAt(i);
                bool?  socialPlatformState = socialIntegrationState[socialPlatform];

                EditorGUILayout.BeginHorizontal();

                bool update       = false;
                bool doIntegrate  = false;
                bool toggleResult = false;
                if (socialPlatformState != null)
                {
                    toggleResult = EditorGUILayout.Toggle(socialPlatform, socialPlatformState.Value);
                    if (toggleResult != socialPlatformState.Value)
                    {
                        socialIntegrationState[socialPlatform] = toggleResult;
                        doIntegrate = toggleResult;
                        update      = true;
                    }
                }
                else
                {
                    doIntegrate  = IsSocialPlatformDetected(socialPlatform);
                    toggleResult = EditorGUILayout.Toggle(socialPlatform, doIntegrate);

                    // User changed automatic value
                    if (doIntegrate != toggleResult)
                    {
                        doIntegrate = toggleResult;
                        socialIntegrationState[socialPlatform] = doIntegrate;
                        update = true;
                    }
                }

                if (update)
                {
                    ApplyIntegrationState(socialPlatform, doIntegrate);
                }

                EditorGUILayout.EndHorizontal();
                DrawPlatformParams(socialPlatform, !toggleResult);
                EditorGUILayout.BeginHorizontal();

                EditorGUILayout.EndHorizontal();
            }

            EditorGUILayout.Space();

            if (EditorGUI.EndChangeCheck())
            {
                WriteSocialIntegrationState();
            }
        }
Ejemplo n.º 43
0
        //Implementación del algoritmo de minimización de autómatas de estado finito.

        public void reduceMachine()
        {
            //Partición inicial p1, se agrupan los estados por salida.
            List <List <State> > partitionk = states.Values.ToList()
                                              .GroupBy(x => ((MealyState)x).adjOuts()).Select(x => x.ToList()).ToList();
            List <List <State> > partitionk1 = new List <List <State> >();
            bool notEqual = true;

            //Mientras pk sea distinto de pk+1
            while (notEqual)
            {
                //Algoritmo de particionamiento.
                foreach (var parti in partitionk)
                {
                    MealyState   st1      = (MealyState)parti.First();
                    List <State> newparti = new List <State>();
                    foreach (MealyState st2 in parti.Skip(1))
                    {
                        bool yes = true;
                        foreach (char ch in alphaIn)
                        {
                            if (!partitionk.Any(x => x.Contains(st1.getAdj()[ch].Key) && x.Contains(st2.getAdj()[ch].Key)))
                            {
                                yes = false;
                                break;
                            }
                        }
                        if (!yes)
                        {
                            newparti.Add(st2);
                        }
                    }
                    if (newparti.Count != 0)
                    {
                        partitionk1.Add(parti.Except(newparti).ToList());
                        partitionk1.Add(newparti);
                    }
                    else
                    {
                        partitionk1.Add(parti);
                    }
                }
                notEqual    = !partitionk.SequenceEqual(partitionk1);
                partitionk  = partitionk1;
                partitionk1 = new List <List <State> >();
            }
            //Cada partición representa un estado nuevo.
            int i = 0;
            Dictionary <char, State> statesnew = new Dictionary <char, State>();

            foreach (var newst in partitionk)
            {
                char id = states.Keys.ElementAt(i);
                statesnew.Add(id, new MealyState(id));
                i++;
            }

            foreach (char c in alphaIn)
            {
                for (int h = 0; h < partitionk.Count; h++)
                {
                    var p = partitionk[h];
                    //Se encuentra en qué partición está el estado inicial y se marca como nuevo estado inicial.
                    if (p.Contains(states[state1]))
                    {
                        state1 = statesnew.ElementAt(h).Value.getId();
                    }
                    //Se encuentran los sucesores de cada estado.
                    MealyState s     = ((MealyState)p.First()).getAdj()[c].Key;
                    char       value = ((MealyState)p.First()).getAdj()[c].Value;
                    for (int l = 0; l < partitionk.Count; l++)
                    {
                        if (partitionk[l].Contains(s))
                        {
                            ((MealyState)statesnew.ElementAt(h).Value).getAdj()
                            .Add(c, new KeyValuePair <MealyState, char>((MealyState)statesnew.ElementAt(l).Value, value));
                            break;
                        }
                    }
                }
            }
            //Se actualiza el autómata.
            states = statesnew;
        }
 // Return the count of items in the specified group
 public override int GetChildrenCount(int groupPosition)
 {
     return(_resultsDictionary.ElementAt(groupPosition).Value.Count);
 }
Ejemplo n.º 45
0
        private void Main()
        {
            while (_isWatch)
            {
                SetDevList();

                try
                {
                    for (var count = 0; count < DevDict.Count; count++)
                    {
                        var element = DevDict.ElementAt(count);
                        var key     = element.Key;

                        if (TempDevDict.ContainsKey(key) == false)
                        {
                            if (element.Value != ",".Split(','))
                            {
                                //当前有脚本在执行
                                UpdateOffline(element.Value[0]);
                                //生成报告
                                DirFile.CreateFile($@"D:\developer\{_gnpy}\data\result\excel\{_ip}@{key}{element.Value[1]}测试总报告.xlsx");
                                Log.Info($@"检测到设备断开连接 {key} {element.Value[0]}已主动生成报告");
                            }
                            else
                            {
                                Log.Info($@"检测到设备断开连接 {key} 当前没有正在执行脚本");
                            }

                            DevDict.Remove(key);
                            deleteDevice(key);
                        }

                        else
                        {
                            var scriptName     = SelectScriptName(key);
                            var selectScriptCn = scriptName[0];
                            var selectScriptEn = scriptName[1];

                            if (selectScriptEn == null)
                            {
                                // 数据库中不存在未执行脚本
                                continue;
                            }

                            if (element.Value[0] == string.Empty)
                            {
                                // 当前设备空闲

                                object[] values = { "python", "controle.py", key, selectScriptEn, selectScriptCn, string.Empty };
                                SetDgvSourceFunction(values);

                                Updatemobile(key, selectScriptEn);
                                Updateflog(1, selectScriptEn);

                                DevDict[key] = $"{selectScriptEn},{selectScriptCn}".Split(',');
                                var caller = new AsyncMethodCaller(StartPython);
                                caller.BeginInvoke(key, selectScriptEn, selectScriptCn, out _, out _, CallbackMethod, null);
                                Log.Info($@"python controle.py {key} {selectScriptEn} {selectScriptCn}");
                            }
                        }
                    }

                    if (RunEnd())
                    {
                        _isWatch = false;
                        break;
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString(), @"main");
                    Log.Error("main:" + e);
                }
            }

            Log.Info(@"循环结束,关闭程序");
            Application.Exit();
        }
Ejemplo n.º 46
0
 public override int RowsInSection(UITableView tableview, int section)
 {
     return(m_userExamTableViewData.ElementAt(section).Value.Count);
 }
Ejemplo n.º 47
0
        /// <summary>
        /// Initial experience, takes in an observance and emits the new contexts related to it. Merge and Convey will merge new contexts into existing ones
        /// </summary>
        /// <param name="actor">Who did the action</param>
        /// <param name="action">The raw input that was observed</param>
        /// <returns>A list of the new contexts generated</returns>
        public IEnumerable <IDictata> Parse(IEntity actor, string action, bool push = false)
        {
            List <IDictata> returnList = new List <IDictata>();

            _currentPlace = actor.CurrentLocation.CurrentLocation();
            _actor        = actor;

            string[] spaceSplit = action.Split(new char[] { ' ', ',', ':' }, StringSplitOptions.RemoveEmptyEntries);

            Dictionary <string, IDictata> brandedWords = BrandWords(spaceSplit);

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

            if (brandedWords.Count(bWord => bWord.Value != null && bWord.Value.WordType == LexicalType.Verb) > 1)
            {
                //multiple verbs means multiple sentences
                IEnumerable <string> punctuationSentences = IsolateSentences(action);

                foreach (string sentence in punctuationSentences)
                {
                    string[] innerSplit = sentence.Split(new char[] { ' ', ',', ':' }, StringSplitOptions.RemoveEmptyEntries);

                    Dictionary <string, IDictata> innerBrands = BrandWords(innerSplit);

                    if (!innerBrands.Any(inWord => inWord.Value != null && inWord.Value.WordType == LexicalType.Conjunction))
                    {
                        sentences.Add(sentence);
                        continue;
                    }

                    bool found = false;
                    foreach ((KeyValuePair <string, IDictata> value, int i)innerVerb in innerBrands.Select((value, i) => (value, i)))
                    {
                        KeyValuePair <string, IDictata> value = innerVerb.value;
                        int index = innerVerb.i;

                        if (value.Value != null && value.Value.WordType != LexicalType.Verb)
                        {
                            continue;
                        }

                        found = true;
                        if (index > 0 && index < innerBrands.Count() - 1)
                        {
                            IDictata wordBefore = innerBrands.ElementAt(index - 1).Value;

                            if (wordBefore.WordType == LexicalType.Conjunction)
                            {
                                int splitIndex = innerBrands.Take(index - 1).Sum(brand => brand.Key.Length + 1);

                                int bumpCount = sentence.Substring(0, splitIndex - 1).Count(ch => ch == ',' || ch == ':');

                                string sentenceOne = sentence.Substring(0, splitIndex - 1 + bumpCount);
                                string sentenceTwo = sentence.Substring(splitIndex + wordBefore.Name.Length + bumpCount);

                                sentences.Add(sentenceOne);
                                sentences.Add(sentenceTwo);
                            }
                        }
                    }

                    if (!found)
                    {
                        sentences.Add(sentence);
                    }
                }
            }
            else
            {
                sentences.Add(action);
            }

            IDictata currentSubject = null;

            foreach (string sentence in sentences)
            {
                IList <Tuple <string, bool> > words = IsolateIndividuals(sentence);

                //can't parse nothing
                if (words.Count == 0)
                {
                    continue;
                }

                IEnumerable <IDictata> fullCommand = ParseAction(words, push, currentSubject);
                currentSubject = fullCommand.LastOrDefault(word => word.WordType == LexicalType.Noun || word.WordType == LexicalType.ProperNoun);

                returnList.AddRange(fullCommand);
            }

            return(returnList);
        }
Ejemplo n.º 48
0
        public static V Random <K, V>(this Dictionary <K, V> dictionary)
        {
            V value = dictionary.ElementAt(_r.Next(0, dictionary.Count)).Value;

            return(value);
        }
Ejemplo n.º 49
0
        /*
         * TODO: Wow this is inefficient, maybe clean up how many loops we do
         */
        private IEnumerable <IDictata> ParseAction(IList <Tuple <string, bool> > words, bool push, IDictata lastSubject)
        {
            /*
             * I kick the can
             * kick the can
             * kicks the can
             * kick the red can
             * kick the large red can
             */
            List <IDictata> returnList = new List <IDictata>();

            Dictionary <string, IDictata> brandedWords = BrandWords(words);

            IDictata currentVerb = null;

            //Find unknown nouns potentially with conjunctions
            foreach ((KeyValuePair <string, IDictata> value, int i)item in brandedWords.Where(ctx => ctx.Value == null).Select((value, i) => (value, i)).OrderByDescending(keypair => keypair.i))
            {
                KeyValuePair <string, IDictata> value = item.value;
                int index = item.i;

                if (index < brandedWords.Count() - 1 && index > 0)
                {
                    IDictata wordAfter  = brandedWords.ElementAt(index + 1).Value;
                    IDictata wordBefore = brandedWords.ElementAt(index - 1).Value;

                    if (wordBefore != null && wordBefore.WordType == LexicalType.Adverb && wordAfter != null && wordAfter.WordType == LexicalType.Verb)
                    {
                        brandedWords[value.Key] = new Dictata()
                        {
                            Name = value.Key, WordType = LexicalType.Adverb
                        };
                        continue;
                    }

                    if ((wordBefore != null && (wordBefore.WordType == LexicalType.Adjective) || wordBefore.WordType == LexicalType.Article) &&
                        (wordAfter != null && (wordAfter.WordType == LexicalType.Noun) || wordAfter.WordType == LexicalType.ProperNoun))
                    {
                        brandedWords[value.Key] = new Dictata()
                        {
                            Name = value.Key, WordType = LexicalType.Adjective
                        };
                        continue;
                    }

                    continue;
                }

                if (index < brandedWords.Count() - 1)
                {
                    IDictata wordAfter = brandedWords.ElementAt(index + 1).Value;

                    if (wordAfter != null && wordAfter.WordType == LexicalType.Noun)
                    {
                        brandedWords[value.Key] = new Dictata()
                        {
                            Name = value.Key, WordType = LexicalType.Adjective
                        };
                        continue;
                    }

                    if (wordAfter != null && wordAfter.WordType == LexicalType.Verb)
                    {
                        brandedWords[value.Key] = new Dictata()
                        {
                            Name = value.Key, WordType = LexicalType.Adverb
                        };
                        continue;
                    }
                }

                if (index > 0)
                {
                    IDictata wordBefore = brandedWords.ElementAt(index - 1).Value;

                    if (wordBefore != null && (wordBefore.WordType == LexicalType.Article || wordBefore.WordType == LexicalType.Adjective))
                    {
                        brandedWords[value.Key] = new Dictata()
                        {
                            Name = value.Key, WordType = LexicalType.Noun
                        };
                        continue;
                    }

                    if (wordBefore != null && wordBefore.WordType == LexicalType.Adverb)
                    {
                        brandedWords[value.Key] = new Dictata()
                        {
                            Name = value.Key, WordType = LexicalType.Verb
                        };
                        continue;
                    }
                }
            }

            //No verb?
            if (!brandedWords.Any(ctx => ctx.Value != null && ctx.Value.WordType == LexicalType.Verb))
            {
                string verbWord = brandedWords.First(ctx => ctx.Value == null).Key;

                currentVerb = new Dictata()
                {
                    Name = verbWord, WordType = LexicalType.Verb
                };
                brandedWords[verbWord] = currentVerb;
            }
            else
            {
                currentVerb = brandedWords.FirstOrDefault(ctx => ctx.Value != null && ctx.Value.WordType == LexicalType.Verb).Value;
            }

            //We might have nouns already
            if (!brandedWords.Any(ctx => ctx.Value == null || (ctx.Value != null &&
                                                               (ctx.Value.WordType == LexicalType.Noun || ctx.Value.WordType == LexicalType.ProperNoun))))
            {
                bool lastSubjectReplaced = false;
                if (lastSubject != null)
                {
                    List <string> keyList = new List <string>();
                    foreach (KeyValuePair <string, IDictata> word in brandedWords.Where(ctx => ctx.Value != null && ctx.Value.WordType == LexicalType.Pronoun))
                    {
                        keyList.Add(word.Key);
                        lastSubjectReplaced = true;
                    }

                    foreach (string key in keyList)
                    {
                        brandedWords[key] = (IDictata)lastSubject.Clone();
                    }
                }

                if (!lastSubjectReplaced)
                {
                    string targetWord = string.Empty;

                    //No valid nouns to make the target? Pick the last one
                    if (!brandedWords.Any(ctx => ctx.Value == null))
                    {
                        targetWord = brandedWords.LastOrDefault().Key;
                    }
                    else
                    {
                        targetWord = brandedWords.LastOrDefault(ctx => ctx.Value == null).Key;
                    }

                    brandedWords[targetWord] = new Dictata()
                    {
                        Name = targetWord, WordType = LexicalType.Noun
                    };
                }
            }

            List <IDictata> descriptors = new List <IDictata>();

            foreach ((KeyValuePair <string, IDictata> value, int i)item in brandedWords.Where(ctx => ctx.Value == null).Select((value, i) => (value, i)))
            {
                KeyValuePair <string, IDictata> value = item.value;
                int index = item.i;

                LexicalType wordType = LexicalType.Adjective;
                if (index == brandedWords.Count() - 1)
                {
                    IDictata wordAfter = brandedWords.ElementAt(index + 1).Value;

                    if (wordAfter != null)
                    {
                        if (wordAfter.WordType == LexicalType.Verb)
                        {
                            wordType = LexicalType.Adverb;
                        }

                        if (wordAfter.WordType == LexicalType.Pronoun)
                        {
                            wordType = LexicalType.Article;
                        }
                    }
                }

                descriptors.Add(new Dictata()
                {
                    Name = value.Key, WordType = wordType
                });
            }

            //Add the nonadjectives and the adjectives
            returnList.AddRange(brandedWords.Where(bws => bws.Value != null).Select(bws => bws.Value));
            returnList.AddRange(descriptors.Select(desc => desc));

            if (push)
            {
                foreach (IDictata item in returnList)
                {
                    LexicalProcessor.VerifyLexeme(item.GetLexeme());
                }
            }

            return(returnList);
        }
        public int GetBadge(int index)
        {
            int actualBadge = _badgeLookup.ElementAt(index).Key;

            return(actualBadge);
        }
Ejemplo n.º 51
0
        public int OrangesRotting(int[][] grid)
        {
            bool changed = false;
            Dictionary <string, bool> dict = new Dictionary <string, bool>();

            for (int i = 0; i < grid.Length; i++)
            {
                for (int j = 0; j < grid[i].Length; j++)
                {
                    if (grid[i][j] == 2)
                    {
                        if (i - 1 >= 0 && grid[i - 1][j] == 1)
                        {
                            if (!dict.ContainsKey(i - 1 + "_" + j))
                            {
                                //  grid[i - 1][j] = 2;
                                dict.Add((i - 1) + "_" + j, true);
                                changed = true;
                            }
                        }
                        if (i + 1 < grid.Length && grid[i + 1][j] == 1)
                        {
                            if (!dict.ContainsKey((i + 1) + "_" + j))
                            {
                                // grid[i + 1][j] = 2;
                                dict.Add(i + 1 + "_" + j, true);
                                changed = true;
                            }
                        }
                        if (j - 1 >= 0 && grid[i][j - 1] == 1)
                        {
                            if (!dict.ContainsKey(i + "_" + (j - 1)))
                            {
                                // grid[i][j-1] = 2;
                                dict.Add(i + "_" + (j - 1), true);
                                changed = true;
                            }
                        }
                        if (j + 1 < grid[i].Length && grid[i][j + 1] == 1)
                        {
                            if (!dict.ContainsKey(i + "_" + (j + 1)))
                            {
                                //  grid[i][j+1] = 2;
                                dict.Add(i + "_" + (j + 1), true);
                                changed = true;
                            }
                        }
                    }
                }
            }
            for (int i = 0; i < dict.Count; i++)
            {
                if (dict.ElementAt(i).Value == true)
                {
                    var row    = Convert.ToInt32(dict.ElementAt(i).Key.Split("_")[0]);
                    var column = Convert.ToInt32(dict.ElementAt(i).Key.Split("_")[1]);
                    grid[row][column] = 2;
                }
            }
            if (changed == true)
            {
                minutes++;
                OrangesRotting(grid);
            }
            else if (changed == false)
            {
                for (int i = 0; i < grid.Length; i++)
                {
                    for (int j = 0; j < grid[i].Length; j++)
                    {
                        if (grid[i][j] == 1)
                        {
                            minutes = -1;
                            //return -1;
                        }
                    }
                }
            }
            return(minutes);
        }
Ejemplo n.º 52
0
        private bool nonGrouped; //TODO: Add persistency to grouping option

        #region Standard Activity Shit
        protected override async void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.main_saved);
            CrossCurrentActivity.Current.Activity = this; //don't remove this, permission stuff needs it

            #region UI Variables
            DrawerLayout drawer    = FindViewById <DrawerLayout>(Resource.Id.drawer_layout);
            ImageButton  drawerBtn = FindViewById <ImageButton>(Resource.Id.drawerBtn);

            NavigationView navigationView = FindViewById <NavigationView>(Resource.Id.nav_view);

            ExpandableListView savedList           = FindViewById <ExpandableListView>(Resource.Id.savedList);
            ImageButton        selectGroupingBtn   = FindViewById <ImageButton>(Resource.Id.selectGroupingBtn);
            ListView           savedListNonGrouped = FindViewById <ListView>(Resource.Id.savedListNonGrouped);
            #endregion

            navigationView.NavigationItemSelected += NavigationView_NavigationViewSelected;
            drawerBtn.Click += delegate
            {
                drawer.OpenDrawer(navigationView);
            };

            selectGroupingBtn.Click += async delegate
            {
                if (!nonGrouped)
                {
                    nonGrouped                     = true;
                    savedList.Visibility           = ViewStates.Gone;
                    savedListNonGrouped.Visibility = ViewStates.Visible;
                    selectGroupingBtn.SetImageDrawable(GetDrawable(Resource.Drawable.ic_ungrouped));
                    await ShowSavedSongs();
                }
                else
                {
                    nonGrouped                     = false;
                    savedList.Visibility           = ViewStates.Visible;
                    savedListNonGrouped.Visibility = ViewStates.Gone;
                    selectGroupingBtn.SetImageDrawable(GetDrawable(Resource.Drawable.ic_grouped));
                    await ShowSavedSongs();
                }
            };

            savedList.ChildClick += async delegate(object sender, ExpandableListView.ChildClickEventArgs e)
            {
                SongBundle selection = artistSongs.ElementAt(e.GroupPosition).Value[e.ChildPosition];

                Log(Type.Action, "Clicked on item from grouped list");
                Analytics.TrackEvent("Clicked on item from non-grouped list", new Dictionary <string, string> {
                    { "SongID", selection.Normal.Id.ToString() }
                });

                await OpenInMainActivity(selection);
            };

            savedListNonGrouped.ItemClick += async delegate(object sender, AdapterView.ItemClickEventArgs e)
            {
                SongBundle selection = allSongs[e.Position];

                Log(Type.Action, "Clicked on item from non-grouped list");
                Analytics.TrackEvent("Clicked on item from non-grouped list", new Dictionary <string, string> {
                    { "SongID", selection.Normal.Id.ToString() }
                });

                await OpenInMainActivity(selection);
            };
        }
Ejemplo n.º 53
0
 internal int GetContainerTotal()
 {
     //Go through the dictionary of items and add all the values together if container is null return 0.
     return(_container?.Select((t, i) => _container?.ElementAt(i).Value).Sum() ?? 0);
 }
Ejemplo n.º 54
0
        private bool checkConditions(IList <Condition> conditions, IList <string> operators, Dictionary <string, int> columnDictionary, object[] recodValues)
        {
            //bool res = true;
            // if single condition
            if (conditions.Count == 0)
            {
                return(true);
            }
            else if (conditions.Count == 1 && operators.Count == 0 && columnDictionary.Count == 1)
            {
                var kV  = columnDictionary.ElementAt(0);
                var col = Columns[kV.Value];
                return(checkCondition(conditions[0], col.Name, col.Type, recodValues[kV.Value]));

                /*switch (col.Type)
                 * {
                 *  case 1:
                 *      {
                 *          var val = Convert.ToInt32(recodValues[kV.Value]);
                 *          res = conditions[0].Operate(col.Name, val);
                 *          return res;
                 *      }
                 *  case 2:
                 *      {
                 *          var val = Convert.ToInt32(recodValues[kV.Value]);
                 *          res = conditions[0].Operate(col.Name, val);
                 *          return res;
                 *      }
                 *  case 3:
                 *      {
                 *          var val = recodValues[kV.Value] as string;
                 *          res = conditions[0].Operate(col.Name, val);
                 *          return res;
                 *      }
                 *  case 4:
                 *      {
                 *          var val = Convert.ToDateTime(recodValues[kV.Value]);// Convert.ToInt64(recodValues[kV.Value]);
                 *          res = conditions[0].Operate(col.Name, val);
                 *          return res;
                 *      }
                 *  default:
                 *      return false;
                 * }*/
            }
            else
            {
                var conditionsResults = new List <int>();
                for (int i = 0; i < conditions.Count(); i++)
                {
                    var kV     = columnDictionary.ElementAt(i);
                    var col    = Columns[kV.Value];
                    var result = checkCondition(conditions[i], col.Name, col.Type, recodValues[kV.Value]);
                    conditionsResults.Add(result ? 1 : 0);
                }
                var sb = new StringBuilder();
                //var res = conditionsResults[0];
                sb.Append(conditionsResults[0]);
                for (int i = 0; i < operators.Count(); i++)
                {
                    if (operators[i].ToLower() == "and")
                    {
                        sb.Append("&&");
                    }
                    if (operators[i].ToLower() == "or")
                    {
                        sb.Append("||");
                    }
                    sb.Append(conditionsResults[i + 1]);
                }
                Expression e   = new Expression(sb.ToString());
                var        res = Convert.ToInt32(e.calculate());
                return(res == 1);
            }
        }
Ejemplo n.º 55
0
 public Data(Dictionary <string, List <double> > d)
 {
     ts         = d;
     numOfLines = d[ts.ElementAt(0).Key].Count;
 }
        static void Main(string[] args)
        {
            Console.WriteLine("List:");
            List <int> intlist = new List <int>();

            intlist.Add(12);
            intlist.Add(34);
            intlist.Add(56);
            Console.WriteLine("Integer list");
            foreach (int i in intlist)
            {
                Console.WriteLine(i);
            }

            List <string> strlist = new List <string>()
            {
                "It", "is", "a", "string", "list"
            };

            Console.WriteLine("String List");
            foreach (String st in strlist)
            {
                Console.WriteLine(st);
            }

            Console.WriteLine("object string");
            List <student> obj = new List <student>()
            {
                new student()
                {
                    Id = 101, name = "Karthik"
                },
                new student()
                {
                    Id = 102, name = "jessi"
                }
            };

            foreach (var item in obj)
            {
                Console.WriteLine("{0},{1}", item.Id, item.name);
            }

            Console.WriteLine();


            //Dictionary
            Console.WriteLine("Dictionary");
            Dictionary <int, string> dic = new Dictionary <int, string>();

            dic.Add(1, "first");
            dic.Add(2, "second");
            dic.Add(3, "third");


            foreach (var d in dic)
            {
                Console.WriteLine("{0},{1}", d.Key, d.Value);
            }

            Console.WriteLine("the first key value pair is {0},{1}", dic.ElementAt(0).Key, dic.ElementAt(0).Value);
            Console.WriteLine();
            IDictionary <int, student> odic = new Dictionary <int, student>()
            {
                { 1, new student()
                  {
                      Id = 301, name = "Varun"
                  } },
                { 2, new student()
                  {
                      Id = 302, name = "Nithya"
                  } }
            };

            foreach (var od in odic)
            {
                Console.WriteLine("{0},{1},{2}", od.Key, od.Value.Id, od.Value.name);
            }
            Console.WriteLine();

            //sorted list
            Console.WriteLine("Sorted List:");
            SortedList <int, string> sl = new SortedList <int, string>();

            sl.Add(1, "India");
            sl.Add(2, "America");
            sl.Add(3, "china");

            foreach (var i in sl)
            {
                Console.WriteLine("{0},{1}", i.Key, i.Value);
            }
            Console.WriteLine("the value for 1st key is {0}", sl[1]);
            Console.WriteLine();


            //stack


            Console.WriteLine("Stack:");
            Stack <string> s = new Stack <string>();

            s.Push("this is");
            s.Push("generic");
            s.Push("stack");
            s.Pop();
            foreach (String str in s)
            {
                Console.WriteLine(str + " ");
            }
            Console.WriteLine();

            //Queue
            Console.WriteLine("Queue:");
            Queue <float> fl = new Queue <float>();

            fl.Enqueue(0.3f);
            fl.Enqueue(.5f);
            fl.Enqueue(.2f);
            fl.Dequeue();
            foreach (float f in fl)
            {
                Console.WriteLine(f + " ");
            }
        }
Ejemplo n.º 57
0
        private static Node AStar(char[,] matrix, int fromX, int fromY, int toX, int toY)
        {
            Dictionary <string, Node> greens = new Dictionary <string, Node>();
            Dictionary <string, Node> reds   = new Dictionary <string, Node>();

            Node startNode = new Node {
                x = fromX, y = fromY, sum = 0
            };
            string key = startNode.x.ToString() + startNode.y.ToString();

            greens.Add(key, startNode);

            Func <KeyValuePair <string, Node> > smallestGreen = () =>
            {
                KeyValuePair <string, Node> smallest = greens.ElementAt(0);

                foreach (KeyValuePair <string, Node> item in greens)
                {
                    if (item.Value.sum < smallest.Value.sum)
                    {
                        smallest = item;
                    }
                    else if (item.Value.sum == smallest.Value.sum &&
                             item.Value.to < smallest.Value.to)
                    {
                        smallest = item;
                    }
                }

                return(smallest);
            };


            List <KeyValuePair <int, int> > fourNeighbors = new List <KeyValuePair <int, int> >()
            {
                new KeyValuePair <int, int>(-1, 0),
                new KeyValuePair <int, int>(0, 1),
                new KeyValuePair <int, int>(1, 0),
                new KeyValuePair <int, int>(0, -1)
            };

            int maxX = C;

            if (maxX == 0)
            {
                return(null);
            }
            int maxY = R;

            while (true)
            {
                if (greens.Count == 0)
                {
                    return(null);
                }

                KeyValuePair <string, Node> current = smallestGreen();
                if (current.Value.x == toX && current.Value.y == toY)
                {
                    return(current.Value);
                }

                greens.Remove(current.Key);
                reds.Add(current.Key, current.Value);

                foreach (KeyValuePair <int, int> plusXY in fourNeighbors)
                {
                    int    nbrX   = current.Value.x + plusXY.Key;
                    int    nbrY   = current.Value.y + plusXY.Value;
                    string nbrKey = nbrX.ToString() + nbrY.ToString();
                    if (nbrX < 0 || nbrY < 0 || nbrX >= maxX || nbrY >= maxY ||
                        matrix[nbrY, nbrX] == '#' ||
                        reds.ContainsKey(nbrKey))
                    {
                        continue;
                    }

                    if (greens.ContainsKey(nbrKey))
                    {
                        Node curNbr = greens[nbrKey];
                        int  from   = Math.Abs(nbrX - fromX) + Math.Abs(nbrY - fromY);
                        if (from < curNbr.fr)
                        {
                            curNbr.fr     = from;
                            curNbr.sum    = current.Value.sum + 1;
                            curNbr.parent = current.Value;
                        }
                    }
                    else
                    {
                        Node curNbr = new Node {
                            x = nbrX, y = nbrY
                        };
                        curNbr.fr     = Math.Abs(nbrX - fromX) + Math.Abs(nbrY - fromY);
                        curNbr.to     = Math.Abs(nbrX - toX) + Math.Abs(nbrY - toY);
                        curNbr.sum    = current.Value.sum + 1;
                        curNbr.parent = current.Value;
                        greens.Add(nbrKey, curNbr);
                    }
                }
            }
        }
 public override Java.Lang.Object GetChild(int groupPosition, int childPosition)
 {
     return(_menuictionary[_menuictionary.ElementAt(groupPosition).Key].ElementAt(childPosition));
 }
        /*
         * Navigate to the selected use case and initialize the appropriate viewcontroller with the appropriate settings
         */
        public override async void RowSelected(UITableView tableView, NSIndexPath indexPath)
        {
            // Because this method might be triggered asynchronously multiple times, we have to make sure
            // that we won't create multiple ViewControllers at the same time.
            if (_isNavigating)
            {
                return;
            }
            lock (_lock) _isNavigating = true;

            if (AnylineViewController.CurrentScanViewController != null)
            {
                AnylineViewController.CurrentScanViewController.Dispose();
                AnylineViewController.CurrentScanViewController = null;
            }

            var name = TableItems.ElementAt(indexPath.Section).Value.ElementAt(indexPath.Row);

            switch (indexPath.Section)
            {
            case 0:     //ENERGY
                var    scanModeItems = new Dictionary <string, ALScanMode>();
                string labelText     = "";
                int    defaultIndex  = 0;

                switch (indexPath.Row)
                {
                case 0:         //Analog Water Meter Scan
                    scanModeItems.Add("", ALScanMode.AnalogMeter);
                    break;

                case 1:         //Digital Meter Scan
                    scanModeItems.Add("", ALScanMode.DigitalMeter);
                    break;

                case 2:         //Heat Meter Scan
                    scanModeItems.Add("4 digits", ALScanMode.HeatMeter4);
                    scanModeItems.Add("5 digits", ALScanMode.HeatMeter5);
                    scanModeItems.Add("6 digits", ALScanMode.HeatMeter6);
                    break;

                case 3:         //Automatic Analog/Digital Meter Scan
                    scanModeItems.Add("", ALScanMode.AutoAnalogDigitalMeter);
                    break;

                case 4:         //Automatic Serial Number Scan
                    scanModeItems.Add("", ALScanMode.SerialNumber);
                    break;
                }
                AnylineViewController.CurrentScanViewController = new AnylineEnergyScanViewController(name, scanModeItems, labelText, defaultIndex);
                break;

            case 1:     //Identification
                //Passport / ID MRZ Scan
                AnylineViewController.CurrentScanViewController = new AnylineMrzScanViewController(name);
                break;

            case 2:     //Barcodes
                //Barcode Scan
                AnylineViewController.CurrentScanViewController = new AnylineBarcodeScanViewController(name);
                break;

            case 3:     //Fintech
                //Iban Scan
                AnylineViewController.CurrentScanViewController = new AnylineIBANScanViewController(name);
                break;

            case 4:     //Document
                //Document Scan
                AnylineViewController.CurrentScanViewController = new AnylineDocumentScanViewController(name);
                break;

            case 5:                     //Loyalty
                if (indexPath.Row == 0) //Voucher Code Scan
                {
                    AnylineViewController.CurrentScanViewController = new AnylineVoucherScanViewController(name);
                }
                if (indexPath.Row == 1)     //Bottlecap Code Scan
                {
                    AnylineViewController.CurrentScanViewController = new AnylineBottlecapScanViewController(name);
                }
                break;

            case 6:     //License Plate
                AnylineViewController.CurrentScanViewController = new AnylineLicensePlateScanViewController(name);
                break;

            default:
                break;
            }

            // navigate to the newly created scan view controller
            if (AnylineViewController.CurrentScanViewController != null)
            {
                AnylineViewController.NavigationController.PushViewController(AnylineViewController.CurrentScanViewController, true);
            }

            // workaround so the row selection is not creating a scanViewController twice
            await Task.Delay(200);

            tableView.DeselectRow(indexPath, true);
            lock (_lock) _isNavigating = false;
        }
Ejemplo n.º 60
0
 public void Remove(Int32 index)
 {
     this.Remove(_tables.ElementAt(index).Key);
 }