Main entry-point for oz's cli
776797
def main():
    """"""

    # Hack to make user code available for import
    sys.path.append(".")

    # Run the specified action
    oz.initialize()
    retr = optfn.run(list(oz._actions.values()))

    if retr == optfn.ERROR_RETURN_CODE:
        sys.exit(-1)
    elif retr == None:
        sys.exit(0)
    elif isinstance(retr, int):
        sys.exit(retr)
    else:
        raise Exception("Unexpected return value from action: %s" % retr)
297592
def main(arguments=None):
    
    # setup the command-line util settings

    dev_flag = False

    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="DEBUG",
        options_first=False,
        projectName="rockAtlas"
    )
    arguments, settings, log, dbConn = su.setup()

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if varname == "import":
            varname = "iimport"
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    ## START LOGGING ##
    startTime = times.get_now_sql_datetime()
    log.info(
        '--- STARTING TO RUN THE cl_utils.py AT %s' %
        (startTime,))

    if init:
        from os.path import expanduser
        home = expanduser("~")
        filepath = home + "/.config/rockAtlas/rockAtlas.yaml"
        try:
            cmd = """open %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass
        try:
            cmd = """start %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass

    # CALL FUNCTIONS/OBJECTS
    if bookkeeping:
        from rockAtlas.bookkeeping import bookkeeper
        bk = bookkeeper(
            log=log,
            settings=settings,
            fullUpdate=fullFlag
        )
        bk.clean_all()

    if astorb:
        from rockAtlas.orbital_elements import astorb
        oe = astorb(
            log=log,
            settings=settings
        )
        oe.refresh()

    if pyephem:

        from rockAtlas.positions import pyephemPositions
        pyeph = pyephemPositions(
            log=log,
            settings=settings,
            dev_flag=dev_flag
        )
        pyeph.get(singleSnapshot=oneFlag)

    if orbfit:
        from rockAtlas.positions import orbfitPositions
        oe = orbfitPositions(
            log=log,
            settings=settings,
            dev_flag=dev_flag
        )
        oe.get(singleExposure=oneFlag)

    if cache:
        from rockAtlas.phot import download
        data = download(
            log=log,
            settings=settings,
            dev_flag=dev_flag
        )
        data.get(days=days)

    if dophot:
        from rockAtlas.phot import dophotMatch
        dp = dophotMatch(
            log=log,
            settings=settings
        )
        dp.get()

    if cycle:
        from rockAtlas.phot import download
        from rockAtlas.positions import pyephemPositions
        from rockAtlas.positions import orbfitPositions
        from rockAtlas.phot import dophotMatch
        from fundamentals.mysql import readquery

        # INITIAL ACTIONS
        # SETUP ALL DATABASE CONNECTIONS
        from rockAtlas import database
        db = database(
            log=log,
            settings=settings
        )
        dbConns, dbVersions = db.connect()
        atlas3DbConn = dbConns["atlas3"]
        atlas4DbConn = dbConns["atlas4"]
        atlasMoversDBConn = dbConns["atlasMovers"]

        while True:

            if dev_flag:
                o = " and dev_flag = 1"
            else:
                o = " "

            sqlQuery = u"""
                select distinct floor(mjd) from (
select mjd from atlas_exposures where dophot_match = 0 %(o)s
union all
select mjd from day_tracker where processed = 0 %(o)s) as a;
            """ % locals()
            rows = readquery(
                log=log,
                sqlQuery=sqlQuery,
                dbConn=atlasMoversDBConn,
                quiet=False
            )

            if len(rows) == 0:
                if dev_flag:
                    print "Processing of the ATLAS development dataset is now complete and up to date"
                else:
                    print "Processing of ATLAS data is now complete and up to date"
                break

            start_time = time.time()

            data = download(
                log=log,
                settings=settings,
                dev_flag=dev_flag
            )
            data.get(days=days)

            print "%d seconds to download ATLAS cache of %s days\n" % (time.time() - start_time, days)
            start_time = time.time()

            pyeph = pyephemPositions(
                log=log,
                settings=settings,
                dev_flag=dev_flag
            )
            pyeph.get()

            print "%d seconds to generate pyephem snapshots\n" % (time.time() - start_time,)
            start_time = time.time()

            oe = orbfitPositions(
                log=log,
                settings=settings,
                dev_flag=dev_flag
            )
            oe.get()

            print "%d seconds to generate orbfit positions\n" % (time.time() - start_time,)
            start_time = time.time()

            dp = dophotMatch(
                log=log,
                settings=settings
            )
            dp.get()

            print "%d seconds to extract dophot measurements\n" % (time.time() - start_time,)
            start_time = time.time()

    if "dbConn" in locals() and dbConn:
        dbConn.commit()
        dbConn.close()
    ## FINISH LOGGING ##
    endTime = times.get_now_sql_datetime()
    runningTime = times.calculate_time_difference(startTime, endTime)
    log.info('-- FINISHED ATTEMPT TO RUN THE cl_utils.py AT %s (RUNTIME: %s) --' %
             (endTime, runningTime, ))

    return
