System.Collections.Generic.IEnumerable.OrderByDescending(System.Func)

Here are the examples of the csharp api System.Collections.Generic.IEnumerable.OrderByDescending(System.Func) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

2229 Examples 7

19 Source : LogLock.cs
with Apache License 2.0
from anjoy8

public static List<LogInfo> GetLogData()
        {
            List<LogInfo> aopLogs = new List<LogInfo>();
            List<LogInfo> excLogs = new List<LogInfo>();
            List<LogInfo> sqlLogs = new List<LogInfo>();
            List<LogInfo> reqresLogs = new List<LogInfo>();

            try
            {
                var aoplogContent = ReadLog(Path.Combine(_contentRoot, "Log"), "AOPLog_", Encoding.UTF8, ReadType.Prefix);

                if (!string.IsNullOrEmpty(aoplogContent))
                {
                    aopLogs = aoplogContent.Split("--------------------------------")
                 .Where(d => !string.IsNullOrEmpty(d) && d != "\n" && d != "\r\n")
                 .Select(d => new LogInfo
                 {
                     Datetime = d.Split("|")[0].ObjToDate(),
                     Content = d.Split("|")[1]?.Replace("\r\n", "<br>"),
                     LogColor = "AOP",
                 }).ToList();
                }
            }
            catch (Exception) { }

            try
            {
                var exclogContent = ReadLog(Path.Combine(_contentRoot, "Log"), $"GlobalExceptionLogs_{DateTime.Now.ToString("yyyMMdd")}.log", Encoding.UTF8);

                if (!string.IsNullOrEmpty(exclogContent))
                {
                    excLogs = exclogContent.Split("--------------------------------")
                                 .Where(d => !string.IsNullOrEmpty(d) && d != "\n" && d != "\r\n")
                                 .Select(d => new LogInfo
                                 {
                                     Datetime = (d.Split("|")[0]).Split(',')[0].ObjToDate(),
                                     Content = d.Split("|")[1]?.Replace("\r\n", "<br>"),
                                     LogColor = "EXC",
                                     Import = 9,
                                 }).ToList();
                }
            }
            catch (Exception) { }


            try
            {
                var sqllogContent = ReadLog(Path.Combine(_contentRoot, "Log"), "SqlLog_", Encoding.UTF8, ReadType.PrefixLatest);

                if (!string.IsNullOrEmpty(sqllogContent))
                {
                    sqlLogs = sqllogContent.Split("--------------------------------")
                                  .Where(d => !string.IsNullOrEmpty(d) && d != "\n" && d != "\r\n")
                                  .Select(d => new LogInfo
                                  {
                                      Datetime = d.Split("|")[0].ObjToDate(),
                                      Content = d.Split("|")[1]?.Replace("\r\n", "<br>"),
                                      LogColor = "SQL",
                                  }).ToList();
                }
            }
            catch (Exception) { }

            //try
            //{
            //    reqresLogs = ReadLog(Path.Combine(_contentRoot, "Log", "RequestResponseLog.log"), Encoding.UTF8)?
            //          .Split("--------------------------------")
            //          .Where(d => !string.IsNullOrEmpty(d) && d != "\n" && d != "\r\n")
            //          .Select(d => new LogInfo
            //          {
            //              Datetime = d.Split("|")[0].ObjToDate(),
            //              Content = d.Split("|")[1]?.Replace("\r\n", "<br>"),
            //              LogColor = "ReqRes",
            //          }).ToList();
            //}
            //catch (Exception)
            //{
            //}

            try
            {
                var Logs = GetRequestInfo(ReadType.PrefixLatest);

                Logs = Logs.Where(d => d.Datetime.ObjToDate() >= DateTime.Today).ToList();

                reqresLogs = Logs.Select(d => new LogInfo
                {
                    Datetime = d.Datetime.ObjToDate(),
                    Content = $"IP:{d.Ip}<br>{d.Url}",
                    LogColor = "ReqRes",
                }).ToList();
            }
            catch (Exception)
            {
            }

            if (excLogs != null)
            {
                aopLogs.AddRange(excLogs);
            }
            if (sqlLogs != null)
            {
                aopLogs.AddRange(sqlLogs);
            }
            if (reqresLogs != null)
            {
                aopLogs.AddRange(reqresLogs);
            }
            aopLogs = aopLogs.OrderByDescending(d => d.Import).ThenByDescending(d => d.Datetime).Take(100).ToList();

            return aopLogs;
        }

19 Source : LogLock.cs
with Apache License 2.0
from anjoy8

public static AccessApiDateView AccessApiByDate()
        {
            List<RequestInfo> Logs = new List<RequestInfo>();
            List<ApiDate> apiDates = new List<ApiDate>();
            try
            {
                Logs = GetRequestInfo(ReadType.Prefix);

                apiDates = (from n in Logs
                            group n by new { n.Date } into g
                            select new ApiDate
                            {
                                date = g.Key.Date,
                                count = g.Count(),
                            }).ToList();

                apiDates = apiDates.OrderByDescending(d => d.date).Take(7).ToList();

            }
            catch (Exception)
            {
            }

            return new AccessApiDateView()
            {
                columns = new string[] { "date", "count" },
                rows = apiDates.OrderBy(d => d.date).ToList(),
            };
        }

19 Source : SwaggerMildd.cs
with Apache License 2.0
from anjoy8

public static void UseSwaggerMildd(this IApplicationBuilder app, Func<Stream> streamHtml)
        {
            if (app == null) throw new ArgumentNullException(nameof(app));

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                //根据版本名称倒序 遍历展示
                var ApiName = Appsettings.app(new string[] { "Startup", "ApiName" });
                typeof(ApiVersions).GetEnumNames().OrderByDescending(e => e).ToList().ForEach(version =>
                {
                    c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"{ApiName} {version}");
                });

                c.SwaggerEndpoint($"https://petstore.swagger.io/v2/swagger.json", $"{ApiName} pet");

                // 将swagger首页,设置成我们自定义的页面,记得这个字符串的写法:{项目名.index.html}
                if (streamHtml.Invoke() == null)
                {
                    var msg = "index.html的属性,必须设置为嵌入的资源";
                    log.Error(msg);
                    throw new Exception(msg);
                }
                c.IndexStream = streamHtml;

                if (Permissions.IsUseIds4)
                {
                    c.OAuthClientId("blogadminjs"); 
                }


                // 路径配置,设置为空,表示直接在根域名(localhost:8001)访问该文件,注意localhost:8001/swagger是访问不到的,去launchSettings.json把launchUrl去掉,如果你想换一个路径,直接写名字即可,比如直接写c.RoutePrefix = "doc";
                c.RoutePrefix = "";
            });
        }

19 Source : OrderMockService.cs
with MIT License
from anjoy8

public async Task<ObservableCollection<Models.Orders.Order>> GetOrdersAsync(string token)
        {
            await Task.Delay(10);

            if (!string.IsNullOrEmpty(token))
            {
                return MockOrders
                    .OrderByDescending(o => o.OrderNumber)
                    .ToObservableCollection();
            }
            else
                return new ObservableCollection<Models.Orders.Order>();
        }

19 Source : FSNController.cs
with Apache License 2.0
from anjoy8

[HttpGet]
        public async Task<MessageModel<PageModel<FSN>>> Get(int GradeId, string AcademicYearSchoolTerm, string ExamName, int fsn, int ClazzId, int page = 1)
        {
            int intPageSize = 100;
            if (!(GradeId > 0 && !string.IsNullOrEmpty(AcademicYearSchoolTerm) && !string.IsNullOrEmpty(ExamName)))
            {
                return new MessageModel<PageModel<FSN>>();
            }

            var exScoreList = await _iExScoreRepository.Query(d => d.IsDeleted == false);

            var gradeList = await _iGradeRepository.Query(d => d.IsDeleted == false && d.Id == GradeId);
            var clazzList = await _iClazzRepository.Query(d => d.IsDeleted == false && d.GradeId == GradeId);
            var courseList = await _iCourseRepository.Query(d => d.IsDeleted == false);
            var examList = await _iExamRepository.Query(d => d.IsDeleted == false && d.gradeid == GradeId);
            var studentsList = await _iStudentsRepository.Query(d => d.IsDeleted == false && d.gradeid == GradeId);
            var cctList = await _iCCTRepository.Query(d => d.IsDeleted == false && d.gradeid == GradeId);
            var teachersList = await _iTeacherRepository.Query(d => d.IsDeleted == false && d.gradeId == GradeId);

            foreach (var item in examList)
            {
                item.grade = gradeList.Where(d => d.Id == item.gradeid).FirstOrDefault();
                item.course = courseList.Where(d => d.Id == item.courseid).FirstOrDefault();
            }

            foreach (var exscore in exScoreList)
            {
                exscore.exam = examList.Where(d => d.Id == exscore.examid).FirstOrDefault();
                var teacherid = cctList.Where(d => d.clazzid == exscore.clazzid && d.gradeid == exscore.exam.gradeid && d.courseid == exscore.exam.courseid).FirstOrDefault()?.teacherid;
                exscore.Teacher = teachersList.Where(d => d.Id == teacherid.ObjToInt()).FirstOrDefault()?.Name;


                exscore.clazz = clazzList.Where(d => d.Id == exscore.clazzid).FirstOrDefault();
                exscore.student = studentsList.Where(d => d.Id == exscore.studentid).FirstOrDefault();
            }


            exScoreList = exScoreList.Where(d => (d.exam != null && d.exam.grade != null && d.exam.grade.Id == GID || (GID == -9999 && true))).ToList();


            if (GradeId > 0)
            {
                exScoreList = exScoreList.Where(d => d.exam != null && d.exam.grade != null && d.exam.gradeid == GradeId).ToList();
            }
            if (!string.IsNullOrEmpty(AcademicYearSchoolTerm))
            {
                exScoreList = exScoreList.Where(d => d.exam != null && d.exam.grade != null && AcademicYearSchoolTerm == (d.exam.AcademicYear + d.exam.SchoolTerm)).ToList();
            }
            if (!string.IsNullOrEmpty(ExamName))
            {
                exScoreList = exScoreList.Where(d => d.exam != null && d.exam.grade != null && d.exam.ExamName == ExamName).ToList();
            }



            List<FSN> FSNs = new List<FSN>();

            foreach (var item in studentsList)
            {
                var clazzModel = clazzList.Where(d => d.Id == item.clazzid).FirstOrDefault();
                var exscoreStudentList = exScoreList.Where(d => d.studentid == item.Id).ToList();

                FSN fSN = new FSN()
                {
                    StudentNo = item.StudentNo,
                    StudentName = item.Name,
                    Clazz = clazzModel.ClreplacedNo,
                    ClazzId = clazzModel.Id,
                    SubjectA = item.SubjectA,
                    SubjectB = item.SubjectB,
                    Chinese = exscoreStudentList.Where(d => d.exam.course.Name == "语文").FirstOrDefault().score,
                    Meth = exscoreStudentList.Where(d => d.exam.course.Name == "数学").FirstOrDefault().score,
                    English = exscoreStudentList.Where(d => d.exam.course.Name == "英语").FirstOrDefault().score,
                    Physics = exscoreStudentList.Where(d => d.exam.course.Name == "物理").FirstOrDefault().score,
                    Chemistry = exscoreStudentList.Where(d => d.exam.course.Name == "化学").FirstOrDefault().score,
                    Politics = exscoreStudentList.Where(d => d.exam.course.Name == "政治").FirstOrDefault().score,
                    History = exscoreStudentList.Where(d => d.exam.course.Name == "历史").FirstOrDefault().score,
                    Biology = exscoreStudentList.Where(d => d.exam.course.Name == "生物").FirstOrDefault().score,
                    Geography = exscoreStudentList.Where(d => d.exam.course.Name == "地理").FirstOrDefault().score,
                };

                fSN.T = fSN.Chinese + fSN.Chinese + fSN.Chinese;

                if (fSN.SubjectA == "物理")
                {
                    fSN.F = fSN.T + fSN.Physics;
                }
                else if (fSN.SubjectA == "历史")
                {
                    fSN.F = fSN.T + fSN.History;
                }

                fSN.S += fSN.F;
                switch (fSN.SubjectB)
                {
                    case "1":
                        fSN.S = fSN.Chemistry + fSN.Biology; break;

                    case "2":
                        fSN.S = fSN.Chemistry + fSN.Politics; break;

                    case "3":
                        fSN.S = fSN.Chemistry + fSN.Geography; break;

                    case "4":
                        fSN.S = fSN.Politics + fSN.Biology; break;

                    case "5":
                        fSN.S = fSN.Geography + fSN.Biology; break;

                    case "6":
                        fSN.S = fSN.Politics + fSN.Geography; break;

                    case "7":
                        fSN.S = fSN.Politics + fSN.Geography; break;

                    case "8":
                        fSN.S = fSN.Politics + fSN.Chemistry; break;

                    case "9":
                        fSN.S = fSN.Politics + fSN.Biology; break;

                    case "10":
                        fSN.S = fSN.Geography + fSN.Chemistry; break;

                    case "11":
                        fSN.S = fSN.Geography + fSN.Biology; break;

                    case "12":
                        fSN.S = fSN.Chemistry + fSN.Biology; break;

                    default:
                        break;
                }

                fSN.N = fSN.Chinese + fSN.Meth + fSN.English + fSN.Physics + fSN.Chemistry + fSN.Biology + fSN.Politics + fSN.History + fSN.Geography;

                FSNs.Add(fSN);
            }




            {
                FSNs = FSNs.OrderByDescending(d => d.Chinese).ToList();
                for (int i = 0; i < FSNs.Count; i++) FSNs[i].ChineseSort = i + 1;

                FSNs = FSNs.OrderByDescending(d => d.Meth).ToList();
                for (int i = 0; i < FSNs.Count; i++) FSNs[i].MethSort = i + 1;

                FSNs = FSNs.OrderByDescending(d => d.English).ToList();
                for (int i = 0; i < FSNs.Count; i++) FSNs[i].EnglishSort = i + 1;

                FSNs = FSNs.OrderByDescending(d => d.Physics).ToList();
                for (int i = 0; i < FSNs.Count; i++) FSNs[i].PhysicsSort = i + 1;

                FSNs = FSNs.OrderByDescending(d => d.Chemistry).ToList();
                for (int i = 0; i < FSNs.Count; i++) FSNs[i].ChemistrySort = i + 1;

                FSNs = FSNs.OrderByDescending(d => d.Politics).ToList();
                for (int i = 0; i < FSNs.Count; i++) FSNs[i].PoliticsSort = i + 1;

                FSNs = FSNs.OrderByDescending(d => d.History).ToList();
                for (int i = 0; i < FSNs.Count; i++) FSNs[i].HistorySort = i + 1;

                FSNs = FSNs.OrderByDescending(d => d.Biology).ToList();
                for (int i = 0; i < FSNs.Count; i++) FSNs[i].BiologySort = i + 1;

                FSNs = FSNs.OrderByDescending(d => d.Geography).ToList();
                for (int i = 0; i < FSNs.Count; i++) FSNs[i].GeographySort = i + 1;

                FSNs = FSNs.OrderByDescending(d => d.T).ToList();
                for (int i = 0; i < FSNs.Count; i++) FSNs[i].TSort = i + 1;

                FSNs = FSNs.OrderByDescending(d => d.F).ToList();
                for (int i = 0; i < FSNs.Count; i++) FSNs[i].FSort = i + 1;

                FSNs = FSNs.OrderByDescending(d => d.S).ToList();
                for (int i = 0; i < FSNs.Count; i++) FSNs[i].SSort = i + 1;

                FSNs = FSNs.OrderByDescending(d => d.N).ToList();
                for (int i = 0; i < FSNs.Count; i++) FSNs[i].NSort = i + 1;

            }


            if (ClazzId > 0)
            {
                FSNs = FSNs.Where(d => d.ClazzId == ClazzId).ToList();
            }



            var totalCount = FSNs.Count;
            int pageCount = (Math.Ceiling(totalCount.ObjToDecimal() / intPageSize.ObjToDecimal())).ObjToInt();


            var exScores = FSNs.Skip((page - 1) * intPageSize).Take(intPageSize).ToList();



            PageModel<FSN> data = new PageModel<FSN>()
            {
                data = exScores,
                dataCount = totalCount,
                page = page,
                pageCount = pageCount,
                PageSize = intPageSize
            };


            return new MessageModel<PageModel<FSN>>()
            {
                msg = "获取成功",
                success = data.dataCount >= 0,
                response = data
            };

        }

19 Source : LogLock.cs
with Apache License 2.0
from anjoy8

