Main http entry point: run the engine
324941
def short_play(self, **kwargs):
        
        # options in URL arguments
        config = self._config_from_url()
        outputs = self.run(kwargs, config)
        return jsonify(outputs)
1224359
final public function run()
    {
        \Devil::registerApplication($this);
        if ($moduleID = $this->url->isModuleRequested()) {
            if ($module = $this->loadModule($moduleID)) {
                if ($module->beforeRun()) {
                    $this->url->useModule($moduleID);
                    $module->run();
                    $module->afterRun();
                } else {
                    $module->errorRun();
                }
            } else {
                throw new HttpException(HttpException::NOT_FOUND);
            }
        } else {
           parent::run();
        }
    }
287440
def start(self):
        
        self.running = True
        while self.running:
            self.update_prompt()
            try:
                self.cmdloop()
            except KeyboardInterrupt:
                print()
            except botocore.exceptions.BotoCoreError as e:
                print(e)
            except ParseException as e:
                print(self.engine.pformat_exc(e))
            except Exception:
                traceback.print_exc()
            self.engine.reset()
612772
def main() -> None:
    """"""
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--json",
        help="output in JSON format",
        action="store_true",
        default=False)
    parser.add_argument(
        "--config-file", help="Select config file to use", default=".snekrc")
    parser.add_argument(
        'files',
        metavar='file',
        nargs='*',
        default=[],
        help='Files to run checks against')
    parser.add_argument(
        "--init", help="generate snekrc", action="store_true", default=False)

    args = parser.parse_args()

    run_main(args)
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)
1370066
public function run()
    {
        header('HTTP/1.1 200 OK');
        header('Content-Type: text/event-stream;charset=UTF-8');
        header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
        header('Pragma: no-cache');

        while (1) {
            $stats = $this->metricsPoller->getStatsForCommandsRunning();

            if (empty($stats)) {
                echo "ping: \n\n";
            } else {
                foreach ($stats as $commandStats) {
                    echo "data: " . json_encode($commandStats) . "\n\n";
                }
            }

            ob_flush();
            flush();
            usleep($this->delay * 1000);
        }
    }
589678
function main() {
  var server = new grpc.Server();
  server.addService(hello_proto.Greeter.service, {sayHello: sayHello});
  server.bind('0.0.0.0:50051', grpc.ServerCredentials.createInsecure());
  server.start();
}
615690
def main():
    # config file
    conf = Config()
    actions = []

    debuglevel = logging.ERROR
    for it in sys.argv[1:]:
        if it == ("-v"):
            debuglevel = logging.WARNING
        elif it == ("-vv"):
            debuglevel = logging.INFO
        elif it == ("-vvv"):
            debuglevel = logging.DEBUG
        if it == ("--valid"):
            actions.append("valid")

    conf.debuglevel = debuglevel

    srv = ServerApp(conf)
    status = srv.login(conf.token)

    if not status:
        sys.exit(100)

    # pick up and run events
    
    srv.do_all_actions(conf)

    """ send data for monitoring """
    if conf.monitoring:
        srv.monitoring()

    """ create repo for web project - apache2/uwsgi"""
    if conf.webproject:
        #data =  srv.get_all_projects()
        #content = aray2xml(data)

        """ Check all repository on this system. """
        srv.check_repo_all()

        """ Recount size of full disk in all project on this system. """
        srv.check_size_all()

        """ reset owners for projects """
        srv.check_rights()

        """ check running services """
        srv.check_services()

        mng = manager(conf)
        for it in actions:
            fc = getattr(mng, it)
            fc()
9317
def main(argv=None):
    '''  '''
    parser = get_parser()

    # Parse arguments and run the function
    global args
    args = parser.parse_args(argv)
    args.func()
1249290
def start(debug=False, host='127.0.0.1'):
    
    if debug:
        debug = True
    nago.protocols.httpserver.app.run(debug=debug, host=host)
