Parse and check the command line arguments.
190253
def main(argv=sys.argv):
    # type: (List[str]) -> int
    """"""
    parser = optparse.OptionParser(
        usage="""\
usage: %prog [options] -o <output_path> <module_path> [exclude_pattern, ...]

Look recursively in <module_path> for Python modules and packages and create
one reST file with automodule directives per package in the <output_path>.

The <exclude_pattern>s can be file and/or directory patterns that will be
excluded from generation.

Note: By default this script will not overwrite already created files.""")

    parser.add_option('-o', '--output-dir', action='store', dest='destdir',
                      help='Directory to place all output', default='')
    parser.add_option('-d', '--maxdepth', action='store', dest='maxdepth',
                      help='Maximum depth of submodules to show in the TOC '
                      '(default: 4)', type='int', default=4)
    parser.add_option('-f', '--force', action='store_true', dest='force',
                      help='Overwrite existing files')
    parser.add_option('-l', '--follow-links', action='store_true',
                      dest='followlinks', default=False,
                      help='Follow symbolic links. Powerful when combined '
                      'with collective.recipe.omelette.')
    parser.add_option('-n', '--dry-run', action='store_true', dest='dryrun',
                      help='Run the script without creating files')
    parser.add_option('-e', '--separate', action='store_true',
                      dest='separatemodules',
                      help='Put documentation for each module on its own page')
    parser.add_option('-P', '--private', action='store_true',
                      dest='includeprivate',
                      help='Include "_private" modules')
    parser.add_option('-T', '--no-toc', action='store_true', dest='notoc',
                      help='Don\'t create a table of contents file')
    parser.add_option('-E', '--no-headings', action='store_true',
                      dest='noheadings',
                      help='Don\'t create headings for the module/package '
                           'packages (e.g. when the docstrings already contain '
                           'them). No effect in combination with -t')
    parser.add_option('-M', '--module-first', action='store_true',
                      dest='modulefirst',
                      help='Put module documentation before submodule '
                      'documentation (no effect in combination with -t)')
    parser.add_option('--implicit-namespaces', action='store_true',
                      dest='implicit_namespaces',
                      help='Interpret module paths according to PEP-0420 '
                           'implicit namespaces specification')
    parser.add_option('-s', '--suffix', action='store', dest='suffix',
                      help='file suffix (default: rst)', default='rst')
    parser.add_option('-F', '--full', action='store_true', dest='full',
                      help='Generate a full project with sphinx-quickstart')
    parser.add_option('-a', '--append-syspath', action='store_true',
                      dest='append_syspath',
                      help='Append module_path to sys.path, used when --full is given')
    parser.add_option("-t", "--templates", action="store", type="string",
                      dest="templates", default=None,
                      help="Custom template directory (default: %default). "
                      "Must contain template files package.rst and/or "
                      "module.rst")
    parser.add_option('-H', '--doc-project', action='store', dest='header',
                      help='Project name (default: root module name)')
    parser.add_option('-A', '--doc-author', action='store', dest='author',
                      type='str',
                      help='Project author(s), used when --full is given')
    parser.add_option('-V', '--doc-version', action='store', dest='version',
                      help='Project version, used when --full is given')
    parser.add_option('-R', '--doc-release', action='store', dest='release',
                      help='Project release, used when --full is given, '
                      'defaults to --doc-version')
    parser.add_option('--version', action='store_true', dest='show_version',
                      help='Show version information and exit')
    group = parser.add_option_group('Extension options')
    for ext in EXTENSIONS:
        group.add_option('--ext-' + ext, action='store_true',
                         dest='ext_' + ext, default=False,
                         help='enable %s extension' % ext)

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

    if opts.show_version:
        #print('Sphinx (sphinx-apidoc) %s' % __display_version__)
        print('better-apidoc %s' % __display_version__)
        return 0

    if not args:
        parser.error('A package path is required.')

    rootpath, excludes = args[0], args[1:]
    if not opts.destdir:
        parser.error('An output directory is required.')
    if opts.header is None:
        opts.header = path.abspath(rootpath).split(path.sep)[-1]
    if opts.suffix.startswith('.'):
        opts.suffix = opts.suffix[1:]
    if not path.isdir(rootpath):
        print('%s is not a directory.' % rootpath, file=sys.stderr)
        sys.exit(1)
    if not path.isdir(opts.destdir):
        if not opts.dryrun:
            os.makedirs(opts.destdir)
    rootpath = path.abspath(rootpath)
    excludes = normalize_excludes(rootpath, excludes)
    try:
        modules = recurse_tree(rootpath, excludes, opts)
    except TemplateNotFound as e:
        print('Cannot find template in %s: %s' %
              (opts.templates, e), file=sys.stderr)
        sys.exit(1)

    if opts.full:
        raise NotImplementedError("--full not supported")
        # This would only make sense if this script was integrated in Sphinx
        from sphinx import quickstart as qs
        modules.sort()
        prev_module = ''  # type: unicode
        text = ''
        for module in modules:
            if module.startswith(prev_module + '.'):
                continue
            prev_module = module
            text += '   %s\n' % module
        d = dict(
            path = opts.destdir,
            sep = False,
            dot = '_',
            project = opts.header,
            author = opts.author or 'Author',
            version = opts.version or '',
            release = opts.release or opts.version or '',
            suffix = '.' + opts.suffix,
            master = 'index',
            epub = True,
            ext_autodoc = True,
            ext_viewcode = True,
            ext_todo = True,
            makefile = True,
            batchfile = True,
            mastertocmaxdepth = opts.maxdepth,
            mastertoctree = text,
            language = 'en',
            module_path = rootpath,
            append_syspath = opts.append_syspath,
        )
        enabled_exts = {'ext_' + ext: getattr(opts, 'ext_' + ext)
                        for ext in EXTENSIONS if getattr(opts, 'ext_' + ext)}
        d.update(enabled_exts)

        if isinstance(opts.header, binary_type):
            d['project'] = d['project'].decode('utf-8')
        if isinstance(opts.author, binary_type):
            d['author'] = d['author'].decode('utf-8')
        if isinstance(opts.version, binary_type):
            d['version'] = d['version'].decode('utf-8')
        if isinstance(opts.release, binary_type):
            d['release'] = d['release'].decode('utf-8')

        if not opts.dryrun:
            qs.generate(d, silent=True, overwrite=opts.force)
    elif not opts.notoc:
        create_modules_toc_file(modules, opts)
    return 0