public static List<LogInfo> GetLogData()
        {
            List<LogInfo> aopLogs = new List<LogInfo>();
            List<LogInfo> excLogs = new List<LogInfo>();
            List<LogInfo> sqlLogs = new List<LogInfo>();
            List<LogInfo> reqresLogs = new List<LogInfo>();
            try
            {
                aopLogs = ReadLog(Path.Combine(contentRoot, "Log", "AOPLog.log"), Encoding.UTF8)
                .Split("--------------------------------")
                .Where(d => !string.IsNullOrEmpty(d) && d != "\n" && d != "\r\n")
                .Select(d => new LogInfo
                {
                    Datetime = d.Split("|")[0].ObjToDate(),
                    Content = d.Split("|")[1]?.Replace("\r\n", "<br>"),
                    LogColor = "AOP",
                }).ToList();

            }
            catch (Exception)
            {
            }

            try
            {
                excLogs = ReadLog(Path.Combine(contentRoot, "Log", $"GlobalExcepLogs_{DateTime.Now.ToString("yyyMMdd")}.log"), Encoding.UTF8)?
                      .Split("--------------------------------")
                      .Where(d => !string.IsNullOrEmpty(d) && d != "\n" && d != "\r\n")
                      .Select(d => new LogInfo
                      {
                          Datetime = (d.Split("|")[0]).Split(',')[0].ObjToDate(),
                          Content = d.Split("|")[1]?.Replace("\r\n", "<br>"),
                          LogColor = "EXC",
                          Import = 9,
                      }).ToList();
            }
            catch (Exception)
            {
            }


            try
            {
                sqlLogs = ReadLog(Path.Combine(contentRoot, "Log", "SqlLog.log"), Encoding.UTF8)
                      .Split("--------------------------------")
                      .Where(d => !string.IsNullOrEmpty(d) && d != "\n" && d != "\r\n")
                      .Select(d => new LogInfo
                      {
                          Datetime = d.Split("|")[0].ObjToDate(),
                          Content = d.Split("|")[1]?.Replace("\r\n", "<br>"),
                          LogColor = "SQL",
                      }).ToList();
            }
            catch (Exception)
            {
            }

            try
            {
                reqresLogs = ReadLog(Path.Combine(contentRoot, "Log", "RequestResponseLog.log"), Encoding.UTF8)
                      .Split("--------------------------------")
                      .Where(d => !string.IsNullOrEmpty(d) && d != "\n" && d != "\r\n")
                      .Select(d => new LogInfo
                      {
                          Datetime = d.Split("|")[0].ObjToDate(),
                          Content = d.Split("|")[1]?.Replace("\r\n", "<br>"),
                          LogColor = "ReqRes",
                      }).ToList();
            }
            catch (Exception)
            {
            }

            if (excLogs != null)
            {
                aopLogs.AddRange(excLogs);
            }
            if (sqlLogs != null)
            {
                aopLogs.AddRange(sqlLogs);
            }
            if (reqresLogs != null)
            {
                aopLogs.AddRange(reqresLogs);
            }
            aopLogs = aopLogs.OrderByDescending(d => d.Import).ThenByDescending(d => d.Datetime).Take(100).ToList();

            return aopLogs;
        }

19 Source : PositivePointController.cs
with Apache License 2.0
from anjoy8

[HttpGet]
        public async Task<MessageModel<List<PositivePointTotal>>> Get(int GradeId, string AcademicYearSchoolTerm, string ExamName, int CourseId, int ClazzId, int page = 1)
        {
            int intPageSize = 100;
            if (!(GradeId > 0 && CourseId > 0 && !string.IsNullOrEmpty(AcademicYearSchoolTerm) && !string.IsNullOrEmpty(ExamName)))
            {
                return new MessageModel<List<PositivePointTotal>>();
            }

            var exScoreList = await _iExScoreRepository.Query(d => d.IsDeleted == false);

            var gradeList = await _iGradeRepository.Query(d => d.IsDeleted == false && d.Id == GradeId);
            var clazzList = await _iClazzRepository.Query(d => d.IsDeleted == false && d.GradeId == GradeId);
            var courseList = await _iCourseRepository.Query(d => d.IsDeleted == false);
            var examList = await _iExamRepository.Query(d => d.IsDeleted == false && d.gradeid == GradeId);
            var studentsList = await _iStudentsRepository.Query(d => d.IsDeleted == false && d.gradeid == GradeId);
            var cctList = await _iCCTRepository.Query(d => d.IsDeleted == false && d.gradeid == GradeId);
            var teachersList = await _iTeacherRepository.Query(d => d.IsDeleted == false && d.gradeId == GradeId);


            foreach (var item in examList)
            {
                item.grade = gradeList.Where(d => d.Id == item.gradeid).FirstOrDefault();
                item.course = courseList.Where(d => d.Id == item.courseid).FirstOrDefault();
            }

            foreach (var exscore in exScoreList)
            {
                try
                {
                    exscore.exam = examList.Where(d => d.Id == exscore.examid).FirstOrDefault();
                    var teacherid = cctList.Where(d => d.clazzid == exscore.clazzid && d.gradeid == exscore.exam.gradeid && d.courseid == exscore.exam.courseid).FirstOrDefault()?.teacherid;
                    exscore.Teacher = teachersList.Where(d => d.Id == teacherid.ObjToInt()).FirstOrDefault()?.Name;


                    exscore.clazz = clazzList.Where(d => d.Id == exscore.clazzid).FirstOrDefault();
                    exscore.student = studentsList.Where(d => d.Id == exscore.studentid).FirstOrDefault();
                }
                catch (Exception ex)
                {

                }
            }


            exScoreList = exScoreList.Where(d => (d.exam != null && d.exam.grade != null && d.exam.grade.Id == GID || (GID == -9999 && true))).ToList();

            // 统计 全年级的 某次考试 全部科目的 全部成绩
            var examSortAllCourse = exScoreList.Where(d => AcademicYearSchoolTerm == (d.exam?.AcademicYear + d.exam?.SchoolTerm) && d.exam?.ExamName == ExamName && d.exam?.gradeid == GradeId).ToList();


            // 统计 全年级的 某次考试 某门科目中 的全部成绩
            var exscoreGrade = examSortAllCourse.Where(d => d.courseid == CourseId).ToList();


            List<PositivePoint> totalGradePositivePoints = new List<PositivePoint>();


            foreach (var item in exscoreGrade)
            {

                PositivePoint PositivePoint = new PositivePoint()
                {
                    StudentNo = item.student.StudentNo,
                    StudentName = item.student.Name,
                    BaseSort = item.BaseSort.ObjToInt(),
                    Score = item.score.ObjToDecimal(),
                    Clazz = item.clazz.ClreplacedNo,
                    Teacher = item.Teacher,
                    Clazzid = item.clazz.Id,

                };
                totalGradePositivePoints.Add(PositivePoint);
            }

            // 基础名次排序 —— 求出来 基础名次ok,序号,本次基础
            totalGradePositivePoints = totalGradePositivePoints.OrderBy(d => d.BaseSort).ToList();

            List<int> baseSortArr = new List<int>();
            var j = 1;
            var clazzCount = clazzList.Count;
            var totalStudentCount = studentsList.Count;
            var examStudentCount = totalGradePositivePoints.Count;

            for (int i = 1; i <= totalGradePositivePoints.Count; i++)
            {
                var item = totalGradePositivePoints[i - 1];
                item.Xuhao = i;

                if (!baseSortArr.Contains(item.BaseSort))
                {
                    j = i;
                    baseSortArr.Add(item.BaseSort);
                }

                item.BaseSortOK = j;
                item.ThisBase = (examStudentCount - (i - 1))*0.01 * clazzCount * 100 / (0.01 * ((examStudentCount + 1)/ 2)* examStudentCount);
            }

            // 基础名次OK排名 —— 求出来 本次基础ok
            totalGradePositivePoints = totalGradePositivePoints.OrderBy(d => d.BaseSortOK).ToList();
            for (int i = 1; i <= totalGradePositivePoints.Count; i++)
            {
                var item = totalGradePositivePoints[i - 1];
                var avgList = totalGradePositivePoints.Where(d => d.BaseSortOK == item.BaseSortOK).Select(d => d.ThisBase).ToList();
                item.ThisBaseOk = avgList.Sum() / avgList.Count;
            }

            // 根据分数排序 —— 得到年级排序ok,序号,本次考试
            totalGradePositivePoints = totalGradePositivePoints.OrderByDescending(d => d.Score).ToList();

            List<decimal> scoreArr = new List<decimal>();
            for (int i = 1; i <= totalGradePositivePoints.Count; i++)
            {
                var item = totalGradePositivePoints[i - 1];
                item.Xuhao = i;

                if (!scoreArr.Contains(item.Score))
                {
                    j = i;
                    scoreArr.Add(item.Score);
                }

                item.GradeSortOk = j;
                item.ThisExam = (examStudentCount - (i - 1)) * 0.01 * clazzCount * 100 / (0.01 * ((examStudentCount + 1) / 2) * examStudentCount);
            }



            // 年级重排OK排名 —— 求出来 本次考试ok
            totalGradePositivePoints = totalGradePositivePoints.OrderBy(d => d.GradeSortOk).ToList();
            for (int i = 1; i <= totalGradePositivePoints.Count; i++)
            {
                var item = totalGradePositivePoints[i - 1];
                var avgList = totalGradePositivePoints.Where(d => d.GradeSortOk == item.GradeSortOk).Select(d => d.ThisExam).ToList();
                item.ThisExamOk = avgList.Sum() / avgList.Count;
            }



            var clazzids = clazzList.Where(d => d.GradeId == GradeId).GroupBy(x => new { x.Id }).Select(s => s.First()).ToList();



            // ↑↑↑↑每个考生正负分完成↑↑↑↑↑↑



            List<PositivePointTotal>  positivePointTotals = new List<PositivePointTotal>();

            foreach (var item in clazzids)
            {
                var totalGradePositivePointsClazz = totalGradePositivePoints.Where(d => d.Clazzid == item.Id).ToList();

                PositivePointTotal positivePointTotal = new PositivePointTotal() {
                    Clazz = item.ClreplacedNo,
                    Teacher = totalGradePositivePointsClazz.FirstOrDefault()?.Teacher,
                    TotalStudentCount = studentsList.Where(d => d.clazzid == item.Id).Count(),
                    ExamStudentCount= totalGradePositivePointsClazz.Count,
                    ThisBaseOk= totalGradePositivePointsClazz.Select(d=>d.ThisBaseOk).Sum(),
                    ThisExamOk= totalGradePositivePointsClazz.Select(d=>d.ThisExamOk).Sum(),
                };

                positivePointTotal.NoExamStudentCount = positivePointTotal.TotalStudentCount- positivePointTotal.ExamStudentCount;
                positivePointTotal.RankBase = positivePointTotal.ThisExamOk - positivePointTotal.ThisBaseOk;


                positivePointTotal.ThisBaseOk= Math.Round(positivePointTotal.ThisBaseOk, 2, MidpointRounding.AwayFromZero);
                positivePointTotal.ThisExamOk = Math.Round(positivePointTotal.ThisExamOk, 2, MidpointRounding.AwayFromZero);
                positivePointTotal.ThisOk = positivePointTotal.ThisExamOk;
                positivePointTotal.RankBase = Math.Round(positivePointTotal.RankBase, 2, MidpointRounding.AwayFromZero);


                positivePointTotals.Add(positivePointTotal);
            }




            return new MessageModel<List<PositivePointTotal>>()
            {
                msg = "获取成功",
                success = positivePointTotals.Count >= 0,
                response = positivePointTotals
            };

        }

19 Source : SmartPlaylist.cs
with GNU Affero General Public License v3.0
from ankenyr

public override IEnumerable<BaseItem> OrderBy(IEnumerable<BaseItem> items)
        {
            return items.OrderByDescending(x => x.PremiereDate);
        }

19 Source : SingleCourseController.cs
with Apache License 2.0
from anjoy8

[HttpGet]
        public async Task<MessageModel<PageModel<SingleCourse>>> Get(int GradeId, string AcademicYearSchoolTerm, string ExamName, int CourseId, int ClazzId, int page = 1)
        {
            int intPageSize = 100;
            if (!(GradeId > 0 && CourseId > 0 && !string.IsNullOrEmpty(AcademicYearSchoolTerm) && !string.IsNullOrEmpty(ExamName)))
            {
                return new MessageModel<PageModel<SingleCourse>>();
            }

            var exScoreList = await _iExScoreRepository.Query(d => d.IsDeleted == false);

            var gradeList = await _iGradeRepository.Query(d => d.IsDeleted == false && d.Id == GradeId);
            var clazzList = await _iClazzRepository.Query(d => d.IsDeleted == false && d.GradeId == GradeId);
            var courseList = await _iCourseRepository.Query(d => d.IsDeleted == false);
            var examList = await _iExamRepository.Query(d => d.IsDeleted == false && d.gradeid == GradeId);
            var studentsList = await _iStudentsRepository.Query(d => d.IsDeleted == false && d.gradeid == GradeId);
            var cctList = await _iCCTRepository.Query(d => d.IsDeleted == false && d.gradeid == GradeId);
            var teachersList = await _iTeacherRepository.Query(d => d.IsDeleted == false && d.gradeId == GradeId);


            var leaveCourseIds = courseList.Where(d => d.Name == "化学" || d.Name == "生物" || d.Name == "政治" || d.Name == "地理").Select(d => d.Id).ToList();

            foreach (var item in examList)
            {
                item.grade = gradeList.Where(d => d.Id == item.gradeid).FirstOrDefault();
                item.course = courseList.Where(d => d.Id == item.courseid).FirstOrDefault();
            }

            foreach (var exscore in exScoreList)
            {
                try
                {
                    exscore.exam = examList.Where(d => d.Id == exscore.examid).FirstOrDefault();
                    var teacherid = cctList.Where(d => d.clazzid == exscore.clazzid && d.gradeid == exscore.exam.gradeid && d.courseid == exscore.exam.courseid).FirstOrDefault()?.teacherid;
                    exscore.Teacher = teachersList.Where(d => d.Id == teacherid.ObjToInt()).FirstOrDefault()?.Name;


                    exscore.clazz = clazzList.Where(d => d.Id == exscore.clazzid).FirstOrDefault();
                    exscore.student = studentsList.Where(d => d.Id == exscore.studentid).FirstOrDefault();
                }
                catch (Exception ex)
                {

                }
            }


            exScoreList = exScoreList.Where(d => (d.exam != null && d.exam.grade != null && d.exam.grade.Id == GID || (GID == -9999 && true))).ToList();

            // 统计 全年级的 某次考试 全部科目的 全部成绩
            var examSortAllCourse = exScoreList.Where(d => AcademicYearSchoolTerm == (d.exam?.AcademicYear + d.exam?.SchoolTerm) && d.exam?.ExamName == ExamName && d.exam?.gradeid == GradeId).ToList();


            // 统计 全年级的 某次考试 某门科目中 的全部成绩
            var exscoreGrade = examSortAllCourse.Where(d => d.courseid == CourseId).ToList();


            List<SingleCourse> totalGradeSingleCourses = new List<SingleCourse>();


            foreach (var item in exscoreGrade)
            {
                var studentAllCourseScore = (examSortAllCourse.Where(d => d.studentid == item.studentid).ToList()).Select(d => d.score).ToList();

                SingleCourse SingleCourse = new SingleCourse()
                {
                    StudentNo = item.student.StudentNo,
                    StudentName = item.student.Name,
                    TotalScore = item.score.ObjToDecimal(),
                    SubjectiveScore = item.SubjectiveScore.ObjToDecimal(),
                    ObjectiveScore = item.ObjectiveScore.ObjToDecimal(),
                    Clazz = item.clazz.ClreplacedNo,
                    Clazzid = item.clazz.Id,
                    courseid=item.courseid,
                    TotalNineScore = (studentAllCourseScore.Sum()).ObjToDecimal(),
                    TotalNineScoreSort = item.BaseSort.ObjToInt(),
                };
                totalGradeSingleCourses.Add(SingleCourse);
            }

            //totalGradeSingleCourses = totalGradeSingleCourses.OrderByDescending(d => d.TotalNineScore).ToList();

            //for (int i = 0; i < totalGradeSingleCourses.Count; i++)
            //{
            //    var item = totalGradeSingleCourses[i];
            //    item.TotalNineScoreSort = (i + 1);
            //}

            totalGradeSingleCourses = totalGradeSingleCourses.OrderByDescending(d => d.TotalScore).ToList();

            List<decimal> scoreLeaveA = new List<decimal>();
            List<decimal> scoreLeaveB = new List<decimal>();
            List<decimal> scoreLeaveC = new List<decimal>();
            List<decimal> scoreLeaveD = new List<decimal>();
            List<decimal> scoreLeaveE = new List<decimal>();

            decimal leaveIndex = 0;
            foreach (var item in totalGradeSingleCourses)
            {
                leaveIndex++;
                item.GradeSort = leaveIndex.ObjToInt();


                if (leaveCourseIds.Contains(item.courseid))
                {

                    if (scoreLeaveA.Contains(item.TotalScore))
                    {
                        item.Leave = "A";
                    }
                    else if (scoreLeaveB.Contains(item.TotalScore))
                    {
                        item.Leave = "B";
                    }
                    else if (scoreLeaveC.Contains(item.TotalScore))
                    {
                        item.Leave = "C";
                    }
                    else if (scoreLeaveD.Contains(item.TotalScore))
                    {
                        item.Leave = "D";
                    }
                    else if (scoreLeaveE.Contains(item.TotalScore))
                    {
                        item.Leave = "E";
                    }
                    else
                    {
                        var totalStudent = totalGradeSingleCourses.Count.ObjToDecimal();

                        if (leaveIndex / totalStudent <= (decimal)0.17)
                        {
                            item.Leave = "A";
                            scoreLeaveA.Add(item.TotalScore);
                        }
                        else if (leaveIndex / totalStudent <= (decimal)0.50)
                        {
                            item.Leave = "B";
                            scoreLeaveB.Add(item.TotalScore);
                        }
                        else if (leaveIndex / totalStudent <= (decimal)0.83)
                        {
                            item.Leave = "C";
                            scoreLeaveC.Add(item.TotalScore);
                        }
                        else if (leaveIndex / totalStudent <= (decimal)0.98)
                        {
                            item.Leave = "D";
                            scoreLeaveD.Add(item.TotalScore);
                        }
                        else
                        {
                            item.Leave = "E";
                            scoreLeaveE.Add(item.TotalScore);
                        }
                    }
                }
            }




            // ↓↓↓四科参考分↓↓↓

            var aMaxStudent = GetStudentMax(totalGradeSingleCourses,"A");
            var aMinStudent = GetStudentMin(totalGradeSingleCourses, "A");
            var aMaxLeave = 100;
            var aMinLeave = 83;

            var bMaxStudent = GetStudentMax(totalGradeSingleCourses, "B");
            var bMinStudent = GetStudentMin(totalGradeSingleCourses, "B");
            var bMaxLeave = 82;
            var bMinLeave = 71;

            var cMaxStudent = GetStudentMax(totalGradeSingleCourses, "C");
            var cMinStudent = GetStudentMin(totalGradeSingleCourses, "C");
            var cMaxLeave = 70;
            var cMinLeave = 59;

            var dMaxStudent = GetStudentMax(totalGradeSingleCourses, "D");
            var dMinStudent = GetStudentMin(totalGradeSingleCourses, "D");
            var dMaxLeave = 58;
            var dMinLeave = 41;

            var eMaxStudent = GetStudentMax(totalGradeSingleCourses, "E");
            var eMinStudent = GetStudentMin(totalGradeSingleCourses, "E");
            var eMaxLeave = 40;
            var eMinLeave = 30;

            for (int i = 0; i < totalGradeSingleCourses.Count; i++)
            {
                var item = totalGradeSingleCourses[i];
                if (leaveCourseIds.Contains(item.courseid))
                {
                    if (item.Leave == "A")
                    {
                        item.ReferenceLeaveScore = (aMaxLeave - aMinLeave) / (aMaxStudent - aMinStudent) * (item.TotalScore - aMinStudent) + aMinLeave;
                    }
                    else if (item.Leave == "B")
                    {
                        item.ReferenceLeaveScore = (bMaxLeave - bMinLeave) / (bMaxStudent - bMinStudent) * (item.TotalScore - bMinStudent) + bMinLeave;
                    }
                    else if (item.Leave == "C")
                    {
                        item.ReferenceLeaveScore = (cMaxLeave - cMinLeave) / (cMaxStudent - cMinStudent) * (item.TotalScore - cMinStudent) + cMinLeave;
                    }
                    else if (item.Leave == "D")
                    {
                        item.ReferenceLeaveScore = (dMaxLeave - dMinLeave) / (dMaxStudent - dMinStudent) * (item.TotalScore - dMinStudent) + dMinLeave;
                    }
                    else if (item.Leave == "E")
                    {
                        item.ReferenceLeaveScore = (eMaxLeave - eMinLeave) / (eMaxStudent - eMinStudent) * (item.TotalScore - eMinStudent) + eMinLeave;
                    }
                    else
                    {
                        item.ReferenceLeaveScore = 0;
                    }
                }

                item.ReferenceLeaveScore = Math.Round(item.ReferenceLeaveScore, 1, MidpointRounding.AwayFromZero);
            }


            // ↑↑↑四科参考分↑↑↑


            var clazzids = clazzList.Where(d => d.GradeId == GradeId).GroupBy(x => new { x.Id }).Select(s => s.First()).ToList();

            List<SingleCourse> dataSC = new List<SingleCourse>();

            foreach (var item in clazzids)
            {
                var totalGradeSingleCoursesClazz = totalGradeSingleCourses.Where(d => d.Clazzid == item.Id).ToList();
                totalGradeSingleCoursesClazz = totalGradeSingleCoursesClazz.OrderByDescending(d => d.TotalScore).ToList();


                for (int i = 0; i < totalGradeSingleCoursesClazz.Count; i++)
                {
                    var itemClazz = totalGradeSingleCoursesClazz[i];
                    itemClazz.ClazzSort = (i + 1);
                }
                dataSC.AddRange(totalGradeSingleCoursesClazz);
            }



            if (ClazzId > 0)
            {
                dataSC = dataSC.Where(d => d.Clazzid == ClazzId).ToList();
            }


            var totalCount = dataSC.Count;
            int pageCount = (Math.Ceiling(totalCount.ObjToDecimal() / intPageSize.ObjToDecimal())).ObjToInt();


            var exScores = dataSC.Skip((page - 1) * intPageSize).Take(intPageSize).ToList();



            PageModel<SingleCourse> data = new PageModel<SingleCourse>()
            {
                data = exScores,
                dataCount = totalCount,
                page = page,
                pageCount = pageCount,
                PageSize = intPageSize
            };


            return new MessageModel<PageModel<SingleCourse>>()
            {
                msg = "获取成功",
                success = data.dataCount >= 0,
                response = data
            };

        }

