public static async Task <object> SubmitGuess( [HttpTrigger(AuthorizationLevel.Anonymous, "post")] Guess guess, [Table("clues", "{clueId}", Clue.RowKeyValue)] Clue clue, [Table("guesses")] IAsyncCollector <Guess> guesses, [SignalR(HubName = "trivia")] IAsyncCollector <SignalRMessage> signalRMessages) { var l = new NormalizedLevenshtein(); var similarity = l.Similarity(NormalizeString(clue.Answer), NormalizeString(guess.Value)); await guesses.AddAsync(guess); var result = new { guess.SessionId, ClueId = clue.PartitionKey, Guess = guess.Value, IsCorrect = similarity > 0.75, Similarity = similarity }; await signalRMessages.AddAsync(new SignalRMessage { Target = "newGuess", Arguments = new object[] { new { clueId = result.ClueId, isCorrect = result.IsCorrect } } }); return(result); }
public static List <string> GetSimilarFiles(string file_name, string folder, double threshold) { List <string> similar_files = new List <string>(); string file_string; if (File.Exists(file_name)) { file_string = File.ReadAllText(file_name); } else { return(similar_files); } if (Directory.Exists(folder)) { var l = new NormalizedLevenshtein(); foreach (string file in Directory.GetFiles(folder)) { if (file != file_name && (Path.GetExtension(file) == ".html" || Path.GetExtension(file) == ".htm")) { string check_file = File.ReadAllText(file); double similarity = l.Similarity(file_string, check_file); if (similarity > threshold) { similar_files.Add(file); } } } } return(similar_files); }
public void HouseAnalysis(CallsInfo[] calls) { _logger.LogInformation("Анализ наличия номера дома"); var l = new NormalizedLevenshtein(); foreach (var call in calls) { if (call.Text == null) { continue; } var words = call.Text.Split(' '); foreach (var announcement in call.Announcements) { if (announcement.House == default) { continue; } double max_similarity = default; string best_word = default; foreach (var word in words) { var similarity = l.Similarity(word.ToLower(), announcement.House.ToLower()); if (similarity >= max_similarity) { best_word = word; max_similarity = similarity; } } //if (max_similarity == 1) { announcement.Features.Add(new FeatureInfo { Name = FeatureInfo.HOUSE, Weight = max_similarity, Data = best_word ?? "" }); } } } _logger.LogInformation("Закончили"); }
public void NormalizedLevenshteinAnalysis(CallsInfo[] calls) { _logger.LogInformation("Анализ похожих методом NormalizedLevenshtein"); var l = new NormalizedLevenshtein(); foreach (var call in calls) { if (call.Text == null) { continue; } var words = call.Text.Split(' '); foreach (var announcement in call.Announcements) { if (announcement.Street == default) { continue; } double max_similarity = default; string best_word = default; foreach (var word in words) { var similarity = l.Similarity(word.ToLower(), announcement.Street.ToLower()); if (similarity >= max_similarity) { best_word = word; max_similarity = similarity; } } announcement.Features.Add(new FeatureInfo { Name = FeatureInfo.LEVENSTAIN, Weight = max_similarity, Data = best_word ?? "" }); } } _logger.LogInformation("Закончили"); }
///// <summary> ///// Calcualtes the Levenshtein distance between two strings ///// </summary> ///// Source: https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#C.23 ///// Explanation: https://en.wikipedia.org/wiki/Levenshtein_distance //private Int32 levenshtein(String a, String b) //{ // if (string.IsNullOrEmpty(a)) // { // if (!string.IsNullOrEmpty(b)) // { // return b.Length; // } // return 0; // } // if (string.IsNullOrEmpty(b)) // { // if (!string.IsNullOrEmpty(a)) // { // return a.Length; // } // return 0; // } // Int32 cost; // Int32[,] d = new int[a.Length + 1, b.Length + 1]; // Int32 min1; // Int32 min2; // Int32 min3; // for (Int32 i = 0; i <= d.GetUpperBound(0); i += 1) // { // d[i, 0] = i; // } // for (Int32 i = 0; i <= d.GetUpperBound(1); i += 1) // { // d[0, i] = i; // } // for (Int32 i = 1; i <= d.GetUpperBound(0); i += 1) // { // for (Int32 j = 1; j <= d.GetUpperBound(1); j += 1) // { // cost = Convert.ToInt32(!(a[i - 1] == b[j - 1])); // min1 = d[i - 1, j] + 1; // min2 = d[i, j - 1] + 1; // min3 = d[i - 1, j - 1] + cost; // d[i, j] = Math.Min(Math.Min(min1, min2), min3); // } // } // return d[d.GetUpperBound(0), d.GetUpperBound(1)]; //} ///// <summary> ///// String-similarity computed with levenshtein-distance ///// </summary> //private double similarityLevenshtein(string a, string b) //{ // if (a.Equals(b)) // { // return 1.0; // } // else // { // if (!(a.Length == 0 || b.Length == 0)) // { // double sim = 1 - (levenshtein(a, b) / Convert.ToDouble(Math.Min(a.Length, b.Length))); // return sim; // } // else // return 0.0; // } //} ///// <summary> ///// String-similarity computed with Dice Coefficient ///// </summary> ///// Source: https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Dice%27s_coefficient#C.23 ///// Explanation: https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient //private double similarityDiceCoefficient(string a, string b) //{ // //Workaround for |a| == |b| == 1 // if (a.Length <= 1 && b.Length <= 1) // { // if (a.Equals(b)) // return 1.0; // else // return 0.0; // } // HashSet<string> setA = new HashSet<string>(); // HashSet<string> setB = new HashSet<string>(); // for (int i = 0; i < a.Length - 1; ++i) // setA.Add(a.Substring(i, 2)); // for (int i = 0; i < b.Length - 1; ++i) // setB.Add(b.Substring(i, 2)); // HashSet<string> intersection = new HashSet<string>(setA); // intersection.IntersectWith(setB); // return (2.0 * intersection.Count) / (setA.Count + setB.Count); //} /// <summary> /// Combines multiple String-similarities with equal weight /// </summary> private double similarity(string a, string b) { List <double> similarities = new List <double>(); double output = 0.0; var l = new NormalizedLevenshtein(); similarities.Add(l.Similarity(a, b)); var jw = new JaroWinkler(); similarities.Add(jw.Similarity(a, b)); var jac = new Jaccard(); similarities.Add(jac.Similarity(a, b)); foreach (double sim in similarities) { output += sim; } return(output / similarities.Count); }
private void Button_Click(object sender, RoutedEventArgs e) { resultTexBox.Text = ""; progressBar.Value = 0; if (jaroWinklerCheckBox.IsChecked.Value) { Thread.Sleep(100); resultTexBox.Text += "\n\nJARO WINKLER:\nDistance = " + jw.Distance(textDoc1, textDoc2) + "\nSimilarity = " + jw.Similarity(textDoc1, textDoc2) * 100 + "%"; } progressBar.Value = 5; if (levenshteinCheckBox.IsChecked.Value) { Thread.Sleep(100); resultTexBox.Text += "\n\nLEVENSHTEIN:\nDistance = " + levenshtein.Distance(textDoc1, textDoc2); } progressBar.Value = 40; if (normalizedLevenshteinCheckBox.IsChecked.Value) { Thread.Sleep(100); resultTexBox.Text += "\n\nNORMALIZED LEVNSHTEIN:\nDistance = " + normalizedLevenshtein.Distance(textDoc1, textDoc2) + "\nSimilarity = " + normalizedLevenshtein.Similarity(textDoc1, textDoc2) * 100 + "%"; } progressBar.Value = 65; if (nGramCheckBox.IsChecked.Value) { Thread.Sleep(100); resultTexBox.Text += "\n\nNGRAM:\nDistance = " + nGram.Distance(textDoc1, textDoc2); } progressBar.Value = 100; }
private async void ButtonValid_Click(object sender, RoutedEventArgs e) { string inputString = myInputTextBox.Text; LImagesMots selectedImage = Images[flipView.SelectedIndex]; string[] lines = inputString.Split('\r'); string voiceString = inputString; double ratingResult = 0.0; foreach (var L in lines) { var l = new NormalizedLevenshtein(); double distance = l.Similarity(L, selectedImage.ImageText); // distance est entre 0 [PERFECT] et 1 if (distance > ratingResult) { ratingResult = distance; } log.Trace("Compare " + L + ", " + selectedImage.ImageText); log.Trace("results =" + l.Similarity(L, selectedImage.ImageText)); if (L == selectedImage.ImageText) { voiceString = L; } } // transformation du result 0..1 en 0..5 (5 est 5 etoile) log.Trace("ratingResults =" + ratingResult + " ---"); log.Trace("5*ratingResult =" + 5 * (ratingResult) + " ---"); ratingResult = 5 * ratingResult; int ratingResultInt = (int)ratingResult; log.Trace(" (int)ratingResult =" + ratingResult + " ---"); string bravoText = ""; switch (ratingResultInt) { case 5: bravoText = " BRAVO !!, "; break; case 4: bravoText = " PRESQUE !!"; break; case 2: case 3: bravoText = " ESSAYE ENCORE !!"; break; case 0: case 1: bravoText = " RECOMMENCE !!"; myInputTextBox.Text = ""; break; default: bravoText = " DEFAULT !!"; break; } Flyout tmpFlyout = Resources["MyFlyout"] as Flyout; MyRating.Value = ratingResultInt; MyResultText.Text = bravoText; voiceString = string.Concat(bravoText + ",", voiceString); myInputTextBox.Focus(FocusState.Programmatic); myInputTextBox.IsTextScaleFactorEnabled = false; await letterPlayer_m.speachAsync(voiceString); tmpFlyout.ShowAt(myInputTextBox); // rend le focus a la text box myInputTextBox.Focus(FocusState.Programmatic); }
protected async Task <ContentStatus> StartContentBoardMission(string name) { if (!await GoToMainScreen()) { Logger.LogError("Couldn't go to main screen."); } if (!await WaitUntilVisible("MAIN_MENU_ENTER")) { Logger.LogError("Cannot find enter button.. Not on main screen?"); return(null); } await Task.Delay(500); Game.Click("CONTENT_STATUS_BOARD_BUTTON"); if (!await WaitUntilVisible("CONTENT_STATUS_BOARD_MENU_HEADER")) { Logger.LogError("Failed to navigate to content status board"); return(null); } await Task.Delay(500); for (int i = 0; i < 3; i++) { for (var row = 0; row < 5; row++) { for (var col = 0; col < 3; col++) { var nameElement = Repository["CONTENT_STATUS_BOARD_ITEM_NAME_DYN", col, row]; var missionName = Game.GetText(nameElement); missionName = missionName.Contains("\n") ? missionName.Split('\n')[0] : missionName; var nl = new NormalizedLevenshtein(); var similarity = nl.Similarity(name, missionName); if (similarity >= 0.8) // 80% should be fine. names are different enough. { var status = Game.GetText(Repository["CONTENT_STATUS_BOARD_ITEM_STATUS_DYN", col, row]); var isCompleted = missionName.Contains("\n") && nl.Similarity("RESETS IN", missionName.TrimEnd().Split('\n').Last()) > 0.8; //var isCompleted = Game.IsVisible(Repository["CONTENT_STATUS_BOARD_ITEM_NAME_COMPLETED_DYN", col, row]); var statusEntry = new ContentStatus(name, isCompleted, status); Logger.LogDebug($"Clicking on element because it matches expected: {name} actual: {missionName} similarity: {similarity}"); Game.Click(nameElement); await Task.Delay(1000); // waiting briefly for page to change. if (Game.IsVisible(UIds.GENERIC_MISSION_CUSTOM_OFFER_FOR_AGENTS)) { Game.Click(UIds.GENERIC_MISSION_CUSTOM_OFFER_FOR_AGENTS_CLOSE); await Task.Delay(1000); } return(statusEntry); } else { Logger.LogDebug($"Found mission {missionName}. But its not what we are looking for. Similarity {similarity}"); } } } Game.Drag("CONTENT_STATUS_BOARD_DRAG_START", "CONTENT_STATUS_BOARD_DRAG_END"); } return(null); }
protected override async Task RunCore(CancellationToken token) { if (!await GoToMainScreen(token)) { Logger.LogError("Could not go to main menu"); return; } if (!await OpenMenu().ConfigureAwait(false)) { Logger.LogError("Could not open main menu"); return; } Game.Click(UIds.MAIN_MENU_CHALLENGES_BUTTON); await Task.Delay(1000, token); if (!await ClickWhenVisible(UIds.CHALLENGES_DAILY_TRIVIA_TAB)) { Game.OnError(new ElementNotFoundError(Repository[UIds.CHALLENGES_DAILY_TRIVIA_TAB])); } await Task.Delay(1000, token); if (!await WaitUntil(() => Game.IsVisible(UIds.CHALLENGES_DAILY_START_BUTTON) || Game.IsVisible(UIds.CHALLENGES_DAILY_TRIVIA_BASIC_REWARD), token)) { Logger.LogInformation("Daily trivia already completed"); return; } if (Game.IsVisible(UIds.CHALLENGES_DAILY_START_BUTTON)) { Game.Click(UIds.CHALLENGES_DAILY_START_BUTTON); } await Task.Delay(2000, token); var questionStatus = Game.GetText(UIds.CHALLENGES_DAILY_TRIVIA_QUESTION_STATUS); if (questionStatus.Contains("/5")) { Logger.LogInformation("Daily Trivia already started"); } else { Logger.LogError("Start button did not appear"); return; } var nl = new NormalizedLevenshtein(); while (Game.IsVisible(UIds.CHALLENGES_DAILY_TRIVIA_BASIC_REWARD) && !token.IsCancellationRequested) { var question = Game.GetText(UIds.CHALLENGES_DAILY_TRIVIA_QUESTION); Logger.LogDebug($"Question is: {question}"); string answer = null; double highestSimilarityQuestion = 0; foreach (var item in _questionsAndAnswers) { var similarity = nl.Similarity(question, item.Question); if (similarity > highestSimilarityQuestion) { highestSimilarityQuestion = similarity; Logger.LogDebug($"Found question that matches better: {item.Question}"); answer = item.Answer; } } Logger.LogDebug($"Expected answer is: {answer}"); double highestSimilarityAnswer = 0; UiElement bestAnswerElement = null; for (int i = 0; i < 4; i++) { var answerId = Repository[UIds.CHALLENGES_DAILY_TRIVIA_ANSWER_DYN, 0, i]; var potentialAnswer = Game.GetText(answerId); var similarity = nl.Similarity(potentialAnswer, answer); Logger.LogDebug($"Found potential answer '{potentialAnswer}' that has a similarity of: {similarity * 100f}%"); if (similarity > highestSimilarityAnswer) { highestSimilarityAnswer = similarity; bestAnswerElement = answerId; } } if (bestAnswerElement == null) { Logger.LogError("Could not find answer for question."); return; } Game.Click(bestAnswerElement); if (!await WaitUntilVisible(UIds.CHALLENGES_DAILY_TRIVIA_CLOSE_BUTTON)) { Logger.LogError($"Close button did not appear. Wrong answer? Q: {question} A: {answer}"); return; } await Task.Delay(500, token); Game.Click(UIds.CHALLENGES_DAILY_TRIVIA_CLOSE_BUTTON); await Task.Delay(2000, token); } Logger.LogInformation("Daily trivia completed"); }
public static double Similarity(this string expected, string actual) { var nl = new NormalizedLevenshtein(); return(nl.Similarity(expected, actual)); }