Sets up the live server and databases, and then loops over handling
        http requests.
175033
def run(self):
        
        server_address = (self.host, self.port)
        threading = True
        if threading:
            httpd_cls = type('WSGIServer', (ThreadingMixIn, WSGIServer), {})
        else:
            httpd_cls = WSGIServer
        self.httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=False)
        wsgi_handler = get_internal_wsgi_application()
        self.httpd.set_app(wsgi_handler)
        self.is_ready.set()
        self.httpd.serve_forever()
1158936
def serve_http(self):
        
        start_http_server(port=self.options.port,
                          addr=str(self.options.address))
398562
protected function setup()
    {
        // Check if a valid access token exists.
        if (!$this->accessToken || $this->accessToken->expired()) {
            // Refresh is successful unless explicitly set to false.
            $refreshSuccess = true;

            // Check if a valid refresh token exists.
            if ($this->refreshToken && $this->refreshToken->getToken()) {
                // Attempt to use the refresh token.
                try {
                    $this->refresh();
                } catch (RequestException $e) {
                    // Check if the exception is due to an HTTP 403.
                    if ($e->getCode() == 403) {
                        $response = $e->getResponse();
                        $json = json_decode($response->getBody());
                        $body = $json->{'nl.divide.iq'};

                        // Check if the error is indeed a "TokenExpired" error,
                        // as expected.
                        if ($body->answer == 'TokenExpired') {
                            // Token is expired; refreshing unsuccessful.
                            $refreshSuccess = false;
                        } else {
                            // Unexpected error. Pass it up the stack. This
                            // might be a "TokenEmpty" error, but that would
                            // still be unexpected, because the token value was
                            // checked beforehand.
                            throw $e;
                        }
                    } else {
                        // Unexpected error. Pass it up the stack.
                        throw $e;
                    }
                }
            } else {
                // There is no refresh token to use; refreshing unsuccessful.
                $refreshSuccess = false;
            }

            // If refreshing failed, login from scratch and then authenticate.
            if (!$refreshSuccess) {
                $this->login()->authenticate();
            }
        }

        // Request the settings if needed.
        if (!$this->settings) {
            $response = $this->client->get('settings', [
                'headers' => ['Authentication' => $this->accessToken->getToken()],
            ]);

            $json = json_decode($response->getBody());
            $body = $json->{'nl.divide.iq'};
            $services = [];
            foreach ($body->services as $service) {
                $services[] = $service->code;
            }

            // Create new settings object.
            $this->settings = new Settings($services, $body->settings_updated);
        }
    }
879475
def main():
    
    setup_main()
    config = ConfigData(clean=True)
    try:
        config.register()
    finally:
        config.clean_after_if_needed()
190429
public function run()
    {
        $this->log("Server listening on {$this->host}:{$this->port}");
        $this->socket->listen($this->port, $this->host);
        $this->loop->run();
    }
648433
def run(cls):
        
        if not all(v is None for v in cls._services.values()):
            cls._set_host_id()
            cls._setup_logging()
            cls._set_process_name()
            cls._set_signal_handlers()
            cls._start_server()
        else:
            cls._logger.error('No services to host')
949080
def simple(application, host='127.0.0.1', port=8080):
	
	
	# Try to be handy as many terminals allow clicking links.
	print("serving on http://{0}:{1}".format(host, port))
	
	# Bind and launch the server; this is a blocking operation.
	make_server(host, int(port), application).serve_forever()
182395
def main(port=8000, n_output=10, use_segmenter=False):
    """"""
    global n
    global use_segmenter_flag
    n = n_output
    use_segmenter_flag = use_segmenter
    logging.info("Start webserver...")
    app.run(port=port)
