ben-sh entry point
194827
def main(argv=None):
    """"""
    arguments = cli_common(__doc__, argv=argv)
    campaign_file = arguments['CAMPAIGN_FILE']
    if arguments['-g']:
        if osp.exists(campaign_file):
            raise Exception('Campaign file already exists')
        with open(campaign_file, 'w') as ostr:
            Generator().write(ostr)
    else:
        node = arguments.get('-n')
        output_dir = arguments.get('--output-dir')
        exclude_nodes = arguments.get('--exclude-nodes')
        srun_tag = arguments.get('--srun')
        driver = CampaignDriver(
            campaign_file,
            node=node,
            output_dir=output_dir,
            srun=srun_tag,
            exclude_nodes=exclude_nodes,
        )
        driver()
        if argv is not None:
            return driver
        campaign_fd = int(arguments.get('--campaign-path-fd') or 1)
        message = (osp.abspath(driver.campaign_path) + '\n').encode()
        os.write(campaign_fd, message)
374199
def main():
    
    common.setup_main()
    config = common.ConfigData()
    dist_folder = 'dist'

    if os.path.isdir(dist_folder):
        shutil.rmtree(dist_folder)
    args = [
        '{}'.format(config.python),
        'setup.py',
        'sdist',
    ]
    if config.setup_quiet:
        args.extend([
            '--quiet',
        ])
    common.check_call_no_output(args)
    files = list(os.listdir(dist_folder))
    assert len(files) == 1, "too many files in {}".format(dist_folder)
    new_file = os.path.join(dist_folder, files[0])
    args = []
    if config.use_sudo:
        args.extend([
            'sudo',
            '-H',
        ])
    args.extend([
        '{}'.format(config.pip),
        'install',
        '--quiet',
        '--upgrade',
        new_file,
    ])
    if config.pip_quiet:
        args.extend([
            '--quiet',
        ])
    if config.install_in_user_folder:
        args.extend([
            '--user',
        ])
    common.check_call_no_output(args)
586078
def main(input_bed, output_file, output_features=False, genome=None,
         only_canonical=False, short=False, extended=False, high_confidence=False,
         ambiguities_method=False, coding_only=False, collapse_exons=False, work_dir=False, is_debug=False):
    
    logger.init(is_debug_=is_debug)

    if not genome:
        raise click.BadParameter('Error: please, specify genome build name with -g (e.g. `-g hg19`)', param='genome')

    if short:
        if extended:        raise click.BadParameter('--short and --extended can\'t be set both', param='extended')
        if output_features: raise click.BadParameter('--short and --output-features can\'t be set both', param='output_features')
    elif output_features or extended:
        extended = True
        short    = False

    if not verify_file(input_bed):
        click.BadParameter(f'Usage: {__file__} Input_BED_file -g hg19 -o Annotated_BED_file [options]', param='input_bed')
    input_bed = verify_file(input_bed, is_critical=True, description=f'Input BED file for {__file__}')

    if work_dir:
        work_dir = join(adjust_path(work_dir), os.path.splitext(basename(input_bed))[0])
        safe_mkdir(work_dir)
        info(f'Created work directory {work_dir}')
    else:
        work_dir = mkdtemp('bed_annotate')
        debug('Created temporary work directory {work_dir}')

    input_bed = clean_bed(input_bed, work_dir)
    input_bed = verify_bed(input_bed, is_critical=True, description=f'Input BED file for {__file__} after cleaning')

    output_file = adjust_path(output_file)

    output_file = annotate(
        input_bed, output_file, work_dir, genome=genome,
        only_canonical=only_canonical, short=short, extended=extended,
        high_confidence=high_confidence, collapse_exons=collapse_exons,
        output_features=output_features,
        ambiguities_method=ambiguities_method, coding_only=coding_only,
        is_debug=is_debug)

    if not work_dir:
        debug(f'Removing work directory {work_dir}')
        shutil.rmtree(work_dir)

    info(f'Done, saved to {output_file}')