1138895
def main(ctx, opts, version):
    """"""
    # pylint: disable=unused-argument
    if version:
        print_version()
    elif ctx.invoked_subcommand is None:
        click.echo(ctx.get_help())
1288815
def main():
    """"""
    check_python_version()
    check_python_modules()
    check_executables()
    home = os.path.expanduser("~")
    print("\033[1mCheck files\033[0m")
    rcfile = os.path.join(home, ".hwrtrc")
    if os.path.isfile(rcfile):
        print("~/.hwrtrc... %sFOUND%s" %
              (Bcolors.OKGREEN, Bcolors.ENDC))
    else:
        print("~/.hwrtrc... %sNOT FOUND%s" %
              (Bcolors.FAIL, Bcolors.ENDC))
    misc_path = pkg_resources.resource_filename('hwrt', 'misc/')
    print("misc-path: %s" % misc_path)
303256
def main():
    """"""
    # Initialize logging to the terminal.
    coloredlogs.install()
    # Prepare for command line argument parsing.
    action = show_matching_entry
    program_opts = dict(exclude_list=[])
    show_opts = dict(filters=[], use_clipboard=is_clipboard_supported())
    verbosity = 0
    # Parse the command line arguments.
    try:
        options, arguments = getopt.gnu_getopt(
            sys.argv[1:],
            "elnp:f:x:vqh",
            ["edit", "list", "no-clipboard", "password-store=", "filter=", "exclude=", "verbose", "quiet", "help"],
        )
        for option, value in options:
            if option in ("-e", "--edit"):
                action = edit_matching_entry
            elif option in ("-l", "--list"):
                action = list_matching_entries
            elif option in ("-n", "--no-clipboard"):
                show_opts["use_clipboard"] = False
            elif option in ("-p", "--password-store"):
                stores = program_opts.setdefault("stores", [])
                stores.append(PasswordStore(directory=value))
            elif option in ("-f", "--filter"):
                show_opts["filters"].append(value)
            elif option in ("-x", "--exclude"):
                program_opts["exclude_list"].append(value)
            elif option in ("-v", "--verbose"):
                coloredlogs.increase_verbosity()
                verbosity += 1
            elif option in ("-q", "--quiet"):
                coloredlogs.decrease_verbosity()
                verbosity -= 1
            elif option in ("-h", "--help"):
                usage(__doc__)
                return
            else:
                raise Exception("Unhandled option! (programming error)")
        if not (arguments or action == list_matching_entries):
            usage(__doc__)
            return
    except Exception as e:
        warning("Error: %s", e)
        sys.exit(1)
    # Execute the requested action.
    try:
        show_opts["quiet"] = verbosity < 0
        kw = show_opts if action == show_matching_entry else {}
        action(QuickPass(**program_opts), arguments, **kw)
    except PasswordStoreError as e:
        # Known issues don't get a traceback.
        logger.error("%s", e)
        sys.exit(1)
    except KeyboardInterrupt:
        # If the user interrupted an interactive prompt they most likely did so
        # intentionally, so there's no point in generating more output here.
        sys.exit(1)
