/// <summary> /// Return the parameters necessary for the chosen sort /// </summary> /// <param name="sort_chosen"></param> /// <returns></returns> public static List<Parameter> sortingParameters(SortOptions sort_chosen) { List<Parameter> parameters = new List<Parameter>(); switch (sort_chosen) { case SortOptions.MostRecent: parameters.Add(new Parameter("sort_on", "created")); parameters.Add(new Parameter("sort_order", "down")); break; case SortOptions.Relevancy: parameters.Add(new Parameter("sort_on", "score")); parameters.Add(new Parameter("sort_order", "down")); break; case SortOptions.HighestPrice: parameters.Add(new Parameter("sort_on", "price")); parameters.Add(new Parameter("sort_order", "down")); break; case SortOptions.LowestPrice: parameters.Add(new Parameter("sort_on", "price")); parameters.Add(new Parameter("sort_order", "up")); break; default: break; } return parameters; }
private int Compare(GanttInfo x, GanttInfo y, SortOptions sort) { if (sort == SortOptions.LOT_ID) { return(x.LotID.CompareTo(y.LotID)); } return(0); }
public async Task <PagedResults <Event> > GetAllByByPocAsync( PagingOptions pagingOptions, SortOptions <Event, EventEntity> sortOptions, SearchOptions <Event, EventEntity> searchOptions, long pocId, CancellationToken ct) { return(await _eventService.GetAllByByPocAsync(pagingOptions, sortOptions, searchOptions, pocId, ct)); }
public ActionResult <List <Room> > GetRooms( [FromQuery] SortOptions <Room> sortOptions, [FromQuery] SearchOptions <Room> searchOptions ) { //To demonstrate server caching Thread.Sleep(3000); return(_roomService.GetRooms(sortOptions, searchOptions)); }
public async Task <PagedResults <User> > GetUsersByRoleAsync( PagingOptions pagingOptions, SortOptions <User, UserEntity> sortOptions, SearchOptions <User, UserEntity> searchOptions, string role, CancellationToken ct) { return(await _userService.GetUsersByRoleAsync(pagingOptions, sortOptions, searchOptions, role, ct)); }
/// <summary> /// The constructor for the class /// </summary> public SettingsViewModel() { foreach (string i in AppSettings.OrderOptions) { SortOptions.Add(i); } DeleteAllNotesCommand = new Command(async() => await DeleteAllNotes()); }
public void ApplySortTest(string text, SortOptions sortOptions, string expectedResult) { ITextProcessAppService textProcessAppService = new TextProcessAppService(); string result = textProcessAppService.ApplySort(text, sortOptions); Assert.IsNotNullOrEmpty(result); Assert.AreEqual(expectedResult, result); }
public void Compare_sort_nosort_to_smembers_mget() { string setKey = "setKey"; int total = 25; int count = 20; var temp = new byte[1]; byte fixedValue = 124; temp[0] = fixedValue; //initialize set and individual keys Redis.Del(setKey); for (var i = 0; i < total; ++i) { string key = setKey + i; Redis.SAdd(setKey, key.ToUtf8Bytes()); Redis.Set(key, temp); } var sw = Stopwatch.StartNew(); byte[][] results = null; for (int i = 0; i < count; ++i) { var keys = Redis.SMembers(setKey); results = Redis.MGet(keys); } sw.Stop(); //make sure that results are valid foreach (var result in results) { Assert.AreEqual(result[0], fixedValue); } Debug.WriteLine(String.Format("Time to call {0} SMembers and MGet operations: {1} ms", count, sw.ElapsedMilliseconds)); var opt = new SortOptions() { SortPattern = "nosort", GetPattern = "*" }; sw = Stopwatch.StartNew(); for (int i = 0; i < count; ++i) { results = Redis.Sort(setKey, opt); } sw.Stop(); //make sure that results are valid foreach (var result in results) { Assert.AreEqual(result[0], fixedValue); } Debug.WriteLine(String.Format("Time to call {0} sort operations: {1} ms", count, sw.ElapsedMilliseconds)); }
/// ------------------------------------------------------------------------------------ private void HandlePhoneticSortOptionsChanged(SortOptions sortOptions) { var item = cboListType.SelectedItem as SortOptionsTypeComboItem; if (item != null) { item.IsDirty = true; } }
private static SortOptions DefaultSort() { var sort = new SortOptions(); sort.Fields.Add(new Sort { Field = "Id", Descending = false }); return(sort); }
public async Task <IEnumerable <Product> > GetSortedList(SortOptions option) { var sortingStrategy = _sortProvider.GetSortingStrategy(option); //Check for null Guard.Against.Null(sortingStrategy, nameof(option)); return(await sortingStrategy.Sort()); }
public Sort(IObservable <IChangeSet <T> > source, IComparer <T>?comparer, SortOptions sortOptions, IObservable <Unit>?resort, IObservable <IComparer <T> >?comparerObservable, int resetThreshold) { _source = source ?? throw new ArgumentNullException(nameof(source)); _resort = resort ?? Observable.Never <Unit>(); _comparerObservable = comparerObservable ?? Observable.Never <IComparer <T> >(); _comparer = comparer ?? Comparer <T> .Default; _sortOptions = sortOptions; _resetThreshold = resetThreshold; }
public List <T> GetSortedEntryValues(IRedisSet <T> fromSet, int startingFrom, int endingAt) { var sortOptions = new SortOptions { Skip = startingFrom, Take = endingAt, }; var multiDataList = client.Sort(fromSet.Id, sortOptions); return(CreateList(multiDataList)); }
public List <T> SortList(IRedisList <T> fromList, int startingFrom, int endingAt) { var sortOptions = new SortOptions { Skip = startingFrom, Take = endingAt, }; var multiDataList = client.Sort(fromList.Id, sortOptions); return(CreateList(multiDataList)); }
public async Task <PagedResults <UserDto> > GetListAsync(int offset, int limit, string keyword, SortOptions <UserDto, UserEntity> sortOptions, FilterOptions <UserDto, UserEntity> filterOptions, IQueryable <UserEntity> querySearch ) { IQueryable <UserEntity> query = _entity; query = sortOptions.Apply(query); query = filterOptions.Apply(query); if (keyword != null) { query = querySearch; } var size = await query.CountAsync(); var items = await query .Skip(offset *limit) .Take(limit) .ToArrayAsync(); List <UserDto> returnUserList = new List <UserDto>(); foreach (UserEntity user in items) { var roleNames = await _userManager.GetRolesAsync(user); var userStorages = _context.UserStorages.Where(us => us.UserId == user.Id).Include(us => us.Storage).OrderBy(s => s.Storage.Name); var storages = new List <StorageDto>(); foreach (var userStorage in userStorages) { storages.Add(Mapper.Map <StorageDto>(userStorage.Storage)); } var userDto = new UserDto { FirstName = user.FirstName, LastName = user.LastName, Email = user.Email, PhoneNumber = user.PhoneNumber, Id = user.Id, UserName = user.UserName, JobTitle = user.JobTitle, IsActive = user.IsActive, RoleNames = roleNames, AccessibleStorages = storages }; returnUserList.Add(userDto); } return(new PagedResults <UserDto> { Items = returnUserList, TotalSize = size }); }
public async Task AddAsync( PagingOptions pagingOptions, SortOptions <Question, QuestionEntity> sortOptions, SearchOptions <Question, QuestionEntity> searchOptions, FeedbackForm feedback) { var questions = await _feedbackService.GetAllByFeedbackTypeAsync( pagingOptions, sortOptions, searchOptions, feedback.FeedbackType, CancellationToken.None); var feedbackModel = new Feedback(); foreach (var reason in feedback.Reason) { var question = questions.Items.Single(x => x.Id.Equals(reason.QuestionId)); feedbackModel.Attended = question.FeedbackType.Equals("participated"); feedbackModel.NotAttended = question.FeedbackType.Equals("notparticipated"); feedbackModel.Unregistered = question.FeedbackType.Equals("unregistered"); if (question.CustomQuestion) { var dbAnswer = question.Answers.Single(a => a.Id.Equals(Guid.Parse(reason.AnswerId))); feedbackModel.ReasonId = Guid.Parse(reason.AnswerId); feedbackModel.Rating = Convert.ToInt32(dbAnswer.Description); } if (!question.FreeTextQuestion) { var dbAnswer = question.Answers.Single(a => a.Id.Equals(Guid.Parse(reason.AnswerId))); feedbackModel.ReasonId = Guid.Parse(reason.AnswerId); feedbackModel.Cons = dbAnswer.Description; } if (question.FreeTextQuestion && question.Description.Contains("like")) { feedbackModel.Pros = reason.AnswerId; } if (question.FreeTextQuestion && question.Description.Contains("improved")) { feedbackModel.Cons = reason.AnswerId; } } var created = await _feedbackService.AddAsync(feedbackModel, feedback.EventId); var participant = await _participantService.FindAsync(feedback.ParticipantId, CancellationToken.None); await _emailService.SendAsync("*****@*****.**", "Admin", participant.EmployeeId, "Feedback Received", "Thanks for the feedback."); participant.FeedbackId = created; participant.IsFeedbackReceived = true; await _participantService.UpdateAsync(participant); }
public void TestSetup() { _prj.PhoneCache.Clear(); _prj.RecordCache.Clear(); _recCache = _prj.RecordCache; _cache = new WordListCache(); _query = new SearchQuery(); _sortOptions = new SortOptions(true, _prj); }
public async Task <PagedResults <Question> > GetAllByFeedbackTypeAsync( PagingOptions pagingOptions, SortOptions <Question, QuestionEntity> sortOptions, SearchOptions <Question, QuestionEntity> searchOptions, string feedbackType, CancellationToken ct) { return(await _feedbackService.GetAllByFeedbackTypeAsync(pagingOptions, sortOptions, searchOptions, feedbackType, ct)); }
public async Task <PagedResults <Opening> > GetOpeningsAsync( PagingOptions pagingOptions, SortOptions <Opening, OpeningEntity> sortOptions, SearchOptions <Opening, OpeningEntity> searchOptions, CancellationToken ct) { var rooms = await _context.Rooms.ToArrayAsync(); var allOpenings = new List <OpeningEntity>(); foreach (var room in rooms) { // Generate a sequence of raw opening slots var allPossibleOpenings = _dateLogicService.GetAllSlots( DateTimeOffset.UtcNow, _dateLogicService.FurthestPossibleBooking(DateTimeOffset.UtcNow)) .ToArray(); var conflictedSlots = await GetConflictingSlots( room.Id, allPossibleOpenings.First().StartAt, allPossibleOpenings.Last().EndAt, ct); // Remove the slots that have conflicts and project var openings = allPossibleOpenings .Except(conflictedSlots, new BookingRangeComparer()) .Select(slot => new OpeningEntity { RoomId = room.Id, Rate = room.Rate, StartAt = slot.StartAt, EndAt = slot.EndAt }); allOpenings.AddRange(openings); } var pseudoQuery = allOpenings.AsQueryable(); pseudoQuery = searchOptions.Apply(pseudoQuery); pseudoQuery = sortOptions.Apply(pseudoQuery); var size = pseudoQuery.Count(); var items = pseudoQuery .Skip(pagingOptions.Offset.Value) .Take(pagingOptions.Limit.Value) .ProjectTo <Opening>() .ToArray(); return(new PagedResults <Opening> { TotalSize = size, Items = items }); }
public async Task GetAllEventStatus_StateUnderTest_ExpectedBehavior_UnAuth() { // Arrange var unitUnderTest = this.CreateReportsController(); this.mockAuthorizationService.Setup( r => r.AuthorizeAsync(It.IsAny <ClaimsPrincipal>(), It.IsAny <string>(), It.IsAny <string>()) ).ReturnsAsync(AuthorizationResult.Failed()); this.mockUserBusiness.Setup(r => r.GetUserIdAsync(It.IsAny <ClaimsPrincipal>())).ReturnsAsync(new Guid()); List <EventStatus> evsts = new List <EventStatus>(); evsts.Add(new EventStatus() { EventDate = DateTime.Now, EventName = "Desc 2", EventId = "1" }); evsts.Add(new EventStatus() { EventDate = DateTime.Now, EventName = "Desc 1", EventId = "2" }); PagedResults <EventStatus> sampleResult = new PagedResults <EventStatus>() { Items = evsts }; mockReportBusiness.Setup(r => r.GetAllByPocAsync( It.IsAny <PagingOptions>(), It.IsAny <SortOptions <Event, EventEntity> >(), It.IsAny <SearchOptions <Event, EventEntity> >(), It.IsAny <long>(), It.IsAny <CancellationToken>())).ReturnsAsync(sampleResult); PagingOptions pagingOptions = new PagingOptions() { Limit = 1, Offset = 1 }; SortOptions <Event, EventEntity> sortOptions = new SortOptions <Event, EventEntity>() { OrderBy = new string[] { "" } }; SearchOptions <Event, EventEntity> searchOptions = new SearchOptions <Event, EventEntity>() { Search = new string[] { "" } }; CancellationToken ct = new CancellationToken(); // Act var result = await unitUnderTest.GetAllEventStatus( pagingOptions, sortOptions, searchOptions, ct); // Assert Assert.True(result.Value != null); }
public async Task GetAllEventStatusReport_StateUnderTest_ExpectedBehavior() { // Arrange var unitUnderTest = this.CreateReportsController(); this.mockAuthorizationService.Setup( r => r.AuthorizeAsync(It.IsAny <ClaimsPrincipal>(), It.IsAny <string>(), It.IsAny <string>()) ).ReturnsAsync(AuthorizationResult.Success()); List <EventStatusReport> evsts = new List <EventStatusReport>(); evsts.Add(new EventStatusReport() { EventDate = DateTime.Now, EventName = "Desc 2", EventId = "1" }); evsts.Add(new EventStatusReport() { EventDate = DateTime.Now, EventName = "Desc 1", EventId = "2" }); PagedResults <EventStatusReport> sampleResult = new PagedResults <EventStatusReport>() { Items = evsts }; mockReportBusiness.Setup(r => r.GetAllReportAsync( It.IsAny <PagingOptions>(), It.IsAny <SortOptions <Event, EventEntity> >(), It.IsAny <SearchOptions <Event, EventEntity> >(), It.IsAny <CancellationToken>())).ReturnsAsync(sampleResult); PagingOptions pagingOptions = new PagingOptions() { Limit = 1, Offset = 1 }; SortOptions <Event, EventEntity> sortOptions = new SortOptions <Event, EventEntity>() { OrderBy = new string[] { "" } }; SearchOptions <Event, EventEntity> searchOptions = new SearchOptions <Event, EventEntity>() { Search = new string[] { "" } }; CancellationToken ct = new CancellationToken(); bool report = false; // Act var result = await unitUnderTest.GetAllEventStatusReport( pagingOptions, sortOptions, searchOptions, report, ct); // Assert Assert.IsType <FileContentResult>(result); }
public async Task <(IEnumerable <Post>, IEnumerable <Comment>)> GetRecentPostsAndCommentsAsync(int count = 0) { SortOptions options = new SortOptions { SortBy = nameof(Post.RowCreatedDateTime), SortOrder = SortOrder.Descending }; return(await _blog.GetRecentPostAndComments(options, count)); }
public static SortOptions GenerateSortOptions(PaginatedRequestCommand model) { var sortOptions = new SortOptions { Fields = (model.OrdersBy == null || model.OrdersBy.Length == 0) ? new[] { "Id" } : model.OrdersBy, Directions = (model.Directions == null || model.Directions.Length == 0) ? new[] { "asc" } : model.Directions }; return(sortOptions); }
public void UpdateFrom(QueryState state) { SortOptions.Clear(); SortOptions.AddRange(state.SortOptions); IsSpatialQuery = state.IsSpatialQuery; Latitude = state.Latitude; Longitude = state.Longitude; Radius = state.Radius; }
public ConfigurationAttribute(string name, type type, Present present, SearchOptions searchOptions = null, FilterOptions filterOptions = null, SortOptions sortOptions = null) { Name = name; Type = type; Present = present; SearchOptions = searchOptions; FilterOptions = filterOptions; SortOptions = sortOptions; }
public async Task <PagedResults <Opening> > GetOpeningsAsync( PagingOptions pagingOptions, SortOptions <Opening, OpeningEntity> sortOptions, SearchOptions <Opening, OpeningEntity> searchOptions) { var rooms = await _context.Rooms.ToArrayAsync(); return(await GetOpeningsForRoomsAsync( rooms, pagingOptions, sortOptions, searchOptions)); }
public ContentWithCommentsCount() { Map = comments => from item in comments select new { ContentId = item.Content.Id, Count = 1 }; Reduce = reduce => from item in reduce group item by item.ContentId into g select new { ContentId = g.Key, Count = g.Sum(item => item.Count) }; SortOptions.Add(x => x.Count, Raven.Database.Indexing.SortOptions.Int); }
public async Task <PagedResults <OrderDto> > GetListAsync( int offset, int limit, string keyword, SortOptions <OrderDto, OrderEntity> sortOptions, FilterOptions <OrderDto, OrderEntity> filterOptions, IQueryable <OrderEntity> querySearch) { IQueryable <OrderEntity> query = _order; query = sortOptions.Apply(query); query = filterOptions.Apply(query); if (keyword != null) { // DateTime a = DateTime.ParseExact(DateTime.Now.Date.ToString(), "dd/MM/yyyy", // System.Globalization.CultureInfo.InvariantCulture).Date; query = query.Where(p => p.Code.Contains(keyword) || p.Status.Contains(keyword) ); } var items = await query .Skip(offset *limit) .Take(limit) .ToArrayAsync(); var totalSize = await query.CountAsync(); var returnItems = Mapper.Map <List <OrderDto> >(items); for (var i = 0; i < items.Length; i++) { returnItems[i].PackageList = new List <PackageDto>(); var packageIdList = JsonConvert.DeserializeObject <List <Guid> >(items[i].PackageIdList); foreach (Guid packageId in packageIdList) { var package = await _context.Packages.SingleOrDefaultAsync(s => s.Id == packageId); if (package == null) { throw new Exception("Can not find storage with Id=" + packageId); } var packageDto = Mapper.Map <PackageDto>(package); returnItems[i].PackageList.Add(packageDto); } } return(new PagedResults <OrderDto> { Items = returnItems, TotalSize = totalSize }); }
private void OnSortingSettingChanged(SortOptions option, bool descending) { SortTitle.IsChecked = SortScore.IsChecked = Sort3.IsChecked = SortAiring.IsChecked = SortNone.IsChecked = SortLastWatched.IsChecked = SortEndDate.IsChecked = SortSeason.IsChecked = SortStartDate.IsChecked = false; switch (option) { case SortOptions.SortTitle: SortTitle.IsChecked = true; break; case SortOptions.SortScore: SortScore.IsChecked = true; break; case SortOptions.SortWatched: Sort3.IsChecked = true; break; case SortOptions.SortAirDay: SortAiring.IsChecked = true; break; case SortOptions.SortNothing: SortNone.IsChecked = true; break; case SortOptions.SortLastWatched: SortLastWatched.IsChecked = true; break; case SortOptions.SortStartDate: SortStartDate.IsChecked = true; break; case SortOptions.SortEndDate: SortEndDate.IsChecked = true; break; case SortOptions.SortSeason: SortSeason.IsChecked = true; break; default: throw new ArgumentOutOfRangeException(nameof(option), option, null); } BtnOrderDescending.IsChecked = descending; }
public async Task <PagedResults <OpeningResource> > GetOpeningsAsync( PagingOptions pagingOptions, SortOptions <OpeningResource, OpeningEntity> sortOptions, SearchOptions <OpeningResource, OpeningEntity> searchOptions, CancellationToken ct) { var rooms = await _context.Rooms.ToArrayAsync(); return(await GetOpeningsForRoomsAsync( rooms, pagingOptions, sortOptions, searchOptions, ct)); }
public async Task <IActionResult> Sort(SortOptions sortOption) { if (sortOption == SortOptions.None) { return(BadRequest("Invalid sort option")); } var products = await _productsService.SortProductsAsync(sortOption); return(Ok(products)); }
public AnimeListPageNavigationArgs(SortOptions sort, int status, bool desc, AnimeListWorkModes seasonal, string source, AnimeSeason season, AnimeListDisplayModes dispMode) { SortOption = sort; Status = status; Descending = desc; WorkMode = seasonal; ListSource = source; NavArgs = true; CurrSeason = season; DisplayMode = dispMode; }
public override void DoWindowContents( Rect inRect ) { base.DoWindowContents( inRect ); // warn the player if no research bench is built if( !_noBenchWarned ) { if( !Find.ListerBuildings.ColonistsHaveBuilding( ThingDefOf.ResearchBench ) ) { Find.WindowStack.Add( new Dialog_Message( "ResearchMenuWithoutBench".Translate() ) ); } _noBenchWarned = true; } // Title Text.Font = GameFont.Medium; Text.Anchor = TextAnchor.UpperCenter; Widgets.Label( new Rect( 0f, 0f, inRect.width, 300f ), "Research".Translate() ); Text.Anchor = TextAnchor.UpperLeft; Text.Font = GameFont.Small; // create content areas Rect sidebar = new Rect(0f, 75f, LeftAreaWidth, inRect.height - 75f); Rect content = new Rect(sidebar.xMax + _margin.x, 45f, inRect.width - sidebar.width - _margin.x, inRect.height - 45f); // draw boxes around content areas Widgets.DrawMenuSection( sidebar, false ); Widgets.DrawMenuSection( content ); // plop in extra row for input + sort buttons // set up rects Rect sortFilterRow = sidebar.ContractedBy(10f); sortFilterRow.height = 30f; Rect filterRect = new Rect(sortFilterRow); filterRect.width = sortFilterRow.width - 110f; Rect deleteFilter = new Rect(filterRect.xMax + _margin.x, filterRect.yMin + 3f, 24f, 24f); Rect sortByName = new Rect(deleteFilter.xMax + _margin.x, filterRect.yMin + 3f, 24f, 24f); Rect sortByCost = new Rect(sortByName.xMax + _margin.x, filterRect.yMin + 3f, 24f, 24f); // finetune rects // tooltips TooltipHandler.TipRegion( filterRect, "RI.filterTooltip".Translate() ); if( _filter != "" ) { TooltipHandler.TipRegion( deleteFilter, "RI.deleteFilterTooltip".Translate() ); } TooltipHandler.TipRegion( sortByName, "RI.sortByNameTooltip".Translate() ); TooltipHandler.TipRegion( sortByCost, "RI.sortByCostTooltip".Translate() ); // filter input, update in realtime - it's not a very expensive op, and we're paused anyway. _filter = Widgets.TextField( filterRect, _filter ); if( _oldFilter != _filter ) { _oldFilter = _filter; RefreshSource(); } if( _filter != "" ) { if( Widgets.ImageButton( deleteFilter, Widgets.CheckboxOffTex ) ) { _filter = ""; RefreshSource(); } } // sort options if( Widgets.ImageButton( sortByName, Icon.SortByName ) ) { if( _sortBy != SortOptions.Name ) { _sortBy = SortOptions.Name; _asc = false; RefreshSource(); } else { _asc = !_asc; RefreshSource(); } } if( Widgets.ImageButton( sortByCost, Icon.SortByCost ) ) { if( _sortBy != SortOptions.Cost ) { _sortBy = SortOptions.Cost; _asc = true; RefreshSource(); } else { _asc = !_asc; RefreshSource(); } } // contract sidebar area for margins, bump down to compensate for filter. Rect sidebarInner = sidebar.ContractedBy(10f); sidebarInner.yMin += ProjectIntervalY + _margin.y; sidebarInner.height -= ProjectIntervalY + _margin.y; // set height float height = ProjectIntervalY * _source.Count() + 100; // begin scrollview and group (group sets x,y coordinates of rects in it to be relative to the groups rect) Rect sidebarContent = new Rect(0f, 0f, sidebarInner.width - 16f, height); Widgets.BeginScrollView( sidebarInner, ref _projectListScrollPosition, sidebarContent ); Rect position = sidebarContent.ContractedBy(_margin.x); GUI.BeginGroup( position ); // Draw the list of researches in the source chosen. int curY = 0; foreach( HelpDef current in from rp in _source select rp ) { Rect sidebarRow = new Rect(0f, curY, position.width, ProjectIntervalY); DrawResearchRow( current, sidebarRow ); curY += ProjectIntervalY; } GUI.EndGroup(); Widgets.EndScrollView(); // Draw the source selection tabs. TabDrawer.DrawTabs( sidebar, SourceTabs ); // Draw the content area. DrawResearchContent( content ); }
static void Main(string[] args) { Redis r; string s; int i; if (args.Length >= 2) r = new Redis(args[0], Convert.ToInt16(args[1])); else if (args.Length >= 1) r = new Redis(args[0]); else r = new Redis(); r.Set ("foo", "bar"); r.FlushAll(); assert ((i = r.Keys.Length) == 0, "there should be no keys but there were {0}", i); r.Set ("foo", "bar"); assert ((i = r.Keys.Length) == 1, "there should be one key but there were {0}", i); r.Set ("foo bär", "bär foo"); assert ((i = r.Keys.Length) == 2, "there should be two keys but there were {0}", i); assert (r.TypeOf ("foo") == Redis.KeyType.String, "type is not string"); r.Set ("bar", "foo"); byte [][] arr = r.MGet ("foo", "bar", "foo bär"); assert (arr.Length == 3, "expected 3 values"); assert ((s = Encoding.UTF8.GetString (arr [0])) == "bar", "expected \"foo\" to be \"bar\", got \"{0}\"", s); assert ((s = Encoding.UTF8.GetString (arr [1])) == "foo", "expected \"bar\" to be \"foo\", got \"{0}\"", s); assert ((s = Encoding.UTF8.GetString (arr [2])) == "bär foo", "expected \"foo bär\" to be \"bär foo\", got \"{0}\"", s); r ["{one}"] = "world"; assert (r.GetSet ("{one}", "newvalue") == "world", "GetSet failed"); assert (r.Rename ("{one}", "two"), "failed to rename"); assert (!r.Rename ("{one}", "{one}"), "should have sent an error on rename"); r.Set("binary", new byte[] { 0x00, 0x8F }); assert((i = r.Get("binary").Length) == 2, "expected 2 bytes, got {0}", i); r.Db = 10; r.Set ("foo", "diez"); assert ((s = r.GetString ("foo")) == "diez", "got {0}", s); assert (r.Remove ("foo"), "could not remove foo"); r.Db = 0; assert (r.GetString ("foo") == "bar", "foo was not bar"); assert (r.ContainsKey ("foo"), "there is no foo"); assert (r.Remove ("foo", "bar") == 2, "did not remove two keys"); assert (!r.ContainsKey ("foo"), "foo should be gone."); r.Save (); r.BackgroundSave (); Console.WriteLine ("Last save: {0}", r.LastSave); //r.Shutdown (); var info = r.GetInfo (); foreach (var k in info.Keys) { Console.WriteLine ("{0} -> {1}", k, info [k]); } var dict = new Dictionary<string,string> (); dict ["hello"] = "world"; dict ["goodbye"] = "my dear"; dict ["schön"] = "grün"; r.Set (dict); assert ((s = r.GetString("hello")) == "world", "got \"{0}\"", s); assert ((s = r.GetString("goodbye")) == "my dear", "got \"{0}\"", s); assert ((s = r.GetString("schön")) == "grün", "got \"{0}\"", s); r.RightPush("alist", "avalue"); r.RightPush("alist", "another value"); assert (r.ListLength("alist") == 2, "List length should have been 2"); string value = Encoding.UTF8.GetString(r.ListIndex("alist", 1)); if(!value.Equals("another value")) Console.WriteLine("error: Received {0} and should have been 'another value'", value); value = Encoding.UTF8.GetString(r.LeftPop("alist")); if (!value.Equals("avalue")) Console.WriteLine("error: Received {0} and should have been 'avalue'", value); if (r.ListLength("alist") != 1) Console.WriteLine("error: List should have one element after pop"); r.LeftPush("alist", "yet another value"); SortOptions so = new SortOptions(); so.Key = "alist"; so.Lexographically = true; assert ((s = Encoding.UTF8.GetString(r.Sort (so) [0])) == "another value", "expected Sort result \"another value\", got \"" + s + "\""); assert ((i = r.Sort ("alist", "alist", new object [] {"ALPHA"}).Length) == 2, "expected Sort result 2, got {0}", i); byte[][] values = r.ListRange("alist", 0, 1); assert (Encoding.UTF8.GetString(values[0]).Equals("another value"), "range did not return the right values"); assert (r.AddToSet("FOO", Encoding.UTF8.GetBytes("BAR")), "problem adding to set"); assert (r.AddToSet("FOO", Encoding.UTF8.GetBytes("BAZ")), "problem adding to set"); assert (r.AddToSet("FOO", "Hoge"), "problem adding string to set"); assert (r.CardinalityOfSet("FOO") == 3, "cardinality should have been 3 after adding 3 items to set"); assert (r.IsMemberOfSet("FOO", Encoding.UTF8.GetBytes("BAR")), "BAR should have been in the set"); assert (r.IsMemberOfSet("FOO", "BAR"), "BAR should have been in the set"); byte[][] members = r.GetMembersOfSet("FOO"); assert (members.Length == 3, "set should have had 3 members"); assert (r.RemoveFromSet("FOO", "Hoge"), "should have removed Hoge from set"); assert (!r.RemoveFromSet("FOO", "Hoge"), "Hoge should not have existed to be removed"); assert (2 == r.GetMembersOfSet("FOO").Length, "set should have 2 members after removing Hoge"); assert (r.AddToSet("BAR", Encoding.UTF8.GetBytes("BAR")), "problem adding to set"); assert (r.AddToSet("BAR", Encoding.UTF8.GetBytes("ITEM1")), "problem adding to set"); assert (r.AddToSet("BAR", Encoding.UTF8.GetBytes("ITEM2")), "problem adding string to set"); assert (r.GetUnionOfSets("FOO","BAR").Length == 4, "resulting union should have 4 items"); assert (1 == r.GetIntersectionOfSets("FOO", "BAR").Length, "resulting intersection should have 1 item"); assert (1 == r.GetDifferenceOfSets("FOO", "BAR").Length, "resulting difference should have 1 item"); assert (2 == r.GetDifferenceOfSets("BAR", "FOO").Length, "resulting difference should have 2 items"); byte[] itm = r.GetRandomMemberOfSet("FOO"); assert (null != itm, "GetRandomMemberOfSet should have returned an item"); assert (r.MoveMemberToSet("FOO","BAR", itm), "data within itm should have been moved to set BAR"); r.FlushDb (); assert ((i = r.Keys.Length) == 0, "there should be no keys but there were {0}", i); r.Dispose (); Console.WriteLine ("\nPassed tests: {0}", nPassed); if (nFailed > 0) Console.WriteLine ("Failed tests: {0}", nFailed); }
public override void DoWindowContents(Rect inRect) { base.DoWindowContents(inRect); if (!_noBenchWarned) { if (!Find.ListerBuildings.ColonistsHaveBuilding(ThingDefOf.ResearchBench)) { Find.WindowStack.Add(new Dialog_Message("ResearchMenuWithoutBench".Translate())); } _noBenchWarned = true; } Text.Font = GameFont.Medium; Text.Anchor = TextAnchor.UpperCenter; Widgets.Label(new Rect(0f, 0f, inRect.width, 300f), "Research".Translate()); Text.Anchor = TextAnchor.UpperLeft; Text.Font = GameFont.Small; Rect sidebar = new Rect(0f, 75f, 330f, inRect.height - 75f); Rect content = new Rect(sidebar.xMax + 10f, 45f, inRect.width - sidebar.width - 10f, inRect.height - 45f); Widgets.DrawMenuSection(sidebar, false); Widgets.DrawMenuSection(content); // plop in extra row for input + sort buttons Rect sortFilterRow = sidebar.ContractedBy(10f); sortFilterRow.height = 30f; Rect filterRect = new Rect(sortFilterRow); filterRect.width = sortFilterRow.width - 110f; Rect deleteFilter = new Rect(filterRect.xMax + 6f, filterRect.yMin + 3f, 24f, 24f); Rect sortByName = new Rect(deleteFilter.xMax + 6f, filterRect.yMin + 3f, 24f, 24f); Rect sortByCost = new Rect(sortByName.xMax + 6f, filterRect.yMin + 3f, 24f, 24f); TooltipHandler.TipRegion(filterRect, "RI.filterTooltip".Translate()); if (_filter != "") TooltipHandler.TipRegion(deleteFilter, "RI.deleteFilterTooltip".Translate()); TooltipHandler.TipRegion(sortByName, "RI.sortByNameTooltip".Translate()); TooltipHandler.TipRegion(sortByCost, "RI.sortByCostTooltip".Translate()); // filter options _filter = Widgets.TextField(filterRect, _filter); if (_oldFilter != _filter) { _oldFilter = _filter; RefreshSource(); } if (_filter != "") { if (Widgets.ImageButton(deleteFilter, Widgets.CheckboxOffTex)) { _filter = ""; RefreshSource(); } } // sort options if (Widgets.ImageButton(sortByName, _sortByNameTex)) { if (_sortBy != SortOptions.Name) { _sortBy = SortOptions.Name; _asc = false; RefreshSource(); } else { _asc = !_asc; RefreshSource(); } } if (Widgets.ImageButton(sortByCost, _sortByCostTex)) { if (_sortBy != SortOptions.Cost) { _sortBy = SortOptions.Cost; _asc = true; RefreshSource(); } else { _asc = !_asc; RefreshSource(); } } // contract sidebar area Rect sidebarInner = sidebar.ContractedBy(10f); sidebarInner.yMin += 30f; sidebarInner.height -= 30f; float height = 25 * _source.Count() + 100; Rect sidebarContent = new Rect(0f, 0f, sidebarInner.width - 16f, height); Widgets.BeginScrollView(sidebarInner, ref _projectListScrollPosition, sidebarContent); Rect position = sidebarContent.ContractedBy(10f); GUI.BeginGroup(position); int num = 0; foreach (ResearchProjectDef current in from rp in _source select rp) { Rect sidebarRow = new Rect(0f, num, position.width, 25f); if (SelectedProject == current) { GUI.DrawTexture(sidebarRow, TexUI.HighlightTex); } string text = current.LabelCap + " (" + current.totalCost.ToString("F0") + ")"; Rect sidebarRowInner = new Rect(sidebarRow); sidebarRowInner.x += 6f; sidebarRowInner.width -= 6f; float num2 = Text.CalcHeight(text, sidebarRowInner.width); if (sidebarRowInner.height < num2) { sidebarRowInner.height = num2 + 3f; } // give the label a colour if we're in the all tab. Color textColor; if (_showResearchedProjects == ShowResearch.All) { if (current.IsFinished) { textColor = new Color(1f, 1f, 1f); } else if (!current.PrereqsFulfilled) { textColor = new Color(.6f, .6f, .6f); } else { textColor = new Color(.8f, .85f, 1f); } } else { textColor = new Color(.8f, .85f, 1f); } if (Widgets.TextButton(sidebarRowInner, text, false, true, textColor)) { SoundDefOf.Click.PlayOneShotOnCamera(); SelectedProject = current; } num += 25; } GUI.EndGroup(); Widgets.EndScrollView(); List<TabRecord> list = new List<TabRecord>(); TabRecord item = new TabRecord("RI.All".Translate(), delegate { this._showResearchedProjects = ShowResearch.All; RefreshSource(); }, _showResearchedProjects == ShowResearch.All); list.Add(item); TabRecord item2 = new TabRecord("Researched".Translate(), delegate { this._showResearchedProjects = ShowResearch.Completed; RefreshSource(); }, _showResearchedProjects == ShowResearch.Completed); list.Add(item2); TabRecord item3 = new TabRecord("RI.Available".Translate(), delegate { this._showResearchedProjects = ShowResearch.Available; RefreshSource(); }, _showResearchedProjects == ShowResearch.Available); list.Add(item3); TabDrawer.DrawTabs(sidebar, list); Rect position2 = content.ContractedBy(20f); GUI.BeginGroup(position2); if (SelectedProject != null) { Text.Font = GameFont.Medium; GenUI.SetLabelAlign(TextAnchor.MiddleLeft); Rect rect6 = new Rect(20f, 0f, position2.width - 20f, 50f); Widgets.Label(rect6, SelectedProject.LabelCap); GenUI.ResetLabelAlign(); Text.Font = GameFont.Small; Rect rect7 = new Rect(0f, 50f, position2.width, position2.height - 50f); string desc = SelectedProject.description; // select prerequisites desc += ".\n\n"; string[] prereqs = SelectedProject.prerequisites.Select(def => def.LabelCap).ToArray(); desc += "RI.Prerequisites".Translate() + ": "; if (prereqs.Length == 0) { desc += "RI.none".Translate(); } else { desc += String.Join(", ", prereqs); } desc += ".\n\n"; // select follow-ups string[] follow = DefDatabase<ResearchProjectDef>.AllDefsListForReading.Where(rpd => rpd.prerequisites.Contains(SelectedProject)).Select(rpd => rpd.LabelCap).ToArray(); desc += "RI.LeadsTo".Translate() + ": "; if (!follow.Any()) { desc += "RI.none".Translate(); } else { desc += String.Join(", ", follow); } desc += ".\n\n"; //// find all unlocks //desc += "Unlocks: "; //string[] unlocks = getUnlocks(selectedProject); //if (unlocks == null || unlocks.Count() == 0) //{ // desc += "none"; //} //else //{ // desc += String.Join(", ", unlocks); //} //desc += ".\n\n"; Widgets.Label(rect7, desc); Rect rect8 = new Rect(position2.width / 2f - 50f, 300f, 100f, 50f); if (SelectedProject.IsFinished) { Widgets.DrawMenuSection(rect8); Text.Anchor = TextAnchor.MiddleCenter; Widgets.Label(rect8, "Finished".Translate()); Text.Anchor = TextAnchor.UpperLeft; } else if (SelectedProject == Find.ResearchManager.currentProj) { Widgets.DrawMenuSection(rect8); Text.Anchor = TextAnchor.MiddleCenter; Widgets.Label(rect8, "InProgress".Translate()); Text.Anchor = TextAnchor.UpperLeft; } else if (!SelectedProject.PrereqsFulfilled) { Widgets.DrawMenuSection(rect8); Text.Anchor = TextAnchor.MiddleCenter; Widgets.Label(rect8, "RI.PreReqLocked".Translate()); Text.Anchor = TextAnchor.UpperLeft; } else { if (Widgets.TextButton(rect8, "Research".Translate())) { SoundDef.Named("ResearchStart").PlayOneShotOnCamera(); Find.ResearchManager.currentProj = SelectedProject; } if (Prefs.DevMode) { Rect rect9 = rect8; rect9.x += rect9.width + 4f; if (Widgets.TextButton(rect9, "Debug Insta-finish")) { Find.ResearchManager.currentProj = SelectedProject; Find.ResearchManager.InstantFinish(SelectedProject); } } } Rect rect10 = new Rect(15f, 450f, position2.width - 30f, 35f); Widgets.FillableBar(rect10, SelectedProject.PercentComplete, BarFillTex, BarBgTex, true); Text.Anchor = TextAnchor.MiddleCenter; Widgets.Label(rect10, SelectedProject.ProgressNumbersString); Text.Anchor = TextAnchor.UpperLeft; } GUI.EndGroup(); }
public byte [][] Sort (SortOptions options) { return Sort (options.Key, options.StoreInKey, options.ToArgs()); }
public virtual JsonResult GetSongs( long localBussinesId, long? playlistId, short startCount, short increment, SortOptions sort, bool descending, long referringPlaylistSongRatingId) { if (playlistId.HasValue) { return GetSongsOfPlaylist( playlistId.Value, startCount, increment, sort, descending, referringPlaylistSongRatingId); } return GetAllSongsOfLocalBusiness( localBussinesId, startCount, increment); }
// TODO: XML-doc private JsonResult GetSongsOfPlaylist( long playlistId, short startCount, short increment, SortOptions sort, bool descending, long referringPlaylistSongRatingId =0) { var playlist = Repository.Get<Playlist>(playlistId); if (playlist == null) { return BuildFailureResult(-1, App_GlobalResources.Errors.invalidPlaylist); } var playlistDto = PlaylistDTOFactory.Map(playlist); /* the query retrieves one more record than needed. This is used to * see if there are more results than requested (paging) */ var ratings = playlist.GetRatings( startCount, (short)(increment + 1), sort, descending, CurrentUser); var ratingsList = ratings.ToList(); if(referringPlaylistSongRatingId!=0) { SetReferringPlaylistSong(referringPlaylistSongRatingId, playlist, ref ratingsList); } /* limit number of returned results to the number specified by the * client and not one more */ var areMore = (ratingsList.Count() > increment); if (areMore) { ratingsList = ratingsList.Take(ratingsList.Count() - 1).ToList(); } var ratingsRslt = GetSongsAndRating(ratingsList); var renderedData = new { startCount, increment, areMore = areMore, songs = ratingsRslt, playlist = playlistDto }; return BuildSuccessResult(0, renderedData); }
private static object GetNullValueForSorting(SortOptions? sortOptions) { switch (sortOptions) { case SortOptions.Short: case SortOptions.Int: return int.MinValue; case SortOptions.Double: return double.MinValue; case SortOptions.Float: return float.MinValue; // ReSharper disable RedundantCaseLabel case SortOptions.Long: // to be able to sort on timestamps case SortOptions.String: case SortOptions.StringVal: case SortOptions.None: case SortOptions.Custom: // ReSharper restore RedundantCaseLabel default: return long.MinValue; } }
public void DrawResearchesListPanel(Rect rectSidePanel) { Widgets.DrawMenuSection(rectSidePanel, false); // controls row that adds search textfield and sorter var rectControlsRow = rectSidePanel.ContractedBy(10f); rectControlsRow.height = 30f; var rectTextFilter = new Rect(rectControlsRow) {width = rectControlsRow.width - 110f}; var rectClearFilterButton = new Rect(rectTextFilter.xMax + 6f, rectTextFilter.yMin + 3f, 24f, 24f); var rectSortByNameButton = new Rect(rectClearFilterButton.xMax + 6f, rectTextFilter.yMin + 3f, 24f, 24f); var rectSortByCostButton = new Rect(rectSortByNameButton.xMax + 6f, rectTextFilter.yMin + 3f, 24f, 24f); // draw filter text field, return input currentFilter = Widgets.TextField(rectTextFilter, currentFilter); if (previousFilter != currentFilter) { previousFilter = currentFilter; RefreshList(); } // if any text in the field if (currentFilter != "") { // draw clear filter text field button if (Widgets.ButtonImage(rectClearFilterButton, Widgets.CheckboxOffTex)) { currentFilter = ""; RefreshList(); } } // draw name sorter button if (Widgets.ButtonImage(rectSortByNameButton, texSortByName)) { // if other sort option was selected before if (currentSortOption != SortOptions.Name) { // do the ascending sort by cost currentSortOption = SortOptions.Name; sortAscending = true; RefreshList(); } // else inverse the sorting method for the current sort option else { sortAscending = !sortAscending; RefreshList(); } } // draw cost sorter button if (Widgets.ButtonImage(rectSortByCostButton, texSortByCost)) { if (currentSortOption != SortOptions.Cost) { currentSortOption = SortOptions.Cost; sortAscending = true; RefreshList(); } else { sortAscending = !sortAscending; RefreshList(); } } // research projects list var rectResearchesList = rectSidePanel.ContractedBy(10f); rectResearchesList.yMin += 30f; rectResearchesList.height -= 30f; float height = 25 * researchProjectsList.Count() + 100; var sidebarContent = new Rect(0f, 0f, rectResearchesList.width - 16f, height); Widgets.BeginScrollView(rectResearchesList, ref projectListScrollPosition, sidebarContent); var position = sidebarContent.ContractedBy(10f); GUI.BeginGroup(position); var num = 0; foreach (var current in researchProjectsList) { var rectCurrentProject = new Rect(0f, num, position.width, 25f); if (selectedProject == current) { GUI.DrawTexture(rectCurrentProject, TexUI.HighlightTex); } var text = current.LabelCap + " (" + current.CostApparent.ToString("F0") + ")"; var sidebarRowInner = new Rect(rectCurrentProject); sidebarRowInner.x += 6f; sidebarRowInner.width -= 6f; var num2 = Text.CalcHeight(text, sidebarRowInner.width); if (sidebarRowInner.height < num2) { sidebarRowInner.height = num2 + 3f; } // give the label a colour if we're in the all categories. Color textColor; if (showResearchedProjects == ShowResearch.All) { if (current.IsFinished) { textColor = new Color(1f, 1f, 1f); } else if (!current.PrerequisitesCompleted) { textColor = new Color(.6f, .6f, .6f); } else { textColor = new Color(.8f, .85f, 1f); } } else { textColor = new Color(.8f, .85f, 1f); } if (Widgets.ButtonText(sidebarRowInner, text, false, true, textColor)) { SoundDefOf.Click.PlayOneShotOnCamera(); selectedProject = current; } num += 25; } Widgets.EndScrollView(); GUI.EndGroup(); // draw research tabs selection var list = new List<TabRecord> { new TabRecord("Available", () => { showResearchedProjects = ShowResearch.Available; RefreshList(); }, showResearchedProjects == ShowResearch.Available), new TabRecord("Researched", () => { showResearchedProjects = ShowResearch.Completed; RefreshList(); }, showResearchedProjects == ShowResearch.Completed) }; if (Prefs.DevMode) { list.Add(new TabRecord("All", () => { showResearchedProjects = ShowResearch.All; RefreshList(); }, showResearchedProjects == ShowResearch.All)); TabDrawer.DrawTabs(rectSidePanel, list); } }
public byte[][] Sort (SortOptions options) { return SendDataCommandExpectMultiBulkReply(null, options.ToCommand() + "\r\n"); }
public virtual IEnumerable<PlaylistSongRating> GetRatings( short skip, short incremenet, SortOptions sort, bool descending, FbUser currentUser = null) { IEnumerable<PlaylistSongRating> songsRating = Ratings; switch (sort) { case SortOptions.None: break; case SortOptions.DateAdded: songsRating = Ratings.OrderByWithDirection(playlistRatings => playlistRatings.FacebookAddedDate, descending); break; case SortOptions.Popularity: //most voted for songs (not heighest rated songs though) songsRating = Ratings.OrderByWithDirection(playlistRatings => playlistRatings.SummedNegativeRating + playlistRatings.SummedPositiveRating, descending); break; case SortOptions.Rating: songsRating = Ratings.OrderByWithDirection(playlistRatings => playlistRatings.SummedPositiveRating, descending); break; case SortOptions.Me : return songsRating = Ratings.Where(playlistRatings => playlistRatings.Details.Any(details => details.VotingUser == currentUser)); default: break; } return songsRating.Skip(skip).Take(incremenet); }
public AnimeListSortFlyoutItem(SortOptions sorting) : base((int)sorting, TextColorBase) { SortOption = sorting; Text = sorting.GetDescription(); }
public PatternListComparer(SortOptions s) { SortOption = s; }
/// <summary> /// Sets provided sort mode or takes one from settings /// </summary> /// <param name="option"></param> public void SetSortOrder(SortOptions? option) { option = option ?? (WorkMode == AnimeListWorkModes.Manga ? Settings.MangaSortOrder : Settings.AnimeSortOrder); if (Settings.AutoDescendingSorting && option != null) { switch (option) { case SortOptions.SortTitle: _sortDescending = false; break; case SortOptions.SortScore: _sortDescending = true; break; case SortOptions.SortWatched: _sortDescending = WorkMode == AnimeListWorkModes.Anime || WorkMode == AnimeListWorkModes.Manga; break; case SortOptions.SortAirDay: _sortDescending = true; break; case SortOptions.SortLastWatched: _sortDescending = true; break; case SortOptions.SortStartDate: _sortDescending = false; break; case SortOptions.SortEndDate: _sortDescending = true; break; case SortOptions.SortNothing: break; case SortOptions.SortSeason: _sortDescending = true; break; default: throw new ArgumentOutOfRangeException(); } SortingSettingChanged?.Invoke(option.Value,_sortDescending); } SortOption = option.Value; }
private void OnSortingMenuSelectionChanged(SortOptions option) { ViewModel.SetSortOrder(option); ViewModel.RefreshList(); _sortingMenu.Dismiss(true); _sortingMenu = null; }
/// <summary> /// Adds the "sort" custom parameter to the query. /// </summary> /// <param name="sortOption">What sort key should be used when sorting the list.</param> /// <param name="sortDirection">The direction in which to sort.</param> /// <returns>this</returns> public CatalogService SortBy(SortOptions sortOption, SortDirection sortDirection) { string sortOptionValue = string.Empty; string sortDirectionValue = string.Empty; switch (sortOption) { case SortOptions.Popularity: sortOptionValue = "popularity"; break; case SortOptions.Rating: sortOptionValue = "rating"; break; case SortOptions.Vintage: sortOptionValue = "vintage"; break; case SortOptions.Winery: sortOptionValue = "winery"; break; case SortOptions.Name: sortOptionValue = "name"; break; case SortOptions.Price: sortOptionValue = "price"; break; case SortOptions.Saving: sortOptionValue = "saving"; break; case SortOptions.JustIn: sortOptionValue = "justIn"; break; default: // throw an exception ? return this; } switch (sortDirection) { case SortDirection.Ascending: sortDirectionValue = "ascending"; break; case SortDirection.Descending: sortDirectionValue = "descending"; break; default: // throw an exception ? return this; } AppendNameValueToQueryString( "sort", string.Format( "{0}|{1}", sortOptionValue, sortDirectionValue)); return this; }