19 Source : StatisticsViewModel.cs
with MIT License
from AnnoDesigner

private ObservableCollection<StatisticsBuilding> GetStatisticBuildings(IEnumerable<IGrouping<string, LayoutObject>> groupedBuildingsByIdentifier, BuildingPresets buildingPresets)
        {
            if (groupedBuildingsByIdentifier is null || !groupedBuildingsByIdentifier.Any())
            {
                return new ObservableCollection<StatisticsBuilding>();
            }

            var tempList = new List<StatisticsBuilding>();

            var validBuildingsGrouped = groupedBuildingsByIdentifier
                        .Where(_ => !_.ElementAt(0).WrappedAnnoObject.Road && _.ElementAt(0).Identifier != null)
                        .OrderByDescending(_ => _.Count());
            foreach (var item in validBuildingsGrouped)
            {
                var statisticBuilding = new StatisticsBuilding();

                var identifierToCheck = item.ElementAt(0).Identifier;
                if (!string.IsNullOrWhiteSpace(identifierToCheck))
                {
                    //try to find building in presets by identifier
                    if (!_cachedPresetsBuilding.TryGetValue(identifierToCheck, out var building))
                    {
                        building = buildingPresets.Buildings.Find(_ => string.Equals(_.Identifier, identifierToCheck, StringComparison.OrdinalIgnoreCase));
                        _cachedPresetsBuilding.TryAdd(identifierToCheck, building);
                    }

                    var isUnknownObject = string.Equals(identifierToCheck, "Unknown Object", StringComparison.OrdinalIgnoreCase);
                    if (building != null || isUnknownObject)
                    {
                        statisticBuilding.Count = item.Count();
                        statisticBuilding.Name = isUnknownObject ? _localizationHelper.GetLocalization("UnknownObject") : building.Localization[_commons.CurrentLanguageCode];
                    }
                    else
                    {
                        /// Ruled those 2 out to keep Building Name Changes done through the Labeling of the building
                        /// and when the building is not in the preset. Those statisticBuildings.name will not translated to
                        /// other luangages anymore, as users can give there own names.
                        /// However i made it so, that if localizations get those translations, it will translated.
                        /// 06-02-2021, on request of user(s) on Discord read this on
                        /// https://discord.com/channels/571011757317947406/571011757317947410/800118895855665203
                        //item.ElementAt(0).Identifier = "";
                        //statisticBuilding.Name = _localizationHelper.GetLocalization("StatNameNotFound");

                        statisticBuilding.Count = item.Count();
                        statisticBuilding.Name = _localizationHelper.GetLocalization(item.ElementAt(0).Identifier);
                    }
                }
                else
                {
                    statisticBuilding.Count = item.Count();
                    statisticBuilding.Name = _localizationHelper.GetLocalization("StatNameNotFound");
                }

                tempList.Add(statisticBuilding);
            }

            return new ObservableCollection<StatisticsBuilding>(tempList.OrderByDescending(x => x.Count).ThenBy(x => x.Name, StringComparer.OrdinalIgnoreCase));
        }

19 Source : MainWindowViewModel.cs
with MIT License
from AnnoDesigner

private void fillAvailableTemplates(BuildingPresets buildingPresets)
        {
            AvailableTemplates.Clear();

            var allTemplates = new Dictionary<string, int>();
            foreach (var curBuilding in buildingPresets.Buildings)
            {
                if (string.IsNullOrWhiteSpace(curBuilding.Template))
                {
                    continue;
                }

                if (!allTemplates.ContainsKey(curBuilding.Template))
                {
                    allTemplates.Add(curBuilding.Template, 1);
                }
                else
                {
                    allTemplates[curBuilding.Template] = ++allTemplates[curBuilding.Template];
                }
            }

            var templateListOrderedByOccurrence = allTemplates.OrderByDescending(x => x.Value).ToList();
            var templateNameList = allTemplates.OrderBy(x => x.Key).Select(x => x.Key).ToList();

            foreach (var curTemplateName in templateNameList)
            {
                AvailableTemplates.Add(curTemplateName);
            }
        }

19 Source : MainWindowViewModel.cs
with MIT License
from AnnoDesigner

private void fillAvailableIdentifiers(BuildingPresets buildingPresets)
        {
            AvailableIdentifiers.Clear();

            var allIdentifiers = new Dictionary<string, int>();
            foreach (var curBuilding in buildingPresets.Buildings)
            {
                if (string.IsNullOrWhiteSpace(curBuilding.Identifier))
                {
                    continue;
                }

                if (!allIdentifiers.ContainsKey(curBuilding.Identifier))
                {
                    allIdentifiers.Add(curBuilding.Identifier, 1);
                }
                else
                {
                    allIdentifiers[curBuilding.Identifier] = ++allIdentifiers[curBuilding.Identifier];
                }
            }

            var identifierListOrderedByOccurrence = allIdentifiers.OrderByDescending(x => x.Value).ToList();
            var identifierNameList = allIdentifiers.OrderBy(x => x.Key).Select(x => x.Key).ToList();

            foreach (var curIdentifierName in identifierNameList)
            {
                AvailableIdentifiers.Add(curIdentifierName);
            }
        }

19 Source : EventSystem.cs
with MIT License
from AnotherEnd15

public override string ToString()
		{
			StringBuilder sb = new StringBuilder();
			HashSet<Type> noParent = new HashSet<Type>();
			Dictionary<Type, int> typeCount = new Dictionary<Type, int>();
			
			HashSet<Type> noDomain = new HashSet<Type>();
			
			foreach (var kv in this.allComponents)
			{
				Type type = kv.Value.GetType();
				if (kv.Value.Parent == null)
				{
					noParent.Add(type);
				}
				
				if (kv.Value.Domain == null)
				{
					noDomain.Add(type);
				}
				
				if (typeCount.ContainsKey(type))
				{
					typeCount[type]++;
				}
				else
				{
					typeCount[type] = 1;
				}
			}

			sb.AppendLine("not set parent type: ");
			foreach (Type type in noParent)
			{
				sb.AppendLine($"\t{type.Name}");	
			}
			
			sb.AppendLine("not set domain type: ");
			foreach (Type type in noDomain)
			{
				sb.AppendLine($"\t{type.Name}");	
			}

			IOrderedEnumerable<KeyValuePair<Type, int>> orderByDescending = typeCount.OrderByDescending(s => s.Value);
			
			sb.AppendLine("Enreplacedy Count: ");
			foreach (var kv in orderByDescending)
			{
				if (kv.Value == 1)
				{
					continue;
				}
				sb.AppendLine($"\t{kv.Key.Name}: {kv.Value}");
			}

			return sb.ToString();
		}

19 Source : ParseTotalModel.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

