Extracts working directory configuration from command-line arguments
for stop/status/wait/verbose commands.
504386
private void setWorkingDir(String[] args) throws FileNotFoundException {
    String workDir = null;
    // skip first node type argument (locator/server/lead)
    for (int i = 1; i < args.length; i++) {
      String arg = args[i];
      if (arg.startsWith(DIR_OPT)) {
        workDir = arg.substring(DIR_OPT.length());
      } else if (!arg.equalsIgnoreCase("stop") &&
          !arg.equalsIgnoreCase("status") &&
          !arg.equalsIgnoreCase("wait") &&
          !arg.equalsIgnoreCase("verbose")) {
        throw new IllegalArgumentException(
            MessageFormat.format(LAUNCHER_UNKNOWN_ARGUMENT, arg));
      }
    }
    processDirOption(workDir);
  }
709245
def exit_config_mode(self, exit_config="exit configuration-mode"):
        """"""
        output = ""
        if self.check_config_mode():
            output = self.send_command_timing(
                exit_config, strip_prompt=False, strip_command=False
            )
            # if 'Exit with uncommitted changes?' in output:
            if "uncommitted changes" in output:
                output += self.send_command_timing(
                    "yes", strip_prompt=False, strip_command=False
                )
            if self.check_config_mode():
                raise ValueError("Failed to exit configuration mode")
        return output
328390
def parse_command_line
      begin
        opts = GetoptLong.new(
          [ '--logfile', '-l',      GetoptLong::REQUIRED_ARGUMENT ],
          [ '--verbose', '-v',      GetoptLong::NO_ARGUMENT ],
          [ '--quiet',   '-q',      GetoptLong::NO_ARGUMENT ],
          [ '--concurrency', '-c',  GetoptLong::REQUIRED_ARGUMENT ],
          [ '--delay', '-d',        GetoptLong::REQUIRED_ARGUMENT ],
          [ '--retry', '-y',        GetoptLong::REQUIRED_ARGUMENT ],
          [ '--port', '-p',         GetoptLong::REQUIRED_ARGUMENT ],
          [ '--bind-address', '-b', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--help', '-h',         GetoptLong::NO_ARGUMENT ],
          [ '--exit', '-x', 				GetoptLong::NO_ARGUMENT ]
        )

        opts.each do |opt, arg|
          case opt
            when '--logfile', '-l'
              @logfile = arg
              Log.logger = Logger.new(@logfile)
            when '--concurrency', '-c'
              @concurrency = arg.to_i
            when '--delay', '-d'
              @delay = arg.to_i
            when '--retry', '-y'
              @retry_count = arg.to_i
            when '--verbose', '-v'
              @verbose = true
            when '--quiet',   '-q'
              @quiet = true
            when '--port', '-p'
              @port = arg
            when '--bind-address', '-b'
              @bind_address = arg.to_s
            when '--help', '-h'
              help
            when '--exit', '-x'
              uri = "http://localhost:#{@port}/admin"
              response = RestClient.post uri, { 'shutdown' => true }.to_yaml
              exit 0
          end
        end
      rescue GetoptLong::InvalidOption => ex
        puts "Syntax: chimpd [--logfile=<name>] [--concurrency=<c>] [--delay=<d>] [--retry=<r>] [--port=<p>] [--bind-address=<addr> ] [--verbose]"
        exit 1
      end

      #
      # Set up logging/verbosity
      #
      Chimp.set_verbose(@verbose, @quiet)

      if not @verbose
      	ENV['REST_CONNECTION_LOG'] = "/dev/null"
      	ENV['RESTCLIENT_LOG'] = "/dev/null"
        Log.threshold= Logger::INFO
      else
        Log.threshold= Logger::DEBUG
      end

      if @quiet
        Log.threshold = Logger::WARN
      end
    end
615912
def parse_conf_args(argv):
    """"""

    args = {}
    for rarg in argv:
        if re.match("^--.*", rarg):
            arg = rarg.replace('--','', 1)

            fsplit = arg.split('=', 1)
            if len(fsplit) != 2:
                raise Exception(
                    "Command option '%s' not recognized." % rarg)

            rkey, value = fsplit
            ssplit = rkey.split('.', 1)
            if len(ssplit) != 2 or not ssplit[1]:
                raise Exception(
                    "Command option '%s' not recognized." % rarg)

            section, option = ssplit
            args[section] = (option, value)
        else:
            raise Exception(
                    "Command option '%s' not recognized." % rarg)

    return args
225442
@Nonnull
	public static String[] parseLocalStateDirectories(Configuration configuration) {
		String configValue = configuration.getString(CheckpointingOptions.LOCAL_RECOVERY_TASK_MANAGER_STATE_ROOT_DIRS, "");
		return splitPaths(configValue);
	}
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
350007
def parse_command_line(self):
        """"""
        result = _Distribution.parse_command_line(self)
        if self.features:
            self._finalize_features()
        return result
1267207
def parse_cmdline(argv=None):
    
    parser = optparse.OptionParser()
    parser.add_option('-c', '--conf', help='Configuration file path.',
                      dest='confpath',default=None)
    parser.add_option('-p', '--bindport',
                      help='Bind to TCP Port. (Default: %d)' % conf['bindport'],
                      dest='bindport', type='int', default=None, action='store')
    parser.add_option('-b', '--bindaddr',
                      help='Bind to IP Address. (Default: %s)' % conf['bindaddr'],
                      dest='bindaddr', default=None, action='store')
    parser.add_option('-u', '--baseurl', 
                      help='Base URL. (Default: %s)' % conf['baseurl'],
                      dest='baseurl', default=None, action='store')
    parser.add_option('-D', '--devel', help='Enable development mode.',
                      dest='devel', default=False, action='store_true')
    if argv is None:
        return parser.parse_args()
    else:
        return parser.parse_args(argv[1:])
976424
def parse_verbosity(self, args):
    '''

    '''

    flags = []

    if args.silent is True:
       flags.append('--silent')
    elif args.quiet is True:
        flags.append('--quiet')
    elif args.debug is True:
       flags.append('--debug')
    elif args.verbose is True:
       flags.append('-' + 'v' * args.verbose)

    return flags
507159
def get_command_line_arguments():
    

    parser = argparse.ArgumentParser(add_help=False)

    parser.add_argument("-h",
                        "--help",
                        action="help",
                        help="'Displays this help message and exit.'")

    parser.add_argument("-t",
                        "--title",
                        type=unicode,
                        dest="title",
                        help="'Package title.'")

    parser.add_argument("-i",
                        "--input",
                        type=unicode,
                        dest="input",
                        help="'Input file to convert.'")

    parser.add_argument("-o",
                        "--output",
                        type=unicode,
                        dest="output",
                        help="'Output file.'")

    parser.add_argument("-c",
                        "--content_directory",
                        type=unicode,
                        dest="content_directory",
                        help="'Content directory.'")

    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)

    return parser.parse_args()
