Run a prompt-toolkit based REPL
548209
def run(q_prompt=False):
    """"""
    lines, columns = console_size()
    q(r'\c %d %d' % (lines, columns))
    if len(sys.argv) > 1:
        try:
            q(r'\l %s' % sys.argv[1])
        except kerr as e:
            print(e)
            raise SystemExit(1)
        else:
            del sys.argv[1]
    if q_prompt:
        q()
    ptp.run()
738589
def main(argv=None):
    """"""
    if argv is None:
        argv = sys.argv[1:]
    usage = '\n\n\n'.join(__doc__.split('\n\n\n')[1:])
    version = 'Gitpress ' + __version__

    # Parse options
    args = docopt(usage, argv=argv, version=version)

    # Execute command
    try:
        return execute(args)
    except RepositoryNotFoundError as ex:
        error('No Gitpress repository found at', ex.directory)
266465
def main(argv=None):
    """"""
    arguments = cli_common(__doc__, argv=argv)
    plugin = 'benchmark' if arguments['benchmark'] else None

    if arguments['-g']:
        template.generate_config(plugin, arguments['<FILE>'])
    else:
        with open(arguments['<FILE>']) as istr:
            context = json.load(istr)
        kwargs = dict(no_input=True, extra_context=context)
        if arguments['--output-dir']:
            kwargs.update(output_dir=arguments['--output-dir'])
        if arguments['--interactive']:
            kwargs.update(no_input=False)
        logging.info(
            'generating template in directory ' + kwargs.get('output_dir', os.getcwd())
        )
        template.generate_template(plugin, **kwargs)
844380
def cmd_repl():
    
    import code
    import rlcompleter  # noqa
    import readline
    import sys

    readline.parse_and_bind("tab: complete")
    shell = code.InteractiveConsole({
        "rocket": rocket,
    })
    shell.interact(banner="%s %s, Python %s on %s" %
                          (APP_NAME, __version__, sys.version, sys.platform))
1294646
function startRepl() {
  var repl = require('repl');

  var gcliEval = function(command, scope, file, callback) {
    // Why does node wrap the command in '(...)\n'?
    command = command.replace(/^\((.*)\n\)$/, function(all, part) {
      return part;
    });

    if (command.length !== 0) {
      requisition.updateExec(command)
                 .then(logResults)
                 .then(function() { callback(); })
                 .catch(function(ex) { util.errorHandler(ex); callback(); });
    }
  };

  console.log('This is also a limited GCLI REPL. ' +
              'Type \'help\' for a list of commands, CTRL+C 3 times to exit:');
  repl.start(': ', process, gcliEval, false, true);
}
1373780
def main():
    """"""

    # Create command line parser.
    parser = argparse.ArgumentParser()

    # Adding command line arguments.
    parser.add_argument("username", help="Github Username", default=None)

    parser.add_argument(
        "--deep_dive",
        help=" ".join(
            [
                "If added considers repositories starred by users",
                "you follow along with repositories you have",
                "starred. Is significantly slower.",
            ]
        ),
        action="store_true",
        default=False,
    )

    # Parse command line arguments.
    arguments = parser.parse_args()

    if arguments.username is None:
        parser.print_help()
        return

    print("")
    print(
        crayons.white(
            "Authentication (with password) have higher rate limits."
        )
    )
    print(
        crayons.white(
            "Skipping password might cause failure due to rate limit."
        )
    )
    print("")

    password = getpass.getpass(
        crayons.blue(
            "Enter password (to skip press enter without entering anything): ",
            bold=True,
        )
    )

    try:
        gs = GitSuggest(
            username=arguments.username,
            password=password,
            token=None,
            deep_dive=arguments.deep_dive,
        )
    except BadCredentialsException:
        print("")
        print(
            crayons.red(
                "Incorrect password provided, to skip password enter nothing.",
                bold=True,
            )
        )
        exit()
    except TwoFactorException:
        print("")
        print(
            crayons.red(
                "\n".join(
                    [
                        "You have 2FA set up, please enter a personal access token.",
                        "You can generate one on https://github.com/settings/tokens",
                    ]
                ),
                bold=True,
            )
        )
        exit()

    print("")
    print(crayons.green("Suggestions generated!"))

    file_name = "/tmp/gitresults.html"
    repos = list(gs.get_suggested_repositories())

    r2h = ReposToHTML(arguments.username, repos)
    r2h.to_html(file_name)

    webbrowser.open_new("file://" + file_name)