public async Task GetParseAsync(
            string characterName,
            string server,
            FFLogsRegions region,
            Job job,
            bool isTest = false)
        {
            // 前の処理の完了を待つ
            for (int i = 0; i < (CheckLimit / CheckInterval); i++)
            {
                if (!isDownloading)
                {
                    break;
                }

                var wait = Random.Next(CheckInterval - 50, CheckInterval);
                await Task.Delay(wait);
            }

            lock (DownlodingLocker)
            {
                if (isDownloading)
                {
                    return;
                }

                isDownloading = true;
            }

            var code = HttpStatusCode.Continue;
            var json = string.Empty;
            var message = string.Empty;

            try
            {
                // サーバー名からKrプレフィックスを除去する
                if (server.StartsWith(ServerPrefixKR))
                {
                    server = server.Replace(ServerPrefixKR, string.Empty);
                }

                if (string.IsNullOrEmpty(Settings.Instance.FFLogs.ApiKey))
                {
                    this.SetMessage(NoAPIKeyMessage);
                    Clear();
                    return;
                }

                if (string.IsNullOrEmpty(characterName))
                {
                    this.SetMessage(NoCharacterNameMessage);
                    Clear();
                    return;
                }

                if (string.IsNullOrEmpty(server))
                {
                    this.SetMessage(NoServerMessage);
                    Clear();
                    return;
                }

                var parreplacedion = Settings.Instance.FFLogs.Parreplacedion;

                if (!isTest)
                {
                    // 同じ条件でn分以内ならば再取得しない
                    if (characterName == this.CharacterNameFull &&
                        server == this.Server &&
                        region == this.Region &&
                        parreplacedion == this.previousParreplacedion)
                    {
                        var interval = Settings.Instance.FFLogs.RefreshInterval;
                        if (!this.ExistsParses)
                        {
                            interval /= 2.0;
                        }

                        if (interval < 1.0d)
                        {
                            interval = 1.0d;
                        }

                        if ((DateTime.Now - this.Timestamp).TotalMinutes <= interval)
                        {
                            return;
                        }
                    }
                }

                this.Timestamp = DateTime.Now;
                this.SetMessage(LoadingMessage);

                var uri = string.Format(
                    "parses/character/{0}/{1}/{2}",
                    Uri.EscapeUriString(characterName),
                    Uri.EscapeUriString(server),
                    region.ToString());

                var query = HttpUtility.ParseQueryString(string.Empty);
                query["timeframe"] = "historical";
                query["api_key"] = Settings.Instance.FFLogs.ApiKey;

                if (parreplacedion != FFLogsParreplacedions.Current)
                {
                    query["parreplacedion"] = ((int)parreplacedion).ToString();
                }

                uri += $"?{query.ToString()}";

                this.previousParreplacedion = parreplacedion;

                var parses = default(ParseModel[]);

                try
                {
                    var res = await this.HttpClient.GetAsync(uri);
                    code = res.StatusCode;
                    if (code != HttpStatusCode.OK)
                    {
                        if (code != HttpStatusCode.BadRequest)
                        {
                            this.SetMessage($"{NoDataMessage} ({(int)code})");
                        }
                        else
                        {
                            this.SetMessage(NoDataMessage);
                        }

                        Clear();
                        return;
                    }

                    json = await res.Content.ReadreplacedtringAsync();
                    parses = JsonConvert.DeserializeObject<ParseModel[]>(json);

                    if (parses == null ||
                        parses.Length < 1)
                    {
                        this.SetMessage(NoDataMessage);
                        Clear();
                        return;
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(
                        ex,
                        $"Error FFLogs API. charactername={characterName} server={server} region={region} uri={uri}");

                    this.SetMessage(ErrorMessage);
                    Clear();
                    return;
                }

                var filter = default(Predicate<ParseModel>);
                if (job != null &&
                    parses.Any(x => x.IsEqualToSpec(job)))
                {
                    filter = x => x.IsEqualToSpec(job);
                }

                var bests =
                    from x in parses
                    where
                    (filter?.Invoke(x) ?? true) &&
                    x.Difficulty >= (int)Settings.Instance.FFLogs.Difficulty
                    orderby
                    x.EncounterID,
                    x.Percentile descending
                    group x by x.EncounterName into g
                    select
                    g.OrderByDescending(y => y.Percentile).First();

                var bestJob = string.Empty;
                if (filter == null)
                {
                    bestJob = parses
                        .OrderByDescending(x => x.Percentile)
                        .FirstOrDefault()?
                        .Spec;
                }

                // Histogramを編集する
                var histogram = default(HistogramsModel);
                if (Settings.Instance.FFLogs.VisibleHistogram)
                {
                    histogram = filter != null ?
                        StatisticsDatabase.Instance.GetHistogram(job) :
                        StatisticsDatabase.Instance.GetHistogram(bestJob);
                }

                if (histogram == null)
                {
                    histogram = EmptyHistogram;
                }

                await WPFHelper.InvokeAsync(() =>
                {
                    this.CharacterNameFull = characterName;
                    this.RefreshCharacterName();
                    this.Server = server;
                    this.Region = region;
                    this.Job = filter != null ? job : null;
                    this.BestJobName = bestJob;
                    this.AddRangeParse(bests);

                    this.Histogram = histogram;

                    foreach (var rank in histogram.Ranks)
                    {
                        rank.IsCurrent = false;
                    }

                    var currentRank = histogram.Ranks
                        .OrderByDescending(x => x.Rank)
                        .FirstOrDefault(x => x.Rank <= this.DPSAvg);
                    if (currentRank != null)
                    {
                        currentRank.IsCurrent = true;
                    }

                    if (!bests.Any())
                    {
                        this.Message = NoDataMessage;
                    }

                    this.HttpStatusCode = code;
                    this.ResponseContent = json;
                });
            }
            catch (Exception)
            {
                Clear();
                throw;
            }
            finally
            {
                lock (DownlodingLocker)
                {
                    isDownloading = false;
                }
            }

            async void Clear()
            {
                await WPFHelper.InvokeAsync(() =>
                {
                    this.CharacterNameFull = characterName;
                    this.RefreshCharacterName();
                    this.Server = server;
                    this.Region = region;
                    this.Job = job;
                    this.BestJobName = string.Empty;
                    this.ParseList.Clear();
                    this.Histogram = EmptyHistogram;
                    this.HttpStatusCode = code;
                    this.ResponseContent = json;
                });
            }
        }

19 Source : StatisticsDatabase.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

public async Task CreateRankingsAsync(
            string rankingFileName,
            int targetZoneID = 0,
            string difficulty = null)
        {
            this.InitializeRankingsDatabase(rankingFileName);

            var targetEncounters = default(BasicEntryModel[]);
            if (targetZoneID == 0)
            {
                targetEncounters = this.zones
                    .OrderByDescending(x => x.ID)
                    .FirstOrDefault()?
                    .Enconters;
            }
            else
            {
                targetEncounters = this.zones
                    .FirstOrDefault(x => x.ID == targetZoneID)?
                    .Enconters;
            }

            var rankingBuffer = new List<RankingModel>(10000);

            foreach (var encounter in targetEncounters)
            {
                this.Log($@"[FFLogs] new rankings ""{encounter.Name}"".");

                var page = 1;
                var count = 0;
                var rankings = default(RankingsModel);

                do
                {
                    var uri = $"rankings/encounter/{encounter.ID}";
                    var query = HttpUtility.ParseQueryString(string.Empty);
                    query["api_key"] = this.APIKey;

                    if (!string.IsNullOrEmpty(difficulty))
                    {
                        query["difficulty"] = difficulty;
                    }

                    query["page"] = page.ToString();
                    uri += $"?{query.ToString()}";

                    rankings = null;
                    var res = await this.HttpClient.GetAsync(uri);
                    if (res.StatusCode == HttpStatusCode.OK)
                    {
                        var json = await res.Content.ReadreplacedtringAsync();
                        rankings = JsonConvert.DeserializeObject<RankingsModel>(json);
                        if (rankings != null)
                        {
                            count += rankings.Count;
                            var targets = rankings.Rankings;
                            targets.AsParallel().ForAll(item =>
                            {
                                item.Database = this;
                                item.EncounterName = encounter.Name;

                                if (this.SpecDictionary != null &&
                                    this.SpecDictionary.ContainsKey(item.SpecID))
                                {
                                    item.Spec = this.SpecDictionary[item.SpecID].Name;
                                }
                            });

                            rankingBuffer.AddRange(rankings.Rankings);
                        }

                        if (page % 100 == 0)
                        {
                            this.InsertRanking(rankingFileName, rankingBuffer);
                            rankingBuffer.Clear();
                            this.Log($@"[FFLogs] new rankings downloaded. ""{encounter.Name}"" page={page} count={count}.");

#if DEBUG
                            // デバッグモードならば100ページで抜ける
                            break;
#endif
                        }

                        page++;
                    }
                    else
                    {
                        this.LogError(
                            $"[FFLogs] Error, REST API Response not OK. status_code={res.StatusCode}");
                        this.LogError(await res?.Content.ReadreplacedtringAsync());
                        break;
                    }

                    await Task.Delay(TimeSpan.FromSeconds(0.10));
                } while (rankings != null && rankings.HasMorePages);

                if (rankingBuffer.Any())
                {
                    this.InsertRanking(rankingFileName, rankingBuffer);
                    rankingBuffer.Clear();
                    this.Log($@"[FFLogs] new rankings downloaded. ""{encounter.Name}"" page={page} count={count}.");
                }
            }

            this.Log($@"[FFLogs] new rankings downloaded.");
        }

19 Source : VideoCapture.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

public void FinishRecording()
        {
            this.StopRecordingSubscriber?.Stop();

            lock (this)
            {
                if (!Config.Instance.IsRecording)
                {
                    return;
                }
            }

            if (!Config.Instance.IsEnabledRecording)
            {
                return;
            }

            if (!Config.Instance.UseObsRpc)
            {
                this.Input.Keyboard.ModifiedKeyStroke(
                    Config.Instance.StopRecordingShortcut.GetModifiers(),
                    Config.Instance.StopRecordingShortcut.GetKeys());
            }
            else
            {
                this.SendToggleRecording();
            }

            var contentName = !string.IsNullOrEmpty(this.contentName) ?
                this.contentName :
                ActGlobals.oFormActMain.CurrentZone;

            if (!string.IsNullOrEmpty(Config.Instance.VideoSaveDictory) &&
                Directory.Exists(Config.Instance.VideoSaveDictory))
            {
                Task.Run(async () =>
                {
                    var now = DateTime.Now;

                    var prefix = Config.Instance.VideFilePrefix.Trim();
                    prefix = string.IsNullOrEmpty(prefix) ?
                        string.Empty :
                        $"{prefix} ";

                    var deathCountText = this.deathCount > 1 ?
                        $" death{this.deathCount - 1}" :
                        string.Empty;

                    var f = $"{prefix}{this.startTime:yyyy-MM-dd HH-mm} {contentName} try{this.TryCount:00} {VideoDurationPlaceholder}{deathCountText}.ext";

                    await Task.Delay(TimeSpan.FromSeconds(8));

                    var files = Directory.GetFiles(
                        Config.Instance.VideoSaveDictory,
                        "*.*");

                    var original = files
                        .OrderByDescending(x => File.GetLastWriteTime(x))
                        .FirstOrDefault();

                    if (!string.IsNullOrEmpty(original))
                    {
                        var timestamp = File.GetLastWriteTime(original);
                        if (timestamp >= now.AddSeconds(-10))
                        {
                            var ext = Path.GetExtension(original);
                            f = f.Replace(".ext", ext);

                            var dest = Path.Combine(
                                Path.GetDirectoryName(original),
                                f);

                            using (var tf = TagLib.File.Create(original))
                            {
                                dest = dest.Replace(
                                    VideoDurationPlaceholder,
                                    $"{tf.Properties.Duration.TotalSeconds:N0}s");

                                tf.Tag.replacedle = Path.GetFileNameWithoutExtension(dest);
                                tf.Tag.Subreplacedle = $"{prefix} - {contentName}";
                                tf.Tag.Album = $"FFXIV - {contentName}";
                                tf.Tag.AlbumArtists = new[] { "FFXIV", this.playerName }.Where(x => !string.IsNullOrEmpty(x)).ToArray();
                                tf.Tag.Genres = new[] { "Game" };
                                tf.Tag.Comment =
                                    $"{prefix} - {contentName}\n" +
                                    $"{this.startTime:yyyy-MM-dd HH:mm} try{this.TryCount}{deathCountText}";
                                tf.Save();
                            }

                            File.Move(
                                original,
                                dest);

                            XIVLogPlugin.Instance.EnqueueLogLine(
                                "00",
                                $"[XIVLog] The video was saved. {Path.GetFileName(dest)}");
                        }
                    }
                });
            }

            WPFHelper.InvokeAsync(() =>
            {
                lock (this)
                {
                    Config.Instance.IsRecording = false;
                }
            });
        }

19 Source : Item.cs
with Apache License 2.0
from anpShawn

public static Item GetBesreplacedemForStatAndType(string inStat, ItemType inType, List<Item> availableItems)
    {
        validItems = availableItems.Where(i => i.itemType == inType).Where(i => i.GetAvailableQuanreplacedy() > 0);

        if (validItems.Count() == 0) return null;
        return validItems.OrderByDescending(i => i.stats.Get(inStat)).ThenByDescending(i => i.numSlots).First();
    }

19 Source : Item.cs
with Apache License 2.0
from anpShawn

public static Item GetBesreplacedemByValueForType(ItemType inType, List<Item> availableItems)
    {
        validItems = availableItems.Where(i => i.itemType == inType).Where(i => i.GetAvailableQuanreplacedy() > 0);

        if (validItems.Count() == 0) return null;
        return validItems.OrderByDescending(i => i.value).First();
    }

19 Source : Item.cs
with Apache License 2.0
from anpShawn

public static Item GetBesreplacedemOfBaseId(string inBaseId, List<Item> availableItems)
    {
        validItems = availableItems.Where(i => i.baseId == inBaseId).Where(i => i.GetAvailableQuanreplacedy() > 0);

        if (validItems.Count() == 0) return null;
        return validItems.OrderByDescending(i => i.level).First();
    }

19 Source : SodaScript.cs
with Apache License 2.0
from anpShawn

private void EvalCondition(SodaScriptCondition inCondition, SodaScriptComparison inComparison, string inCompareValue, List<CharacterData> inTargets )
    {
        CharacterData targ;
        EnemyCharacterData ecd;
        PlayerCharacterData pcd;
        culledTargets.Clear();

        if(inCondition == SodaScriptCondition.WEAKEST)
        {
            culledTargets.Add(GetLowestHpPercentTarget(inTargets));
        }
        else if(inCondition == SodaScriptCondition.TEAM_ALIVE)
        {
            targ = inTargets[0];
            CharacterTeam team = targ.IsInFaction(Faction.PLAYER) ? adventure.playerTeam : adventure.enemyTeam;
            if (EvalNumericComparison(team.GetNumLivingMembers(), int.Parse(inCompareValue), inComparison))
                culledTargets.Add(targ);
        }
        else if(inCondition == SodaScriptCondition.TEAM_HP)
        {
            targ = inTargets[0];
            CharacterTeam team = targ.IsInFaction(Faction.PLAYER) ? adventure.playerTeam : adventure.enemyTeam;
            if (EvalNumericComparison(team.GetTeamHPPercent(), int.Parse(inCompareValue), inComparison))
                culledTargets.Add(targ);
        }
        else if(inCondition == SodaScriptCondition.TEAM_NUM_BACK_TURNED)
        {
            targ = inTargets[0];
            CharacterTeam team = targ.IsInFaction(Faction.PLAYER) ? adventure.playerTeam : adventure.enemyTeam;
            int numBackTurned = team.GetNumMembersWithBackTurnedTo(activeCharacter);
            if (EvalNumericComparison(numBackTurned, int.Parse(inCompareValue), inComparison))
                culledTargets.Add(targ);
        }
        else
        {
            for(int i=0; i<inTargets.Count; i++)
            {
                targ = inTargets[i];
                if(inCondition == SodaScriptCondition.HP)
                {
                    if (EvalNumericComparison(targ.GetHpPercent(), int.Parse(inCompareValue), inComparison))
                        culledTargets.Add(targ);
                }
                else if(inCondition == SodaScriptCondition.MP)
                {
                    if (EvalNumericComparison(targ.GetMpPercent(), int.Parse(inCompareValue), inComparison))
                        culledTargets.Add(targ);
                }
                else if(inCondition == SodaScriptCondition.POSITION)
                {
                    if (EvalNumericComparison(targ.originalOrderInTeam+1, int.Parse(inCompareValue), inComparison))
                        culledTargets.Add(targ);
                }
                else if(inCondition == SodaScriptCondition.RANK)
                {
                    bool foundRank = false;
                    EnemyRank enemyRank = EnemyRank.NORM;
                    EnemyRank parsedRank = (EnemyRank)Enum.Parse(typeof(EnemyRank), inCompareValue);

                    if(targ is EnemyCharacterData)
                    {
                        foundRank = true;
                        ecd = (EnemyCharacterData)targ;
                        enemyRank = ecd.rank;
                    }
                    else if(targ.id == CharId.JANITOR)
                    {
                        foundRank = true;
                        enemyRank = EnemyRank.BOSS;
                    }

                    if(foundRank)
                    {
                        if (EvalNumericComparison((int)enemyRank, (int)parsedRank, inComparison))
                            culledTargets.Add(targ);
                    }
                }
                else if(inCondition == SodaScriptCondition.IS_ORE)
                {
                    if (targ.isOre)
                        culledTargets.Add(targ);
                }
                else if(inCondition == SodaScriptCondition.ISNT_ORE)
                {
                    if (!targ.isOre)
                        culledTargets.Add(targ);
                }
                else if(inCondition == SodaScriptCondition.IS_JANITOR)
                {
                    if (targ.id == CharId.JANITOR)
                        culledTargets.Add(targ);
                }
                else if(inCondition == SodaScriptCondition.ISNT_JANITOR)
                {
                    if (targ.id != CharId.JANITOR)
                        culledTargets.Add(targ);
                }
                else if(inCondition == SodaScriptCondition.BACK_IS_TURNED)
                {
                    if(!targ.isOre && targ.BackIsTurnedTo(activeCharacter))
                        culledTargets.Add(targ);
                }
                else if(inCondition == SodaScriptCondition.BACK_ISNT_TURNED)
                {
                    if(!targ.isOre && !targ.BackIsTurnedTo(activeCharacter))
                        culledTargets.Add(targ);
                }
                else if(inCondition == SodaScriptCondition.HAS_ESSENCE)
                {
                    if (targ.hasEssence)
                        culledTargets.Add(targ);
                }
                else if(inCondition == SodaScriptCondition.NO_ESSENCE)
                {
                    if (!targ.hasEssence)
                        culledTargets.Add(targ);
                }
                else if(inCondition == SodaScriptCondition.STATUS)
                {
                    StatusEffectCategory parsedCategory = (StatusEffectCategory)Enum.Parse(typeof(StatusEffectCategory), inCompareValue);
                    if (parsedCategory == StatusEffectCategory.POSITIVE)
                    {
                        bool hasPos = targ.HasPostiveStatusEffect();
                        if ((inComparison == SodaScriptComparison.EQUALS && hasPos) ||
                            (inComparison == SodaScriptComparison.NOT_EQUALS && !hasPos))
                            culledTargets.Add(targ);
                    }
                    else if(parsedCategory == StatusEffectCategory.NEGATIVE)
                    {
                        bool hasNeg = targ.HasNegativeStatusEffect();
                        if ((inComparison == SodaScriptComparison.EQUALS && hasNeg) ||
                            (inComparison == SodaScriptComparison.NOT_EQUALS && !hasNeg))
                            culledTargets.Add(targ);
                    }
                    else if(parsedCategory == StatusEffectCategory.NONE)
                    {
                        bool hasAny = targ.HasAnyStatusEffect();
                        if ((inComparison == SodaScriptComparison.EQUALS && !hasAny) ||
                            (inComparison == SodaScriptComparison.NOT_EQUALS && hasAny))
                            culledTargets.Add(targ);
                    }
                }
                else
                {
                    throw new Exception("Trigger condition " + inCondition + " is not supported as a condition");
                }
            }

            //do a final list sort based on the condition?
            if(inCondition == SodaScriptCondition.HP)
            {
                if (inComparison == SodaScriptComparison.GREATER_THAN)
                    culledTargets = culledTargets.OrderByDescending(t => t.GetHpPercent()).ToList<CharacterData>();
                else if (inComparison == SodaScriptComparison.LESS_THAN)
                    culledTargets = culledTargets.OrderBy(t => t.GetHpPercent()).ToList<CharacterData>();
            }
            else if(inCondition == SodaScriptCondition.MP)
            {
                if (inComparison == SodaScriptComparison.GREATER_THAN)
                    culledTargets = culledTargets.OrderByDescending(t => t.GetMpPercent()).ToList<CharacterData>();
                else if (inComparison == SodaScriptComparison.LESS_THAN)
                    culledTargets = culledTargets.OrderBy(t => t.GetMpPercent()).ToList<CharacterData>();
            }
        }

        potentialTargets.Clear();
        potentialTargets.AddRange(culledTargets);
    }

19 Source : SodaScript.cs
with Apache License 2.0
from anpShawn

private CharacterData GetHighestHpPercentTarget(List<CharacterData> inTargets)
    {
        return inTargets.OrderByDescending(t => t.GetHpPercent()).First();
    }

19 Source : SodaScript.cs
with Apache License 2.0
from anpShawn

private CharacterData GetHighestMpPercentTarget(List<CharacterData> inTargets)
    {
        return inTargets.OrderByDescending(t => t.GetMpPercent()).First();
    }

19 Source : FeaturedContentAppService.cs
with MIT License
from anteatergames

public IEnumerable<UserContentToBeFeaturedViewModel> GetContentToBeFeatured()
        {
            IEnumerable<UserContent> finalList = userContentDomainService.GetAll();
            IEnumerable<FeaturedContent> featured = featuredContentDomainService.GetAll();

            IEnumerable<UserContentToBeFeaturedViewModel> vms = mapper.Map<IEnumerable<UserContent>, IEnumerable<UserContentToBeFeaturedViewModel>>(finalList);

            foreach (UserContentToBeFeaturedViewModel item in vms)
            {
                FeaturedContent featuredNow = featured.FirstOrDefault(x => x.UserContentId == item.Id && x.StartDate.Date <= DateTime.Today && (!x.EndDate.HasValue || (x.EndDate.HasValue && x.EndDate.Value.Date > DateTime.Today)));

                if (featuredNow != null)
                {
                    item.CurrentFeatureId = featuredNow.Id;
                }

                item.IsFeatured = item.CurrentFeatureId.HasValue;

                item.AuthorName = string.IsNullOrWhiteSpace(item.AuthorName) ? Constants.UnknownSoul : item.AuthorName;

                item.replacedleCompliant = !string.IsNullOrWhiteSpace(item.replacedle) && item.replacedle.Length <= 25;

                item.IntroCompliant = !string.IsNullOrWhiteSpace(item.Introduction) && item.Introduction.Length <= 55;

                item.ContentCompliant = !string.IsNullOrWhiteSpace(item.Content) && item.Content.Length >= 800;

                item.IsArticle = !string.IsNullOrWhiteSpace(item.replacedle) && !string.IsNullOrWhiteSpace(item.Introduction);
            }

            vms = vms.OrderByDescending(x => x.IsFeatured).ToList();

            return vms;
        }

19 Source : JobPositionAppService.cs
with MIT License
from anteatergames

public OperationResultVo GetAllAvailable(Guid currentUserId)
        {
            try
            {
                IEnumerable<JobPosition> allModels = jobPositionDomainService.GetAllAvailable();

                List<JobPositionViewModel> vms = mapper.Map<IEnumerable<JobPosition>, IEnumerable<JobPositionViewModel>>(allModels).ToList();

                foreach (JobPositionViewModel vm in vms)
                {
                    SetPermissions(currentUserId, vm);
                    vm.ApplicantCount = vm.Applicants.Count;
                    vm.CurrentUserApplied = vm.Applicants.Any(x => x.UserId == currentUserId);
                }

                vms = vms.OrderByDescending(x => x.CreateDate).ToList();

                return new OperationResultListVo<JobPositionViewModel>(vms);
            }
            catch (Exception ex)
            {
                return new OperationResultVo(ex.Message);
            }
        }

19 Source : JobPositionAppService.cs
with MIT License
from anteatergames

public OperationResultVo GetAllMine(Guid currentUserId)
        {
            try
            {
                IEnumerable<JobPosition> allModels = jobPositionDomainService.GetByUserId(currentUserId);

                List<JobPositionViewModel> vms = mapper.Map<IEnumerable<JobPosition>, IEnumerable<JobPositionViewModel>>(allModels).ToList();

                foreach (JobPositionViewModel vm in vms)
                {
                    SetPermissions(currentUserId, vm);
                    vm.ApplicantCount = vm.Applicants.Count;
                }

                vms = vms.OrderByDescending(x => x.CreateDate).ToList();

                return new OperationResultListVo<JobPositionViewModel>(vms);
            }
            catch (Exception ex)
            {
                return new OperationResultVo(ex.Message);
            }
        }

19 Source : LocalizationAppService.cs
with MIT License
from anteatergames

public OperationResultListVo<LocalizationViewModel> GetAll(Guid currentUserId)
        {
            try
            {
                IEnumerable<Localization> allModels = translationDomainService.GetAll();

                List<LocalizationViewModel> vms = mapper.Map<IEnumerable<Localization>, IEnumerable<LocalizationViewModel>>(allModels).ToList();

                foreach (LocalizationViewModel item in vms)
                {
                    item.TermCount = item.Terms.Count;

                    SetGameViewModel(item.Game.Id, item);
                    item.Game.replacedle = string.Empty;

                    SetPermissions(currentUserId, item);

                    int totalTermCount = item.Terms.Count;
                    int distinctEntriesCount = item.Entries.Select(x => new { x.TermId, x.Language }).Distinct().Count();
                    int languageCount = item.Entries.Select(x => x.Language).Distinct().Count();

                    item.TranslationPercentage = translationDomainService.CalculatePercentage(totalTermCount, distinctEntriesCount, languageCount);
                }

                vms = vms.OrderByDescending(x => x.CreateDate).ToList();

                return new OperationResultListVo<LocalizationViewModel>(vms);
            }
            catch (Exception ex)
            {
                return new OperationResultListVo<LocalizationViewModel>(ex.Message);
            }
        }

19 Source : LocalizationAppService.cs
with MIT License
from anteatergames

public OperationResultVo GetByUserId(Guid currentUserId, Guid userId)
        {
            try
            {
                IEnumerable<Localization> allModels = translationDomainService.GetByUserId(userId);

                List<LocalizationViewModel> vms = mapper.Map<IEnumerable<Localization>, IEnumerable<LocalizationViewModel>>(allModels).ToList();

                foreach (LocalizationViewModel item in vms)
                {
                    item.TermCount = item.Terms.Count;

                    ViewModels.Game.GameViewModel game = GetGameWithCache(gameDomainService, item.Game.Id);
                    item.Game.replacedle = game.replacedle;

                    SetPermissions(userId, item);
                }

                vms = vms.OrderByDescending(x => x.CreateDate).ToList();

                return new OperationResultListVo<LocalizationViewModel>(vms);
            }
            catch (Exception ex)
            {
                return new OperationResultListVo<LocalizationViewModel>(ex.Message);
            }
        }

19 Source : Dbg.cs
with Apache License 2.0
from AnthonyLloyd

public static void Output(Action<string> output)
    {
        foreach (var s in info)
            output(string.Concat("[Dbg] ", s));
        int maxLength = 0, total = 0;
        foreach (var kv in counts)
        {
            total += kv.Value;
            if (kv.Key.Length > maxLength) maxLength = kv.Key.Length;
        }
        foreach (var kc in counts.OrderByDescending(i => i.Value))
        {
            var percent = ((float)kc.Value / total).ToString("0.0%").PadLeft(7);
            output(string.Concat("Count: ", kc.Key.PadRight(maxLength), percent, " ", kc.Value));
        }
        maxLength = 0;
        int maxPercent = 0, maxTime = 0, maxCount = 0;
        foreach (var kv in times)
        {
            if (kv.Key.Length > maxLength) maxLength = kv.Key.Length;
            if ((kv.Value.Item1 * 1000L / Stopwatch.Frequency).ToString("#,0").Length > maxTime)
                maxTime = (kv.Value.Item1 * 1000L / Stopwatch.Frequency).ToString("#,0").Length;
            if (((float)kv.Value.Item1 / times.Value(0).Item1).ToString("0.0%").Length > maxPercent)
                maxPercent = ((float)kv.Value.Item1 / times.Value(0).Item1).ToString("0.0%").Length;
            if (kv.Value.Item2.ToString().Length > maxCount)
                maxCount = kv.Value.Item2.ToString().Length;
        }
        foreach (var kc in times)
        {
            var time = (kc.Value.Item1 * 1000L / Stopwatch.Frequency).ToString("#,0").PadLeft(maxTime + 1);
            var percent = ((float)kc.Value.Item1 / times.Value(0).Item1).ToString("0.0%").PadLeft(maxPercent + 1);
            var count = kc.Value.Item2.ToString().PadLeft(maxCount + 1);
            output(string.Concat("Time: ", kc.Key.PadRight(maxLength), time, "ms", percent, count));
        }
        Clear();
    }

19 Source : BrainstormAppService.cs
with MIT License
from anteatergames

public OperationResultListVo<BrainstormIdeaViewModel> GetAllBySessionId(Guid userId, Guid sessionId)
        {
            try
            {
                IEnumerable<BrainstormIdea> allIdeas = brainstormDomainService.GetIdeasBySession(sessionId);

                IEnumerable<BrainstormIdeaViewModel> vms = mapper.Map<IEnumerable<BrainstormIdea>, IEnumerable<BrainstormIdeaViewModel>>(allIdeas);

                foreach (BrainstormIdeaViewModel idea in vms)
                {
                    idea.UserContentType = UserContentType.Idea;
                    idea.VoteCount = idea.Votes.Count;
                    idea.Score = idea.Votes.Sum(x => (int)x.VoteValue);
                    idea.CurrentUserVote = idea.Votes.FirstOrDefault(x => x.UserId == userId)?.VoteValue ?? VoteValue.Neutral;

                    idea.CommentCount = idea.Comments.Count;
                }

                vms = vms.OrderByDescending(x => x.Score).ThenByDescending(x => x.CreateDate);

                return new OperationResultListVo<BrainstormIdeaViewModel>(vms);
            }
            catch (Exception ex)
            {
                return new OperationResultListVo<BrainstormIdeaViewModel>(ex.Message);
            }
        }

19 Source : FeaturedContentAppService.cs
with MIT License
from anteatergames

public CarouselViewModel GetFeaturedNow()
        {
            IQueryable<FeaturedContent> allModels = featuredContentDomainService.GetFeaturedNow();

            if (allModels.Any())
            {
                IEnumerable<FeaturedContentViewModel> vms = allModels.ProjectTo<FeaturedContentViewModel>(mapper.ConfigurationProvider);

                CarouselViewModel model = new CarouselViewModel
                {
                    Items = vms.OrderByDescending(x => x.CreateDate).ToList()
                };

                foreach (FeaturedContentViewModel vm in model.Items)
                {
                    string[] imageSplit = vm.ImageUrl.Split("/");
                    Guid userId = vm.OriginalUserId == Guid.Empty ? vm.UserId : vm.OriginalUserId;

                    vm.FeaturedImage = ContentHelper.SetFeaturedImage(userId, imageSplit.Last(), ImageRenderType.Full);
                    vm.FeaturedImageLquip = ContentHelper.SetFeaturedImage(userId, imageSplit.Last(), ImageRenderType.LowQuality);
                }

                return model;
            }
            else
            {
                CarouselViewModel fake = FakeData.FakeCarousel();

                return fake;
            }
        }

19 Source : UserContentDomainService.cs
with MIT License
from anteatergames

public new IEnumerable<UserContentSearchVo> Search(Expression<Func<UserContent, bool>> where)
        {
            IEnumerable<UserContent> all = base.Search(where);

            IEnumerable<UserContentSearchVo> selected = all.OrderByDescending(x => x.CreateDate)
                .Select(x => new UserContentSearchVo
                {
                    ContentId = x.Id,
                    replacedle = x.replacedle,
                    FeaturedImage = x.FeaturedImage,
                    Content = (string.IsNullOrWhiteSpace(x.Introduction) ? x.Content : x.Introduction).GetFirstWords(20),
                    Language = (x.Language == 0 ? SupportedLanguage.English : x.Language)
                });

            return selected;
        }

19 Source : FeedViewComponent.cs
with MIT License
from anteatergames

public async Task<IViewComponentResult> InvokeAsync(int count, Guid? gameId, Guid? userId, Guid? oldestId, DateTime? oldestDate, bool? articlesOnly)
        {
            UserPreferencesViewModel preferences = _userPreferencesAppService.GetByUserId(CurrentUserId);

            ActivityFeedRequestViewModel vm = new ActivityFeedRequestViewModel
            {
                CurrentUserId = CurrentUserId,
                Count = count,
                GameId = gameId,
                UserId = userId,
                Languages = preferences.Languages,
                OldestId = oldestId,
                OldestDate = oldestDate,
                ArticlesOnly = articlesOnly
            };

            List<UserContentViewModel> model = _userContentAppService.GetActivityFeed(vm).ToList();

            ApplicationUser user = await UserManager.FindByIdAsync(CurrentUserId.ToString());
            bool userIsAdmin = user != null && await UserManager.IsInRoleAsync(user, Roles.Administrator.ToString());

            foreach (UserContentViewModel item in model)
            {
                if (item.UserContentType == UserContentType.TeamCreation)
                {
                    FormatTeamCreationPost(item);
                }
                if (item.UserContentType == UserContentType.JobPosition)
                {
                    FormatJobPositionPostForTheFeed(item);
                }
                else
                {
                    item.Content = ContentHelper.FormatContentToShow(item.Content);
                }

                foreach (CommentViewModel comment in item.Comments)
                {
                    comment.Text = ContentHelper.FormatHashTagsToShow(comment.Text);
                }

                item.Permissions.CanEdit = !item.HasPoll && (item.UserId == CurrentUserId || userIsAdmin);

                item.Permissions.CanDelete = item.UserId == CurrentUserId || userIsAdmin;
            }

            if (model.Any())
            {
                UserContentViewModel oldest = model.OrderByDescending(x => x.CreateDate).Last();

                ViewData["OldestPostGuid"] = oldest.Id;
                ViewData["OldestPostDate"] = oldest.CreateDate.ToString("o");
            }

            ViewData["IsMorePosts"] = oldestId.HasValue;

            ViewData["UserId"] = userId;

            return await Task.Run(() => View(model));
        }

19 Source : MessageHandlingService.cs
with MIT License
from AntonyVorontsov

private async Task ProcessMessageEvent(MessageHandlingContext context, IEnumerable<string> matchingRoutes)
        {
            var container = _messageHandlerContainers.FirstOrDefault(x => x.Exchange == context.Message.Exchange) ??
                _messageHandlerContainers.FirstOrDefault(x => x.IsGeneral);
            if (container is null)
            {
                return;
            }

            var messageHandlerOrderingContainers = new List<MessageHandlerOrderingContainer>();
            foreach (var matchingRoute in matchingRoutes)
            {
                if (!container.MessageHandlers.ContainsKey(matchingRoute))
                {
                    continue;
                }

                var orderingContainers = container.MessageHandlers[matchingRoute]
                    .Select(handler => new MessageHandlerOrderingContainer(handler, matchingRoute, container.GetOrderForHandler(handler)));
                messageHandlerOrderingContainers.AddRange(orderingContainers);
            }

            var executedHandlers = new List<Type>();
            var orderedContainers = messageHandlerOrderingContainers.OrderByDescending(x => x.Order)
                .ThenByDescending(x => x.MessageHandler.GetHashCode())
                .ToList();
            foreach (var orderedContainer in orderedContainers)
            {
                var handlerType = orderedContainer.MessageHandler.GetType();
                if (executedHandlers.Contains(handlerType))
                {
                    continue;
                }

                switch (orderedContainer.MessageHandler)
                {
                    case IMessageHandler messageHandler:
                        RunMessageHandler(messageHandler, context, orderedContainer.MatchingRoute);
                        break;
                    case IAsyncMessageHandler asyncMessageHandler:
                        await RunAsyncMessageHandler(asyncMessageHandler, context, orderedContainer.MatchingRoute).ConfigureAwait(false);
                        break;
                    default:
                        throw new NotSupportedException($"The type {orderedContainer.MessageHandler.GetType()} of message handler is not supported.");
                }

                executedHandlers.Add(handlerType);
            }
        }

19 Source : MessageHandlingServiceTests.cs
with MIT License
from AntonyVorontsov

private static IEnumerable<MessageHandlerOrderingContainerTestModel> GetTestingOrderingModels(
            HandleMessageReceivingEventTestDataModel testDataModel,
            IMock<IMessageHandler> messageHandlerMock,
            IMock<IAsyncMessageHandler> asyncMessageHandlerMock)
        {
            var collection = new List<MessageHandlerOrderingContainerTestModel>
            {
                new()
                {
                    MessageHandler = messageHandlerMock.Object,
                    ShouldTrigger = testDataModel.MessageHandlerShouldTrigger,
                    OrderValue = testDataModel.MessageHandlerOrder
                },
                new()
                {
                    MessageHandler = asyncMessageHandlerMock.Object,
                    ShouldTrigger = testDataModel.AsyncMessageHandlerShouldTrigger,
                    OrderValue = testDataModel.AsyncMessageHandlerOrder
                }
            };

            var callOrder = 1;
            var orderedCollection = collection.OrderByDescending(x => x.OrderValue)
                .ThenByDescending(x => x.MessageHandler.GetHashCode())
                .ToList();
            foreach (var item in orderedCollection.Where(item => item.ShouldTrigger))
            {
                item.CallOrder = callOrder++;
            }
            return orderedCollection;
        }

19 Source : VersionUpgraderWindow.cs
with GNU Lesser General Public License v3.0
from ApexGameTools

private IEnumerator<Action> ExecuteUpdates()
        {
            var actions = _allActions.Where(a => !a.isOptional).Concat(_optionalActions.Where(oa => oa.selected).Select(oa => oa.action)).OrderByDescending(a => a.priority).ToArray();

            if (_includePrefabs)
            {
                _progressMessage = "Updating prefabs";
                Repaint();

                var prefabs = from f in Directory.GetFiles(Application.dataPath, "*.prefab", SearchOption.AllDirectories)
                              select replacedetPath.ProjectRelativePath(f);

                yield return () =>
                {
                    var loadedPrefabs = new List<UnityEngine.Object>();
                    foreach (var prefab in prefabs)
                    {
                        if (_cancelled)
                        {
                            return;
                        }

                        loadedPrefabs.Add(replacedetDatabase.LoadMainreplacedetAtPath(prefab));
                    }

                    foreach (var act in actions)
                    {
                        act.Upgrade();
                    }
                };
            }

            //Next scenes
            string curScene = GetCurrentScene();
            var scenes = GetScenePaths(_scenes);

            _failedScenes = new List<string>();
            _scenesTotal = scenes.Length;

            for (int i = 0; i < scenes.Length; i++)
            {
                if (_cancelled)
                {
                    yield break;
                }

                _progressMessage = string.Format("Updating scene {0}/{1}: {2}", i, scenes.Length, scenes[i]);
                Repaint();

                yield return () =>
                {
                    if (OpenScene(scenes[i]))
                    {
                        bool changed = false;
                        foreach (var act in actions)
                        {
                            changed |= act.Upgrade();
                        }

                        if (changed)
                        {
                            _changedScenes++;
                            SaveScene();
                        }

                        _processedScenes++;
                    }
                    else
                    {
                        _failedScenes.Add(scenes[i]);
                    }
                };
            }

            OpenScene(curScene);
            replacedetDatabase.Savereplacedets();
            Resources.UnloadUnusedreplacedets();
        }

19 Source : ApexPointSeries.cs
with MIT License
from apexcharts

public IEnumerable<IDataPoint<replacedem>> GetData()
        {
            IEnumerable<DataPoint<replacedem>> data;

            if (YValue != null)
            {
                data = Items.Select(e => new DataPoint<replacedem>
                {
                    X = XValue.Compile().Invoke(e),
                    Y = YValue.Compile().Invoke(e),
                    Items = new List<replacedem> { e }
                });

            }
            else if (YAggregate != null)
            {
                data = Items.GroupBy(e => XValue.Compile().Invoke(e))
               .Select(d => new DataPoint<replacedem>
               {
                   X = d.Key,
                   Y = YAggregate.Compile().Invoke(d),
                   Items = d.ToList()
               });
            }
            else
            {
                return new List<IDataPoint<replacedem>>();
            }


            if (OrderBy != null)
            {
                data = data.OrderBy(o => OrderBy.Compile().Invoke(o));
            }
            else if (OrderByDescending != null)
            {
                data = data.OrderByDescending(o => OrderByDescending.Compile().Invoke(o));
            }

            return data;
        }

19 Source : BirdAtlasMockAPI.cs
with MIT License
from AppCreativity

public Task<IEnumerable<Story>> GetNewestStories(int amount)
        {
            amount = amount > _stories.Count ? _stories.Count : amount;
            return Task.FromResult<IEnumerable<Story>>(_stories.OrderByDescending(story => story.PublishedOn).Take(amount));
        }

19 Source : Cooking.cs
with MIT License
from ArchaicQuest

public Item.Item GenerateCookedItem(Player player, Room room, List<Tuple<Item.Item, int>> ingredients)
        {
          

            var prefixes = new List<string>()
            {
                "Boiled",
                "Baked",
                "Fried",
                "Toasted",
                "Smoked",
                "Roast",
                "Poached"
            };

            var suffixes = new List<string>()
            {
                "soup",
                "stew",
                "pie",
                "curry",
                "skewer"
            };

            var ingredientOrder = ingredients.OrderByDescending(item => item.Item2);
            var mainIngredient = ingredientOrder.First();

            var foodName = "";
 
             
           
            if (_dice.Roll(1, 1, 2) == 1)
            {
                var prefix = prefixes[_dice.Roll(1, 0, 6)];

                foodName = $"{prefix} {Helpers.RemoveArticle(mainIngredient.Item1.Name).ToLower()} {(ingredientOrder.Count() > 1 ? $"with {Helpers.RemoveArticle(ingredientOrder.ElementAt(1).Item1.Name).ToLower()}" : "")} {(ingredientOrder.Count() > 2 ? $"and {Helpers.RemoveArticle(ingredientOrder.ElementAt(2).Item1.Name).ToLower()}" : "")}";
            }
            else
            {
                var suffix = suffixes[_dice.Roll(1, 0, 5)];

                foodName =  $"{Helpers.RemoveArticle(mainIngredient.Item1.Name)} {(ingredientOrder.Count() > 1 ? $"with {Helpers.RemoveArticle(ingredientOrder.ElementAt(1).Item1.Name).ToLower()}" : "")} {(ingredientOrder.Count() > 2 ? $"  {Helpers.RemoveArticle(ingredientOrder.ElementAt(2).Item1.Name).ToLower()} " : "")}{suffix}";
            }

            var food = new Item.Item()
            {
                Name = foodName,
                ArmourRating = new ArmourRating(),
                Value = 75,
                Portal = new Portal(),
                ItemType = Item.Item.ItemTypes.Cooked,
                Container = new Container(),
                Description = new Description()
                {
                    Look =
                        $"A tasty looking {foodName.ToLower()} made with {Helpers.RemoveArticle(mainIngredient.Item1.Name).ToLower()}s{(ingredientOrder.Count() > 1 ? $" and {Helpers.RemoveArticle(ingredientOrder.ElementAt(1).Item1.Name).ToLower()}." : ".")}",
                    Exam =
                        $"A tasty looking {foodName.ToLower()} made with {Helpers.RemoveArticle(mainIngredient.Item1.Name).ToLower()}s{(ingredientOrder.Count() > 1 ? $" and {Helpers.RemoveArticle(ingredientOrder.ElementAt(1).Item1.Name).ToLower()}." : ".")}"
                },
                Modifier = new Modifier()
                {
                    HP = CalculateModifer(ingredientOrder, "hp"),
                    Strength = CalculateModifer(ingredientOrder, "strength"),
                    Dexterity = CalculateModifer(ingredientOrder, "dexterity"),
                    Consreplacedution = CalculateModifer(ingredientOrder, "consreplacedution"),
                    Intelligence = CalculateModifer(ingredientOrder, "intelligence"),
                    Wisdom = CalculateModifer(ingredientOrder, "wisdom"),
                    Charisma = CalculateModifer(ingredientOrder, "charisma"),
                    Moves = CalculateModifer(ingredientOrder, "moves"),
                    Mana = CalculateModifer(ingredientOrder, "mana"),
                    DamRoll = CalculateModifer(ingredientOrder, "damroll"),
                    HitRoll = CalculateModifer(ingredientOrder, "hitroll"),
                    Saves = CalculateModifer(ingredientOrder, "saves"),
                },
                Level = 1,
                Slot = Equipment.EqSlot.Held,
                Uses = 1,
                Weight = 0.3F,

            };



            return food;

        }

19 Source : Animator.cs
with MIT License
from arcusmaximus

private static replacedLine CreateInitialLine(replacedLine originalLine, List<AnimationWithSectionIndex> anims)
        {
            replacedLine newLine = (replacedLine)originalLine.Clone();
            newLine.Start = TimeUtil.RoundTimeToFrameCenter(newLine.Start);

            foreach (AnimationWithSectionIndex anim in anims.Where(a => a.Animation.EndTime < originalLine.Start)
                                                            .OrderBy(a => a.Animation.EndTime))
            {
                ApplyAnimation(newLine, anim, 1);
            }

            foreach (AnimationWithSectionIndex anim in anims.Where(a => a.Animation.AffectsPast && a.Animation.StartTime >= originalLine.Start)
                                                            .OrderByDescending(a => a.Animation.StartTime))
            {
                ApplyAnimation(newLine, anim, 0);
            }

            return newLine;
        }

19 Source : AutosavesPage.cs
with GNU Affero General Public License v3.0
from arklumpus

private void BuildCodeGrid()
        {
            CodeGrid.Margin = new Thickness(25, 0, 0, 0);

            CodeGrid.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
            CodeGrid.RowDefinitions.Add(new RowDefinition(1, GridUnitType.Star));

            Grid replacedleGrid = new Grid() { Margin = new Thickness(0, 0, 0, 5) };
            replacedleGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
            replacedleGrid.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));

            CodeGrid.Children.Add(replacedleGrid);

            replacedleGrid.Children.Add(new TextBlock() { FontSize = 20, Foreground = new SolidColorBrush(Color.FromRgb(0, 114, 178)), Text = "Autosaved code" });


            StackPanel deleteAllCodeButtonContent = new StackPanel() { Orientation = Avalonia.Layout.Orientation.Horizontal };

            deleteAllCodeButtonContent.Children.Add(new DPIAwareBox(Icons.GetIcon16("TreeViewer.replacedets.Trash")));

            deleteAllCodeButtonContent.Children.Add(new TextBlock() { Text = "Delete all", FontSize = 12, Foreground = new SolidColorBrush(Color.FromRgb(102, 102, 102)), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, Margin = new Thickness(2, 0, 0, 0) });

            Button deleteAllCodeButton = new Button() { Content = deleteAllCodeButtonContent, Margin = new Thickness(5, 0, 0, 0), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, Background = Brushes.Transparent, Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Arrow) };
            deleteAllCodeButton.Clreplacedes.Add("SideBarButton");
            Grid.SetColumn(deleteAllCodeButton, 1);
            replacedleGrid.Children.Add(deleteAllCodeButton);



            StackPanel codeContainer = new StackPanel();

            ScrollViewer scroller = new ScrollViewer() { HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled, VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto, Padding = new Thickness(0, 0, 17, 0), AllowAutoHide = false };
            scroller.Content = codeContainer;
            Grid.SetRow(scroller, 1);
            CodeGrid.Children.Add(scroller);

            string autosavePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), replacedembly.GetEntryreplacedembly().GetName().Name);

            deleteAllCodeButton.Click += async (s, e) =>
            {
                try
                {
                    string autosavePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), replacedembly.GetEntryreplacedembly().GetName().Name);

                    if (Directory.Exists(autosavePath))
                    {
                        Dictionary<DateTime, List<(string, string, string, int)>> items = new Dictionary<DateTime, List<(string, string, string, int)>>();

                        foreach (string directory in Directory.GetDirectories(autosavePath))
                        {
                            string name = Path.GetFileName(directory);

                            if (name != "Autosave" && name != "Keys" && name != "modules" && name != "Recent")
                            {
                                Directory.Delete(directory, true);
                            }
                        }
                    }
                    codeContainer.Children.Clear();

                }
                catch (Exception ex)
                {
                    await new MessageBox("Attention!", "An error occurred while deleting the files!\n" + ex.Message).ShowDialog2(this.FindAncestorOfType<Window>());
                }
            };

            if (Directory.Exists(autosavePath))
            {
                Dictionary<DateTime, List<(string, string, string, int)>> items = new Dictionary<DateTime, List<(string, string, string, int)>>();

                foreach (string directory in Directory.GetDirectories(autosavePath))
                {
                    string editorId = Path.GetFileName(directory);

                    if (editorId != "Autosave" && editorId.Contains("_") && !editorId.StartsWith("ModuleCreator"))
                    {
                        try
                        {
                            string type = editorId.Substring(0, editorId.IndexOf("_"));

                            editorId = editorId.Substring(editorId.IndexOf("_") + 1);

                            string parameterName = editorId.Substring(0, editorId.LastIndexOf("_")).Replace("_", " ").Trim();

                            DirectoryInfo info = new DirectoryInfo(directory);

                            DateTime date = info.LastWriteTime.Date;

                            if (!items.TryGetValue(date, out List<(string, string, string, int)> list))
                            {
                                list = new List<(string, string, string, int)>();
                                items[date] = list;
                            }

                            int count = info.EnumerateFiles().Count();

                            if (count > 0)
                            {
                                list.Add((directory, type, parameterName, count));
                            }
                        }
                        catch { }
                    }
                }

                foreach (KeyValuePair<DateTime, List<(string, string, string, int)>> kvp in items.OrderByDescending(a => a.Key))
                {
                    if (kvp.Value.Count > 0)
                    {

                        Accordion exp = new Accordion() { Margin = new Thickness(0, 5, 0, 5), ArrowSize = 12, HeaderForegroundOpen = new SolidColorBrush(Colors.Black) };
                        exp.HeaderHoverBackground = new SolidColorBrush(Color.FromRgb(210, 210, 210));

                        Grid header = new Grid() { Height = 27 };
                        header.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                        header.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));

                        header.Children.Add(new TextBlock() { Text = kvp.Key.ToString("D"), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, FontSize = 14 });

                        StackPanel deleteAllButtonContent = new StackPanel() { Orientation = Avalonia.Layout.Orientation.Horizontal };

                        deleteAllButtonContent.Children.Add(new DPIAwareBox(Icons.GetIcon16("TreeViewer.replacedets.Trash")));

                        deleteAllButtonContent.Children.Add(new TextBlock() { Text = "Delete all", FontSize = 12, Foreground = new SolidColorBrush(Color.FromRgb(102, 102, 102)), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, Margin = new Thickness(2, 0, 0, 0) });

                        Button deleteAllButton = new Button() { Content = deleteAllButtonContent, Margin = new Thickness(5, 0, 0, 0), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, Background = Brushes.Transparent, Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Arrow), IsVisible = false };
                        deleteAllButton.Clreplacedes.Add("SideBarButton");
                        Grid.SetColumn(deleteAllButton, 1);
                        header.Children.Add(deleteAllButton);

                        exp.AccordionHeader = header;

                        bool contentsBuilt = false;

                        exp.PointerEnter += (s, e) =>
                        {
                            deleteAllButton.IsVisible = true;
                        };

                        exp.PointerLeave += (s, e) =>
                        {
                            deleteAllButton.IsVisible = false;
                        };

                        exp.PropertyChanged += (s, e) =>
                        {
                            if (e.Property == Accordion.IsOpenProperty)
                            {
                                if (!contentsBuilt)
                                {
                                    StackPanel contents = new StackPanel();

                                    deleteAllButton.Click += async (s, e) =>
                                    {
                                        try
                                        {
                                            foreach ((string, string, string, int) item in kvp.Value)
                                            {
                                                if (Directory.Exists(item.Item1))
                                                {
                                                    Directory.Delete(item.Item1, true);
                                                }
                                            }

                                            codeContainer.Children.Remove(exp);
                                        }
                                        catch (Exception ex)
                                        {
                                            await new MessageBox("Attention!", "An error occurred while deleting the files!\n" + ex.Message).ShowDialog2(this.FindAncestorOfType<Window>());
                                        }
                                    };

                                    int index = 0;

                                    foreach ((string, string, string, int) item in kvp.Value)
                                    {
                                        Grid itemGrid = new Grid() { Height = 53, Margin = new Thickness(0, 0, 0, 4), Background = Brushes.Transparent };
                                        itemGrid.ColumnDefinitions.Add(new ColumnDefinition(50, GridUnitType.Pixel));
                                        itemGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                                        itemGrid.ColumnDefinitions.Add(new ColumnDefinition(50, GridUnitType.Pixel));
                                        itemGrid.ColumnDefinitions.Add(new ColumnDefinition(29, GridUnitType.Pixel));

                                        {
                                            Canvas can = new Canvas() { Height = 1, Background = new SolidColorBrush(Color.FromRgb(210, 210, 210)), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Bottom };
                                            Grid.SetColumnSpan(can, 4);
                                            itemGrid.Children.Add(can);
                                        }

                                        StackPanel namePanel = new StackPanel() { Margin = new Thickness(0, 0, 5, 0), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                                        Grid.SetColumn(namePanel, 1);
                                        itemGrid.Children.Add(namePanel);

                                        {
                                            string text = item.Item3;
                                            if (text.EndsWith("..."))
                                            {
                                                text = text.Substring(0, text.Length - 3);
                                            }
                                            if (text.EndsWith(":"))
                                            {
                                                text = text.Substring(0, text.Length - 1);
                                            }

                                            TrimmedTextBox2 block = new TrimmedTextBox2() { Text = text, FontSize = 16, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                                            AvaloniaBugFixes.SetToolTip(block, new TextBlock() { Text = text, TextWrapping = TextWrapping.NoWrap });
                                            namePanel.Children.Add(block);
                                        }

                                        {
                                            string text = "";

                                            switch (item.Item2)
                                            {
                                                case "CodeEditor":
                                                    text = "Custom script";
                                                    itemGrid.Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.SourceCode")) { Width = 32, Height = 32 });
                                                    break;
                                                case "StringFormatter":
                                                    text = "String formatter";
                                                    itemGrid.Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.StringFormatter")) { Width = 32, Height = 32 });
                                                    break;
                                                case "NumberFormatter":
                                                    text = "Number formatter";
                                                    itemGrid.Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.NumberFormatter")) { Width = 32, Height = 32 });
                                                    break;
                                                case "ColourFormatter":
                                                    text = "Colour formatter";
                                                    itemGrid.Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.ColourFormatter")) { Width = 32, Height = 32 });
                                                    break;
                                                case "MarkdownEditor":
                                                    text = "Markdown code";
                                                    itemGrid.Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.Markdown")) { Width = 32, Height = 32 });
                                                    break;
                                            }

                                            TrimmedTextBox2 block = new TrimmedTextBox2() { Text = text, Foreground = new SolidColorBrush(Color.FromRgb(102, 102, 102)), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, FontSize = 12 };
                                            AvaloniaBugFixes.SetToolTip(block, new TextBlock() { Text = text, TextWrapping = TextWrapping.NoWrap });
                                            namePanel.Children.Add(block);
                                        }

                                        StackPanel timeSizePanel = new StackPanel() { VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, Orientation = Avalonia.Layout.Orientation.Horizontal, Background = Brushes.Transparent };

                                        AvaloniaBugFixes.SetToolTip(timeSizePanel, "Saved " + item.Item4.ToString() + " times");
                                        Grid.SetColumn(timeSizePanel, 2);
                                        itemGrid.Children.Add(timeSizePanel);

                                        {
                                            timeSizePanel.Children.Add(new DPIAwareBox(Icons.GetIcon16("TreeViewer.replacedets.History")) { Width = 16, Height = 16, Margin = new Thickness(0, 0, 5, 0) });
                                            TextBlock block = new TextBlock() { Text = item.Item4.ToString(), Foreground = new SolidColorBrush(Color.FromRgb(102, 102, 102)), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center };
                                            timeSizePanel.Children.Add(block);
                                        }

                                        StackPanel buttonsPanel = new StackPanel() { VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                                        Grid.SetColumn(buttonsPanel, 3);
                                        itemGrid.Children.Add(buttonsPanel);

                                        Button deleteButton = new Button() { Foreground = Brushes.Black, Content = new DPIAwareBox(Icons.GetIcon16("TreeViewer.replacedets.Trash")) { Width = 16, Height = 16 }, Background = Brushes.Transparent, Padding = new Thickness(0), Width = 24, Height = 24, Margin = new Thickness(0, 0, 0, 2), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, IsVisible = false };
                                        buttonsPanel.Children.Add(deleteButton);
                                        AvaloniaBugFixes.SetToolTip(deleteButton, new TextBlock() { Text = "Delete", Foreground = Brushes.Black });
                                        deleteButton.Clreplacedes.Add("SideBarButton");

                                        itemGrid.PointerEnter += (s, e) =>
                                        {
                                            deleteButton.IsVisible = true;
                                            itemGrid.Background = new SolidColorBrush(Color.FromRgb(210, 210, 210));
                                        };

                                        itemGrid.PointerLeave += (s, e) =>
                                        {
                                            deleteButton.IsVisible = false;
                                            itemGrid.Background = Brushes.Transparent;
                                        };

                                        itemGrid.PointerPressed += (s, e) =>
                                        {
                                            itemGrid.Background = new SolidColorBrush(Color.FromRgb(177, 177, 177));
                                        };

                                        itemGrid.PointerReleased += async (s, e) =>
                                        {
                                            itemGrid.Background = new SolidColorBrush(Color.FromRgb(210, 210, 210));

                                            Point pos = e.GetCurrentPoint(itemGrid).Position;

                                            if (pos.X >= 0 && pos.Y >= 0 && pos.X <= itemGrid.Bounds.Width && pos.Y <= itemGrid.Bounds.Height)
                                            {
                                                if (item.Item2 != "MarkdownEditor")
                                                {
                                                    CodeViewerWindow win = new CodeViewerWindow();
                                                    await win.Initialize(item.Item2, item.Item1);
                                                    await win.ShowDialog2(this.FindAncestorOfType<Window>());
                                                }
                                                else
                                                {
                                                    CodeViewerWindow win = new CodeViewerWindow();
                                                    await win.Initialize(item.Item2, item.Item1);
                                                    await win.ShowDialog2(this.FindAncestorOfType<Window>());
                                                }
                                            }
                                        };

                                        deleteButton.Click += async (s, e) =>
                                        {
                                            try
                                            {
                                                int ind = Grid.GetRow(deleteButton);

                                                Directory.Delete(item.Item1, true);
                                                contents.Children.Remove(itemGrid);

                                                if (contents.Children.Count == 0)
                                                {
                                                    this.FindControl<StackPanel>("CodeContainer").Children.Remove(exp);
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                await new MessageBox("Attention!", "An error occurred while deleting the files!\n" + ex.Message).ShowDialog2(this.FindAncestorOfType<Window>());
                                            }

                                            exp.InvalidateHeight();

                                        };

                                        contents.Children.Add(itemGrid);

                                        index++;
                                    }

                                    exp.AccordionContent = contents;

                                    contentsBuilt = true;
                                }
                            }
                        };

                        codeContainer.Children.Add(exp);
                    }
                }
            }
        }

