For a given command line supplied argument, negotiate the content, parse
    the schema and then return any issues to stdout or if no schema issues,
    return success exit code.
766938
def main(source):
    
    if source is None:
        click.echo(
            "You need to supply a file or url to a schema to a swagger schema, for"
            "the validator to work."
        )
        return 1
    try:
        load(source)
        click.echo("Validation passed")
        return 0
    except ValidationError as e:
        raise click.ClickException(str(e))
1087965
def parse_args(argv=None):
    
    parent_parser = get_parent_parser()

    # Main parser
    desc = "Data Version Control"
    parser = DvcParser(
        prog="dvc",
        description=desc,
        parents=[parent_parser],
        formatter_class=argparse.RawTextHelpFormatter,
    )

    # NOTE: On some python versions action='version' prints to stderr
    # instead of stdout https://bugs.python.org/issue18920
    parser.add_argument(
        "-V",
        "--version",
        action=VersionAction,
        nargs=0,
        help="Show program's version.",
    )

    # Sub commands
    subparsers = parser.add_subparsers(
        title="Available Commands",
        metavar="COMMAND",
        dest="cmd",
        help="Use dvc COMMAND --help for command-specific help.",
    )

    fix_subparsers(subparsers)

    for cmd in COMMANDS:
        cmd.add_parser(subparsers, parent_parser)

    args = parser.parse_args(argv)

    return args
657135
private static boolean parseArguments(String args[],
                                        Configuration conf) {
    int argsLen = (args == null) ? 0 : args.length;
    StartupOption startOpt = StartupOption.REGULAR;
    for(int i=0; i < argsLen; i++) {
      String cmd = args[i];
      if ("-r".equalsIgnoreCase(cmd) || "--rack".equalsIgnoreCase(cmd)) {
        LOG.error("-r, --rack arguments are not supported anymore. RackID " +
            "resolution is handled by the NameNode.");
        System.exit(-1);
      } else if ("-rollback".equalsIgnoreCase(cmd)) {
        startOpt = StartupOption.ROLLBACK;
      } else if ("-regular".equalsIgnoreCase(cmd)) {
        startOpt = StartupOption.REGULAR;
      } else if ("-d".equalsIgnoreCase(cmd)) {
        ++i;
        if(i >= argsLen) {
          LOG.error("-D option requires following argument.");
          System.exit(-1);
        }
        String[] keyval = args[i].split("=", 2);
        if (keyval.length == 2) {
          conf.set(keyval[0], keyval[1]);
        } else {
          LOG.error("-D option invalid (expected =): " + args[i]);
          System.exit(-1);
        }
      } else
        return false;
    }
    setStartupOption(conf, startOpt);
    return true;
  }
1261174
def get_parser(output_formats=[], conf=None):
    

    def _conf_or_default(key, value):
        return value if conf is None else conf.get_or_set(key, value)

    parser = ArgumentParser(description='crate shell')
    parser.add_argument('-v', '--verbose', action='count',
                        dest='verbose', default=_conf_or_default('verbosity', 0),
                        help='print debug information to STDOUT')
    parser.add_argument('-A', '--no-autocomplete', action='store_false',
                        dest='autocomplete',
                        default=_conf_or_default('autocomplete', True),
                        help='disable SQL keywords autocompletion')
    parser.add_argument('-a', '--autocapitalize', action='store_true',
                        dest='autocapitalize',
                        default=False,
                        help='enable automatic capitalization of SQL keywords while typing')
    parser.add_argument('-U', '--username', type=str, metavar='USERNAME',
                        help='Authenticate as USERNAME.')
    parser.add_argument('-W', '--password', action='store_true',
                        dest='force_passwd_prompt', default=_conf_or_default('force_passwd_prompt', False),
                        help='force a password prompt')
    parser.add_argument('--schema', type=str,
                        help='default schema for statements if schema is not explicitly stated in queries')
    parser.add_argument('--history', type=str, metavar='FILENAME',
                        help='Use FILENAME as a history file', default=HISTORY_PATH)
    parser.add_argument('--config', type=str, metavar='FILENAME',
                        help='use FILENAME as a configuration file', default=CONFIG_PATH)

    group = parser.add_mutually_exclusive_group()
    group.add_argument('-c', '--command', type=str, metavar='STATEMENT',
                       help='Execute the STATEMENT and exit.')
    group.add_argument('--sysinfo', action='store_true', default=False,
                       help='print system and cluster information')

    parser.add_argument('--hosts', type=str, nargs='*',
                        default=_conf_or_default('hosts', ['localhost:4200']),
                        help='connect to HOSTS.', metavar='HOSTS')
    parser.add_argument('--verify-ssl', type=boolean, default=True,
                        help='force the verification of the server SSL certificate')
    parser.add_argument('--cert-file', type=file_with_permissions, metavar='FILENAME',
                        help='use FILENAME as the client certificate file')
    parser.add_argument('--key-file', type=file_with_permissions, metavar='FILENAME',
                        help='Use FILENAME as the client certificate key file')
    parser.add_argument('--ca-cert-file', type=file_with_permissions, metavar='FILENAME',
                        help='use FILENAME as the CA certificate file')
    parser.add_argument('--format', type=str,
                        default=_conf_or_default('format', 'tabular'),
                        choices=output_formats, metavar='FORMAT',
                        help='the output FORMAT of the SQL response')
    parser.add_argument('--version', action='store_true', default=False,
                        help='print the Crash version and exit')

    return parser
