Return the peep hash of one or more files, returning a shell status code
    or raising a PipException.

    :arg argv: The commandline args, starting after the subcommand
349537
def peep_hash(argv):
    
    parser = OptionParser(
        usage='usage: %prog hash file [file ...]',
        description='Print a peep hash line for one or more files: for '
                    'example, "# sha256: '
                    'oz42dZy6Gowxw8AelDtO4gRgTW_xPdooH484k7I5EOY".')
    _, paths = parser.parse_args(args=argv)
    if paths:
        for path in paths:
            print('# sha256:', hash_of_file(path))
        return ITS_FINE_ITS_FINE
    else:
        parser.print_usage()
        return COMMAND_LINE_ERROR
1311365
def exec_prog(args):
    

    program_name = args[0]
    logging.info(" ".join(args))
    output = subprocess.check_output(args, stderr=subprocess.STDOUT)
    if not os.access(program_name+".OK", os.F_OK):
        logging.error("No {}.OK file?".format(program_name))
        raise subprocess.CalledProcessError(-1, ' '.join(args), output)
    os.unlink(program_name+".OK")
    if os.access(program_name+".FAILED", os.F_OK):
        os.unlink(program_name+".FAILED")
    return output
674821
def main(argv=None):  # suppress(unused-function)
    
    argv = argv or sys.argv

    if "--" not in argv:
        sys.stderr.write("""Must specify command after '--'.\n""")
        return 1

    cmd_index = argv.index("--")
    args, cmd = (argv[1:cmd_index], argv[cmd_index + 1:])

    parser = argparse.ArgumentParser(description="""Cache results from jobs""")
    parser.add_argument("--dependencies",
                        metavar="PATH",
                        nargs="*",
                        help="""A list of paths which, if more recent than the last time this job was invoked, will cause the job to be re-invoked.""")
    parser.add_argument("--output-files",
                        metavar="PATH",
                        nargs="*",
                        help="""A list of expected output paths form this command, which, if they do not exist, will cause the job to be re-invoked.""")
    parser.add_argument("--stamp-directory",
                        metavar="DIRECTORY",
                        type=str,
                        help="""A directory to store cached results from this command. If a matching invocation is used and the files specified in --dependencies and --output-files are up-to-date, then the cached stdout, stderr and return code is used and the command is not run again.""")
    parser.add_argument("--use-hashes",
                        action="store_true",
                        help="""Use hash comparison in order to determine if dependencies have changed since the last invocation of the job. This method is slower, but can withstand files being copied or moved.""")
    namespace = parser.parse_args(args)
    stamp_directory = namespace.stamp_directory
    if namespace.use_hashes:
        method = jobstamp.HashMethod
    else:
        method = jobstamp.MTimeMethod

    result = jobstamp.run(_run_cmd,
                          cmd,
                          jobstamps_dependencies=namespace.dependencies,
                          jobstamps_output_files=namespace.output_files,
                          jobstamps_cache_output_directory=stamp_directory,
                          jobstamps_method=method)

    sys.stdout.write(result["stdout"].decode())
    sys.stderr.write(result["stderr"].decode())
    return result["code"]
340801
def main():
    
    global args
    args = parse_args()

    if not args:
        return 1

    state = MyState(args)

    for path in args.paths:
        if os.path.isdir(path):
            walk_dir(path, args, state)
        else:
            safe_process_files(os.path.dirname(path), [os.path.basename(path)], args, state)
        if state.should_quit():
            break
    if state.failed_files:
        sys.stderr.write("error: %i/%i AEADs failed\n" % (len(state.failed_files), state.file_count))
        return 1
    if args.debug:
        sys.stderr.write("Successfully processed %i AEADs\n" % (state.file_count))
