Beispiel #1
0
        public void MatchTest()
        {
            var sources = new List <string>()
            {
                "file open in browser-test",
                "Install Package",
                "add new bsd",
                "Inste",
                "aac",
            };


            var results = new List <Wox.Plugin.Result>();

            foreach (var str in sources)
            {
                results.Add(new Plugin.Result()
                {
                    Title = str,
                    Score = FuzzyMatcher.Create("inst").Evaluate(str).Score
                });
            }

            results = results.Where(x => x.Score > 0).OrderByDescending(x => x.Score).ToList();

            Assert.IsTrue(results.Count == 3);
            Assert.IsTrue(results[0].Title == "Inste");
            Assert.IsTrue(results[1].Title == "Install Package");
            Assert.IsTrue(results[2].Title == "file open in browser-test");
        }
 public void DamerauLevenshteinDistanceStrTests()
 {
     var str1 = "dog";
     var str2 = "d";
     var e    = FuzzyMatcher.DamerauLevenshteinDistanceStr(str1, str2, 10);
     var p    = 0;
 }
Beispiel #3
0
        protected override List <Result> QueryInternal(Query query)
        {
            if (string.IsNullOrEmpty(query.RawQuery) || query.RawQuery.EndsWith(" ") || query.RawQuery.Length <= 1)
            {
                return(new List <Result>());
            }

            var            fuzzyMather = FuzzyMatcher.Create(query.RawQuery);
            List <Program> returnList  = installedList.Where(o => MatchProgram(o, fuzzyMather)).ToList();

            returnList.ForEach(ScoreFilter);
            //return ordered list instead of return the score, because programs scores will affect other
            //plugins, the weight of program should be less than the plugins when they showed at the same time.
            returnList = returnList.OrderByDescending(o => o.Score).ToList();

            return(returnList.Select(c => new Result()
            {
                Title = c.Title,
                SubTitle = c.ExecutePath,
                IcoPath = c.IcoPath,
                Score = 0,
                Action = (e) =>
                {
                    context.HideApp();
                    context.ShellRun(c.ExecutePath);
                    return true;
                }
            }).ToList());
        }
        public List <Result> Query(Query query)
        {
            string param = query.GetAllRemainingParameter().TrimStart();

            // Should top results be returned? (true if no search parameters have been passed)
            var topResults = string.IsNullOrEmpty(param);

            var returnList = cachedBookmarks;

            if (!topResults)
            {
                // Since we mixed chrome and firefox bookmarks, we should order them again
                var fuzzyMatcher = FuzzyMatcher.Create(param);
                returnList = cachedBookmarks.Where(o => MatchProgram(o, fuzzyMatcher)).ToList();
                returnList = returnList.OrderByDescending(o => o.Score).ToList();
            }

            return(returnList.Select(c => new Result()
            {
                Title = c.Name,
                SubTitle = "Bookmark: " + c.Url,
                IcoPath = @"Images\bookmark.png",
                Score = 5,
                Action = (e) =>
                {
                    context.API.HideApp();
                    context.API.ShellRun(c.Url);
                    return true;
                }
            }).ToList());
        }
Beispiel #5
0
        public override List <Result> Query(Query query)
        {
            var matcher = FuzzyMatcher.Create(query.RawQuery);

            var ret = new List <Result>();

            foreach (var file in FileCache)
            {
                var fn  = Path.GetFileName(file);
                var ans = matcher.Evaluate(fn);
                if (ans.Success)
                {
                    ret.Add(CreateResult(file, ans.Score));
                }
                else
                {
                    var pyans = matcher.EvaluatePinYin(fn);
                    if (pyans.Success)
                    {
                        ret.Add(CreateResult(file, pyans.Score));
                    }
                }
            }
            return(ret);
        }
