Serve a rueckenwind application
11446
def serv(args):
    """"""
    if not args.no_debug:
        tornado.autoreload.start()

    extra = []

    if sys.stdout.isatty():
        # set terminal title
        sys.stdout.write('\x1b]2;rw: {}\x07'.format(' '.join(sys.argv[2:])))

    if args.cfg:
        extra.append(os.path.abspath(args.cfg))

    listen = (int(args.port), args.address)
    ioloop = tornado.ioloop.IOLoop.instance()
    setup_app(app=args.MODULE, extra_configs=extra,
              ioloop=ioloop, listen=listen)
    ioloop.start()
1266511
def run(config):
    ""
    app = make_app(config=config)

    app.run(
            host=app.config.get("HOST", '127.0.0.1'),
            port=app.config.get("PORT", 5000),
            use_reloader=True,
            )
971971
def listen(self):
        """"""

        msgtmpl = (u'Serving on host %(host)s:%(port)s')
        host = CONF.wsgi.wsgi_host
        port = CONF.wsgi.wsgi_port
        LOG.info(msgtmpl,
                 {'host': host, 'port': port})
        server_cls = self._get_server_cls(host)
        httpd = simple_server.make_server(host,
                                          port,
                                          self.app,
                                          server_cls)
        httpd.serve_forever()
1190827
def start(path, query_parameters = {}, &block)
      if EventMachine.reactor_running?
        connect(path, query_parameters, &block)
      else
        if EventMachine.epoll?
          EventMachine.epoll
        elsif EventMachine.kqueue?
          EventMachine.kqueue
        else
          Kernel.warn('Your OS does not support epoll or kqueue.')
        end

        EventMachine.run do
          connect(path, query_parameters, &block)
        end
      end
    end
430298
def run(create_app, config, description=None, args=None, namespace=None, options=None):
    
    import argparse

    class HelpFormatter(
        # argparse.RawTextHelpFormatter,
        argparse.RawDescriptionHelpFormatter,
        # argparse.ArgumentDefaultsHelpFormatter,
        # argparse.HelpFormatter,
        ):
        pass

    # Get configurations data if
    envName = getattr(config, 'ENV', None)
    envMap = getattr(config, 'envMap', None)
    envHelp = getattr(config, 'envHelp', {})
    envSelectVar = getattr(config, 'envSelectVar', None)
    configurations = getattr(config, 'configurations', None)
    envSelectable = callable(getattr(config, 'select', None))
    envPrintable = config.__str__ is not object.__str__

    parser = argparse.ArgumentParser(
        description = description or getattr(config, 'description',
            'runs Flask-based web application using Python WSGI reference server'),
        epilog = ''.join((
            '\n\noptional environment variables:\n{}'.format(
                '\n'.join(sorted('  {:<20}  {}'.format(envMap[key], envHelp.get(key, ''))
                for key in envMap))) if envMap else '',
            '\n\navailable environment configurations (*: active):\n{}'.format(
                '\n'.join('{} {}'.format(
                    '*' if envName in c.names else ' ',
                    ' | '.join(c.names)
                ) for c in configurations)) if configurations else '',
        )),
        formatter_class = HelpFormatter)

    parser.add_argument('-b', '--bind', metavar='[HOST|:PORT]', default='127.0.0.1:5000',
        help = 'bind to HOST:PORT (default: 127.0.0.1:5000)')

    debug = config.DEBUG
    debugMsg = ' (default in {})'.format(config.ENV)
    debugTrueMsg = debugMsg if debug else ''
    debugFalseMsg = debugMsg if not debug else ''

    parser.add_argument('-r', '--reload', action='store_true', default=debug,
        help = 'reload server on code change' + debugTrueMsg)
    parser.add_argument('-R', '--no-reload', action='store_false', dest='reload',
        help = 'do not reload server on code change' + debugFalseMsg)

    parser.add_argument('-d', '--debug', action='store_true', default=debug,
        help = 'show debugger on exception' + debugTrueMsg)
    parser.add_argument('-D', '--no-debug', action='store_false', dest='debug',
        help = 'do not show debugger on exception' + debugFalseMsg)

    if envSelectable:
        parser.add_argument('-e', '--env', default=config.ENV,
            help = 'select environment config (default: {})'.format(config.ENV))

    if envPrintable:
        if envSelectable:
            parser.add_argument('-E', '--show-env', nargs='?', const=True,
                help = 'show environment config and exit ({}default: {})'
                    .format('*: all, ' if configurations else '', config.ENV))
        else:
            parser.add_argument('-E', '--show-env', action='store_true',
                help = 'show environment config and exit')

    parser.add_argument('-g', '--gen-key', action='store_true',
        help = 'generate a good secret key and exit')


    args = parser.parse_args(args, namespace)

    if args.gen_key:
        # See http://flask.pocoo.org/docs/0.10/quickstart/#sessions
        import os
        key = os.urandom(24)
        return print(key)
        # return print('{0}\n{0!r}'.format(key))

    if envSelectable and args.env:
        config = config.select(args.env)

    if envPrintable and args.show_env:
        if configurations and args.show_env == '*':
            print('\n\n'.join('# {}\n{}'.format(' | '.join(c.names), c) for c in configurations))
        elif args.show_env is True:
            print(config)
        else:
            print(config.select(args.show_env))

        return

    host, port = (args.bind + ':').split(':')[:2]
    host = host or '127.0.0.1'
    port = int(port) if port else 5000

    return create_app(config).run(host, port, args.debug, use_reloader=args.reload, **(options or {}))
