Switch to async Python REPL
547763
def do_console(self) -> None:
        """"""
        if not self._console_enabled:
            self._sout.write('Python console disabled for this sessiong\n')
            self._sout.flush()
            return

        h, p = self._host, self._console_port
        log.info('Starting console at %s:%d', h, p)
        fut = init_console_server(
            self._host, self._console_port, self._locals, self._loop)
        server = fut.result(timeout=3)
        try:
            console_proxy(
                self._sin, self._sout, self._host, self._console_port)
        finally:
            coro = close_server(server)
            close_fut = asyncio.run_coroutine_threadsafe(coro, loop=self._loop)
            close_fut.result(timeout=15)
332962
def repl_proc(self, inputstring, log=True, **kwargs):
        """"""
        return self.apply_procs(self.replprocs, kwargs, inputstring, log=log)
954209
async def run_async(self):
        
        try:
            await self.run_loop_async()
        except Exception as err:  # pylint: disable=broad-except
            _logger.error("Run loop failed %r", err)

        try:
            _logger.info("Shutting down all pumps %r", self.host.guid)
            await self.remove_all_pumps_async("Shutdown")
        except Exception as err:  # pylint: disable=broad-except
            raise Exception("Failed to remove all pumps {!r}".format(err))
1179233
def simple_wait(func):
    
    @wraps(func)
    def wrapper(*args, **kwargs):
        wait = Wait()
        wait.start()
        try:
            ret = func(*args, **kwargs)
        finally:
            wait.stop()
        sys.stdout.write('\n')
        return ret
    return wrapper
370393
def interactive_shell():
    
    print('You should be able to read and update the "counter[0]" variable from this shell.')
    try:
        yield from embed(globals=globals(), return_asyncio_coroutine=True, patch_stdout=True)
    except EOFError:
        # Stop the loop when quitting the repl. (Ctrl-D press.)
        loop.stop()
1337101
async def jsk_python(self, ctx: commands.Context, *, argument: CodeblockConverter):
        

        arg_dict = get_var_dict_from_ctx(ctx, SCOPE_PREFIX)
        arg_dict["_"] = self.last_result

        scope = self.scope

        try:
            async with ReplResponseReactor(ctx.message):
                with self.submit(ctx):
                    async for result in AsyncCodeExecutor(argument.content, scope, arg_dict=arg_dict):
                        if result is None:
                            continue

                        self.last_result = result

                        if isinstance(result, discord.File):
                            await ctx.send(file=result)
                        elif isinstance(result, discord.Embed):
                            await ctx.send(embed=result)
                        elif isinstance(result, PaginatorInterface):
                            await result.send_to(ctx)
                        else:
                            if not isinstance(result, str):
                                # repr all non-strings
                                result = repr(result)

                            if len(result) > 2000:
                                # inconsistency here, results get wrapped in codeblocks when they are too large
                                #  but don't if they're not. probably not that bad, but noting for later review
                                paginator = WrappedPaginator(prefix='```py', suffix='```', max_size=1985)

                                paginator.add_line(result)

                                interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
                                await interface.send_to(ctx)
                            else:
                                if result.strip() == '':
                                    result = "\u200b"

                                await ctx.send(result.replace(self.bot.http.token, "[token omitted]"))
        finally:
            scope.clear_intersection(arg_dict)
678804
async def work_async(self):
        """"""
        try:
            raise self._error
        except TypeError:
            pass
        except Exception as e:
            _logger.warning("%r", e)
            raise
        try:
            await self.lock_async()
            if self._closing:
                _logger.debug("Connection unlocked but shutting down.")
                return
            await self.loop.run_in_executor(self._executor, functools.partial(self._conn.do_work))
        except asyncio.TimeoutError:
            _logger.debug("Connection %r timed out while waiting for lock acquisition.", self.container_id)
        finally:
            self.release_async()
600833
def start(io_loop=None, check_time=2):

    
    io_loop = io_loop or asyncio.get_event_loop()
    if io_loop in _io_loops:
        return
    _io_loops[io_loop] = True
    if len(_io_loops) > 1:
        logger.warning("aiohttp_autoreload started more than once in the same process")
    # if _has_execv:
    #     add_reload_hook(functools.partial(io_loop.close, all_fds=True))
    modify_times = {}
    callback = functools.partial(_reload_on_update, modify_times)
    logger.debug("Starting periodic checks for code changes")
    call_periodic(check_time, callback, loop=io_loop)