19 Source : AutosavesPage.cs
with GNU Affero General Public License v3.0
from arklumpus

private void BuildTreesGrid()
        {
            TreesGrid.Margin = new Thickness(25, 0, 0, 0);

            TreesGrid.RowDefinitions.Add(new RowDefinition(0, GridUnitType.Auto));
            TreesGrid.RowDefinitions.Add(new RowDefinition(1, GridUnitType.Star));

            Grid replacedleGrid = new Grid() { Margin = new Thickness(0, 0, 0, 5) };
            replacedleGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
            replacedleGrid.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));

            TreesGrid.Children.Add(replacedleGrid);

            replacedleGrid.Children.Add(new TextBlock() { FontSize = 20, Foreground = new SolidColorBrush(Color.FromRgb(0, 114, 178)), Text = "Autosaved trees" });


            StackPanel deleteAllTreesButtonContent = new StackPanel() { Orientation = Avalonia.Layout.Orientation.Horizontal };

            deleteAllTreesButtonContent.Children.Add(new DPIAwareBox(Icons.GetIcon16("TreeViewer.replacedets.Trash")));

            deleteAllTreesButtonContent.Children.Add(new TextBlock() { Text = "Delete all", FontSize = 12, Foreground = new SolidColorBrush(Color.FromRgb(102, 102, 102)), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, Margin = new Thickness(2, 0, 0, 0) });

            Button deleteAllTreesButton = new Button() { Content = deleteAllTreesButtonContent, Margin = new Thickness(5, 0, 0, 0), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, Background = Brushes.Transparent, Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Arrow) };
            deleteAllTreesButton.Clreplacedes.Add("SideBarButton");
            Grid.SetColumn(deleteAllTreesButton, 1);
            replacedleGrid.Children.Add(deleteAllTreesButton);



            StackPanel treeContainer = new StackPanel();

            ScrollViewer scroller = new ScrollViewer() { HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled, VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto, Padding = new Thickness(0, 0, 17, 0), AllowAutoHide = false };
            scroller.Content = treeContainer;
            Grid.SetRow(scroller, 1);
            TreesGrid.Children.Add(scroller);

            string autosavePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), replacedembly.GetEntryreplacedembly().GetName().Name, "Autosave");

            deleteAllTreesButton.Click += async (s, e) =>
            {
                try
                {
                    string autosavePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), replacedembly.GetEntryreplacedembly().GetName().Name, "Autosave");

                    if (Directory.Exists(autosavePath))
                    {
                        Dictionary<DateTime, List<(string, string, string, int)>> items = new Dictionary<DateTime, List<(string, string, string, int)>>();

                        foreach (string directory in Directory.GetDirectories(autosavePath))
                        {
                            Directory.Delete(directory, true);
                        }
                    }
                    treeContainer.Children.Clear();

                }
                catch (Exception ex)
                {
                    await new MessageBox("Attention!", "An error occurred while deleting the files!\n" + ex.Message).ShowDialog2(this.FindAncestorOfType<Window>());
                }
            };

            if (Directory.Exists(autosavePath))
            {
                foreach (string directory in Directory.GetDirectories(autosavePath).OrderByDescending(a => a))
                {
                    if (Directory.EnumerateDirectories(directory).Count() > 0)
                    {
                        string dateString = Path.GetFileName(directory);

                        int[] dateItems = (from el in dateString.Split('_') select int.Parse(el)).ToArray();

                        DateTime date = new DateTime(dateItems[0], dateItems[1], dateItems[2]);

                        Accordion exp = new Accordion() { Margin = new Thickness(0, 5, 0, 5), ArrowSize = 12, HeaderForegroundOpen = new SolidColorBrush(Colors.Black) };
                        exp.HeaderHoverBackground = new SolidColorBrush(Color.FromRgb(210, 210, 210));

                        Grid header = new Grid() { Height = 27 };
                        header.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                        header.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));

                        header.Children.Add(new TextBlock() { Text = date.ToString("D"), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, FontSize = 14 });

                        StackPanel deleteAllButtonContent = new StackPanel() { Orientation = Avalonia.Layout.Orientation.Horizontal };

                        deleteAllButtonContent.Children.Add(new DPIAwareBox(Icons.GetIcon16("TreeViewer.replacedets.Trash")));

                        deleteAllButtonContent.Children.Add(new TextBlock() { Text = "Delete all", FontSize = 12, Foreground = new SolidColorBrush(Color.FromRgb(102, 102, 102)), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, Margin = new Thickness(2, 0, 0, 0) });

                        Button deleteAllButton = new Button() { Content = deleteAllButtonContent, Margin = new Thickness(5, 0, 0, 0), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, Background = Brushes.Transparent, Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Arrow), IsVisible = false };
                        deleteAllButton.Clreplacedes.Add("SideBarButton");
                        Grid.SetColumn(deleteAllButton, 1);
                        header.Children.Add(deleteAllButton);

                        exp.AccordionHeader = header;

                        bool contentsBuilt = false;

                        exp.PointerEnter += (s, e) =>
                        {
                            deleteAllButton.IsVisible = true;
                        };

                        exp.PointerLeave += (s, e) =>
                        {
                            deleteAllButton.IsVisible = false;
                        };

                        exp.PropertyChanged += (s, e) =>
                        {
                            if (e.Property == Accordion.IsOpenProperty)
                            {
                                if (!contentsBuilt)
                                {
                                    StackPanel contents = new StackPanel();

                                    deleteAllButton.Click += async (s, e) =>
                                    {
                                        try
                                        {
                                            Directory.Delete(directory, true);

                                            treeContainer.Children.Remove(exp);
                                        }
                                        catch (Exception ex)
                                        {
                                            await new MessageBox("Attention!", "An error occurred while deleting the files!\n" + ex.Message).ShowDialog2(this.FindAncestorOfType<Window>());
                                        }
                                    };

                                    int index = 0;

                                    List<string> fileDirs = new List<string>(Directory.GetDirectories(directory));
                                    Dictionary<string, AutosaveData> saveDatas = new Dictionary<string, AutosaveData>();

                                    foreach (string fileDirectory in fileDirs)
                                    {
                                        string autosaveFile = Path.Combine(fileDirectory, "autosave.json");

                                        if (File.Exists(autosaveFile))
                                        {
                                            saveDatas[fileDirectory] = System.Text.Json.JsonSerializer.Deserialize<AutosaveData>(File.ReadAllText(autosaveFile), Modules.DefaultSerializationOptions);
                                        }
                                    }

                                    foreach (string fileDirectory in (from el in fileDirs where saveDatas.ContainsKey(el) orderby saveDatas[el].SaveTime descending select el))
                                    {
                                        string treeFile = Path.Combine(fileDirectory, Path.GetFileName(fileDirectory) + ".nex");
                                        string autosaveFile = Path.Combine(fileDirectory, "autosave.json");

                                        if (File.Exists(autosaveFile) && File.Exists(treeFile))
                                        {
                                            string extension = "tree";

                                            Grid itemGrid = new Grid() { Height = 53, Margin = new Thickness(0, 0, 0, 4), Background = Brushes.Transparent };
                                            itemGrid.ColumnDefinitions.Add(new ColumnDefinition(50, GridUnitType.Pixel));
                                            itemGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                                            itemGrid.ColumnDefinitions.Add(new ColumnDefinition(80, GridUnitType.Pixel));
                                            itemGrid.ColumnDefinitions.Add(new ColumnDefinition(29, GridUnitType.Pixel));

                                            AutosaveData saveData = saveDatas[fileDirectory];

                                            FileInfo info = new FileInfo(treeFile);

                                            long size = info.Length;

                                            {
                                                Canvas can = new Canvas() { Height = 1, Background = new SolidColorBrush(Color.FromRgb(210, 210, 210)), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Bottom };
                                                Grid.SetColumnSpan(can, 4);
                                                itemGrid.Children.Add(can);
                                            }

                                            StackPanel namePanel = new StackPanel() { Margin = new Thickness(0, 0, 5, 0), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                                            Grid.SetColumn(namePanel, 1);
                                            itemGrid.Children.Add(namePanel);

                                            if (!string.IsNullOrEmpty(saveData.OriginalPath))
                                            {
                                                extension = Path.GetExtension(saveData.OriginalPath).ToLowerInvariant().Replace(".", "");

                                                if (!FileExtensions.EmbeddedFileTypeIcons.Contains(extension))
                                                {
                                                    extension = "tree";
                                                }

                                                TrimmedTextBox2 block = new TrimmedTextBox2() { Text = Path.GetFileName(saveData.OriginalPath), FontSize = 16, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                                                AvaloniaBugFixes.SetToolTip(block, new TextBlock() { Text = saveData.OriginalPath, TextWrapping = TextWrapping.NoWrap });
                                                namePanel.Children.Add(block);
                                            }
                                            else
                                            {
                                                extension = "nex";

                                                TextBlock block = new TextBlock() { Text = "(None)", FontSize = 16, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                                                namePanel.Children.Add(block);
                                            }

                                            if (!string.IsNullOrEmpty(saveData.OriginalPath))
                                            {
                                                TrimmedTextBox2 block = new TrimmedTextBox2() { Text = Path.GetDirectoryName(saveData.OriginalPath), Foreground = new SolidColorBrush(Color.FromRgb(102, 102, 102)), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, FontSize = 12 };
                                                AvaloniaBugFixes.SetToolTip(block, new TextBlock() { Text = saveData.OriginalPath, TextWrapping = TextWrapping.NoWrap });
                                                namePanel.Children.Add(block);
                                            }
                                            else
                                            {
                                                TextBlock block = new TextBlock() { Text = "(None)", FontStyle = FontStyle.Italic, Foreground = new SolidColorBrush(Color.FromRgb(102, 102, 102)), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                                                namePanel.Children.Add(block);
                                            }

                                            itemGrid.Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.FileTypeIcons." + extension)) { Width = 32, Height = 32 });

                                            StackPanel timeSizePanel = new StackPanel() { VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                                            Grid.SetColumn(timeSizePanel, 2);
                                            itemGrid.Children.Add(timeSizePanel);

                                            {
                                                TextBlock block = new TextBlock() { Text = saveData.SaveTime.ToString("t"), Foreground = new SolidColorBrush(Color.FromRgb(102, 102, 102)), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left };
                                                timeSizePanel.Children.Add(block);
                                            }

                                            {
                                                TextBlock block = new TextBlock() { Text = GetHumanReadableSize(size), Foreground = new SolidColorBrush(Color.FromRgb(102, 102, 102)), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Left };
                                                timeSizePanel.Children.Add(block);
                                            }

                                            StackPanel buttonsPanel = new StackPanel() { VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                                            Grid.SetColumn(buttonsPanel, 3);
                                            itemGrid.Children.Add(buttonsPanel);

                                            Button deleteButton = new Button() { Foreground = Brushes.Black, Content = new DPIAwareBox(Icons.GetIcon16("TreeViewer.replacedets.Trash")) { Width = 16, Height = 16 }, Background = Brushes.Transparent, Padding = new Thickness(0), Width = 24, Height = 24, Margin = new Thickness(0, 0, 0, 2), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, IsVisible = false };
                                            buttonsPanel.Children.Add(deleteButton);
                                            AvaloniaBugFixes.SetToolTip(deleteButton, new TextBlock() { Text = "Delete", Foreground = Brushes.Black });
                                            deleteButton.Clreplacedes.Add("SideBarButton");

                                            itemGrid.PointerEnter += (s, e) =>
                                            {
                                                deleteButton.IsVisible = true;
                                                itemGrid.Background = new SolidColorBrush(Color.FromRgb(210, 210, 210));
                                            };

                                            itemGrid.PointerLeave += (s, e) =>
                                            {
                                                deleteButton.IsVisible = false;
                                                itemGrid.Background = Brushes.Transparent;
                                            };

                                            itemGrid.PointerPressed += (s, e) =>
                                            {
                                                itemGrid.Background = new SolidColorBrush(Color.FromRgb(177, 177, 177));
                                            };

                                            itemGrid.PointerReleased += async (s, e) =>
                                            {
                                                itemGrid.Background = new SolidColorBrush(Color.FromRgb(210, 210, 210));

                                                Point pos = e.GetCurrentPoint(itemGrid).Position;

                                                if (pos.X >= 0 && pos.Y >= 0 && pos.X <= itemGrid.Bounds.Width && pos.Y <= itemGrid.Bounds.Height)
                                                {
                                                    await this.FindAncestorOfType<MainWindow>().LoadFile(treeFile, false, saveData.OriginalPath);
                                                }
                                            };

                                            deleteButton.Click += async (s, e) =>
                                            {
                                                try
                                                {
                                                    int ind = Grid.GetRow(deleteButton);

                                                    Directory.Delete(fileDirectory, true);

                                                    contents.Children.Remove(itemGrid);

                                                    if (contents.Children.Count == 0)
                                                    {
                                                        treeContainer.Children.Remove(exp);
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    await new MessageBox("Attention!", "An error occurred while deleting the files!\n" + ex.Message).ShowDialog2(this.FindAncestorOfType<Window>());
                                                }

                                                exp.InvalidateHeight();

                                            };

                                            contents.Children.Add(itemGrid);

                                            index++;
                                        }
                                    }

                                    exp.AccordionContent = contents;

                                    contentsBuilt = true;
                                }
                            }
                        };

                        treeContainer.Children.Add(exp);
                    }
                }
            }
        }

19 Source : ModuleCreatorWindow.axaml.cs
with GNU Affero General Public License v3.0
from arklumpus

private void InitializeComponent()
        {
            AvaloniaXamlLoader.Load(this);

            if (GlobalSettings.Settings.InterfaceStyle == GlobalSettings.InterfaceStyles.MacOSStyle)
            {
                this.Clreplacedes.Add("MacOSStyle");
            }
            else if (GlobalSettings.Settings.InterfaceStyle == GlobalSettings.InterfaceStyles.WindowsStyle)
            {
                this.Clreplacedes.Add("WindowsStyle");
            }

            this.FindControl<Grid>("HeaderGrid").Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.ModuleCreator")) { Width = 32, Height = 32 });



            ((Grid)this.FindControl<Button>("FileTypeModuleButton").Content).Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.FileType")) { Width = 32, Height = 32 });
            ((Grid)this.FindControl<Button>("LoadFileModuleButton").Content).Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.LoadFile")) { Width = 32, Height = 32 });
            ((Grid)this.FindControl<Button>("TransformerModuleButton").Content).Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.Transformer")) { Width = 32, Height = 32 });
            ((Grid)this.FindControl<Button>("FurtherTransformationModuleButton").Content).Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.FurtherTransformations")) { Width = 32, Height = 32 });
            ((Grid)this.FindControl<Button>("CoordinatesModuleButton").Content).Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.Coordinates")) { Width = 32, Height = 32 });
            ((Grid)this.FindControl<Button>("PlotActionModuleButton").Content).Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.PlotActions")) { Width = 32, Height = 32 });
            ((Grid)this.FindControl<Button>("SelectionActionModuleButton").Content).Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.SelectionAction")) { Width = 32, Height = 32 });
            ((Grid)this.FindControl<Button>("ActionModuleButton").Content).Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.Action")) { Width = 32, Height = 32 });
            ((Grid)this.FindControl<Button>("MenuActionModuleButton").Content).Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets.MenuAction")) { Width = 32, Height = 32 });

            if (DebuggerServer == null)
            {
                DebuggerServer = Modules.GetNewDebuggerServer();
            }

            ((IControlledApplicationLifetime)Application.Current.ApplicationLifetime).Exit += (s, e) =>
            {
                DebuggerServer.Dispose();
            };

            NativeMenu menu = new NativeMenu();
            NativeMenuItem moduleMenu = new NativeMenuItem() { Header = "Edit" };

            NativeMenu moduleSubMenu = new NativeMenu();

            NativeMenuItem encodeBinaryFile = new NativeMenuItem() { Header = "Encode binary file in Base64...", Command = new SimpleCommand(win => ((ModuleCreatorWindow)win).CodeEditor != null, async a => await EncodeBinaryFileInBase64(), this, CodeEditorProperty) };
            moduleSubMenu.Add(encodeBinaryFile);

            NativeMenuItem encodeTextFile = new NativeMenuItem() { Header = "Encode text file in Base64...", Command = new SimpleCommand(win => ((ModuleCreatorWindow)win).CodeEditor != null, async a => await EncodeTextFileInBase64(), this, CodeEditorProperty) };
            moduleSubMenu.Add(encodeTextFile);

            moduleMenu.Menu = moduleSubMenu;
            menu.Add(moduleMenu);

            NativeMenu.SetMenu(this, menu);

            this.Closing += (s, e) =>
            {
                SplashScreen splash = new SplashScreen(SubsequentArgs);
                splash.OnModulesLoaded = loadAdditionalModule;

                splash.Show();
            };

            List<(string, string, int, DateTime)> recenreplacedems = new List<(string, string, int, DateTime)>();

            string autosavePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), replacedembly.GetEntryreplacedembly().GetName().Name);

            if (Directory.Exists(autosavePath))
            {
                foreach (string directory in Directory.GetDirectories(autosavePath))
                {
                    string editorId = Path.GetFileName(directory);

                    if (editorId.StartsWith("ModuleCreator"))
                    {
                        try
                        {
                            editorId = editorId.Substring(editorId.IndexOf("_") + 1);

                            string moduleType = editorId.Substring(0, editorId.IndexOf("_"));

                            DirectoryInfo info = new DirectoryInfo(directory);

                            DateTime date = info.LastWriteTime;

                            int count = info.EnumerateFiles().Count();

                            if (count > 0)
                            {
                                recenreplacedems.Add((directory, moduleType, count, date));
                            }
                        }
                        catch { }
                    }
                }

                int index = 2;

                foreach ((string, string, int, DateTime) item in recenreplacedems.OrderByDescending(a => a.Item4))
                {
                    Grid itemGrid = new Grid() { Height = 42, Width = 260, Margin = new Thickness(0, 0, 5, 5), Background = Avalonia.Media.Brushes.Transparent };
                    itemGrid.ColumnDefinitions.Add(new ColumnDefinition(37, GridUnitType.Pixel));
                    itemGrid.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
                    itemGrid.ColumnDefinitions.Add(new ColumnDefinition(0, GridUnitType.Auto));

                    StackPanel namePanel = new StackPanel() { Margin = new Thickness(5, 0, 5, 0), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                    Grid.SetColumn(namePanel, 1);
                    itemGrid.Children.Add(namePanel);

                    TrimmedTextBox2 nameBlock;
                    TrimmedTextBox2 dateBlock;

                    {
                        nameBlock = new TrimmedTextBox2() { Text = moduleTypeTranslations[item.Item2], FontSize = 16, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                        AvaloniaBugFixes.SetToolTip(nameBlock, new TextBlock() { Text = moduleTypeTranslations[item.Item2], TextWrapping = Avalonia.Media.TextWrapping.NoWrap });
                        namePanel.Children.Add(nameBlock);
                    }

                    {
                        dateBlock = new TrimmedTextBox2() { Text = item.Item4.ToString("f"), Foreground = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(102, 102, 102)), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, FontSize = 12 };
                        AvaloniaBugFixes.SetToolTip(dateBlock, new TextBlock() { Text = item.Item4.ToString("f"), TextWrapping = Avalonia.Media.TextWrapping.NoWrap });
                        namePanel.Children.Add(dateBlock);
                    }

                    itemGrid.Children.Add(new DPIAwareBox(Icons.GetIcon32("TreeViewer.replacedets." + moduleTypeIcons[item.Item2])) { Width = 32, Height = 32, Margin = new Thickness(5, 0, 0, 0), HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center });

                    StackPanel buttonsPanel = new StackPanel() { VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
                    Grid.SetColumn(buttonsPanel, 2);
                    itemGrid.Children.Add(buttonsPanel);

                    Button deleteButton = new Button() { Foreground = Avalonia.Media.Brushes.Black, Content = new DPIAwareBox(Icons.GetIcon16("TreeViewer.replacedets.Trash")) { Width = 16, Height = 16 }, Background = Avalonia.Media.Brushes.Transparent, Padding = new Thickness(0), Width = 24, Height = 24, Margin = new Thickness(0, 0, 0, 2), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center, HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Center, IsVisible = false };
                    buttonsPanel.Children.Add(deleteButton);
                    AvaloniaBugFixes.SetToolTip(deleteButton, new TextBlock() { Text = "Delete", Foreground = Avalonia.Media.Brushes.Black });
                    deleteButton.Clreplacedes.Add("SideBarButton");

                    itemGrid.PointerEnter += (s, e) =>
                    {
                        deleteButton.IsVisible = true;
                        itemGrid.Background = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(210, 210, 210));
                    };

                    itemGrid.PointerLeave += (s, e) =>
                    {
                        deleteButton.IsVisible = false;
                        itemGrid.Background = Avalonia.Media.Brushes.Transparent;
                    };

                    itemGrid.PointerPressed += (s, e) =>
                    {
                        itemGrid.Background = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(177, 177, 177));
                    };

                    itemGrid.PointerReleased += async (s, e) =>
                    {
                        itemGrid.Background = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.FromRgb(210, 210, 210));

                        Point pos = e.GetCurrentPoint(itemGrid).Position;

                        if (pos.X >= 0 && pos.Y >= 0 && pos.X <= itemGrid.Bounds.Width && pos.Y <= itemGrid.Bounds.Height)
                        {
                            string guid = Path.GetFileName(item.Item1);

                            string oldestFile = null;
                            DateTime oldestTime = DateTime.UnixEpoch;

                            foreach (string sr in Directory.GetFiles(item.Item1))
                            {
                                FileInfo fi = new FileInfo(sr);

                                if (fi.LastWriteTime.CompareTo(oldestTime) == 1)
                                {
                                    oldestTime = fi.LastWriteTime;
                                    oldestFile = sr;
                                }
                            }

                            string moduleSource = File.ReadAllText(oldestFile);

                            await InitializeEditor(moduleSource, guid);
                        }
                    };

                    deleteButton.Click += async (s, e) =>
                    {
                        try
                        {
                            Directory.Delete(item.Item1, true);

                            this.FindControl<WrapPanel>("RecentFilesGrid").Children.Remove(itemGrid);
                        }
                        catch (Exception ex)
                        {
                            MessageBox box = new MessageBox("Attention", "An error occurred while deleting the file!\n" + ex.Message);
                            await box.ShowDialog2(this);
                        }
                    }; ;


                    this.FindControl<WrapPanel>("RecentFilesGrid").Children.Add(itemGrid);

                    index++;
                }
            }
            else
            {
                Directory.CreateDirectory(autosavePath);
            }

            this.FindControl<Button>("FileTypeModuleButton").Click += async (s, e) =>
            {
                string moduleSource;
                using (StreamReader reader = new StreamReader(replacedembly.GetExecutingreplacedembly().GetManifestResourceStream("TreeViewer.Templates.FileType.cs")))
                {
                    moduleSource = reader.ReadToEnd();
                }

                Guid guid = Guid.NewGuid();

                moduleSource = moduleSource.Replace("@NamespaceHere", "a" + guid.ToString("N"));
                moduleSource = moduleSource.Replace("@GuidHere", guid.ToString());

                await InitializeEditor(moduleSource, "ModuleCreator_FileType_" + guid.ToString());
            };

            this.FindControl<Button>("PlotActionModuleButton").Click += async (s, e) =>
            {
                string moduleSource;
                using (StreamReader reader = new StreamReader(replacedembly.GetExecutingreplacedembly().GetManifestResourceStream("TreeViewer.Templates.PlotAction.cs")))
                {
                    moduleSource = reader.ReadToEnd();
                }

                Guid guid = Guid.NewGuid();

                moduleSource = moduleSource.Replace("@NamespaceHere", "a" + guid.ToString("N"));
                moduleSource = moduleSource.Replace("@GuidHere", guid.ToString());

                await InitializeEditor(moduleSource, "ModuleCreator_PlotAction_" + guid.ToString());
            };

            this.FindControl<Button>("LoadFileModuleButton").Click += async (s, e) =>
            {
                string moduleSource;
                using (StreamReader reader = new StreamReader(replacedembly.GetExecutingreplacedembly().GetManifestResourceStream("TreeViewer.Templates.LoadFile.cs")))
                {
                    moduleSource = reader.ReadToEnd();
                }

                Guid guid = Guid.NewGuid();

                moduleSource = moduleSource.Replace("@NamespaceHere", "a" + guid.ToString("N"));
                moduleSource = moduleSource.Replace("@GuidHere", guid.ToString());

                await InitializeEditor(moduleSource, "ModuleCreator_LoadFile_" + guid.ToString());
            };

            this.FindControl<Button>("TransformerModuleButton").Click += async (s, e) =>
            {
                string moduleSource;
                using (StreamReader reader = new StreamReader(replacedembly.GetExecutingreplacedembly().GetManifestResourceStream("TreeViewer.Templates.Transformer.cs")))
                {
                    moduleSource = reader.ReadToEnd();
                }

                Guid guid = Guid.NewGuid();

                moduleSource = moduleSource.Replace("@NamespaceHere", "a" + guid.ToString("N"));
                moduleSource = moduleSource.Replace("@GuidHere", guid.ToString());

                await InitializeEditor(moduleSource, "ModuleCreator_Transformer_" + guid.ToString());
            };

            this.FindControl<Button>("FurtherTransformationModuleButton").Click += async (s, e) =>
            {
                string moduleSource;
                using (StreamReader reader = new StreamReader(replacedembly.GetExecutingreplacedembly().GetManifestResourceStream("TreeViewer.Templates.FurtherTransformation.cs")))
                {
                    moduleSource = reader.ReadToEnd();
                }

                Guid guid = Guid.NewGuid();

                moduleSource = moduleSource.Replace("@NamespaceHere", "a" + guid.ToString("N"));
                moduleSource = moduleSource.Replace("@GuidHere", guid.ToString());

                await InitializeEditor(moduleSource, "ModuleCreator_FurtherTransformation_" + guid.ToString());
            };

            this.FindControl<Button>("CoordinatesModuleButton").Click += async (s, e) =>
            {
                string moduleSource;
                using (StreamReader reader = new StreamReader(replacedembly.GetExecutingreplacedembly().GetManifestResourceStream("TreeViewer.Templates.Coordinates.cs")))
                {
                    moduleSource = reader.ReadToEnd();
                }

                Guid guid = Guid.NewGuid();

                moduleSource = moduleSource.Replace("@NamespaceHere", "a" + guid.ToString("N"));
                moduleSource = moduleSource.Replace("@GuidHere", guid.ToString());

                await InitializeEditor(moduleSource, "ModuleCreator_Coordinates_" + guid.ToString());
            };

            this.FindControl<Button>("SelectionActionModuleButton").Click += async (s, e) =>
            {
                string moduleSource;
                using (StreamReader reader = new StreamReader(replacedembly.GetExecutingreplacedembly().GetManifestResourceStream("TreeViewer.Templates.SelectionAction.cs")))
                {
                    moduleSource = reader.ReadToEnd();
                }

                Guid guid = Guid.NewGuid();

                moduleSource = moduleSource.Replace("@NamespaceHere", "a" + guid.ToString("N"));
                moduleSource = moduleSource.Replace("@GuidHere", guid.ToString());

                await InitializeEditor(moduleSource, "ModuleCreator_SelectionAction_" + guid.ToString());
            };

            this.FindControl<Button>("ActionModuleButton").Click += async (s, e) =>
            {
                string moduleSource;
                using (StreamReader reader = new StreamReader(replacedembly.GetExecutingreplacedembly().GetManifestResourceStream("TreeViewer.Templates.Action.cs")))
                {
                    moduleSource = reader.ReadToEnd();
                }

                Guid guid = Guid.NewGuid();

                moduleSource = moduleSource.Replace("@NamespaceHere", "a" + guid.ToString("N"));
                moduleSource = moduleSource.Replace("@GuidHere", guid.ToString());

                await InitializeEditor(moduleSource, "ModuleCreator_Action_" + guid.ToString());
            };

            this.FindControl<Button>("MenuActionModuleButton").Click += async (s, e) =>
            {
                string moduleSource;
                using (StreamReader reader = new StreamReader(replacedembly.GetExecutingreplacedembly().GetManifestResourceStream("TreeViewer.Templates.MenuAction.cs")))
                {
                    moduleSource = reader.ReadToEnd();
                }

                Guid guid = Guid.NewGuid();

                moduleSource = moduleSource.Replace("@NamespaceHere", "a" + guid.ToString("N"));
                moduleSource = moduleSource.Replace("@GuidHere", guid.ToString());

                await InitializeEditor(moduleSource, "ModuleCreator_MenuAction_" + guid.ToString());
            };
        }

