Pre-parse the command line to extract the value of the --testrunner
        option. This allows a test runner to define additional command line
        arguments.
484348
def run_from_argv(self, argv):
        
        option = '--testrunner='
        for arg in argv[2:]:
            if arg.startswith(option):
                self.test_runner = arg[len(option):]
                break
        super(Command, self).run_from_argv(argv)
850628
def parse_known_args():
    
    parser = argparse.ArgumentParser()
    parser.add_argument('-V', '--version',
                        action='store_true',
                        dest='version',
                        help='Print the version number and exit')
    mutually_exclusive_group = parser.add_mutually_exclusive_group()
    mutually_exclusive_group.add_argument(
        '-v', '--verbose',
        action='store_true',
        help='Show verbose information.'
        ' Higher verbosity can be selected by --verbosity flag')
    parser.add_argument('-o', '--old',
                        type=str,
                        help='Old word to be replaced')
    parser.add_argument('-n', '--new', type=str, help='New replacement word')
    parser.add_argument('-d', '--dry-run', action='store_true', help='Dry Run')

    args, otherthings = parser.parse_known_args()
    return args, otherthings
1369097
def parse(self):
        
        self._options, self._arguments = self._parse_args()
        self._arguments = self._arguments or ['.']

        if not self._validate_options(self._options):
            raise IllegalConfiguration()

        self._run_conf = self._create_run_config(self._options)

        config = self._create_check_config(self._options, use_defaults=False)
        self._override_by_cli = config