414404
public function listen()
    {
        // Env check
        if (!$this->_isLinux()) {
            die("Error environment: Queue Listener requires Linux OS, you could use `work` or `single` instead.");
        }
        
        // Pre-work check
        if (!method_exists($this, 'handleListen'))
            throw new Exception("You need to declare `handleListen()` method in your worker controller.", 500);
        if (!method_exists($this, 'handleWork'))
            throw new Exception("You need to declare `handleWork()` method in your worker controller.", 500);
        if ($this->logPath && !file_exists($this->logPath)) {
            // Try to access or create log file
            if ($this->_log('')) {
                throw new Exception("Log file doesn't exist: `{$this->logPath}`.", 500);
            }
        }

        // INI setting
        if ($this->debug) {
            error_reporting(-1);
            ini_set('display_errors', 1);
        }
        set_time_limit(0);

        // Worker command builder
        // Be careful to avoid infinite loop by opening listener itself
        $workerAction = 'work';
        $route = $this->router->fetch_directory() . $this->router->fetch_class() . "/{$workerAction}";
        $workerCmd = "{$this->phpCommand} " . FCPATH . "index.php {$route}";

        // Static variables
        $startTime = 0;
        $workerCount = 0;
        $workingFlag = false;

        // Setting check
        $this->workerMaxNum = ($this->workerMaxNum >= 1) ? floor($this->workerMaxNum) : 1;
        $this->workerStartNum = ($this->workerStartNum <= $this->workerMaxNum) ? floor($this->workerStartNum) : $this->workerMaxNum;
        $this->workerWaitSeconds = ($this->workerWaitSeconds >= 1) ? $this->workerWaitSeconds : 10;

        while (true) {

            // Loading insurance
            sleep(0.1);
            
            // Call customized listener process, assigns works while catching true by callback return
        	$hasEvent = ($this->handleListen($this->_staticListen)) ? true : false;

            // Start works if exists
            if ($hasEvent) {  

                // First time to assign works
                if (!$workingFlag) {
                    $workingFlag = true;
                    $startTime = microtime(true);
                    $this->_log("Queue Listener - Job detect");
                    $this->_log("Queue Listener - Start dispatch");

                    if ($this->workerStartNum > 1) {
                        // Execute extra worker numbers
                        for ($i=1; $i < $this->workerStartNum ; $i++) { 
                            $workerCount ++;
                            $r = $this->_workerCmd($workerCmd, $workerCount);
                        }
                    }
                }

                // Max running worker numbers check, otherwise keeps dispatching more workers
                if ($this->workerMaxNum <= $workerCount) {

                    // Worker heath check
                    if ($this->workerHeathCheck) {
                        foreach ($this->_pidStack as $id => $pid) {
                            $isAlive = $this->_isPidAlive($pid);
                            if (!$isAlive) {
                                $this->_log("Queue Listener - Worker health check: Missing #{$id} (PID: {$pid})");
                                $r = $this->_workerCmd($workerCmd, $id);
                            }
                        }
                    }

                    sleep($this->workerWaitSeconds);
                    continue;
                }

                // Assign works
                $workerCount ++;
                // Create a worker
                $r = $this->_workerCmd($workerCmd, $workerCount);

                sleep($this->workerWaitSeconds);
                continue;
            }

            // The end of assignment (No more work), close the assignment
            if ($workingFlag) {
                $workingFlag = false;
                $workerCount = 0;
                // Clear worker stack
                $this->_pidStack = [];
                $costSeconds = number_format(microtime(true) - $startTime, 2, '.', '');
                $this->_log("Queue Listener - Job empty");
                $this->_log("Queue Listener - Stop dispatch, total cost: {$costSeconds}s");
            }
            
            // Idle
            if ($this->listenerSleep) {
                sleep($this->listenerSleep);
            }
        }
    }
