Twisted dev server implementation
431465
def run_twisted(self, args):
        
        server = self

        from twisted.internet import reactor
        from twisted.web import resource
        from twisted.web.static import File
        from twisted.web.server import Site
        from autobahn.twisted.websocket import (WebSocketServerFactory,
                                                WebSocketServerProtocol)
        from autobahn.twisted.resource import WebSocketResource

        class DevWebSocketHandler(WebSocketServerProtocol):
            def onConnect(self, request):
                super(DevWebSocketHandler, self).onConnect(request)
                server.on_open(self)

            def onMessage(self, payload, isBinary):
                server.on_message(self, payload)

            def onClose(self, wasClean, code, reason):
                super(DevWebSocketHandler,self).onClose(wasClean, code, reason)
                server.on_close(self)

            def write_message(self, message, binary=False):
                self.sendMessage(message, binary)

        #: Set the call later method
        server.call_later = reactor.callLater
        server.add_callback = reactor.callFromThread

        factory = WebSocketServerFactory(u"ws://0.0.0.0:{}".format(self.port))
        factory.protocol = DevWebSocketHandler

        class MainHandler(resource.Resource):
            def render_GET(self, req):
                return str(server.index_page)

        root = resource.Resource()
        root.putChild("", MainHandler())
        root.putChild("dev", WebSocketResource(factory))
        reactor.listenTCP(self.port, Site(root))
        print("Twisted Dev server started on {}".format(self.port))
        reactor.run()
642538
public void launchWorker(Map conf, IContext sharedContext, String topologyId,
                             String supervisorId, Integer port, String workerId,
                             ConcurrentHashMap<String, String> workerThreadPidsAtom) throws Exception {
        String pid = UUID.randomUUID().toString();
        WorkerShutdown worker = Worker.mk_worker(conf, sharedContext, topologyId, supervisorId, port, workerId, null);
        ProcessSimulator.registerProcess(pid, worker);
        workerThreadPidsAtom.put(workerId, pid);
    }
389146
private function initPushServer()
    {
        $pushBind = $this->sandstoneApplication['sandstone.push.server']['bind'];
        $pushPort = $this->sandstoneApplication['sandstone.push.server']['port'];

        $context = new Context($this->loop);
        $pushServer = $context->getSocket(ZMQ::SOCKET_PULL);

        $pushServer->bind("tcp://$pushBind:$pushPort");

        $pushServer->on('message', function ($message) {
            $data = $this->sandstoneApplication['sandstone.push.event_serializer']->deserializeEvent($message);

            $this->logger->info('Push message event', ['event' => $data['name']]);

            $this->sandstoneApplication['dispatcher']->dispatch($data['name'], $data['event']);
        });
    }
