Пример #1
0
        public async Task <IActionResult> Edit(int id, [Bind("ID,English,Japanese,Pronunciation,Definition,Notes,Category,Synonyms,Example,System")] WordModel wordModel)
        {
            if (id != wordModel.ID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(wordModel);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!WordModelExists(wordModel.ID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(wordModel));
        }
Пример #2
0
        public WordModel CheckWord(ref IEnumerable <WordModel> wordModels, string secretText, string letterOrWord, Guid userId)
        {
            var words = wordModels.ToList();

            if (words.Count > 0)
            {
                //слово которое нужно угадать
                var word = new WordModel {
                    SecretWord = words[0].SecretWord, TryCount = words[0].TryCount, Question = words[0].Question, Id = words[0].Id
                };

                //Создается новый матч (игра)
                var match = new Match
                {
                    Id     = Guid.NewGuid(),
                    UserId = userId,
                    WordId = word.Id,
                };

                word = CheckWordSecondary(word, secretText, letterOrWord);

                //если выиграл возвращает null
                if (word == null)
                {
                    //стирает угаданное слово из списка вопросов , что бы не повторялось
                    words.RemoveAt(0);
                    match.Result = true;
                    unitOfWork.Match.Add(match);
                    unitOfWork.SaveChangesAsync();

                    if (words.Count > 0)
                    {
                        wordModels = words;
                        return(GetSecretWord(new WordModel {
                            Question = wordModels.First().Question, SecretWord = wordModels.First().SecretWord, TryCount = wordModels.First().TryCount
                        }));
                    }

                    return(null);
                }
                else
                {
                    if (word.IsLose)
                    {
                        //lose
                        match.Result = false;
                        unitOfWork.Match.Add(match);
                        unitOfWork.SaveChangesAsync();
                        throw new ArgumentOutOfRangeException();
                    }
                    else
                    {
                        words[0].TryCount = word.TryCount;
                        return(word);
                    }
                }
            }

            return(null);
        }
Пример #3
0
 public void AddWord(WordModel wordModel)
 {
     context.Words.Add(new Words {
         WordId = wordModel.WordId, Word = wordModel.Word, Definition = wordModel.Definition, Etymology = wordModel.Etymology
     });
     context.SaveChanges();
 }
Пример #4
0
        public async Task <int> AddWord(WordModel model)
        {
            using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                int origWordId = await wordService.AddAsync(model);

                if (model.Translations != null && model.Translations.Count > 0)
                {
                    List <int> translationIds = await CreateNonExistingWords(model.Translations, model.TranslationLanguageId);

                    await wordTranslationService.AddIdRangeAsync(origWordId, translationIds, model.OwnerId);
                }

                if (model.Synonyms != null && model.Synonyms.Count > 0)
                {
                    List <int> synonymIds = await CreateNonExistingWords(model.Synonyms, model.LanguageId);

                    await wordTranslationService.AddIdRangeAsync(origWordId, synonymIds, model.OwnerId);
                }

                if (model.Tags != null && model.Tags.Count > 0)
                {
                    List <int> tagIds = await CreateNonExistingTags(model.Tags);

                    await tagService.AddRangeToWordAsync(origWordId, tagIds);
                }

                transaction.Complete();
                return(origWordId);
            }
        }