253340
function sh(cmd, env = {}) {
  let args = cmd.split(/\s+/);
  console.log(args.join(" "));
  let exe = args.shift();
  // Use this node if node is specified.
  if (exe === "node") exe = process.execPath;
  let r = spawnSync(exe, args, {
    stdio: 'inherit',
    env: { ...process.env, ...env }
  });
  if (r.error) throw r.error;
  if (r.status) {
    console.log("Error", args[0]);
    process.exit(r.status);
  }
}
298724
def main():
    
    arg_parse = setup_argparse()
    args = arg_parse.parse_args()

    if not args.quiet:
        print('GNS3 Topology Converter')

    if args.debug:
        logging_level = logging.DEBUG
    else:
        logging_level = logging.WARNING

    logging.basicConfig(level=logging_level,
                        format=LOG_MSG_FMT, datefmt=LOG_DATE_FMT)

    logging.getLogger(__name__)

    # Add the main topology to the list of files to convert
    if args.topology == 'topology.net':
        args.topology = os.path.join(os.getcwd(), 'topology.net')

    topology_files = [{'file': topology_abspath(args.topology),
                       'snapshot': False}]

    # Add any snapshot topologies to be converted
    topology_files.extend(get_snapshots(args.topology))

    topology_name = name(args.topology, args.name)

    # Do the conversion
    for topology in topology_files:
        do_conversion(topology, topology_name, args.output, args.debug)
