public void ReadOnlyDictionary_ContainsKey()
        {
            var random    = new Random();
            var testCount = 5;

            for (var i = 0; i < testCount; i++)
            {
                var count    = (i == 0) ? 0 : random.Next(10) + 1;
                var original = new Dictionary <Guid, int>(count);
                var keys     = new HashSet <Guid>();
                for (var j = 0; j < count; j++)
                {
                    var key = Guid.NewGuid();
                    original.Add(key, random.Next());
                    keys.Add(key);
                }

                Assert.AreEqual(count, keys.Count);
                var dictionary = new ReadOnlyDictionary <Guid, int>(original);
                foreach (var key in keys)
                {
                    Assert.IsTrue(dictionary.ContainsKey(key));
                }

                Assert.IsFalse(dictionary.ContainsKey(Guid.NewGuid()));
            }
        }
        public void ContainsKeyTest()
        {
            IDictionary <string, string> target = new ReadOnlyDictionary <string, string>(testDictionary);

            Assert.IsTrue(target.ContainsKey("Item1"));
            Assert.IsFalse(target.ContainsKey("Test1"));
        }
Пример #3
0
        public void ReadOnlyDictionary_Basic()
        {
            Dictionary <string, string>  dictionary = new Dictionary <string, string>();
            IDictionary <string, string> readOnly;
            string value;

            readOnly = new ReadOnlyDictionary <string, string>(dictionary);
            Assert.IsTrue(readOnly.IsReadOnly);
            Assert.AreEqual(0, readOnly.Count);
            Assert.IsFalse(readOnly.ContainsKey("test"));
            Assert.IsFalse(readOnly.TryGetValue("test", out value));

            dictionary.Add("foo", "bar");
            dictionary.Add("hello", "world");

            readOnly = new ReadOnlyDictionary <string, string>(dictionary);
            Assert.AreEqual(2, readOnly.Count);
            Assert.IsTrue(readOnly.ContainsKey("hello"));
            Assert.IsTrue(readOnly.TryGetValue("hello", out value));
            Assert.AreEqual("world", value);
            Assert.AreEqual("world", readOnly["hello"]);

            readOnly = dictionary.ToReadOnly();
            Assert.AreEqual(2, readOnly.Count);
            Assert.IsTrue(readOnly.ContainsKey("hello"));
            Assert.IsTrue(readOnly.TryGetValue("hello", out value));
            Assert.AreEqual("world", value);
            Assert.AreEqual("world", readOnly["hello"]);
        }
Пример #4
0
        public void TestConstructorWrapsKeyValuePairs()
        {
            var pairs = new List <KeyValuePair <int, bool> >
            {
                new KeyValuePair <int, bool>(0, true),
                new KeyValuePair <int, bool>(1, false),
                new KeyValuePair <int, bool>(2, true),
                new KeyValuePair <int, bool>(3, false)
            };

            var toTest = new ReadOnlyDictionary <int, bool>(pairs);

            Assert.IsTrue(toTest.IsReadOnly);
            Assert.AreEqual(4, toTest.Count);
            Assert.IsTrue(toTest.ContainsKey(0));
            Assert.IsTrue(toTest.ContainsKey(1));
            Assert.IsTrue(toTest.ContainsKey(2));
            Assert.IsTrue(toTest.ContainsKey(3));
            Assert.AreEqual(true, toTest[0]);
            Assert.AreEqual(false, toTest[1]);
            Assert.AreEqual(true, toTest[2]);
            Assert.AreEqual(false, toTest[3]);

            Assert.IsTrue(pairs.OrderBy(kv => kv.Key).SequenceEqual(toTest.OrderBy(kv => kv.Key)));
            Assert.IsTrue(pairs.Select(kv => kv.Key).OrderBy(k => k).SequenceEqual(toTest.Keys.OrderBy(k => k)));
            Assert.IsTrue(pairs.Select(kv => kv.Value).OrderBy(v => v).SequenceEqual(toTest.Values.OrderBy(v => v)));
        }
Пример #5
0
 /// <summary>
 /// Replace the style of the current text with the one the user specified
 /// </summary>
 /// <param Name="selection">The current selection</param>
 /// <param Name="arguments">The arguments provided to the command</param>
 public override void Execute(UMD.HCIL.PiccoloX.Util.PStyledTextHelpers.Selection selection, string[] arguments)
 {
     //If the selection exists, and the first argument is a style
     if (selection != null && arguments.Length > 0 && Styles.ContainsKey(arguments[0]))
     {
         //Apply that style to the text
         ApplyStyle(selection, Styles[arguments[0]]);
     }
 }