499950
function Cli(argv) {
  var Cucumber = require('cucumber');
  var Command = require('commander').Command;
  var path = require('path');

  function collect(val, memo) {
    memo.push(val);
    return memo;
  }

  function getProgram() {
    var program = new Command(path.basename(argv[1]));

    program
      .usage('[options] [<DIR|FILE[:LINE]>...]')
      .version(Cucumber.VERSION, '-v, --version')
      .option('-b, --backtrace', 'show full backtrace for errors')
      .option('--compiler <EXTENSION:MODULE>', 'require files with the given EXTENSION after requiring MODULE (repeatable)', collect, [])
      .option('-d, --dry-run', 'invoke formatters without executing steps')
      .option('--fail-fast', 'abort the run on first failure')
      .option('-f, --format <TYPE[:PATH]>', 'specify the output format, optionally supply PATH to redirect formatter output (repeatable)', collect, ['pretty'])
      .option('--name <REGEXP>', 'only execute the scenarios with name matching the expression (repeatable)', collect, [])
      .option('--no-colors', 'disable colors in formatter output')
      .option('--no-snippets', 'hide step definition snippets for pending steps')
      .option('--no-source', 'hide source uris')
      .option('-p, --profile <NAME>', 'specify the profile to use (repeatable)', collect, [])
      .option('-r, --require <FILE|DIR>', 'require files before executing features (repeatable)', collect, [])
      .option('--snippet-syntax <FILE>', 'specify a custom snippet syntax')
      .option('-S, --strict', 'fail if there are any undefined or pending steps')
      .option('-t, --tags <EXPRESSION>', 'only execute the features or scenarios with tags matching the expression (repeatable)', collect, []);

    program.on('--help', function () {
      console.log('  For more details please visit https://github.com/cucumber/cucumber-js#cli\n');
    });

    return program;
  }

  function getConfiguration() {
    var program = getProgram();
    program.parse(argv);
    var profileArgs = Cucumber.Cli.ProfilesLoader.getArgs(program.profile);
    if (profileArgs.length > 0) {
      var fullArgs = argv.slice(0, 2).concat(profileArgs).concat(argv.slice(2));
      program = getProgram();
      program.parse(fullArgs);
    }
    var configuration = Cucumber.Cli.Configuration(program.opts(), program.args);
    return configuration;
  }

  var self = {
    run: function run(callback) {
      var configuration = getConfiguration();
      var runtime = Cucumber.Runtime(configuration);
      var formatters = [createIpcFormatter()].concat(configuration.getFormatters());
      formatters.forEach(function (formatter) {
        runtime.attachListener(formatter);
      });
      try {
        runtime.start(callback);
      } catch (e) {
        console.log(e.stack || e)
        callback(false)
      }
    }
  };
  return self;
}
313304
def main(argv, stdout=sys.stdout, stderr=sys.stderr):
    """"""
    # Wrap sys stdout for python 2, so print can understand unicode.
    linesep = os.linesep
    if sys.version_info[0] < 3:
        if stdout == sys.stdout:
            stdout = codecs.getwriter("utf-8")(stdout)
        if stderr == sys.stderr:
            stderr = codecs.getwriter("utf-8")(stderr)
        linesep = unicode(os.linesep)  # pylint: disable=undefined-variable

    arguments = docopt.docopt(
        __doc__, argv=argv[1:], version='git-lint v%s' % __VERSION__)

    json_output = arguments['--json']

    vcs, repository_root = get_vcs_root()

    if vcs is None:
        stderr.write('fatal: Not a git repository' + linesep)
        return 128

    commit = None
    if arguments['--last-commit']:
        commit = vcs.last_commit()

    if arguments['FILENAME']:
        invalid_filenames = find_invalid_filenames(arguments['FILENAME'],
                                                   repository_root)
        if invalid_filenames:
            invalid_filenames.append(('', ''))
            stderr.write(
                linesep.join(invalid[1] for invalid in invalid_filenames))
            return 2

        changed_files = vcs.modified_files(
            repository_root,
            tracked_only=arguments['--tracked'],
            commit=commit)
        modified_files = {}
        for filename in arguments['FILENAME']:
            normalized_filename = os.path.abspath(filename)
            modified_files[normalized_filename] = changed_files.get(
                normalized_filename)
    else:
        modified_files = vcs.modified_files(
            repository_root,
            tracked_only=arguments['--tracked'],
            commit=commit)

    linter_not_found = False
    files_with_problems = 0
    gitlint_config = get_config(repository_root)
    json_result = {}

    with futures.ThreadPoolExecutor(max_workers=multiprocessing.cpu_count())\
            as executor:
        processfile = functools.partial(process_file, vcs, commit,
                                        arguments['--force'], gitlint_config)
        for filename, result in executor.map(
                processfile, [(filename, modified_files[filename])
                              for filename in sorted(modified_files.keys())]):

            rel_filename = os.path.relpath(filename)

            if not json_output:
                stdout.write('Linting file: %s%s' % (termcolor.colored(
                    rel_filename, attrs=('bold', )), linesep))

            output_lines = []
            if result.get('error'):
                output_lines.extend('%s: %s' % (ERROR, reason)
                                    for reason in result.get('error'))
                linter_not_found = True
            if result.get('skipped'):
                output_lines.extend('%s: %s' % (SKIPPED, reason)
                                    for reason in result.get('skipped'))
            if not result.get('comments', []):
                if not output_lines:
                    output_lines.append(OK)
            else:
                files_with_problems += 1
                for data in result['comments']:
                    formatted_message = format_comment(data)
                    output_lines.append(formatted_message)
                    data['formatted_message'] = formatted_message

            if json_output:
                json_result[filename] = result
            else:
                output = linesep.join(output_lines)
                stdout.write(output)
                stdout.write(linesep + linesep)

    if json_output:
        # Hack to convert to unicode, Python3 returns unicode, wheres Python2
        # returns str.
        stdout.write(
            json.dumps(json_result,
                       ensure_ascii=False).encode('utf-8').decode('utf-8'))

    if files_with_problems > 0:
        return 1
    if linter_not_found:
        return 4
    return 0
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
299295
def _get_hash_by_shell():
    '''
    
    '''
    id_ = __opts__.get('id', '')
    id_hash = None
    py_ver = sys.version_info[:2]
    if py_ver >= (3, 3):
        # Python 3.3 enabled hash randomization, so we need to shell out to get
        # a reliable hash.
        id_hash = __salt__['cmd.run']([sys.executable, '-c', 'print(hash("{0}"))'.format(id_)],
                                      env={'PYTHONHASHSEED': '0'})
        try:
            id_hash = int(id_hash)
        except (TypeError, ValueError):
            log.debug('Failed to hash the ID to get the server_id grain. Result of hash command: %s', id_hash)
            id_hash = None
    if id_hash is None:
        # Python < 3.3 or error encountered above
        id_hash = hash(id_)

    return abs(id_hash % (2 ** 31))
