public bool IsFourOfAKind(IHand hand)
        {
            if (!this.IsValidHand(hand))
            {
                return false;
            }

            Dictionary<CardFace, int> faces = new Dictionary<CardFace, int>();
            for (var i = 0; i < NumberOfCardsInHand; i++)
            {
                if (!faces.ContainsKey(hand.Cards[i].Face))
                {
                    faces.Add(hand.Cards[i].Face, 1);
                }
                else
                {
                    faces[hand.Cards[i].Face] = faces[hand.Cards[i].Face] + 1;
                }
            }

            if (faces.Count == 2 && faces.ContainsValue(4) && faces.ContainsValue(1) && faces.Count == 2)

            {
                return true;
            }
            else
            {
                return false;
            }
        }
Exemplo n.º 2
0
        public collections_example()
        {
            //rule of thumb: generics exist and are a wonderful thing.

            //Lists
            List<string> sList = new List<string>();
            var namesList = new List<string>();//this is implying that var is a List<string>. It shortens variable declarations. This cannot be used as a return type. Variables only.

            sList.Add("James");//this is rather time consuming and not helpful. You are usually adding this from a db or data file.

            //you can add arrays to collections.
            string[] names = new string[]{
                "James",
                "John",
                "Jennifer",
                "Jackie",
                "Jake",
                "Jeremy"
            };
            namesList.AddRange(names);//this adds all the names in an array

            Console.WriteLine("The number of items in namesList is "+namesList.Count); //checks how many values are in the collection.

            bool james = namesList.Contains("James");//would return true.
            bool katie = namesList.Contains("Katie");// returns false

            Console.WriteLine("Does it contain James? {0}\nDoes it contain Katie? {1}\n", james, katie);

            var newList = namesList.FindAll((s) => s[1] == 'a');//lamba expressions, quickest way to write a predicate. More on this in future lessons.
            //copies the name whose second letter contains an a
            Console.WriteLine(newList.ToArray());//prints the name of the array, not the names IN the array.

            foreach (var name in newList)
            {
                Console.WriteLine(name);
            }

            //there's all sorts of stuff you can do to these. Remove, add, skip, sort, foreach, and far more. Use them on an as-needed basis.

            namesList.Clear();//clears everything so it is back at 0. Good for "cleaning the slate". YOU CANNOT GET THEM BACK!

            //Dictionaries
            Dictionary<int, string> dict = new Dictionary<int, string>();//could use var as well.
            dict.Add(0, "Jeremy");//keys must be unique. Int is the key.
            dict.Add(1, "Jake");// this changes the key value.
            dict.Add(2, "Hanna");

            string value = dict[0];//Jeremy
            Console.WriteLine("The value of value is: " + value);

            dict.ContainsValue("0");//returns true
            dict.ContainsValue("9");//returns false

            dict.Remove(1);//usually use a foreach loop to remove all values.

            foreach (var key in dict)
            {
                Console.WriteLine(key.Key + " = " + key.Value);
            }
        }
Exemplo n.º 3
0
        public override HandRanking Catagorize(Hand hand)
        {
            Dictionary<Value, int> seen = new Dictionary<Value, int>();

            foreach (Card c in hand.Cards)
            {
                if (seen.ContainsKey(c.Value))
                {
                    seen[c.Value]++;
                }
                else
                {
                    seen[c.Value] = 1;
                }
            }

            if (seen.Count == 2)
            {
                if(seen.ContainsValue(3) && seen.ContainsValue(2))
                {
                    return HandRanking.FullHouse;
                }
            }

            return Next.Catagorize(hand);
        }
Exemplo n.º 4
0
        public void TheIdMapWillContainAMapOfAllChildren()
        {
            TestHierarchy h = new TestHierarchy();
            Dictionary<int, UnityObject> ids = new Dictionary<int, UnityObject>();

            h.root.SetNewId(ids);
            Assert.That(ids.ContainsValue(h.root), Is.True);
            Assert.That(ids.ContainsValue(h.child), Is.True);
            Assert.That(ids.ContainsValue(h.childOfChild), Is.True);
        }
Exemplo n.º 5
0
        public void TheIdMapWillContainTheObjectAndItsOriginalId()
        {
            Dictionary<int, UnityObject> ids = new Dictionary<int, UnityObject>();
            GameObject go = new GameObject();

            go.SetNewId(ids);

            Assert.That(ids.Count, Is.EqualTo(2));
            Assert.That(ids.ContainsValue(go), Is.True);
            Assert.That(ids.ContainsValue(go.transform), Is.True);
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            //Get the string from the application config
            var initialWord = ConfigurationManager.AppSettings["initialString"];

            initialWord = initialWord.ToLower();
            var initialWordFrequence=Class1.getFrequenceVector(initialWord);

            //The words from the file are kept in a dictionary, together with their frequence vector
            var wordsFromFileDict = new Dictionary<string, Dictionary<char, int>>();

            //The result strings are kept in a dictionary
            var resultDict = new Dictionary<string, string>();

            var reader = new StreamReader("wordList.txt");
            var line = "";
            while (line != null)
            {
                line = reader.ReadLine();

                if (line == null)
                    break;
                line = line.ToLower();
                if(!wordsFromFileDict.ContainsKey(line))
                    wordsFromFileDict.Add(line, Class1.getFrequenceVector(line));
            }

            foreach (var x in wordsFromFileDict)
            {

                //Console.WriteLine(x.ToLower());
                foreach (var y in wordsFromFileDict)
                {
                    initialWordFrequence = Class1.getFrequenceVector(initialWord);
                    if (Class1.canBeAnagrams(x.Value, y.Value, initialWordFrequence))

                        if (Class1.areAnagrams(x.Value, y.Value, initialWordFrequence))
                            //Doesn't add duplicates in the result
                            if(!(resultDict.ContainsKey(x.Key) && resultDict.ContainsValue(y.Key))
                                && !(resultDict.ContainsKey(y.Key) && resultDict.ContainsValue(x.Key) ))
                                    resultDict.Add(x.Key, y.Key);
                }
            }

            //Print the results
            foreach (var item in resultDict)
            {
                Console.WriteLine(String.Format("Anagrams of {0} : {1} - {2}", initialWord, item.Key, item.Value));
            }

            Console.ReadLine();
        }
Exemplo n.º 7
0
 public void agregarUsuariosMismoNombreDiccionario()
 {
     Dictionary<int,UsuarioView> usuarios = new Dictionary<int, UsuarioView>();
     UsuarioView a = new UsuarioView(1, "a", "b", "c");
     UsuarioView c = new UsuarioView(2, "a", "b", "c");
     usuarios.Add(int.Parse(a.id), a);
     usuarios.Add(int.Parse(c.id), c);
     bool expected = true;
     bool expected1 = usuarios.ContainsValue(a);
     bool expected2 = usuarios.ContainsValue(c);
     Assert.AreEqual(expected1,expected);
     Assert.AreEqual(expected2, expected);
 }
Exemplo n.º 8
0
        public static async Task<string> GetDataV2(RequestMethod method, string command, Dictionary<string, string> reqParams)
        {
            string json;

            if (reqParams != null && (reqParams.ContainsValue("True") || reqParams.ContainsValue("False")))
            {
                json = JsonConvert.SerializeObject(BoolDictionary(reqParams), Formatting.None);
            }
            else
            {
                json = JsonConvert.SerializeObject(reqParams, Formatting.None);
            }
            return await GetDataV2WithJson(method, command, json);
        }
        private bool IsIsomorphic(string s, string t)
        {
            if (string.IsNullOrEmpty(s) && string.IsNullOrEmpty(t)) return true;

            int slength = s.Length;
            int tlength = t.Length;
            if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(t) || slength != tlength) return false;

            Dictionary<char, char> dic = new Dictionary<char, char>();
            for (int index = 0; index < slength; index++)
            {
                if (dic.ContainsKey(s[index]))
                {
                    if (dic[s[index]] != t[index])
                    {
                        return false;
                    }
                }
                else
                {
                    if (dic.ContainsValue(t[index]))
                    {
                        return false;
                    }
                    else
                    {
                        dic.Add(s[index], t[index]);
                    }
                }
            }
            return true;
        }
Exemplo n.º 10
0
        /// <summary>
        /// Publish Reusable Workflow
        /// </summary>
        /// <param name="mapping"></param>
        public void PublishReusableWorkflow(NWFMappingEntry mapping)
        {
            SPContentType ct = web.ContentTypes[mapping.BindingName];
            string workflowName = mapping.WorkflowName;
            string pathToNWF = Path.Combine(properties.Definition.RootDirectory, mapping.WorkflowFileName);
            byte[] workflowData = File.ReadAllBytes(pathToNWF);
            string workflowFile = Utility.ConvertByteArrayToString(workflowData);

            while ((int)workflowFile[0] != (int)char.ConvertFromUtf32(60)[0])
                workflowFile = workflowFile.Remove(0, 1);

            ExportedWorkflowWithListMetdata workflowWithListMetdata = ExportedWorkflowWithListMetdata.Deserialize(workflowFile);
            string xmlMessage = workflowWithListMetdata.ExportedWorkflowSeralized;
            SPListCollection lists = web.Lists;
            Dictionary<string, Guid> dictionary = new Dictionary<string, Guid>(lists.Count);
            foreach (SPList spList in lists)
            {
                if (!dictionary.ContainsKey(spList.Title.ToUpper()))
                    dictionary.Add(spList.Title.ToUpper(), spList.ID);
            }
            foreach (var listReference in workflowWithListMetdata.ListReferences)
            {
                string key = listReference.ListName.ToUpper();
                if (dictionary.ContainsKey(key) && !dictionary.ContainsValue(listReference.ListId))
                    xmlMessage = xmlMessage.Replace(Utility.FormatGuid(listReference.ListId), Utility.FormatGuid(dictionary[key]));
            }
            var exportedWorkflow = WorkflowPart.Deserialize<ExportedWorkflow>(xmlMessage);
            foreach (var config in exportedWorkflow.Configurations.ActionConfigs)
                WorkflowRenderer.ProcessActionConfig(config);

            Guid listId = Guid.Empty;
            bool validateWorkflow = true;
            Publish publish = new Publish(web);
            publish.PublishAWorkflow(workflowName, exportedWorkflow.Configurations, listId, web, (ImportContext)null, validateWorkflow, ct.Id, string.Empty);
        }
Exemplo n.º 11
0
 public Dictionary<string, Dictionary<string, string>> getBill()
 {
     String html = NetUtils.getHtml(HOME_URL);
     html = NetUtils.formateHtml(html);
     if (html == null) {
         return null;
     }
     String pattern = null;
     MatchCollection matches = null;
     Dictionary<string, Dictionary<string, string>> bill;
     bill = new Dictionary<String, Dictionary<String, String>>();
     foreach (String week in allWeek) {
         Dictionary<String, String> playbill = new Dictionary<String, String>();
         pattern = TextUtils.weekToEng(week) + @"array\.push[\s\S]*?,'([\s\S]*?)','([\s\S]*?)'";
         matches = Regex.Matches(html, pattern, RegexOptions.Compiled);
         foreach (Match m in matches) {
             if (playbill.ContainsValue(m.Groups[2].ToString())) {
                 continue;
             }
             playbill.Add(NetUtils.stripHtml(m.Groups[1].ToString()), m.Groups[2].ToString());
         }
         bill.Add(week, playbill);
     }
     return bill;
 }
        private static string UniqueNumber(int[] arr)
        {
            string result = string.Empty;

            if (arr != null && arr.Length > 0 && arr.Length % 2 != 0)
            {
                Dictionary<int, int> count = new Dictionary<int, int>();

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

                if (count.ContainsValue(1))
                {
                    foreach (var item in count)
                    {
                        if (item.Value == 1)
                        {
                            result = item.Key.ToString();
                            break;
                        }
                    }
                }
            }

            return result;
        }