643138
function startServer(argv, httpPort, httpsPort, certs) {
  console.log('Launching proxy server...');
  console.log('   http: ' + httpPort);
  console.log('  https: ' + httpsPort);

  // Injects a node stream by buffering all data, transforming it, and writing
  // it back out.
  // Module IDs are assigned on demand and rotate 0-126.
  var nextModuleId = 0;
  function injectStream(url, source, target) {
    var moduleId = nextModuleId++;
    if (nextModuleId >= 127) {
      nextModuleId = 0;
    }
    var sourceCode = '';
    source.on('data', function(chunk) {
      sourceCode += chunk;
    });
    source.on('end', function() {
      try {
        var targetCode = transformCode(moduleId, url, sourceCode, argv);
        target.end(targetCode);
      } catch (e) {
        console.log('Error during transformation, writing through.');
        console.log(e);
        target.end(sourceCode);
      }
    });
  };

  // Handles both HTTP and HTTPS requests.
  function handler(req, res) {
    // Support both the ?url= mode and the X-WTF-URL header.
    var targetUrl;
    if (req.headers['x-wtf-url']) {
      targetUrl = req.headers['x-wtf-url'];
    } else {
      var parsedUrl = url.parse(req.url, true);
      var query = parsedUrl.query;
      targetUrl = query.url;
    }
    if (!targetUrl || targetUrl.indexOf('http') != 0) {
      res.writeHead(404, ['Content-Type', 'text/plain']);
      res.end();
      return;
    }

    res.on('error', function(e) {
      console.log('ERROR (source): ' + e);
    });

    var targetModule = targetUrl.indexOf('https') == 0 ? https : http;
    targetModule.get(targetUrl, function(originalRes) {
      // Eat errors, otherwise the app will die.
      originalRes.on('error', function(e) {
        console.log('ERROR (target): ' + e);
      });

      // Pull out content type to see if we are interested in it.
      var supportedContentType = false;
      var contentType = originalRes.headers['content-type'];
      if (contentType && contentType.indexOf(';') != 0) {
        contentType = contentType.substr(0, contentType.indexOf(';'));
      }
      switch (contentType) {
        case 'text/javascript':
        case 'application/javascript':
          supportedContentType = true;
          break;
      }

      // Also parse the URL - some servers don't return content type for some
      // reason.
      var supportedPath = false;
      var contentUrl = url.parse(targetUrl);
      if (path.extname(contentUrl.pathname) == '.js') {
        supportedPath = true;
      }

      if (supportedContentType || supportedPath) {
        var headers = [];
        for (var key in originalRes.headers) {
          if (key == 'content-length') {
            continue;
          }
          headers.push([key, originalRes.headers[key]]);
        }
        res.writeHead(originalRes.statusCode, headers);
        injectStream(targetUrl, originalRes, res);
      } else {
        console.log('Pass-through: ' + targetUrl, contentType);
        res.writeHead(originalRes.statusCode, originalRes.headers);
        originalRes.pipe(res);
      }
    }).on('error', function(e) {
      console.log(e);
      res.writeHead(404, ['Content-Type', 'text/plain']);
      res.end(e.message);
    });
  };

  // HTTP server.
  var httpServer = http.createServer(handler);
  httpServer.listen(httpPort);

  // HTTPS server.
  var httpsServer = https.createServer({
    key: certs.privateKey,
    cert: certs.certificate
  }, handler);
  httpsServer.listen(httpsPort);

  console.log('Server ready, use ctrl-c to exit...');
  console.log('');
}
999190
def main():
    """"""
    arguments = docopt.docopt(__doc__, version='Coil CMS v{0}'.format(
        coil.__version__))
    if arguments['write_users']:
        sys.exit(write_users(arguments))
    elif arguments['devserver']:
        sys.exit(devserver(arguments))
    elif arguments['unlock']:
        sys.exit(unlock(arguments))
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()
691965
def connectionMade(self):
        """"""

        self.factory.request_xml = str(self.factory.payload)

        self.sendCommand('POST', '/cimom')

        self.sendHeader('Host', '%s:%d' %
                        (self.transport.addr[0], self.transport.addr[1]))
        self.sendHeader('User-Agent', 'pywbem/twisted')
        self.sendHeader('Content-length', len(self.factory.payload))
        self.sendHeader('Content-type', 'application/xml')

        if self.factory.creds:
            auth = base64.b64encode('%s:%s' % (self.factory.creds[0],
                                               self.factory.creds[1]))

            self.sendHeader('Authorization', 'Basic %s' % auth)

        self.sendHeader('CIMOperation', str(self.factory.operation))
        self.sendHeader('CIMMethod', str(self.factory.method))
        self.sendHeader('CIMObject', str(self.factory.object))

        self.endHeaders()

        # TODO: Figure out why twisted doesn't support unicode.  An
        # exception should be thrown by the str() call if the payload
        # can't be converted to the current codepage.

        self.transport.write(str(self.factory.payload))
878888
def dev():
    """"""
    env.roledefs = {
        'web': ['192.168.1.2'],
        'lb': ['192.168.1.2'],
    }
    env.user = 'vagrant'
    env.backends = env.roledefs['web']
    env.server_name = 'django_search_model-dev.net'
    env.short_server_name = 'django_search_model-dev'
    env.static_folder = '/site_media/'
    env.server_ip = '192.168.1.2'
    env.no_shared_sessions = False
    env.server_ssl_on = False
    env.goal = 'dev'
    env.socket_port = '8001'
    env.map_settings = {}
    execute(build_env)