1078996
def get_exitcode_stdout_stderr(cmd):
    
    from subprocess import Popen, PIPE
    import shlex
    args = shlex.split(cmd)

    proc = Popen(args, stdout=PIPE, stderr=PIPE)
    out, err = proc.communicate()
    exitcode = proc.returncode

    return exitcode, out, err
845384
def main(argv=None):
    

    if argv is None:
        argv = sys.argv

    # setup command line parser
    parser = U.OptionParser(version="%prog version: $Id$",
                            usage=usage,
                            description=globals()["__doc__"])

    group = U.OptionGroup(parser, "extract-specific options")

    # (Experimental option) Retain the UMI in the sequence read"
    group.add_option("--retain-umi", dest="retain_umi", action="store_true",
                     help=optparse.SUPPRESS_HELP)
    group.add_option("--read2-out", dest="read2_out", type="string",
                     help="file to output processed paired read to")
    group.add_option("--read2-stdout", dest="read2_stdout",
                     action="store_true",
                     help="Paired reads, send read2 to stdout, discarding read1")
    group.add_option("--quality-filter-threshold",
                     dest="quality_filter_threshold", type="int",
                     help=("Remove reads where any UMI base quality score "
                           "falls below this threshold"))
    group.add_option("--quality-filter-mask",
                     dest="quality_filter_mask", type="int",
                     help=("If a UMI base has a quality below this threshold, "
                           "replace the base with 'N'"))
    group.add_option("--quality-encoding",
                     dest="quality_encoding", type="choice",
                     choices=["phred33", "phred64", "solexa"],
                     help=("Quality score encoding. Choose from 'phred33'"
                           "[33-77] 'phred64' [64-106] or 'solexa' [59-106]"))
    group.add_option("--filter-cell-barcode",
                     dest="filter_cell_barcode",
                     action="store_true",
                     help="Filter the cell barcodes")
    group.add_option("--error-correct-cell",
                     dest="error_correct_cell",
                     action="store_true",
                     help=("Correct errors in the cell barcode"))
    group.add_option("--whitelist",
                     dest="whitelist", type="string",
                     help=("A whitelist of accepted cell barcodes"))
    group.add_option("--blacklist",
                     dest="blacklist", type="string",
                     help=("A blacklist of rejected cell barcodes"))
    group.add_option("--subset-reads", "--reads-subset",
                     dest="reads_subset", type="int",
                     help=("Only extract from the first N reads. If N is "
                           "greater than the number of reads, all reads will "
                           "be used"))
    group.add_option("--reconcile-pairs",
                     dest="reconcile", action="store_true",
                     help=("Allow the presences of reads in read2 input that "
                           "are not present in read1 input. This allows cell "
                           "barcode filtering of read1s without "
                           "considering read2s"))

    parser.add_option_group(group)

    group = U.OptionGroup(parser, "[EXPERIMENTAl] barcode extraction options")

    group.add_option("--either-read", dest="either_read", action="store_true",
                     help="UMI may be on either read (see "
                     "--either-read-resolve) for options to resolve cases where"
                     "UMI is on both reads")
    group.add_option("--either-read-resolve",
                     dest="either_read_resolve", type="choice",
                     choices=["discard", "quality"],
                     help=("How to resolve instances where both reads "
                           "contain a UMI but using --either-read."
                           "Choose from 'discard' or 'quality'"
                           "(use highest quality). default=dicard"))

    parser.add_option_group(group)

    parser.set_defaults(extract_method="string",
                        filter_cell_barcodes=False,
                        whitelist=None,
                        blacklist=None,
                        error_correct_cell=False,
                        pattern=None,
                        pattern2=None,
                        read2_in=None,
                        read2_out=False,
                        read2_stdout=False,
                        quality_filter_threshold=None,
                        quality_encoding=None,
                        reconcile=False,
                        either_read=False,
                        either_read_resolve="discard")

    # add common options (-h/--help, ...) and parse command line

    (options, args) = U.Start(parser, argv=argv,
                              add_extract_options=True,
                              add_group_dedup_options=False,
                              add_umi_grouping_options=False,
                              add_sam_options=False)

    if options.retain_umi and not options.extract_method == "regex":
        raise ValueError("option --retain-umi only works with --extract-method=regex")

    if options.quality_filter_threshold or options.quality_filter_mask:
        if not options.quality_encoding:
            U.error("must provide a quality encoding (--quality-"
                    "encoding) to filter UMIs by quality (--quality"
                    "-filter-threshold) or mask low quality bases "
                    "with (--quality-filter-mask)")

    extract_cell, extract_umi = U.validateExtractOptions(options)

    if options.either_read:
        if extract_cell:
            U.error("Option to extract from either read (--either-read) "
                    "is not currently compatible with cell barcode extraction")
        if not options.extract_method == "regex":
            U.error("Option to extract from either read (--either-read)"
                    "requires --extract-method=regex")
        if not options.pattern or not options.pattern2:
            U.error("Option to extract from either read (--either-read)"
                    "requires --bc-pattern=[PATTERN1] and"
                    "--bc-pattern2=[PATTERN2]")

    if options.filter_cell_barcodes:

        if not options.whitelist:
                U.error("must provide a whitelist (--whitelist) if using "
                        "--filter-cell-barcode option")

        if not extract_cell:
            if options.extract_method == "string":
                U.error("barcode pattern(s) do not include any cell bases "
                        "(marked with 'Cs') %s, %s" % (
                            options.pattern, options.pattern2))
            elif options.extract_method == "regex":
                U.error("barcode regex(es) do not include any cell groups "
                        "(starting with 'cell_') %s, %s" (
                            options.pattern, options.pattern2))

    read1s = umi_methods.fastqIterate(options.stdin)

    # set up read extractor
    ReadExtractor = extract_methods.ExtractFilterAndUpdate(
        options.extract_method,
        options.pattern,
        options.pattern2,
        options.prime3,
        extract_cell,
        options.quality_encoding,
        options.quality_filter_threshold,
        options.quality_filter_mask,
        options.filter_cell_barcode,
        options.retain_umi,
        options.either_read,
        options.either_read_resolve)

    if options.filter_cell_barcode:
        cell_whitelist, false_to_true_map = whitelist_methods.getUserDefinedBarcodes(
            options.whitelist, options.error_correct_cell)

        ReadExtractor.cell_whitelist = cell_whitelist
        ReadExtractor.false_to_true_map = false_to_true_map

    if options.blacklist:
        blacklist = set()
        with U.openFile(options.blacklist, "r") as inf:
            for line in inf:
                blacklist.add(line.strip().split("\t")[0])
        ReadExtractor.cell_blacklist = blacklist

    # variables for progress monitor
    progCount = 0
    displayMax = 100000
    U.info("Starting barcode extraction")

    if options.read2_in is None:
        for read in read1s:

            # incrementing count for monitoring progress
            progCount += 1

            # Update display in every 100kth iteration
            if progCount % displayMax == 0:
                U.info("Parsed {} reads".format(progCount))

            new_read = ReadExtractor(read)

            if options.reads_subset:
                if (ReadExtractor.read_counts['Input Reads'] >
                    options.reads_subset):
                    break

            if not new_read:
                continue

            options.stdout.write(str(new_read) + "\n")

    else:
        read2s = umi_methods.fastqIterate(U.openFile(options.read2_in))

        if options.read2_out:
            read2_out = U.openFile(options.read2_out, "w")

        if options.reconcile:
            strict = False
        else:
            strict = True

        for read1, read2 in umi_methods.joinedFastqIterate(
                read1s, read2s, strict):

            # incrementing count for monitoring progress
            progCount += 1

            # Update display in every 100kth iteration
            if progCount % displayMax == 0:
                U.info("Parsed {} reads".format(progCount))
                sys.stdout.flush()

            reads = ReadExtractor(read1, read2)

            if options.reads_subset:
                if (ReadExtractor.read_counts['Input Reads'] >
                    options.reads_subset):
                    break

            if not reads:
                continue
            else:
                new_read1, new_read2 = reads

            if options.read2_stdout:
                options.stdout.write(str(new_read2) + "\n")
            else:
                options.stdout.write(str(new_read1) + "\n")

                if options.read2_out:
                    read2_out.write(str(new_read2) + "\n")

    if options.read2_out:
        read2_out.close()

    for k, v in ReadExtractor.getReadCounts().most_common():
        U.info("%s: %s" % (k, v))

    U.Stop()