700427
function parse(args, optsSpec) {
  if (args[0] == "?") return printHelp()

  optsSpec = optsSpec || {}
  optsSpec.port    = [ "p", Number  ]
  optsSpec.verbose = [ "v", Boolean ]
  optsSpec.help    = [ "h", Boolean ]

  var longOpts   = {}
  var shortOpts  = {}
  var defValues  = {}

  for (var name in optsSpec) {
    var fixedName = name.replace(/_/g, "-")

    var opt = optsSpec[name]

    var shortName = opt[0]
    var type      = opt[1]
    var defValue  = opt[2]

    if (type == Boolean) defValue = false

    shortOpts[shortName] = "--" + fixedName
    longOpts[fixedName]  = type

    if (defValue != null) {
      defValues[fixedName] = defValue
    }
  }

  var parsed = nopt(longOpts, shortOpts, args, 0)

  if (parsed.help) return printHelp()

  var opts

  args = parsed.argv.remain
  opts = _.pick(parsed, _.keys(longOpts))
  opts = _.defaults(opts, defValues)

  if (opts.port == null) {
    if (process.env.PORT != null) opts.port = process.env.PORT
  }

  if (opts.port == null) {
    opts.port = ports.getPort(utils.COMMAND)
  }

  utils.verbose(opts.verbose)

  return {args:args, opts:opts}
}
682750
def parse(cmdline = ARGV)
    vals = {}
    required = {}

    opt :version, "Print version and exit" if @version && ! (@specs[:version] || @long["version"])
    opt :help, "Show this message" unless @specs[:help] || @long["help"]

    @specs.each do |sym, opts|
      required[sym] = true if opts[:required]
      vals[sym] = opts[:default]
      vals[sym] = [] if opts[:multi] && !opts[:default] # multi arguments default to [], not nil
    end

    resolve_default_short_options!

    ## resolve symbols
    given_args = {}
    @leftovers = each_arg cmdline do |arg, params|
      ## handle --no- forms
      arg, negative_given = if arg =~ /^--no-([^-]\S*)$/
        ["--#{$1}", true]
      else
        [arg, false]
      end

      sym = case arg
        when /^-([^-])$/      then @short[$1]
        when /^--([^-]\S*)$/  then @long[$1] || @long["no-#{$1}"]
        else                       raise CommandlineError, "invalid argument syntax: '#{arg}'"
      end

      sym = nil if arg =~ /--no-/ # explicitly invalidate --no-no- arguments

      next 0 if ignore_invalid_options && !sym
      raise CommandlineError, "unknown argument '#{arg}'" unless sym

      if given_args.include?(sym) && !@specs[sym][:multi]
        raise CommandlineError, "option '#{arg}' specified multiple times"
      end

      given_args[sym] ||= {}
      given_args[sym][:arg] = arg
      given_args[sym][:negative_given] = negative_given
      given_args[sym][:params] ||= []

      # The block returns the number of parameters taken.
      num_params_taken = 0

      unless params.nil?
        if SINGLE_ARG_TYPES.include?(@specs[sym][:type])
          given_args[sym][:params] << params[0, 1]  # take the first parameter
          num_params_taken = 1
        elsif MULTI_ARG_TYPES.include?(@specs[sym][:type])
          given_args[sym][:params] << params        # take all the parameters
          num_params_taken = params.size
        end
      end

      num_params_taken
    end

    ## check for version and help args
    raise VersionNeeded if given_args.include? :version
    raise HelpNeeded if given_args.include? :help

    ## check constraint satisfaction
    @constraints.each do |type, syms|
      constraint_sym = syms.find { |sym| given_args[sym] }
      next unless constraint_sym

      case type
      when :depends
        syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym][:long]} requires --#{@specs[sym][:long]}" unless given_args.include? sym }
      when :conflicts
        syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym][:long]} conflicts with --#{@specs[sym][:long]}" if given_args.include?(sym) && (sym != constraint_sym) }
      end
    end

    required.each do |sym, val|
      raise CommandlineError, "option --#{@specs[sym][:long]} must be specified" unless given_args.include? sym
    end

    ## parse parameters
    given_args.each do |sym, given_data|
      arg, params, negative_given = given_data.values_at :arg, :params, :negative_given

      opts = @specs[sym]
      if params.empty? && opts[:type] != :flag
        raise CommandlineError, "option '#{arg}' needs a parameter" unless opts[:default]
        params << (opts[:default].kind_of?(Array) ? opts[:default].clone : [opts[:default]])
      end

      vals["#{sym}_given".intern] = true # mark argument as specified on the commandline

      case opts[:type]
      when :flag
        vals[sym] = (sym.to_s =~ /^no_/ ? negative_given : !negative_given)
      when :int, :ints
        vals[sym] = params.map { |pg| pg.map { |p| parse_integer_parameter p, arg } }
      when :float, :floats
        vals[sym] = params.map { |pg| pg.map { |p| parse_float_parameter p, arg } }
      when :string, :strings
        vals[sym] = params.map { |pg| pg.map(&:to_s) }
      when :io, :ios
        vals[sym] = params.map { |pg| pg.map { |p| parse_io_parameter p, arg } }
      when :date, :dates
        vals[sym] = params.map { |pg| pg.map { |p| parse_date_parameter p, arg } }
      end

      if SINGLE_ARG_TYPES.include?(opts[:type])
        if opts[:multi]       # multiple options, each with a single parameter
          vals[sym] = vals[sym].map { |p| p[0] }
        else                  # single parameter
          vals[sym] = vals[sym][0][0]
        end
      elsif MULTI_ARG_TYPES.include?(opts[:type]) && !opts[:multi]
        vals[sym] = vals[sym][0]  # single option, with multiple parameters
      end
      # else: multiple options, with multiple parameters

      opts[:callback].call(vals[sym]) if opts.key?(:callback)
    end

    ## modify input in place with only those
    ## arguments we didn't process
    cmdline.clear
    @leftovers.each { |l| cmdline << l }

    ## allow openstruct-style accessors
    class << vals
      def method_missing(m, *_args)
        self[m] || self[m.to_s]
      end
    end
    vals
  end
316853
public static void main(String... args) {
        CommandLineRunner runner = new CommandLineRunner();

        try {
            runner.run(args);
        } catch (Exception t) {
            System.err.println(t.getMessage());
            System.err.println("Try '--help' for more information.");

            t.printStackTrace(System.err);

            System.exit(1);
        }

        System.exit(0);
    }