Пример #6
0
        public void ConstructorKeySelector()
        {
            var dict = new ReadOnlyDictionary<int, DateTime> (new[]{
                new DateTime (2009, 1, 1),
                new DateTime (2008, 1, 1),
                new DateTime (2007, 1, 1)
            }.ToDictionary(d => d.Year));

            Assert.IsTrue (dict.ContainsKey (2009));
            Assert.IsTrue (dict.ContainsKey (2008));
            Assert.IsTrue (dict.ContainsKey (2007));
        }
Пример #7
0
        public void ConstructorKeySelector()
        {
            var dict = new ReadOnlyDictionary <int, DateTime> (new[] {
                new DateTime(2009, 1, 1),
                new DateTime(2008, 1, 1),
                new DateTime(2007, 1, 1)
            }.ToDictionary(d => d.Year));

            Assert.IsTrue(dict.ContainsKey(2009));
            Assert.IsTrue(dict.ContainsKey(2008));
            Assert.IsTrue(dict.ContainsKey(2007));
        }
Пример #8
0
 private Card GetValidCard(Card externalCard)
 {
     if ((externalCard.ID == null && !string.IsNullOrEmpty(externalCard.Name)) ||
         !CardDictionary.ContainsKey(externalCard.ID))
     {//find card by name in current data, this allows for ID udpates or loading by name
         var updatedCard = CardDictionary.FirstOrDefault(c => c.Value.Name == externalCard.Name);
         return(updatedCard.Value);
     }
     else
     {
         return(CardDictionary[externalCard.ID]);
     }
 }
Пример #9
0
        GivenQueuingReportAndPolling_WhenAllDataIsValid_TheReportIsDownloaded_AndIsReturnedInTheCallbackMethodAlongWithTheCallbackData()
        {
            // arrange
            var validFeedType    = $"{_testEntriesIdentifier}_VALID_FEED_TYPE_";
            var validFeedContent = "This is some test content. Und die Katze läuft auf der Straße.";

            var expectedFeedSubmissionId        = "test feed submission Id";
            var expectedFeedProcessingStatus    = "_DONE_";
            var feedSubmissionContainer         = GenerateFeedContainer(validFeedContent, validFeedType);
            var expectedCallbackData            = ("test", "callback", "data");
            var expectedSubmissionReportContent = "Test submission report content. Und die Katze läuft auf der Straße.";

            Setup_SubmitFeed_Returns_FeedSubmissionIdWasGenerated(expectedFeedSubmissionId, validFeedType);
            Setup_GetFeedSubmissionList_Returns_FeedSubmittedSuccessfully(expectedFeedSubmissionId, expectedFeedProcessingStatus);
            Setup_GetFeedSubmissionResult_Returns_SubmissionReportContentStream(expectedFeedSubmissionId, expectedSubmissionReportContent);
            _actualFeedSubmissionReportContent = null;
            var feedUploadedEventNumberOfInvocations            = 0;
            ReadOnlyDictionary <string, object> targetEventArgs = null;

            _easyMwsClient.FeedUploaded += (s, e) =>
            {
                feedUploadedEventNumberOfInvocations++;
                targetEventArgs = e.TargetHandlerArgs;
                _actualFeedSubmissionReportContent = e.ProcessingReportContent;
            };

            // act - queue report
            _easyMwsClient.QueueFeed(feedSubmissionContainer, "targetEventId", new Dictionary <string, object> {
                { "key1", "value1" }, { "key2", "value2" }
            });

            // act - Poll report request process, in order for the queuedReport delegate to be invoked.
            _easyMwsClient.Poll();

            // assert - callback was invoked successfully with expected content.
            Assert.AreEqual(2, targetEventArgs.Count);
            Assert.IsTrue(targetEventArgs.ContainsKey("key1"));
            Assert.IsTrue(targetEventArgs.ContainsKey("key2"));
            Assert.IsNotNull(targetEventArgs.FirstOrDefault(kvp => kvp.Value == "value1"));
            Assert.IsNotNull(targetEventArgs.FirstOrDefault(kvp => kvp.Value == "value2"));
            Assert.AreEqual(1, feedUploadedEventNumberOfInvocations);
            Assert.AreEqual(expectedSubmissionReportContent, _actualFeedSubmissionReportContent == null ? null : new StreamReader(_actualFeedSubmissionReportContent).ReadToEnd());
            _mwsClientMock.Verify(mws => mws.SubmitFeed(It.IsAny <SubmitFeedRequest>()), Times.Once);
            _mwsClientMock.Verify(mws => mws.GetFeedSubmissionList(It.IsAny <GetFeedSubmissionListRequest>()), Times.Once);
            _mwsClientMock.Verify(mws => mws.GetFeedSubmissionResult(It.IsAny <GetFeedSubmissionResultRequest>()), Times.Once);

            var dbEntry = _dbContext.ReportRequestEntries.FirstOrDefault(rre => rre.ReportType == validFeedType);

            Assert.IsNull(dbEntry);
        }