489051
async function setupServer() {
  return new Promise(async (resolve, reject) => {
    config = config || (await getConfig());
    config.components.individual = [];
    config.prod = true;
    config.enableCache = true;
    config.mode = 'server';
    config.env = 'pwa';
    config.sourceMaps = false;
    config.copy = [];
    config.webpackDevServer = false;
    config.buildDir = path.join(config.wwwDir, 'build-ssr');
    config.dataDir = path.join(config.wwwDir, 'build-ssr', 'data');

    app.use(express.static(path.relative(process.cwd(), config.wwwDir)));

    // generate a fresh webpack build + pass along asset data to dynamic HTML template rendered
    server = await app.listen(port);

    app.get('/ssr', function(req, res) {
      res.send(template(html || '', port, webpackStatsGenerated || []));
    });

    // handle cleaning up + shutting down the server instance
    process.on('SIGTERM', shutDownSSRServer);
    process.on('SIGINT', shutDownSSRServer);

    server.on('connection', connection => {
      connections.push(connection);
      connection.on(
        'close',
        // eslint-disable-next-line no-return-assign
        () => (connections = connections.filter(curr => curr !== connection)),
      );
    });

    resolve();
  });
}
73753
def run(self):
        

        #######################################################################
        # Config
        #######################################################################
        self.config = load_config(self.configfile)

        collectors = load_collectors(self.config['server']['collectors_path'])
        metric_queue_size = int(self.config['server'].get('metric_queue_size',
                                                          16384))
        self.metric_queue = self.manager.Queue(maxsize=metric_queue_size)
        self.log.debug('metric_queue_size: %d', metric_queue_size)

        #######################################################################
        # Handlers
        #
        # TODO: Eventually move each handler to it's own process space?
        #######################################################################

        if 'handlers_path' in self.config['server']:
            handlers_path = self.config['server']['handlers_path']

            # Make an list if not one
            if isinstance(handlers_path, basestring):
                handlers_path = handlers_path.split(',')
                handlers_path = map(str.strip, handlers_path)
                self.config['server']['handlers_path'] = handlers_path

            load_include_path(handlers_path)

        if 'handlers' not in self.config['server']:
            self.log.critical('handlers missing from server section in config')
            sys.exit(1)

        handlers = self.config['server'].get('handlers')
        if isinstance(handlers, basestring):
            handlers = [handlers]

        # Prevent the Queue Handler from being a normal handler
        if 'diamond.handler.queue.QueueHandler' in handlers:
            handlers.remove('diamond.handler.queue.QueueHandler')

        self.handlers = load_handlers(self.config, handlers)

        QueueHandler = load_dynamic_class(
            'diamond.handler.queue.QueueHandler',
            Handler
        )

        self.handler_queue = QueueHandler(
            config=self.config, queue=self.metric_queue, log=self.log)

        handlers_process = multiprocessing.Process(
            name="Handlers",
            target=handler_process,
            args=(self.handlers, self.metric_queue, self.log),
        )

        handlers_process.daemon = True
        handlers_process.start()

        #######################################################################
        # Signals
        #######################################################################

        if hasattr(signal, 'SIGHUP'):
            signal.signal(signal.SIGHUP, signal_to_exception)

        #######################################################################

        while True:
            try:
                active_children = multiprocessing.active_children()
                running_processes = []
                for process in active_children:
                    running_processes.append(process.name)
                running_processes = set(running_processes)

                ##############################################################
                # Collectors
                ##############################################################

                running_collectors = []
                for collector, config in self.config['collectors'].iteritems():
                    if config.get('enabled', False) is not True:
                        continue
                    running_collectors.append(collector)
                running_collectors = set(running_collectors)

                # Collectors that are running but shouldn't be
                for process_name in running_processes - running_collectors:
                    if 'Collector' not in process_name:
                        continue
                    for process in active_children:
                        if process.name == process_name:
                            process.terminate()

                collector_classes = dict(
                    (cls.__name__.split('.')[-1], cls)
                    for cls in collectors.values()
                )

                load_delay = self.config['server'].get('collectors_load_delay',
                                                       1.0)
                for process_name in running_collectors - running_processes:
                    # To handle running multiple collectors concurrently, we
                    # split on white space and use the first word as the
                    # collector name to spin
                    collector_name = process_name.split()[0]

                    if 'Collector' not in collector_name:
                        continue

                    if collector_name not in collector_classes:
                        self.log.error('Can not find collector %s',
                                       collector_name)
                        continue

                    collector = initialize_collector(
                        collector_classes[collector_name],
                        name=process_name,
                        configfile=self.configfile,
                        handlers=[self.handler_queue])

                    if collector is None:
                        self.log.error('Failed to load collector %s',
                                       process_name)
                        continue

                    # Splay the loads
                    time.sleep(float(load_delay))

                    process = multiprocessing.Process(
                        name=process_name,
                        target=collector_process,
                        args=(collector, self.metric_queue, self.log)
                    )
                    process.daemon = True
                    process.start()

                if not handlers_process.is_alive():
                    self.log.error('Handlers process exited')
                    if (str_to_bool(self.config['server'].get(
                            'abort_on_handlers_process_exit', 'False'))):
                        raise Exception('Handlers process exited')

                ##############################################################

                time.sleep(1)

            except SIGHUPException:
                # ignore further SIGHUPs for now
                original_sighup_handler = signal.getsignal(signal.SIGHUP)
                signal.signal(signal.SIGHUP, signal.SIG_IGN)

                self.log.info('Reloading state due to HUP')
                self.config = load_config(self.configfile)
                collectors = load_collectors(
                    self.config['server']['collectors_path'])
                # restore SIGHUP handler
                signal.signal(signal.SIGHUP, original_sighup_handler)