1035375
def parse_command_line():
    

    import argparse

    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument('-v',
                        '--version',
                        action='version',
                        version='%(prog)s ' + __version__,
                        help="Show version number and exit.")
    parser.add_argument('input_filename',
                        metavar='INPUT_FILE',
                        type=str,
                        help='Path of the input file to be preprocessed')
    parser.add_argument('-q',
                        '--quiet',
                        dest='should_be_quiet',
                        action='store_true',
                        default=False,
                        help="Disables verbose logging")
    parser.add_argument('-L',
                        '--log-level',
                        '--logging-level',
                        dest='logging_level',
                        choices=[
                            'DEBUG',
                            'INFO',
                            'WARNING',
                            'ERROR',
                            'CRITICAL',
                            'NONE',
                            ],
                        default='INFO',
                        help="Logging level.")
    parser.add_argument('-o',
                        '--output',
                        metavar="OUTPUT_FILE",
                        dest='output_filename',
                        default=None,
                        help='Output file name (default STDOUT)')
    parser.add_argument('-f',
                        '--force',
                        dest='should_force_overwrite',
                        action='store_true',
                        default=False,
                        help='Force overwrite existing output file.')
    parser.add_argument('-D',
                        '--define',
                        metavar="EXPR",
                        dest='definitions',
                        action='append',
                        help="""\
Define a variable for preprocessing. <define>
can simply be a variable name (in which case it
will be true) or it can be of the form
<var>=<val>. An attempt will be made to convert
<val> to an integer so -D 'FOO=0' will create a
false value.""")
    parser.add_argument('-I',
                        '--include',
                        metavar="DIR_PATH",
                        dest='include_paths',
                        action='append',
                        default=['.'],
                        help='Add a directory to the include path for #include directives.')
    parser.add_argument('-k',
                        '--keep-lines',
                        dest='should_keep_lines',
                        action='store_true',
                        default=False,
                        help='''\
Emit empty lines for preprocessor statement
lines and skipped output lines. This allows line
numbers to stay constant.''')
    parser.add_argument('-s',
                        '--substitute',
                        dest='should_substitute',
                        action='store_true',
                        default=False,
                        help='''\
Substitute #defines into emitted lines.
(Disabled by default to avoid polluting strings)''')
    parser.add_argument('--default-content-type',
                        metavar="CONTENT_TYPE",
                        dest='default_content_type',
                        default=None,
                        help='If the content type of the file cannot be determined this will be used. (Default: an error is raised)')
    parser.add_argument('-c',
                        '--content-types-path',
                        '--content-types-config',
                        metavar="PATH",
                        dest='content_types_config_files',
                        default=[],
                        action='append',
                        help="""\
Specify a path to a content.types file to assist
with file type determination. Use the -p or -P flags
to display content types as read by pepe.""")
    parser.add_argument('-p',
                        '--print-content-types',
                        dest='should_print_content_types',
                        action='store_true',
                        default=False,
                        help='Display content types and exit.')
    parser.add_argument('-P',
                        '--print-content-types-config',
                        dest='should_print_content_types_config',
                        action='store_true',
                        default=False,
                        help='Display content types configuration and exit.')
    return parser.parse_args()