14749
def run_with_standalone_parser(self):
        
        parser = argparse.ArgumentParser(description=self.description())
        self.configure_parser(parser)
        self.run(parser.parse_args())
819920
def parse_command_line_parameters():
    
    usage = 'usage: %prog [options] fasta_filepath'
    version = 'Version: %prog 0.1'
    parser = OptionParser(usage=usage, version=version)

    # A binary 'verbose' flag
    parser.add_option('-p', '--is_protein', action='store_true',
                      dest='is_protein', default=False,
                      help='Pass if building db of protein sequences [default:'
                           ' False, nucleotide db]')

    parser.add_option('-o', '--output_dir', action='store', type='string',
                      dest='output_dir', default=None,
                      help='the output directory [default: directory '
                           'containing input fasta_filepath]')

    opts, args = parser.parse_args()
    num_args = 1
    if len(args) != num_args:
        parser.error('Must provide single filepath to build database from.')

    return opts, args
1280174
def parse_options(self, arg):
        

        if not arg.startswith('-'):
            return False

        value = None
        if '=' in arg:
            arg, value = arg.split('=')

        for option in self._option_list:

            if arg not in (option.shortname, option.longname):
                continue

            action = option.action
            if action:
                action()

            if option.key == option.shortname:
                self._results[option.key] = True
                return True

            if option.boolean and option.default:
                self._results[option.key] = False
                return True

            if option.boolean:
                self._results[option.key] = True
                return True

            # has tag, it should has value
            if not value:
                if self._argv:
                    value = self._argv[0]
                    self._argv = self._argv[1:]

            if not value:
                raise RuntimeError('Missing value for: %s' % option.name)

            self._results[option.key] = option.to_python(value)
            return True

        return False
1304158
public static CommandLine parse(Options options, String... args) throws Exception {
        return CommandLineParser.parse(options, args);
    }
1358406
public void cli(String[] args) {
        CommandLineParser cli = new CommandLineParser();
        cli.addOption(NamedOption.builder()
                .name("data")
                .description("Data to use for training or testing")
                .required(true)
                .type(Resource.class)
                .build());
        cli.addOption(NamedOption.builder()
                .name("format")
                .description("Format for reading data")
                .defaultValue("JSON_OPL")
                .type(String.class)
                .build());
        cli.addOption(NamedOption.builder()
                .name("corpusType")
                .description("Type of corpus to create (e.g. in-memory)")
                .defaultValue("IN_MEMORY")
                .type(CorpusType.class)
                .build());
        cli.addOption(NamedOption.builder()
                .name("mode")
                .description("Train/Test/Split")
                .defaultValue("TEST")
                .type(Mode.class)
                .build());
        cli.addOption(NamedOption.builder()
                .name("model")
                .description("Model to save/load")
                .type(Resource.class)
                .required(true)
                .build());
        cli.addOption(NamedOption.builder()
                .name("undersample")
                .description("Undersample")
                .type(Boolean.class)
                .required(false)
                .defaultValue(false)
                .build());
        cli.addOption(NamedOption.builder()
                .name("oversample")
                .description("Oversample")
                .type(Boolean.class)
                .required(false)
                .defaultValue(false)
                .build());
        cli.parse(args);
        Hermes.initializeApplication(args);

        Dataset<Instance> data = getDataset(cli.get("data"), cli.get("format"), cli.get("corpusType"),
                cli.get("undersample"),
                cli.get("oversample"));

        Mode mode = cli.get("mode");
        switch (mode) {
            case TEST:
                try {
                    this.classifier = Cast.<BasicTextClassifier>as(TextClassifier.read(cli.get("model"))).classifier;
                } catch (Exception e) {
                    throw Throwables.propagate(e);
                }
                test(data);
                break;
            case SPLIT:
                TrainTestSplit<Instance> split = Iterables.getFirst(data.split(0.8), null);
                train(split.getTrain());
                test(split.getTest());
                break;
            case TRAIN:
                train(data);
                try {
                    write(cli.get("model"));
                } catch (Exception e) {
                    throw Throwables.propagate(e);
                }
                break;
            case CV3:
            case CV10:
                TrainTestSet<Instance> folds = data.fold(mode == Mode.CV3 ? 3 : 10);
                ClassifierEvaluation evaluation = new ClassifierEvaluation();
                for (TrainTestSplit<Instance> fold : folds) {
                    train(fold.getTrain());
                    evaluation.merge(test(fold.getTest(), false));
                }
                evaluation.output(System.out);
                break;
            default:
                System.err.println("Unknown option");
        }
    }
