Main `ybt` console script entry point - run YABT from command-line.
1321
def main():
    """"""
    conf = init_and_get_conf()
    logger = make_logger(__name__)
    logger.info('YaBT version {}', __version__)
    handlers = {
        'build': YabtCommand(func=cmd_build, requires_project=True),
        'dot': YabtCommand(func=cmd_dot, requires_project=True),
        'test': YabtCommand(func=cmd_test, requires_project=True),
        'tree': YabtCommand(func=cmd_tree, requires_project=True),
        'version': YabtCommand(func=cmd_version, requires_project=False),
        'list-builders': YabtCommand(func=cmd_list, requires_project=False),
    }
    command = handlers[conf.cmd]
    if command.requires_project and not conf.in_yabt_project():
        fatal('Not a YABT project (or any of the parent directories): {}',
              BUILD_PROJ_FILE)
    try:
        command.func(conf)
    except Exception as ex:
        fatal('{}', ex)
649568
def main():
    """"""
    WIDTH, HEIGHT = 120, 60
    TITLE = None

    with tcod.console_init_root(WIDTH, HEIGHT, TITLE, order="F",
                                renderer=tcod.RENDERER_SDL) as console:
        tcod.sys_set_fps(24)
        while True:
            tcod.console_flush()
            for event in tcod.event.wait():
                print(event)
                if event.type == "QUIT":
                    raise SystemExit()
                elif event.type == "MOUSEMOTION":
                    console.ch[:, -1] = 0
                    console.print_(0, HEIGHT - 1, str(event))
                else:
                    console.blit(console, 0, 0, 0, 1, WIDTH, HEIGHT - 2)
                    console.ch[:, -3] = 0
                    console.print_(0, HEIGHT - 3, str(event))
118209
def main(argv=None):
    """"""
    parser = ArgumentParser(prog="pygenstub")
    parser.add_argument("--version", action="version", version="%(prog)s " + __version__)
    parser.add_argument("files", nargs="*", help="generate stubs for given files")
    parser.add_argument(
        "-m",
        "--module",
        action="append",
        metavar="MODULE",
        dest="modules",
        default=[],
        help="generate stubs for given modules",
    )
    parser.add_argument(
        "-o", "--output", metavar="PATH", dest="out_dir", help="change the output directory"
    )
    parser.add_argument(
        "--generic", action="store_true", default=False, help="generate generic stubs"
    )
    parser.add_argument("--debug", action="store_true", help="enable debug messages")

    argv = argv if argv is not None else sys.argv
    arguments = parser.parse_args(argv[1:])

    # set debug mode
    if arguments.debug:
        logging.basicConfig(level=logging.DEBUG)
        _logger.debug("running in debug mode")

    out_dir = arguments.out_dir if arguments.out_dir is not None else ""
    if (out_dir == "") and (len(arguments.modules) > 0):
        print("Output directory must be given when generating stubs for modules.")
        sys.exit(1)

    modules = []
    for path in arguments.files:
        paths = Path(path).glob("**/*.py") if Path(path).is_dir() else [Path(path)]
        for source in paths:
            if str(source).startswith(os.path.pardir):
                source = source.absolute().resolve()
            if (out_dir != "") and source.is_absolute():
                source = source.relative_to(source.root)
            destination = Path(out_dir, source.with_suffix(".pyi"))
            modules.append((source, destination))

    for mod_name in arguments.modules:
        modules.extend(get_pkg_paths(mod_name, out_dir))

    for source, destination in modules:
        _logger.info("generating stub for %s to path %s", source, destination)
        with source.open() as f:
            code = f.read()
        try:
            stub = get_stub(code, generic=arguments.generic)
        except Exception as e:
            print(source, "-", e, file=sys.stderr)
            continue

        if stub != "":
            if not destination.parent.exists():
                destination.parent.mkdir(parents=True)
            with destination.open("w") as f:
                f.write("# " + EDIT_WARNING + "\n\n" + stub)
125283
def _main():
    
    if argv[1:]:
        stdout.write(_CLI_HELP)
        raise SystemExit()
    for line in stdin:
        try:
            message = loads(line)
        except ValueError:
            stdout.write("Not JSON: {}\n\n".format(line.rstrip(b"\n")))
            continue
        if REQUIRED_FIELDS - set(message.keys()):
            stdout.write(
                "Not an Eliot message: {}\n\n".format(line.rstrip(b"\n")))
            continue
        result = pretty_format(message) + "\n"
        if PY2:
            result = result.encode("utf-8")
        stdout.write(result)