Beispiel #6
0
        private Result ConvertMFTSearch(MFTSearchRecord record, string query)
        {
            string icoPath = "Images/file.png";

            if (record.IsFolder)
            {
                icoPath = "Images/folder.png";
            }

            string       name    = Path.GetFileName(record.FullPath);
            FuzzyMatcher matcher = FuzzyMatcher.Create(query);

            return(new Result()
            {
                Title = name,
                Score = matcher.Evaluate(name).Score,
                SubTitle = record.FullPath,
                IcoPath = icoPath,
                Action = _ =>
                {
                    try
                    {
                        Process.Start(record.FullPath);
                    }
                    catch
                    {
                        context.API.ShowMsg("Can't open " + record.FullPath, string.Empty, string.Empty);
                        return false;
                    }
                    return true;
                },
                ContextMenu = GetContextMenu(record)
            });
        }
        public void GetBestMatchesTest1()
        {
            var prude       = "prude";
            var bestMatches = TestUtilities.DictionaryWords.Select(w => FuzzyMatcher.FuzzyMatch(w, prude)).GetBestMatches();

            Assert.IsTrue(bestMatches.Length == 1);
        }
Beispiel #8
0
        private static void TestFuzzyMatch(string desiredItem, string notDesiredItem, string searchText)
        {
            (bool isMatch, int score)desiredItemResult    = FuzzyMatcher.FuzzyMatch(desiredItem, searchText);
            (bool isMatch, int score)notDesiredItemResult = FuzzyMatcher.FuzzyMatch(notDesiredItem, searchText);

            desiredItemResult.score.Should().BeGreaterThan(notDesiredItemResult.score);
        }
        public void GetBestMatchesTest2()
        {
            var falcie      = "fal";
            var bestMatches = TestUtilities.DictionaryWords.Select(w => FuzzyMatcher.FuzzyMatch(w, falcie)).GetBestMatches();

            Assert.IsTrue(bestMatches.Length == 8);
        }
Beispiel #10
0
        public void Search_FromCandidates_ShouldAsExpected()
        {
            var ss     = new FuzzyMatcher(_candidates);
            var result = ss.Match("40' High Cube Dry");

            Assert.AreEqual(("_40 HC 40' HIGH CUBE CONTAINER", 3), result);
        }
Beispiel #11
0
        protected override List <Result> QueryInternal(Query query)
        {
            if (string.IsNullOrEmpty(query.RawQuery) || query.RawQuery.EndsWith(" ") || query.RawQuery.Length <= 1)
            {
                return(new List <Result>());
            }

            var             fuzzyMather = FuzzyMatcher.Create(query.RawQuery);
            List <Bookmark> returnList  = bookmarks.Where(o => MatchProgram(o, fuzzyMather)).ToList();

            returnList = returnList.OrderByDescending(o => o.Score).ToList();
            return(returnList.Select(c => new Result()
            {
                Title = c.Name,
                SubTitle = "Bookmark: " + c.Url,
                IcoPath = Path.GetDirectoryName(Application.ExecutablePath) + @"\Images\bookmark.png",
                Score = 5,
                Action = (e) =>
                {
                    context.HideApp();
                    context.ShellRun(c.Url);
                    return true;
                }
            }).ToList());
        }