486453
def main(raw_args=None):
    """"""
    parser = argparse.ArgumentParser(
        description="poor man's integration testing")
    parser.add_argument(
        'cmds', metavar='cmd', default=['test'], nargs='*',
        help='Run command(s) defined in the configuration file. Each command '
             'is run on each package before proceeding with the next command. '
             '(default: "test")')
    parser.add_argument(
        '-c', '--config', dest='file', type=argparse.FileType('r'),
        default='toll.ini',
        help='ini-style file to read the configuration from')
    parser.add_argument(
        '--start-at', dest='start_at', type=str, default='',
        help='Skip over the packages in the config file listed before this'
             ' one. (It does a substring match to find the first package.)')

    args = parser.parse_args(raw_args)
    config_file = config.parsed_file(args.file)
    commands = config.commands(config_file, args.cmds)
    packages = config.packages(config_file)
    runner = Runner(commands, packages, start_at=args.start_at)
    return runner()
305983
def example_repl(self, text, example, start_index, continue_flag):
        
        if start_index:
            start_index = start_index + 1
            cmd = ' '.join(text.split()[:start_index])
            example_cli = CommandLineInterface(
                application=self.create_application(
                    full_layout=False),
                eventloop=create_eventloop())
            example_cli.buffers['example_line'].reset(
                initial_document=Document(u'{}\n'.format(
                    add_new_lines(example)))
            )
            while start_index < len(text.split()):
                if self.default_command:
                    cmd = cmd.replace(self.default_command + ' ', '')
                example_cli.buffers[DEFAULT_BUFFER].reset(
                    initial_document=Document(
                        u'{}'.format(cmd),
                        cursor_position=len(cmd)))
                example_cli.request_redraw()
                answer = example_cli.run()
                if not answer:
                    return "", True
                answer = answer.text
                if answer.strip('\n') == cmd.strip('\n'):
                    continue
                else:
                    if len(answer.split()) > 1:
                        start_index += 1
                        cmd += " " + answer.split()[-1] + " " +\
                               u' '.join(text.split()[start_index:start_index + 1])
            example_cli.exit()
            del example_cli
        else:
            cmd = text

        return cmd, continue_flag
185012
def run(self, *args):
        """"""

        params = self.parser.parse_args(args)
        sources = params.source
        code = self.autocomplete(sources)

        return code
255956
def run(self, text):
        
        for regex in self.regexes:
            text = regex.sub(self.repl, text)
        return text
432695
def run(self):
        
        # Make sure everything is in sync, before starting.
        self.sync_with_prompt_toolkit()

        def pre_run():
            # Start in navigation mode.
            self.application.vi_state.input_mode = InputMode.NAVIGATION

        # Run eventloop of prompt_toolkit.
        self.application.run(pre_run=pre_run)
821635
def main():
    

    # Parse arguments and configure application instance.
    arguments, parser = parse_arguments()

    # Start iterating
    store = RevisionStore()
    sys.stdout.write("Iterating over %d items.\n" % arguments.number)

    for i in xrange(arguments.number):
        key = chr(65 + (i % 26))
        value = [key * (i % 26), key * (i % 13), key * (i % 5)]

        store.add(key, value)

    # Wait for an enter
    if arguments.pause:
        sys.stdout.write("Done!")
        sys.stdin.readline()
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
1120557
def main(argv=None):
    
    @contextmanager
    def tmpdir():
        """ Create a self-deleting temporary directory. """
        path = mkdtemp()
        try:
            yield path
        finally:
            rmtree(path)
        return

    def test():
        """ Execute the test suite. """
        install = "{:s} install -r requirements-test.txt"
        check_call(install.format(pip).split())
        pytest = join(path, "bin", "py.test")
        test = "{:s} test/".format(pytest)
        check_call(test.split())
        uninstall = "{:s} uninstall -y -r requirements-test.txt"
        check_call(uninstall.format(pip).split())
        return

    args = _cmdline(argv)
    path = join(abspath(args.root), args.name)
    with tmpdir() as tmp:
        clone = "git clone {:s} {:s}".format(args.repo, tmp)
        check_call(clone.split())
        chdir(tmp)
        checkout = "git checkout {:s}".format(args.checkout)
        check_call(checkout.split())
        virtualenv = "virtualenv {:s}".format(path)
        check_call(virtualenv.split())
        pip = join(path, "bin", "pip")
        install = "{:s} install -U -r requirements.txt .".format(pip)
        check_call(install.split())
        if args.test:
            test()
    return 0
