public void Sorting() { Expression<Func<Product, int>> expr = x => x.Id; var sort = new Sorting<Product, int>(expr, SortOrder.Desc); Assert.Equal(expr, sort.Expression); Assert.Equal(SortOrder.Desc, sort.SortOrder); }
protected void SetSorting(Sorting.Sorting sorting) { NavigationData navigationData = GetCurrentNavigationData(); if (navigationData == null) return; navigationData.CurrentSorting = sorting; }
public List<Product> GetProducts() { Sorting<Common.Domain.Models.Product> [] sortings = new Sorting<Common.Domain.Models.Product>[] { new Sorting<Common.Domain.Models.Product>() { SortingType = SortingType.Desc, Expression = p=>p.Name }, new Sorting<Common.Domain.Models.Product>() { SortingType = SortingType.Asc, Expression = p=>p.Description } }; var queryParams = new GeneralQueryParams<Common.Domain.Models.Product>() { WhereExpressions = null,//new Expression<Func<Common.Domain.Models.Product, bool>>[] { p => p.Name.StartsWith("fir") }, SortExpressions = sortings }; var commonProducts = new ProductsService().GetProducts("parentCat", queryParams); return commonProducts.Select(cp => new Product() { Id = cp.Id, Name = cp.Name, CategoryName = cp.Categories.Single().Name, Description = cp.Description, CreatedTime = cp.CreatedTime, Energy = cp.AttributeValues.Single(av => av.Attribute.Name == "Energy").Value }).ToList(); }
static void Main(string[] args) { int[] array = new int[] { 0, -2, 9, 3, 2, 7, 2, -4 }; int n = 20; int[] array2 = new int[n]; Random random = new Random(); for (int i = 0; i < n; i++) { array2[i] = random.Next(-100, 100); } Sorting<int> sorting = new Sorting<int>(array2); //sorting.array = new int[] { 0,4,-9,0,2,4,4,9,-9,4,2,8,2,33,24,27 }; sorting.Print(); Console.WriteLine("-----------------------------------"); sorting.SortInsertion(); sorting.Print(); Console.WriteLine("-----------------------------------"); sorting.SortBubble(); sorting.Print(); Console.WriteLine("-----------------------------------"); sorting.SortSelection(); sorting.Print(); Console.ReadLine(); }
public GameCharacter(Sorting sort, string str, int layer) : base(sort, str, layer) { BodyShape = new CircleShape(BodyRadius, 8); BodyShape.Origin = new Vector2f(BodyRadius, BodyRadius); Game.Sounds.Prepare(ref SFX_Death, "GenericHit1", 100, 0.5f); }
public DataSelectParameter(string fullName, ICondition condition, string scope, Paging paging, Sorting[] sortings) : base(fullName) { _condition = condition; _scope = scope; _paging = paging; _sortings = sortings; }
public async Task<List<ImageLink>> GetImgurLinksFromSubReddit(Reddit reddit, string sub, SearchRange searchRange, Sorting sortOrder, string outputPath, CancellationToken token) { token.ThrowIfCancellationRequested(); Subreddit subreddit = null; var links = new List<ImageLink>(); if (!string.IsNullOrWhiteSpace(sub)) { try { subreddit = reddit.GetSubreddit(sub); OutputLine($"{subreddit.Name}: Begining Search..."); } catch (Exception e) { OutputLine($"Error connecting to reddit: {e.Message}"); return links; } } if (_filter == null) _filter = string.Empty; var searchTo = DateTime.Now; var searchFrom = DateTime.Now; switch (searchRange) { case SearchRange.Today: searchFrom = searchFrom.AddDays(-1); break; case SearchRange.Week: searchFrom = searchFrom.AddDays(-7); break; case SearchRange.Fortnight: searchFrom = searchFrom.AddDays(-14); break; case SearchRange.Month: searchFrom = searchFrom.AddMonths(-1); break; case SearchRange.ThreeMonths: searchFrom = searchFrom.AddMonths(-3); break; case SearchRange.SixMonths: searchFrom = searchFrom.AddMonths(-6); break; } var search = !string.IsNullOrWhiteSpace(sub) ? searchRange == SearchRange.AllTime ? subreddit?.Search(_filter) : subreddit?.Search(searchFrom, searchTo, sortOrder) : reddit.Search<Post>(_filter); token.ThrowIfCancellationRequested(); var listings = search?.GetEnumerator(); links = CombineLinkLists(await GetImagesFromListing(reddit, listings, outputPath, token), links); return links; }
public void Test_InsertionSort() { int[] items = new int[] { 80, 60, 40, 20, 10, 30, 50, 70 }; int[] expected = new int[] { 10, 20, 30, 40, 50, 60, 70, 80 }; Sorting sorter = new Sorting(); int[] actual = sorter.InsertionSort(items); CollectionAssert.AreEqual(expected, actual); }
public void Test_QuickSortRecursive() { int[] items = new int[] { 80, 60, 120, 40, 20, 90, 100, 10, 30, 110, 50, 70 }; int[] expected = new int[] { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120 }; int length = items.Length - 1; Sorting sorter = new Sorting(); int[] actual = sorter.QuickSortRecursive(items, 0, length); CollectionAssert.AreEqual(expected, actual); }
static void Main(string[] args) { Sorting sort = new Sorting(); sort.printArray(sort.bubbleSort(sort.getActualArray())); sort.printArray(sort.gnomeSort(sort.getActualArray())); int[] array = { 1, 4, 8, 11, 15}; Sorting sorting = new Sorting(array, array.Length); sorting.printArray(sorting.bubbleSort(sorting.getArray())); sorting.printArray(sorting.gnomeSort(sorting.getArray())); Console.Read(); }
/// <summary> /// Gets the posts from the api. /// </summary> /// <param name="sorting">Current sorting</param> public async Task GetPostsAsync(Sorting sorting = Sorting.Latest) { this.currentSorting = sorting; using (var client = new RestClient("http://localhost:55298/api/")) { var request = new RestRequest("posts/{sorting}", Method.GET); request.AddUrlSegment("sorting", sorting.ToString()); var result = await client.Execute<List<Post>>(request); this.Posts = result.Data; } }
/// <summary> /// Initializes a new instance of the <see cref="OrderByClause" /> struct. /// </summary> /// <param name="field">The field.</param> public OrderByClause(string field) { FieldName = field; SortOrder = Sorting.Ascending; }
/// <summary> /// 添加Orderby /// </summary> /// <param name="sort">排序字段</param> /// <param name="order">排序方向 asc desc</param> /// <param name="expr">默认排序属性</param> /// <param name="defaultOrder">默认排序方向</param> /// <returns></returns> public IQuery <T> AutoOrderBy(string sort, string order, Expression <Func <T, object> > expr = null, Sorting defaultOrder = Sorting.Asc) { if (!string.IsNullOrEmpty(sort)) { List <PiMap> piMapList = DtoMappingHelper.GetPiMapList <T>(); if (piMapList != null && piMapList.Count > 0) { PiMap piMap = piMapList.FirstOrDefault(a => a.PiName.ToLower() == sort.ToLower() && a.IsIgnore == false); if (piMap != null) { this.orderByClauseList.Add(new OrderByClause() { FieldName = piMap.FieldName, Order = order.ToLower() == "desc" ? Sorting.Desc : Sorting.Asc }); } else { throw new Exception($"无效的排序属性{sort}"); } } } else if (expr != null) { if (defaultOrder == Sorting.Asc) { OrderBy(expr); } else { OrderByDesc(expr); } } return(this); }
/// <summary> /// Return a <see cref="Listing{T}"/> of items matching search with a given time period. /// </summary> /// <typeparam name="T"><see cref="Thing"/></typeparam> /// <param name="from">When to begin. </param> /// <param name="to">When to end. </param> /// <param name="query">string to query</param> /// <param name="subreddit">subreddit in which to search</param> /// <param name="sortE">Order by <see cref="Sorting"/></param> /// <param name="timeE">Order by <see cref="TimeSorting"/></param> /// <returns></returns> public Listing <T> SearchByTimestamp <T>(DateTimeOffset from, DateTimeOffset to, string query = "", string subreddit = "", Sorting sortE = Sorting.Relevance, TimeSorting timeE = TimeSorting.All) where T : Thing { string sort = sortE.ToString().ToLower(); string time = timeE.ToString().ToLower(); var fromUnix = from.ToUnixTimeSeconds(); var toUnix = to.ToUnixTimeSeconds(); string searchQuery = "(and+timestamp:" + fromUnix + ".." + toUnix + "+'" + query + "'+" + "subreddit:'" + subreddit + "')&syntax=cloudsearch"; return(new Listing <T>(this, string.Format(SearchUrl, searchQuery, sort, time), WebAgent)); }
public PairedTextMethod(string text, Sorting <T> method) { Text = text ?? throw new ArgumentNullException(nameof(text)); Method = method ?? throw new ArgumentNullException(nameof(method)); }
public TestAppContext(Sorting<Book>[] bookOrdenation) { BookOrdenation = bookOrdenation; }
public void AddOrderBy(Enum field, Sorting order) { this.AddOrderBy(field.ToString(), order); }
public async Task <IEnumerable <T> > GetDataAsync <T> (string tableName, DateTimeOffset from, DateTimeOffset to, IPredicate <T> filter = null, Sorting sort = Sorting.ByTime, string orgId = DataStore.DefaultOrgId, uint controllerId = 0, string field = null, bool skipNulls = true) where T : EntryBase, IDataFileFormatConverter { if (UseAzure) { return(await GetAzureTableDataAsync <T>(tableName, from, to, filter, sort, orgId, controllerId, field, skipNulls)); } if (UseDatabase) { return(await GetOdbcDatabaseDataAsync <T>(tableName, from, to, filter, sort, orgId, controllerId, field, skipNulls)); } throw new ApplicationException(); }
/// <summary> /// Creates and adds a new Oderby clause to the current query object /// </summary> /// <param name="fieldName"></param> /// <param name="order"></param> public SelectQueryBuilder OrderBy(string fieldName, Sorting order) => Query?.OrderBy(fieldName, order);
public Listing<Post> Search(string terms, Sorting sortE = Sorting.Relevance, TimeSorting timeE = TimeSorting.All) { string sort = sortE.ToString().ToLower(); string time = timeE.ToString().ToLower(); return new Listing<Post>(Reddit, string.Format(SearchUrl, Name, Uri.EscapeUriString(terms), sort, time), WebAgent); }
public void AddOrderBy(string FieldName, Sorting Order) { OrderByStatements.Add(new OrderByClause(FieldName, Order)); }
public OrderByClause(string field, Sorting order) { FieldName = field; SortOrder = order; }
public CrossTabulationClause(Column col, Sorting sortOrder) { _col = col; _sortSet = true; _sortOrder = sortOrder; }
public static void Demo() { var sort = new Sorting(); var list = new[] { 100, 50, 1, 200, 23, 15 }; foreach (var i in list) Console.Write(i + " "); //sort.Selection<int>(list, list.Length); //Console.WriteLine("\nAftert Sorting ..."); //foreach (var i in list) // Console.Write(i + " "); //sort.Insertion<int>(list, list.Length); //Console.WriteLine("\nAftert Sorting ..."); //foreach (var i in list) // Console.Write(i + " "); // // O(n) with insertion // // //var l = new[] { 1, 5, 14, 20, 30 }; //foreach (var i in l) // Console.Write(i + " "); //sort.Insertion<int>(l, l.Length); //Console.WriteLine("\nAftert Sorting ..."); //foreach (var i in l) // Console.Write(i + " "); // // //sort.MergSort<int>(list, 0, list.Length - 1); //Console.WriteLine("\nAftert Sorting ..."); //foreach (var i in list) // Console.Write(i + " "); //Console.WriteLine(); //var listForMerg = new[] { 1.8, 1.5, 0.4, 12, 3.14 , 0}; //sort.MergSort<double>(listForMerg, 0, listForMerg.Length - 1); //foreach (var i in listForMerg) // Console.Write(i + " "); //sort.Quick<int>(list, 0, list.Length); //Console.WriteLine("\nAftert Sorting ..."); //foreach (var i in list) // Console.Write(i + " "); //Console.WriteLine(); //var arr = new[] { 1, 2, 2, 1, 1, 2, 2, 1, 2, 1, 2, 1 }; //arr.ToList().ForEach(i => Console.Write(i + " ")); //Console.WriteLine(); //sort.ReallySimpleSort(arr, arr.Length); //arr.ToList().ForEach(i => Console.Write(i + " ")); //Console.WriteLine(); //var list10 = new[] { 10, 2, 1, 2, 5, 0, 10, 1, 2, 3, 4, 5 }; //list10.ToList().ForEach(i => Console.Write(i + " ")); //Console.WriteLine(); //var sorted = sort.Count(list10, list10.Length, 11); //sorted.ToList().ForEach(i => Console.Write(i + " ")); //Console.WriteLine(); //sort.Bubble(list, list.Length); //list.ToList().ForEach(i => Console.Write(i + " ")); Console.WriteLine(); var res = sort.HeapSort(list, list.Length, new PriorityQueue<int>()); res.ToList().ForEach(i => Console.Write(i + " ")); }
public IEnumerable <T> FindAll <T>(Expression <Func <T, bool> > criteria, int offset = 0, int limit = 0, Sorting <T> orderBy = null) where T : class { // Reduce invalid cache combinations if (offset < 0) { offset = 0; } if (limit < 0) { limit = 0; } var key = CacheKey(criteria, offset, limit, orderBy); IList <T> items; if (!_cache.Get(key, out items)) { items = _repository.FindAll <T>(criteria, offset, limit).ToArray(); _cache.Set(key, items); } return(items); }
public async Task <ListResult <Account> > GetList(PaginationEntry pagination, Sorting sorting, string filtering) { var query = _context.Accounts.Include(x => x.AccountType).Include(x => x.Admins).Include(x => x.Users).OrderBy(x => x.Id).AsQueryable(); // filtering if (!string.IsNullOrEmpty(filtering)) { query = query.Where(x => x.Name.Contains(filtering)); } // sorting query = query.ApplySorting(sorting, "Id", x => x.Id); query = query.ApplySorting(sorting, "name", x => x.Name); // Paging var pagedQuery = query.ApplyPaging(pagination); var result = await pagedQuery.ToListAsync(); return(new ListResult <Account>(result, result.Count)); }
public IEnumerable <T> FindAll(ISpecification <T> criteria, int offset = 0, int limit = 0, Sorting <T> orderBy = null) { return(FindAll(((Specification <T>)criteria).Predicate, offset, limit, orderBy)); }
public SortingResult Bubble([FromBody] List <int> arr) { return(Execute(() => Sorting.BubbleSort(arr))); }
private void LoadData() { dummyAnyAnimeForMonth.Visible = false; monthNow = new DateTime(MainWindow.CurrentCalendarYear, MainWindow.CurrentCalendarMonth, 1); monthMinusOne = monthNow.AddMonths(-1); monthMinusTwo = monthNow.AddMonths(-2); monthMinusThree = monthNow.AddMonths(-3); monthPlusOne = monthNow.AddMonths(1); monthPlusTwo = monthNow.AddMonths(2); monthPlusThree = monthNow.AddMonths(3); setGUIProperty("Calendar.CurrentMonth", monthNow.ToString("MMM")); setGUIProperty("Calendar.CurrentYear", monthNow.ToString("yyyy")); setGUIProperty("Calendar.MinusOneMonth", monthMinusOne.ToString("MMM")); setGUIProperty("Calendar.MinusOneYear", monthMinusOne.ToString("yyyy")); setGUIProperty("Calendar.MinusTwoMonth", monthMinusTwo.ToString("MMM")); setGUIProperty("Calendar.MinusTwoYear", monthMinusTwo.ToString("yyyy")); setGUIProperty("Calendar.MinusThreeMonth", monthMinusThree.ToString("MMM")); setGUIProperty("Calendar.MinusThreeYear", monthMinusThree.ToString("yyyy")); setGUIProperty("Calendar.PlusOneMonth", monthPlusOne.ToString("MMM")); setGUIProperty("Calendar.PlusOneYear", monthPlusOne.ToString("yyyy")); setGUIProperty("Calendar.PlusTwoMonth", monthPlusTwo.ToString("MMM")); setGUIProperty("Calendar.PlusTwoYear", monthPlusTwo.ToString("yyyy")); setGUIProperty("Calendar.PlusThreeMonth", monthPlusThree.ToString("MMM")); setGUIProperty("Calendar.PlusThreeYear", monthPlusThree.ToString("yyyy")); // find the anime for this month colAnime = JMMServerHelper.GetAnimeForMonthYear(monthNow.Month, monthNow.Year); if (colAnime.Count > 0) { dummyAnyAnimeForMonth.Visible = true; } // now sort the groups by air date List <SortPropOrFieldAndDirection> sortCriteria = new List <SortPropOrFieldAndDirection>(); sortCriteria.Add(new SortPropOrFieldAndDirection("AirDate", false, SortType.eDateTime)); colAnime = Sorting.MultiSort <AniDB_AnimeVM>(colAnime, sortCriteria); //BaseConfig.MyAnimeLog.Write(monthNow.ToString("MMM yyyy").ToUpper()); GUIControl.ClearControl(this.GetID, m_Facade.GetID); m_Facade.CurrentLayout = GUIFacadeControl.Layout.Filmstrip; int selIndex = 0; int pos = 0; foreach (AniDB_AnimeVM anime in colAnime) { //BaseConfig.MyAnimeLog.Write(anime.ToString()); string imagePath = GUIGraphicsContext.Skin + @"\Media\MyAnime3\anime3_question_poster.png"; if (anime.DefaultPosterPath.Trim().Length > 0) { if (File.Exists(anime.DefaultPosterPath)) { imagePath = anime.DefaultPosterPath; } } if (anime.AnimeID == MainWindow.GlobalSeriesID) { selIndex = pos; } pos++; GUIListItem item = new GUIListItem(); item.IconImage = item.IconImageBig = imagePath; item.TVTag = anime; item.OnItemSelected += new GUIListItem.ItemSelectedHandler(onFacadeItemSelected); m_Facade.Add(item); } if (m_Facade.Count > 0) { //BaseConfig.MyAnimeLog.Write("selIndex: {0}", selIndex.ToString()); int currentIndex = m_Facade.SelectedListItemIndex; if (selIndex >= 0 && selIndex < m_Facade.Count && selIndex != currentIndex) { int increment = (currentIndex < selIndex) ? 1 : -1; MediaPortal.GUI.Library.Action.ActionType actionType = (currentIndex < selIndex) ? MediaPortal.GUI.Library.Action.ActionType.ACTION_MOVE_RIGHT : MediaPortal.GUI.Library.Action.ActionType.ACTION_MOVE_LEFT; for (int i = currentIndex; i != selIndex; i += increment) { m_Facade.OnAction(new MediaPortal.GUI.Library.Action(actionType, 0, 0)); } } m_Facade.SelectedListItemIndex = selIndex; AniDB_AnimeVM anime = m_Facade.SelectedListItem.TVTag as AniDB_AnimeVM; if (anime != null) { SetAnime(anime); } } // set the focus button btnCurrentPlusOne.Focus = false; switch (MainWindow.CurrentCalendarButton) { case 3: btnCurrentMinusOne.Focus = true; break; case 4: btnCurrentPlusOne.Focus = true; break; } }
public void Test() { int[] a1 = { 4, 5, 23, 7, 545, 7676, 34, 45, 7, 9, 1, 3, 878, 7, -1, 23, -9, 0, 5 }; int[] a2 = { }; int[] a3 = { 1 }; int[] a4 = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; int[] a5 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int[] a6 = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4 }; int[] a7 = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, 11 }; string[] s1 = { "A", "a", "abcde", "abced", "ABCDE", "", "0", "A" }; Console.WriteLine("-------SELECTION SORT"); Console.WriteLine(Sorting.SelectionSort(a1)); Console.WriteLine(Sorting.SelectionSort(a2)); Console.WriteLine(Sorting.SelectionSort(a3)); Console.WriteLine(Sorting.SelectionSort(a4)); Console.WriteLine(Sorting.SelectionSort(a5)); Console.WriteLine(Sorting.SelectionSort(a6)); Console.WriteLine(Sorting.SelectionSort(a7)); Console.WriteLine(Sorting.SelectionSort(s1)); Console.WriteLine("-------INSERTION SORT"); Console.WriteLine(Sorting.InsertionSort(a1)); Console.WriteLine(Sorting.InsertionSort(a2)); Console.WriteLine(Sorting.InsertionSort(a3)); Console.WriteLine(Sorting.InsertionSort(a4)); Console.WriteLine(Sorting.InsertionSort(a5)); Console.WriteLine(Sorting.InsertionSort(a6)); Console.WriteLine(Sorting.InsertionSort(a7)); Console.WriteLine(Sorting.InsertionSort(s1)); Console.WriteLine("-------BUBBLE SORT"); Console.WriteLine(Sorting.BubbleSort(a1)); Console.WriteLine(Sorting.BubbleSort(a2)); Console.WriteLine(Sorting.BubbleSort(a3)); Console.WriteLine(Sorting.BubbleSort(a4)); Console.WriteLine(Sorting.BubbleSort(a5)); Console.WriteLine(Sorting.BubbleSort(a6)); Console.WriteLine(Sorting.BubbleSort(a7)); Console.WriteLine(Sorting.BubbleSort(s1)); Console.WriteLine("-------QUICK SORT"); Console.WriteLine(Sorting.QuickSort(a1)); Console.WriteLine(Sorting.QuickSort(a2)); Console.WriteLine(Sorting.QuickSort(a3)); Console.WriteLine(Sorting.QuickSort(a4)); Console.WriteLine(Sorting.QuickSort(a5)); Console.WriteLine(Sorting.QuickSort(a6)); Console.WriteLine(Sorting.QuickSort(a7)); Console.WriteLine(Sorting.QuickSort(s1)); Console.WriteLine("-------MERGE SORT"); Console.WriteLine(Sorting.MergeSort(a1)); Console.WriteLine(Sorting.MergeSort(a2)); Console.WriteLine(Sorting.MergeSort(a3)); Console.WriteLine(Sorting.MergeSort(a4)); Console.WriteLine(Sorting.MergeSort(a5)); Console.WriteLine(Sorting.MergeSort(a6)); Console.WriteLine(Sorting.MergeSort(a7)); Console.WriteLine(Sorting.MergeSort(s1)); Console.WriteLine("-------HEAP SORT"); Console.WriteLine(Sorting.HeapSort(a1)); Console.WriteLine(Sorting.HeapSort(a2)); Console.WriteLine(Sorting.HeapSort(a3)); Console.WriteLine(Sorting.HeapSort(a4)); Console.WriteLine(Sorting.HeapSort(a5)); Console.WriteLine(Sorting.HeapSort(a6)); Console.WriteLine(Sorting.HeapSort(a7)); Console.WriteLine(Sorting.HeapSort(s1)); }
/// <summary> /// Constructor /// </summary> /// <param name="field">The field being ordered</param> /// <param name="order">The sorting direction of the field</param> public OrderByClause(string field, Sorting order) { this.FieldName = field; this.SortOrder = order; }
public async Task <IActionResult> Index(string sort) { EntriesViewModel viewModel = new EntriesViewModel(); IQueryable <Entry> dbQuery; if (signInManager.IsSignedIn(User)) { viewModel.SignedIn = true; viewModel.CurrentUser = await userManager.GetUserAsync(User); dbQuery = context.GetUnhiddenPostsQuery(viewModel.CurrentUser); } else { viewModel.SignedIn = false; dbQuery = context.GetPostsQuery(); } var ticksNow = DateTime.Now.Ticks; if (sort != null) { sort = sort.ToLower(); } switch (sort) { case "hot": viewModel.Sort = EntriesViewModel.SortType.Hot; viewModel.Entries = await dbQuery.ToListAsync(); viewModel.Entries.Sort((x, y) => Sorting.HotScore(y, ticksNow).CompareTo(Sorting.HotScore(x, ticksNow))); break; case "new": viewModel.Sort = EntriesViewModel.SortType.New; viewModel.Entries = await dbQuery .OrderByDescending(p => p.DateCreated) .ToListAsync(); break; case "controversial": viewModel.Sort = EntriesViewModel.SortType.Controversial; viewModel.Entries = await dbQuery.ToListAsync(); viewModel.Entries.Sort((x, y) => Sorting.ControversyScore(y).CompareTo(Sorting.ControversyScore(x))); break; case "top": viewModel.Sort = EntriesViewModel.SortType.Top; viewModel.Entries = await dbQuery .OrderByDescending(p => p.VoteScore) .ToListAsync(); break; default: viewModel.Sort = EntriesViewModel.SortType.Hot; viewModel.Entries = await dbQuery.ToListAsync(); viewModel.Entries.Sort((x, y) => Sorting.HotScore(y, ticksNow).CompareTo(Sorting.HotScore(x, ticksNow))); break; } return(View("Entries", viewModel)); }
/// <summary> /// Return a <see cref="Listing{T}"/> of items matching search with a given time period. /// </summary> /// <typeparam name="T"><see cref="Thing"/></typeparam> /// <param name="from">When to begin. </param> /// <param name="to">When to end. </param> /// <param name="query">string to query</param> /// <param name="subreddit">subreddit in which to search</param> /// <param name="sortE">Order by <see cref="Sorting"/></param> /// <param name="timeE">Order by <see cref="TimeSorting"/></param> /// <returns></returns> public Listing <T> SearchByTimestamp <T>(DateTime from, DateTime to, string query = "", string subreddit = "", Sorting sortE = Sorting.Relevance, TimeSorting timeE = TimeSorting.All) where T : Thing { return(SearchByTimestamp <T>(new DateTimeOffset(from), new DateTimeOffset(to), query, subreddit, sortE, timeE)); }
public OrderByStatement(string field, Sorting order) { this.Add(new OrderByClause(field, order)); }
/// <inheritdoc /> public async Task <LazyLoadedResult <DeviceModel> > GetAll(FilteringModel filter, LazyLoadParameters lazyLoadFilters, Sorting sorting, string token) { var resultLazy = new LazyLoadedResult <DeviceModel>(); var deviceList = new List <DeviceModel>(); var companyId = await _validationHelper.GetCompanyIdByPermission(token, new [] { Const.Permissions.Device.AdminRead }); List <TenantFullModel> tenants = new List <TenantFullModel>(); if (companyId != null) { filter.CompanyIds = new List <int> { companyId.Value }; var tenant = await _httpService.GetTenantSingleByCompanyId(companyId.Value, token); tenants.Add(tenant); } else { if (filter.TenantIds.Any()) { var tenantIdsString = filter.TenantIds.Select(x => x.ToString()).ToList(); tenants = await _httpService.GetTenantsByIds(token, GetQuery("TenantIds", tenantIdsString)); var companyIds = tenants.SelectMany(x => x.Companies).Select(x => x.Id).ToList(); filter.CompanyIds = filter.CompanyIds != null ? companyIds.Count > 0 ? filter.CompanyIds.Intersect(companyIds).ToList() : null : companyIds; } else { tenants = await _httpService.GetTenantsByIds(token); } } var devices = await _deviceRepository.GetWithoutIncludeAsync(GetFilterExpression(filter)); var devicesHistories = await _deviceHistoryRepository.GetAsync(); if (!devices.Any()) { return(resultLazy); } var compIds = (from device in devices select device.CompanyId.ToString()).ToList(); var branchIds = (from device in devices select device.BranchId.ToString()).ToList(); var deviceAndLastHistoryQuery = (from device in devices from history in devicesHistories.Where(x => x.DeviceId == device.Id).OrderByDescending(x => x.CreatedOn).Take(1) select new { Device = device, LastHistory = history }); var usersIds = deviceAndLastHistoryQuery.Where(x => x.LastHistory.LoggedInUserId.HasValue).Select(x => x.LastHistory.LoggedInUserId.ToString().ToLower()).Distinct().ToList(); //var companies = await _httpService.GetCompaniesByIds(GetQuery("CompanyIds", compIds), token); var companyTenant = tenants.SelectMany(tenant => tenant.Companies, (tenant, company) => new { Company = company, Tenant = tenant }); var branches = await _httpService.GetBranchesByIds(GetQuery("BranchIds", branchIds), token); var users = await _httpService.GetUsersByIdsAsync(token, GetQuery("UsersId", usersIds)); var fdeviceList = (from deviceInfo in deviceAndLastHistoryQuery join company in companyTenant on deviceInfo.Device.CompanyId equals company.Company.Id into _c from company in _c.DefaultIfEmpty() join branch in branches on deviceInfo.Device.BranchId equals branch.Id into _b from branch in _b.DefaultIfEmpty() join user in users on deviceInfo.LastHistory.LoggedInUserId equals user.Id into _u from user in _u.DefaultIfEmpty() select new DeviceModel { Id = deviceInfo.Device.Id, Udid = deviceInfo.Device.Udid, CreatedOn = deviceInfo.Device.CreatedOn, HexnodeUdid = deviceInfo.Device.HexnodeUdid, DeviceName = deviceInfo.Device.DeviceName, IsPending = deviceInfo.Device.IsPending, Latitude = deviceInfo.Device.Latitude, Longitude = deviceInfo.Device.Longitude, Radius = deviceInfo.Device.Radius, IsDeleted = deviceInfo.Device.IsDeleted, IsOnline = deviceInfo.LastHistory.IsOnline, IsInLocation = deviceInfo.LastHistory.IsInLocation, StatusSince = deviceInfo.LastHistory.CreatedOn, Branch = branch, Company = company.Company, Tenant = company.Tenant.Adapt <TenantModel>(), LoggedInAs = user, Phone = deviceInfo.Device.Phone, CurrentDeviceLocationLatitude = deviceInfo.LastHistory.CurrentDeviceLocationLatitude, CurrentDeviceLocationLongitude = deviceInfo.LastHistory.CurrentDeviceLocationLongitude, }); resultLazy = GetSorted(fdeviceList, sorting).GetPart(lazyLoadFilters); return(resultLazy); }
public void Add(string field, Sorting order) { this.Add(new OrderByClause(field, order)); }
public Listing <Post> Search(DateTime from, DateTime to, Sorting sortE) { string sort = sortE.ToString().ToLower(); return(new Listing <Post>(Reddit, string.Format(SearchUrlDate, Name, from.DateTimeToUnixTimestamp(), to.DateTimeToUnixTimestamp(), sort), WebAgent)); }
/// <summary> /// 添加 ORDER BY 从句 /// </summary> /// <param name="field">字段名枚举</param> /// <param name="order">排序</param> public void AddOrderBy(Enum field, Sorting order) { this.AddOrderBy(field.ToString(), order); }
/// <summary> /// Initializes a new instance of the <see cref="OrderByClause" /> struct. /// </summary> /// <param name="field">The field.</param> /// <param name="order">The order.</param> public OrderByClause(string field, Sorting order) { FieldName = field; SortOrder = order; }
/// <summary> /// 添加 ORDER BY 从句 /// </summary> /// <param name="field">字段名</param> /// <param name="order">排序</param> public void AddOrderBy(string field, Sorting order) { OrderByClause NewOrderByClause = new OrderByClause(field, order); _orderByStatement.Add(NewOrderByClause); }
public Listing<Post> Search(DateTime from, DateTime to, Sorting sortE = Sorting.New) { string sort = sortE.ToString().ToLower(); return new Listing<Post>(Reddit, string.Format(SearchUrlDate, Name, from.DateTimeToUnixTimestamp(), to.DateTimeToUnixTimestamp(), sort), WebAgent); }
public GameObject(Sorting sort, string str, int layer = 0) { Layer = layer; Group = (Sorting.Group == sort) ? str : null; Tag = (Sorting.Tag == sort) ? str : null; }
public IEnumerable <T> FindAll(Expression <Func <T, bool> > criteria, int offset = 0, int limit = 0, Sorting <T> orderBy = null) { // Reduce invalid cache combinations if (offset < 0) { offset = 0; } if (limit < 0) { limit = 0; } var key = _cache.CacheKey(criteria, offset, limit, orderBy, _paths); IList <T> items; if (!_cache.Cache.Get(key, out items)) { items = _service.FindAll(criteria, offset, limit, orderBy).ToArray(); _cache.Cache.Set(key, items); } return(items); }
// If the suppressActions parameter is set to <c>true</c>, no actions will be built. Instead, they will be inherited from // the parent navigation step. That is used for subview navigation where the navigation step doesn't produce own // workflow actions. protected NavigationData(NavigationData parent, string navigationContextName, Guid parentWorkflowStateId, Guid currentWorkflowStateId, ViewSpecification baseViewSpecification, AbstractScreenData defaultScreen, ICollection<AbstractScreenData> availableScreens, Sorting.Sorting currentSorting, bool suppressActions) { _parent = parent; _navigationContextName = navigationContextName; _currentWorkflowStateId = currentWorkflowStateId; _baseWorkflowStateId = parentWorkflowStateId; _baseViewSpecification = baseViewSpecification; _currentScreenData = defaultScreen; _availableScreens = availableScreens ?? new List<AbstractScreenData>(); _currentSorting = currentSorting; if (suppressActions) _dynamicWorkflowActions = null; else BuildWorkflowActions(); }
private string CacheKey <T>(Expression <Func <T, bool> > predicate = null, int offset = 0, int limit = 0, Sorting <T> orderBy = null, IEnumerable <Expression> paths = null) { var identity = new StringBuilder(); if (predicate != null) { Expression expression = predicate; // locally evaluate as much of the query as possible expression = Evaluator.PartialEval(expression); // support local collections expression = LocalCollectionExpander.Rewrite(expression); identity.Append(expression); } else { identity.Append("All"); } if (offset > 0) { identity.AppendFormat("|offset:{0}", offset); } if (limit > 0) { identity.AppendFormat("|limit:{0}", limit); } if (orderBy != null) { identity.AppendFormat("|orderby:{0}", orderBy); } if (paths != null) { var includes = new SortedSet <string>(); foreach (var path in paths) { includes.Add(path.ToString()); } identity.AppendFormat("|includes:[{0}]", string.Join(",", includes)); } var hash = ComputeHash(identity.ToString()); return(string.Concat(typeof(T).FullName, "/", GetGeneration <T>(), "/", hash)); }
public ListBoxBase(c000069 p0) : base(p0) { this.f00005b = new List<c000112>(); this.f000078 = new List<c000112>(); this.f000001 = enum078.f000001; this.f00088a = new c000043<c00006c>(); this.f000056 = false; this.f000057 = false; this.f00000f = -1; this.f0000a0 = false; this.f0000a1 = false; this.f000156 = Sorting.f000156; this.f0000f1 = 1.4f; this.f0000f2 = -1f; this.f0000a2 = true; this.f00088b = new List<Keys>(); this.f000038 = new c000075(); this.f000038.m000143(base.m00014b() - (0.0001f * c000076.f000066.Z)); this.f000017 = new c00007c(base.f000029); this.m000097(this.f000017); this.m00036a(); }
public virtual async Task <IEnumerable <T> > GetAll(Filtering filters, Sorting sorting, Paging paging) { return(await dbSet.ToListAsync()); }
public OrderByClause(string field) { FieldName = field; SortOrder = Sorting.Ascending; }
public void Populate(JMMServerBinary.Contract_AniDB_AnimeDetailed contract, int animeID) { AnimeID = animeID; AnimeTitles = new List <AnimeTitleVM>(); AnimeTitlesSummary = new List <AnimeTitleVM>(); AnimeTitlesMain = new List <AnimeTitleVM>(); AnimeTitlesOfficial = new List <AnimeTitleVM>(); AnimeTitlesSynonym = new List <AnimeTitleVM>(); AnimeTitlesShort = new List <AnimeTitleVM>(); AnimeTags = new List <AnimeTagVM>(); AnimeTagsSummary = new List <AnimeTagVM>(); CustomTags.Clear(); try { AniDB_Anime = new AniDB_AnimeVM(contract.AniDBAnime); UserVote = null; if (contract.UserVote != null) { UserVote = new AniDB_VoteVM(contract.UserVote); } UserHasVoted = UserVote != null; UserHasNotVoted = UserVote == null; if (UserVote == null) { UserRating = 0; } else { UserRating = UserVote.VoteValue; } UserRatingFormatted = Utils.FormatAniDBRating((double)UserRating); if (UserVote != null) { UserRatingFormatted += " ("; if (UserVote.VoteType == 1) { UserRatingFormatted += Properties.Resources.VoteTypeAnimePermanent; } if (UserVote.VoteType == 2) { UserRatingFormatted += Properties.Resources.VoteTypeAnimeTemporary; } UserRatingFormatted += ")"; } this.Stat_AllVideoQuality = new HashSet <string>(contract.Stat_AllVideoQuality); this.Stat_AllVideoQuality_Episodes = new HashSet <string>(contract.Stat_AllVideoQuality_Episodes); this.Stat_AudioLanguages = new HashSet <string>(contract.Stat_AudioLanguages); this.Stat_SubtitleLanguages = new HashSet <string>(contract.Stat_SubtitleLanguages); foreach (JMMServerBinary.Contract_AnimeTag tag in contract.Tags) { AnimeTagVM vtag = new AnimeTagVM(tag); AnimeTags.Add(vtag); } //AnimeTags.Sort(); List <SortPropOrFieldAndDirection> sortCriteria = new List <SortPropOrFieldAndDirection>(); sortCriteria.Add(new SortPropOrFieldAndDirection("Weight", true, SortType.eInteger)); AnimeTags = Sorting.MultiSort <AnimeTagVM>(AnimeTags, sortCriteria); int i = 0; /* * foreach (AnimeTagVM tag in AnimeTags) * { * if (i <= 5) * AnimeTagsSummary.Add(tag); * else * break; * i++; * } */ foreach (JMMServerBinary.Contract_CustomTag ctag in contract.CustomTags) { CustomTagVM vtag = new CustomTagVM(ctag); CustomTags.Add(vtag); } CustomTags.Sort(); ViewCustomTags.Refresh(); foreach (JMMServerBinary.Contract_AnimeTitle title in contract.AnimeTitles) { AnimeTitleVM vtitle = new AnimeTitleVM(title); AnimeTitles.Add(vtitle); if (title.TitleType.Trim().ToUpper() == Constants.AnimeTitleType.Main.ToUpper()) { AnimeTitlesMain.Add(vtitle); } if (title.TitleType.Trim().ToUpper() == Constants.AnimeTitleType.Official.ToUpper()) { AnimeTitlesOfficial.Add(vtitle); } if (title.TitleType.Trim().ToUpper() == Constants.AnimeTitleType.Synonym.ToUpper()) { AnimeTitlesSynonym.Add(vtitle); } if (title.TitleType.Trim().ToUpper() == Constants.AnimeTitleType.ShortName.ToUpper()) { AnimeTitlesShort.Add(vtitle); } } i = 0; foreach (AnimeTitleVM title in AnimeTitlesOfficial) { if (i <= 5) { AnimeTitlesSummary.Add(title); } else { break; } i++; } } catch (Exception ex) { Utils.ShowErrorMessage(ex); } }
Init( IList <double> t, IList <double> x ) { if (null == t) { throw new ArgumentNullException("t"); } if (null == x) { throw new ArgumentNullException("x"); } if (t.Count < 5) { throw new ArgumentOutOfRangeException("t"); } if (t.Count != x.Count) { throw new ArgumentException(Properties.Resources.ArgumentVectorsSameLengths, "x"); } int n = t.Count; double[] tt = new double[n]; t.CopyTo(tt, 0); double[] xx = new double[n]; x.CopyTo(xx, 0); Sorting.Sort(tt, xx); // Prepare W (weights), Diff (divided differences) double[] w = new double[n - 1]; double[] diff = new double[n - 1]; for (int i = 0; i < diff.Length; i++) { diff[i] = (xx[i + 1] - xx[i]) / (tt[i + 1] - tt[i]); } for (int i = 1; i < w.Length; i++) { w[i] = Math.Abs(diff[i] - diff[i - 1]); } // Prepare Hermite interpolation scheme double[] d = new double[n]; for (int i = 2; i < d.Length - 2; i++) { if (!Number.AlmostZero(w[i - 1]) || !Number.AlmostZero(w[i + 1])) { d[i] = (w[i + 1] * diff[i - 1] + w[i - 1] * diff[i]) / (w[i + 1] + w[i - 1]); } else { d[i] = ((tt[i + 1] - tt[i]) * diff[i - 1] + (tt[i] - tt[i - 1]) * diff[i]) / (tt[i + 1] - tt[i - 1]); } } d[0] = DifferentiateThreePoint(tt[0], tt[0], xx[0], tt[1], xx[1], tt[2], xx[2]); d[1] = DifferentiateThreePoint(tt[1], tt[0], xx[0], tt[1], xx[1], tt[2], xx[2]); d[n - 2] = DifferentiateThreePoint(tt[n - 2], tt[n - 3], xx[n - 3], tt[n - 2], xx[n - 2], tt[n - 1], xx[n - 1]); d[n - 1] = DifferentiateThreePoint(tt[n - 1], tt[n - 3], xx[n - 3], tt[n - 2], xx[n - 2], tt[n - 1], xx[n - 1]); // Build Akima spline using Hermite interpolation scheme _hermiteSpline.InitInternal(tt, xx, d); }
public QueryRequest GetPageTypeInstancesQueryRequest(Guid pageTypeId, Guid languageId, SecurityToken token) { // Set up page query. var request = new QueryRequest(languageId, CmsSearchDomains.Pages, token); // Set pagetype. request.FilterTags.Add(new Tag(TagNames.PageTypeId, pageTypeId)); // Only published pages. request.FilterTags.Add(new Tag(TagNames.IsPublished, true)); // Sort order. Sorting sorting = new Sorting(TagNames.PageIndex, SortingFieldType.Int); request.Sortings.Add(sorting); // Fetch many. request.Paging = new Paging(1, 999999); return request; }
public async Task <IActionResult> WebDataDownloadAsync <T> (string table, string title, string orgId, uint controllerId, DateTimeOffset?from = null, DateTimeOffset?to = null, Sorting sort = Sorting.ByTime, IPredicate <T> filter = null, DataFileFormats format = DataFileFormats.JSON, double timezone = 0.0) where T : EntryBase, IDataFileFormatConverter { IEnumerable <T> data; try { (from, to) = Utils.ProcessDateTimeRange(from, to); using (var db = new ConfigDB()) { using (var ana = new AnalyticsEngine(db)) { data = await ana.GetDataAsync <T>(table, from.Value, to.Value, filter, sort, orgId, controllerId); if (data == null) { return(NotFound()); } } } } catch (ArgumentException ex) { return(BadRequest(ex.ToString())); } // Encode result string[] headers = null; string filename = "data"; if (format != DataFileFormats.JSON) { if (typeof(T) == typeof(EventX)) { headers = EventX.Headers; filename = "events"; } else if (typeof(T) == typeof(AlarmX)) { headers = AlarmX.Headers; filename = "alarms"; } else if (typeof(T) == typeof(AuditTrailX)) { headers = AuditTrailX.Headers; filename = "audit"; } else if (typeof(T) == typeof(CycleDataX)) { headers = CycleDataX.Headers.Concat((data as IEnumerable <CycleDataX>).SelectMany(x => x.Data.Keys).Distinct()).ToArray(); filename = "cycledata"; } else { throw new ApplicationException(); } } switch (format) { case DataFileFormats.JSON: return(Json(data)); case DataFileFormats.CSV: return(Content(DataFileGenerator.BuildCSVFile(headers, data, timezone), "text/csv", Encoding.UTF8)); case DataFileFormats.TSV: return(Content(DataFileGenerator.BuildCSVFile(headers, data, timezone, "\t", false), "text/csv", Encoding.UTF8)); case DataFileFormats.XLS: case DataFileFormats.XLSX: { IWorkbook xls; string mime; string ext; switch (format) { case DataFileFormats.XLS: xls = new HSSFWorkbook(); ext = ".xls"; mime = "application/vnd.ms-excel"; break; case DataFileFormats.XLSX: xls = new XSSFWorkbook(); ext = ".xlsx"; mime = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; break; default: throw new ApplicationException(); } using (var stream = new MemoryStream()) { DataFileGenerator.BuildXLSFile(stream, xls, title, headers, data, timezone); var filedata = stream.ToArray(); return(File(filedata, mime, filename + ext)); } } default: throw new ApplicationException(); } }
public IActionResult Index([Bind("SearchName")] Filtering makeFiltering, Sorting sorting, Paging paging) { if (paging.PageNumber == 1) { ViewBag.OrderBy = sorting.OrderBy == "DESC" ? "ASC" : "DESC"; CurrentOrder = sorting.OrderBy; CurrentSort = sorting.SortBy; } if (String.IsNullOrEmpty(sorting.SortBy)) { sorting.SortBy = "Name"; sorting.OrderBy = "ASC"; } paging.TotalPages = MakeService.CountMakers(); CurrentPage = paging.PageNumber; ElementsGot = paging.Elements; #region HasNextButton if ((ElementsGot + NumberOfElements) < paging.TotalPages) { ViewBag.HasNext = true; } else { ViewBag.HasNext = false; } #endregion #region HasPrevButton if (paging.HasPreviousPage) { ViewBag.HasPrevious = true; } else { ViewBag.HasPrevious = false; } #endregion #region Search if (!String.IsNullOrEmpty(makeFiltering.SearchName)) { if (!MakeService.HasNameInDatabase(makeFiltering.SearchName)) { return(NotFound(makeFiltering.SearchName + " not Found")); } string countQuery = String.Format("SELECT * FROM dbo.VehicleMakers Where Name = '{0}'", makeFiltering.SearchName); paging.TotalPages = MakeService.GetVehicleMakes(countQuery).Count(); ElementsGot = 0; string searchQuery = String.Format("SELECT * FROM dbo.VehicleMakers Where Name = '{0}' ORDER BY {1} {2} OFFSET {3} ROWS FETCH NEXT {4} ROWS ONLY", makeFiltering.SearchName, sorting.SortBy, sorting.OrderBy, ElementsGot, NumberOfElements); var searchMake = MakeService.GetVehicleMakes(searchQuery).Select(Mapper.Map <VehicleMakeDTO>); #region HasNextButton if ((ElementsGot + NumberOfElements) < paging.TotalPages) { ViewBag.HasNext = true; } else { ViewBag.HasNext = false; } #endregion #region HasPrevButton if (paging.HasPreviousPage) { ViewBag.HasPrevious = true; } else { ViewBag.HasPrevious = false; } #endregion return(View(searchMake)); } #endregion string query = String.Format("SELECT * FROM dbo.VehicleMakers ORDER BY {0} {1} OFFSET {2} ROWS FETCH NEXT {3} ROWS ONLY", sorting.SortBy, sorting.OrderBy, ElementsGot, NumberOfElements); var make = MakeService.GetVehicleMakes(query).Select(Mapper.Map <VehicleMake, VehicleMakeDTO>); return(View(make)); }
public void AddOrderBy(string field, Sorting order) { OrderByClause NewOrderByClause = new OrderByClause(field, order); _orderByStatement.Add(NewOrderByClause); }
/// <summary> /// Creates a new navigation data structure for a new media navigation step. /// </summary> /// <param name="parent">Parent navigation data, this navigation data is derived from.</param> /// <param name="navigationContextName">Name, which is used for the corresponding workflow navigation context.</param> /// <param name="currentWorkflowStateId">Id of the workflow state which corresponds to the new media navigation step.</param> /// <param name="parentWorkflowStateId">Id of the workflow state to which the workflow navigation should be reverted when /// another filter is choosen.</param> /// <param name="baseViewSpecification">View specification for the media items of the new media navigation step.</param> /// <param name="defaultScreen">Screen which should present the new navigation step by default.</param> /// <param name="availableScreens">Available set of screen descriptions which can present the new media navigation step.</param> /// <param name="currentSorting">Denotes the current sorting for the items to be shown. If this is set to <c>null</c>, /// default sorting will be applied.</param> public NavigationData(NavigationData parent, string navigationContextName, Guid parentWorkflowStateId, Guid currentWorkflowStateId, ViewSpecification baseViewSpecification, AbstractScreenData defaultScreen, ICollection<AbstractScreenData> availableScreens, Sorting.Sorting currentSorting) : this(parent, navigationContextName, parentWorkflowStateId, currentWorkflowStateId, baseViewSpecification, defaultScreen, availableScreens, currentSorting, false) { }
/// <summary> /// Get the topN items for each user /// </summary> /// <param name="topN"></param> /// <returns>Dictionary with user index as the key and top N items /// as the values for this user.</returns> public Dictionary <int, List <int> > GetTopNItemsByUser(int topN) { int userCount = this.UserCount; int itemCount = this.ItemCount; Dictionary <int, List <int> > topNItemsByUser = new Dictionary <int, List <int> >(userCount); Dictionary <int, List <int> > topNItemsByUserNew = new Dictionary <int, List <int> >(userCount); // Compute the topN list for each user Object lockMe = new Object(); Parallel.ForEach(preferenceRelations, pair => { // topN stores the top N item IDs and positions Dictionary <int, double> topNItems = new Dictionary <int, double>(topN); int userIndex = pair.Key; Utils.PrintEpoch("Get topN items for user/total", userIndex, userCount); SparseMatrix userPreferences = pair.Value; #region The old correct but slow version /* * * // Compute the position of each item * double minPosition = double.MinValue; * int min_iid = int.MinValue; * double maxPosition = 0.0; * foreach (Tuple<int, Vector<double>> row in userPreferences.EnumerateRowsIndexed()) * { * int iid = row.Item1; * SparseVector preferences = SparseVector.OfVector(row.Item2); * // TODO: check it, I expect the best item to have the highest position * int preferredCount = 0; * int lessPreferredCount = 0; * foreach (double preference in preferences.Enumerate(Zeros.AllowSkip)) * { * if (preference == Config.Preferences.Preferred) ++preferredCount; * else if (preference == Config.Preferences.LessPreferred) ++lessPreferredCount; * } * double iid_position = (double)(lessPreferredCount-preferredCount)/preferences.NonZerosCount; * if (iid_position > maxPosition) maxPosition = iid_position; * // All items are added into the topN list if it is not full * // otherwise the least positioned item will be replaced * if (topNItems.Count < topN) * { * topNItems[iid] = iid_position; * if (topNItems.Count == topN) * { * min_iid = topNItems.Aggregate((l, r) => l.Value < r.Value ? l : r).Key; * minPosition = topNItems[min_iid]; * } * } * else if (iid_position > minPosition) * { * // Replace the least positioned item * topNItems.Remove(min_iid); * // Add the current item * topNItems[iid] = iid_position; * * // Find the item with least position * min_iid = topNItems.Aggregate((l, r) => l.Value < r.Value ? l : r).Key; * minPosition = topNItems[min_iid]; * } * * if (iid == 21 && userIndex == 0) * { * Console.WriteLine("Position of 21 = " + iid_position); * } * if (iid == 141 && userIndex == 0) * { * int a = preferenceRelations[userIndex].Row(141).Count(x=>x==Config.Preferences.Preferred?true:false); * int b =preferenceRelations[userIndex].Row(141).Count(x => x == Config.Preferences.LessPreferred? true : false); * int c = a - b; * Console.WriteLine("Position of 141 = " + iid_position); * } * } * * // Get the keys (iid) in the topN list sorted by positions * List<int> sortedItems = new List<int>(from entry in topNItems orderby entry.Value ascending select entry.Key); * lock (lockMe) * { * topNItemsByUser[userIndex] = sortedItems; * } */ #endregion // This gives me an array of how many preferred for each item Vector <double> preferredCountByItem = DenseVector.OfArray( userPreferences.FoldByRow((count, rating) => count + (rating == Config.Preferences.Preferred ? 1 : 0), 0.0)); Vector <double> lessPreferredCountByItem = DenseVector.OfArray( userPreferences.FoldByRow((count, rating) => count + (rating == Config.Preferences.LessPreferred ? 1 : 0), 0.0)); Vector <double> equallyPreferredCountByItem = DenseVector.OfArray( userPreferences.FoldByRow((count, rating) => count + (rating == Config.Preferences.EquallyPreferred ? 1 : 0), 0.0)); List <double> positionByItem = (preferredCountByItem - lessPreferredCountByItem).PointwiseDivide( lessPreferredCountByItem + preferredCountByItem + equallyPreferredCountByItem ).ToList(); List <int> itemIndexSortedByPosition = Enumerable.Range(0, positionByItem.Count).ToList(); Sorting.Sort(positionByItem, itemIndexSortedByPosition); positionByItem.Reverse(); // This is now the sorted position values itemIndexSortedByPosition.Reverse(); // This is now the the item index sorted by position // LINQ version //var sorted = positionByItem // .Select((x, i) => new KeyValuePair<double, int>(x, i)) //.OrderBy(x => x.Key) //.ToList(); //List<double> B = sorted.Select(x => x.Key).ToList(); //List<int> idx = sorted.Select(x => x.Value).ToList(); lock (lockMe) { topNItemsByUserNew[userIndex] = itemIndexSortedByPosition.GetRange(0, topN); // The corresponding top N position values are in positionByItem.GetRange(0, topN); } }); return(topNItemsByUser); }
public void m0003ca(Sorting p0) { if (p0 != this.f000156) { this.f000156 = p0; if (p0 == Sorting.f000157) { this.m0003af(); } } }
public Branch[] BranchAndBound(int sampleSize, int iterations, double confidenceLevel = 0.95, bool cullDuplicates = true, bool multiThread = true) { // Sanity check the initial sample size if (sampleSize < 30) { throw new ArgumentOutOfRangeException("Sample size must be at least 30."); } BestFitnessObserved = double.PositiveInfinity; double branchingFactor = 0; // Keeps track of average branches per active region per layer, which may not be constant if there is overlap between regions //double BestObservedValue = double.PositiveInfinity; Branch[] activeBranches = new Branch[] { SolutionSpace }; //List<Branch> discardedRegions = new List<Branch>(512); // Tentative // === Main Loop === for (int iteration = 0; iteration < iterations; iteration++) { Console.WriteLine($"On iteration {iteration + 1} of {iterations}"); #region Branch Step var newActiveBranches = new List <Branch>(); foreach (Branch branch in activeBranches) { if (branch != null) { newActiveBranches.AddRange(branch.GetBranches()); } } Program.logger.WriteLine($"Branched to produce {newActiveBranches.Count} new regions."); // Cull duplicates if desired if (cullDuplicates) { for (int i = 1; i < newActiveBranches.Count; i++) { for (int j = 0; j < i; j++) { if (newActiveBranches[i].Equals(newActiveBranches[j])) { newActiveBranches.RemoveAt(i); i--; break; } } } Program.logger.WriteLine($"Duplicates culled. {newActiveBranches.Count} regions remain."); } // Update branching factor branchingFactor = (branchingFactor * iteration + newActiveBranches.Count / activeBranches.Length) / (iteration + 1); Program.logger.WriteLine($"Branching factor revised to {branchingFactor}"); activeBranches = newActiveBranches.ToArray(); // Storage for the estimating distribution of the guiding parameter of each branch var negatedDistributions = new IDistributionWrapper[activeBranches.Length]; #endregion #region Sampling // --- Sample the regions (now with more threads!) --- var batches = new BranchSamplingBatch <T> [activeBranches.Length]; // This provides deterministic RNG without race conditions for multithreaded execution at a modest memory cost for (int i = 0; i < batches.Length; i++) { batches[i] = new BranchSamplingBatch <T>(activeBranches[i], new Xoshiro256StarStar(Program.rand.Next())); } void GetParameterDistribution(int index) { // Inefficient allocation, but not a big deal double[] fitnessStorage = new double[sampleSize]; double[] bootstrapStorage = new double[MONTE_CARLO_SAMPLE_SIZE]; // Run the sampling batches[index].SampleNonAlloc(fitnessStorage, FitnessFunction); // Compute the estimating distribution of the guiding parameter switch (GuidingParam) { case GuidingParameter.Mean: { Normal dist = ParameterDistributions.MeanCLT(fitnessStorage); negatedDistributions[index] = new NegatedDistribution(dist, dist.Mean - NormalBoundStdDevs * dist.StdDev, dist.Mean + NormalBoundStdDevs * dist.StdDev); break; } case GuidingParameter.Median: { // Sort the fitness data in place Sorting.Sort(fitnessStorage); Normal dist = ParameterDistributions.MedianBootstrapMemoryFriendly(fitnessStorage, bootstrapStorage, activeBranches[index].rand); negatedDistributions[index] = new NegatedDistribution(dist, dist.Mean - NormalBoundStdDevs * dist.StdDev, dist.Mean + NormalBoundStdDevs * dist.StdDev); break; } case GuidingParameter.LowerMean: { Normal dist = ParameterDistributions.MeanOfLessThanQuantile(fitnessStorage, 0.1); negatedDistributions[index] = new NegatedDistribution(dist, dist.Mean - NormalBoundStdDevs * dist.StdDev, dist.Mean + NormalBoundStdDevs * dist.StdDev); break; } case GuidingParameter.OneOverNthQuantile: { for (int j = 0; j < sampleSize; j++) { fitnessStorage[j] *= -1.0; } Sorting.Sort(fitnessStorage); negatedDistributions[index] = ParameterDistributions.OneOverNthQuantileViaSampleMinimumParameterDistribution(fitnessStorage, bootstrapStorage, activeBranches[index].rand); break; } } } if (multiThread) { //int threadCount = Environment.ProcessorCount; // # of logical processors, including hyperthreading etc. int threadCount = 6; // Temp limit Parallel.For(0, batches.Length, new ParallelOptions() { MaxDegreeOfParallelism = threadCount }, (int i) => { GetParameterDistribution(i); }); } else // Synchronous case { var fitnessStorage = new double[sampleSize]; var monteCarloStorage = new double[MONTE_CARLO_SAMPLE_SIZE]; for (int i = 0; i < batches.Length; i++) { batches[i].SampleNonAlloc(fitnessStorage, FitnessFunction); // Assuming 1/nth quantile for testing // Negate the observations to get observations from -X for (int j = 0; j < sampleSize; j++) { fitnessStorage[j] *= -1.0; } Sorting.Sort(fitnessStorage); negatedDistributions[i] = ParameterDistributions.OneOverNthQuantileViaSampleMinimumParameterDistribution(fitnessStorage, monteCarloStorage, activeBranches[i].rand); } #if DEBUG Program.logger.WriteLine("Break SID 172"); #endif } #endregion // Update the best observation so far for (int i = 0; i < batches.Length; i++) { if (batches[i].BestObservedFitness < BestFitnessObserved) { BestFitnessObserved = batches[i].BestObservedFitness; BestElementObserved = batches[i].BestObservation; } } #region Discarding // --- Pre-emptive discarding --- // Normal Pairwise Discarding if (negatedDistributions[0].GetWrappedDistribution().GetType() == typeof(Normal)) { // Manual recast to a non-negated Normal[] Normal[] normals = new Normal[negatedDistributions.Length]; for (int i = 0; i < normals.Length; i++) { normals[i] = (Normal)(negatedDistributions[i].GetWrappedDistribution()); } for (int i = 0; i < negatedDistributions.Length - 1; i++) { int discardIndex = DiscardProbabilityComputation.BestPairwiseDiscardNormal(normals, out double discardProb); if (discardProb > PreemptiveDiscardConfidenceThreshold) { negatedDistributions[discardIndex] = null; normals[discardIndex] = null; activeBranches[discardIndex] = null; continue; } break; } } else // Non-normal case { // We have negated the distributions at this point, so we need to compare upper bounds against the largest lower bound double maxLowerBound = double.NegativeInfinity; for (int i = 0; i < negatedDistributions.Length; i++) { maxLowerBound = Math.Max(maxLowerBound, negatedDistributions[i].GetLowerBound()); } // Discard any distribution with an upper bound less than max lower bound for (int i = 0; i < negatedDistributions.Length; i++) { if (negatedDistributions[i].GetUpperBound() < maxLowerBound) { negatedDistributions[i] = null; activeBranches[i] = null; } } } // Compact the arrays of active branches and their corresponding negated distributions, keeping them paired by their indices var compactBranches = new List <Branch>(activeBranches.Length); var compactNegatedDists = new List <IDistributionWrapper>(activeBranches.Length); for (int i = 0; i < activeBranches.Length; i++) { if (activeBranches[i] != null) { compactBranches.Add(activeBranches[i]); compactNegatedDists.Add(negatedDistributions[i]); } } activeBranches = compactBranches.ToArray(); negatedDistributions = compactNegatedDists.ToArray(); // --- Compute Discard Probabilities --- double[] discardComplements; // The discard probabilities are in complement form (1 - P(D_i)) in this array if (GuidingParam == GuidingParameter.OneOverNthQuantile) { //discardComplements = DiscardProbabilityComputation.ComplementsMonteCarloMaximizing(negatedDistributions); //discardComplements = DiscardProbabilityComputation.ComplementsQuantileTrapRule(negatedDistributions); discardComplements = DiscardProbabilityComputation.ComplementsClenshawCurtisAutomatic(negatedDistributions); } else { discardComplements = DiscardProbabilityComputation.ComplementsClenshawCurtisAutomatic(negatedDistributions, errorTolerance: 1E-8, maxIterations: 10); //discardComplements = DiscardProbabilityComputation.ComplementsMonteCarloMaximizing(negatedDistributions); } // --- Discarding --- // Note: Nullifying a branch in activeBranches[] will discard it // Find the largest discard complement for reference double largestComplementDiscard = 0; for (int i = 0; i < discardComplements.Length; i++) { largestComplementDiscard = Math.Max(largestComplementDiscard, discardComplements[i]); } double confidence = 1.0; while (true) { // Find the branch with the best probability to discard double smallestComplementDiscard = 1; int smallestCDIndex = 0; for (int i = 0; i < discardComplements.Length; i++) { if (activeBranches[i] != null && discardComplements[i] < smallestComplementDiscard) { smallestComplementDiscard = discardComplements[i]; smallestCDIndex = i; } } // Try to discard the associated branch if (smallestComplementDiscard < 0.5 * largestComplementDiscard && // Relative size requirement confidence - smallestComplementDiscard >= confidenceLevel) // Maintain the confidence level { activeBranches[smallestCDIndex] = null; // Discard the branch confidence -= smallestComplementDiscard; // Account for the cost in confidence } else { break; // If we can't discard that one, then we can't do any better, so end the discard loop } } // Print the list to the log Program.logger.WriteLine($"Completed iteration {iteration}. Active branches:"); for (int i = 0; i < activeBranches.Length; i++) { if (activeBranches[i] != null) { Program.logger.WriteLine($"{activeBranches[i].ToString()}"); } } #endregion } // Compact the result and return var compactedBranches = new List <Branch>(activeBranches); compactedBranches.RemoveAll(b => b == null); // Remove null activeBranches = compactedBranches.ToArray(); return(activeBranches); }
public virtual void Reposition () { if (Application.isPlaying && !mInitDone && NGUITools.GetActive(this)) Init(); // Legacy functionality if (sorted) { sorted = false; if (sorting == Sorting.None) sorting = Sorting.Alphabetic; NGUITools.SetDirty(this); } if (!mInitDone) Init(); // Get the list of children in their current order List<Transform> list = GetChildList(); // Reset the position and order of all objects in the list ResetPosition(list); // Constrain everything to be within the panel's bounds if (keepWithinPanel) ConstrainWithinPanel(); // Notify the listener if (onReposition != null) onReposition(); }
public virtual void Reposition () { if (Application.isPlaying && !mInitDone && NGUITools.GetActive(this)) { mReposition = true; return; } // Legacy functionality if (sorted) { sorted = false; if (sorting == Sorting.None) sorting = Sorting.Alphabetic; NGUITools.SetDirty(this); } if (!mInitDone) Init(); // Get the list of children in their current order BetterList<Transform> list = GetChildList(); // Sort the list using the desired sorting logic if (sorting != Sorting.None) { if (sorting == Sorting.Alphabetic) list.Sort(SortByName); else if (sorting == Sorting.Horizontal) list.Sort(SortHorizontal); else if (sorting == Sorting.Vertical) list.Sort(SortVertical); else if (onCustomSort != null) list.Sort(onCustomSort); else Sort(list); } // Reset the position and order of all objects in the list ResetPosition(list); // Constrain everything to be within the panel's bounds if (keepWithinPanel) ConstrainWithinPanel(); // Notify the listener if (onReposition != null) onReposition(); }