634053
def parse_options(arguments=None):
    
    if arguments is None:
        arguments = sys.argv[1:]
    if isinstance(arguments, str):
        arguments = arguments.split()
    if isinstance(arguments, argparse.Namespace):
        return arguments
    parser = create_args_parser()
    args = parser.parse_args(arguments)
    # pprint(args.__dict__)

    args.dialect = args.dialect.lower()
    if args.dialect not in ['lisp', 'newlisp', 'clojure', 'scheme', 'all', '']:
        parser.error("`{0}' is not a recognized dialect".format(args.dialect))

    args.backup_dir = os.path.expanduser(args.backup_dir)
    if not os.path.exists(args.backup_dir):
        parser.error("Directory `{0}' does not exist".format(args.backup_dir))

    if len(args.files) > 1 and args.output_file:
        parser.error('Cannot use the -o flag when more than one file is specified')

    if not args.files:
        # Indentation from standard input
        if args.modify and not args.output_file:
            args.modify = False
        args.backup = False
        args.warning = False

    if args.output_diff:
        # If someone requests a diff we assume he/she doesn't want the file to be
        # modified
        args.modify = False

    return args
1325741
def parse_command_line(args: List[str] = None, final: bool = True) -> List[str]:
    
    return options.parse_command_line(args, final=final)
134452
def parse_known_args(self, args=None, namespace=None):
        """"""
        # run parse args once to make sure the name space is populated with
        # the input files. We'll turn off raising NoInputFileErrors on this
        # pass
        self.no_input_file_err = True
        self._unset_required()
        opts, extra_opts = super(ResultsArgumentParser, self).parse_known_args(
            args, namespace)
        # now do it again
        self.no_input_file_err = False
        self._reset_required()
        opts, extra_opts = super(ResultsArgumentParser, self).parse_known_args(
            args, opts)
        # populate the parameters option if it wasn't specified
        if opts.parameters is None:
            parameters = get_common_parameters(opts.input_file,
                                               collection='variable_params')
            # now call parse parameters action to populate the namespace
            self.actions['parameters'](self, opts, parameters)
        # parse the sampler-specific options and check for any unknowns
        unknown = []
        for fn in opts.input_file:
            fp = loadfile(fn, 'r')
            sampler_parser, _ = fp.extra_args_parser(skip_args=self.skip_args)
            if sampler_parser is not None:
                opts, still_unknown = sampler_parser.parse_known_args(
                    extra_opts, namespace=opts)
                unknown.append(set(still_unknown))
        # the intersection of the unknowns are options not understood by
        # any of the files
        if len(unknown) > 0:
            unknown = set.intersection(*unknown)
        return opts, list(unknown)
1074620
def get_argument_parser():
    
    file_mv = cli.file_mv

    desc = 'Find all runs (SRR..) associated with an SRA experiment (SRX...).'

    parser = cli.get_argument_parser(desc=desc)

    parser.add_argument(
        '-e', '--experiment-file', type=str, required=True, metavar=file_mv,
        help='File with SRA experiment IDs (starting with "SRX").'
    )

    parser.add_argument(
        '-o', '--output-file', type=str, required=True, metavar=file_mv,
        help='The output file.'
    )

    cli.add_reporting_args(parser)

    return parser