Пример #5
0
        public async Task <IActionResult> Edit(long id, [Bind("WordId,Title,WordName")] WordModel wordModel)
        {
            if (id != wordModel.WordId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(wordModel);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!WordModelExists(wordModel.WordId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(wordModel));
        }
        //constructor for viewmodel takes in user word for search
        public OtherViewModel(String input)
        {
            wordmodel = new WordModel(); //instantiate wordModel
            var wordInput = input;

            LoadData(wordInput); //passes user input to LoadData method
        }
Пример #7
0
        private void SetupAnomaly(ContainerBuilder builder)
        {
            logger.LogInformation("Setting up lexicon libraries");
            var tagger = new NaivePOSTagger(new BNCList(), WordTypeResolver.Instance);

            builder.RegisterInstance(tagger).As <IPOSTagger>();

            var dictionary = new NRCDictionary();

            dictionary.Load();
            builder.RegisterInstance(dictionary).As <INRCDictionary>();

            var inquirer = new InquirerManager();

            inquirer.Load();
            builder.RegisterInstance(inquirer).As <IInquirerManager>();

            builder.RegisterType <FrequencyListManager>().As <IFrequencyListManager>().SingleInstance();
            builder.RegisterType <StyleFactory>().As <IStyleFactory>();
            builder.RegisterType <AnomalyFactory>().As <IAnomalyFactory>();
            builder.RegisterType <SupervisedAnomaly>().As <ISupervisedAnomaly>();
            builder.RegisterType <DocumentReconstructor>().As <IDocumentReconstructor>();
            builder.RegisterType <DocumentExtractor>().As <IDocumentExtractor>();

            builder.RegisterType <EmbeddingVectorSource>().As <IDocumentVectorSource>();
            builder.RegisterType <SvmModelStorageFactory>().As <IModelStorageFactory>();

            logger.LogInformation("Downloading model...");
            var model = new Uri(Configuration["Anomaly:model"]);

            new DataDownloader(loggerFactory).DownloadFile(model, "resources").Wait();
            builder.Register(context => WordModel.Load("resources/model.bin")).SingleInstance();
        }
Пример #8
0
 /// <summary>
 /// It reads the Spellings-Puzzle App-Template, from the .buildmlearn file.
 /// </summary>
 /// <param name="fileName">Name of the file</param>
 public static void readSpellingsFile(string fileName)
 {
     try
     {
         SpellingsModel   model    = SpellingsModel.getInstance();
         List <WordModel> wordList = new List <WordModel>();
         XmlDocument      doc      = new XmlDocument();
         doc.LoadXml(XDocument.Load("Assets/Apps/" + fileName + ".xml").ToString());
         model.setPuzzleName(doc.GetElementsByTagName("title").ElementAt(0).InnerText.Trim());
         model.setPuzzleDescription(doc.GetElementsByTagName("description").ElementAt(0).InnerText.Trim());
         string[] author = doc.GetElementsByTagName("author").ElementAt(0).InnerText.Split('\n');
         model.setPuzzleAuthor(author[1].Trim());
         model.setPuzzleAuthorEmail(author[2].Trim());
         model.setPuzzleVersion(doc.GetElementsByTagName("version").ElementAt(0).InnerText.Trim());
         XmlNodeList item = doc.GetElementsByTagName("item");
         // looping through all item nodes <app>
         for (int i = 0; i < item.Length; i++)
         {
             string[]  ar   = item.ElementAt(i).InnerText.Split('\n');
             WordModel word = new WordModel(ar[1].Trim(), ar[2].Trim());
             wordList.Add(word);
         }
         model.setSpellingsList(wordList);
     }
     catch (Exception) { }
 }
Пример #9
0
        public ActionResult Words(WordModel word)
        {
            ClearAlerts("Alert Words M", 3);

            // get the list of words from Session
            List <WordModel> words = getWords();

            // we'll need to validate the data
            if (words.Exists(w => w.Text == word.Text))
            {
                Session.Add("Alert Words M2", "Word already exists. Please use a distinct text.");
                return(View());
            }

            // we need to add the word to the database first to get the Id
            word.Id = WordProcessor.CreateWord(word.Text, (int)Session["Language"], word.ClassificationId, word.Description, word.Pronounciation);
            words.Add(word);

            // lastly, we'll need to clear the values in the fields
            ModelState.SetModelValue("Text", new ValueProviderResult("", "", ModelState["Text"].Value.Culture));
            ModelState.SetModelValue("Description", new ValueProviderResult("", "", ModelState["Description"].Value.Culture));
            ModelState.SetModelValue("Pronounciation", new ValueProviderResult("", "", ModelState["Pronounciation"].Value.Culture));

            return(View());
        }
Пример #10
0
        public HashSet <WordModel> GetWords()
        {
            _wordList = new HashSet <WordModel>();


            Environment.CurrentDirectory = target;

            using (StreamReader sr = new StreamReader($@"{target}/zodynas.txt"))
            {
                string line;
                while (sr.Peek() >= 0)
                {
                    line = sr.ReadLine().Trim();
                    string[]  words = line.Split(new[] { '\t' });
                    WordModel word1 = new WordModel(words[0]);
                    WordModel word2 = new WordModel(words[2]);

                    if (!_wordList.Contains(word1))
                    {
                        _wordList.Add(word1);
                    }

                    if (!_wordList.Contains(word2))
                    {
                        _wordList.Add(word2);
                    }
                }
            }

            return(_wordList);
        }
Пример #11
0
        public WordModel CheckWord(string wordValue, Guid userId)
        {
            WordModel model = null;

            var words = context.Words.Include("Translations").Include("Translations.LanguageAccessory").Where(m => m.WordValue == wordValue);

            this.RegistrationUserActivity(userId);

            if (words.Any())
            {
                var word = words.First();
                model = new WordModel()
                {
                    WordValue     = wordValue,
                    Probabilities = new List <TranslationModel>(word.Translations
                                                                .Select(m => new TranslationModel()
                    {
                        Language    = m.LanguageAccessory.Name,
                        Probability = m.Probability
                    }))
                };
            }

            return(model);
        }
Пример #12
0
        public void AddResult(string wordhash, int result, int note, int time)
        {
            WordModel actual = _repo.GetWord(wordhash);

            actual.LastAccess = DateTime.Now;
            if (actual.ReactionTime > 0)
            {
                actual.ReactionTime = (actual.ReactionTime + time) / 2;
            }
            else
            {
                actual.ReactionTime = time;
            }

            if (result == 1)
            {
                actual.Goods++;
            }
            else
            {
                actual.Bads++;
            }
            actual.Note = note;
            _repo.EditWord(actual);
        }
Пример #13
0
        private string WordMeaningStr(WordModel word)
        {
            var wordTypeStr = "";

            switch (word.WordType)
            {
            case 1:
                wordTypeStr = "(noun) ";
                break;

            case 2:
                wordTypeStr = "(verb) ";
                break;

            case 3:
                wordTypeStr = "(adj) ";
                break;

            case 4:
                wordTypeStr = "(adv) ";
                break;

            case 5:
                wordTypeStr = "(idiom) ";
                break;

            default:
                wordTypeStr = "";
                break;
            }
            return(wordTypeStr + word.Meaning);
        }
Пример #14
0
        public async void add_keys_should_create_new_word_and_return_bool()
        {
            //arrange
            var validModel = new WordModel
            {
                Key         = "key",
                Tag         = "tag",
                Description = "desc"
            };
            var wordService = new Mock <IWordService>();

            wordService.Setup(x => x.Create(validModel)).Returns(Task.FromResult(validModel.Key));

            //act
            var sut = new ApiControllerBuilder().WithWordService(wordService.Object)
                      .Build();

            var result = await sut.AddKeys(validModel.Key, validModel.Tag);

            //assert
            Assert.NotNull(result);
            Assert.NotNull(result.Data);
            Assert.IsAssignableFrom(typeof(bool), result.Data);

            sut.AssertPostAttribute(ActionNameAddKeys, new[] { typeof(string), typeof(string) });

            wordService.Verify(x => x.Create(It.IsAny <WordModel>()), Times.AtLeastOnce);
        }
        public void TestLoadingTextInAnotherCulture()
        {
            CultureInfo.DefaultThreadCurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR");
            var model = WordModel.Load(GetPath("model.txt"));

            TestLoadedModel(model);
        }
        protected void VariantMouseLeftDown(object sender, EventArgs e)
        {
            WordModel choosen = GetChoosenWordModel((sender as Border).Tag);

            VariantClick(sender, choosen.Translate, answer.Translate, choosen.WordId);
            win.Variant_MouseLeftButtonDown -= new EventHandler(VariantMouseLeftDown);
        }
Пример #17
0
        public void Search_API_Lookup_Test()
        {
            // Arrange
            IDingDb db          = new DingDbTest();
            var     mockService = new Mock <ILookupService>();

            mockService.Setup(x => x.DbLookup(It.IsAny <string>())).Returns((string x) => { return(null); });
            mockService.Setup(x => x.APILookup(It.IsAny <string>())).Returns((string x) => { return(new WordModel()
                {
                    word = "api-test", definitions = "api test definition"
                }); });
            SearchController controller = new SearchController(mockService.Object);
            WordModel        testWord   = new WordModel {
                word = "api-test", definitions = "api test definition"
            };                                                                                             //expected result from mocked Dictionary API call
            //int expectedCount = 6; //5 initial entries + intel = 6 entries


            // Act
            ViewResult result     = controller.Search("api-test") as ViewResult;
            WordModel  resultWord = result.Model as WordModel;

            //int testCount = db.Query<WordModel>().Count();


            // Assert
            Assert.IsNotNull(resultWord);
            Assert.AreEqual(testWord.word, resultWord.word);
            Assert.AreEqual(testWord.definitions, resultWord.definitions);
            //Assert.AreEqual(expectedCount, testCount);
        }
Пример #18
0
        public void Init()
        {
            gameConfig = new GameConfig();
            word       = new WordModel {
                Id = 8, Word = "superb"
            };
            player = new PlayerModel {
                Id = 4, Name = "Frank", Games = new List <GameModel>()
            };
            gameMock = new GameModel
            {
                Id                   = 16,
                WordGuessed          = false,
                StartTime            = DateTime.Now.AddDays(-5),
                GuessedLetters       = new List <GuessedLetterModel>(),
                NrOfIncorrectGuesses = 0,
                Player               = player,
                PlayerId             = player.Id,
                WordToGuess          = word,
                WordToGuessId        = word.Id
            };

            playerRepositoryMock = new Mock <IPlayerRepository>();
            playerRepositoryMock.Setup(x => x.GetOrCreatePlayerByName(It.IsAny <string>())).Returns(player);

            wordRepositoryMock = new Mock <IWordRepository>();
            wordRepositoryMock.Setup(x => x.GetRandomWord()).Returns(word);

            gameRepositoryMock = new Mock <IGameRepository>();
            gameRepositoryMock.Setup(x => x.Add(It.IsAny <GameModel>()));
            gameRepositoryMock.Setup(x => x.Get(It.IsAny <int>())).Returns(gameMock);

            sut = new GameController(gameRepositoryMock.Object, wordRepositoryMock.Object, playerRepositoryMock.Object, gameConfig);
        }
Пример #19
0
        public ActionResult Save(string model)
        {
            WordModel _model = new WordModel(model);

            _model.CreatedBy = User.Identity.Name;
            bool _inserted = _wordManager.Insert(_model);

            if (_inserted)
            {
                if (Request.IsAjaxRequest())
                {
                    return(PartialView("Messages/_HtmlString", "Saved"));
                }
                else
                {
                    return(View("Messages/_HtmlString", "Saved"));
                }
            }
            else
            {
                if (Request.IsAjaxRequest())
                {
                    return(PartialView("Messages/_HtmlString", "Can't insert"));
                }
                else
                {
                    return(View("Messages/_HtmlString", "Can't insert"));
                }
            }
        }
Пример #20
0
        private void frmManageLanguageMain_Load(object sender, EventArgs e)
        {
            this.Visible = false;
            Util.EndAnimate(this, Util.Effect.Slide, 150, 180);
            Language = frmHome.languageModel;
            //_lstWord = _Word.getLstWord(this.Name);

            if (frmHome.lstLanguageWord != null)
            {
                _lstLanWord = _WL.getLstLanguageWord(Language.StrLanguageID, this.Name);
                foreach (LanguageWordModel lnword in _lstLanWord)
                {
                    _wordModel = _Word.getWordSelected(lnword.StrWordID);
                    if (lblTitle.Text == _wordModel.StrWordName)
                    {
                        lblTitle.Text = _WL.getMeanByID(lnword.StrID, Language.StrLanguageID);
                    }
                    if (btnManageLanguage.Text == _wordModel.StrWordName)
                    {
                        btnManageLanguage.Text = _WL.getMeanByID(lnword.StrID, Language.StrLanguageID);
                    }
                    if (btnManageWord.Text == _wordModel.StrWordName)
                    {
                        btnManageWord.Text = _WL.getMeanByID(lnword.StrID, Language.StrLanguageID);
                    }
                    if (btnAddWord.Text == _wordModel.StrWordName)
                    {
                        btnAddWord.Text = _WL.getMeanByID(lnword.StrID, Language.StrLanguageID);
                    }
                }
            }
        }
Пример #21
0
        public async Task GetWordsFromUrl(string url)
        {
            WebClient webClient = new WebClient();
            string    source    = webClient.DownloadString(url);

            HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
            document.LoadHtml(source);

            var wordList = document.DocumentNode.InnerText.Split(' ');

            foreach (var word in wordList)
            {
                if (string.IsNullOrEmpty(word))
                {
                    continue;
                }

                var model = new WordModel
                {
                    Title    = url,
                    WordName = word.Length > 100 ? word.Substring(0, 99) : word
                };

                _context.Words.Add(model);
            }
            await _context.SaveChangesAsync();
        }
Пример #22
0
        public async Task Add_RuturnsNegativeOne_IfWordExists_WS()
        {
            //Arrange
            string            value    = "value";
            int               Id       = 8;
            int               expected = -1;
            IQueryable <Word> words    = new List <Word>
            {
                new Word
                {
                    Id         = Id,
                    Value      = value,
                    LanguageId = Id
                }
            }.AsQueryable <Word>();
            WordModel word = new WordModel {
                Value = value, LanguageId = Id
            };
            var mockSet = GenerateMockDbSet <Word>(words);

            _words.Setup(w => w.GetAll()).Returns(mockSet.Object);

            //Act
            int actual = await _service.AddAsync(word);

            //Assert
            _factory.Verify(f => f.GetUnitOfWork(), Times.Exactly(2));
            _uow.Verify(u => u.WordRepository, Times.Once);
            _words.Verify(w => w.GetAll(), Times.Once);
            Assert.AreEqual(actual, expected);
        }
Пример #23
0
        public static void UpdateEntityWithModel(WordModel source, Word target)
        {
            target.Name  = source.Name;
            target.Level = source.Level.Value;
            target.Meanings.Clear();

            foreach (var group in source.Definitions.GroupBy(d => d.PartOfSpeech))
            {
                var meaning = new Meaning
                {
                    PartOfSpeech = group.Key.Value,
                    Definitions  = new List <Definition>()
                };

                foreach (var value in group)
                {
                    var definition = new Definition
                    {
                        Language = Language.English,
                        Define   = value.Define,
                        Example  = value.Example,
                        Antonyms = value.Antonyms.AsAntonyms(),
                        Synonyms = value.Synonyms.AsSynonyms()
                    };

                    meaning.Definitions.Add(definition);
                }

                target.Meanings.Add(meaning);
            }
        }
Пример #24
0
        public Guid CreateWord(WordModel word)
        {
            var language1 = db.Languages.FirstOrDefault(l => l.LanguageCode == word.Language);
            var language2 = db.Languages.FirstOrDefault(l => l.LanguageCode == word.ToLanguage);

            Guid wordId      = Guid.NewGuid();
            var  wordLearned = new WordLearned();

            wordLearned.LanguageID  = language1.ID;
            wordLearned.Language    = language1;
            wordLearned.Word        = word.Word;
            wordLearned.WordID      = wordId;
            wordLearned.Description = word.Description;
            db.WordLearneds.Add(wordLearned);

            var toWordLearned2 = new WordLearned();

            toWordLearned2.LanguageID  = language2.ID;
            toWordLearned2.Language    = language2;
            toWordLearned2.Word        = word.ToWord;
            toWordLearned2.Description = word.ToDescription;
            toWordLearned2.WordID      = wordId;
            db.WordLearneds.Add(toWordLearned2);

            db.SaveChangesAsync();
            return(wordId);
        }
Пример #25
0
        /// <summary>
        /// Gets the word model.
        /// </summary>
        /// <param name="wordModelDataType">Type of the invalid word model data.</param>
        /// <param name="id">The identifier.</param>
        /// <returns></returns>
        public WordModel GetWordModel(WordModelDataType wordModelDataType = WordModelDataType.None)
        {
            Word word = wordModelDataType == WordModelDataType.WordAsChildWord
                                ? Words.First().TranslateChildrenWords.First()
                                : Words.First();

            var wordModel = new WordModel
            {
                Id         = wordModelDataType == WordModelDataType.WordNoExists? 999 : word.Id,
                Categories = new []
                {
                    new CategoryModel
                    {
                        Id = wordModelDataType == WordModelDataType.CategoryNoExists
                                                        ? 999
                                                        : wordModelDataType == WordModelDataType.UpdatingValidData
                                                                ? Categories.Last().Id
                                                                : word.CategoriesWord.First().CategoryId
                    }
                },
                Value        = word.Value + " New",
                LanguageType = new LanguageTypeModel
                {
                    Tag = wordModelDataType == WordModelDataType.UpdatingValidData
                                                ? word.LanguageType.Tag == "EN"
                                                        ? LanguageTypeEnum.PL
                                                        : LanguageTypeEnum.EN
                                                : Enum.Parse <LanguageTypeEnum>(word.LanguageType.Tag)
                },
                TranslatedWords = (wordModelDataType == WordModelDataType.WordAsChildWord ||
                                   wordModelDataType == WordModelDataType.EmptyTranslatedWordsCollection)
                                        ? new TranslatedWord[] { }
                                        : word.TranslateChildrenWords.Select(item =>
                                                                             new TranslatedWord
                {
                    Id           = item.Id,
                    LanguageType = new LanguageTypeModel
                    {
                        Name = item.LanguageType.Name,
                        Tag  = Enum.Parse <LanguageTypeEnum>(item.LanguageType.Tag)
                    },
                    Value = wordModelDataType == WordModelDataType.EmptyTranslatedWordValue
                                                        ? string.Empty
                                                        : item.Value + "New"
                }).ToArray()
            };

            switch (wordModelDataType)
            {
            case WordModelDataType.EmptyOriginalValue:
                wordModel.Value = string.Empty;
                break;

            case WordModelDataType.OriginalValueExists:
                wordModel.Value = Words[1].Value;
                break;
            }

            return(wordModel);
        }
Пример #26
0
        public static WordModel ConvertEntityToModel(Word source)
        {
            var wordModel = new WordModel
            {
                Name        = source.Name,
                Level       = source.Level,
                Definitions = new List <DefinitionModel>()
            };

            if (source.Meanings != null)
            {
                foreach (var meaningEntity in source.Meanings)
                {
                    var definitionModel = new DefinitionModel
                    {
                        PartOfSpeech = meaningEntity.PartOfSpeech
                    };

                    if (meaningEntity.Definitions != null)
                    {
                        foreach (var definitionEntity in meaningEntity.Definitions.Where(d => d.Language == Language.English))
                        {
                            definitionModel.Define   = definitionEntity.Define;
                            definitionModel.Example  = definitionEntity.Example;
                            definitionModel.Antonyms = definitionEntity.Antonyms?.AsString();
                            definitionModel.Synonyms = definitionEntity.Synonyms?.AsString();
                        }
                    }

                    wordModel.Definitions.Add(definitionModel);
                }
            }

            return(wordModel);
        }
Пример #27
0
 public void SetUp()
 {
     GlobalSettings.Random = new Random(48);
     vectorSource          = new EmbeddingVectorSource(WordModel.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, @"Data\model.bin")));
     pageDetector          = new SvmAnomalyDetector(vectorSource, new NullLoggerFactory(), null);
     document = new DocumentBlock(JsonConvert.DeserializeObject <Document[]>(File.ReadAllText(Path.Combine(TestContext.CurrentContext.TestDirectory, "Data", "docs.json"))));
 }
