Ejemplo n.º 1
0
        private async Task <DictionaryResult> Search(string word, LanguagePair languagePair, CultureInfo culture)
        {
            word = word.ToLower(culture);

            DictionaryEntry entry = SearchOffline(word, languagePair);

            if (entry != null)
            {
                return(entry.Result);
            }

            DictionaryResult result = await SearchOnline(word, languagePair, culture).ConfigureAwait(false);

            if (result?.Definitions?.Length > 0)
            {
                return(result);
            }

            string correction = await YandexService.Correct(word, languagePair.InputLanguage).ConfigureAwait(false);

            if (!String.IsNullOrWhiteSpace(correction) && String.Compare(word, correction, true, culture) != 0)
            {
                return(await Search(correction, languagePair, culture).ConfigureAwait(false));
            }

            return(null);
        }
Ejemplo n.º 2
0
        public async Task <SearchResult[]> Search(string word, CultureInfo inputCulture, CultureInfo outputCulture)
        {
            if (word.IsNonAlpha())
            {
                return(null);
            }

            word = word.SingleWhiteSpace();

            if (word.Length < 2 || word.Length > 25)
            {
                return(null);
            }

            LanguagePair     languagePair     = CreateLangPair(inputCulture, outputCulture);
            DictionaryResult dictionaryResult = await Search(word, languagePair, inputCulture).ConfigureAwait(false);

            return(dictionaryResult?.Definitions?.Select(x => new SearchResult
            {
                Word = x.Word,
                WordClass = x.WordClass,
                Inflections = x.Inflections,
                Definition = x.GetTranslations()
            }).ToArray());
        }
Ejemplo n.º 3
0
        private async Task <DictionaryResult> SearchOnline(string word, LanguagePair languagePair, CultureInfo culture)
        {
            DictionaryResult result = await YandexService.Lookup(word, languagePair).ConfigureAwait(false);

            if (result?.Definitions?.Length > 0)
            {
                string          returnedWord = result.Definitions[0].Word.ToLower(culture);
                DictionaryEntry entry        = SearchOffline(returnedWord, languagePair);
                if (entry != null)
                {
                    entry.Variations += word + "|";
                    Dictionary.Update(entry);
                }
                else
                {
                    entry          = new DictionaryEntry();
                    entry.Word     = returnedWord;
                    entry.Result   = result;
                    entry.Language = languagePair.ToString();

                    if (String.Compare(word, returnedWord, true, culture) != 0)
                    {
                        entry.Variations += word + "|";
                    }

                    Dictionary.Insert(entry);
                }
            }

            return(result);
        }
Ejemplo n.º 4
0
        private async Task <DictionaryResult> SearchOnline(string word, LanguagePair languagePair, CultureInfo culture)
        {
            DictionaryResult result = await YandexService.Lookup(word, languagePair).ConfigureAwait(false);

            if (result != null && result.Definitions != null && result.Definitions.Length > 0)
            {
                string           returnedWord = result.Definitions[0].Word.ToLower(culture);
                DictionaryEntity entity       = SearchOffline(returnedWord, languagePair);
                if (entity != null)
                {
                    entity.Variations += word + "|";
                    entity.Save();
                }
                else
                {
                    entity            = new DictionaryEntity(UnitOfWork);
                    entity.Word       = returnedWord;
                    entity.Definition = result.ToJson();
                    entity.Language   = languagePair.ToString();

                    if (String.Compare(word, returnedWord, true, culture) != 0)
                    {
                        entity.Variations += word + "|";
                    }

                    entity.Save();
                }

                UnitOfWork.CommitChanges();
            }

            return(result);
        }
 public static DictionaryResult <TValue> TryGet <TKey, TValue>(this IDictionary <TKey, TValue> dict, TKey key)
 {
     if (dict.TryGetValue(key, out var val))
     {
         return(DictionaryResult <TValue> .Found(val));
     }
     return(DictionaryResult <TValue> .NotFound());
 }
        protected void SendDictionaryResult(Dictionary <string, string> dict)
        {
            var result = new DictionaryResult()
            {
                Id      = this.Id,
                Results = dict
            };

            Send(result);
        }