841913
def load_configuration_from_file(directory, args):
    """"""
    args = copy.copy(args)

    directory_or_file = directory
    if args.config is not None:
        directory_or_file = args.config

    options = _get_options(directory_or_file, debug=args.debug)

    args.report = options.get('report', args.report)
    threshold_dictionary = docutils.frontend.OptionParser.thresholds
    args.report = int(threshold_dictionary.get(args.report, args.report))

    args.ignore_language = get_and_split(
        options, 'ignore_language', args.ignore_language)

    args.ignore_messages = options.get(
        'ignore_messages', args.ignore_messages)

    args.ignore_directives = get_and_split(
        options, 'ignore_directives', args.ignore_directives)

    args.ignore_substitutions = get_and_split(
        options, 'ignore_substitutions', args.ignore_substitutions)

    args.ignore_roles = get_and_split(
        options, 'ignore_roles', args.ignore_roles)

    return args
1044012
def parse_arguments():
    
    # Pull a few settings from the environment, should they exist
    base_dn = os.environ['PUDL_BASE_DN'] if 'PUDL_BASE_DN' in os.environ \
              else 'OU=Departments,DC=example,DC=com'
    domain = os.environ['PUDL_DOMAIN'].upper() if 'PUDL_DOMAIN' in os.environ else 'EXAMPLE'
    page_size = os.environ['PUDL_PAGE_SIZE'].upper() if 'PUDL_PAGE_SIZE' in os.environ else 300
    tls_no_verify = bool(os.environ['PUDL_TLS_NO_VERIFY'].lower().capitalize()) \
                    if 'PUDL_TLS_NO_VERIFY' in os.environ else False

    parser = argparse.ArgumentParser(prog='pudl',
                                     description='A script for interacting with Active ' + \
                                     'Directory, leveraging python-ldap')
    parser.add_argument('-V', '--version', action='version', version='pudl v' + pudl_version,
                        help="Print the version number and exit")
    subparsers = parser.add_subparsers(dest='subcommand', help='Sub-command help')
    parser_common = subparsers.add_parser('common', add_help=False)
    parser_common.add_argument('--user', '-u', action='store', dest='user',
                               help='The ldap user (bind dn) to connect as. ' + \
                               'The full DN will work, or often, just the CN may be ' + \
                               'sufficient, such as "John Smith", or more commonly, ' + \
                               'specify the domain and sAMAccountName. Defaults to ' + \
                               '{0}\\username.  The domain '.format(domain) + \
                               'portion may be overridden with PUDL_DOMAIN',
                               default='{0}\\{1}'.format(domain, getpass.getuser()))
    parser_common.add_argument('--password', '-p', action='store',
                               dest='password', help="The connecting user's password")
    parser_common.add_argument('--host', '-H', action='store',
                               dest='host', help='The AD/LDAP host, defaults to ldap',
                               default='ldap')
    parser_common.add_argument('--port', '-P', action='store', dest='port',
                               help='The ldap port, defaults to 389.  389 is ' + \
                               'is the standard port', type=int, default=389)
    parser_common.add_argument('--page-size', '-s', action='store', dest='page_size',
                               help='The ldap results are paged, specify the ' + \
                               'number of results per page, defaults to ' + \
                               '{0}. May be overridden with PUDL_PAGE_SIZE'.format(page_size),
                               type=int, default=page_size)
    parser_common.add_argument('--base-dn', '-b', action='store',
                               dest='base_dn', default=base_dn,
                               help="The Base DN to use, defaults to {0}. ".format(base_dn) + \
                               "May be overridden with PUDL_BASE_DN")
    parser_common.add_argument('--attribute', '-a', action='append',
                               dest='attributes', metavar='ATTRIBUTE',
                               help="Attributes to include in results objects.  Note that " + \
                               "any nested objects return all attributes.  Maybe be used " + \
                               "multiple times, and if not specified, all " + \
                               "attributes are included in top-level objects")
    parser_common.add_argument('--grep', '-g', action='append', dest='grep',
                               help='Filter results to only those matching the specified ' + \
                               'regular expression (compares against all attributes). ' + \
                               'May be used multiple times')
    parser_common.add_argument('--attributes-only', '-A', action='store_true',
                               dest='attributes_only', help="Only display a list of attributes " + \
                               "that are present for the object type returned by the LDAP query")
    parser_common.add_argument('--output-format', '-f', action='store', dest='output_format',
                               choices=['json', 'yaml'], default='json',
                               help="Output format, defaults to json.")
    parser_common.add_argument('--verbose', '-v', action='store_true', dest='verbose',
                               help='Turn on verbose output', default=False)
    parser_common.add_argument('--debug', '-d', action='store_true', dest='debug', default=False,
                               help="Print out debugging information, very chatty")
    parser_common.add_argument('--tls-no-verify', '-V', action='store_true',
                               dest='tls_no_verify',
                               default=tls_no_verify, help="Don't verify the authenticity " + \
                               "of the server's certificate, defaults to " + \
                               "{0} and may be overridden with ".format(tls_no_verify) + \
                               "PUDL_TLS_NO_VERIFY")
    parser_user = subparsers.add_parser('user', parents=[parser_common], conflict_handler='resolve',
                                        help='Pull user objects from AD')
    parser_user.add_argument(nargs="*", dest='samaccountnames',
                             help='sAMAccountNames for any user objects that are to be ' + \
                             'looked up. If unspecified, returns all users under the base ' + \
                             'DN provided')
    parser_user.add_argument('--explicit-membership-only', '-e', action='store_true',
                             dest='explicit_membership_only', default=False,
                             help="Only show membership for users that is explicit, " + \
                             "not taking into account group nesting.  Defaults to False")
    parser_group = subparsers.add_parser('group', parents=[parser_common],
                                         conflict_handler='resolve',
                                         help='Pull group objects from AD')
    parser_group.add_argument(nargs="*", dest='samaccountnames',
                              help="sAMAccountNames for any group objects that are to be " + \
                              'looked up. If unspecified, returns all groups under the base ' + \
                              'DN provided. sAMAccountName may not be present in group ' + \
                              'objects in modern AD schemas')
    parser_group.add_argument('--explicit-membership-only', '-e', action='store_true',
                              dest='explicit_membership_only', default=False,
                              help="Only show membership for users that is explicit, " + \
                              "not taking into account group nesting.  Defaults to False")
    parser_computer = subparsers.add_parser('computer', parents=[parser_common],
                                            conflict_handler='resolve',
                                            help='Pull computer objects from AD')
    parser_computer.add_argument(nargs="*", dest='samaccountnames',
                                 help="sAMAccountNames for any computer objects that are to be " + \
                                 'looked up. If unspecified, returns all computers under ' + \
                                 'the base DN provided.')

    # sphinx is not add_help=False aware...
    del subparsers.choices['common']

    return parser