115273
def main():
    """"""

    # in contrast to argparse, this works at least under Python < 2.7
    import optparse
    from .utils import import_string

    parser = optparse.OptionParser(usage="Usage: %prog [options] app_module:app_object")
    parser.add_option(
        "-b",
        "--bind",
        dest="address",
        help="The hostname:port the app should listen on.",
    )
    parser.add_option(
        "-d",
        "--debug",
        dest="use_debugger",
        action="store_true",
        default=False,
        help="Use Werkzeug's debugger.",
    )
    parser.add_option(
        "-r",
        "--reload",
        dest="use_reloader",
        action="store_true",
        default=False,
        help="Reload Python process if modules change.",
    )
    options, args = parser.parse_args()

    hostname, port = None, None
    if options.address:
        address = options.address.split(":")
        hostname = address[0]
        if len(address) > 1:
            port = address[1]

    if len(args) != 1:
        sys.stdout.write("No application supplied, or too much. See --help\n")
        sys.exit(1)
    app = import_string(args[0])

    run_simple(
        hostname=(hostname or "127.0.0.1"),
        port=int(port or 5000),
        application=app,
        use_reloader=options.use_reloader,
        use_debugger=options.use_debugger,
    )
1300424
def main():
    
    args = app.parse_args(sys.argv[1:])
    params = args.__dict__
    params.update(**load_config(args.config_file))

    if params['debug']:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig()

    try:
        imhotep = app.gen_imhotep(**params)
    except NoGithubCredentials:
        log.error("You must specify a GitHub username or password.")
        return False
    except NoCommitInfo:
        log.error("You must specify a commit or PR number")
        return False
    except UnknownTools as e:
        log.error("Didn't find any of the specified linters.")
        log.error("Known linters: %s", ', '.join(e.known))
        return False

    imhotep.invoke()
834249
def main():
    
    logging.basicConfig(
        format='[%(asctime)s] %(levelname)s -- %(message)s',
        level=logging.DEBUG)

    parser = argparse.ArgumentParser(description='')
    parser.add_argument('git_url', help='Url of the repo to sync')
    parser.add_argument('branch_name', default='master', help='Branch of repo to sync', nargs='?')
    parser.add_argument('repo_dir', default='.', help='Path to clone repo under', nargs='?')
    args = parser.parse_args()

    for line in GitPuller(
        args.git_url,
        args.branch_name,
        args.repo_dir
    ).pull():
        print(line)
178058
def run_main(args: argparse.Namespace, do_exit=True) -> None:
    
    if args.init:
        generate()
        return None  # exit after generate instead of starting to lint

    handler = CheckHandler(
        file=args.config_file, out_json=args.json, files=args.files)

    for style in get_stylers():
        handler.run_linter(style())

    for linter in get_linters():
        handler.run_linter(linter())

    for security in get_security():
        handler.run_linter(security())

    for tool in get_tools():
        tool = tool()

        # Only run pypi if everything else passed
        if tool.name == "pypi" and handler.status_code != 0:
            continue

        handler.run_linter(tool)

    if do_exit:
        handler.exit()
    return handler.status_code
1287784
def main(argv=None):
  """"""
  args = parse_arguments(sys.argv if argv is None else argv)
  temp_dir = os.path.join(args.output, 'tmp')

  if args.cloud:
    pipeline_name = 'DataflowRunner'
  else:
    pipeline_name = 'DirectRunner'
    # Suppress TF warnings.
    os.environ['TF_CPP_MIN_LOG_LEVEL']='3'

  options = {
      'job_name': args.job_name,
      'temp_location': temp_dir,
      'project': args.project_id,
      'setup_file':
          os.path.abspath(os.path.join(
              os.path.dirname(__file__),
              'setup.py')),
  }
  if args.num_workers:
    options['num_workers'] = args.num_workers
  if args.worker_machine_type:
    options['worker_machine_type'] = args.worker_machine_type

  pipeline_options = beam.pipeline.PipelineOptions(flags=[], **options)

  p = beam.Pipeline(pipeline_name, options=pipeline_options)
  preprocess(pipeline=p, args=args)
  pipeline_result = p.run()

  if not args.async:
    pipeline_result.wait_until_finish()
  if args.async and args.cloud:
    print('View job at https://console.developers.google.com/dataflow/job/%s?project=%s' %
        (pipeline_result.job_id(), args.project_id))
933855
public static void main(String[] args)
            throws YamlConvertException, IllegalDataStructureException, IllegalTestScriptException {
        if (args.length == 0) {
            throw new IllegalArgumentException(MSG_NO_COMMAND_LINE_ARGUMENT);
        }
        Action action = null;
        try {
            action = Action.getEnum(args[0]);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException(String.format(MSG_UNKNOWN_ACTION, args[0]));
        }
        String configFilePath;
        if (args.length <= 1) {
            configFilePath = "sahagin.yml";
        } else {
            configFilePath = args[1];
        }
        File configFile = new File(configFilePath);
        if (!configFile.exists()) {
            throw new IllegalArgumentException(String.format(
                    MSG_CONFIG_NOT_FOUND, configFile.getAbsolutePath()));
        }
        Config config = Config.generateFromYamlConfig(configFile);
        Logging.setLoggerEnabled(config.isOutputLog());
        AcceptableLocales locales = AcceptableLocales.getInstance(config.getUserLocale());
        SysMessages.globalInitialize(locales);

        switch (action) {
        case Report:
            report(config);
            break;
        default:
            throw new RuntimeException("implementation error");
        }
    }