Ejemplo n.º 7
0
        private void GenerateWords(IDictionaryRequest request, PartitionInfo partitionInfo)
        {
            var partitionedWords = new ConcurrentQueue <IDictionary <int, IGeneratedWord> >();
            var useNoise         = dictionaryConfiguration.UseNoise;
            var startTime        = DateTime.Now;

            maxValue = dictionary.WordList.Count;

            FireGenerateChanged(new ProgressChangedEventArgs(10, String.Empty));

            // Multi-Threaded block
            var tasks = new Task[partitionInfo.NumberOfPartitions];
            var index = 0;

            for (; index < partitionInfo.NumberOfPartitions; index++)
            {
                tasks[index] = Task.Run(() =>
                {
                    var iterations = index == partitionInfo.NumberOfPartitions - 1 ?
                                     partitionInfo.LastPartitionSize :
                                     partitionInfo.FullPartitionSize;

                    var wordsPartition = useNoise ?
                                         GeneratePartitionedWordsWithNoise(iterations) :
                                         GeneratePartitionedWords(iterations);

                    partitionedWords.Enqueue(wordsPartition);
                });
            }

            try
            {
                Task.WaitAll(tasks);

                var words = new WordContainer(dictionaryConfiguration.UseNoise)
                {
                    PartitionedWords = partitionedWords
                };

                var endTime  = DateTime.Now;
                var duration = endTime - startTime;

                var result = new DictionaryResult(request, duration, words)
                {
                    Words = words
                };

                FireGenerateChanged(new ProgressChangedEventArgs(100, null));
                FireGenerateCompleted(new DictionaryEventArgs(null, false, null, result));
            }
            catch (AggregateException ae)
            {
                FireGenerateCompleted(new DictionaryEventArgs(ae.Flatten(), false, ae, null));
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Adds the dictionary node.
        /// </summary>
        /// <param name="keyValuePair">The key value pair.</param>
        /// <param name="nodesSource">The nodes source.</param>
        /// <param name="nodesDestionation">The nodes destionation.</param>
        private void AddDictionaryNode(KeyValuePair <string, DictionaryResult> keyValuePair, TreeNodeCollection nodesSource, TreeNodeCollection nodesDestionation)
        {
            DictionaryResult dictionaryResult = keyValuePair.Value;

            TreeNode destionationNode = AddDictionaryNode(keyValuePair.Key, dictionaryResult.IsEquals, nodesDestionation);
            TreeNode sourceNode       = AddDictionaryNode(keyValuePair.Key, dictionaryResult.IsEquals, nodesSource);



            foreach (string key in dictionaryResult.Keys)
            {
                DictionaryEntryResult dictionaryEntryResult = dictionaryResult[key];

                AddObjectResult(dictionaryEntryResult.ResultType, dictionaryEntryResult.ObjectResult, sourceNode.Nodes, destionationNode.Nodes);
            }
        }
Ejemplo n.º 9
0
        public void DictionaryNotEqualItemTest()
        {
            CompareObject destination = GetObject();

            destination.NestedObjects["Nested2"].IntValue = 444;
            ObjectResult result = (ObjectResult)conf.Compare(typeof(CompareObject), GetObject(), destination);

            Assert.IsNotNull(result);
            Assert.IsFalse(result.IsEquals);

            Assert.IsTrue(result.Results["Name"].IsEquals);
            Assert.IsTrue(result.Results["LinkedObject"].IsEquals);

            Assert.IsFalse(result.Results["NestedObjects"].IsEquals);

            DictionaryResult dictionaryResult = result.Results["NestedObjects"] as DictionaryResult;

            Assert.AreEqual(dictionaryResult["Nested1"].ResultType, ResultType.Equal);
            Assert.AreEqual(dictionaryResult["Nested2"].ResultType, ResultType.NotEqual);
        }
Ejemplo n.º 10
0
        public void EqualTest()
        {
            var result = (ObjectResult)conf.Compare(typeof(CompareObject), GetObject(), GetObject());

            Assert.IsNotNull(result);
            Assert.IsTrue(result.IsEquals);

            Assert.IsTrue(result.Results["Name"].IsEquals);
            Assert.IsTrue(result.Results["LinkedObject"].IsEquals);
            Assert.IsTrue(result.Results["NestedObjects"].IsEquals);

            DictionaryResult dictionaryResult = result.Results["NestedObjects"] as DictionaryResult;

            Assert.AreEqual(dictionaryResult["Nested1"].ResultType, ResultType.Equal);
            Assert.AreEqual(dictionaryResult["Nested2"].ResultType, ResultType.Equal);

            KeyEnumerableResult enumerableResult = result.Results["KeyObjects"] as KeyEnumerableResult;

            Assert.AreEqual(enumerableResult["1"].ResultType, ResultType.Equal);
            Assert.AreEqual(enumerableResult["2"].ResultType, ResultType.Equal);
        }
Ejemplo n.º 11
0
        public void DictionaryNewItemTest()
        {
            CompareObject source = GetObject();

            source.NestedObjects.Add("New object", new NestedObject("New object", 3));

            ObjectResult result = (ObjectResult)conf.Compare(typeof(CompareObject), source, GetObject());

            Assert.IsNotNull(result);
            Assert.IsFalse(result.IsEquals);

            Assert.IsTrue(result.Results["Name"].IsEquals);
            Assert.IsTrue(result.Results["LinkedObject"].IsEquals);

            Assert.IsFalse(result.Results["NestedObjects"].IsEquals);

            DictionaryResult dictionaryResult = result.Results["NestedObjects"] as DictionaryResult;

            Assert.AreEqual(dictionaryResult["Nested1"].ResultType, ResultType.Equal);
            Assert.AreEqual(dictionaryResult["Nested2"].ResultType, ResultType.Equal);
            Assert.AreEqual(dictionaryResult["New object"].ResultType, ResultType.New);
        }
Ejemplo n.º 12
0
        public void DictionaryDeleteItemTest()
        {
            var source      = GetObject();
            var destination = GetObject();

            destination.NestedObjects.Add("New object", new NestedObject("New object", 3));

            var result = (ObjectResult)conf.Compare(typeof(CompareObject), source, destination);

            Assert.IsNotNull(result);
            Assert.IsFalse(result.IsEquals);

            Assert.IsTrue(result.Results["Name"].IsEquals);
            Assert.IsTrue(result.Results["LinkedObject"].IsEquals);

            Assert.IsFalse(result.Results["NestedObjects"].IsEquals);

            DictionaryResult dictionaryResult = result.Results["NestedObjects"] as DictionaryResult;

            Assert.AreEqual(dictionaryResult["Nested1"].ResultType, ResultType.Equal);
            Assert.AreEqual(dictionaryResult["Nested2"].ResultType, ResultType.Equal);
            Assert.AreEqual(dictionaryResult["New object"].ResultType, ResultType.Delete);
        }
    public static DictionaryResult <T> Found(T value)
    {
        var result = new DictionaryResult <T>(value);

        return(result);
    }
Ejemplo n.º 14
0
 private void APICallSucceed(DictionaryResult entry)
 {
     Debug.Log(entry.outputs[0].output);
     question.text = entry.outputs[0].output;
 }
        protected void SendDictionaryResult(Dictionary<string, string> dict)
        {
            var result = new DictionaryResult()
                {
                    Id = this.Id,
                    Results = dict
                };

            Send(result);
        }
Ejemplo n.º 16
0
        public async Task Dictionary(string word)
        {
            string url = $"https://od-api.oxforddictionaries.com:443/api/v1/entries/en/{word.ToLower ()}";

            string json = await FetchJson(url);

            if (string.IsNullOrEmpty(json))
            {
                return;
            }
            DictionaryData data = DictionaryData.FromJson(json);

            string           finalMessage = string.Empty;
            bool             hasData      = false;
            DictionaryResult result       = data.Results [0];

            finalMessage += $"**{result.Word.ToUpper ()}**\n";

            if (result.LexicalEntries [0].Pronunciations != null)
            {
                finalMessage += $"/{result.LexicalEntries [0].Pronunciations [0].PhoneticSpelling}/\n\n";
                hasData       = true;
            }

            foreach (DictionaryLexicalEntry lexicalEntry in result.LexicalEntries ?? Enumerable.Empty <DictionaryLexicalEntry> ())
            {
                finalMessage += $"**{lexicalEntry.LexicalCategory.UppercaseFirst ()}**\n";
                foreach (DictionaryEntry entry in lexicalEntry.Entries ?? Enumerable.Empty <DictionaryEntry> ())
                {
                    for (int j = 0; j < entry.Senses.Length; j++)
                    {
                        DictionarySense sense = entry.Senses [j];
                        foreach (string definition in sense.Definitions ?? Enumerable.Empty <string> ())
                        {
                            finalMessage += $"{j + 1}. {definition.UppercaseFirst ()}\n";
                            hasData       = true;
                        }
                        foreach (DictionaryExample example in sense.Examples ?? Enumerable.Empty <DictionaryExample> ())
                        {
                            finalMessage += $"    {example.Text.UppercaseFirst ()}\n";
                            hasData       = true;
                        }
                        finalMessage += "\n";
                    }
                }
            }

            if (finalMessage.Length >= 2000 && hasData)
            {
                IEnumerable <string> messages = finalMessage.SplitEveryNth(2000);
                foreach (string message in messages)
                {
                    await ReplyAsync(message);
                }
                return;
            }
            else if (hasData)
            {
                await ReplyAsync(finalMessage);
            }
            else
            {
                await ReplyAsync($"No data found for: {word}.");
            }
        }