1204092
def run_main():
    

    parser = argparse.ArgumentParser(
        description=(
            'Search Splunk'))
    parser.add_argument(
        '-u',
        help='username',
        required=False,
        dest='user')
    parser.add_argument(
        '-p',
        help='user password',
        required=False,
        dest='password')
    parser.add_argument(
        '-f',
        help='splunk-ready request in a json file',
        required=False,
        dest='datafile')
    parser.add_argument(
        '-i',
        help='index to search',
        required=False,
        dest='index_name')
    parser.add_argument(
        '-a',
        help='host address: <fqdn:port>',
        required=False,
        dest='address')
    parser.add_argument(
        '-e',
        help='(Optional) earliest_time minutes back',
        required=False,
        dest='earliest_time_minutes')
    parser.add_argument(
        '-l',
        help='(Optional) latest_time minutes back',
        required=False,
        dest='latest_time_minutes')
    parser.add_argument(
        '-q',
        '--queryargs',
        nargs='*',
        help=(
            'query string for searching splunk: '
            'search index="antinex" AND levelname="ERROR"'),
        required=False,
        dest='query_args')
    parser.add_argument(
        '-j',
        help='(Optional) view as json dictionary logs',
        required=False,
        dest='json_view',
        action='store_true')
    parser.add_argument(
        '-t',
        help=(
            '(Optional) pre-existing Splunk token '
            'which can be set using export '
            'SPLUNK_TOKEN=<token>  - if provided '
            'the user (-u) and password (-p) '
            'arguments are not required'),
        required=False,
        dest='token')
    parser.add_argument(
        '-m',
        help='(Optional) verbose message when getting logs',
        required=False,
        dest='message_details',
        action='store_true')
    parser.add_argument(
        '-v',
        help='(Optional) verify certs - disabled by default',
        required=False,
        dest='verify',
        action='store_true')
    parser.add_argument(
        '-b',
        help='verbose',
        required=False,
        dest='verbose',
        action='store_true')
    args = parser.parse_args()

    user = SPLUNK_USER
    password = SPLUNK_PASSWORD
    token = SPLUNK_TOKEN
    address = SPLUNK_API_ADDRESS
    index_name = SPLUNK_INDEX
    verbose = SPLUNK_VERBOSE
    show_message_details = bool(str(ev(
        'MESSAGE_DETAILS',
        '0')).lower() == '1')
    earliest_time_minutes = None
    latest_time_minutes = None
    verify = False
    code_view = True
    json_view = False
    datafile = None

    if args.user:
        user = args.user
    if args.password:
        password = args.password
    if args.address:
        address = args.address
    if args.datafile:
        datafile = args.datafile
    if args.index_name:
        index_name = args.index_name
    if args.verify:
        verify = args.verify
    if args.earliest_time_minutes:
        earliest_time_minutes = int(args.earliest_time_minutes)
    if args.latest_time_minutes:
        latest_time_minutes = int(args.latest_time_minutes)
    if args.verbose:
        verbose = True
    if args.message_details:
        show_message_details = args.message_details
    if args.token:
        token = args.token
    if args.json_view:
        json_view = True
        code_view = False

    default_search_query = 'index="{}" | head 10 | reverse'.format(
        index_name)
    search_query = ev(
        'SPLUNK_QUERY',
        default_search_query)
    if args.query_args:
        search_query = ' '.join(
            args.query_args)

    valid = True
    if not user or user == 'user-not-set':
        log.critical('missing user')
        valid = False
    if not password or password == 'password-not-set':
        log.critical('missing password')
        valid = False
    if not index_name:
        log.critical('missing splunk index')
        valid = False
    if token:
        # if the token is present,
        # then the user and the password are not required
        if not valid and index_name:
            valid = True
    if not valid:
        log.critical(
            'Please run with the following arguments:\n')
        log.error(
            '-u <username> -p <password> '
            '-i <index> -t <token if user and password not set> '
            '-a <host address as: fqdn:port>')
        log.critical(
            '\n'
            'Or you can export the following '
            'environment variables and retry the command: '
            '\n')
        log.error(
            'export SPLUNK_ADDRESS="splunkenterprise:8088"\n'
            'export SPLUNK_API_ADDRESS="splunkenterprise:8089"\n'
            'export SPLUNK_PASSWORD="123321"\n'
            'export SPLUNK_USER="trex"\n'
            'export SPLUNK_INDEX="antinex"\n'
            'export SPLUNK_TOKEN="<Optional pre-existing Splunk token>"\n')
        sys.exit(1)

    if verbose:
        log.info((
            'creating client user={} address={}').format(
                user,
                address))

    last_msg = ''
    host = ''
    port = -1
    try:
        last_msg = (
            'Invalid address={}').format(
                address)
        address_split = address.split(':')
        last_msg = (
            'Failed finding host in address={} '
            '- please use: -a <fqdn:port>').format(
                address)
        host = address_split[0]
        last_msg = (
            'Failed finding integer port in address={} '
            '- please use: -a <fqdn:port>').format(
                address)
        port = int(address_split[1])
    except Exception as e:
        log.error((
            'Failed to parse -a {} for the '
            'splunk host address: {} which threw an '
            'ex={}').format(
                address,
                last_msg,
                e))
        sys.exit(1)
    # end of try ex

    if verbose:
        log.info((
            'connecting {}@{}:{}').format(
                user,
                host,
                port))

    req_body = None
    if datafile:
        if verbose:
            log.info((
                'loading request in datafile={}').format(
                    datafile))

        with open(datafile, 'r') as f:
            req_body = json.loads(f.read())

    earliest_time = None
    latest_time = None
    now = datetime.datetime.now()
    if earliest_time_minutes:
        min_15_ago = now - datetime.timedelta(
            minutes=earliest_time_minutes)
        earliest_time = min_15_ago.strftime(
            '%Y-%m-%dT%H:%M:%S.000-00:00')
    if latest_time_minutes:
        latest_time = (now - datetime.timedelta(
            minutes=latest_time_minutes)).strftime(
                '%Y-%m-%dT%H:%M:%S.000-00:00')

    # Step 2: Create a search job
    if not search_query.startswith('search'):
        search_query = 'search {}'.format(
            search_query)

    search_data = req_body
    if not search_data:
        search_data = {
            'search': search_query
        }
        if earliest_time:
            search_data['earliest_time'] = earliest_time
        if latest_time:
            search_data['latest_time'] = latest_time

    res = sp.search(
        user=user,
        password=password,
        address=address,
        token=token,
        query_dict=search_data,
        verify=verify)

    if res['status'] == SUCCESS:
        result_list = []
        try:
            result_list = res['record'].get(
                'results',
                result_list)
            if len(result_list) == 0:
                log.info((
                    'No matches for search={} '
                    'response={}').format(
                        ppj(search_data),
                        ppj(res['record'])))
        except Exception as e:
            result_list = []
            log.error((
                'Failed to find results for the query={} '
                'with ex={}').format(
                    ppj(search_data),
                    e))

        for ridx, log_record in enumerate(result_list):
            log_raw = log_record.get(
                '_raw',
                None)
            if log_raw:
                show_search_results(
                    log_rec=log_raw,
                    code_view=code_view,
                    json_view=json_view,
                    show_message_details=show_message_details)
            else:
                show_non_search_results(
                    log_rec=log_record,
                    code_view=code_view,
                    json_view=json_view,
                    show_message_details=show_message_details)
            # end of handling log record presentation as a view
        # end for all log records
    else:
        log.error((
            'Failed searching splunk with status={} and '
            'error: {}').format(
                res['status'],
                res['err']))
    # end of if job_id

    if verbose:
        log.info('done')