114393
def main(argv, version=DEFAULT_VERSION):
    """"""
    tarball = download_setuptools()
    _install(tarball, _build_install_args(argv))
1068129
def main():
    
    parser = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument("path", nargs="+", help="File or directory path")
    parser.add_argument("--exclude", nargs="+", help="Exclude glob patterns")
    parser.add_argument(
        "--no-recursive",
        dest="recursive",
        action="store_false",
        help="Search directories recursively",
    )
    parser.add_argument(
        "--ignore-invalid", action="store_true", help="Ignore invalid paths"
    )
    parser.add_argument(
        "--pycharm", action="store_true", help="Enable PyCharm integration"
    )
    parser.add_argument(
        "--diff",
        dest="show_diff",
        action="store_true",
        help="Show diff and do not modify any files",
    )
    parser.add_argument(
        "--dry-run", action="store_true", help="Process files but do not write results"
    )
    parser.add_argument("--debug", action="store_true", help="Debug level logging")

    args = parser.parse_args()
    d1_common.util.log_setup(args.debug)

    repo_path = d1_dev.util.find_repo_root_by_path(__file__)
    repo = git.Repo(repo_path)

    specified_file_path_list = get_specified_file_path_list(args)
    tracked_path_list = list(d1_dev.util.get_tracked_files(repo))
    format_path_list = sorted(
        set(specified_file_path_list).intersection(tracked_path_list)
    )

    progress_logger.start_task_type("Format modules", len(format_path_list))

    for i, format_path in enumerate(format_path_list):
        progress_logger.start_task("Format modules", i)
        format_all_docstr(args, format_path)

    progress_logger.end_task_type("Format modules")