365600
function run(program, options, library) {
    var opts = Assign({}, DEFAULT_OPTIONS, options);
    var argv = opts.argv || [];
    var event = opts.event || null;

    var tokens = RuniqParser.lex(program);
    var ast = RuniqParser.parse(tokens);
    if (!library) library = _createLibrary();
    var interpreter = new RuniqInterpreter(library, opts);

    interpreter.run(ast, argv, event, function(err, result) {
        if (err && opts.error) return opts.error(err);
        if (opts.success) return opts.success(result);
    });
}
1120041
def main(cl_args=None):
    

    if cl_args is None and len(sys.argv) > 1:
        cl_args = sys.argv[1:]
    args = options.parse_args(cl_args)

    print("-------------------------------------------------------------------")
    print("                      __   _____   ___   ____    _ __     ")
    print("                     / /  /  _/ | / / | / / /__ (_) /_    ")
    print("                    / /___/ / | |/ /| |/ /  '_// / __/    ")
    print("                   /____/___/ |___/ |___/_/\_\/_/\__/     ")
    print("")
    print("                   Land Ice Verification & Validation     ")
    print("-------------------------------------------------------------------")
    print("")
    print("  Current run: " + livvkit.timestamp)
    print("  User: " + livvkit.user)
    print("  OS Type: " + livvkit.os_type)
    print("  Machine: " + livvkit.machine)
    print("  " + livvkit.comment)

    from livvkit.components import numerics
    from livvkit.components import verification
    from livvkit.components import performance
    from livvkit.components import validation
    from livvkit import scheduler
    from livvkit.util import functions
    from livvkit.util import elements

    summary_elements = []

    if livvkit.verify or livvkit.validate:
        functions.setup_output()

    if livvkit.verify:
        summary_elements.append(scheduler.run("numerics", numerics,
                                              functions.read_json(livvkit.numerics_model_config)))
        summary_elements.append(scheduler.run("verification", verification,
                                              functions.read_json(livvkit.verification_model_config)))
        summary_elements.append(scheduler.run("performance", performance,
                                              functions.read_json(livvkit.performance_model_config)))
    if livvkit.validate:
        print(" -----------------------------------------------------------------")
        print("   Beginning the validation test suite ")
        print(" -----------------------------------------------------------------")
        print("")
        validation_config = {}
        for conf in livvkit.validation_model_configs:
            validation_config = functions.merge_dicts(validation_config,
                                                      functions.read_json(conf))
        summary_elements.extend(scheduler.run_quiet(validation, validation_config,
                                                    group=False))
        print(" -----------------------------------------------------------------")
        print("   Validation test suite complete ")
        print(" -----------------------------------------------------------------")
        print("")

    if livvkit.verify or livvkit.validate:
        result = elements.page("Summary", "", element_list=summary_elements)
        functions.write_json(result, livvkit.output_dir, "index.json")
        print("-------------------------------------------------------------------")
        print(" Done!  Results can be seen in a web browser at:")
        print("  " + os.path.join(livvkit.output_dir, 'index.html'))
        print("-------------------------------------------------------------------")

    if args.serve:
        try:
            # Python 3
            import http.server as server
            import socketserver as socket
        except ImportError:
            # Python 2
            # noinspection PyPep8Naming
            import SimpleHTTPServer as server
            # noinspection PyPep8Naming
            import SocketServer as socket

        httpd = socket.TCPServer(('', args.serve), server.SimpleHTTPRequestHandler)

        sa = httpd.socket.getsockname()
        print('\nServing HTTP on {host} port {port} (http://{host}:{port}/)'.format(host=sa[0], port=sa[1]))
        print('\nView the generated website by navigating to:')
        print('\n    http://{host}:{port}/{path}/index.html'.format(host=sa[0], port=sa[1],
                                                                    path=os.path.relpath(livvkit.output_dir)
                                                                    ))
        print('\nExit by pressing `ctrl+c` to send a keyboard interrupt.\n')
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print('\nKeyboard interrupt received, exiting.\n')
            sys.exit(0)
1370624
def run(client, outputs, no_output, success_codes, isolation, command_line):
    """"""
    working_dir = client.repo.working_dir
    mapped_std = _mapped_std_streams(client.candidate_paths)
    factory = CommandLineToolFactory(
        command_line=command_line,
        directory=os.getcwd(),
        working_dir=working_dir,
        successCodes=success_codes,
        **{
            name: os.path.relpath(path, working_dir)
            for name, path in mapped_std.items()
        }
    )

    with client.with_workflow_storage() as wf:
        with factory.watch(
            client, no_output=no_output, outputs=outputs
        ) as tool:
            # Make sure all inputs are pulled from a storage.
            client.pull_paths_from_storage(
                *(
                    path
                    for _, path in tool.iter_input_files(client.workflow_path)
                )
            )

            returncode = call(
                factory.command_line,
                cwd=os.getcwd(),
                **{key: getattr(sys, key)
                   for key in mapped_std.keys()},
            )

            if returncode not in (success_codes or {0}):
                raise errors.InvalidSuccessCode(
                    returncode, success_codes=success_codes
                )

            sys.stdout.flush()
            sys.stderr.flush()

            wf.add_step(run=tool)