5189
def parse(args)
      @options = {
        reporters: [DEFAULT_REPORTER],
      }

      OptionParser.new do |parser|
        parser.banner = "Usage: #{parser.program_name} [options] [scss-files]"

        add_display_options parser
        add_linter_options parser
        add_file_options parser
        add_info_options parser
      end.parse!(args)

      # Any remaining arguments are assumed to be files
      @options[:files] = args

      @options
    rescue OptionParser::InvalidOption => e
      raise SCSSLint::Exceptions::InvalidCLIOption,
            e.message,
            e.backtrace
    end
778924
@SuppressWarnings({"checkstyle:cyclomaticcomplexity", "checkstyle:npathcomplexity"})
	public static String[] parseCommandLine(String[] args) {
		final CommandLineParser parser = new DefaultParser();
		try {
			final CommandLine cmd = parser.parse(getOptions(), args, false);

			boolean noLogo = false;
			boolean embedded = false;
			boolean userClasspath = false;
			int verbose = LoggerCreator.toInt(JanusConfig.VERBOSE_LEVEL_VALUE);

			final Iterator<Option> optIterator = cmd.iterator();
			while (optIterator.hasNext()) {
				final Option opt = optIterator.next();
				String optName = opt.getLongOpt();
				if (Strings.isNullOrEmpty(optName)) {
					optName = opt.getOpt();
				}
				switch (optName) {
				case CLI_OPTION_HELP_LONG:
					showHelp(true);
					return null;
				case CLI_OPTION_VERSION:
					showVersion(true);
					return null;
				case CLI_OPTION_SHOWDEFAULTS_LONG:
					showDefaults();
					return null;
				case CLI_OPTION_SHOWCLASSPATH:
					setDefaultClasspath(userClasspath);
					showClasspath();
					return null;
				case CLI_OPTION_SHOWCLIARGUMENTS_LONG:
					showCommandLineArguments(args);
					return null;
				case CLI_OPTION_FILE_LONG:
					final String rawFilename = opt.getValue();
					if (rawFilename == null || "".equals(rawFilename)) { //$NON-NLS-1$
						showHelp(true);
					}
					final File file = new File(rawFilename);
					if (!file.canRead()) {
						showError(MessageFormat.format(Messages.Boot_0,
								rawFilename), null);
						return null;
					}
					setPropertiesFrom(file);
					break;
				case CLI_OPTION_CLASSPATH_LONG:
					userClasspath = true;
					addToSystemClasspath(opt.getValue());
					break;
				case CLI_OPTION_OFFLINE_LONG:
					setOffline(true);
					break;
				case CLI_OPTION_RANDOMID_LONG:
					setRandomContextUUID();
					break;
				case CLI_OPTION_BOOTID_LONG:
					setBootAgentTypeContextUUID();
					break;
				case CLI_OPTION_WORLDID_LONG:
					setDefaultContextUUID();
					break;
				case CLI_OPTION_DEFINE_LONG:
					final String name = opt.getValue(0);
					if (!Strings.isNullOrEmpty(name)) {
						setProperty(name, Strings.emptyToNull(opt.getValue(1)));
					}
					break;
				case CLI_OPTION_LOG_LONG:
					verbose = Math.max(LoggerCreator.toInt(opt.getValue()), 0);
					break;
				case CLI_OPTION_QUIET_LONG:
					if (verbose > 0) {
						--verbose;
					}
					break;
				case CLI_OPTION_VERBOSE_LONG:
					++verbose;
					break;
				case CLI_OPTION_NOLOGO_LONG:
					noLogo = true;
					break;
				case CLI_OPTION_EMBEDDED_LONG:
					embedded = true;
					break;
				default:
				}
			}

			setDefaultClasspath(userClasspath);

			// Show the help when there is no argument.
			if (cmd.getArgs().length == 0) {
				showHelp(true);
				return null;
			}

			// Change the verbosity
			setVerboseLevel(verbose);
			// Do nothing at exit
			if (embedded) {
				setExiter(() -> {
					ExecutorService.neverReturn();
				});
			}
			// Show the Janus logo?
			if (noLogo || verbose == 0) {
				setProperty(JanusConfig.JANUS_LOGO_SHOW_NAME, Boolean.FALSE.toString());
			}
			return cmd.getArgs();
		} catch (IOException | ParseException e) {
			showError(e.getLocalizedMessage(), e);
			// Event if showError never returns, add the return statement for
			// avoiding compilation error.
			return null;
		}
	}
