private static void PrintHelp(NDesk.Options.OptionSet options) { Logger.WriteLine("{0} Utility, Version: {1}", Tiled2Unity.Info.GetLibraryName(), Tiled2Unity.Info.GetVersion()); Logger.WriteLine("Usage: {0} [OPTIONS]+ TMXPATH [UNITYDIR]", Tiled2Unity.Info.GetLibraryName()); Logger.WriteLine("Example: {0} -s=0.01 MyTiledMap.tmx ../../MyUnityProjectFolder/Assets/Tiled2Unity", Tiled2Unity.Info.GetLibraryName()); Logger.WriteLine(""); Logger.WriteLine("Options:"); TextWriter writer = new StringWriter(); options.WriteOptionDescriptions(writer); Logger.WriteLine(writer.ToString()); Logger.WriteLine("Prefab object properties (set in TMX file for map or Tile/Object layer properties)"); Logger.WriteLine(" unity:sortingLayerName"); Logger.WriteLine(" unity:sortingOrder"); Logger.WriteLine(" unity:layer"); Logger.WriteLine(" unity:tag"); Logger.WriteLine(" unity:scale"); Logger.WriteLine(" unity:isTrigger"); Logger.WriteLine(" unity:convex"); Logger.WriteLine(" unity:ignore (value = [false|true|collision|visual])"); Logger.WriteLine(" unity:resource (value = [false|true])"); Logger.WriteLine(" unity:resourcePath"); Logger.WriteLine(" (Other properties are exported for custom scripting in your Unity project)"); Logger.WriteLine("Support Tiled Map Editor on Patreon: https://www.patreon.com/bjorn"); Logger.WriteLine("Make a donation for Tiled2Unity: http://www.seanba.com/donate"); }
static void Main(string[] args) { try { Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.DarkCyan; Console.Clear(); Console.WriteLine("OTAPI Test Launcher."); var options = new NDesk.Options.OptionSet() .Add("as:|auto-start:", x => Config.AutoStart = true); options.Parse(args); AttachHooks(); if (Config.AutoStart) { StartServer(args); } else { Menu(args); } } catch (Exception ex) { Console.WriteLine(ex); Console.ReadKey(true); } }
static int Main(string[] args) { //arguments: path to xml file, size of fragment, max edit distance, difference between hashes, //using multithreading: 1 - one thread used, 2 - two threads, 3 - three threads try { var options = new NDesk.Options.OptionSet { { "document=", v => FilePath = v }, { "frgamentsize=", v => FragmentSize = int.Parse(v) }, { "maxeditdist=", v => EditDist = int.Parse(v) }, { "maxhashdist=", v => HashDist = int.Parse(v) }, { "threads=", v => NumberOfThreads = int.Parse(v) }, { "language=", v => Language = v } }.Parse(args); var converter = new CloneFinder(FilePath, FragmentSize, EditDist, HashDist, NumberOfThreads, new LanguageSupport(Language)); converter.Run(); return(0); } catch (Exception exception) { Console.Error.WriteLine("Exception was thrown: {0}", exception.Message); Console.Error.WriteLine("Stack:"); Console.Error.WriteLine(exception.StackTrace); return(-1); } }
static void MainSimExportExample(string[] args) { string loginServer = Settings.AGNI_LOGIN_SERVER; string filename = "simexport.tgz"; string regionName = "OpenSim Test", firstName = "My", lastName = "Bot", password = "******"; bool showhelp = false; NDesk.Options.OptionSet argParser = new NDesk.Options.OptionSet() .Add("s|login-server=", "URL of the login server (default is '" + loginServer + "')", delegate(string v) { loginServer = v; }) .Add("r|region-name=", "name of the region to export", delegate(string v) { regionName = v; }) .Add("f|firstname=", "first name of the bot to log in", delegate(string v) { firstName = v; }) .Add("l|lastname=", "last name of the bot to log in", delegate(string v) { lastName = v; }) .Add("p|password="******"password of the bot to log in", delegate(string v) { password = v; }) .Add("o|output=", "filename of the OAR to write (default is 'simexport.tgz')", delegate(string v) { filename = v; }) .Add("h|?|help", delegate(string v) { showhelp = (v != null); }) .Add("v|verbose", delegate(string v) { if (v != null) { ++Verbosity; } }); argParser.Parse(args); if (!showhelp && !String.IsNullOrEmpty(regionName) && !String.IsNullOrEmpty(firstName) && !String.IsNullOrEmpty(lastName) && !String.IsNullOrEmpty(password)) { SimExport exporter = new SimExport(firstName, lastName, password, loginServer, regionName, filename); } else { WriteLine("Usage: SimExport.exe [OPTION]..."); WriteLine("An interactive client for exporting assets"); WriteLine("Options:"); argParser.WriteOptionDescriptions(Console.Out); } }
static bool ParseInput(IEnumerable <string> args, out string inputFile, out string outputFile, out string?puzzle, out string dictionary) { bool help = false; string?i = null, o = null, p = null, d = null; var optionSet = new NDesk.Options.OptionSet { { "i|input=", "(input file)", v => i = v }, { "d|dictionary=", "(dictionary)", v => d = v }, { "o|output=", "(output file)", v => o = v }, { "p|puzzle=", "(puzze)", v => p = v }, { "h|?|help", "(help)", v => help = v != null }, }; var unparsed = optionSet.Parse(args); inputFile = i !; outputFile = o !; puzzle = p; dictionary = d !; if (help || unparsed.Count > 1 || string.IsNullOrEmpty(inputFile) || string.IsNullOrEmpty(outputFile) || string.IsNullOrEmpty(dictionary)) { optionSet.WriteOptionDescriptions(Console.Out); return(false); } return(true); }
private static void ArgsFail(string errMsg, NDesk.Options.OptionSet opts) { _log.Error(errMsg); Console.Error.WriteLine(errMsg); PrintHelp(opts); Environment.Exit(1); }
public override void AddOptions(NDesk.Options.OptionSet optionSet) { optionSet.Add( @"sa|enable-static-alloc", @"Performs static allocations at compile time.", enable => this.Enabled = enable != null); }
protected override void OnStartup(StartupEventArgs e) { // this is necessary since the Start With Windows option puts our directory in System32 if (System.Diagnostics.Debugger.IsAttached == false) { var DirName = System.Reflection.Assembly.GetExecutingAssembly().Location; DirName = System.IO.Path.GetDirectoryName(DirName); System.IO.Directory.SetCurrentDirectory(DirName); } bool bResetAppSettings = false; var options = new NDesk.Options.OptionSet() { { "r|reset", "Reset application settings to default", s => bResetAppSettings = s != null }, { "log", "output debug information to a log file", s => bLog = s != null }, }; options.Parse(e.Args); if (bResetAppSettings) { QuickCutsUI.Properties.Settings.Default.Reset(); } base.OnStartup(e); }
static void Main(string[] args) { string loginServer = Settings.AGNI_LOGIN_SERVER; string filename = "simexport.tgz"; string regionName = null, firstName = null, lastName = null, password = null; bool showhelp = false; NDesk.Options.OptionSet argParser = new NDesk.Options.OptionSet() .Add("s|login-server=", "URL of the login server (default is '" + loginServer + "')", delegate(string v) { loginServer = v; }) .Add("r|region-name=", "name of the region to export", delegate(string v) { regionName = v; }) .Add("f|firstname=", "first name of the bot to log in", delegate(string v) { firstName = v; }) .Add("l|lastname=", "last name of the bot to log in", delegate(string v) { lastName = v; }) .Add("p|password="******"password of the bot to log in", delegate(string v) { password = v; }) .Add("o|output=", "filename of the OAR to write (default is 'simexport.tgz')", delegate(string v) { filename = v; }) .Add("h|?|help", delegate(string v) { showhelp = (v != null); }) .Add("v|verbose", delegate(string v) { if (v != null) ++Verbosity; }); argParser.Parse(args); if (!showhelp && !String.IsNullOrEmpty(regionName) && !String.IsNullOrEmpty(firstName) && !String.IsNullOrEmpty(lastName) && !String.IsNullOrEmpty(password)) { SimExport exporter = new SimExport(firstName, lastName, password, loginServer, regionName, filename); } else { Console.WriteLine("Usage: SimExport.exe [OPTION]..."); Console.WriteLine("An interactive client for exporting assets"); Console.WriteLine("Options:"); argParser.WriteOptionDescriptions(Console.Out); } }
static void Main(string[] args) { M3CpyFlags flags = new M3CpyFlags(); // Parse the options and setup the M3CpyFlags struct for later use. var opt = new NDesk.Options.OptionSet() { { "f|m3u=", v => flags.M3uPath = (v) }, { "o|out=", v => flags.OutputPath = (v) }, { "h|?|help", v => flags.ShowHelp = (v != null) }, { "rm", v => flags.TryErase = (v != null) }, { "v|verbose", v => flags.Verbose = (v != null) }, { "replace", v => flags.Overwrite = (v != null) } }; opt.Parse(args); // First sanity checks, ensure that some arguments were passed and that they're not empty. if (args.Length == 0 || flags.M3uPath == "" || flags.OutputPath == "") { flags.ShowHelp = true; } if (flags.ShowHelp) { DisplayHelp(); } else { ReadM3UAndCopy(flags); } }
public static int Main(string[] args) { log4net.Config.BasicConfigurator.Configure(); log4net.LogManager.GetLogger(typeof(MainClass).FullName).Debug("Started"); _options = new NDesk.Options.OptionSet(). Add("file=", o => _files.Add(o) ). Add("print", o => _action = Print ). Add("console", o => { _action = new CodeConsole().Run; }). Add("scan", o => _action = () => {new BinScanner().AddFiles(_files).Scan(); }). Add("translate", o => _action = () => new SqlTranslator().Select(_unparsed)). Add("help|h|?", o => _action = () => { _options.WriteOptionDescriptions(SysConsole.Error); }); var remains = _options.Parse(args); if(remains != null && remains.Count > 0) _unparsed = string.Join(" ", remains.ToArray()); if(_action == null) { _options.WriteOptionDescriptions(SysConsole.Error); return 1; } _action(); SysConsole.WriteLine("Done"); return 0; }
protected override void AddOptions(NDesk.Options.OptionSet optionSet) { base.AddOptions(optionSet); optionSet.Add("o=|optimizers=", "Load additional optimizer assemblies", delegate(string s) { AddAssembly(s); }); optionSet.Add("d=|datadir=", "Specify directory to store data files", delegate(string s) { d_dataDirectory = s; }); optionSet.Add("l:|list:", "List available optimizers and extensions", delegate(string s) { d_listOptimizers = s != null ? s : ""; }); optionSet.Add("f=|filename=", "Results database filename", delegate(string s) { d_filename = s; }); optionSet.Add("r=|repeat=", "Repeat job N times", delegate(string s) { d_repeat = UInt32.Parse(s); }); optionSet.Add("g=|generate-initial-population=", "Generate initial population into the specified file. Additional command line arguments are databases from which the initial population is drawn. Specific iteration/solution can be specified using 'filename.db[:iteration-id[:solution-id]]'.", delegate(string s) { d_initialPopulation = s; }); optionSet.Add("n=|select-n-best=", "Select N-best solutions to generate initial population from.", delegate(string s) { d_nbest = UInt32.Parse(s); }); }
protected virtual void ParseArguments(ref string[] args) { NDesk.Options.OptionSet optionSet = new NDesk.Options.OptionSet(); AddOptions(optionSet); args = optionSet.Parse(args).ToArray(); }
private static void ShowHelp(NDesk.Options.OptionSet options) { Console.WriteLine("Usage: {0} [OPTIONS]+ <tlpobjdir> <portsdir> <distdir>", AssemblyName()); Console.WriteLine("Generate TeXLive FreeBSD ports"); Console.WriteLine(); Console.WriteLine("Options:"); options.WriteOptionDescriptions(Console.Out); }
private void ShowHelp(NDesk.Options.OptionSet optionSet) { System.Console.WriteLine("Usage: optirunner [OPTIONS] <jobs>"); System.Console.WriteLine(); System.Console.WriteLine("Options:"); optionSet.WriteOptionDescriptions(System.Console.Out); Environment.Exit(0); }
protected virtual void AddOptions(NDesk.Options.OptionSet optionSet) { optionSet.Add("h|help", "Show this help message", s => ShowHelp(optionSet)); optionSet.Add("m=|master=", "Specify master connection string", s => d_masterAddress = s); optionSet.Add("t=|tokensrv=", "Specify token server connection string", s => d_tokenAddress = s); optionSet.Add("token=", "Specify token string", s => d_token = s); optionSet.Add("override-setting=", "Specify override dispatcher settings (key=value)", s => AddOverrideSetting(s)); optionSet.Add("log", "Log various events", s => d_log = true); }
public static int Main(string[] args) { var runtime = new ConsoleRuntime(); string configFile = null; var languages = new List <String>(); string knockoutPrefix = null; string outputFile = null; var optionSet = new NDesk.Options.OptionSet() { { "language=", "", v => languages.Add(v) }, { "knockoutPrefix=", "", v => knockoutPrefix = v }, { "configFile=", "", v => configFile = v }, { "outputFile=", "", v => outputFile = v } }; optionSet.Parse(args); if (!File.Exists(configFile)) { runtime.Error("config file '{0}' does not exist: use, e.g., /configFile=<configFile.xml>", configFile); return(-1); } runtime.Log("Reading config file: " + configFile); var assemblyLoader = new AssemblyLoader(runtime); var generators = languages.Select(language => GetGenerator(language, knockoutPrefix, runtime)).ToArray(); var lines = File.ReadAllLines(configFile); var fileGenerator = new FileGenerator(assemblyLoader); string fileContent; var loaded = fileGenerator.TryGenerate(configFile, lines, runtime, generators, out fileContent); if (!loaded) { runtime.Error("Could not generate the file for " + configFile); return(-2); } var fullOutputFile = Path.GetFullPath(outputFile); if (!File.Exists(fullOutputFile) || File.ReadAllText(fullOutputFile) != fileContent) { runtime.Log("TypeWalker is writing a new version of " + fullOutputFile); File.WriteAllText(fullOutputFile, fileContent); } else { runtime.Log("TypeWalker output file is up to date: " + fullOutputFile); } return(0); }
public static int Main(string[] args) { var runtime = new ConsoleRuntime(); string configFile = null; var languages = new List<String>(); string knockoutPrefix = null; string outputFile = null; var optionSet = new NDesk.Options.OptionSet() { { "language=", "", v => languages.Add(v) }, { "knockoutPrefix=", "", v => knockoutPrefix = v }, { "configFile=", "", v => configFile = v }, { "outputFile=", "", v => outputFile = v } }; optionSet.Parse(args); if (!File.Exists (configFile)) { runtime.Error("config file '{0}' does not exist: use, e.g., /configFile=<configFile.xml>", configFile); return -1; } runtime.Log("Reading config file: " + configFile); var assemblyLoader = new AssemblyLoader(runtime); var generators = languages.Select(language => GetGenerator(language, knockoutPrefix, runtime)).ToArray(); var lines = File.ReadAllLines(configFile); var fileGenerator = new FileGenerator(assemblyLoader); string fileContent; var loaded = fileGenerator.TryGenerate(configFile, lines, runtime, generators, out fileContent); if (!loaded) { runtime.Error("Could not generate the file for " + configFile); return -2; } var fullOutputFile = Path.GetFullPath(outputFile); if (!File.Exists(fullOutputFile) || File.ReadAllText(fullOutputFile) != fileContent) { runtime.Log("TypeWalker is writing a new version of " + fullOutputFile); File.WriteAllText(fullOutputFile, fileContent); } else { runtime.Log("TypeWalker output file is up to date: " + fullOutputFile); } return 0; }
static void Main(string[] args) { try { bool startMainApp = true; NDesk.Options.OptionSet p = new NDesk.Options.OptionSet() .Add("p", pass => { startMainApp = false; SimpleConfiguration config = null; try { config = new SimpleConfiguration("simple.cfg"); if (!config.HasValue("SimpleSalt")) { throw new Exception(); } } catch { Console.WriteLine("simpletorrent: ERROR! Either \"simple.cfg\" does not exist, or the SimpleSalt value has not been defined." + " Please fix this issue before creating a password."); return; } Console.Write("Password (Press enter when done): "); string password = Utilities.ReadLine(); Console.WriteLine("simpletorrent: Benchmarking SCrypt..."); int its; Utilities.SCryptBenchmark(out its); Console.WriteLine(); Console.WriteLine(its + ":" + Convert.ToBase64String( Org.BouncyCastle.Crypto.Generators.SCrypt.Generate(Encoding.UTF8.GetBytes(password), Encoding.UTF8.GetBytes(config.GetValue("SimpleSalt")), its, 8, 1, 32))); }); p.Parse(args); if (startMainApp) { Program prog = new Program(); prog.Start(); prog.Stop(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); Console.WriteLine("==============================\n"); Console.WriteLine("Message: {0}", ex.Message); Console.ReadLine(); } }
private static void PrintHelp(NDesk.Options.OptionSet opts) { _log.InfoFormat("Showing options in console..."); Console.Out.WriteLine($"Usage: examples (--producer|--consumer) --brokers <ip|name>[:port][,<ip|name>[:port]...] --topic=<topic-name> [Options]+"); Console.Out.WriteLine("Options:"); Console.Out.WriteLine(); opts.WriteOptionDescriptions(Console.Out); Console.Out.WriteLine("Press any key to continue..."); Console.In.Read(); }
public void Main(string[] args) { try { _config = new Config(); AppDomain.CurrentDomain.AssemblyResolve += delegate(object sender, ResolveEventArgs sargs) { var asm = typeof(Terraria.Program).Assembly; var resourceName = new AssemblyName(sargs.Name).Name + ".dll"; var text = Array.Find(asm.GetManifestResourceNames(), (string element) => element.EndsWith(resourceName)); if (text == null) { return(null); } using (Stream manifestResourceStream = asm.GetManifestResourceStream(text)) { var array = new byte[manifestResourceStream.Length]; manifestResourceStream.Read(array, 0, array.Length); return(Assembly.Load(array)); } }; Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.DarkCyan; Console.Clear(); Console.WriteLine("OTAPI Test Launcher."); var options = new NDesk.Options.OptionSet() .Add("as:|auto-start:", x => _config.AutoStart = true); options.Parse(args); //AttachHooks(); PreStart?.Invoke(this, EventArgs.Empty); if (_config.AutoStart) { StartGame(args); } else { Menu(args); } } catch (Exception ex) { Console.WriteLine(ex); Console.ReadKey(true); } }
static void HandleOptionsParser(string[] args) { var loadHelp = false; var loadDat = false; var compileToAssembly = false; var generateOutputUnits = false; var verbose = false; var getVersion = false; var p = new NDesk.Options.OptionSet() { { "h|?|help", v => loadHelp = true }, { "load-dat", v => loadDat = true }, { "get-assembly", v => compileToAssembly = true }, { "gen-ou", v => generateOutputUnits = true }, { "verbose", v => verbose = true }, { "version|v", v => getVersion = true }, }; List <string> extra; try { extra = p.Parse(args); } catch (NDesk.Options.OptionException e) { Console.WriteLine(e.Message); return; } if (getVersion) { Console.WriteLine($"v{version}"); return; } if (loadHelp || extra.Count == 0) { ShowHelp(); } else { var filePath = extra[0]; if (loadDat) { AnalyzeDATFile(filePath); } else { CompileDaedalus(filePath, compileToAssembly, verbose, generateOutputUnits); } } }
private static void ParseArguments(IEnumerable <string> args) { var p = new NDesk.Options.OptionSet() .Add("assembly=", "Assembly to process.", s => s_AssemblyPath = s) .Add("output=", "Output path for assembly", s => s_OutputPath = s); var remaining = p.Parse(args); if (remaining.Any()) { Console.Write("Unknown option: " + remaining[0]); throw new NDesk.Options.OptionException(); } }
/// <summary> /// Parses the command line options. Returns extra arguments that were not /// part of the options. In practice, one extra argument should be present: /// the name of the XML file. /// </summary> /// <param name="args">Command line arguments.</param> public static List <string> ParseCommandLineOptions(string[] args) { NDesk.Options.OptionSet p = new NDesk.Options.OptionSet() { { "h|?|help", (string str) => { OptionDisplayHelp = true; } }, { "a|algebra=", (string s) => { Algebras.Add(s.ToLower()); } }, { "s|shuffle", (string s) => { Shuffle = true; } }, { "sa|sample_algebras", (string s) => { SampleAlgebras = true; } }, { "r|reduce=", (int r) => { ReduceNbTestsBy = r; } }, }; List <string> extra = p.Parse(args); return(extra); }
} // end of Main() /// <summary> /// Parses the command line options. Returns extra arguments that were not /// part of the options. In practice, one extra argument should be present: /// the name of the XML file. /// </summary> /// <param name="args">Command line arguments.</param> public static List <string> ParseCommandLineOptions(string[] args) { NDesk.Options.OptionSet p = new NDesk.Options.OptionSet() { { "h|?|help", (string str) => { OptionDisplayHelp = true; } }, { "v|version", (string str) => { OptionDisplayVersion = true; } }, { "s|save=", (string str) => { OptionSaveSpecXmlFile = str; } }, { "f|filelist=", (string str) => { OptionSaveFileListFile = str; } }, { "d|deterministic=", (Boolean B) => G25.CG.Shared.Threads.SetRunThreadsSerially(B) }, }; List <string> extra = p.Parse(args); return(extra); }
public void Main(string[] args) { try { _config = new Config(); AppDomain.CurrentDomain.AssemblyResolve += delegate (object sender, ResolveEventArgs sargs) { var asm = typeof(Terraria.Program).Assembly; var resourceName = new AssemblyName(sargs.Name).Name + ".dll"; var text = Array.Find(asm.GetManifestResourceNames(), (string element) => element.EndsWith(resourceName)); if (text == null) { return null; } using (Stream manifestResourceStream = asm.GetManifestResourceStream(text)) { var array = new byte[manifestResourceStream.Length]; manifestResourceStream.Read(array, 0, array.Length); return Assembly.Load(array); } }; Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.DarkCyan; Console.Clear(); Console.WriteLine("OTAPI Test Launcher."); var options = new NDesk.Options.OptionSet() .Add("as:|auto-start:", x => _config.AutoStart = true); options.Parse(args); //AttachHooks(); PreStart?.Invoke(this, EventArgs.Empty); if (_config.AutoStart) StartGame(args); else Menu(args); } catch (Exception ex) { Console.WriteLine(ex); Console.ReadKey(true); } }
internal AppSettings(string[] args, JRunUI.Properties.Settings defaults ) { LoadFromAppSettings(defaults); defaults.SettingsSaving += new System.Configuration.SettingsSavingEventHandler(defaults_SettingsSaving); var options = new NDesk.Options.OptionSet() { { "f=|file=", "File to load shortcuts from. Default is 'Shortcuts.xml'.", s => XmlFile = s }, { "p=|profile'", "Profile to execute the shortcut in. Default is the first profile.", s => ProfileName = s }, { "s=|selector=", "Program to execute to determine which profile to use.", s => ProfileSelector = s }, { "r|reset", "Reset application settings to default", s => bResetAppSettings = s != null }, { "log", "output debug information to a log file", s => bLog = s != null }, }; options.Parse(args); }
static int Main(string[] args) { bool isAuto = false; NDesk.Options.OptionSet options = new NDesk.Options.OptionSet () { { "a|auto-export", "Automatic export", a => isAuto = true } }; options.Parse (args); if (isAuto) { // Run Tiled2UnityLite with no GUI return Tiled2Unity.Tiled2UnityLite.Run (args); } NSApplication.Init (); NSApplication.Main (args); return 0; }
static void EntryPoint(string[] args) { // Some defaults to use if nothing is passed in. string origin = "1313 Disneyland Dr, Anaheim, CA 92802"; string destination = "Walt Disney World Resort, Orlando, FL 32830"; bool help = false; var p = new NDesk.Options.OptionSet() { { "h|?|help", v => help = v != null }, { "o|origin=", v => origin = v }, { "d|destination=", v => destination = v } }; p.Parse(args); Directions dir = new Directions(origin, destination); Console.WriteLine("Origin lat: " + dir.Origin.Latitude + ", long: " + dir.Origin.Longitude); var originWeather = new Weather(dir.Origin); WeatherData?nullableData = originWeather.GetWeatherEstimateByDateTime(DateTime.UtcNow); if (nullableData.HasValue) { WeatherData data = nullableData.Value; Console.WriteLine("Weather at " + originWeather.Location.Address + ", at " + data.TimeStamp.ToLocalTime() + ", temp: " + data.TemperatureFahrenheit + "°F, humidity: " + (data.Humidity * 100.0f).ToString("0") + ", wind: " + data.WindSpeedMPH + " mph"); } var destinationWeather = new Weather(dir.Destination); nullableData = destinationWeather.GetWeatherEstimateByDateTime(DateTime.UtcNow + dir.Duration); if (nullableData.HasValue) { WeatherData data = nullableData.Value; Console.WriteLine("Weather at " + destinationWeather.Location.Address + ", at " + data.TimeStamp.ToLocalTime() + ", temp: " + data.TemperatureFahrenheit + "°F, humidity: " + (data.Humidity * 100.0f).ToString("0") + ", wind: " + data.WindSpeedMPH + " mph"); } }
private static void Main(string[] args) { var options = new NDesk.Options.OptionSet { { "src=", v => PathSource = v }, { "dst=", v => PathDest = v }, { "n=", v => CommonNamespace = v }, { "jc=", v => JClass = v }, }; options.Parse(args); _schemaDll = Path.Combine(PathDest, CommonNamespace, CommonNamespace + ".dll"); var dest = Path.Combine(PathDest, CommonNamespace); ClearDirectory(dest); var assembly = LoadAssembly(LoadSource(PathSource)); UpdateSchemas(assembly, PathDest); Console.WriteLine("Done"); }
static void Main(string[] args) { string key = null; string token = null; var options = new NDesk.Options.OptionSet { { "key=", k => key = k }, { "token=", t => token = t } }; options.Parse(args); if (string.IsNullOrWhiteSpace(key)) { Usage(); Environment.Exit(1); } var trello = new Trello(key); if (string.IsNullOrWhiteSpace(token)) { var url = trello.GetAuthorizationUrl("TrelloExample", Scope.ReadOnly); Console.WriteLine("No token provided for this app. Get one via this url:"); Console.WriteLine(url); Usage(); Environment.Exit(2); } trello.Authorize(token); foreach (var board in trello.Boards.ForMe()) { Console.WriteLine("Board name: {0}", board.Name); foreach (var card in trello.Cards.ForBoard(board)) { Console.WriteLine("\tCard: {0}", card.Name); } } }
static int Main(string[] args) { bool isAuto = false; NDesk.Options.OptionSet options = new NDesk.Options.OptionSet() { { "a|auto-export", "Automatic export", a => isAuto = true } }; options.Parse(args); if (isAuto) { // Run Tiled2UnityLite with no GUI return(Tiled2Unity.Tiled2UnityLite.Run(args)); } NSApplication.Init(); NSApplication.Main(args); return(0); }
public Configuration(string[] args) { Dictionary <string, string> commandParams = new Dictionary <string, string>(); m_optionsSet = new NDesk.Options.OptionSet() { { "h|help", "show this message and exit.", v => m_showHelp = (v != null) }, { s_dbParamName + "=", "sets the database name to connect.", v => commandParams.Add(s_dbParamName, v) }, { s_serverAddressParamName + "=", "sets the database server address.", v => commandParams.Add(s_serverAddressParamName, v) }, { s_dbUserParamName + "=", "sets the database user name.", v => commandParams.Add(s_dbUserParamName, v) }, { s_dbUserPasswordParamName + "=", "sets the database user password.", v => commandParams.Add(s_dbUserPasswordParamName, v) } }; m_optionsSet.Parse(args); m_databaseName = commandParams.ContainsKey(s_dbParamName) ? commandParams[s_dbParamName] : "webcrawler"; m_server = commandParams.ContainsKey(s_serverAddressParamName) ? commandParams[s_serverAddressParamName] : "127.0.0.1"; m_user = commandParams.ContainsKey(s_dbUserParamName) ? commandParams[s_dbUserParamName] : "root"; m_password = commandParams.ContainsKey(s_dbUserPasswordParamName) ? commandParams[s_dbUserPasswordParamName] : "root"; }
public static bool Load(string[] args) { try { backgroundImageLocation = "BG.jpg"; // this allows dragging the file into the program if (args.Length > 0 && (args[0].Contains(".png") || args[0].Contains(".jpg"))) { backgroundImageLocation = args[0]; } var options = new NDesk.Options.OptionSet() { { "r|restore=", "restore all beatmap backgrounds", r => { if (r != null) { restoreImages = Boolean.Parse(r); } } }, { "c|color=", "color of beatmap backgrounds", c => { if (c != null) { backgroundColor = osuImage.colorFromString(c); } } }, { "d|directory=", "relative directory of beatmap folder ( if different than `Songs` )", d => { if (d != null) { beatmapDirectory = d; } } }, }; options.Parse(args); return(true); } catch (Exception) { return(false); } }
static int Main(string[] args) { bool isAuto = false; NDesk.Options.OptionSet options = new NDesk.Options.OptionSet() { { "a|auto-export", "Automatic export", a => isAuto = true } }; options.Parse(args); if (isAuto) { return(Tiled2UnityLite.Run(args)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); using (Tiled2UnityForm form = new Tiled2UnityForm()) { Application.Run(form); } return(0); }
/// <summary> /// Parses incoming command-line variables and decides what to do (try to run or display help, with or without an error message) /// </summary> /// <param name="args">The original args passed in from the original Main() invocation.</param> /// <returns>0 = continue execution, 1 = display help and return error, 2 = display help and return OK (i.e., help was requested)</returns> private static InitialAction ParseArgs(string[] argsToParse) { InitialAction iaReturn = InitialAction.DisplayHelpWithError; // Invoke NDesk parser to parse incoming arguments // (Based on sample from http://stackoverflow.com/questions/491595/best-way-to-parse-command-line-arguments-in-c) bool bShowHelp = false; bool bTryQuiet = false; string sDebug = ""; bool bUseAppConfig = false; // Note that this gets read BEFORE ParseArgs is called - just here for completeness var p = new NDesk.Options.OptionSet() { { "config=", "the config file", v => sConfigPath = v }, { "help", "show this message and exit", v => bShowHelp = v != null }, { "quiet", "suppress program information and help", v => bTryQuiet = v != null }, { "debug=", "log4net override debug level", v => sDebug = v }, { "useappconfig", "force use of app.config file", v => bUseAppConfig = v != null }, }; List<string> extra; try { extra = p.Parse(argsToParse); } catch { // Parser encountered an error! log.Error("Could not read command line arguments - execution halted!"); return InitialAction.DisplayHelpWithError; } // First set the debug level if (sDebug.Length > 0) { switch (sDebug.ToUpper()) { case "ERROR": ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root.Level = log4net.Core.Level.Error; ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).RaiseConfigurationChanged(EventArgs.Empty); break; case "WARN": ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root.Level = log4net.Core.Level.Warn; ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).RaiseConfigurationChanged(EventArgs.Empty); break; case "INFO": ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root.Level = log4net.Core.Level.Info; ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).RaiseConfigurationChanged(EventArgs.Empty); break; case "DEBUG": ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root.Level = log4net.Core.Level.Debug; ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).RaiseConfigurationChanged(EventArgs.Empty); break; default: log.WarnFormat("Ignoring invalid debug level! Log4Net value of {0} will be used instead.", ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root.Level); break; } } // Look for explicit request for help. If there is one, ignore the quiet flag (otherwise check it appropriately) if (bShowHelp) { return InitialAction.DisplayHelpOK; } else { // If the user didn't explicit ask for help or run into any command line argument exceptions, we should attempt to continue iaReturn = InitialAction.NormalExecution; if (bTryQuiet) { bQuiet = true; } } // Also check to see if the configuration file exists if (!System.IO.File.Exists(sConfigPath)) { log.Error("Could not find configuration file - execution halted!"); return InitialAction.DisplayHelpWithError; } return iaReturn; }
static void Main(string[] args) { DateTime appStart = DateTime.Now; string filePath = "Shortcuts.xml"; string profile = ""; string exportPath = null; string cmd = null; bool bReportTime = false; var options = new NDesk.Options.OptionSet() { { "cmd:|shortcut", "The name of the shortcut to execute.", s => cmd = s }, { "f:|file:", "File to load shortcuts from. Default is 'Shortcuts.xml'.", s => filePath = s }, { "p:|profile:", "Profile to execute the shortcut in. Default is the first profile.", s => profile = s }, //{ "e:|export:", "The SlickRun (.qrs) file to export all of the profile's shortcuts to.", s => exportPath = s }, { "timed", "Prints how long it takes to find and execute the shortcut.", s => bReportTime = s != null }, }; options.Parse(args); if (cmd == null) { if (args.Length > 0 && args[0].Length > 0 && args[0][0] != '-') { cmd = args[0]; } } if (cmd != null) { try { DateTime executeStart = DateTime.Now; var jparams = new ShortcutParams().SetFile(filePath).SetProfile(profile).SetShortcut(cmd); var bSuccess = ShortcutExecutor.ExecuteShortcut(jparams); if (!bSuccess) { Console.WriteLine("Could not find shortcut \"{0}\" for profile \"{1}\" in xml file \"{2}\"", cmd, profile, filePath); } if (bReportTime) { DateTime End = DateTime.Now; TimeSpan appTime = End - appStart; TimeSpan executeTime = End - executeStart; Console.WriteLine("App Time: {0}, Execute Time: {1}", appTime.TotalMilliseconds, executeTime.TotalMilliseconds); Console.ReadKey(); } } catch (Exception ex) { for (var innerEx = ex; innerEx != null; innerEx = innerEx.InnerException) { Console.WriteLine(innerEx.Message); } Console.ReadKey(); } } else if (exportPath != null) { // TODO support exporting shortcuts to other formats } }
private static void ParseCommandLine(string[] args, Options options) { var cmdOptions = new NDesk.Options.OptionSet() .Add<long>("windowId=", "Window handle ({HWND}) to be cloned.", id => { options.WindowId = new IntPtr(id); options.WindowTitle = null; options.WindowClass = null; }) .Add<string>("windowTitle=", "Partial {TITLE} of the window to be cloned.", s => { options.WindowId = null; options.WindowTitle = s; options.WindowClass = null; }) .Add<string>("windowClass=", "{CLASS} of the window to be cloned.", s => { options.WindowId = null; options.WindowTitle = null; options.WindowClass = s; }) .Add("v|visible", "If set, only clones windows that are visible.", s => { options.MustBeVisible = true; }) .Add<Size>("size=", "Target {WIDTH,HEIGHT} of the cloned thumbnail, or", s => { options.StartSize = s; }) .Add<int>("width=", "Target WIDTH of cloned thumbnail, or", i => { if (options.StartSize.HasValue || options.StartHeight.HasValue) return; options.StartWidth = i; }) .Add<int>("height=", "Target HEIGHT of cloned thumbnail.", i => { if (options.StartSize.HasValue || options.StartWidth.HasValue) return; options.StartHeight = i; }) .Add<Size>("position=", "Target {X,Y} of the OnTopReplica window.", s => { options.StartLocation = new Point(s.Width, s.Height); options.StartPositionLock = null; }) .Add<ScreenPosition>("screenPosition=", "Resolution independent window position on current screen, with locking. Values: {TR|TL|C|BR|BL}.", pos => { options.StartLocation = null; options.StartPositionLock = pos; }) .Add<Rectangle>("r|region=", "Region {X,Y,W,H} of the cloned window.", region => { options.Region = new ThumbnailRegion(region); }) .Add<System.Windows.Forms.Padding>("p|padding=", "Region padding {LEFT,TOP,RIGHT,BOTTOM} of the clone.", padding => { options.Region = new ThumbnailRegion(padding); }) .Add<byte>("o|opacity=", "Opacity of the window: {0-255}.", opacity => { options.Opacity = opacity; }) .Add("clickForwarding", "Enables click forwarding.", s => { options.EnableClickForwarding = true; }) .Add("clickThrough", "Enables click through.", s => { options.EnableClickThrough = true; }) .Add("chromeOff", "Disables the window's chrome (border).", s => { options.DisableChrome = true; }) .Add("fs|fullscreen", "Starts up in fullscreen mode.", s => { options.Fullscreen = true; }) .Add("h|help|?", "Show command line help.", s => { options.Status = CliStatus.Information; }); List<string> values; try { values = cmdOptions.Parse(args); } catch (NDesk.Options.OptionException ex) { options.DebugMessageWriter.WriteLine(ex.Message); options.DebugMessageWriter.WriteLine("Try 'OnTopReplica /help' for more information."); options.Status = CliStatus.Error; } if (options.Status == CliStatus.Information) { cmdOptions.WriteOptionDescriptions(options.DebugMessageWriter); } }
// Returns true if the program is to keep going. Will return false if there is an error parsing options or if we were only interested in help/version information private bool ParseOptions(string[] args) { bool displayVersion = false; bool displayHelp = false; bool isAuto = false; NDesk.Options.OptionSet options = new NDesk.Options.OptionSet() { { "o|object-type-xml=", "Supply an Object Type XML file for types and their properties", o => Tiled2Unity.Settings.ObjectTypeXml = !String.IsNullOrEmpty(o) ? Path.GetFullPath(o) : "" }, { "s|scale=", "Scale the output vertices by a value.\nA value of 0.01 is popular for many Unity projects that use 'Pixels Per Unit' of 100 for sprites.\nDefault is 1 (no scaling).", s => Tiled2Unity.Settings.Scale = ParseFloatDefault(s, 1.0f) }, { "c|convex", "Limit polygon colliders to be convex with no holes. Increases the number of polygon colliders in export. Can be overriden on map or layer basis with unity:convex property.", c => Tiled2Unity.Settings.PreferConvexPolygons = true }, { "t|texel-bias=", "Bias for texel sampling.\nTexels are offset by 1 / value.\nDefault value is 8192.\n A value of 0 means no bias.", t => Tiled2Unity.Settings.TexelBias = ParseFloatDefault(t, Tiled2Unity.Settings.DefaultTexelBias) }, { "d|depth-buffer", "Uses a depth buffer to render the layers of the map in order. Useful for sprites that may be drawn below or above map layers depending on location.", d => Tiled2Unity.Settings.DepthBufferEnabled = true }, { "a|auto-export", "Automatically run exporter and exit. TMXPATH and UNITYDIR are not optional in this case.", a => isAuto = true }, { "v|version", "Display version information.", v => displayVersion = true }, { "h|help", "Display this help message.", h => displayHelp = true }, }; // Parse the options List<string> extra = options.Parse(args); // Are we displaying the version? if (displayVersion) { Logger.WriteLine("{0} ({1}) version {2}", Tiled2Unity.Info.GetLibraryName(), Tiled2Unity.Info.GetPlatform(), Tiled2Unity.Info.GetVersion()); return false; } // Are we displaying help? if (displayHelp) { PrintHelp(options); return false; } if (isAuto) { Logger.WriteLine("Running automatic export."); } bool success = true; // If we're here then we're 'running' the program // First left over option is the TMX file we are exporting if (extra.Count() == 0) { Logger.WriteLine("Missing TMXPATH argument."); Logger.WriteLine(" If using the GUI, try opening a TMX file now"); Logger.WriteLine(" If using the command line, provide a path to a TMX file"); Logger.WriteLine(" If using from Tiled Map Editor, try adding %mapfile to the command"); } else { this.TmxFilePath = Path.GetFullPath(extra[0]); if (!File.Exists(this.TmxFilePath)) { Logger.WriteError("TMXPATH file '{0}' does not exist.", this.TmxFilePath); this.TmxFilePath = null; success = false; } extra.RemoveAt(0); } // The next 'left over' option is the Tiled2Unity folder of the Unity project that we are exporting to if (extra.Count() > 0) { this.UnityExportFolderPath = Path.GetFullPath(extra[0]); if (String.IsNullOrEmpty(this.UnityExportFolderPath)) { Logger.WriteError("UNITYDIR argument is not a valid path '{0}'", extra[0]); this.UnityExportFolderPath = null; success = false; } else if (!Directory.Exists(this.UnityExportFolderPath)) { Logger.WriteError("UNITYDIR Unity Tiled2Unity Project Directory '{0}' does not exist", this.UnityExportFolderPath); this.UnityExportFolderPath = null; success = false; } else if (!File.Exists(Path.Combine(this.UnityExportFolderPath, "Tiled2Unity.export.txt"))) { Logger.WriteError("UNITYDIR '{0}' is not a Tiled2Unity Unity Project folder", this.UnityExportFolderPath); this.UnityExportFolderPath = null; success = false; } extra.RemoveAt(0); } // Do we have any other options left over? We shouldn't. if (extra.Count() > 0) { Logger.WriteError("Too many arguments. Can't parse '{0}'", extra[0]); success = false; } if (!success) { Logger.WriteError("Command line arguments: {0}", String.Join(" ", args)); PrintHelp(options); return false; } return true; }
public static void Main(string[] args) { bool defaultPause = !Util.IsUnix; string subject = null; uint limit = 10; bool help = false; bool pause = defaultPause; bool defaults = true; bool largestFiles = false; bool largestDirs = false; bool includeTotals = true; bool rawSize = false; bool license = false; bool fileCountReport = false; var p = new NDesk.Options.OptionSet() { {"l|limit=", v => limit = InOut.parse(v, limit)}, {"h|?|help|version", v => help = v != null}, {"enable-pause", v => pause = v != null}, {"disable-pause", v => pause = v == null}, {"top-files", v => largestFiles = v != null}, {"top-dirs", v => largestDirs = v != null}, {"nodef", v => defaults = v == null}, {"enable-totals", v => includeTotals = v != null}, {"disable-totals", v => includeTotals = v == null}, {"raw-file-length", v => rawSize = v != null}, {"top-file-count", v => fileCountReport = v != null}, {"license", v => license = v != null}, }; List<string> extraArgs = p.Parse(args); subject = InOut.parseSubject(extraArgs); if (subject == null) { help = true; } if (license) { Console.WriteLine(InOut.getLicenseText()); } else if (help) { Func<string, string, KeyValuePair<string, string>> mk = (c, d) => new KeyValuePair<string, string>(c, d); var generalOptionsHelp = new List<KeyValuePair<string, string>> { mk("--limit=LIMIT, -l LIMIT", "number of lines per report (default: 10)"), mk("--enable-pause, --disable-pause", "press any key prompt (default: " + (defaultPause ? "enabled" : "disabled") + ")"), mk("--nodef", "disables default set of reports"), mk("--top-files", "enables largest files report (default: on)"), mk("--top-dirs", "enables largest directories report (default: on)"), mk("--top-file-count", "enables top file count report (default: off)"), mk("--enable-totals, --disable-totals", "toggles totals section (default: enabled)"), mk("--raw-file-length", "output file/directory size in bytes"), mk("--license", "shows license"), mk("--help, -h, --version, /?", "this help page") }; Console.WriteLine("DSR: simple disk usage reporter"); Console.WriteLine("Version: " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()); Console.WriteLine("Usage: dsr [options] path"); Console.WriteLine(""); Console.WriteLine("general options:"); generalOptionsHelp.ForEach(sdef => { int leftMargin = 2; int cmdWidth = generalOptionsHelp.Max(x => x.Key.Length); int descriptionWidth = 80 - leftMargin - cmdWidth - 2 - 1; cmdWidth *= -1; descriptionWidth *= -1; Console.WriteLine(String.Format("{0,2}{1," + cmdWidth + "} {2," + descriptionWidth + "}", "", sdef.Key, sdef.Value)); }); } else { var rq = new Report.StateModel.ReportRequest(); rq.Subject = subject; rq.Timer = new System.Diagnostics.Stopwatch(); rq.RawSizeFormat = rawSize; var trace = new Report.StateModel.SimpleTrace(); var filters = new List<IReportFilter>{ new Report.Filter.FilterRealFiles() }; var reports = new List<IReportGenerator>{}; Action<bool, Func<IReportGenerator>> _insrep = (b, r) => {if (b) reports.Add(r());}; _insrep(defaults || largestFiles, () => new Report.Generator.ReportLargestFiles(rq, limit)); _insrep(defaults || largestDirs, () => new Report.Generator.ReportLargestDirectories(rq, limit)); _insrep(fileCountReport, () => new Report.Generator.ReportTopFileCount(rq, limit)); _insrep(includeTotals, () => new Report.Generator.ReportTotals(rq)); int fileSizeColumnWidth = 0; int totalCaptionColumnWidth = 0; Func<Report.StateModel.ReportResponse, IEnumerable<string>> genTotalLines = (resp) => { return resp.Totals.Select(x => String.Format("{0, -" + (totalCaptionColumnWidth).ToString() + "} {1}", x.Key, x.Value)); }; Action<Report.StateModel.ReportResponse> outputMembers = (resp) => { if (resp.Members.Count > 0) { InOut.outputStdSection(resp.Name, resp.Members.Select(x => { return String.Format("{1," + (fileSizeColumnWidth).ToString() + "} {2}", "", x.FormattedNumber, x.Path); })); } }; var roller = MainRecursiveLoop.make(); rq.Timer.Start(); roller(subject, reports, filters, trace); var results = reports.Select(x => x.getResult()).ToList(); fileSizeColumnWidth = results.Select(x => x.Members).Concat().Select(x => x.FormattedNumber.Length).DefaultIfEmpty(0).Max(); totalCaptionColumnWidth = results.Select(x => x.Totals).Concat().Select(x => x.Key.Length).DefaultIfEmpty(0).Max(); results.ForEach(outputMembers); if (includeTotals) { InOut.outputStdSection("", results.Select(x => genTotalLines(x)).Concat()); } trace.Warning.ForEach(x => Console.WriteLine("WARNING: " + x)); } if (pause) { Console.WriteLine("Press any key to continue . . ."); Console.ReadKey(true); } }
private static void Execute(string[] args) { try { bool showHelp = false; NDesk.Options.OptionSet optionSet = new NDesk.Options.OptionSet { { "f|file=", "the configuration {FILE} to use", v => ConfigurationFile = v }, { "p|path=", "the {PATH} to which the system will save the data file", v => DataPath = v }, { "h|help", "show this message and exit", v => showHelp = v != null }, { "mf|mailfrom=", "the email address {FROM} which the system sends notifications", v => MailFrom = v }, { "mt|mailto=", "the email address {TO} which the system sends notifications", v => MailTo = v }, { "ms|mailserver=", "the SMTP {SERVER} through which the system sends notifications", v => MailServer = v } }; optionSet.Parse(args); if (showHelp) { Console.WriteLine(); ShowHelp(optionSet); return; } // Ensure that the command was invoked with a valid configuration file if (string.IsNullOrWhiteSpace(ConfigurationFile) || !File.Exists(ConfigurationFile) || !IsValidConfigurationFile(ConfigurationFile)) { throw new ArgumentException(string.Format("You must specify a valid configuration file that specifies the weather data source URL(s). Specified file was:\r\n\r\n{0}", ConfigurationFile)); } // Ensure that the command was invoked with a valid data file path if (string.IsNullOrWhiteSpace(DataPath) || !Directory.Exists(DataPath)) { throw new ArgumentException(string.Format("You must specify a valid path in which to store the weather data file(s). Specified path was:\r\n\r\n{0}", DataPath)); } GetWeatherData(); } catch (Exception x) { Console.WriteLine(); Console.WriteLine("ERROR: "); Console.WriteLine(x.Message); Console.WriteLine(); Console.WriteLine("Try 'weatherscraper --help' for more information."); WriteToEventApplicationLog(x); SendMail(x.Message); } }
static void Main(string[] args) { try { bool startMainApp = true; NDesk.Options.OptionSet p = new NDesk.Options.OptionSet() .Add("p", pass => { startMainApp = false; SimpleConfiguration config = null; try { config = new SimpleConfiguration("simple.cfg"); if (!config.HasValue("SimpleSalt")) throw new Exception(); } catch { Console.WriteLine("simpletorrent: ERROR! Either \"simple.cfg\" does not exist, or the SimpleSalt value has not been defined." + " Please fix this issue before creating a password."); return; } Console.Write("Password (Press enter when done): "); string password = Utilities.ReadLine(); Console.WriteLine("simpletorrent: Benchmarking SCrypt..."); int its; Utilities.SCryptBenchmark(out its); Console.WriteLine(); Console.WriteLine(its + ":" + Convert.ToBase64String( Org.BouncyCastle.Crypto.Generators.SCrypt.Generate(Encoding.UTF8.GetBytes(password), Encoding.UTF8.GetBytes(config.GetValue("SimpleSalt")), its, 8, 1, 32))); }); p.Parse(args); if (startMainApp) { Program prog = new Program(); prog.Start(); prog.Stop(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); Console.WriteLine("==============================\n"); Console.WriteLine("Message: {0}", ex.Message); Console.ReadLine(); } }
/// <summary> /// Prevents a default instance of the <see cref="CLAutoThumbnailer"/> class from being created. /// </summary> /// <param name="args">Command line arguments.</param> /// <param name="baseDir">If created via command file the directory of the command file, /// otherwise <c>null</c>.</param> /// <exception cref="NDesk.Options.OptionException">Thrown when option error occurs.</exception> CLAutoThumbnailer(string[] args, string baseDir) { InitializeThumbnailSettings (); InitializeVideoRE (); System.Collections.Specialized.StringCollection fixedArgs = new System.Collections.Specialized.StringCollection (); foreach (string arg in args) { if (arg.EndsWith("\"")) { fixedArgs.Add(arg.Remove(arg.Length-1)); } else fixedArgs.Add(arg); } String[] fixedArgsArray = new String[fixedArgs.Count]; fixedArgs.CopyTo(fixedArgsArray, 0); double doubleInterval = -1; _oset = new NDesk.Options.OptionSet () { { "d|directory=", "{DIRECTORY} to process. Generate thumbnails for\n" + "files with the following extensions:\n" + _videoExtensions, v => _directoryArg = v }, { "exts=", "add/remove video {EXTENSIONS} " + "(\"[+]ext1, -ext2\")", v => { string[] exts = _commaRE.Split(v); foreach (string ext in exts) { string s = ext.Trim().ToLower(); bool addExt = true; if (s[0] == '-') { s = s.Substring(1); addExt = false; } else if (s[0] == '+') { s = s.Substring (1); } if (addExt) { if (_videoExts.Contains (s)) THelper.Error ("Error: '{0}' is already in valid video extensions list.", s); else { THelper.Information ("'{0}' added to valid video extensions list.", s); _videoExts.Add (s); _videoExtsChanged = true; } } else { if (!_videoExts.Contains (s)) THelper.Error ("Error: '{0}' isn't in valid video extensions list.", s); else { THelper.Information ("'{0}' removed from valid video extensions list.", s); _videoExts.Remove (s); _videoExtsChanged = true; } } } if (_videoExtsChanged) { System.Collections.ArrayList temp = System.Collections.ArrayList.Adapter(_videoExts); temp.Sort (); _videoExts = new System.Collections.Specialized.StringCollection (); _videoExts.AddRange ((String[]) temp.ToArray(typeof(string))); } } }, { "minsize=", String.Format("Minimum {{FILESIZE}} of video files (0 to disable) [{0} ({1})]", _minFileSize, ThumbnailCreator.GetFileSizeString(_minFileSize)), (long v) => { if (v < 0) v = 0; _minFileSize = v; } }, { "m|cmddir=", "create initial command file for {DIRECTORY}", v => _cmdDirectory = v }, { "s|start=", String.Format(@"start {{TIME}} in h:mm:ss [{0}]", _tnSettings.Start.ToString(@"h\:mm\:ss")), (TimeSpan v) => _tnSettings.Start = v }, { "e|end=", String.Format(@"end {{TIME}} in h:mm:ss [{0}{1}]", _tnSettings.End.TotalSeconds < 0 ? "-" : "", _tnSettings.End.ToString(@"h\:mm\:ss")), (TimeSpan v) => _tnSettings.End = v }, { "v|overview", String.Format("create Overview page (-v- disables) [{0}]", _createOverview), v => _createOverview = v != null }, { "n=", String.Format("Overview page desired # of {{ROWS or COLUMNS}} [{0}]", _tnSettings.OverviewThumbs), (int v) => { if (v < 1) v = 1; _tnSettings.OverviewThumbs = v; } }, { "c|columns=", String.Format("Overview page actual # of {{COLUMNS}} [{0}]", _tnSettings.OverviewColumns), (int v) => { if (v < 1) v = 1; _tnSettings.OverviewColumns = v; } }, { "r|rows=", String.Format("Overview page actual # of {{ROWS}} [{0}]", _tnSettings.OverviewRows), (int v) => { if (v < 1) v = 1; _tnSettings.OverviewRows = v; } }, { "i|interval=", String.Format("Detail page thumbnail interval {{SECONDS}} [{0:F2}]", _tnSettings.Interval.TotalSeconds), (double v) => { if (v != 0.0 && v < 1.0 / 30.0) v = 1.0 / 30.0; doubleInterval = v; } }, { "autointerval", String.Format("use automatic interval based on duration [{0}]", _autoInterval), v => _autoInterval = v != null }, { "autointervals=", String.Format("automatic interval {{SPECIFICATION}}\n" + "( <min1=secs1, <min2=secs2, <min3=secs3, secs4 )\n" + "[ {0} ]", _intervalsStr), v => { _intervalsStr = v; InitializeAutoIntervals (_intervalsStr); } }, { "N=", String.Format("Detail page desired # of {{ROWS or COLUMNS}} [{0}]", _tnSettings.DetailThumbs), (int v) => { if (v < 1) v = 1; _tnSettings.DetailThumbs = v; } }, { "C|Columns=", String.Format("Detail page actual # of {{COLUMNS}} [{0}]", _tnSettings.DetailColumns), (int v) => { if (v < 1) v = 1; _tnSettings.DetailColumns = v; } }, { "R|Rows=", String.Format("Detail page actual # of {{ROWS}} [{0}]", _tnSettings.DetailRows), (int v) => { if (v < 1) v = 1; _tnSettings.DetailRows = v; } }, { "dfts", String.Format("add Detail page filename timestamps\n" + "(--dfts- disables) [{0}]", _tnSettings.DetailFileTimestamps), v => _tnSettings.DetailFileTimestamps = v != null }, { "y|layout=", String.Format("layout {{MODE}}\n(0=Auto,1=Actual,2=Row Priority,3=Column Priority) [{0}]", _tnSettings.LayoutMode), (int v) => { if (v < 0 || v > 3) v = 0; _tnSettings.LayoutMode = (ThumbnailSettings.LayoutModes) v; } }, { "othres=", String.Format("video aspect ratio {{THRESHOLD}} for\n" + "Auto Layout of Overview Page [{0:F2}]", _tnSettings.OverviewThreshold), (double v) => { if (v != 0.0 && v < 0.2) v = 0.2; if (v > 4.0) v = 4.0; _tnSettings.OverviewThreshold = v; } }, { "dthres=", String.Format("video aspect ratio {{THRESHOLD}} for\n" + "Auto Layout of Detail Pages [{0:F2}]", _tnSettings.DetailThreshold), (double v) => { if (v != 0.0 && v < 0.2) if (v < 0.2) v = 0.2; if (v > 4.0) v = 4.0; _tnSettings.DetailThreshold = v; } }, { "rcopt", String.Format("do row/column optimizations\n" + "(--rcopt- disables) [{0}]", _tnSettings.RCOptimization), v => _tnSettings.RCOptimization = v != null }, { "maxoptsteps=", String.Format("max # of row/column optimization {{STEPS}}\n" + "(0=unlimited) [{0}]", _tnSettings.MaxOptimizationSteps), (int v) => { if (v < 0) v = 0; _tnSettings.MaxOptimizationSteps = v; } }, { "wthres=", String.Format("width {{THRESHOLD}} for adding columns (0.1 - 1.0) [{0:F2}]", _tnSettings.WidthThreshold), (double v) => { if (v < 0.1) v = 0.1; if (v > 1.0) v = 1.0; _tnSettings.WidthThreshold = v; } }, { "hthres=", String.Format("height {{THRESHOLD}} for adding rows (0.1 - 1.0)\n[{0:F2}]", _tnSettings.HeightThreshold), (double v) => { if (v < 0.1) v = 0.1; if (v > 1.0) v = 1.0; _tnSettings.HeightThreshold = v; } }, { "mincols=", String.Format("minimum # of {{COLUMNS}} [{0}]", _tnSettings.MinColumns), (int v) => { if (v < 1) v = 1; _tnSettings.MinColumns = v; } }, { "minrows=", String.Format("minimum # of {{ROWS}} [{0}]", _tnSettings.MinRows), (int v) => { if (v < 1) v = 1; _tnSettings.MinRows = v; } }, { "p|crop=", "crop {ASPECT RATIO}", (double v) => { if (v < 0.2) v = 0.2; if (v > 4.0) v = 4.0; _cropAspect = v; } }, { "rect=", "source {RECTANGLE} ( X,Y+WxH )", v => { System.Text.RegularExpressions.Match m = _rectRE.Match (v); if (!m.Success) throw new NDesk.Options.OptionException ( "Need to specify X,Y+WxH for --rect option.", "--rect"); _srcRect = new System.Drawing.Rectangle (Int32.Parse (m.Groups["x"].Value), Int32.Parse (m.Groups["y"].Value), Int32.Parse (m.Groups["w"].Value), Int32.Parse (m.Groups["h"].Value)); } }, { "t|stretch=", "stretch {ASPECT RATIO}", (double v) => { if (v < 0.2) v = 0.2; if (v > 4.0) v = 4.0; _stretchAspect = v; } }, { "aar", String.Format("do auto aspect ratio adjustment\n" + "(--aar- disables) [{0}]", _autoAspectRatio), v => _autoAspectRatio = v != null }, { "o|outdir=", "Output {DIRECTORY}", v => _outputDirectory = v }, { "subdir=", String.Format("Output sub-directory {{NAME}} [\"{0}\"]", _tnSettings.SubDirectory), v => { if (v=="" || !_subdirRE.IsMatch(v)) throw new NDesk.Options.OptionException ( "Subdirectory name can only contain alphanumerics, '_', and '-'.", "--subdir"); _tnSettings.SubDirectory = v; } }, { "name=", "Display {NAME}", v => _displayFilename = v }, { "l|label=", String.Format("timestamp label {{POSITION}}\n(0=Off,1=LR,2=LL,3=UR,4=UL) [{0}]", _tnSettings.LabelPosition), (int v) => { if (v < 0 || v > 4) v = 1; _tnSettings.LabelPosition = (ThumbnailSettings.LabelPositions) v; } }, { "ms", String.Format("show non-zero millisecond display in timestamps [{0}]", _tnSettings.AlwaysShowMilliseconds), v => _tnSettings.AlwaysShowMilliseconds = v != null }, { "f|scalefactor=", String.Format("page {{SCALE FACTOR}} [{0:F2}]", _tnSettings.ScaleFactor), (double v) => { if (v < 0.25) v = 0.25; if (v > 3.0) v = 3.0; _tnSettings.ScaleFactor = v; } }, { "w|width=", String.Format("page width {{PIXELS}} [{0}]", _tnSettings.Width), (int v) => { if (v < 100) v = 100; _tnSettings.Width = v; } }, { "h|height=", String.Format("page height {{PIXELS}} [{0}]", _tnSettings.Height), (int v) => { if (v < 100) v = 100; _tnSettings.Height = v; } }, { "margin=", String.Format("margin between thumbnails {{PIXELS}} [{0}]", _tnSettings.Margin), (int v) => { if (v < 0) v = 0; _tnSettings.Margin = v; } }, { "border=", String.Format("thumbnail border width {{PIXELS}} [{0}]", _tnSettings.Border), (int v) => { if (v < 0) v = 0; _tnSettings.Border = v; } }, { "save", "save current settings as defaults", v => _saveSettings = v != null }, { "reset", "reset settings to initial defaults", v => _resetSettings = v != null }, { "dumpcr:", "dump # columns/rows diagnostic plot to {FILE}", v => { _dumpCRs = true; if (v != null) { _dumpFilename = v; if (_dumpFilename.Contains ("|")) { string[] parts = _dumpFilename.Split (new char[] { '|' }, 2); _dumpFilename = parts[1]; string flag = parts[0].Trim ().ToLower (); if (flag.StartsWith ("nothr")) _dumpThresholds = false; } } } }, { "debug:", String.Format("show debugging information"), v => { if (v == null) _debug = DebugModes.ShowDebuggingMessages; else { int debug = Int32.Parse (v); if (debug < 0) { debug = -debug; THelper.SetLoggerLevel("mainlogger", System.Diagnostics.SourceLevels.Information); } else { THelper.SetConsoleLevel (System.Diagnostics.SourceLevels.Verbose); } _debug = (DebugModes) debug; } } }, { "?|help", "show this message and exit", v => _show_help = v != null }, { "version", "show version and exit", v => _show_version = v != null }, #if false { "x|maxmulti=", "max # of multi-page {ROWS}", (int v) => _tnSettings.MaxMultiRows = v }, { "n|minoverview=", "minimum # of overview {ROWS}", (int v) => _tnSettings.MinOverviewRows = v }, NDesk.Options.Option rectOption = _oset.Add( ); #endif }; List<string> extra; extra = _oset.Parse (fixedArgsArray); if (_show_help && baseDir != null) { ShowHelp (_oset); return; } if (_debug == DebugModes.ShowDebuggingMessages && baseDir != null) { THelper.Information ("Displaying debugging information."); } if (extra.Count > 0) { _filename = extra[0]; } if (_filename != null) { if (baseDir != null) { if (!System.IO.Path.IsPathRooted (_filename)) _filename = System.IO.Path.Combine (baseDir, _filename); } _fileList = CreateFileList (_filename); if (_fileList == null) { THelper.Critical ("\"" + _filename + "\" doesn't exist."); _filename = null; return; } if (_fileList.Count == 0) { THelper.Critical ("\"" + _filename + "\" doesn't match any files."); _filename = null; _fileList = null; return; } } if (_directoryArg != null) { if (baseDir != null) { if (!System.IO.Path.IsPathRooted(_directoryArg)) _directoryArg = System.IO.Path.Combine(baseDir, _directoryArg); } if (!System.IO.Directory.Exists(_directoryArg)) { _directoryArg = null; THelper.Critical ("\"" + _directoryArg + "\" doesn't exist."); return; } } if (doubleInterval != -1) { int intervalSeconds = (int) Math.Truncate (doubleInterval); int intervalMilliseconds = 0; double fractSeconds = Math.Abs (doubleInterval - (double) intervalSeconds); if (fractSeconds >= 0.001) intervalMilliseconds = (int) (1000 * fractSeconds); _tnSettings.Interval = new TimeSpan (0, 0, 0, intervalSeconds, intervalMilliseconds); } if (_tnSettings.OverviewThreshold == 0.0) _tnSettings.OverviewThreshold = _tnSettings.AspectRatio * _tnSettings.LayoutThresholdAdjustment; if (_tnSettings.DetailThreshold == 0.0) _tnSettings.DetailThreshold = _tnSettings.AspectRatio * _tnSettings.LayoutThresholdAdjustment; }
/// <summary> /// The entry point of the program, where the program control starts and ends. /// </summary> /// <param name="args">The command-line arguments.</param> public static void Main(string[] args) { try { //-user HFYBot -pass password -sub HFY -maxcount 500 string username = ""; string password = ""; string subname = "HFY"; // GetSubreddit will remove /r/ from the front anyways. Lowercase doesn't matter int maxCount = 500; int maxDays = 60; bool fastcutoff = false; bool reallypost = false; bool verbose = false; bool quiet = false; bool showhelp = false; string oAuthClientID = ""; string oAuthClientSecret = ""; var optsParse = new NDesk.Options.OptionSet() { {"user="******"{username} of the account to run this bot under (required).", v => {if (v != null) username=v;} }, {"pass="******"{password} for the account to run this bot under (required).", v => {if (v != null) password=v;} }, {"oauthid=", "{client id} as generated by https://www.reddit.com/prefs/apps (optional).", v => {if (v != null) oAuthClientID=v;} }, {"oauthsecret=", "{client secret} as generated by https://www.reddit.com/prefs/apps (optional).", v => {if (v != null) oAuthClientSecret=v;} }, {"sub=", "{subbedit} to process (optional, defaults to HFY).", v => {if (v != null) subname=v;} }, {"maxcount=", "{max} # of posts to scan (optional, defaults to 500).", (int v) => maxCount=v }, {"maxdays=", "{max} # of days to scan into the past for unprocessed posts (optional, defaults to 60).", (int v) => maxDays=v }, {"fastcutoff", "if set, then only considers posts made after the last HFY bot comment.", v => { if (v != null) fastcutoff=true; } }, {"reallypost", "if set, the posts are actually made; if not set, then dumped to console.", v => { if (v != null) reallypost=true; } }, {"v|verbose", "if set, then progress lines are displayed as the posts and comments are built.", v => { if (v != null) verbose=true; } }, {"q|quiet", "if set, then as little output as possible is generated.", v => { if (v != null) quiet=true; } }, {"h|help", "show this help.", v => { if (v != null) showhelp=true; } }, }; try { List<string> leftovers = optsParse.Parse(args); } catch (NDesk.Options.OptionException e) { Console.WriteLine(e.Message); Console.WriteLine("Try 'hfybot --help' for more information."); return; } if (showhelp) { optsParse.WriteOptionDescriptions(Console.Out); return; } if (username == "" || password == "") { Console.WriteLine("Username and password must be supplied."); System.Environment.Exit(0); } if (subname == "") { Console.WriteLine("Subbedit name must be supplied."); System.Environment.Exit(0); } if (maxCount < 1 || maxCount > 500) maxCount = 500; // enforce default if (maxDays < 1 || maxDays > 90) maxDays = 60; // enforce default if (verbose) quiet = false; if (oAuthClientID != "" && oAuthClientSecret != "") { // Log in via oauth (which still requires the username and password, but also a secondary username and password called a client id and secret) if (!quiet) Console.WriteLine("Logging in user {0} via OAUTH2 protocol...", username); try { authProvider = new AuthProvider(oAuthClientID, oAuthClientSecret, "http://reddit.com"); authTokenString = authProvider.GetOAuthToken(username, password); if (authTokenString == "") { Console.WriteLine("Login for user {0} (user:{1}) refused, empty token returned.", oAuthClientID, username); System.Environment.Exit(0); } if (verbose) Console.WriteLine("Auth token is {0}", authTokenString); reddit = new Reddit(authTokenString); } catch (System.Security.Authentication.AuthenticationException) { Console.WriteLine("Login for user {0} (user:{1}) refused.", oAuthClientID, username); System.Environment.Exit(0); } catch (System.Net.WebException we) { Console.WriteLine("Network error when connecting to reddit. Please check your connection. {0}",we.ToString()); System.Environment.Exit(0); } } else { // Log in without oauth in a traditional mode. if (!quiet) Console.WriteLine("Logging in user {0}...", username); try { reddit = new Reddit(username, password); } catch (System.Security.Authentication.AuthenticationException) { Console.WriteLine("Login for user {0} refused.", username); System.Environment.Exit(0); } catch (System.Net.WebException we) { Console.WriteLine("Network error when connecting to reddit. Please check your connection. {0}",we.ToString()); System.Environment.Exit(0); } } reddit.RateLimit = WebAgent.RateLimitMode.Burst; if (!quiet) Console.WriteLine("Login successful. Getting sub {0}...", subname); RedditSharp.Things.Subreddit subit = reddit.GetSubreddit(subname); if (subit == null) { Console.WriteLine("Subbedit {0} does not exist.", subname); System.Environment.Exit(0); } if (!quiet) { Console.WriteLine("Processing posts and creating new comments as needed (maxcount={0}, maxdays={1}).", maxCount, maxDays); if (!reallypost) Console.WriteLine("NOTE: running in TEST mode only, will not actually make comments."); } ProcessNewPosts prm = new ProcessNewPosts(reddit, subit); prm.Run(maxCount, maxDays, fastcutoff, reallypost, verbose); } catch (Exception e) { Console.WriteLine("General exception: {0}", e.ToString()); System.Environment.Exit(0); } }
static void Main(string[] args) { string inputPath = null; string outputPath = null; string methodName = null; double percentRemoved = 0.5; int targetTriangles = 0; bool showHelp = false; bool verbose = false; bool target = false; bool ratio = false; var options = new NDesk.Options.OptionSet() { {"i|input=", "The input file.", value => inputPath = value }, {"o|output=", "The output file", value => outputPath = value }, {"m|method=", "The used method.", value => methodName = value }, {"h|help", "Shows help message and exit.", value => showHelp = value != null }, {"r|ratio=", "The percentage of triangles to remove", value => { percentRemoved = Convert.ToDouble(value, System.Globalization.CultureInfo.InvariantCulture.NumberFormat); ratio = true; } }, {"t|target=", "The target number of triangles", value => { targetTriangles = Convert.ToInt32(value); target = true; } }, {"v|verbose", "Verbose", value => verbose = value != null }, }; List<string> extra; Console.WriteLine("Terramesh Remesh Converter"); Console.WriteLine("Grzybowski & Ruchwa (C) 2012"); Console.WriteLine(); try { extra = options.Parse(args); } catch (NDesk.Options.OptionException e) { Console.WriteLine("{0}", e.Message); } if (showHelp) { Console.WriteLine("Usage: trcm [OPTIONS]"); options.WriteOptionDescriptions(Console.Out); return; } if (verbose) { Console.WriteLine(@"Verbose mode."); } try { if (inputPath != null && outputPath != null && methodName != null && (ratio || target)) { if (verbose) { Console.WriteLine(@"Converting '{0}' to '{1}' using '{2}' method", inputPath, outputPath, methodName); } var inFile = new FileStream(inputPath, FileMode.Open); var outFile = new FileStream(outputPath, FileMode.Create); var reader = new Remeshing.MeshReader(inFile); var writer = new Remeshing.MeshWriter(outFile); var verticesIn = new List<Remeshing.Vertex>(); var indicesIn = new List<int>(); var verticesOut = new List<Remeshing.Vertex>(); var indicesOut = new List<int>(); Remeshing.IRemeshingMethod method = null; switch (methodName) { case "asem": { method = new Remeshing.AngleSumErrorMetricMethod(); break; } case "rem": { method = new Remeshing.RandomRemeshingMethod(); break; } default: { Console.WriteLine("Unknown method name."); return; } } if (verbose) { Console.WriteLine("Using '{0}' method.", method.GetType().ToString()); } reader.ReadMesh(out verticesIn, out indicesIn, new Listener("Reading")); var mesh = new Remeshing.Mesh(ref verticesIn, ref indicesIn); if (ratio) { method.Process(ref mesh, percentRemoved, new Listener("Remeshing")); } else { method.Process(ref mesh, targetTriangles, new Listener("Remeshing")); } mesh.Save(out verticesOut, out indicesOut); writer.WriteMesh(ref verticesOut, ref indicesOut, new Listener("Writing")); } else { Console.WriteLine("Not all required arguments specified. Please use: ./trc --help to show help message."); } } catch (Exception e) { Console.WriteLine(e.Message); } }
public static void Main(string[] args) { int[,] refimg = null; int[,] img1 = null; bool show_help = false; bool useheuristic = false; bool decompose = false; bool imgcmp = false; string imgcomparer = "sceneparse.FullPixelDiffImageComparer"; IVisNode[] genos = null; int numiter = int.MaxValue; var opset = new NDesk.Options.OptionSet() { {"r|ref=", "the {REF} image file", (string v) => { refimg = LoadImage(v); useheuristic = true; }}, {"i|img=", "the {IMAGE} file to load", (string v) => { img1 = LoadImage(v); }}, {"g|gen=", "comma,separted {LIST} of objects", (string v) => { var objnames = v.Split(','); genos = new IVisNode[objnames.Length]; for (int i = 0; i < objnames.Length; ++i) { var nv = objnames[i].DeepCopy(); if (!nv.Contains(".")) nv = "sceneparse."+nv; genos[i] = (IVisNode)Activator.CreateInstance(Type.GetType(nv)); } }}, {"l|load=", "object {TYPE} to load", (string v) => { var nv = v.DeepCopy(); if (!nv.Contains(".")) nv = "sceneparse."+nv; var diri = new DirectoryInfo(v); var fil = diri.GetFiles("*.xml"); genos = new IVisNode[fil.Length]; for (int i = 0; i < fil.Length; ++i) { genos[i] = DeSerializeFromFile(fil[i].FullName); } }}, {"d|decompose=", "comma,separted {LIST} of objects", (string v) => { var objnames = v.Split(','); genos = new IVisNode[objnames.Length]; for (int i = 0; i < objnames.Length; ++i) { var nv = objnames[i].DeepCopy(); if (!nv.Contains(".")) nv = "sceneparse."+nv; genos[i] = (IVisNode)Activator.CreateInstance(Type.GetType(nv)); } numiter = 100; decompose = true; useheuristic = true; }}, {"t|itr=", "number of {ITERATIONS} to go", (string v) => { numiter = int.Parse(v); }}, {"m|comparer=", "the {COMPARER} to use", (string v) => { imgcomparer = v.DeepCopy(); if (!imgcomparer.Contains("ImageComparer")) imgcomparer += "ImageComparer"; if (!imgcomparer.Contains(".")) imgcomparer = "sceneparse."+imgcomparer; }}, {"topgm=", "png {FILE} to convert", (string v) => { LoadImage(v).ToPGM(v.ReplaceExtension("pgm")); }}, {"topbm=", "png {FILE} to convert", (string v) => { LoadImage(v).ToPBM(v.ReplaceExtension("pbm")); }}, {"topng=", "pnm {FILE} to convert", (string v) => { LoadImage(v).ToPNG(v.ReplaceExtension("png")); }}, {"u|uheu", "use heuristic", (string v) => { if (v != null) { useheuristic = true; } }}, {"c|compare", "compare images", (string v) => { if (v != null) { imgcmp = true; } }}, {"h|help", "show this message and exit", (string v) => { show_help = (v != null); }}, }; List<string> extrargs; try { extrargs = opset.Parse (args); } catch (NDesk.Options.OptionException e) { Console.Write (Constants.myname+": "); Console.WriteLine (e.Message); Console.WriteLine ("Try `"+Constants.myname+" --help' for more information."); return; } if (show_help) { ShowHelp(opset); return; } if (imgcmp) { if (refimg == null) { Console.WriteLine("need ref img"); } else if (img1 == null) { Console.WriteLine("need img"); } else { int xout = 0; int yout = 0; IImageComparer imgc = (IImageComparer)Activator.CreateInstance(Type.GetType(imgcomparer), new object[] {refimg}); //IImageComparer imgc = new PixelPropImageComparer(refimg); //int heuv = 0; int heuv = imgc.CompareImg(img1, ref xout, ref yout); //int heuv = SlidingImgComp2(refimg, img1, ref xout, ref yout); Console.WriteLine(heuv+" at "+xout+","+yout); } } if (decompose) { int imgn = 0; int[,] fullimg = new int[refimg.Width(),refimg.Height()]; int[,] supstruct = new int[refimg.Width(),refimg.Height()]; int[,] rendertarg = new int[refimg.Width(),refimg.Height()]; int subimgn = 0; var search = new SearchAstar<IVisNode>((IVisNode cn) => { Console.WriteLine(cn.Describe()); Console.WriteLine(); if (rendertarg != null) { cn.Data.CopyMatrix(rendertarg, cn.StartX, cn.StartY); rendertarg.ToPBM("out"+subimgn+"-"+imgn); rendertarg.SetRegion(0, cn.StartX, cn.StartX+cn.Data.Width()-1, cn.StartY, cn.StartY+cn.Data.Height()-1); } else { cn.Data.ToPBM("out"+subimgn+"-"+imgn); } cn.SerializeToFile("out"+subimgn+"-"+imgn); ++imgn; }); int BestHeu = int.MaxValue; IVisNode BestNode = null; IImageComparer imgc = (IImageComparer)Activator.CreateInstance(Type.GetType(imgcomparer), new object[] {refimg}); search.FlushNodeCache = imgc.FlushNodeCache; search.FullFlushNodeCache = imgc.FullFlushNodeCache; search.NodeHeuristic = (IVisNode cn) => { //return 0; // disable heuristic return imgc.CompareImg(cn); }; search.NodeTermination = (IVisNode cn) => { if (cn.Heuv < BestHeu) { BestHeu = cn.Heuv; BestNode = cn; search.Lifetime = numiter; } if (cn.Heuv <= 0) { return true; } Console.WriteLine("current heuv is"+cn.Heuv); return false; }; while (true) { search.Lifetime = numiter; search.AddNewRange(genos); search.Run(); Console.WriteLine("object type is"+BestNode.Name); Console.WriteLine("object description is"+BestNode.Describe()); Console.WriteLine("heuristic value is "+BestNode.Heuv); if (rendertarg != null) { BestNode.Data.CopyMatrix(rendertarg, BestNode.StartX, BestNode.StartY); rendertarg.ToPBM("outresult"+subimgn); //rendertarg.SetRegion(0, BestNode.StartX, BestNode.StartX+BestNode.Data.Width()-1, BestNode.StartY, BestNode.StartY+BestNode.Data.Height()-1); } else { BestNode.Data.ToPBM("outresult"+subimgn); } BestNode.SerializeToFile("outresult"+subimgn); supstruct[BestNode.StartX+BestNode.Width/2, BestNode.StartY+BestNode.Height/2] = 255; supstruct.ToPBM("outresult-sup"); fullimg = fullimg.AddMatrix(rendertarg); fullimg.ToPBM("outresult-full"); imgc = (IImageComparer)Activator.CreateInstance(Type.GetType(imgcomparer), new object[] {refimg, fullimg}); if (!genos.Contains(BestNode)) genos = genos.AddResize(BestNode); //rendertarg.SetAll(0); rendertarg.SetRegion(0, BestNode.StartX, BestNode.StartX+BestNode.Data.Width()-1, BestNode.StartY, BestNode.StartY+BestNode.Data.Height()-1); search.Reset(); ++subimgn; if (search.BestHeu <= 0) break; } } else if (genos != null) { int imgn = 0; int[,] rendertarg = null; if (refimg != null) { rendertarg = new int[refimg.Width(),refimg.Height()]; } var search = new SearchAstar<IVisNode>((IVisNode cn) => { Console.WriteLine(cn.Describe()); Console.WriteLine(); if (rendertarg != null) { cn.Data.CopyMatrix(rendertarg, cn.StartX, cn.StartY); rendertarg.ToPBM("out"+imgn); rendertarg.SetRegion(0, cn.StartX, cn.StartX+cn.Data.Width()-1, cn.StartY, cn.StartY+cn.Data.Height()-1); } else { cn.Data.ToPBM("out"+imgn); } cn.SerializeToFile("out"+imgn); ++imgn; }); int BestHeu = int.MaxValue; IVisNode BestNode = null; if (useheuristic) { IImageComparer imgc = (IImageComparer)Activator.CreateInstance(Type.GetType(imgcomparer), new object[] {refimg}); search.FlushNodeCache = imgc.FlushNodeCache; search.FullFlushNodeCache = imgc.FullFlushNodeCache; search.NodeHeuristic = (IVisNode cn) => { //return 0; // disable heuristic return imgc.CompareImg(cn); }; search.NodeTermination = (IVisNode cn) => { if (cn.Heuv < BestHeu) { BestHeu = cn.Heuv; BestNode = cn; } if (cn.Heuv <= 0) { return true; } Console.WriteLine("current heuv is"+cn.Heuv); return false; }; } search.Lifetime = numiter; search.AddNewRange(genos); search.Run(); if (useheuristic) { Console.WriteLine("object type is"+BestNode.Name); Console.WriteLine("object description is"+BestNode.Describe()); Console.WriteLine("heuristic value is "+BestNode.Heuv); if (rendertarg != null) { BestNode.Data.CopyMatrix(rendertarg, BestNode.StartX, BestNode.StartY); rendertarg.ToPBM("outresult"); rendertarg.SetRegion(0, BestNode.StartX, BestNode.StartX+BestNode.Data.Width()-1, BestNode.StartY, BestNode.StartY+BestNode.Data.Height()-1); } else { BestNode.Data.ToPBM("outresult"); } BestNode.SerializeToFile("outresult"); } } }
/// <summary> /// Parses the command line options. Returns extra arguments that were not /// part of the options. In practice, one extra argument should be present: /// the name of the XML file. /// </summary> /// <param name="args">Command line arguments.</param> public static List<string> ParseCommandLineOptions(string[] args) { NDesk.Options.OptionSet p = new NDesk.Options.OptionSet() { { "h|?|help", (string str) => {OptionDisplayHelp = true;} }, { "v|version", (string str) => {OptionDisplayVersion = true;} }, { "s|save=", (string str) => {OptionSaveSpecXmlFile = str;} }, { "f|filelist=", (string str) => {OptionSaveFileListFile = str;} }, { "d|deterministic=", (Boolean B) => G25.CG.Shared.Threads.SetRunThreadsSerially(B) }, }; List<string> extra = p.Parse(args); return extra; }
private static void Main(string[] args) { var logicDurationWatch = new Stopwatch(); logicDurationWatch.Start(); _executingDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); _gameServerRepository = "https://github.com/LeagueSandbox/GameServer.git"; _repositoryBranch = "indev"; _gameServerSourceFileName = "GameServer-Source"; _copyBuildToFolder = "Compiled-GameServer"; _needsCopied = true; _pauseAtEnd = true; _configJson = ""; _needsConfig = true; _configurationMode = "Release"; _onlyPrintBranches = false; var p = new NDesk.Options.OptionSet { { "gameServerRepository=", "The game server repository", v => _gameServerRepository = v }, { "repositoryBranch=", "The game server repository branch", v => _repositoryBranch = v }, { "gameServerSourceFileName=", "Game server source folder name", v => _gameServerSourceFileName = v }, { "copyBuildToFolder=", "The folder that the build gets copied to", v => _copyBuildToFolder = v }, { "needsCopied=", "Does it need copied even if it doesn't need built?", (bool v) => _needsCopied = v }, { "needsConfig=", "Does it need JSON config?", (bool v) => _needsConfig = v }, { "pauseAtEnd=", "Should it be pasued at the end?", (bool v) => _pauseAtEnd = v }, { "configJSON=", "The config JSON for the compiled game server.", v => _configJson = v }, { "onlyPrintBranches=", "Only print the repository branches and exit", (bool v) => _onlyPrintBranches = v } }; try { p.Parse(args); } catch (NDesk.Options.OptionException e) { Console.WriteLine($"Command line error: {e.Message}"); return; } Console.WriteLine("Welcome to the GameServer updater!"); bool needsCompiled; Console.WriteLine($"Repository: {_gameServerRepository}, Branch: {_repositoryBranch}"); if (_onlyPrintBranches) { Console.WriteLine("Repository Branches:"); foreach (var refer in Repository.ListRemoteReferences(_gameServerRepository)) { if (refer.IsLocalBranch) { var name = refer.CanonicalName; name = name.Replace("refs/heads/", ""); Console.WriteLine(name); } } Console.WriteLine("End Repository Branches"); if (_pauseAtEnd) { Console.ReadKey(true); } return; } if (IsRepositoryValid(_gameServerSourceFileName, _repositoryBranch)) { Console.WriteLine("Repository is valid, fetching updates."); //Get current commit var lastUpdate = GetLastRepositoryCommit(_gameServerSourceFileName, _repositoryBranch); Console.WriteLine($"Old Commit: {lastUpdate}"); FetchServer(); //Get current commit, compare to past var newUpdate = GetLastRepositoryCommit(_gameServerSourceFileName, _repositoryBranch); Console.WriteLine($"New Commit: {newUpdate}"); needsCompiled = !lastUpdate.Equals(newUpdate); } else { //Download repository Console.WriteLine("Repository is invalid, downloading updates."); DownloadServer(); needsCompiled = true; } if (needsCompiled) { Console.WriteLine("Compiling server."); CompileServer(); } if (_needsCopied) { Console.WriteLine("Copying server."); //Copy server to build location CopyCompiledBuild(); //Create config file for copied build if (_needsConfig) { CreateConfigFile(); } } Console.WriteLine("Everything is completed."); logicDurationWatch.Stop(); var timeElapsed = logicDurationWatch.ElapsedMilliseconds; Console.WriteLine($"Time took: {timeElapsed / 1000.0} seconds"); if (_pauseAtEnd) { Console.Write("Press any key to exit. "); Console.ReadKey(true); } }
public void CommandBenchmarkMessageBuilder(CommandModel cmd) { Trace.Call(cmd); var count = 1000; var showHelp = false; var appendMessage = false; var appendText = false; var appendEvent = false; var appendFormat = false; var toMessage = false; try { var opts = new NDesk.Options.OptionSet() { { "c|count=", v => count = Int32.Parse(v) }, { "m|append-message", v => appendMessage = true }, { "t|append-text", v => appendText = true }, { "e|append-event", v => appendEvent = true }, { "f|append-format", v => appendFormat = true }, { "T|to-message", v => toMessage = true }, }; opts.Add("h|?|help", x => { showHelp = true; var writer = new StringWriter(); opts.WriteOptionDescriptions(writer); AddMessageToFrontend( cmd, CreateMessageBuilder(). AppendHeader("{0} usage", cmd.Command). AppendText("\n"). AppendText("Parameters:\n"). AppendText(writer.ToString()). ToMessage() ); return; }); opts.Parse(cmd.Parameter.Split(' ')); if (showHelp) { return; } } catch (Exception ex) { AddMessageToFrontend( cmd, CreateMessageBuilder(). AppendErrorText("Invalid parameter: {0}", ex.Message). ToMessage() ); return; } DateTime start, stop; start = DateTime.UtcNow; MessageBuilder builder; for (var i = 0; i < count; i++) { builder = new MessageBuilder(); if (appendMessage) { builder.AppendMessage("This is message with a link to https://www.smuxi.org/."); } if (appendText) { builder.AppendText("This is message with just text."); } if (appendEvent) { builder.AppendEventPrefix(); } if (appendFormat) { builder.AppendFormat("{0} [{1}] has joined {2}", "meebey3", "[email protected]", "#smuxi-devel"); } if (toMessage) { var msg = builder.ToMessage(); } } stop = DateTime.UtcNow; builder = new MessageBuilder(); builder.AppendText("MessageBuilder()."); if (appendMessage) { builder.AppendText("AppendMessage()."); } if (appendText) { builder.AppendText("AppendText()."); } if (appendEvent) { builder.AppendText("AppendEventPrefix()."); } if (appendFormat) { builder.AppendText("AppendFormat()."); } if (toMessage) { builder.AppendText("ToMessage()"); } builder.AppendText( " count: {1} took: {2:0} ms avg: {3:0.00} ms", cmd.Data, count, (stop - start).TotalMilliseconds, (stop - start).TotalMilliseconds / count ); AddMessageToFrontend(cmd, builder.ToMessage()); }
static bool ParseInput(IEnumerable<string> args, out string inputFile, out string outputFile, out string puzzle, out string dictionary) { bool help = false; string i = null, o = null, p = null, d = null; var optionSet = new NDesk.Options.OptionSet { { "i|input=", "(input file)", v => i = v }, { "d|dictionary=", "(dictionary)", v => d = v }, { "o|output=", "(output file)", v => o = v }, { "p|puzzle=", "(puzze)", v => p = v }, { "h|?|help", "(help)", v => help = v != null }, }; var unparsed = optionSet.Parse(args); inputFile = i; outputFile = o; puzzle = p; dictionary = d; if (help || unparsed.Count > 1 || string.IsNullOrEmpty(inputFile) || string.IsNullOrEmpty(outputFile) || string.IsNullOrEmpty(dictionary)) { optionSet.WriteOptionDescriptions(Console.Out); return false; } return true; }
private static void ParseCommandLine(string[] args, Options options) { var cmdOptions = new NDesk.Options.OptionSet() .Add<long>("windowId=", "Window handle ({HWND}) to be cloned.", id => { options.WindowId = new IntPtr(id); }) .Add<string>("windowTitle=", "{TITLE} of the window to be cloned.", s => { options.WindowTitle = s; }) .Add<string>("windowClass=", "{CLASS} of the window to be cloned.", s => { options.WindowClass = s; }) .Add("v|visible", "If set, only clones windows that are visible.", s => { options.MustBeVisible = true; }) .Add<Size>("size=", "Target {SIZE} of the cloned thumbnail.", s => { options.StartSize = s; }) .Add<Size>("position=", "Target {COORDINATES} of the OnTopReplica window.", s => { options.StartLocation = new Point(s.Width, s.Height); options.StartScreenPosition = null; }) .Add<ScreenPosition>("screenPosition=", "Resolution independent window position on current screen, with locking (TR|TL|C|BR|BL).", pos => { options.StartLocation = null; options.StartScreenPosition = pos; }) .Add<Rectangle>("r|region=", "Region {BOUNDS} of the original window.", region => { options.Region = region; }) .Add<byte>("o|opacity=", "Opacity of the window (0-255).", opacity => { options.Opacity = opacity; }) .Add("clickForwarding", "Enables click forwarding.", s => { options.EnableClickForwarding = true; }) .Add("chromeOff", "Disables the window's chrome (border).", s => { options.DisableChrome = true; }) .Add("fs|fullscreen", "Starts up in fullscreen mode.", s => { options.Fullscreen = true; }) .Add("h|help|?", "Show command line help.", s => { options.Status = CliStatus.Information; }); List<string> values; try { values = cmdOptions.Parse(args); } catch (NDesk.Options.OptionException ex) { options.DebugMessageWriter.WriteLine(ex.Message); options.DebugMessageWriter.WriteLine("Try 'OnTopReplica /help' for more information."); options.Status = CliStatus.Error; } if (options.Status == CliStatus.Information) { cmdOptions.WriteOptionDescriptions(options.DebugMessageWriter); } }