1283821
def Main():
  
  argument_parser = argparse.ArgumentParser(description=(
      'Calculates a message digest hash for every file in a directory or '
      'storage media image.'))

  argument_parser.add_argument(
      '--output_file', '--output-file', dest='output_file', action='store',
      metavar='source.hashes', default=None, help=(
          'path of the output file, default is to output to stdout.'))

  argument_parser.add_argument(
      'source', nargs='?', action='store', metavar='image.raw',
      default=None, help='path of the directory or storage media image.')

  options = argument_parser.parse_args()

  if not options.source:
    print('Source value is missing.')
    print('')
    argument_parser.print_help()
    print('')
    return False

  logging.basicConfig(
      level=logging.INFO, format='[%(levelname)s] %(message)s')

  if options.output_file:
    output_writer = FileOutputWriter(options.output_file)
  else:
    output_writer = StdoutWriter()

  try:
    output_writer.Open()
  except IOError as exception:
    print('Unable to open output writer with error: {0!s}.'.format(
        exception))
    print('')
    return False

  return_value = True
  mediator = command_line.CLIVolumeScannerMediator()
  recursive_hasher = RecursiveHasher(mediator=mediator)

  try:
    base_path_specs = recursive_hasher.GetBasePathSpecs(options.source)
    if not base_path_specs:
      print('No supported file system found in source.')
      print('')
      return False

    recursive_hasher.CalculateHashes(base_path_specs, output_writer)

    print('')
    print('Completed.')

  except errors.ScannerError as exception:
    return_value = False

    print('')
    print('[ERROR] {0!s}'.format(exception))

  except errors.UserAbort as exception:
    return_value = False

    print('')
    print('Aborted.')

  output_writer.Close()

  return return_value