559891
function main(args, callback) {

  var opts = {};
  Object.keys(options).forEach(key => {
    var opt = options[key];
    if (opt.aliases)
      (opts.alias || (opts.alias = {}))[key] = opt.aliases;
    if (opt.default !== undefined)
      (opts.default || (opts.default = {}))[key] = opt.default;
    if (opt.type === "string")
      (opts.string || (opts.string = [])).push(key);
    else if (opt.type === "boolean")
      (opts.boolean || (opts.boolean = [])).push(key);
  });

  var argv = minimist(args, opts);

  var files = argv._;
  var configFile;

  // prefer specified config file
  if (argv.config)
    configFile = argv.config;

  // otherwise check entry file directory
  else if (files.length)
    if (!fs.existsSync(configFile = path.join(path.dirname(files[0]), "asconfig.json"))) {
      configFile = undefined;
      if (!fs.existsSync(configFile = path.join(path.dirname(files[0]), "tsconfig.json")))
        configFile = undefined;
    }

  // load config file
  if (configFile) {
    try {
      var config = JSON.parse(fs.readFileSync(configFile, "utf8"));
      if (config.assembly)
        config = config.assembly;
      if (config.entryFile) {
        if (!files.length) // prefer command line
          files = [ config.entryFile ];
        delete config.entryFile;
      }
      Object.keys(config).forEach(key => {
        if (options[key] && key !== "config") // prefer command line
          if (options[key].isPath)
            argv[key] = path.isAbsolute(config[key]) ? config[key] : path.join(path.dirname(configFile), config[key]);
          else
            argv[key] = config[key];
      });
    } catch (e) {
      if (!argv.quiet)
        process.stderr.write(chalk.red("\nFailed to load config file: " + e.message + "\n"));
      return callback(EFAILURE);
    }
  }

  // print usage information if requested or no input files have been provided
  if (argv.help || files.length !== 1) {
    (argv.help ? process.stdout : process.stderr).write([
      "Version " + pkg.version + (isDev ? "-dev" + (isOut ? " (out)" : "") : ""),
      "Syntax: "+ chalk.reset.cyan.bold("asc") + " [options] entryFile",
      "",
      chalk.reset.white.bold("Options:"),
      ""
    ].concat(Object.keys(options).map(key => {
      var opt = options[key];
      var cmd = " --" + key;
      if (opt.aliases && opt.aliases.length && opt.aliases[0].length === 1)
        cmd += ", -" + opt.aliases[0];
      while (cmd.length < 18)
        cmd += " ";
      return cmd + "  " + opt.desc.replace(/\n/g, "\n                    ") + "\n";
    })).join("\n").replace(/\[default\]/g, chalk.gray("[default]")));
    return callback(argv.help ? ESUCCESS : EUSAGE);
  }

  // compile to a Binaryen module
  var wasmModule = Compiler.compileFile(files[0], {
    silent: !!argv.quiet,
    target: argv.target,
    noTreeShaking: !!argv.noTreeShaking,
    noImplicitConversion: !!argv.noImplicitConversion,
    noRuntime: !!argv.noRuntime,
    exportRuntime: Array.isArray(argv.exportRuntime) ? argv.exportRuntime
                 : typeof argv.exportRuntime === "string" ? [ argv.exportRuntime ]
                 : undefined
  });

  // bail out if that didn't work
  if (!wasmModule)
    return callback(EFAILURE);

  // from this point on the module must be disposed (finish does this implicitly)

  // optimize the Binaryen module if requested
  if (argv.optimize)
    wasmModule.optimize();

  // validate the Binaryen module if requested
  if (argv.validate) {
    var result = wasmModule.validate(); // FIXME: this always prints to console on error
    if (!result) {
      if (!argv.quiet)
        process.stderr.write(chalk.red("\nValidation failed. See above for details.\n"));
      return finish(Error("validation failed"));
    }
  }

  // default to text format if --outFile references a .wast, .wat or .js and --textFormat isn't specified
  if (argv.outFile && !argv.textFormat) {
    if (/\.wast$/.test(argv.outFile))
      argv.textFormat = "sexpr";
    else if (/\.wat$/.test(argv.outFile))
      argv.textFormat = "linear";
    else if (/\.js$/.test(argv.outfile))
      argv.textFormat = "asmjs";
  }

  // emit to --outFile if specified, otherwise print to stdout
  var output = argv.outFile ? fs.createWriteStream(argv.outFile) : process.stdout;

  // emit text format (textFormat is requested but no textFile has been specified) + asm.js (if applicable)
  if ((argv.textFormat !== undefined || output.isTTY) && !argv.textFile) {
    if (argv.textFormat === "asmjs" || /\.js$/.test(argv.outFile))
      writeAsmjs(wasmModule, output, finish);
    else
      writeText(wasmModule, argv.textFormat, output, maybeWriteAsmjs);

  // emit a binary + text format (if specified) + asm.js (if specified)
  } else
    writeBinary(wasmModule, output, maybeWriteText);

  function maybeWriteText(err) {
    if (err || !argv.textFile)
      return finish(err);
    if (argv.textFormat === "asmjs" || (!argv.textFormat && /\.js$/.test(argv.textFile)))
      writeAsmjs(wasmModule, fs.createWriteStream(argv.textFile), finish);
    else
      writeText(wasmModule, argv.textFormat || /\.wat$/.test(argv.textFile) && "linear" || "sexpr", fs.createWriteStream(argv.textFile), maybeWriteAsmjs);
  }

  function maybeWriteAsmjs(err) {
    if (err || !argv.asmjsFile)
      return finish(err);
    writeAsmjs(wasmModule, fs.createWriteStream(argv.asmjsFile), finish);
  }

  function finish(err) {
    wasmModule.dispose();
    return callback(err ? EFAILURE : ESUCCESS);
  }
}
576597
def init():
    

    mochapyfile = os.path.join(os.path.join(CWD, "brew.py"))

    header("Initializing Mocha ...")
    if os.path.isfile(mochapyfile):
        print("WARNING: It seems like Mocha is already setup!")
        print("*" * 80)
    else:
        print("")
        print("Copying files to the current directory...")
        copy_resource_dir(SKELETON_DIR + "/create/", CWD)
        print("")

        _npm_install_static()
        print("")
        print("----- Your Mocha is ready! ----")
        print("")
        print("> What's next?")
        print("- Edit the config [ application/config.py ] ")
        print("- If necessary setup your model database [ mocha :initdb ]")
        print("- Launch app on development mode, run [ mocha :serve ]")
        print("")
        print("*" * 80)