160756
def main():
  
  parser = argparse.ArgumentParser(description='A distributed test framework')
  parser.add_argument('testfile',
      help='The file that is used to determine the test suite run')
  parser.add_argument('--test-only',
      nargs='*',
      dest='test_list',
      help='run only the named tests to help debug broken tests')
  parser.add_argument('--machine-list',
      nargs='*',
      dest='machine_list',
      help='''mapping of logical host names to physical names allowing the same
              test suite to run on different hardware, each argument is a pair
              of logical name and physical name separated by a =''')
  parser.add_argument('--config-overrides',
      nargs='*',
      dest='config_overrides',
      help='''config overrides at execution time, each argument is a config with
              its value separated by a =. This has the highest priority of all
              configs''')
  parser.add_argument('-d', '--output-dir',
      dest='output_dir',
      help='''Directory to write output files and logs. Defaults to the current
              directory.''')
  parser.add_argument("--log-level", dest="log_level", help="Log level (default INFO)", default="INFO")
  parser.add_argument("--console-log-level", dest="console_level", help="Console Log level (default ERROR)",
                      default="ERROR")
  parser.add_argument("--nopassword", action='store_true', dest="nopassword", help="Disable password prompt")
  parser.add_argument("--user", dest="user", help="user to run the test as (defaults to current user)")
  args = parser.parse_args()
  try:
    call_main(args)
  except ValueError:
    #We only sys.exit here, as call_main is used as part of a unit test
    #and should not exit the system
    sys.exit(1)
478328
public static void main(String[] args) throws Exception {

		Options opt = new Options();

		opt.addOption("h", false, "Print help for this application");
		opt.addOption("iter", true, "iterative num, default 50");
		opt.addOption("c1", true, "parameters 1, default 1");
		opt.addOption("c2", true, "parameters 2, default 0.1");
		opt.addOption("train", false,
				"switch to training mode(Default: test model");
		opt.addOption("labelwise", false,
				"switch to labelwise mode(Default: viterbi model");
		opt.addOption("margin", false, "use hamming loss as margin threshold");
		opt.addOption("interim", false, "save interim model file");

		BasicParser parser = new BasicParser();
		CommandLine cl;
		try {
			cl = parser.parse(opt, args);
		} catch (Exception e) {
			System.err.println("Parameters format error");
			return;
		}

		if (args.length == 0 || cl.hasOption('h')) {
			HelpFormatter f = new HelpFormatter();
			f.printHelp(
					"Tagger:\n"
							+ "tagger [option] -train templet_file train_file model_file [test_file];\n"
							+ "tagger [option] model_file test_file output_file\n",
							opt);
			return;
		}
		addedTagger tagger = new addedTagger();
		tagger.iterNum = Integer.parseInt(cl.getOptionValue("iter", "50"));
		tagger.c1 = Float.parseFloat(cl.getOptionValue("c1", "1"));
		tagger.c2 = Float.parseFloat(cl.getOptionValue("c2", "0.1"));
		tagger.useLoss = cl.hasOption("margin");
		tagger.interim = cl.hasOption("interim");

		String[] arg = cl.getArgs();
		if (cl.hasOption("train") && arg.length == 3) {
			tagger.templateFile = arg[0];
			tagger.train = arg[1];
			tagger.model = arg[2];
			System.out.println("Training model ...");
			tagger.train();
		} else if (cl.hasOption("train") && arg.length == 4) {
			tagger.templateFile = arg[0];
			tagger.train = arg[1];
			tagger.model = arg[2];
			tagger.testfile = arg[3];
			System.out.println("Training model ...");
			tagger.train();
		} else if (cl.hasOption("train") && arg.length == 5) {
			tagger.templateFile = arg[0];
			tagger.train = arg[1];
			tagger.model = arg[2];
			tagger.testfile = arg[3];
			System.out.println("Training model ...");
			tagger.train();
			System.gc();
			tagger.output = arg[4];
			tagger.test();
		} else if (arg.length == 3) {
			tagger.model = arg[0];
			tagger.testfile = arg[1];
			tagger.output = arg[2];
			tagger.test();
		} else if (arg.length == 2) {
			tagger.model = arg[0];
			tagger.testfile = arg[1];
			tagger.test();
		} else {
			System.err.println("paramenters format error!");
			System.err.println("Print option \"-h\" for help.");
			return;
		}

		System.gc();

	}