250617
def main(args):
  of = sys.stdout
  if args.output and args.output[-4:] == '.bam':
    cmd = 'samtools view -Sb - -o '+args.output
    pof = Popen(cmd.split(),stdin=PIPE)
    of = pof.stdin
  elif args.output:
    of = open(args.output,'w')
  """"""

  header = None
  if args.HQ:
    cmd = 'samtools view -H '+args.HQ
    sys.stderr.write(cmd+"\n")
    header = Popen(cmd.split(),stdout=PIPE).communicate()[0]
    of.write(header)
  if (not header) and args.HQCorrected:
    cmd = 'samtools view -H '+args.HQCorrected
    sys.stderr.write(cmd+"\n")
    header = Popen(cmd.split(),stdout=PIPE).communicate()[0]
    of.write(header)
  if (not header) and args.AQ:
    cmd = 'samtools view -H '+args.AQ
    sys.stderr.write(cmd+"\n")
    header = Popen(cmd.split(),stdout=PIPE).communicate()[0]
    of.write(header)
  if (not header) and args.AQCorrected:
    cmd = 'samtools view -H '+args.AQCorrected
    sys.stderr.write(cmd+"\n")
    header = Popen(cmd.split(),stdout=PIPE).communicate()[0]
    of.write(header)
  if (not header) and args.subreads:
    cmd = 'samtools view -H '+args.subreads
    sys.stderr.write(cmd+"\n")
    header = Popen(cmd.split(),stdout=PIPE).communicate()[0]
    of.write(header)
  if (not header) and args.subreadsCorrected:
    cmd = 'samtools view -H '+args.subreadsCorrected
    sys.stderr.write(cmd+"\n")
    header = Popen(cmd.split(),stdout=PIPE).communicate()[0]
    of.write(header)

  _nameprog = re.compile('^(\S+)')
  negative_filter = set() # remove these
  """ Next read throught he alignments THAT ALIGNED in order of priority"""
  negative_filter = get_best_set(negative_filter,'-F 4',of,args,True)
  """After traversing all the aligned reads we can do it all over again
     this time with the unaligned portion of reads Finally go through the reads that did NOT ALIGN to get anything left"""
  get_best_set(negative_filter,'-f 4',of,args,False)
  if args.output and args.output[-4:] == '.bam':
    pof.communicate()
  else:
    of.close()