619277
def parse_args_and_kwargs(self, cmdline):
        '''
        
        '''
        # Parse args and kwargs
        args = []
        kwargs = {}

        if len(cmdline) > 1:
            for item in cmdline[1:]:
                if '=' in item:
                    (key, value) = item.split('=', 1)
                    kwargs[key] = value
                else:
                    args.append(item)
        return (args, kwargs)
84063
def _parse_arguments():
    """"""
    parser = argparse.ArgumentParser(description="CMake AST Dumper")
    parser.add_argument("filename", nargs=1, metavar=("FILE"),
                        help="read FILE")
    return parser.parse_args()
940661
def parse_input():
    """"""
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('-c', '--config', type=str,
                        help="Specify a configuration file")
    return parser.parse_args()
159567
def parse_command_line():
    """"""
    parser = argparse.ArgumentParser(
        prog='csp_pulsar_sender',
        description='Send fake pulsar data using ftp protocol.')
    parser.add_argument('config_file', type=argparse.FileType('r'),
                        help='JSON configuration file.')
    parser.add_argument('-v', '--verbose', help='Enable verbose messages.',
                        action='store_true')
    parser.add_argument('-p', '--print_settings', help='Print settings file.',
                        action='store_true')
    return parser.parse_args()
1108599
def args(parsed_args, name=None):
    """"""
    strings = parsed_args.arg_strings(name)
    files = [s for s in strings if os.path.isfile(s)]
    if files:
        streams = [open(f) for f in files]
    else:
        streams = []
    if getattr(parsed_args, 'paste', not files):
        streams.append(clipboard_stream())
    if getattr(parsed_args, 'stdin', False):
        streams.append(sys.stdin)
    elif not streams:
        streams = [sys.stdin]
    return streams
815964
def p_arguments(p):
    """'"""
    p[0] = { 'args' : p[1], }
    if len(p) > 2:
        if p[2] == '(':
            p[0]['tests'] = p[3]
        else:
            p[0]['tests'] = [ p[2] ]