1165631
function serve() {
  util.log(util.colors.green('Serving unminified js'));

  nodemon({
    script: require.resolve('../server/server.js'),
    watch: [
      require.resolve('../server/server.js')
    ],
    env: {
      'NODE_ENV': 'development',
      'SERVE_PORT': port,
      'SERVE_HOST': host,
      'SERVE_USEHTTPS': useHttps,
      'SERVE_PROCESS_ID': process.pid,
      'SERVE_QUIET': quiet
    },
  })
  .once('quit', function () {
    util.log(util.colors.green('Shutting down server'));
  });
  if (!quiet) {
    util.log(util.colors.yellow('Run `gulp build` then go to ' + getHost()));
  }
}
616170
public void launch() throws Exception {
        if (init.get())
            return;
        // Register a SIGINT handler for graceful shutdown.
        if (!init.get())
            init();

        log.info("Subscribing to " + channel + " on stream Id " + streamId);

        // Register a SIGINT handler for graceful shutdown.
        SigInt.register(() -> running.set(false));

        // Create an Aeron instance with client-provided context configuration, connect to the
        // media driver, and add a subscription for the given channel and stream using the supplied
        // dataHandler method, which will be called with new messages as they are received.
        // The Aeron and Subscription classes implement AutoCloseable, and will automatically
        // clean up resources when this try block is finished.
        //Note here that we are either creating 1 or 2 subscriptions.
        //The first one is a  normal 1 subscription listener.
        //The second one is when we want to send responses
        boolean started = false;
        int numTries = 0;
        while (!started && numTries < 3) {
            try {
                try (final Subscription subscription = aeron.addSubscription(channel, streamId)) {
                    log.info("Beginning subscribe on channel " + channel + " and stream " + streamId);
                    AeronUtil.subscriberLoop(new FragmentAssembler(NDArrayResponseFragmentHandler.builder().aeron(aeron)
                                    .context(ctx).streamId(responseStreamId).holder(ndArrayHolder).build()),
                                    fragmentLimitCount, running, launched).accept(subscription);
                    started = true;
                }


            } catch (Exception e) {
                numTries++;
                log.warn("Failed to connect..trying again", e);
            }
        }

        if (numTries >= 3)
            throw new IllegalStateException("Was unable to start responder after " + numTries + "tries");


    }
634471
def run(app=None, server=WSGIRefServer, host='127.0.0.1', port=8080,
        interval=1, reloader=False, **kargs):
    
    app = app if app else default_app()
    quiet = bool(kargs.get('quiet', False))
    # Instantiate server, if it is a class instead of an instance
    if isinstance(server, type):
        server = server(host=host, port=port, **kargs)
    if not isinstance(server, ServerAdapter):
        raise RuntimeError("Server must be a subclass of WSGIAdapter")
    if not quiet and isinstance(server, ServerAdapter): # pragma: no cover
        if not reloader or os.environ.get('BOTTLE_CHILD') == 'true':
            print("Bottle server starting up (using %s)..." % repr(server))
            print("Listening on http://%s:%d/" % (server.host, server.port))
            print("Use Ctrl-C to quit.")
            print()
        else:
            print("Bottle auto reloader starting up...")
    try:
        if reloader and interval:
            reloader_run(server, app, interval)
        else:
            server.run(app)
    except KeyboardInterrupt:
        if not quiet: # pragma: no cover
            print("Shutting Down...")
586297
def run(self, app):
        """"""
        GlimLog.info('Glim server started on %s environment' % self.args.env)
        try:
            kwargs = Config.get('app.server.options')
            run(app.wsgi,
                host=Config.get('app.server.host'),
                port=Config.get('app.server.port'),
                debug=Config.get('app.server.debugger'),
                reloader=Config.get('app.server.reloader'),
                server=Config.get('app.server.wsgi'),
                **kwargs)
        except Exception as e:
            print(traceback.format_exc())
            exit()
151931
def runserver(hostname, port, no_reloader, debugger, no_evalex, threaded, processes):
    """"""
    app = make_app()
    reloader = not no_reloader
    evalex = not no_evalex
    run_simple(
        hostname,
        port,
        app,
        use_reloader=reloader,
        use_debugger=debugger,
        use_evalex=evalex,
        threaded=threaded,
        processes=processes,
    )