201013
private static CommandLine parseCommandLine(Options options, String[] args) throws ParseException {
        CommandLineParser parser = new GroovyInternalPosixParser();
        return parser.parse(options, args, true);
    }
1289528
def _cmdline(argv=None):
    
    parser = ArgumentParser()
    parser.add_argument("-c", "--config", action="append",
            help="config file [etc/config.yml]")
    parser.add_argument("-v", "--version", action="version",
            version="pipsort {:s}".format(__version__),
            help="print version and exit")
    parser.add_argument("-w", "--warn", default="WARNING",
            help="logger warning level [WARNING]")
    parser.add_argument("search_term", type=str,
                        help="Search term for PyPI")
    args = parser.parse_args(argv)
    if not args.config:
        args.config = ["etc/config.yml"]
    return args
33666
private CommandLine parseArgs(String[] args) throws ParseException {
        final CommandLineParser parser = new DefaultParser();
        final Options options = createCommandLineOptions();
        return parser.parse(options, args);
    }
997244
def parse(self, *args, **kw):
        """"""

        ev = 'errex' in kw and kw.pop('errex')
        if ev and not isinstance(ev, int):
            raise TypeError("error exit value should be an integer")

        try:
            self.cmdline = self.parser.parse_args(*args, **kw)
        except OptParseError:
          if ev:
              sys.exit(ev)
          raise

        return self.fuse_args
678424
def validate_args(**args):
	
	if not args['query']:
		print("\nMissing required query argument.")
		sys.exit()

	for key in DEFAULTS:
		if key not in args:
			args[key] = DEFAULTS[key]

	return args
373468
def parse_arguments(argv):
  
  parser = argparse.ArgumentParser(
      description='Runs Preprocessing on structured data.')
  parser.add_argument('--output-dir',
                      type=str,
                      required=True,
                      help='Google Cloud Storage which to place outputs.')

  parser.add_argument('--schema-file',
                      type=str,
                      required=False,
                      help=('BigQuery json schema file'))
  parser.add_argument('--input-file-pattern',
                      type=str,
                      required=False,
                      help='Input CSV file names. May contain a file pattern')

  # If using bigquery table
  # TODO(brandondutra): maybe also support an sql input, so the table can be
  # ad-hoc.
  parser.add_argument('--bigquery-table',
                      type=str,
                      required=False,
                      help=('project:dataset.table_name'))

  args = parser.parse_args(args=argv[1:])

  if not args.output_dir.startswith('gs://'):
    raise ValueError('--output-dir must point to a location on GCS')

  if args.bigquery_table:
    if args.schema_file or args.input_file_pattern:
      raise ValueError('If using --bigquery-table, then --schema-file and '
                       '--input-file-pattern, '
                       'are not needed.')
  else:
    if not args.schema_file or not args.input_file_pattern:
      raise ValueError('If not using --bigquery-table, then --schema-file and '
                       '--input-file-pattern '
                       'are required.')

    if not args.input_file_pattern.startswith('gs://'):
      raise ValueError('--input-file-pattern must point to files on GCS')

  return args
1285718
def get_code(results):
    
    status = EXIT_SUCCESS

    for file_result in results:
        error = any(object_result.errors for object_result in file_result.object_results)

        fatal = file_result.fatal

        if error:
            status |= EXIT_SCHEMA_INVALID
        if fatal:
            status |= EXIT_VALIDATION_ERROR

    return status
