public static void Generate(GenerateOptions options, IConsoleWriter console) { if (string.IsNullOrEmpty(options.File)) { options.File = "CommandLine.json"; if (options.Verbose) { console.WriteLine($"Definition file name not specified. Using '{options.File}'"); } } if (!File.Exists(options.File)) { console.WriteError($"ERROR: Command line definition file {options.File} not found."); return; } CliDefinitionList cliDefinition; try { cliDefinition = JsonConvert.DeserializeObject <CliDefinitionList>(File.ReadAllText(options.File)); } catch (Exception exc) { console.WriteError($"ERROR: Could not load the definition file {options.File}"); console.WriteError(exc.Message); return; } Generate(cliDefinition, options.OutputPath, options.OverwriteFiles, options.Verbose, console); }
public void GenerateList_WithRandomSort_ReturnsRandomList() { DateTime startTime = new DateTime( DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day + 1, 12, 0, 0); List <Victim> inputVictims = new List <Victim>(); inputVictims.Add(new Victim("Aaron Jones", "*****@*****.**", "R&D")); inputVictims.Add(new Victim("John Doe", "*****@*****.**", "Sales")); inputVictims.Add(new Victim("John Meyers", "*****@*****.**", "Sales")); GenerateOptions options = new GenerateOptions(); options.Randomize = true; options.MinutesBetweenScheduledEmails = 5; options.StartAtDateTime = startTime; options.MinimumHour = 8; options.MinimumMinute = 30; options.MaximumHour = 18; options.MaximumMinute = 0; GenerateVictims sut = new GenerateVictims(); List <GeneratedVictim> actual = sut.GenerateVictimList(inputVictims, options); Assert.NotEmpty(actual); Assert.Equal(inputVictims.Count, actual.Count); }
public IActionResult Get( [FromRoute(Name = "name")][FromQuery(Name = "n")][Required] string name, [FromQuery(Name = "s")][Range(16, 1024)] int size = 64, [FromQuery(Name = "bg")] string backgroundColor = null, [FromQuery(Name = "fg")] string foregroundColor = null, [FromRoute(Name = "outputformat")][FromQuery(Name = "o")] OutputFormat outputFormat = OutputFormat.Png, [FromQuery(Name = "f")] BackgroundFormat backgroundFormat = BackgroundFormat.Square) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var text = GetInitials(name) ?? string.Empty; if (!TryParseColor(foregroundColor, out var fg)) { fg = Color.White; } if (!TryParseColor(backgroundColor, out var bg)) { int index = text.Select(c => (int)c).Sum(); bg = _backgroundColors[index % _backgroundColors.Length]; } if (!TryParseImageFormat(outputFormat, out var imageFormat)) { imageFormat = ImageFormat.Png; } var options = new GenerateOptions(text, size, fg, bg, backgroundFormat, imageFormat); var cacheKey = options.ComputeCacheKey(); if (!_cache.TryGetValue(cacheKey, out byte[] result))
private static async Task <int> RunGenerateAndReturnExitCode(GenerateOptions opts) { var repo = GetCorrectRepository(opts); var cmd = new GenerateCommand(opts, repo, new FileSystem()); var result = await cmd.RunAsync(); return(!result ? 1 : 0); }
private void HandleGenerate(GenerateOptions options) { container.RegisterInstance(options); container.RegisterInstance <Options>(options); IVerbHandler handler = container.Resolve <GenerateHandler>(); handler.Run(); }
/// <summary> /// Create a permutation set from the provided list of values. /// If type is MetaCollectionType.WithholdRepetitionSets, then the values will be compared using the supplied IComparer. /// </summary> /// <param name="values">List of values to permute.</param> /// <param name="flags">The type of permutation set to calculate.</param> /// <param name="comparer">Comparer used for defining the lexicographic order.</param> public Permutations(IEnumerable <T> values, GenerateOptions flags, IComparer <T>?comparer) { _ = values ?? throw new ArgumentNullException(nameof(values)); // Copy information provided and then create a parallel int array of lexicographic // orders that will be used for the actual permutation algorithm. // The input array is first sorted as required for WithoutRepetition and always just for consistency. // This array is constructed one of two way depending on the type of the collection. // // When type is MetaCollectionType.WithRepetition, then all N! permutations are returned // and the lexicographic orders are simply generated as 1, 2, ... N. // E.g. // Input array: {A A B C D E E} // Lexicographic Orders: {1 2 3 4 5 6 7} // // When type is MetaCollectionType.WithoutRepetition, then fewer are generated, with each // identical element in the input array not repeated. The lexicographic sort algorithm // handles this natively as long as the repetition is repeated. // E.g. // Input array: {A A B C D E E} // Lexicographic Orders: {1 1 2 3 4 5 5} Flags = flags; _myValues = values.ToList(); _myLexicographicOrders = new int[_myValues.Count]; if (Type == GenerateOption.WithRepetition) { for (var i = 0; i < _myLexicographicOrders.Length; ++i) { _myLexicographicOrders[i] = i; } } else { comparer ??= Comparer <T> .Default; _myValues.Sort(comparer); var j = 1; if (_myLexicographicOrders.Length > 0) { _myLexicographicOrders[0] = j; } for (var i = 1; i < _myLexicographicOrders.Length; ++i) { if (comparer.Compare(_myValues[i - 1], _myValues[i]) != 0) { ++j; } _myLexicographicOrders[i] = j; } } _count = new Lazy <BigInteger>(GetCount); }
protected string GenerateTableVariable(string connStr, string variableName, string query) { SqlSchemaGenerator generator = new SqlSchemaGenerator(connStr); GenerateOptions options = new GenerateOptions { GenerateKeys = this.GeneratePrimaryKey, PrimaryKeyName = this.PrimaryKeyName }; return(generator.GenerateTableVariable(variableName, query, options)); }
public Generator(GenerateOptions options) { _options = options; if (string.IsNullOrWhiteSpace(_options.FileName)) { throw new ArgumentException("Empty file name"); } _size = SizeHelper.GetBytesFromSizeString(_options.SizeStr); }
public async Task It_can_GetBits() { // Arrange var opts = new GenerateOptions(); var repo = Substitute.For <IFeatureBitsRepo>(); var filesystem = Substitute.For <IFileSystem>(); var it = new GenerateCommand(opts, repo, filesystem); repo.GetAllAsync().Returns(info => _featureBitDefinitions); // Act (string Name, int Id)[] result = (await it.GetBits()).ToArray();
protected override void ProcessRecord() { base.ProcessRecord(); SqlSchemaGenerator generator = new SqlSchemaGenerator(ConnectionString); GenerateOptions options = new GenerateOptions { GenerateKeys = this.GeneratePrimaryKey, PrimaryKeyName = this.PrimaryKeyName }; string output = generator.GenerateTableSql(OutputName, Query, options); WriteObject(output); }
public void It_can_be_created() { // Arrange var opts = new GenerateOptions(); var repo = Substitute.For <IFeatureBitsRepo>(); var filesystem = Substitute.For <IFileSystem>(); // Act var it = new GenerateCommand(opts, repo, filesystem); // Assert it.Should().NotBeNull(); }
public void GenerateList_WithoutRandomSort_CreatesSendOutTimesAfterMinimumHour() { DateTime startTime = new DateTime( DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day + 1, 3, 0, 0); List <Victim> inputVictims = new List <Victim>(); inputVictims.Add(new Victim("John Meyers", "*****@*****.**", "Sales")); inputVictims.Add(new Victim("John Doe", "*****@*****.**", "Sales")); inputVictims.Add(new Victim("Aaron Jones", "*****@*****.**", "R&D")); GenerateOptions options = new GenerateOptions(); options.Randomize = false; options.MinutesBetweenScheduledEmails = 5; options.StartAtDateTime = startTime; options.MinimumHour = 8; options.MinimumMinute = 30; options.MaximumHour = 18; options.MaximumMinute = 0; GenerateVictims sut = new GenerateVictims(); List <GeneratedVictim> actual = sut.GenerateVictimList(inputVictims, options); Assert.NotEmpty(actual); Assert.Equal(inputVictims.Count, actual.Count); Assert.Equal("R&D", actual[0].Dept); Assert.Equal("Sales", actual[1].Dept); Assert.Equal("Sales", actual[2].Dept); Assert.Equal("Aaron Jones", actual[0].Name); Assert.Equal("John Doe", actual[1].Name); Assert.Equal("John Meyers", actual[2].Name); Assert.Equal("*****@*****.**", actual[0].Email); Assert.Equal("*****@*****.**", actual[1].Email); Assert.Equal("*****@*****.**", actual[2].Email); Assert.Equal(new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day + 1, 8, 30, 0), actual[0].SendOutTime); Assert.Equal(new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day + 1, 8, 35, 0), actual[1].SendOutTime); Assert.Equal(new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day + 1, 8, 40, 0), actual[2].SendOutTime); }
private static int ExecuteGenerator(GenerateOptions options) { if (!options.Validate()) { return(1); } var generator = new FileGenerator(options); var timer = Stopwatch.StartNew(); Console.WriteLine($"File '{options.Output}' creation started..."); generator.Generate(); Console.WriteLine($"File creation executed at {timer.Elapsed}"); return(0); }
static int RunGenerate(GenerateOptions opts) { CheckInputFileExists(); var generator = new TranslationFileGenerator(GetInputFilename()); try { generator.GenerateFile(opts.Filename); ShowMessage($"Generated file {opts.Filename}"); return(0); } catch (Exception ex) { ShowError(ex.Message); return(1); } }
private static void Generate(GenerateOptions options) { var client = new CrmServiceClient(options.CrmConnectionString); foreach (var entityName in options.EntitiesList) { var entityMetadata = ((RetrieveEntityResponse)client.Execute( new RetrieveEntityRequest { EntityFilters = EntityFilters.All, LogicalName = entityName })).EntityMetadata; var model = new Model(entityMetadata, options.Namespace); var generator = new Generator(model); options.Directory.Create(); var outputFile = new FileInfo(Path.Combine(options.Directory.FullName, $"{model.LogicalName.ToPascalCase()}.Generated.cs")); using var streamWriter = outputFile.CreateText(); generator.Generate(streamWriter); } }
public async Task PerformGeneration(GenerateOptions options) { if (options.WithInitialization) { await PerformInit(); } await InitData(); _random = new Random(); using IUnitOfWork uow = new UnitOfWork(); for (int i = 0; options.IsEndless || i < options.NrOfGenerations; i++) { await GenerateMessagesAsync(uow); await Task.Delay(_random.Next(500)); } }
public void IEquatableT_Equalsが非virtualで生成される() { const string source = @" using Aetos.ComparisonGenerator; [Comparable] public partial class Person { [CompareBy(Order = 0)] public string FirstName { get; set; } [CompareBy(Order = 1)] public string LastName { get; set; } }"; var options = new GenerateOptions( generateEquatable: true, generateMethodsAsVirtual: false); var generator = new ComparableObjectGenerator(options); var assembly = RunGeneratorAndGenerateAssembly( generator, source, out _); Assert.That(assembly, Is.Not.Null); var type = assembly.GetType("Person"); Assert.That(type, Is.Not.Null); var equals = GetMethod( type, "Equals", type); Assert.That(equals, Is.Not.Null); // インターフェイスの実装であるメソッドは明示的に virtual と書かなくても IsVirtual は True になる。 // 明示的に virtual と書いていない場合、IsFinal が True になり、オーバーライドできない。 Assert.That(equals.IsFinal, Is.True); }
public void IEquatableT_Equalsがvirtualで生成される() { const string source = @" using Aetos.ComparisonGenerator; [Comparable] public partial class Person { [CompareBy(Order = 0)] public string FirstName { get; set; } [CompareBy(Order = 1)] public string LastName { get; set; } }"; var options = new GenerateOptions( generateEquatable: true, generateMethodsAsVirtual: true); var generator = new ComparableObjectGenerator(options); var assembly = RunGeneratorAndGenerateAssembly( generator, source, out _); Assert.That(assembly, Is.Not.Null); var type = assembly.GetType("Person"); Assert.That(type, Is.Not.Null); var equals = GetMethod( type, "Equals", type); Assert.That(equals, Is.Not.Null); Assert.That(equals.IsFinal, Is.False); }
public override IEnumerable <ISigo> Generate(GenerateOptions options) { switch (options) { case GenerateOptions.Unique: { var ret = new SigoHashSet(GenerateInternal(options)); return(ret); } case GenerateOptions.Sorted: { var ret = new List <ISigo>(GenerateInternal(options)); ret.Sort(new SigoComparer()); return(ret); } case GenerateOptions.Unique | GenerateOptions.Sorted: { var ret = new SigoSortedSet(GenerateInternal(options)); return(ret.ToList()); } case GenerateOptions.None: default: return(GenerateInternal(options)); } }
private static void GenerateVictims() { ReadJson readJson = new ReadJson(new VictimInfoProvider()); List <Lib.Models.Victim> victims = readJson.GetVictims(); GenerateVictims generateVictims = new GenerateVictims(); DateTime startAtDateTime = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.AddDays(1).Day, 12, 0, 0); GenerateOptions options = new GenerateOptions( true, 5, startAtDateTime, 8, 30, 18, 0); List <Lib.Models.GeneratedVictim> generatedVictims = generateVictims.GenerateVictimList(victims, options); foreach (Lib.Models.GeneratedVictim generatedVictim in generatedVictims) { Console.WriteLine($"{generatedVictim.Name},{generatedVictim.Email},{generatedVictim.Dept},{generatedVictim.SendOutTime}"); } }
public void Object_Equalsが生成さない() { const string source = @" using Aetos.ComparisonGenerator; [Comparable] public partial class Person { [CompareBy(Order = 0)] public string FirstName { get; set; } [CompareBy(Order = 1)] public string LastName { get; set; } }"; var options = new GenerateOptions( overrideObjectMethods: false); var generator = new ComparableObjectGenerator(options); var assembly = RunGeneratorAndGenerateAssembly( generator, source, out _); Assert.That(assembly, Is.Not.Null); var type = assembly.GetType("Person"); Assert.That(type, Is.Not.Null); var equals = GetMethod( type, "Equals", typeof(object)); Assert.That(equals, Is.Null); }
public override IEnumerable <ISigo> Generate(GenerateOptions options) { return(GetType(Name).Generate(options)); }
public DefaultAggregatedServiceRegistrator(AggregatedServicesBuilder builder, GenerateOptions generateOptions) { _builder = builder; _generateOptions = generateOptions; }
public void Object_EqualsがIEquitableT_Equalsに移譲される() { const string source = @" using System; using Aetos.ComparisonGenerator; using Aetos.ComparisonGenerator.IntegrationTests.Injection; [Comparable] public partial class Person : IEquatable<Person> { private readonly ITestHooks _hooks; public Person( ITestHooks hooks) { this._hooks = hooks; } [CompareBy(Order = 0)] public string FirstName { get; set; } [CompareBy(Order = 1)] public string LastName { get; set; } bool IEquatable<Person>.Equals( Person? other) { return this._hooks.EqualsHook(this, other); } }"; var options = new GenerateOptions( overrideObjectMethods: true, generateEquatable: false); var generator = new ComparableObjectGenerator(options); var assembly = RunGeneratorAndGenerateAssembly( generator, source, out _); Assert.That(assembly, Is.Not.Null); var type = assembly.GetType("Person"); Assert.That(type, Is.Not.Null); var equals = GetMethod(type, "Equals", typeof(object)); Assert.That(equals, Is.Not.Null); var hook = Substitute.For <ITestHooks>(); var hook2 = new TestHooks(hook); var instance = Activator.CreateInstance(type, hook2); hook .EqualsHook(Arg.Any <object>(), Arg.Any <object>()) .Returns(true); var result = equals.Invoke(instance, new[] { instance }); Assert.That(result, Is.True); hook.Received().EqualsHook(Arg.Any <object>(), Arg.Any <object>()); }
static async Task Generate(GenerateOptions options) => await new Generator(options).Generate();
/// <summary>Generates a source file from the given PlcBlock</summary> /// <param name="exportItem">The export item.</param> /// <param name="exportPath">The export path.</param> /// <param name="options"></param> /// <returns>String</returns> /// <exception cref="System.ArgumentNullException">Parameter is null;exportItem</exception> /// <exception cref="System.ArgumentException">Parameter is null or empty;exportPath</exception> /// <exception cref="Siemens.Engineering.EngineeringException"></exception> /// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.UnauthorizedAccessException"></exception> /// <exception cref="System.IO.DirectoryNotFoundException"></exception> public static string GenerateSourceFromBlock(PlcBlock exportItem, string exportPath, GenerateOptions options) { if (exportItem == null) { throw new ArgumentNullException(nameof(exportItem), "Parameter is null"); } if (String.IsNullOrEmpty(exportPath)) { throw new ArgumentException("Parameter is null or empty", nameof(exportPath)); } var filePath = Path.GetFullPath(exportPath); if (!exportItem.IsKnowHowProtected) { Directory.CreateDirectory(filePath); switch (exportItem.ProgrammingLanguage) { case ProgrammingLanguage.DB: filePath = Path.Combine(filePath, AdjustNames.AdjustFileName(exportItem.Name) + ".db"); break; case ProgrammingLanguage.SCL: filePath = Path.Combine(filePath, AdjustNames.AdjustFileName(exportItem.Name) + ".scl"); break; case ProgrammingLanguage.STL: filePath = Path.Combine(filePath, AdjustNames.AdjustFileName(exportItem.Name) + ".awl"); break; default: return(null); } if (File.Exists(filePath)) { File.Delete(filePath); } IEngineeringInstance temp = exportItem; do { temp = temp.Parent; }while (!(temp is PlcSoftware)); (temp as PlcSoftware).ExternalSourceGroup.GenerateSource(new[] { exportItem }, new FileInfo(filePath), options); return(filePath); } throw new EngineeringException(string.Format(CultureInfo.InvariantCulture, "Block: '{0}' is Know-how protected! \r\n 'Generate source from block' is not possible on know how protected blocks!", exportItem.Name)); }
public override IEnumerable <ISigo> Generate(GenerateOptions options) { yield return(Value); }
/// <summary> /// Generate a permutation of <paramref name="source"/> with the chosen <paramref name="generateOption"/>. /// </summary> /// <typeparam name="T">The elements type of the set you want to permute.</typeparam> /// <param name="source">The source set.</param> /// <param name="generateOption">Specify if you want repetition or not.</param> /// <returns>All the possible orderings of the elements in <paramref name="source"/></returns> public static IEnumerable <IEnumerable <T> > Permute <T>(this IEnumerable <T> source, GenerateOptions generateOption) => source.Count() == 1 ? new[] { source } : generateOption == GenerateOptions.WithRepetition ? source.SelectMany((e1, i1) => source.Where((e2, i2) => i1 != i2).Permute(generateOption), (e, p) => new[] { e }.Concat(p)) : source.SelectMany(e => source.Except(new[] { e }).Permute(generateOption), (e, p) => new[] { e }.Concat(p));
/// <summary> /// Generate a <paramref name="k"/>-partial permutation of <paramref name="source"/> with the chosen /// <paramref name="generateOption"/>. /// </summary> /// <typeparam name="T">The elements type of the set you want to partial permute.</typeparam> /// <param name="source">The source set.</param> /// <param name="k">The size of the groups.</param> /// <param name="generateOption">Specify if you want repetition or not.</param> /// <returns>A subset of <paramref name="k"/> distinct elements (where order doesn't matter) /// of <paramref name="source"/></returns> public static IEnumerable <IEnumerable <T> > PartialPermute <T>(this IEnumerable <T> source, int k, GenerateOptions generateOption) => k == 0 ? new[] { new T[0] } : generateOption == GenerateOptions.WithRepetition ? source.SelectMany((e, i) => source.PartialPermute(k - 1, generateOption), (e, p) => new[] { e }.Concat(p)) : source.SelectMany((e, i) => source.Except(new[] { e }).PartialPermute(k - 1, generateOption), (e, p) => new[] { e }.Concat(p));
/// <summary> /// Generate a <paramref name="k" />-combination of <paramref name="source"/> with the chosen <paramref name="generateOption"/>. /// </summary> /// <typeparam name="T">The elements type of the set you want to combine.</typeparam> /// <param name="source">The source set.</param> /// <param name="k">The size of the groups.</param> /// <param name="generateOption">Specify if you want repetition or not.</param> /// <returns>A subset of <paramref name="k"/> distinct elements (where order matters) of <paramref name="source"/></returns> public static IEnumerable <IEnumerable <T> > Combine <T>(this IEnumerable <T> source, int k, GenerateOptions generateOption) => k == 0 ? new[] { new T[0] } : generateOption == GenerateOptions.WithRepetition ? source.SelectMany((e, i) => source.Skip(i).Combine(k - 1, generateOption), (e, c) => new[] { e }.Concat(c)) : source.SelectMany((e, i) => source.Skip(i + 1).Combine(k - 1, generateOption), (e, c) => new[] { e }.Concat(c));