19 Source : Extensions.cs
with MIT License
from arqueror

public static MuxedStreamInfo WithHighestVideoQuality(this IEnumerable<MuxedStreamInfo> streamInfos) =>
            streamInfos.OrderByDescending(s => s.VideoQuality).FirstOrDefault();

19 Source : Extensions.cs
with MIT License
from arqueror

public static VideoStreamInfo WithHighestVideoQuality(this IEnumerable<VideoStreamInfo> streamInfos) =>
            streamInfos.OrderByDescending(s => s.VideoQuality).FirstOrDefault();

19 Source : Extensions.cs
with MIT License
from arqueror

public static AudioStreamInfo WithHighestBitrate(this IEnumerable<AudioStreamInfo> streamInfos) =>
            streamInfos.OrderByDescending(s => s.Bitrate).FirstOrDefault();

19 Source : Extensions.cs
with MIT License
from arqueror

public static VideoStreamInfo WithHighestBitrate(this IEnumerable<VideoStreamInfo> streamInfos) =>
            streamInfos.OrderByDescending(s => s.Bitrate).FirstOrDefault();

19 Source : CachingAccountRepository.cs
with MIT License
from ASF-Framework

public async Task<(IList<Account> Accounts, int TotalCount)> GetList(AccountListPagedRequestDto requestDto)
        {
            var list = await this.GetList();
            var queryable = list.Where(w => w.IsDeleted == requestDto.IsDeleted);
            if (!string.IsNullOrEmpty(requestDto.Vague))
            {
                queryable = queryable
                    .Where(w => w.Id.ToString() == requestDto.Vague
                    || w.Name.Contains(requestDto.Vague)
                    || w.Username.Contains(requestDto.Vague)
                    );
            }
            if (requestDto.Status == 1)
                queryable = queryable.Where(w => w.Status == AccountStatus.Normal);
            if (requestDto.Status == 2)
                queryable = queryable.Where(w => w.Status == AccountStatus.NotAllowedLogin);

            var result = queryable.OrderByDescending(p => p.CreateInfo.CreateTime);
            return (result.Skip((requestDto.SkipPage - 1) * requestDto.PagedCount).Take(requestDto.PagedCount).ToList(), result.Count());
        }