Beispiel #12
0
        protected override List <Result> QueryInternal(Query query)
        {
            if (query.RawQuery.Trim().Length <= 1)
            {
                return(new List <Result>());
            }

            var            fuzzyMather = FuzzyMatcher.Create(query.RawQuery);
            List <Program> returnList  = programs.Where(o => MatchProgram(o, fuzzyMather)).ToList();

            returnList.ForEach(ScoreFilter);
            returnList = returnList.OrderByDescending(o => o.Score).ToList();

            return(returnList.Select(c => new Result()
            {
                Title = c.Title,
                SubTitle = c.ExecutePath,
                IcoPath = c.IcoPath,
                Score = c.Score,
                Action = (e) =>
                {
                    context.API.HideApp();
                    context.API.ShellRun(c.ExecutePath);
                    return true;
                }
            }).ToList());
        }
        public void FuzzyMatchWithScoreTest()
        {
            var match = FuzzyMatcher.FuzzyMatch(ReferenceString, ReferencePattern);

            Assert.IsInstanceOf <FuzzyMatchResult>(match);
            Assert.IsTrue(match.DidMatch);
            Assert.AreEqual(-16, match.Score);
        }
        public void FuzzyMatchWordsWithPartialSpellingTest()
        {
            var facility = TestUtilities.DictionaryWords[133956];
            var facilityPartialSpellingMatchTest = FuzzyMatcher.FuzzyMatch(facility, "failt");

            Assert.IsTrue(facilityPartialSpellingMatchTest.DidMatch);
            Assert.IsTrue(facilityPartialSpellingMatchTest.Score == 15);
        }
        public void FuzzyMatchWithNoMatchAndSubZeroScoreTest()
        {
            var faciobrachial = TestUtilities.DictionaryWords[133963];
            var test          = FuzzyMatcher.FuzzyMatch(faciobrachial, "yt");

            Assert.IsFalse(test.DidMatch);
            Assert.IsTrue(test.Score == -13);
        }
        /// <summary>
        /// 通用(特征码替换)
        /// </summary>
        public void CommonPatch()
        {
            if (FileCommonModifyInfo == null)
            {
                throw new Exception("特征码替换:缺失对应特征码信息");
            }
            // 1. 拷贝一份临时文件
            File.Copy(FilePath, fileReplacedPath, true);
            // 2. 读取整个临时文件
            byte[] fileByteArray = File.ReadAllBytes(fileReplacedPath);
            // 3. 循环查找所有未替换的替换点
            int           needReplaceNum = 0;
            List <Change> changes        = new List <Change>();

            foreach (ReplacePattern pattern in FileCommonModifyInfo.ReplacePatterns)
            {
                int[] indexs = FuzzyMatcher.MatchNotReplaced(fileByteArray, pattern.Search, pattern.Replace);
                if (indexs.Length == 1)
                {
                    needReplaceNum++;
                    changes.Add(new Change(indexs[0], pattern.Replace));
                }
            }
            // 判断是否可以使用特征码替换的方式
            if (needReplaceNum == 0)
            {
                // 查找所有替换点
                int matchNum = 0;
                foreach (ReplacePattern pattern in FileCommonModifyInfo.ReplacePatterns)
                {
                    int[] indexs = FuzzyMatcher.MatchAll(fileByteArray, pattern.Search);
                    if (indexs.Length == 1)
                    {
                        matchNum++;
                    }
                }
                if (matchNum == FileCommonModifyInfo.ReplacePatterns.Count)
                {
                    throw new BusinessException("already_replace", "特征码替换:当前应用已经防撤回");
                }
                else
                {
                    throw new BusinessException("not_found_to_replace", "特征码替换:没有搜索到撤回的相关特征");
                }
            }
            else if (needReplaceNum == FileCommonModifyInfo.ReplacePatterns.Count)
            {
                // 正常情况下每个替换点都能找到
                // 3. 替换所有未替换的替换点
                FileUtil.EditMultiHex(fileReplacedPath, changes);
                // 4. 覆盖特征码替换后的文件
                File.Copy(fileReplacedPath, FilePath, true);
            }
            else
            {
                throw new BusinessException("found_num_err", "特征码替换:可替换的特征数不正确");
            }
        }
Beispiel #17
0
        private bool MatchProgram(Program program, FuzzyMatcher matcher)
        {
            var scores = new List <string> {
                program.Title, program.PinyinTitle, program.AbbrTitle, program.ExecuteName
            };

            program.Score = scores.Select(s => matcher.Evaluate(s ?? string.Empty).Score).Max();
            return(program.Score > 0);
        }
Beispiel #18
0
 public void MatchIsCaseInsensitive()
 {
     FuzzyMatcher f = new FuzzyMatcher();
     var filenames = new[]
     {
         "/home/ngeor/iTunes/ARTIST/Album/01 TRACK.mp3".NormalizePath()
     };
     var result = f.Find("/home/ngeor/iTunes/".NormalizePath(), filenames, "Artist - Track");
     CollectionAssert.AreEqual(filenames, result);
 }
Beispiel #19
0
 public void MatchStartsWith()
 {
     FuzzyMatcher f = new FuzzyMatcher();
     var filenames = new[]
         {
             "/home/ngeor/iTunes/Compilations/A Tribute To Abba/03 Gimme! Gimme! Gimme! (A Man After Midnight).mp3".NormalizePath()
         };
     var result = f.Find("/home/ngeor/iTunes/".NormalizePath(), filenames, "Compilations - Gimme, Gimme, Gimme");
     CollectionAssert.AreEqual(filenames, result);
 }
