public void ShouldAcceptionOptionalArguments() { var environmentProvider = Substitute.For <IEnvironmentProvider>(); var buildService = Substitute.For <IBuildService>(); var cloneRoot = Faker.Random.String(10); var commitHash = Faker.Random.String(10); var gitHubOwner = Faker.Random.String(10); var gitHubRepo = Faker.Random.String(10); var token = Faker.Random.String(10); var configuration = Faker.Random.String(10); var annotationCount = Faker.Random.Int(0); var pullrequest = Faker.Random.Int(0); buildService.CloneRoot.Returns(cloneRoot); buildService.CommitHash.Returns(commitHash); buildService.GitHubOwner.Returns(gitHubOwner); buildService.GitHubRepo.Returns(gitHubRepo); environmentProvider.GetEnvironmentVariable("BCC_TOKEN").Returns(token); var parameterParser = new ParameterParser(environmentProvider, buildService); var parameters = parameterParser.Parse($"configuration={configuration};annotationcount={annotationCount};pullrequest={pullrequest}"); parameters.Should().NotBeNull(); parameters.CloneRoot.Should().Be(cloneRoot); parameters.Hash.Should().Be(commitHash); parameters.Owner.Should().Be(gitHubOwner); parameters.Repo.Should().Be(gitHubRepo); parameters.Token.Should().Be(token); parameters.ConfigurationFile.Should().Be(configuration); parameters.AnnotationCount.Should().Be(annotationCount); parameters.PullRequestNumber.Should().Be(pullrequest); }
/// <summary> /// The main program /// </summary> static int Main(string[] args) { Console.WriteLine("OpenIZ HTML Applet Compiler v{0} ({1})", Assembly.GetEntryAssembly().GetName().Version, Assembly.GetEntryAssembly().GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion); Console.WriteLine("Copyright (C) 2015-2018 Mohawk College of Applied Arts and Technology"); int retVal = 0; ParameterParser <ConsoleParameters> parser = new ParameterParser <ConsoleParameters>(); var parameters = parser.Parse(args); if (parameters.Help) { parser.WriteHelp(Console.Out); return(0); } else if (parameters.Compile) { return(Compile(parameters)); } else if (parameters.Sign) { return(Sign(parameters)); } else { Console.WriteLine("Nothing to do!"); return(0); } }
public void convert(string name, ParameterParser args, Stream from, Stream to) { var table = new Table(); table.Read(from); var mappedDb = new MappedDB(); mappedDb.AddTable(table); StreamWriter writer = new StreamWriter(to, Encoding.UTF8, 1024, true); switch ((ModuleType)table.rows.First().Key.Module) { default: case ModuleType.Unknown: writeUnknownTable(writer, table); break; case ModuleType.Dialog: writeDialogTable(writer, mappedDb); break; case ModuleType.Fairy: writeFairyTable(writer, mappedDb); break; case ModuleType.Item: writeItemTable(writer, mappedDb); break; case ModuleType.Npc: writeNpcTable(writer, mappedDb); break; case ModuleType.Spell: writeSpellTable(writer, mappedDb); break; case ModuleType.Text: writeTextTable(writer, mappedDb); break; } }
public void convert(string name, ParameterParser args, Stream from, Stream to) { var obj = zzio.rwbs.Section.ReadNew(from); byte[] buffer = Encoding.Default.GetBytes(Utils.convertToJSON(obj, new RWBSContractResolver())); to.Write(buffer, 0, buffer.Length); }
public override Verb CreateVerb(string[] tokens) { Color(position, tokens[1].Length, IDEColor.EntityType.Whitespace); string visibility = tokens[2]; Color(visibility.Length, IDEColor.EntityType.Verb); string scope = tokens[3]; Color(scope.Length, IDEColor.EntityType.Verb); ClassParser.SetScopeAndVisibility(scope, visibility, this); string messageName = tokens[4]; Color(messageName.Length, IDEColor.EntityType.Variable); Color(tokens[5].Length, IDEColor.EntityType.Structure); var compiler = new OrangeCompiler(source, position + length); Block parameterBlock = compiler.Compile(); int index = compiler.Position; List <Parameter> parameterList = ParameterParser.GetParameterList(parameterBlock); var parameters = new Parameters(parameterList); if (functionBodyParser.Scan(source, index)) { return(createMethod(messageName, functionBodyParser, parameters, false)); } return(equalBlockParser.Scan(source, index) ? createMethod(messageName, equalBlockParser, parameters, true) : null); }
public void convert(string name, ParameterParser args, Stream from, Stream to) { effect.EffectCombiner obj = new effect.EffectCombiner(); obj.Read(from); byte[] buffer = Encoding.Default.GetBytes(Utils.convertToJSON(obj)); to.Write(buffer, 0, buffer.Length); }
public void ShouldBeOverrideable() { var environmentProvider = Substitute.For <IEnvironmentProvider>(); var buildService = Substitute.For <IBuildService>(); buildService.CloneRoot.Returns(Faker.Random.String(10)); buildService.CommitHash.Returns(Faker.Random.String(10)); buildService.GitHubOwner.Returns(Faker.Random.String(10)); buildService.GitHubRepo.Returns(Faker.Random.String(10)); environmentProvider.GetEnvironmentVariable("BCC_TOKEN").Returns(Faker.Random.String(10)); var cloneRoot = Faker.Random.String(10); var commitHash = Faker.Random.String(10); var gitHubOwner = Faker.Random.String(10); var gitHubRepo = Faker.Random.String(10); var token = Faker.Random.String(10); var parameterParser = new ParameterParser(environmentProvider, buildService); var parameters = parameterParser.Parse($"cloneroot={cloneRoot};hash={commitHash};owner={gitHubOwner};repo={gitHubRepo};token={token}"); parameters.Should().NotBeNull(); parameters.CloneRoot.Should().Be(cloneRoot); parameters.Hash.Should().Be(commitHash); parameters.Owner.Should().Be(gitHubOwner); parameters.Repo.Should().Be(gitHubRepo); parameters.Token.Should().Be(token); }
public void SingleParameter() { ParameterParser parameterParser = new ParameterParser("KEYA=VALUEA"); Assert.Equal(1, parameterParser.Parameters.Length); Assert.Equal(new Parameter("KEYA", "VALUEA"), parameterParser.Parameters[0]); }
public void TestArray() { // Test that we can parse array parameters, and we strip empty entries var obj = new ArrayTest(); var onlyNum = new Dictionary <string, Variant>(); onlyNum["num1"] = new Variant("10,11,12"); onlyNum["str"] = new Variant("string 1,string2,,,,,,,,,,,string three"); ParameterParser.Parse(obj, onlyNum); Assert.NotNull(obj.num1); Assert.NotNull(obj.num2); Assert.NotNull(obj.str); Assert.AreEqual(3, obj.num1.Length); Assert.AreEqual(0, obj.num2.Length); Assert.AreEqual(3, obj.str.Length); Assert.AreEqual(10, obj.num1[0]); Assert.AreEqual(11, obj.num1[1]); Assert.AreEqual(12, obj.num1[2]); Assert.AreEqual("string 1", obj.str[0]); Assert.AreEqual("string2", obj.str[1]); Assert.AreEqual("string three", obj.str[2]); }
public void SingleParameter() { ParameterParser parameterParser = new ParameterParser("KEYA=VALUEA"); Assert.Single(parameterParser.Parameters); Assert.Equal(new Parameter("KEYA", "VALUEA"), parameterParser.Parameters[0]); }
public async Task <JsonResult> Filter(HomeSearchBindingModel model) { var cacheKey = KeyGenerator.Generate( WebConstants.CacheHomeFilterPrepend, model.SelectedCarType.ToString(), model.SelectedModelType, model.SelectedPriceRange, model.SelectedYear); var cachedModel = await this.cacheService.GetOrDefaultAsync <HomeSearchBindingModel>(cacheKey); if (cachedModel != null) { return(Json(cachedModel)); } var priceRanges = ParameterParser.ParsePriceRange(model.SelectedPriceRange); var filterStrategies = CarFilterStrategyFactory .GetStrategies(model.SelectedYear, priceRanges[0], priceRanges[1], WebConstants.AllFilterTypeModelValue); var mutipleFilterStrategy = CarMultipleFilterStrategyFactory.GetStrategy(new string[] { model.SelectedModelType }); var filteredCars = this.carsService.GetFiltered <BaseCar>(filterStrategies.ToArray()); filteredCars = mutipleFilterStrategy.Filter(filteredCars); var searchModel = await this.homeService.GetSearchModelAsync(filteredCars, model.SelectedCarType); _ = this.cacheService.AddInfinityCacheAsync(searchModel, cacheKey, WebConstants.CacheCarsType); return(Json(searchModel)); }
private static void Main(string[] args) { try { var parser = new ParameterParser(new MainExecutionGroup(), new EveMarketExecutionGroup()); parser.Parse(args); if (!parser.Execute()) { parser.ShowHelp(); } } catch (RequiredParametersMissingException requiredE) { Console.WriteLine("Required parameters were not set: " + requiredE.MissingRequiredParameters.Join(", ")); Environment.Exit(3); } catch (UnknownParameterException unknownE) { Console.WriteLine("Unknown parameter: " + unknownE.Parameter); Environment.Exit(2); } catch (Exception e) { Console.WriteLine(e.GetStackTrace()); Environment.Exit(-10); } }
public void CaseSensitivity() { IQ.Config.IgnoreCaseParameters = false; var sql = "select * FROM table where col = @Parm1"; var pp = new ParameterParser(sql, "p1value"); Assert.AreEqual(pp.Parameters[0].ParameterName, "@Parm1"); Assert.AreEqual(pp.Parameters[0].Value, "p1value"); Assert.Throws <ArgumentException>(() => { pp = new ParameterParser(sql, "@parm1", 123); }); Assert.Throws <ArgumentException>(() => { pp = new ParameterParser(sql, new { parm1 = 123 }); }); IQ.Config.IgnoreCaseParameters = true; pp = new ParameterParser(sql, "@parm1", 123); Assert.AreEqual(pp.Parameters[0].ParameterName, "@Parm1"); Assert.AreEqual(pp.Parameters[0].Value, 123); }
public void CircleTest() { ParameterParser parser = new ParameterParser(); Assert.IsFalse(parser.validateInput("circle", "circle(20, 20)")); }
public void Test_Parameters_Wrong_Amount() { var parameterParser = new ParameterParser(); var parameters = parameterParser.ParseParameters(new string[] { "data.csv", "abc" }); Assert.Null(parameters); }
public void convert(string name, ParameterParser args, Stream from, Stream to) { var obj = MapMarker.ReadFile(from); byte[] buffer = Encoding.Default.GetBytes(Utils.convertToJSON(obj)); to.Write(buffer, 0, buffer.Length); }
public void Test_Parameters_No_filename() { var parameterParser = new ParameterParser(); var parameters = parameterParser.ParseParameters(new string[] { "1000" }); Assert.Null(parameters); }
//--------------------------------------------------------------------- /// <summary> /// Initializes the plug-in with a data file. /// </summary> /// <param name="dataFile"> /// Path to the file with initialization data. /// </param> /// <param name="startTime"> /// Initial timestep (year): the timestep that will be passed to the /// first call to the component's Run method. /// </param> public override void Initialize(string dataFile, PlugIns.ICore modelCore) { Model.Core = modelCore; ParameterParser.EcoregionsDataset = Model.Core.Ecoregions; ParameterParser parser = new ParameterParser(); IParameters parameters = Data.Load<IParameters>(dataFile, parser); Timestep = parameters.Timestep; mapNameTemplate = parameters.MapNamesTemplate; cohorts = Model.Core.SuccessionCohorts as ILandscapeCohorts; if (cohorts == null) throw new ApplicationException("Error: Cohorts don't support age-cohort interface"); SiteVars.Initialize(); Model.Core.RegisterSiteVar(SiteVars.TimeOfLastEvent, "Wind.TimeOfLastEvent"); Event.Initialize(parameters.EventParameters, parameters.WindSeverities); UI.WriteLine("Opening wind log file \"{0}\" ...", parameters.LogFileName); log = Data.CreateTextFile(parameters.LogFileName); log.AutoFlush = true; log.WriteLine("Time,Initiation Site,Total Sites,Damaged Sites,Cohorts Killed,Mean Severity"); }
/// <summary> /// /// </summary> /// <param name="stream">Stream containing the content</param> /// <param name="contentType">Content type header</param> /// <param name="encoding">Stream encoding</param> /// <returns>Collection with all parameters.</returns> /// <exception cref="FormatException">Body format is invalid for the specified content type.</exception> /// <exception cref="InternalServerException">Failed to read all bytes from body stream.</exception> public DecodedData Decode(Stream stream, ContentTypeHeader contentType, Encoding encoding) { if (stream == null || stream.Length == 0) { return(null); } if (encoding == null) { encoding = Encoding.UTF8; } try { var content = new byte[stream.Length]; int bytesRead = stream.Read(content, 0, content.Length); if (bytesRead != content.Length) { throw new InternalServerException("Failed to read all bytes from body stream."); } return(new DecodedData { Parameters = ParameterParser.Parse(new BufferReader(content, encoding)) }); } catch (ArgumentException err) { throw new FormatException(err.Message, err); } }
public void SingleParameter() { ParameterParser parameterParser = new ParameterParser("KEYA=VALUEA"); Assert.AreEqual(1, parameterParser.Parameters.Length); Assert.AreEqual(new Parameter("KEYA", "VALUEA"), parameterParser.Parameters[0]); }
/// Arguments /// [0] - Map Info Path /// [1] - Map starting position file path /// [1] - [Optional] Seed for initial individual state static void Main(string[] args) { var parameters = ParameterParser.GetSimulationParameters(args); var ga = new GeneralGA.GeneralGA(); ga.CreateIndividual = CreateNeighbour; ga.CrossoverEnabled = true; ga.MutationEnabled = true; ga.MutateParentsAsChildren = true; ga.CrossoverIndividuals = DoCrossover; ga.PopulationCount = Configuration.IsRace ? 1 : 500; ga.SpawnPopulation(); List <Parameters> maps = GetMaps(); if (Configuration.IsRace) { var raceCompetitors = new List <ICarAI>() { new HumanCar(), new CarAi(new int[] { 12, 12, 12, 4 }, Random, null) }; StartSimulation(parameters, raceCompetitors.OfType <ICarAI>()); int generation = 0; while (true) { EvaluateAgents(raceCompetitors, maps); generation++; } } else { StartSimulation(parameters, ga.GetPopulation().OfType <ICarAI>()); int generation = 0; while (true) { EvaluateAgents(ga.GetPopulation().OfType <ICarAI>(), maps); ga.DoGeneration(); if (generation % 20 == 0) { var existingFittest = ga.GetFittestIndividual(); var localOffspring = ga.PerformLocalSearch(500); EvaluateAgents(localOffspring.OfType <ICarAI>(), maps); ga.ReplaceIndividual(existingFittest, localOffspring.OrderByDescending(o => o.GetFitness()).First()); } generation++; } } }
public void ShouldGetFromBuildService() { var environmentProvider = Substitute.For <IEnvironmentProvider>(); var buildService = Substitute.For <IBuildService>(); var cloneRoot = Faker.Random.String(10); var commitHash = Faker.Random.String(10); var gitHubOwner = Faker.Random.String(10); var gitHubRepo = Faker.Random.String(10); var token = Faker.Random.String(10); buildService.CloneRoot.Returns(cloneRoot); buildService.CommitHash.Returns(commitHash); buildService.GitHubOwner.Returns(gitHubOwner); buildService.GitHubRepo.Returns(gitHubRepo); environmentProvider.GetEnvironmentVariable("BCC_TOKEN").Returns(token); var parameterParser = new ParameterParser(environmentProvider, buildService); var parameters = parameterParser.Parse(string.Empty); parameters.Should().NotBeNull(); parameters.CloneRoot.Should().Be(cloneRoot); parameters.Hash.Should().Be(commitHash); parameters.Owner.Should().Be(gitHubOwner); parameters.Repo.Should().Be(gitHubRepo); parameters.Token.Should().Be(token); }
public void WithNullInputStr_ShouldThrowException() { var minKeywordLength = 1; Assert.Throws <NullReferenceException>(() => ParameterParser.ParseSearchKeyWordsParameter(null, minKeywordLength)); }
static void Main(string[] args) { // Parse paramters try { // Setup parameters ParameterParser<ConsoleParameters> parser = new ParameterParser<ConsoleParameters>(); ConsoleParameters parms = parser.Parse(args); MessageWriter mw = new MessageWriter(Console.Out, String.IsNullOrEmpty(parms.Verbosity) ? MessageWriter.VerbosityType.Information : (MessageWriter.VerbosityType)Int32.Parse(parms.Verbosity)); System.Diagnostics.Trace.Listeners.Add(mw); if (String.IsNullOrEmpty(parms.Output) || String.IsNullOrEmpty(parms.Assembly)) { Console.WriteLine("Must specify the output and assembly parameters"); return; } FileName = parms.Output; FileContents = GenerateScaffold(parms); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { #if DEBUG System.Console.ReadKey(); #endif } }
public void Parse_WithID_ReturnsDictionaryWithParameter() { var context = BuildContext("http://localhost/test/1", "/test/{id}"); var parameters = ParameterParser.Parse(context); ApiAssert.ContainsParameter(parameters, "id", 1); }
private static void Main(string[] args) { Console.WriteLine("SanteDB Business Rule & CDSS Debugger v{0} ({1})", Assembly.GetEntryAssembly().GetName().Version, Assembly.GetEntryAssembly().GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion); Console.WriteLine(Assembly.GetEntryAssembly().GetCustomAttribute <AssemblyCopyrightAttribute>().Copyright); ParameterParser <DebuggerParameters> parser = new ParameterParser <DebuggerParameters>(); var parameters = parser.Parse(args); if (parameters.Help || args.Length == 0) { parser.WriteHelp(Console.Out); } else if (parameters.Protocol) { new ProtoDebugger(parameters).Debug(); } else if (parameters.BusinessRule) { new BreDebugger(parameters).Debug(); } else { Console.WriteLine("Nothing to do!"); } }
public void Parse_WithParameter_AddsStringToDictionary() { var context = BuildContext("http://localhost/test?param=value", "/test"); var parameters = ParameterParser.Parse(context); ApiAssert.ContainsParameter(parameters, "param", "value"); }
public VmwareMonitor(IAgent agent, string name, Dictionary <string, Variant> args) : base(agent, name, args) { ParameterParser.Parse(this, args); if (!SnapshotIndex.HasValue && string.IsNullOrEmpty(SnapshotName)) { throw new PeachException("Either SnapshotIndex or SnapshotName is required."); } if (SnapshotIndex.HasValue && !string.IsNullOrEmpty(SnapshotName)) { throw new PeachException("Only specify SnapshotIndex or SnapshotName, not both."); } try { GetErrorText(VixError.VIX_OK); } catch (DllNotFoundException ex) { string msg = "VMWare VIX library could not be found. Ensure VIX API 1.12 has been installed. The SDK download can be found at 'http://www.vmware.com/support/developer/vix-api/'"; throw new PeachException(msg, ex); } }
public void Execute(ParameterParser parser) { var parameters = parser.GetActiveParameters(this); Console.WriteLine(Locale.Current["please-wait"]); Api.Current.StaticData.UpdateStaticDataAsync().RunSync(); Api.Current.CachePriceAsync().RunSync(); var itemTypes = new Func <string, IEnumerable <KeyValuePair <long, ItemType> > >(searchString => Api.Current.StaticData.ItemTypes .Where(x => x.Value.IsPublished && (x.Value.Name.Contains(searchString, StringComparison.CurrentCultureIgnoreCase) || x.Value.GroupName.Contains(searchString, StringComparison.CurrentCultureIgnoreCase))) .OrderBy(x => x.Value.Name) .ThenBy(x => x.Value.GroupName) .ThenBy(x => x.Value.Id) .Take(20)); if (parameters.Contains(nameof(ItemIdOf))) { if (string.IsNullOrEmpty(this.ItemIdOf)) { throw new InvalidOperationException("Invalid value"); } var items = itemTypes(this.ItemIdOf); if (this.PricesOf) { ConsoleUtils.WriteTable(new ConsoleTableColumn[] { new ConsoleTableColumn(items.Select(x => x.Value.Id.ToString())), new ConsoleTableColumn(items.Select(x => x.Value.Name)) { Width = 4 }, new ConsoleTableColumn(items.Select(x => Locale.Current[Api.Current.GetItemAveragePrice(x.Value.Id)] + " ISK")) { Width = 2, Alignment = ColumnAlignment.Right } }); } else { ConsoleUtils.WriteTable(new ConsoleTableColumn[] { new ConsoleTableColumn(items.Select(x => x.Value.Id.ToString())), new ConsoleTableColumn(items.Select(x => x.Value.Name)) { Width = 4 }, new ConsoleTableColumn(items.Select(x => x.Value.Group.Name)) { Width = 2 } }); } } }
public LinuxDebugger(IAgent agent, string name, Dictionary <string, Variant> args) : base(agent, name, args) { ParameterParser.Parse(this, args); _exploitable = FindExploitable(); }
static void Main(string[] args) { // Parse paramters try { // Setup parameters ParameterParser <ConsoleParameters> parser = new ParameterParser <ConsoleParameters>(); ConsoleParameters parms = parser.Parse(args); MessageWriter mw = new MessageWriter(Console.Out, String.IsNullOrEmpty(parms.Verbosity) ? MessageWriter.VerbosityType.Information : (MessageWriter.VerbosityType)Int32.Parse(parms.Verbosity)); System.Diagnostics.Trace.Listeners.Add(mw); if (String.IsNullOrEmpty(parms.Output) || String.IsNullOrEmpty(parms.Assembly)) { Console.WriteLine("Must specify the output and assembly parameters"); return; } FileName = parms.Output; FileContents = GenerateScaffold(parms); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { #if DEBUG System.Console.ReadKey(); #endif } }
public void convert(string name, ParameterParser args, Stream from, Stream to) { var obj = ActorExDescription.ReadNew(from); byte[] buffer = Encoding.Default.GetBytes(Utils.convertToJSON(obj)); to.Write(buffer, 0, buffer.Length); }
public void ShouldThrowOnUnknown() { var environmentProvider = Substitute.For <IEnvironmentProvider>(); var buildService = Substitute.For <IBuildService>(); var cloneRoot = Faker.Random.String(10); var commitHash = Faker.Random.String(10); var gitHubOwner = Faker.Random.String(10); var gitHubRepo = Faker.Random.String(10); var token = Faker.Random.String(10); var configuration = Faker.Random.String(10); var annotationCount = Faker.Random.Int(0); buildService.CloneRoot.Returns(cloneRoot); buildService.CommitHash.Returns(commitHash); buildService.GitHubOwner.Returns(gitHubOwner); buildService.GitHubRepo.Returns(gitHubRepo); environmentProvider.GetEnvironmentVariable("BCC_TOKEN").Returns(token); var parameterParser = new ParameterParser(environmentProvider, buildService); new Action(() => parameterParser.Parse($"unknown=value")) .Should().Throw <ArgumentException>() .WithMessage("Unknown key `unknown`"); }
public void MultipleParameters() { ParameterParser parameterParser = new ParameterParser("KEYA=VALUEA", "KEYB=VALUEB"); Assert.Equal(2, parameterParser.Parameters.Length); Assert.Equal(new Parameter("KEYA", "VALUEA"), parameterParser.Parameters[0]); Assert.Equal(new Parameter("KEYB", "VALUEB"), parameterParser.Parameters[1]); }
//--------------------------------------------------------------------- public override void LoadParameters(string dataFile, ICore mCore) { modelCore = mCore; SiteVars.Initialize(mCore); ParameterParser parser = new ParameterParser(); parameters = mCore.Load<IInputParameters>(dataFile, parser); modelCore.Log.WriteLine("Exiting LoadParameters method !!!"); }
/// <summary> /// Represents the main entry point in the command line tool. /// </summary> /// <param name="args"> /// Contains the command line arguments. /// For a complete description of the command line arguments see method TypeHelpPage. /// </param> /// <returns> /// 0 - Success. /// 1 - Error. /// </returns> private static int Main(string[] args) { int result = 1; // Assume error. try { ParameterParser<DatabaseGeneratorParameters> parameterParser = new ParameterParser<DatabaseGeneratorParameters>(DatabaseGeneratorParameters.ParameterListRules); DatabaseGeneratorParameters parameters = parameterParser.ParseParameters(args); if (parameters.IsHelpSpecified) { TypeHelpPage(); result = 0; // Success. } else { Console.WriteLine(GetApplicationNameAndVersion()); if (parameters.IsShowDbSchemaSpecified) { TypeDbSchema(); result = 0; // Success. } else if (parameters.IsRunValidationSpecified) { AutoValidator autoValidator = new AutoValidator( parameters.SqlServerName, parameters.SqlDbName, parameters.SqlUserName, parameters.SqlPassword); result = autoValidator.Validate() ? 0 : 1; } else { Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Active threads: {0}", parameters.Threads)); Console.WriteLine(); DatabaseConnection databaseConnection = DatabaseConnection.CreateSqlServerConnection(parameters.SqlServerName, parameters.SqlDbName, parameters.SqlUserName, parameters.SqlPassword); DatabaseGenerator databaseGenerator = new DatabaseGenerator(parameters, databaseConnection); databaseGenerator.GenerateAndPopulateDatabase().Wait(); result = 0; // Success. } } } catch (Exception ex) { HandleException(ex); } Console.WriteLine(); //// TypePeakMemoryUsage(); return result; }
//--------------------------------------------------------------------- public override void LoadParameters(string dataFile, ICore modelCore) { Model.Core = modelCore; Landis.Library.BiomassHarvest.Main.InitializeLib(Model.Core); Model.Core.UI.WriteLine(" Loading parameters from {0}", dataFile); ParameterParser parser = new ParameterParser(Model.Core.Species); parameters = Landis.Data.Load<Parameters>(dataFile, parser); }
public void Init() { parser = new ParameterParser(); Ecoregions.DatasetParser ecoregionsParser = new Ecoregions.DatasetParser(); reader = OpenFile("Ecoregions.txt"); try { ParameterParser.EcoregionsDataset = ecoregionsParser.Parse(reader); } finally { reader.Close(); } }
public void TestFixtureSetup() { _parser = new ParameterParser<FakeItem>(); _items = new[] { new FakeItem { IntValue = 2, DoubleValue = 2 }, new FakeItem { IntValue = 1, DoubleValue = 1 }, new FakeItem { IntValue = 3, DoubleValue = 3 } }; _nestedItems = new[] { new FakeItem { IntValue = 2, DoubleValue = 2, Children = { new FakeChildItem { ChildStringValue = "1" }, new FakeChildItem { ChildStringValue = "2" }, new FakeChildItem { ChildStringValue = "3" } } }, new FakeItem { IntValue = 1, DoubleValue = 1, Children = { new FakeChildItem { ChildStringValue = "2" }, new FakeChildItem { ChildStringValue = "3" }, new FakeChildItem { ChildStringValue = "4" } } }, new FakeItem { IntValue = 3, DoubleValue = 3, Children = { new FakeChildItem { ChildStringValue = "3" }, new FakeChildItem { ChildStringValue = "4" }, new FakeChildItem { ChildStringValue = "5" } } }, }; }
//--------------------------------------------------------------------- public override void Initialize(string dataFile, PlugIns.ICore modelCore) { Model.Core = modelCore; ParameterParser.EcoregionsDataset = Model.Core.Ecoregions; ParameterParser parser = new ParameterParser(); IParameters parameters = Data.Load<IParameters>(dataFile, parser); Timestep = parameters.Timestep; mapNameTemplate = parameters.MapNamesTemplate; summaryEcoregionEventCount = new int[Model.Core.Ecoregions.Count]; cohorts = Model.Core.SuccessionCohorts as ILandscapeCohorts; if (cohorts == null) throw new ApplicationException("Error: Cohorts don't support age-cohort interface"); SiteVars.Initialize(cohorts); Event.Initialize(parameters.FireParameters, parameters.FireCurves, parameters.WindCurves, parameters.FireDamages); UI.WriteLine("Opening Fire log file \"{0}\" ...", parameters.LogFileName); log = Data.CreateTextFile(parameters.LogFileName); log.AutoFlush = true; log.Write("Time,Initiation Site,Sites Checked,Cohorts Killed,Mean Severity,"); foreach (IEcoregion ecoregion in Model.Core.Ecoregions) { if (ecoregion.Active) log.Write("{0},", ecoregion.Name); } log.Write("TotalSiteInEvent"); log.WriteLine(""); summaryLog = Data.CreateTextFile(parameters.SummaryLogFileName); summaryLog.AutoFlush = true; summaryLog.Write("TimeStep,TotalSitesBurned,TotalNumberEvents"); foreach (IEcoregion ecoregion in Model.Core.Ecoregions) { if (ecoregion.Active) summaryLog.Write(",{0}", ecoregion.Name); } summaryLog.WriteLine(""); }
//--------------------------------------------------------------------- /// <summary> /// Initializes the plug-in with a data file. /// </summary> /// <param name="dataFile"> /// Path to the file with initialization data. /// </param> /// <param name="startTime"> /// Initial timestep (year): the timestep that will be passed to the /// first call to the component's Run method. /// </param> public void Initialize(string dataFile, int startTime) { ParameterParser.EcoregionsDataset = Model.Ecoregions; ParameterParser parser = new ParameterParser(); IParameters parameters = Data.Load<IParameters>(dataFile, parser); timestep = parameters.Timestep; nextTimeToRun = startTime - 1 + timestep; mapNameTemplate = parameters.MapNamesTemplate; SiteVars.Initialize(); Event.Initialize(parameters.EventParameters, parameters.WindSeverities); UI.WriteLine("Opening wind log file \"{0}\" ...", parameters.LogFileName); log = Data.CreateTextFile(parameters.LogFileName); log.AutoFlush = true; log.WriteLine("Time,Initiation Site,Total Sites,Damaged Sites,Cohorts Killed,Mean Severity"); }
//--------------------------------------------------------------------- public override void Initialize(string dataFile, PlugIns.ICore modelCore) { Model.Core = modelCore; cohorts = Model.Core.SuccessionCohorts as ILandscapeCohorts; if (cohorts == null) throw new ApplicationException("Error: Cohorts don't support age-cohort interface"); SiteVars.Initialize(cohorts); ParameterParser parser = new ParameterParser(); IInputParameters parameters = Data.Load<IInputParameters>(dataFile, parser); Timestep = parameters.Timestep; mapNameTemplate = parameters.MapNamesTemplate; dynamicEcos = parameters.DynamicFireRegions; summaryFireRegionEventCount = new int[FireRegions.Dataset.Count]; Event.Initialize(parameters.FireDamages); UI.WriteLine("Opening Fire log file \"{0}\" ...", parameters.LogFileName); log = Data.CreateTextFile(parameters.LogFileName); log.AutoFlush = true; log.Write("Time,InitialSiteRow,InitialSiteColumn,SitesChecked,CohortsKilled,MeanSeverity,"); foreach (IFireRegion ecoregion in FireRegions.Dataset) log.Write("{0},", ecoregion.Name); log.Write("TotalBurnedSites"); log.WriteLine(""); summaryLog = Data.CreateTextFile(parameters.SummaryLogFileName); summaryLog.AutoFlush = true; summaryLog.Write("Time,TotalSitesBurned,TotalNumberEvents"); foreach (IFireRegion ecoregion in FireRegions.Dataset) summaryLog.Write(",{0}", ecoregion.Name); summaryLog.WriteLine(""); }
//--------------------------------------------------------------------- public override void Initialize(string dataFile, PlugIns.ICore modelCore) { Model.Core = modelCore; SiteVars.Initialize(); Model.Core.RegisterSiteVar(SiteVars.Ecoregion, "Fire.Ecoregion"); ParameterParser.EcoregionsDataset = Model.Core.Ecoregions; ParameterParser parser = new ParameterParser(); IParameters parameters = Data.Load<IParameters>(dataFile, parser); //foreach(FuelTypeParameters ftparms in parameters.FuelTypeParameters) // UI.WriteLine(" InitProb = {0}.", ftparms.InitiationProbability); //foreach(FireParameters fparms in parameters.FireParameters) // UI.WriteLine(" MeanSize = {0}.", fparms.MeanSize); Timestep = parameters.Timestep; fireSizeType = parameters.FireSizeType; bui = parameters.BUI; mapNameTemplate = parameters.MapNamesTemplate; Event.Initialize(parameters.SeasonParameters, parameters.FuelTypeParameters,parameters.FireDamages); seasonParameters = parameters.SeasonParameters; windDirectionParameters = parameters.WindDirectionParameters; summaryEcoregionEventCount = new int[Model.Core.Ecoregions.Count]; foreach (IEcoregion ecoregion in Ecoregions.Dataset) { if (ecoregion.MoreEcoregionParameters == null) UI.WriteLine(" Fire Parameters empty."); IMoreEcoregionParameters eventParms = ecoregion.MoreEcoregionParameters; UI.WriteLine(" FireSize={0}, SD={1}", eventParms.MeanSize, eventParms.StandardDeviation); } // Initialize list of sites per ecoregion: foreach (Site site in Model.Core.Landscape) { if (site.IsActive) { IEcoregion ecoregion = SiteVars.Ecoregion[site]; ecoregion.MoreEcoregionParameters.EcoregionSites.Add(site.Location); } } UI.WriteLine(" Opening Fire log file \"{0}\" ...", parameters.LogFileName); log = Data.CreateTextFile(parameters.LogFileName); log.AutoFlush = true; //-----Edited by BRM----- //-----To add Duration log.Write("Time,InitSite,InitEcoregion,InitFuel,InitPercentConifer,SelectedSize,Duration,FireSeason,WindSpeed,WindDirection,FFMC,BUI,PercentCuring,SitesChecked,CohortsKilled,MeanSeverity,"); //---------- foreach (IEcoregion ecoregion in Ecoregions.Dataset) { log.Write("{0},", ecoregion.Name); } log.Write("TotalSitesInEvent"); log.WriteLine(""); summaryLog = Data.CreateTextFile(parameters.SummaryLogFileName); summaryLog.AutoFlush = true; summaryLog.Write("TimeStep, TotalSitesBurned,"); foreach (IEcoregion ecoregion in Ecoregions.Dataset) { summaryLog.Write("{0},", ecoregion.Name); } summaryLog.Write("TotalNumberEvents"); summaryLog.WriteLine(""); }
public void NoParameters() { ParameterParser parameterParser = new ParameterParser(new string[0]); Assert.Equal(0, parameterParser.Parameters.Length); }
static void Main(string[] args) { Console.WriteLine("XML ITS1 Formatter Pregenerator Utility"); Console.WriteLine("Copyright (C) 2012, Mohawk College of Applied Arts and Technology"); ParameterParser<Parameters> parser = new ParameterParser<Parameters>(); try { var arguments = parser.Parse(args); if (arguments.ShowHelp) { ShowHelp(); return; } // Generate formatter utility MARC.Everest.Formatters.XML.ITS1.CodeGen.TypeFormatterCreator creator = new MARC.Everest.Formatters.XML.ITS1.CodeGen.TypeFormatterCreator(); // Create code namespace CodeNamespace ns = new CodeNamespace(arguments.TargetNs); // Load assembly Assembly rmimAssembly = Assembly.LoadFile(arguments.AssemblyFile); List<Type> rmimTypes = new List<Type>(); if (arguments.Interactions != null) foreach (var s in arguments.Interactions) rmimTypes.Add(rmimAssembly.GetTypes().First(o => o.Name == s)); else rmimTypes.AddRange(rmimAssembly.GetTypes()); // Validate parameters if (rmimTypes.Count == 0) throw new ArgumentException("Type array must have at least one element", "t"); // Create a list of types (a todo list) that represent the types we want to format List<Type> types = new List<Type>(200); // Iterate through types and create formatter // Iterate throgh the types foreach (Type type in rmimTypes) { if (type.Assembly != rmimAssembly) throw new InvalidOperationException("All types must belong to the same revision assembly"); GetUniqueTypes(type, types, true); } // Waith thread pool WaitThreadPool wtp = new WaitThreadPool(); try { // Create type definitions foreach (Type t in types) { // Check if we need to gen this type if (t.GetCustomAttributes(typeof(StructureAttribute), false).Length == 0 || s_formatterGenerated.Contains(t)) continue; s_formatterGenerated.Add(t); // Structure Attribute StructureAttribute sta = t.GetCustomAttributes(typeof(StructureAttribute), false)[0] as StructureAttribute; // Type formatter creator TypeFormatterCreator crtr = new TypeFormatterCreator(); // Reset event crtr.CodeTypeDeclarationCompleted += new CreateTypeFormatterCompletedDelegate(delegate(CodeTypeDeclaration result) { // Add to the code currently created if (result != null) lock (ns) ns.Types.Add(result); }); // Helper result wtp.QueueUserWorkItem(crtr.CreateTypeFormatter, t); } // Wait for final pool to clear wtp.WaitOne(); } finally { wtp.Dispose(); } if (ns.Types.Count == 0) { Console.WriteLine("Didn't create any formatter helpers..."); return; } // Setup compiler and referenced assemblies CSharpCodeProvider csharpCodeProvider = new CSharpCodeProvider(); using (TextWriter tw = File.CreateText(arguments.Output ?? "output.cs")) csharpCodeProvider.GenerateCodeFromNamespace(ns, tw, new System.CodeDom.Compiler.CodeGeneratorOptions() { IndentString = "\t" }); } catch (ArgumentNullException) { ShowHelp(); } catch (Exception e) { Console.WriteLine(e.ToString()); return; } finally { } #if DEBUG Console.ReadKey(); #endif }
/// <summary> /// Show help /// </summary> private static void ShowHelp() { Console.WriteLine("\r\nCreates XML ITS1 formatter helper classes and saves the result to a C# file which can be imported into either an Everest or" + "Everest for Windows Phone project. Performing this operation before an application is compiled will greatly increase formatter performance"); ParameterParser<Parameters> parser = new ParameterParser<Parameters>(); parser.WriteHelp(Console.Out); }
public static void Main(string[] args) { ConsoleTraceWriter consoleWriter = null; try { // Create a parser ParameterParser<MifConverterParameters> parser = new ParameterParser<MifConverterParameters>(); parameters = parser.Parse(args); // Create the console writer consoleWriter = new ConsoleTraceWriter(MessageWriter.VerbosityType.Information | MessageWriter.VerbosityType.Fatal | MessageWriter.VerbosityType.Error); // Are there any shortcuts if (parameters.Quiet) consoleWriter.Verbosity = MessageWriter.VerbosityType.None; else if (parameters.ErrorsOnly) consoleWriter.Verbosity = MessageWriter.VerbosityType.Error | MessageWriter.VerbosityType.Fatal; else if (parameters.Debug) consoleWriter.Verbosity = (MessageWriter.VerbosityType)15; else if (parameters.Chatty) consoleWriter.Verbosity = (MessageWriter.VerbosityType)31; else if(parameters.Verbosity != null) consoleWriter.Verbosity = (MessageWriter.VerbosityType)Convert.ToInt32(parameters.Verbosity); // Are we doing anything? bool noAction = !parameters.Help && !parameters.ShowVersion && (args.Length == 0 || parameters.Sources == null || parameters.Sources.Count == 0 || parameters.Renderers == null || parameters.Renderers.Count == 0); // IF no parameters, then help will be displayed // Now default System.Diagnostics.Trace.Listeners.Add(consoleWriter); // Display information Console.WriteLine("General Purpose MIF Converter & Render Tool v{0}", Assembly.GetEntryAssembly().GetName().Version); Console.WriteLine("Copyright (C) 2008-2013 Mohawk College of Applied Arts and Technology"); Console.WriteLine("All rights reserved"); // Load extensions loadAssemblies(consoleWriter); // Help being displayed? if (noAction) { Console.WriteLine("\r\nNothing to do! \r\nUsage:"); Console.WriteLine("gpmr --renderer=xxxx --source=source.mif\r\ngpmr --renderer=xxxx source.mif\r\ngpmr --renderer=xxxx --output-dir=out_dir\r\n"); Console.WriteLine("For parameter listing use : gpmr --help"); } else if (parameters.Help) dumpHelp(); else if (parameters.ShowVersion) dumpVersions(); else processTranformation(); // Write out stats Console.WriteLine("\r\nOperation completed, following messages were generated:"); foreach (KeyValuePair<string, Int32> kv in consoleWriter.MessageCount) Console.WriteLine("{0} -> {1}", kv.Key, kv.Value); Environment.Exit(0); } catch(Exception e) { Console.WriteLine(e.Message); System.Diagnostics.Debug.Print(e.ToString()); Environment.Exit(1); } #if DEBUG System.Console.ReadKey(); #endif }