public void Select_Finds_FirstToSatisfyAllConstraints() { var mockery = new MockRepository(); var constraint1 = mockery.StrictMock<IResidentConstraint>(); var constraint2 = mockery.StrictMock<IResidentConstraint>(); var selector = new ResidentSelector(); selector.Constraints.Clear(); selector.Constraints.Add(constraint1); selector.Constraints.Add(constraint2); var residents = new List<Resident> { new Resident(), new Resident(), new Resident() }; var shift = new Shift(DateTime.Today, DateTime.Today, DateTime.Today); using (mockery.Record()) { SetupResult.For(constraint1.Assignable(residents.First(), shift)).Return(false); SetupResult.For(constraint2.Assignable(residents.First(), shift)).Return(true); SetupResult.For(constraint1.Assignable(residents.Skip(1).First(), shift)).Return(true); SetupResult.For(constraint2.Assignable(residents.Skip(1).First(), shift)).Return(false); SetupResult.For(constraint1.Assignable(residents.Skip(2).First(), shift)).Return(true); SetupResult.For(constraint2.Assignable(residents.Skip(2).First(), shift)).Return(true); } using (mockery.Playback()) { Assert.AreEqual(residents.Skip(2).First(), selector.Select(residents, shift)); } }
public static List<List<Tuple<Teams, Teams>>> ListMatches(List<Teams> listTeam) { var result = new List<List<Tuple<Teams, Teams>>>(); int numDays = (listTeam.Count - 1); int halfSize = listTeam.Count / 2; var teams = new List<Teams>(); teams.AddRange(listTeam.Skip(halfSize).Take(halfSize)); teams.AddRange(listTeam.Skip(1).Take(halfSize - 1).ToArray().Reverse()); int teamsSize = teams.Count; for (int day = 0; day < numDays; day++) { var round = new List<Tuple<Teams, Teams>>(); int teamIdx = day % teamsSize; round.Add(new Tuple<Teams, Teams>(teams[teamIdx], listTeam[0])); for (int idx = 1; idx < halfSize; idx++) { int firstTeam = (day + idx) % teamsSize; int secondTeam = (day + teamsSize - idx) % teamsSize; round.Add(new Tuple<Teams, Teams>(teams[firstTeam], teams[secondTeam])); } result.Add(round); } return result; }
/// <summary> /// Get the 10 newest posts in a specific category /// </summary> /// <param name="category">The category to search</param> /// <param name="pager">Skip in increments of 10</param> /// <returns></returns> public static IEnumerable <Post> GetTenPostsFromCategory(string category, int pager = 0) { var result = new List <Post>(); foreach (var post in _memoryCache) { //check for partial matches if (post?.Categories != null && post.Categories.Contains(category)) { //possible lead, check for full matches var thisPostCat = post.Categories.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (thisPostCat.Contains(category)) { //gotcha result.Add(post); //break out if we have enough if (result.Count >= (10 * (pager + 1))) { result.Sort((p1, p2) => p2.PostedTime.CompareTo(p1.PostedTime)); return(result?.Skip(pager * 10)?.Take(10)); } } } } //if we end up here there arent the full amount of results (so the break if never happened) result.Sort((p1, p2) => p2.PostedTime.CompareTo(p1.PostedTime)); return(result?.Skip(pager * 10)?.Take(10)); }
public Season CreateFirstSeason(Game game, List<Team> teams, IUnitOfWorkRepository repository) { // First check the number of teams can be evenly divided into the number of leagues. bool teamsOk = teams.Count % Constants.HowManyLeagues == 0; if (!teamsOk) { throw new Exception($"The number of teams must be divided by {Constants.HowManyLeagues}"); } var newSeasonInfo = new NewSeasonInfo { Game = game, SeasonNumber = 0 }; // Divide all teams between the four leagues based on the team rating. teams.Sort((team1, team2) => team2.Rating.CompareTo(team1.Rating)); int countTeamsPerLeague = teams.Count / Constants.HowManyLeagues; newSeasonInfo.TeamsLeague1 = teams.Take(countTeamsPerLeague).ToList(); newSeasonInfo.TeamsLeague2 = teams.Skip(countTeamsPerLeague).Take(countTeamsPerLeague).ToList(); newSeasonInfo.TeamsLeague3 = teams.Skip(countTeamsPerLeague * 2).Take(countTeamsPerLeague).ToList(); newSeasonInfo.TeamsLeague4 = teams.Skip(countTeamsPerLeague * 3).ToList(); // The teams have been sorted on rating, so given them an initial league table position. AssignInitialLeagueTablePosition(teams); // In the first season there are no champion and cup winner yet, so pick the two best teams. newSeasonInfo.NationalChampion = teams[0]; newSeasonInfo.NationalCupWinner = teams[1]; // Now all teams have been placed in the right leagues, so create match schedules for all competitions. var seasonAndCompetitionSchedules = CreateSeasonAndCompetitionSchedules(newSeasonInfo); // Insert the season and all competition schedules. var season = InsertSeasonAndCompetitionSchedule(repository, seasonAndCompetitionSchedules); return season; }
private void SortGlobalSections(List<Line> lines) { var begin = lines .Where(line => line.Content.Trim().StartsWith("GlobalSection(", StringComparison.OrdinalIgnoreCase)) .ToList(); var sections = begin.Select(line => new { Begin = line, Entries = lines.Skip(line.Index + 1) .TakeWhile(x => !x.Content.Trim().Equals("EndGlobalSection", StringComparison.OrdinalIgnoreCase)) .OrderBy(x => x.Content) .ToList(), End = lines.Skip(line.Index + 1) .First(x => x.Content.Trim().Equals("EndGlobalSection", StringComparison.OrdinalIgnoreCase)) }).ToList(); foreach (var section in sections) { lines.RemoveRange(section.Begin.Index + 1, section.Entries.Count); lines.InsertRange(section.Begin.Index + 1, section.Entries); } ResetIndexes(lines); }
private void ReceiveData(List<byte> data, IReadState readState, Action<FrameType, byte[]> processFrame) { while (data.Count >= 2) { bool isFinal = (data[0] & 128) != 0; var frameType = (FrameType)(data[0] & 15); int length = (data[1] & 127); var reservedBits = (data[0] & 112); if (reservedBits != 0) { return; } int index = 2; int payloadLength; if (length == 127) { if (data.Count < index + 8) return; //Not complete payloadLength = data.Skip(index).Take(8).ToArray().ToLittleEndianInt(); index += 8; } else if (length == 126) { if (data.Count < index + 2) return; //Not complete payloadLength = data.Skip(index).Take(2).ToArray().ToLittleEndianInt(); index += 2; } else { payloadLength = length; } if (data.Count < index + 4) return; //Not complete if (data.Count < index + payloadLength) return; //Not complete IEnumerable<byte> payload = data .Skip(index) .Take(payloadLength) .Select(b => b); readState.Data.AddRange(payload); data.RemoveRange(0, index + payloadLength); if (frameType != FrameType.Continuation) readState.FrameType = frameType; if (!isFinal || !readState.FrameType.HasValue) continue; byte[] stateData = readState.Data.ToArray(); FrameType? stateFrameType = readState.FrameType; readState.Clear(); processFrame(stateFrameType.Value, stateData); } }
public static void RunArgs (List<String> args) { if (args!=null && args.Count>0) { var x = args[0].ToUpper(); if (x=="XTCLI") { App.ExeType="CLI"; App.CommandClass="XT.App+CLI+Commands"; args=args.Skip(1).ToList(); } if (x=="XTGUI") { App.ExeType="GUI"; App.CommandClass="XT.App+GUI+Commands"; args=args.Skip(1).ToList(); } if (x=="XTSVC") { App.ExeType="SVC"; App.CommandClass="XT.App+SVC+Commands"; args=args.Skip(1).ToList(); } } //if (args[0].Contains(".Commands")) { App.CommandClass = args[0]; args = args.Skip(1).ToList(); } RunCommand(App.CommandClass,args); }
public PriceModel(List<double> deltas, double tailPercent) { this.tailPercent = tailPercent; // отсечь 0.2% + 0.2% результатов "справа" и "слева" как "хвосты" var tailCount = (int)(deltas.Count * this.tailPercent / 100); var bodyCount = deltas.Count - tailCount * 2; tailLeft = new ValueRange(deltas.Take(tailCount).ToArray(), StepsPerTail); body = new ValueRange(deltas.Skip(tailCount).Take(bodyCount).ToArray(), StepsPerBody); tailRight = new ValueRange(deltas.Skip(tailCount + bodyCount).ToArray(), StepsPerTail); }
/// <summary> /// Retorna uma lista de KeyValuePair, onde a chave são os valores de input e o seu valor correspondente são os valores de output /// </summary> /// <param name="dados"></param> /// <param name="janelaEntrada">tamanho do input</param> /// <param name="janelaSaida">tamanho do output</param> /// <param name="considerarSaidasComoEntradas">se verdadeiro, teremos 'dados.Count / janelaEntrada' registros como saida, caso contrario, 'dados.Count / (janelaEntrada + janelaSaida)' </param> /// <returns></returns> public static List<KeyValuePair<double[], double[]>> SelecionarCotacoesPorJanelamento(List<double> dados, int janelaEntrada, int janelaSaida, bool considerarSaidasComoEntradas) { /*Cria um mapeamento de entradas para saida com o janelamento informado*/ List<KeyValuePair<double[], double[]>> dadosPorJanelamento = new List<KeyValuePair<double[], double[]>>(); for (int i = 0; i < dados.Count - (janelaEntrada + janelaSaida); i += janelaEntrada + (considerarSaidasComoEntradas ? 0 : janelaSaida)) { dadosPorJanelamento.Add(new KeyValuePair<double[], double[]>(dados.Skip(i).Take(janelaEntrada).ToArray(), dados.Skip(i + janelaEntrada).Take(janelaSaida).ToArray())); } /*Cria um mapeamento de entradas para saida com o janelamento informado*/ return dadosPorJanelamento; }
public void Select_Finds_Resident_Associated_With_RotationShift_First() { var rotationShift = new RotationShift(BitwiseDayOfWeek.Monday | BitwiseDayOfWeek.Tuesday, TimeConstants.StartOfDay12HourDay, TimeConstants.EndOfDay12HourDay); var shifts = new ShiftFactory().Create(new List<RotationShift> { rotationShift }, new DateTime(2012, 12, 3), new DateTime(2012, 12, 4)).ToList(); var residents = new List<Resident> { new Resident(), new Resident() }; shifts.First().Resident = residents.Skip(1).First(); var selector = new ResidentSelector(); selector.Constraints.Clear(); Assert.AreEqual(residents.Skip(1).First(), selector.Select(residents, shifts.Skip(1).First())); }
public ActionResult SearchUsers(string searchText, int page = 1) { UsersViewModel vm = new UsersViewModel(); List<ApplicationUser> users = new List<ApplicationUser>(); if (searchText == null) { return View(); } if (searchText == "All") { users = UserManager.Users.ToList(); } else { users = UserManager.Users.Where(u => u.UserName.Contains(searchText) || u.Email.Contains(searchText)).ToList(); } PageInfo pageInfo = new PageInfo() { PageSize = 20, CurrentPage = 1 }; pageInfo.PageCount = (users.Count() - 1) / pageInfo.PageSize + 1; pageInfo.CurrentPage = page <= pageInfo.PageCount ? page : 1; pageInfo.Url = "/admin/adminaccount/searchUsers?searchText=" + searchText + "@page="; vm.Users = users.Skip((pageInfo.CurrentPage - 1) * pageInfo.PageSize).Take(pageInfo.PageSize).ToList(); vm.PageInfo = pageInfo; return View(vm); }
public OperationResult Parse(string arguments) { if (arguments == null) { return new OperationResult("default"); } var components = new List<CommandComponent>(); var tokens = arguments.Split((char[]) null, StringSplitOptions.RemoveEmptyEntries); int currentIndex = 0; foreach (var token in tokens) { currentIndex = arguments.IndexOf(token, currentIndex, StringComparison.Ordinal); components.Add(new CommandComponent(currentIndex, token)); } if (components.Count == 0) { return new OperationResult("default"); } if (components[0].Value.StartsWith("-")) { return operations["default"].Parse(components, "default", arguments); } if (!operations.ContainsKey(components[0].Value)) { return operations["default"].Parse(components, "default", arguments); } else { return operations[components[0].Value].Parse(components.Skip(1), components[0].Value, arguments); } }
private static void HandleLambda(HashSet<string> accessedVariables, HashSet<string> definedVariables, List<object> list) { List<object> parameters = (List<object>)list[1]; AssertAllFunctionParametersAreSymbols(parameters); foreach (var i in FindFreeVariablesInLambda(parameters.Select(i => i.ToString()), list.Skip(2), new HashSet<string>())) if (!definedVariables.Contains(i)) accessedVariables.Add(i); }
private bool ExecuteAddRemove(HaloTag tag, List<string> args) { if (args.Count < 3) return false; var dependencies = args.Skip(2).Select(a => ArgumentParser.ParseTagIndex(_cache, a)).ToList(); if (dependencies.Count == 0 || dependencies.Any(d => d == null)) return false; if (args[0] == "add") { foreach (var dependency in dependencies) { if (tag.Dependencies.Add(dependency.Index)) Console.WriteLine("Added dependency on tag {0:X8}.", dependency.Index); else Console.Error.WriteLine("Tag {0:X8} already depends on tag {1:X8}.", tag.Index, dependency.Index); } } else { foreach (var dependency in dependencies) { if (tag.Dependencies.Remove(dependency.Index)) Console.WriteLine("Removed dependency on tag {0:X8}.", dependency.Index); else Console.Error.WriteLine("Tag {0:X8} does not depend on tag {1:X8}.", tag.Index, dependency.Index); } } using (var stream = _fileInfo.Open(FileMode.Open, FileAccess.ReadWrite)) _cache.UpdateTag(stream, tag); return true; }
private const double RATIO = 0.5; // The probability that a prisoner's value is true #endregion Fields #region Methods // Don't change any code beyond this line. This is the bookkeeping of the simulation. public static void Main(string[] args) { var random = new Random(); var prisoners = new List<bool>(Enumerable.Range(0, N).Select(i => random.NextDouble() < RATIO)); var ahead = new List<bool>(prisoners); var dead = new List<bool>(); var declared = new List<bool>(); var numDead = 0; // The game loop for (int i = 0; i < N; i++) { ahead.RemoveAt(0); bool declaration = PrisonerAction(i, dead, declared, ahead); declared.Add(declaration); dead.Add(declaration != prisoners[i]); if (declaration != prisoners[i]) { numDead++; } } Console.WriteLine("Out of {0} prisoners, you killed {1}.", N, numDead); if (numDead > 1 || dead.Skip(1).Count(d => d) != 0) { Console.WriteLine("You can do better than that!"); } else { Console.WriteLine("Great job! You found the right algorithm!"); } Console.ReadKey(); }
private IEnumerable<int[]> Chop(List<int> list) { for (int i = 0; i < list.Count - 4; i++) { yield return list.Skip(i).Take(4).ToArray(); } }
public ActionResult LoadUserGrid(string ColumnName = "none") { var Users = _db.User.ToList(); var registrationViewModelObjList = new List <RegistrationViewModel>(); foreach (var usr in Users) { var registrationViewModelObj = new RegistrationForm.ViewModels.RegistrationViewModel(); registrationViewModelObj = new RegistrationForm.ViewModels.RegistrationViewModel(); registrationViewModelObj.Countries = new SelectList(GetAllCountries(usr.CountryId), "Id", "CountryName"); registrationViewModelObj.States = new SelectList(GetAllStates().Where(s => s.Id == usr.StateId).ToList(), "Id", "StateName"); registrationViewModelObj.Skills = _db.Skill.ToList(); registrationViewModelObj.User = usr; registrationViewModelObj.User.DOB = DateTime.Now; var Img = _db.Image.FirstOrDefault(img => img.UserId == usr.Id).ImageName; registrationViewModelObj.ImageFilePath = Img; registrationViewModelObjList.Add(registrationViewModelObj); } // return View(ShortListBasedOnColumn(registrationViewModelObjList, ColumnName)); numberOdUsers = registrationViewModelObjList.Count(); noOfPages = (double)Math.Round((decimal)registrationViewModelObjList.Count() / 5); ViewBag.noOfPages = noOfPages + 1; registrationViewModelObjList[0].noOfPages = noOfPages + 1; userList = registrationViewModelObjList; int skip = Convert.ToInt32(ViewBag.skippedRecords); registrationViewModelObjList = registrationViewModelObjList?.Skip(skip).Take(5).ToList(); return(View(registrationViewModelObjList)); }
public override Widget build(BuildContext context) { return(new Wrap( runSpacing: 8f, children: _breadcrumbs? .Skip(1) // Maybe the first one is not so reasonable to display on the page? .Select <Breadcrumb, Widget>( breadcrumb => new ClickableText( text: breadcrumb.content, normalStyle: _normalBreadcrumbStyle, hoverStyle: _hoverBreadCrumbStyle, onTap: () => LocationUtil.Go($"/Manual/{breadcrumb.link}") ) ).SelectMany <Widget, Widget>((widget, i) => { if (i == 0) { return new[] { widget }; } return new[] { new Container( margin: EdgeInsets.symmetric(horizontal: 8f), child: new Text( _splitter, style: _splitterStyle ) ), widget, }; }).ToList() )); }
public string GetDebugView() { var matchers = new List<IMatcherTreeNode>(); var parent = this.Parent; while (!(parent is MethodInfoMatcherTreeNode)) { matchers.Add(parent); parent = parent.Parent; } matchers.Reverse(); var method = ((MethodInfoMatcherTreeNode)parent).MethodInfo; var sb = new StringBuilder(); bool isInstance = !method.IsStatic || method.IsExtensionMethod(); var argMatchers = isInstance ? matchers.Skip(1) : matchers; if (isInstance) sb.AppendFormat("({0}).", matchers[0].Matcher.DebugView); else sb.AppendFormat("{0}.", method.DeclaringType); sb.AppendFormat("{0}({1}) called {2} time{3}; (signature: {4})", method.Name, ", ".Join(argMatchers.Select(m => m.Matcher.DebugView)), this.Calls, this.Calls != 1 ? "s" : "", method); return sb.ToString(); }
public List <OrderInfo> SearchOrder(SearchCriteria searchCriteria) { var dataToSend = new List <OrderInfo>(); int page = 0; int pageSize = 20; if (searchCriteria?.IsValid() ?? false) { //var data = GetJsondata(); StreamReader streamReader = new StreamReader(Server.MapPath("~/Data/OrderInfo.json")); string readData = streamReader.ReadToEnd(); var dataSet = JsonConvert.DeserializeObject <List <OrderInfo> >(readData); if (dataSet.Count() > 0) { var pageData = new List <OrderInfo>(); if (searchCriteria?.CompletionDte != null) { if (searchCriteria?.OrderId != null) { pageData = dataSet.Where(x => x.OrderId == searchCriteria.OrderId && x.CompletionDte.Value.Date == searchCriteria.CompletionDte.Value.Date)?.ToList(); } else if (searchCriteria?.MSA != null && searchCriteria?.Status != null) { pageData = dataSet.Where(x => x.MSA == searchCriteria.MSA && x.Status == searchCriteria.Status && x.CompletionDte.Value.Date == searchCriteria.CompletionDte.Value.Date)?.ToList(); } } if (pageData?.Count() > 0) { dataToSend = pageData?.Skip(page * pageSize).Take(pageSize).ToList(); } } } return(dataToSend); }
private IDictionary<string, ITriangle> BuildTriangles(List<string[]> csvRows) { //could potentially read header row to cope with columns changing order. will keep it simple for now var dataRows = csvRows.Skip(1); var triangleDictionary = new Dictionary<string, ITriangle>(); var dataGroups = dataRows.GroupBy(row => row[0]).ToArray(); foreach (var dataGroup in dataGroups) { var triangleDatapoints = new List<TriangleDataPoint>(); foreach (var row in dataGroup) { try { int originYear = int.Parse(row[1]); int developmentYear = int.Parse(row[2]); double value = double.Parse(row[3]); triangleDatapoints.Add(new TriangleDataPoint(originYear, developmentYear, value)); } catch (FormatException e) { throw new FormatException("Row bad format: " + row[0] + ", " + row[1] + ", " + row[2] + ", " + row[3], e); } } var triangleName = dataGroup.Key; triangleDictionary.Add(triangleName, new Triangle(triangleName, triangleDatapoints)); } return triangleDictionary; }
public void Write(Storage storage, string fileSpecificPath, string fileWordsPath) { var bitmap = new List<byte>(); var words = GenerateWordsStringAndBitmap(bitmap, storage); if (words == null || words == "") return; var bytemap = new List<byte>(); while (bitmap.Count > 0) { var oneByte = bitmap.Take(8).ToList(); bitmap = bitmap.Skip(8).ToList(); bytemap.Add(oneByte.Aggregate((byte)0, (result, bit) => (byte)((result << 1) | bit))); } using (var streamWriter = new StreamWriter(fileWordsPath)) { streamWriter.Write(words); } using (var fileStream = new FileStream(fileSpecificPath, FileMode.OpenOrCreate)) { fileStream.Write(bytemap.ToArray(), 0, bytemap.Count); fileStream.Close(); } }
public static iDeviceError GetDeviceList(out List<IDevice> deviceList) { List<IDevice> devices = new List<IDevice>(); IntPtr devicesPtr; iDeviceError returnCode = SearchForDevices(out devices, out devicesPtr); devices = devices.Where(x => devices.Skip(devices.IndexOf(x) + 1).Count(y => y.Udid == x.Udid) == 0).ToList(); deviceList = new List<IDevice>(); foreach (IDevice currDevice in devices) { IntPtr lockdownService; IntPtr lockdownClient; Lockdown.LockdownError lockdownReturnCode = Lockdown.Start(currDevice.Handle, out lockdownClient, out lockdownService); XDocument deviceProperties; lockdownReturnCode = Lockdown.GetProperties(lockdownClient, out deviceProperties); IEnumerable<XElement> keys = deviceProperties.Descendants("dict").Descendants("key"); deviceList.Add(new IDevice( IntPtr.Zero, keys.Where(x => x.Value == "UniqueDeviceID").Select(x => (x.NextNode as XElement).Value).FirstOrDefault(), keys.Where(x => x.Value == "SerialNumber").Select(x => (x.NextNode as XElement).Value).FirstOrDefault(), keys.Where(x => x.Value == "DeviceName").Select(x => (x.NextNode as XElement).Value).FirstOrDefault(), keys.Where(x => x.Value == "ProductType").Select(x => (x.NextNode as XElement).Value).FirstOrDefault() )); // Freeing lockdownReturnCode = Lockdown.FreeService(lockdownService); lockdownReturnCode = Lockdown.FreeClient(lockdownClient); returnCode = FreeDevice(currDevice.Handle); } return returnCode; }
private static string Solve(string[] words) { string prefix = string.Empty; List sorted = new List(words); while (true) { sorted = sorted.OrderBy(x => x).ToList(); if (sorted.Count == 0) break; string pr = sorted.First(); string sf = sorted.Skip(1) .Where(a => a.StartsWith(pr)) .Select(s => s.Substring(pr.Length)) .Where(s => !string.IsNullOrEmpty(s)) .OrderBy(x => x + pr) .FirstOrDefault(); if (string.Compare(pr + pr, pr + sf) < 0) sf = null; prefix += pr + sf; sorted.Remove(pr + sf); } return prefix; }
// This method will recompute the Bound without precondition. It will not cascade upwards to parent nodes, because // it is intended to be called recursively. public void BottomUpRecalculateBound() { List<BoundingBox> childBounds = new List<BoundingBox>(); foreach (SceneNode child in mChildren) { ImplicitBoundingBoxNode implicitBVChild = child as ImplicitBoundingBoxNode; if (implicitBVChild != null) { implicitBVChild.BottomUpRecalculateBound(); childBounds.Add(implicitBVChild.Bound); } else { childBounds.AddRange(child.FindExplicitBoundingVolumes()); } } BoundingBox combinedBound = childBounds.First(); foreach (BoundingBox childBox in childBounds.Skip(1)) { combinedBound = BoundingBox.CreateMerged(combinedBound, childBox); } Bound = combinedBound; }
public static String GetPath(this XmlNode target) { List<KeyValuePair<String, Int32?>> path = new List<KeyValuePair<String, Int32?>> { }; while (target.ParentNode != null) { var siblings = target.ParentNode.SelectNodes(target.Name); if (siblings.Count > 1) { var siblingIndex = 0; foreach (var sibling in siblings) { if (sibling == target) { path.Add(new KeyValuePair<String, Int32?>(target.ParentNode.Name, siblingIndex)); } siblingIndex++; } } else { path.Add(new KeyValuePair<String, Int32?>(target.ParentNode.Name, null)); } target = target.ParentNode; } path.Reverse(); return String.Join(".", path.Skip(3).Select(p => p.Value.HasValue ? String.Format("{0}[{1}]", p.Key, p.Value) : p.Key)); }
private List<Song> QuickSort(List<Song> collection) { if (collection.Count == 1) { return collection; } if (collection.Count != 1) { int key = collection.Count/2; List<Song> result = new List<Song>(); result.Add(collection[key]); for (int i = 0; i < collection.Count(); i++) { if (collection[i].CompareTo(collection[key]) == -1) { result.Insert(0, collection[i]); } if (collection[i].CompareTo(collection[key]) == 1) { result.Add(collection[i]); } if (key == i) continue; } List<Song> Left = QuickSort(result.Take(key).ToList()); List<Song> Right = QuickSort(result.Skip(key).ToList()); result = Left.Union(Right).ToList(); return result; } return collection; }
public void EigenUpdateWithoutUpdateURL() { string dir; string outDir; using (Utility.WithTempDirectory(out outDir)) using (IntegrationTestHelper.WithFakeInstallDirectory(out dir)) { var di = new DirectoryInfo(dir); var progress = new Subject<int>(); var bundledRelease = ReleaseEntry.GenerateFromFile(di.GetFiles("*.nupkg").First().FullName); var fixture = new InstallManager(bundledRelease, outDir); var pkg = new ZipPackage(Path.Combine(dir, "SampleUpdatingApp.1.1.0.0.nupkg")); var progressValues = new List<int>(); progress.Subscribe(progressValues.Add); fixture.ExecuteInstall(dir, pkg, progress).Wait(); var filesToLookFor = new[] { "SampleUpdatingApp\\app-1.1.0.0\\SampleUpdatingApp.exe", "SampleUpdatingApp\\packages\\RELEASES", "SampleUpdatingApp\\packages\\SampleUpdatingApp.1.1.0.0.nupkg", }; filesToLookFor.ForEach(f => Assert.True(File.Exists(Path.Combine(outDir, f)), "Could not find file: " + f)); // Progress should be monotonically increasing progressValues.Count.ShouldBeGreaterThan(2); progressValues.Zip(progressValues.Skip(1), (prev, cur) => cur - prev).All(x => x > 0).ShouldBeTrue(); } }
public static string BytesToStringDescription(List<byte> bytes) { bytes = bytes.Skip(8).Take(32).ToList(); var encoding = Encoding.GetEncoding(1251); string result = encoding.GetString(bytes.ToArray()).TrimEnd(); return result; }
private static string GetReplacementIL(List<byte> bytes) { int index = 2; int length = ReadPackedLen(bytes, ref index); return Encoding.UTF8.GetString(bytes.Skip(index).Take(length).ToArray()); }
public CertificateValidationResult Validate(Certificate certificate) { if (certificate == null) throw new ArgumentNullException("certificate"); try { var x509Certs = new List<X509Certificate>(); x509Certs.AddRange(_chain.Select(c => c.BouncyX509Certificate)); x509Certs.Add(certificate.BouncyX509Certificate); IX509Store x509CertStore = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(x509Certs)); var x509Certificates = x509Certs.Skip(1).ToList(); var certPath = new PkixCertPath(x509Certificates); ISet trust = new HashSet { new TrustAnchor(x509Certs.First(), null) }; var certPathValidator = new PkixCertPathValidator(); var paramsPkix = new PkixParameters(trust); paramsPkix.AddStore(x509CertStore); paramsPkix.IsRevocationEnabled = false; var pkixResult = certPathValidator.Validate(certPath, paramsPkix); return new CertificateValidationResult(pkixResult); } catch (Exception e) { return new CertificateValidationResult(e); } }
public static InitializerPath FromResolveResult(ResolveResult resolveResult) { InitializerPath initializerPath = null; var memberPath = new List<IMember>(); var currentResolveResult = resolveResult; do { if (currentResolveResult is MemberResolveResult) { var memberResolveResult = (MemberResolveResult)currentResolveResult; memberPath.Add(memberResolveResult.Member); currentResolveResult = memberResolveResult.TargetResult; } else if (currentResolveResult is LocalResolveResult) { var localResolveResult = (LocalResolveResult)currentResolveResult; memberPath.Reverse(); initializerPath = new InitializerPath(localResolveResult.Variable) { MemberPath = memberPath }; break; } else if (currentResolveResult is ThisResolveResult) { break; } else { return null; } } while (currentResolveResult != null); if (initializerPath == null) { // This path is rooted at a member memberPath.Reverse(); initializerPath = new InitializerPath(memberPath [0]) { MemberPath = memberPath.Skip(1).ToList() }; } return initializerPath; }
public Statistics(IEnumerable<double> values) { list = values.ToList(); N = list.Count; if (N == 0) throw new InvalidOperationException("StatSummary: Sequence contains no elements"); list.Sort(); if (N == 1) Q1 = Median = Q3 = list[0]; else { Func<IList<double>, double> getMedian = x => x.Count % 2 == 0 ? (x[x.Count / 2 - 1] + x[x.Count / 2]) / 2 : x[x.Count / 2]; Median = getMedian(list); Q1 = getMedian(list.Take(N / 2).ToList()); Q3 = getMedian(list.Skip((N + 1) / 2).ToList()); } Min = list.First(); Mean = list.Average(); Max = list.Last(); InterquartileRange = Q3 - Q1; LowerFence = Q1 - 1.5 * InterquartileRange; UpperFence = Q3 + 1.5 * InterquartileRange; Outliers = list.Where(IsOutlier).ToArray(); StandardDeviation = N == 1 ? 0 : Math.Sqrt(list.Sum(d => Math.Pow(d - Mean, 2)) / (N - 1)); StandardError = StandardDeviation / Math.Sqrt(N); ConfidenceInterval = new ConfidenceInterval(Mean, StandardError); Percentiles = new PercentileValues(list); }
public static List<FortData> Optimize(FortData[] pokeStops, LatLong latlng, GMapOverlay routeOverlay) { List<FortData> optimizedRoute = new List<FortData>(pokeStops); // NN FortData NN = FindNN(optimizedRoute, latlng.Latitude, latlng.Longitude); optimizedRoute.Remove(NN); optimizedRoute.Insert(0, NN); for (int i = 1; i < pokeStops.Length; i++) { NN = FindNN(optimizedRoute.Skip(i), NN.Latitude, NN.Longitude); optimizedRoute.Remove(NN); optimizedRoute.Insert(i, NN); Visualize(optimizedRoute, routeOverlay); } // 2-Opt bool isOptimized; do { optimizedRoute = Optimize2Opt(optimizedRoute, out isOptimized); Visualize(optimizedRoute, routeOverlay); } while (isOptimized); return optimizedRoute; }
public List <PlayerHeldItem> Fetch() { var remaining = Remaining; var batch = _items?.Skip(_skip).Take(remaining); this._skip += remaining; return(batch?.ToList() ?? new List <PlayerHeldItem>()); }
/// <summary> /// list转换pageList /// </summary> /// <param name="T"></typeparam> /// <param name="allList">需要分页的数据</param> /// <returns></returns> private PageList <T> ConvertPageList <T>(List <T> allList, int pageIndex, int pageSize) { pageIndex = pageIndex <= 0 ? 1 : pageIndex; pageSize = pageSize <= 0 ? 10 : pageSize; int skip = (pageIndex - 1) * pageSize; var list = allList?.Skip(skip).Take(pageSize).ToList(); return(new PageList <T>(list, pageIndex, pageSize, allList == null ? 0 : allList.LongCount())); }
/// <summary> /// list转换pageList /// </summary> /// <typeparam name="T"></typeparam> /// <param name="allList">需要分页的数据</param> /// <returns></returns> private PageList <T> ConvertPageList <T>(List <T> allList, int pageIndex, int pageSize) { pageIndex = pageIndex <= 0 ? 1 : pageIndex; pageSize = pageSize <= 0 ? 10 : pageSize; int skip = (pageIndex - 1) * pageSize; var list = allList?.Skip(skip).Take(pageSize).ToList(); List <string> operateList = Get_UserOperateList((long)Client.LoginUser.OperateFlag); return(new PageList <T>(list, pageIndex, pageSize, allList == null ? 0 : allList.LongCount(), operateList)); }
/// <summary> /// list转换pageList /// </summary> /// <typeparam name="T"></typeparam> /// <param name="allList">需要分页的数据</param> /// <returns></returns> private PageList <T> ConvertPageList <T>(List <T> allList, int pageIndex, int pageSize) { using (MiniProfilerLog.Step("转化为列表page方法 ConvertPageList")) { pageIndex = pageIndex <= 0 ? 1 : pageIndex; pageSize = pageSize <= 0 ? 10 : pageSize; int skip = (pageIndex - 1) * pageSize; var list = allList?.Skip(skip).Take(pageSize).ToList(); return(new PageList <T>(list, pageIndex, pageSize, allList == null ? 0 : allList.LongCount())); } }
/// /////////////////////////////////////////////////////////////////////// /// ReadRow /// <summary> /// </summary> /// <param name="row"> /// Contains the values in the current row, in the order in which they /// appear in the file. /// </param> /// <returns> /// True if a row was returned in parameter "row". /// False if no row returned. In that case, you're at the end of the file. /// </returns> public bool ReadRow(IDataRow row, List <int> charactersLength = null) { row.Clear(); var i = 0; while (true) { // Number of the line where the item starts. Note that an item // can span multiple lines. var startingLineNbr = m_lineNbr; string item = null; var itemLength = charactersLength?.Skip(i).First(); var moreAvailable = GetNextItem(ref item, itemLength); if (charactersLength != null) { if (!(charactersLength.Count() > i + 1)) { if (moreAvailable) { row.Add(new DataRowItem(item, startingLineNbr)); } if (!EOL) { AdvanceToEndOfLine(); moreAvailable = false; } } } if (!moreAvailable) { return(row.Count > 0); } row.Add(new DataRowItem(item, startingLineNbr)); i++; } }
public async Task <IList <Comment> > GetCommentsWithFilters(int productId, FilterModel filter) { List <Comment> result = null; if (filter.ByDateAscending) { result = await _context.Comments.AsNoTracking().Where(p => p.ProductId == productId).OrderBy(p => p.DateOfAdding).ToListAsync(); } else if (filter.ByDateDescending) { result = await _context.Comments.AsNoTracking().Where(p => p.ProductId == productId).OrderByDescending(p => p.AmountOfLikes).ToListAsync(); } else if (filter.IsMostPopular) { result = await _context.Comments.Where(p => p.ProductId == productId).OrderBy(p => p.AmountOfLikes).ToListAsync(); } return(result?.Skip((filter.Page - 1) * filter.Size).Take(filter.Size).ToList()); }
private async Task ProcessBatchJob(CancellationToken token, List <JobDetail> jobsBuffer, Job job) { do { var jobsInBatch = 0; foreach (var jobToRun in jobsBuffer.Take(MaxBatchSize)) { await JobDetailUpdateAsync(token, jobToRun); jobsInBatch++; } job.Completed += jobsInBatch; await _jobRepository.UpdateJobAsync(job); jobsBuffer = jobsBuffer?.Skip(MaxBatchSize)?.ToList(); }while (jobsBuffer != null && jobsBuffer.Any()); }
public ActionResult OrderBy(string ColumnName, string sortOrder) { ViewBag.shortedColumByOrder = sortOrder; if (sortOrder.Substring(sortOrder.IndexOf("_") + 1) == "UP") { ViewBag.shortOrder = "DOWN"; } else { ViewBag.shortOrder = "UP"; } LoadUserGrid(ColumnName); int skip = Convert.ToInt32(ViewBag.skippedRecords); userList = userList?.Skip(skip).Take(5).ToList(); return(View("LoadUserGrid", ShortListBasedOnColumn(userList, sortOrder, ViewBag.shortOrder))); }
private static object Subtotal(List <Expression> p) { // Skip cells that already evaluate a SUBTOTAL bool hasSubtotalInFormula(Expression e) { if (e is FunctionExpression fe && (fe.FunctionDefinition.Function.Method.Name == nameof(Subtotal) || fe.Parameters.Any(fp => hasSubtotalInFormula(fp)))) { return(true); } if (e is BinaryExpression be) { return(hasSubtotalInFormula(be.LeftExpression) || hasSubtotalInFormula(be.RightExpression)); } if (e is UnaryExpression ue) { return(hasSubtotalInFormula(ue.Expression)); } return(false); }; IEnumerable <Expression> extractExpressionsWithoutSubtotal(CellRangeReference crr) { var ce = crr.CalcEngine as XLCalcEngine; return(crr.Range .CellsUsed() .Where(c => { if (c.HasFormula) { var expression = ce.ExpressionCache[c.FormulaA1]; return !hasSubtotalInFormula(expression); } else { return true; } }) .Select(c => new XObjectExpression(new CellRangeReference(c.AsRange(), (XLCalcEngine)crr.CalcEngine)) as Expression)); }; var expressions = p.Skip(1) .SelectMany(e => e is XObjectExpression xoe && xoe.Value is CellRangeReference crr ? extractExpressionsWithoutSubtotal(crr) : new[] { e }) .ToArray(); var fId = (int)(Double)p[0]; var tally = new Tally(expressions); switch (fId) { case 1: return(tally.Average()); case 2: return(tally.Count(true)); case 3: return(tally.Count(false)); case 4: return(tally.Max()); case 5: return(tally.Min()); case 6: return(tally.Product()); case 7: return(tally.Std()); case 8: return(tally.StdP()); case 9: return(tally.Sum()); case 10: return(tally.Var()); case 11: return(tally.VarP()); default: throw new ArgumentException("Function not supported."); } }
private void PopulateList() { List <Task> taskCeption = new List <Task>(); List <ListOfFoldersFromThread> FolderList = new List <ListOfFoldersFromThread>(); List <string> Directories = null; foreach (var dir in SourceList) { DirectoryName = dir; if (chkMultiThread.Checked) { Directories = Directory.GetDirectories(dir).ToList(); double DirectoriesCount = 0; double DivisionNumber = 20.0; //////////////////////////This needs to be changed if (Directories.Count() < 20) { DirectoriesCount = Directories.Count(); DivisionNumber = 1; } if (Directories.Count() > 60) { DirectoriesCount = (Directories.Count() / DivisionNumber) + .5; DirectoriesCount = Math.Round(DirectoriesCount); } taskCeption.Add(Task.Factory.StartNew(() => FolderList.Add(new ListOfFoldersFromThread() { Folders = new List <Folder> { new Folder() { FolderName = dir, Files = Directory.GetFiles(dir).ToList() } } }))); Task.WaitAll(taskCeption.ToArray()); for (int i = 1; i < DirectoriesCount; i++) { FolderList.Add(new ListOfFoldersFromThread() { Folders = new List <Folder>() }); } int IncrementThreads = 0; for (int i = 0; i < DirectoriesCount; i++) { var w = Directories.Skip((int)DivisionNumber * i).Take((int)DivisionNumber).ToList(); taskCeption.Add(Task.Factory.StartNew(() => BreakUpSearch(w, IncrementThreads++, FolderList))); } Task.WaitAll(taskCeption.ToArray()); } else { List <string> ShortNamesFileList = new List <string>(); if (chkHidePath.Checked) { foreach (var item in Directory.EnumerateDirectories(dir)) { ShortNamesFileList.Add(item.Substring(item.LastIndexOf("\\") + 1)); } FolderList[0].Folders = new List <Folder>() { new Folder() { FolderName = dir, Files = ShortNamesFileList } }; } else { foreach (var item in Directory.EnumerateDirectories(dir)) { FolderList[0].Folders = new List <Folder>() { new Folder() { FolderName = item, Files = null } } } ; } } } lstBoxFileList.Invoke(new MethodInvoker(delegate { var lstBoxFileListDataSource = PrintList(FolderList).GroupBy(x => x).Select(y => y.First()).OrderBy(x => x).ToList(); lstBoxFileListDataSource.Add(lstBoxFileListDataSource.Count() + ""); lstBoxFileList.DataSource = lstBoxFileListDataSource; })); }
/// <summary> /// Returns a list of the names of recognized audio devices. /// </summary> /// <remarks> /// The No Sound device that is in the list of Audio Devices that are stored internally is not returned. /// Regarding the .Skip(1) as implementation for removing "No Sound", see http://bass.radio42.com/help/html/e5a666b4-1bdd-d1cb-555e-ce041997d52f.htm. /// </remarks> /// <returns>A list of the names of recognized audio devices.</returns> private IEnumerable <string> getDeviceNames(List <DeviceInfo> devices) => devices.Skip(1).Select(d => d.Name);
public static Blueprint Generate(VideoMemoryConfiguration configuration, List <bool[, ]> frames = null) { var width = configuration.Width ?? 32; var height = configuration.Height ?? 2; var baseAddress = configuration.BaseAddress ?? 1; var frameHeight = frames?.ElementAtOrDefault(0)?.GetLength(0) ?? 0; const int framesPerRow = 32; const int maxFilters = 20; var entities = new List <Entity>(); var memoryRows = new MemoryRow[height]; var metadata = new Entity { Name = ItemNames.ConstantCombinator, Position = new Position { X = 2, Y = 0 }, Direction = Direction.Down, Control_behavior = new ControlBehavior { Filters = new List <Filter> { Filter.Create(VirtualSignalNames.LetterOrDigit('Z'), frames?.Count ?? 0) } } }; entities.Add(metadata); for (var row = 0; row < height; row++) { var cellY = row * 9 - (row % 2 == 1 ? 1 : 0) + 2; var rowFrames = frames?.Skip(row * framesPerRow).Take(framesPerRow).ToList(); var addressMatcher = new Entity { Name = ItemNames.DeciderCombinator, Position = new Position { X = 1, Y = cellY + 0.5 }, Direction = Direction.Down, Control_behavior = new ControlBehavior { Decider_conditions = new DeciderConditions { First_signal = SignalID.Create(VirtualSignalNames.Info), Constant = row + baseAddress, Comparator = Comparators.IsNotEqual, Output_signal = SignalID.Create(VirtualSignalNames.Check), Copy_count_from_input = false } } }; entities.Add(addressMatcher); var memoryCells = new MemoryCell[width]; for (var column = 0; column < width; column++) { var cellX = column + 2; var enabler = new Entity { Name = ItemNames.DeciderCombinator, Position = new Position { X = cellX, Y = cellY + 0.5 }, Direction = Direction.Up, Control_behavior = new ControlBehavior { Decider_conditions = new DeciderConditions { First_signal = SignalID.Create(VirtualSignalNames.Check), Constant = 0, Comparator = Comparators.IsEqual, Output_signal = SignalID.Create(VirtualSignalNames.Everything), Copy_count_from_input = true } } }; entities.Add(enabler); var pixelFilters = Enumerable.Range(0, frameHeight) .Select(frameRow => { var pixel = rowFrames .Select((frame, frameOffset) => frame[frameRow, column] ? 1 << frameOffset : 0) .Sum(); return(Filter.Create(ScreenUtil.PixelSignals[frameRow], pixel)); }) .Where(pixelFilter => pixelFilter.Count != 0) .ToList(); var subCellCount = column % 18 >= 16 ? 6 : 7; var subCells = new Entity[subCellCount]; for (var subCellIndex = 0; subCellIndex < subCellCount; subCellIndex++) { var subCell = new Entity { Name = ItemNames.ConstantCombinator, Position = new Position { X = cellX, Y = subCellIndex < 6 || row % 2 == 1 ? cellY + subCellIndex + 2 : cellY - 1 }, Direction = Direction.Down, Control_behavior = new ControlBehavior { Filters = pixelFilters.Skip(subCellIndex * maxFilters).Take(maxFilters).ToList() } }; entities.Add(subCell); subCells[subCellIndex] = subCell; } memoryCells[column] = new MemoryCell { Enabler = enabler, SubCells = subCells }; } memoryRows[row] = new MemoryRow { AddressMatcher = addressMatcher, Cells = memoryCells }; } BlueprintUtil.PopulateEntityNumbers(entities); var substationWidth = (width + 9) / 18 + 1; var substationHeight = height / 2 + 1; entities.AddRange(CreateSubstations(substationWidth, substationHeight, 0, 0, entities.Count + 1)); for (var row = 0; row < height; row++) { var memoryRow = memoryRows[row]; AddConnection(CircuitColor.Red, memoryRow.AddressMatcher, CircuitId.Output, memoryRow.Cells[0].Enabler, CircuitId.Input); var adjacentRow = row - 1; if (adjacentRow >= 0) { var adjacentMemoryRow = memoryRows[adjacentRow]; AddConnection(CircuitColor.Green, memoryRow.AddressMatcher, CircuitId.Input, adjacentMemoryRow.AddressMatcher, CircuitId.Input); for (var column = 0; column < width; column++) { var memoryCell = memoryRow.Cells[column]; var adjacentMemoryCell = adjacentMemoryRow.Cells[column]; AddConnection(CircuitColor.Green, memoryCell.Enabler, CircuitId.Output, adjacentMemoryCell.Enabler, CircuitId.Output); } } for (var column = 0; column < width; column++) { var memoryCell = memoryRow.Cells[column]; AddConnection(CircuitColor.Green, memoryCell.SubCells[0], null, memoryCell.Enabler, CircuitId.Input); for (var subCellIndex = 1; subCellIndex < memoryCell.SubCells.Length; subCellIndex++) { var subCell = memoryCell.SubCells[subCellIndex]; var adjacentSubCell = memoryCell.SubCells[subCellIndex < 6 || row % 2 == 1 ? subCellIndex - 1 : 0]; AddConnection(CircuitColor.Green, subCell, null, adjacentSubCell, null); } var adjacentColumn = column - 1; if (adjacentColumn >= 0) { var adjacentMemoryCell = memoryRow.Cells[adjacentColumn]; AddConnection(CircuitColor.Red, memoryCell.Enabler, CircuitId.Input, adjacentMemoryCell.Enabler, CircuitId.Input); } } } return(new Blueprint { Label = $"Video ROM", Icons = new List <Icon> { Icon.Create(ItemNames.Lamp), Icon.Create(ItemNames.ConstantCombinator) }, Entities = entities, Item = ItemNames.Blueprint, Version = BlueprintVersions.CurrentVersion }); }
static void Main(string[] args) { List <string> input = Console.ReadLine().Split(new string[] { ": ", ", " }, StringSplitOptions.RemoveEmptyEntries).Distinct().ToList(); string name = input[0]; List <string> cards = input.Skip(1).ToList(); Dictionary <string, List <string> > players = new Dictionary <string, List <string> >(); int sum = 0; while (name != "JOKER") { if (players.ContainsKey(name) == false) { players.Add(name, cards); } else { players[name].AddRange(cards); } input = Console.ReadLine().Split(new string[] { ": ", ", " }, StringSplitOptions.RemoveEmptyEntries).Distinct().ToList(); name = input[0]; cards = input.Skip(1).ToList(); } int multiplyer = 0; int value = 0; foreach (var player in players) { foreach (var card in player.Value) { switch (card[card.Length - 1]) { case 'S': multiplyer = 4; break; case 'H': multiplyer = 3; break; case 'D': multiplyer = 2; break; case 'C': multiplyer = 1; break; } switch (card[0]) { case '2': value = 2; break; case '3': value = 3; break; case '4': value = 4; break; case '5': value = 5; break; case '6': value = 6; break; case '7': value = 7; break; case '8': value = 8; break; case '9': value = 9; break; case '1': value = 10; break; case 'J': value = 11; break; case 'Q': value = 12; break; case 'K': value = 13; break; case 'A': value = 14; break; } sum += value * multiplyer; } Console.WriteLine($"{player.Key}: {sum}"); sum = 0; } }
public IActionResult GetAllFixtures(int offset = 0, int limit = Int32.MaxValue) { return(Ok(_fixtures?.Skip(offset).Take(limit).Select(Mapper.Map <FixturesResponse>).ToList())); }
public Task SendPlayCommand(PlayRequest command, CancellationToken cancellationToken) { _logger.LogDebug("{0} - Received PlayRequest: {1}", this._session.DeviceName, command.PlayCommand); var user = command.ControllingUserId.Equals(Guid.Empty) ? null : _userManager.GetUserById(command.ControllingUserId); var items = new List <BaseItem>(); foreach (var id in command.ItemIds) { AddItemFromId(id, items); } var startIndex = command.StartIndex ?? 0; if (startIndex > 0) { items = items.Skip(startIndex).ToList(); } var playlist = new List <PlaylistItem>(); var isFirst = true; foreach (var item in items) { if (isFirst && command.StartPositionTicks.HasValue) { playlist.Add(CreatePlaylistItem(item, user, command.StartPositionTicks.Value, command.MediaSourceId, command.AudioStreamIndex, command.SubtitleStreamIndex)); isFirst = false; } else { playlist.Add(CreatePlaylistItem(item, user, 0, null, null, null)); } } _logger.LogDebug("{0} - Playlist created", _session.DeviceName); if (command.PlayCommand == PlayCommand.PlayLast) { _playlist.AddRange(playlist); } if (command.PlayCommand == PlayCommand.PlayNext) { _playlist.AddRange(playlist); } if (!command.ControllingUserId.Equals(Guid.Empty)) { _sessionManager.LogSessionActivity( _session.Client, _session.ApplicationVersion, _session.DeviceId, _session.DeviceName, _session.RemoteEndPoint, user); } return(PlayItems(playlist, cancellationToken)); }
/// <summary> /// Get users page /// </summary> /// <param name="pageSize">The maximum possible number of elements on one page</param> /// <param name="pageIndex">Number of elements from the current position</param> /// <returns></returns> public List <User> GetUsersPage(int pageSize, int pageIndex) { var result = (users.Skip(pageIndex).Take(pageSize)).ToList(); return(result); }
public JsonResponse GetListBlog([FromBody] BaseViewModel model) { try { var dicwhere = new Dictionary <string, object>() { { nameof(Bloginfo.IsDeleted), 0 }, { nameof(Bloginfo.States), 0 }, }; if (model.KID > 0) { dicwhere.Add(nameof(Bloginfo.Type), model.KID); } string key = ConfigUtil.BlogListCacheKey; var cacheobj = CacheHelper.GetCacheItem(key)?.ToString() ?? ""; List <Bloginfo> alllist = new List <Bloginfo>(); if (!string.IsNullOrEmpty(cacheobj)) { alllist = CacheHelper.GetCacheItem(key)?.DeserialObjectToList <Bloginfo>(); } int cut = 0; if (alllist == null || alllist.Count == 0) { var chaxun = BlogHelper.GetJsonListPage_Bloginfo(1, 1000, "CreateTime desc", new Dictionary <string, object>() { { nameof(Bloginfo.IsDeleted), 0 }, { nameof(Bloginfo.States), 0 } }); if (chaxun.code.Toint() != 0) { return(new JsonResponse { Code = chaxun.code.Toint(), Data = "", Msg = chaxun.msg }); } if (chaxun.data != null && chaxun.data.Count > 0) { alllist = chaxun.data; CacheHelper.AddCacheItem(ConfigUtil.BlogListCacheKey, chaxun.data.SerializObject(), DateTime.Now.AddDays(2), Cache.NoSlidingExpiration, CacheItemPriority.High); } } List <Bloginfo> retlist = null; if (model.KID > 0) { retlist = alllist.Where(x => x.Type == model.KID)?.ToList(); } else { retlist = alllist; } cut = retlist.Count; retlist = retlist?.Skip((model.Page - 1) * model.Limit).Take(model.Limit).ToList(); #region 统计访问地址信息 Task.Run(() => { if (model.KID <= 0) { var adddic = new Dictionary <string, object>() { { nameof(Access.AccessType), 0 }, { nameof(Access.IpAddress), GetIP() }, { nameof(Access.CreateTime), DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") }, { nameof(Access.CreateUserId), 1 }, { nameof(Access.CreateUserName), "system" } }; BlogHelper.Add_Access(adddic, new OpertionUser { }); } }); #endregion return(new JsonResponse { Code = 0, Data = retlist, Count = cut }); } catch (Exception ex) { LogHelper.WriteLog(ex, "BlogController/GetListBlog"); return(new JsonResponse { Code = 1, Msg = "程序好像开小差了" + ex.Message }); } }
/// <summary> /// Get the list of open shift entities from Kronos and pushes to Shifts. /// </summary> /// <param name="isRequestFromLogicApp">Checks if request is coming from logic app or portal.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> internal async Task ProcessOpenShiftsAsync(string isRequestFromLogicApp) { this.telemetryClient.TrackTrace($"{Resource.ProcessOpenShiftsAsync} started at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)} for isRequestFromLogicApp: {isRequestFromLogicApp}"); // Adding the telemetry properties. var telemetryProps = new Dictionary <string, string>() { { "MethodName", Resource.ProcessOpenShiftsAsync }, { "CallingAssembly", Assembly.GetCallingAssembly().GetName().Name }, }; if (isRequestFromLogicApp == null) { throw new ArgumentNullException(nameof(isRequestFromLogicApp)); } var allRequiredConfigurations = await this.utility.GetAllConfigurationsAsync().ConfigureAwait(false); if (allRequiredConfigurations?.IsAllSetUpExists == false) { throw new Exception($"{Resource.SyncOpenShiftsFromKronos} - {Resource.SetUpNotDoneMessage} - Some configuration settings were missing."); } this.utility.SetQuerySpan(Convert.ToBoolean(isRequestFromLogicApp, CultureInfo.InvariantCulture), out var openShiftStartDate, out var openShiftEndDate); // Check whether date range are in correct format. if (!Utility.CheckDates(openShiftStartDate, openShiftEndDate)) { throw new Exception($"{Resource.SyncOpenShiftsFromKronos} - Query date was invalid."); } var monthPartitions = Utility.GetMonthPartition(openShiftStartDate, openShiftEndDate); if (monthPartitions?.Count > 0) { telemetryProps.Add("MonthPartitionsStatus", "There are no month partitions found!"); } var orgJobBatchSize = int.Parse(this.appSettings.ProcessNumberOfOrgJobsInBatch, CultureInfo.InvariantCulture); var orgJobPaths = await this.teamDepartmentMappingProvider.GetAllOrgJobPathsAsync().ConfigureAwait(false); var mappedTeams = await this.teamDepartmentMappingProvider.GetMappedTeamToDeptsWithJobPathsAsync().ConfigureAwait(false); int orgJobPathIterations = Utility.GetIterablesCount(orgJobBatchSize, orgJobPaths.Count); // The monthPartitions is a list of strings which are formatted as: MM_YYYY to allow processing in batches foreach (var monthPartitionKey in monthPartitions) { if (monthPartitionKey == null) { this.telemetryClient.TrackTrace($"{Resource.MonthPartitionKeyStatus} - MonthPartitionKey cannot be found please check the data."); this.telemetryClient.TrackTrace(Resource.SyncOpenShiftsFromKronos, telemetryProps); continue; } this.telemetryClient.TrackTrace($"Processing data for the month partition: {monthPartitionKey} at {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}"); Utility.GetNextDateSpan( monthPartitionKey, monthPartitions.FirstOrDefault(), monthPartitions.LastOrDefault(), openShiftStartDate, openShiftEndDate, out string queryStartDate, out string queryEndDate); var orgJobPathList = new List <string>(orgJobPaths); // This for loop will iterate over the batched Org Job Paths. for (int iteration = 0; iteration < orgJobPathIterations; iteration++) { this.telemetryClient.TrackTrace($"OpenShiftController - Processing on iteration number: {iteration}"); var orgJobsInBatch = orgJobPathList?.Skip(orgJobBatchSize * iteration).Take(orgJobBatchSize); // Get the response for a batch of org job paths. var openShiftsResponse = await this.GetOpenShiftResultsByOrgJobPathInBatchAsync( allRequiredConfigurations.WFIId, allRequiredConfigurations.WfmEndPoint, allRequiredConfigurations.KronosSession, orgJobsInBatch.ToList(), queryStartDate, queryEndDate).ConfigureAwait(false); if (openShiftsResponse != null) { foreach (var orgJob in orgJobsInBatch) { this.telemetryClient.TrackTrace($"OpenShiftController - Processing the org job path: {orgJob}"); // Open Shift models for Create/Update operation var lookUpEntriesFoundList = new List <AllOpenShiftMappingEntity>(); var openShiftsNotFoundList = new List <OpenShiftRequestModel>(); var formattedOrgJob = Utility.OrgJobPathDBConversion(orgJob); var mappedOrgJobEntity = mappedTeams?.FirstOrDefault(x => x.PartitionKey == allRequiredConfigurations.WFIId && x.RowKey == formattedOrgJob); // Retrieve lookUpData for the open shift entity. var lookUpData = await this.openShiftMappingEntityProvider.GetAllOpenShiftMappingEntitiesInBatch( monthPartitionKey, formattedOrgJob, queryStartDate, queryEndDate).ConfigureAwait(false); if (lookUpData != null) { // This foreach loop will process the openShiftSchedule item(s) that belong to a specific Kronos Org Job Path. foreach (var openShiftSchedule in openShiftsResponse?.Schedules.Where(x => x.OrgJobPath == orgJob)) { this.telemetryClient.TrackTrace($"OpenShiftController - Processing the Open Shift schedule for: {openShiftSchedule.OrgJobPath}, and date range: {openShiftSchedule.QueryDateSpan}"); var scheduleShiftCount = (int)openShiftSchedule.ScheduleItems?.ScheduleShifts?.Count; if (scheduleShiftCount > 0) { if (mappedOrgJobEntity != null) { this.telemetryClient.TrackTrace($"OpenShiftController - Processing Open Shifts for the mapped team: {mappedOrgJobEntity.ShiftsTeamName}"); // This foreach builds the Open Shift object to push to Shifts via Graph API. foreach (var scheduleShift in openShiftSchedule?.ScheduleItems?.ScheduleShifts) { var shiftSegmentCount = scheduleShift.ShiftSegments; this.telemetryClient.TrackTrace($"OpenShiftController - Processing {scheduleShift.StartDate} with {shiftSegmentCount} segments."); var openShiftActivity = new List <Activity>(); // This foreach loop will build the OpenShift activities. foreach (var segment in scheduleShift.ShiftSegments.ShiftSegment) { openShiftActivity.Add(new Activity { IsPaid = true, StartDateTime = this.utility.CalculateStartDateTime(segment, mappedOrgJobEntity.KronosTimeZone), EndDateTime = this.utility.CalculateEndDateTime(segment, mappedOrgJobEntity.KronosTimeZone), Code = string.Empty, DisplayName = segment.SegmentTypeName, }); } var shift = new OpenShiftRequestModel() { SchedulingGroupId = mappedOrgJobEntity.TeamsScheduleGroupId, SharedOpenShift = new OpenShiftItem { DisplayName = string.Empty, OpenSlotCount = Constants.ShiftsOpenSlotCount, Notes = this.utility.GetOpenShiftNotes(scheduleShift), StartDateTime = openShiftActivity.First().StartDateTime, EndDateTime = openShiftActivity.Last().EndDateTime, Theme = this.appSettings.OpenShiftTheme, Activities = openShiftActivity, }, }; // Generates the uniqueId for the OpenShift. shift.KronosUniqueId = this.utility.CreateUniqueId(shift, mappedOrgJobEntity); // Logging the output of the KronosHash creation. this.telemetryClient.TrackTrace("OpenShiftController-KronosHash: " + shift.KronosUniqueId); if (lookUpData.Count == 0) { this.telemetryClient.TrackTrace($"OpenShiftController - Adding {shift.KronosUniqueId} to the openShiftsNotFoundList as the lookUpData count = 0"); openShiftsNotFoundList.Add(shift); } else { var kronosUniqueIdExists = lookUpData.Where(c => c.RowKey == shift.KronosUniqueId); if ((kronosUniqueIdExists != default(List <AllOpenShiftMappingEntity>)) && kronosUniqueIdExists.Any()) { this.telemetryClient.TrackTrace($"OpenShiftController - Adding {kronosUniqueIdExists.FirstOrDefault().RowKey} to the lookUpEntriesFoundList as there is data in the lookUpData list."); lookUpEntriesFoundList.Add(kronosUniqueIdExists.FirstOrDefault()); } else { this.telemetryClient.TrackTrace($"OpenShiftController - Adding {shift.KronosUniqueId} to the openShiftsNotFoundList."); openShiftsNotFoundList.Add(shift); } } } } else { this.telemetryClient.TrackTrace($"{Resource.SyncOpenShiftsFromKronos} - There is no mappedTeam found with WFI ID: {allRequiredConfigurations.WFIId}"); continue; } } else { this.telemetryClient.TrackTrace($"ScheduleShiftCount - {scheduleShiftCount} for {openShiftSchedule.OrgJobPath}"); continue; } } if (lookUpData.Except(lookUpEntriesFoundList).Any()) { this.telemetryClient.TrackTrace($"OpenShiftController - The lookUpEntriesFoundList has {lookUpEntriesFoundList.Count} items which could be deleted"); await this.DeleteOrphanDataOpenShiftsEntityMappingAsync(allRequiredConfigurations.ShiftsAccessToken, lookUpEntriesFoundList, lookUpData, mappedOrgJobEntity).ConfigureAwait(false); } if (openShiftsNotFoundList.Count > 0) { this.telemetryClient.TrackTrace($"OpenShiftController - The openShiftsNotFoundList has {openShiftsNotFoundList.Count} items which could be added."); await this.CreateEntryOpenShiftsEntityMappingAsync(allRequiredConfigurations.ShiftsAccessToken, openShiftsNotFoundList, monthPartitionKey, mappedOrgJobEntity).ConfigureAwait(false); } } else { this.telemetryClient.TrackTrace($"{Resource.SyncOpenShiftsFromKronos} - There is no lookup data present with the schedulingGroupId: " + mappedOrgJobEntity?.TeamsScheduleGroupId); continue; } } } } } this.telemetryClient.TrackTrace($"{Resource.ProcessOpenShiftsAsync} ended at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)} for isRequestFromLogicApp: {isRequestFromLogicApp}"); }
public Session LoadConfiguration(string[] args) { var options = new OptionSet { { "o|output=", $"Reports output directory\n(default: '{Output}')", v => Output = v }, { "p|profile=", $"Profile TOML file with current settings\n(default: '{Profile}')", v => Profile = v }, { "t|template=", $"HTML report template file\n(default: '{Template}')", v => Template = v }, { "h|help", "Show this message", v => ShowHelpAndExit = v != null } }; List <string> free = null; try { free = options.Parse(args); } catch (OptionException e) { log.LogError($"Option '{e.OptionName}' value is invalid: {e.Message}"); Error = Error.InvalidArgs; return(this); } if (!PathHelper.FileExistsWithOptionalExt(ref Profile, ".toml")) { log.LogError($"Profile '{Profile}' not found"); Error = Error.InvalidArgs; return(this); } if (!PathHelper.FileExistsWithOptionalExt(ref Template, ".html")) { log.LogError($"Template '{Template}' not found"); Error = Error.InvalidArgs; return(this); } try { Settings = Settings.Read(Profile.RelativeToBaseDirectory()); } catch (Exception e) { log.LogError($"Failed to read profile '{Profile}': {e.Message}"); Error = Error.InvalidArgs; return(this); } try { if (free?.Count >= 2) { SvcLeft = new Uri(free[0]); SvcRight = new Uri(free[1]); } } catch (Exception e) { log.LogError(e.Message); Error = Error.InvalidArgs; return(this); } Input = free?.Skip(2).FirstOrDefault(); if (Input != null && !File.Exists(Input.RelativeToBaseDirectory())) { log.LogError("Input file with URLs not found"); Error = Error.InvalidArgs; } if (ShowHelpAndExit || Error != Error.None || Settings == null || free == null || free.Count < 2) { PrintUsageInfo(options); Error = Error.Exit; return(this); } return(this); }
/// <summary> /// Get the 10 newest posts /// </summary> /// <returns>10 Posts in reverse order</returns> public static IEnumerable <Episode> GetTenPosts(int pager = 0) { return(_memoryCache?.Skip(pager * 10)?.Take(10)); }
public IEnumerable <Business> GetBusinessesBySearch(string companyname, string city, int?from, int?to, out int totalBusinessCount) { List <Business> oBusinesss = new List <Business>(); totalBusinessCount = 0; try { oBusinesss = DBContext.Businesses .Include(o => o.BusinessAddresses .Select(ua => ua.Address) .Select(ad => ad.TypeCode) .Select(typ => typ.ClassType) ) .Include(p => p.Achievements) .Include(p => p.Experiences) .Include(p => p.BusinessImages .Select(k => k.Image)) .Include(o => o.BusinessAddresses .Select(ua => ua.Address) .Select(ad => ad.Country) ) .Include(o => o.BusinessEmails .Select(ue => ue.Email) .Select(e => e.TypeCode) .Select(typ => typ.ClassType) ) .Include(o => o.BusinessPhones .Select(up => up.Phone) .Select(p => p.TypeCode) .Select(typ => typ.ClassType) ).Include(o => o.BusinessPhones.Select(up => up.Phone)) .Include(o => o.Experiences) .Include(o => o.Achievements) .Include(o => o.BusinessImages) .Include(o => o.Jobs.Select(p => p.JobApplications)) .OrderByDescending(x => x.insdt) .ToList(); if (!string.IsNullOrEmpty(companyname)) { oBusinesss = oBusinesss.Where(x => x.Name != null && x.Name.ToLower().Contains(companyname.ToLower())).ToList(); } if (!string.IsNullOrEmpty(city)) { oBusinesss = (from a in oBusinesss join b in DBContext.BusinessAddresses on a.BusinessID equals b.Business.BusinessID where (b.IsPrimary == true && b.Address != null && (b.Address.City != null && b.Address.City.ToLower().Contains(city.ToLower())) || (b.Address.State != null && b.Address.State.ToLower().Contains(city.ToLower())) || (b.Address.ZipCode != null && b.Address.ZipCode.ToLower().Contains(city.ToLower())) ) select a).ToList(); } totalBusinessCount = oBusinesss.Count(); if (from.HasValue && to.HasValue) { oBusinesss = oBusinesss.Skip(from.Value).Take(to.Value - from.Value).ToList(); } } catch (Exception ex) { //Log Exception. } return(oBusinesss); }
Vector3 Bz(List <Segment> ps, float t) { return(ps.Count == 1 ? ps.First().GetLerp(t) : Bz(ps.ZipWith(ps.Skip(1), (a, b) => new Segment(a.GetLerp(t), b.GetLerp(t))).ToList(), t)); }
public static List <DescriptionApiModel> GetPage(List <DescriptionApiModel> list, int page, int pageSize) { return(list.Skip((page - 1) * pageSize).Take(pageSize).ToList()); }
public static List <string> GetPage(List <string> list, int page, int pageSize) { return(list.Skip((page - 1) * pageSize).Take(pageSize).ToList()); }
public override object Execute(List <string> args) { if (args.Count < 2) { return(false); } // // Verify Blam tag instance // var unitName = args[0].ToLower(); if (unitName != "spartan" && unitName != "elite") { Console.WriteLine("ERROR: Only 'spartan' and 'elite' armor variants are allowed."); return(false); } args.RemoveAt(0); var blamTagName = unitName == "spartan" ? @"objects\characters\masterchief\mp_masterchief\mp_masterchief" : @"objects\characters\elite\mp_elite\mp_elite"; Console.Write($"Verifying {blamTagName}.render_model..."); CacheFile.IndexItem blamTag = null; foreach (var tag in BlamCache.IndexItems) { if ((tag.GroupTag == "mode") && (tag.Name == blamTagName)) { blamTag = tag; break; } } if (blamTag == null) { Console.WriteLine($"ERROR: Blam tag does not exist: {blamTagName}.render_model"); return(true); } Console.WriteLine("done."); // // Load the Blam tag definition // var variantName = args[0]; args.RemoveAt(0); CachedTag edModeTag = null; var isScenery = false; var regionNames = new List <string>(); while (args.Count != 0) { switch (args[0].ToLower()) { case "scenery": isScenery = true; args.RemoveAt(0); break; case "replace:": edModeTag = CacheContext.GetTag(args[1]); args.RemoveAt(1); args.RemoveAt(0); break; case "regions:": regionNames.AddRange(args.Skip(1)); args.Clear(); break; default: throw new InvalidDataException($"{args}"); } } var blamContext = new CacheSerializationContext(ref BlamCache, blamTag); var edModeDefinition = BlamCache.Deserializer.Deserialize <RenderModel>(blamContext); var materials = edModeDefinition.Materials.Select(i => new RenderMaterial { BreakableSurfaceIndex = i.BreakableSurfaceIndex, Properties = i.Properties, RenderMethod = i.RenderMethod, Skins = i.Skins, Unknown = i.Unknown, Unknown2 = i.Unknown2, Unknown3 = i.Unknown3, Unknown4 = i.Unknown4 }).ToList(); edModeDefinition = (RenderModel)ConvertData(null, edModeDefinition, false); var variantRegions = new List <RenderModel.Region>(); foreach (var region in edModeDefinition.Regions) { if (regionNames.Count != 0 && !regionNames.Contains(CacheContext.GetString(region.Name))) { continue; } var variantRegion = new RenderModel.Region { Name = region.Name, Permutations = new List <RenderModel.Region.Permutation>() }; foreach (var permutation in region.Permutations) { if (variantName == CacheContext.GetString(permutation.Name)) { variantRegion.Permutations.Add(permutation); } } variantRegions.Add(variantRegion); } var variantMeshes = new List <int>(); var variantMaterials = new List <int>(); var variantVertexBuffers = new List <int>(); var variantIndexBuffers = new List <int>(); foreach (var region in variantRegions) { foreach (var permutation in region.Permutations) { for (var i = permutation.MeshIndex; i < (short)(permutation.MeshIndex + permutation.MeshCount); i++) { var mesh = edModeDefinition.Geometry.Meshes[i]; foreach (var part in mesh.Parts) { if (part.MaterialIndex != -1 && !variantMaterials.Contains(part.MaterialIndex)) { variantMaterials.Add(part.MaterialIndex); } } foreach (var vertexBuffer in mesh.VertexBufferIndices) { if (vertexBuffer != -1 && !variantVertexBuffers.Contains(vertexBuffer)) { variantVertexBuffers.Add(vertexBuffer); } } foreach (var indexBuffer in mesh.IndexBufferIndices) { if (indexBuffer != -1 && !variantIndexBuffers.Contains(indexBuffer)) { variantIndexBuffers.Add(indexBuffer); } } if (!variantMeshes.Contains(i)) { variantMeshes.Add(i); } } } } variantMeshes.Sort(); variantMaterials.Sort(); variantVertexBuffers.Sort(); variantIndexBuffers.Sort(); foreach (var meshIndex in variantMeshes) { var mesh = edModeDefinition.Geometry.Meshes[meshIndex]; foreach (var part in mesh.Parts) { if (part.MaterialIndex != -1) { part.MaterialIndex = (short)variantMaterials.IndexOf(part.MaterialIndex); } } } foreach (var region in variantRegions) { foreach (var permutation in region.Permutations) { if (permutation.MeshIndex != -1) { permutation.MeshIndex = (short)variantMeshes.IndexOf(permutation.MeshIndex); } } } foreach (var meshIndex in variantMeshes) { var mesh = edModeDefinition.Geometry.Meshes[meshIndex]; for (var i = 0; i < mesh.VertexBufferIndices.Length; i++) { if (!variantVertexBuffers.Contains(mesh.VertexBufferIndices[i])) { mesh.VertexBufferIndices[i] = ushort.MaxValue; } else { mesh.VertexBufferIndices[i] = (ushort)variantVertexBuffers.IndexOf(mesh.VertexBufferIndices[i]); } } for (var i = 0; i < mesh.IndexBufferIndices.Length; i++) { if (!variantIndexBuffers.Contains(mesh.IndexBufferIndices[i])) { mesh.IndexBufferIndices[i] = ushort.MaxValue; } else { mesh.IndexBufferIndices[i] = (ushort)variantIndexBuffers.IndexOf(mesh.IndexBufferIndices[i]); } } } edModeDefinition.Regions = variantRegions; edModeDefinition.Geometry.Meshes = edModeDefinition.Geometry.Meshes.Where(i => variantMeshes.Contains(edModeDefinition.Geometry.Meshes.IndexOf(i))).ToList(); // // Port Blam render_model materials // materials = materials.Where(i => variantMaterials.Contains(materials.IndexOf(i))).ToList(); using (var stream = CacheContext.OpenTagCacheReadWrite()) { for (var i = 0; i < materials.Count; i++) { var material = materials[i]; if (material.RenderMethod.Index == -1) { continue; } var blamRenderMethod = materials[i].RenderMethod; var blamRenderMethodTag = BlamCache.IndexItems.GetItemByID(blamRenderMethod.Index); var renderMethodExists = false; foreach (var instance in CacheContext.TagCache.Index.FindAllInGroup("rm ")) { if (instance?.Name == blamRenderMethodTag.Name) { renderMethodExists = true; material.RenderMethod = instance; break; } } if (!renderMethodExists) { material.RenderMethod = CacheContext.GetTag <Shader>(@"shaders\invalid"); } } } edModeDefinition.Materials = materials; // // Load Blam resource data // var resourceData = BlamCache.GetRawFromID(edModeDefinition.Geometry.Resource.Gen3ResourceID); if (resourceData == null) { Console.WriteLine("Blam render_geometry resource contains no data."); return(true); } // // Load Blam resource definition // Console.Write("Loading Blam render_geometry resource definition..."); var definitionEntry = BlamCache.ResourceGestalt.TagResources[edModeDefinition.Geometry.Resource.Gen3ResourceID.Index]; var resourceDefinition = new RenderGeometryApiResourceDefinition { VertexBuffers = new List <TagStructureReference <VertexBufferDefinition> >(), IndexBuffers = new List <TagStructureReference <IndexBufferDefinition> >() }; using (var definitionStream = new MemoryStream(BlamCache.ResourceGestalt.FixupInformation)) using (var definitionReader = new EndianReader(definitionStream, EndianFormat.BigEndian)) { var dataContext = new DataSerializationContext(definitionReader, null, CacheAddressType.Definition); definitionReader.SeekTo(definitionEntry.FixupInformationOffset + (definitionEntry.FixupInformationLength - 24)); var vertexBufferCount = definitionReader.ReadInt32(); definitionReader.Skip(8); var indexBufferCount = definitionReader.ReadInt32(); definitionReader.SeekTo(definitionEntry.FixupInformationOffset); for (var i = 0; i < vertexBufferCount; i++) { resourceDefinition.VertexBuffers.Add(new TagStructureReference <VertexBufferDefinition> { Definition = new VertexBufferDefinition { Count = definitionReader.ReadInt32(), Format = (VertexBufferFormat)definitionReader.ReadInt16(), VertexSize = definitionReader.ReadInt16(), Data = new TagData { Size = definitionReader.ReadInt32(), Unused4 = definitionReader.ReadInt32(), Unused8 = definitionReader.ReadInt32(), Address = new CacheAddress(CacheAddressType.Memory, definitionReader.ReadInt32()), Unused10 = definitionReader.ReadInt32() } } }); } definitionReader.Skip(vertexBufferCount * 12); for (var i = 0; i < indexBufferCount; i++) { resourceDefinition.IndexBuffers.Add(new TagStructureReference <IndexBufferDefinition> { Definition = new IndexBufferDefinition { Format = (IndexBufferFormat)definitionReader.ReadInt32(), Data = new TagData { Size = definitionReader.ReadInt32(), Unused4 = definitionReader.ReadInt32(), Unused8 = definitionReader.ReadInt32(), Address = new CacheAddress(CacheAddressType.Memory, definitionReader.ReadInt32()), Unused10 = definitionReader.ReadInt32() } } }); } } Console.WriteLine("done."); // // Convert Blam resource data // using (var edResourceStream = new MemoryStream()) { // // Convert Blam render_geometry_api_resource_definition // using (var blamResourceStream = new MemoryStream(resourceData)) { // // Convert Blam vertex buffers // Console.Write("Converting vertex buffers..."); var previousVertexBufferCount = -1; for (var i = 0; i < resourceDefinition.VertexBuffers.Count; i++) { if (!variantVertexBuffers.Contains(i)) { continue; } blamResourceStream.Position = definitionEntry.ResourceFixups[i].Offset; if (i > 0) { previousVertexBufferCount = resourceDefinition.VertexBuffers[i - 1].Definition.Count; } GeometryConverter.ConvertVertexBuffer(resourceDefinition, blamResourceStream, edResourceStream, i, previousVertexBufferCount); } Console.WriteLine("done."); // // Convert Blam index buffers // Console.Write("Converting index buffers..."); for (var i = 0; i < resourceDefinition.IndexBuffers.Count; i++) { if (!variantIndexBuffers.Contains(i)) { continue; } blamResourceStream.Position = definitionEntry.ResourceFixups[resourceDefinition.VertexBuffers.Count * 2 + i].Offset; GeometryConverter.ConvertIndexBuffer(resourceDefinition, blamResourceStream, edResourceStream, i); } Console.WriteLine("done."); } resourceDefinition.VertexBuffers = resourceDefinition.VertexBuffers.Where(i => variantVertexBuffers.Contains(resourceDefinition.VertexBuffers.IndexOf(i))).ToList(); resourceDefinition.IndexBuffers = resourceDefinition.IndexBuffers.Where(i => variantIndexBuffers.Contains(resourceDefinition.IndexBuffers.IndexOf(i))).ToList(); // // Finalize the new ElDorado geometry resource // Console.Write("Writing resource data..."); edModeDefinition.Geometry.Resource.HaloOnlinePageableResource = new PageableResource { Page = new RawPage(), Resource = new TagResourceGen3 { ResourceType = TagResourceTypeGen3.RenderGeometry, ResourceFixups = new List <TagResourceGen3.ResourceFixup>(), ResourceDefinitionFixups = new List <TagResourceGen3.ResourceDefinitionFixup>(), Unknown2 = 1 } }; edResourceStream.Position = 0; var resourceContext = new ResourceSerializationContext(CacheContext, edModeDefinition.Geometry.Resource.HaloOnlinePageableResource); CacheContext.Serializer.Serialize(resourceContext, resourceDefinition); edModeDefinition.Geometry.Resource.HaloOnlinePageableResource.ChangeLocation(ResourceLocation.ResourcesB); CacheContext.AddResource(edModeDefinition.Geometry.Resource.HaloOnlinePageableResource, edResourceStream); Console.WriteLine("done."); } edModeDefinition.Name = CacheContext.GetStringId(variantName); if (edModeTag == null) { for (var i = 0; i < CacheContext.TagCache.Index.Count; i++) { if (CacheContext.TagCache.Index[i] == null) { CacheContext.TagCache.Index[i] = edModeTag = new CachedTag(i, TagGroup.Instances[new Tag("mode")]); break; } } if (edModeTag == null) { edModeTag = CacheContext.TagCache.AllocateTag(TagGroup.Instances[new Tag("mode")]); } } // // Create a new armor model tag // Model edHlmtDefinition = null; CachedTag edHlmtTag = null; if (isScenery) { Console.Write($"Verifying {blamTagName}.model..."); CacheFile.IndexItem blamHlmtTag = null; foreach (var tag in BlamCache.IndexItems) { if ((tag.GroupTag == "hlmt") && (tag.Name == blamTagName)) { blamHlmtTag = tag; break; } } if (blamHlmtTag == null) { Console.WriteLine($"ERROR: Blam tag does not exist: {blamTagName}.model"); return(true); } Console.WriteLine("done."); blamContext = new CacheSerializationContext(ref BlamCache, blamHlmtTag); edHlmtDefinition = (Model)ConvertData(null, BlamCache.Deserializer.Deserialize <Model>(blamContext), false); edHlmtDefinition.RenderModel = edModeTag; edHlmtDefinition.ReduceToL1SuperLow = 36.38004f; edHlmtDefinition.ReduceToL2Low = 27.28503f; edHlmtDefinition.Variants = new List <Model.Variant>(); edHlmtDefinition.Materials = new List <Model.Material>(); edHlmtDefinition.NewDamageInfo = new List <Model.GlobalDamageInfoBlock>(); edHlmtDefinition.Targets = new List <Model.Target>(); var collisionRegions = new List <Model.CollisionRegion>(); foreach (var collisionRegion in edHlmtDefinition.CollisionRegions) { var found = false; foreach (var variantRegion in variantRegions) { if (collisionRegion.Name == variantRegion.Name) { found = true; break; } } if (!found) { continue; } found = false; foreach (var permutation in collisionRegion.Permutations) { if (permutation.Name == CacheContext.GetStringId(variantName)) { found = true; break; } } if (found) { collisionRegions.Add(collisionRegion); } } foreach (var collisionRegion in collisionRegions) { Model.CollisionRegion.Permutation permutation = null; foreach (var collisionPermutation in collisionRegion.Permutations) { if (collisionPermutation.Name == CacheContext.GetStringId(variantName)) { permutation = collisionPermutation; break; } } if (permutation == null) { throw new KeyNotFoundException(); } collisionRegion.Permutations = new List <Model.CollisionRegion.Permutation> { permutation }; } edHlmtDefinition.CollisionRegions = collisionRegions; for (var i = 0; i < CacheContext.TagCache.Index.Count; i++) { if (CacheContext.TagCache.Index[i] == null) { CacheContext.TagCache.Index[i] = edHlmtTag = new CachedTag(i, TagGroup.Instances[new Tag("hlmt")]); break; } } if (edHlmtTag == null) { edHlmtTag = CacheContext.TagCache.AllocateTag(TagGroup.Instances[new Tag("hlmt")]); } } // // Create a new armor scenery tag // Scenery edScenDefinition = null; CachedTag edScenTag = null; if (isScenery) { edScenDefinition = new Scenery { ObjectType = new GameObjectType { Halo2 = GameObjectTypeHalo2.Scenery, Halo3Retail = GameObjectTypeHalo3Retail.Scenery, Halo3ODST = GameObjectTypeHalo3ODST.Scenery, HaloOnline = GameObjectTypeHaloOnline.Scenery }, BoundingRadius = 0.44f, BoundingOffset = new RealPoint3d(-0.02f, 0.0f, 0.0f), AccelerationScale = 1.2f, SweetenerSize = GameObject.SweetenerSizeValue.Medium, Model = edHlmtTag, ChangeColors = new List <GameObject.ChangeColor> { new GameObject.ChangeColor(), new GameObject.ChangeColor(), new GameObject.ChangeColor(), new GameObject.ChangeColor(), new GameObject.ChangeColor() }, NodeMaps = new List <GameObject.NodeMap>() }; for (sbyte i = 0; i < 51; i++) { edScenDefinition.NodeMaps.Add(new GameObject.NodeMap { TargetNode = i }); } for (var i = 0; i < CacheContext.TagCache.Index.Count; i++) { if (CacheContext.TagCache.Index[i] == null) { CacheContext.TagCache.Index[i] = edScenTag = new CachedTag(i, TagGroup.Instances[new Tag("scen")]); break; } } if (edScenTag == null) { edScenTag = CacheContext.TagCache.AllocateTag(TagGroup.Instances[new Tag("scen")]); } } // // Serialize new ElDorado tag definitions // using (var cacheStream = CacheContext.OpenTagCacheReadWrite()) { CacheContext.Serialize(cacheStream, edModeTag, edModeDefinition); edModeTag.Name = isScenery ? (unitName == "spartan" ? $@"objects\characters\masterchief\mp_masterchief\armor\{variantName}" : $@"objects\characters\elite\mp_elite\armor\{variantName}") : (unitName == "spartan" ? @"objects\characters\masterchief\mp_masterchief\mp_masterchief" : @"objects\characters\elite\mp_elite\mp_elite"); if (isScenery) { CacheContext.Serialize(cacheStream, edHlmtTag, edHlmtDefinition); CacheContext.Serialize(cacheStream, edScenTag, edScenDefinition); edScenTag.Name = unitName == "spartan" ? $@"objects\characters\masterchief\mp_masterchief\armor\{variantName}" : $@"objects\characters\elite\mp_elite\armor\{variantName}"; } } return(true); }
public static List <ComponentApiModel> GetPage(List <ComponentApiModel> list, int page, int pageSize) { return(list.Skip((page - 1) * pageSize).Take(pageSize).ToList()); }