34676
function history(repl, file) {

  try {
    var stat = fs.statSync(file);
    repl.rli.history = fs.readFileSync(file, 'utf-8').split('\n').reverse();
    repl.rli.history.shift();
    repl.rli.historyIndex = -1;
  } catch (e) {}

  var fd = fs.openSync(file, 'a'),
    reval = repl.eval;

  repl.rli.addListener('line', function(code) {
    if (code && code !== '.history') {
      fs.write(fd, code + '\n');
    } else {
      repl.rli.historyIndex++;
      repl.rli.history.pop();
    }
  });

  process.on('exit', function() {
    fs.closeSync(fd);
  });

  repl.commands['.history'] = {
    help: 'Show the history',
    action: function() {
      var out = [];
      repl.rli.history.forEach(function(v, k) {
        out.push(v);
      });
      repl.outputStream.write(out.reverse().join('\n') + '\n');
      repl.displayPrompt();
    }
  };
}
452025
def wrap_sync(func):
    """"""
    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        fut = asyncio.Future()
        def green():
            try:
                fut.set_result(func(*args, **kwargs))
            except BaseException as e:
                fut.set_exception(e)
        greenlet.greenlet(green).switch()
        return fut
    return wrapped
787365
async function action(projectDir, options) {
  await Detach.detachAsync(projectDir, options);
  // yesno lib doesn't properly shut down. without this the command won't exit
  process.stdin.pause();
}
957229
def _async_callable(func):
    """"""
    if isinstance(func, types.CoroutineType):

        return func

    @functools.wraps(func)
    async def _async_def_wrapper(*args, **kwargs):
        """Wrap a a sync callable in an async def."""
        return func(*args, **kwargs)

    return _async_def_wrapper
175511
def run_async(self, time_limit):
        '''  '''

        self.background = time_limit
        results = self.run()
        return results, poller.AsyncPoller(results, self)
409536
private static boolean repStep(
			BufferedReader in,
			boolean readConsoleInput) throws IOException, InterruptedException {

		// wait until CLIENT_POLLING_INTERVAL is over or the user entered something.
		long startTime = System.currentTimeMillis();
		while ((System.currentTimeMillis() - startTime) < CLIENT_POLLING_INTERVAL_MS
			&& (!readConsoleInput || !in.ready())) {
			Thread.sleep(200L);
		}
		//------------- handle interactive command by user. ----------------------

		if (readConsoleInput && in.ready()) {
			String command = in.readLine();
			switch (command) {
				case "quit":
				case "stop":
					return false;

				case "help":
					System.err.println(YARN_SESSION_HELP);
					break;
				default:
					System.err.println("Unknown command '" + command + "'. Showing help:");
					System.err.println(YARN_SESSION_HELP);
					break;
			}
		}

		return true;
	}
1052081
def _await_if_required(
        target: typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]]
    ) -> typing.Callable[..., typing.Any]:
        """"""

        @functools.wraps(target)
        def wrapper(*args, **kwargs):  # type: (typing.Any, typing.Any) -> typing.Any
            """Decorator/wrapper."""
            result = target(*args, **kwargs)
            if asyncio.iscoroutine(result):
                loop = asyncio.new_event_loop()
                result = loop.run_until_complete(result)
                loop.close()
            return result

        return wrapper