Пример #10
0
        internal void AddButtonFromKeyDown(Keys Key)
        {
            if (!ButtonsBinding.ContainsKey(Key))
            {
                return;
            }
            Buttons b = ButtonsBinding[Key];

            if (IsDownedButtons.Contains(b))
            {
                return;
            }
            IsDownedButtons.Add(b);
        }
Пример #11
0
        private string GetDeviceModelName()
        {
            var    biosInfo = BiosInfo.BiosInfo.Create();
            string sysName  = biosInfo?.SystemName.Trim();

            if (sysName == null)
            {
                return(null);
            }

            sysName = Regex.Replace(sysName, RemoveBracketsPattern, "").Trim();
            string vendor = biosInfo?.SystemVendor?.Trim();

            if (vendor != null)
            {
                if (VendorAliases.ContainsKey(vendor))
                {
                    vendor = VendorAliases[vendor];
                }

                if (!sysName.StartsWith(vendor, StringComparison.OrdinalIgnoreCase))
                {
                    sysName = $"{vendor} {sysName}";
                }
            }

            return(sysName);
        }
        public void TestDictionary()
        {
            // Default ctor.
            var data = Enumerable.Range(1, 5).ToDictionary(x => x, x => x.ToString());
            var dict = new ReadOnlyDictionary <int, string>(data);

            Assert.AreEqual(5, dict.Count);
            Assert.IsTrue(dict.IsReadOnly);
            CollectionAssert.AreEqual(data, dict);
            CollectionAssert.AreEqual(data.Keys, dict.Keys);
            CollectionAssert.AreEqual(data.Values, dict.Values);

            Assert.IsTrue(dict.GetEnumerator().MoveNext());
            Assert.IsTrue(((IEnumerable)dict).GetEnumerator().MoveNext());

            Assert.IsTrue(dict.ContainsKey(1));
            Assert.IsTrue(dict.Contains(new KeyValuePair <int, string>(4, "4")));
            Assert.AreEqual("3", dict[3]);

            string val;

            Assert.IsTrue(dict.TryGetValue(2, out val));
            Assert.AreEqual("2", val);

            var arr = new KeyValuePair <int, string> [5];

            dict.CopyTo(arr, 0);
            CollectionAssert.AreEqual(data, arr);

            Assert.Throws <NotSupportedException>(() => dict.Add(1, "2"));
            Assert.Throws <NotSupportedException>(() => dict.Add(new KeyValuePair <int, string>(1, "2")));
            Assert.Throws <NotSupportedException>(() => dict.Clear());
            Assert.Throws <NotSupportedException>(() => dict.Remove(1));
            Assert.Throws <NotSupportedException>(() => dict.Remove(new KeyValuePair <int, string>(1, "2")));
        }
Пример #13
0
        public bool Evaluate(ReadOnlyDictionary <string, string[]> properties)
        {
            bool present = properties.ContainsKey(Name);
            bool match   = present && properties[Name].Contains(Value);

            return(present && (Negate ^ match));
        }
Пример #14
0
        public ChemistryBase GetFromPath(string path)
        {
            try
            {
                //first part of the path has to be a molecule
                if (path.StartsWith("/"))
                {
                    path = path.Substring(1); //strip off the first separator
                }

                string molID = path.UpTo("/");

                if (!Molecules.ContainsKey(molID))
                {
                    throw new ArgumentException("First child is not a molecule");
                }

                string relativepath = Helpers.Utils.GetRelativePath(molID, path);
                if (relativepath != "")
                {
                    return(Molecules[molID].GetFromPath(relativepath));
                }
                else
                {
                    return(Molecules[molID]);
                }
            }
            catch (ArgumentException ex)
            {
                throw new ArgumentException($"Object {path} not found {ex.Message}");
            }
        }
        /// <summary>
        /// Takes a snapshot of the child signals before making a change, then makes the change, then takes another
        /// snapshot, does a comparison, and fires a signal changed event for any signals that are different.
        /// </summary>
        /// <param name="act">Action that does changes to the tree</param>
        public void NotifySignals(Action act)
        {
            var oldChildren = new ReadOnlyDictionary <FieldGuid, NodeBase>(new Dictionary <FieldGuid, NodeBase>());

            if (Node != null)
            {
                oldChildren = Node.GetChildrenRecursive();
            }

            act();

            var newChildren = new ReadOnlyDictionary <FieldGuid, NodeBase>(new Dictionary <FieldGuid, NodeBase>());

            if (Node != null)
            {
                newChildren = Node.GetChildrenRecursive();
            }

            foreach (var newChildKey in newChildren.Keys)
            {
                if (!oldChildren.ContainsKey(newChildKey))
                {
                    // it's an edited node
                    var sig = newChildren[newChildKey] as NodeSignal;
                    runtimeService.NotifySignalChanged(sig);
                }
            }
        }