19 Source : TypesToMenu.cs
with MIT License
from ashblue

private static List<TypeEntry> GetTypeEntries () {
            var list = new List<TypeEntry>();
            foreach (var replacedembly in AppDomain.CurrentDomain.Getreplacedemblies()) {
                foreach (var type in replacedembly.GetTypes()) {
                    if (!type.IsSubclreplacedOf(typeof(T)) || type.IsAbstract) continue;
                    var attr = type.GetCustomAttribute<CreateMenuAttribute>();

                    list.Add(new TypeEntry {
                        type = type,
                        path = attr?.Path ?? type.FullName,
                        priority = attr?.Priority ?? 0,
                    });
                }
            }

            return list
                .OrderByDescending(t => t.priority)
                .ToList();
        }

19 Source : StatsContainerEditor.cs
with MIT License
from ashblue

void RebuildDisplay () {
			_definitions.Clear();

			List<StatDefinition> results;
			if (Target.collection == null) {
				results = StatDefinitionsCompiled.GetDefinitions(StatsSettings.Current.DefaultStats);
			} else {
				results = StatDefinitionsCompiled.GetDefinitions(Target.collection);
			}

			if (results == null) return;

			_definitions = results;
			_definitions = _definitions
				.OrderByDescending(d => d.SortIndex)
				.ThenBy(d => d.DisplayName)
				.ToList();

			Target.overrides.Clean();

			serializedObject.ApplyModifiedProperties();
		}