274452
def runserver(ctx, conf, port, foreground):
    """"""
    config = read_config(conf)

    debug = config['conf'].get('debug', False)
    click.echo('Debug mode {0}.'.format('on' if debug else 'off'))

    port = port or config['conf']['server']['port']

    app_settings = {
        'debug': debug,
        'auto_reload': config['conf']['server'].get('auto_reload', False),
    }
    handlers_settings = __create_handler_settings(config)

    if foreground:
        click.echo('Requested mode: foreground')
        start_app(port, app_settings, handlers_settings)
    else:
        click.echo('Requested mode: background')
        # subprocess.call([sys.executable, 'yourscript.py'], env=os.environ.copy())
        raise NotImplementedError
938549
def __setup_fileserver(self):
        '''
        
        '''
        fs_ = salt.fileserver.Fileserver(self.opts)
        self._serve_file = fs_.serve_file
        self._file_find = fs_._find_file
        self._file_hash = fs_.file_hash
        self._file_list = fs_.file_list
        self._file_list_emptydirs = fs_.file_list_emptydirs
        self._dir_list = fs_.dir_list
        self._symlink_list = fs_.symlink_list
        self._file_envs = fs_.envs
90530
def start():
    '''
    
    '''
    from wsgiref.simple_server import make_server

    # When started outside of salt-api __opts__ will not be injected
    if '__opts__' not in globals():
        globals()['__opts__'] = get_opts()

        if __virtual__() is False:
            raise SystemExit(1)

    mod_opts = __opts__.get(__virtualname__, {})

    # pylint: disable=C0103
    httpd = make_server('localhost', mod_opts['port'], application)

    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        raise SystemExit(0)
1322372
def setServer(self, server):
        
        if server == 'live':
            self.__server__ = server
            self.__server_url__ = 'api.sense-os.nl'
            self.setUseHTTPS()
            return True
        elif server == 'dev':
            self.__server__ = server
            self.__server_url__ = 'api.dev.sense-os.nl'
            # the dev server doesn't support https
            self.setUseHTTPS(False)
            return True
        elif server == 'rc':
            self.__server__ = server
            self.__server_url__ = 'api.rc.dev.sense-os.nl'
            self.setUseHTTPS(False)
        else:
            return False
357294
def _setupHttp(self):
        
        if self._http == None:
            http = httplib2.Http()
            self._http = self._credentials.authorize(http)
620044
public function setup()
    {
        //====================================================================//
        // Read Parameters
        $this->id = Splash::configuration()->WsIdentifier;
        $this->key = Splash::configuration()->WsEncryptionKey;

        //====================================================================//
        // If Another Host is Defined => Allow Overide of Server Host Address
        if (!empty(Splash::configuration()->WsHost)) {
            $this->host = Splash::configuration()->WsHost;
        } else {
            $this->host = self::SPLASHHOST;
        }

        //====================================================================//
        // If Http Auth is Required => Setup User & Password
        if (isset(Splash::configuration()->HttpAuth) && !empty(Splash::configuration()->HttpAuth)) {
            $this->httpAuth = true;
        }
        if ($this->httpAuth && isset(Splash::configuration()->HttpUser)) {
            $this->httpUser = Splash::configuration()->HttpUser;
        }
        if ($this->httpAuth && isset(Splash::configuration()->HttpPassword)) {
            $this->httpPassword = Splash::configuration()->HttpPassword;
        }

        //====================================================================//
        // Safety Check
        if (!$this->verify()) {
            return false;
        }

        return Splash::log()->deb('MsgWsSetParams');
    }
1166525
def run(self, host="localhost", port=8000, shutdown_timeout=60.0, **kwargs):
        
        print("Running service on http://localhost:%i. " % port + \
                                            "Press Ctrl+C to terminate.")

        # apply the configuration to the service config
        self.config.port = port
        self.config.host = host

        # start the loop
        try:
            # if an event broker has been created for this service
            if self.event_broker:
                # start the broker
                self.event_broker.start()
                # announce the service
                self.loop.run_until_complete(self.announce())

            # the handler for the http server
            http_handler = self.app.make_handler()
            # create an asyncio server
            self._http_server = self.loop.create_server(http_handler, host, port)

            # grab the handler for the server callback
            self._server_handler = self.loop.run_until_complete(self._http_server)
            # start the event loop
            self.loop.run_forever()

        # if the user interrupted the server
        except KeyboardInterrupt:
            # keep going
            pass

        # when we're done
        finally:
            try:
                # clean up the service
                self.cleanup()
            # if we end up closing before any variables get assigned
            except UnboundLocalError:
                # just ignore it (there was nothing to close)
                pass

            # close the event loop
            self.loop.close()