701868
def parse_args(self, *args, **kwargs):
        """"""
        if _debug: ArgumentParser._debug("parse_args")

        # pass along to the parent class
        result_args = _ArgumentParser.parse_args(self, *args, **kwargs)

        # check to dump labels
        if result_args.buggers:
            loggers = sorted(logging.Logger.manager.loggerDict.keys())
            for loggerName in loggers:
                sys.stdout.write(loggerName + '\n')
            sys.exit(0)

        # check for debug
        if result_args.debug is None:
            # --debug not specified
            result_args.debug = []
        elif not result_args.debug:
            # --debug, but no arguments
            result_args.debug = ["__main__"]

        # check for debugging from the environment
        if BACPYPES_DEBUG:
            result_args.debug.extend(BACPYPES_DEBUG.split())
        if BACPYPES_COLOR:
            result_args.color = True

        # keep track of which files are going to be used
        file_handlers = {}

        # loop through the bug list
        for i, debug_name in enumerate(result_args.debug):
            color = (i % 6) + 2 if result_args.color else None

            debug_specs = debug_name.split(':')
            if len(debug_specs) == 1:
                ConsoleLogHandler(debug_name, color=color)
            else:
                # the debugger name is just the first component
                debug_name = debug_specs[0]

                # if the file is already being used, use the already created handler
                file_name = debug_specs[1]
                if file_name in file_handlers:
                    handler = file_handlers[file_name]
                else:
                    if len(debug_specs) >= 3:
                        maxBytes = int(debug_specs[2])
                    else:
                        maxBytes = BACPYPES_MAXBYTES
                    if len(debug_specs) >= 4:
                        backupCount = int(debug_specs[3])
                    else:
                        backupCount = BACPYPES_BACKUPCOUNT

                    # create a handler
                    handler = logging.handlers.RotatingFileHandler(
                        file_name, maxBytes=maxBytes, backupCount=backupCount,
                        )
                    handler.setLevel(logging.DEBUG)

                    # save it for more than one instance
                    file_handlers[file_name] = handler

                # use this handler, no color
                ConsoleLogHandler(debug_name, handler=handler)

        # return what was parsed
        return result_args
680514
def command_line_parsed(
            self,
            available_plugins: Set[Type[Plugin]],
            args_command_list: Any,
            malformed_servers: List[ServerStringParsingError]
    ) -> None:
        
1286547
def parse_args(args=None):
    """"""
    parser = argparse.ArgumentParser(description='afraid.org dyndns client')

    ## positional arguments

    parser.add_argument('user')
    parser.add_argument('password')
    parser.add_argument('hosts',
            nargs='*',
            help='(deafult: all associated hosts)',
            default=None
    )

    ## optional arguments

    # should we fork?
    parser.add_argument('--daemonize', '-d',
        action='store_true',
        default=False,
        help='run in background (default: no)',
    )

    # log to a file or stdout
    parser.add_argument('--log',
        help='log to file (default: log to stdout)',
        type=argparse.FileType('w'),
        default=sys.stdout,
        metavar='file'
    )

    # how long to sleep between updates
    parser.add_argument('--interval',
        help='update interval, in seconds (default: 21600)',
        metavar='seconds',
        default=6 * 60 * 60, # 6 hours
        type=int
    )

    return parser.parse_args(args)
1194816
def parse_arguments():
    """"""
    parser = create_parser()
    args = parser.parse_args()
    if not args.role_requirements_old_commit:
        args.role_requirements_old_commit = args.role_requirements
    if not args.rpc_product_old_commit:
        args.rpc_product_old_commit = args.rpc_product
    return args
197957
function Args() {
    if (argv._.length >= 1) {
        try {
            // Attempt to parse 1st argument as JSON string
            _.extend(this, JSON.parse(argv._[0]));
        } catch (err) {
            // Pass, we must be in the console so don't worry about it
        }
    }
}
50667
private void parseCommandLineArgs(String[] args) throws ConfigurationException {
        if (args == null || args.length == 0) {
            return;
        }
        logger.info("Parsing command line arguments");
        m_commandLineArgs = args;
        
        try {
            for (int inx = 0; inx < args.length; inx++) {
                String arg = args[inx];
                if (arg.equals("-?") || arg.equalsIgnoreCase("-h") || arg.equalsIgnoreCase("-help")) {
                    System.out.println("See documentation and doradus.yaml for help.");
                    System.exit(0);
                }
                Utils.require(arg.charAt(0) == '-', "Unrecognized argument: %s", arg);
                Utils.require(inx + 1 < args.length, "A value is expected after: %s", arg);
                String name = arg.substring(1);
                String value = args[++inx];
                setCommandLineParam(name, value);
            }
        } catch (Exception e) {
            logger.error("Failed to parse command line arguments", e);
            throw new ConfigurationException("Failed to parse command line arguments", e);
        }
    }
