/// <summary> /// Find the best move for a player using minmax search /// </summary> /// <param name="chessBoard"> Chess board</param> /// <param name="searchMode"> Search mode</param> /// <param name="ePlayerColor"> Color doing the move</param> /// <param name="moveList"> Move list</param> /// <param name="arrIndex"> Order of evaluation of the moves</param> /// <param name="posInfo"> Information about pieces attacks</param> /// <param name="moveBest"> Best move found</param> /// <param name="iPermCount"> Nb of permutations evaluated</param> /// <param name="iCacheHit"> Nb of cache hit</param> /// <param name="iMaxDepth"> Maximum depth evaluated</param> /// <returns> /// true if a move has been found /// </returns> protected override bool FindBestMove(ChessBoard chessBoard, SearchEngine.SearchMode searchMode, ChessBoard.PlayerColorE ePlayerColor, List<ChessBoard.MovePosS> moveList, int[] arrIndex, ChessBoard.PosInfoS posInfo, ref ChessBoard.MovePosS moveBest, out int iPermCount, out int iCacheHit, out int iMaxDepth) { bool bRetVal = false; DateTime dtTimeOut; int iDepth; int iPermCountAtLevel; iPermCount = 0; iCacheHit = 0; if (searchMode.m_iSearchDepth == 0) { dtTimeOut = DateTime.Now + TimeSpan.FromSeconds(searchMode.m_iTimeOutInSec); iDepth = 0; do { bRetVal = FindBestMoveUsingMinMaxAtDepth(chessBoard, searchMode, ePlayerColor, moveList, arrIndex, iDepth + 1, ref moveBest, out iPermCountAtLevel); iPermCount += iPermCountAtLevel; iDepth++; } while (DateTime.Now < dtTimeOut); iMaxDepth = iDepth; } else { iMaxDepth = searchMode.m_iSearchDepth; bRetVal = FindBestMoveUsingMinMaxAtDepth(chessBoard, searchMode, ePlayerColor, moveList, arrIndex, iMaxDepth, ref moveBest, out iPermCount); } return(bRetVal); }
/// <summary> /// Class constructor /// </summary> /// <param name="searchMode"> Actual search mode</param> /// <param name="boardEvalUtil"> Board Evaluation list</param> public frmSearchMode(SearchEngine.SearchMode searchMode, BoardEvaluationUtil boardEvalUtil) : this() { int iPos; m_searchMode = searchMode; m_boardEvalUtil = boardEvalUtil; foreach (IBoardEvaluation boardEval in m_boardEvalUtil.BoardEvaluators) { iPos = comboBoxWhiteBEval.Items.Add(boardEval.Name); if (searchMode.m_boardEvaluationWhite == boardEval) { comboBoxWhiteBEval.SelectedIndex = iPos; } iPos = comboBoxBlackBEval.Items.Add(boardEval.Name); if (searchMode.m_boardEvaluationBlack == boardEval) { comboBoxBlackBEval.SelectedIndex = iPos; } } checkBoxTransTable.IsChecked = ((searchMode.m_eOption & SearchEngine.SearchMode.OptionE.UseTransTable) != 0); if (searchMode.m_eThreadingMode == SearchEngine.SearchMode.ThreadingModeE.OnePerProcessorForSearch) { radioButtonOnePerProc.IsChecked = true; } else if (searchMode.m_eThreadingMode == SearchEngine.SearchMode.ThreadingModeE.DifferentThreadForSearch) { radioButtonOneForUI.IsChecked = true; } else { radioButtonNoThread.IsChecked = true; } checkBoxBookOpening.IsChecked = ((searchMode.m_eOption & SearchEngine.SearchMode.OptionE.UseBook) != 0); if ((searchMode.m_eOption & SearchEngine.SearchMode.OptionE.UseAlphaBeta) != 0) { radioButtonAlphaBeta.IsChecked = true; } else { radioButtonMinMax.IsChecked = true; checkBoxTransTable.IsEnabled = false; } if (searchMode.m_iSearchDepth == 0) { radioButtonAvgTime.IsChecked = true; textBoxTimeInSec.Text = searchMode.m_iTimeOutInSec.ToString(); plyCount.Value = 6; } else { if ((searchMode.m_eOption & SearchEngine.SearchMode.OptionE.UseIterativeDepthSearch) == SearchEngine.SearchMode.OptionE.UseIterativeDepthSearch) { radioButtonFixDepthIterative.IsChecked = true; } else { radioButtonFixDepth.IsChecked = true; } plyCount.Value = searchMode.m_iSearchDepth; textBoxTimeInSec.Text = "15"; } plyCount2.Content = plyCount.Value.ToString(); switch(searchMode.m_eRandomMode) { case SearchEngine.SearchMode.RandomModeE.Off: radioButtonRndOff.IsChecked = true; break; case SearchEngine.SearchMode.RandomModeE.OnRepetitive: radioButtonRndOnRep.IsChecked = true; break; default: radioButtonRndOn.IsChecked = true; break; } textBoxTransSize.Text = (TransTable.TranslationTableSize / 1000000 * 32).ToString(); // Roughly 32 bytes / entry plyCount.ValueChanged += new RoutedPropertyChangedEventHandler<double>(plyCount_ValueChanged); }
public MainForm() { InitializeComponent(); columnHeaderFileName.Tag = new TextComparer<SearchFileInfo>(s => Path.GetFileName(s.Path)); columnHeaderDirectory.Tag = new TextComparer<SearchFileInfo>(s => Path.GetDirectoryName(s.Path)); columnHeaderModifyDate.Tag = new DateTimeComparer<SearchFileInfo>(s => s.LastWriteTime); columnHeaderSize.Tag = new Int64Comparer<SearchFileInfo>(s => s.Length); columnHeaderSearchTextHits.Tag = new TextComparer<SearchFileInfo>(s => s.SearchTexts); // Create an instance of a ListView column sorter and assign it to the ListView control. lvwColumnSorter = new ListViewColumnSorter(); lvwColumnSorter.CompareItems += new EventHandler<ListViewColumnSorterCompareEventArgs>(lvwColumnSorter_CompareItems); this.listViewResults.ListViewItemSorter = lvwColumnSorter; searchEngine = new SearchEngine(); searchEngine.SearchingPath += new EventHandler<SearchEventArgs>(SearchEngineSearchingPath); searchEngine.SearchFound += new EventHandler<SearchFoundEventArgs>(SearchEngineSearchFound); // Apply settings to combo boxes Properties.Settings.Default.DirectoryItems = ApplyComboBoxSetting(comboBoxDirectory, Properties.Settings.Default.DirectoryItems); Properties.Settings.Default.DirectorySubPaths = ApplyComboBoxSetting(comboBoxDirPath, Properties.Settings.Default.DirectorySubPaths); Properties.Settings.Default.FileNames = ApplyComboBoxSetting(comboBoxFileName, Properties.Settings.Default.FileNames); Properties.Settings.Default.Texts = ApplyComboBoxSetting(comboBoxText, Properties.Settings.Default.Texts); ShowHidePreviewPane(); imageLoader = new FileImageLoader(); imageLoader.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(imageLoader_LoadCompleted); }
public MemberManager() { // TODO: IoC refactor UnitOfWork = new EFUnitOfWork(); MemberSearchEngine = new SearchEngine<McMember>(UnitOfWork.MemberRepo); ProcessSearchEngine = new SearchEngine<Process>(UnitOfWork.ProcessRepo); CaseDocSearchEngine = new SearchEngine<CaseDocument>(UnitOfWork.CaseDocumentRepo); MemberTypeSearchEngine = new SearchEngine<McMemberType>(UnitOfWork.MemberTypeRepo); }
public void ExecuteSearch_NullArgument_ThrowsException() { // Arrange var mocks = new MockRepository(); var host = mocks.DynamicMock<IHost>(); var searchEngine = new SearchEngine(host); // Act, Assert Assert.Throws<ArgumentNullException>(() => searchEngine.ExecuteSearch(null)); }
/// <summary> /// 根据索引路径获取一个搜索引擎实例 /// </summary> /// <param name="indexPath">索引路径</param> /// <returns>搜索引擎实例</returns> public static SearchEngine GetSearchEngine(string indexPath) { SearchEngine searchEngine = null; if (!searchEngines.TryGetValue(indexPath, out searchEngine)) { searchEngine = new SearchEngine(indexPath); searchEngines.TryAdd(indexPath, searchEngine); } return searchEngine; }
static void Main(string[] args) { var searchEngine = new SearchEngine<Movie>(); var documents = GetDocuments(); searchEngine.Index(documents, x => x.Fields.Title); var compare = args.Any() && args[0].Equals("compare", StringComparison.InvariantCultureIgnoreCase); List<LinqIndexEntry> linqIndex = null; if (compare) { linqIndex = documents.Where(x => !string.IsNullOrWhiteSpace(x.Fields.Title)) .Select(x => new LinqIndexEntry() { Words = x.Fields.Title.Split(new[] { ' ', '\n', '\r', '\t', '-' }, StringSplitOptions.RemoveEmptyEntries), Movie = x }) .ToList(); } while (true) { Console.Write("Enter search term: "); var searchTerm = Console.ReadLine(); if (string.IsNullOrEmpty(searchTerm)) break; // ---------- SEARCH ENGINE SEARCH ---------------- Console.WriteLine("Using search engine"); Console.WriteLine("==================="); var searchResults = searchEngine.Search(searchTerm); foreach (var result in searchResults) Console.WriteLine("*** {0}", result.Fields.Title); Console.WriteLine("{0} results ({1} seconds)", searchResults.Count(), searchResults.Elapsed.TotalSeconds.ToString("0.00####################")); Console.WriteLine(); // ---------- LINQ SEARCH ---------------- if (compare) { Console.WriteLine("Using LINQ"); Console.WriteLine("=========="); var stopwatch = Stopwatch.StartNew(); var results = linqIndex.Where(x => x.Words.Any(e => e.StartsWith(searchTerm, StringComparison.InvariantCultureIgnoreCase))).ToList(); stopwatch.Stop(); foreach (var result in results) Console.WriteLine("*** {0}", result.Movie.Fields.Title); Console.WriteLine("{0} results ({1} seconds)", results.Count(), stopwatch.Elapsed.TotalSeconds.ToString("0.00####################")); Console.WriteLine(); } } }
public void ExecuteSearch_InvalidArgument_ThrowsException() { // Arrange var mocks = new MockRepository(); var host = mocks.DynamicMock<IHost>(); var expectedResult = new ErrorResult("test"); host.Expect(h => h.Execute(null)).IgnoreArguments().Return(expectedResult); var searchEngine = new SearchEngine(host); var searchTerms = new Dictionary<string, string>(); mocks.ReplayAll(); // Act, Assert Assert.Throws<Exception>(() => searchEngine.ExecuteSearch(searchTerms), "test"); mocks.VerifyAll(); }
public Form1() { InitializeComponent(); INotifier notifier = new ConfigurableNotifier((notification) => { progressTextBox.BeginInvoke((MethodInvoker)(() => progressTextBox.AppendText(notification))); }, (completedMessage) => { resultsTextBox.BeginInvoke((MethodInvoker)(() => resultsTextBox.AppendText(completedMessage))); }, (percentage) => { progressBarBackgroundWorker.ReportProgress(percentage); }); _spider = new SearchEngine(notifier); }
//********************************************************* // /// <summary> /// Form constructor /// </summary> /// <param name="boardEvalUtil"> Board evaluation utility class</param> /// <param name="searchModeTemplate"> Search mode template</param> // //********************************************************* public frmTestBoardEval(BoardEvaluationUtil boardEvalUtil, SearchEngine.SearchMode searchModeTemplate) : this() { m_searchMode = new SearchEngine.SearchMode(boardEvalUtil.BoardEvaluators[0], boardEvalUtil.BoardEvaluators[0], SearchEngine.SearchMode.OptionE.UseAlphaBeta, searchModeTemplate.m_eThreadingMode, 4, 0, searchModeTemplate.m_eRandomMode); foreach (IBoardEvaluation boardEval in boardEvalUtil.BoardEvaluators) { comboBoxWhiteBEval.Items.Add(boardEval.Name); comboBoxBlackBEval.Items.Add(boardEval.Name); } comboBoxWhiteBEval.SelectedIndex = 0; comboBoxBlackBEval.SelectedIndex = (comboBoxBlackBEval.Items.Count == 0) ? 0 : 1; m_boardEvalUtil = boardEvalUtil; SetButtonState(); }
public void ExecuteSearch_ValidArgument_ReturnsResult() { // Arrange var mocks = new MockRepository(); var host = mocks.DynamicMock<IHost>(); var expectedResult = new SearchResult(5); host.Expect(h => h.Execute(null)).IgnoreArguments().Return(expectedResult); var searchEngine = new SearchEngine(host); var searchTerms = new Dictionary<string, string>(); mocks.ReplayAll(); // Act var searchResult = searchEngine.ExecuteSearch(searchTerms); // Assert Assert.AreSame(expectedResult, searchResult); mocks.VerifyAll(); }
public void SearchEngine_GetSearchResultsAsync_CaptionMissing_OneResult() { // arrange var searchTerm = "RAF"; var expectedUrl = "https://www.bbc.co.uk/news"; var expectedTitle = "RAF cameras capture world's biggest iceberg"; var testHtml = $"<html><body><div class=\"result\">" + $"<p class=\"url\"\">{expectedUrl}\"</p>" + $"<p class=\"title\">{expectedTitle}</p>" + $"</div></body></html>"; var parser = new HtmlParser(); var document = parser.ParseDocument(testHtml); var htmlParserMock = new Mock <IAngleSharpHtmlParser>(); htmlParserMock.Setup(x => x.Parse(It.IsAny <string>())).Returns(document); var queryStringEncoderMock = new Mock <IQueryStringEncoder>(); queryStringEncoderMock.Setup(x => x.Encode(It.IsAny <string>())).Returns(searchTerm); var searchEngineSelectorMock = new Mock <ISelector>(); searchEngineSelectorMock.Setup(x => x.GetUrl(It.IsAny <IElement>())).Returns(expectedUrl); searchEngineSelectorMock.Setup(x => x.GetTitle(It.IsAny <IElement>())).Returns(expectedTitle); searchEngineSelectorMock.Setup(x => x.GetCaption(It.IsAny <IElement>())).Returns((string)null); var searchEngine = new SearchEngine(htmlParserMock.Object, searchEngineSelectorMock.Object, queryStringEncoderMock.Object, "https://test.com/search", "div.result"); // act var results = searchEngine.GetSearchResults(searchTerm); // assert Assert.IsNotNull(results); Assert.AreEqual(1, results.Count()); Assert.AreEqual(expectedUrl, results.First().Url); Assert.AreEqual(expectedTitle, results.First().Title); }
public void TestWithMissingSize() { var shirts = BuildTestShirts(); var searchEngine = new SearchEngine(shirts); var searchOptions = new SearchOptions { Colors = new List <Color> { Color.Blue } }; var results = searchEngine.Search(searchOptions); AssertResults(results.Shirts, searchOptions); AssertSizeCounts(shirts, searchOptions, results.SizeCounts); AssertColorCounts(shirts, searchOptions, results.ColorCounts); }
/// <summary> /// cmdReIndex_Click runs when the ReIndex LinkButton is clicked. It re-indexes the /// site (or application if run on Host page) /// </summary> /// <remarks> /// </remarks> /// <history> /// [cnurse] 11/16/2004 created /// </history> protected void cmdReIndex_Click(object sender, EventArgs e) { try { SearchEngine se = new SearchEngine(); if (PortalSettings.ActiveTab.ParentId == PortalSettings.SuperTabId) { se.IndexContent(); } else { se.IndexContent(PortalId); } } catch (Exception exc) //Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } }
private void ThisAddIn_Startup(object sender, EventArgs e) { if (!Directory.Exists(GetPluginDirectory())) { Directory.CreateDirectory(GetPluginDirectory()); } // TODO: Multiple excel instances, wont that break? differntiate, add tid/pid suffix? logger = new Logger(GetPluginDirectory() + "\\bExcelRegex.log"); searchEngine = new SearchEngine(); userControl = new SearchControl(); taskPane = this.CustomTaskPanes.Add(userControl, TaskPaneTitle); taskPane.Visible = false; taskPane.DockPosition = Office.MsoCTPDockPosition.msoCTPDockPositionFloating; taskPane.DockPosition = Office.MsoCTPDockPosition.msoCTPDockPositionRight; taskPane.DockPositionRestrict = Office.MsoCTPDockPositionRestrict.msoCTPDockPositionRestrictNoHorizontal; //taskPane.Width = userControl.size }
public void TestWithMissingColor() { var shirts = BuildTestShirts(); var searchEngine = new SearchEngine(shirts); var searchOptions = new SearchOptions { Sizes = new List <Size> { Size.Small } }; var results = searchEngine.Search(searchOptions); AssertResults(results.Shirts, searchOptions); AssertSizeCounts(shirts, searchOptions, results.SizeCounts); AssertColorCounts(shirts, searchOptions, results.ColorCounts); }
private void RemoveItemFromTileUnderConstructionPlan() { //find closest free spot bool RequirementsFunction(Tile t) => (t is null) ? false : !t.Contents.HasItem; Tile haulToTile = SearchEngine.FindClosestTileWhere(Position, RequirementsFunction); if (haulToTile != null) { Job job = new HaulJob(Utils.TileAt(Position).Contents.Item, haulToTile.Position); _jobs.Add(job); JobSystem.GetInstance().AddJob(job); job.JobResultHandler += OnTileClearJobFinish; } else { Debug.LogError("No empty tile to move item to was found. Implement wait function to try again some time later. P: " + Position); } }
public void SearchEngineCreatePostTest() { using (SearchEngineController searchEngineController = new SearchEngineController()) { SearchEngine google = new SearchEngine() { Name = "Google", Domain = "https://www.google.com", URL = "https://www.google.com/search?q=" }; Task <ActionResult> task = searchEngineController.Create(google); task.Wait(); ActionResult actionResult = task.Result; RedirectToRouteResult redirectToRouteResult = actionResult as RedirectToRouteResult; Assert.IsNotNull(redirectToRouteResult); Assert.IsTrue(google.Id > 0); } }
public void QuickSort_ListAlreadySorted_ListUnchanged() { sut = new List <Word>(); sut.Add(new Word("Alban", "TextFile")); sut.Add(new Word("Bengt", "TextFile")); sut.Add(new Word("Cilla", "TextFile")); sut.Add(new Word("David", "TextFile")); sut.Add(new Word("Emil", "TextFile")); sut.Add(new Word("Felicia", "TextFile")); SearchEngine <Word> .QuickSort(sut, 0, 5); Assert.AreEqual("Alban", sut[0].Value); Assert.AreEqual("Bengt", sut[1].Value); Assert.AreEqual("Cilla", sut[2].Value); Assert.AreEqual("David", sut[3].Value); Assert.AreEqual("Emil", sut[4].Value); Assert.AreEqual("Felicia", sut[5].Value); }
public void SearchEngine_GetSearchResultsAsync_TitleMissing_NoResult() { // arrange var searchTerm = "RAF"; var expectedUrl = "https://www.bbc.co.uk/news"; var expectedCaption = "An RAF aircraft has obtained images of the world's biggest " + "iceberg as it drifts through the South Atlantic."; var testHtml = $"<html><body><div class=\"result\">" + $"<p class=\"url\"\">{expectedUrl}\"</p>" + $"<p class=\"caption\">{expectedCaption}</p>" + $"</div></body></html>"; var parser = new HtmlParser(); var document = parser.ParseDocument(testHtml); var htmlParserMock = new Mock <IAngleSharpHtmlParser>(); htmlParserMock.Setup(x => x.Parse(It.IsAny <string>())).Returns(document); var queryStringEncoderMock = new Mock <IQueryStringEncoder>(); queryStringEncoderMock.Setup(x => x.Encode(It.IsAny <string>())).Returns(searchTerm); var searchEngineSelectorMock = new Mock <ISelector>(); searchEngineSelectorMock.Setup(x => x.GetUrl(It.IsAny <IElement>())).Returns(expectedUrl); searchEngineSelectorMock.Setup(x => x.GetTitle(It.IsAny <IElement>())).Returns((string)null); searchEngineSelectorMock.Setup(x => x.GetCaption(It.IsAny <IElement>())).Returns(expectedCaption); var searchEngine = new SearchEngine(htmlParserMock.Object, searchEngineSelectorMock.Object, queryStringEncoderMock.Object, "https://test.com/search", "div.result"); // act var results = searchEngine.GetSearchResults(searchTerm); // assert Assert.IsNotNull(results); Assert.AreEqual(0, results.Count()); }
public void Search_Without_Criteria_When_Shirts_Available() { var shirts = new List <Shirt> { new Shirt(Guid.NewGuid(), "Red - Small", Size.Small, Color.Red), new Shirt(Guid.NewGuid(), "Black - Medium", Size.Medium, Color.Black), new Shirt(Guid.NewGuid(), "Blue - Large", Size.Large, Color.Blue), }; var searchEngine = new SearchEngine(shirts); var searchOptions = new SearchOptions(); var results = searchEngine.Search(searchOptions); AssertResults(results.Shirts, searchOptions); AssertSizeCounts(shirts, searchOptions, results.SizeCounts); AssertColorCounts(shirts, searchOptions, results.ColorCounts); }
protected override IObservable <string[]> Lookup(IObservable <string> texts) => texts .__LOG_RAW_TEXT_FOR_DEMO() .Throttle(_throttleDueTime) .DistinctUntilChanged() .__LOG_TEXT_FOR_DEMO() .__DO_FOR_CONTROL(text => SetCancelButtonAccessibility(enable: true)) .Select(text => Observable.FromAsync(async ct => await SearchEngine.Search(text, ct)) .__LOG_TIMEINTERVAL_FOR_DEMO($"search: {text}") .Timeout(_timeoutDueTime) .__LOG_ERROR_FOR_DEMO("RETRY") .Retry(_retryCount) .Catch((TimeoutException ex) => Observable.Return(new[] { "<< TIMEOUT >>" }).__LOG_ERROR_FOR_DEMO("TIMEOUT", ex)) .Catch((Exception ex) => Observable.Return(new[] { "<< ERROR >>" }).__LOG_ERROR_FOR_DEMO("FATAL ERROR", ex)) .Amb(Cancellations.FirstAsync().Select(unit => new[] { "<< CANCEL >>" }).__LOG_FOR_DEMO("CANCEL")) ) .Switch() .__DO_FOR_CONTROL(text => SetCancelButtonAccessibility(enable: false));
/// <summary> /// Build request url for this engine, create HttpWebRequest, add headers to request /// </summary> public HttpWebRequest BuildRequestToEngine(string searchQuery, SearchEngine engine) { string completeUrl = GetCompliteUrl(searchQuery, engine.Parameters, engine.BaseUrl); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(completeUrl); if (engine.Headers != null) { foreach (RequestHeader header in engine.Headers) { if (header.HeaderValue != string.Empty) { request.Headers[header.HeaderName] = header.HeaderValue; } } } return(request); }
private List <SearchResultViewModel> ProcessSearchEngine(SearchEngine searchEngine, string searchTerm, int numOfResults) { // get the url var searchUrl = searchEngine.URL.Replace("{searchTerm}", searchTerm).Replace("{numOfResults}", numOfResults.ToString()); // get the HTML from the search var result = GetSearchResult(searchUrl); var results = new List <SearchResultViewModel>(); // I have used the HTML Agility Pack to traverse and select the HTML nodes // create a new HTML document and load the search result HTML string var doc = new HtmlDocument(); doc.LoadHtml(result); // select all the search result elements from the HTML document var htmlNodes = doc.DocumentNode.SelectNodes(searchEngine.XPathResultNodes); // loop through all the nodes extracting the title, url and summary foreach (var node in htmlNodes) { var title = node.SelectSingleNode(searchEngine.XPathTitleNodes)?.InnerText ?? string.Empty; var url = node.SelectSingleNode(searchEngine.XPathUrlNodes)?.Attributes["href"].Value ?? string.Empty; var summary = node.SelectSingleNode(searchEngine.XPathSummaryNodes)?.InnerText ?? string.Empty; // ignore if title or summary are empty if (string.IsNullOrWhiteSpace(title) || string.IsNullOrWhiteSpace(summary)) { continue; } // add to a result collection results.Add(new SearchResultViewModel { Title = title, URL = url, Summary = summary }); } return(results); }
public void WhenSearchingForAnyColorAndAnySizeShirts_ShouldReturnInputShirtResult() { var shirts = new List <Shirt> { new Shirt(Guid.NewGuid(), "Red - Small", Size.Small, Color.Red), new Shirt(Guid.NewGuid(), "Black - Medium", Size.Medium, Color.Black), new Shirt(Guid.NewGuid(), "Blue - Large", Size.Large, Color.Blue), }; var searchEngine = new SearchEngine(shirts); var searchOptions = new SearchOptions { }; var results = searchEngine.Search(searchOptions); AssertResults(results.Shirts, searchOptions); AssertSizeCounts(shirts, searchOptions, results.SizeCounts); AssertColorCounts(shirts, searchOptions, results.ColorCounts); }
public void BinarySearch_LoadsNull_ReturnsEmptyDictionary() { WordExtractor extractor = new WordExtractor(); string path1 = null; string text1 = InputOutput.ReadFile(path1); extractor.ExtractWordsFromTextFile(text1, path1); List <Word> list = extractor.GetCompoundedList(); SearchEngine <Word> .QuickSort(list, 0, list.Count - 1); var result = SearchEngine <Word> .BinarySearch(list, true, "could"); Dictionary <string, int> expected = new Dictionary <string, int>(); Assert.AreEqual(expected, result); }
public void FindsAllShirtsUsingNoSearchOptions() { var shirts = new List <Shirt> { new Shirt(Guid.NewGuid(), "Red - Small", Size.Small, Color.Red), new Shirt(Guid.NewGuid(), "Black - Medium", Size.Medium, Color.Black), new Shirt(Guid.NewGuid(), "Blue - Large", Size.Large, Color.Blue), }; var searchEngine = new SearchEngine(shirts); var searchOptions = new SearchOptions(); var results = searchEngine.Search(searchOptions); AssertResults(results.Shirts, searchOptions); AssertSizeCounts(shirts, searchOptions, results.SizeCounts); AssertColorCounts(shirts, searchOptions, results.ColorCounts); }
public void BinarySearch_LoadsEmptyTextFile_ReturnsEmptyDictionary() { WordExtractor extractor = new WordExtractor(); string path1 = $"{AppDomain.CurrentDomain.BaseDirectory}TestFiles\\EmptyTextFile.txt"; string text1 = InputOutput.ReadFile(path1); extractor.ExtractWordsFromTextFile(text1, path1); List <Word> list = extractor.GetCompoundedList(); SearchEngine <Word> .QuickSort(list, 0, list.Count - 1); var result = SearchEngine <Word> .BinarySearch(list, true, ""); Dictionary <string, int> expected = new Dictionary <string, int>(); Assert.AreEqual(expected, result); }
private SearchEngine CreateEngine() { var searchEngine = new SearchEngine(); searchEngine.AddNonSponsoredLink( new NonSponsoredLink("fooblog.com", "some blog", DateTime.Today, LinkKind.Blog)); searchEngine.AddNonSponsoredLink( new NonSponsoredLink("fooforum.com", "some forum", DateTime.Today, LinkKind.Forum)); searchEngine.AddNonSponsoredLink( new NonSponsoredLink("foobar.com", "something else", DateTime.Today, LinkKind.Forum)); searchEngine.AddSponsoredLink( new SponsoredLink("fooshop.com", "some online store", "some guy", 0.25m)); searchEngine.AddSponsoredLink( new SponsoredLink("foostore.com", "probably losing to Amazon", "some dude", 0.3m)); searchEngine.AddSponsoredLink( new SponsoredLink("foolife.com", "definitely losing to Amazon", "some hippie", 0.2m)); return(searchEngine); }
public static SearchEngine QuerySearchEngineByName(string SearchEngineName) { // escape the single ticks SearchEngineName = EscapeSingleTicks(SearchEngineName); SearchEngine searchEngine = new SearchEngine(); SqliteConnection conn = OpenDatabase(); SqliteCommand command = conn.CreateCommand(); command.CommandText = $"Select TSearchEngines.searchEngineID, TSearchEngines.searchEngineName, TSearchEngines.searchEngineBaseURL, TSearchEngines.searchEngineQueryString From TSearchEngines Where TSearchEngines.searchEngineName = '{SearchEngineName}';"; using (SqliteDataReader reader = command.ExecuteReader()) { while (reader.Read()) { searchEngine = SearchEngine.FromDataRow(reader); } } conn.Close(); return(searchEngine); }
public void TestNavPoints_AfterAppliedSuspectUnreachable() { var map = new Map(new Point(-2, -2), new Point(2, 2), 0.2f); map.StartNode = map.Nodes.Find(x => x.Name == $"Node_1_1"); map.EndNode = map.Nodes.Find(x => x.Name == $"Node_3_3"); map.ApplySuspectUnreachable(new List <Node>() { map.Nodes.First(x => x.Name == "Node_2_1"), map.Nodes.First(x => x.Name == "Node_1_3"), map.Nodes.First(x => x.Name == "Node_3_2") }); var searchEngine = new SearchEngine(map); var navPoints = searchEngine.GetShortestPathDijikstra(); navPoints.Count.Should().Be(5); AssertPath(navPoints, "Node_1_1", "Node_1_2", "Node_2_2", "Node_2_3", "Node_3_3"); }
public void Search_MultipleFiles() { // Arrange var sut = new SearchEngine(".txt"); var file1 = new TxtFile(Path.Combine(Directory.GetCurrentDirectory(), @"ExampleFiles\ValidTxtFile.txt")); var file2 = new TxtFile(Path.Combine(Directory.GetCurrentDirectory(), @"ExampleFiles\ValidTxtFile2.txt")); var file3 = new TxtFile(Path.Combine(Directory.GetCurrentDirectory(), @"ExampleFiles\ValidTxtFile3.txt")); // Act sut.Files.Add(file1); sut.Files.Add(file2); sut.Files.Add(file3); var result = sut.Search("his"); // Assert Assert.AreEqual(3, result.Count); Assert.AreEqual(Path.GetFileName(file2.FilePath), result[0].Key); Assert.AreEqual(6, result[0].Value); }
public void Should_ReturnResults_When_NoShirtsInStock() { var shirts = new List <Shirt>(); var searchOptions = new SearchOptions { Colors = new List <Color> { Color.Black }, Sizes = new List <Size> { Size.Large } }; var searchEngine = new SearchEngine(shirts, _mockValidateService.Object); var results = searchEngine.Search(searchOptions); AssertResults(results.Shirts, searchOptions); AssertSizeCounts(shirts, searchOptions, results.SizeCounts); AssertColorCounts(shirts, searchOptions, results.ColorCounts); }
public JsonResult saveEngin(string EngineUrl, int HowManyResults, string EngineName, string EngineNameUpdt, bool FullUrl, string ReturnUrlAfter, string ReturnUrlBefor, string SearchUrl, bool isUpdate) { try { //EngineName,EngineUrl,EngineUrlHttp,EngineUrlHttps,HowManyResults,SearchUrl, //ReturnFullUrl, ReturnUrlAfter, ReturnUrlBefor SearchEngine se = new SearchEngine(); se.EngineUrl = EngineUrl; se.HowManyResults = HowManyResults; se.SearchUrl = EngineUrl + SearchUrl; se.ReturnFullUrl = FullUrl; se.ReturnUrlAfter = ReturnUrlAfter; se.ReturnUrlBefor = ReturnUrlBefor; if (!isUpdate) { se.Name = EngineName; SearchEngine.AddNewSearchEngine(se); } else { se.Name = EngineNameUpdt; SearchEngine.EditSearchEngine(se); } //EditSearchEngine return(Json("", JsonRequestBehavior.AllowGet)); } catch (Exception er) { Response.StatusCode = 500; return(Json(er.Innerexception().Message, JsonRequestBehavior.AllowGet)); } }
private void _clientItemDatabase_TupleModified(object sender, TKey key, TValue value) { if (SearchEngine.SubsetCondition == null) { SearchEngine.SetOrder(value); } else { if (SearchEngine.SubsetCondition(value)) { SearchEngine.SetOrder(value); } else { _listView.Items.Delete(value); Table.FastItems.Remove(value); } } }
public void WhenSearchOptionsIsEmpty_ShuldReturnCorrectResult() { var shirts = new List <Shirt> { new Shirt(Guid.NewGuid(), "Red - Small", Size.Small, Color.Red), new Shirt(Guid.NewGuid(), "Black - Medium", Size.Medium, Color.Black), new Shirt(Guid.NewGuid(), "Blue - Large", Size.Large, Color.Blue), }; var searchEngine = new SearchEngine(shirts); var searchOptions = new SearchOptions(); var results = searchEngine.Search(searchOptions); AssertResults(shirts, searchOptions, results.Shirts); AssertSizeCounts(shirts, searchOptions, results.SizeCounts); AssertColorCounts(shirts, searchOptions, results.ColorCounts); }
public void Search_WithNoSearchOptions_ReturnsAllShirts() { var shirts = new List <Shirt> { new Shirt(Guid.NewGuid(), "Red - Small", Size.Small, Color.Red), new Shirt(Guid.NewGuid(), "Black - Medium", Size.Medium, Color.Black), new Shirt(Guid.NewGuid(), "Blue - Large", Size.Large, Color.Blue) }; var searchEngine = new SearchEngine(shirts); var searchOptions = new SearchOptions { }; var results = searchEngine.Search(searchOptions); Assert.AreEqual(shirts.Count, results.Shirts.Count); }
public void SearchBySmallMediumRed_AndSmallMediumYellow_ShouldReturnSmallRedAndMediumRedAndSmallYellowAndMediumYellowShirts() { //Arrange var shirts = new List <Shirt> { new Shirt(Guid.NewGuid(), "Red - Small", Size.Small, Color.Red), new Shirt(Guid.NewGuid(), "Red - Medium", Size.Medium, Color.Red), new Shirt(Guid.NewGuid(), "Red - Large", Size.Large, Color.Red), new Shirt(Guid.NewGuid(), "Yellow - Small", Size.Small, Color.Yellow), new Shirt(Guid.NewGuid(), "Yellow - Medium", Size.Medium, Color.Yellow), new Shirt(Guid.NewGuid(), "White - Small", Size.Small, Color.White), new Shirt(Guid.NewGuid(), "White - Medium", Size.Medium, Color.White), new Shirt(Guid.NewGuid(), "Black - Medium", Size.Medium, Color.Black), new Shirt(Guid.NewGuid(), "Black - Large", Size.Large, Color.Black), new Shirt(Guid.NewGuid(), "Blue - Small", Size.Small, Color.Blue), new Shirt(Guid.NewGuid(), "Blue - Large", Size.Large, Color.Blue) }; SetupExpectedSizeCounts(Size.Small, 2); SetupExpectedSizeCounts(Size.Medium, 2); SetupExpectedColorCounts(Color.Red, 2); SetupExpectedColorCounts(Color.Yellow, 2); var searchEngine = new SearchEngine(shirts); var searchOptions = new SearchOptions { Colors = new List <Color> { Color.Red, Color.Yellow }, Sizes = new List <Size> { Size.Small, Size.Medium } }; //Act var results = searchEngine.Search(searchOptions); //Assert results.Shirts.Count.Should().Be(4); AssertResults(results.Shirts, searchOptions); AssertSizeCounts(_sizeCounts, results.SizeCounts); AssertColorCounts(_colorCounts, results.ColorCounts); }
public void ASearchWillReturnTheSameResultsAsAScoredSearch() { InitializeContext(); LuceneIndexerOptions options = new LuceneIndexerOptions() { Path = "lucene" }; SearchEngine <TestDbContext> searchProvider = new SearchEngine <TestDbContext>(options, _context, new MemoryCache(new MemoryCacheOptions())); searchProvider.CreateIndex(); SearchOptions searchOptions = new SearchOptions("Joh*", "FirstName"); // test var results = searchProvider.Search <User>(searchOptions); Assert.Equal(10, results.TotalHits); searchProvider.DeleteIndex(); }
public void Search_WithEmptySearchOptions_ShouldReturnAllResults(SearchOptions searchOptions) { // Arrange var shirts = _shirtList; var searchEngine = new SearchEngine(shirts); // Act var results = searchEngine.Search(searchOptions); // Assert var expectedShirtResults = shirts; var expectedColourCounts = new List <ColorCount> { new ColorCount { Color = Color.Black, Count = 3 }, new ColorCount { Color = Color.Blue, Count = 2 }, new ColorCount { Color = Color.Red, Count = 2 }, new ColorCount { Color = Color.White, Count = 1 }, }; var expectedSizeCounts = new List <SizeCount> { new SizeCount { Size = Size.Small, Count = 2 }, new SizeCount { Size = Size.Medium, Count = 4 }, new SizeCount { Size = Size.Large, Count = 2 } }; var expectedResults = GenerateSearchResults(expectedShirtResults, expectedColourCounts, expectedSizeCounts); results.Should().BeEquivalentTo(expectedResults); }
/// <summary> /// Método que evaluar el resultado de la busqueda /// </summary> /// <param name="words">words</param> /// <returns>Devuelvo la cadena a mostrar</returns> public string evaluateSearch(List <string> words) { SearchEngine searchEngine = new SearchEngine(); List <GenericEntity> FinalList = new List <GenericEntity>(); string finalSentence = string.Empty; string sentenceA = string.Empty; string sentenceB = string.Empty; foreach (var word in words) { List <GenericEntity> listSearchEngine = new List <GenericEntity>(); listSearchEngine.Add(addList("Google", word)); listSearchEngine.Add(addList("Bing", word)); finalSentence = string.Format("{0}: ", word); foreach (var item in listSearchEngine) { searchEngine.SearchCall(item); finalSentence = finalSentence + string.Format("{0}: {1} ", item.name, item.resultado); FinalList.Add(new GenericEntity() { name = item.name, resultado = item.resultado, q = item.q }); } sentenceA = sentenceA + finalSentence; sentenceA = sentenceA + "<br />"; finalSentence = string.Empty; sentenceB = sentenceB + string.Format("{0}", listSearchEngine.First(x => x.resultado == listSearchEngine.Max(y => y.resultado)).name) + " winner: " + string.Format("{0} ", listSearchEngine.First(x => x.resultado == listSearchEngine.Max(y => y.resultado)).q); sentenceB = sentenceB + "<br />"; } finalSentence = sentenceA + sentenceB; return(finalSentence = finalSentence + string.Format("Total winner: " + "{0}", FinalList.First(x => x.resultado == FinalList.Max(y => y.resultado)).q)); }
static void Main(string[] args) { SearchEngine searchEngine1 = new SearchEngine(); SearchEngine searchEngine2 = new GoogleSearch(); SearchEngine searchEngine3 = new BingSearch(); string[] resSimpleSearch = searchEngine1.Search("Hello by Adele"); Console.WriteLine("Simple Search:"); PrintResults(resSimpleSearch); string[] resGoogleSearch = searchEngine2.Search("Hello by Adele"); Console.WriteLine("Google Search:"); PrintResults(resGoogleSearch); string[] resBingSearch = searchEngine3.Search("Hello by Adele"); Console.WriteLine("Bing Search:"); PrintResults(resBingSearch); Console.ReadKey(); }
/// ----------------------------------------------------------------------------- /// <summary> /// DoWork runs the scheduled item /// </summary> /// <remarks> /// </remarks> /// <history> /// [cnurse] 11/15/2004 documented /// [vqnguyen] 05/28/2013 updated /// </history> /// ----------------------------------------------------------------------------- public override void DoWork() { try { var lastSuccessFulDateTime = SearchHelper.Instance.GetLastSuccessfulIndexingDateTime(ScheduleHistoryItem.ScheduleID); Utils.Logger.Trace("Search: File Crawler - Starting. Content change start time " + lastSuccessFulDateTime.ToString("g")); ScheduleHistoryItem.AddLogNote(string.Format("Starting. Content change start time <b>{0:g}</b>", lastSuccessFulDateTime)); var searchEngine = new SearchEngine(); try { searchEngine.IndexContent(lastSuccessFulDateTime); foreach (var result in searchEngine.Results) { ScheduleHistoryItem.AddLogNote(string.Format("<br/> {0} Indexed: {1}", result.Key, result.Value)); } } finally { //searchEngine.Commit(); } ScheduleHistoryItem.Succeeded = true; ScheduleHistoryItem.AddLogNote("<br/><b>Indexing Successful</b>"); SearchHelper.Instance.SetLastSuccessfulIndexingDateTime(ScheduleHistoryItem.ScheduleID, ScheduleHistoryItem.StartDate); Utils.Logger.Trace("Search: File Crawler - Indexing Successful"); } catch (Exception ex) { ScheduleHistoryItem.Succeeded = false; ScheduleHistoryItem.AddLogNote("<br/>EXCEPTION: " + ex.Message); Errored(ref ex); if (ScheduleHistoryItem.ScheduleSource != ScheduleSource.STARTED_FROM_BEGIN_REQUEST) { Exceptions.LogException(ex); } } }
/// <summary> /// Class Ctor /// </summary> /// <param name="boardEvalUtil"> Board evaluation utility class</param> /// <param name="searchModeTemplate"> Search mode template</param> public frmTestBoardEval(BoardEvaluationUtil boardEvalUtil, SearchEngine.SearchMode searchModeTemplate) : this() { m_searchMode = new SearchEngine.SearchMode(boardEvalUtil.BoardEvaluators[0], boardEvalUtil.BoardEvaluators[0], SearchEngine.SearchMode.OptionE.UseAlphaBeta, searchModeTemplate.m_eThreadingMode, 4, 0, searchModeTemplate.m_eRandomMode); foreach (IBoardEvaluation boardEval in boardEvalUtil.BoardEvaluators) { comboBoxWhiteBEval.Items.Add(boardEval.Name); comboBoxBlackBEval.Items.Add(boardEval.Name); } comboBoxWhiteBEval.SelectedIndex = 0; comboBoxBlackBEval.SelectedIndex = (comboBoxBlackBEval.Items.Count == 0) ? 0 : 1; m_boardEvalUtil = boardEvalUtil; plyCount2.Content = plyCount.Value.ToString(); gameCount2.Content = gameCount.Value.ToString(); plyCount.ValueChanged += new RoutedPropertyChangedEventHandler<double>(plyCount_ValueChanged); gameCount.ValueChanged += new RoutedPropertyChangedEventHandler<double>(gameCount_ValueChanged); }
//********************************************************* // /// <summary> /// Find a move from the opening book /// </summary> /// <param name="searchMode"> Search mode</param> /// <param name="ePlayerColor"> Color doing the move</param> /// <param name="arrPrevMove"> Previous move</param> /// <param name="move"> Found move</param> /// <returns> /// true if succeed, false if no move found in book /// </returns> // //********************************************************* public bool FindBookMove(SearchEngine.SearchMode searchMode, PlayerColorE ePlayerColor, MovePosS[] arrPrevMove, out ChessBoard.MovePosS move) { bool bRetVal; int iMove; Random rnd; if (searchMode.m_eRandomMode == SearchEngine.SearchMode.RandomModeE.Off) { rnd = null; } else if (searchMode.m_eRandomMode == SearchEngine.SearchMode.RandomModeE.OnRepetitive) { rnd = m_rndRep; } else { rnd = m_rnd; } move.OriginalPiece = PieceE.None; move.StartPos = 255; move.EndPos = 255; move.Type = ChessBoard.MoveTypeE.Normal; iMove = m_book.FindMoveInBook(arrPrevMove, rnd); if (iMove == -1) { bRetVal = false; } else { move = FindIfValid(ePlayerColor, iMove & 255, iMove >> 8); move.Type |= MoveTypeE.MoveFromBook; bRetVal = (move.StartPos != 255); } return(bRetVal); }
//********************************************************* // /// <summary> /// Find the best move for a player using alpha-beta pruning or minmax search /// </summary> /// <param name="searchMode"> Search mode</param> /// <param name="ePlayerColor"> Color doing the move</param> /// <param name="moveBest"> Best move found</param> /// <param name="iPermCount"> Total permutation evaluated</param> /// <param name="iCacheHit"> Number of moves found in the translation table cache</param> /// <param name="iMaxDepth"> Maximum depth reached</param> /// <returns> /// true if a move has been found /// </returns> // //********************************************************* public bool FindBestMove(SearchEngine.SearchMode searchMode, PlayerColorE ePlayerColor, out MovePosS moveBest, out int iPermCount, out int iCacheHit, out int iMaxDepth) { bool bRetVal; bool bUseAlphaBeta; SearchEngine searchEngine; bUseAlphaBeta = ((searchMode.m_eOption & SearchEngine.SearchMode.OptionE.UseAlphaBeta) != 0); searchEngine = bUseAlphaBeta ? (SearchEngine)m_searchEngineAlphaBeta : (SearchEngine)m_searchEngineMinMax; bRetVal = searchEngine.FindBestMove(this, searchMode, ePlayerColor, out moveBest, out iPermCount, out iCacheHit, out iMaxDepth); return(bRetVal); }
//********************************************************* // /// <summary> /// Evaluates a board. The number of point is greater than 0 if white is in advantage, less than 0 if black is. /// </summary> /// <param name="searchMode"> Search mode</param> /// <param name="ePlayerToPlay"> Color of the player to play</param> /// <param name="iMoveCountDelta"> White move count - Black move count</param> /// <param name="iAttackedPos"> Number of square attacked by all pieces. (Value computed before the last move for performance reason)</param> /// <param name="iAttackedPieces"> Number of enemy peices attacked by all pieces. (Value computed before the last move for performance reason)</param> /// <returns> /// Number of points for the current board /// </returns> // //********************************************************* public int Points(SearchEngine.SearchMode searchMode, PlayerColorE ePlayerToPlay, int iMoveCountDelta, int iAttackedPos, int iAttackedPieces) { int iRetVal; IBoardEvaluation boardEval; if (ePlayerToPlay == PlayerColorE.White) { boardEval = searchMode.m_boardEvaluationWhite; } else { boardEval = searchMode.m_boardEvaluationBlack; iAttackedPos = -iAttackedPos; iAttackedPieces = -iAttackedPieces; } iRetVal = boardEval.Points(m_pBoard, m_piPiecesCount, iAttackedPos, iAttackedPieces, m_iWhiteKingPos, m_iBlackKingPos, m_bWhiteCastle, m_bBlackCastle, iMoveCountDelta); return(iRetVal); }
static void GetTotori(string searchWord, int _page, bool isSafeSearch, SearchEngine engine = SearchEngine.Google) { var page = _page * 20; var urlWord = Uri.EscapeUriString(searchWord); int done = 0, fail = 0; List<string> totori = new List<string>(); Console.WriteLine("Page "+_page+" GET Start\nSearch Engine: "+engine.ToString()); if (engine == SearchEngine.Google) { #region Google画像検索 WebClient wc = new WebClient(); wc.Proxy = null; //%E3%83%88%E3%83%88%E3%83%AA var isSafeStr = "off"; if (isSafeSearch) isSafeStr = "on"; byte[] data = wc.DownloadData("https://www.google.co.jp/search?q=" + urlWord + "&hl=ja&safe=" + isSafeStr + "&sout=1&biw=1920&tbm=isch&sa=N&start=" + page); //Console.WriteLine("解析中"); Encoding enc = Encoding.GetEncoding("Shift_JIS"); string html = enc.GetString(data); var links = html.Split(new string[] { "http://www.google.co.jp/imgres?imgurl=", "&imgrefurl=" }, StringSplitOptions.RemoveEmptyEntries); //string[] tototi = new string[30]; foreach (var item in links) { if (item.StartsWith("http") && (item.EndsWith("jpg") || item.EndsWith("png") || item.EndsWith("bmp") || item.EndsWith("gif"))) { totori.Add(item); //Console.WriteLine(item); } } #endregion } else if (engine == SearchEngine.Bing) { #region Bing画像検索 var bing = new BingSearchContainer(new Uri("https://api.datamarket.azure.com/Bing/Search/")) { Credentials = new NetworkCredential(bingKey, bingKey) }; var isSafeStr = "Off"; if (isSafeSearch) isSafeStr = "Moderate"; var query = bing.Image(searchWord, null, null, isSafeStr, null, null, null, 20, page); var results = query.Execute(); foreach (var result in results) { totori.Add(result.MediaUrl); } #endregion } Parallel.ForEach(totori, (u) => { try { var url = new Uri(u); var filePath = Path.Combine(savePath, Path.GetFileName(url.LocalPath)); new WebClient().DownloadFile(url, filePath); done++; //Console.WriteLine("downloaded: {0} => {1}", url, filePath); } catch// (Exception e) { fail++; //Console.WriteLine("failed: {0}, {1}", url, e); } }); //Console.WriteLine("end"); Console.WriteLine("Page " + _page + " End"); Console.WriteLine("Done: " + done + " Error: " + fail); }
/// <summary> /// Test the computer play against itself /// </summary> /// <param name="iGameCount"> Number of games to play</param> /// <param name="searchMode"> Searching mode</param> private void TestComputerAgainstComputer(int iGameCount, SearchEngine.SearchMode searchMode) { bool bMultipleThread; bMultipleThread = (m_searchMode.m_eThreadingMode == SearchEngine.SearchMode.ThreadingModeE.DifferentThreadForSearch || m_searchMode.m_eThreadingMode == SearchEngine.SearchMode.ThreadingModeE.OnePerProcessorForSearch); PlayingMode = PlayingModeE.ComputerAgainstComputer; StartAsyncComputing(); if (bMultipleThread) { Task.Factory.StartNew(() => TestComputerAgainstComputerAsync(iGameCount, searchMode)); } else { TestComputerAgainstComputerAsync(iGameCount, searchMode); } }
//********************************************************* // /// <summary> /// Find the best move for a player using alpha-beta /// </summary> /// <param name="chessBoard"> Chess board</param> /// <param name="searchMode"> Search mode</param> /// <param name="ePlayerColor"> Color doing the move</param> /// <param name="moveList"> Move list</param> /// <param name="arrIndex"> Order of evaluation of the moves</param> /// <param name="moveBest"> Best move found</param> /// <param name="iPermCount"> Total permutation evaluated</param> /// <param name="iCacheHit"> Number of moves found in the translation table cache</param> /// <param name="iMaxDepth"> Maximum depth to use</param> /// <returns> /// true if a move has been found /// </returns> // //********************************************************* protected override bool FindBestMove(ChessBoard chessBoard, SearchEngine.SearchMode searchMode, ChessBoard.PlayerColorE ePlayerColor, List<ChessBoard.MovePosS> moveList, int[] arrIndex, ref ChessBoard.MovePosS moveBest, out int iPermCount, out int iCacheHit, out int iMaxDepth) { bool bRetVal = false; bool bMultipleThread; bool bUseTransTable; ChessBoard[] arrChessBoard; FindBestMoveUsingAlphaBetaAsyncDel[] arrDelFindBestMoveUsingAlphaBetaAsync; IAsyncResult[] arrAsyncResult; List<ChessBoard.MovePosS>[] arrMoveList; ChessBoard.MovePosS movePosTmp; int iPts; int iAlpha; int iBeta; int iThreadCount; int iMovePermCount; int iMaxDepthTmp; //TODO Enable transposition table when bug on 3 repetition move draw will be found. searchMode.m_eOption &= ~SearchMode.OptionE.UseTransTable; bUseTransTable = ((searchMode.m_eOption & SearchMode.OptionE.UseTransTable) != 0); iCacheHit = 0; iMaxDepth = 0; iPermCount = 0; iAlpha = -10000000; iBeta = +10000000; bMultipleThread = (searchMode.m_eThreadingMode == SearchMode.ThreadingModeE.OnePerProcessorForSearch); iThreadCount = System.Environment.ProcessorCount; if (bMultipleThread && iThreadCount < 2) { bMultipleThread = false; // No reason to go with multi-threading if only one processor } if (bMultipleThread) { arrChessBoard = new ChessBoard[iThreadCount]; arrAsyncResult = new IAsyncResult[iThreadCount]; arrDelFindBestMoveUsingAlphaBetaAsync = new FindBestMoveUsingAlphaBetaAsyncDel[iThreadCount]; arrMoveList = new List<ChessBoard.MovePosS>[iThreadCount]; for (int iIndex = 0; iIndex < iThreadCount; iIndex++) { arrChessBoard[iIndex] = chessBoard.Clone(); arrDelFindBestMoveUsingAlphaBetaAsync[iIndex] = new FindBestMoveUsingAlphaBetaAsyncDel(FindBestMoveUsingAlphaBetaAsync); arrMoveList[iIndex] = new List<ChessBoard.MovePosS>(moveList.Count / iThreadCount + 1); for (int iStep = iIndex; iStep < moveList.Count; iStep += iThreadCount) { arrMoveList[iIndex].Add(moveList[arrIndex[iStep]]); } } for (int iStep = 0; iStep < iThreadCount; iStep++) { arrAsyncResult[iStep] = arrDelFindBestMoveUsingAlphaBetaAsync[iStep].BeginInvoke(arrChessBoard[iStep], searchMode, ePlayerColor, iStep, arrMoveList[iStep], moveList.Count, iAlpha, iBeta, out iMovePermCount, out movePosTmp, out iMaxDepth, null, null); } iMaxDepth = 999; for (int iStep = 0; iStep < iThreadCount; iStep++) { iPts = arrDelFindBestMoveUsingAlphaBetaAsync[iStep].EndInvoke(out iMovePermCount, out movePosTmp, out iMaxDepthTmp, arrAsyncResult[iStep]); if (movePosTmp.StartPos != 255) { iPermCount += iMovePermCount; iMaxDepth = Math.Min(iMaxDepth, iMaxDepthTmp); if (bUseTransTable) { iCacheHit += TransTable.GetTransTable(iStep).CacheHit; } if (iPts > iAlpha) { iAlpha = iPts; moveBest = movePosTmp; bRetVal = true; } } } if (iMaxDepth == 999) { iMaxDepth = -1; } } else { ChessBoard chessBoardTmp; List<ChessBoard.MovePosS> moveListTmp; chessBoardTmp = chessBoard.Clone(); moveListTmp = new List<ChessBoard.MovePosS>(moveList.Count); for (int iIndex = 0; iIndex < moveList.Count; iIndex++) { moveListTmp.Add(moveList[arrIndex[iIndex]]); } iPts = FindBestMoveUsingAlphaBetaAsync(chessBoardTmp, searchMode, ePlayerColor, 0, // ThreadId moveListTmp, moveList.Count, iAlpha, iBeta, out iPermCount, out movePosTmp, out iMaxDepth); if (movePosTmp.StartPos != 255) { if (bUseTransTable) { iCacheHit += TransTable.GetTransTable(0).CacheHit; } moveBest = movePosTmp; bRetVal = true; } } return(bRetVal); }
/// <summary> /// Find a move from the opening book /// </summary> /// <param name="searchMode"> Search mode</param> /// <param name="move"> Found move</param> /// <returns> /// true if succeed, false if no move found in book /// </returns> public bool FindBookMove(SearchEngine.SearchMode searchMode, out ChessBoard.MovePosS move) { bool bRetVal; ChessBoard.MovePosS[] arrMoves; if (!m_board.StandardInitialBoard) { move.OriginalPiece = ChessBoard.PieceE.None; move.StartPos = 255; move.EndPos = 255; move.Type = ChessBoard.MoveTypeE.Normal; bRetVal = false; } else { arrMoves = MoveList; bRetVal = m_board.FindBookMove(searchMode, m_board.NextMoveColor, arrMoves, out move); } return(bRetVal); }
/// <summary> /// Find the best move for a player using alpha-beta pruning or minmax search /// </summary> /// <param name="searchMode"> Search mode</param> /// <param name="chessBoard"> Chess board to use. Null to use the base one</param> /// <param name="moveBest"> Best move found</param> /// <param name="iPermCount"> Total permutation evaluated</param> /// <param name="iCacheHit"> Number of moves found in the translation table cache</param> /// <param name="iMaxDepth"> Maximum depth evaluated</param> /// <returns> /// true if a move has been found /// </returns> public bool FindBestMove(SearchEngine.SearchMode searchMode, ChessBoard chessBoard, out ChessBoard.MovePosS moveBest, out int iPermCount, out int iCacheHit, out int iMaxDepth) { bool bRetVal; bool bUseBook; bUseBook = ((searchMode.m_eOption & SearchEngine.SearchMode.OptionE.UseBook) != 0); if (bUseBook && FindBookMove(searchMode, out moveBest)) { iPermCount = -1; iCacheHit = -1; iMaxDepth = 0; bRetVal = true; } else { if (chessBoard == null) { chessBoard = m_board; } m_dateTimeStartSearching = DateTime.Now; bRetVal = chessBoard.FindBestMove(searchMode, m_board.NextMoveColor, out moveBest, out iPermCount, out iCacheHit, out iMaxDepth); m_timeSpanLastSearch = DateTime.Now - m_dateTimeStartSearching; } return(bRetVal); }
/// <summary> /// ShowHint: Find and show a hint on the next move to do /// </summary> /// <param name="searchMode"> Search mode</param> /// <param name="movePos"> Move position found</param> /// <param name="iPermCount"> Permutation count</param> /// <param name="iCacheHit"> Cache hit</param> /// <returns> /// true if a hint has been shown /// </returns> public bool ShowHint(SearchEngine.SearchMode searchMode, out ChessBoard.MovePosS movePos, out int iPermCount, out int iCacheHit) { bool bRetVal; int iMaxDepth; if (FindBestMove(searchMode, null, out movePos, out iPermCount, out iCacheHit, out iMaxDepth)) { ShowHintMove(movePos); bRetVal = true; } else { bRetVal = false; } return(bRetVal); }
/// <summary> /// Show a hint. Can be called asynchronously by a secondary thread. /// </summary> /// <param name="searchMode"> Search mode</param> private void ShowHintAsync(SearchEngine.SearchMode searchMode) { Action delShowHintMove; Action delUnlockBoard; ChessBoard chessBoard; ChessBoard.MovePosS move; int iPermCount; int iCacheHit; int iMaxDepth; bool bMoveFound; bool bMultipleThread; chessBoard = m_chessCtl.ChessBoard.Clone(); bMultipleThread = (searchMode.m_eThreadingMode == SearchEngine.SearchMode.ThreadingModeE.DifferentThreadForSearch || searchMode.m_eThreadingMode == SearchEngine.SearchMode.ThreadingModeE.OnePerProcessorForSearch); bMoveFound = m_chessCtl.FindBestMove(searchMode, chessBoard, out move, out iPermCount, out iCacheHit, out iMaxDepth); if (bMultipleThread) { if (bMoveFound) { delShowHintMove = () => ShowHintMove(move, iPermCount, iMaxDepth, iCacheHit); Dispatcher.Invoke(delShowHintMove); } delUnlockBoard = () => UnlockBoard(); Dispatcher.Invoke(delUnlockBoard); } else { if (bMoveFound) { ShowHintMove(move, iPermCount, iMaxDepth, iCacheHit); } UnlockBoard(); } }
/// <summary> /// Computer play a move. Can be called asynchronously by a secondary thread. /// </summary> /// <param name="bFlash"> true to use flash when moving pieces</param> /// <param name="searchMode"> Search mode</param> private void PlayComputerAsync(bool bFlash, SearchEngine.SearchMode searchMode) { Func<bool> delPlayComputerMove; Action delUnlockBoard; Action delSetPlayingMode; ChessBoard chessBoard; ChessBoard.MovePosS move; int iPermCount; int iCacheHit; int iMaxDepth; bool bEndOfGame; bool bMoveFound; bool bMultipleThread; chessBoard = m_chessCtl.ChessBoard.Clone(); bMultipleThread = (searchMode.m_eThreadingMode == SearchEngine.SearchMode.ThreadingModeE.DifferentThreadForSearch || searchMode.m_eThreadingMode == SearchEngine.SearchMode.ThreadingModeE.OnePerProcessorForSearch); bMoveFound = m_chessCtl.FindBestMove(searchMode, chessBoard, out move, out iPermCount, out iCacheHit, out iMaxDepth); if (bMoveFound) { if (bMultipleThread) { delPlayComputerMove = () => PlayComputerMove(bFlash, MessageModeE.CallEndGame, move, iPermCount, iMaxDepth, iCacheHit, null); bEndOfGame = (bool)Dispatcher.Invoke(delPlayComputerMove); } else { bEndOfGame = PlayComputerMove(bFlash, MessageModeE.CallEndGame, move, iPermCount, iMaxDepth, iCacheHit, null); } } else { bEndOfGame = DisplayMessage(m_chessCtl.ChessBoard.CheckNextMove(), MessageModeE.CallEndGame); } if (bMultipleThread) { delUnlockBoard = () => UnlockBoard(); Dispatcher.Invoke(delUnlockBoard); if (bEndOfGame) { delSetPlayingMode = () => SetPlayingMode(PlayingModeE.PlayerAgainstPlayer); Dispatcher.Invoke(delSetPlayingMode); } } else { UnlockBoard(); if (bEndOfGame) { SetPlayingMode(PlayingModeE.PlayerAgainstPlayer); } } }
/// <summary> /// Let's the computer play against itself. Can be called asynchronously by a secondary thread. /// </summary> /// <param name="bFlash"> true to flash the moving piece</param> /// <param name="searchMode"> Search mode</param> private void PlayComputerAgainstComputerAsync(bool bFlash, SearchEngine.SearchMode searchMode) { bool bEndOfGame; int iCount; Func<ChessBoard.MovePosS,int,int,int,bool> delPlayComputerMove = null; Action delUnlockBoard; Action delSetPlayingMode; ChessBoard chessBoard; ChessBoard.MovePosS move; int iPermCount; int iCacheHit; int iMaxDepth; bool bMoveFound; bool bMultipleThread; bMultipleThread = (searchMode.m_eThreadingMode == SearchEngine.SearchMode.ThreadingModeE.DifferentThreadForSearch || searchMode.m_eThreadingMode == SearchEngine.SearchMode.ThreadingModeE.OnePerProcessorForSearch); if (bMultipleThread) { delPlayComputerMove = (a1,a2,a3,a4) => { return(PlayComputerMove(bFlash, MessageModeE.CallEndGame, a1, a2, a3, a4, null)); }; } iCount = 0; do { chessBoard = m_chessCtl.ChessBoard.Clone(); bMoveFound = m_chessCtl.FindBestMove(searchMode, chessBoard, out move, out iPermCount, out iCacheHit, out iMaxDepth); if (bMoveFound) { if (bMultipleThread) { bEndOfGame = (bool)Dispatcher.Invoke(delPlayComputerMove, new object[] { move, iPermCount, iMaxDepth, iCacheHit }); } else { bEndOfGame = PlayComputerMove(bFlash, MessageModeE.CallEndGame, move, iPermCount, iMaxDepth, iCacheHit, null); } } else { bEndOfGame = DisplayMessage(m_chessCtl.ChessBoard.CheckNextMove(), MessageModeE.Verbose); } iCount++; } while (!bEndOfGame && PlayingMode == PlayingModeE.ComputerAgainstComputer && iCount < 500); if (PlayingMode != PlayingModeE.ComputerAgainstComputer) { MessageBox.Show("Automatic play canceled"); } else { if (bMultipleThread) { delSetPlayingMode = () => SetPlayingMode(PlayingModeE.PlayerAgainstPlayer); Dispatcher.Invoke(delSetPlayingMode); } else { SetPlayingMode(PlayingModeE.PlayerAgainstPlayer); } if (iCount >= 500) { MessageBox.Show("Tie!"); } } if (bMultipleThread) { delUnlockBoard = () => UnlockBoard(); Dispatcher.Invoke(delUnlockBoard); } else { UnlockBoard(); } }
/// <summary> /// Show the test result of a computer playing against a computer /// </summary> /// <param name="iGameCount"> Number of games played.</param> /// <param name="searchMode"> Search mode</param> /// <param name="stat"> Statistic.</param> /// <param name="iMethod1Win"> Number of games won by method #1</param> /// <param name="iMethod2Win"> Number of games won by method #2</param> private void TestShowResult(int iGameCount, SearchEngine.SearchMode searchMode, ComputerPlayingStat stat, int iMethod1Win, int iMethod2Win) { string strMsg; string strMethod1; string strMethod2; int iTimeMethod1; int iTimeMethod2; strMethod1 = searchMode.m_boardEvaluationWhite.Name; strMethod2 = searchMode.m_boardEvaluationBlack.Name; iTimeMethod1 = (stat.m_iMethod1MoveCount == 0) ? 0 : stat.m_timeSpanMethod1.Milliseconds / stat.m_iMethod1MoveCount; iTimeMethod2 = (stat.m_iMethod2MoveCount == 0) ? 0 : stat.m_timeSpanMethod2.Milliseconds / stat.m_iMethod2MoveCount; strMsg = iGameCount.ToString() + " game(s) played.\r\n" + iMethod1Win.ToString() + " win(s) for method #1 (" + strMethod1 + "). Average time = " + iMethod1Win.ToString() + " ms per move.\r\n" + iMethod2Win.ToString() + " win(s) for method #2 (" + strMethod2 + "). Average time = " + iMethod2Win.ToString() + " ms per move.\r\n" + (iGameCount - iMethod1Win - iMethod2Win).ToString() + " draw(s)."; MessageBox.Show(strMsg); }
//********************************************************* // /// <summary> /// Class constructor. Build a board. /// </summary> // //********************************************************* public ChessBoard(SearchEngine.ITrace trace) : this(null, null) { m_trace = trace; m_searchEngineAlphaBeta = new SearchEngineAlphaBeta(trace, m_rnd, m_rndRep); m_searchEngineMinMax = new SearchEngineMinMax(trace, m_rnd, m_rndRep); }
static void Main(string[] args) { bool optimize = true; bool show_help = false; bool doquery = false; string indexFolder = ".totalrecall"; string website = ""; string query = ""; var p = new OptionSet() { { "o|optimize", "optimize index (default true)", v => { optimize = v != null; } }, { "q|query", "Query index", v => { doquery = v != null; } }, { "h|?|help", "show this screen", v => { show_help = v != null; } }, { "i|index=", "Lucene index location (default .totalrecall)" , v => { indexFolder = v; } } }; List<string> extras; try { extras = p.Parse(args); if (!doquery && extras.Count > 0) website = extras[0]; else if (doquery && extras.Count > 0) query = extras[0]; } catch (OptionException e) { Console.Write("rekall: "); Console.WriteLine(e.Message); Console.WriteLine("Try `rekall -?' for more information."); return; } if ((String.IsNullOrEmpty(website) && String.IsNullOrEmpty(query)) || show_help) { PrintUsage(); p.WriteOptionDescriptions(Console.Out); return; } if (doquery) { var se = new SearchEngine(); int index = 1; foreach (var hit in se.Search(query, 9)) { Console.WriteLine("{0}. {1}", index, hit.Title); Console.WriteLine(" {0}", hit.Url); Console.WriteLine(); index++; } } else { var crawler = new SiteCrawler(website, new ConsoleConfig() { IndexFolder = indexFolder, Optimize = optimize }, new ConsoleLogWrapper()); crawler.Crawl(); } #if DEBUG Console.WriteLine(); Console.Write("Press any key to continue"); Console.ReadKey(); #endif }
/// <summary> /// Tests the computer playing against itself. Can be called asynchronously by a secondary thread. /// </summary> /// <param name="iGameCount"> Number of games to play.</param> /// <param name="searchMode"> Search mode</param> private void TestComputerAgainstComputerAsync(int iGameCount, SearchEngine.SearchMode searchMode) { int iCount; Func<ChessBoard.MovePosS,int,int,int,ComputerPlayingStat,bool> delPlayComputerMove = null; Action delResetBoard = null; Action delUnlockBoard; Action delSetPlayingMode; Action delShowResultDel; ChessBoard chessBoard; ChessBoard.MovePosS move; int iPermCount; int iCacheHit; int iMaxDepth; int iGameIndex; int iMethod1Win = 0; int iMethod2Win = 0; DateTime dateTime; bool bMoveFound; bool bMultipleThread; bool bEven; bool bEndOfGame; IBoardEvaluation boardEvaluation1; IBoardEvaluation boardEvaluation2; ComputerPlayingStat stat; stat = new ComputerPlayingStat(); bMultipleThread = (searchMode.m_eThreadingMode == SearchEngine.SearchMode.ThreadingModeE.DifferentThreadForSearch || searchMode.m_eThreadingMode == SearchEngine.SearchMode.ThreadingModeE.OnePerProcessorForSearch); boardEvaluation1 = searchMode.m_boardEvaluationWhite; boardEvaluation2 = searchMode.m_boardEvaluationBlack; if (bMultipleThread) { delPlayComputerMove = (a1, a2, a3, a4, a5) => PlayComputerMove(false, MessageModeE.Silent, a1, a2, a3, a4, a5); delResetBoard = () => ResetBoard(); } iGameIndex = 0; while (iGameIndex < iGameCount && !stat.m_bUserCancel) { bEven = ((iGameIndex & 1) == 0); searchMode.m_boardEvaluationWhite = bEven ? boardEvaluation1 : boardEvaluation2; searchMode.m_boardEvaluationBlack = bEven ? boardEvaluation2 : boardEvaluation1; if (bMultipleThread) { Dispatcher.Invoke(delResetBoard); } else { ResetBoard(); } iCount = 0; do { chessBoard = m_chessCtl.ChessBoard.Clone(); dateTime = DateTime.Now; bMoveFound = m_chessCtl.FindBestMove(searchMode, chessBoard, out move, out iPermCount, out iCacheHit, out iMaxDepth); if (bMoveFound) { if ((m_chessCtl.NextMoveColor == ChessBoard.PlayerColorE.White && bEven) || (m_chessCtl.NextMoveColor == ChessBoard.PlayerColorE.Black && !bEven)) { stat.m_timeSpanMethod1 += DateTime.Now - dateTime; stat.m_iMethod1MoveCount++; } else { stat.m_timeSpanMethod2 += DateTime.Now - dateTime; stat.m_iMethod2MoveCount++; } if (bMultipleThread) { bEndOfGame = (bool)Dispatcher.Invoke(delPlayComputerMove, new object[] { move, iPermCount, iMaxDepth, iCacheHit, stat } ); } else { bEndOfGame = PlayComputerMove(false, MessageModeE.Silent, move, iPermCount, iMaxDepth, iCacheHit, stat); } } else { bEndOfGame = true; } iCount++; } while (!bEndOfGame && PlayingMode == PlayingModeE.ComputerAgainstComputer && iCount < 250); if (PlayingMode != PlayingModeE.ComputerAgainstComputer) { stat.m_bUserCancel = true; } else if (iCount < 250) { if (stat.m_eResult == ChessBoard.MoveResultE.Mate) { if ((m_chessCtl.NextMoveColor == ChessBoard.PlayerColorE.Black && bEven) || (m_chessCtl.NextMoveColor == ChessBoard.PlayerColorE.White && !bEven)) { iMethod1Win++; } else { iMethod2Win++; } } } iGameIndex++; } searchMode.m_boardEvaluationWhite = boardEvaluation1; searchMode.m_boardEvaluationBlack = boardEvaluation2; if (bMultipleThread) { delSetPlayingMode = () => SetPlayingMode(PlayingModeE.PlayerAgainstPlayer); delUnlockBoard = () => UnlockBoard(); delShowResultDel = () => TestShowResult(iGameIndex, searchMode, stat, iMethod1Win, iMethod2Win); Dispatcher.Invoke(delShowResultDel); Dispatcher.Invoke(delSetPlayingMode); Dispatcher.Invoke(delUnlockBoard); } else { TestShowResult(iGameIndex, searchMode, stat, iMethod1Win, iMethod2Win); SetPlayingMode(PlayingModeE.PlayerAgainstPlayer); UnlockBoard(); } }