322597
def parse_config_input_output(args=sys.argv):
    
    parser = argparse.ArgumentParser(
        description='Process the input files using the given config')
    parser.add_argument(
        'config_file',
        help='Configuration file.',
        metavar='FILE', type=extant_file)
    parser.add_argument(
        'input_dir',
        help='Directory containing the input files.',
        metavar='DIR', type=extant_dir)
    parser.add_argument(
        'output_dir',
        help='Directory where the output files should be saved.',
        metavar='DIR', type=extant_dir)
    return parser.parse_args(args[1:])
112886
def cmdline(argv=sys.argv[1:]):
    
    parser = ArgumentParser(
        description='Create and merge collections of stop words')
    parser.add_argument(
        'language', help='The language used in the collection')
    parser.add_argument('sources', metavar='FILE', nargs='+',
                        help='Source files to parse')
    options = parser.parse_args(argv)

    factory = StopWordFactory()
    language = options.language
    stop_words = factory.get_stop_words(language, fail_safe=True)

    for filename in options.sources:
        stop_words += StopWord(language, factory.read_collection(filename))

    filename = factory.get_collection_filename(stop_words.language)
    factory.write_collection(filename, stop_words.collection)
191886
def get_env(working_directory=None):
    
    working = working_directory if working_directory else os.getcwd()
    dist_dirs = glob.glob(working + "/f5-*-dist")
    print(dist_dirs)
    dist_dir_re = re.compile('/([^/]+)-dist/?')
    if dist_dirs:
        dist_dir = dist_dirs[0]
        match = dist_dir_re.search(dist_dir)
        if match:
            project_name = match.group(1)
        else:
            print("Unrecognized run location:\n" + working)
            exit_cleanly(errnum=errno.EIO)
    elif '-dist/scripts' in working:
        match = dist_dir_re.search(working)
        if match:
            project_name = match.group(1)
    else:
        print("Unable to determine the *-dist directory from " + working)
        exit_cleanly(errnum=errno.ENOSYS)
    stdeb_cfg = dist_dir + "/deb_dist/stdeb.cfg"
    setup_cfg = working + "/setup.cfg"
    stp_reqs = working + "/setup_requirements.txt"
    scripts = dist_dir + "/scripts"
    env = {'working': working, 'dist_dir': dist_dir, 'stdeb_cfg': stdeb_cfg,
           'setup_requirements': stp_reqs, 'setup_cfg': setup_cfg,
           'scripts': scripts, 'project': project_name}
    return env