Пример #16
0
        /// <summary>
        /// Constructs an <see cref="ErrorRecord"/> from an <see cref="AcmeClient.AcmeWebException"/>,
        /// populating as much detail as can be derived.
        /// </summary>
        /// <param name="ex"></param>
        /// <param name="targetObject"></param>
        /// <returns></returns>
        public static ErrorRecord CreateErrorRecord(AcmeClient.AcmeWebException ex, object targetObject = null)
        {
            // Resolve Error ID
            var errorId = "(n/a)";
            if ((bool)ex.Data?.Contains(nameof(errorId)))
                errorId = ex.Data[nameof(errorId)] as string;
            else if (ex.Response?.ProblemDetail != null)
                errorId = $"{ex.Response.ProblemDetail.Type} ({ex.Response.ProblemDetail.Status})";

            // Resolve Error Category
            var errorCategory = ErrorCategory.NotSpecified;
            var problemType = ex?.Response?.ProblemDetail?.Type;
            if ((bool)ex.Data?.Contains(nameof(errorCategory)))
                errorCategory = (ErrorCategory)ex.Data[nameof(errorCategory)];
            else if (PROBLEM_DETAIL_TYPE_TO_ERROR_CATEGORY.ContainsKey(problemType))
                errorCategory = PROBLEM_DETAIL_TYPE_TO_ERROR_CATEGORY[problemType];

            // Resolve any inner/deeper error message
            ErrorDetails errorDetails = null;
            if (!string.IsNullOrEmpty(ex.Response?.ProblemDetail?.Detail))
                errorDetails = new ErrorDetails(ex.Response.ProblemDetail.Detail);
            else if (ex.InnerException != null)
                errorDetails = new ErrorDetails(ex.InnerException.Message);

            return new ErrorRecord(ex, errorId, errorCategory, targetObject)
            {
                ErrorDetails = errorDetails
            };
        }
Пример #17
0
        /// <summary>
        /// Log message callback from ffmpeg library.
        /// </summary>
        /// <param name="p0">The p0.</param>
        /// <param name="level">The level.</param>
        /// <param name="format">The format.</param>
        /// <param name="vl">The vl.</param>
        private static unsafe void OnFFmpegMessageLogged(void *p0, int level, string format, byte *vl)
        {
            const int lineSize = 1024;

            lock (FFmpegLogBufferSyncLock)
            {
                if (level > ffmpeg.av_log_get_level())
                {
                    return;
                }
                var lineBuffer  = stackalloc byte[lineSize];
                var printPrefix = 1;
                ffmpeg.av_log_format_line(p0, level, format, vl, lineBuffer, lineSize, &printPrefix);
                var line = FFInterop.PtrToStringUTF8(lineBuffer);
                FFmpegLogBuffer.Add(line);

                var messageType = MediaLogMessageType.Debug;
                if (FFmpegLogLevels.ContainsKey(level))
                {
                    messageType = FFmpegLogLevels[level];
                }

                if (line.EndsWith("\n"))
                {
                    line = string.Join(string.Empty, FFmpegLogBuffer);
                    line = line.TrimEnd();
                    FFmpegLogBuffer.Clear();
                    LogGlobal(messageType, line);
                }
            }
        }
Пример #18
0
        // Token: 0x06002CCF RID: 11471 RVA: 0x000ACAD0 File Offset: 0x000AACD0
        protected override void vmethod_2(BinaryReader reader, int version)
        {
            this.EstatePlantSettings = new Dictionary <Enum13, Class94>();
            this.BeanCombinations    = new List <Class322>();
            int num = reader.ReadInt32();

            for (int i = 0; i < num; i++)
            {
                Enum13  key   = (Enum13)reader.ReadByte();
                Class94 value = new Class94(reader);
                if (!this.EstatePlantSettings.ContainsKey(key))
                {
                    this.EstatePlantSettings.Add(key, value);
                }
            }
            this.PlantMethod = (Enum115)reader.ReadByte();
            num = reader.ReadInt32();
            ReadOnlyDictionary <int, Class322> readOnlyDictionary_ = Class322.readOnlyDictionary_0;

            for (int j = 0; j < num; j++)
            {
                int key2 = reader.ReadInt32();
                if (readOnlyDictionary_.ContainsKey(key2))
                {
                    this.BeanCombinations.Add(readOnlyDictionary_[key2]);
                }
            }
            base.vmethod_2(reader, version);
        }