120706
def main(arguments=None):
    
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="WARNING",
        options_first=False,
        projectName="polyglot"
    )
    arguments, settings, log, dbConn = su.setup()

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    ## START LOGGING ##
    startTime = times.get_now_sql_datetime()
    log.info(
        '--- STARTING TO RUN THE cl_utils.py AT %s' %
        (startTime,))

    # for k, v in locals().iteritems():
    #     print k, v

    if not destinationFolder:
        destinationFolder = os.getcwd()
    if not filenameFlag:
        filenameFlag = False
    if not cleanFlag:
        readability = False
    else:
        readability = True

    if init:
        from os.path import expanduser
        home = expanduser("~")
        filepath = home + "/.config/polyglot/polyglot.yaml"
        try:
            cmd = """open %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass
        try:
            cmd = """start %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass

    if pdf and url:
        filepath = printpdf.printpdf(
            log=log,
            settings=settings,
            url=url,
            folderpath=destinationFolder,
            title=filenameFlag,
            append=False,
            readability=readability
        ).get()

    if html and url:

        cleaner = htmlCleaner.htmlCleaner(
            log=log,
            settings=settings,
            url=url,
            outputDirectory=destinationFolder,
            title=filenameFlag,  # SET TO FALSE TO USE WEBPAGE TITLE,
            style=cleanFlag,  # add polyglot's styling to the HTML document
            metadata=True,  # include metadata in generated HTML (e.g. title),
            h1=True  # include title as H1 at the top of the doc
        )
        filepath = cleaner.clean()

    if epub:
        if url:
            iinput = url
        else:
            iinput = docx
        from polyglot import ebook
        epub = ebook(
            log=log,
            settings=settings,
            urlOrPath=iinput,
            title=filenameFlag,
            bookFormat="epub",
            outputDirectory=destinationFolder
        )
        filepath = epub.get()

    if mobi:
        if url:
            iinput = url
        else:
            iinput = docx
        from polyglot import ebook
        mobi = ebook(
            log=log,
            settings=settings,
            urlOrPath=iinput,
            title=filenameFlag,
            bookFormat="mobi",
            outputDirectory=destinationFolder,
        )
        filepath = mobi.get()

    if kindle:
        if url:
            iinput = url
        else:
            iinput = docx
        from polyglot import kindle
        sender = kindle(
            log=log,
            settings=settings,
            urlOrPath=iinput,
            title=filenameFlag
        )
        success = sender.send()

    if kindleNB2MD:
        basename = os.path.basename(notebook)
        extension = os.path.splitext(basename)[1]
        filenameNoExtension = os.path.splitext(basename)[0]
        if destinationFolder:
            filepath = destinationFolder + "/" + filenameNoExtension + ".md"
        else:
            filepath = notebook.replace("." + extension, ".md")
        from polyglot.markdown import kindle_notebook
        nb = kindle_notebook(
            log=log,
            kindleExportPath=notebook,
            outputPath=filepath
        )
        nb.convert()

    if openFlag:
        try:
            cmd = """open %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass
        try:
            cmd = """start %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass

    if "dbConn" in locals() and dbConn:
        dbConn.commit()
        dbConn.close()
    ## FINISH LOGGING ##
    endTime = times.get_now_sql_datetime()
    runningTime = times.calculate_time_difference(startTime, endTime)
    log.info('-- FINISHED ATTEMPT TO RUN THE cl_utils.py AT %s (RUNTIME: %s) --' %
             (endTime, runningTime, ))

    return
