Create a new Processor with the specified options.

@param {Object} options (optional)
@param {Bool} start_as_slave (optional)
@api public
168480
function (options, start_as_slave) {
    isSlave = start_as_slave && !process.env._CHILD_ID_;
    isMaster = !start_as_slave && !process.env._CHILD_ID_;

    this.options = options || {};
    this.jobs = {};
}
984176
function(options) {
  // task id
  this.id = -1;

  // task name
  this.name = options.name || sNoTaskName;

  // task has no parent
  this.parent = options.parent || null;

  // save run function
  this.run = options.run;

  // create a queue of subtasks to run
  this.subtasks = [];

  // error flag
  this.error = false;

  // state of the task
  this.state = READY;

  // number of times the task has been blocked (also the number
  // of permits needed to be released to continue running)
  this.blocks = 0;

  // timeout id when sleeping
  this.timeoutId = null;

  // no swap time yet
  this.swapTime = null;

  // no user data
  this.userData = null;

  // initialize task
  // FIXME: deal with overflow
  this.id = sNextTaskId++;
  sTasks[this.id] = this;
  if(sVL >= 1) {
    forge.log.verbose(cat, '[%s][%s] init', this.id, this.name, this);
  }
}
1094933
def start(params={})
      id = params.delete(:id) || self.id
      response = Zcloudjp::Client.post("/machines/#{id}/start", self.request_options)
      update_attributes(response.parsed_response)
    end
803560
function (options) {
        options = options || {};
        var accessKeyId = options.accessKeyId || process.env.AWS_ACCESS_KEY_ID,
            secretAccessKey = options.secretAccessKey || process.env.AWS_SECRET_ACCESS_KEY,
            awssum = require('awssum'),
            amazon = awssum.load('amazon/amazon'),
            S3Service = awssum.load('amazon/s3');

        if (!accessKeyId || !secretAccessKey) {
            throw "Error: Must specify the env variables AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY";
        }
        return new S3Service(accessKeyId, secretAccessKey, "ops", amazon.US_EAST_1);
    }
411003
@Override
    public Processor newProcessor(Processor sourceProcessor) {
        PredictionCombinerProcessor newProcessor = new PredictionCombinerProcessor();
        PredictionCombinerProcessor originProcessor = (PredictionCombinerProcessor) sourceProcessor;
        if (originProcessor.getOutputStream() != null) {
            newProcessor.setOutputStream(originProcessor.getOutputStream());
        }
        newProcessor.setSizeEnsemble(originProcessor.getSizeEnsemble());
        return newProcessor;
    }