Пример #19
0
        public void TestConstructBaseDictionaryChanged()
        {
            var basedic = new Dictionary<string, string>() {
            {"key1", "val1"},
            {"key2", "val2"},
            {"key3", "val3"},
              };
              var dic = new ReadOnlyDictionary<string, string>(basedic);

              Assert.IsTrue(dic.IsReadOnly);
              Assert.IsTrue(dic.ContainsKey("key1"));
              Assert.IsFalse(dic.ContainsKey("key4"));

              basedic.Add("key4", "val4");

              Assert.IsTrue(dic.ContainsKey("key4"));
        }
Пример #20
0
        static CurrencyInfo()
        {
            var fractualCurrencySymbols = new ReadOnlyDictionary <string, FractionInfo>(new Dictionary <string, FractionInfo> {
                { "£", new FractionInfo("penny", "p", 100) }
            });
            var currencies = new Dictionary <string, CurrencyInfo>()
            {
                { "USD", new CurrencyInfo {
                      Name = "US Dollar", NativeName = "United States, Dollar", ISOSymbol = "USD", Symbol = "$", Fraction = new FractionInfo("cent", "¢", 100)
                  } },
                { "EUR", new CurrencyInfo {
                      Name = "Euro", NativeName = "Euro Member Countries, Euro", ISOSymbol = "EUR", Symbol = "€", Fraction = new FractionInfo("cent", "c", 100), AlignRight = true
                  } },
                { "GBP", new CurrencyInfo {
                      Name = "British Pound", NativeName = "United Kingdom, Pound", ISOSymbol = "GBP", Symbol = "£", Fraction = new FractionInfo("penny", "p", 100)
                  } }
            };
            var symbols = currencies.Values.Select(c => c.Symbol).ToList();

            foreach (var country in CountryInfo.Countries)
            {
                try {
                    var region = new RegionInfo(country.TwoLetterCode);
                    if (!currencies.ContainsKey(region.ISOCurrencySymbol))
                    {
                        var currency = currencies[region.ISOCurrencySymbol] = new CurrencyInfo()
                        {
                            Name       = region.EnglishName,
                            NativeName = region.DisplayName,
                            ISOSymbol  = region.ISOCurrencySymbol,
                            Symbol     = region.CurrencySymbol,
                            Fraction   = fractualCurrencySymbols.ContainsKey(region.CurrencySymbol) ? fractualCurrencySymbols[region.CurrencySymbol] : new FractionInfo("cent", "c", 100),
                        };
                        symbols.Add(currency.Symbol);
                        if (!fractualCurrencySymbols.ContainsKey(region.CurrencySymbol))
                        {
                            symbols.Add(currency.Fraction.Symbol);
                        }
                    }
                } catch {
                    ;
                }
            }
            Currencies      = currencies.Values.OrderByDescending(ci => ci.IsCommon).ThenBy(ci => ci.IsCommon ? "0" : ci.Name).ToArray();
            CurrencySymbols = new HashSet <string>(symbols.Distinct());
        }
Пример #21
0
 /// <summary>
 /// Gets the annotation with the specified id.
 /// </summary>
 /// <param name="id">The identifier.</param>
 /// <returns>The <see cref="BratAnnotation"/> object or null if the key does no exist in this document.</returns>
 public BratAnnotation GetAnnotation(string id)
 {
     if (annotationMap.ContainsKey(id))
     {
         return(annotationMap[id]);
     }
     return(null);
 }
Пример #22
0
 private char translateWithPlugboard(char c)
 {
     if (PlugboardDictionary.ContainsKey(c))
     {
         return(PlugboardDictionary[c]);
     }
     return(c);
 }
Пример #23
0
 public byte AttrTabSearch(char symbol)
 {
     if (attributes.ContainsKey(symbol))
     {
         return(attributes[symbol]);
     }
     return(5);
 }
Пример #24
0
        public bool ContainsRobot([NotNull] string robotName)
        {
            if (robotName == null)
            {
                throw new ArgumentNullException(nameof(robotName));
            }

            return(robotDescriptions.ContainsKey(robotName));
        }