756499
def main(arguments=None):
    
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="ERROR",
        options_first=True
    )
    arguments, settings, log, dbConn = su.setup()

    # tab completion for raw_input
    readline.set_completer_delims(' \t\n;')
    readline.parse_and_bind("tab: complete")
    readline.set_completer(tab_complete)

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    ## START LOGGING ##
    startTime = times.get_now_sql_datetime()
    log.info(
        '--- STARTING TO RUN THE cl_utils.py AT %s' %
        (startTime,))

    # set options interactively if user requests
    if "interactiveFlag" in locals() and interactiveFlag:

        # load previous settings
        moduleDirectory = os.path.dirname(__file__) + "/resources"
        pathToPickleFile = "%(moduleDirectory)s/previousSettings.p" % locals()
        try:
            with open(pathToPickleFile):
                pass
            previousSettingsExist = True
        except:
            previousSettingsExist = False
        previousSettings = {}
        if previousSettingsExist:
            previousSettings = pickle.load(open(pathToPickleFile, "rb"))

        # x-raw-input
        # x-boolean-raw-input
        # x-raw-input-with-default-value-from-previous-settings

        # save the most recently used requests
        pickleMeObjects = []
        pickleMe = {}
        theseLocals = locals()
        for k in pickleMeObjects:
            pickleMe[k] = theseLocals[k]
        pickle.dump(pickleMe, open(pathToPickleFile, "wb"))

    # call the worker function
    # x-if-settings-or-database-credientials
    if cone and filelist:
        import codecs
        pathToReadFile = pathToCoordinateList
        readFile = codecs.open(pathToReadFile, encoding='utf-8', mode='r')

        listOfCoordinates = []
        for line in readFile.readlines():
            line = line.strip()
            [ra, dec] = line.split()
            listOfCoordinates.append(str(ra) + " " + str(dec))
        search = conesearch(
            log=log,
            radiusArcsec=radiusArcsec,
            nearestOnly=nearestFlag,
            unclassified=unclassifiedFlag,
            listOfCoordinates=listOfCoordinates,
            outputFilePath=outPutFile,
            verbose=verboseFlag,
            redshift=redshiftFlag)
    elif cone:
        search = conesearch(
            log=log,
            ra=ra,
            dec=dec,
            radiusArcsec=radiusArcsec,
            nearestOnly=nearestFlag,
            unclassified=unclassifiedFlag,
            outputFilePath=outPutFile,
            verbose=verboseFlag,
            redshift=redshiftFlag
        )
    elif obj:
        search = namesearch(
            log=log,
            names=objectName,
            verbose=verboseFlag,
            outputFilePath=outPutFile
        )
    search.get()

    if "dbConn" in locals() and dbConn:
        dbConn.commit()
        dbConn.close()
    ## FINISH LOGGING ##
    endTime = times.get_now_sql_datetime()
    runningTime = times.calculate_time_difference(startTime, endTime)
    log.info('-- FINISHED ATTEMPT TO RUN THE cl_utils.py AT %s (RUNTIME: %s) --' %
             (endTime, runningTime, ))

    return
1252129
def main():
    
    from optparse import OptionParser, OptionGroup
    from os import sep
    from os.path import basename, getsize
    from sys import argv, exit as sysExit
    from chardet import detect
    from codecs import BOM_UTF8, open as codecsOpen

    def optParse():
        """
        Parses command line options.

        Generally we're supporting all the command line options that doxypy.py
        supports in an analogous way to make it easy to switch back and forth.
        We additionally support a top-level namespace argument that is used
        to trim away excess path information.
        """

        parser = OptionParser(prog=basename(argv[0]))

        parser.set_usage("%prog [options] filename")
        parser.add_option(
            "-a", "--autobrief",
            action="store_true", dest="autobrief",
            help="parse the docstring for @brief description and other information"
        )
        parser.add_option(
            "-c", "--autocode",
            action="store_true", dest="autocode",
            help="parse the docstring for code samples"
        )
        parser.add_option(
            "-n", "--ns",
            action="store", type="string", dest="topLevelNamespace",
            help="specify a top-level namespace that will be used to trim paths"
        )
        parser.add_option(
            "-t", "--tablength",
            action="store", type="int", dest="tablength", default=4,
            help="specify a tab length in spaces; only needed if tabs are used"
        )
        parser.add_option(
            "-s", "--stripinit",
            action="store_true", dest="stripinit",
            help="strip __init__ from namespace"
        )
        parser.add_option(
            "-O", "--object-respect",
            action="store_true", dest="object_respect",
            help="By default, doxypypy hides object class from class dependencies even if class inherits explictilty from objects (new-style class), this option disable this."
        )
        group = OptionGroup(parser, "Debug Options")
        group.add_option(
            "-d", "--debug",
            action="store_true", dest="debug",
            help="enable debug output on stderr"
        )
        parser.add_option_group(group)

        ## Parse options based on our definition.
        (options, filename) = parser.parse_args()

        # Just abort immediately if we are don't have an input file.
        if not filename:
            stderr.write("No filename given." + linesep)
            sysExit(-1)

        # Turn the full path filename into a full path module location.
        fullPathNamespace = filename[0].replace(sep, '.')[:-3]
        # Use any provided top-level namespace argument to trim off excess.
        realNamespace = fullPathNamespace
        if options.topLevelNamespace:
            namespaceStart = fullPathNamespace.find(options.topLevelNamespace)
            if namespaceStart >= 0:
                realNamespace = fullPathNamespace[namespaceStart:]
        if options.stripinit:
            realNamespace = realNamespace.replace('.__init__', '')
        options.fullPathNamespace = realNamespace

        return options, filename[0]

    # Figure out what is being requested.
    (options, inFilename) = optParse()

    # Figure out encoding of input file.
    numOfSampleBytes = min(getsize(inFilename), 32)
    sampleBytes = open(inFilename, 'rb').read(numOfSampleBytes)
    sampleByteAnalysis = detect(sampleBytes)
    encoding = sampleByteAnalysis['encoding'] or 'ascii'

    # Switch to generic versions to strip the BOM automatically.
    if sampleBytes.startswith(BOM_UTF8):
        encoding = 'UTF-8-SIG'
    if encoding.startswith("UTF-16"):
        encoding = "UTF-16"
    elif encoding.startswith("UTF-32"):
        encoding = "UTF-32"

    # Read contents of input file.
    if encoding == 'ascii':
        inFile = open(inFilename)
    else:
        inFile = codecsOpen(inFilename, encoding=encoding)
    lines = inFile.readlines()
    inFile.close()
    # Create the abstract syntax tree for the input file.
    astWalker = AstWalker(lines, options, inFilename)
    astWalker.parseLines()
    # Output the modified source.
    print(astWalker.getLines())