Пример #28
0
 void GenerateContent()
 {
     if (model.Words.Count != 0)
     {
         Window win = window as Window;
         Grid grid = (Grid)LogicalTreeHelper.FindLogicalNode(win, "DataGrid");
         int index = rand.Next(0, model.Words.Count);
         answer = model.Words[index];
         userAnswer = new char[answer.Word.Length];
         Viewbox translate = DynamicElements.CreateViewBoxLabel(answer.Translate, answer.WordId);
         DynamicElements.SetRowColumnProperties(translate, 1, 0, 2, 1);
         grid.Children.Add(translate);
         Grid targetGrid = DynamicElements.CreateGrid(answer.Word.Length, 1, GridUnitType.Star, GridUnitType.Star);
         targetGrid.Name = "TargetGrid";
         DynamicElements.SetRowColumnProperties(targetGrid, 2, 0, 2, 1);
         grid.Children.Add(targetGrid);
         Grid questGrid = DynamicElements.CreateGrid(answer.Word.Length, 1, GridUnitType.Star, GridUnitType.Star);
         questGrid.Name = "QuestGrid";
         DynamicElements.SetRowColumnProperties(questGrid, 4, 0, 2, 1);
         grid.Children.Add(questGrid);
         FillGrid(Shuffle(answer.Word), questGrid);
         model.Words.RemoveAt(index);
         AddNextComplete(model.Words.Count);
         if (model.Words.Count != 0)
         {
             ((Border)LogicalTreeHelper.FindLogicalNode(win, "NextBord")).Visibility = Visibility.Visible;
         }
         else
         {
             ((Border)LogicalTreeHelper.FindLogicalNode(win, "CompleteBord")).Visibility = Visibility.Visible;
         }
     }
 }