Пример #25
0
		/// <summary>
		/// 次のレベルに上がるのに必要な経験値の量を取得します。
		/// </summary>
		/// <param name="expTable">経験値テーブル。</param>
		/// <param name="current">現在の累積経験値。</param>
		private static int GetNextExp( ReadOnlyDictionary<int, Experience> expTable, int current ) {

			Experience l = expTable.Values.FirstOrDefault( e => e.Total + e.Next > current );

			if ( l == null || !expTable.ContainsKey( l.Level + 1 ) )
				return 0;

			return expTable[l.Level + 1].Total - current;
		}
Пример #26
0
    public string TestVerbDictionaryWithNoum(ReadOnlyDictionary <string, string> verbDictionary, string verb, string noum)
    {
        if (verbDictionary.ContainsKey(noum))
        {
            return(verbDictionary[noum]);
        }

        return("You can't " + verb + " " + noum);
    }
Пример #27
0
        private Window CreateWindow(Type viewModel)
        {
            if (_navigationMap.ContainsKey(viewModel))
            {
                return(_navigationMap[viewModel].Invoke());
            }

            throw new NavigationNotFoundException(viewModel);
        }
Пример #28
0
        /**
         * Return the group belonging to a modal word
         * @param word
         * @return
         */
        public static GCodeGroups whatGroup(string word)
        {
            if (modalToGroup.ContainsKey(word))
            {
                return(modalToGroup[word]);
            }

            return(GCodeGroups.Default);
        }
        public static TValue?GetNullableValue <TKey, TValue>(this ReadOnlyDictionary <TKey, TValue> source, TKey key) where TValue : struct, IComparable
        {
            if (!source.ContainsKey(key))
            {
                return(null);
            }

            return(source[key]);
        }
Пример #30
0
        /// <summary>
        /// 指定したレベルに上がるのに必要な経験値の量を取得します。
        /// </summary>
        /// <param name="expTable">経験値テーブル。</param>
        /// <param name="current">現在の累積経験値。</param>
        /// <param name="level">対象のレベル。</param>
        private static int GetExpToLevel(ReadOnlyDictionary <int, Experience> expTable, int current, int level)
        {
            if (!expTable.ContainsKey(level))
            {
                return(0);
            }

            return(expTable[level].Total - current);
        }
Пример #31
0
        private static bool TryFindSecretPhrase(int numWordsInSentence,
                                                int numCharactersInAnagram,
                                                ReadOnlyDictionary <char, int> anagramCharCounts,
                                                ReadOnlyDictionary <int, string[]> wordCandidatesGroupedByLength,
                                                string secretPhraseMd5Hash,
                                                out string secretPhrase)
        {
            ReadOnlyCollection <ReadOnlyCollection <int> > wordLengthCombinations = GenerateWordLengthCombinations(numCharactersInAnagram, numWordsInSentence);

            string foundPhrase = null; // Alas, closures don't allow out parameters...

            Action <ReadOnlyCollection <int>, ParallelLoopState> TryFindPhrase = (wordLengthCombination, state) =>
            {
                if (wordLengthCombination.Any(wordLength => !wordCandidatesGroupedByLength.ContainsKey(wordLength)))
                {
                    return; // Failure
                }

                var initialCharacters = new CharacterPool(anagramCharCounts);

                LinkedList <string> sentences = FindSentencesWithWordLengths(wordLengthCombination, initialCharacters, wordCandidatesGroupedByLength);

                if (sentences.Any())
                {
                    foreach (string sentence in sentences)
                    {
                        IEnumerable <IEnumerable <string> > permutationsOfSentence = Math.FindPermutations(sentence.Split(), numWordsInSentence);

                        // Lazily traverse through all permutations of the sentence and exit immediately if we find the secret phrase.
                        foreach (IEnumerable <string> permutation in permutationsOfSentence)
                        {
                            if (state.IsStopped)
                            {
                                return; // Another task found the secret phrase
                            }

                            string permutationString = String.Join(" ", permutation.ToArray());
                            string candidateMd5Hash  = permutationString.ComputeMD5Hash().ConvertToHexString(useLowerCase: true);

                            if (candidateMd5Hash == secretPhraseMd5Hash)
                            {
                                foundPhrase = permutationString;
                                state.Stop();

                                return; // Success
                            }
                        }
                    }
                }
            };

            Parallel.ForEach(wordLengthCombinations, TryFindPhrase);
            secretPhrase = foundPhrase;

            return(secretPhrase != null);
        }
        public void TestContainsKey_KeyMissing_ReturnsFalse()
        {
            var dictionary = new ReadOnlyDictionary <int, int>(new Dictionary <int, int>()
            {
                { 1, 1 }
            });
            bool exists = dictionary.ContainsKey(2);

            Assert.IsFalse(exists, "The key should not have been found.");
        }