571309
def main():
	
	parser = cli.Cli()
	parser.parse(sys.argv[1:])
	return parser.run()
1298359
def main() -> None:
    """"""

    # Make sure we have access to self
    if 'self' not in globals():
        print("Run 'set locals_in_py true' and then rerun this script")
        return

    # Make sure the user passed in an output file
    if len(sys.argv) != 2:
        print("Usage: {} <output_file>".format(os.path.basename(sys.argv[0])))
        return

    # Open the output file
    outfile_path = os.path.expanduser(sys.argv[1])
    try:
        outfile = open(outfile_path, 'w')
    except OSError as e:
        print("Error opening {} because: {}".format(outfile_path, e))
        return

    # Write the help summary
    header = '{0}\nSUMMARY\n{0}\n'.format(ASTERISKS)
    outfile.write(header)

    result = app('help -v')
    outfile.write(result.stdout)

    # Get a list of all commands and help topics and then filter out duplicates
    all_commands = set(self.get_all_commands())
    all_topics = set(self.get_help_topics())
    to_save = list(all_commands | all_topics)
    to_save.sort()

    for item in to_save:
        is_command = item in all_commands
        add_help_to_file(item, outfile, is_command)

        if is_command:
            # Add any sub-commands
            for subcmd in get_sub_commands(getattr(self.cmd_func(item), 'argparser', None)):
                full_cmd = '{} {}'.format(item, subcmd)
                add_help_to_file(full_cmd, outfile, is_command)

    outfile.close()
    print("Output written to {}".format(outfile_path))
497791
def cli_main():
    """"""
    SearchContext.commit()
    args = parser.parse_args()
    # open up a browser
    firefox_remote = Remote("http://127.0.0.1:4444/wd/hub", DesiredCapabilities.FIREFOX)
    with contextlib.closing(firefox_remote):
        context = SearchContext.from_instances([FastSearch(), Browser(firefox_remote)])
        search = Search(parent=context)

        if args.fast:
            with context.use(FastSearch, Browser):
                main(search, args.query)
        else:
            with context.use(Browser):
                main(search, args.query)