268753
def get_parser():
    """"""

    main_parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter)

    main_parser.add_argument(
        '-c', '--config',
        dest='config',
        type=str,
        nargs='?',
        help='Pull the latest repositories from config(s)'
    ).completer = argcomplete.completers.FilesCompleter(
        allowednames=('.yaml', '.yml', '.json'), directories=False
    )

    main_parser.add_argument(
        '-p', '--push',
        dest='do_push',
        action='store_true', default=False,
        help='Push result to target',
    )

    main_parser.add_argument(
        '-d', '--dirmatch',
        dest='dirmatch',
        type=str,
        nargs='?',
        help='Pull only from the directories. Accepts fnmatch(1)'
             'by commands'
    )
    main_parser.add_argument(
        '--log-level',
        default='INFO',
        dest='log_level',
        type=_log_level_string_to_int,
        nargs='?',
        help='Set the logging output level. {0}'.format(_LOG_LEVEL_STRINGS))

    main_parser.add_argument(
        '-e', '--expand-env',
        dest='expand_env',
        default=False,
        action='store_true',
        help='Expand environment variables in configuration file',
    )
    main_parser.add_argument(
        '-f', '--force',
        dest='force',
        default=False,
        action='store_true',
        help='Force cleanup and aggregation on dirty repositories.',
    )

    main_parser.add_argument(
        '-j', '--jobs',
        dest='jobs',
        default=1,
        type=int,
        help='Amount of processes to use when aggregating repos. '
             'This is useful when there are a lot of large repos. '
             'Set `1` or less to disable multiprocessing (default).',
    )

    main_parser.add_argument(
        'command',
        nargs='?',
        default='aggregate',
        help='aggregate (default): run the aggregation process.\n'
             'show-all-prs: show GitHub pull requests in merge sections\n'
             '              such pull requests are indentified as having\n'
             '              a github.com remote and a\n'
             '              refs/pull/NNN/head ref in the merge section.\n'
             'show-closed-prs: show pull requests that are not open anymore.\n'
    )

    return main_parser
881785
def get_installed_distributions(skip=stdlib_pkgs):
    
    return [d for d in pkg_resources.working_set
            if d.key not in skip]