Пример #33
0
        public static int FrequencyScoreChar(char byteChar)
        {
            var c = char.ToLower(Convert.ToChar(byteChar));

            if (Frequency.ContainsKey(c))
            {
                return(Frequency[c]);
            }
            return(0);
        }
Пример #34
0
        public void ReadOnlyDictionary_Unit_ContainsKey_KeyDoesNotExist()
        {
            IDictionary<String, String> dictionary = new Dictionary<String, String>() {
                { "Key1", "Value1" },
                { "Key2", "Value2" },
                { "Key3", "Value3" }
            };
            ReadOnlyDictionary<String, String> target = new ReadOnlyDictionary<String, String>(dictionary);
            String key = "MyKey";

            Boolean actual = target.ContainsKey(key);
            Assert.AreEqual(false, actual);
        }
Пример #35
0
        public void ReadOnlyDictionary_Unit_ContainsKey_KeyIsNull()
        {
            IDictionary<String, String> dictionary = new Dictionary<String, String>() {
                { "Key1", "Value1" },
                { "Key2", "Value2" },
                { "Key3", "Value3" }
            };
            ReadOnlyDictionary<String, String> target = new ReadOnlyDictionary<String, String>(dictionary);
            String key = null;

            target.ContainsKey(key);
        }
Пример #36
0
        public void ReadOnlyDictionary_Unit_ContainsKey_Optimal()
        {
            IDictionary<String, String> dictionary = new Dictionary<String, String>() {
                { "Key1", "Value1" },
                { "Key2", "Value2" },
                { "Key3", "Value3" }
            };
            ReadOnlyDictionary<String, String> target = new ReadOnlyDictionary<String, String>(dictionary);
            String key = dictionary.Keys.First();

            Boolean actual = target.ContainsKey(key);
            Assert.AreEqual(true, actual);
        }
Пример #37
0
        public void TestReadOperations()
        {
            var dic = new ReadOnlyDictionary<string, string>(new Dictionary<string, string>() {
            {"key1", "val1"},
            {"key2", "val2"},
            {"key3", "val3"},
              });

              Assert.AreEqual(3, dic.Count);

              Assert.AreEqual("val1", dic["key1"]);
              Assert.IsTrue(dic.Contains(new KeyValuePair<string, string>("key2", "val2")));
              Assert.IsTrue(dic.ContainsKey("key3"));

              foreach (var pair in dic) {
              }

              foreach (var key in dic.Keys) {
              }

              foreach (var val in dic.Values) {
              }

              var pairs = new KeyValuePair<string, string>[3];

              dic.CopyTo(pairs, 0);

              string outval = null;

              Assert.IsTrue(dic.TryGetValue("key1", out outval));
              Assert.AreEqual(outval, "val1");
        }
Пример #38
0
        /// <summary>
        /// Takes a snapshot of the child signals before making a change, then makes the change, then takes another
        /// snapshot, does a comparison, and fires a signal changed event for any signals that are different.
        /// </summary>
        /// <param name="act">Action that does changes to the tree</param>
        public void NotifySignals(Action act)
        {
            var oldChildren = new ReadOnlyDictionary<FieldGuid, NodeBase>(new Dictionary<FieldGuid, NodeBase>());
            if (Node != null)
            {
                oldChildren = Node.GetChildrenRecursive();
            }

            act();

            var newChildren = new ReadOnlyDictionary<FieldGuid, NodeBase>(new Dictionary<FieldGuid, NodeBase>());
            if (Node != null)
            {
                newChildren = Node.GetChildrenRecursive();
            }

            foreach (var newChildKey in newChildren.Keys)
            {
                if (!oldChildren.ContainsKey(newChildKey))
                {
                    // it's an edited node
                    var sig = newChildren[newChildKey] as NodeSignal;
                    runtimeService.NotifySignalChanged(sig);
                }
            }
        }
Пример #39
0
		private static FileInfo[] GetFileInfo(ReadOnlyDictionary<long, ReadOnlyCollection<FileInfo>> names, long awbId)
		{
			return names != null && names.ContainsKey(awbId) ? names[awbId].ToArray() : null;
		}
Пример #40
0
		/// <summary>
		/// 指定したレベルに上がるのに必要な経験値の量を取得します。
		/// </summary>
		/// <param name="expTable">経験値テーブル。</param>
		/// <param name="current">現在の累積経験値。</param>
		/// <param name="level">対象のレベル。</param>
		private static int GetExpToLevel( ReadOnlyDictionary<int, Experience> expTable, int current, int level ) {

			if ( !expTable.ContainsKey( level ) )
				return 0;

			return expTable[level].Total - current;
		}