858893
def main():
    
    # Locale
    locale.setlocale(locale.LC_ALL, '')

    # Encoding for output streams
    if str == bytes:  # PY2
        writer = codecs.getwriter(locale.getpreferredencoding())
        o_stdout, o_stderr = sys.stdout, sys.stderr
        sys.stdout = writer(sys.stdout)
        sys.stdout.buffer = o_stdout
        sys.stderr = writer(sys.stderr)
        sys.stderr.buffer = o_stderr
    else:  # PY3
        sys.stdin = sys.stdin.buffer

    # Parses command-line

    # Runtime to setup
    def add_runtime_option(opt):
        opt.add_argument(
            '-r', '--runtime', action='store',
            help="runtime to deploy on the server if the queue doesn't exist. "
                 "If unspecified, will auto-detect what is appropriate, and "
                 "fallback on 'default'.")

    # Destination selection
    def add_destination_option(opt):
        opt.add_argument('destination', action='store',
                         help="Machine to SSH into; [user@]host[:port]")
        opt.add_argument('--queue', action='store', default=DEFAULT_TEJ_DIR,
                         help="Directory for tej's files")

    # Root parser
    parser = argparse.ArgumentParser(
        description="Trivial Extensible Job-submission")
    parser.add_argument('--version', action='version',
                        version="tej version %s" % tej_version)
    parser.add_argument('-v', '--verbose', action='count', default=1,
                        dest='verbosity',
                        help="augments verbosity level")
    subparsers = parser.add_subparsers(title="commands", metavar='')

    # Setup action
    parser_setup = subparsers.add_parser(
        'setup',
        help="Sets up tej on a remote machine")
    add_destination_option(parser_setup)
    add_runtime_option(parser_setup)
    parser_setup.add_argument('--make-link', action='append',
                              dest='make_link')
    parser_setup.add_argument('--make-default-link', action='append_const',
                              dest='make_link', const=DEFAULT_TEJ_DIR)
    parser_setup.add_argument('--force', action='store_true')
    parser_setup.add_argument('--only-links', action='store_true')
    parser_setup.set_defaults(func=_setup)

    # Submit action
    parser_submit = subparsers.add_parser(
        'submit',
        help="Submits a job to a remote machine")
    add_destination_option(parser_submit)
    add_runtime_option(parser_submit)
    parser_submit.add_argument('--id', action='store',
                               help="Identifier for the new job")
    parser_submit.add_argument('--script', action='store',
                               help="Relative name of the script in the "
                                    "directory")
    parser_submit.add_argument('directory', action='store',
                               help="Job directory to upload")
    parser_submit.set_defaults(func=_submit)

    # Status action
    parser_status = subparsers.add_parser(
        'status',
        help="Gets the status of a job")
    add_destination_option(parser_status)
    parser_status.add_argument('--id', action='store',
                               help="Identifier of the running job")
    parser_status.set_defaults(func=_status)

    # Download action
    parser_download = subparsers.add_parser(
        'download',
        help="Downloads files from finished job")
    add_destination_option(parser_download)
    parser_download.add_argument('--id', action='store',
                                 help="Identifier of the job")
    parser_download.add_argument('files', action='store',
                                 nargs=argparse.ONE_OR_MORE,
                                 help="Files to download")
    parser_download.set_defaults(func=_download)

    # Kill action
    parser_kill = subparsers.add_parser(
        'kill',
        help="Kills a running job")
    add_destination_option(parser_kill)
    parser_kill.add_argument('--id', action='store',
                             help="Identifier of the running job")
    parser_kill.set_defaults(func=_kill)

    # Delete action
    parser_delete = subparsers.add_parser(
        'delete',
        help="Deletes a finished job")
    add_destination_option(parser_delete)
    parser_delete.add_argument('--id', action='store',
                               help="Identifier of the finished job")
    parser_delete.set_defaults(func=_delete)

    # List action
    parser_list = subparsers.add_parser(
        'list',
        help="Lists remote jobs")
    add_destination_option(parser_list)
    parser_list.set_defaults(func=_list)

    args = parser.parse_args()
    setup_logging(args.verbosity)

    try:
        args.func(args)
    except Error as e:
        # No need to show a traceback here, this is not an internal error
        logger.critical(e)
        sys.exit(1)
    sys.exit(0)