899836
def main():
    
    args = parse_args()
    utils.set_device(args.cuda, args.local_rank)
    utils.init_distributed(args.cuda)
    setup_logging()

    if args.env:
        utils.log_env_info()

    logging.info(f'Run arguments: {args}')

    if not args.cuda and torch.cuda.is_available():
        warnings.warn('cuda is available but not enabled')
    if not args.cudnn:
        torch.backends.cudnn.enabled = False

    # load checkpoint and deserialize to CPU (to save GPU memory)
    checkpoint = torch.load(args.model, map_location={'cuda:0': 'cpu'})

    # build GNMT model
    tokenizer = Tokenizer()
    tokenizer.set_state(checkpoint['tokenizer'])
    vocab_size = tokenizer.vocab_size
    model_config = checkpoint['model_config']
    model_config['batch_first'] = args.batch_first
    model = GNMT(vocab_size=vocab_size, **model_config)
    model.load_state_dict(checkpoint['state_dict'])

    for (math, batch_size, beam_size) in product(args.math, args.batch_size,
                                                 args.beam_size):
        logging.info(f'math: {math}, batch size: {batch_size}, '
                     f'beam size: {beam_size}')
        if math == 'fp32':
            dtype = torch.FloatTensor
        if math == 'fp16':
            dtype = torch.HalfTensor
        model.type(dtype)

        if args.cuda:
            model = model.cuda()
        model.eval()

        # construct the dataset
        test_data = TextDataset(src_fname=args.input,
                                tokenizer=tokenizer,
                                sort=args.sort)

        # build the data loader
        test_loader = test_data.get_loader(batch_size=batch_size,
                                           batch_first=args.batch_first,
                                           shuffle=False,
                                           pad=True,
                                           num_workers=0)

        # build the translator object
        translator = Translator(model=model,
                                tokenizer=tokenizer,
                                loader=test_loader,
                                beam_size=beam_size,
                                max_seq_len=args.max_seq_len,
                                len_norm_factor=args.len_norm_factor,
                                len_norm_const=args.len_norm_const,
                                cov_penalty_factor=args.cov_penalty_factor,
                                cuda=args.cuda,
                                print_freq=args.print_freq,
                                dataset_dir=args.dataset_dir)

        # execute the inference
        translator.run(calc_bleu=args.bleu, eval_path=args.output,
                       reference_path=args.reference, summary=True)