206001
async function main() {

  // Retrieve the name of the network being used.
  const network = process.argv[process.argv.length - 1];
  console.log(`Running script with the ${network} network...`);

  // Delete any previous ZeppelinOS files.
  console.log(`Deleting previous zos files...`);
  if(fs.existsSync('zos.json')) fs.unlinkSync('zos.json');
  if(fs.existsSync(`zos.${network}.json`)) fs.unlinkSync(`zos.${network}.json`);

  // Enable command logging in ZeppelinOS.
  const Logger = lib.Logger;
  Logger.silent(false);
  Logger.verbose(true);

  // Retrieve ZeppelinOS scripts.
  // These are analogous to `zos` CLI commands.
  const { init, add, push, create, publish } = zos.scripts;

  // Initialize ZeppelinOS with Truffle's Web3 provider.
  console.log(`Initializing ZeppelinOS...`);
  const ZWeb3 = lib.ZWeb3;
  ZWeb3.initialize(web3.currentProvider);

  // Set the default parameters to be used in future transactions.
  const Contracts = lib.Contracts;
  Contracts.setArtifactsDefaults({
    gas: 6721975,
    gasPrice: 100000000000
  });

  // Retrieve the default transaction params.
  // This will include a default `from` address.
  const txParams = await Contracts.getDefaultTxParams();
  console.log(`Default params to be used in transactions:`, txParams);

  // Initialize the ZeppelinOS project.
  // Notice that publish is set to true, so that the project uses an App contract.
  // This App contract will be used from within Factory.sol to dynamically create
  // proxy instances from the contract itself.
  await init({name: 'creating-instances-from-solidity', version: '0.1.0', publish: true});

  // Add the Factory.sol and Instance.sol contracts to the ZeppelinOS project.
  console.log(`Adding contracts...`);
  await add({contractsData: [
    {alias: 'Factory', name: 'Factory'},
    {alias: 'Instance', name: 'Instance'}
  ]});

  // Push the contracts implementations to the network.
  console.log(`Pushing contract implementations...`);
  await push({force: true, network });

  // Retrieve the address of the project's App contract.
  // This address will be passed to an instance of the Factory contract,
  // so that it can call the App contract's create function.
  const zosLocalData = require(`./zos.${network}.json`);
  const appAddress = zosLocalData.app.address;
  console.log(`App deployed at ${appAddress}.`);

  // Create and initialize a proxy instance of the Factory contract.
  console.log(`Creating proxy instance of Factory.sol...`);
  const factoryProxy = await create({
    packageName: 'creating-instances-from-solidity',
    contractAlias: 'Factory',
    methodName: 'initialize',
    methodArgs: [appAddress],
    network
  });
  console.log(`Factory proxy created at ${factoryProxy.address}`);

  // Use the Factory proxy address to create a javascript Factory contract object.
  const factoryContract = Contracts.getFromLocal('Factory').at(factoryProxy.address);

  // Construct the call data for the initialize method of Instance.sol.
  // This call data consists of the contract's `initialize` method with the value of `42`.
  const encodeCall = lib.encodeCall;
  const data = encodeCall('initialize', ['uint256'], [42]);
  console.log(`Call data for Instance.sol's initialize: ${data}`);

  // TODO: Ideally, we'd want to retrieve the ProxyAdmin and forward that address
  // to the Factory's createInstance method. The problem is that the ProxyAdmin is created
  // lazily, and is not available at this time. Once this is changed,
  // we can also remove the reference to the transparent proxy problem 
  // from a few lines below.

  // Create and initialize a proxy instance of the Instance contract,
  // but do so via the Factory contract instead of using the create script.
  // This is the main concept of this example: proxies can be created from deployed contracts.
  console.log(`Creating proxy instance of Instance.sol (via Factory.sol)...`);
  const transactionReceipt = await factoryContract.methods.createInstance(data).send(txParams);
  const uint256ToAddress = require('zos-lib/lib/utils/Addresses.js').uint256ToAddress;
  const instanceAddress = uint256ToAddress(transactionReceipt.events['0'].raw.data);
  console.log(`Instance proxy created at ${instanceAddress}`);

  // Use the Instance proxy address to create a javascript Instance contract object.
  const instanceContract = Contracts.getFromLocal('Instance').at(instanceAddress);

  // Retrieve the value stored in the instance contract.
  // Note that we cannot make the call using the same address that created the proxy
  // because of the transparent proxy problem. See: https://docs.zeppelinos.org/docs/faq.html#why-are-my-getting-the-error-cannot-call-fallback-function-from-the-proxy-admin
  const anotherAccount = (await ZWeb3.accounts())[1];
  const value = await instanceContract.methods.value().call({ ...txParams, from: anotherAccount });
  console.log(`Retrieved value from the created Instance contract: ${value}`);

  return value;
}
1231090
function (port = 9090) {
  return store => {
    const getId = idGenerator();
    // initialize socket connection
    const socket = io('http://localhost:' + port);
    // register event noting connection to sockets (client app)
    let initEvent = buildEvent(getId(), 'CONNECTED TO SERVER', 'Successfully connected Vuetron to server.');
    store.commit('addNewEvent', initEvent);

    socket.on('clientAppConnected', function () {
      let event = buildEvent(getId(), 'CLIENT APP CONNECTED', 'Successfully connected to client application.');
      store.commit('addNewEvent', event);
    });

    socket.on('setInitState', function (state) {
      let event = buildEvent(getId(), 'STATE INITIALIZED', state);
      // register event noting receipt of initial client state
      store.commit('addNewEvent', event);
      // initialize client state value
      store.commit('updateClientState', state);
    });

    // listen for state changes from client and update
    //  vuetron's client state store accordingly along
    //  with mutation log
    socket.on('stateUpdate', function (changes, mutation, newState) {
      let updatedState = buildEvent(getId(), 'STATE CHANGE', {'changes': changes});
      // add mutations
      updatedState.mutation = mutation;
      // add newState
      updatedState.state = JSON.stringify(newState);
      // register event for state change
      store.commit('addNewEvent', updatedState);
      // update client's current state to newState
      store.commit('updateClientState', newState);
      // check if any of the mutations are subscribed
      if (changes) {
        for (let change of changes) {
          const parsedPath = pathParser(JSON.stringify(change.path));
          // if subscribed, push to that path's array for display
          for (let key of Object.keys(store.state.subscriptions)) {
            if (key === parsedPath || parsedPath.search(key) !== -1) {
              store.commit('addEventToSubscription', { key, change });
            }
          }
        }
      }
    });

    socket.on('eventUpdate', function (event) {
      let newEvent = buildEvent(getId(), 'EVENT EMITTED', event);
      store.commit('addNewEvent', newEvent);
    });

    socket.on('domUpdate', function (dom) {
      store.commit('updateClientDom', dom);
    });

    // listen for API responses made from FETCH requests and add to Event Stream
    socket.on('apiRequestResponse', function (response) {
      const display = {
        requestObj: response.requestConfig.slice(0),
        responseObj: response
      };
      delete display.responseObj.requestConfig;
      const apiEvent = buildEvent(getId(), 'API REQUEST / RESPONSE', display);
      store.commit('addNewEvent', apiEvent);
    });
  };
}
878230
def get_exitcode_reactor():
    
    from twisted.internet.main import installReactor
    from twisted.internet.selectreactor import SelectReactor

    class ExitCodeReactor(SelectReactor):

        def stop(self, exitStatus=0):
            super(ExitCodeReactor, self).stop()
            self.exitStatus = exitStatus

        def run(self, *args, **kwargs):
            super(ExitCodeReactor, self).run(*args, **kwargs)
            return self.exitStatus

    reactor = ExitCodeReactor()
    installReactor(reactor)
    return reactor