Пример #41
0
    IDisposable key_correlator_replay(DDS.DomainParticipant participant, bool useLinq)
    {
        int MAX_COLORS = 8;

        var rx_square_reader =
        DDSObservable.FromKeyedTopic<string, ShapeTypeExtended>(participant, "Square", shape => shape.color);

        var dictionary = new Dictionary<string, string>();
        dictionary.Add("PURPLE", "BLUE");
        dictionary.Add("RED", "GREEN");
        dictionary.Add("YELLOW", "CYAN");
        dictionary.Add("MAGENTA", "ORANGE");

        var associations = new ReadOnlyDictionary<string, string>(dictionary);

        var cache = rx_square_reader.Replay();
        cache.Connect();

        if (useLinq)
        {
          return
          (from group1 in cache.Where(groupedSq => associations.ContainsKey(groupedSq.Key))
           from group2 in cache.Take(MAX_COLORS)
           where associations[group1.Key] == group2.Key
           select new { k1 = group1, k2 = group2 })
            .Subscribe(pair =>
            {
              Console.WriteLine("MATCH {0}--{1}", pair.k1.Key, pair.k2.Key);
              pair.k1.CombineLatest(pair.k2,
                                   (a, b) =>
                                   {
                                     return new ShapeTypeExtended
                                     {
                                       x = (int)((a.x + b.x) / 2),
                                       y = (int)((a.y + b.y) / 2),
                                       color = a.color,
                                       shapesize = a.shapesize
                                     };
                                   })
                     .Subscribe(triangle_writer);
            });
        }
        else
        {
          return
        cache
           .Where(groupedSq => associations.ContainsKey(groupedSq.Key))
           .SelectMany(groupedSq => cache.Take(MAX_COLORS),
                      (groupedSq, cached_groupedSq) =>
                      {
                        if (associations[groupedSq.Key] == cached_groupedSq.Key)
                        {
                          Console.WriteLine("MATCH {0} -- {1}", groupedSq.Key, cached_groupedSq.Key);
                          groupedSq
                            .CombineLatest(cached_groupedSq,
                                          (a, b) =>
                                          {
                                            return new ShapeTypeExtended
                                            {
                                              x = (int)((a.x + b.x) / 2),
                                              y = (int)((a.y + b.y) / 2),
                                              color = a.color,
                                              shapesize = a.shapesize
                                            };
                                          })
                            .Subscribe(triangle_writer);
                        }
                        else
                          Console.WriteLine("NO-MATCH {0} -- {1}", groupedSq.Key, cached_groupedSq.Key);

                        return (IGroupedObservable<string, ShapeTypeExtended>)groupedSq;
                      }).Subscribe();
        }
    }
Пример #42
0
        private static void TryMinifyNumberWithUnit(NumberWithUnitValue value, ReadOnlyDictionary<Unit, decimal> possibleConversions, ref NumberWithUnitValue smallest)
        {
            if (!possibleConversions.ContainsKey(value.Unit)) return;

            var min = MinifyNumberValue(value);

            var ret = new NumberWithUnitValue(min.Value, value.Unit);
            string retStr;
            using (var buffer = new StringWriter())
            {
                ret.Write(buffer);
                retStr = buffer.ToString();
            }

            var inBasic = min.Value * possibleConversions[value.Unit];

            foreach (var unit in possibleConversions.Keys)
            {
                var conversion = possibleConversions[unit];

                var maxPrecision = inBasic / conversion;

                // 5 decimal points seems like an acceptable level of precision; webkit seems to agree
                var inUnit = decimal.Round(maxPrecision, 5);

                var asNum = new NumberValue(inUnit);
                var minified = MinifyNumberValue(asNum);

                var newMin = new NumberWithUnitValue(minified.Value, unit);
                string newMinStr;

                using (var buffer = new StringWriter())
                {
                    newMin.Write(buffer);
                    newMinStr = buffer.ToString();
                }

                if (newMinStr.Length < retStr.Length)
                {
                    ret = newMin;
                    retStr = newMinStr;
                }
            }

            smallest = ret;
        }
Пример #43
0
 public static void ThrowIfNotFound(ReadOnlyDictionary<string, string> dictionary, string data, string key)
 {
     if (dictionary.ContainsKey(key))
         return;
     throw new KeyNotFoundException($"The key '{key}' is missing in '{data}'");
 }
Пример #44
0
 private static void TryAdd(ReadOnlyDictionary<string, string> dictionary, List<string> parts, string key)
 {
     if (dictionary.ContainsKey(key))
         parts.Add(dictionary[key]);
 }