Exemplo n.º 13
0
    public WindowsPaths()
    {
      _paths = new Dictionary<string, string>();
      //_paths.Add("%ProgramFiles", Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles));

      foreach (string options in Enum.GetNames(typeof (Environment.SpecialFolder)))
      {
        if (!string.IsNullOrEmpty(Environment.GetFolderPath(
          (Environment.SpecialFolder)Enum.Parse(typeof (Environment.SpecialFolder), options))))
          _paths.Add(string.Format("%{0}%", options),
                     Environment.GetFolderPath(
                       (Environment.SpecialFolder)Enum.Parse(typeof (Environment.SpecialFolder), options)));
      }
      string fontsDir = Environment.GetEnvironmentVariable("windir");

      if (fontsDir == null)
      {
        fontsDir = "C:\\WINDOWS\\Fonts";
      }
      else
      {
        fontsDir = Path.Combine(fontsDir, "Fonts");
      }

      if (!_paths.ContainsValue(fontsDir))
      {
        _paths.Add("%Fonts%", fontsDir);
      }
      _paths.Add("%Temp%", Path.GetTempPath());
    }
        public bool IsValid(string s)
        {
            var map = new Dictionary<char, char>
            {
                {'(', ')'},
                {'{', '}'},
                {'[', ']'}
            };

            var bracketStack = new Stack<char>();

            for (var idx = 0; idx < s.Length; ++idx)
            {
                if (map.ContainsKey(s[idx]))
                {
                    bracketStack.Push(map[s[idx]]);
                    continue;
                }
                if (map.ContainsValue(s[idx]))
                {
                    if (bracketStack.Count == 0) return false;
                    var expectedClosingBracket = bracketStack.Pop();
                    if (s[idx] == expectedClosingBracket) continue;
                    return false;
                }
            }

            return (bracketStack.Count == 0);
        }
Exemplo n.º 15
0
        public bool MakeGETDownloadRequestToAws(bool useSSL, string bucketName, string keyName, string queryString)
        {
            var result = false;
            var mySettings = new Properties.Settings();

            //create an instance of the REST class
            var myDownload = new SprightlySoftAWS.S3.Download();

            // build the URL to call. The bucket name and key name must be empty to return all buckets
            RequestURL = myDownload.BuildS3RequestURL(useSSL, "s3.amazonaws.com", bucketName, keyName, queryString);

            RequestMethod = "GET";

            ExtraRequestHeaders = new Dictionary<String, String> {
                {
                    "x-amz-date", DateTime.UtcNow.ToString("r")
                }};
            //add a date header

            //generate the authorization header value
            var authorizationValue = myDownload.GetS3AuthorizationValue(RequestURL, RequestMethod, ExtraRequestHeaders, "AKIAJCHWEMYQ5UXHOWSQ", "GLQ3fzqhpJmEvRf3J6SWquH1KbQdVEI+3tqqWGiy");
            //add the authorization header
            if (!ExtraRequestHeaders.ContainsValue(authorizationValue))
            {
                ExtraRequestHeaders.Add("Authorization", authorizationValue);
            }

            //call Download file to submit the download request
            result = myDownload.DownloadFile(RequestURL, RequestMethod, ExtraRequestHeaders, DownloadFileName, true);

            return result;
        }
Exemplo n.º 16
0
        public void DiceRollsShouldBeSeeminglyRandom()
        {
            var countOfPossibleRolls = new Dictionary<Int32, Int32>
                                           {
                                               { 2, 0 },
                                               { 3, 0 },
                                               { 4, 0 },
                                               { 5, 0 },
                                               { 6, 0 },
                                               { 7, 0 },
                                               { 8, 0 },
                                               { 9, 0 },
                                               { 10, 0 },
                                               { 11, 0 },
                                               { 12, 0 }
                                           };

            for (var i = 0; i < 150; i++)
            {
                dice.Roll();
                var totalRoll = dice.Value;
                countOfPossibleRolls[totalRoll]++;
            }

            Assert.That(!countOfPossibleRolls.ContainsValue(0));
        }
Exemplo n.º 17
0
        static void Main(string[] args)
        {
            Dictionary<int, Figure> figures = new Dictionary<int, Figure>();

            Circle cir1 = new Circle(3, Color.Orange);
            Rectangle rect1 = new Rectangle(2, 5, Color.Blue);
            Triangle tri1 = new Triangle(3, 7, 8, Color.Green);

            try
            {
                figures.Add(1, cir1);
                figures.Add(2, rect1);
                figures.Add(1, tri1);
            }
            catch (ArgumentException ex)
            {
                figures.Add(3, tri1);
                Console.WriteLine(ex.ToString() + "\n");
            }

            foreach (KeyValuePair<int, Figure> kvp in figures)
            {
                Console.WriteLine(kvp.Value + "\n");
            }

            Rectangle rect2 = rect1; // reference
            rect2.Color = Color.Black;

            Console.WriteLine(rect1);
            Console.WriteLine(figures.ContainsValue(rect2));
        }
        /// <summary>
        /// Filters the promotions.
        /// </summary>
        /// <param name="evaluationContext">The evaluation context.</param>
        /// <param name="records">The records, must be sorted in the order they are applied.</param>
        /// <returns></returns>
		public PromotionRecord[] FilterPromotions(IPromotionEvaluationContext evaluationContext, PromotionRecord[] records)
		{
            var appliedRecords = new List<PromotionRecord>();

            var groups = new Dictionary<string, string>();

            foreach (var record in records)
            {
                if (!groups.ContainsKey(record.PromotionType)) // we already have exclusive withing a current group, so ignore
                {
                    if (record.Reward.Promotion.ExclusionTypeId == (int)ExclusivityType.Group)
                    {
                        groups.Add(record.PromotionType, record.Reward.Promotion.PromotionId);
                    }

                    appliedRecords.Add(record);
                }
                else // remove the rest of promotion records unless it was generated by the applied group promotion
                {
                    if (groups.ContainsValue(record.Reward.Promotion.PromotionId))
                        appliedRecords.Add(record);
                }
            }

            return appliedRecords.ToArray();
		}
Exemplo n.º 19
0
        public static void Main(string[] args)
        {
            /* List Operations */

            List<int> list = new List<int>();

            list.Add (10);

            list.AddRange (new List<int> () { 20, 30, 40 });

            list.Remove (10);

            list.Insert (0, 10);

            list.Clear ();

            /* Dictionary Operations */

            Dictionary<int, string> dictionary = new Dictionary<int, string> ();

            dictionary.Add (1, "Sanjana");
            dictionary.Add (2, "Sumana");

            dictionary.ContainsValue ("Sanjana");
            dictionary.Remove (1);

            dictionary.Add (3, "Srinivas");

            dictionary.Clear ();
        }
Exemplo n.º 20
0
        static void Main(string[] args)
        {
            // Task: to convert the Dictionary collection "elements"
            //to List with keeping hierarchy of elements
            Dictionary<string, string> elements = new Dictionary<string, string>()
            {
                {"Tissue", "Organ"},
                {"Cell", "Cells"},
                {"System", "Body"},
                {"Cells", "Tissue"},
                {"Organ", "System"},
            };

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

            string first = elements.Keys.First(el => !elements.ContainsValue(el));
            hierarchy.Add(first);

            while (elements.ContainsKey(hierarchy.Last()))
                hierarchy.Add(elements[hierarchy.Last()]);

            foreach (var item in hierarchy)
                Console.WriteLine(item);

            Console.ReadKey();
        }
Exemplo n.º 21
0
        public static void Initialize()
        {
            int messagesCount = 0;

            InfoEvents = new Dictionary<string, uint>();

            foreach (var Packet in typeof(RevcHeaders).GetFields())
            {
                var PacketId = (uint)Packet.GetValue(0);
                var PacketName = Packet.Name;

                if (!InfoEvents.ContainsValue(PacketId))
                {
                    InfoEvents.Add(PacketName, PacketId);
                }
            }

            foreach (Type t in Assembly.GetCallingAssembly().GetTypes())
            {
                if (t.GetInterface("IPacketEvent") != null)
                {
                    var message = Activator.CreateInstance(t) as IPacketEvent;

                    if (message != null) Messages.Add(message.EventId, message);

                    messagesCount++;
                }
            }

            Application.Logging.WriteLine(string.Format("RevEmu invoked: {0} Events.", messagesCount));
        }