1290332
def _stream(self):  # pragma: no cover
        """"""
        self.factory.protocol = LiveStream
        self.factory.datasift = {
            'on_open': self._on_open,
            'on_close': self._on_close,
            'on_message': self._on_message,
            'send_message': None
        }
        if self.config.ssl:
            from twisted.internet import ssl
            options = ssl.optionsForClientTLS(hostname=WEBSOCKET_HOST)
            connectWS(self.factory, options)
        else:
            connectWS(self.factory)
        reactor.run()
580607
async function watchSauce(server, cfg) {
    try {
      debug('reading sauce pid');
      const pid = parseInt(await readFile(process.env.SC_PID_FILE), 10);

      debug(`sauce pid is ${pid}`);

      let done = false;

      server.once('run_complete', () => {
        debug('run complete');
        done = true;
      });

      const delay = 1000;

      // eslint-disable-next-line no-unmodified-loop-condition
      while (!done) {
        debug(`waiting ${delay}ms`);
        await new Promise((resolve) => setTimeout(resolve, delay));
        debug(`waited ${delay}ms`);
        await new Promise((resolve, reject) => {
          debug(`checking if ${pid} is running`);
          ps.lookup({
            psargs: '-A',
            pid
          }, (err, resultList) => {
            if (err) {
              debug('ps-node produced an error', err);
              reject(err);

              return;
            }

            if (resultList.length === 0) {
              debug(`pid ${pid} is not running`);
              reject(new Error(`pid ${pid} is not running`));

              return;
            }

            debug(`pid ${pid} is running`);
            resolve();
          });
        });
      }
    }
    catch (err) {
      console.error(err);
      console.error('Sauce Tunnel is not running, stopping server and exiting');
      stopper.stop(cfg);
      // so, this is a bit harsh, but due to karma's api,there's no great way to
      // communicate back to test.js that karma failed because the tunnel
      // disappeared. By exiting here, cmd.sh should restart sauce and run the
      // suite again
      //  eslint-disable-next-line no-process-exit
      process.exit(65);
    }
  }
