public async IAsyncEnumerable <Item> GetBalancedItems([EnumeratorCancellation] CancellationToken cancellationToken) { var allItems = await _persistenceProvider.GetItems(_options.Value.ConnectionString, _options.Value.CategorizedFacesContainerName, cancellationToken) .ToListAsync(); var grouped = allItems .GroupBy(item => Path.GetDirectoryName(item)) .Select(group => (Name: group.Key, Count: group.Count(), Items: group.AsEnumerable())) .GroupJoin(_options.Value.CategoriesToIgnore, tuple => tuple.Name.ToLower(), ignore => ignore.ToLower(), (tuple, ignored) => (tuple.Name, tuple.Count, tuple.Items, Include: !ignored.Any())) .Where(tuple => tuple.Include) .ToArray(); var minItems = grouped.Min(group => group.Count); _logger.LogInformation("Balaned input comprises {0} items per category", minItems); foreach (var group in grouped) { foreach (var blobName in group.Items.Take(minItems)) { var item = await _persistenceProvider.GetBlobItemAsync(_options.Value.ConnectionString, _options.Value.CategorizedFacesContainerName, blobName, stream => CreateItem(group.Name, stream), cancellationToken); yield return(item); } } }
public async Task TMostlyValidCharacter() { var defenses = _fullCharacter.Defenses !; defenses.Add(new FullCharacter.CharDefense() { Type = defenses[0].Type, Defense = defenses[1].Defense }); defenses.Add(new FullCharacter.CharDefense() { Type = defenses[1].Type, Defense = defenses[0].Defense }); IActionResult response = await _controller.Create(_fullCharacter); var character = await _db.Characters .Include(c => c.Defenses) .SingleAsync(); if (!(response is ObjectResult objectResponse)) { Assert.IsTrue(false, "controller response should be an object result"); return; } Assert.AreEqual(201, objectResponse.StatusCode, "should have accepted the character"); if (!(objectResponse.Value is HitPointsResult hp)) { Assert.IsTrue(false, "controller should have responded with a hit points result"); return; } Assert.AreEqual(_fullCharacter.Defenses !.Count - 2, character.Defenses.Count, "should have the same number of defenses"); var mismatched = character.Defenses ! .GroupJoin(_fullCharacter.Defenses, c => c.DamageType, fc => fc.Type, (cd, fcd) => ( DamageType: cd.DamageType, InputIsImmune: (fcd.OrderBy(fc => fc.Defense).First().Defense == Immunity), RecordIsImmune: cd.IsImmune ) ) .Where(join => join.InputIsImmune != join.RecordIsImmune) .Select(join => join.DamageType) .ToList(); CollectionAssert.AreEqual(new string[0], mismatched, $"damage immunity mismatch"); }
internal async Task <IEnumerable <VendorInfo> > GetVendorsAsync() { //IEnumerable<VendorInfo> model = await (from v in vendorRepository.Vendors // join p in productRepository.Products on v.VendorID equals p.VendorID // group p by new { p.Vendor.Name } into g // select new VendorInfo() // { // VendorName = g.Key.Name, // ProductCount = g.Count(), // FavoriteProductCount = g.Where(x => x.IsFavorite).Count() // }).ToListAsync(); //TODO: отображать вендора, даже если нет товаров IEnumerable <VendorInfo> model = await(from v in vendorRepository.Vendors join p in productRepository.Products.Include(x => x.Vendor) on v equals p.Vendor into GroupJoin from r in GroupJoin.DefaultIfEmpty() group r by new { r.Vendor.Name } into g select new VendorInfo() { VendorName = (g.Key.Name == null ? "XZ" : g.Key.Name), ProductCount = g.Count(), FavoriteProductCount = g.Where(x => x.IsFavorite).Count() }).ToListAsync(); return(model); }
public vGroupJoin(GroupJoin groupJoin) { ID = groupJoin.ID; UserID = groupJoin.UserID; User = groupJoin.User; Content = groupJoin.Content; Time = groupJoin.Time; }
private void LeftJoin() { var query = from person in MockData.People join pet in MockData.Pets on person.Id equals pet.OwnerId into GroupJoin from pet in GroupJoin.DefaultIfEmpty() select new { OwnerName = person.FirstName + " " + person.LastName, PetName = pet?.Name ?? string.Empty }; }
public IActionResult Callback([FromBody] Updates updates) { switch (updates.Type) { case "confirmation": return(Ok(_configuration["Config:Confirmation"])); case "message_new": { // Десериализация var msg = Message.FromJson(new VkResponse(updates.Object)); var peerId = msg.PeerId; if (msg.Text == "/log") { LogMessage(updates, msg); break; } if (JoinGroupTest(peerId, msg, updates.GroupId)) { break; } var user = _usersState.GetUser(peerId.Value); if (user == null || user != null && !user.RequestToJoinGroptSent) { FirstTimeEnter(peerId, updates.GroupId); } else { SendMessage(peerId, "Если хочешь вступить в эту супер илитную групку, то отвечай на вопросы! " + "И используй кнопки! 😠"); SendMessage(peerId, user.LastQuestion, user.LastKeyboard); } break; } case "group_join": { var peerId = GroupJoin.FromJson(new VkResponse(updates.Object)).UserId; FirstTimeEnter(peerId, updates.GroupId); break; } } return(Ok("ok")); }
public async Task GroupJoin(GroupJoin join) { const string groupJoinMessage = "Спасибо за подписку! ❤\n" + "Если у тебя возникнут вопросы, то ты всегда можешь связаться с администрацией бота " + "при помощи команды 'админ *сообщение*' (подробнее смотри в справке)"; _logger.Information("Пользователь id{0} вступил в группу", join.UserId); await SendMessageToAdmins(join.UserId.Value, "подписался!"); if (join.JoinType.HasValue && join.JoinType != GroupJoinType.Join) { return; } await TrySendMessageToUser(join.UserId.Value, groupJoinMessage); }
// ---------------------------------------------------------- // // -------------------- Page Management --------------------- // // ---------------------------------------------------------- // // --------------- Navigation --------------- // // ------------- Data retrieval ------------- // public static List <AuditProxy> AllLogEntries(DateTime fromDate, DateTime toDate, string tableName, string userID) { DateTime maxTime = toDate.AddDays(1); try { ProjectTileSqlDatabase existingPtDb = SqlServerConnection.ExistingPtDbConnection(); using (existingPtDb) { return((from ae in existingPtDb.AuditEntries join s in existingPtDb.Staff on ae.UserName.Replace(DbUserPrefix, "") equals s.UserID into GroupJoin from ss in GroupJoin.DefaultIfEmpty() where ae.ChangeTime >= fromDate && ae.ChangeTime < maxTime && ae.TableName == tableName && (userID == "" || userID == AllCodes || userID == ae.UserName.Replace(DbUserPrefix, "")) orderby ae.ChangeTime descending, ae.PrimaryValue ascending select new AuditProxy { ID = ae.ID, ActionType = ae.ActionType, User = ss ?? null, UserName = ae.UserName.Replace(DbUserPrefix, ""), ChangeTime = (DateTime)ae.ChangeTime, TableName = ae.TableName, PrimaryColumn = ae.PrimaryColumn, PrimaryValue = ae.PrimaryValue, ChangeColumn = ae.ChangeColumn, OldValue = ae.OldValue, NewValue = ae.NewValue } ).ToList()); } } catch (Exception generalException) { MessageFunctions.Error("Error retrieving log entry details", generalException); return(null); } }
public static void SetErrorLogEntries(DateTime fromDate, DateTime toDate, string type, string userID) { DateTime maxTime = toDate.AddDays(1); try { ProjectTileSqlDatabase existingPtDb = SqlServerConnection.ExistingPtDbConnection(); using (existingPtDb) { ErrorLogEntries = (from el in existingPtDb.ErrorLog join s in existingPtDb.Staff on el.LoggedBy equals s.UserID into GroupJoin from ss in GroupJoin.DefaultIfEmpty() where el.LoggedAt >= fromDate && el.LoggedAt <= maxTime && (type == AllRecords || el.ExceptionType.Replace("System.", "") == type) && (userID == "" || userID == AllCodes || userID == el.LoggedBy.Replace(DbUserPrefix, "")) orderby(DateTime) el.LoggedAt descending select new ErrorProxy { // ID = el.ID, CustomMessage = el.CustomMessage, ExceptionMessage = el.ExceptionMessage, ExceptionType = el.ExceptionType, TargetSite = el.TargetSite, LoggedAt = DbFunctions.CreateDateTime( // Have to do this 'long hand' to make sure we get distinct results ((DateTime)el.LoggedAt).Year, ((DateTime)el.LoggedAt).Month, ((DateTime)el.LoggedAt).Day, ((DateTime)el.LoggedAt).Hour, ((DateTime)el.LoggedAt).Minute, 0), LoggedBy = el.LoggedBy, User = ss ?? null, InnerException = el.InnerException } ).Distinct().ToList(); //foreach (ErrorProxy el in allErrors) //{ // DateTime dt = el.LoggedAt; // el.LoggedAt = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, 0); //} //ErrorLogEntries = allErrors.Select(ae => new ErrorProxy //{ // CustomMessage = ae.CustomMessage, // ExceptionMessage = ae.ExceptionMessage, // ExceptionType = ae.ExceptionType, // TargetSite = ae.TargetSite, // LoggedAt = ae.LoggedAt, // LoggedBy = ae.LoggedBy, // User = ae.User, // InnerException = ae.InnerException //} //).Distinct().ToList(); } } catch (Exception generalException) { MessageFunctions.Error("Error retrieving error log entries", generalException); } }
/// <summary> /// Разобрать из json. /// </summary> /// <param name="response"> Ответ сервера. </param> /// <returns> </returns> public static GroupUpdate FromJson(VkResponse response) { var fromJson = JsonConvert.DeserializeObject <GroupUpdate>(response.ToString()); var resObj = response["object"]; switch (fromJson.Type) { case GroupLongPollUpdateType.MessageNew: case GroupLongPollUpdateType.MessageEdit: case GroupLongPollUpdateType.MessageReply: fromJson.Message = resObj; fromJson.UserId = fromJson.Message.FromId; break; case GroupLongPollUpdateType.MessageAllow: fromJson.MessageAllow = MessageAllow.FromJson(resObj); fromJson.UserId = fromJson.MessageAllow.UserId; break; case GroupLongPollUpdateType.MessageDeny: fromJson.MessageDeny = MessageDeny.FromJson(resObj); fromJson.UserId = fromJson.MessageDeny.UserId; break; case GroupLongPollUpdateType.PhotoNew: fromJson.Photo = resObj; break; case GroupLongPollUpdateType.PhotoCommentNew: case GroupLongPollUpdateType.PhotoCommentEdit: case GroupLongPollUpdateType.PhotoCommentRestore: fromJson.PhotoComment = PhotoComment.FromJson(resObj); fromJson.UserId = fromJson.PhotoComment.FromId; break; case GroupLongPollUpdateType.PhotoCommentDelete: fromJson.PhotoCommentDelete = PhotoCommentDelete.FromJson(resObj); fromJson.UserId = fromJson.PhotoCommentDelete.DeleterId; break; case GroupLongPollUpdateType.AudioNew: fromJson.Audio = resObj; break; case GroupLongPollUpdateType.VideoNew: fromJson.Video = resObj; break; case GroupLongPollUpdateType.VideoCommentNew: case GroupLongPollUpdateType.VideoCommentEdit: case GroupLongPollUpdateType.VideoCommentRestore: fromJson.VideoComment = VideoComment.FromJson(resObj); fromJson.UserId = fromJson.VideoComment.FromId; break; case GroupLongPollUpdateType.VideoCommentDelete: fromJson.VideoCommentDelete = VideoCommentDelete.FromJson(resObj); fromJson.UserId = fromJson.VideoCommentDelete.DeleterId; break; case GroupLongPollUpdateType.WallPostNew: case GroupLongPollUpdateType.WallRepost: fromJson.WallPost = WallPost.FromJson(resObj); fromJson.UserId = fromJson.WallPost.FromId > 0 ? fromJson.WallPost.FromId : null; break; case GroupLongPollUpdateType.WallReplyNew: case GroupLongPollUpdateType.WallReplyEdit: case GroupLongPollUpdateType.WallReplyRestore: fromJson.WallReply = WallReply.FromJson(resObj); fromJson.UserId = fromJson.WallReply.FromId; break; case GroupLongPollUpdateType.WallReplyDelete: fromJson.WallReplyDelete = WallReplyDelete.FromJson(resObj); fromJson.UserId = fromJson.WallReplyDelete.DeleterId; break; case GroupLongPollUpdateType.BoardPostNew: case GroupLongPollUpdateType.BoardPostEdit: case GroupLongPollUpdateType.BoardPostRestore: fromJson.BoardPost = BoardPost.FromJson(resObj); fromJson.UserId = fromJson.BoardPost.FromId > 0 ? fromJson.BoardPost.FromId : (long?)null; break; case GroupLongPollUpdateType.BoardPostDelete: fromJson.BoardPostDelete = BoardPostDelete.FromJson(resObj); break; case GroupLongPollUpdateType.MarketCommentNew: case GroupLongPollUpdateType.MarketCommentEdit: case GroupLongPollUpdateType.MarketCommentRestore: fromJson.MarketComment = MarketComment.FromJson(resObj); fromJson.UserId = fromJson.MarketComment.FromId; break; case GroupLongPollUpdateType.MarketCommentDelete: fromJson.MarketCommentDelete = MarketCommentDelete.FromJson(resObj); fromJson.UserId = fromJson.MarketCommentDelete.DeleterId; break; case GroupLongPollUpdateType.GroupLeave: fromJson.GroupLeave = GroupLeave.FromJson(resObj); fromJson.UserId = fromJson.GroupLeave.IsSelf == true ? fromJson.GroupLeave.UserId : null; break; case GroupLongPollUpdateType.GroupJoin: fromJson.GroupJoin = GroupJoin.FromJson(resObj); fromJson.UserId = fromJson.GroupJoin.UserId; break; case GroupLongPollUpdateType.UserBlock: fromJson.UserBlock = UserBlock.FromJson(resObj); fromJson.UserId = fromJson.UserBlock.AdminId; break; case GroupLongPollUpdateType.UserUnblock: fromJson.UserUnblock = UserUnblock.FromJson(resObj); fromJson.UserId = fromJson.UserUnblock.ByEndDate == true ? null : fromJson.UserUnblock.AdminId; break; case GroupLongPollUpdateType.PollVoteNew: fromJson.PollVoteNew = PollVoteNew.FromJson(resObj); fromJson.UserId = fromJson.PollVoteNew.UserId; break; case GroupLongPollUpdateType.GroupChangePhoto: fromJson.GroupChangePhoto = GroupChangePhoto.FromJson(resObj); fromJson.UserId = fromJson.GroupChangePhoto.UserId; break; case GroupLongPollUpdateType.GroupOfficersEdit: fromJson.GroupOfficersEdit = GroupOfficersEdit.FromJson(resObj); fromJson.UserId = fromJson.GroupOfficersEdit.AdminId; break; } return(fromJson); }
static void Main(string[] args) { List <Students> studentArray = new List <Students> { new Students() { StudentID = 1, StudentName = "John", Age = 18 }, new Students() { StudentID = 2, StudentName = "Steve", Age = 21 }, new Students() { StudentID = 3, StudentName = "Bill", Age = 25 }, new Students() { StudentID = 4, StudentName = "Ram", Age = 20 }, new Students() { StudentID = 5, StudentName = "Ron", Age = 21 }, new Students() { StudentID = 6, StudentName = "Chris", Age = 17 }, new Students() { StudentID = 7, StudentName = "Rob", Age = 18 }, new Students() { StudentID = 8, StudentName = "John", Age = 22 }, new Students() { StudentID = 9, StudentName = "Ram", Age = 55 }, }; //using delegate as parameter List <Students> st = StudentExtension.where (studentArray, delegate(Students std) { return(std.Age > 12 && std.Age < 20); }); foreach (var item in st) { if (item != null) { Console.WriteLine(item.StudentName); } } //same result using lambda expression var result = studentArray.Select(a => a).Where(a => a.Age > 12 && a.Age < 20); PrintCollection(result); //operator ofType var stringResult = studentArray.OfType <string>(); Console.WriteLine("-----------OrderBy, ThenBy (ascending, descending)-----------"); //OrderBy, ThenBy (ascending, descending). Sort first Name i ascendig then sort by Age var orderThenBy = studentArray.OrderBy(x => x.StudentName).ThenByDescending(x => x.Age); Console.WriteLine("OrderBy, ThenBy (ascending, descending)"); PrintCollection(orderThenBy); Console.WriteLine("-----------Group by-----------"); //GroupBy na Lookup //only difference is GroupBy execution is deferred, whereas ToLookup execution is immediate GroupByLookUp grb = new GroupByLookUp(); grb.GroupByAge(studentArray); grb.LookUp(studentArray); Console.WriteLine("-----------Join-----------"); //Join outer and inner collection JoinStudents joins = new JoinStudents(); List <Courses> course = new List <Courses>() { new Courses() { CourseName = "C#", ID = 1 }, new Courses() { CourseName = "Java", ID = 2 }, new Courses() { CourseName = "Perl", ID = 3 }, new Courses() { CourseName = "Cplqs_plqs", ID = 4 }, }; joins.Joins(studentArray, course); Console.WriteLine("-----------GroupJoin-----------"); GroupJoin groupJoinObject = new GroupJoin(); groupJoinObject.GroupJopinInTwoCollection(studentArray); //more example groupJoinObject.SpeakLang(); Console.WriteLine("-----------Aggregate-----------"); List <string> ls = new List <string>() { "one", "two", "three", "four" }; string aggregate = ls.Aggregate((str1, str2) => str1 + "," + str2); Console.WriteLine(aggregate); Console.WriteLine("-----------Extension method: Except-----------"); OperatorExcept excObj = new OperatorExcept(); var excResult = excObj.groupOneOfStudents.Except(excObj.groupTwoOfStudents, new OperatorExcept.StudentComparer()); foreach (var item in excResult) { Console.WriteLine(item.StudentName); } Console.WriteLine("-----------Extension method: Skip/SkipWhile/Take/TakeWhile-----------"); int[] arrs = { 5, 1, 3, 22, 30, 60, 44, 55, 59, 38 }; var numbers = arrs.OrderBy(i => i). SkipWhile(i => i < 30). TakeWhile(i => i < 60); foreach (var number in numbers) { Console.Write(number + " "); } Console.WriteLine("-----------Extension method: ToDictionary-----------"); List <Students> studentsToDict = new List <Students>() { new Students() { StudentID = 1, StudentName = "Peshko", Age = 3 }, new Students() { StudentID = 2, StudentName = "Goshklo", Age = 4 }, new Students() { StudentID = 3, StudentName = "Penio", Age = 5 }, new Students() { StudentID = 4, StudentName = "Vladko", Age = 6 }, new Students() { StudentID = 5, StudentName = "Bai ivan", Age = 1 } }; var toDictionary = studentsToDict.ToDictionary <Students, int>(x => x.Age); List <string> list = new List <string>() { "cat", "dog", "animal" }; var animals = list.ToDictionary(x => x, x => true); if (animals.ContainsKey("dog")) { // This is in the Dictionary. Console.WriteLine("dog exists"); } }
public void ShowExample_Click(object sender, EventArgs e) { Form form = null; switch (((Button)sender).Name) { // LINQ Dynamic | Restriction Operators case "uiROWhere": form = new Where(); break; // LINQ Dynamic | Projection Operators case "uiPOSelect": form = new Select(); break; case "uiPOSelectMany": form = new SelectMany(); break; // LINQ Dynamic | Aggregate Operators case "uiAOMin": form = new Min(); break; case "uiAOMax": form = new Max(); break; case "uiAOSum": form = new Sum(); break; case "uiAOCount": form = new Count(); break; case "uiAOAverage": form = new Average(); break; case "uiAOAggregate": form = new Aggregate(); break; // LINQ Dynamic | Query Execution case "uiQEDeferredExecution": form = new DeferredExecution(); break; case "uiQEQueryReuse": form = new QueryReuse(); break; case "uiQEImmediateExecution": form = new ImmediateExecution(); break; // LINQ Dynamic | Join Operators case "uiJOCrossJoin": form = new CrossJoin(); break; case "uiJOGroupJoin": form = new GroupJoin(); break; case "uiJOCrossWithGroupJoin": form = new CrossJoinwithGroupJoin(); break; case "uiJOLeftOuterJoin": form = new LeftOuterJoin(); break; // LINQ Dynamic | Set Operators case "uiSODistinct": form = new Distinct(); break; case "uiSOExcept": form = new Except(); break; case "uiSOIntersect": form = new Intersect(); break; case "uiSOUnion": form = new Union(); break; // LINQ Dynamic | Element Operators case "uiEOElementAt": form = new ElementAt(); break; case "uiEOFirst": form = new First(); break; case "uiEOFirstDefault": form = new FirstOrDefault(); break; // LINQ Dynamic | Custom Sequence Operators case "uiCSOCombine": form = new Combine(); break; // LINQ Dynamic | Quantifiers case "uiQuantifiersAll": form = new All(); break; case "uiQuantifiersAny": form = new Any(); break; // LINQ Dynamic | Grouping Operators case "uiGOGroupBy": form = new GroupBy(); break; // LINQ Dynamic | Miscellaneous Operators case "uiMOConcat": form = new Concat(); break; case "uiMOEqualAll": form = new EqualAll(); break; // LINQ Dynamic | Generation Operators case "uiGORepeat": form = new Repeat(); break; case "uiGORange": form = new Range(); break; // LINQ Dynamic | Ordering Operators case "uiOOOrderBy": form = new OrderBy(); break; case "uiOOThenBy": form = new ThenBy(); break; case "uiOOThenByDescending": form = new ThenByDescending(); break; case "uiOOOrderByDescending": form = new OrderByDescending(); break; case "uiOOReverse": form = new Reverse(); break; // LINQ Dynamic | Conversion Operators case "uiCOOfType": form = new OfType(); break; case "uiCOToArray": form = new ToArray(); break; case "uiCOToDictionary": form = new ToDictionary(); break; case "uiCOToList": form = new ToList(); break; // LINQ Dynamic | Partitioning Operators case "uiPOTake": form = new Take(); break; case "uiPOTakeWhile": form = new TakeWhile(); break; case "uiPOSkip": form = new Skip(); break; case "uiPOSkipWhile": form = new SkipWhile(); break; } form.StartPosition = FormStartPosition.CenterParent; form.ShowDialog(); }