Пример #29
0
        public async Task <OperationResult> SaveAsync(WordModel model)
        {
            var result = new OperationResult();

            var word = await unitOfWork.Word.All().FirstOrDefaultAsync(x => x.Id == model.Id);

            if (word == null)
            {
                var sword = await unitOfWork.Word.All().FirstOrDefaultAsync(x => x.SecretWord == model.SecretWord);

                if (sword == null)
                {
                    sword    = mapper.Map <Word>(model);
                    model.Id = Guid.NewGuid();
                    unitOfWork.Word.Add(sword);
                }

                else
                {
                    result.Message = "error";
                }
            }
            else
            {
                mapper.Map(model, word);
                //word.SecretWord = model.SecretWord;
                //word.Question = model.Question;
            }

            await unitOfWork.SaveChangesAsync();

            return(result);
        }
Пример #30
0
        public void should_create_word()
        {
            //arrange
            var model = new WordModel
            {
                Key = "key",
                Tag = "tag1"
            };

            var wordRepository = new Mock <IRepository <Word> >();

            wordRepository.Setup(x => x.SaveChanges()).Returns(true);

            //act
            var sut = new WordServiceBuilder().WithWordRepository(wordRepository.Object).Build();

            var result = sut.Create(model);

            //assert
            Assert.IsNotNull(result);
            Assert.AreEqual(model.Key, result.Result);

            wordRepository.Verify(x => x.Create(It.IsAny <Word>()), Times.Once);
            wordRepository.Verify(x => x.SaveChanges(), Times.Once);
        }
