public static Compute ( string s, string t ) : int | ||
s | string | |
t | string | |
Результат | int |
private bool ValidateAndTryFix(WorkItem sourceWorkItem, WorkItem newWorkItem) { ArrayList array = newWorkItem.Validate(); bool isInError = array.Count != 0; foreach (Field item in array) { if (!CorrectErrorsAbsolutely) { logger.WarnFormat("Work item {0} Validation Error in field: {1} : {2}", sourceWorkItem.Id, item.Name, newWorkItem.Fields[item.Name].Value); } else { var initialValue = item.Value.ToString(); var allowedValueSortedByAcceptability = item.AllowedValues.OfType <string>().OrderBy(e => LevenshteinDistance.Compute(initialValue, e)); var value = allowedValueSortedByAcceptability.First(); item.Value = value; logger.WarnFormat("Work item {0} Validation Error in field: {1} : {2}=> Replaced by value: {3}", sourceWorkItem.Id, item.Name, initialValue, value); } } if (isInError && CorrectErrorsAbsolutely) { array = newWorkItem.Validate(); } return(array.Count == 0); }
public async Task <IPlayable> SearchTrack(string artist, string title) { PlayableBase result = null; var sw = Stopwatch.StartNew(); foreach (var track in Tracks.Tracks) { if (track.Title.IndexOf(title.Trim(), StringComparison.OrdinalIgnoreCase) > -1 && !string.IsNullOrEmpty(track.Artist?.Name) && LevenshteinDistance.Compute(artist.ToLower(), track.Artist.Name.ToLower()) <= Math.Abs(artist.Length - track.Artist.Name.Length)) { result = track; break; } } Debug.Print($"Search track in local collection: {sw.ElapsedMilliseconds} ms"); if (result != null) { return(result); } return (await MusicStreamingPluginManager.DefaultMusicStreaming.GetTrack( $"{artist} - {title}")); }
public static async Task <RetrieveEntityResult <string> > BestLevenshteinMatchAsync ( [NotNull, ItemNotNull] this IQueryable <string> @this, [NotNull] string search, double tolerance = 0.25 ) { var candidates = from candidate in @this let distance = LevenshteinDistance.Compute ( candidate.ToLowerInvariant(), search.ToLowerInvariant() ) let maxDistance = Math.Max(candidate.Length, search.Length) let percentile = distance / (float)maxDistance select new Tuple <string, int, double>(candidate, distance, percentile); var hasAnyPassing = await candidates.Where(c => c.Item3 <= tolerance).AnyAsync(); if (!hasAnyPassing) { return(RetrieveEntityResult <string> .FromError("No sufficiently close match found.")); } var best = await candidates.OrderBy(x => x.Item2).FirstAsync(); return(RetrieveEntityResult <string> .FromSuccess(best.Item1)); }
public GameInfoModel GetDataFromApi(string filename) { var platform = "?platformID[]=11"; var name = "&name=" + filename.Replace(" ", "+"); var response = ScrapeArt.WebClient(BaseUrl, p => p.DownloadString("search.php" + platform + name) ); var html = CQ.CreateDocument(response); if (html["div#display"].Children().Any() == false) { return(null); } var sanitizedSearchFilename = SanitizeSeach(filename); var resultRoot = html["div#display div > a[href]"]; var results = IterateResults(resultRoot).ToArray(); // result is in the wrong order, so i attempt to find the most relevant of the results var orderedByRelevance = ( from item in results let sanitizedSerachTitle = SanitizeSeach(item.Title) let levenshteinDistance = LevenshteinDistance.Compute(sanitizedSearchFilename, sanitizedSerachTitle) let lengthDifference = sanitizedSearchFilename.Length - sanitizedSerachTitle.Length orderby lengthDifference orderby levenshteinDistance select item ).ToArray(); return(orderedByRelevance.FirstOrDefault()); }
void CompareButtonClicked(object sender, EventArgs e) { var result = LevenshteinDistance.Compute(FirstWordTextField.Text, SecondWordTextField.Text); ResultLabel.Text = result.ToString(); }
private void MapTeams(TeamSheetTeam team, int managerId) { var leagueTeams = db.Teams.ToList(); foreach (var goalKeeper in team.GoalKeepers) { string matchText = goalKeeper.Team.Replace(" ", string.Empty).ToUpper(); int bestDistance = -1; int bestTeamId = -1; foreach (var leagueTeam in leagueTeams) { var distance = LevenshteinDistance.Compute(matchText, leagueTeam.Alias.Replace(" ", string.Empty).ToUpper()); if (bestDistance == -1 || distance < bestDistance) { bestDistance = distance; bestTeamId = leagueTeam.TeamId; } } if (bestTeamId != -1) { db.ManagerGoalKeepers.Add(new ManagerGoalKeeper(bestTeamId, managerId, goalKeeper.Substitute)); } } }
public ICompareResult search(string sentence) { var s = removePunctuation(sentence); var minDistance = 10000; Entity minE = null; foreach (var entity in this.models) { foreach (var sent in entity.sentenses) { var d = LevenshteinDistance.Compute(s, sent); if (d == 0) { return new CompareResult { Success = true, BestResult = entity, Rank = 100 } } ; if (d < minDistance) { minDistance = d; minE = entity; } } } if (s.Length < 5 && minDistance == 1) { return new CompareResult { Success = true, BestResult = minE, Rank = 95 } } ; if (s.Length < 8 && minDistance <= 2) { return new CompareResult { Success = true, BestResult = minE, Rank = 95 - minDistance * 5 } } ; if (s.Length < 12 && minDistance <= 3) { return new CompareResult { Success = true, BestResult = minE, Rank = 90 - minDistance * 10 } } ; var r = 60 - minDistance * 5; if (r < 0) { r = 0; } return(new CompareResult { Success = false, BestResult = minE, Rank = r }); } } }
public static RetrieveEntityResult <string> BestLevenshteinMatch ( this IEnumerable <string> @this, string search, double tolerance = 0.25 ) { var candidates = @this.Select ( s => { var distance = LevenshteinDistance.Compute ( s.ToLowerInvariant(), search.ToLowerInvariant() ); var maxDistance = Math.Max(s.Length, search.Length); var percentile = distance / (float)maxDistance; return(value: s, distance, percentile); } ); var passing = candidates.Where(c => c.percentile <= tolerance).ToList(); if (!passing.Any()) { return(RetrieveEntityResult <string> .FromError("No sufficiently close match found.")); } var best = passing.MinBy(c => c.distance).First(); return(RetrieveEntityResult <string> .FromSuccess(best.value)); }
private (string bestMatch, int levenshteinDistance) GetBestMatch(string value, ISet <string> setToMatch) { if (value == null) { return(null, 0); } value = value.ToLower(); string bestMatch = null; int bestLevDist = int.MaxValue; int currentLevDist; foreach (string setValue in setToMatch) { if (value == setValue.ToLower()) { return(setValue, 0); } currentLevDist = LevenshteinDistance.Compute(value, setValue.ToLower()); if (setValue.ToLower().Contains(value)) { currentLevDist -= value.Length; } else if (value.Contains(setValue.ToLower())) { currentLevDist -= setValue.Length; } if (currentLevDist < bestLevDist) { bestLevDist = currentLevDist; bestMatch = setValue; } } return(bestMatch, bestLevDist); }
public async Task Ship(SocketUser user1, SocketUser user2 = null) { try { user2 = user2 ?? Context.User; await GetAvatar(user1); await GetAvatar(user2); ProfileImageGeneration.GenerateShipping($"Shipping/{user1.Id}Avatar.png", $"Shipping/{user2.Id}Avatar.png", $"Shipping/ship{user1.Id}{user2.Id}.png"); int distance = LevenshteinDistance.Compute(Utility.GiveUsernameDiscrimComb(user1), Utility.GiveUsernameDiscrimComb(user2)); await Context.Channel.SendFileAsync($"Shipping/ship{user1.Id}{user2.Id}.png", $"💕 Probability: {Math.Round(Math.Min(100, distance*multiplier),2)}%"); } catch (Exception e) { await SentryService.SendMessage(e.ToString()); } if (File.Exists($"Shipping/{user1.Id}Avatar.png")) { File.Delete($"Shipping/{user1.Id}Avatar.png"); } if (File.Exists($"Shipping/{user2.Id}Avatar.png")) { File.Delete($"Shipping/{user2.Id}Avatar.png"); } if (File.Exists($"Shipping/ship{user1.Id}{user2.Id}.png")) { File.Delete($"Shipping/ship{user1.Id}{user2.Id}.png"); } }
internal static List <ListViewItem> FindDeveloperById(UnityOfWork unit, string id) { var developers = unit.Developer.GetAll(); List <ListViewItem> developersItemList = new List <ListViewItem>(); var SearcheDeveloper = new Developer() { Id = id }; foreach (var developer in developers) { int Distance = LevenshteinDistance.Compute(SearcheDeveloper.Id, developer.Id); int moresimilar = 30; if (Distance <= 4) { ListViewItem item = new ListViewItem(developer.Id); developersItemList.Add(item); } } return(developersItemList); }
private void MapPlayers(TeamSheetTeam team, int managerId) { var leaguePlayers = db.Players.ToList(); foreach (var player in team.Players) { string matchText = player.Name.Replace(" ", string.Empty).ToUpper(); int bestDistance = -1; int bestPlayerId = -1; foreach (var leaguePlayer in leaguePlayers.Where(x => x.Position == player.Position)) { var distance = LevenshteinDistance.Compute(matchText, string.Format("{0}-{1}", leaguePlayer.LastName, leaguePlayer.Team.Alias).Replace(" ", string.Empty).ToUpper()); if ((bestDistance == -1 || distance < bestDistance) || (distance == bestDistance && leaguePlayer.LastName.Contains(player.Name))) { bestDistance = distance; bestPlayerId = leaguePlayer.PlayerId; } } if (bestPlayerId != -1) { db.ManagerPlayers.Add(new ManagerPlayer(bestPlayerId, managerId, player.Substitute)); } } }
internal static List <ListViewItem> GetProjectsByInput(UnityOfWork unit, string text, string client_Id) { var projects = unit.Project .GetAll() .Where(p => p.Client.Contains( unit.Client.GetAll().FirstOrDefault(c => c.Id == client_Id)) ); List <ListViewItem> ProjectsItemList = new List <ListViewItem>(); var SearchedProject = new Project() { Project_ID = text }; foreach (var project in projects) { int Distance = LevenshteinDistance.Compute(SearchedProject.Project_ID, project.Project_ID); if (Distance <= 4) { ListViewItem item = new ListViewItem(project.Project_ID.ToString()); item.SubItems.Add(project.Description.ToString()); item.SubItems.Add(project.DeadLine.ToString()); item.SubItems.Add(project.Result.ToString()); if (project.Client.Count > 0) { item.SubItems.Add(project.Client.FirstOrDefault().Id); } ProjectsItemList.Add(item); } } return(ProjectsItemList); }
static void Analyze() { Settings settings = Settings.Instance; Console.WriteLine("Please enter the directory path to analyze : "); var path = PathUtils.Normalize(Console.ReadLine()); if (string.IsNullOrEmpty(path) || !Directory.Exists(path)) { throw new Exception("Not found path"); } var files = new MusicFileDaoDetector().Search(new List <string>() { path }); foreach (var i in files) { IEnumerable <MusicDao> tag = null; try { tag = new MusicTagDetector(settings.ApiHost, settings.ApiKey, settings.SecretKey).Recognize(i.Path); } catch (Exception e) { Console.WriteLine("File audio error : " + i.Path); Console.WriteLine(e.Message); continue; } if (tag == null || tag.Count() <= 0) { Console.WriteLine("File not recognized : " + i.Path); continue; } Console.WriteLine("File recognized : " + i.Path); if (tag.Count() == 1) { i.Map(tag.First()); } else { int nbMin = int.MaxValue; MusicDao tagMin = null; foreach (var j in tag) { var nb = LevenshteinDistance.Compute(i.FileName, string.Format("{0} - {1}", j.Artist, j.Title)); if (nb < nbMin) { nbMin = nb; tagMin = j; } } i.Map(tagMin); } i.Save(); } }
public void LevenshteinDistance_ComputeWithValidStrings_ShouldWork(string string1, string string2, int distance) { // Act var result = LevenshteinDistance.Compute(string1, string2); // Assert Assert.AreEqual(distance, result); }
public Task <List <LiteTag> > FindTagsAsync(ulong guildId, string name, int stop) { int tolerance = LiteConfiguration.Load().RelatedTagsLimit; var tags = Tags.Where(x => x.GuildId == guildId && x.Aliases.Any(y => LevenshteinDistance.Compute(name, y) <= tolerance)); var selected = tags.OrderBy(x => x.Aliases.Sum(y => LevenshteinDistance.Compute(name, y))).Take(stop); return(Task.FromResult(selected.ToList())); }
/// <summary> /// Return the Levenshtein distance (edit distance) between the given PersonResponsibility's commentary and function fields. /// /// Of temporary use during cleanup of PersonResponsibility.Commentary field when virtual function field introduced. /// </summary> /// <returns></returns> public virtual int GetEditDistanceBetweenCommentaryAndFunction() { if (!string.IsNullOrEmpty(this.Commentary) && !string.IsNullOrEmpty(this.GetPersonFunctionUnitSummary())) { return(LevenshteinDistance.Compute(this.Commentary, this.GetPersonFunctionUnitSummary())); } return(int.MaxValue); }
public void LevenshteinDistance_Compute_IsCommutative(string leftString, string rightString) { // Act var distanceLeft = LevenshteinDistance.Compute(leftString, rightString); var distanceRight = LevenshteinDistance.Compute(rightString, leftString); // Assert Assert.AreEqual(distanceLeft, distanceRight); }
public void LevenshteinDistance_Compute_IsCommutative(string string1, string string2) { // Act var distanceLeft = LevenshteinDistance.Compute(string1, string2); var distanceRight = LevenshteinDistance.Compute(string2, string1); // Assert Assert.AreEqual(distanceLeft, distanceRight); }
public ActionResult Search() { string tag = Request["tag"]; if (string.IsNullOrWhiteSpace(tag)) { return(RedirectToAction("Index")); } tag = tag.Trim(); var onePlayer = db.Players.Where(p => p.Tag == tag).FirstOrDefault(); if (onePlayer != null) { return(RedirectToAction("Detail", new { tag = onePlayer.URL })); } tag = tag.ToUpperInvariant(); char[] tagArray = tag.ToCharArray(); var allPlayers = from p in db.Players select p; int maxDistance = Math.Max((int)((double)tagArray.Length / 5.0), 1); //fool with this if it sux List <Player> foundPlayers = new List <Player>(); foreach (Player player in allPlayers) { string playerTag = player.Tag.ToUpperInvariant(); int distance = LevenshteinDistance.Compute(playerTag, tag); if (distance <= maxDistance) { var computeArray = playerTag.ToCharArray(); int union = tagArray.Union(computeArray).Count(); //total chars int intersect = tagArray.Intersect(computeArray).Count(); //shared chars if ((union * 1.0 - intersect) / union <= .5) { //non-shared chars. should be close to 0 foundPlayers.Add(player); } } } int players = foundPlayers.Count(); if (players == 0) { db.Dispose(); return(RedirectToAction("Index")); } else if (players == 1) { String playerURL = foundPlayers.First().URL; db.Dispose(); return(RedirectToAction("Detail", new { tag = playerURL })); } else { var viewPlayers = foundPlayers.AsQueryable <Player>(); db.Dispose(); return(View("SearchFoundMultiple", viewPlayers)); } }
public IEnumerable <PlayerScore> Run(IEnumerable <Player> players, IEnumerable <string> alreadyPlayed) { var path = @"..\..\..\ESPNStatImporter\bin\Debug"; var files = Directory.GetFiles(path, "*.json"); var newestWeek = files.Select(f => int.Parse(Path.GetFileNameWithoutExtension(f).Substring(4))).OrderByDescending(f => f).First(); var file = File.ReadAllText(Path.Combine(path, $"week{newestWeek}.json")); var results = JsonConvert.DeserializeObject <PlayerResult[]>(file); var misses = new List <PlayerResult>(); foreach (var result in results) { if (alreadyPlayed.Contains(result.Team, StringComparer.CurrentCultureIgnoreCase)) { continue; } var team = MapTeam(result.Team); var hits = players .Where(p => string.Equals(p.Team, team, StringComparison.CurrentCultureIgnoreCase) && string.Equals(p.Position, result.Position, StringComparison.CurrentCultureIgnoreCase)) .Select(p => new { Player = p, Distance = LevenshteinDistance.Compute(p.Name, result.Name), }) .OrderBy(x => x.Distance) .ToArray(); if (hits.Any(h => h.Distance <= 4 && h.Player.Name == "Matt Ryan")) { var x = 1; } if (!hits.Any() || hits.First().Distance > 4) { misses.Add(result); var score = PlayerScore.CalcScore(result); if (result.Team == "FA" || score == 0) { continue; } //yield return new PlayerScore(new Player { Name = $"MISS - {result.Name}", Team = team }, result); } else { var hit = hits.First().Player; if (result.Team == "FA" || hit.Salary == 0) { continue; } yield return(new PlayerScore(hit, result)); } } }
public Task <ClizerPostAction> Intercept(CommandContext context, CancellationToken cancellationToken) { if (context.Command is not null) { return(Task.FromResult(ClizerPostAction.CONTINUE)); } Console.WriteLine($"Unknown command for {context.Execute}. See '--help'"); // list similar commands if (context.RootCommand is null) { return(Task.FromResult(ClizerPostAction.CONTINUE)); } var similarCommands = context.RootCommand .GetAll() .Select(x => x.Name.ToLower()) .Where(x => LevenshteinDistance.Compute(x, context.Execute) <= 3); if (similarCommands.Any()) { Console.WriteLine("Most similar commands:"); foreach (var similar in similarCommands) { Console.WriteLine($" - {similar}"); } } // list similar aliases var aliasesResolver = _services.GetService <AliasesResolver>(); if (aliasesResolver is null) { return(Task.FromResult(ClizerPostAction.EXIT)); } var similarAliases = aliasesResolver .Aliases .Select(x => x.Name.ToLower()) .Where(x => LevenshteinDistance.Compute(context.Execute, x) <= 2); if (!similarAliases.Any()) { return(Task.FromResult(ClizerPostAction.EXIT)); } Console.WriteLine(string.Empty); Console.WriteLine("Most similar aliases:"); foreach (var similar in similarAliases) { Console.WriteLine($" - {similar}"); } return(Task.FromResult(ClizerPostAction.EXIT)); }
public void ShouldReturnCostOfSeventeen() { string validOpt = "anthropomorphology"; string optToValidate = "addddddddddddddddd"; int expectedCost = 17; LevenshteinCost result = LevenshteinDistance.Compute(optToValidate, validOpt); Assert.AreEqual(expectedCost, result.Cost); }
public Dictionary <Faq, int> GetSimilar(IConfigurationRoot config, ulong guildId, string name) { var faqs = GetAll(guildId); var faqDictionary = faqs.ToDictionary(faq => faq, faq => LevenshteinDistance.Compute(name, faq.Name)); return(faqDictionary .Where(pair => pair.Value <= Convert.ToInt32(config["MaxLevenshteinDistance"])) .OrderBy(pair => pair.Value) .ToDictionary()); }
public static IDictionary <string, int> WordDistanceToWordsInSentence(string word, string sentence) { IDictionary <string, int> wordDistanceToWordsInSentence = new Dictionary <string, int>(); foreach (string wordInSentence in sentence.Split(' ')) { wordDistanceToWordsInSentence.Add(wordInSentence, LevenshteinDistance.Compute(word, wordInSentence)); } return(wordDistanceToWordsInSentence); }
internal async Task <GlobalFaqEntry> FuzzyGetGlobalEntryAsync(string name) { var guildEntries = await _mongo.GetCollection <GlobalFaqEntry>(_client).GetGlobalFaqsAsync(); var entryDictionary = guildEntries.ToDictionary(globalEntry => globalEntry, globalEntry => LevenshteinDistance.Compute(name, globalEntry.Name)); var entry = entryDictionary.MinBy(pair => pair.Value); return(entry.Value <= _config.MaxLevenshteinDistance ? entry.Key : null); }
internal async Task <Dictionary <GlobalFaqEntry, int> > GetSimilarGlobalEntries(string name) { var guildEntries = await _mongo.GetCollection <GlobalFaqEntry>(_client).GetGlobalFaqsAsync(); var entryDictionary = guildEntries.ToDictionary(globalEntry => globalEntry, globalEntry => LevenshteinDistance.Compute(name, globalEntry.Name)); return(entryDictionary.Where(pair => pair.Value <= _config.MaxLevenshteinDistance).OrderBy(pair => pair.Value) .ToDictionary()); }
public void ShouldReturnKeyAndCostOfOne() { string validOpt = "Cheese"; string optToValidate = "Chaese"; var expected = (validOpt, 1); LevenshteinCost result = LevenshteinDistance.Compute(optToValidate, validOpt); Assert.AreEqual(expected.Item2, result.Cost); Assert.AreEqual(expected.validOpt, result.Key); }
public static bool CurrentListComparer(string line) { foreach (var item in itemList) { if (LevenshteinDistance.Compute(line, item.Name) < 8) { return(false); } } return(true); }
private void uninstalled_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { int limit = 6; if (e.Action == NotifyCollectionChangedAction.Add) { // scroll the new item into view //listView.ScrollIntoView(e.NewItems[0]); //Console.WriteLine(((INSTALLED)e.NewItems[0]).name); INSTALLED lv_uninstalled_item = ((INSTALLED)e.NewItems[0]); INSTALLEDS.Remove(lv_uninstalled_item); foreach (SHORTCUT item in lv_alllnk.Items) { int diff = LevenshteinDistance.Compute(item.name, lv_uninstalled_item.name); if (diff <= limit) { lv_dellnk.Items.Add(item); break; } } foreach (SHORTCUT item in lv_allstartmenu.Items) { int diff = LevenshteinDistance.Compute(item.name, lv_uninstalled_item.name); if (diff <= limit) { lv_delstartmenu.Items.Add(item); break; } } } else if (e.Action == NotifyCollectionChangedAction.Remove) { INSTALLED lv_uninstalled_item = ((INSTALLED)e.OldItems[0]); INSTALLEDS.Add(lv_uninstalled_item); foreach (SHORTCUT item in lv_dellnk.Items) { int diff = LevenshteinDistance.Compute(item.name, lv_uninstalled_item.name); if (diff < limit) { lv_dellnk.Items.Remove(item); break; } } foreach (SHORTCUT item in lv_delstartmenu.Items) { int diff = LevenshteinDistance.Compute(item.name, lv_uninstalled_item.name); if (diff < limit) { lv_delstartmenu.Items.Remove(item); break; } } } }