769616
function start( next ) {
	/* jshint validthis:true */
	cnt += 1;

	this.rid = process.pid + ':' + cnt;

	this.start = null;
	this.end = null;
	this.timer = null;

	this.req = {
		'opts': this._opts,
		'body': this._body
	};
	this.res = {
		'status': null,
		'headers': null,
		'body': null,
		'bytes': 0
	};

	next();
}
165561
function init(options){
	options = util._extend({ssl:null, port:12345}, options);
	var serverWorkers = {}; // save main server sockets
	var clientSocket = []; // save local server socket
	var clientOptions = []; // save optioin obj
	var wsServer;
	if(options.ssl)
		wsServer = require('https').createServer(options.ssl);
	else wsServer = require('http').createServer();
	var io = require('socket.io')(wsServer);
	
	if(options.auth)	
	io.set('authorization', function (handshakeData, callback) {
		if(handshakeData.url.match('username='+options.auth.username+'&password='+options.auth.password))
        	callback(null, true); // error first callback style 
        else callback('no auth', false);
    });

	io.on('connection', function(socket){
		// 0. save server sockets & local socket
		socket.on('init', function(data){
			if(data._type == 'localServer'){
				socket._type = 'localServer';
				if(clientSocket.length>0)
					clientSocket.slice(-1)[0].emit('hold');			
				// then handle new one
				clientSocket.push(socket);
				clientOptions.push(data);
				// inform server the new client
				for(i in serverWorkers)
					serverWorkers[i].emit('client', data);
			}else if(data._type == 'server'){
				socket._type = 'server';
				serverWorkers[socket.id] = socket;
			}else{
				// ignore this connection
			}
		})
		// handle req from server, relay data to client
		socket.on('req', function(data){
			if(clientSocket.length > 0){
				data._sid = socket.id;
				clientSocket.slice(-1)[0].emit('req', data)
			}
		})
		// handle res from client, relay the data to the server
		socket.on('res', function(data){
			if(serverWorkers[data._sid])
				serverWorkers[data._sid].emit('res', data);
		});
		socket.on('disconnect', function(reason){
			if(socket._type == 'localServer'){
				var last = false;
				for(i in clientSocket){
					if(socket.id == clientSocket[i].id){
						if(i == clientSocket.length-1)
							last = true;
						clientSocket.splice(i, 1);
						clientOptions.splice(i,1);
						break;
					}
				}
				if(clientSocket.length > 0 && clientOptions.length > 0){
					if(last)
						clientSocket.slice(-1)[0].emit('back');	
					for(i in serverWorkers)
						serverWorkers[i].emit('client', clientOptions.slice(-1)[0]);
				}
				else
					for(i in serverWorkers)
						serverWorkers[i].emit('client', false);
			}
			else if(socket._type == 'server')
				delete serverWorkers[socket.id];
		});
	});
	wsServer.listen(options.port).on('listening', function(){
		options.listening ? options.listening() : noop();
		//console.log('[NLT] Server is ready on port ' + options.port);
	}).on('error', function(e){
		options.error ? options.error(e) : noop();
		//console.log('[NLT] Setup error', e)
	});
}
1244867
function createHandler(options) {
  /**
   * Client request handler
   * Data from the incoming request (plus options) is forwarded to the AWS module
   */
  return async (ctx) => {
    const { credentials, endpoint, region } = options
    const { rawBody: body, header: headers, method, url: path } = ctx.request

    console.log(chalk.cyan(method, path))

    const params = { body, credentials, endpoint, headers, method, path, region }
    const req = createSignedAWSRequest(params)
    const res = await sendAWSRequest(req)

    ctx.status = 200
    ctx.type = 'application/json'
    ctx.response.header = stripProxyResHeaders(res)
    ctx.body = res.body
  }
}
1210574
async function start() {
  if (server) return server;
  server = express();
  server.use(errorOverlayMiddleware());
  server.use(express.static(path.resolve(__dirname, '../public')));

  // Configure client-side hot module replacement
  const clientConfig = webpackConfig.find(config => config.name === 'client');
  clientConfig.entry.client = ['./tools/lib/webpackHotDevClient']
    .concat(clientConfig.entry.client)
    .sort((a, b) => b.includes('polyfill') - a.includes('polyfill'));
  clientConfig.output.filename = clientConfig.output.filename.replace(
    'chunkhash',
    'hash',
  );
  clientConfig.output.chunkFilename = clientConfig.output.chunkFilename.replace(
    'chunkhash',
    'hash',
  );
  clientConfig.module.rules = clientConfig.module.rules.filter(
    x => x.loader !== 'null-loader',
  );
  clientConfig.plugins.push(new webpack.HotModuleReplacementPlugin());

  // Configure server-side hot module replacement
  const serverConfig = webpackConfig.find(config => config.name === 'server');
  serverConfig.output.hotUpdateMainFilename = 'updates/[hash].hot-update.json';
  serverConfig.output.hotUpdateChunkFilename =
    'updates/[id].[hash].hot-update.js';
  serverConfig.module.rules = serverConfig.module.rules.filter(
    x => x.loader !== 'null-loader',
  );
  serverConfig.plugins.push(new webpack.HotModuleReplacementPlugin());

  // Configure compilation
  await run(clean);
  const multiCompiler = webpack(webpackConfig);
  const clientCompiler = multiCompiler.compilers.find(
    compiler => compiler.name === 'client',
  );
  const serverCompiler = multiCompiler.compilers.find(
    compiler => compiler.name === 'server',
  );
  const clientPromise = createCompilationPromise(
    'client',
    clientCompiler,
    clientConfig,
  );
  const serverPromise = createCompilationPromise(
    'server',
    serverCompiler,
    serverConfig,
  );

  // https://github.com/webpack/webpack-dev-middleware
  server.use(
    webpackDevMiddleware(clientCompiler, {
      publicPath: clientConfig.output.publicPath,
      logLevel: 'silent',
      watchOptions,
    }),
  );

  // https://github.com/glenjamin/webpack-hot-middleware
  server.use(webpackHotMiddleware(clientCompiler, { log: false }));

  let appPromise;
  let appPromiseResolve;
  let appPromiseIsResolved = true;
  serverCompiler.hooks.compile.tap('server', () => {
    if (!appPromiseIsResolved) return;
    appPromiseIsResolved = false;
    // eslint-disable-next-line no-return-assign
    appPromise = new Promise(resolve => (appPromiseResolve = resolve));
  });

  let app;
  server.use((req, res) => {
    appPromise
      .then(() => app.handle(req, res))
      .catch(error => console.error(error));
  });

  function checkForUpdate(fromUpdate) {
    const hmrPrefix = '[\x1b[35mHMR\x1b[0m] ';
    if (!app.hot) {
      throw new Error(`${hmrPrefix}Hot Module Replacement is disabled.`);
    }
    if (app.hot.status() !== 'idle') {
      return Promise.resolve();
    }
    return app.hot
      .check(true)
      .then(updatedModules => {
        if (!updatedModules) {
          if (fromUpdate) {
            console.info(`${hmrPrefix}Update applied.`);
          }
          return;
        }
        if (updatedModules.length === 0) {
          console.info(`${hmrPrefix}Nothing hot updated.`);
        } else {
          console.info(`${hmrPrefix}Updated modules:`);
          updatedModules.forEach(moduleId =>
            console.info(`${hmrPrefix} - ${moduleId}`),
          );
          checkForUpdate(true);
        }
      })
      .catch(error => {
        if (['abort', 'fail'].includes(app.hot.status())) {
          console.warn(`${hmrPrefix}Cannot apply update.`);
          delete require.cache[require.resolve('../build/server')];
          // eslint-disable-next-line global-require, import/no-unresolved
          app = require('../build/server').default;
          console.warn(`${hmrPrefix}App has been reloaded.`);
        } else {
          console.warn(
            `${hmrPrefix}Update failed: ${error.stack || error.message}`,
          );
        }
      });
  }

  serverCompiler.watch(watchOptions, (error, stats) => {
    if (app && !error && !stats.hasErrors()) {
      checkForUpdate().then(() => {
        appPromiseIsResolved = true;
        appPromiseResolve();
      });
    }
  });

  // Wait until both client-side and server-side bundles are ready
  await clientPromise;
  await serverPromise;

  const timeStart = new Date();
  console.info(`[${format(timeStart)}] Launching server...`);

  // Load compiled src/server.js as a middleware
  // eslint-disable-next-line global-require, import/no-unresolved
  app = require('../build/server').default;
  appPromiseIsResolved = true;
  appPromiseResolve();

  // Launch the development server with Browsersync and HMR
  await new Promise((resolve, reject) =>
    browserSync.create().init(
      {
        // https://www.browsersync.io/docs/options
        server: 'src/server.js',
        middleware: [server],
        open: !process.argv.includes('--silent'),
        ...(isDebug ? {} : { notify: false, ui: false }),
      },
      (error, bs) => (error ? reject(error) : resolve(bs)),
    ),
  );

  const timeEnd = new Date();
  const time = timeEnd.getTime() - timeStart.getTime();
  console.info(`[${format(timeEnd)}] Server launched after ${time} ms`);
  return server;
}
78633
def init(options = {})
      return if @initialized_hardware

      defaults = {
        device: ENV["SMALRUBOT_DEVICE"] || nil,
        baud: 19_200,
      }
      opt = Util.process_options(options, defaults)

      txrx = Smalrubot::TxRx.new(opt)
      begin
        world.board = Smalrubot::Board.new(txrx)
        @initialized_hardware = true
      rescue Exception
        Util.print_exception($!)
        @failed_init_hardware = true
      end
    end
