/// <summary> /// Parses the object. /// </summary> /// <param name="relativePaths">The relative paths. <example>{"site1","themes","default"}</example></param> /// <returns>the remaining paths. <example>{"site1"}</example></returns> internal override IEnumerable<string> ParseObject(IEnumerable<string> relativePaths) { var index = Array.LastIndexOf(relativePaths.Select(it => it.ToLower()).ToArray(), PATH_NAME.ToLower()); relativePaths = relativePaths.Take(index + 2); this.Name = relativePaths.Last(); return relativePaths.Take(relativePaths.Count() - 2); }
public static IEnumerable<byte> Replace(IEnumerable<byte> input, IEnumerable<byte> from, IEnumerable<byte> to) { var fromEnumerator = from.GetEnumerator(); fromEnumerator.MoveNext(); int match = 0; foreach (var data in input) { if (data == fromEnumerator.Current) { match++; if (fromEnumerator.MoveNext()) { continue; } foreach (byte d in to) { yield return d; } match = 0; fromEnumerator.Reset(); fromEnumerator.MoveNext(); continue; } if (0 != match) { foreach (byte d in from.Take(match)) { yield return d; } match = 0; fromEnumerator.Reset(); fromEnumerator.MoveNext(); } yield return data; } if (0 != match) { foreach (byte d in from.Take(match)) { yield return d; } } }
public List<RealtimeReview> filteRealtimeReview(TNS.Metadata.Query.QRealtimeReview condition, IEnumerable<RealtimeReview> result) { try { result = result.Where(x => x.hotelId == condition.hotelId.ToString()).Select(x => x); if (!string.IsNullOrEmpty(condition.checkin)) { if (condition.isDateRange) { result = result.Where(i => i.startDate.ConvertToDateTime().CompareTo(condition.checkin.ConvertToDateTime()) >= 0).Select(i => i); } else { result = result.Where(i => i.startDate.ConvertToDateTime().CompareTo(condition.checkin.ConvertToDateTime()) == 0).Select(i => i); } } if (!string.IsNullOrEmpty(condition.checkout)) { if (condition.isDateRange) { result = result.Where(x => x.endDate.ConvertToDateTime().CompareTo(condition.checkout.ConvertToDateTime()) <= 0).Select(x => x); } else { result = result.Where(x => x.endDate.ConvertToDateTime().CompareTo(condition.checkout.ConvertToDateTime()) == 0).Select(x => x); } } result = result.Take(condition.itemsCount); } catch (Exception ex) { string message = ex.Message; } return result.ToList(); }
/// <summary> /// Converts from HSB. /// </summary> public static Color FromHsb(IEnumerable<byte> source) { // http://ja.wikipedia.org/wiki/HSV%E8%89%B2%E7%A9%BA%E9%96%93 var h = Utility.ToUInt16(source.Take(2)) / 182.04; var s = Utility.ToUInt16(source.Skip(2).Take(2)) / 655.35; var b = Utility.ToUInt16(source.Skip(4).Take(2)) / 655.35; // Convert to RGB var h_i = (int)(Math.Floor(h / 60) % 6); var f = (h / 60) - h_i; var p = (int)(b * (1 - s)); var q = (int)(b * (1 - f * s)); var t = (int)(b * (1 - (1 - f) * s)); switch (h_i) { case 0: return Color.FromArgb((int)b, t, p); case 1: return Color.FromArgb(q, (int)b, p); case 2: return Color.FromArgb(p, (int)b, t); case 3: return Color.FromArgb(p, q, (int)b); case 4: return Color.FromArgb(t, p, (int)b); case 5: return Color.FromArgb((int)b, p, q); default: throw new Exception(); } }
public static void SplitDic(IEnumerable<int> dic, int step) { //SplitList =new ConcurrentQueue<List<int>>(); // ConcurrentQueue<List<int>> SplitList = new ConcurrentQueue<List<int>>(); if (dic.Count() > step) { IEnumerable<int> keyvaluelist = dic.Take(step); List<int> newdic = new List<int>(); foreach (int s in keyvaluelist) { newdic.Add(s); } SplitList.Enqueue(newdic); SplitDic(dic.Skip(step), step); } else { List<int> newdic = new List<int>(); foreach (int s in dic) { newdic.Add(s); } SplitList.Enqueue(newdic); } //return SplitList; }
private static IEnumerable<Tuple<SpecificationProperty, Maybe<Error>>> MapValuesImpl( IEnumerable<SpecificationProperty> specProps, IEnumerable<string> values, Func<IEnumerable<string>, System.Type, bool, Maybe<object>> converter) { if (specProps.Empty() || values.Empty()) { yield break; } var pt = specProps.First(); var taken = values.Take(pt.Specification.GetMaxValueCount().Return(n => n, values.Count())); if (taken.Empty()) { yield break; } yield return converter(taken, pt.Property.PropertyType, pt.Specification.ConversionType.IsScalar()) .Return( converted => Tuple.Create(pt.WithValue(Maybe.Just(converted)), Maybe.Nothing<Error>()), Tuple.Create<SpecificationProperty, Maybe<Error>>( pt, Maybe.Just<Error>(new BadFormatConversionError(NameInfo.EmptyName)))); foreach (var value in MapValuesImpl(specProps.Skip(1), values.Skip(taken.Count()), converter)) { yield return value; } }
/// <summary> /// Parses the object. /// </summary> /// <param name="relativePaths">The relative paths. <example>{"site1","scripts","js.js"}</example></param> /// <returns> /// the remaining paths.<example>{"site1"}</example> /// </returns> public override IEnumerable<string> ParseObject(IEnumerable<string> relativePaths) { //call base return {"site1","scripts"} relativePaths = base.ParseObject(relativePaths); return relativePaths.Take(relativePaths.Count() - 1); }
public override void ExecuteCmdlet() { IEnumerable <Tile> tiles = null; using (var client = this.CreateClient()) { if (this.WorkspaceId != default) { tiles = client.Reports.GetTilesForWorkspace(workspaceId: this.WorkspaceId, dashboardId: this.DashboardId); } else { tiles = this.Scope == PowerBIUserScope.Individual ? client.Reports.GetTiles(this.DashboardId) : client.Reports.GetTilesAsAdmin(this.DashboardId); } } if (this.Id != default) { tiles = tiles?.Where(d => this.Id == d.Id); } if (this.Skip.HasValue) { tiles = tiles?.Skip(this.Skip.Value); } if (this.First.HasValue) { tiles = tiles?.Take(this.First.Value); } this.Logger.WriteObject(tiles, true); }
/// <summary> /// Initializes a new instance of the <see cref="GorgonStreamOutLayout"/> class. /// </summary> /// <param name="name">Name of the object.</param> /// <param name="elements">The input elements to assign to this layout.</param> /// <exception cref="ArgumentNullException">Thrown when the <paramref name="name"/>, or the <paramref name="elements"/> parameter is <b>null</b>.</exception> /// <exception cref="ArgumentEmptyException">Thrown when the <paramref name="name"/>, or the <paramref name="elements"/> parameter is empty.</exception> /// <exception cref="ArgumentException">Thrown when an element with the same context, slot and index appears more than once in the <paramref name="elements"/> parameter.</exception> /// <remarks> /// <para> /// The <paramref name="elements"/> list can contain up to 64 elements. If the list is longer than 64 elements, then it will be truncated to 64. /// </para> /// </remarks> public GorgonStreamOutLayout(string name, IEnumerable <GorgonStreamOutElement> elements) : base(name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentEmptyException(nameof(name)); } Name = name; // Make a copy so we don't allow changing of the original reference. _elements = elements?.Take(64).ToArray() ?? throw new ArgumentNullException(nameof(elements)); if (_elements.Length == 0) { throw new ArgumentEmptyException(nameof(elements)); } // Check for duplicated elements. for (int i = 0; i < _elements.Length; ++i) { FindDuplicateElements(_elements, _elements[i], i, nameof(elements)); } Native = new D3D11.StreamOutputElement[_elements.Length]; for (int i = 0; i < _elements.Length; ++i) { Native[i] = _elements[i].NativeElement; } }
public static bool TeamFormationValid(IEnumerable<Position> positions) { var startingPositions = positions.Take(11).ToList(); return startingPositions.Count(x => x == Position.Goalkeeper) == 1 && startingPositions.Count(x => x == Position.Defender) >= GameConstants.MinimumDefendersInStartingTeam && startingPositions.Count(x => x == Position.Forward) >= GameConstants.MinimumForwardsInStartingTeam; }
public override IEnumerable<IUnit> PickNextTargets(IEnumerable<IUnit> candidateTargets) { if (base.Unit.HealthPoints <= 150) return candidateTargets.Take(1); else return candidateTargets; }
public IWordState Reduce(IEnumerable<IWordState> set, int len) { if (len == 0) return new Chunk(""); if (len == 1) return set.First(); else { int pivot = len / 2; //var i1 = set.Take(pivot).ToList(); //var i2 = set.Skip(pivot).ToList(); //var t1 = new Task<IWordState>(() => Reduce(i1, pivot)); //var t2 = new Task<IWordState>(() => Reduce(i2, pivot + len % 2)); var firstHalf = Reduce(set.Take(pivot), pivot); var secondHalf = Reduce(set.Skip(pivot), pivot + len % 2); IWordState result = firstHalf.Combine(secondHalf); return result; } }
public ForecastEntry Forecast(IEnumerable<DataEntry> dataEntries, int period, dynamic strategyParameters) { if (period - 1 < 0) return null; int numberOfPeriods = strategyParameters.PeriodCount; if (numberOfPeriods > dataEntries.Count()) throw new ArgumentException("The number of periods can not be greater than the number of entries."); double value; if (dataEntries.Count() == 1 || period == 1) value = dataEntries.ElementAt(0).Value; else if (period < numberOfPeriods) value = dataEntries.ElementAt(period - 1).Value; else if (dataEntries.Count() > 1 && period <= dataEntries.Count() + 1) value = dataEntries.Take(period - 1).Reverse().Take(numberOfPeriods).Reverse().Sum(entry => (entry.Value))/ numberOfPeriods; else value = dataEntries.Reverse().Take(numberOfPeriods).Reverse().Sum(entry => (entry.Value))/ numberOfPeriods; return new ForecastEntry { Period = period, DataEntry = period > dataEntries.Count() ? dataEntries.Last() : dataEntries.ElementAt(period - 1), ForecastValue = value, ConfidenceIntervalLow = value, ConfidenceIntervalHigh = value, IsHoldout = period > dataEntries.Count()*0.7 //holdout data is always 70 percent }; }
public IList<Artifact> SearchArtifacts(IEnumerable<ArtifactSearch> searches) { var result = new List<Artifact>(searches.Count()); while (searches.Any()) { var request = new RestRequest(Method.POST); request.Resource = "search/artifact/"; request.RequestFormat = DataFormat.Json; request.OnBeforeDeserialization = BeforeSerialization; request.AddBody(searches.Take(this._pageSize)); var response = Execute<ArtifactResponse>(request); if (response.ResponseStatus == ResponseStatus.Error) { throw new ApiClientTransportException(response.ErrorMessage, response.ErrorException); } result.AddRange(response.Data); searches = searches.Skip(this._pageSize); } return result; }
public override void ExecuteCmdlet() { if (this.Workspace != null) { this.WorkspaceId = this.Workspace.Id; } if (this.Id != default) { this.Filter = $"id eq '{this.Id}'"; } if (this.Name != default) { this.Filter = $"tolower(name) eq '{this.Name.ToLower()}'"; } IEnumerable <Dashboard> dashboards = null; using (var client = this.CreateClient()) { if (this.WorkspaceId != default) { dashboards = this.Scope == PowerBIUserScope.Individual ? client.Reports.GetDashboardsForWorkspace(workspaceId: this.WorkspaceId) : client.Reports.GetDashboardsAsAdminForWorkspace(workspaceId: this.WorkspaceId, filter: this.Filter, top: this.First, skip: this.Skip); } else { dashboards = this.Scope == PowerBIUserScope.Individual ? client.Reports.GetDashboards() : client.Reports.GetDashboardsAsAdmin(filter: this.Filter, top: this.First, skip: this.Skip); } } if (this.Scope == PowerBIUserScope.Individual) { if (this.Id != default) { dashboards = dashboards?.Where(d => this.Id == d.Id); } if (!string.IsNullOrEmpty(this.Name)) { dashboards = dashboards?.Where(d => d.Name.Equals(this.Name, StringComparison.OrdinalIgnoreCase)); } if (this.Skip.HasValue) { dashboards = dashboards?.Skip(this.Skip.Value); } if (this.First.HasValue) { dashboards = dashboards?.Take(this.First.Value); } } this.Logger.WriteObject(dashboards, true); }
public static IEnumerable <BttvSharedEmote>?GetBttvEmotes(string channel, int count) { IEnumerable <BttvSharedEmote>?emotes = GetBttvEmotes(channel); NormalizeCount(emotes, ref count); return(emotes?.Take(count)); }
/// <summary> Determines if the set of specified RangeRequests represents a partial range or multiple range requests. </summary> /// <remarks> ebrown, 2/14/2011. </remarks> /// <exception cref="ArgumentNullException"> Thrown when rangeRequests are null. </exception> /// <param name="rangeRequests"> The set of range requests (typically returned by TryParseRangeRequests). </param> /// <param name="fileLength"> Total length of the file to which the requests apply. </param> /// <returns> true if a set of range requests or the single range request is for a partial range, false if not. </returns> public static bool IsPartialOrMultipleRangeRequests(IEnumerable<RangeRequest> rangeRequests, long fileLength) { if (null == rangeRequests) { throw new ArgumentNullException("rangeRequests"); } var first = rangeRequests.FirstOrDefault(); return ((rangeRequests.Take(2).Count() > 1) || (0 != first.Start) || (fileLength != (first.End + 1))); }
/// <summary> /// Calculates Exponential Moving Average (EMA) indicator /// </summary> /// <param name="input">Input signal</param> /// <param name="period">Number of periods</param> /// <param name="uisngavg">Start with Average or start with first element</param> /// <returns>Object containing operation results</returns> public static EMAResult EMA(IEnumerable<double> input, int period, bool usingavg=true) { var returnValues = new List<double>(); double multiplier = (2.0 / (period + 1)); int start = usingavg ? period : 1; if ( input.Count() >= start) { double initialEMA = usingavg ? input.Take(period).Average() : input.First(); returnValues.Add(initialEMA); var copyInputValues = input.ToList(); for (int i = start; i < copyInputValues.Count; i++) { var resultValue = (copyInputValues[i] - returnValues.Last()) * multiplier + returnValues.Last(); returnValues.Add(resultValue); } } var result = new EMAResult() { Values = returnValues, StartIndexOffset = start - 1 }; return result; }
/// <summary> /// Function to convert this geometry shader to use a stream output. /// </summary> /// <param name="streamOutLayout">The stream output layout for the shader.</param> /// <param name="strides">[Optional] A list of strides that define the size of an element for each buffer.</param> /// <returns>A new <see cref="GorgonGeometryShader"/> that is capable of stream output.</returns> /// <exception cref="ArgumentNullException">Thrown when the <paramref name="streamOutLayout"/> parameter is <b>null</b>.</exception> /// <remarks> /// <para> /// A base geometry shader must be converted to use stream output if an application wants to send data from the shader into a buffer. /// </para> /// <para> /// If the <paramref name="strides"/> parameter is supplied, then it will be limited to 4 items at most, any more than that and the list will be truncated. /// </para> /// </remarks> public GorgonGeometryShader ToStreamOut(GorgonStreamOutLayout streamOutLayout, IEnumerable <int> strides = null) { if (streamOutLayout == null) { throw new ArgumentNullException(nameof(streamOutLayout)); } int[] strideList = strides?.Take(4).ToArray() ?? Array.Empty <int>(); // Clone the byte code just in case we decide to destroy the original. var byteCode = new ShaderBytecode(D3DByteCode.Data); Graphics.Log.Print($"Converting '{Name}' to Stream-Out.", LoggingLevel.Verbose); var shader = new D3D11.GeometryShader(Graphics.D3DDevice, byteCode, streamOutLayout.Native, strideList, 0) { DebugName = $"{Name}_ID3D11GeometryShader (SO)" }; var result = new GorgonGeometryShader(Graphics, Name + " (SO)", IsDebug, byteCode, shader) { StreamOutLayout = streamOutLayout }; result.RegisterDisposable(Graphics); return(result); }
bool TryEliminate (IEnumerable<string> methods, int chunkSize) { var count = methods.Count (); if (chunkSize < 1 || chunkSize > count) throw new Exception ("I can't do math."); var numChunks = (count + chunkSize - 1) / chunkSize; foreach (var i in EliminationOrder (numChunks)) { var firstIndex = i * chunkSize; var lastPlusOneIndex = (i + 1) * chunkSize; var methodsLeft = methods.Take (firstIndex).Concat (methods.Skip (lastPlusOneIndex)); if (chunkSize == 1) Console.WriteLine ("Running without method at position {0}", firstIndex); else Console.WriteLine ("Running without methods at positions {0} to {1}", firstIndex, lastPlusOneIndex - 1); var success = RunWithMethods (methodsLeft); Console.WriteLine ("Crashed: {0}", !success); if (!success) { Console.WriteLine ("Eliminating further from {0} methods.", methodsLeft.Count ()); return EliminationStep (methodsLeft); } } return false; }
public void Combine(World world, IEnumerable<Actor> newSelection, bool isCombine, bool isClick) { if (isClick) { var adjNewSelection = newSelection.Take(1); /* TODO: select BEST, not FIRST */ if (isCombine) actors.SymmetricExceptWith(adjNewSelection); else { actors.Clear(); actors.UnionWith(adjNewSelection); } } else { if (isCombine) actors.UnionWith(newSelection); else { actors.Clear(); actors.UnionWith(newSelection); } } var voicedActor = actors.FirstOrDefault(a => a.Owner == world.LocalPlayer && a.IsInWorld && a.HasTrait<IVoiced>()); if (voicedActor != null) voicedActor.PlayVoice("Select"); foreach (var a in newSelection) foreach (var sel in a.TraitsImplementing<INotifySelected>()) sel.Selected(a); foreach (var ns in world.WorldActor.TraitsImplementing<INotifySelection>()) ns.SelectionChanged(); }
public override void PathBuild() { _links = CategoryWithChild(CategoryId); CurrentCatalog(_links.First()); //skip the last element so he is our link CategoryTree(_links.Take(_links.Count() - 1)); }
private static IEnumerable<Movie> MergeResults(IEnumerable<Movie> netflixResults, IEnumerable<Movie> rottenTomatoesResults) { var movies = (from nf in netflixResults from rt in rottenTomatoesResults where nf.Title.ToUpper() == rt.Title.ToUpper() select new Movie { Title = nf.Title, Availability = nf.Availability.Union(rt.Availability).ToList(), Cast = rt.Cast, Key = new MovieKey { NetflixId = nf.ProviderMovieId, RottenTomatoesId = rt.ProviderMovieId }, MPAARating = rt.MPAARating, ProviderMovieId = "MovieMon", Source = "MovieMon", RelatedClips = rt.RelatedClips, Reviews = rt.Reviews, RunTime = nf.RunTime, Summary = nf.Summary, Rating = rt.Rating, RelatedImages = nf.RelatedImages } ).ToList(); var netflixMax = GetMax(netflixResults.Count()); var rtMax = GetMax(rottenTomatoesResults.Count()); var mergedMax = GetMax(movies.Count); Logger.InfoFormat("Merging additional results: added {0} from netflix and {1} from rotten tomatoes", netflixMax, rtMax); movies = movies.Take(mergedMax).ToList(); var merged = movies.Union(netflixResults.Take(netflixMax)).ToList(); merged = merged.Union(rottenTomatoesResults.Take(rtMax)).ToList(); var filtered = merged.Distinct(new MovieComparer()).ToList(); return filtered; }
/// <summary> /// Loads the specified collection into the recent file list. Use this method when you need to initialize the RecentFileList /// manually. This can be useful when you are using an own persistence implementation. /// </summary> /// <remarks>Recent file items that exist before the Load method is called are removed.</remarks> /// <param name="recentFiles">The recent files.</param> /// <exception cref="ArgumentNullException">The argument recentFiles must not be null.</exception> public void Load(IEnumerable<RecentFile> recentFiles) { if (recentFiles == null) { throw new ArgumentNullException(nameof(recentFiles)); } Clear(); AddRange(recentFiles.Take(maxFilesNumber)); }
private static double CalcVariance(IEnumerable<double> v1, double mean1, IEnumerable<double> v2, double mean2, int length) { var zipped = v1.Take(length).Zip(v2.Take(length), (i1, i2) => new[] { i1, i2 }); var sum = zipped.AsParallel().Sum(z => (z[0] - mean1) * (z[1] - mean2)); return sum / (length - 1); }
// TODO: Move drawing methods to a wrapper type that handles graphics only public void DrawRow(int top, IEnumerable<ConsolePixel> pixels) { if (top >= _size.Height) return; SetCursorPosition(0, top); foreach (ConsolePixel pixel in pixels.Take(_size.Width)) pixel.Print(); }
int GetIndicatorCount(Row row, IEnumerable<string> columns) { if (row.Level == "E" && row.Level == "M") { columns = columns.Take(3); } return columns.Where(c => CountableValues.Contains(row[c])).Count(); }
public static QueryBodySyntax WithAllClauses( this QueryBodySyntax body, IEnumerable<SyntaxNode> allClauses) { var clauses = SyntaxFactory.List(allClauses.Take(allClauses.Count() - 1).Cast<QueryClauseSyntax>()); var selectOrGroup = (SelectOrGroupClauseSyntax)allClauses.Last(); return body.WithClauses(clauses).WithSelectOrGroup(selectOrGroup); }
public override IEnumerable<IUnit> PickNextTargets(IEnumerable<IUnit> candidateTargets) { if (this.Unit.HealthPoints <= 150) { return candidateTargets.Take(1); } return candidateTargets; }
public virtual SyndicationFeed GetFeed(IEnumerable<Article> articles) { SyndicationFeed feed = CreateFeed(articles.First().GetDate()); feed.Authors.Add(new SyndicationPerson { Name = _config.Author }); feed.Items = CreateItems(articles.Take(10)); return feed; }
public IEnumerable<IUnit> PickNextTargets(IEnumerable<IUnit> candidateTargets) { if (candidateTargets == null) { throw new ArgumentNullException("targets", "Target list can not be null"); } return this.Unit.HealthPoints <= 150 ? candidateTargets.Take(1) : candidateTargets; }
private NameSnippet CreateNameSnippet(IEnumerable<string> matches, int i, IMappingOptions mappingOptions) { return new NameSnippet { First = String.Join(mappingOptions.SourceMemberNamingConvention.SeparatorCharacter, matches.Take(i).ToArray()), Second = String.Join(mappingOptions.SourceMemberNamingConvention.SeparatorCharacter, matches.Skip(i).ToArray()) }; }
public static void InsertModlogRecords(IEnumerable<ModAction> log) { using (var db = CreateConnection()) using (var sql = db.CreateCommand()) { /* "description" : null, "mod_id36" : "8937y", "created_utc" : 1448759942.0, "subreddit" : null, "target_permalink" : "/r/politics/comments/3ulxdn/xxxxxxxxxxxxxxxxxxxxxxxxxxxx/yyyyyyyy", "details" : "confirm_ham", "action" : "approvecomment", "target_author" : "xxxxxxx", "target_fullname" : "t1_cxfw7gj", "sr_id36" : "2cneq", "id" : "ModAction_2d05ebaa-9637-11e5-876e-0e44750760a5", "mod" : "xxxxxx" */ db.Open(); sql.CommandText = @"INSERT INTO modlog (description,mod_id36,created_utc,subreddit,target_permalink, details,modaction,target_author,target_fullname,sr_id36, redditId, mod) Values (@description,@mod_id36,@created_utc,@subreddit,@target_permalink, @details,@modaction,@target_author,@target_fullname,@sr_id36, @redditId, @mod;"; var parameters = new Dictionary<string, object>(); foreach (var action in log.Take(500)) { parameters.Add("@description", ""); parameters.Add("@mod_id36", ""); parameters.Add("@created_utc", action.TimeStamp.Value.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss")); parameters.Add("@subreddit", Config.RedditSubreddit); parameters.Add("@target_permalink", action.TargetThing.Shortlink); parameters.Add("@details", action.Details); parameters.Add("@modaction", action.Action); parameters.Add("@target_author", action.TargetAuthor); parameters.Add("@target_fullname", action.TargetThingFullname); parameters.Add("@sr_id36", ""); parameters.Add("@redditId", action.Id); parameters.Add("@mod", action.ModeratorName); foreach (var item in parameters) { var x = sql.CreateParameter(); x.ParameterName = item.Key; x.Value = item.Value; } sql.Prepare(); sql.ExecuteNonQuery(); } db.Close(); } }
public static void SetPixels(this IPixelRenderer renderer, IEnumerable<Color> pixels) { var rgbs = pixels .Take(renderer.PixelCount) .Select(ToRgb) .ToArray() ; renderer.SetPixels(rgbs); }
private IEnumerable<string> ApplyCapitalization(IEnumerable<string> words) { switch (CapitalizationScheme) { case Capitalization.PascalCase: return words.Select(CapitalizeFirstLetter); case Capitalization.CamelCase: return words.Take(1).Select(DecapitalizeFirstLetter).Concat(words.Skip(1).Select(CapitalizeFirstLetter)); case Capitalization.FirstUpper: return words.Take(1).Select(CapitalizeFirstLetter).Concat(words.Skip(1).Select(DecapitalizeFirstLetter)); case Capitalization.AllUpper: return words.Select(w => w.ToUpper()); case Capitalization.AllLower: return words.Select(w => w.ToLower()); default: throw new InvalidOperationException(); } }
public DescriptionAttributeAnnotationBase(AnnotationType annotationType, QualifiedSelection qualifiedSelection, VBAParser.AnnotationContext context, IEnumerable <string> attributeValues) : base(annotationType, qualifiedSelection, context, attributeValues?.Take(1).ToList()) { Description = AttributeValues?.FirstOrDefault(); if ((Description?.StartsWith("\"") ?? false) && Description.EndsWith("\"")) { // strip surrounding double quotes Description = Description.Substring(1, Description.Length - 2); } }
public StatusesModel(IEnumerable <Status> list, MessageService messageService) : base(list?.Take(0x20).Select((x, i) => new StatusModel(i, x, messageService))) { for (int i = this.list.Count; i < 0x20; i++) { this.list.Add(new StatusModel(i, new Status(), messageService)); } Messages = messageService.Tags; this.messageService = messageService; }
public IEnumerable <Component> GetComponentsByModule(string domainId, int moduleId, int snapshotId, string businessCriteria, int count) { IEnumerable <Component> res = null; if (businessCriteria == "60016") { res = TestUtility.GetSampleResult <Component>(@".\Data\Component60016ModSnap.json").ToList(); } if (count != -1) { res = res?.Take(count); } return(res); }
public IEnumerable <Transaction> GetTransactions(string snapshotHref, string businessCriteria, int count) { IEnumerable <Transaction> res = null; if (businessCriteria == "60016") { res = TestUtility.GetSampleResult <Transaction>(@".\Data\Transactions60016Snap.json").ToList(); } if (count != -1) { res = res?.Take(count); } return(res); }
protected FlexibleAttributeValueAnnotationBase(AnnotationType annotationType, QualifiedSelection qualifiedSelection, VBAParser.AnnotationContext context, IEnumerable <string> parameters) : base(annotationType, qualifiedSelection, context) { var flexibleAttributeValueInfo = FlexibleAttributeValueInfo(annotationType); if (flexibleAttributeValueInfo == null) { Attribute = string.Empty; AttributeValues = new List <string>(); return; } Attribute = flexibleAttributeValueInfo.Value.attribute; AttributeValues = parameters?.Take(flexibleAttributeValueInfo.Value.numberOfValues).ToList() ?? new List <string>(); }
public override void ExecuteCmdlet() { if (this.Dataset != null) { this.DatasetId = this.Dataset.Id; } if (this.Workspace != null) { this.WorkspaceId = this.Workspace.Id; } IEnumerable <Table> tables = null; using (var client = this.CreateClient()) { if (this.WorkspaceId != default) { tables = client.Datasets.GetTables(this.DatasetId, this.WorkspaceId); } else { tables = client.Datasets.GetTables(this.DatasetId); } } if (!string.IsNullOrEmpty(this.Name)) { tables = tables?.Where(d => d.Name.Equals(this.Name, StringComparison.OrdinalIgnoreCase)); } if (this.Skip.HasValue) { tables = tables?.Skip(this.Skip.Value); } if (this.First.HasValue) { tables = tables?.Take(this.First.Value); } this.Logger.WriteObject(tables, true); }
protected TelemetryDataClientBase( ITracer tracer, IHttpClientWrapper httpClientWrapper, ICredentialsFactory credentialsFactory, IExtendedAzureResourceManagerClient azureResourceManagerClient, string queryUriFormat, TimeSpan queryTimeout, string telemetryDbType, IEnumerable <string> telemetryResourceIds) { this.tracer = Diagnostics.EnsureArgumentNotNull(() => tracer); this.httpClientWrapper = Diagnostics.EnsureArgumentNotNull(() => httpClientWrapper); this.credentialsFactory = Diagnostics.EnsureArgumentNotNull(() => credentialsFactory); this.AzureResourceManagerClient = Diagnostics.EnsureArgumentNotNull(() => azureResourceManagerClient); this.queryUriFormat = Diagnostics.EnsureStringNotNullOrWhiteSpace(() => queryUriFormat); this.Timeout = Diagnostics.EnsureArgumentInRange(() => queryTimeout, TimeSpan.FromMinutes(0), TimeSpan.FromHours(2)); this.telemetryDbType = telemetryDbType; int maximumNumberOfTelemetryResources = int.Parse(ConfigurationManager.AppSettings["MaximumNumberOfTelemetryResources"] ?? "300", CultureInfo.InvariantCulture); this.TelemetryResourceIds = telemetryResourceIds?.Take(maximumNumberOfTelemetryResources).ToList() ?? new List <string>(); this.retryPolicy = PolicyExtensions.CreateTransientHttpErrorPolicy(this.tracer, this.telemetryDbType); }
public override void ExecuteCmdlet() { if (this.Workspace != null) { this.WorkspaceId = this.Workspace.Id; } if (this.Id != default) { this.Filter = $"id eq '{this.Id}'"; } if (this.Name != default) { this.Filter = $"tolower(name) eq '{this.Name.ToLower()}'"; } IEnumerable <Report> reports = null; using (var client = this.CreateClient()) { if (this.WorkspaceId != default) { reports = this.Scope == PowerBIUserScope.Individual ? client.Reports.GetReportsForWorkspace(this.WorkspaceId) : client.Reports.GetReportsAsAdminForWorkspace(this.WorkspaceId, filter: this.Filter, top: this.First, skip: this.Skip); } else { reports = this.Scope == PowerBIUserScope.Individual ? client.Reports.GetReports() : client.Reports.GetReportsAsAdmin(filter: this.Filter, top: this.First, skip: this.Skip); } } // Bug in OData filter for ID, workaround is to use LINQ if (this.Id != default) { reports = reports?.Where(r => this.Id == r.Id); } if (this.Scope == PowerBIUserScope.Individual) { if (!string.IsNullOrEmpty(this.Name)) { reports = reports?.Where(r => r.Name.Equals(this.Name, StringComparison.OrdinalIgnoreCase)); } if (this.Skip.HasValue) { reports = reports?.Skip(this.Skip.Value); } if (this.First.HasValue) { reports = reports?.Take(this.First.Value); } } this.Logger.WriteObject(reports, true); }
public static ReadOnlyMemory <T> TakeReadOnlyMemory <T>(this IEnumerable <T> src, int length) => src.Take(length).ToMemory();
static void Main(string[] args) { CS2Patcher cs2Patch = new CS2Patcher { InstallDir = @"C:\Programs\Games\Frontwing\Eden of Grisaia - Copy (2)", }; Console.WriteLine(cs2Patch.Patch()); Console.WriteLine("FINISHED"); Console.ReadLine(); /*Stopwatch buf1w = new Stopwatch(); * Stopwatch buf2w = new Stopwatch(); * const int maxSize = 64 * 64 * 2; * IntPtr src = Marshal.AllocHGlobal(maxSize); * IntPtr dst = Marshal.AllocHGlobal(maxSize); * for (int i = 1; i <= 64; i++) { * int size = i * i; * * for (int j = 0; j < 10000; j++) { * Buffer.MemoryCopy(src.ToPointer(), dst.ToPointer(), size, size); * Buffer451.MemoryCopy(src.ToPointer(), dst.ToPointer(), size, size); * } * } * for (int i = 1; i <= 64; i++) { * int size = i * i; * * for (int j = 0; j < 100000; j++) { * buf1w.Start(); * Buffer.MemoryCopy(src.ToPointer(), dst.ToPointer(), size, size); * buf1w.Stop(); * buf2w.Start(); * Buffer451.MemoryCopy(src.ToPointer(), dst.ToPointer(), size, size); * buf2w.Stop(); * } * } * Marshal.FreeHGlobal(src); * Marshal.FreeHGlobal(dst); * Console.WriteLine(buf1w.ElapsedMilliseconds); * Console.WriteLine(buf2w.ElapsedMilliseconds); * byte[] src2 = new byte[maxSize]; * byte[] dst2 = new byte[maxSize]; * buf1w.Restart(); * buf2w.Restart(); * for (int i = 1; i <= 64; i++) { * int size = i * i; * * for (int j = 0; j < 10000; j++) { * Buffer.BlockCopy(src2, 0, dst2, 0, size); * Array.Copy(src2, 0, dst2, 0, size); * } * } * for (int i = 1; i <= 64; i++) { * int size = i * i; * * for (int j = 0; j < 500000; j++) { * buf1w.Start(); * Buffer.BlockCopy(src2, 0, dst2, 0, size); * buf1w.Stop(); * buf2w.Start(); * Array.Copy(src2, 0, dst2, 0, size); * buf2w.Stop(); * } * } * Console.WriteLine(buf1w.ElapsedMilliseconds); * Console.WriteLine(buf2w.ElapsedMilliseconds); * Console.ReadLine();*/ JsonTest jtest = new JsonTest(""); jtest.A = 100; jtest.B = 200; string json = JsonConvert.SerializeObject(jtest, Formatting.Indented); JsonTest jtest2 = JsonConvert.DeserializeObject <JsonTest>(json); string rawPath = @"C:\Users\Onii-chan\Pictures\Sprites\Grisaia\Cs2\Raw2"; string hg3Path = @"C:\Users\Onii-chan\Pictures\Sprites\Grisaia\Cs2\Hg3"; string outputPath = @"C:\Users\Onii-chan\Pictures\Sprites\Grisaia\Cs2\Output2"; string outputPath2 = @"C:\Users\Onii-chan\Pictures\Sprites\Grisaia\Cs2\Output3"; string outputExpandPath = @"C:\Users\Onii-chan\Pictures\Sprites\Grisaia\Cs2\OutputExpand"; string output1 = "hg3-1"; string output2 = "hg3-2"; Directory.CreateDirectory(output1); Directory.CreateDirectory(output2); int hg3Index = 0; Console.Write($"\r{hg3Index}"); //HgxImage.Extract(@"C:\Programs\Tools\CatSystem2_v401\tool\img_flipped.hg3"); var hg3Cs2Files = Directory.EnumerateFiles(rawPath, "*.hg3"); //.SkipWhile(s => !s.EndsWith("click.hg3")); Stopwatch hwatch = new Stopwatch(); Stopwatch hwatch2 = new Stopwatch(); /*foreach (string file in hg3Cs2Files) { * Console.Write($"\r{hg3Index++}"); * hwatch.Start(); * HgxImage hg3Image = HgxImage.ExtractImages(file, outputPath, HgxOptions.None); * hwatch.Stop(); * hwatch2.Start(); * using (var stream = File.OpenRead(file)) { * HgxImage hg3Image2 = HgxImage.Extract(stream, file); * hg3Image2.ExtractImages(stream, outputPath2, HgxOptions.None); * } * hwatch2.Stop(); * //hg3Image = HgxImage.ExtractImages(file, outputExpandPath, HgxOptions.Expand); * //hg3Image.SaveJsonToDirectory(hg3Path); * }*/ Console.WriteLine($"\r{hg3Index}"); Console.WriteLine(hwatch.ElapsedMilliseconds); hwatch.Reset(); Console.WriteLine(hwatch2.ElapsedMilliseconds); hwatch2.Reset(); string grisaiaInstallDir = @"C:\Programs\Games\Frontwing\The Fruit of Grisaia"; string grisaiaExe = Path.Combine(grisaiaInstallDir, "Grisaia.exe"); string grisaiaConfigInt = Path.Combine(grisaiaInstallDir, "config.int"); VCodes grisaiaVCodes = VCodes.Load(grisaiaExe); KifintLookup lookup = KifintArchive.LoadLookup(KifintType.Image, grisaiaInstallDir, grisaiaVCodes.VCode2); CatDebug.SpeedTestHgx = true; using (KifintStream kifintStream = new KifintStream()) { lookup["sys_mwnd03.hg3"].ExtractToFile("sys_mwnd03.hg3"); hg3Index = 0; int top = Console.CursorTop; Console.CursorVisible = false; /*Console.WriteLine($"\r{hg3Index}"); * Console.WriteLine(hwatch.ElapsedMilliseconds); hwatch.Reset(); * Console.WriteLine(hwatch2.ElapsedMilliseconds); hwatch2.Reset();*/ foreach (KifintEntry entry in lookup) { if (entry.Extension != ".hg3") { continue; } hwatch.Start(); HgxImage hg3Image = entry.ExtractHgxAndImages(kifintStream, output1, HgxOptions.None); hwatch.Stop(); hwatch2.Start(); using (var stream = entry.ExtractToStream(kifintStream)) { HgxImage hg3Image2 = entry.ExtractHgx(kifintStream); hg3Image2.ExtractImages(stream, output2, HgxOptions.None); } hwatch2.Stop(); //if (hg3Index % 25 == 0) { Console.WriteLine($"\r{hg3Index++}"); Console.WriteLine(hwatch.ElapsedMilliseconds); Console.Write(hwatch2.ElapsedMilliseconds); Console.CursorTop = top; /*} * else { * Console.Write($"\r{hg3Index++}"); * }*/ } Console.CursorVisible = true; } Console.WriteLine($"\r{hg3Index}"); Console.WriteLine(hwatch.ElapsedMilliseconds); hwatch.Reset(); Console.WriteLine(hwatch2.ElapsedMilliseconds); hwatch2.Reset(); Console.WriteLine("FINISHED"); Console.ReadLine(); var screen = FesScreen.Extract(@"C:\Users\Onii-chan\Source\C#\TriggersTools\CatSystem2\samples\CatTesting\bin\Debug\fcgview.fes"); var screen2 = FesScreen.Extract(@"C:\Programs\Tools\CatSystem2_v401\system\fes\cgview.fes"); //SceneScript.DecompileToFile(@) string vc2 = string.Empty; Stopwatch watchNative = new Stopwatch(); Stopwatch watchManaged = new Stopwatch(); Stopwatch watchManaged2 = new Stopwatch(); VCodes vcodes = VCodes.Load(@"C:\Programs\Games\Frontwing\Labyrinth of Grisaia - Copy (2)\Grisaia2.bin.bak"); /*using (var stream = File.OpenRead("config.fes")) { * byte[] dat = new byte[20]; * stream.Position = stream.Length - 1; * BinaryReader reader = new BinaryReader(stream); * Console.WriteLine(stream.Read(dat, 0, dat.Length)); * Console.WriteLine(stream.Read(dat, 0, dat.Length)); * stream.Position = stream.Length - 1; * reader.ReadUInt16(); * Console.ReadLine(); * }*/ vc2 = vcodes.VCode2; /*for (int i = 0; i < 100000; i++) { * CatDebug.NativeBlowfish = true; * watchNative.Start(); * vc2 = vcodes.VCode2; * watchNative.Stop(); * CatDebug.NativeBlowfish = false; * CatDebug.ManagedBlowfishRound = true; * watchManaged.Start(); * vc2 = vcodes.VCode2; * watchManaged.Stop(); * CatDebug.ManagedBlowfishRound = false; * watchManaged2.Start(); * vc2 = vcodes.VCode2; * watchManaged2.Stop(); * } * Console.WriteLine(watchNative.ElapsedMilliseconds); * Console.WriteLine(watchManaged.ElapsedMilliseconds); * Console.WriteLine(watchManaged2.ElapsedMilliseconds);*/ string kajitsuDir = @"C:\Programs\Games\Frontwing\The Fruit of Grisaia"; string kajitsuExe = "Grisaia.exe"; VCodes kajitsoVCodes = VCodes.Load(Path.Combine(kajitsuDir, kajitsuExe)); string hg3Key = "bg15n_d.hg3"; KifintLookup images = KifintArchive.LoadLookup(KifintType.Image, kajitsuDir, kajitsoVCodes.VCode2); Stopwatch watch1 = new Stopwatch(); Stopwatch watch2 = new Stopwatch(); Directory.CreateDirectory("hg3"); CatDebug.SpeedTestHgx = true; CatDebug.NativeBlowfish = true; //var entr = images[hg3Key]; Stopwatch w1 = new Stopwatch(); Stopwatch w2 = new Stopwatch(); using (KifintStream kifintStream = new KifintStream()) { int index = 0; foreach (var entry in images.Take(25)) { //if (entry.Length < 100000) // continue; if (entry.Extension != ".hg3") { continue; } //if (entry.FileNameWithoutExtension != "yum011a") // continue; //if (index % 25 == 0) // Console.Write($"\r{index}"); //index++; //int loops = 1;// Math.Max(Math.Min(2000, 5 * 26000000 / entry.Length), 5); //Console.WriteLine($"{entry} Loops={loops}"); CatDebug.StreamExtract = false; //w1.Start(); //for (int i = 0; i < loops; i++) entry.ExtractHgxAndImages(kifintStream, "hg3", HgxOptions.None); //.CopyTo(Stream.Null); //w1.Stop(); //Console.WriteLine($"Extract: {w.ElapsedMilliseconds}ms"); CatDebug.StreamExtract = true; //w2.Start(); //for (int i = 0; i < loops; i++) entry.ExtractHgxAndImages(kifintStream, "hg3", HgxOptions.None); //.CopyTo(Stream.Null); //w2.Stop(); //Console.WriteLine($" Stream: {w.ElapsedMilliseconds}ms"); //Console.WriteLine(); //Thread.Sleep(1000); } foreach (var entry in images) { //if (entry.Length < 100000) // continue; if (entry.Extension != ".hg3") { continue; } //if (entry.FileNameWithoutExtension != "yum011a") // continue; if (index % 25 == 0) { Console.Write($"\r{index}"); } index++; int loops = 1; // Math.Max(Math.Min(2000, 5 * 26000000 / entry.Length), 5); //Console.WriteLine($"{entry} Loops={loops}"); CatDebug.StreamExtract = false; w1.Start(); //for (int i = 0; i < loops; i++) entry.ExtractHgxAndImages(kifintStream, "hg3", HgxOptions.None); //.CopyTo(Stream.Null); w1.Stop(); //Console.WriteLine($"Extract: {w.ElapsedMilliseconds}ms"); CatDebug.StreamExtract = true; w2.Start(); //for (int i = 0; i < loops; i++) entry.ExtractHgxAndImages(kifintStream, "hg3", HgxOptions.None); //.CopyTo(Stream.Null); w2.Stop(); //Console.WriteLine($" Stream: {w.ElapsedMilliseconds}ms"); //Console.WriteLine(); //Thread.Sleep(1000); } Console.WriteLine($"\r{index}"); Console.WriteLine($"Extract: {w1.ElapsedMilliseconds}ms"); Console.WriteLine($" Stream: {w2.ElapsedMilliseconds}ms"); } /*for (int j = 0; j < 4; j++) { * CatDebug.ManagedBlowfishRound = true; * watch1.Reset(); * watch2.Reset(); * for (int i = 0; i < 6; i++) { * watch1.Start(); * imageLookup[hg3Key].ExtractHg3AndImages("hg3", HgxOptions.None); * watch1.Stop(); * watch2.Start(); * using (var stream = KifintArchive.ExtractToStream(new KifintStream(), imageLookup[hg3Key])) * HgxImage.ExtractImages(stream, hg3Key, "hg3", HgxOptions.None); * watch2.Stop(); * } * Console.WriteLine(watch1.ElapsedMilliseconds); * Console.WriteLine(watch2.ElapsedMilliseconds); * CatDebug.ManagedBlowfishRound = false; * watch1.Reset(); * watch2.Reset(); * for (int i = 0; i < 6; i++) { * watch1.Start(); * imageLookup[hg3Key].ExtractHg3AndImages("hg3", HgxOptions.None); * watch1.Stop(); * watch2.Start(); * using (var stream = KifintArchive.ExtractToStream(new KifintStream(), imageLookup[hg3Key])) * HgxImage.ExtractImages(stream, hg3Key, "hg3", HgxOptions.None); * watch2.Stop(); * } * Console.WriteLine(watch1.ElapsedMilliseconds); * Console.WriteLine(watch2.ElapsedMilliseconds); * }*/ images = null; Console.ReadLine(); using (KifintStream kifintStream = new KifintStream()) { KifintLookup movies; //CatDebug.NativeBlowfish = true; CatDebug.ManagedBlowfishRound = true; movies = KifintArchive.LoadLookup(KifintType.Movie, @"C:\Programs\Games\Frontwing\Labyrinth of Grisaia", vc2); GC.Collect(); watchNative.Restart(); foreach (KifintEntry movie in movies) { //movie.ExtractToFile(kifintStream, "mov.mpg"); movie.ExtractToBytes(kifintStream); } Console.WriteLine(watchNative.ElapsedMilliseconds); //CatDebug.NativeBlowfish = true; CatDebug.ManagedBlowfishRound = false; movies = KifintArchive.LoadLookup(KifintType.Movie, @"C:\Programs\Games\Frontwing\Labyrinth of Grisaia", vc2); GC.Collect(); watchNative.Restart(); foreach (KifintEntry movie in movies) { //movie.ExtractToFile(kifintStream, "mov.mpg"); movie.ExtractToBytes(kifintStream); } Console.WriteLine(watchNative.ElapsedMilliseconds); //CatDebug.NativeBlowfish = false; CatDebug.ManagedBlowfishRound = false; movies = KifintArchive.LoadLookup(KifintType.Movie, @"C:\Programs\Games\Frontwing\Labyrinth of Grisaia", vc2); GC.Collect(); watchManaged.Restart(); foreach (KifintEntry movie in movies) { //movie.ExtractToFile(kifintStream, "mov.mpg"); movie.ExtractToBytes(kifintStream); } Console.WriteLine(watchManaged.ElapsedMilliseconds); /*CatDebug.NativeBlowfish = true; * movies = KifintArchive.LoadLookup(KifintType.Movie, @"C:\Programs\Games\Frontwing\Labyrinth of Grisaia", vc2); * GC.Collect(); * watchNative.Restart(); * foreach (KifintEntry movie in movies) { * using (var fs = File.Create("mov.mpg")) * KifintArchive.ExtractToStream(kifintStream, movie, fs); * } * Console.WriteLine(watchNative.ElapsedMilliseconds); * * CatDebug.NativeBlowfish = false; * movies = KifintArchive.LoadLookup(KifintType.Movie, @"C:\Programs\Games\Frontwing\Labyrinth of Grisaia", vc2); * GC.Collect(); * watchManaged.Restart(); * foreach (KifintEntry movie in movies) { * using (var fs = File.Create("mov.mpg")) * KifintArchive.ExtractToStream(kifintStream, movie, fs); * } * Console.WriteLine(watchManaged.ElapsedMilliseconds); * GC.Collect();*/ } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Console.WriteLine("FINISHED"); Console.ReadLine(); Random random = new Random(); const int rngLength = 1024 * 64; byte[] rngBytesOrigin = new byte[rngLength]; byte[] rngBytes = new byte[rngLength]; byte[] rngUints = new byte[rngLength]; byte[] rngBytesAdd = new byte[rngLength]; random.NextBytes(rngBytesOrigin); random.NextBytes(rngBytesAdd); Buffer.BlockCopy(rngBytesOrigin, 0, rngBytes, 0, rngLength); Buffer.BlockCopy(rngBytesOrigin, 0, rngUints, 0, rngLength); unchecked { unsafe { fixed(byte *pRngBytesAdd = rngBytesAdd) fixed(byte *pRngBytes = rngUints) { uint *pRngUintsAdd = (uint *)pRngBytesAdd; uint *pRngUints = (uint *)pRngBytes; for (int i = 0; i < rngLength / 4; i++) { pRngUints[i] += pRngUintsAdd[i]; } /*for (int i = 0; i < rngLength; i++) { * pRngBytes[i] += pRngBytesAdd[i]; * }*/ } for (int i = 0; i < rngLength; i++) { rngBytes[i] += rngBytesAdd[i]; } } } /*for (int i = 0; i < rngLength; i++) { * if (rngBytes[i] != rngUints[i]) * Console.WriteLine(i); * }*/ bool isEqual = rngBytes.SequenceEqual(rngUints); /*string vcode22 = VCodes.FindVCode2(@"C:\Programs\Games\Frontwing\Labyrinth of Grisaia - Copy (2)\Grisaia2.bin.bak"); * Kifint.DecryptLookup(KifintType.Image, @"C:\Programs\Games\Frontwing\Labyrinth of Grisaia", vcode22); * Kifint.DecryptLookup(KifintType.Image, @"C:\Programs\Games\Frontwing\Labyrinth of Grisaia", vcode22, csBlowfish: true); * var ll = Kifint.DecryptLookup(KifintType.Image, @"C:\Programs\Games\Frontwing\Labyrinth of Grisaia", vcode22); * var lll = Kifint.DecryptLookup(KifintType.Image, @"C:\Programs\Games\Frontwing\Labyrinth of Grisaia", vcode22, csBlowfish: true); * for (int i = 0; i < ll.Count; i++) { * * }*/ Directory.CreateDirectory("img2"); Directory.CreateDirectory("imgv"); Directory.CreateDirectory("imgnv"); HgxImage.ExtractImages("sys_flipped.hg3", "imgv", HgxOptions.Flip).SaveJsonToDirectory("imgv"); HgxImage.ExtractImages("sys_flipped.hg3", "imgnv", HgxOptions.None).SaveJsonToDirectory("imgnv"); //HgxImage.ExtractImages("img_flipped.hg3", "img2", HgxOptions.None).SaveJsonToDirectory("img2"); //HgxImage.ExtractImages("img_notflipped.hg3", "img2", HgxOptions.None).SaveJsonToDirectory("img2"); Console.ReadLine(); Directory.CreateDirectory("img"); IEnumerable <string> hg3Files = Directory.GetFiles(@"C:\Programs\Games\Frontwing\Labyrinth of Grisaia - Copy (2)\image", "*.hg3"); //hg3Files = hg3Files.Take(100); int take = 100; try { foreach (string hg3File in hg3Files.Take(10)) { HgxImage.ExtractImages(hg3File, "img", HgxOptions.None); } /*Stopwatch hg3Watch = HgxImage.ProcessImageWatch; hg3Watch.Reset(); * for (int i = 0; i < 10; i++) { * foreach (string hg3File in hg3Files.Take(take)) * HgxImage.ExtractImages(hg3File, "img", false); * Console.WriteLine(hg3Watch.ElapsedMilliseconds); hg3Watch.Reset(); * }*/ } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(ex); } Console.ReadLine(); Environment.Exit(0); HgxImage.ExtractImages(@"C:\Programs\Tools\CatSystem2_v401\tool\img_test2.hg3", ".", HgxOptions.None); //StringsScraper.BinaryScrape("cs2_open.exe", "strings/null/cs2", 0x5B6458, 0x5B7558); Console.ReadLine(); //StringsScraper.BinarySearch("cs2_open.exe", "page"); //foreach (string file in Directory.GetFiles(@"C:\Programs\Tools\CatSystem2_v401\system\scene", "*.cst")) { foreach (string file in Directory.GetFiles(@"C:\Programs\Games\Frontwing\Labyrinth of Grisaia - Copy (2)\scene", "*.cst")) { CstScene scene2 = CstScene.Extract(file); foreach (ISceneLine line in scene2) { if (line.Type == SceneLineType.Page) { Console.WriteLine(file); } } } Console.Write("FINISHED"); Console.ReadLine(); /*using (FileStream fp = File.OpenRead("mc.exe")) { * BinaryReader reader = new BinaryReader(fp); * while (!fp.IsEndOfStream()) { * ushort type = reader.ReadUInt16(); * if (type == 0x0301) { * Console.WriteLine($"{fp.Position:X8}"); * } * } * }*/ //byte[] data = File.ReadAllBytes("mc.exe"); //for (int i = 0; i <) //StringsScraper.BinarySearch("mc.exe", "page"); CstScene scene = CstScene.Extract(@"C:\Programs\Games\Frontwing\Labyrinth of Grisaia - Copy (2)\scene\ama_006.cst"); foreach (ISceneLine line in scene) { if (line.Type == SceneLineType.Command) { var command = (ISceneCommand)line; } } //var h = LoadLibrary(@"C:\Users\Onii-chan\AppData\Local\Temp\TriggersToolsGames\CatSystem2\asmodean.dll"); //Embedded var hg3 = HgxImage.ExtractImages(@"C:\Programs\Tools\CatSystem2_v401\system\image\sys_confirm.hg3", ".", HgxOptions.None); grisaiaInstallDir = @"C:\Programs\Games\Frontwing\Labyrinth of Grisaia - Copy (2)"; grisaiaExe = Path.Combine(grisaiaInstallDir, "Grisaia2.bin.bak"); grisaiaConfigInt = Path.Combine(grisaiaInstallDir, "config.int"); grisaiaVCodes = VCodes.Load(grisaiaExe); //KifintLookup lookup = Kifint.DecryptLookup(KifintType.Config, grisaiaInstallDir, grisaiaVCodes.VCode2); //lookup["startup.xml"].ExtractToFile("startup2.xml"); /*File.Copy("startup2.xml", "startup.xml", true); * var patcher = new ResolveXmlCommentErrorsPatch("startup.xml"); * var patcher2 = new CS2XmlDebugPatch("startup.xml", true, "TriggersTools.CatSystem2.Patcher.Resources.CS2"); * patcher.Patch(); * patcher2.Patch(); * Console.WriteLine("FINISHED"); * Console.ReadLine(); * for (int i = 0; i < 10; i++) { * Stopwatch swatch = Stopwatch.StartNew(); * //var vcodes = VCodes.Load(@"C:\Programs\Games\Frontwing\Labyrinth of Grisaia - Copy (2)\Grisaia2.bin"); * string exeFile = CatUtils.FindCatExecutable(@"C:\Programs\Games\Frontwing\Labyrinth of Grisaia - Copy (2)"); * Console.WriteLine(swatch.ElapsedMilliseconds); * Console.WriteLine(exeFile ?? string.Empty); * } * Console.ReadLine();*/ //vcodes.Save(@"C:\Programs\Games\Frontwing\Labyrinth of Grisaia - Copy (2)\Grisaia2.bin"); //File.WriteAllText("vcodes.json", JsonConvert.SerializeObject(vcodes, Formatting.Indented)); //vcodes.KeyCode = vcodes.KeyCode; //vcodes.KeyCode = new byte[4] { 0x1, 0x1, 0x1, 0x1 }; Console.Beep(); Console.ReadLine(); using (var ms = new MemoryStream()) { BinaryReader reader = new BinaryReader(ms); BinaryWriter writer = new BinaryWriter(ms); writer.Write(1); ms.Position = 0; byte[] buffer = reader.ReadBytes(4); int[] ints = new int[1]; Buffer.BlockCopy(buffer, 0, ints, 0, 4); Console.WriteLine(ints[0]); } //ushort us = 1; byte[] bs = { 1, 0 }; byte[] decompressedA; //byte[] decompressedB; //344AC //@"C:\Programs\Tools\CatSystem2_v401\psds\BA01_1.hg2" Directory.CreateDirectory("hg3"); HgxImage.Extract(@"C:\Programs\Tools\CatSystem2_v401\tool\img_test2.hg3"); HgxImage.Extract(@"C:\Programs\Tools\CatSystem2_v401\psds\sys_confirm.hg2"); var hg3Img = HgxImage.ExtractImages(@"C:\Programs\Tools\CatSystem2_v401\psds\BA01_1.hg3", "hg3", HgxOptions.None); hg3Img.SaveJsonToDirectory("hg3"); Console.OutputEncoding = CatUtils.ShiftJIS; /*ZTPatcher zt2 = new ZTPatcher { * InstallDir = ".", * }; * zt2.Patch(); * WGCPatcher wgc2 = new WGCPatcher { * InstallDir = ".", * }; * wgc2.Patch();*/ Console.ReadLine(); string[] lines = File.ReadAllLines("strings/wgc/binary.txt"); //StringsScraper.BinaryValidate(lines); Console.ReadLine(); lines = File.ReadAllLines("strings/zt/binary.txt"); //StringsScraper.BinaryValidate(lines); Console.ReadLine(); //StringsScraper.BinarySearch("WGC.exe", "img_jpg");//256C28, 256C8C Console.ReadLine(); /*BinaryRange[] rangess = { * new BinaryRange(0x211DD4, 0x211DEC), * new BinaryRange(0x211E54, 0x211FA8), * new BinaryRange(0x212078, 0x212138), * new BinaryRange(0x212154, 0x2121A0), * new BinaryRange(0x2122F0, 0x212204), * new BinaryRange(0x212304, 0x2123C4), * new BinaryRange(0x2123D8, 0x2123F4), * new BinaryRange(0x21C300, 0x21C31C), * * new BinaryRange(0x25BAF8, 0x25BD20), * new BinaryRange(0x25BD60, 0x25BD90), * new BinaryRange(0x25BDD0, 0x25BDF4), * new BinaryRange(0x25BE90, 0x25BFC0), * new BinaryRange(0x25C00C, 0x25C118), * }; * StringsScraper.BinaryScrape("WGC.exe", "strings/wgc", rangess); //2120A0 * * Console.ReadLine(); * StringsScraper.BinaryScrape("ztpack.exe", "strings/zt", 0x344AC, 0x345F8);*/ Console.ReadLine(); /*var resInfo = new ResourceInfo("cs2_open_en.exe"); * File.Copy("cs2_open_en.exe", "cs2_open_en2.exe", true); * Thread.Sleep(400); * resInfo.Save("cs2_open_en2.exe"); * var menuRes = new MenuResource("cs2_open.exe", 105, 1041); * var dialogRes = new DialogResource("cs2_open.exe", 201, 1041); * var menu = (MenuTemplate) menuRes.Template; * var dialog = (DialogExTemplate) dialogRes.Template; * dialog.Caption = "Hello World!"; * dialog.Controls[0].CaptionId = "OK WORLD!"; * dialog.Controls[1].HelpId = 25; * menu.MenuItems[0].MenuString = "Hello World!"; * menu.MenuItems.Add(new MenuTemplateItemPopup { * MenuString = "Popup", * MenuItems = { * new MenuTemplateItemCommand { * IsSeparator = true, * }, * new MenuTemplateItemCommand { * MenuString = "Do Nothing", * MenuId = 2555, * }, * }, * }); * //IntPtr ptr = Marshal.StringToHGlobalUni(null); * //File.Copy("cs2_open.exe", "cs2_open2.exe", true); * Thread.Sleep(400); * Resource.SaveTo("cs2_open_en2.exe", new Resource[] { menuRes, dialogRes });*/ /*CS2Patcher cs2Patcher = new CS2Patcher { * InstallDir = ".", * }; * Console.WriteLine(cs2Patcher.Patch()); * Console.WriteLine("FINISHED"); * WGCPatcher wgc = new WGCPatcher { * InstallDir = ".", * }; * Console.WriteLine(wgc.Patch()); * Console.WriteLine("FINISHED"); * Console.ReadLine();*/ //ResourceInfo reInfo = new ResourceInfo(); //reInfo.Load(@"C:\Programs\Games\Frontwing\Labyrinth of Grisaia - Copy (2)\Grisaia2.bin.bak"); //Console.Write(""); /*PsDotNet * /*using (var s = File.OpenRead(@"C:\Programs\Tools\CatSystem2_v401\psds\CS2用_キャラクター立ち絵2.psd")) { * BinaryReverseReader2 reader = new BinaryReverseReader2(s); * while (!s.IsEndOfStream()) { * int sh = reader.ReadInt32(); * if (sh == 930) * Console.WriteLine($"{s.Position:X8}"); * } * }*/ /* Console.OutputEncoding = CatUtils.ShiftJIS; * Document psd = new Document(@"C:\Programs\Tools\CatSystem2_v401\psds\CS2用_キャラクター立ち絵.psd"); * psd.SaveXml("psd.xml", false); * foreach (var layer in psd.Layers) { * Console.WriteLine(layer.Name); * }*/ //Document psd2 = new Document(@"C:\Programs\Tools\CatSystem2_v401\tool\img_test.psd"); //psd2.SaveXml("psd.xml", false); //Document psd2 = new Document(@"C:\Programs\Tools\CatSystem2_v401\tool\img_test.psd"); //StringsScraper.BinarySearch("WGC.exe", "選択されたファイルをリストから"); //StringsScraper.BinaryScrape("WGC.exe", "strings/wgc", 0x211000, 0x212F00); //StringsScraper.BinaryScrape("WGC.exe", "strings/wgc", 0x256000, 0x1000000); //StringsScraper.BinarySearch("WGC.exe", "mode");//21220C //212298 //string vcode = VCodes.FindVCode(@"C:\Programs\Games\Frontwing\Labyrinth of Grisaia - Copy (2)\Grisaia2.bin.bak"); string vcode2 = VCodes.FindVCode2(@"C:\Programs\Games\Frontwing\Labyrinth of Grisaia - Copy (2)\Grisaia2.bin.bak"); var hg = HgxImage.ExtractImages(@"C:\Programs\Tools\CatSystem2_v401\tool\img_test2.hg3", ".", HgxOptions.None); hg = HgxImage.Extract(@"C:\Programs\Tools\CatSystem2_v401\system\image\sys_confirm.hg3"); //int iiii = int.Parse("FFFFFFFF", NumberStyles.HexNumber); hg = HgxImage.Extract(@"C:\Programs\Games\Frontwing\Labyrinth of Grisaia - Copy (2)\image\Tmic1cs_6.hg3"); byte[] zt = File.ReadAllBytes("zt.zt"); /*using (var ms = new MemoryStream()) { * BinaryWriter writer = new BinaryWriter(ms); * writer.Write(zt.Take(0x110).ToArray()); * writer.Write(zt.Skip(0x110).Take(0x194 - 0x110).ToArray()); * ms.Position = 0; * writer.Write(405); * writer.Write(0); * writer.Write() * ms.Position = 404; * writer.Write((byte) 0); * writer.Write(zt.Skip(404).ToArray()); * //ms.Position = 0x110; * //writer.Write(123233); * zt = ms.ToArray(); * }*/ //File.WriteAllBytes("zt2.zt", zt); var ztpackage = ZtPackage.ExtractFiles("zt.zt", "ztout"); Environment.Exit(0); /*using (FileStream fs = File.Create("out.zt")) { * long offset = 0x100000194; * BinaryWriter writer = new BinaryWriter(fs); * writer.Write(zt.Take(0x194).ToArray()); * fs.Position = offset; * writer.Write(zt.Skip(0x194).ToArray()); * }*/ //StringsScraper.BinaryValidate(File.ReadAllLines("strings/cs2/binary_5.txt")); /*CS2Patcher cs2 = new CS2Patcher { * InstallDir = ".", * }; * //Console.WriteLine(cs2.Patch("cs2_open.exe", "cs2_open_en.exe")); * Console.WriteLine(cs2.Patch()); * Console.WriteLine("FINISHED"); * Console.ReadLine();*/ /*using (StreamWriter writer = File.CreateText("ranges_out.txt")) { * List<int> starts = new List<int>(); * List<int> ends = new List<int>(); * Regex regex = new Regex(@"\t\t// 0x(?'start'[A-Fa-f0-9]+), 0x(?'end'[A-Fa-f0-9]+)"); * foreach (string line in File.ReadAllLines("ranges.txt")) { * Match match = regex.Match(line); * if (match.Success) { * starts.Add(int.Parse(match.Groups["start"].Value, NumberStyles.HexNumber)); * ends.Add(int.Parse(match.Groups["end"].Value, NumberStyles.HexNumber)); * if (starts.Last() >= ends.Last()) * throw new Exception(); * } * } * for (int i = 0; i < starts.Count; i++) { * int start1 = starts[i]; * int end1 = ends[i]; * if (start1 >= end1) * throw new Exception(); * for (int j = 0; j < starts.Count; j++) { * if (i == j) * continue; * int start2 = starts[j]; * int end2 = ends[j]; * if (start1 >= start2 && start1 <= end2) * throw new Exception(); * if (end1 >= start2 && end1 <= end2) * throw new Exception(); * } * } * starts.Sort(); * ends.Sort(); * for (int i = 0; i < starts.Count; i++) { * * int start = starts[i]; * int end = ends[i]; * writer.WriteLine($"new BinaryRange(0x{start:X6}, 0x{end:X6}),"); * } * writer.Flush(); * } * Console.WriteLine("FINISHED"); * Console.ReadLine(); * CS2Patcher cs2 = new CS2Patcher { * Executable = "cs2_open.exe", * }; * Console.WriteLine(cs2.Patch()); * Console.WriteLine("FINISHED"); * Console.ReadLine();*/ /*var ranges = new BinaryRange[] { * new BinaryRange(0x58CFA0, 0x58CFC0), * new BinaryRange(0x590960, 0x590B7C), * new BinaryRange(0x590C14, 0x590C38), * new BinaryRange(0x590CA0, 0x590D9C), * new BinaryRange(0x590E14, 0x591120), * new BinaryRange(0x591160, 0x5911BC), * new BinaryRange(0x5911FC, 0x59122C), * new BinaryRange(0x59126C, 0x59144C), * new BinaryRange(0x5914F4, 0x59158C), * new BinaryRange(0x5915E8, 0x59164C), * new BinaryRange(0x5917B0, 0x5917E8), * new BinaryRange(0x591864, 0x591890), * new BinaryRange(0x591944, 0x5919CC), * new BinaryRange(0x5919F0, 0x591AE0), * new BinaryRange(0x591B04, 0x591BA0), * new BinaryRange(0x591BD4, 0x591C64), * new BinaryRange(0x591C88, 0x591D18), * new BinaryRange(0x591D3C, 0x591DD0), * new BinaryRange(0x591FD8, 0x592000), * new BinaryRange(0x5920E8, 0x59211C), * new BinaryRange(0x59259C, 0x59263C), * new BinaryRange(0x5962C4, 0x596334), * new BinaryRange(0x596368, 0x596388), * new BinaryRange(0x5963B8, 0x59645C), * new BinaryRange(0x596638, 0x5967A4), * new BinaryRange(0x596970, 0x596C44), * new BinaryRange(0x596F9C, 0x597334), * new BinaryRange(0x597380, 0x59754C), * new BinaryRange(0x59797C, 0x597AF8), * new BinaryRange(0x597C20, 0x597D84), * new BinaryRange(0x597DB0, 0x597E10), * new BinaryRange(0x597E78, 0x597FB4), * new BinaryRange(0x597FC8, 0x5980EC), * new BinaryRange(0x598130, 0x5981C0), * new BinaryRange(0x598270, 0x598328), * new BinaryRange(0x598370, 0x5988B4), * new BinaryRange(0x598988, 0x598B14), * new BinaryRange(0x598BA8, 0x598C04), * new BinaryRange(0x598DEC, 0x598F20), * new BinaryRange(0x598F34, 0x5990CC), * new BinaryRange(0x599204, 0x599220), * new BinaryRange(0x5992AC, 0x599384), * new BinaryRange(0x5993E0, 0x599470), * new BinaryRange(0x599500, 0x5997C0), * new BinaryRange(0x5AFC20, 0x5AFC48), * new BinaryRange(0x5AFD00, 0x5AFE24), * new BinaryRange(0x5B02EC, 0x5B03D0), * new BinaryRange(0x5B0814, 0x5B0880), * new BinaryRange(0x5B0A48, 0x5B0AAC), * new BinaryRange(0x5B25E8, 0x5B27D0), * new BinaryRange(0x5B2844, 0x5B28DC), * new BinaryRange(0x5B2BC8, 0x5B2BD8), * new BinaryRange(0x5B3480, 0x5B34B8), * new BinaryRange(0x5B3578, 0x5B35B4), * new BinaryRange(0x5B4324, 0x5B4420), * new BinaryRange(0x5B4518, 0x5B4534), * new BinaryRange(0x5B464C, 0x5B4850), * new BinaryRange(0x5B4FB4, 0x5B50D4), * };*/ /*Console.OutputEncoding = CatUtils.ShiftJIS; * StringsScraper.ResourceScrape("cs2_open.exe", "strings/cs2"); * Console.WriteLine("FINISHED"); * Console.ReadLine();*/ //StringsScraper.BinaryScrape("cs2_open.exe", "strings/cs2", ranges); Console.WriteLine("FINISHED"); Console.ReadLine(); //StringsScraper.BinarySearch("cs2_open.exe", "--全て表示--");//596368 //StringsScraper.BinaryScrape("cs2_open.exe", "strings/cs2", 0x596368, 0x596388); // 0x5990E0, 0x5990E4 (?) // 0x599500, 0x5997C0 // 0x5993E0, 0x599470 // 0x5992AC, 0x599384 // 0x599204, 0x599220 // 0x598F34, 0x5990CC // 0x598DEC, 0x598F20 // 0x598BA8, 0x598C04 // 0x598988, 0x598B14 // 0x598370, 0x5988B4 // 0x598270, 0x598328 // 0x598130, 0x5981C0 // 0x597FC8, 0x5980EC // 0x597E78, 0x597FB4 // 0x597DB0, 0x597E10 // 0x597C20, 0x597D84 // 0x59797C, 0x597AF8 // 0x597380, 0x59754C // 0x596F9C, 0x597334 // 0x596970, 0x596C44 // 0x596638, 0x5967A4 // 0x5963B8, 0x59645C // 0x596368, 0x596388 // 0x5962C4, 0x596334 // 0x59259C, 0x59263C // 0x5920E8, 0x59211C // 0x591FD8, 0x592000 // 0x591D3C, 0x591DD0 // 0x591C88, 0x591D18 // 0x591BD4, 0x591C64 // 0x591B04, 0x591BA0 // 0x5919F0, 0x591AE0 // 0x591944, 0x5919CC // 0x591864, 0x591890 // 0x5917B0, 0x5917E8 // 0x5915E8, 0x59164C // 0x5914F4, 0x59158C // 0x59126C, 0x59144C // 0x5911FC, 0x59122C // 0x591160, 0x5911BC // 0x590E14, 0x591120 // 0x590CA0, 0x590D9C // 0x590C14, 0x590C38 // 0x590960, 0x590B7C // 0x58CFA0, 0x58CFC0 // 0x5B4FB4, 0x5B50D4 // 0x5B464C, 0x5B4850 // 0x5B4518, 0x5B4534 // 0x5B4324, 0x5B4420 // 0x5B3578, 0x5B35B4 // 0x5B3480, 0x5B34B8 // 0x5B2BC8, 0x5B2BD8 // 0x5B2844, 0x5B28DC // 0x5B25E8, 0x5B27D0 // 0x5B0A48, 0x5B0AAC // 0x5B0814, 0x5B0880 // 0x5B02EC, 0x5B03D0 // 0x5AFD00, 0x5AFE24 // 0x5AFC20, 0x5AFC48 // 0x, 0x // 0x, 0x // 0x, 0x // 0x, 0x // 0x, 0x // 0x, 0x // 0x, 0x // 0x, 0x // 0x, 0x // 0x, 0x // 0x, 0x // 0x, 0x // 0x, 0x // 0x, 0x Console.WriteLine("FINISHED"); Console.ReadLine(); /*StringsScraper.BinaryScrape("mc.exe", "strings/mc", 0x1AEE8, 0x1B1F4); * Console.Read(); * Environment.Exit(0);*/ //StringsScraper.BinarySearch("fes.exe", "画面スクリプト(fes)コンバータ fes.exe\n"); //StringsScraper.BinaryScrape("fes.exe", "strings/fes", 0x3D828, 0x3DC68); //Console.Beep(); //Console.ReadLine(); /*ACPatcher ac = new ACPatcher { * InstallDir = ".", * }; * Console.WriteLine(ac.Patch()); * //Console.ReadLine(); * //Console.Clear(); * MCPatcher mc = new MCPatcher { * InstallDir = ".", * }; * Console.WriteLine(mc.Patch()); * //Console.ReadLine(); * //Console.Clear(); * FESPatcher fes = new FESPatcher { * InstallDir = ".", * }; * Console.WriteLine(fes.Patch());*/ //WGCPatcher wgc = new WGCPatcher { // InstallDir = ".", //}; //Console.WriteLine(wgc.Patch()); Console.ReadLine(); }
/// <summary> /// Overridden ProcessRecord method. /// </summary> protected override void ProcessRecord() { switch (ParameterSetName) { case "infoonly": { if (ProcessId != -1) { WriteObject(QueryThreadInformation(ProcessId), true); } else { WriteObject(QueryThreadInformation(), true); } } break; case "current": WriteObject(GetCurrentThread(Access, PseudoHandle)); break; case "all": { IEnumerable <NtThread> threads = NtThread.GetThreads(Access, FromSystem); if (FilterScript == null && First <= 0) { WriteObject(threads, true); } else { using (var ths = new DisposableList <NtThread>(threads)) { threads = ths; if (FilterScript != null) { threads = threads.Where(t => ArbitraryFilter(t, FilterScript)); } if (First > 0) { threads = threads.Take(First); } WriteObject(threads.Select(t => t.Duplicate()).ToArray(), true); } } } break; case "pid": { using (NtProcess process = NtProcess.Open(ProcessId, ProcessAccessRights.MaximumAllowed)) { WriteObject(process.GetThreads(), true); } } break; case "tid": { if (ProcessId != -1) { WriteObject(NtThread.Open(ProcessId, ThreadId, Access)); } else { WriteObject(NtThread.Open(ThreadId, Access)); } } break; case "next": WriteObject(NextThread?.GetNextThread(Process, Access) ?? Process.GetFirstThread(Access)); break; } }
public override void ExecuteCmdlet() { if (this.Workspace != null) { this.WorkspaceId = this.Workspace.Id; this.Logger.WriteDebug($"Using {nameof(this.Workspace)} object to get {nameof(this.WorkspaceId)} parameter. Value: {this.WorkspaceId}"); } if (this.Id != default) { this.Filter = $"id eq '{this.Id}'"; } if (this.Name != default) { this.Filter = $"tolower(name) eq '{this.Name.ToLower()}'"; } IEnumerable <Dataflow> dataflows = null; using (var client = this.CreateClient()) { if (this.WorkspaceId != default) { dataflows = this.Scope == PowerBIUserScope.Organization ? client.Dataflows.GetDataflowsAsAdminForWorkspace(this.WorkspaceId, filter: this.Filter, top: this.First, skip: this.Skip) : client.Dataflows.GetDataflows(this.WorkspaceId); } else if (this.Scope == PowerBIUserScope.Organization) { // No workspace id - Works only for organization scope dataflows = client.Dataflows.GetDataflowsAsAdmin(filter: this.Filter, top: this.First, skip: this.Skip); } } // In individual scope - filter the results locally if (this.Scope == PowerBIUserScope.Individual) { if (this.Id != default) { dataflows = dataflows?.Where(d => this.Id == d.Id); } if (!string.IsNullOrEmpty(this.Name)) { dataflows = dataflows?.Where(d => d.Name.Equals(this.Name, StringComparison.OrdinalIgnoreCase)); } if (this.Skip.HasValue) { dataflows = dataflows?.Skip(this.Skip.Value); } if (this.First.HasValue) { dataflows = dataflows?.Take(this.First.Value); } } this.Logger.WriteObject(dataflows, true); }
public static T[] TakeArray <T>(this IEnumerable <T> src, int length) => src.Take(length).ToArray();
/// <summary> /// Initializes a new instance of the <see cref="TruncatedCollection{T}"/> class. /// </summary> /// <param name="source">The collection to be truncated.</param> /// <param name="pageSize">The page size.</param> public TruncatedCollection(IEnumerable <T> source, int pageSize) : base(source.Take(checked (pageSize + 1))) { Initialize(pageSize); }
/// <summary> /// Gets the specified request. /// </summary> /// <param name="request">The request.</param> /// <returns>Task{ItemsResult}.</returns> protected QueryResult <BaseItemDto> GetResult(GetItemsByName request) { var dtoOptions = GetDtoOptions(AuthorizationContext, request); User user = null; BaseItem parentItem; if (!string.IsNullOrWhiteSpace(request.UserId)) { user = UserManager.GetUserById(request.UserId); parentItem = string.IsNullOrEmpty(request.ParentId) ? LibraryManager.GetUserRootFolder() : LibraryManager.GetItemById(request.ParentId); } else { parentItem = string.IsNullOrEmpty(request.ParentId) ? LibraryManager.RootFolder : LibraryManager.GetItemById(request.ParentId); } IList <BaseItem> items; var excludeItemTypes = request.GetExcludeItemTypes(); var includeItemTypes = request.GetIncludeItemTypes(); var mediaTypes = request.GetMediaTypes(); var query = new InternalItemsQuery(user) { ExcludeItemTypes = excludeItemTypes, IncludeItemTypes = includeItemTypes, MediaTypes = mediaTypes, DtoOptions = dtoOptions }; Func <BaseItem, bool> filter = i => FilterItem(request, i, excludeItemTypes, includeItemTypes, mediaTypes); if (parentItem.IsFolder) { var folder = (Folder)parentItem; if (!string.IsNullOrWhiteSpace(request.UserId)) { items = request.Recursive ? folder.GetRecursiveChildren(user, query).ToList() : folder.GetChildren(user, true).Where(filter).ToList(); } else { items = request.Recursive ? folder.GetRecursiveChildren(filter) : folder.Children.Where(filter).ToList(); } } else { items = new[] { parentItem }.Where(filter).ToList(); } var extractedItems = GetAllItems(request, items); var filteredItems = FilterItems(request, extractedItems, user); filteredItems = LibraryManager.Sort(filteredItems, user, request.GetOrderBy()); var ibnItemsArray = filteredItems.ToList(); IEnumerable <BaseItem> ibnItems = ibnItemsArray; var result = new QueryResult <BaseItemDto> { TotalRecordCount = ibnItemsArray.Count }; if (request.StartIndex.HasValue || request.Limit.HasValue) { if (request.StartIndex.HasValue) { ibnItems = ibnItems.Skip(request.StartIndex.Value); } if (request.Limit.HasValue) { ibnItems = ibnItems.Take(request.Limit.Value); } } var tuples = ibnItems.Select(i => new Tuple <BaseItem, List <BaseItem> >(i, new List <BaseItem>())); var dtos = tuples.Select(i => DtoService.GetItemByNameDto(i.Item1, dtoOptions, i.Item2, user)); result.Items = dtos.Where(i => i != null).ToArray(); return(result); }
public BasePostModel(PostType type, string text, IEnumerable <string> attachments) { Type = type; Text = text; Attachments = attachments?.Take(10).ToArray(); }
/// <summary> /// Get an enumerator that returns all of the files that match the wildcards that /// are in any of the directories to be searched. /// </summary> /// <returns>An IEnumerable that returns all matching files one by one.</returns> /// <remarks>The enumerator that is returned finds files using a lazy algorithm that /// searches directories incrementally as matches are consumed.</remarks> public IEnumerable <FileInfo> Matches(FileSortOptions sortOrder, TimeSpan minFileAge, int maxNumberOfFiles) { // Set the search options depending on directory matches SearchOption searchOpt = SearchOption.TopDirectoryOnly; if (IncludeSubDirs) { searchOpt = SearchOption.AllDirectories; } DirectoryInfo diTop = new DirectoryInfo(m_path); IEnumerable <FileInfo> files = null; foreach (string filter in m_filterList) { IEnumerable <FileInfo> tmpFiles = null; DateTime timeStamp = DateTime.UtcNow; // Only send files which are at least minFileAge old if (minFileAge != TimeSpan.Zero) { timeStamp = DateTime.UtcNow.Subtract(minFileAge); } if (sortOrder == FileSortOptions.None) { tmpFiles = from file in diTop.EnumerateFiles(filter, searchOpt) where file.CreationTimeUtc < timeStamp select file; } else if (sortOrder == FileSortOptions.CreationTimeUtcAscending) { // LINQ query to sort by CreationTime tmpFiles = from file in diTop.EnumerateFiles(filter, searchOpt) where file.CreationTimeUtc < timeStamp orderby file.CreationTimeUtc ascending select file; } else if (sortOrder == FileSortOptions.CreationTimeUtcDescending) { tmpFiles = from file in diTop.EnumerateFiles(filter, searchOpt) where file.CreationTimeUtc < timeStamp orderby file.CreationTimeUtc descending select file; } else if (sortOrder == FileSortOptions.FileNameAscending) { tmpFiles = from file in diTop.EnumerateFiles(filter, searchOpt) where file.CreationTimeUtc < timeStamp orderby file.Name ascending select file; } else if (sortOrder == FileSortOptions.FileNameDescending) { tmpFiles = from file in diTop.EnumerateFiles(filter, searchOpt) where file.CreationTimeUtc < timeStamp orderby file.Name descending select file; } // Remove unwanted files if (!IncludeEmptyFiles) { tmpFiles = from file in tmpFiles where file.Length > 0 select file; } if (!IncludeHiddenFiles) { tmpFiles = from file in tmpFiles where !file.Attributes.HasFlag(FileAttributes.Hidden) select file; } if (!IncludeReadOnlyFiles) { tmpFiles = from file in tmpFiles where !file.Attributes.HasFlag(FileAttributes.ReadOnly) select file; } if (!IncludeSystemFiles) { tmpFiles = from file in tmpFiles where !file.Attributes.HasFlag(FileAttributes.System) select file; } if (!IncludeTemporatyFiles) { tmpFiles = from file in tmpFiles where !file.Attributes.HasFlag(FileAttributes.Temporary) select file; } // Concatenate the files if (files != null) { files = files.Concat(tmpFiles); } else { files = tmpFiles; } } if (maxNumberOfFiles == -1) { return(files); } else { return(files.Take(maxNumberOfFiles)); } }
public ExpandableListFull(IEnumerable <T> list, int pageSize) { this.PageSize = pageSize; this.HasMoreElements = list.Count() > pageSize; this.List = list.Take(pageSize); }
public override ProcedureBase GetTrampolineDestination(IEnumerable <RtlInstructionCluster> rdr, IRewriterHost host) { var dasm = rdr.Take(8).ToArray(); if (dasm.Length < 8) { return(null); } //ImmediateOperand immOp; //MemoryOperand memOp; throw new NotImplementedException(); /* * //addi r12,r0,0000 * instr = dasm[0].Instructions[0]; * if (instr.Mnemonic != Mnemonic.addi) * return null; * * //oris r12,r12,0006 * instr = dasm.DisassembleInstruction(); * if (instr.Mnemonic != Mnemonic.oris) * return null; * immOp = (ImmediateOperand) instr.op3; * uint aFuncDesc = immOp.Value.ToUInt32() << 16; * * //lwz r12,nnnn(r12) * instr = dasm.DisassembleInstruction(); * if (instr.Mnemonic != Mnemonic.lwz) * return null; * memOp = (MemoryOperand)instr.op2; * int offset = memOp.Offset.ToInt32(); * aFuncDesc = (uint)(aFuncDesc + offset); * * //std r2,40(r1) * instr = dasm.DisassembleInstruction(); * if (instr.Mnemonic != Mnemonic.std) * return null; * * //lwz r0,0(r12) * // Have a pointer to a trampoline * instr = dasm.DisassembleInstruction(); * if (instr.Mnemonic != Mnemonic.lwz) * return null; * * //lwz r2,4(r12) * instr = dasm.DisassembleInstruction(); * if (instr.Mnemonic != Mnemonic.lwz) * return null; * * // mtctr r0 * instr = dasm.DisassembleInstruction(); * if (instr.Mnemonic != Mnemonic.mtctr) * return null; * * // bcctr 14,00 * instr = dasm.DisassembleInstruction(); * if (instr.Mnemonic != Mnemonic.bcctr) * return null; * * // Read the function pointer from the function descriptor. * * offset = (int)aFuncDesc - (int)rdr.Address.ToUInt32(); * rdr.Offset = rdr.Offset + offset; * var aFn = rdr.ReadUInt32(); * return null; */ }
public void Begin() { if (CancelToken.IsCancellationRequested) { return; } FilePaths = SearchExtensions.SelectMany(searchPattern => Directory.EnumerateFiles(SearchDirectory, searchPattern, SearchOption.TopDirectoryOnly)); //FilePaths = Directory.EnumerateFiles(SearchDirectory, SearchExtension, SearchOption.TopDirectoryOnly); if (FilePaths == null) { throw new Exception("No files to process!"); } byte[] bytes = new byte[] { }; ANS1PrivateKey ans1Key = null; StringBuilder output = new StringBuilder(); List <string> filesToDelete = new List <string>(); IEnumerable <string> pathBatch = FilePaths.Take(BatchSize); while (pathBatch.Any() && !CancelToken.IsCancellationRequested) { foreach (string file in pathBatch) { bytes = GetEncodedBytes(file); if (bytes == null) { continue; } else if (bytes == EmptyByteArray) { if (DeleteFiles) { filesToDelete.Add(file); } } using (ans1Key = new ANS1PrivateKey(bytes)) { ans1Key.ParseBuffer(); EncodingUtility.AssertValidRSAPrivateKey(ans1Key); if (ExportOnlyPQ) { PrivateKeySerializer.WritePQDocument(output, ans1Key); } else { PrivateKeySerializer.WriteXMLDocument(output, ans1Key); } bytes = null; if (DeleteFiles) { filesToDelete.Add(file); } } } File.AppendAllText(OutputFilename, output.ToString()); output.Clear(); bytes = null; if (DeleteFiles && filesToDelete.Any()) { foreach (string file in filesToDelete) { File.Delete(file); } filesToDelete.Clear(); } FilePaths = FilePaths.Skip(BatchSize); pathBatch = FilePaths.Take(BatchSize); } }
/// <summary> /// Returns whether the sequence contains a certain amount of elements. /// </summary> /// <typeparam name = "T">The type of the elements of the input sequence.</typeparam> /// <param name = "source">The source for this extension method.</param> /// <param name = "count">The amount of elements the sequence should contain.</param> /// <returns>True when the sequence contains the specified amount of elements, false otherwise.</returns> public static bool HasCountOf <T>(this IEnumerable <T> source, int count) { return(source.Take(count + 1).Count() == count); }
public IEnumerable <Clothes> GetPopularByLastMonth(int count) { return(clothesList?.Take(count)); }
public override async Task WriteAsync(TemplateScopeContext scope, PageBlockFragment block, CancellationToken token) { if (block.Argument.IsNullOrEmpty()) { throw new NotSupportedException("'each' block requires the collection to iterate"); } var cache = (EachArg)scope.Context.Cache.GetOrAdd(block.ArgumentString, _ => ParseArgument(scope, block)); var collection = cache.Source.Evaluate(scope, out var syncResult, out var asyncResult) ? (IEnumerable)syncResult : (IEnumerable)(await asyncResult); var index = 0; if (collection != null) { if (cache.Where != null || cache.OrderBy != null || cache.OrderByDescending != null || cache.Skip != null || cache.Take != null) { var filteredResults = new List <Dictionary <string, object> >(); foreach (var element in collection) { // Add all properties into scope if called without explicit in argument var scopeArgs = !cache.HasExplicitBinding && CanExportScopeArgs(element) ? element.ToObjectDictionary() : new Dictionary <string, object>(); scopeArgs[cache.Binding] = element; scopeArgs[nameof(index)] = AssertWithinMaxQuota(index++); var itemScope = scope.ScopeWithParams(scopeArgs); if (cache.Where != null) { var result = await cache.Where.EvaluateToBoolAsync(itemScope); if (!result) { continue; } } filteredResults.Add(scopeArgs); } IEnumerable <Dictionary <string, object> > selectedResults = filteredResults; var comparer = (IComparer <object>)Comparer <object> .Default; if (cache.OrderBy != null) { var i = 0; selectedResults = selectedResults.OrderBy(scopeArgs => { scopeArgs[nameof(index)] = i++; return(cache.OrderBy.Evaluate(scope.ScopeWithParams(scopeArgs))); }, comparer); } else if (cache.OrderByDescending != null) { var i = 0; selectedResults = selectedResults.OrderByDescending(scopeArgs => { scopeArgs[nameof(index)] = i++; return(cache.OrderByDescending.Evaluate(scope.ScopeWithParams(scopeArgs))); }, comparer); } if (cache.Skip != null) { var skip = cache.Skip.Evaluate(scope).ConvertTo <int>(); selectedResults = selectedResults.Skip(skip); } if (cache.Take != null) { var take = cache.Take.Evaluate(scope).ConvertTo <int>(); selectedResults = selectedResults.Take(take); } index = 0; foreach (var scopeArgs in selectedResults) { var itemScope = scope.ScopeWithParams(scopeArgs); itemScope.ScopedParams[nameof(index)] = index++; await WriteBodyAsync(itemScope, block, token); } } else { foreach (var element in collection) { // Add all properties into scope if called without explicit in argument var scopeArgs = !cache.HasExplicitBinding && CanExportScopeArgs(element) ? element.ToObjectDictionary() : new Dictionary <string, object>(); scopeArgs[cache.Binding] = element; scopeArgs[nameof(index)] = AssertWithinMaxQuota(index++); var itemScope = scope.ScopeWithParams(scopeArgs); await WriteBodyAsync(itemScope, block, token); } } } if (index == 0) { await WriteElseAsync(scope, block.ElseBlocks, token); } }
/// <summary> /// Returns the only element of a sequence, or a default value if the sequence is empty or contains more than one element. /// </summary> public static TSource TheOneOrDefault <TSource>(this IEnumerable <TSource> source) { var elements = source.Take(2).ToArray(); return((elements.Length == 1) ? elements[0] : default(TSource)); }
public static IEnumerable <T> SkipLast <T>(this IEnumerable <T> This, int count) { return(This.Take(This.Count() - count)); }