355436
def parse_args(self, ctx, args):
        """"""
        if args and args[0] in self.commands:
            args.insert(0, '')
        super(OptionalGroup, self).parse_args(ctx, args)
692076
def parse_args(args=None):
    """"""
    parser = argparse.ArgumentParser()

    parser.add_argument(
        '-w', '--window',
        default="pyqt5",
        choices=find_window_classes(),
        help='Name for the window type to use',
    )
    parser.add_argument(
        '-fs', '--fullscreen',
        action="store_true",
        help='Open the window in fullscreen mode',
    )
    parser.add_argument(
        '-vs', '--vsync',
        type=str2bool,
        default="1",
        help="Enable or disable vsync",
    )
    parser.add_argument(
        '-s', '--samples',
        type=int,
        default=4,
        help="Specify the desired number of samples to use for multisampling",
    )
    parser.add_argument(
        '-c', '--cursor',
        type=str2bool,
        default="true",
        help="Enable or disable displaying the mouse cursor",
    )

    return parser.parse_args(args or sys.argv[1:])
1153502
def _parse_args():
    """"""
    class HelpOnErrorArgParser(argparse.ArgumentParser):
        """Print help message as well when an error is raised."""
        def error(self, message):
            sys.stderr.write("Error: %s\n" % message)
            self.print_help()
            sys.exit(2)

    def validate(_file):
        """Validate if the given target argument is a valid file or a valid directory"""
        _file = abspath(_file)
        if not exists(_file):
            if not exists(dirname(_file)):
                # Argparse uses the ArgumentTypeError to give a rejection message like:
                # error: argument input: x does not exist
                raise argparse.ArgumentTypeError("{0} does not exist".format(_file))
        return _file

    def expand_cg_args(cg_args):
        """Separate clubbed flags in command line args for the generator.py

        Allows flags to be clubbed like, -ilt example.txt.
        """
        expanded = list()
        for item in cg_args:
            if len(item) < 3:
                # If at all a flag, must be single flag
                expanded.append(item)
                continue
            if item.startswith("-"):
                if not item.startswith("--"):
                    for flag in item[1:]:
                        expanded.append('-' + flag)
                    continue
            expanded.append(item)
        return expanded

    class AssignDefaultIgnore(argparse.Action):
        """If argument is specified but nothing provided, use pre-defined.

        nargs="*" doesn't allow const and default kwarg can't be used as we might not want to
        ignore as well.
        """
        def __call__(self, parser, args, values, option_string=None):
            if values is not None and not len(values):
                values = IGNORE_METHODS
            setattr(args, self.dest, values)

    try:
        indx = sys.argv.index('--')
        cg_args, sys.argv = sys.argv[1:indx], sys.argv[:1] + sys.argv[indx + 1:]
    except ValueError:
        cg_args = []

    cg_args = expand_cg_args(cg_args)  # allow -il type of usage
    parser = HelpOnErrorArgParser(description=DESCRIPTION)
    parser.add_argument(
        "-l", "--long", action='store_true', default=False,
        help="File reference of method in call graph is absolute, i.e. starts with ansible, "
             "otherwise just the basename if not __init__.py")
    parser.add_argument(
        "-t", "--target", nargs="?", type=validate, const=TARGET_FILE, default=TARGET_FILE,
        help="Filepath to write call graph, defaults to %(default)s")
    parser.add_argument(
        "-i", "--ignore", nargs='*', action=AssignDefaultIgnore,
        help="Methods to ignore while generating call graph")
    # TODO: Aloow classes that can be intercepted
    parser.usage = \
        parser.format_usage()[len("usage: "):].rstrip() + " -- <ansible-playbook options>\n"
    cg_args = parser.parse_args(cg_args)

    if not len(sys.argv[1:]):
        parser.print_help()
        sys.exit(2)

    return cg_args
203543
def parse_args():
    """"""
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        description='Diagnose script for checking the current system.')
    choices = ['python', 'pip', 'mxnet', 'os', 'hardware', 'network']
    for choice in choices:
        parser.add_argument('--' + choice, default=1, type=int,
                            help='Diagnose {}.'.format(choice))
    parser.add_argument('--region', default='', type=str,
                        help="Additional sites in which region(s) to test. \
                        Specify 'cn' for example to test mirror sites in China.")
    parser.add_argument('--timeout', default=10, type=int,
                        help="Connection test timeout threshold, 0 to disable.")
    args = parser.parse_args()
    return args