724867
def main():
    """"""
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers()

    appengine.register_commands(subparsers)
    requirements.register_commands(subparsers)
    pylint.register_commands(subparsers)

    args = parser.parse_args()
    args.func(args)
971415
def main_cli(ctx, verbose=False):
    
    sTime = time.time()
    if ctx.obj is None:  # Fix for bug (as of 3.0)
        # https://github.com/pallets/click/issues/888
        ctx.obj = {}
    ctx.obj['VERBOSE'] = verbose
    ctx.obj['STIME'] = sTime

    click.secho("Ontospy " + VERSION, fg='white')
    # click.secho("------------", fg='white')
    if not verbose and ctx.invoked_subcommand is None:
        click.echo(ctx.get_help())
240690
def main() -> None:
    
    parser = ArgumentParser(
        formatter_class=RawDescriptionHelpFormatter,
        description="""
Performs a grep (global-regular-expression-print) search of files in OpenXML
format, which is to say inside ZIP files.

Note that you can chain; for example, to search for OpenXML files containing
both "armadillo" and "bonobo", you can do:

    grep_in_openxml -l armadillo *.pptx | grep_in_openxml -x -l bonobo
                    ^^                                    ^^
                print filenames                       read filenames from stdin

"""
    )
    parser.add_argument(
        "pattern",
        help="Regular expression pattern to apply."
    )
    parser.add_argument(
        "filename", nargs="*",
        help="File(s) to check. You can also specify directores if you use "
             "--recursive"
    )
    parser.add_argument(
        "--filenames_from_stdin", "-x", action="store_true",
        help="Take filenames from stdin instead, one line per filename "
             "(useful for chained grep)."
    )
    parser.add_argument(
        "--recursive", action="store_true",
        help="Allow search to descend recursively into any directories "
             "encountered."
    )
    # Flag abbreviations to match grep:
    parser.add_argument(
        "--ignore_case", "-i", action="store_true",
        help="Ignore case"
    )
    parser.add_argument(
        "--invert_match", "-v", action="store_true",
        help="Invert match"
    )
    parser.add_argument(
        "--files_with_matches", "-l", action="store_true",
        help="Show filenames of files with matches"
    )
    parser.add_argument(
        "--files_without_match", "-L", action="store_true",
        help="Show filenames of files with no match"
    )
    parser.add_argument(
        "--grep_inner_file_name", action="store_true",
        help="Search the NAMES of the inner files, not their contents."
    )
    parser.add_argument(
        "--show_inner_file", action="store_true",
        help="For hits, show the filenames of inner files, within each ZIP."
    )
    parser.add_argument(
        "--nprocesses", type=int, default=multiprocessing.cpu_count(),
        help="Specify the number of processes to run in parallel."
    )
    parser.add_argument(
        "--verbose", action="store_true",
        help="Verbose output"
    )
    args = parser.parse_args()
    main_only_quicksetup_rootlogger(
        level=logging.DEBUG if args.verbose else logging.INFO)
    if args.files_with_matches and args.files_without_match:
        raise ValueError("Can't specify both --files_with_matches (-l) and "
                         "--files_without_match (-L)!")
    if bool(args.filenames_from_stdin) == bool(args.filename):
        raise ValueError("Specify --filenames_from_stdin or filenames on the "
                         "command line, but not both")

    # Compile regular expression
    if args.grep_inner_file_name:
        final_pattern = args.pattern
    else:
        encoding = getdefaultencoding()
        final_pattern = args.pattern.encode(encoding)
    flags = re.IGNORECASE if args.ignore_case else 0
    log.debug("Using regular expression {!r} with flags {!r}",
              final_pattern, flags)
    regex = re.compile(final_pattern, flags)

    # Set up pool for parallel processing
    pool = multiprocessing.Pool(processes=args.nprocesses)

    # Iterate through files
    parse_kwargs = dict(
        regex=regex,
        invert_match=args.invert_match,
        files_with_matches=args.files_with_matches,
        files_without_match=args.files_without_match,
        grep_inner_file_name=args.grep_inner_file_name,
        show_inner_file=args.show_inner_file
    )
    if args.filenames_from_stdin:
        for line in stdin.readlines():
            zipfilename = line.strip()
            parallel_kwargs = {'zipfilename': zipfilename}
            parallel_kwargs.update(**parse_kwargs)
            pool.apply_async(parse_zip, [], parallel_kwargs)
    else:
        for zipfilename in gen_filenames(starting_filenames=args.filename,
                                         recursive=args.recursive):
            parallel_kwargs = {'zipfilename': zipfilename}
            parallel_kwargs.update(**parse_kwargs)
            pool.apply_async(parse_zip, [], parallel_kwargs)
    pool.close()
    pool.join()