98238
def main(argv: Optional[Sequence[str]] = None, *, check: bool = True, **runargs) -> Optional[CompletedProcess]:
    
    parser = ArgumentParser(description="There are a few packages providing commands. Try e.g. `pip install scanpy-scripts`!")
    parser.set_defaults(func=parser.print_help)
    
    subparsers: DelegatingSubparsersAction = parser.add_subparsers(
        action=DelegatingSubparsersAction,
        _command='scanpy',
        _runargs={**runargs, 'check': check},
    )
    
    parser_settings = subparsers.add_parser('settings')
    parser_settings.set_defaults(func=cmd_settings)
    
    args = parser.parse_args(argv)
    return args.func()
1107009
def sh2(cmd):
    """"""
    p = Popen(cmd, stdout=PIPE, shell=True, env=sub_environment())
    out = p.communicate()[0]
    retcode = p.returncode
    if retcode:
        raise CalledProcessError(retcode, cmd)
    else:
        return out.rstrip()
853188
def command_line(argv):
    
    arguments = parse_command_line(argv)
    if arguments.generate:
        generate_fixer_file(arguments.generate)
    paths = edit_files(arguments.patterns,
                       expressions=arguments.expressions,
                       functions=arguments.functions,
                       executables=arguments.executables,
                       start_dirs=arguments.start_dirs,
                       max_depth=arguments.max_depth,
                       dry_run=arguments.dry_run,
                       output=arguments.output,
                       encoding=arguments.encoding,
                       newline=arguments.newline)
    # If the output is not sys.stdout, we need to close it because
    # argparse.FileType does not do it for us.
    is_sys = arguments.output in [sys.stdout, sys.stderr]
    if not is_sys and isinstance(arguments.output, io.IOBase):
        arguments.output.close()
    return paths
