private void SearchProcessDataReceived(DataReceivedEventArgs e) { var output = e.Data.Trim(); if (string.IsNullOrWhiteSpace(output)) { return; } if (output.Contains("yt command exited")) { Log.Debug("Done with Youtube Search, Processing..."); return; } if (output.Contains("yt command")) { Log.Debug($"Running with {output}"); return; } var trimmedLine = output; var ytResult = ParseSearchResult(trimmedLine); if (ytResult == null) { return; } SearchResults.Add(ytResult); SearchProgress?.Invoke(ytResult); }
public async Task <IList <ArmorSetSearchResult> > SearchArmorSets(ISolverData solverData, CancellationToken cancellationToken) { var innerCancellation = new CancellationTokenSource(); Task updateTask = UpdateSearchProgression(innerCancellation.Token, cancellationToken); IList <ArmorSetSearchResult> result = await Task.Factory.StartNew(() => { return(SearchArmorSetsInternal( solverData, cancellationToken )); }, TaskCreationOptions.LongRunning).Unwrap(); innerCancellation.Cancel(); await updateTask; if (cancellationToken.IsCancellationRequested == false) { SearchProgress?.Invoke(1.0); } return(result); }
public void StartSearch(Node node, String searchText, SearchProgress updator, ReflectionSearchResult resultRoot) { if (searchCoroutine != null) { StopCoroutine(searchCoroutine); searchCoroutine = null; } VisitedInstanceIDs.Clear(); resultRoot.Clear(); resultRoot.Node = node; StopAllCoroutines(); updator(0, 0, 1); if (node == null) { return; } SequenceNumber++; Main.Log($"seq: {SequenceNumber} - search for: {searchText}"); if (searchText.Length == 0) { } else { var todo = new List <Node> { node }; searchCoroutine = Search(searchText, todo, 0, 0, SequenceNumber, updator, resultRoot); StartCoroutine(searchCoroutine); } }
public SearchDirectoryResponse(string[] files, long[] filesSize, string[] folders, DateTime[] lastModificationDates, DateTime[] creationDates, SearchProgress progress) { this.Files = files; this.FilesSize = filesSize; this.Folders = folders; this.LastModificationDates = lastModificationDates; this.CreationDates = creationDates; this.Progress = progress; }
/// <summary> /// Searches for missing songs. /// </summary> /// <param name="missingSongs">List of songs to search for.</param> /// <param name="directory">Directory to search in.</param> /// <param name="searchTags">Whether to scan tags if filename search fails.</param> /// <param name="searchCue">Whether to scan cue files if filename search fails.</param> /// <param name="callbackAction">Callback to use to report progress.</param> /// <returns>Tuple of songs and found filepaths.</returns> public static List <(Song song, string file)> SearchSongs(List <Song> missingSongs, string directory, bool searchFilenames, bool searchTags, bool searchCue, Action <SearchProgress> callbackAction = null) { var foundSongs = new List <(Song song, string file)>(); var progress = new SearchProgress(missingSongs.Count); if (!(callbackAction is null)) { callbackAction(progress); } var files = Directory.GetFiles(directory, "*", SearchOption.AllDirectories); var _lock = new object(); progress.Status = SearchProgress.SearchStatus.Filenames; if (!(callbackAction is null)) { callbackAction(progress); } if (searchFilenames) { // Try to find the song in the search directory. Parallel.ForEach(missingSongs, song => { var found = false; // In theory, FLAC and MP3 files are much more likely to be found so prioritise searching by // extension rather than trying each extension on each file one after the other. foreach (var extension in Properties.Settings.Default.MusicExtensions) { var songFile = Path.GetFileName(Path.ChangeExtension(song.Path, extension)); if (found) { continue; } foreach (var file in files) { if (found) { continue; } // Update the data grid with the new filename if we found it. if (songFile == Path.GetFileName(file)) { lock (_lock) { foundSongs.Add((song, file)); if (!(callbackAction is null)) { progress.FoundSongs = foundSongs.Count; callbackAction(progress); } } found = true; }
// Processed in the main thread, called by workStart public void workProgress(Object sender, ProgressChangedEventArgs e) { SearchProgress progress = ((SearchProgress)e.UserState); labelStatus.Text = progress.Status; if (!progress.StatusOnly) { grid.Rows.Add(progress.FileName, progress.MatchingLineNumber, progress.MatchingLine); } }
private void ReportProgress(BackgroundWorker workerBee, string status) { SearchProgress progress = new SearchProgress() { StatusOnly = true, Status = status }; workerBee.ReportProgress(0, progress); }
private async Task UpdateSearchProgression(CancellationToken innerCancel, CancellationToken cancellationToken) { while (innerCancel.IsCancellationRequested == false && cancellationToken.IsCancellationRequested == false) { if (totalCombinations > 0) { SearchProgress?.Invoke(currentCombinations / totalCombinations); } await Task.Delay(250); } }
private void ReportProgress(BackgroundWorker workerBee, string fileName, string matchingLine, int?matchingLineNumber = null) { SearchProgress progress = new SearchProgress() { StatusOnly = false, Status = "Match Found: " + fileName, FileName = fileName, MatchingLine = matchingLine, MatchingLineNumber = matchingLineNumber }; workerBee.ReportProgress(0, progress); }
private void GraphsForm_Activated(object sender, EventArgs e) { if (activationFlag == false) { return; } SearchProgress.Show(); this.Enabled = false; performHarmonySearch(); plotChart(); SearchProgress.Hide(); this.Enabled = true; activationFlag = false; }
private void RerunButton_Click(object sender, EventArgs e) { SearchProgress.Show(); this.Enabled = false; performHarmonySearch(); numericsTab.Controls.RemoveByKey("aestheticsLabel"); for (int k = 1; k <= totalNotes; k++) { numericsTab.Controls.RemoveByKey("x" + k + "Label"); notesTab.Controls.RemoveByKey("x" + k + "Chart"); } plotChart(); SearchProgress.Hide(); this.Enabled = true; }
//============================================================= // Public constructors //============================================================= /// <summary> /// Creates instance of this class. /// </summary> /// <param name="key">TMDB API key.</param> /// <exception cref="System.ArgumentException">Thrown when provided key is invalid.</exception> public Database(string key) { if (!IsKeyValid(key)) { throw new ArgumentException("Invalid key.", "key"); } // Initialization. _client = new TMDbClient(key); _progress = new SearchProgress(); _seriesProgress = new SearchProgress(); // Setting up current state. CurrentState = State.Idle; Reset(); }
public SearchPage() { NavigationPage.SetHasNavigationBar(this, false); InitializeComponent(); BindingContext = this.searchViewModel = new SearchViewModel(); SearchListView.ItemsSource = searchViewModel.SearchList; SearchText.Completed += (sender, e) => { Search_Clicked(sender, e); }; SearchProgress.SetBinding(IsVisibleProperty, nameof(searchViewModel.IsProgressVisible)); SearchButton.SetBinding(IsVisibleProperty, nameof(searchViewModel.IsButtonVisible)); }
private void HandleSearchProgress(SearchProgress searchProgress) { UpdateSearchProgressStatus(searchProgress.ItemsFound); }
public bool Equals(SearchProgress progress) { return(NumResults == progress.NumResults && State == progress.State); }
/// <summary> /// Searches for missing songs. /// </summary> /// <param name="missingSongs">List of songs to search for.</param> /// <param name="directory">Directory to search in.</param> /// <param name="searchTags">Whether to scan tags if filename search fails.</param> /// <param name="searchCue">Whether to scan cue files if filename search fails.</param> /// <param name="callbackAction">Callback to use to report progress.</param> /// <returns>Tuple of songs and found filepaths.</returns> public static List <(Song song, string file)> SearchSongsSingle(List <Song> missingSongs, string directory, bool searchTags, bool searchCue, Action <SearchProgress> callbackAction = null) { var foundSongs = new List <(Song song, string file)>(); var progress = new SearchProgress(missingSongs.Count); if (!(callbackAction is null)) { callbackAction(progress); } var files = FileUtil.GetFiles(directory); progress.Status = SearchProgress.SearchStatus.Filenames; if (!(callbackAction is null)) { callbackAction(progress); } // Try to find the song in the search directory. foreach (var song in missingSongs) { var found = false; // In theory, FLAC and MP3 files are much more likely to be found so prioritise searching by // extension rather than trying each extension on each file one after the other. foreach (var extension in Properties.Settings.Default.MusicExtensions) { if (found) { continue; } foreach (var file in files) { if (found) { continue; } // Update the data grid with the new filename if we found it. if (Path.GetFileName(Path.ChangeExtension(song.Path, extension)) == Path.GetFileName(file)) { foundSongs.Add((song, file)); found = true; if (!(callbackAction is null)) { progress.FoundSongs = foundSongs.Count; callbackAction(progress); } } } } } progress.Status = SearchProgress.SearchStatus.CueSheets; if (!(callbackAction is null)) { callbackAction(progress); } if (searchCue) { foreach (var song in foundSongs.Select(x => x.song)) { missingSongs.Remove(song); } if (missingSongs.Count > 0) { var filteredFiles = files.Where(x => String.Compare(Path.GetExtension(x), ".cue", StringComparison.OrdinalIgnoreCase) == 0); foreach (var cueFile in filteredFiles) { if (missingSongs.Count == 0) { break; } var cueSheet = new CueSheet(cueFile); for (var i = 0; i < missingSongs.Count; i++) { var song = missingSongs[i]; if (String.Compare(song.Album, cueSheet.Album, StringComparison.OrdinalIgnoreCase) == 0) { for (var j = 0; j < cueSheet.Tracks.Count; j++) { if (String.Compare(song.Title, cueSheet.Tracks[j].Title, StringComparison.OrdinalIgnoreCase) == 0) { foundSongs.Add((song, $"{cueFile}:{j}")); missingSongs.RemoveAt(i); i--; if (!(callbackAction is null)) { progress.FoundSongs = foundSongs.Count; callbackAction(progress); } break; } } } } } } } progress.Status = SearchProgress.SearchStatus.Tags; if (!(callbackAction is null)) { callbackAction(progress); } if (searchTags) { // As the list might have been pruned in the cue search, we can't just remove // all the entries without checking first. foreach (var song in foundSongs.Select(x => x.song)) { if (missingSongs.Contains(song)) { missingSongs.Remove(song); } } // Songs that couldn't be found from path alone. if (missingSongs.Count > 0) { var filteredFiles = (from file in files let extension = Path.GetExtension(file) where extension.Length > 1 where Properties.Settings.Default.MusicExtensions.Contains(extension.Substring(1)) select file).ToList(); // Search through every music file found. foreach (var file in filteredFiles) { // No point loading tags if all songs have been found already. if (missingSongs.Count == 0) { break; } var tag = GetTags(file); for (var i = 0; i < missingSongs.Count; i++) { var song = missingSongs[i]; if (string.Compare(song.Title, tag.Title, StringComparison.OrdinalIgnoreCase) == 0 && string.Compare(song.Album, tag.Album, StringComparison.OrdinalIgnoreCase) == 0) { // That's probably the right song. foundSongs.Add((song, file)); missingSongs.RemoveAt(i); if (!(callbackAction is null)) { progress.FoundSongs = foundSongs.Count; callbackAction(progress); } break; } } } } } progress.Status = SearchProgress.SearchStatus.Complete; if (!(callbackAction is null)) { callbackAction(progress); } return(foundSongs); }
private void InvokeProgressChanged(double value) { SearchProgress?.Invoke(value); }
public bool StartProcessing() { using (DataSet data = new DataSet()) { //clean data string[] datas = File.ReadAllLines(srcFile); string headLine = datas[0]; string newHeadlLine = headLine.Replace('"', ' '); TextWriter tw = new StreamWriter(srcFile); tw.WriteLine(newHeadlLine); for (int i = 1; i < datas.Length; i++) { tw.WriteLine(datas[i]); } tw.Close(); if (!data.import_ascii(srcFile)) { throw new ArgumentException("Unable to import this file"); } Console.WriteLine("Data imported successfully"); Console.WriteLine(data.summary()); using (SearchOptions options = new SearchOptions(srcModel)) { Console.WriteLine("> Setting the search options"); //options.building_blocks_.Remove("a-b"); for (int i = 0; i < options.building_blocks_.Count; i++) { Console.WriteLine(options.building_blocks_[i]); } using(Connection conn = new Connection()){ try { //140.113.88.194 Console.WriteLine("> Connecting to a eureqa server at " + srcIP); if (!conn.connect(srcIP)) { Console.WriteLine("Unable to connect to server at " + srcIP); Console.WriteLine(@"Try running the eureqa_server binary provided with the Eureqa API (""server"" sub-directory) first."); throw new ApplicationException("Unable to connect to server at " + srcIP); } else HandleLastResult(conn, "Connection made", "Connected to server"); Console.WriteLine("> Querying the server systems information"); using (ServerInfo serv = new ServerInfo()) { if (!conn.query_server_info(serv)) { Console.WriteLine("Unable to recieve the server information"); throw new ApplicationException("Unable to recieve the server information"); } else { Console.WriteLine("Recieved server information successfully:"); Console.WriteLine(serv.summary()); } } Console.WriteLine("> Sending the data set to the server"); if (!conn.send_data_set(data)) { Console.WriteLine("Unable to transfer the data set"); throw new ArgumentException("Unable to transfer the data set"); } else HandleLastResult(conn, "Data set transferred"); Console.WriteLine("> Sending search options to the server"); if (!conn.send_options(options)) { Console.WriteLine("Unable to transfer the search options"); } else HandleLastResult(conn, "Search options transferred"); Console.WriteLine("> Telling server to start searching"); if (!conn.start_search()) { Console.WriteLine("Unable to send the start command"); throw new ApplicationException("Unable to send the start command"); } else HandleLastResult(conn, "Start command sent"); Console.WriteLine("> Monitoring the search progress"); Dictionary<float, Tuple<float, string>> fitSize = new Dictionary<float, Tuple<float, string>>(); ArrayList models = new ArrayList(); using (SearchProgress progress = new SearchProgress()) { using (SolutionFrontier bestSolutions = new SolutionFrontier()) { int c = 0; //string output; Console.WriteLine("Debug 1"); while (conn.query_progress(progress)) { //Console.WriteLine("> " + progress.summary()); Console.WriteLine("Debug 2"); using (var solution = progress.solution_) { Console.WriteLine("Debug 3"); if (bestSolutions.add(solution)) { Console.Write("New solution found:"); Console.WriteLine(solution.text_); } //output = " >> fitness >> " + solution.fitness_ + " >> size >> " + solution.complexity_ + " >> equation >> " + solution.text_; // Console.WriteLine(output); fitSize[solution.fitness_] = new Tuple<float,string>(solution.complexity_,solution.text_); //models.Add(solution.text_); } //Console.WriteLine(); //Console.WriteLine(bestSolutions.to_string()); //Console.WriteLine(); //Thread.Sleep(new TimeSpan(0, 0, 1)); ++c; if (c > _loops) break; } } } var list = fitSize.Keys.ToList(); list.Sort(); using (TextWriter tw2 = new StreamWriter(saveModelPath)) { for (int i = 0; i < 1; i++) { tw2.WriteLine(fitSize[list[i]].Item2); Console.WriteLine(fitSize[list[i]].Item2); } //tw2.Close(); } } finally { conn.disconnect(); } } } } return true; }
private void ReportProgress(SearchProgress obj) { tslBlobStatus.Text = $"Searching {obj.AccountName}.{obj.ContainerName} {obj.Path}..."; }
void Setup() { if (reflectionValue == null) { reflectionValue = MemberData.none; } if (filter == null) { filter = new FilterAttribute() { UnityReference = false, OnlyGetType = onlyGetType }; } if (onlyGetType) { filter = new FilterAttribute(filter) { OnlyGetType = onlyGetType } } ; if (filter.OnlyGetType) { filter.ValidTargetType = MemberData.TargetType.Type | MemberData.TargetType.Null; } if (targetObject) { uNodeRoot UNR = null; if (targetObject is uNodeRoot) { UNR = targetObject as uNodeRoot; } else if (targetObject is RootObject) { UNR = (targetObject as RootObject).owner; } else if (targetObject is NodeComponent) { UNR = (targetObject as NodeComponent).owner; } else if (targetObject is TransitionEvent) { UNR = (targetObject as TransitionEvent).owner; } if (UNR) { uNodeData data = UNR.GetComponent <uNodeData>(); if (data) { //Clear the default namespace usingNamespaces.Clear(); //Add graph namespaces foreach (var n in data.GetNamespaces()) { usingNamespaces.Add(n); } } if (UNR is IIndependentGraph graph) { if (data == null) { //Clear the default namespace usingNamespaces.Clear(); } foreach (var n in graph.UsingNamespaces) { usingNamespaces.Add(n); } } } } editorData.manager = new Manager(new TreeViewState()); editorData.manager.window = this; editorData.searchField = new SearchField(); editorData.searchField.downOrUpArrowKeyPressed += editorData.manager.SetFocusAndEnsureSelectedItem; editorData.searchField.autoSetFocusOnFindCommand = true; window = this; uNodeThreadUtility.Queue(DoSetup); } void DoSetup() { editorData.setup.Setup((progress) => { if (progress == 1) { uNodeThreadUtility.Queue(() => { var categories = new List <TreeViewItem>(); if (displayDefaultItem) { var categoryTree = new SelectorCategoryTreeView("#", "", uNodeEditorUtility.GetUIDFromString("[CATEG]#"), -1); categories.Add(categoryTree); var recentTree = new SelectorCategoryTreeView("Recently", "", uNodeEditorUtility.GetUIDFromString("[CATEG]#Recently"), -1); categories.Add(recentTree); if (displayNoneOption && filter.IsValidTarget(MemberData.TargetType.None)) { categoryTree.AddChild(new SelectorMemberTreeView(MemberData.none, "None", uNodeEditorUtility.GetUIDFromString("#None")) { icon = uNodeEditorUtility.GetTypeIcon(typeof(TypeIcons.NullTypeIcon)) as Texture2D }); } if (!filter.SetMember) { if (!filter.IsValueTypes() && filter.IsValidTarget(MemberData.TargetType.Null) && !filter.OnlyGetType) { categoryTree.AddChild(new SelectorMemberTreeView(MemberData.Null, "Null", uNodeEditorUtility.GetUIDFromString("#Null")) { icon = uNodeEditorUtility.GetTypeIcon(typeof(TypeIcons.NullTypeIcon)) as Texture2D }); } //if(!filter.OnlyGetType && filter.IsValidTarget(MemberData.TargetType.Values) && // (filter.Types == null || filter.Types.Count != 1 || filter.Types[0] != typeof(Type))) { // categoryTree.AddChild(new SelectorCallbackTreeView((cRect) => { // var screenRect = cRect.ToScreenRect(); // FilterAttribute F = new FilterAttribute(filter); // F.OnlyGetType = true; // ItemSelector w = null; // Action<MemberData> action = delegate (MemberData m) { // if(w != null) { // w.Close(); // //EditorGUIUtility.ExitGUI(); // } // if(filter.CanManipulateArray()) { // if(Event.current.button == 0) { // TypeSelectorWindow.ShowAsNew(Rect.zero, F, delegate (MemberData[] members) { // Type t = members[0].Get<Type>(); // SelectValues(t); // }, m).ChangePosition(screenRect); // } else { // CommandWindow.CreateWindow(screenRect, (items) => { // var member = CompletionEvaluator.CompletionsToMemberData(items); // if(member != null) { // Type t = member.Get<Type>(); // SelectValues(t); // return true; // } // return false; // }, new CompletionEvaluator.CompletionSetting() { // validCompletionKind = CompletionKind.Type | CompletionKind.Namespace | CompletionKind.Keyword, // }); // } // } else { // Type t = m.Get<Type>(); // SelectValues(t); // } // }; // w = ShowAsNew(targetObject, F, action, true).ChangePosition(screenRect); // }, "Values", uNodeEditorUtility.GetUIDFromString("#Values"), -1) { // icon = uNodeEditorUtility.GetTypeIcon(typeof(TypeIcons.ValueIcon)) as Texture2D // }); //} } if (displayRecentItem) { var listRecentItems = new List <TreeViewItem>(); if (uNodeEditor.SavedData.recentItems != null) { foreach (var recent in uNodeEditor.SavedData.recentItems) { if (recent != null && recent.info != null) { if (recent.info is Type) { listRecentItems.Add(new TypeTreeView(recent.info as Type, recent.GetHashCode(), -1)); } else if (!filter.OnlyGetType && (recent.isStatic || filter.DisplayInstanceOnStatic)) { listRecentItems.Add(new MemberTreeView(recent.info, recent.GetHashCode(), -1)); } } } } while (listRecentItems.Count > 10) { listRecentItems.RemoveAt(listRecentItems.Count - 1); } if (listRecentItems.Count > 0) { foreach (var item in listRecentItems) { if (item is MemberTreeView) { var tree = item as MemberTreeView; if (!(tree.member is Type)) { tree.displayName = tree.member.DeclaringType.Name + "." + tree.displayName; } } recentTree.AddChild(item); } recentTree.expanded = false; } } if (!filter.OnlyGetType && filter.UnityReference) { if (reflectionValue != null && reflectionValue.GetInstance() != null && !(reflectionValue.GetInstance() is IGraphSystem) && !(reflectionValue.GetInstance() is INode)) { categories.Add(TreeFunction.CreateTargetItem(reflectionValue.GetInstance(), "Target Reference", filter)); } categories.AddRange(TreeFunction.CreateGraphItem(targetObject, reflectionValue, filter)); } if (filter.UnityReference) { categories.AddRange(TreeFunction.CreateRootItem(targetObject, filter)); } categories.AddRange(TreeFunction.CreateCustomItem(customItems)); if (filter.DisplayDefaultStaticType) { categoryTree.AddChild(new SelectorGroupedTreeView(() => { var result = new List <TreeViewItem>(); result.Add(new SelectorSearchTreeView((prog) => { var treeResult = new List <TreeViewItem>(); var sp = new SearchProgress(); prog?.Invoke(sp); var allTypes = GetAllTypes((currProgress) => { prog?.Invoke(currProgress); }, true, true); sp.info = "Setup Items"; for (int i = 0; i < allTypes.Count; i++) { var pair = allTypes[i]; var nsTree = new SelectorCategoryTreeView(pair.Key, "", uNodeEditorUtility.GetUIDFromString("[CATEG-SEARCH]" + pair.Key), -1); foreach (var type in pair.Value) { nsTree.AddChild(new TypeTreeView(type, type.GetHashCode(), -1)); } treeResult.Add(nsTree); sp.progress = (float)i / (float)allTypes.Count; prog?.Invoke(sp); } return(treeResult); }, "Search All Types", uNodeEditorUtility.GetUIDFromString("[SAT]"), -1)); var nestedNS = new HashSet <string>(); //var excludedNs = uNodePreference.GetExcludedNamespace(); var namespaces = new List <string>(EditorReflectionUtility.GetNamespaces()); namespaces.Sort(); namespaces.RemoveAll(i => /*excludedNs.Contains(i) ||*/ i == null || i.Contains(".")); foreach (var ns in namespaces) { result.Add(new NamespaceTreeView(ns, uNodeEditorUtility.GetUIDFromString("[N]" + ns), -1)); } //var nsTypes = GetNamespaceTypes(namespaces); //foreach(var pair in nsTypes) { // var nsTree = new SelectorCategoryTreeView(pair.Key, "", uNodeEditorUtility.GetUIDFromString("[Nested-NS]" + pair.Key), -1); // foreach(var ns in nestedNS) { // if(ns.StartsWith(pair.Key)) { // nsTree.AddChild(new NamespaceTreeView(ns, uNodeEditorUtility.GetUIDFromString("[N]" + ns), -1)); // } // } // foreach(var type in pair.Value) { // nsTree.AddChild(new TypeTreeView(type, type.GetHashCode(), -1)); // } // //nsTree.children.Sort((x, y) => string.Compare(x.displayName, y.displayName)); // nsTree.expanded = false; // result.Add(nsTree); //} return(result); }, "All Namespaces", uNodeEditorUtility.GetUIDFromString("[ALL-NS]"), -1) { icon = uNodeEditorUtility.GetTypeIcon(typeof(TypeIcons.NamespaceIcon)) as Texture2D }); categoryTree.AddChild(new SelectorGroupedTreeView(() => { var result = new List <TreeViewItem>(); var favorites = uNodeEditor.SavedData.favoriteItems; if (favorites != null) //Favorite Type and Members { var typeTrees = new List <TypeTreeView>(); var memberTrees = new List <MemberTreeView>(); foreach (var fav in favorites) { if (fav.info != null && window.filter.IsValidMember(fav.info)) { if (fav.info is Type type) { typeTrees.Add(new TypeTreeView(type)); } else { var tree = new MemberTreeView(fav.info); tree.displayName = tree.member.DeclaringType.Name + "." + tree.displayName; memberTrees.Add(tree); } } } typeTrees.Sort((x, y) => string.Compare(x.displayName, y.displayName)); memberTrees.Sort((x, y) => string.Compare(x.displayName, y.displayName)); var typeCategory = new SelectorCategoryTreeView("Types", "", uNodeEditorUtility.GetUIDFromString("[TYPES]"), -1); foreach (var tree in typeTrees) { typeCategory.AddChild(tree); } var memberCategory = new SelectorCategoryTreeView("Members", "", uNodeEditorUtility.GetUIDFromString("[MEMBERS]"), -1); foreach (var tree in memberTrees) { memberCategory.AddChild(tree); } if (typeCategory.hasChildren) { result.Add(typeCategory); } if (memberCategory.hasChildren) { result.Add(memberCategory); } } { //Favorite Namespaces var nsTrees = new List <NamespaceTreeView>(); foreach (var fav in uNodeEditor.SavedData.favoriteNamespaces) { nsTrees.Add(new NamespaceTreeView(fav, uNodeEditorUtility.GetUIDFromString("[NS-FAV]" + fav), -1)); } nsTrees.Sort((x, y) => string.Compare(x.displayName, y.displayName)); var nsCategory = new SelectorCategoryTreeView("Namespaces", "", uNodeEditorUtility.GetUIDFromString("[NS]"), -1); foreach (var tree in nsTrees) { nsCategory.AddChild(tree); } if (nsCategory.hasChildren) { result.Add(nsCategory); } } return(result); }, "Favorites", uNodeEditorUtility.GetUIDFromString("[fav]"), -1) { icon = uNodeGUIUtility.Styles.favoriteIconOn }); var namespaceTrees = new SelectorCategoryTreeView("Types", "", uNodeEditorUtility.GetUIDFromString("[NS]"), -1); if (displayGeneralType) { var categTree = new SelectorCategoryTreeView("General", "", uNodeEditorUtility.GetUIDFromString("[GENERAL]"), -1); var items = TreeFunction.GetGeneralTrees(); items.ForEach(tree => categTree.AddChild(tree)); namespaceTrees.AddChild(categTree); } if (filter.DisplayRuntimeType) { var runtimeItems = TreeFunction.GetRuntimeItems(); var runtimeTypes = new Dictionary <string, List <TypeTreeView> >(); foreach (var item in runtimeItems) { var ns = item.type.Namespace; if (string.IsNullOrEmpty(ns) || ns == RuntimeType.RuntimeNamespace) { ns = "Generated Type"; } List <TypeTreeView> list; if (!runtimeTypes.TryGetValue(ns, out list)) { list = new List <TypeTreeView>(); runtimeTypes[ns] = list; } list.Add(item); } foreach (var pair in runtimeTypes) { var categTree = new SelectorCategoryTreeView(pair.Key, "", uNodeEditorUtility.GetUIDFromString("[RT]" + pair.Key), -1); var items = pair.Value; items.ForEach(tree => categTree.AddChild(tree)); namespaceTrees.AddChild(categTree); } } var typeList = editorData.setup.typeList; foreach (var pair in typeList) { var nsTree = new SelectorCategoryTreeView(pair.Key, "", uNodeEditorUtility.GetUIDFromString("[CATEG]" + pair.Key), -1); foreach (var type in pair.Value) { nsTree.AddChild(new TypeTreeView(type, type.GetHashCode(), -1)); } namespaceTrees.AddChild(nsTree); } categories.Add(namespaceTrees); } }
private async Task <IList <ArmorSetSearchResult> > SearchArmorSetsInternal( ISolverData data, CancellationToken cancellationToken ) { if (cancellationToken.IsCancellationRequested) { return(null); } var allCharms = new List <ICharmLevel>(); if (cancellationToken.IsCancellationRequested) { return(null); } var heads = new List <IArmorPiece>(); var chests = new List <IArmorPiece>(); var gloves = new List <IArmorPiece>(); var waists = new List <IArmorPiece>(); var legs = new List <IArmorPiece>(); var test = new List <ArmorSetSearchResult>(); var generator = new EquipmentCombinationGenerator( searchEquipmentsObjectPool, data.AllHeads.Where(x => x.IsSelected).Select(x => x.Equipment), data.AllChests.Where(x => x.IsSelected).Select(x => x.Equipment), data.AllGloves.Where(x => x.IsSelected).Select(x => x.Equipment), data.AllWaists.Where(x => x.IsSelected).Select(x => x.Equipment), data.AllLegs.Where(x => x.IsSelected).Select(x => x.Equipment), data.AllCharms.Where(x => x.IsSelected).Select(x => x.Equipment) ); var sb = new StringBuilder(); long hh = data.AllHeads.Count(x => x.IsSelected); long cc = data.AllChests.Count(x => x.IsSelected); long gg = data.AllGloves.Count(x => x.IsSelected); long ww = data.AllWaists.Count(x => x.IsSelected); long ll = data.AllLegs.Count(x => x.IsSelected); long ch = data.AllCharms.Count(x => x.IsSelected); long combinationCount = Math.Max(hh, 1) * Math.Max(cc, 1) * Math.Max(gg, 1) * Math.Max(ww, 1) * Math.Max(ll, 1) * Math.Max(ch, 1); await Task.Yield(); var parallelOptions = new ParallelOptions { //MaxDegreeOfParallelism = 1, // to ease debugging MaxDegreeOfParallelism = Environment.ProcessorCount }; currentCombinations = 0; totalCombinations = combinationCount; ParallelLoopResult parallelResult; try { OrderablePartitioner <IEquipment[]> partitioner = Partitioner.Create(generator.All(cancellationToken), EnumerablePartitionerOptions.NoBuffering); parallelResult = Parallel.ForEach(partitioner, parallelOptions, equips => { if (cancellationToken.IsCancellationRequested) { searchEquipmentsObjectPool.PutObject(equips); return; } ArmorSetSearchResult searchResult = IsArmorSetMatching(data.WeaponSlots, equips, data.AllJewels, data.DesiredAbilities); Interlocked.Increment(ref currentCombinations); if (searchResult.IsMatch) { searchResult.ArmorPieces = new IArmorPiece[] { (IArmorPiece)equips[0], (IArmorPiece)equips[1], (IArmorPiece)equips[2], (IArmorPiece)equips[3], (IArmorPiece)equips[4], }; searchResult.Charm = (ICharmLevel)equips[5]; lock (test) { test.Add(searchResult); } } searchEquipmentsObjectPool.PutObject(equips); }); if (cancellationToken.IsCancellationRequested == false) { SearchProgress?.Invoke(1.0); } } finally { generator.Reset(); } return(test); }
private IEnumerator Search(String searchText, List <Node> todo, int depth, int visitCount, int sequenceNumber, SearchProgress updator, ReflectionSearchResult resultRoot) { yield return(null); if (sequenceNumber != SequenceNumber) { yield return(null); } var todoText = todo.Count > 0 ? todo.First().Name : "n/a"; //Main.Log(depth, $"seq: {sequenceNumber} depth: {depth} - count: {todo.Count} - todo[0]: {todoText}"); var newTodo = new List <Node> { }; var breadth = todo.Count(); foreach (var node in todo) { bool foundMatch = false; var instanceID = node.InstanceID; bool alreadyVisted = false; if (instanceID is int instID) { if (VisitedInstanceIDs.Contains(instID)) { alreadyVisted = true; } else { VisitedInstanceIDs.Add(instID); } } visitCount++; //Main.Log(depth, $"node: {node.Name} - {node.GetPath()}"); try { if (Matches(node.Name, searchText) || Matches(node.ValueText, searchText)) { foundMatch = true; updator(visitCount, depth, breadth); resultRoot.AddSearchResult(node); Main.Log(depth, $"matched: {node.GetPath()} - {node.ValueText}"); Main.Log($"{resultRoot.ToString()}"); } } catch (Exception e) { Main.Log(depth, $"caught - {e}"); } node.Matches = foundMatch; if (!foundMatch) { //Main.Log(depth, $"NOT matched: {node.Name} - {node.ValueText}"); //if (node.Expanded == ToggleState.On && node.GetParent() != null) { // node.Expanded = ToggleState.Off; //} if (visitCount % 100 == 0) { updator(visitCount, depth, breadth); } } if (node.hasChildren && !alreadyVisted) { if (node.InstanceID is int instID2 && instID2 == this.GetInstanceID()) { break; } if (node.Name == "searchCoroutine") { break; } //if (node.Name == "SyncRoot") break; //if (node.Name == "normalized") break; try { foreach (var child in node.GetItemNodes()) { //Main.Log(depth + 1, $"item: {child.Name}"); newTodo.Add(child); } } catch (Exception e) { Main.Log(depth, $"caught - {e}"); } try { foreach (var child in node.GetComponentNodes()) { //Main.Log(depth + 1, $"comp: {child.Name}"); newTodo.Add(child); } } catch (Exception e) { Main.Log(depth, $"caught - {e}"); } try { foreach (var child in node.GetPropertyNodes()) { //Main.Log(depth + 1, $"prop: {child.Name}"); newTodo.Add(child); } } catch (Exception e) { Main.Log(depth, $"caught - {e}"); } try { foreach (var child in node.GetFieldNodes()) { //Main.Log(depth + 1, $"field: {child.Name}"); newTodo.Add(child); } } catch (Exception e) { Main.Log(depth, $"caught - {e}"); } } if (visitCount % 1000 == 0) { yield return(null); } } if (newTodo.Count > 0 && depth < Main.settings.maxSearchDepth) { yield return(Search(searchText, newTodo, depth + 1, visitCount, sequenceNumber, updator, resultRoot)); } else { Stop(); } }
public void Run(string srcFile, string srcModel, string srcIP) { using (DataSet data = new DataSet()) { string sourcePath = srcFile; //clean data string[] datas = File.ReadAllLines(sourcePath); string headLine = datas[0]; string newHeadlLine = headLine.Replace('"', ' '); TextWriter tw = new StreamWriter(sourcePath); tw.WriteLine(newHeadlLine); for (int i = 1; i < datas.Length; i++) { tw.WriteLine(datas[i]); } tw.Close(); if (!data.import_ascii(sourcePath)) { throw new ArgumentException("Unable to import this file"); } Console.WriteLine("Data imported successfully"); Console.WriteLine(data.summary()); string model = srcModel; using (SearchOptions options = new SearchOptions(model)) { Console.WriteLine("> Setting the search options"); for (int i = 0; i < options.building_blocks_.Count; i++) { Console.WriteLine(options.building_blocks_[i]); } using (Connection conn = new Connection()) { try { //140.113.88.194 string ipServer = srcIP; Console.WriteLine("> Connecting to a eureqa server at " + ipServer); if (!conn.connect(ipServer)) { Console.WriteLine("Unable to connect to server"); Console.WriteLine(@"Try running the eureqa_server binary provided with the Eureqa API (""server"" sub-directory) first."); throw new ApplicationException("Cannot connect to the local server."); } else HandleLastResult(conn, "Connection made", "Connected to server"); using (ServerInfo serv = new ServerInfo()) { Console.WriteLine("> Querying the server systems information"); if (!conn.query_server_info(serv)) { Console.WriteLine("Unable to recieve the server information"); throw new ApplicationException("No info"); } else { Console.WriteLine("Recieved server information successfully:"); Console.WriteLine(serv.summary()); } } Console.WriteLine("> Sending the data set to the server"); if (!conn.send_data_set(data)) { Console.WriteLine("Unable to transfer the data set"); throw new ArgumentException("Cannot send data set"); } else HandleLastResult(conn, "Data set transferred"); Console.WriteLine("> Sending search options to the server"); if (!conn.send_options(options)) { Console.WriteLine("Unable to transfer the search options"); } else HandleLastResult(conn, "Search options transferred"); Console.WriteLine("> Telling server to start searching"); if (!conn.start_search()) { Console.WriteLine("Unable to send the start command"); throw new ApplicationException("Unable to send the start command"); } else HandleLastResult(conn, "Start command sent"); Console.WriteLine("> Monitoring the search progress"); Dictionary<float, float> fitSize = new Dictionary<float, float>(); ArrayList models = new ArrayList(); using (SearchProgress progress = new SearchProgress()) { using (SolutionFrontier bestSolutions = new SolutionFrontier()) { int c = 0; while (conn.query_progress(progress)) { Console.WriteLine("> " + progress.summary()); using (var solution = progress.solution_) { if (bestSolutions.add(solution)) { Console.Write("New solution found:"); Console.WriteLine(solution.text_); } Console.WriteLine(" >> fitness >> " + solution.fitness_ + " >> size " + solution.complexity_ + " equation " + solution.text_); fitSize[solution.fitness_] = solution.complexity_; models.Add(solution.text_); } //Console.WriteLine(); //Console.WriteLine(bestSolutions.to_string()); //Console.WriteLine(); //Thread.Sleep(new TimeSpan(0, 0, 1)); ++c; if (c > 50000) break; } } } Console.ReadKey(); } finally { conn.disconnect(); } } } } }