Beispiel #20
0
        public void FuzzyMatchWorks_Basic()
        {
            (bool isMatch, int score)goodResult = FuzzyMatcher.FuzzyMatch("Reilly Wood", "rei");
            Assert.True(goodResult.isMatch);

            (bool isMatch, int score)badResult = FuzzyMatcher.FuzzyMatch("Reilly Wood", "xcv");
            Assert.False(badResult.isMatch);

            Assert.True(goodResult.score > badResult.score);
        }
Beispiel #21
0
 public void SimpleWithTrackNumber()
 {
     FuzzyMatcher f = new FuzzyMatcher();
     var filenames = new[]
     {
         "/home/ngeor/iTunes/Artist/Album/01 Track.mp3".NormalizePath()
     };
     var result = f.Find("/home/ngeor/iTunes/".NormalizePath(), filenames, "Artist - Track");
     CollectionAssert.AreEqual(filenames, result);
 }
        public void FuzzyMatchUsingLinqTest1()
        {
            var results = TestUtilities.DictionaryWords
                          .Select(w => FuzzyMatcher.FuzzyMatch(w, "fal"))
                          .Where(r => r.DidMatch)
                          .ToList();

            Assert.IsNotEmpty(results);
            Assert.IsTrue(results.Count == 4956);
        }
Beispiel #23
0
 /// <summary>
 /// Gets a list of fuzzy matching commands and their scores.
 /// </summary>
 /// <param name="pattern">Command pattern.</param>
 /// <param name="context">Execution context.</param>
 /// <param name="commandOrigin">Command origin.</param>
 /// <param name="rediscoverImportedModules">If true, rediscovers imported modules.</param>
 /// <param name="moduleVersionRequired">Specific module version to be required.</param>
 /// <returns>IEnumerable tuple containing the CommandInfo and the match score.</returns>
 internal static IEnumerable <CommandScore> GetFuzzyMatchingCommands(string pattern, ExecutionContext context, CommandOrigin commandOrigin, bool rediscoverImportedModules = false, bool moduleVersionRequired = false)
 {
     foreach (CommandInfo command in GetMatchingCommands(pattern, context, commandOrigin, rediscoverImportedModules, moduleVersionRequired, useFuzzyMatching: true))
     {
         int score = FuzzyMatcher.GetDamerauLevenshteinDistance(command.Name, pattern);
         if (score <= FuzzyMatcher.MinimumDistance)
         {
             yield return(new CommandScore(command, score));
         }
     }
 }
Beispiel #24
0
        static void Main(string[] args)
        {
            var availableCommands = new [] { "stash", "diff", "commit" };

            Console.WriteLine("\nAvailable commands: {0}\n", string.Join(", ", availableCommands));

            var input = Console.ReadLine();
            var match = FuzzyMatcher.Match(availableCommands, input);

            Console.WriteLine($"Did you mean '{match}'?\n");
        }