880354
def main(args=sys.argv):
    

    if len(args) < 2:
        return usage("Command expected")

    command = args[1]
    rest = args[2:]

    if "create".startswith(command):
        return cli_create(rest)
    elif "query".startswith(command):
        return cli_query(rest)
    elif "verify".startswith(command):
        return cli_verify(rest)
    else:
        return usage("Unknown command: %s" % command)
739714
def parse_command_line(argv):
    
    import textwrap

    example = textwrap.dedent("""
    Examples:
    # Simple string substitution (-e). Will show a diff. No changes applied.
    {0} -e "re.sub('failIf', 'assertFalse', line)" *.py

    # File level modifications (-f). Overwrites the files in place (-w).
    {0} -w -f fixer:fixit *.py

    # Will change all test*.py in subdirectories of tests.
    {0} -e "re.sub('failIf', 'assertFalse', line)" -s tests test*.py
    """).format(os.path.basename(argv[0]))
    formatter_class = argparse.RawDescriptionHelpFormatter
    parser = argparse.ArgumentParser(description="Python mass editor",
                                     epilog=example,
                                     formatter_class=formatter_class)
    parser.add_argument("-V", "--version", action="version",
                        version="%(prog)s {}".format(__version__))
    parser.add_argument("-w", "--write", dest="dry_run",
                        action="store_false", default=True,
                        help="modify target file(s) in place. "
                        "Shows diff otherwise.")
    parser.add_argument("-v", "--verbose", dest="verbose_count",
                        action="count", default=0,
                        help="increases log verbosity (can be specified "
                        "multiple times)")
    parser.add_argument("-e", "--expression", dest="expressions", nargs=1,
                        help="Python expressions applied to target files. "
                        "Use the line variable to reference the current line.")
    parser.add_argument("-f", "--function", dest="functions", nargs=1,
                        help="Python function to apply to target file. "
                        "Takes file content as input and yield lines. "
                        "Specify function as [module]:?<function name>.")
    parser.add_argument("-x", "--executable", dest="executables", nargs=1,
                        help="Python executable to apply to target file.")
    parser.add_argument("-s", "--start", dest="start_dirs",
                        help="Directory(ies) from which to look for targets.")
    parser.add_argument("-m", "--max-depth-level", type=int, dest="max_depth",
                        help="Maximum depth when walking subdirectories.")
    parser.add_argument("-o", "--output", metavar="FILE",
                        type=argparse.FileType("w"), default=sys.stdout,
                        help="redirect output to a file")
    parser.add_argument("-g", "--generate", metavar="FILE", type=str,
                        help="generate input file suitable for -f option")
    parser.add_argument("--encoding", dest="encoding",
                        help="Encoding of input and output files")
    parser.add_argument("--newline", dest="newline",
                        help="Newline character for output files")
    parser.add_argument("patterns", metavar="pattern",
                        nargs="*",  # argparse.REMAINDER,
                        help="shell-like file name patterns to process.")
    arguments = parser.parse_args(argv[1:])

    if not (arguments.expressions or
            arguments.functions or
            arguments.generate or
            arguments.executables):
        parser.error(
            '--expression, --function, --generate or --executable missing')

    # Sets log level to WARN going more verbose for each new -V.
    log.setLevel(max(3 - arguments.verbose_count, 0) * 10)
    return arguments