1276506
async function start () {
  let exitCode = 0
  const port = process.env.PORT || 3000
  console.log(chalk`{magenta creating app bundle}`)

  /**
   * Creating rollup bundle by bundling `test/qunit/index.js` file.
   */
  const bundle = await rollup.rollup({
    input: path.join(__dirname, '../test', 'qunit', 'index'),
    plugins: require('../rollupPlugins')
  })

  const { code } = await bundle.generate({
    file: path.join(__dirname, '../tmp', 'qunit.js'),
    format: 'umd',
    name: 'indicativeSpec'
  })

  const server = await sauceLabs.serve(qUnitTemplate(code), port)
  console.log(chalk`started app server on {green http://localhost:${port}}`)

  /**
   * Starting the HTTP server. If `SAUCE_USERNAME` and `SAUCE_ACCESS_KEY`
   * env variables exists, we will run tests on sauce, otherwise
   * we will run them on user machine.
   */
  if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
    console.log(chalk`{yellow pass SAUCE_USERNAME & SAUCE_ACCESS_KEY to run tests on saucelabs}`)
    opn(`http://localhost:${port}`)
    return
  }

  const ngrok = require('ngrok')
  try {
    /**
     * Ngrok url
     */
    const publicUrl = await sauceLabs.getPublicUrl(port)
    console.log(chalk`started ngrok tunnel on {green ${publicUrl}}`)

    /**
     * Creating jobs with sauce labs
     */
    const jobs = await sauceLabs.createTestsJob(browsers, publicUrl)
    console.log(chalk`created {green ${jobs.length} jobs}`)

    /**
     * Monitoring jobs for results
     */
    console.log(chalk`{magenta monitoring jobs}`)
    const results = await sauceLabs.getJobsResult(jobs)

    /**
     * Got some results
     */
    results.forEach((result) => {
      console.log('')
      console.log(chalk`{bold ${result.platform.join(' ')}}`)
      console.log(chalk`  {green Passed ${result.result.passed}}`)
      console.log(chalk`  {red Failed ${result.result.failed}}`)
      console.log(`  Total ${result.result.total}`)
    })

    /**
     * Creating a new build to be annotated
     */
    const buildId = `build-${new Date().getTime()}`

    console.log('annotating jobs result')
    for (let result of results) {
      await sauceLabs.annotateJob(result.job_id, buildId, result.result.failed === 0)
    }
    console.log(chalk`{green done}`)
  } catch (error) {
    console.log(chalk`  {red Reaceived error}`)
    console.log(error)
    exitCode = 1
  }

  /**
   * Cleanup
   */
  ngrok.kill()
  server.close()
  process.exit(exitCode)
}
13153
def main():
    
    mkdir_p('/tmp/test/test')
    source('/root/.bash_profile')
    yum_install(['httpd', 'git'])
    yum_install(['httpd', 'git'], dest_dir='/tmp/test/test', downloadonly=True)
    sed('/Users/yennaco/Downloads/homer_testing/network', '^HOSTNAME.*', 'HOSTNAME=foo.joe')
    test_script = '/Users/yennaco/Downloads/homer/script.sh'
    results = run_command([test_script], timeout_sec=1000)
    print('Script {s} produced exit code [{c}] and output:\n{o}'.format(
        s=test_script, c=results['code'], o=results['output']))
165371
def main():
    ''''''
    args = docopt(__doc__, version=__version__)

    if 'bam_coverage' in args:
        bam_coverage(args['<reference>'],
                     args['<alignments>'],
                     int(args['<minmatch>']),
                     min_mapq=int(args['--mapq']),
                     min_len=float(args['--minlen']))
1287588
def main():
    """"""
    import colorama
    import argparse
    import logging
    import sys
    import os

    parser = argparse.ArgumentParser(prog="gulpless",
                                     description="Simple build system.")
    parser.add_argument("-v", "--version",
                        action="version",
                        version="%(prog)s 0.7.6")
    parser.add_argument("-d", "--directory",
                        action="store",
                        default=os.getcwd(),
                        help="Look for `build.py` in this folder (defaults to "
                             "the current directory)")
    parser.add_argument("mode",
                        action="store",
                        choices=["build", "interactive"],
                        default="interactive",
                        metavar="mode",
                        nargs="?",
                        help="If `interactive` (the default), will wait for "
                             "filesystem events and attempt to keep the input "
                             "and output folders in sync. If `build`, it will "
                             "attempt to build all updated files, then exit.")

    args = parser.parse_args()
    os.chdir(args.directory)
    sys.path.append(os.getcwd())

    if os.environ.get("TERM") == "cygwin":
        # colorama doesn't play well with git bash
        del os.environ["TERM"]
        colorama.init()
        os.environ["TERM"] = "cygwin"
    else:
        colorama.init()

    try:
        old, sys.dont_write_bytecode = sys.dont_write_bytecode, True
        import build
    except ImportError:
        sys.exit("No `build.py` found in current folder.")
    finally:
        sys.dont_write_bytecode = old

    try:
        logging.basicConfig(level=build.LOGGING,
                            format="%(message)s")
    except AttributeError:
        logging.basicConfig(level=logging.INFO,
                            format="%(message)s")

    reactor = Reactor(build.SRC, build.DEST)
    for handler in build.HANDLERS:
        reactor.add_handler(handler)
    reactor.run(args.mode == "build")
114393
def main(argv, version=DEFAULT_VERSION):
    """"""
    tarball = download_setuptools()
    _install(tarball, _build_install_args(argv))