Beispiel #25
0
 public void ShouldMatchAllArtistsIfOnlyTrackIsGiven()
 {
     FuzzyMatcher f = new FuzzyMatcher();
     var filenames = new[]
         {
             "/home/ngeor/iTunes/Artist1/Album3/01-2 Track.mp3".NormalizePath(),
             "/home/ngeor/iTunes/Artist2/Album4/01-2 Track.mp3".NormalizePath()
         };
     var result = f.Find("/home/ngeor/iTunes/".NormalizePath(), filenames, "Track");
     CollectionAssert.AreEqual(filenames, result);
 }
        public void FuzzyMatchDidNotMatchButScoreAboveZeroTest()
        {
            var plantaginaceae = TestUtilities.DictionaryWords[300001];

            var test = FuzzyMatcher.FuzzyMatch(plantaginaceae, "planet", true);

            Assert.IsFalse(test.DidMatch);
            Assert.IsTrue(test.MatchedIndices.Length == 5);
            Assert.IsTrue(test.Score > 0);
            Assert.IsTrue(test.Score == 17);
        }
        public void GetBestMatchTest()
        {
            var corvus       = "corvus";
            var matchResults = TestUtilities.DictionaryWords.Select(w => FuzzyMatcher.FuzzyMatch(w, corvus));
            var bestMatch    = matchResults.GetBestMatch();

            Assert.IsNotNull(bestMatch);
            Assert.IsInstanceOf <FuzzyMatchResult>(bestMatch);

            Assert.IsTrue(bestMatch.DidMatch);
            Assert.IsTrue(bestMatch.MatchedIndices.Length == corvus.Length);
        }
        public void FuzzyMatchFormattedConsecutiveStringTest()
        {
            var nescience = TestUtilities.DictionaryWords[252662];

            var test = FuzzyMatcher.FuzzyMatch(stringToSearch: nescience,
                                               pattern: "nes",
                                               formatString: true);

            Assert.IsTrue(test.DidMatch);
            Assert.IsTrue(test.Score == 15);
            Assert.IsTrue(test.FormattedString.Length > test.OriginalString.Length);
        }
        public void FuzzyMatchFormattedNonConsecutiveStringTest()
        {
            var nescience = TestUtilities.DictionaryWords[252662];

            var test = FuzzyMatcher.FuzzyMatch(stringToSearch: nescience,
                                               pattern: "neie",
                                               formatString: true);

            Assert.IsTrue(test.DidMatch);
            Assert.IsTrue(test.Score == 16);
            Assert.IsNotEmpty(test.FormattedString);
        }
        public void Pruned()
        {
            FuzzyMatcher f = MatcherBuilder.Matcher(new string[] {
                "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-_abcdefghijklmnopqrstuvwxyz",
                "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-_abcdefghijklmnopqrstuvwxyz",
                "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-_abcdefghijklmnopqrstuvwxyz",
                "+",
                "\\",
                "/"
            });

            Assert.AreEqual("-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz", f.Signature);
        }
Beispiel #31
0
        public void Search_WithWeights_ShouldAsExpected()
        {
            var weights = new ScoreWeights();

            weights.Add(
                ("container", 0.1m),
                ("STANDARD", 0.3m)
                );
            var ss     = new FuzzyMatcher(_candidates, weights);
            var result = ss.Match("25' STANDARD CONTAINER");

            Assert.AreEqual((null, 0.4m), result);
        }
Beispiel #32
0
        public void GivenRegularMatcher_ExpectGreaterDistanceThanNormalizedMatcher()
        {
            IFuzzyMatcher <string, string> regularStringMatcher = new FuzzyMatcher <string, string>(StringTargets, new StringDistance());

            GivenNormalizedMatcher_ExpectLessDistanceThanRegularMatcher(stringMatcher, regularStringMatcher, queryToString);

            IFuzzyMatcher <string, EnPronunciation> regularPhoneticMatcher = new FuzzyMatcher <string, EnPronunciation>(StringTargets, new EnPhoneticDistance(), queryToPronunciation);

            GivenNormalizedMatcher_ExpectLessDistanceThanRegularMatcher(phoneticMatcher, regularPhoneticMatcher, queryToPronunciation);

            IFuzzyMatcher <string, DistanceInput> regularHybridMatcher = new FuzzyMatcher <string, DistanceInput>(StringTargets, new EnHybridDistance(PhoneticWeightPercentage), queryToDistanceInput);

            GivenNormalizedMatcher_ExpectLessDistanceThanRegularMatcher(hybridMatcher, regularHybridMatcher, queryToDistanceInput);
        }
Beispiel #33
0
        private bool MatchProgram(Program program, FuzzyMatcher matcher)
        {
            program.Score = matcher.Score(program.Title);
            if (program.Score > 0)
            {
                return(true);
            }
            program.Score = matcher.Score(ChineseToPinYin.ToPinYin(program.Title).Replace(" ", ""));
            if (program.Score > 0)
            {
                return(true);
            }

            return(false);
        }
        public void FuzzyMatcherUsingLinqTest2()
        {
            var results = TestUtilities
                          .DictionaryWords
                          .Select(w => FuzzyMatcher.FuzzyMatch(w, "involute", true))
                          .Where(r => r.DidMatch || r.Score > 0)
                          .ToList();

            Assert.IsNotEmpty(results);
            Assert.IsTrue(results.Count == 13839);

            var didMatch = results.Where(r => r.DidMatch).ToList();

            Assert.IsNotEmpty(didMatch);
            Assert.IsTrue(didMatch.Count == 16);
        }