541904
function handleArguments(env) {

  // This translates the --continue flag in gulp
  // To the settle env variable for undertaker
  // We use the process.env so the user's gulpfile
  // Can know about the flag
  if (opts.continue) {
    process.env.UNDERTAKER_SETTLE = 'true';
  }

  if (opts.help) {
    parser.showHelp(console.log);
    exit(0);
  }

  // Anything that needs to print outside of the logging mechanism should use console.log
  if (opts.version) {
    console.log('CLI version:', cliVersion);
    console.log('Local version:', env.modulePackage.version || 'Unknown');
    exit(0);
  }

  if (opts.verify) {
    var pkgPath = opts.verify !== true ? opts.verify : 'package.json';
    /* istanbul ignore else */
    if (path.resolve(pkgPath) !== path.normalize(pkgPath)) {
      pkgPath = path.join(env.cwd, pkgPath);
    }
    log.info('Verifying plugins in ' + pkgPath);
    return getBlacklist(function(err, blacklist) {
      /* istanbul ignore if */
      if (err) {
        return logBlacklistError(err);
      }

      var blacklisted = verifyDeps(require(pkgPath), blacklist);

      logVerify(blacklisted);
    });
  }

  if (!env.modulePath) {
    /* istanbul ignore next */
    var missingNodeModules =
      fs.existsSync(path.join(env.cwd, 'package.json'))
      && !fs.existsSync(path.join(env.cwd, 'node_modules'));

    /* istanbul ignore next */
    var missingGulpMessage =
      missingNodeModules
        ? 'Local modules not found in'
        : 'Local gulp not found in';
    log.error(
      ansi.red(missingGulpMessage),
      ansi.magenta(tildify(env.cwd))
    );
    /* istanbul ignore next */
    var installCommand =
      missingNodeModules
        ? 'npm install'
        : 'npm install gulp';
    log.error(ansi.red('Try running: ' + installCommand));
    exit(1);
  }

  if (!env.configPath) {
    log.error(ansi.red('No gulpfile found'));
    exit(1);
  }

  // Chdir before requiring gulpfile to make sure
  // we let them chdir as needed
  if (process.cwd() !== env.cwd) {
    process.chdir(env.cwd);
    log.info(
      'Working directory changed to',
      ansi.magenta(tildify(env.cwd))
    );
  }

  // Find the correct CLI version to run
  var range = findRange(env.modulePackage.version, ranges);

  if (!range) {
    log.error(
      ansi.red('Unsupported gulp version', env.modulePackage.version)
    );
    exit(1);
  }

  // Load and execute the CLI version
  var versionedDir = path.join(__dirname, '/lib/versioned/', range, '/');
  require(versionedDir)(opts, env, env.configProps);
}
1336759
static void processArgs(String[] args, final PrintStream out, final PrintStream err) {
        GroovyCommand groovyCommand = new GroovyCommand();
        CommandLine parser = new CommandLine(groovyCommand).setUnmatchedArgumentsAllowed(true).setStopAtUnmatched(true);
        try {
            List<CommandLine> result = parser.parse(args);
            if (CommandLine.printHelpIfRequested(result, out, err, Help.Ansi.AUTO)) {
                return;
            }
            // TODO: pass printstream(s) down through process
            if (!groovyCommand.process(parser)) {
                // If we fail, then exit with an error so scripting frameworks can catch it.
                System.exit(1);
            }

        } catch (ParameterException ex) { // command line arguments could not be parsed
            err.println(ex.getMessage());
            ex.getCommandLine().usage(err);
        } catch (IOException ioe) {
            err.println("error: " + ioe.getMessage());
        }
    }
1052405
def main(argv=None):
    
    args = _parse_args((argv if argv else sys.argv)[1:])
    cnf = os.environ.copy() if args.env else {}

    extra_opts = dict()
    if args.extra_opts:
        extra_opts = anyconfig.parser.parse(args.extra_opts)

    diff = _load_diff(args, extra_opts)

    if cnf:
        API.merge(cnf, diff)
    else:
        cnf = diff

    if args.args:
        diff = anyconfig.parser.parse(args.args)
        API.merge(cnf, diff)

    if args.validate:
        _exit_with_output("Validation succeds")

    cnf = API.gen_schema(cnf) if args.gen_schema else _do_filter(cnf, args)
    _output_result(cnf, args.output, args.otype, args.inputs, args.itype,
                   extra_opts=extra_opts)