1102679
def main():
    '''
    
    '''
    args = CLI.parse_args(__doc__)

    if args['--verbose']:
        requests_log = logging.getLogger("requests.packages.urllib3")
        requests_log.setLevel(logging.DEBUG)
        logging.basicConfig(level=logging.DEBUG)

    if not args['-k']:
        print("No API key given. Please create an API key on <https://octopart.com/api/dashboard>")
        return ReturnValues.NO_APIKEY

    if args['-t'] == 'octopart':
        engine = PyPartsOctopart(args['-k'], verbose=args['--verbose'])
    elif args['-t'] == 'parts.io':
        engine = PyPartsPartsIO(args['-k'], verbose=args['--verbose'])
    else:
        engine = PyPartsBase(args['-k'], verbose=args['--verbose'])

    try:
        if 'lookup' in args or 'search' in args:
            return engine.part_search(args['<part>'])
        elif 'specs' in args:
            return engine.part_specs(args['<part>'])
        elif 'datasheet' in args:
            if args['<action>'] == 'open':
                if args['--output']:
                    return engine.part_datasheet(args['<part>'], command=args['--command'], path=args['--output'])
                else:
                    return engine.part_datasheet(args['<part>'], command=args['--command'])
            elif args['<action>'] == 'save':
                return engine.part_datasheet(args['<part>'], path=args['--output'])
        elif 'show' in args:
            return engine.part_show(args['<part>'], printout=args['--print'])
    except OctopartException as err:
        print(err)
        return ReturnValues.RUNTIME_ERROR
1110891
def main():
    
    print('\n\n /------- AIKIF Installation --------\\')
    print(' |  s. show current setup            |')
    print(' |  f. setup folder structures       |')
    print(' |  c. create sample data            |')
    # not yet - wait for beta release print(' w. wipe data and install everything from scratch')
    print(' |  q. quit                          |')
    print(' \\-----------------------------------/')
    cmd = input('?')
    if cmd == 's':
        show_setup()   
    elif cmd == 'f':
        setup_folders()
    elif cmd == 'c':
        create_sample_data()   
    #elif cmd == 'w':
    #    wipe_and_rebuild_all()
    elif cmd == 'q':
        exit(0)
    main()
302118
def entry_point():
    
    try:
        main("omego", items=[
            (InstallCommand.NAME, InstallCommand),
            (UpgradeCommand.NAME, UpgradeCommand),
            (ConvertCommand.NAME, ConvertCommand),
            (DownloadCommand.NAME, DownloadCommand),
            (DbCommand.NAME, DbCommand),
            (Version.NAME, Version)])
    except Stop, stop:
        if stop.rc != 0:
            print "ERROR:", stop
        else:
            print stop
        sys.exit(stop.rc)
573289
def main():
    """"""
    args = parser.parse_args()
    args_dict = vars(args)
    root_dir = args_dict['root'] if 'root' in args else None

    # If a root directory is specified, get the absolute path and
    # check if it exists. Abort if it doesn't exist!
    if root_dir:
        root_dir = os.path.abspath(root_dir)
        if not os.path.exists(root_dir):
            print("The specified directory doesn't exist!")
            sys.exit(1)
    # Default to home directory if no root is specified
    else:
        root_dir = os.path.expanduser('~')

    if args.stopdaemon:
        print_command_factory('STOPDAEMON')(vars(args), root_dir)
    elif args.nodaemon:
        daemon_factory(root_dir)()
    elif args.daemon:
        config_dir = os.path.join(root_dir, '.config/pueue')
        os.makedirs(config_dir, exist_ok=True)
        daemon = Daemonize(app='pueue', pid=os.path.join(config_dir, 'pueue.pid'),
                           action=daemon_factory(root_dir), chdir=root_dir)
        daemon.start()
    elif hasattr(args, 'func'):
        try:
            args.func(args_dict, root_dir)
        except EOFError:
            print('Apparently the daemon just died. Sorry for that :/')
    else:
        print('Invalid Command. Please check -h')