public override void Solve() { base.Solve(); var expressionGrammar = new LabGrammar(); var language = new LanguageData(expressionGrammar); var parser = new Parser(language); var runtime = new LabRuntime(language); ParseTree tree = parser.Parse(Function); if (tree.HasErrors()) { Results.Add(new BoxModel("Error at parsing", "Syntax errors found. Abrting.")); return; } if (Precision * Math.Abs(A - B) > 0.3 && Method != "simpson") { Results.Add(new BoxModel("Precision too small", "Use Simpson's method or make precisionne bigger")); return; } Results.AddRange(IntegralCalculator.Calculate( tree, runtime, A, B, Precision, Method, Subtype )); }
public override void Solve() { base.Solve(); Results.Add(new ArrayBoxModel <Fraction>($"Input (Using #{Method})", _matrix)); switch (_method) { case LinearSolverMethod.Gauss: case LinearSolverMethod.GaussMain: Results.AddRange( GaussSolver.GaussSolution(_matrix, _method == LinearSolverMethod.GaussMain) ); break; case LinearSolverMethod.SimpleIterations: case LinearSolverMethod.Seidel: Results.AddRange( IterationsSolver.Solve(_matrix, Precision, _method == LinearSolverMethod.Seidel) ); break; default: Results.Add(new BoxModel("Not implemented method", $"Method {_method} is not implemented.")); break; } }
public async Task LoadMoreData() { if (IsFetching) { return; } try { var ids = QueryResult.Result.Skip(Results?.Count ?? 0).Take(10).ToList(); if (ids.Count == 0) { return; } IsFetching = true; var result = await tradeSearchService.GetResults(QueryResult.Id, ids, GetModifierFilters()); IsFetching = false; if (result != null && result.Any()) { Results.AddRange(result.Select(x => new PriceItem(x) { ImageUrl = new Uri($"{gameLanguageProvider.Language.PoeCdnBaseUrl}{itemStaticDataProvider.GetImage(x.Price.Currency)}").AbsoluteUri, })); } UpdateCountString(); } catch (Exception e) { logger.LogError(e, "Error loading more data"); } }
protected override Task <bool> SearchPage(object searchParameters, ulong offset, int requestId) { var tcs = new TaskCompletionSource <bool>(); if (offset >= Convert.ToUInt64(m_ids.Count)) { tcs.SetResult(false); return(tcs.Task); } GetOptionQuotesResponse.BeginGetOptionQuotes( AccountManager.GetAuthInfo, async response => { GetOptionQuotesResponse.EndGetOptionQuotes(response); var res = response.AsyncState as GetOptionQuotesResponse; Results.AddRange(res.OptionQuotes); await Task.Delay(TimeSpan.FromMilliseconds(50)); tcs.SetResult(true); }, requestId, Filters, m_ids.Skip(Convert.ToInt32(offset)).Take(20).ToList() ); return(tcs.Task); }
public void NothingToDoTest() { Stream configStream = Assembly.GetExecutingAssembly().GetManifestResourceStream( "RemoteInstallUnitTests.TestConfigs.NothingToDo.config"); string configFileName = Path.GetTempFileName(); using (StreamReader sr = new StreamReader(configStream)) { File.WriteAllText(configFileName, sr.ReadToEnd()); } string outputDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(outputDir); try { Driver driver = new Driver(outputDir, true, configFileName, null, 0); Results results = new Results(); results.AddRange(driver.Run()); Assert.Fail("Expected InvalidConfigurationException"); } catch (InvalidConfigurationException ex) { Console.WriteLine("Expected exception: {0}", ex.Message); } finally { Directory.Delete(outputDir, true); File.Delete(configFileName); } }
public async Task Search(string term) { var results = await repositories.SearchAsync(term); Results.Clear(); Results.AddRange(results.Select(r => new RepositoryListViewModel(r))); }
public async Task LoadMoreData() { var ids = QueryResult.Result.Skip(Results?.Count ?? 0).Take(10).ToList(); if (IsFetching || ids.Count == 0) { return; } IsFetching = true; var getResult = await tradeSearchService.GetResults(QueryResult.Id, ids); IsFetching = false; if (getResult.Result.Any()) { Results.AddRange(getResult.Result.Select(result => new PriceItem(result) { ImageUrl = new Uri( languageProvider.Language.PoeCdnBaseUrl, staticDataService.GetImage(result.Listing.Price.Currency) ).AbsoluteUri, })); } UpdateCountString(); }
public PagedResult(IEnumerable <T> results) { if (null != results) { Results.AddRange(results); } }
protected override Task <bool> SearchPage(object searchString, ulong offset, int requestId) { var tcs = new TaskCompletionSource <bool>(); SearchSymbolsResponse.BeginSearchSymbols( AccountManager.GetAuthInfo, async response => { SearchSymbolsResponse.EndSearchSymbols(response); var res = response.AsyncState as SearchSymbolsResponse; if (res.Symbols.Count == 0) { tcs.SetResult(false); } else { Results.AddRange(res.Symbols); await Task.Delay(TimeSpan.FromMilliseconds(50)); tcs.SetResult(true); } }, requestId, searchString as string, offset); return(tcs.Task); }
public PagedResult(IEnumerable <T> results, PaginationDetails paginationDetails) { if (null != results) { Results.AddRange(results); } PaginationDetails = paginationDetails; }
public void AddResult(List <Trade> result) { lock (Results) { Results.AddRange(result); } _testResultsUpdated.OnNext(result); }
public void SortAthletesSeasonBest(string season) { var keys = Results.Keys.OrderBy(athlete => athlete.BestMarkOfSeasonEvent(this, season)).ToList(); var newDict = new Dictionary <Athlete, Mark>(); keys.ForEach(key => newDict.Add(key, Results[key])); Results.Clear(); Results.AddRange(newDict); }
public void EverythingSimulationTest() { Stream everythingConfigStream = Assembly.GetExecutingAssembly().GetManifestResourceStream( "RemoteInstallUnitTests.TestConfigs.Everything.config"); string configFileName = Path.GetTempFileName(); using (StreamReader everythingConfigReader = new StreamReader(everythingConfigStream)) { File.WriteAllText(configFileName, everythingConfigReader.ReadToEnd()); } Stream everythingXmlStream = Assembly.GetExecutingAssembly().GetManifestResourceStream( "RemoteInstallUnitTests.TestConfigs.EverythingTask.xml"); using (StreamReader everythingXmlReader = new StreamReader(everythingXmlStream)) { File.WriteAllText(Path.Combine(Path.GetDirectoryName(configFileName), "EverythingTask.xml"), everythingXmlReader.ReadToEnd()); } string outputDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(outputDir); NameValueCollection vars = new NameValueCollection(); vars["root"] = @"..\..\..\.."; Driver driver = new Driver( outputDir, true, configFileName, vars, 1); // save results Results results = new Results(); results.AddRange(driver.Run()); string xmlFileName = Path.Combine(outputDir, "Results.xml"); new ResultCollectionXmlWriter().Write(results, xmlFileName); // make sure results is a valid xml document with a number of results XmlDocument xmlResults = new XmlDocument(); xmlResults.Load(xmlFileName); Assert.AreEqual(1, xmlResults.SelectNodes("/remoteinstallresultsgroups").Count); // reload the xml results Results resultsCopy = new Results(); resultsCopy.Load(xmlResults); Assert.AreEqual(1, resultsCopy.GetXml().SelectNodes("/remoteinstallresultsgroups").Count); Directory.Delete(outputDir, true); File.Delete(configFileName); }
/// <summary> /// 校验DataSource /// </summary> /// <param name="ds"></param> /// <returns></returns> private void ValidateDataSource(DataSource ds) { int pagemode = 0; Int32.TryParse(ds.PageMode, out pagemode); if (pagemode == 0) { Results.AddRange(AnalysisSql(ds.Sql, ds.Entity, ds.KeyName, pagemode, ds.Order)); } }
/// <summary> /// Use the useragent to determine the closest matching device /// from the handlers provided. /// </summary> /// <param name="userAgent">Useragent to be found.</param> /// <param name="handlers">Handlers capable of finding devices for the request.</param> /// <returns>The closest matching device or null if one can't be found.</returns> private static DeviceInfo GetDeviceInfo(string userAgent, Handler[] handlers) { DeviceInfo device = null; Results results = new Results(); #if VER4 foreach (Results temp in handlers.Select(t => t.Match(userAgent)).Where(temp => temp != null)) { results.AddRange(temp); } #elif VER2 for (int i = 0; i < handlers.Length; i++) { // Find the closest matching devices. Results temp = handlers[i].Match(userAgent); // If some results have been found. if (temp != null) { // Combine the results with results from previous // handlers. results.AddRange(temp); } } #endif if (results.Count == 1) { // Use the only result provided. device = results[0].Device; } else if (results.Count > 1) { // Uses the matcher to narrow down the results. device = Matcher.Match(userAgent, results); } if (device == null) { // No device was found so use the default device for the first // handler provided. device = handlers[0].DefaultDevice; } return(device); }
/// <summary> /// Returns all the devices that match the UA prof provided. /// </summary> /// <param name="uaprof">UA prof to search for.</param> /// <returns>Results containing all the matching devices.</returns> internal Results GetResultsFromUAProf(string uaprof) { DeviceInfo[] devices = GetDeviceInfo(_uaprofs, uaprof); if (devices != null && devices.Length > 0) { // Add the devices to the list of results and return. Results results = new Results(); results.AddRange(devices); return(results); } return(null); }
private void ExecQAction(PagingArgs page) { ExecQModel.FilterBaseFieldsSrc();//这里是为了执行查询前,删除由于主表、关联表改变导致的垃圾数据 Results.Clear(); //1、转换QueryModel QueryModel qModel = null; bool success = ParseQueryModel(out qModel); if (success == false) { return; } //2、查询条件展示 //3、过滤条件展示 //4、查询结果DataGrid动态列 BuildDataGridCols(); //5、分页 qModel.Page = new PageQuery { pageIndex = page.PageIndex, pageSize = page.PageSize }; //6、执行查询,返回结果,绑定Results var url = ApiUtils.GetApiUrl(ApiKeys.Cq_ExecQuery); var rst = HttpUtils.PostResult(url, qModel, ClientContext.Token); if (rst.code != ResultCode.Success) { MessageWindow.ShowMsg(MessageType.Error, OperationDesc.Cq_ExecQuery, rst.msg); return; } if (rst.data != null && rst.data.total != null) { page.RecordsCount = (int)rst.data.total; if (page.RecordsCount == 0) { page.PageCount = 0; page.PageIndex = 1; return; } page.PageCount = Convert.ToInt32(Math.Ceiling(page.RecordsCount * 1.0 / page.PageSize)); var rows = JsonConvert.DeserializeObject <IEnumerable <dynamic> >(((JArray)rst.data.rows).ToString()); if (rows.IsNotEmpty()) { Results.AddRange(rows); } //设置行号 DgResults.LoadingRow -= SetDgRowNumber; DgResults.LoadingRow += SetDgRowNumber; } }
public void EverythingSimulationTest() { Stream everythingConfigStream = Assembly.GetExecutingAssembly().GetManifestResourceStream( "RemoteInstallUnitTests.TestConfigs.Everything.config"); string configFileName = Path.GetTempFileName(); using (StreamReader everythingConfigReader = new StreamReader(everythingConfigStream)) { File.WriteAllText(configFileName, everythingConfigReader.ReadToEnd()); } Stream everythingXmlStream = Assembly.GetExecutingAssembly().GetManifestResourceStream( "RemoteInstallUnitTests.TestConfigs.EverythingTask.xml"); using (StreamReader everythingXmlReader = new StreamReader(everythingXmlStream)) { File.WriteAllText(Path.Combine(Path.GetDirectoryName(configFileName), "EverythingTask.xml"), everythingXmlReader.ReadToEnd()); } string outputDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(outputDir); NameValueCollection vars = new NameValueCollection(); vars["root"] = @"..\..\..\.."; Driver driver = new Driver( outputDir, true, configFileName, vars, 1); // save results Results results = new Results(); results.AddRange(driver.Run()); string xmlFileName = Path.Combine(outputDir, "Results.xml"); new ResultCollectionXmlWriter().Write(results, xmlFileName); // make sure results is a valid xml document with a number of results XmlDocument xmlResults = new XmlDocument(); xmlResults.Load(xmlFileName); Assert.AreEqual(1, xmlResults.SelectNodes("/remoteinstallresultsgroups").Count); // reload the xml results Results resultsCopy = new Results(); resultsCopy.Load(xmlResults); Assert.AreEqual(1, resultsCopy.GetXml().SelectNodes("/remoteinstallresultsgroups").Count); Directory.Delete(outputDir, true); File.Delete(configFileName); }
public override void Exec() { try { UIHierarchy solExplorer = this.ApplicationObject.ToolWindows.SolutionExplorer; if (((System.Array)solExplorer.SelectedItems).Length != 1) { return; } UIHierarchyItem hierItem = ((UIHierarchyItem)((System.Array)solExplorer.SelectedItems).GetValue(0)); ProjectItem pi = (ProjectItem)hierItem.Object; Window w = pi.Open(BIDSViewKinds.Designer); //opens the designer w.Activate(); IDesignerHost designer = w.Object as IDesignerHost; if (designer == null) { return; } EditorWindow win = (EditorWindow)designer.GetService(typeof(Microsoft.DataWarehouse.ComponentModel.IComponentNavigator)); Package package = win.PropertiesLinkComponent as Package; if (package == null) { return; } PackageHelper.SetTargetServerVersion(package); //set the TargetServerVersion variable so that we can retrieve it later Results results = new Results(); foreach (DesignPractice practice in _practices) { if (!practice.Enabled) { continue; } practice.Check(package, pi); results.AddRange(practice.Results); } AddErrorsToVSErrorList(w, results); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace); } }
/// <summary> /// Add new results to ResultCollection /// </summary> public void AddResults(List <Result> newRawResults, CancellationToken ct) { if (newRawResults == null) { throw new ArgumentNullException(nameof(newRawResults)); } List <ResultViewModel> newResults = new List <ResultViewModel>(newRawResults.Count); foreach (Result r in newRawResults) { newResults.Add(new ResultViewModel(r)); ct.ThrowIfCancellationRequested(); } Results.AddRange(newResults); }
public void DrawRange(object sender, MouseButtonEventArgs e) { if (contextMenu == null) { contextMenu = new ContextMenu(); contextMenu.Closed += ContextMenu_Closed; contextMenu.Style = (System.Windows.Style)StaticConstant.mw.Resources["myContextMenu"]; RunCombo.ContextMenu = contextMenu; } string[] strs = RunCombo.Text.Split(','); Results.Clear(); Results.AddRange(strs); contextMenu.Items.Clear(); List <string> fileNames = Business.FileBusiness.CreateInstance().GetFilesName(StaticConstant.mw.LastProjectPath + @"\Play", new List <string>() { ".lightPage" }); foreach (var item in fileNames) { MenuItem file = new MenuItem { Header = item }; if (Results.Contains(item)) { file.Icon = ResourcesUtils.Resources2BitMap("check.png"); } else { file.Icon = null; } file.Click += MenuItemList_Click; contextMenu.Items.Add(file); } needClose = true; contextMenu.IsOpen = true; }
private void TextBoxBase_OnTextChanged(object sender, TextChangedEventArgs e) { var q = (Query.Text ?? string.Empty).ToUpper(); var records = DataBase.Cities .Where(x => x.Name.ToUpper().Contains(q) || x.Country.ToUpper().Contains(q)) .OrderByDescending(x => x.Population) .Take(15) .ToArray(); Results.Clear(); Results.AddRange(records); Labels.Clear(); foreach (var record in records) { Labels.Add(record.Name); } }
private void product_searchtxt_TextChanged(object sender, TextChangedEventArgs e) { var q = (product_searchtxt.Text ?? string.Empty).ToUpper(); var records = Db .Where(x => x.Name.ToUpper().Contains(q) || x.Country.ToUpper().Contains(q)) .OrderByDescending(x => x.Population) .Take(15) .ToArray(); Results.Clear(); Results.AddRange(records); Labels.Clear(); foreach (var record in records) { Labels.Add(record.Name); } }
/// <summary> /// Return true when this aggregate has all the required items. /// </summary> public bool Push(IEnumerable <long> results) { // Remove any duplicates results = results.Where(i => !Results.Contains(i)); // Short stop; if we have too many items return early var remainingItemsToConsume = Limit - Results.Count; if (remainingItemsToConsume <= 0) { return(true); } // If we have an offset, the offset is reduced by each result set we've successfully skipped over. var remainingItemsToSkip = Offset - Skipped; var allItems = results.Take(remainingItemsToSkip + remainingItemsToConsume + 1).ToArray(); // If we only skip this entire result set, do that and update the counts var itemsSkipped = allItems.Length >= remainingItemsToSkip ? remainingItemsToSkip : allItems.Length; Skipped += itemsSkipped; // This is now the left over of items we can actually consume var consumableItems = allItems.Skip(itemsSkipped).ToArray(); // Take as many items from the consumables as we can var consumed = consumableItems.Take(remainingItemsToConsume).ToArray(); // Update lists if (consumed.Length > 0) { Results.AddRange(consumed); } // Were there extra items we discarded? if (consumableItems.Length > consumed.Length) { TooManyResults = true; } return(Results.Count >= Limit); }
private void textBox1_TextChanged(object sender, EventArgs e) { var newValue = ((TextBox)sender).Text ?? string.Empty; newValue = newValue.ToUpper(); var records = PopulationCountryData.Countries .Where(x => x.Name.ToUpper().Contains(newValue)) .OrderByDescending(x => x.CountryPopulation) .Take(15) .ToArray(); Results.Clear(); Results.AddRange(records); Labels.Clear(); foreach (var record in records) { Labels.Add(record.Name); } }
private async Task Execute() { T ruleResult = await RuleAction(); if (ruleResult != null) { Results.Add(ruleResult); } if (SubRule != null) { var subRuleResult = await SubRule.GetResultList(); Results.AddRange(subRuleResult); } if (_next != null) { Results.AddRange(await _next.GetResultList()); } }
public void SnapshotsWithParametersTest() { Stream configStream = Assembly.GetExecutingAssembly().GetManifestResourceStream( "RemoteInstallUnitTests.TestConfigs.SnapshotWithParameters.config"); string configFileName = Path.GetTempFileName(); using (StreamReader sr = new StreamReader(configStream)) { File.WriteAllText(configFileName, sr.ReadToEnd()); } string outputDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(outputDir); try { Driver driver = new Driver(outputDir, true, configFileName, null, 0); Results results = new Results(); results.AddRange(driver.Run()); // four individual results Assert.AreEqual(4, results.Count); foreach (ResultsGroup group in results) { Console.WriteLine("{0}: {1}", group.Vm, group.Snapshot); foreach (Result result in group) { // installer name is defined as name="@{snapshot.installargs}" // and each installargs is vm.snapshot Assert.AreEqual(string.Format("{0}.{1}", group.Vm, group.Snapshot), result.InstallerName); } } } finally { Directory.Delete(outputDir, true); File.Delete(configFileName); } }
private void PerformSearch() { Results.ClearEx(); var categories = CategoryOptionsCBL.GetSelectedItems().OfType <FileCategory>().ToList(); var searchGames = new List <string>(); if (SearchME1) { searchGames.Add(@"masseffect"); } if (SearchME2) { searchGames.Add(@"masseffect2"); } if (SearchME3) { searchGames.Add(@"masseffect3"); } QueryInProgress = true; Task.Run(() => { try { foreach (var domain in searchGames) { var db = LoadedDatabases[domain]; // Check if the name exists in filenames. If it doesn't, it will never find it #if DEBUG /* * var ignoredItems = new List<string>() * { * @"DLC_MOD_FMRM_Patches", * @"DLC_MOD_FJRM_Patches", * @"DLC_ASH_MiniSkirt_Mods", * @"DLC_Explorer", * @"DLC_LIA_RA4_MeshOnly", * @"DLC_ASH_Shorts_Mod", * @"DLC_ASH_Alt_Mods", * @"DLC_ASH_Socks_Mod", * @"DLC_ASH_Topless_Mod", * @"DLC_GAR_FRM_Altered_Face_Legs_Mod", * @"DLC_GAR_GFC_Altered_Face_Legs_Mod", * @"DLC_LIA_NKDSlippers_Mod", * @"DLC_LIA_NKDSnickers_Mod", * @"DLC_GAR_GFC_New_Version", * @"DLC_GAR_GFC_Old_Version", * @"DLC_GAR_FRM_Textures", * @"DLC_MIR_Shorts_Mod", * @"DLC_MOD_IT_RUS", * * }; * var dlcNames = db.NameTable.Values.Where(x => !ignoredItems.Contains(x) && x.StartsWith(@"DLC_") && Path.GetExtension(x) == string.Empty && !x.Contains(" ") && ThirdPartyServices.GetThirdPartyModInfo(x, MEGame.ME3) == null).Select(x => x.Trim()).Distinct().ToList(); * var xx = new List<string>(); * foreach (var i in db.FileInstances.Values) * { * foreach (var f in i) * { * if (f.ParentPathID > 0) * { * var path = db.Paths[f.ParentPathID].GetFullPath(db); * if (path.ContainsAny(dlcNames, StringComparison.Ordinal)) * { * var finfo = $@"https://nexusmods.com/masseffect/mods/{f.ModID}"; * xx.Add(db.NameTable[db.ModFileInfos[f.FileID].NameID] + " " + finfo); * } * * } * } * } * File.WriteAllLines(@"D:\dlcNames.txt", dlcNames); * File.WriteAllLines(@"D:\mods.txt", xx);*/ #endif var match = db.NameTable.FirstOrDefault(x => x.Value.Equals(SearchTerm, StringComparison.InvariantCultureIgnoreCase)); if (match.Key != 0) { // Found var instances = db.FileInstances[match.Key].Where(x => categories.Contains(db.ModFileInfos[x.FileID].Category)); //Application.Current.Dispatcher.Invoke(() => //{ Results.AddRange(instances.Select(x => new SearchedItemResult() { Instance = x, Domain = domain, Filename = db.NameTable[x.FilenameId], AssociatedDB = db })); //}); } } StatusText = M3L.GetString(M3L.string_interp_resultsCount, Results.Count); QueryInProgress = false; } catch (Exception e) { Log.Error($@"Could not perform search: {e.Message}"); QueryInProgress = false; } }); }
public void NothingToDoTest() { Stream configStream = Assembly.GetExecutingAssembly().GetManifestResourceStream( "RemoteInstallUnitTests.TestConfigs.NothingToDo.config"); string configFileName = Path.GetTempFileName(); using (StreamReader sr = new StreamReader(configStream)) { File.WriteAllText(configFileName, sr.ReadToEnd()); } string outputDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(outputDir); try { Driver driver = new Driver(outputDir, true, configFileName, null, 0); Results results = new Results(); results.AddRange(driver.Run()); Assert.Fail("Expected InvalidConfigurationException"); } catch (InvalidConfigurationException ex) { Console.WriteLine("Expected exception: {0}", ex.Message); } finally { Directory.Delete(outputDir, true); File.Delete(configFileName); } }
/// <summary> /// Use the HttpRequest fields to determine the closest matching device /// from the handlers provided. /// </summary> /// <param name="request">HttpRequest object.</param> /// <param name="handlers">Handlers capable of finding devices for the request.</param> /// <returns>The closest matching device or null if one can't be found.</returns> private static DeviceInfo GetDeviceInfo(HttpRequest request, Handler[] handlers) { DeviceInfo device = null; Results results = new Results(); #if VER4 foreach (Results temp in handlers.Select(t => t.Match(request)).Where(temp => temp != null)) { results.AddRange(temp); } #elif VER2 for (int i = 0; i < handlers.Length; i++) { // Find the closest matching devices. Results temp = handlers[i].Match(request); // If some results have been found. if (temp != null) // Combine the results with results from previous // handlers. results.AddRange(temp); } #endif if (results.Count == 1) { // Use the only result provided. device = results[0].Device; } else if (results.Count > 1) { // Uses the matcher to narrow down the results. device = Matcher.Match(GetUserAgent(request), results); } if (device == null) // No device was found so use the default device for the first // handler provided. device = handlers[0].DefaultDevice; return device; }
/// <summary> /// Returns all the devices that match the UA prof provided. /// </summary> /// <param name="uaprof">UA prof to search for.</param> /// <returns>Results containing all the matching devices.</returns> internal Results GetResultsFromUAProf(string uaprof) { BaseDeviceInfo[] devices = GetDeviceInfo(_uaprofs, uaprof); if (devices != null && devices.Length > 0) { // Add the devices to the list of results and return. Results results = new Results(); results.AddRange(devices); return results; } return null; }
public override void Process(HttpContext context) { string query = context.Request.QueryString["q"]; if (query == null) return; // Look for special searches if (SpecialSearches.ContainsKey(query)) { string path = SpecialSearches[query]; if (context.Request.QueryString["jsonp"] != null) { // TODO: Does this include the JSONP headers? SendFile(context, JsonConstants.MediaType, path); return; } if (Accepts(context, JsonConstants.MediaType)) { SendFile(context, JsonConstants.MediaType, path); return; } return; } // // Do the search // ResourceManager resourceManager = new ResourceManager(context.Server, context.Cache); SectorMap map = SectorMap.FromName(SectorMap.DefaultSetting, resourceManager); query = query.Replace('*', '%'); // Support * and % as wildcards query = query.Replace('?', '_'); // Support ? and _ as wildcards if (UWP_REGEXP.IsMatch(query)) query = "uwp:" + query; const int NUM_RESULTS = 160; var searchResults = SearchEngine.PerformSearch(query, resourceManager, SearchEngine.SearchResultsType.Default, NUM_RESULTS); Results resultsList = new Results(); if (searchResults != null) { resultsList.AddRange(searchResults .Select(loc => Results.LocationToSearchResult(map, resourceManager, loc)) .OfType<Results.SearchResultItem>() .OrderByDescending(item => item.Importance) .Take(NUM_RESULTS)); } SendResult(context, resultsList); }
private async Task ExecuteReport() { QueryErrorMessage.Value = ""; IsErrorVisible.Value = false; if (string.IsNullOrEmpty(GroupByField.Value)) { ApplicationModel.Current.Notifications.Add(new Notification("You must select a field to group by")); return; } if (ValueCalculations.Count == 0) { ApplicationModel.Current.Notifications.Add(new Notification("You must add at least one Value")); return; } var facets = new List <AggregationQuery>(); foreach (var value in ValueCalculations) { var facetForField = facets.FirstOrDefault(f => f.AggregationField == value.Field); if (facetForField != null) { facetForField.Aggregation |= value.SummaryMode; } else { facets.Add(new AggregationQuery { Name = GroupByField.Value, DisplayName = GroupByField.Value + "-" + value.Field, AggregationField = value.Field, Aggregation = value.SummaryMode }); } } ResultColumns = null; Results.Clear(); var cancelationTokenSource = new CancellationTokenSource(); var progressWindow = new ProgressWindow() { Title = "Preparing Report", IsIndeterminate = false, CanCancel = true }; progressWindow.Closed += delegate { cancelationTokenSource.Cancel(); }; progressWindow.Show(); var queryStartTime = DateTime.UtcNow.Ticks; try { var results = new List <KeyValuePair <string, FacetResult> >(); var hasMoreResults = true; var fetchedResults = 0; while (hasMoreResults) { var queryFacetsTask = DatabaseCommands.GetFacetsAsync(IndexName, new IndexQuery() { Query = FilterDoc.Text }, AggregationQuery.GetFacets(facets), fetchedResults, 256); await TaskEx.WhenAny( queryFacetsTask, TaskEx.Delay(int.MaxValue, cancelationTokenSource.Token)); if (cancelationTokenSource.IsCancellationRequested) { return; } var facetResults = await queryFacetsTask; results.AddRange(facetResults.Results); fetchedResults += facetResults.Results.Select(r => r.Value.Values.Count).Max(); var remainingResults = facetResults.Results.Select(r => r.Value.RemainingTermsCount).Max(); var totalResults = fetchedResults + remainingResults; progressWindow.Progress = (int)((fetchedResults / (double)totalResults) * 100); hasMoreResults = remainingResults > 0; } var rowsByKey = new Dictionary <string, ReportRow>(); var rows = new List <ReportRow>(); foreach (var facetResult in results) { var calculatedField = facetResult.Key.Split('-')[1]; foreach (var facetValue in facetResult.Value.Values) { ReportRow result; if (!rowsByKey.TryGetValue(facetValue.Range, out result)) { result = new ReportRow { Key = facetValue.Range }; rowsByKey.Add(result.Key, result); rows.Add(result); } foreach ( var valueCalculation in ValueCalculations.Where(v => v.Field == calculatedField)) { var value = facetValue.GetAggregation(valueCalculation.SummaryMode); if (value.HasValue) { result.Values.Add(valueCalculation.Header, facetValue.GetAggregation(valueCalculation.SummaryMode) ?? 0); } } } } var columns = new ColumnsModel(); columns.Columns.Add(new ColumnDefinition() { Header = "Key", Binding = "Key" }); columns.Columns.AddRange( ValueCalculations.Select( k => new ColumnDefinition() { Header = k.Header, Binding = "Values[" + k.Header + "]" })); Results.AddRange(rows); ResultColumns = columns; var queryEndTime = DateTime.UtcNow.Ticks; ExecutionElapsedTime.Value = new TimeSpan(queryEndTime - queryStartTime); } catch (AggregateException ex) { var badRequest = ex.ExtractSingleInnerException() as BadRequestException; if (badRequest != null) { QueryErrorMessage.Value = badRequest.Message; IsErrorVisible.Value = true; } else { throw; } } catch (TaskCanceledException) { } finally { // there's a bug in silverlight where if a ChildWindow gets closed too soon after it's opened, it leaves the UI // disabled; so delay closing the window by a few milliseconds TaskEx.Delay(TimeSpan.FromMilliseconds(350)) .ContinueOnSuccessInTheUIThread(progressWindow.Close); } }
public void SnapshotsWithParametersTest() { Stream configStream = Assembly.GetExecutingAssembly().GetManifestResourceStream( "RemoteInstallUnitTests.TestConfigs.SnapshotWithParameters.config"); string configFileName = Path.GetTempFileName(); using (StreamReader sr = new StreamReader(configStream)) { File.WriteAllText(configFileName, sr.ReadToEnd()); } string outputDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(outputDir); try { Driver driver = new Driver(outputDir, true, configFileName, null, 0); Results results = new Results(); results.AddRange(driver.Run()); // four individual results Assert.AreEqual(4, results.Count); foreach (ResultsGroup group in results) { Console.WriteLine("{0}: {1}", group.Vm, group.Snapshot); foreach(Result result in group) { // installer name is defined as name="@{snapshot.installargs}" // and each installargs is vm.snapshot Assert.AreEqual(string.Format("{0}.{1}", group.Vm, group.Snapshot), result.InstallerName); } } } finally { Directory.Delete(outputDir, true); File.Delete(configFileName); } }
public void SimulateAllMsiSequencesTest() { Stream sequencesConfigStream = Assembly.GetExecutingAssembly().GetManifestResourceStream( "RemoteInstallUnitTests.TestConfigs.MsiSequences.config"); string configFileName = Path.GetTempFileName(); using (StreamReader sequencesConfigReader = new StreamReader(sequencesConfigStream)) { File.WriteAllText(configFileName, sequencesConfigReader.ReadToEnd()); } string outputDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(outputDir); foreach (InstallersSequence sequence in Enum.GetValues(typeof(InstallersSequence))) { Console.WriteLine("Sequence: {0}", sequence); NameValueCollection vars = new NameValueCollection(); vars["root"] = @"..\..\..\.."; vars["sequence"] = sequence.ToString(); Driver driver = new Driver( outputDir, true, configFileName, vars, 1); Results results = new Results(); results.AddRange(driver.Run()); switch (sequence) { case InstallersSequence.clean: // a clean sequence is like 2 separate, clean installations Assert.AreEqual(2, results.Count); Assert.AreEqual(1, results[0].Count); Assert.AreEqual(1, results[1].Count); break; case InstallersSequence.alternate: case InstallersSequence.install: case InstallersSequence.uninstall: // two installers alternating with install+uninstall in the same run // or just install or uninstall Assert.AreEqual(1, results.Count); Assert.AreEqual(2, results[0].Count); break; default: // two installers split into install+uninstall in a sequence of 4 Assert.AreEqual(1, results.Count); Assert.AreEqual(4, results[0].Count); break; } } Directory.Delete(outputDir, true); File.Delete(configFileName); }
protected ArrayQueryBase(ArraySource source, LambdaExpression kernel) { Sources.Add(source); Kernel = kernel; Results.AddRange(GetTypes(kernel.ReturnType)); }
private void Page_Load(object sender, System.EventArgs e) { if (!ServiceConfiguration.CheckEnabled("search", Response)) { return; } string query = Request.QueryString["q"]; if (query == null) return; // Look for special searches var index = Array.FindIndex(SpecialSearchTerms, s => String.Compare(s, query, ignoreCase: true, culture: CultureInfo.InvariantCulture) == 0); if (index != -1) { if (Request.QueryString["jsonp"] != null) { // TODO: Does this include the JSONP headers? SendFile(JsonConstants.MediaType, SpecialSearchResultsJson[index]); return; } foreach (var type in AcceptTypes) { if (type == JsonConstants.MediaType) { SendFile(JsonConstants.MediaType, SpecialSearchResultsJson[index]); return; } if (type == MediaTypeNames.Text.Xml) { SendFile(MediaTypeNames.Text.Xml, SpecialSearchResultsXml[index]); return; } } SendFile(MediaTypeNames.Text.Xml, SpecialSearchResultsXml[index]); return; } // // Do the search // ResourceManager resourceManager = new ResourceManager(Server, Cache); SectorMap map = SectorMap.FromName(SectorMap.DefaultSetting, resourceManager); query = query.Replace('*', '%'); // Support * and % as wildcards query = query.Replace('?', '_'); // Support ? and _ as wildcards if (UWP_REGEXP.IsMatch(query)) { query = "uwp:" + query; } var searchResults = SearchEngine.PerformSearch(query, resourceManager, SearchEngine.SearchResultsType.Default, 160); Results resultsList = new Results(); if (searchResults != null) { resultsList.AddRange(searchResults .Select(loc => Results.LocationToSearchResult(map, resourceManager, loc)) .OfType<Results.SearchResultItem>()); } SendResult(resultsList); }
public override void Exec() { UIHierarchy solExplorer = this.ApplicationObject.ToolWindows.SolutionExplorer; if (((System.Array)solExplorer.SelectedItems).Length != 1) return; UIHierarchyItem hierItem = ((UIHierarchyItem)((System.Array)solExplorer.SelectedItems).GetValue(0)); ProjectItem pi = (ProjectItem)hierItem.Object; Window w = pi.Open(BIDSViewKinds.Designer); //opens the designer w.Activate(); IDesignerHost designer = w.Object as IDesignerHost; if (designer == null) return; EditorWindow win = (EditorWindow)designer.GetService(typeof(Microsoft.DataWarehouse.ComponentModel.IComponentNavigator)); Package package = win.PropertiesLinkComponent as Package; if (package == null) return; Results results = new Results(); foreach (DesignPractice practice in _practices) { if (!practice.Enabled) continue; practice.Check(package, pi); results.AddRange(practice.Results); } AddErrorsToVSErrorList(w, results); }
static int Main(string[] args) { //TODO: CruiseControl.Net interprets a return code of -1 as a timeout error ConsoleOutput.WriteLine("RemoteInstaller {0}: Product Test Driver", Assembly.GetExecutingAssembly().GetName().Version); ConsoleOutput.WriteLine(); InstallerArgs iArgs = new InstallerArgs(); if (!Parser.ParseArgumentsWithUsage(args, iArgs)) { return(-1); } Results results = new Results(); try { iArgs.Parse(); if (iArgs.verboseOutput) { ConsoleOutput.ShowExceptionStack = true; ConsoleOutput.WriteLine("Parsed command line arguments: "); foreach (string arg in args) { ConsoleOutput.WriteLine(" {0}", arg); } } Driver driver = new Driver( iArgs.outputDir, iArgs.simulationOnly, iArgs.configFile, iArgs.VariablesCollection, iArgs.pipelineCount); ConsoleOutput.WriteLine("Results will be written to '{0}'", Path.GetFullPath(iArgs.outputDir)); Directory.CreateDirectory(iArgs.outputDir); string outputXmlFile = Path.Combine(iArgs.outputDir, iArgs.outputXml); if (iArgs.appendOutput && !string.IsNullOrEmpty(iArgs.outputXml) && File.Exists(outputXmlFile)) { ConsoleOutput.WriteLine("Loading '{0}'", outputXmlFile); results.Load(outputXmlFile); } else if (!string.IsNullOrEmpty(iArgs.outputXml) && File.Exists(outputXmlFile)) { File.Delete(outputXmlFile); } results.AddRange(driver.Run()); return(results.Success ? 0 : -1); } catch (Exception ex) { ConsoleOutput.WriteLine(ex); return(-2); } finally { if (!string.IsNullOrEmpty(iArgs.outputXml)) { string xmlFileName = Path.Combine(iArgs.outputDir, iArgs.outputXml); ConsoleOutput.WriteLine("Writing {0}", xmlFileName); new ResultCollectionXmlWriter().Write(results, xmlFileName); } if (!string.IsNullOrEmpty(iArgs.outputHtml)) { string htmlFileName = Path.Combine(iArgs.outputDir, iArgs.outputHtml); ConsoleOutput.WriteLine("Writing {0}", htmlFileName); new ResultCollectionHtmlWriter().Write(results, htmlFileName); } } }