914332
@Override
  public SparkAppHandle startApplication(SparkAppHandle.Listener... listeners) throws IOException {
    if (builder.isClientMode(builder.getEffectiveConfig())) {
      LOG.warning("It's not recommended to run client-mode applications using InProcessLauncher.");
    }

    Method main = findSparkSubmit();
    LauncherServer server = LauncherServer.getOrCreateServer();
    InProcessAppHandle handle = new InProcessAppHandle(server);
    for (SparkAppHandle.Listener l : listeners) {
      handle.addListener(l);
    }

    String secret = server.registerHandle(handle);
    setConf(LauncherProtocol.CONF_LAUNCHER_PORT, String.valueOf(server.getPort()));
    setConf(LauncherProtocol.CONF_LAUNCHER_SECRET, secret);

    List<String> sparkArgs = builder.buildSparkSubmitArgs();
    String[] argv = sparkArgs.toArray(new String[sparkArgs.size()]);

    String appName = CommandBuilderUtils.firstNonEmpty(builder.appName, builder.mainClass,
      "<unknown>");
    handle.start(appName, main, argv);
    return handle;
  }
964123
def run
      $0 = "rs_ohai" # to prevent showing full path to executalbe in help banner
      Log.program_name = 'RightLink'
      init_logger
      RightScale::OhaiSetup.configure_ohai
      Ohai::Application.new.run
      true
    end
634624
def main(http_port, peer_name, node_name, app_id):
    
    # Create the framework
    framework = pelix.framework.create_framework(
        ('pelix.ipopo.core',
         'pelix.ipopo.waiting',
         'pelix.shell.core',
         'pelix.shell.ipopo',
         'pelix.shell.console',
         'pelix.http.basic',

         # Herald core
         'herald.core',
         'herald.directory',
         'herald.shell',

         # Herald HTTP
         'herald.transports.http.directory',
         'herald.transports.http.discovery_multicast',
         'herald.transports.http.servlet',
         'herald.transports.http.transport',

         # RPC
         'pelix.remote.dispatcher',
         'pelix.remote.registry',
         'herald.remote.discovery',
         'herald.remote.herald_xmlrpc',),
        {herald.FWPROP_NODE_UID: node_name,
         herald.FWPROP_NODE_NAME: node_name,
         herald.FWPROP_PEER_NAME: peer_name,
         herald.FWPROP_APPLICATION_ID: app_id})

    # Start everything
    framework.start()
    context = framework.get_bundle_context()

    # Instantiate components
    with use_waiting_list(context) as ipopo:
        # ... HTTP server
        ipopo.add(pelix.http.FACTORY_HTTP_BASIC, "http-server",
                  {pelix.http.HTTP_SERVICE_PORT: http_port})

        # ... HTTP reception servlet
        ipopo.add(herald.transports.http.FACTORY_SERVLET,
                  "herald-http-servlet")

        # ... HTTP multicast discovery
        ipopo.add(herald.transports.http.FACTORY_DISCOVERY_MULTICAST,
                  "herald-http-discovery-multicast")

    # Start the framework and wait for it to stop
    framework.wait_for_stop()
1016625
function serveClientOnExpressRoute(app) {


  app.get("/myelements/myelements.jquery.js", function(req, res) {
    //logic taken form socket.io's serveClient
    // var etag = req.headers['if-none-match'];
    // if (etag) {
    //   if (clientVersion == etag) {
    //     debug('serve client 304');
    //     res.writeHead(304);
    //     res.end();
    //     return;
    //   }
    // }
    // debug('serve client source');
    // res.setHeader('ETag', clientVersion);
    res.setHeader("Content-type", "application/javascript");
    var result = Server.client();

    res.send(result);
    //res.sendFile(path.join(__dirname, "client.js"));
  });
}
158505
def app(config, src, dst, features, reload, force):
    """"""
    config = Path(config)
    if reload:
        argv = sys.argv.copy()
        argv.remove('--reload')
        monitor(config.dirname(), src, dst, argv)
    else:
        run(config, src, dst, force)
1210010
def _serve_process(self, slaveFd, serverPid):
        
        self.serverPid = serverPid
        if sys.stdin.isatty():
            self.oldTermios = termios.tcgetattr(sys.stdin.fileno())
        else:
            self.oldTermios = None
        self.oldStderr = SavedFile(2, sys, 'stderr')
        self.oldStdout = SavedFile(1, sys, 'stdout')
        self.oldStdin = SavedFile(0, sys, 'stdin')
        self.oldStderr.save(slaveFd, mode="w")
        self.oldStdout.save(slaveFd, mode="w")
        self.oldStdin.save(slaveFd, mode="r")
        os.close(slaveFd)
        self.closed = False