public void Run(IProgress <BuddhabrotReportProgress> progress = null) { long previousTotalHits = 0; do { float cx = XMin + (float)Rand.NextDouble() * (XMax - XMin); float cy = YMin + (float)Rand.NextDouble() * (Ymax - YMin); var point = new BuddhabrotPoint(cx, cy, MaxIteration); Hits.Add(point); if ((TotalHits - previousTotalHits * 1d) / HitsMax > 1 / 100d) { previousTotalHits = TotalHits; if (progress != null) { //progress.Report(new BuddhabrotReportProgress(this)); } } }while (Hits.Count < HitsMax); Completed = true; if (progress != null) { // progress.Report(new BuddhabrotReportProgress(this, true)); } }
internal void Reset() { LastUpdateTime = DateTime.Now; LastMergeCount = 0; Hits.Clear(); Hits.FireListUpdated(); }
public void Initialize_Indexes_All_Nodes() { string elementIdForTestingSearch = _deepNodeFinder.GetNodesForIndexing()[0].Id; int expectedNumNodes = _deepNodeFinder.GetNodesForIndexing().Length; Assert.AreEqual("usfr-pte_NetCashFlowsProvidedUsedOperatingActivitiesDirectAbstract", elementIdForTestingSearch, "TEST SANITY: element id for test search"); Assert.AreEqual(1595, expectedNumNodes, "TEST SANITY: Number of nodes in found in the test taxonomy"); IndexReader indexReader = IndexReader.Open(_indexMgr.LuceneDirectory_ForTesting); Assert.AreEqual(expectedNumNodes, indexReader.NumDocs(), "An incorrect number of documents were found in the Lucene directory after initialization"); IndexSearcher searcher = new IndexSearcher(_indexMgr.LuceneDirectory_ForTesting); try { Hits results = searcher.Search(new TermQuery(new Term(LuceneNodeIndexer.ELEMENTID_FOR_DELETING_FIELD, elementIdForTestingSearch))); Assert.AreEqual(1, results.Length(), "Search results should only have 1 hit"); Assert.AreEqual(elementIdForTestingSearch, results.Doc(0).Get(LuceneNodeIndexer.ELEMENTID_FIELD), "Search results yielded the wrong element!"); } finally { searcher.Close(); } }
static void Main(string[] args) { Directory index = new RAMDirectory(); Analyzer analyzer = new KeywordAnalyzer(); IndexWriter writer = new IndexWriter(index, analyzer, true); Document doc = new Document(); doc.Add(new Field("title", "t1", Field.Store.YES, Field.Index.TOKENIZED)); writer.AddDocument(doc); doc = new Document(); doc.Add(new Field("title", "t2", Field.Store.YES, Field.Index.TOKENIZED)); writer.AddDocument(doc); writer.Close(); Searcher searcher = new IndexSearcher(index); Query query = new MatchAllDocsQuery(); Filter filter = new LuceneCustomFilter(); Sort sort = new Sort("title", true); Hits hits = searcher.Search(query, filter, sort); IEnumerator hitsEnumerator = hits.Iterator(); while (hitsEnumerator.MoveNext()) { Hit hit = (Hit)hitsEnumerator.Current; Console.WriteLine(hit.GetDocument().GetField("title"). StringValue()); } }
public ArrayList getNotesMatchingTitle(string search) { ArrayList snotes = new ArrayList(); try { QueryParser parser = new QueryParser("title", analyzer); string lucsearch = search + "*^4" + " content:" + search + "*"; Query query = parser.Parse(lucsearch); IndexSearcher searcher = new IndexSearcher(lucIdx); Hits hits = searcher.Search(query); int results = hits.Length(); Console.WriteLine("Found {0} results", results); for (int i = 0; i < results; i++) { Document doc = hits.Doc(i); //float score = hits.Score (i); snotes.Add(new Note(doc.Get("title"), doc.Get("lastmod"))); } } catch (Exception e) { Console.WriteLine("ERROR Search: " + e.Message); } return(snotes); }
IEnumerable <Hit> GetProximalHits(int proximity) { var proximalHits = new List <Hit>(); Hits = Hits.OrderByDescending(h => h.Index).ThenByDescending(h => h.Skip).ToList(); for (var i = 0; i < Hits.Count(); i++) { var current = Hits[i]; var j = i + 1 < Hits.Count() ? i + 1 : i; var next = Hits[j]; var currentIndex = current.Index; var nextIndex = next.Index; var currentSkip = current.Skip; var nextSkip = next.Skip; if (Math.Abs(currentSkip - nextSkip) <= proximity || Math.Abs(currentIndex - nextIndex) <= proximity) { if (!proximalHits.Contains(current)) { proximalHits.Add(current); } if (!proximalHits.Contains(next)) { proximalHits.Add(next); } } } Hits = Hits.OrderBy(h => h.Index).ThenBy(h => h.Skip).ToList(); return(proximalHits); }
/// <summary> /// Searches the index. /// </summary> /// <param name="indexPath">The index path.</param> /// <param name="searchText">The search text.</param> /// <returns></returns> public List <IndexInformation> SearchIndex(string indexPath, string searchText) { List <IndexInformation> searchResults = new List <IndexInformation>(); try { using (Lucene.Net.Store.Directory directory = FSDirectory.Open(new DirectoryInfo(indexPath))) { Analyzer analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29); var parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, RegularExpression, analyzer); Query query = parser.Parse(searchText); using (var searcher = new IndexSearcher(directory, true)) { Hits topDocs = searcher.Search(query); if (topDocs != null) { for (int i = 0; i < topDocs.Length(); i++) { searchResults.Add(new IndexInformation { FilePath = topDocs.Doc(i).Get(FilePath), Date = topDocs.Doc(i).Get(Date) }); } } } } } catch (Exception ex) { throw; } return(searchResults); }
private bool isInIndex(IndexableFileInfo fileInfo) { IndexSearcher searcher = new IndexSearcher(this.luceneIndexDir); try { BooleanQuery bq = new BooleanQuery(); bq.Add(new TermQuery(new Term("filename", fileInfo.Filename)), BooleanClause.Occur.MUST); bq.Add(new TermQuery(new Term("LastModified", DateTools.DateToString(fileInfo.LastModified, DateTools.Resolution.SECOND))), BooleanClause.Occur.MUST); Hits hits = searcher.Search(bq); int count = hits.Length(); if (count > 0) { return(true); } } catch (Exception ex) { Console.Write(ex.Message); } finally { searcher.Close(); } return(false); }
public static IDictionary <string, string> Query(string searchTerm) { BuildIndexTask.Wait(); System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex("[^a-zA-Z0-9]"); searchTerm = rgx.Replace(searchTerm, " "); IndexSearcher searcher = new IndexSearcher(luceneIndexDirectory); QueryParser parser = new QueryParser("Guideline", analyzer); Query query = parser.Parse(searchTerm.ToLower()); Hits hitsFound = searcher.Search(query); IDictionary <string, string> results = new Dictionary <string, string>(); for (int i = 0; i < hitsFound.Length(); i++) { Document doc = hitsFound.Doc(i); float score = hitsFound.Score(i); string CodeSnippetName = doc.Get("CodeSnippetName"); string CodeSnippet = doc.Get("CodeSnippet"); if (score > 0.6) { results.Add(CodeSnippetName, CodeSnippet); } } searcher.Close(); return(results); }
public TokenResult FindExact(TokenParameter parameter) { IndexSearcher indexSearcher = Searcher; string projectIdentifier = string.Format("{0}_{1}", parameter.Username, parameter.Project).ToLower(); var projectQuery = new TermQuery(new Term(ItemProjectIdentifier, projectIdentifier)); var identfierQuery = new TermQuery(new Term(ItemIdentifier, string.Format("{0}", parameter.FullyQualifiedName))); var booleanQuery = new BooleanQuery(); booleanQuery.Add(projectQuery, BooleanClause.Occur.MUST); booleanQuery.Add(identfierQuery, BooleanClause.Occur.MUST); Hits hits = indexSearcher.Search(booleanQuery); if (hits.Length() > 0) { var document = hits.Doc(0); // Take only the first one string filePath = document.Get(ItemPath); int location = Int32.Parse(document.Get(ItemLocation)); var projectCodeDirectory = this.applicationConfigurationProvider.GetProjectSourceCodePath(parameter.Username, parameter.Project); //string relativePath = filePath //projectCodeDirectory.MakeRelativePath(filePath); return(new Models.TokenResult { FileName = Path.GetFileName(filePath), Position = location, Path = filePath }); } return(null); }
public static IList <string> Search(string searchTerm) { System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex("[^a-zA-Z0-9]"); searchTerm = rgx.Replace(searchTerm, " "); IndexSearcher searcher = new IndexSearcher(luceneIndexDirectory); QueryParser parser = new QueryParser("Data", analyzer); Query query = parser.Parse(searchTerm.ToLower()); Hits hitsFound = searcher.Search(query); IList <string> results = new List <string>(); for (int i = 0; i < hitsFound.Length(); i++) { Document doc = hitsFound.Doc(i); float score = hitsFound.Score(i); string fileName = doc.Get("FileName"); if (score > 0.6) { results.Add(doc.Get("FileName")); } } searcher.Close(); return(results); }
public IEnumerable <DataFileRow> Search(string searchTerm) { IndexSearcher searcher = new IndexSearcher(luceneIndexDirectory); QueryParser parser = new QueryParser("LineText", analyzer); Query query = parser.Parse(searchTerm); Hits hitsFound = searcher.Search(query); List <DataFileRow> results = new List <DataFileRow>(); DataFileRow sampleDataFileRow = null; for (int i = 0; i < hitsFound.Length(); i++) { sampleDataFileRow = new DataFileRow(); Document doc = hitsFound.Doc(i); sampleDataFileRow.LineNumber = int.Parse(doc.Get("LineNumber")); sampleDataFileRow.LineText = doc.Get("LineText"); float score = hitsFound.Score(i); sampleDataFileRow.Score = score; results.Add(sampleDataFileRow); } luceneIndexDirectory.Close(); searcher.Close(); return(results.OrderByDescending(x => x.Score).ToList()); }
public static void Main(string[] args) { string indexpath = args[0]; string query = args[1]; IndexSearcher searcher = new IndexSearcher(indexpath); Query parsedquery = QueryParser.Parse(query, "summary", new StandardAnalyzer()); Hits hits = searcher.Search(parsedquery); Console.WriteLine("Found " + hits.Length() + " document(s) that matched query '" + query + "':\n"); for (int i = 0; i < hits.Length(); i++) { Document doc = hits.Doc(i); Console.WriteLine(hits.Score(i) + ": " + doc.Get("excerpt") + "\n"); if (i == 50) { break; } } searcher.Close(); }
public static void Execute(InstrumentationResult result, string output, float threshold) { var hits = Hits.TryReadFromFile(result.HitsFile); var document = new XDocument( new XDeclaration("1.0", "utf-8", null), CreateCoverageElement(result, hits) ); var xmlWriterSettings = new XmlWriterSettings { Indent = true }; var path = Path.GetDirectoryName(output); if (!string.IsNullOrEmpty(path)) { Directory.CreateDirectory(Path.GetDirectoryName(output)); } using (StreamWriter sw = File.CreateText(output)) using (XmlWriter writer = XmlWriter.Create(sw, xmlWriterSettings)) { document.WriteTo(writer); } }
protected void BindLucene() { StandardAnalyzer analyzer = new Lucene.Net.Analysis.Standard.StandardAnalyzer(); IndexSearcher searcher = new IndexSearcher("C:\\Clients\\NWTD5.0.200\\SearchIndex\\eCommerceFramework\\CatalogEntryIndexer"); BooleanQuery boolQuery = new BooleanQuery(); boolQuery.Add(new TermQuery(new Term("_catalog", "NWTD")), BooleanClause.Occur.MUST); Hits hits = searcher.Search(boolQuery, new Sort("TypeSort")); DataTable dt = new DataTable(); dt.Columns.Add("Code"); dt.Columns.Add("Name"); dt.Columns.Add("TypeSort"); for (int hitIndex = 0; hitIndex < hits.Length() && hitIndex < 10; hitIndex++) { Document hitDocument = hits.Doc(hitIndex); object[] param = new[] { hitDocument.GetField("Code").StringValue(), hitDocument.GetField("Name").StringValue(), hitDocument.GetField("TypeSort").StringValue() }; dt.Rows.Add(param); } this.gvLuceneSearchResults.DataSource = dt; this.gvLuceneSearchResults.DataBind(); }
public async Task <ActionResult <Hits> > Get(int id) { string spanId = string.Format("GET {0}", id); using (IScope scope = tracer.BuildSpan(spanId).StartActive(finishSpanOnDispose: true)) { var key = id.ToString(); Hits result = null; using (IScope getScope = tracer.BuildSpan("GetHits").AsChildOf(scope.Span).StartActive(finishSpanOnDispose: true)) { result = await cache.Get <Hits>(key); if (result != null) { getScope.Span.SetTag("Id", result.Id); } } if (result == null) { using (IScope createOrUpdateScope = tracer.BuildSpan("InitHits").AsChildOf(scope.Span).StartActive(finishSpanOnDispose: true)) { result = new Hits(id); await cache.CreateOrUpdate <Hits>(key, result); createOrUpdateScope.Span.SetTag("Id", result.Id); } } result.BackendVersion = version; return(result); } }
public List <string> Search(string text) { List <string> lstFilteredValue = new List <string>(); try { IndexSearcher MyIndexSearcher = new IndexSearcher(LuceneDirectory); Query mainQuery = this.GetParsedQuerywc(text); //Do the search Hits hits = MyIndexSearcher.Search(mainQuery); int results = hits.Length(); for (int i = 0; i < results; i++) { Document doc = hits.Doc(i); float score = hits.Score(i); lstFilteredValue.Add(doc.Get("Name") + "," + doc.Get("Id")); } } catch (Exception GeneralException) { } return(lstFilteredValue); }
public async Task Post([FromBody] Hits hits) { string spanId = string.Format("POST {0} {1}", hits.Id, hits.Count); using (IScope scope = tracer.BuildSpan(spanId).StartActive(finishSpanOnDispose: true)) { var key = hits.Id.ToString(); var result = await cache.Get <Hits>(key); if (result != null) { scope.Span.SetTag("Id", result.Id); } if (result == null) { result = new Hits(hits.Id); } using (IScope createOrUpdateScope = tracer.BuildSpan("UpdateHits").AsChildOf(scope.Span).StartActive(finishSpanOnDispose: true)) { result.Count++; createOrUpdateScope.Span.SetTag("Count", result.Count); result.LastUpdated = DateTime.Now; await cache.CreateOrUpdate <Hits>(key, result); } } }
public CodeCoverageTracer(List <CodeCoveragePoint> points) { _debug = Environment.GetEnvironmentVariable("PESTER_CC_DEBUG") == "1"; _debugFile = Environment.GetEnvironmentVariable("PESTER_CC_DEBUG_FILE") ?? "CoverageTestFile"; foreach (var point in points) { var key = $"{point.Line}:{point.Column}"; if (!Hits.ContainsKey(point.Path)) { var lineColumn = new Dictionary <string, List <CodeCoveragePoint> > (StringComparer.OrdinalIgnoreCase) { [key] = new List <CodeCoveragePoint> { point } }; Hits.Add(point.Path, lineColumn); continue; } var hits = Hits[point.Path]; if (!hits.ContainsKey(key)) { hits.Add(key, new List <CodeCoveragePoint> { point }); continue; } else { var pointsOnLineAndColumn = hits[key]; pointsOnLineAndColumn.Add(point); } } }
public override List <SearchResult> Search(string searchStr) { List <SearchResult> results = new List <SearchResult>(); string cleanSearchStr = cleaner.Replace(searchStr, "").ToLower().Trim(); IndexSearcher searcher = new IndexSearcher(directory); //QueryParser parser = new QueryParser("title", analyzer); //Query query = parser.Parse(cleanSearchStr + "~0.7"); Query query = parser.Parse(cleanSearchStr + "~0.7"); Hits hits = searcher.Search(query); int resultCount = hits.Length(); for (int i = 0; i < resultCount; i++) { SearchResult result = new SearchResult(); result.Item = DatabaseManager.Get <T>(int.Parse(hits.Doc(i).Get("id"))); result.Score = hits.Score(i); results.Add(result); } return(results); }
public void ShouldMergeTests() { var tests = new[] { new HitTestMethod("Sample.Tests.XUnit, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Sample.Tests.XUnit.UnitTest1", "XUnitTest2", @"C:\\Repos\\minicover\\sample\\test\\Sample.Tests.XUnit\\bin\\Debug\\netcoreapp2.0\\Sample.Tests.XUnit.dll", 1, new Dictionary <int, int> { { 8, 1 }, }), new HitTestMethod("Sample.Tests.XUnit, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Sample.Tests.XUnit.UnitTest1", "XUnitTest2", @"C:\\Repos\\minicover\\sample\\test\\Sample.Tests.XUnit\\bin\\Debug\\netcoreapp2.0\\Sample.Tests.XUnit.dll", 1, new Dictionary <int, int> { { 8, 1 }, }) }; var hits = Hits.ConvertToHits(tests); hits.GetInstructionHitCount(8).ShouldBe(2); hits.GetInstructionTestMethods(8).ShouldHaveSingleItem(); hits.GetInstructionTestMethods(8).First().Counter.ShouldBe(2); }
public List <string> GetDocumentsSimilarToDocument(string document_filename) { List <string> fingerprints = new List <string>(); IndexReader index_reader = IndexReader.Open(LIBRARY_INDEX_BASE_PATH, true); Searcher index_searcher = new IndexSearcher(index_reader); LuceneMoreLikeThis mlt = new LuceneMoreLikeThis(index_reader); mlt.SetFieldNames(new string[] { "content" }); mlt.SetMinTermFreq(0); Query query = mlt.Like(new StreamReader(document_filename)); Hits hits = index_searcher.Search(query); var i = hits.Iterator(); while (i.MoveNext()) { Hit hit = (Hit)i.Current; string fingerprint = hit.Get("fingerprint"); fingerprints.Add(fingerprint); } // Close the index index_searcher.Close(); index_reader.Close(); return(fingerprints); }
public override SqlString ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery, IDictionary <string, IFilter> enabledFilters) { System.Type type = GetCriteriaClass(criteria); ISearchFactoryImplementor searchFactory = ContextHelper.GetSearchFactory(GetSession(criteria)); Iesi.Collections.Generic.ISet <System.Type> types; IndexSearcher searcher = FullTextSearchHelper.BuildSearcher(searchFactory, out types, type); if (searcher == null) { throw new SearchException("Could not find a searcher for class: " + type.FullName); } Lucene.Net.Search.Query query = FullTextSearchHelper.FilterQueryByClasses(types, luceneQuery); Hits hits = searcher.Search(query); List <object> ids = new List <object>(); for (int i = 0; i < hits.Length(); i++) { object id = DocumentBuilder.GetDocumentId(searchFactory, type, hits.Doc(i)); ids.Add(id); } base.Values = ids.ToArray(); return(base.ToSqlString(criteria, criteriaQuery, enabledFilters)); }
public static void PrintHits(Hits hits) { if (hits == null) { Console.WriteLine("Hits: 0"); } else { Console.WriteLine("Hits: " + hits.Length()); // iterate over the first few results. for (int i = 0; i < 50 && i < hits.Length(); i++) { var doc = hits.Doc(i); string id = doc.Get("id"); int n; for (n = 0; n < Data.GetLength(0); ++n) { if (id == Data[n, 1]) { Console.WriteLine("{0}: {1} ==> {2} {3}", n, GetPath(n), GetContent(n), GetExternals(n)); break; } } } Console.WriteLine("-"); } }
public string DidYouMean(string pattern) { try { IndexSearcher searcher = new IndexSearcher(m_HistoryPath); Term t = new Term(Constants.SearchedText, pattern); FuzzyQuery query = new FuzzyQuery(t); Hits hits = searcher.Search(query); if (hits.Length() != 0) { return(hits.Doc(0).Get(Constants.SearchedText)); } else { return(""); } } catch (Exception) { return(""); } }
/// <summary> /// 根据产品编号搜索产品 /// (从索引) /// </summary> /// <param name="productSysNo">产品编号</param> /// <returns>产品列表</returns> /// <remarks>2013-08-12 黄波 创建</remarks> public PdProductIndex Search(int productSysNo , ProductStatus.产品价格来源 priceSource = ProductStatus.产品价格来源.会员等级价 , int priceSourceSysNo = CustomerLevel.初级) { var returnValue = new PdProductIndex(); BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term("SysNo", productSysNo.ToString())), BooleanClause.Occur.SHOULD); //搜索 var searchIndex = Hyt.Infrastructure.Lucene.ProductIndex.Searcher; Hits hits = searchIndex.Search(query); for (var i = 0; i < hits.Length(); i++) { try { var pdProductIndex = Hyt.Infrastructure.Lucene.ProductIndex.Instance.DocumentToModel(hits.Doc(i)); pdProductIndex.RankPrice = GetProductRankPrice(pdProductIndex.Prices, pdProductIndex.BasicPrice, priceSource, priceSourceSysNo); returnValue = pdProductIndex; } catch { } } // searchIndex.Close(); return(returnValue); }
public bool PreFilterMessage(ref Message m) { switch (m.Msg) { case (int)MSG_RECV.FACET_CHANGED: Map = (byte)m.WParam; if (!Global.IsFacetChanged && !Global.FreeView) { Global.Facet = Map; } break; case (int)MSG_RECV.HP_MAXHP: Hits.Set((ushort)m.LParam.ToInt32(), (ushort)(m.WParam.ToInt32() & 65535)); break; case (int)MSG_RECV.MANA_MAXMANA: Mana.Set((ushort)m.LParam.ToInt32(), (ushort)(m.WParam.ToInt32() & 65535)); break; case (int)MSG_RECV.STAM_MAXSTAM: Stamina.Set((ushort)m.LParam.ToInt32(), (ushort)(m.WParam.ToInt32() & 65535)); break; } return(false); }
private void Awake() { pickupItem = GetComponent <PickupItem>(); pickupItem.onPickupItemHealth += HealthPowerUp; hitsPersistentObject = GameObject.FindObjectOfType <Hits>(); UpdateHitsTaken(hits); }
public bool TryHit(Location location) { if (location.X < 0 || location.X >= _mapConfiguration.Width) { throw new InvalidOperationException("X coorinate is out of range."); } if (location.Y < 0 || location.Y >= _mapConfiguration.Height) { throw new InvalidOperationException("X coorinate is out of range."); } if (GetMapCellStatus(location.X, location.Y) != MapCellStatus.Default) { throw new InvalidOperationException("This cell has already been chosen."); } var isHit = Ships.Any(ship => ship.TryHit(location)); if (isHit) { Hits.Add(location); } else { Misses.Add(location); } return(isHit); }
public override List <ISearchEntity> GetSearchResult(out int MatchCount) { Analyzer analyzer = new StandardAnalyzer(); IndexSearcher searcher = new IndexSearcher(searchInfo.ConfigElement.IndexDirectory); MultiFieldQueryParser parserName = new MultiFieldQueryParser(new string[] { "title", "content", "keywords" }, analyzer); Query queryName = parserName.Parse(searchInfo.QueryString); Hits hits = searcher.Search(queryName); List <ISearchEntity> ResultList = new List <ISearchEntity>(); for (int i = 0; i < hits.Length(); i++) { Document doc = hits.Doc(i); ResultList.Add((ISearchEntity) new NewsModel() { EntityIdentity = Convert.ToInt32(doc.Get("newsid")), Title = Convert.ToString(doc.Get("title")), Content = Convert.ToString(doc.Get("content")), Keywords = doc.Get("keywords") }); } searcher.Close(); MatchCount = hits.Length(); return(ResultList); }