1157841
function common_start(params) {
      params.umecob = params.umecob || umecob;
      var configs = get_current_setting(params);
      /* execute start functions */
      for (var i in configs.start) {
        configs.start[i].call(configs, params);
      }
      return configs;
    }
649680
function Startline(options) {

  event.call(this);
  var self = this; // closure
  var temp = '';
  this.options = options;
  this.head = 0;
  this.tail = 0;
  this.line = 0;
  this._stream = null;

  if (options.rc4 || options.autokey) { // cipher
    var cipher;
    this._stream = interfac(this.options, options.start, options.end);
    if (options.rc4) {
      cipher = require('arc4')('arc4', String(options.rc4), options.lodash);
      this._stream.on('data', function(callbacks) {

        var callback = cipher.decodeBuffer(callbacks).toString();
        for (var i = 0, ii = callback.length; i < ii; ++i) {
          if (callback[i] === eol) {
            self.tail = self.head + self.line;
            self.head = self.tail + temp.length;
            self.emit('line', temp);
            self.line = 1;
            temp = '';
          } else {
            temp += callback[i];
          }
        }
        if (temp.length > 0) {
          self.tail = self.head + self.line;
          self.head = self.tail + temp.length;
          self.emit('line', temp);
          self.line = 1;
        }
        return;
      });

    } else {
      cipher = require('autokey')(String(options.autokey), options.lodash);
      this._stream.on('data', function(callbacks) {

        var callback = cipher.decodeBuffer(callbacks).toString();
        for (var i = 0, ii = callback.length; i < ii; ++i) {
          if (callback[i] === eol) {
            self.tail = self.head + self.line;
            self.head = self.tail + temp.length;
            self.emit('line', temp);
            self.line = 1;
            temp = '';
          } else {
            temp += callback[i];
          }
        }
        if (temp.length > 0) {
          self.tail = self.head + self.line;
          self.head = self.tail + temp.length;
          self.emit('line', temp);
          self.line = 1;
        }
        return;
      });
    }

  } else if (options.end >= 0) { // no cipher, EOF
    this._stream = interfac(this.options, options.start, options.end);
    this._stream.on('data', function(callbacks) {

      var callback = callbacks.toString();
      for (var i = 0, ii = callback.length; i < ii; ++i) {
        if (callback[i] === eol) {
          self.tail = self.head + self.line;
          self.head = self.tail + temp.length;
          self.emit('line', temp);
          self.line = 1;
          temp = '';
        } else {
          temp += callback[i];
        }
      }
      if (temp.length > 0) {
        self.tail = self.head + self.line;
        self.head = self.tail + temp.length;
        self.emit('line', temp);
        self.line = 1;
      }
      return;
    });

  } else { // file
    this._stream = readlin(this.options, options.start, options.end);
    this._stream.on('line', function(callback) {

      self.tail = self.head + self.line;
      self.head = self.tail + callback.length;
      self.emit('line', callback);
      self.line = 1;
      return;
    });
  }

  // standard events
  this._stream.on('pause', function() {

    return self.emit('pause');
  }).on('resume', function() {

    return self.emit('resume');
  }).on('open', function(fd) {

    return self.emit('open', fd);
  }).on('close', function() {

    return self.emit('close');
  }).on('end', function() {

    return self.emit('end');
  }).on('error', function(err) {

    return self.emit('error', err);
  });
}
101898
function init(options) {
  options = options || {}
  var port = options.port || 6466
  global.client = global.client || socketIOClient(`http://localhost:${port}`)
  client = global.client
  log.debug(`Started global js socketIO client for ${process.env.ADAPTER} at ${port}`)
  client.emit('join', ioid) // first join for serialization
  client.on('disconnect', client.disconnect)
  client.on('take', hasher.handle) // add listener
  
  // add methods
  client.pass = pass
  client.clientPass = clientPass
  return client
}
1178699
function start( next, isHeadless, options ) {
    function seleniumStarted() {
        console.log( 'seleniumrc webdriver ready on ' + options.host + ':' + options.port );
        started = true;
        starting = false;
        if ( typeof next === 'function' ) {
            return next();
        }
    }

    if ( started ) {
        return next(console.log('already started'));
    }

    if ( isHeadless ) {
        selOptions.push ( '-role');
        selOptions.push ( 'hub');
    }

    selOptions.push ( '-host' );
    selOptions.push ( options.host );

    selOptions.push ( '-port' );
    selOptions.push ( options.port );

    if ( options.timeout) {
        selOptions.push( '-timeout' );
        selOptions.push( options.timeout );
    }

    if ( options.maxSession) {
        selOptions.push( '-maxSession' );
        selOptions.push( options.maxSession );
    }

    var spawnOptions = options['cwd'] ? {cwd: options['cwd']} : undefined;
    seleniumServerProcess = spawn( 'java', selOptions, spawnOptions );
    // selenium webdriver has a port prober in it which could be factored in.
    seleniumServerProcess.on('uncaughtException', function(err) {
        if(err.errno === 'EADDRINUSE' ){
            console.log ('PORT already IN USE, assume selenium running');
            next();
        } else {
            console.trace(err);
            process.exit(1);
        }
    });

    seleniumServerProcess.stderr.setEncoding('utf8');
    // parse procee output until server is actually ready, otherwise next task will break
    seleniumServerProcess.stderr.on('data', function(data) {
        var errMsg;
        data = data.trim();
        if ( isHeadless  ) {
            // check for grid started, which is outputted to standard error
            if ( data.indexOf( 'Selenium Grid hub is up and running' ) > -1 ) {
//                console.log ('selenium hub ready');
                return startPhantom(next, options);
            } else if ( data.indexOf ('Address already in use') > -1 ) {
                // throw error if already started
                 errMsg = 'FATAL ERROR starting selenium: ' + data + ' maybe try killall -9 java';
                throw errMsg;
            }
        } else if ( data.indexOf( 'Selenium Server is up and running' ) > -1 ) {
            // seems selenium 2.43.1 now outputs logs to standard error too so listening to standard out is redundant?
            seleniumStarted();
        } else if ( !started &&  data.indexOf( 'Selenium Server is up and running') > -1  ) {
            // as of 2.471 this nice clear message appears
            seleniumStarted();
        } else if ( data &&
             // throw error if something unexpected happens
             data.indexOf('org.openqa.grid.selenium.GridLauncher main') === -1 &&
             data.indexOf('Setting system property') === -1 &&
             data.indexOf('INFO') === -1 &&
             data.indexOf('WARNING') === -1 &&
             !started
              ) {
            errMsg = 'FATAL ERROR starting selenium: ' + data+ ' is java runtime installed?';
            throw errMsg;
        }
    });
    seleniumServerProcess.stdout.setEncoding('utf8');
    // seems selenium 2.43.1 now outputs logs to standard error too so this is now redundant
    // will leave for now. Tested on mac and ubuntu
    seleniumServerProcess.stdout.on('data', function( msg ) {
        console.log('STDOUT' , msg);
        // monitor process output for ready message, most recent version gives a nice clear message on standard error
        // but have left java trigger for support for older seleniums as can select in config
        if ( !started && ( msg.indexOf( 'Started org.openqa.jetty.jetty.servlet.ServletHandler' ) > -1  )) {
            seleniumStarted();
        }
    });

}
960126
function createWorkerPool(options)
{
	var clientSet = new Set();
	var clientArr = [];
	var counter = 0;
	var logConnection = getOption(options, 'logConnection', true);
	
	function resetClients()
	{
		if ( logConnection )
		{
			console.log('CLIENTS ' + clientSet.size);
		}
		clientArr = [];
		if ( clientSet.size > 0 )
		{
			clientSet.forEach((client) => clientArr.push(client));
		}
	}
	
	function addClient(client)
	{
		clientSet.add(client);
		resetClients();
	}
	
	function deleteClient(client)
	{
		if ( clientSet.has(client) )
		{
			clientSet.delete(client);
			resetClients();
		}
	}
	
	function getNextClient()
	{
		var idx = counter++ % clientArr.length;
		return clientArr[idx];
	}
	
	function sendRequest(cmd, args, body, timeout, callback)
	{
		if ( clientArr.length === 0 )
		{
			callback({code: '500', tid: 0, args: ['no_workers'], body: null, isValid: true});
		}
		else
		{
			getNextClient().sendRequest(cmd, args, body, timeout, callback);
		}
	}
	
	function sendMessage(cmd, tid, args, body)
	{
		if ( clientArr.length > 0 )
		{
			getNextClient().sendMessage(cmd, tid, args, body);
		}
	}
	
	function createSession(protocol, session_args)
	{
		if ( clientArr.length > 0 )
		{
			return getNextClient().createSession(protocol, session_args);
		}
		else
		{
			throw new Error('There is no worker(s) for session creating');
		}
	}
	
	function getPoolSize()
	{
		return clientSet.size;
	}
	
	return {
		addClient: addClient,
		deleteClient: deleteClient,
		getNextClient: getNextClient,
		sendRequest: sendRequest,
		sendMessage: sendMessage,
		createSession: createSession,
		getPoolSize: getPoolSize
	};
}
1372096
def add_processor(self, processor_instance: Processor, priority=0) -> None:
        
        assert issubclass(processor_instance.__class__, Processor)
        processor_instance.priority = priority
        processor_instance.world = self
        self._processors.append(processor_instance)
        self._processors.sort(key=lambda proc: proc.priority, reverse=True)
1014956
def init_options_parser(options)
      OptionParser.new do |opts|
        opts.banner = "Usage:\n"\
        "\tsshez add <alias> (role@host) [options]\n"\
        "\tsshez connect <alias>\n"\
        "\tsshez remove <alias>\n\tsshez list\n"\
        "\tsshez reset\n"
        opts.separator ''
        opts.separator 'Specific options:'
        options_for_add(opts, options)
        # signals that we are in testing mode
        opts.on('-t', '--test', 'Writes nothing') {options.test = true}
        common_options(opts, options)
      end # OptionParser.new
    end