248271
def main():
    
    # Define Parser object and add to jobTree
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter)

    # Generate subparsers
    subparsers = parser.add_subparsers(dest='command')
    subparsers.add_parser('generate-config',
                          help='Generates an editable config in the current working directory.')
    subparsers.add_parser('generate-manifest',
                          help='Generates an editable manifest in the current working directory.')
    subparsers.add_parser('generate',
                          help='Generates a config and manifest in the current working directory.')

    # Run subparser
    parser_run = subparsers.add_parser('run', help='Runs the GATK germline pipeline')
    parser_run.add_argument('--config',
                            required=True,
                            type=str,
                            help='Path to the (filled in) config file, generated with '
                                 '"generate-config".')
    parser_run.add_argument('--manifest',
                            type=str,
                            help='Path to the (filled in) manifest file, generated with '
                                 '"generate-manifest".\nDefault value: "%(default)s".')
    parser_run.add_argument('--sample',
                            default=None,
                            nargs=2,
                            type=str,
                            help='Input sample identifier and BAM file URL or local path')
    parser_run.add_argument('--output-dir',
                            default=None,
                            help='Path/URL to output directory')
    parser_run.add_argument('-s', '--suffix',
                            default=None,
                            help='Additional suffix to add to the names of the output files')
    parser_run.add_argument('--preprocess-only',
                            action='store_true',
                            help='Only runs preprocessing steps')

    Job.Runner.addToilOptions(parser_run)
    options = parser.parse_args()

    cwd = os.getcwd()
    if options.command == 'generate-config' or options.command == 'generate':
        generate_file(os.path.join(cwd, 'config-toil-germline.yaml'), generate_config)
    if options.command == 'generate-manifest' or options.command == 'generate':
        generate_file(os.path.join(cwd, 'manifest-toil-germline.tsv'), generate_manifest)
    elif options.command == 'run':
        # Program checks
        for program in ['curl', 'docker']:
            require(next(which(program)),
                    program + ' must be installed on every node.'.format(program))

        require(os.path.exists(options.config), '{} not found. Please run "generate-config"'.format(options.config))

        # Read sample manifest
        samples = []
        if options.manifest:
            samples.extend(parse_manifest(options.manifest))

        # Add BAM sample from command line
        if options.sample:
            uuid, url = options.sample
            # samples tuple: (uuid, url, paired_url, rg_line)
            # BAM samples should not have as paired URL or read group line
            samples.append(GermlineSample(uuid, url, None, None))

        require(len(samples) > 0,
                'No samples were detected in the manifest or on the command line')

        # Parse inputs
        inputs = {x.replace('-', '_'): y for x, y in
                  yaml.load(open(options.config).read()).iteritems()}

        required_fields = {'genome_fasta',
                           'output_dir',
                           'run_bwa',
                           'sorted',
                           'snp_filter_annotations',
                           'indel_filter_annotations',
                           'preprocess',
                           'preprocess_only',
                           'run_vqsr',
                           'joint_genotype',
                           'run_oncotator',
                           'cores',
                           'file_size',
                           'xmx',
                           'suffix'}

        input_fields = set(inputs.keys())
        require(input_fields > required_fields,
                'Missing config parameters:\n{}'.format(', '.join(required_fields - input_fields)))

        if inputs['output_dir'] is None:
            inputs['output_dir'] = options.output_dir

        require(inputs['output_dir'] is not None,
                'Missing output directory PATH/URL')

        if inputs['suffix'] is None:
            inputs['suffix'] = options.suffix if options.suffix else ''

        if inputs['preprocess_only'] is None:
            inputs['preprocess_only'] = options.preprocess_only

        if inputs['run_vqsr']:
            # Check that essential VQSR parameters are present
            vqsr_fields = {'g1k_snp', 'mills', 'dbsnp', 'hapmap', 'omni'}
            require(input_fields > vqsr_fields,
                    'Missing parameters for VQSR:\n{}'.format(', '.join(vqsr_fields - input_fields)))

        # Check that hard filtering parameters are present. If only running preprocessing steps, then we do
        # not need filtering information.
        elif not inputs['preprocess_only']:
            hard_filter_fields = {'snp_filter_name', 'snp_filter_expression',
                                  'indel_filter_name', 'indel_filter_expression'}
            require(input_fields > hard_filter_fields,
                    'Missing parameters for hard filtering:\n{}'.format(', '.join(hard_filter_fields - input_fields)))

            # Check for falsey hard filtering parameters
            for hard_filter_field in hard_filter_fields:
                require(inputs[hard_filter_field], 'Missing %s value for hard filtering, '
                                                   'got %s.' % (hard_filter_field, inputs[hard_filter_field]))

        # Set resource parameters
        inputs['xmx'] = human2bytes(inputs['xmx'])
        inputs['file_size'] = human2bytes(inputs['file_size'])
        inputs['cores'] = int(inputs['cores'])

        inputs['annotations'] = set(inputs['snp_filter_annotations'] + inputs['indel_filter_annotations'])

        # HaplotypeCaller test data for testing
        inputs['hc_output'] = inputs.get('hc_output', None)

        # It is a toil-scripts convention to store input parameters in a Namespace object
        config = argparse.Namespace(**inputs)

        root = Job.wrapJobFn(run_gatk_germline_pipeline, samples, config)
        Job.Runner.startToil(root, options)
341946
def init(confdir="/etc/cslbot"):
    
    multiprocessing.set_start_method('spawn')

    parser = argparse.ArgumentParser()
    parser.add_argument('-d', '--debug', help='Enable debug logging.', action='store_true')
    parser.add_argument('--validate', help='Initialize the db and perform other sanity checks.', action='store_true')
    args = parser.parse_args()
    loglevel = logging.DEBUG if args.debug else logging.INFO
    logging.basicConfig(level=loglevel, format="%(asctime)s %(levelname)s:%(module)s:%(message)s")
    # We don't need a bunch of output from the requests module.
    logging.getLogger("requests").setLevel(logging.WARNING)

    cslbot = IrcBot(confdir)

    if args.validate:
        cslbot.shutdown_mp()
        print("Everything is ready to go!")
        return

    try:
        cslbot.start()
    except KeyboardInterrupt:
        # KeyboardInterrupt means someone tried to ^C, so shut down the bot
        cslbot.disconnect('Bot received a Ctrl-C')
        cslbot.shutdown_mp()
        sys.exit(0)
    except Exception as ex:
        cslbot.shutdown_mp(False)
        logging.error("The bot died! %s", ex)
        output = "".join(traceback.format_exc()).strip()
        for line in output.split('\n'):
            logging.error(line)
        sys.exit(1)
964833
def main(ctx, config, debug):  # pragma: no cover
    
    ctx.obj = {}
    ctx.obj['args'] = {}
    ctx.obj['args']['debug'] = debug
    ctx.obj['args']['config'] = config
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)
1256536
def main():
    """"""
    if len(argv) < 2:
        targetfile = 'target.y'
    else:
        targetfile = argv[1]
    print 'Parsing ruleset: ' + targetfile,
    flex_a = Flexparser()
    mma = flex_a.yyparse(targetfile)
    print 'OK'
    print 'Perform minimization on initial automaton:',
    mma.minimize()
    print 'OK'
    print 'Perform StateRemoval on minimal automaton:',
    state_removal = StateRemoval(mma)
    mma_regex = state_removal.get_regex()
    print mma_regex