Пример #31
0
 public static WordModel GetBestSynonym(WordModel word, ICollection<WordModel> synonyms, WordTrait desired = null)
 {
     if (!synonyms.Any())
     {
         return word;
     }
     if (synonyms.Count() == 1)
     {
         return synonyms.First();
     }
     return BestSynonymMatchByTrait(synonyms, desired);
 }
Пример #32
0
        private WordModel ConvertWord(string word, WordModel.WordType wordtype)
        {
            WordModel model = db.Words.FirstOrDefault(w => w.Word == word);
            if (model == null)
            {
                model = ThesaurusQueryService.GetModelWithSynonyms(word);
                db.Words.Add(model);
                db.SaveChanges();
            }
            else if (!model.SynonymsQueried)
            {
                ThesaurusQueryService.GetSynonyms(ref model);
                db.SaveChanges();
            }
            WordModel returnModel;
            switch (wordtype)
            {
                case WordModel.WordType.Noun:
                case WordModel.WordType.NounPlural:
                    returnModel = SynonymLogicService.GetBestSynonym(model, model.NounSynonyms);
                    break;
                case WordModel.WordType.Adjective:
                    returnModel = SynonymLogicService.GetBestSynonym(model, model.AdjectiveSynonyms);
                    break;
                case WordModel.WordType.Verb:
                    returnModel = SynonymLogicService.GetBestSynonym(model, model.VerbSynonyms);
                    break;
                case WordModel.WordType.Adverb:
                    returnModel = SynonymLogicService.GetBestSynonym(model, model.AdverbSynonyms);
                    break;
                case WordModel.WordType.Default:
                    returnModel = SynonymLogicService.GetBestSynonym(model, model.GetLongestSynonymSet());
                    break;
                default:
                    returnModel = model;
                    break;
            }

            if (wordtype == WordModel.WordType.NounPlural)
            {
                returnModel.IsPlural = true;
            }

            return returnModel;
        }