19 Source : HeightCalculator.cs
with MIT License
from AshleighAdams

private static async Task<(int height, TaggedVersion? version)> FromCommit(
			Commit commit,
			string commitDescriptor,
			FromCommitOptions options)
		{
			var visited = new HashSet<Commit>();
			var toVisit = new Stack<(Commit commit, int height, string descriptor, int heightSinceBranch)>();
			toVisit.Push((commit, 0, commitDescriptor, 0));

			var candidates = new List<(int height, TaggedVersion? version)>();

			while (toVisit.Count > 0)
			{
				var (current, height, rootDescriptor, heightSinceBranch) = toVisit.Pop();

				// Stryker disable all: used for logging only
				var descriptor = heightSinceBranch == 0 ? rootDescriptor : $"{rootDescriptor}~{heightSinceBranch}";
				// Stryker restore all

				// already visited in an ultimately prior parent
				if (!visited.Add(current))
				{
					options.Log?.Verbatim($"{descriptor} found in prior parent, discontinuing branch.");
					continue;
				}

				var currentTags = options.Tags.FindCommitTags(current);
				var versions = currentTags
					.Where(t => t.Name.StartsWith(options.TagPrefix, StringComparison.Ordinal))
					.SelectWhereSemver(options.TagPrefix, options.Log)
					.OrderByDescending(v => v.Version)
					.ToList();

				options.Log?.Verbatim($"{descriptor} has {currentTags.Count} total tags with {versions.Count} versions.");

				foreach (var tag in currentTags)
					options.Log?.Verbatim($"  found tag: {tag.Name}");

				List<TaggedVersion>? filteredVersions = null;
				foreach (var version in versions)
				{
					bool preplacedesFilter = options.TagFilter is null || await options.TagFilter.PreplacedesFilter(version);

					if (preplacedesFilter)
					{
						options.Log?.Verbatim($"  version candidate: {version.Version}");
						filteredVersions ??= new();
						filteredVersions.Add(version);
					}
					else
						options.Log?.Verbatim($"  version filtered: {version.Version} (from tag {version.Tag.Name})");
				}

				if (filteredVersions is not null)
				{
					var candidateVersion = filteredVersions[0];
					candidates.Add((height, candidateVersion));
					options.Log?.Verbose($"Candidate version {candidateVersion.Version} found with {height} height at {descriptor}.");
					continue;
				}

				var parents = await options.Repo.GetParents(current);

				if (parents.Count == 0)
				{
					int phantomCommitHeight = height + 1;
					candidates.Add((phantomCommitHeight, null));
				}
				else
				{
					// commits to visit must be added in the reverse order, so the earlier parents are visited first
					for (int i = parents.Count; i --> 0;)
					{
						var parent = parents[i];
						var parentHeight = height + 1;
						// Stryker disable all: used for logging only
						var isDiverging = i != 0;
						var parentDescriptor = isDiverging ? $"{descriptor}^{i + 1}" : rootDescriptor;
						var parentHeightSinceBranch = isDiverging ? 0 : heightSinceBranch + 1;
						// Stryker restore all

						toVisit.Push((parents[i], parentHeight, parentDescriptor, parentHeightSinceBranch));
					}
				}
			}

			Debug.replacedert(candidates.Count != 0);

			return candidates
				.OrderByDescending(x => x.version is not null)
				.ThenByDescending(x => x.version?.Version)
				.First();
		}

See More Examples