public IdenticaClient(string username, string password) { Statuses = new Statuses(this); Account = new Account(this); DirectMessages = new DirectMessages(this); Favourites = new Favourites(this); Block = new Block(this); Friendships = new Friendship(this); Lists = new List(this); Search = new Search(this); Users = new Users(this); FriendsAndFollowers = new FriendsAndFollowers(this); Credentials = new BasicAuthCredentials { Username = username, Password = password }; Client = new RestClient { Authority = "http://identi.ca/api", }; Authority = "http://identi.ca/api"; Encode = false; }
static void Main(string[] args) { var mySearch = new Search(); List<string> myList= new List<string>(); myList=mySearch.SplitString("din mor er en mand"); foreach (string s in myList) { Console.WriteLine(s); } var component1 = new Component(); component1._name = "myComponent"; var component2 = new Component(); component2._name = "myComponent"; var myComponentsList=new List<Component>(); myComponentsList.Add(component1); myComponentsList.Add(component2); var myComponents = new Components(myComponentsList); Console.WriteLine(myComponents.GetAvaiableQuantity("myComponent")); }
/// <summary> /// base constructor /// </summary> /// <param name="v"></param> public VM(MainPage v) { view = v; byPoint = true; _searchObj = new Search(); _rad = view._changedRadius; }
public OnboardingViewModel( CommuterApplication application, Search.SearchService search) { _application = application; _search = search; }
/// <summary> /// /// </summary> /// <param name="reload">是否是重新加载</param> /// <returns></returns> private async Task LoadData(bool reload = false) { this.IsBusy = true; var method = new Search() { Page = reload ? 1 : this.Page }; var datas = await ApiClient.Execute(method); if (!method.HasError && datas.Count() > 0) { if (reload) { this.Datas.Clear(); } if (Device.OS == TargetPlatform.Windows) { foreach (var d in datas) { this.Datas.Add(new SearchedItemViewModel(d, this.NS)); } } else this.Datas.AddRange(datas.Select(d => new SearchedItemViewModel(d, this.NS) )); //this.NotifyOfPropertyChange(() => this.Datas); this.Page++; } this.IsBusy = false; }
public ActionResult Index(Search<Product> search) { if (!ModelState.IsValid) return View (search); var qry = from x in Product.Queryable orderby x.Name select x; if (!string.IsNullOrEmpty (search.Pattern)) { qry = from x in Product.Queryable where x.Name.Contains (search.Pattern) || x.Code.Contains (search.Pattern) || x.Model.Contains (search.Pattern) || x.SKU.Contains (search.Pattern) || x.Brand.Contains (search.Pattern) orderby x.Name select x; } search.Total = qry.Count (); search.Results = qry.Skip (search.Offset).Take (search.Limit).ToList (); ViewBag.PriceLists = PriceList.Queryable.ToList (); return PartialView ("_Index", search); }
public SearchAgent(Problem p, Search search) { actionList = search.search(p); actionIterator = actionList.GetEnumerator(); searchMetrics = search.getMetrics(); }
public IEnumerable<SearchResultView> Post(Search user) { IQueryable<LmsUser> userList = _opp.QueryForSearch(); if (user.FirstName != null) { userList = userList.Where(x => x.Id != null && x.FirstName.StartsWith(user.FirstName)); } if (user.LastName != null) { userList = userList.Where(x => x.Id != null && x.LastName.StartsWith(user.LastName)); } if (user.Email != null) { userList = userList.Where(x => x.Id != null && x.Email.StartsWith(user.Email)); } if (user.Role != "null") { userList = userList.Where(x => x.SuggestedRole == user.Role && x.Id != null); } var matchToSearch = from x in userList select new SearchResultView{FirstName = x.FirstName,LastName = x.LastName,Email = x.Email,Role = x.SuggestedRole,Id = x.UserId }; return matchToSearch; }
public static Search resetInstance() { if (instance != null) instance = null; //Garbage collection return getInstance(); }
public TwitterClient(IRestClient client, string consumerKey, string consumerSecret, string callback) : base(client) { Encode = true; Statuses = new Statuses(this); Account = new Account(this); DirectMessages = new DirectMessages(this); Favourites = new Favourites(this); Block = new Block(this); Friendships = new Friendship(this); Lists = new List(this); Search = new Search(this); Users = new Users(this); FriendsAndFollowers = new FriendsAndFollowers(this); OAuthBase = "https://api.twitter.com/oauth/"; TokenRequestUrl = "request_token"; TokenAuthUrl = "authorize"; TokenAccessUrl = "access_token"; Authority = "https://api.twitter.com/"; Version = "1"; #if !SILVERLIGHT ServicePointManager.Expect100Continue = false; #endif Credentials = new OAuthCredentials { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret, }; if (!string.IsNullOrEmpty(callback)) ((OAuthCredentials)Credentials).CallbackUrl = callback; }
public ActionResult SearchLocation(Search search, float lat, float lng, float? miles) { if (miles.HasValue) return (this.NewtonJson(this.searchAdapter.SearchLocation(lat, lng, miles.Value))); else return (this.NewtonJson(this.searchAdapter.SearchLocation(lat, lng))); }
private Search OrgViewSearch(Search search) { ObjectTypes types; if (search == null || search.Query == null || search.Query.QueryScope == null) { types = IncludeFolders ? ObjectTypes.AllIncFolders : ObjectTypes.AllExcFolders; } else { types = IncludeFolders ? search.Query.QueryScope.ObjectTypes : (search.Query.QueryScope.ObjectTypes & ~ObjectTypes.Folder); } QueryScope scope = new QueryScope(types); QueryFilter filter; if (search == null || search.Query == null || search.Query.QueryFilter == null) filter = Query; else if (Query == null) filter = search.Query.QueryFilter; else filter = new GroupQuery(new[] { search.Query.QueryFilter, Query }, GroupQuery.GroupQueryType.And); return new Search(new Query(scope, filter), Grouping, false, "", null, null, new Sort[] { }); }
public MapAgent(Map map, EnvironmentViewNotifier notifier, Search search, int maxGoalsToFormulate) : base ( maxGoalsToFormulate) { this.map = map; this.notifier = notifier; this._search = search; }
// Use this for initialization void Start () { int[,] map = new int[5, 5]{ {0,1,0,0,0}, {0,1,0,0,0}, {0,1,0,0,0}, {0,1,0,0,0}, {0,0,0,0,0} }; var graph = new Graph(map); Search search = new Search(graph); search.Start (graph.nodes[0], graph.nodes[8]); while(!search.finished) { search.Step(); } print ("Search done. Path length " + search.path.Count+ " iteration " + search.iterations); ResetMapGroup (graph); foreach (var node in search.path) { GetImage(node.label).color = Color.red; } }
void Next() { if(myLastSearch.mySearchee) { myPreviousBeings.Add(myLastSearch); } --mySearcheesToGo; myState = ConveyorBeltStates.Moving; myLastSearch = myCurrentSearch; if(mySearcheesToGo == 0) { if(myState != ConveyorBeltStates.Done) { AssessSession(false); } } else { myCurrentSearch = new Search(); myCurrentSearch.mySearchee = Helper.GetNewBeing(); myCurrentSearch.mySearchee.transform.position = new Vector3(15, 0, 0); myState = ConveyorBeltStates.Moving; } }
public void InvalidCollectionReturnsError() { //try //{ // ClearContainer(); // var container = Startup.Container; // container.Register<IEndPointConfiguration>(c => new TestEndPointConfiguration()); // ServiceLocator.SetLocatorProvider(() => container); //} //catch (Exception) //{ // // Ignore //} try { var s = new Search<TestDocument>(new Settings("a-collection-that-does-not-exist")); var results = s.Execute("crownpeak"); Assert.IsTrue(results.Count == 10, "Expected 10 results, got " + results.Count); } catch (Exception ex) { throw ex; } finally { // Restore the state SetupSearch(); } }
public ParentMenuItemFeatureCommand(IMainWindow mainWindow, IEnumerable<SelectedItem> selection, ParentMenuItemFeature owner, Search search) : base(mainWindow, selection) { Util.ThrowIfParameterNull(owner, "owner"); _owner = owner; _search = search; }
public List<SearchResult> GetClientCasesByPhysicianId(Search search) { int physicianId = (int)search.SearchParameters[0]; var query = from ao in this.m_DataContext.GetTable<Domain.AccessionOrder>() from pso in ao.PanelSetOrders where ao.PhysicianId == physicianId orderby ao.MasterAccessionNo descending select new SearchResult { MasterAccessionNo = ao.MasterAccessionNo, ReportNo = pso.ReportNo, AccessionDate = ao.AccessionDate, PatientName = ao.PFirstName + ' ' + ao.PLastName, PCAN = ao.PCAN, PSex = ao.PSex, PBirthdate = ao.PBirthdate, PSSN = ao.PSSN, CollectionDate = ao.CollectionDate, ClientId = ao.ClientId, ClientName = ao.ClientName, PhysicianName = ao.PhysicianName, PhysicianId = ao.PhysicianId, FinalTime = pso.FinalTime, PanelSetName = pso.PanelSetName }; return query.Take<SearchResult>(100).ToList<SearchResult>(); }
public void Campaign() { var criteria = new[] { new CampaignSearchCriteria { InternalName = CampaignSearchCriteria.DonatedToCampaign, SearchOperator = SearchOperator.StartsWith, Type = SearchFieldType.String, Value = "Christmas" } }; var expr = new Search().CompileCampaignCriteria(criteria, null); var reference = expr.LeftOperand as ObjectReference; Assert.IsNotNull(reference); Assert.AreEqual("Name", reference.GetName()); Assert.AreEqual(SimpleExpressionType.Function, expr.Type); var function = expr.RightOperand as SimpleFunction; Assert.IsNotNull(function); Assert.AreEqual("like", function.Name.ToLowerInvariant()); Assert.AreEqual(1, function.Args.Count); Assert.AreEqual("Christmas%", function.Args.First()); }
public static void changeSearch(Search search = null) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 3; j++) { if (search == Grid.searches[i, j]) { Grid.searches[i, j].active = true; Grid.searches[i, j].GetComponent<SpriteRenderer>().sprite = Grid.searches[i, j].activeTextures[searchIndices[i, j]]; searchRow = i; searchCol = j; setupColumns(); convoySearch(); targetsRolled = false; LoadTdcTargets(); } else { if (Grid.searches[i, j].active) { Grid.searches[i, j].active = false; Grid.searches[i, j].GetComponent<SpriteRenderer>().sprite = Grid.searches[i, j].dimTextures[searchIndices[i, j]]; } } } } }
public MatchyBackend.Search MapToService(Search search) { BrancheMapping brancheMapper = null; EducationMapper eduMapper = null; if(search.Branche != null) brancheMapper = new BrancheMapping(); if(search.Education != null) eduMapper = new EducationMapper(); MatchyBackend.Search result = new MatchyBackend.Search(); if (search != null) { return new MatchyBackend.Search() { SearchTerm = search.SearchTerm, Education = eduMapper != null ? eduMapper.MapToService(search.Education) : null, City = search.City, Hours = search.Hours, Branche = brancheMapper != null ? brancheMapper.mapToService(search.Branche) : null }; } else return result; }
private void considerLink(IDiagramLine l, IDiagramPort p, Search s, ArrayList items) { bool flag1 = (s & Search.NotSelf) == ((Search)0); if ((l.FromPort == p) && ((flag1 || (l.ToPort.DiagramShape == null)) || !l.ToPort.DiagramShape.IsChildOf(this))) { if ((s & Search.LinksOut) != ((Search)0)) { this.addItem(items, l); } if ((s & Search.NodesOut) != ((Search)0)) { this.addItem(items, l.ToNode); } } if ((l.ToPort == p) && ((flag1 || (l.FromPort.DiagramShape == null)) || !l.FromPort.DiagramShape.IsChildOf(this))) { if ((s & Search.LinksIn) != ((Search)0)) { this.addItem(items, l); } if ((s & Search.NodesIn) != ((Search)0)) { this.addItem(items, l.FromNode); } } }
public string CompareWithQrel(Search search) { int found = 0, diff = 0; string query = search.Query.OriginalQuery; string qrelResult = ""; if (Queries.ContainsKey(query)) { Qrel qrel = Queries[query]; foreach (QrelLine qrelLine in search.ResultList) { if (qrel.Lines.Contains(qrelLine)) { found += 1; } else { diff += 1; } } qrelResult = "Trouvé : " + found + "/" + qrel.Lines.Count + " - Résultats supplémentaires : " + diff; } else { qrelResult = "Pas de Qrel associée à ces critères"; } return "Total : " + search.ResultList.Count + " - " + qrelResult; }
public void SetUp() { twitterClient = Substitute.For<IBaseTwitterClient>(); searchClient = Substitute.For<IRestClient>(); search = new Search(twitterClient, s => searchClient); }
protected void btConfirm_Click(object sender, EventArgs e) { Admin admin = new Admin (); Search search = new Search(); TeacherInfo thisTeacher = new TeacherInfo(); thisTeacher.StrUserName=tbxUserName.Text; thisTeacher.StrTeacherName=tbxName.Text; thisTeacher.StrIdentityId=tbxIdentityNO.Text; MD5CryptoServiceProvider HashMD5 = new MD5CryptoServiceProvider(); thisTeacher.StrPassword=ASCIIEncoding.ASCII.GetString(HashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes("888888"))); string s = tbxUserName.Text; string last4userName = s.Substring(s.Length - 4, 4); string p = tbxIdentityNO.Text; string last4IdentityNO = p.Substring(p.Length - 4, 4); if (last4userName!=last4IdentityNO) { Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "<script>alert('请确认用户名末四位与身份证号末四位相同')</script>"); } //else if (thisTeacher.StrIdentityId==search.GetTeacherByUsername(s).StrIdentityId) else if (thisTeacher.StrIdentityId == search.GetTeacherByIdentityID(p).StrIdentityId)// 武剑洁修改,2009-9-11 { Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "<script>alert('身份证号重复,已存在该老师')</script>"); tbxIdentityNO.Text = ""; } else if (search.GetTeacherIdByUsername(thisTeacher.StrUserName) > 0)// 尚书修改,2012-8-5 { Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "<script>alert('该用户名已存在,请更换')</script>"); tbxUserName.Text = ""; } else if (search.GetTeacherIdByName(thisTeacher.StrTeacherName) > 0)// 武剑洁修改,2012-8-5 { Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "<script>alert('老师姓名重复,请修改姓名以区分两位老师')</script>"); tbxName.Text = ""; } else { if (admin.AddTeacher(thisTeacher)) { //Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", // "<script>alert('添加成功!')</script>"); // 武剑洁修改,添加页面跳转,2009-9-10 Response.Write("<script>alert('添加成功!');window.location='./Teacher_Manage.aspx'</script>"); } else { //Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", // "<script>alert('添加失败!')</script>"); // 武剑洁修改,添加页面跳转,2009-9-10 Response.Write("<script>alert('添加失败!');window.location='./Teacher_Manage.aspx'</script>"); } } }
public async Task<IHttpActionResult> SearchPerson(Search search) { var result = await _searchService.AdminContactPersonSearch(User, search); return Ok(new { data = result }); }
public MenuItemFeatureCommand(IMainWindow mainWindow, IEnumerable<SelectedItem> selection, MenuItemFeature menuItemFeature, Search search, PluginSerializationLevel serialization) : base(mainWindow, selection) { Util.ThrowIfParameterNull(menuItemFeature, "menuItemFeature"); _menuItemFeature = menuItemFeature; _search = search; _serialization = serialization; }
public static Search getInstance() { if (instance != null) return instance; instance = new Search(); return instance; }
public async Task<IHttpActionResult> SearchSite(Search search) { var result = await _searchService.AdminSiteSearch(User, search); return Ok(new { data = result }); }
public override void Init (bool white) { base.Init (white); searcher = new Search (); if (GameManager.instance.gameMode == GameManager.GameMode.Regular) { useBuiltinMoveDelay = false; } }
public void UserRatesMovie() { NLogger nLogger = new NLogger(); try { Menu menu = new Menu(); var userId = ""; int userIdInt = 0; System.Console.Write("Rate a Movie "); Console.ForegroundColor = ConsoleColor.Red; System.Console.WriteLine("Wizard"); Console.ForegroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Yellow; System.Console.Write("Step 1 of 4: Identify User?\t\t"); Console.ForegroundColor = ConsoleColor.White; System.Console.Write("What is your User Id?\t"); andAgain: userId = Console.ReadLine(); if (!Int32.TryParse(userId, out userIdInt)) { System.Console.Write("\t Entering the User's ID\t"); goto andAgain; } nLogger.nLog("User Id : " + userIdInt); using (var db = new MovieContext()) { int count = 0; var users = db.Users.Include(x => x.Occupation) .Where(x => x.Id == userIdInt).ToList(); foreach (var user in users) { if (user.Id == userIdInt) { count = 1; } System.Console.WriteLine($"Welcome user: ({user.Id}) Sex: {user.Gender} Age: {user.Age} Zip: {user.ZipCode} {user.Occupation.Name}"); File.WriteAllText(Path.Combine(Environment.CurrentDirectory, "rate.sav"), userId); } if (count == 0) { System.Console.WriteLine("User Not Found, Returning to Menu"); File.WriteAllText(Path.Combine(Environment.CurrentDirectory, "rate.sav"), "rate"); menu.menuSelect(); } Console.ForegroundColor = ConsoleColor.Yellow; System.Console.Write("Step 2 of 4: Search Movie\t\t"); Console.ForegroundColor = ConsoleColor.White; // System.Console.Write("Find the Movie to Rate. Hit any key\t"); // Console.ReadKey(); // System.Console.WriteLine(); Search search = new Search(); search.searchMovie(); } } catch (System.Exception) { System.Console.WriteLine("Problem with the Rating process, returning to Menu"); Menu menu = new Menu(); menu.menuSelect(); } }
/// <summary> /// EXISTS /// </summary> /// <param name="fromSection"></param> /// <returns></returns> public static WhereOperation Exists(Search fromSection) { return(new WhereOperation(string.Concat(" EXISTS (", fromSection.SqlString, ") "), fromSection.Parameters.ToArray())); }
public void BinarySearch_Method_Typed_With_Double_Works_Properly() { Assert.That( Search <double> .BinarySearch(TestDouble, -13.6), Is.EqualTo(1)); }
public void BinarySearch_Method_Typed_With_CustomType_Works_Properly() { Assert.That( Search <Person> .BinarySearch(TestCustom, new Person("Alex", 24)), Is.EqualTo(1)); }
public static Icons GetIconFor(Search search) { return(search.DefaultSearch ? Icons.DefaultSearch : Icons.Search); }
public void ShouldReturnCorrectIndexOnBinarySearchWhenItemInTheMiddleOfArray() { int[] array = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; Assert.AreEqual(3, Search.BinarySearch(array, 4)); }
internal static int SetupStatePos = 0; // *SetupState = StateRingBuf; /// Wait for a command from the user, parse this text string as an UCI command, /// and call the appropriate functions. Also intercepts EOF from stdin to ensure /// that we exit gracefully if the GUI dies unexpectedly. In addition to the UCI /// commands, the function also supports a few debug commands. internal static void uci_loop(string args) { for (int i = 0; i < 102; i++) { StateRingBuf[i] = new StateInfo(); } Position pos = new Position(StartFEN, false, Threads.main_thread()); // The root position string cmd, token = string.Empty; while (token != "quit") { if (args.Length > 0) { cmd = args; } else if (String.IsNullOrEmpty(cmd = Plug.ReadLine())) // Block here waiting for input { cmd = "quit"; } Stack <string> stack = Utils.CreateStack(cmd); token = stack.Pop(); if (token == "quit" || token == "stop") { Search.SignalsStop = true; Threads.wait_for_search_finished(); // Cannot quit while threads are running } else if (token == "ponderhit") { // The opponent has played the expected move. GUI sends "ponderhit" if // we were told to ponder on the same move the opponent has played. We // should continue searching but switching from pondering to normal search. Search.Limits.ponder = false; if (Search.SignalsStopOnPonderhit) { Search.SignalsStop = true; Threads.main_thread().wake_up(); // Could be sleeping } } else if (token == "go") { go(pos, stack); } else if (token == "ucinewgame") { /* Avoid returning "Unknown command" */ } else if (token == "isready") { Plug.Write("readyok"); Plug.Write(Constants.endl); } else if (token == "position") { set_position(pos, stack); } else if (token == "setoption") { set_option(stack); } else if (token == "validmoves") { Search.validmoves(pos, stack); } else if (token == "d") { pos.print(0); } else if (token == "flip") { pos.flip(); } else if (token == "eval") { Plug.Write(Evaluate.trace(pos)); Plug.Write(Constants.endl); } else if (token == "bench") { Benchmark.benchmark(pos, stack); } else if (token == "key") { Plug.Write("key: "); Plug.Write(String.Format("{0:X}", pos.key())); Plug.Write("\nmaterial key: "); Plug.Write(pos.material_key().ToString()); Plug.Write("\npawn key: "); Plug.Write(pos.pawn_key().ToString()); Plug.Write(Constants.endl); } else if (token == "uci") { Plug.Write("id name "); Plug.Write(Utils.engine_info(true)); Plug.Write("\n"); Plug.Write(OptionMap.Instance.ToString()); Plug.Write("\nuciok"); Plug.Write(Constants.endl); } else if (token == "perft") { token = stack.Pop(); // Read depth Stack <string> ss = Utils.CreateStack( string.Format("{0} {1} {2} current perft", OptionMap.Instance["Hash"].v, OptionMap.Instance["Threads"].v, token) ); Benchmark.benchmark(pos, ss); } else { Plug.Write("Unknown command: "); Plug.Write(cmd); Plug.Write(Constants.endl); } if (args.Length > 0) // Command line arguments have one-shot behaviour { Threads.wait_for_search_finished(); break; } } }
public void Searching(ActionExecutionContext context) { var keyArgs = context.EventArgs as KeyEventArgs; if (string.IsNullOrEmpty(Search) || Search == "Keresés...") { SearchableDolgozo = new BindableCollection <Dolgozo>(Dolgozok); return; } if (keyArgs != null) { SearchableDolgozo = new BindableCollection <Dolgozo>(); foreach (Dolgozo item in Dolgozok.Where(p => p.NameWithGroupName.ToLower().Contains(Search.ToLower())).ToArray()) { SearchableDolgozo.Add(item); } } }
public void SearchAudioFiles(WebData webData, int page = 0, long artistID = 0, long albumID = 0, long categoryID = 0, long genreID = 0, long tagID = 0, string filter = null, string title = null, string album = null, string artist = null, string genre = null, string tag = null) { if (title == null) { title = filter; } Search search = Search.None; if (artistID > 0) { if (artist != null) { throw new WebServerException(WebError.InvalidParameters, 0, "Cannot use artist search and artistID at the same time!"); } search &= Search.FieldEquals(nameof(MDBAudioFile.AlbumArtistID), artistID) | Search.FieldEquals(nameof(MDBAudioFile.SongArtistID), artistID); } else if (artist != null) { var ids = mdb.Artists.FindRows(Search.FieldLike(nameof(MDBArtist.Name), artist)); search &= Search.FieldIn(nameof(MDBAudioFile.AlbumArtistID), ids) | Search.FieldIn(nameof(MDBAudioFile.SongArtistID), ids); } if (albumID > 0) { search &= Search.FieldEquals(nameof(MDBAudioFile.AlbumID), albumID); if (album != null) { throw new WebServerException(WebError.InvalidParameters, 0, "Cannot use album search and albumID at the same time!"); } } else if (album != null) { var ids = mdb.Albums.FindRows(Search.FieldLike(nameof(MDBArtist.Name), album)); search &= Search.FieldIn(nameof(MDBAudioFile.AlbumID), ids); } if (categoryID > 0) { search &= GetCategorySearch(categoryID); } if (genreID > 0) { search &= Search.FieldEquals(nameof(MDBAudioFile.GenreID), genreID); } if (tagID > 0) { search &= Search.FieldEquals(nameof(MDBAudioFile.TagID), tagID); } if (genre != null) { search &= Search.FieldLike(nameof(MDBAudioFile.Genres), MDBSearch.Text("%" + genre + "%")); } if (tag != null) { search &= Search.FieldLike(nameof(MDBAudioFile.Tags), MDBSearch.Text("%" + tag + "%")); } if (title != null) { search &= Search.FieldLike(nameof(MDBAudioFile.Title), MDBSearch.Text("%" + title + "%")); } { long rowCount = mdb.AudioFiles.Count(search); var ids = mdb.AudioFiles.FindRows(search, ResultOption.Limit(RowsPerPage) + ResultOption.Offset(page * RowsPerPage) + ResultOption.SortAscending(nameof(MDBAudioFile.Title))); webData.Result.AddMessage(webData.Method, "Found {0} matching AudioFiles.", rowCount); AddPagination(webData, page, rowCount); var files = ids.Select(i => RPCAudioFile.Load(mdb, i)); webData.Result.AddStructs(files); } }
public BuildControl(Build build, string logFilePath) { InitializeComponent(); UpdateWatermark(); searchLogControl.ExecuteSearch = searchText => { var search = new Search(Build); var results = search.FindNodes(searchText); return(results); }; searchLogControl.ResultsTreeBuilder = BuildResultTree; searchLogControl.WatermarkDisplayed += () => UpdateWatermark(); VirtualizingPanel.SetIsVirtualizing(treeView, SettingsService.EnableTreeViewVirtualization); DataContext = build; Build = build; LogFilePath = logFilePath; if (build.SourceFilesArchive != null) { // first try to see if the source archive was embedded in the log sourceFileResolver = new SourceFileResolver(build.SourceFilesArchive); } else { // otherwise try to read from the .zip file on disk if present sourceFileResolver = new SourceFileResolver(logFilePath); } sharedTreeContextMenu = new ContextMenu(); copyAllItem = new MenuItem() { Header = "Copy All" }; copyAllItem.Click += (s, a) => CopyAll(); sharedTreeContextMenu.Items.Add(copyAllItem); var contextMenu = new ContextMenu(); contextMenu.Opened += ContextMenu_Opened; copyItem = new MenuItem() { Header = "Copy" }; copySubtreeItem = new MenuItem() { Header = "Copy subtree" }; copyChildrenItem = new MenuItem() { Header = "Copy children" }; sortChildrenItem = new MenuItem() { Header = "Sort children" }; copyNameItem = new MenuItem() { Header = "Copy name" }; copyValueItem = new MenuItem() { Header = "Copy value" }; viewItem = new MenuItem() { Header = "View" }; preprocessItem = new MenuItem() { Header = "Preprocess" }; hideItem = new MenuItem() { Header = "Hide" }; copyItem.Click += (s, a) => Copy(); copySubtreeItem.Click += (s, a) => CopySubtree(); copyChildrenItem.Click += (s, a) => CopyChildren(); sortChildrenItem.Click += (s, a) => SortChildren(); copyNameItem.Click += (s, a) => CopyName(); copyValueItem.Click += (s, a) => CopyValue(); viewItem.Click += (s, a) => Invoke(treeView.SelectedItem as ParentedNode); preprocessItem.Click += (s, a) => Preprocess(treeView.SelectedItem as Project); hideItem.Click += (s, a) => Delete(); contextMenu.Items.Add(viewItem); contextMenu.Items.Add(preprocessItem); contextMenu.Items.Add(copyItem); contextMenu.Items.Add(copySubtreeItem); contextMenu.Items.Add(copyChildrenItem); contextMenu.Items.Add(sortChildrenItem); contextMenu.Items.Add(copyNameItem); contextMenu.Items.Add(copyValueItem); contextMenu.Items.Add(hideItem); var existingTreeViewItemStyle = (Style)Application.Current.Resources[typeof(TreeViewItem)]; var treeViewItemStyle = new Style(typeof(TreeViewItem), existingTreeViewItemStyle); treeViewItemStyle.Setters.Add(new Setter(TreeViewItem.IsExpandedProperty, new Binding("IsExpanded") { Mode = BindingMode.TwoWay })); treeViewItemStyle.Setters.Add(new Setter(TreeViewItem.IsSelectedProperty, new Binding("IsSelected") { Mode = BindingMode.TwoWay })); treeViewItemStyle.Setters.Add(new Setter(TreeViewItem.VisibilityProperty, new Binding("IsVisible") { Mode = BindingMode.TwoWay, Converter = new BooleanToVisibilityConverter() })); treeViewItemStyle.Setters.Add(new EventSetter(MouseDoubleClickEvent, (MouseButtonEventHandler)OnItemDoubleClick)); treeViewItemStyle.Setters.Add(new EventSetter(PreviewMouseRightButtonDownEvent, (MouseButtonEventHandler)OnPreviewMouseRightButtonDown)); treeViewItemStyle.Setters.Add(new EventSetter(RequestBringIntoViewEvent, (RequestBringIntoViewEventHandler)TreeViewItem_RequestBringIntoView)); treeViewItemStyle.Setters.Add(new EventSetter(KeyDownEvent, (KeyEventHandler)OnItemKeyDown)); treeView.ContextMenu = contextMenu; treeView.ItemContainerStyle = treeViewItemStyle; treeView.KeyDown += TreeView_KeyDown; treeView.SelectedItemChanged += TreeView_SelectedItemChanged; treeView.GotFocus += (s, a) => ActiveTreeView = treeView; ActiveTreeView = treeView; searchLogControl.ResultsList.ItemContainerStyle = treeViewItemStyle; searchLogControl.ResultsList.SelectedItemChanged += ResultsList_SelectionChanged; searchLogControl.ResultsList.GotFocus += (s, a) => ActiveTreeView = searchLogControl.ResultsList; searchLogControl.ResultsList.ContextMenu = sharedTreeContextMenu; if (archiveFile != null) { findInFilesControl.ExecuteSearch = FindInFiles; findInFilesControl.ResultsTreeBuilder = BuildFindResults; findInFilesControl.GotFocus += (s, a) => ActiveTreeView = findInFilesControl.ResultsList; findInFilesControl.ResultsList.ItemContainerStyle = treeViewItemStyle; findInFilesControl.ResultsList.GotFocus += (s, a) => ActiveTreeView = findInFilesControl.ResultsList; findInFilesControl.ResultsList.ContextMenu = sharedTreeContextMenu; filesTab.Visibility = Visibility.Visible; findInFilesTab.Visibility = Visibility.Visible; PopulateFilesTab(); filesTree.ResultsList.ItemContainerStyle = treeViewItemStyle; filesTree.TextChanged += FilesTree_SearchTextChanged; var filesNote = new TextBlock(); var text = @"This log contains the full text of projects and imported files used during the build. You can use the 'Files' tab in the bottom left to view these files and the 'Find in Files' tab for full-text search. For many nodes in the tree (Targets, Tasks, Errors, Projects, etc) pressing SPACE or ENTER or double-clicking on the node will navigate to the corresponding source code associated with the node. More functionality is available from the right-click context menu for each node. Right-clicking a project node may show the 'Preprocess' option if the version of MSBuild was at least 15.3."; build.Unseal(); build.AddChild(new Note { Text = text }); build.Seal(); } breadCrumb.SelectionChanged += BreadCrumb_SelectionChanged; Loaded += BuildControl_Loaded; preprocessedFileManager = new PreprocessedFileManager(this, sourceFileResolver); PopulateTimeline(); }
internal static bool Creates(this ObjectCreationExpressionSyntax creation, ConstructorDeclarationSyntax ctor, Search search, SemanticModel semanticModel, CancellationToken cancellationToken) { var created = semanticModel.GetSymbolSafe(creation, cancellationToken) as IMethodSymbol; var ctorSymbol = semanticModel.GetDeclaredSymbolSafe(ctor, cancellationToken); if (SymbolComparer.Equals(ctorSymbol, created)) { return(true); } return(search == Search.Recursive && IsRunBefore(created, ctorSymbol, semanticModel, cancellationToken)); }
public void GetPlayerState(WebData webData, int hash = 0, long streamID = 0) { //default is JukeBob if (streamID == 0) { streamID = (long)MDBStreamType.JukeBob; } MDBNowPlaying nowPlaying = mdb.NowPlaying.TryGetStruct(1); var myHash = nowPlaying.GetHashCode() ^ mdb.PlayListSequenceNumber ^ -1; DateTime timeout = DateTime.UtcNow.AddSeconds(30 + DefaultRNG.UInt8 % 30); while (hash == myHash && DateTime.UtcNow < timeout) { Thread.Sleep(200); nowPlaying = mdb.NowPlaying.TryGetStruct(1); myHash = nowPlaying.GetHashCode() ^ mdb.PlayListSequenceNumber ^ -1; } var playList = new List <MDBPlayListItem>(); playList.AddRange(mdb.PlayListItems.GetStructs( Search.FieldEquals(nameof(MDBPlayListItem.StreamID), streamID) & Search.FieldGreater(nameof(MDBPlayListItem.OwnerID), 0), ResultOption.SortAscending(nameof(MDBPlayListItem.Added)))); playList.AddRange(mdb.PlayListItems.GetStructs( Search.FieldEquals(nameof(MDBPlayListItem.StreamID), streamID) & Search.FieldEquals(nameof(MDBPlayListItem.OwnerID), 0), ResultOption.SortAscending(nameof(MDBPlayListItem.Added)))); var audioFileIDs = new Set <long>(nowPlaying.AudioFileID, playList.Select(i => i.AudioFileID)); var files = mdb.AudioFiles.GetStructs(audioFileIDs); var albums = mdb.Albums.GetStructs(files.Select(f => f.AlbumID)); var artistIDs = new Set <long>(files.Select(f => f.AlbumArtistID), files.Select(f => f.SongArtistID)); var artists = mdb.Artists.GetStructs(artistIDs); var users = authTables.Users.GetStructs(playList.Select(i => i.OwnerID).Where(i => i > 0)).Select(u => u.ClearPrivateFields()); var subsetIDs = playList.Where(i => i.SubsetID > 0).Select(i => i.SubsetID).ToSet(); if (nowPlaying.SubsetID > 0) { subsetIDs.Include(nowPlaying.SubsetID); } var subsets = mdb.Subsets.GetStructs(subsetIDs); long ownerID; if (webData.Session.IsAuthenticated()) { ownerID = webData.Session.GetUser().ID; } else { ownerID = -webData.Session.ID; } webData.Result.AddMessage(webData.Method, "Retrieved JukeBob NowPlaying"); webData.Result.AddStructs(playList); webData.Result.AddStructs(files); webData.Result.AddStructs(albums); webData.Result.AddStructs(artists); webData.Result.AddStructs(subsets); webData.Result.AddStructs(users); webData.Result.AddStruct(new MDBPlayerState() { ID = ownerID, Hash = myHash, StreamType = MDBStreamType.JukeBob }); nowPlaying.UpdateDateTime = DateTime.UtcNow; webData.Result.AddStruct(nowPlaying); }
public async Task <IEnumerable <Caisse> > GetSearchAchatAsync(Search search) { return(await _context.Caisses.Where(f => f.Date >= search.Fromdo).Where(f => f.Date <= search.Fromto).ToListAsync()); }
public void ShouldReturnMinusOneOnBinarySearchWhenItemDoesNotExistInArray() { int[] array = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; Assert.AreEqual(-1, Search.BinarySearch(array, 200)); }
/* This service method calls the google API to discover WSDL services */ public string[] DiscoverWsdlServices(string keywords) { int i = 0; /* The keyword WSDL is appended to the provided search query */ /* to ensure that returned results are more in-line with */ /* the requirement, i.e. WSDL services. */ string query = keywords + " WSDL"; /* Create an array of URLs to be returned */ string[] urls = new string[MAX_SEARCH_COUNT * MAX_PAGES_PER_SEARCH]; /* Create a custom search service object and set the API key */ CustomsearchService customSearchService = new CustomsearchService( new Google.Apis.Services.BaseClientService.Initializer() { ApiKey = GOOGLE_API_KEY }); /* Create a list request object to perform the search */ CseResource.ListRequest listRequest = customSearchService.Cse.List(query); /* Set the search engine ID */ listRequest.Cx = GOOGLE_SEARCH_ENGINE_ID; /* This loop varies the start index and repeatedly performs the search */ for (int k = 1; k < (MAX_SEARCH_COUNT * MAX_PAGES_PER_SEARCH); k += MAX_PAGES_PER_SEARCH) { /* Setting the start index */ listRequest.Start = k; /* Perform the search. Along with the query to search for, the WSDL search */ /* would need certain URL patterns to look for. These URL patterns such as */ /* "*.wsdl", "*.svc?wsdl", "*.asmx?wsdl" and "*.php?wsdl" are programmed */ /* into the search engine while creating it using the google's custom */ /* search engine control panel. The search engine ID helps recognize the */ /* custom search engine that has been created. */ Search search = listRequest.Execute(); /* If the search returns no results, break. There's no */ /* point in searching more. */ if (search.Items == null) { continue; } /* Traverse the search result list and copy links that match WSDL type URLs */ /* into an array of strings to be returned */ foreach (var item in search.Items) { #if FILTER if (item.Link.EndsWith(".wsdl") || item.Link.EndsWith(".svc?wsdl") || item.Link.EndsWith(".asmx?wsdl") || item.Link.EndsWith(".php?wsdl")) #endif { urls[i++] = item.Title + URL_TITLE_LINK_SEPARATOR + item.Link; } } } return(urls); }
public string DiscoverySearchTwitter(string UserId, string keyword) { List <Domain.Socioboard.Domain.DiscoverySearch> lstDiscoverySearch = new List <Domain.Socioboard.Domain.DiscoverySearch>(); string profileid = string.Empty; try { oAuthTwitter oauth = new oAuthTwitter(); Twitter obj = new Twitter(); TwitterAccountRepository twtAccRepo = new TwitterAccountRepository(); List <Domain.Socioboard.Domain.TwitterAccount> alst = twtAccRepo.getTwtAccount(); foreach (Domain.Socioboard.Domain.TwitterAccount item in alst) { oauth.AccessToken = item.OAuthToken; oauth.AccessTokenSecret = item.OAuthSecret; oauth.TwitterUserId = item.TwitterUserId; oauth.TwitterScreenName = item.TwitterScreenName; obj.SetCofigDetailsForTwitter(oauth); try { Users _Users = new Users(); JArray _AccountVerify = _Users.Get_Account_Verify_Credentials(oauth); string id = _AccountVerify["id_str"].ToString(); break; } catch (Exception ex) { } //if (this.CheckTwitterToken(oauth, keyword)) //{ // break; //} } Search search = new Search(); JArray twitterSearchResult = search.Get_Search_Tweets(oauth, keyword); foreach (var item in twitterSearchResult) { var results = item["statuses"]; foreach (var chile in results) { try { objDiscoverySearch = new Domain.Socioboard.Domain.DiscoverySearch(); objDiscoverySearch.SearchKeyword = keyword; objDiscoverySearch.Network = "twitter"; objDiscoverySearch.Id = Guid.NewGuid(); objDiscoverySearch.UserId = Guid.Parse(UserId); if (!dissearchrepo.isKeywordPresentforNetwork(objDiscoverySearch.SearchKeyword, objDiscoverySearch.Network)) { dissearchrepo.addNewSearchResult(objDiscoverySearch); } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } try { objDiscoverySearch = new Domain.Socioboard.Domain.DiscoverySearch(); objDiscoverySearch.CreatedTime = Utility.ParseTwitterTime(chile["created_at"].ToString().TrimStart('"').TrimEnd('"'));; objDiscoverySearch.EntryDate = DateTime.Now; objDiscoverySearch.FromId = chile["user"]["id_str"].ToString().TrimStart('"').TrimEnd('"'); objDiscoverySearch.FromName = chile["user"]["screen_name"].ToString().TrimStart('"').TrimEnd('"'); objDiscoverySearch.ProfileImageUrl = chile["user"]["profile_image_url"].ToString().TrimStart('"').TrimEnd('"'); objDiscoverySearch.SearchKeyword = keyword; objDiscoverySearch.Network = "twitter"; objDiscoverySearch.Message = chile["text"].ToString().TrimStart('"').TrimEnd('"'); objDiscoverySearch.MessageId = chile["id_str"].ToString().TrimStart('"').TrimEnd('"'); objDiscoverySearch.Id = Guid.NewGuid(); objDiscoverySearch.UserId = Guid.Parse(UserId); lstDiscoverySearch.Add(objDiscoverySearch); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } } } return(new JavaScriptSerializer().Serialize(lstDiscoverySearch)); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); return(new JavaScriptSerializer().Serialize("Please try Again")); } }
////////////////////////////////////////////////////////////////////////// //Операции общего назначения private void EditField_TextChanged(object sender, TextChangedEventArgs e) { TextBox textBox = (TextBox)sender; if (Name.Equals(textBox)) { if (Name.Text.Length > 0) { NameWatermark.Visibility = Visibility.Hidden; } else { NameWatermark.Visibility = Visibility.Visible; } } else if (Surname.Equals(textBox)) { if (Surname.Text.Length > 0) { SurnameWatermark.Visibility = Visibility.Hidden; } else { SurnameWatermark.Visibility = Visibility.Visible; } } else if (Patronymic.Equals(textBox)) { if (Patronymic.Text.Length > 0) { PatronymicWatermark.Visibility = Visibility.Hidden; } else { PatronymicWatermark.Visibility = Visibility.Visible; } } else if (Password.Equals(textBox)) { if (Password.Text.Length > 0) { PasswordWatermark.Visibility = Visibility.Hidden; } else { PasswordWatermark.Visibility = Visibility.Visible; } } else if (AuthorSurname.Equals(textBox)) { if (AuthorSurname.Text.Length > 0) { AuthorSurnameWatermark.Visibility = Visibility.Hidden; } else { AuthorSurnameWatermark.Visibility = Visibility.Visible; } } else if (AuthorName.Equals(textBox)) { if (AuthorName.Text.Length > 0) { AuthorNameWatermark.Visibility = Visibility.Hidden; } else { AuthorNameWatermark.Visibility = Visibility.Visible; } } else if (AuthorPatronymic.Equals(textBox)) { if (AuthorPatronymic.Text.Length > 0) { AuthorPatronymicWatermark.Visibility = Visibility.Hidden; } else { AuthorPatronymicWatermark.Visibility = Visibility.Visible; } } else if (BookName.Equals(textBox)) { if (BookName.Text.Length > 0) { BookNameWatermark.Visibility = Visibility.Hidden; } else { BookNameWatermark.Visibility = Visibility.Visible; } } else if (Publisher.Equals(textBox)) { if (Publisher.Text.Length > 0) { PublisherWatermark.Visibility = Visibility.Hidden; } else { PublisherWatermark.Visibility = Visibility.Visible; } } else if (PublicationDate.Equals(textBox)) { if (PublicationDate.Text.Length > 0) { PublicationDateWatermark.Visibility = Visibility.Hidden; } else { PublicationDateWatermark.Visibility = Visibility.Visible; } } else if (PageCount.Equals(textBox)) { if (PageCount.Text.Length > 0) { PageCountWatermark.Visibility = Visibility.Hidden; } else { PageCountWatermark.Visibility = Visibility.Visible; } } else if (Location.Equals(textBox)) { if (Location.Text.Length > 0) { LocationWatermark.Visibility = Visibility.Hidden; } else { LocationWatermark.Visibility = Visibility.Visible; } } else if (Search.Equals(textBox)) { SearchUpdate(); } }
public BuiltInFunctions() { // Text Functions["len"] = new Len(); Functions["lower"] = new Lower(); Functions["upper"] = new Upper(); Functions["left"] = new Left(); Functions["right"] = new Right(); Functions["mid"] = new Mid(); Functions["replace"] = new Replace(); Functions["rept"] = new Rept(); Functions["substitute"] = new Substitute(); Functions["concatenate"] = new Concatenate(); Functions["concat"] = new Concat(); Functions["char"] = new CharFunction(); Functions["exact"] = new Exact(); Functions["find"] = new Find(); Functions["fixed"] = new Fixed(); Functions["proper"] = new Proper(); Functions["search"] = new Search(); Functions["text"] = new Text.Text(); Functions["t"] = new T(); Functions["hyperlink"] = new Hyperlink(); Functions["value"] = new Value(); Functions["trim"] = new Trim(); Functions["clean"] = new Clean(); // Numbers Functions["int"] = new CInt(); // Math Functions["abs"] = new Abs(); Functions["asin"] = new Asin(); Functions["asinh"] = new Asinh(); Functions["cos"] = new Cos(); Functions["cosh"] = new Cosh(); Functions["power"] = new Power(); Functions["sign"] = new Sign(); Functions["sqrt"] = new Sqrt(); Functions["sqrtpi"] = new SqrtPi(); Functions["pi"] = new Pi(); Functions["product"] = new Product(); Functions["ceiling"] = new Ceiling(); Functions["count"] = new Count(); Functions["counta"] = new CountA(); Functions["countblank"] = new CountBlank(); Functions["countif"] = new CountIf(); Functions["countifs"] = new CountIfs(); Functions["fact"] = new Fact(); Functions["floor"] = new Floor(); Functions["sin"] = new Sin(); Functions["sinh"] = new Sinh(); Functions["sum"] = new Sum(); Functions["sumif"] = new SumIf(); Functions["sumifs"] = new SumIfs(); Functions["sumproduct"] = new SumProduct(); Functions["sumsq"] = new Sumsq(); Functions["stdev"] = new Stdev(); Functions["stdevp"] = new StdevP(); Functions["stdev.s"] = new Stdev(); Functions["stdev.p"] = new StdevP(); Functions["subtotal"] = new Subtotal(); Functions["exp"] = new Exp(); Functions["log"] = new Log(); Functions["log10"] = new Log10(); Functions["ln"] = new Ln(); Functions["max"] = new Max(); Functions["maxa"] = new Maxa(); Functions["median"] = new Median(); Functions["min"] = new Min(); Functions["mina"] = new Mina(); Functions["mod"] = new Mod(); Functions["average"] = new Average(); Functions["averagea"] = new AverageA(); Functions["averageif"] = new AverageIf(); Functions["averageifs"] = new AverageIfs(); Functions["round"] = new Round(); Functions["rounddown"] = new Rounddown(); Functions["roundup"] = new Roundup(); Functions["rand"] = new Rand(); Functions["randbetween"] = new RandBetween(); Functions["rank"] = new Rank(); Functions["rank.eq"] = new Rank(); Functions["rank.avg"] = new Rank(true); Functions["quotient"] = new Quotient(); Functions["trunc"] = new Trunc(); Functions["tan"] = new Tan(); Functions["tanh"] = new Tanh(); Functions["atan"] = new Atan(); Functions["atan2"] = new Atan2(); Functions["atanh"] = new Atanh(); Functions["acos"] = new Acos(); Functions["acosh"] = new Acosh(); Functions["var"] = new Var(); Functions["varp"] = new VarP(); Functions["large"] = new Large(); Functions["small"] = new Small(); Functions["degrees"] = new Degrees(); // Information Functions["isblank"] = new IsBlank(); Functions["isnumber"] = new IsNumber(); Functions["istext"] = new IsText(); Functions["isnontext"] = new IsNonText(); Functions["iserror"] = new IsError(); Functions["iserr"] = new IsErr(); Functions["error.type"] = new ErrorType(); Functions["iseven"] = new IsEven(); Functions["isodd"] = new IsOdd(); Functions["islogical"] = new IsLogical(); Functions["isna"] = new IsNa(); Functions["na"] = new Na(); Functions["n"] = new N(); // Logical Functions["if"] = new If(); Functions["iferror"] = new IfError(); Functions["ifna"] = new IfNa(); Functions["not"] = new Not(); Functions["and"] = new And(); Functions["or"] = new Or(); Functions["true"] = new True(); Functions["false"] = new False(); // Reference and lookup Functions["address"] = new Address(); Functions["hlookup"] = new HLookup(); Functions["vlookup"] = new VLookup(); Functions["lookup"] = new Lookup(); Functions["match"] = new Match(); Functions["row"] = new Row(); Functions["rows"] = new Rows(); Functions["column"] = new Column(); Functions["columns"] = new Columns(); Functions["choose"] = new Choose(); Functions["index"] = new RefAndLookup.Index(); Functions["indirect"] = new Indirect(); Functions["offset"] = new Offset(); // Date Functions["date"] = new Date(); Functions["today"] = new Today(); Functions["now"] = new Now(); Functions["day"] = new Day(); Functions["month"] = new Month(); Functions["year"] = new Year(); Functions["time"] = new Time(); Functions["hour"] = new Hour(); Functions["minute"] = new Minute(); Functions["second"] = new Second(); Functions["weeknum"] = new Weeknum(); Functions["weekday"] = new Weekday(); Functions["days360"] = new Days360(); Functions["yearfrac"] = new Yearfrac(); Functions["edate"] = new Edate(); Functions["eomonth"] = new Eomonth(); Functions["isoweeknum"] = new IsoWeekNum(); Functions["workday"] = new Workday(); Functions["networkdays"] = new Networkdays(); Functions["networkdays.intl"] = new NetworkdaysIntl(); Functions["datevalue"] = new DateValue(); Functions["timevalue"] = new TimeValue(); // Database Functions["dget"] = new Dget(); Functions["dcount"] = new Dcount(); Functions["dcounta"] = new DcountA(); Functions["dmax"] = new Dmax(); Functions["dmin"] = new Dmin(); Functions["dsum"] = new Dsum(); Functions["daverage"] = new Daverage(); Functions["dvar"] = new Dvar(); Functions["dvarp"] = new Dvarp(); //Finance Functions["pmt"] = new Pmt(); }
public void ShouldReturnCorrectIndexOnBinarySearchWhenItemAtTheEndOfArray() { int[] array = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; Assert.AreEqual(7, Search.BinarySearch(array, 8)); }
private void SessionIdSearch(string sessionId, bool directMatch = true) { try { //ensure the grid has records loaded if (dgvMain.Rows.Count <= 0) { return; } //ensure the 'SessionID' column exists if (SessionIdPresent()) { //the search rule dictates the matching pattern var rule = directMatch ? SearchRule.EqualsKey : SearchRule.ContainsKey; //the information to be used for initiating the grid search var searchContext = new SearchData { SearchColumn = "SessionID", SearchRule = rule, SearchTable = _logRecords, SearchTerm = sessionId }; //utilise the common search framework to start a grid search if (Search.RunTitleSearch(dgvMain, searchContext)) { //set the grid status _isFiltered = true; //update the GUI to reflect a search being active GuiSetStartSearch(); } else { //if the common framework returned false, then an error occurred; cancel the search and reset the GUI. CancelSearch(); } } else { //inform the user of the error UIMessages.Error("Couldn't find a valid 'SessionID' column. Have you got the correct log loaded?", "Validation Error"); //if the common framework returned false, then an error occurred; cancel the search and reset the GUI. CancelSearch(); } } catch (Exception ex) { //log the error LoggingHelpers.RecordException(ex.Message, "LogSearchError"); //alert the user UIMessages.Error(ex.ToString()); //reset the GUI and clear the search CancelSearch(); } }
public Workforce[] Get() { var collection = JsonConvert.DeserializeObject <List <Workforce> >(File.ReadAllText("C:/Users/Arthur/source/repos/src/Challenge/data/workforce.json")); //Deserializando json em objetos do tipo correto List <Workforce> aux_collection = new List <Workforce>(); //Lista auxiliar para armazenar a quantia certa do array para retornar. for (int i = 0; i < collection.Count; i++) { if (collection[i].Name.Contains(Search.GetInstance().query) || collection[i].Shift.Contains(Search.GetInstance().query)) //Condições de busca { aux_collection.Add(collection[i]); } } Workforce[] workforceArray = new Workforce[aux_collection.Count]; //Criando array de valores para retornar for (int i = 0; i < aux_collection.Count; i++) { workforceArray[i] = aux_collection[i]; //Atribuindo todos os valores da lista auxiliar ao array de retorno. } return(workforceArray); //Retornando json }
private void unbindChapters(msOrder orderToUse, string membershipItemGuid) { if (!divChapter.Visible) // chapters aren't even enabled { return; } List <string> chapters = new List <string>(); // ok, first let's pull the primary chapter var primaryChapter = ddlSelectChapter.SelectedValue; if (primaryChapter != null) { chapters.Add(primaryChapter); } // now, if additional chapters are supported, we'll pull those if (divAdditionalChapters.Visible) { foreach (ListItem secondaryChapter in lbAdditionalChapters.Items) { if (secondaryChapter.Selected && !chapters.Contains(secondaryChapter.Value)) // don't duplicate { chapters.Add(secondaryChapter.Value); } } } // ok, now we need to get the products for these chapters and any organizational layers they are under using (var api = GetConciegeAPIProxy()) { foreach (var chapter in chapters) { var productID = api.GetDefaultChapterProduct2(targetEntity.ID, targetMembership.Type, chapter).ResultValue.SafeGetValue <string>("ID"); orderToUse.LineItems.Add(new msOrderLineItem { Quantity = 1, Product = productID, LinkedOrderLineItemID = membershipItemGuid }); Search s = new Search("ChapterOrganizationalLayers"); s.Context = chapter; s.AddOutputColumn("ID"); SearchResult sr = APIExtensions.GetSearchResult(api, s, 0, null); foreach (DataRow dataRow in sr.Table.Rows) { string organizationalLayerId = dataRow["ID"].ToString(); var productResult = api.GetDefaultOrganizationalLayerProduct(targetMembership.Type, organizationalLayerId).ResultValue; if (productResult == null) { continue; } productID = productResult.SafeGetValue <string>("ID"); orderToUse.LineItems.Add(new msOrderLineItem { Quantity = 1, Product = productID, LinkedOrderLineItemID = membershipItemGuid }); } } } // ok, that's it }
public static Image GetImage16For(Search search) { return(GetImage16For(GetIconFor(search))); }
/// <summary> /// Executes a search against the Concierge API for events with a future start date that are set to be visible in the portal. /// </summary> /// <returns></returns> private void loadDataFromConcierge() { Search s = new Search { Type = msEvent.CLASS_NAME }; s.AddOutputColumn("ID"); s.AddOutputColumn("Name"); s.AddOutputColumn("StartDate"); s.AddOutputColumn("EndDate"); s.AddOutputColumn("Category"); s.AddOutputColumn("ShortSummary"); s.AddOutputColumn("VisibleInPortal"); s.AddOutputColumn("PostToWeb"); s.AddOutputColumn("RemoveFromWeb"); s.AddOutputColumn("Location_City"); s.AddOutputColumn("Location_State"); s.AddOutputColumn("DisplayStartEndDateTimesAs"); s.AddOutputColumn("InviteOnly"); s.AddOutputColumn("Url"); // CORE-1017 s.AddSortColumn("StartDate", false); if (targetCategory != null) { if (targetCategory.ID != "null") { s.AddCriteria(Expr.Equals("Category", targetCategory.ID)); } else { s.AddCriteria(Expr.IsBlank("Category")); } } // MS-1366 - If there's a background user, then we can show the non-visible - otherwise no if (!ConciergeAPI.HasBackgroundConsoleUser) // there's no background user { s.AddCriteria(Expr.Equals("VisibleInPortal", 1)); } s.AddCriteria(Expr.DoesNotEqual("IsClosed", true)); // it's not over s.AddCriteria(Expr.IsGreaterThan("EndDate", DateTime.Now)); var searchResult = APIExtensions.GetSearchResult(s, 0, null); var dt = searchResult.Table; // now, let's pull upcoming exhibit shows that are NOT tied to an event if (IsModuleActive("Exhibits") || ConciergeAPI.CurrentEntity == null) // put this in as a hack since you can't check modules when not logged in { Search se = new Search(msExhibitShow.CLASS_NAME); se.AddOutputColumn("ID"); se.AddOutputColumn("Name"); se.AddOutputColumn("StartDate"); se.AddOutputColumn("EndDate"); se.AddOutputColumn("ShortSummary"); se.AddOutputColumn("Category"); se.AddOutputColumn("VisibleInPortal"); se.AddOutputColumn("PostToWeb"); se.AddOutputColumn("RemoveFromWeb"); se.AddSortColumn("StartDate", false); if (!ConciergeAPI.HasBackgroundConsoleUser) // there's no background user { se.AddCriteria(Expr.Equals("VisibleInPortal", 1)); } // it's not over se.AddCriteria(Expr.IsGreaterThan("EndDate", DateTime.Now)); se.AddCriteria(Expr.IsBlank(msExhibitShow.FIELDS.Event)); // only shows with no events tied to them! if (targetCategory != null) { if (targetCategory.ID != "null") { se.AddCriteria(Expr.Equals("Category", targetCategory.ID)); } else { se.AddCriteria(Expr.IsBlank("Category")); } } var shows = APIExtensions.GetSearchResult(se, 0, null).Table; foreach (DataRow dr in shows.Rows) // this ONLY works because the columns are the same! { dt.ImportRow(dr); } } DataTable dtInvitations = null; if (ConciergeAPI.CurrentEntity != null) { Search sInvitees = new Search("EventInvitee"); sInvitees.AddOutputColumn("Event"); sInvitees.AddCriteria(Expr.Equals("Invitee", ConciergeAPI.CurrentEntity.ID)); dtInvitations = APIExtensions.GetSearchResult(sInvitees, 0, null).Table; } // MS-1366 - let's make sure if we show non-visible records we marked it as so foreach (DataRow dr in searchResult.Table.Rows) { if (!Convert.ToBoolean(dr["VisibleInPortal"])) { dr["Name"] = dr["Name"] + " [HIDDEN]"; } } // now, let's remove all that shouldn't be posted for (int i = dt.Rows.Count - 1; i >= 0; i--) { DataRow dr = dt.Rows[i]; if (!_checkPostRemoveDate(dr)) { if (ConciergeAPI.HasBackgroundConsoleUser) { dr["Name"] += " [UNPOSTED]"; } else { dt.Rows.RemoveAt(i); continue; } } if (!_canSeeEvent(dr, dtInvitations)) { dt.Rows.RemoveAt(i); } } dvEvents = dt.DefaultView; dvEvents.Sort = "StartDate"; }
public Workforce[] Get() { var collection = JsonConvert.DeserializeObject <List <Workforce> >(File.ReadAllText("C:/xampp/htdocs/dashboard/src/Controllers/workforce.json")); List <Workforce> aux_collection = new List <Workforce>(); for (int i = 0; i < collection.Count; i++) { if (collection[i].Name.Contains(Search.GetInstance().query) || collection[i].Shift.Contains(Search.GetInstance().query)) { aux_collection.Add(collection[i]); } } Workforce[] workforceArray = new Workforce[aux_collection.Count]; for (int i = 0; i < aux_collection.Count; i++) { workforceArray[i] = aux_collection[i]; } return(workforceArray); }
static void Main(string[] args) { // Get an AmazonDynamoDBClient for the local DynamoDB database AmazonDynamoDBClient client = GetLocalClient(); // Get a Table object for the table that you created in Step 1 Table table = GetTableObject(client, "Movies"); if (table == null) { PauseForDebugWindow(); return; } /*----------------------------------------------------------------------- * 4.2a: Call Table.Scan to return the movies released in the 1950's, * displaying title, year, lead actor and lead director. *-----------------------------------------------------------------------*/ ScanFilter filter = new ScanFilter(); filter.AddCondition("year", ScanOperator.Between, new DynamoDBEntry[] { 1950, 1959 }); ScanOperationConfig config = new ScanOperationConfig { AttributesToGet = new List <string> { "year, title, info" }, Filter = filter }; Search search = table.Scan(filter); // Display the movie information returned by this query Console.WriteLine("\n\n Movies released in the 1950's (Document Model):" + "\n--------------------------------------------------"); List <Document> docList = new List <Document>(); Document infoDoc; string movieFormatString = " \"{0}\" ({1})-- lead actor: {2}, lead director: {3}"; do { try { docList = search.GetNextSet(); } catch (Exception ex) { Console.WriteLine("\n Error: Search.GetNextStep failed because: " + ex.Message); break; } foreach (var doc in docList) { infoDoc = doc["info"].AsDocument(); Console.WriteLine(movieFormatString, doc["title"], doc["year"], infoDoc["actors"].AsArrayOfString()[0], infoDoc["directors"].AsArrayOfString()[0]); } } while (!search.IsDone); /*----------------------------------------------------------------------- * 4.2b: Call AmazonDynamoDBClient.Scan to return all movies released * in the 1960's, only downloading the title, year, lead * actor and lead director attributes. *-----------------------------------------------------------------------*/ ScanRequest sRequest = new ScanRequest { TableName = "Movies", ExpressionAttributeNames = new Dictionary <string, string> { { "#yr", "year" } }, ExpressionAttributeValues = new Dictionary <string, AttributeValue> { { ":y_a", new AttributeValue { N = "1960" } }, { ":y_z", new AttributeValue { N = "1969" } }, }, FilterExpression = "#yr between :y_a and :y_z", ProjectionExpression = "#yr, title, info.actors[0], info.directors[0]" }; ScanResponse sResponse; try { sResponse = client.Scan(sRequest); } catch (Exception ex) { Console.WriteLine("\n Error: Low-level scan failed, because: " + ex.Message); PauseForDebugWindow(); return; } // Display the movie information returned by this scan Console.WriteLine("\n\n Movies released in the 1960's (low-level):" + "\n-------------------------------------------"); foreach (Dictionary <string, AttributeValue> item in sResponse.Items) { Dictionary <string, AttributeValue> info = item["info"].M; Console.WriteLine(movieFormatString, item["title"].S, item["year"].N, info["actors"].L[0].S, info["directors"].L[0].S); } }
public SearchCommissionMultiplier(Search search) : base(search) { }
public void SearchAlbums(WebData webData, long artistID = 0, string filter = null, int page = 0, long categoryID = 0, long genreID = 0, long tagID = 0, string genre = null, string tag = null) { ICollection <long> albumIDs = null; //select audio files if (genreID != 0 || categoryID != 0 || tagID != 0 || genre != null || tag != null) { Search s = Search.None; if (genreID != 0) { s &= Search.FieldEquals(nameof(MDBAudioFile.GenreID), genreID); } if (tagID != 0) { s &= Search.FieldEquals(nameof(MDBAudioFile.TagID), tagID); } if (genre != null) { s &= Search.FieldLike(nameof(MDBAudioFile.Genres), MDBSearch.Text("%" + genre + "%")); } if (tag != null) { s &= Search.FieldLike(nameof(MDBAudioFile.Tags), MDBSearch.Text("%" + tag + "%")); } if (categoryID > 0) { s &= GetCategorySearch(categoryID); } int fieldIndex = mdb.AudioFiles.Layout.GetFieldIndex(nameof(MDBAudioFile.AlbumID)); albumIDs = mdb.AudioFiles.GetRows(s).Select(r => (long)r.GetValue(fieldIndex)).ToList(); } //select artists IList <MDBAlbum> albums; long rowCount; { Search search = Search.None; if (filter != null) { search &= Search.FieldLike(nameof(MDBAlbum.Name), MDBSearch.Text("%" + filter + "%")); } if (albumIDs != null) { search &= Search.FieldIn(nameof(MDBAlbum.ID), albumIDs); } if (artistID != 0) { search &= Search.FieldEquals(nameof(MDBAlbum.ArtistID), artistID); } if (search.Mode == SearchMode.None) { rowCount = mdb.Albums.RowCount; } else { rowCount = mdb.Albums.Count(search); } albums = mdb.Albums.GetStructs(search, ResultOption.SortAscending(nameof(MDBAlbum.Name)) + ResultOption.Offset(page * RowsPerPage) + ResultOption.Limit(RowsPerPage)); } //join var result = albums.Select(i => RPCAlbum.Load(mdb, i)); //return webData.Result.AddMessage(webData.Method, "Retrieved Albums."); AddPagination(webData, page, rowCount); webData.Result.AddStructs(result); }
public SearchResult <T> Search(Search search) { throw new NotImplementedException(); }
static public void Main(string[] Args) { //Upgrade settings System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly(); Version appVersion = a.GetName().Version; string appVersionString = appVersion.ToString(); log.DebugFormat("Application version of new settings {0}", appVersionString); try { if (Properties.Settings.Default.ApplicationVersion != appVersion.ToString()) { log.Debug("Upgrading settings..."); Properties.Settings.Default.Upgrade(); // if program's hash has changed (e.g. by upgrading to .NET 4.0), then Upgrade() doesn't import the previous application settings // because it cannot locate a previous user.config file. In this case a new user.config file is created with the default settings. // We will try and find a config file from a previous installation and update the settings from it if (Properties.Settings.Default.ApplicationVersion == "" && Properties.Settings.Default.DoUpgrade) { SettingsUpdate.Update(); } log.DebugFormat("Settings upgraded from '{0}' to '{1}'", Properties.Settings.Default.ApplicationVersion, appVersionString); Properties.Settings.Default.ApplicationVersion = appVersionString; Settings.TrySaveSettings(); } } catch (ConfigurationErrorsException ex) { log.Error("Could not load settings.", ex); var msg = string.Format("{0}\n\n{1}", Messages.MESSAGEBOX_LOAD_CORRUPTED_TITLE, string.Format(Messages.MESSAGEBOX_LOAD_CORRUPTED, Settings.GetUserConfigPath())); var dlog = new ThreeButtonDialog(new ThreeButtonDialog.Details(SystemIcons.Error, msg, Messages.XENCENTER)) { StartPosition = FormStartPosition.CenterScreen, //For reasons I do not fully comprehend at the moment, the runtime //overrides the above StartPosition with WindowsDefaultPosition if //ShowInTaskbar is false. However it's a good idea anyway to show it //in the taskbar since the main form is not launcched at this point. ShowInTaskbar = true }; dlog.ShowDialog(); Application.Exit(); return; } // Reset statics, because XenAdminTests likes to call Main() twice. TestExceptionString = null; Exiting = false; // Clear XenConnections and History so static classes like OtherConfigAndTagsWatcher // listening to changes still work when Main is called more than once. ConnectionsManager.XenConnections.Clear(); ConnectionsManager.History.Clear(); Search.InitSearch(Branding.Search); TreeSearch.InitSearch(); ArgType argType = ArgType.None; AppDomain.CurrentDomain.UnhandledException -= CurrentDomain_UnhandledException; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Application.ThreadException -= Application_ThreadException; Application.ThreadException += Application_ThreadException; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); try { if (SystemInformation.FontSmoothingType == 2) // ClearType { TransparentUsually = SystemColors.Window; } } catch (NotSupportedException) { // Leave TransparentUsually == Color.Transparent. This is an old platform // without FontSmoothingType support. } switch (Environment.OSVersion.Version.Major) { case 6: // Vista, 2K8, Win7. if (Application.RenderWithVisualStyles) { // Vista, Win7 with styles. TitleBarStartColor = Color.FromArgb(242, 242, 242); TitleBarEndColor = Color.FromArgb(207, 207, 207); TitleBarBorderColor = Color.FromArgb(160, 160, 160); TitleBarForeColor = Color.FromArgb(60, 60, 60); HeaderGradientForeColor = Color.White; HeaderGradientFont = new Font(DefaultFont.FontFamily, 11.25f); HeaderGradientFontSmall = DefaultFont; TabbedDialogHeaderFont = HeaderGradientFont; TabPageRowBorder = Color.Gainsboro; TabPageRowHeader = Color.WhiteSmoke; } else { // 2K8, and Vista, Win7 without styles. TitleBarForeColor = SystemColors.ControlText; HeaderGradientForeColor = SystemColors.ControlText; HeaderGradientFont = new Font(DefaultFont.FontFamily, DefaultFont.Size + 1f, FontStyle.Bold); HeaderGradientFontSmall = DefaultFontBold; TabbedDialogHeaderFont = HeaderGradientFont; TabPageRowBorder = Color.DarkGray; TabPageRowHeader = Color.Silver; } break; default: TitleBarStartColor = ProfessionalColors.OverflowButtonGradientBegin; TitleBarEndColor = ProfessionalColors.OverflowButtonGradientEnd; TitleBarBorderColor = TitleBarEndColor; TitleBarForeColor = Application.RenderWithVisualStyles ? Color.White : SystemColors.ControlText; HeaderGradientForeColor = TitleBarForeColor; HeaderGradientFont = new Font(DefaultFont.FontFamily, DefaultFont.Size + 1f, FontStyle.Bold); HeaderGradientFontSmall = DefaultFontBold; TabbedDialogHeaderFont = new Font(DefaultFont.FontFamily, DefaultFont.Size + 1.75f, FontStyle.Bold); TabPageRowBorder = Color.DarkGray; TabPageRowHeader = Color.Silver; break; } // Force the current culture, to make the layout the same whatever the culture of the underlying OS (CA-46983). Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture = new CultureInfo(InvisibleMessages.LOCALE, false); if (string.IsNullOrEmpty(Thread.CurrentThread.Name)) { Thread.CurrentThread.Name = "Main program thread"; } ServicePointManager.DefaultConnectionLimit = 20; ServicePointManager.ServerCertificateValidationCallback = SSL.ValidateServerCertificate; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; XenAPI.Session.UserAgent = string.Format("XenCenter/{0}", ClientVersion()); ReconfigureConnectionSettings(); log.Info("Application started"); logSystemDetails(); OptionsDialog.Log(); if (Args.Length > 0) { log.InfoFormat("Args[0]: {0}", Args[0]); } List <string> sanitizedArgs = new List <string>(Args); // Remove the '--wait' argument, which may have been passed to the splash screen sanitizedArgs.Remove("--wait"); string[] args = null; if (sanitizedArgs.Count > 1) { argType = ParseFileArgs(sanitizedArgs, out args); if (argType == ArgType.Passwords) { log.DebugFormat("Handling password request using '{0}'", args[0]); try { PasswordsRequest.HandleRequest(args[0]); } catch (Exception exn) { log.Fatal(exn, exn); } Application.Exit(); return; } } else if (sanitizedArgs.Count == 1 && sanitizedArgs[0] == "messageboxtest") { new Dialogs.MessageBoxTest().ShowDialog(); Application.Exit(); return; } else if (sanitizedArgs.Count > 0) { log.Warn("Unrecognised command line options"); } try { ConnectPipe(); } catch (System.ComponentModel.Win32Exception exn) { log.Error("Creating named pipe failed. Continuing to launch XenCenter.", exn); } Application.ApplicationExit -= Application_ApplicationExit; Application.ApplicationExit += Application_ApplicationExit; MainWindow mainWindow = new MainWindow(argType, args); Application.Run(mainWindow); log.Info("Application main thread exited"); }