Exemplo n.º 22
0
    public bool PosTest2()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method ContainsValue(TValue) when the dictionary contains specified value .");

        try
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            dictionary.Add("txt", "notepad.exe");

            bool actual = dictionary.ContainsValue("notepad.exe");
            bool expected = true;
            if (actual != expected)
            {
                TestLibrary.TestFramework.LogError("001.1", "Method ContainsValue(TValue) Err.");
                TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
Exemplo n.º 23
0
        public static void Main(string[] args)
        {
            /* List Operations */

            List<int> list = new List<int>();

            list.Add (1);
            list.Add (2);
            list.Add (3);

            list.Remove (1);

            list.Insert (0, 20);

            Console.WriteLine ("before clearing the list {0}",list.Count);
            list.Clear ();

            Console.WriteLine ("afetr clearing the list {0}",list.Count);

            /* Dictionary Operations */

            Dictionary<int, string> dictionary = new Dictionary<int, string> ();

            dictionary.Add (1, "xxx");
            dictionary.Add (2, "yyy");

            dictionary.ContainsValue ("yyy");
            dictionary.Remove (2);

            dictionary.Add (3, "zzz");
            Console.WriteLine ("before clearing the dictionary {0}",dictionary.Count);
            dictionary.Clear ();
            Console.WriteLine ("after clearing the dictionary {0}",dictionary.Count);
        }
        protected void Filterlist_SelectedIndexChanged(object sender, EventArgs e)
        {
            Dictionary<string, bool> paramPreview = new Dictionary<string, bool>();

            for (int i = 0; i < filterlist.Items.Count; i++)
            {
                if (filterlist.Items[i].Selected == true)
                {
                    paramPreview.Add(filterlist.Items[i].Value, true);
                }
            }
            //Keys key = Search.GetID(FederationForms);
            Session["ParamPreview"] = paramPreview;
            if (paramPreview.ContainsValue(true))
            {
                List<Guid> list = Search.GetPropertyIDsSearch(paramPreview, FederationForms);
                lstPropertyView.DataSource = Search.GetPropertyTable(FederationForms, list);
                lstPropertyView.DataBind();

            }
            else
            {
                ListDataBind();

            }
        }
Exemplo n.º 25
0
        public void RemoveAll_MultipleCollection()
        {
            var collection = new Dictionary<int, int> { { 1, 1 }, { 2, 2 }, { 3, 3 }, { 4, 2 }, { 5, 3 } };
            collection.RemoveAll (kvp => kvp.Value == 2);

            Assert.AreEqual (3, collection.Count);
            Assert.IsFalse (collection.ContainsValue (2), "Collection still contains removed items");
        }
Exemplo n.º 26
0
 public void AddItemPriceTest_addItem_itemAddedToDictionary() {
     PricingModel pricingModel = new PricingModel(new string[0]);
     Dictionary<Item, double> existingDictionary = new Dictionary<Item, double>();            
     pricingModel.AddItemPrice(existingDictionary, "Apple,2.50");
     Assert.AreEqual(1, existingDictionary.Count);
     Assert.IsTrue(existingDictionary.ContainsKey(new Item("Apple")));
     Assert.IsTrue(existingDictionary.ContainsValue(2.50));
 }
Exemplo n.º 27
0
        static void Main(string[] args)
        {
            Dictionary<string, string> languagesDictionary = new Dictionary<string, string>();
            languagesDictionary.Add("C#", "The best programming language in the world.");

            Console.WriteLine("This is a dictionary of computer programming languages.  To search for a language by it's name press N or to search by description enter D");
            Console.WriteLine("Alternatively you can enter C to find out how many languages are held in the dictionary or X to quit.");

            char userInput = Convert.ToChar(Console.ReadLine().ToLower());

            do
            {
                switch (userInput)
                {

                    case 'n':
                        Console.WriteLine("Please enter the name of the language you are searching for.");
                        string searchName = Console.ReadLine();
                        if (languagesDictionary.ContainsKey(searchName) == true)
                        {
                            Console.WriteLine(searchName + " is in the dictionary.");
                        }
                        else
                        {
                            Console.WriteLine(searchName + " could not be found.");
                        }
                        break;

                    case 'd':
                        Console.WriteLine("Please enter a description of the language you are searching for.");
                        string searchDescription = Console.ReadLine();
                        if (languagesDictionary.ContainsValue(searchDescription) == true)
                        {
                            Console.WriteLine(searchDescription + " is in the dictionary.");
                        }
                        else
                        {
                            Console.WriteLine(searchDescription + " could not be found.");
                        }
                        break;

                    case 'c':
                        int dictionarySize = languagesDictionary.Count();
                        Console.WriteLine("There are " + dictionarySize + " languages in the dictionary");
                        break;

                    default:
                        break;

                }
                Console.WriteLine("To search for a language by it's name press N or to search by description enter D.  Alternatively you can enter C to find out how many languages are held in the dictionary or X to quit.");
                userInput = Convert.ToChar(Console.ReadLine().ToLower());

            } while (userInput != 'x');

                Console.WriteLine("Your session has now ended.");
        }
Exemplo n.º 28
0
 // This subs in the name used in the SELECT if it's a fuzzy matched column.
 // TODO: Seems like this might belong on the TableContext?
 // TODO: Looking it up with every row is pretty danged inefficient.
 // Flipping the key/value here b/c the fuzzy name is unique, not the strict name,
 // now that we're supporting the same column multiple times with different [fuzzy, for now]
 // names.
 // TODO: Allow column name aliases.
 public static string GetFuzzyNameIfExists(string strStrictColName, Dictionary<string, string> dictNameMapping)
 {
     string strReturn = strStrictColName;
     if (dictNameMapping.ContainsValue(strStrictColName))
     {
         strReturn = dictNameMapping.XGetFirstKeyByValue<string>(strStrictColName);
     }
     return strReturn;
 }
Exemplo n.º 29
0
        internal MarketLog parseMarketLog(FileInfo fi, ref Dictionary<int, string> dRegionNames)
        {
            String sFileName = fi.Name.Substring(0, fi.Name.LastIndexOf('.')).ToString();
            string sDateCreated = string.Empty;
            string sItem = string.Empty;
            string sRegion = string.Empty;
            int iLastHyphen = sFileName.LastIndexOf('-');
            int iFirstHyphen = sFileName.IndexOf('-');

            if (iLastHyphen != -1 && iFirstHyphen != -1 && !(iLastHyphen == iFirstHyphen))
            {
                sDateCreated = sFileName.Substring(iLastHyphen + 1, sFileName.Length - iLastHyphen - 1).Trim();
                sItem = sFileName.Substring(iFirstHyphen + 1, iLastHyphen - iFirstHyphen - 1).Trim();
                sRegion = sFileName.Substring(0, iFirstHyphen).Trim();

                // Check for regions with hyphens
                if (!dRegionNames.ContainsValue(sRegion))
                {
                    string[] saFileNameParts = sFileName.Split('-');
                    sRegion = string.Format("{0}-{1}", saFileNameParts);
                    // If error give light error message and return null, but continue parsing.
                    if (!dRegionNames.ContainsValue(sRegion)) //throw new Exception("Error parsing file: " + sFileName);
                    {
                        MarketScanner.Main.LightErrorMessage += string.Format("Error parsing file:{1}{0}", Environment.NewLine, fi.Name);
                        return null;
                    }
                    // Fix the item
                    sItem = sItem.Substring(sItem.IndexOf('-') + 1).Trim();
                }

                MarketLog oMarketLog = new MarketLog();
                oMarketLog.Created = parseTimestamp(sDateCreated);
                oMarketLog.Item = sItem;
                oMarketLog.Region = sRegion;
                oMarketLog.FileName = fi.Name;
                oMarketLog.FilePath = fi.FullName;

                return oMarketLog;
            }
            else
            {
                return null;
            }
        }
Exemplo n.º 30
0
        public void AmbiguousCiteTemplateDates2()
        {
            Dictionary<int, int> ambigDates = new Dictionary<int, int>();

            ambigDates = Parsers.AmbigCiteTemplateDates(@"now {{cite web | url=http://site.it | title=a |date=7-6-2005 }}");

            Assert.AreEqual(ambigDates.Count, 1);
            Assert.IsTrue(ambigDates.ContainsKey(52));
            Assert.IsTrue(ambigDates.ContainsValue(8));
        }
Exemplo n.º 31
0
 /// <summary>
 /// Returns true if the specified vehicle is currently being rented out
 /// </summary>
 public bool IsRented(string registration) => _rentals.ContainsValue(registration);
Exemplo n.º 32
0
 public bool ContainsEntity(GameEntity ge)
 {
     return(lookup.ContainsValue(ge));
 }
Exemplo n.º 33
0
 public static Keys KeyFromControl(ControlActions controlActions)
 {
     return(KeyToControl.ContainsValue(controlActions)
         ? KeyToControl.First(kv => kv.Value == controlActions).Key
         : Keys.None);
 }
Exemplo n.º 34
0
 public static bool ContainsLanguage(string language)
 {
     return(!string.IsNullOrEmpty(language) && RFC5646_TAGS.ContainsValue(language));
 }
Exemplo n.º 35
0
 public bool ContainsValue(object val)
 {
     return(resources.ContainsValue(val));
 }
Exemplo n.º 36
0
 public static bool IsAcceptedImage(string mime)
 {
     return(AcceptedImagesMIMETypesDictionary.ContainsValue(mime));
 }
Exemplo n.º 37
0
 public static void GetLetter(List <double> list)
 {
     var t = DesiresDictionary.ContainsValue(list);
 }
Exemplo n.º 38
0
        public static TagCompound GetCompressedTileData(Tile[,] tile) //Not compressed very well but ehhhh
        {
            TileData currentTile = TileData.NULLDATA;

            (int, int)currentCounter = (-1, 0);
            Dictionary <TileData, int> dictionary = new Dictionary <TileData, int>();
            List <(int, int)>          tileList   = new List <(int, int)>(); //First ushort is the dictionary id, second int is the quantity

            //ModContent.GetInstance<StarSailorMod>().Logger.Info(dimension + " peep ");

            for (int j = 0; j < tile.GetLength(1); j++)
            {
                for (int i = 0; i < tile.GetLength(0); i++)
                {
                    Tile t = tile[i, j];
                    if (t == null)
                    {
                        currentTile = TileData.NULLDATA;
                        if (dictionary.ContainsValue(-1))
                        {
                            if (currentCounter.Item1 == -1)
                            {
                                currentCounter.Item2 += 1;
                            }
                            else
                            {
                                if (currentCounter.Item2 >= 1)
                                {
                                    tileList.Add(currentCounter);
                                }
                                currentCounter = (-1, 1);
                            }
                        }
                        else
                        {
                            dictionary.Add(TileData.NULLDATA, -1);
                            if (currentCounter.Item2 >= 1)
                            {
                                tileList.Add(currentCounter);
                            }
                            currentCounter = (-1, 1);
                        }
                    }
                    else
                    {
                        TileData td = new TileData(t.type, t.wall, t.active(), t.liquid, t.liquidType(), t.slope(), t.frameX, t.frameY);
                        if (td == currentTile)
                        {
                            currentCounter.Item2 += 1;
                        }
                        else if (currentCounter.Item2 >= 1)
                        {
                            tileList.Add(currentCounter);
                            currentTile = td;
                            int val;
                            if (dictionary.TryGetValue(td, out val))
                            {
                                currentCounter = (val, 1);
                            }
                            else
                            {
                                int newID;
                                if (td != TileData.NULLDATA)
                                {
                                    newID = dictionary.Count;
                                }
                                else
                                {
                                    newID = -1;
                                }

                                dictionary.Add(td, newID);
                                currentCounter = (newID, 1);
                            }
                        }
                    }
                }
            }
            if (currentCounter.Item2 >= 1)
            {
                tileList.Add(currentCounter);
            }

            List <Vector2> pos  = new List <Vector2>();
            List <int>     data = new List <int>();

            for (int i = 0; i < tile.GetLength(0); i++)
            {
                for (int j = 0; j < tile.GetLength(1); j++)
                {
                    Tile t = tile[i, j];
                    if (t != null)
                    {
                        int num = 0;
                        num += t.actuator() ? 1 : 0;
                        num += t.wire() ? 2 : 0;
                        num += t.wire2() ? 4 : 0;
                        num += t.wire3() ? 8 : 0;
                        num += t.wire4() ? 16 : 0;
                        if (num != 0)
                        {
                            pos.Add(new Vector2(i, j));
                            data.Add(num);
                        }
                    }
                }
            }
            List <int>         counterIDs    = new List <int>();
            List <int>         counterCounts = new List <int>();
            List <int>         tileIDs       = new List <int>();
            List <TagCompound> tileData      = new List <TagCompound>();

            foreach ((int, int)k in tileList)
            {
                counterIDs.Add(k.Item1);
                counterCounts.Add(k.Item2);
            }
            foreach (KeyValuePair <TileData, int> k in dictionary)
            {
                tileIDs.Add(k.Value);
                tileData.Add(k.Key.ToTagCompound());
            }
            return(new TagCompound
            {
                ["tileIDs"] = tileIDs,
                ["tileData"] = tileData,
                ["counterIDs"] = counterIDs,
                ["counterCounts"] = counterCounts,
                ["extraLocations"] = pos,
                ["extraData"] = data,
            });
            //return new BasicTileData(dictionary, tileList);
        }
Exemplo n.º 39
0
        static void Main(string[] args)
        {
            var person = new Dictionary <string, int>();

            Console.Write("Broy elementi:");
            int brEl = int.Parse(Console.ReadLine());

            for (int i = 0; i < brEl; i++)
            {
                Console.Write("Name: ");
                string name = Console.ReadLine();
                Console.Write("Age: ");
                int age = int.Parse(Console.ReadLine());
                person.Add(name, age);
            }


            foreach (var item in person)
            {
                Console.WriteLine($"Name: {item.Key} => {item.Value} years");
            }


            //Промяна на стойност по ключ
            person["a"] = 2;

            //Добавяне на нов елемент
            person["Name"] = 10;
            person.Add("NAME_1", 100);

            Console.WriteLine();
            foreach (KeyValuePair <string, int> item in person)
            {
                Console.WriteLine($"Name: {item.Key} => {item.Value} years");
            }


            //Проверка дали даден ключ се съдържа в речника
            Console.WriteLine();
            foreach (var item in person)
            {
                if (person.ContainsKey("Name"))
                {
                    Console.WriteLine("Yes,ima element sas КЛЮЧ Name");
                    break;
                }
            }

            //Проверка дали даденa стойност се съдържа в речника
            Console.WriteLine();
            foreach (var item in person)
            {
                if (person.ContainsValue(100))
                {
                    Console.WriteLine($"{item.Key} ====> {item.Value}");
                }
            }

            //Сортиране по ключ
            Console.WriteLine();
            Console.WriteLine("Сортиране по ключ");
            foreach (var item in person.OrderBy(x => x.Key))
            {
                Console.WriteLine($"{item.Key} ====> {item.Value}");
            }



            //Изтриване на елемент от речник по ключ
            Console.WriteLine();
            Console.WriteLine("Изтриване на елемент от речник по ключ");
            person.Remove("Name");
            foreach (KeyValuePair <string, int> item in person)
            {
                Console.WriteLine($"Name: {item.Key} => {item.Value} years");
            }

            //Брой на елементите на речник
            Console.WriteLine();
            Console.WriteLine("Брой на елементите на речник");
            int brEl_Rechnik = person.Count;

            Console.WriteLine($"Брой:[{brEl_Rechnik}]");

            //Сортиране по стойност
            Console.WriteLine();
            Console.WriteLine("//Сортиране по стойност");
            person.OrderBy(x => x.Value);
            Console.WriteLine(string.Join(" ", person));
        }
Exemplo n.º 40
0
        public ViewDesignerDoc(int itemId, DataViewHierarchyAccessor accessor, string viewName)
        {
            _accessor   = accessor;
            _connection = accessor.Connection;
            _itemId     = itemId;
            InitializeComponent();

            _init = true;
            try
            {
                _typeQB = SQLiteDataAdapterToolboxItem._vsdesigner.GetType("Microsoft.VSDesigner.Data.Design.QueryBuilderControl");

                if (_typeQB != null)
                {
                    _queryDesigner = Activator.CreateInstance(_typeQB) as UserControl;
                    _typeQB.InvokeMember("Provider", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.SetProperty | System.Reflection.BindingFlags.NonPublic, null, _queryDesigner, new object[] { "System.Data.SQLite" });
                    _typeQB.InvokeMember("ConnectionString", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.SetProperty | System.Reflection.BindingFlags.NonPublic, null, _queryDesigner, new object[] { _connection.ConnectionSupport.ConnectionString });
                    _typeQB.InvokeMember("EnableMorphing", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.SetProperty | System.Reflection.BindingFlags.NonPublic, null, _queryDesigner, new object[] { false });
                    Controls.Add(_queryDesigner);
                    _queryDesigner.Dock    = DockStyle.Fill;
                    _queryDesigner.Visible = true;
                }

                StringBuilder tables = new StringBuilder();

                using (DataReader reader = _connection.Command.Execute("SELECT * FROM sqlite_master", 1, null, 30))
                {
                    while (reader.Read())
                    {
                        tables.Append(reader.GetItem(2).ToString());
                        tables.Append(",");
                    }
                }

                int n = 1;

                if (String.IsNullOrEmpty(viewName))
                {
                    string alltables = tables.ToString();

                    do
                    {
                        viewName = String.Format(CultureInfo.InvariantCulture, "View{0}", n);
                        n++;
                    } while (alltables.IndexOf(viewName + ",", StringComparison.OrdinalIgnoreCase) > -1 || _editingTables.ContainsValue(viewName));

                    _editingTables.Add(GetHashCode(), viewName);
                }
                _view = new SQLite.Designer.Design.View(viewName, _connection.ConnectionSupport.ProviderObject as DbConnection, this);
            }
            finally
            {
                _init = false;
            }
        }
Exemplo n.º 41
0
    //	public void InitColor ()
    //	{
    //		SingleBoxPiece[] mypieces = GetComponentsInChildren <SingleBoxPiece> ();
    //		cubecolor.Clear ();
    //		foreach (SingleBoxPiece p in mypieces) {
    //			p.GetComponent <MeshRenderer> ().material.color = Color.gray;
    //			cubecolor.Add (p.gameObject, MagicColor.None);
    //		}
    //	}

    public void SetColor(GameObject p)
    {
        if (operater == null)
        {
            operater = FindObjectOfType <MyMagicCube> ();
        }
        MagicColor curcolor = operater.Color;

//		print (operater.EditColorStore [curcolor]);
        if (curcolor != MagicColor.None && operater.EditColorStore [curcolor] > 7)
        {
            //print ("此颜色已经编辑完成" + curcolor + operater.EditColorStore [curcolor]);
            return;
        }
        if (cubecolor.ContainsKey(p) && cubecolor [p] == curcolor)
        {
            //print ("颜色相同");
            return;
        }

        bool cansetcolor = true;

        if (editcolorfinished)
        {
            operater.ColorMapDelete(this);
        }

        MagicColor orignalcolor = MagicColor.None;

        // 如果字典里面有当前的物体,则为替换颜色,如果没有,则为添加颜色
        if (cubecolor.ContainsKey(p))
        {
            orignalcolor = cubecolor [p];
            // 这些只是为了防止同一个块上出现两个相同的颜色和对面的颜色
            foreach (GameObject g in cubecolor.Keys)
            {
                if (g != p)
                {
                    if (!cubecolor [g].Equals(MagicColor.None))
                    {
                        if (cubecolor [g] == curcolor)
                        {
                            cansetcolor = false;
                            //print ("此块已经有相同颜色,请勿重复编辑");
                            break;
                        }
                        int index = (int)curcolor;
                        if (index >= 3 && (int)cubecolor [g] == index - 3)
                        {
                            cansetcolor = false;
                            //print ("颜色不匹配");
                            break;
                        }
                        else if (index < 3 && (int)cubecolor [g] == index + 3)
                        {
                            cansetcolor = false;
                            //print ("颜色不匹配");
                            break;
                        }
                    }
                }
            }
        }
        else
        {
            cubecolor.Add(p, curcolor);
            //print ("添加新颜色");
        }

        // 这里先假设将颜色附上去,如果不合适再去掉
        if (cansetcolor)
        {
            cubecolor [p] = curcolor;
        }
        else
        {
            return;
        }

        // TODO: 判断是否完成当前cube的颜色设定,如果完成则保存到字典中,如果没有则等待完成
        if ((cubestyle == CubeStyle.Edge && cubecolor.Count == 2) || (cubestyle == CubeStyle.Corner && cubecolor.Count == 3))
        {
            editcolorfinished = true;
        }
        else
        {
            editcolorfinished = false;
        }

        if (editcolorfinished)
        {
//			foreach (GameObject g in cubecolor.Keys) {
//				editcolorfinished = true;
//				if (g.GetComponent <CubeFace> ().mycolor == MagicColor.None) {
//					editcolorfinished = false;
//				}
//			}
            if (cubecolor.ContainsValue(MagicColor.None))
            {
                editcolorfinished = false;
            }
        }

        if (editcolorfinished)
        {
            //print ("当前块的颜色已经设置完成");

            // TODO: 根据设定的颜色来标识当前cube,判断是否有重复
            CubeMark mark = GetCubeMark();
            if (operater.EditColorMap.ContainsValue(mark) && mark != CubeMark.None)
            {
                // print ("已经有这样的颜色块啦,请不要编辑错误了哦" + mark);
                cubecolor [p] = orignalcolor;
            }
            else
            {
                // print ("颜色编辑成功" + mark);

                operater.ColorDelete(orignalcolor);
                operater.ColorAdd();
                operater.ColorMapAdd(this, mark);
                p.GetComponent <MeshRenderer> ().material.color = MyMapPrefab.ColorMap [curcolor];
            }
        }
        else
        {
            // print ("当前块的颜色尚未设置完成");
            operater.ColorDelete(orignalcolor);
            operater.ColorAdd();
            p.GetComponent <MeshRenderer> ().material.color = MyMapPrefab.ColorMap [curcolor];
        }
    }
Exemplo n.º 42
0
        static void Main(string[] args)
        {
            Console.WriteLine("Day 24");
            Console.WriteLine("Star 1");
            Console.WriteLine("");

            //Each group also has an effective power:
            //the number of units in that group multiplied by their attack damage.

            //During the target selection phase, each group attempts to choose one target.
            //In decreasing order of effective power, groups choose their targets;
            //in a tie, the group with the higher initiative chooses first.
            //The attacking group chooses to target the group in the enemy army to which
            //it would deal the most damage
            //(after accounting for weaknesses and immunities, but not accounting for whether the
            //defending group has enough units to actually receive all of that damage).

            //If an attacking group is considering two defending groups to which it would deal
            //equal damage, it chooses to target the defending group with the
            //largest effective power;
            //if there is still a tie, it chooses the defending group with the highest initiative.
            //If it cannot deal any defending groups damage, it does not choose a target.
            //Defending groups can only be chosen as a target by one attacking group.


            //At the end of the target selection phase,
            //each group has selected zero or one groups to attack,
            //and each group is being attacked by zero or one groups.

            //By default, an attacking group would deal damage equal to its effective power
            //to the defending group.
            //However, if the defending group is immune to the attacking group's attack type,
            //the defending group instead takes no damage;
            //if the defending group is weak to the attacking group's attack type,
            //the defending group instead takes double damage.

            string[] input = System.IO.File.ReadAllLines(inputFile);

            List <UnitGroup> rawUnits = new List <UnitGroup>();

            bool immuneSystem = true;

            foreach (string line in input)
            {
                if (string.IsNullOrEmpty(line))
                {
                    continue;
                }
                else if (line == "Immune System:")
                {
                    immuneSystem = true;
                    continue;
                }
                else if (line == "Infection:")
                {
                    immuneSystem = false;
                    continue;
                }

                rawUnits.Add(new UnitGroup(line, immuneSystem));
            }

            List <UnitGroup> units = new List <UnitGroup>();

            foreach (UnitGroup unit in rawUnits)
            {
                units.Add(new UnitGroup(unit, 1570));
            }

            Comparer <UnitGroup> targettingComparer = new UnitGroupTargetSelectionOrder();
            Comparer <UnitGroup> turnComparer       = new UnitGroupTurnSelectionOrder();

            Dictionary <UnitGroup, UnitGroup> targetDictionary = new Dictionary <UnitGroup, UnitGroup>();

            while (true)
            {
                units.Sort(targettingComparer);

                foreach (UnitGroup unit in units)
                {
                    UnitGroup selectedTarget = null;
                    int       damage         = 0;

                    foreach (UnitGroup target in units)
                    {
                        if (target.ImmuneSystem == unit.ImmuneSystem || targetDictionary.ContainsValue(target))
                        {
                            //Skip friendlies, self, and already-targeted units
                            continue;
                        }

                        int potentialDamage = unit.CalculateDamage(target);
                        if (potentialDamage > damage)
                        {
                            selectedTarget = target;
                            damage         = potentialDamage;
                        }
                        else if (potentialDamage > 0 && potentialDamage == damage)
                        {
                            if (target.EffectivePower > selectedTarget.EffectivePower ||
                                (target.EffectivePower == selectedTarget.EffectivePower &&
                                 target.Initiative > selectedTarget.Initiative))
                            {
                                selectedTarget = target;
                            }
                        }
                    }

                    if (selectedTarget != null)
                    {
                        targetDictionary.Add(unit, selectedTarget);
                    }
                }

                units.Sort(turnComparer);

                foreach (UnitGroup unit in units)
                {
                    if (!unit.Alive || !targetDictionary.ContainsKey(unit))
                    {
                        continue;
                    }

                    UnitGroup target = targetDictionary[unit];
                    target.TakeDamage(unit.CalculateDamage(target));
                }
                targetDictionary.Clear();

                units.RemoveAll(x => !x.Alive);

                int immuneSystemCount = units.Count(x => x.ImmuneSystem);
                if (immuneSystemCount == units.Count || immuneSystemCount == 0)
                {
                    //End when one side is dead
                    break;
                }

                //Console.WriteLine($"Immune:[{string.Join(",", units.Where(x => x.ImmuneSystem).Select(x => x.UnitCount.ToString()).ToArray())}]  Infection:[{string.Join(",", units.Where(x => !x.ImmuneSystem).Select(x => x.UnitCount.ToString()).ToArray())}]");
            }

            Console.WriteLine($"{(units[0].ImmuneSystem ? "ImmuneSystem" : "Infection")} wins with: {units.Sum(x => x.UnitCount)} units remaining.");
            Console.WriteLine("");

            Console.WriteLine("Star 2");
            Console.WriteLine("");

            bool growing = true;
            bool done    = false;

            int boost   = 2;
            int boostLB = 1;
            int boostUB = 2;

            while (!done)
            {
                Console.Write($"Immune Boost: {boost}");

                //Reset
                units.Clear();
                foreach (UnitGroup unit in rawUnits)
                {
                    units.Add(new UnitGroup(unit, boost));
                }

                string lastRound = "";

                //Simulate battle
                while (true)
                {
                    units.Sort(targettingComparer);

                    foreach (UnitGroup unit in units)
                    {
                        UnitGroup selectedTarget = null;
                        int       damage         = 0;

                        foreach (UnitGroup target in units)
                        {
                            if (target.ImmuneSystem == unit.ImmuneSystem || targetDictionary.ContainsValue(target))
                            {
                                //Skip friendlies, self, and already-targeted units
                                continue;
                            }

                            int potentialDamage = unit.CalculateDamage(target);
                            if (potentialDamage > damage)
                            {
                                selectedTarget = target;
                                damage         = potentialDamage;
                            }
                            else if (potentialDamage > 0 && potentialDamage == damage)
                            {
                                if (target.EffectivePower > selectedTarget.EffectivePower ||
                                    (target.EffectivePower == selectedTarget.EffectivePower &&
                                     target.Initiative > selectedTarget.Initiative))
                                {
                                    selectedTarget = target;
                                }
                            }
                        }

                        if (selectedTarget != null)
                        {
                            targetDictionary.Add(unit, selectedTarget);
                        }
                    }

                    units.Sort(turnComparer);

                    foreach (UnitGroup unit in units)
                    {
                        if (!unit.Alive || !targetDictionary.ContainsKey(unit))
                        {
                            continue;
                        }

                        UnitGroup target = targetDictionary[unit];

                        if (!target.Alive)
                        {
                            continue;
                        }

                        target.TakeDamage(unit.CalculateDamage(target));
                    }
                    targetDictionary.Clear();

                    units.RemoveAll(x => !x.Alive);

                    int immuneSystemCount = units.Count(x => x.ImmuneSystem);
                    if (immuneSystemCount == units.Count || immuneSystemCount == 0)
                    {
                        //End when one side is dead
                        break;
                    }

                    string thisRound = $"Immune:[{string.Join(",", units.Where(x => x.ImmuneSystem).Select(x => x.UnitCount.ToString()).ToArray())}]  Infection:[{string.Join(",", units.Where(x => !x.ImmuneSystem).Select(x => x.UnitCount.ToString()).ToArray())}]";

                    if (thisRound == lastRound)
                    {
                        //End if there is a stalemate
                        break;
                    }

                    lastRound = thisRound;
                }

                bool immuneWon = units.Count(x => x.ImmuneSystem) == units.Count;

                Console.WriteLine(immuneWon ? " Won" : " Loss");

                if (growing)
                {
                    if (immuneWon)
                    {
                        growing = false;
                        //Move to binary search

                        boost = (boostUB + boostLB) / 2;
                    }
                    else
                    {
                        boostLB  = boostUB;
                        boostUB *= 2;
                        boost    = boostUB;
                    }
                }
                else
                {
                    if (immuneWon)
                    {
                        if (boostUB == boostLB)
                        {
                            break;
                        }

                        boostUB = boost;
                    }
                    else
                    {
                        boostLB = boost + 1;
                    }

                    boost = (boostUB + boostLB) / 2;
                }
            }


            Console.WriteLine($"{(units[0].ImmuneSystem ? "ImmuneSystem" : "Infection")} wins with: {units.Sum(x => x.UnitCount)} units remaining.");
            Console.WriteLine("");
            Console.ReadKey();
        }
Exemplo n.º 43
0
        /// <summary>
        /// Some preparation and check before creating room.
        /// </summary>
        /// <param name="curPhase">Current phase used to create room, all rooms will be created in this phase.</param>
        /// <returns>Number indicates how many new rooms were created.</returns>
        private int RoomCreationStart()
        {
            int nNewRoomsSize = 0;
            // transaction is used to cancel room creation when exception occurs
            SubTransaction myTransaction = new SubTransaction(m_document);

            try
            {
                // Preparation before room creation starts
                Phase curPhase = null;
                if (!RoomCreationPreparation(ref curPhase))
                {
                    return(0);
                }

                // get all existing rooms which have mapped to spreadsheet rooms.
                // we should skip the creation for those spreadsheet rooms which have been mapped by Revit rooms.
                Dictionary <int, string> existingRooms = new Dictionary <int, string>();
                foreach (Room room in m_roomData.Rooms)
                {
                    Parameter sharedParameter = room.get_Parameter(RoomsData.SharedParam);
                    if (null != sharedParameter && false == String.IsNullOrEmpty(sharedParameter.AsString()))
                    {
                        existingRooms.Add(room.Id.IntegerValue, sharedParameter.AsString());
                    }
                }

                #region Rooms Creation and Set
                myTransaction.Start();
                // create rooms with spread sheet based rooms data
                for (int row = 0; row < m_spreadRoomsTable.Rows.Count; row++)
                {
                    // get the ID column value and use it to check whether this spreadsheet room is mapped by Revit room.
                    String externaId = m_spreadRoomsTable.Rows[row][RoomsData.RoomID].ToString();
                    if (existingRooms.ContainsValue(externaId))
                    {
                        // skip the spreadsheet room creation if it's mapped by Revit room
                        continue;
                    }

                    // create rooms in specified phase, but without placing them.
                    Room newRoom = m_document.Create.NewRoom(curPhase);
                    if (null == newRoom)
                    {
                        // abort the room creation and pop up failure message
                        myTransaction.RollBack();

                        MyMessageBox("Create room failed.", MessageBoxIcon.Warning);
                        return(0);
                    }

                    // set the shared parameter's value of Revit room
                    Parameter sharedParam = newRoom.get_Parameter(RoomsData.SharedParam);
                    if (null == sharedParam)
                    {
                        // abort the room creation and pop up failure message
                        myTransaction.RollBack();
                        MyMessageBox("Failed to get shared parameter, please try again.", MessageBoxIcon.Warning);
                        return(0);
                    }
                    else
                    {
                        sharedParam.Set(externaId);
                    }

                    // Update this new room with values of spreadsheet
                    UpdateNewRoom(newRoom, row);

                    // remember how many new rooms were created, based on spread sheet data
                    nNewRoomsSize++;
                }

                // end this transaction if create all rooms successfully.
                myTransaction.Commit();
                #endregion
            }
            catch (Exception ex)
            {
                // cancel this time transaction when exception occurs
                if (myTransaction.HasStarted())
                {
                    myTransaction.RollBack();
                }

                MyMessageBox(ex.Message, MessageBoxIcon.Warning);
                return(0);
            }

            // output unplaced rooms creation message
            String strMessage    = string.Empty;
            int    nSkippedRooms = m_spreadRoomsTable.Rows.Count - nNewRoomsSize;
            if (nSkippedRooms > 0)
            {
                strMessage = string.Format("{0} unplaced {1} created successfully.\r\n{2} skipped, {3}",
                                           nNewRoomsSize,
                                           (nNewRoomsSize > 1) ? ("rooms were") : ("room was"),
                                           nSkippedRooms.ToString() + ((nSkippedRooms > 1) ? (" were") : (" was")),
                                           (nSkippedRooms > 1) ? ("because they were already mapped by Revit rooms.") :
                                           ("because it was already mapped by Revit rooms."));
            }
            else
            {
                strMessage = string.Format("{0} unplaced {1} created successfully.",
                                           nNewRoomsSize,
                                           (nNewRoomsSize > 1) ? ("rooms were") : ("room was"));
            }

            // output creation message
            MyMessageBox(strMessage, MessageBoxIcon.Information);
            return(nNewRoomsSize);
        }
Exemplo n.º 44
0
        public string GetNameForRelationship(
            EntityMetadata entityMetadata
            , RelationshipMetadataBase relationshipMetadata
            , EntityRole?reflexiveRole
            , ICodeGenerationServiceProvider iCodeGenerationServiceProvider
            )
        {
            string str = reflexiveRole.HasValue ? reflexiveRole.Value.ToString() : string.Empty;

            string keyRelationship = entityMetadata.MetadataId.Value.ToString() + relationshipMetadata.MetadataId.Value + str;

            if (this._knowNames.ContainsKey(keyRelationship))
            {
                return(this._knowNames[keyRelationship]);
            }

            string validName = NamingService.CreateValidName(relationshipMetadata.SchemaName + (!reflexiveRole.HasValue ? string.Empty : reflexiveRole.Value == EntityRole.Referenced ? "_Referenced" : "_Referencing"));

            Dictionary <string, string> knownNamesForEntityMetadata = this._knowNames.Where(d => d.Key.StartsWith(entityMetadata.MetadataId.Value.ToString())).ToDictionary(d => d.Key, d => d.Value);

            validName = ResolveConflictName(validName, s => this._reservedAttributeNames.Contains(s) || knownNamesForEntityMetadata.ContainsValue(s) || string.Equals(s, _typeName, StringComparison.InvariantCultureIgnoreCase));

            this._knowNames.Add(keyRelationship, validName);

            return(validName);
        }
Exemplo n.º 45
0
 /// <summary>Check if Value exists in Dictionary</summary>
 /// <param name="value">Value to check for</param>
 /// <returns><see langword="true"/> if found, <see langword="false"/> otherwise</returns>
 public bool ContainsValue(TValue value)
 {
     lock (Dictionary) return(Dictionary.ContainsValue(value));
 }
Exemplo n.º 46
0
        /// <summary>
        /// 保留部分属性
        /// </summary>
        /// <param name="listSheet"></param>
        private void GetChaoDaiRemainProperties(IListSheet listSheet)
        {
            try
            {
                string[] parameters        = this.Parameters.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                string   columnMapFilePath = parameters[0];

                ExcelReader columnMapER = new ExcelReader(columnMapFilePath, "朝代属性");
                int         rowCount    = columnMapER.GetRowCount();
                Dictionary <string, string> columnAliasToColumns = new Dictionary <string, string>();
                for (int i = 0; i < rowCount; i++)
                {
                    Dictionary <string, string> columnRow = columnMapER.GetFieldValues(i);
                    string columnName = columnRow["column"].Trim();
                    columnAliasToColumns.Add(columnName, columnName);

                    string   aliasColumnsStr = columnRow["aliasColumns"];
                    string[] aliasColumns    = aliasColumnsStr.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string alias in aliasColumns)
                    {
                        columnAliasToColumns.Add(alias.Trim(), columnName);
                    }
                }

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

                ExcelWriter chaoDaiInfoExcelWriter = this.CreateChaoDaiRemainPropertyListWriter();
                for (int i = 0; i < listSheet.RowCount; i++)
                {
                    Dictionary <string, string> listRow = listSheet.GetRow(i);
                    bool   giveUp  = "Y".Equals(listRow[SysConfig.GiveUpGrabFieldName]);
                    string pageUrl = listRow[SysConfig.DetailPageUrlFieldName];
                    string name    = listRow["name"];
                    if (!giveUp)
                    {
                        try
                        {
                            HtmlAgilityPack.HtmlDocument htmlDoc = this.RunPage.GetLocalHtmlDocument(listSheet, i);
                            HtmlNodeCollection           dtNodes = htmlDoc.DocumentNode.SelectNodes("//div[@class=\"basic-info cmn-clearfix\"]/dl/dt");
                            if (dtNodes != null)
                            {
                                List <string> oneIChaoDaiProperties = new List <string>();
                                foreach (HtmlNode dtNode in dtNodes)
                                {
                                    string pKey   = CommonUtil.HtmlDecode(dtNode.InnerText).Trim().Replace(" ", "").Replace(" ", "").Replace(" ", "");
                                    string pValue = this.GetNextDDNodeText(dtNode);

                                    int    sameNamePKeyCount = 1;
                                    string newPKey           = pKey;
                                    while (oneIChaoDaiProperties.Contains(newPKey))
                                    {
                                        sameNamePKeyCount++;
                                        newPKey = pKey + "_" + sameNamePKeyCount.ToString();
                                    }
                                    oneIChaoDaiProperties.Add(newPKey);

                                    if (!propertyColumnNames.Contains(newPKey) && columnAliasToColumns.ContainsValue(newPKey))
                                    {
                                        propertyColumnNames.Add(newPKey);
                                    }

                                    if (columnAliasToColumns.ContainsKey(newPKey))
                                    {
                                        string columnName = columnAliasToColumns[newPKey];

                                        Dictionary <string, string> row = new Dictionary <string, string>();

                                        row.Add("name", name);
                                        row.Add("pKey", columnName);
                                        row.Add("pValue", pValue);
                                        row.Add("url", pageUrl);

                                        chaoDaiInfoExcelWriter.AddRow(row);
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                }
                chaoDaiInfoExcelWriter.SaveToDisk();

                ExcelWriter chaoDaiColumnPropertyExcelWriter = this.CreateChaoDaiRemainColumnPropertyListWriter(propertyColumnNames);
                for (int i = 0; i < listSheet.RowCount; i++)
                {
                    Dictionary <string, string> listRow = listSheet.GetRow(i);
                    bool   giveUp  = "Y".Equals(listRow[SysConfig.GiveUpGrabFieldName]);
                    string pageUrl = listRow[SysConfig.DetailPageUrlFieldName];
                    string name    = listRow["name"];
                    if (!giveUp)
                    {
                        try
                        {
                            HtmlAgilityPack.HtmlDocument htmlDoc = this.RunPage.GetLocalHtmlDocument(listSheet, i);
                            HtmlNodeCollection           dtNodes = htmlDoc.DocumentNode.SelectNodes("//div[@class=\"basic-info cmn-clearfix\"]/dl/dt");
                            Dictionary <string, string>  row     = new Dictionary <string, string>();
                            row.Add("name", name);
                            row.Add("url", pageUrl);
                            if (dtNodes != null)
                            {
                                List <string> oneIChaoDaiProperties = new List <string>();
                                foreach (HtmlNode dtNode in dtNodes)
                                {
                                    string pKey   = CommonUtil.HtmlDecode(dtNode.InnerText).Trim().Replace(" ", "").Replace(" ", "").Replace(" ", "");
                                    string pValue = this.GetNextDDNodeText(dtNode);

                                    int    sameNamePKeyCount = 1;
                                    string newPKey           = pKey;
                                    while (oneIChaoDaiProperties.Contains(newPKey))
                                    {
                                        sameNamePKeyCount++;
                                        newPKey = pKey + "_" + sameNamePKeyCount.ToString();
                                    }
                                    oneIChaoDaiProperties.Add(newPKey);

                                    if (columnAliasToColumns.ContainsKey(newPKey))
                                    {
                                        string columnName = columnAliasToColumns[newPKey];
                                        if (row.ContainsKey(columnName))
                                        {
                                            row[columnName] = row[columnName] + ";" + pValue;
                                        }
                                        else
                                        {
                                            row.Add(columnName, pValue);
                                        }
                                    }
                                }
                            }

                            chaoDaiColumnPropertyExcelWriter.AddRow(row);
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                }
                chaoDaiColumnPropertyExcelWriter.SaveToDisk();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 47
0
        public override CommandResult OnExecute(ICommandSource src, ICommandArgs args)
        {
            if (args.Length < 1)
            {
                return(CommandResult.ShowUsage());
            }

            var player   = src.ToPlayer();
            var senderId = player.CSteamId.m_SteamID;

            switch (args[0].ToLowerString)
            {
            case "accept":
            case "a":
            {
                if (!player.HasPermission($"{Permission}.accept"))
                {
                    return(CommandResult.Lang(EssLang.COMMAND_NO_PERMISSION));
                }

                if (!Requests.ContainsValue(senderId))
                {
                    return(CommandResult.Lang(EssLang.TPA_NONE));
                }

                var whoSentId = new List <ulong>(Requests.Keys).FirstOrDefault(k => Requests[k] == senderId);
                var whoSent   = UPlayer.From(new Steamworks.CSteamID(whoSentId));

                /* Should never happen */
                if (whoSent == null)
                {
                    return(CommandResult.Lang(EssLang.TPA_NONE));
                }

                if (whoSent.Stance == EPlayerStance.DRIVING ||
                    whoSent.Stance == EPlayerStance.SITTING)
                {
                    EssLang.CANNOT_TELEPORT_DRIVING.SendTo(whoSent);
                    return(CommandResult.Lang(EssLang.TPA_CANNOT_TELEPORT, whoSent.DisplayName));
                }

                EssLang.TPA_ACCEPTED_SENDER.SendTo(src, whoSent.DisplayName);
                EssLang.TPA_ACCEPTED.SendTo(whoSent, src.DisplayName);
                Requests.Remove(whoSentId);

                var tpaSettings = EssCore.Instance.Config.Tpa;

                if (tpaSettings.TeleportDelay > 0)
                {
                    Tasks.New(t => {
                            if (!whoSent.IsOnline || !player.IsOnline)
                            {
                                return;
                            }
                            whoSent.Teleport(player.Position);
                        }).Delay(tpaSettings.TeleportDelay * 1000).Go();
                }
                else
                {
                    whoSent.Teleport(player.Position);
                }
                break;
            }

            case "deny":
            case "d":
            {
                if (!player.HasPermission($"{Permission}.deny"))
                {
                    return(CommandResult.Lang(EssLang.COMMAND_NO_PERMISSION));
                }

                if (!Requests.ContainsValue(senderId))
                {
                    return(CommandResult.Lang(EssLang.TPA_NONE));
                }

                var whoSentId = new List <ulong>(Requests.Keys).FirstOrDefault(k => Requests[k] == senderId);
                var whoSent   = UPlayer.From(new Steamworks.CSteamID(whoSentId));

                if (whoSent != null)
                {
                    EssLang.TPA_DENIED.SendTo(whoSent, src.DisplayName);
                }

                EssLang.TPA_DENIED_SENDER.SendTo(src, whoSent == null ? "Unknown" : whoSent.DisplayName);
                Requests.Remove(whoSentId);
                break;
            }

            case "cancel":
            case "c":
            {
                if (!player.HasPermission($"{Permission}.cancel"))
                {
                    return(CommandResult.Lang(EssLang.COMMAND_NO_PERMISSION));
                }

                if (!Requests.ContainsKey(senderId))
                {
                    return(CommandResult.Lang(EssLang.TPA_NONE));
                }

                Requests.Remove(senderId);
                EssLang.TPA_CANCELLED.SendTo(src);
                break;
            }

            default:
            {
                if (!player.HasPermission($"{Permission}.send"))
                {
                    return(CommandResult.Lang(EssLang.COMMAND_NO_PERMISSION));
                }

                if (!args[0].IsValidPlayerName)
                {
                    return(CommandResult.Lang(EssLang.PLAYER_NOT_FOUND, args[0]));
                }

                /*
                 *  Cancel current request
                 */
                if (Requests.ContainsKey(senderId))
                {
                    Requests.Remove(senderId);
                }

                var target = args[0].ToPlayer;

                if (target == player)
                {
                    return(CommandResult.Lang(EssLang.TPA_YOURSELF));
                }

                Requests.Add(senderId, target.CSteamId.m_SteamID);
                EssLang.TPA_SENT_SENDER.SendTo(src, target.DisplayName);
                EssLang.TPA_SENT.SendTo(target, src.DisplayName);

                var tpaSettings = EssCore.Instance.Config.Tpa;

                if (tpaSettings.ExpireDelay > 0)
                {
                    Tasks.New(t => {
                            Requests.Remove(senderId);
                        }).Delay(tpaSettings.ExpireDelay * 1000).Go();
                }
                else
                {
                    Requests.Remove(senderId);
                }
                break;
            }
            }

            return(CommandResult.Success());
        }
Exemplo n.º 48
0
        public static byte[] GetBytes(string String, int maxSize = 0)
        {
            var i = 0;

            switch (_saveType)
            {
            case SaveType.AnimalCrossing:
                var returnedString = new byte[maxSize > 0 ? maxSize : String.Length];
                var t = StringInfo.GetTextElementEnumerator(String);
                while (t.MoveNext() && i < returnedString.Length)
                {
                    if (_charDictionary.ContainsValue((string)t.Current))
                    {
                        returnedString[i] = _charDictionary.FirstOrDefault(o => o.Value == (string)t.Current).Key;
                    }
                    else
                    {
                        returnedString[i] = Encoding.UTF8.GetBytes(new[] { String[t.ElementIndex] })[0];
                    }
                    i++;
                }
                for (var x = 0; x < returnedString.Length; x++)
                {
                    if (returnedString[x] == 0)
                    {
                        returnedString[x] = 0x20;
                    }
                }
                return(returnedString);

            case SaveType.DoubutsuNoMori:
            case SaveType.DoubutsuNoMoriPlus:
            case SaveType.DoubutsuNoMoriEPlus:
            case SaveType.AnimalForestEPlus:
            {
                var stringBytes = new byte[maxSize > 0 ? maxSize : String.Length];
                for (i = 0; i < String.Length; i++)
                {
                    if (i >= stringBytes.Length)
                    {
                        break;
                    }
                    if (StringUtility.DoubutsuNoMoriEPlusCharMap.ContainsValue(String[i].ToString()))
                    {
                        stringBytes[i] = StringUtility.DoubutsuNoMoriEPlusCharMap.First(o => o.Value == String[i].ToString()).Key;
                    }
                    else
                    {
                        stringBytes[i] = Encoding.ASCII.GetBytes(new[] { String[i] })[0];
                    }
                }

                if (maxSize <= 0 || String.Length >= maxSize)
                {
                    return(stringBytes);
                }
                for (i = String.Length; i < maxSize; i++)
                {
                    stringBytes[i] = 0x20;
                }
                return(stringBytes);
            }

            case SaveType.WildWorld:
            {
                var stringBuffer = new byte[maxSize > 0 ? maxSize : String.Length];
                for (i = 0; i < String.Length; i++)
                {
                    var character = String[i].ToString();
                    if (StringUtility.WwCharacterDictionary.ContainsValue(character))
                    {
                        stringBuffer[i] = StringUtility.WwCharacterDictionary.FirstOrDefault(o => o.Value.Equals(character)).Key;
                    }
                }

                return(stringBuffer);
            }

            case SaveType.CityFolk:
            {
                var stringBuffer = new byte[maxSize > 0 ? maxSize : String.Length * 2];     //Characters are now unicode
                var stringBytes  = Encoding.Unicode.GetBytes(String);
                for (i = 0; i < stringBytes.Length; i += 2)
                {
                    Buffer.BlockCopy(stringBytes.Skip(i).Take(2).Reverse().ToArray(), 0, stringBuffer, i, 2);
                }
                return(stringBuffer);
            }

            case SaveType.NewLeaf:
            case SaveType.WelcomeAmiibo:
            {
                var stringBuffer = Encoding.Unicode.GetBytes(String);
                if (maxSize > 0)
                {
                    Array.Resize(ref stringBuffer, maxSize);
                }
                return(stringBuffer);
            }

            case SaveType.AnimalForest:     // Animal Forest iQue support will be added soon
                return(null);

            case SaveType.Unknown:
                MainForm.DebugManager.WriteLine(
                    $"StringUtil was passed an unknown SaveType enum. Received Type: {_saveType.ToString()}", DebugLevel.Error);
                return(null);

            default:
                return(null);
            }
        }
Exemplo n.º 49
0
        static void UpdateAlwaysOnTopToMenu(IntPtr windowHwnd, bool remove = false)
        {
            IntPtr sysMenu;
            int    count;

            sysMenu = GetSystemMenu(windowHwnd, false);
            if ((count = GetMenuItemCount(sysMenu)) < 0) // Check if menu already modified
            {
                sysMenu = GetSystemMenu(windowHwnd, true);
                if ((count = GetMenuItemCount(sysMenu)) < 0)
                {
                    sysMenu = GetSystemMenu(windowHwnd, false);
                    if ((count = GetMenuItemCount(sysMenu)) < 0)
                    {
                        return;
                    }
                }
            }

            // Calculate target position
            uint position = (uint)Math.Max(0, count - OffsetFromBottom);

            // Check if it's already our menu item
            var item = new MENUITEMINFO(MIIM.STATE | MIIM.FTYPE | MIIM.ID | MIIM.STRING);

            item.dwTypeData = new string(' ', 64);
            item.cch        = (uint)item.dwTypeData.Length;
            if (!GetMenuItemInfo(sysMenu, (uint)Math.Max(0, (int)position - 1), true, item))
            {
                return;
            }
            // Need to add new menu item?
            var newItem = item.dwTypeData != MenuItemName && item.wID != MenuId;
            var state   = IsTopmost(windowHwnd) ? MFS_CHECKED : MFS_UNCHECKED;
            // Need to update menu item?
            var updateItem = !newItem && (
                (state & (MFS_CHECKED | MFS_UNCHECKED))
                != (item.fState & (MFS_CHECKED | MFS_UNCHECKED))
                );

            if (remove)
            {
                if (!newItem) // If menu item exists
                //RemoveMenu(sysMenu, (uint)Math.Max(0, (int)position - 1), true);
                {
                    GetSystemMenu(windowHwnd, true); // Reset menu
                }
            }
            else if (newItem || updateItem)
            {
                item            = new MENUITEMINFO(MIIM.STATE | MIIM.FTYPE | MIIM.ID | MIIM.STRING);
                item.fType      = MFT_STRING;
                item.dwTypeData = MenuItemName;
                item.cch        = (uint)item.dwTypeData.Length;
                item.fState     = state;
                item.wID        = MenuId;
                if (newItem) // Add menu item
                {
                    InsertMenuItem(sysMenu, position, true, item);
                }
                else if (updateItem) // Update menu item
                {
                    SetMenuItemInfo(sysMenu, (uint)Math.Max(0, (int)position - 1), true, item);
                }
            }

            if (remove) // Deattach hook?
            {
                var hooks = windowHandles.Where(kv => kv.Value == windowHwnd).Select(kv => kv.Key).ToArray();
                foreach (var hook in hooks)
                {
                    UnhookWinEvent(hook);
                    windowHandles.Remove(hook);
                }
            }
            // Attach hook to target window
            else if (!windowHandles.ContainsValue(windowHwnd))
            {
                var hhook = SetWinEventHook(EVENT_OBJECT_INVOKED, EVENT_OBJECT_INVOKED, windowHwnd,
                                            WinEventObjectInvoked, 0, 0, WINEVENT_OUTOFCONTEXT);
                if (hhook != IntPtr.Zero)
                {
                    windowHandles[hhook] = windowHwnd;
                }
            }
        }
Exemplo n.º 50
0
 public static bool IsKnownPredefinedServiceName(string serviceName)
 {
     return(_screenOSPredefinedServices.ContainsValue(serviceName));
 }
Exemplo n.º 51
0
 public bool ContainsValue(TValue value)
 {
     return(TrueDictionary.ContainsValue(value));
 }
Exemplo n.º 52
0
        static void Main(string[] args)
        {
            Queue <int> liquids = new Queue <int>(Console.ReadLine().Split(" ", StringSplitOptions.RemoveEmptyEntries).Select(int.Parse));
            Stack <int> items   = new Stack <int>(Console.ReadLine().Split(" ", StringSplitOptions.RemoveEmptyEntries).Select(int.Parse));
            Dictionary <string, int> materials = new Dictionary <string, int>
            {
                ["Glass"]        = 0,
                ["Aluminium"]    = 0,
                ["Lithium"]      = 0,
                ["Carbon fiber"] = 0
            };

            while (true)
            {
                if (liquids.Count == 0 || items.Count == 0)
                {
                    break;
                }

                int liquid   = liquids.Peek();
                int physItem = items.Peek();

                if (liquid + physItem == 25)
                {
                    materials["Glass"]++;

                    liquids.Dequeue();
                    items.Pop();
                }
                else if (liquid + physItem == 50)
                {
                    materials["Aluminium"]++;

                    liquids.Dequeue();
                    items.Pop();
                }
                else if (liquid + physItem == 75)
                {
                    materials["Lithium"]++;

                    liquids.Dequeue();
                    items.Pop();
                }
                else if (liquid + physItem == 100)
                {
                    materials["Carbon fiber"]++;

                    liquids.Dequeue();
                    items.Pop();
                }
                else
                {
                    liquids.Dequeue();
                    physItem += 3;
                    items.Pop();
                    List <int> temp = items.ToList();
                    temp.Insert(0, physItem);
                    items = new Stack <int>(temp.ToArray().Reverse());
                }
            }

            if (!materials.ContainsValue(0))
            {
                Console.WriteLine("Wohoo! You succeeded in building the spaceship!");
            }
            else
            {
                Console.WriteLine("Ugh, what a pity! You didn't have enough materials to build the spaceship.");
            }

            if (liquids.Count > 0)
            {
                Console.WriteLine("Liquids left: " + string.Join(", ", liquids));
            }
            else
            {
                Console.WriteLine("Liquids left: none");
            }

            if (items.Count > 0)
            {
                Console.WriteLine("Physical items left: " + string.Join(", ", items));
            }
            else
            {
                Console.WriteLine("Physical items left: none");
            }

            foreach (var item in materials.OrderBy(x => x.Key))
            {
                Console.WriteLine($"{item.Key}: {item.Value}");
            }
        }
Exemplo n.º 53
0
 public string GetPrefix(IReadOnlyPackage package)
 {
     return(explicitMounts.ContainsValue(package) ? explicitMounts.First(f => f.Value == package).Key : null);
 }
Exemplo n.º 54
0
        static void Main(string[] args)
        {
            var dictionaryOfEvents = new Dictionary <long, string>();

            var dictionaryOfParticipants = new Dictionary <string, List <string> >();

            var line = Console.ReadLine();

            while (line != "Time for Code")
            {
                var inputRequest = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();

                if (inputRequest[0].All(char.IsDigit))
                {
                    var eventId = long.Parse(inputRequest[0]);

                    var eventName = inputRequest[1];

                    if (eventName.First() == '#')
                    {
                        var listOfParticipants = new List <string>();

                        //creat list of participant
                        for (int p = 2; p < inputRequest.Count; p++)
                        {
                            if (inputRequest[p].First() == '@')
                            {
                                listOfParticipants.Add(inputRequest[p]);
                            }
                        }

                        var name = new string(eventName.Skip(1).ToArray());

                        if (!dictionaryOfEvents.ContainsKey(eventId))
                        {
                            dictionaryOfEvents[eventId]    = eventName;
                            dictionaryOfParticipants[name] = new List <string>();
                            dictionaryOfParticipants[name].AddRange(listOfParticipants.Distinct());
                        }
                        else if (dictionaryOfEvents.ContainsValue(eventName))
                        {
                            foreach (var participant in listOfParticipants)
                            {
                                if (!dictionaryOfParticipants[name].Contains(participant))
                                {
                                    dictionaryOfParticipants[name].Add(participant);
                                }
                            }
                        }
                    }
                }

                line = Console.ReadLine();
            }

            foreach (var events in dictionaryOfParticipants.Distinct().OrderByDescending(x => x.Value.Count).ThenBy(n => n.Key))
            {
                Console.WriteLine($"{events.Key} - {events.Value.Count}");

                foreach (var participant in events.Value.OrderBy(x => x))
                {
                    Console.WriteLine(participant);
                }
            }
            Console.WriteLine();
        }
Exemplo n.º 55
0
        public virtual bool ContainsValue(TData data)
        {
            bool contais = _dictionary.ContainsValue(data);

            return(contais);
        }
Exemplo n.º 56
0
 public bool InternalNameExists(string internalName)
 {
     return(_dosDevices.ContainsValue(internalName));
 }
Exemplo n.º 57
0
        private void Compile(TextEditorToolRoutedEventArgs Args)
        {
            ServiceVirtualization SV = new ServiceVirtualization();

            try
            {
                List <int> BodyLines        = new List <int>();
                List <int> InteractionLines = new List <int>();
                string     EditorText       = Args.txt;
                Args.ErrorLines = new List <int>();
                string[] lines = EditorText.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);

                for (int i = 0; i < lines.Length; i++)
                {
                    string st = lines[i].TrimStart();

                    if (st.StartsWith("PACT:"))
                    {
                    }
                    else if (string.IsNullOrEmpty(st))
                    {
                    }
                    else if (st.StartsWith("@"))
                    {
                        string[] Tags = st.Split(new string[] { " " }, StringSplitOptions.None);
                        foreach (string tag in Tags)
                        {
                            if (!tag.TrimStart().StartsWith("@"))
                            {
                                Args.ErrorLines.Add(i + 2);
                                Args.ErrorMessage = Args.ErrorMessage + "Line number: " + (i + 2) + "-Tags must start with @" + Environment.NewLine;
                            }
                        }
                    }
                    else if (st.StartsWith("Interaction") || st.StartsWith("Interaction Outline"))
                    {
                        InteractionLines.Add(i);
                        if (lines[i + 1].TrimStart().StartsWith("Given"))
                        {
                            if (string.IsNullOrEmpty(GetStringBetween(lines[i + 1], "\"", "\"")))
                            {
                                Args.ErrorLines.Add(i + 2);
                                Args.ErrorMessage = Args.ErrorMessage + "Line number: " + (i + 2) + "-Given value cannot be empty" + Environment.NewLine;
                            }
                        }
                        else
                        {
                            Args.ErrorLines.Add(i + 2);
                            Args.ErrorMessage = Args.ErrorMessage + "Line number: " + (i + 2) + "-Given is missing." + Environment.NewLine;
                            i = i - 1;
                        }

                        if (lines[i + 2].TrimStart().StartsWith("Upon Receiving"))
                        {
                            if (string.IsNullOrEmpty(GetStringBetween(lines[i + 2], "\"", "\"")))
                            {
                                Args.ErrorLines.Add(i + 3);
                                Args.ErrorMessage = Args.ErrorMessage + "Line number: " + (i + 3) + "-Upon Receiving value cannot be empty" + Environment.NewLine;
                            }
                        }
                        else
                        {
                            Args.ErrorLines.Add(i + 3);
                            Args.ErrorMessage = Args.ErrorMessage + "Line number: " + (i + 3) + "-Upon Receiving is missing." + Environment.NewLine;
                            i = i - 1;
                        }

                        if (lines[i + 3].TrimStart().StartsWith("Method"))
                        {
                            if (string.IsNullOrEmpty(GetStringBetween(lines[i + 3], "\"", "\"")))
                            {
                                Args.ErrorLines.Add(i + 4);
                                Args.ErrorMessage = Args.ErrorMessage + "Line number: " + (i + 4) + "-Method value cannot be empty" + Environment.NewLine;
                            }
                        }
                        else
                        {
                            Args.ErrorLines.Add(i + 4);
                            Args.ErrorMessage = Args.ErrorMessage + "Line number: " + (i + 4) + "-Method is missing." + Environment.NewLine;
                            i = i - 1;
                        }

                        if (lines[i + 4].TrimStart().StartsWith("Path"))
                        {
                            if (string.IsNullOrEmpty(GetStringBetween(lines[i + 4], "\"", "\"")))
                            {
                                Args.ErrorLines.Add(i + 5);
                                Args.ErrorMessage = Args.ErrorMessage + "Line number: " + (i + 5) + "-Path value cannot be empty" + Environment.NewLine;
                            }
                        }
                        else
                        {
                            Args.ErrorLines.Add(i + 5);
                            Args.ErrorMessage = Args.ErrorMessage + "Line number: " + (i + 5) + "-Path is missing." + Environment.NewLine;
                            i = i - 1;
                        }

                        if (lines[i + 5].TrimStart().StartsWith("Headers:"))
                        {
                            string HeadersColumns = lines[i + 6].TrimStart();
                            Dictionary <string, string> HeadersDict = GetDictBetween(HeadersColumns, "|", "|", true);
                            if (!HeadersDict.ContainsKey("Key") || HeadersDict["Key"] != "Value")
                            {
                                Args.ErrorLines.Add(i + 7);
                                Args.ErrorMessage = Args.ErrorMessage + "Line number: " + (i + 7) + "-Headers Columns has to be Key and Value" + Environment.NewLine;
                            }
                        }
                        else
                        {
                            Args.ErrorLines.Add(i + 7);
                            Args.ErrorMessage = Args.ErrorMessage + "Line number: " + (i + 7) + "-Headers definition is missing." + Environment.NewLine;
                            i = i - 1;
                        }
                        int j = i + 7;

                        while (lines[j].TrimStart().StartsWith("|"))
                        {
                            string line = lines[j].TrimStart();
                            Dictionary <string, string> ValuesDict = GetDictBetween(line, "|", "|");
                            if (ValuesDict.ContainsKey("") || ValuesDict.ContainsValue(""))
                            {
                                Args.ErrorLines.Add(j + 1);
                                Args.ErrorMessage = Args.ErrorMessage + "Line number: " + (j + 1) + "-Headers Values have to be wrapped by quotes and cannot be empty" + Environment.NewLine;
                            }
                            j = j + 1;
                        }
                        i = j;
                        if (lines[i].TrimStart().StartsWith("Body"))
                        {
                            BodyLines.Add(i + 2);
                        }
                        else
                        {
                            Args.ErrorLines.Add(i + 1);
                            Args.ErrorMessage = Args.ErrorMessage + "Line number: " + (i + 1) + "-Body definition is missing.";
                            i = i - 1;
                        }

                        j = i + 1;

                        while (lines[j].TrimStart().StartsWith("{"))
                        {
                            string line = lines[j].TrimStart();
                            //TODO: Add code for validating Body
                            j = j + 1;
                        }

                        i = j;

                        if (lines[i].TrimStart().StartsWith("Will Respond With"))
                        {
                        }
                        else
                        {
                            Args.ErrorLines.Add(i + 1);
                            Args.ErrorMessage = Args.ErrorMessage + "Line number: " + (i + 1) + "-Will Respond With is missing." + Environment.NewLine;
                            i = i - 1;
                        }

                        if (lines[i + 1].TrimStart().StartsWith("Status"))
                        {
                            if (string.IsNullOrEmpty(GetStringBetween(lines[i + 1], "\"", "\"")))
                            {
                                Args.ErrorLines.Add(i + 2);
                                Args.ErrorMessage = Args.ErrorMessage + "Line number: " + (i + 2) + "-Status value cannot be empty" + Environment.NewLine;
                            }
                        }
                        else
                        {
                            Args.ErrorLines.Add(i + 3);
                            Args.ErrorMessage = Args.ErrorMessage + "Line number: " + (i + 3) + "-Status is missing." + Environment.NewLine;
                            i = i - 1;
                        }

                        if (lines[i + 2].TrimStart().StartsWith("Headers:"))
                        {
                            string HeadersColumns = lines[i + 3].TrimStart();
                            Dictionary <string, string> HeadersDict = GetDictBetween(HeadersColumns, "|", "|", true);
                            if (!HeadersDict.ContainsKey("Key") || HeadersDict["Key"] != "Value")
                            {
                                Args.ErrorLines.Add(i + 4);
                                Args.ErrorMessage = Args.ErrorMessage + "Line number: " + (i + 4) + "-Headers Columns has to be Key and Value" + Environment.NewLine;
                            }
                        }
                        else
                        {
                            Args.ErrorLines.Add(i + 4);
                            Args.ErrorMessage = Args.ErrorMessage + "Line number: " + (i + 4) + "-Headers definition is missing." + Environment.NewLine;
                        }

                        j = i + 4;

                        while (lines[j].TrimStart().StartsWith("|"))
                        {
                            string line = lines[j].TrimStart();
                            Dictionary <string, string> ValuesDict = GetDictBetween(line, "|", "|");
                            if (ValuesDict.ContainsKey("") || ValuesDict.ContainsValue(""))
                            {
                                Args.ErrorLines.Add(j + 1);
                                Args.ErrorMessage = Args.ErrorMessage + "Line number: " + (j + 1) + "-Headers Values have to be wrapped by quotes and cannot be empty" + Environment.NewLine;
                            }
                            j = j + 1;
                        }
                        i = j;

                        if (lines[i].TrimStart().StartsWith("Body"))
                        {
                            BodyLines.Add(i + 2);
                        }
                        else
                        {
                            Args.ErrorLines.Add(i + 1);
                            Args.ErrorMessage = Args.ErrorMessage + "Line number: " + (i + 1) + "-Body definition is missing." + Environment.NewLine;
                            i = i - 1;
                        }

                        j = i + 1;

                        while (lines[j].TrimStart().StartsWith("{"))
                        {
                            string line = lines[j].TrimStart();
                            //TODO: Add code for validating Body
                            j = j + 1;
                        }
                        i = j;
                    }
                }

                if (!string.IsNullOrEmpty(Args.ErrorMessage))
                {
                    SV.MockProviderService.Stop();
                    return;
                }

                List <ProviderServiceInteraction> PSIList = ParsePACT(Args.txt);
                //TODO: reuse the same code port is dummy, need to create SV constructor for creating json
                int InteractionsIndexes = 0;
                try
                {
                    foreach (ProviderServiceInteraction PSI in PSIList)
                    {
                        SV.AddInteraction(PSI);
                        InteractionsIndexes = InteractionsIndexes + 1;
                    }
                }
                catch (Exception ex)
                {
                    Args.ErrorLines.Add(InteractionLines[InteractionsIndexes] + 1);
                    Args.ErrorMessage = Args.ErrorMessage + "Failed to Build Interaction no- " + (InteractionsIndexes + 1) + Environment.NewLine;
                    throw ex;
                }

                //Validate Json Body
                int BodysIndexes = 0;
                foreach (ProviderServiceInteraction PSI in PSIList)
                {
                    try
                    {
                        KeyValuePair <string, string> KVP = new KeyValuePair <string, string>("Content-Type", "application/json");

                        if (PSI.Request.Headers.Contains(KVP))
                        {
                            JObject BodyJsonObj = null;
                            Dictionary <string, string> BodydictObj = null;
                            BodyJsonObj = JObject.Parse(PSI.Request.Body);
                            BodydictObj = BodyJsonObj.ToObject <Dictionary <string, string> >();
                        }
                        BodysIndexes = BodysIndexes + 1;
                        if (PSI.Response.Headers.Contains(KVP))
                        {
                            JObject BodyJsonObj = null;
                            Dictionary <string, string> BodydictObj = null;
                            BodyJsonObj = JObject.Parse(PSI.Response.Body);
                            BodydictObj = BodyJsonObj.ToObject <Dictionary <string, string> >();
                        }
                        BodysIndexes = BodysIndexes + 1;
                    }
                    catch (Exception)
                    {
                        Args.ErrorLines.Add(BodyLines[BodysIndexes]);
                        Args.ErrorMessage = Args.ErrorMessage + "Body's Json is not in the correct Json format" + Environment.NewLine;
                    }
                }

                SV.MockProviderService.Stop();
                if (string.IsNullOrEmpty(Args.ErrorMessage))
                {
                    Args.SuccessMessage = "Compilation Passed Successfully";
                }
            }
            catch (Exception ex)
            {
                Args.ErrorMessage = "Compilation Failed" + Environment.NewLine + Args.ErrorMessage + ex.Message + Environment.NewLine + ex.InnerException;
                SV.MockProviderService.Stop();
            }
        }
Exemplo n.º 58
0
        public LinkedList <FrameworkElement> getSelectedControls(Tree <Symbol> tree)
        {
            Terminal t = (Terminal)tree.Child(0).Element();

            LinkedList <FrameworkElement> res = new LinkedList <FrameworkElement>();

            if (t is Identifier)
            {
                res.AddLast((FrameworkElement)win.FindName(t.GetText()));
            }
            else if (t is ControlType || t is All)
            {
                LinkedList <FrameworkElement> controls = getControlByType((Grid)win.Content, t.GetText());
                foreach (FrameworkElement fe in controls)
                {
                    if (controlEvolutions.ContainsKey(fe.Name) || (!controlEvolutions.ContainsKey(fe.Name) && !controlEvolutions.ContainsValue(fe)))
                    {
                        res.AddLast(fe);
                    }
                }
            }
            else if (t is Lexer.Selector)
            {
                Terminal   param = (Terminal)tree.Child(1).Child(0).Element();
                Type       type  = Type.GetType("Animator.SitInterpreter.Selector." + t.GetText());
                SelectorAb s     = (SelectorAb)Activator.CreateInstance(type, new object[] { param.GetText() });
                //Console.WriteLine(s.options);
                LinkedList <FrameworkElement> controls = s.getControls((Grid)win.Content);
                foreach (FrameworkElement fe in controls)
                {
                    if (controlEvolutions.ContainsKey(fe.Name) || (!controlEvolutions.ContainsKey(fe.Name) && !controlEvolutions.ContainsValue(fe)))
                    {
                        //Console.WriteLine(fe.Name);
                        res.AddLast(fe);
                    }
                }
            }

            return(res);
        }
Exemplo n.º 59
0
 public static bool HasKey(string value)
 {
     return(Map?.ContainsValue(value) == true);
 }
Exemplo n.º 60
0
 public bool HoldsValue(dynamic Value)
 {
     return(Host.ContainsValue(Value));
 }