578394
def main():
    """"""
    parser = OptionParser()
    parser.add_option('-a', '--hostname',
                      help='ClamAV source server hostname',
                      dest='hostname',
                      type='str',
                      default='db.de.clamav.net')
    parser.add_option('-r', '--text-record',
                      help='ClamAV Updates TXT record',
                      dest='txtrecord',
                      type='str',
                      default='current.cvd.clamav.net')
    parser.add_option('-w', '--work-directory',
                      help='Working directory',
                      dest='workdir',
                      type='str',
                      default='/var/spool/clamav-mirror')
    parser.add_option('-d', '--mirror-directory',
                      help='The mirror directory',
                      dest='mirrordir',
                      type='str',
                      default='/srv/www/clamav')
    parser.add_option('-u', '--user',
                      help='Change file owner to this user',
                      dest='user',
                      type='str',
                      default='nginx')
    parser.add_option('-g', '--group',
                      help='Change file group to this group',
                      dest='group',
                      type='str',
                      default='nginx')
    parser.add_option('-l', '--locks-directory',
                      help='Lock files directory',
                      dest='lockdir',
                      type='str',
                      default='/var/lock/subsys')
    parser.add_option('-v', '--verbose',
                      help='Display verbose output',
                      dest='verbose',
                      action='store_true',
                      default=False)
    options, _ = parser.parse_args()
    try:
        lockfile = os.path.join(options.lockdir, 'clamavmirror')
        with open(lockfile, 'w+') as lock:
            fcntl.lockf(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
            work(options)
    except IOError:
        info("=> Another instance is already running")
        sys.exit(254)
376098
def main():
    
    from os import path as op
    from inspect import getfile, currentframe
    from setuptools import setup, find_packages
    from niworkflows.__about__ import (
        __packagename__,
        __author__,
        __email__,
        __maintainer__,
        __license__,
        __description__,
        __longdesc__,
        __url__,
        DOWNLOAD_URL,
        CLASSIFIERS,
        REQUIRES,
        SETUP_REQUIRES,
        LINKS_REQUIRES,
        TESTS_REQUIRES,
        EXTRA_REQUIRES,
    )

    pkg_data = {
        'niworkflows': [
            'data/t1-mni_registration*.json',
            'data/bold-mni_registration*.json',
            'reports/figures.json',
            'reports/fmriprep.yml',
            'reports/report.tpl',
        ]}

    root_dir = op.dirname(op.abspath(getfile(currentframe())))
    version = None
    cmdclass = {}
    if op.isfile(op.join(root_dir, __packagename__, 'VERSION')):
        with open(op.join(root_dir, __packagename__, 'VERSION')) as vfile:
            version = vfile.readline().strip()
        pkg_data[__packagename__].insert(0, 'VERSION')

    if version is None:
        import versioneer
        version = versioneer.get_version()
        cmdclass = versioneer.get_cmdclass()

    setup(
        name=__packagename__,
        version=version,
        description=__description__,
        long_description=__longdesc__,
        author=__author__,
        author_email=__email__,
        maintainer=__maintainer__,
        maintainer_email=__email__,
        license=__license__,
        url=__url__,
        download_url=DOWNLOAD_URL,
        classifiers=CLASSIFIERS,
        packages=find_packages(exclude=['*.tests']),
        zip_safe=False,
        # Dependencies handling
        setup_requires=SETUP_REQUIRES,
        install_requires=list(set(REQUIRES)),
        dependency_links=LINKS_REQUIRES,
        tests_require=TESTS_REQUIRES,
        extras_require=EXTRA_REQUIRES,
        # Data
        package_data=pkg_data,
        include_package_data=True,
        cmdclass=cmdclass,
    )