1037336
def start_simple_server():
	""
	args = _get_args()
	addr = ('', args.port)
	DebuggingServer(addr, None)
	asyncore.loop()
342375
function runServer(cb) {
  function onStdOut(data) {
    const time = new Date().toTimeString();
    const match = data.toString('utf8').match(RUNNING_REGEXP);

    process.stdout.write(time.replace(/.*(\d{2}:\d{2}:\d{2}).*/, '[$1] '));
    process.stdout.write(data);

    if (match) {
      server.stdout.removeListener('data', onStdOut);
      server.stdout.on('data', x => process.stdout.write(x));
      if (cb) {
        cb(null, match[1]);
      }
    }
  }

  if (server) {
    server.kill('SIGTERM');
  }

  server = cp.spawn('node', [serverPath], {
    env: Object.assign({ NODE_ENV: 'development' }, process.env),
    silent: false,
  });

  server.stdout.on('data', onStdOut);
  server.stderr.on('data', x => process.stderr.write(x));
}
900441
function Server(config) {
        RED.nodes.createNode(this, config);

        // Start a DLPA server.
        // Options:
        //   --port PORT           Listening port number.
        //   --clients CLIENTS     The number of clicents.
        //   --max-workers MAX_WORKERS
        //                         The maximum number of workiers (default: 10).
        const proc = spawn("python3", [
            "-m", "dlpa.server",
            "--port", config.port,
            "--clients", config.nclient,
            "--key-length", "128",
            "--time-span", config.span ? config.span : "300"
        ], {
            cwd: __dirname,
        });
        let exited = false;
        proc.on("exit", (code, signal) => {
            this.log(`DLPA server is closed: ${signal}`);
            exited = true;
        })
        const logger = readline.createInterface({
            input: proc.stderr
        });
        logger.on("line", (line) => {
            this.log(line);
        })

        // Wait results which should be outputted into stderr; and then
        // post a message based on each output.
        const rl = readline.createInterface({
            input: proc.stdout
        });
        rl.on("line", (line) => {
            const payload = JSON.parse(line);
            this.send({
                "topic": config.topic,
                "payload": matrix(
                    parseInt(config.rows, 10),
                    parseInt(config.columns, 10),
                    payload.value.map(v => (v / MAG) - MAG))
            });
        });

        // Stop the server.
        this.on("close", (done) => {
            if (exited) {
                done();
                return;
            }

            // Wait the server is closed.
            proc.on("exit", () => {
                done();
            });

            // Send a signal.
            this.log("DLPA server is closing");
            proc.stdin.close();
            rl.close();
            logger.close();
            proc.kill();

        });

    }
1220130
def logTwisted():
    
    global _initializedTwisted

    if _initializedTwisted:
        return

    debug('log', 'Integrating twisted logger')

    # integrate twisted's logging with us
    from twisted.python import log as tlog

    # this call imports the reactor
    # that is why we do this in a separate method
    from twisted.spread import pb

    # we don't want logs for pb.Error types since they
    # are specifically raised to be handled on the other side
    observer = _getTheTwistedLogObserver()
    observer.ignoreErrors([pb.Error, ])
    tlog.startLoggingWithObserver(observer.emit, False)

    _initializedTwisted = True