301129
async function runProgram() {
    let argvFragment = process.argv.slice(2);
    if (argvFragment.length === 0) {
        argvFragment = ['-h'];
    }

    const latest = await latestVersion(pkg.name, {version: `>${pkg.version}`})
        .catch(() => pkg.version);
    if (semver.gt(latest, pkg.version)) {
        process.stderr.write(chalk.default.white(`\n     Update available `));
        process.stderr.write(chalk.default.grey(`${pkg.version}`));
        process.stderr.write(chalk.default.white(` -> `));
        process.stderr.write(chalk.default.greenBright(`${latest}\n`));
        process.stderr.write(chalk.default.white(`     Run `));
        process.stderr.write(chalk.default.blueBright(`npm i -g ${pkg.name} `));
        process.stderr.write(chalk.default.white(`to update.\n\n`));
    }

    args = minimist(argvFragment);

    if (args.prefix) {
        intercept(function (txt) {
            return `[${pkg.name}]\n${txt}`;
        });
    }

    if (args['!'] ||
        args.help ||
        args.h ||
        args._.includes('help')) {
        return help(args, process.stdout);
    }


    if (args._.length === 1 && args._[0] === 'init') {
        const result = await initializeConfig();
        if (result) {
            await stdoutAsync(`Successfully wrote ${process.cwd()}/.qnamakerrc\n`);
        }
        return;
    }

    if (args.version || args.v) {
        await stdoutAsync(require(path.join(__dirname, '../package.json')).version + '\n');
        return;
    }

    let serviceIn = {};
    if (args.stdin) {
        let json = await stdin();
        serviceIn = JSON.parse(json);
    }

    const config = await composeConfig(args);
    args.kbId = args.kbId || serviceIn.kbId || config.kbId;
    args.subscriptionKey = args.subscriptionKey || serviceIn.subscriptionKey || config.subscriptionKey;
    args.endpointKey = args.endpointKey || serviceIn.endpointKey || config.endpointKey;
    args.hostname = args.hostname || serviceIn.hostname || config.hostname;

    ServiceBase.config = args;

    validateConfig(args);

    if (args._[0] === 'set')
        return await handleSetCommand(args, config);

    const serviceManifest = getServiceManifest(args);

    let requestBody = await validateArguments(serviceManifest);

    // special case operations
    switch (serviceManifest.operation.methodAlias) {
        case 'delete':
            if (!args.f && !args.force) {
                let kbResult = await new Knowledgebase().getKnowledgebaseDetails(config);
                let kb = JSON.parse(await kbResult.text());
                if (!args.force) {
                    let answer = readlineSync.question(`Are you sure you would like to delete ${kb.name} [${kb.id}]? [no] `, {defaultInput: 'no'});
                    if (answer.trim()[0] === 'n') {
                        process.stderr.write('operation canceled');
                        return;
                    }
                }
            }
            break;

        case 'create':
            if (args.name)
                requestBody.name = args.name;

            if (!requestBody.name) {
                if (!(args.q || args.quiet)) {
                    let answer = readlineSync.question(`What would you like to name your new knowledgebase? `);
                    if (answer && answer.length > 0)
                        requestBody.name = answer.trim();
                }
            }
            // hack to map incorrect export property from expected import.  Export uses qnaDocuments, create/update/replace qnaList :(
            if (requestBody.qnaDocuments && !requestBody.qnaList) {
                requestBody.qnaList = requestBody.qnaDocuments;
                delete requestBody.qnaDocuments;
            }
            break;

        case 'replace':
        case 'update':
            // hack to map incorrect export property from expected.  Export uses qnaDocuments, create/update/replace qnaList :(
            if (requestBody.qnaDocuments && !requestBody.qnaList) {
                requestBody.qnaList = requestBody.qnaDocuments;
                delete requestBody.qnaDocuments;
            }
            break;
    }

    let result = await qnamaker(config, serviceManifest, args, requestBody);
    if (result.error) {
        throw new Error(JSON.stringify(result.error, null, 4));
    }

    // special case response
    switch (serviceManifest.operation.name) {
        case 'getKnowledgebaseDetails': {
            config.kbId = result.id;
            let kb = await updateKbId(config);
            if (args.msbot) {
                await stdoutAsync(JSON.stringify({
                    type: 'qna',
                    name: kb.name,
                    id: kb.id,
                    kbId: kb.id,
                    subscriptionKey: config.subscriptionKey,
                    endpointKey: config.endpointKey,
                    hostname: kb.hostName
                }, null, 2) + '\n');
            } else {
                await stdoutAsync(JSON.stringify(result, null, 2) + '\n');
            }
            break;
        }
        case 'createKnowledgebase':
            if (args.wait || args.msbot) {
                result = await waitForOperationSucceeded(config, result);

                let kbId = result.resourceLocation.split('/')[2];
                config.kbId = kbId;
                let kb = await updateKbId(config);
                if (args.msbot) {
                    await stdoutAsync(JSON.stringify({
                        type: 'qna',
                        name: kb.name,
                        id: kb.id,
                        kbId: kb.id,
                        subscriptionKey: config.subscriptionKey,
                        endpointKey: config.endpointKey,
                        hostname: config.hostname
                    }, null, 2) + '\n');

                } else {
                    await stdoutAsync(JSON.stringify(result, null, 2));
                }
                if (args.wait && !(args.q || args.quiet) && !args.msbot) {
                    let answer = readlineSync.question(`Would you like to save ${kb.name} ${kb.id} in your .qnamakerrc so that future commands will be with this KB? [yes] `, {defaultInput: 'yes'});
                    if (answer[0] === 'y') {
                        await fs.writeJson(path.join(process.cwd(), '.qnamakerrc'), config, {spaces: 2});
                        await stdoutAsync('.qnamakerrc updated' + '\n');
                    }
                }
            } else {
                await stdoutAsync(JSON.stringify(result, null, 2));
            }
            break;

        case 'updateKnowledgebase':
            if (args.wait || args.msbot) {
                result = await waitForOperationSucceeded(config, result);
            }
            await stdoutAsync(JSON.stringify(result, null, 2));
            break;

        default: {
            // dump json as json stringified
            if (typeof result === 'string')
                await stdoutAsync(result + '\n');
            else
                await stdoutAsync(JSON.stringify(result, null, 2) + '\n');
            break;
        }
    }
}
376814
def repl_update(self, config):
        """"""
        cfg = config.copy()
        cfg['version'] += 1
        try:
            result = self.run_command("replSetReconfig", cfg)
            if int(result.get('ok', 0)) != 1:
                return False
        except pymongo.errors.AutoReconnect:
            self.update_server_map(cfg)  # use new server_map
        self.waiting_member_state()
        self.waiting_config_state()
        return self.connection() and True