111250
def run(self):
        
        httpd = HTTPServer((self.host, self.port), self._Handler)
        sa = httpd.socket.getsockname()
        serve_message = "Serving HTTP on {host} port {port} (http://{host}:{port}/) ..."
        print(serve_message.format(host=sa[0], port=sa[1]))
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\nKeyboard interrupt received, exiting.")
            httpd.shutdown()
889412
async function main() {
  event.$emit('before-client-render')

  if (globalState.initialData) {
    dataStore.replaceState(globalState.initialData)
  }

  await routerReady(router)

  if (router.getMatchedComponents().length === 0) {
    throw new ReamError(pageNotFound(router.currentRoute.path))
  }
}
1068257
def run(self):
        """"""
        self.logger.info("Running main flask method on port " +
                         str(self.settings['FLASK_PORT']))
        self.app.run(host='0.0.0.0', port=self.settings['FLASK_PORT'])
1130938
function main() {
  var server = new grpc.Server();
  server.addService(services.GreeterService, {sayHello: sayHello});
  server.bind('0.0.0.0:50051', grpc.ServerCredentials.createInsecure());
  server.start();
}
581547
def main():
    """"""
    # Check command line arguments.
    if len(sys.argv) != 2:
        raise RuntimeError('Usage: python3 async_send.py <json config>')

    # Set up logging.
    sip_logging.init_logger(show_thread=False)

    # Load SPEAD configuration from JSON file.
    # _path = os.path.dirname(os.path.abspath(__file__))
    # with open(os.path.join(_path, 'spead_send.json')) as file_handle:
    #     spead_config = json.load(file_handle)
    spead_config = json.loads(sys.argv[1])
    try:
        _path = os.path.dirname(os.path.abspath(__file__))
        schema_path = os.path.join(_path, 'config_schema.json')
        with open(schema_path) as schema_file:
            schema = json.load(schema_file)
        validate(spead_config, schema)
    except ValidationError as error:
        print(error.cause)
        raise

    # Set up the SPEAD sender and run it (see method, above).
    sender = SpeadSender(spead_config)
    sender.run()
1051050
def main(arguments=None):
    ''''''
    if arguments is None:
        arguments = sys.argv[1:]

    server_parameters = get_server_parameters(arguments)
    config = get_config(server_parameters.config_path, server_parameters.use_environment)
    configure_log(config, server_parameters.log_level.upper())

    validate_config(config, server_parameters)

    importer = get_importer(config)

    with get_context(server_parameters, config, importer) as context:
        application = get_application(context)
        server = run_server(application, context)
        setup_signal_handler(server, config)
        logging.debug('thumbor running at %s:%d' % (context.server.ip, context.server.port))
        tornado.ioloop.IOLoop.instance().start()