Create a LatchedObserver with the given indexed callback function(s).
166214
public static <T> LatchedObserver<T> createIndexed(Action2<? super T, ? super Integer> onNext, Action1<? super Throwable> onError) {
        return createIndexed(onNext, onError, new CountDownLatch(1));
    }
176606
function _suspendBeforeObserver(obj, path, target, method, callback) {
      return suspendListener(obj, beforeEvent(path), target, method, callback);
    }
811920
function makeAsync(cb) {
    return function () {
        var args = arguments;
        process.nextTick(function () {
            cb.apply(null, args);
        });
    };
}
799047
public static <T> LatchedObserver<T> create(Action1<? super T> onNext) {
        return create(onNext, new CountDownLatch(1));
    }
1076353
def register_callback(self, key):
        """"""
        if self.pending_callbacks is None:
            # Lazily initialize the old-style YieldPoint data structures.
            self.pending_callbacks = set()
            self.results = {}
        if key in self.pending_callbacks:
            raise KeyReuseError("key %r is already pending" % (key,))
        self.pending_callbacks.add(key)
53457
function callbackOnce(err, arg) {
            var cb = callback;
            callback = null;
            if (cb) { cb(err, arg); }
        }
1154718
function StatelessServerChannel(server, readableFactory, opts) {
  ServerChannel.call(this, server, opts);

  this._writable = undefined;
  var self = this;
  var readable;

  process.nextTick(function () {
    // Delay listening to allow handlers to be attached even if the factory is
    // purely synchronous.
    readable = readableFactory.call(self, function (err, writable) {
      process.nextTick(function () {
        // We delay once more here in case this call is synchronous, to allow
        // the readable to always be populated first.
        if (err) {
          onFinish(err);
          return;
        }
        self._writable = writable.on('finish', onFinish);
        self.emit('_writable');
      });
    }).on('data', onRequest).on('end', onEnd);
  });


  function onRequest(obj) {
    var id = obj.id;
    var buf = Buffer.concat(obj.payload);
    var err;
    try {
      var parts = readHead(HANDSHAKE_REQUEST_TYPE, buf);
      var hreq = parts.head;
      var adapter = self._getAdapter(hreq);
    } catch (cause) {
      err = toRpcError('INVALID_HANDSHAKE_REQUEST', cause);
    }

    var hres = self._createHandshakeResponse(err, hreq);
    self.emit('handshake', hreq, hres);
    if (err) {
      done(self._encodeSystemError(err));
    } else {
      self._receive(parts.tail, adapter, done);
    }

    function done(resBuf) {
      if (!self.destroyed) {
        if (!self._writable) {
          self.once('_writable', function () { done(resBuf); });
          return;
        }
        self._writable.write({
          id: id,
          payload: [HANDSHAKE_RESPONSE_TYPE.toBuffer(hres), resBuf]
        });
      }
      if (self._writable && self._endWritable) {
        self._writable.end();
      }
    }
  }

  function onEnd() { self.destroy(); }

  function onFinish(err) {
    readable
      .removeListener('data', onRequest)
      .removeListener('end', onEnd);
    self.destroy(err || true);
  }
}
209424
def _create_indexer(cls, name, indexer):
        """"""
        if getattr(cls, name, None) is None:
            _indexer = functools.partial(indexer, name)
            setattr(cls, name, property(_indexer, doc=indexer.__doc__))
993344
public static <ReqT, RespT> Iterator<RespT> blockingServerStreamingCall(
      Channel channel, MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, ReqT req) {
    ThreadlessExecutor executor = new ThreadlessExecutor();
    ClientCall<ReqT, RespT> call = channel.newCall(method, callOptions.withExecutor(executor));
    BlockingResponseStream<RespT> result = new BlockingResponseStream<>(call, executor);
    asyncUnaryRequestCall(call, req, result.listener(), true);
    return result;
  }
1329413
function pubServer(opts) {

  if (!(this instanceof pubServer)) return new pubServer(opts);
  events.EventEmitter.call(this);

  var server = this;

  // pass platform-specific ./node_modules path to resolve-opts for builtin packages
  server.opts = opts = require('pub-resolve-opts')(opts, path.join(__dirname, 'node_modules'));

  opts.production  = opts.production || (process.env.NODE_ENV === 'production');
  opts.port        = opts.port       || process.env.PORT || '3001';
  opts.appUrl      = opts.appUrl     || process.env.APP  || ('http://localhost:' + opts.port);

  server.run       = run;

  var generator = server.generator = require('pub-generator')(opts);

  u.each(opts.serverPlugins.reverse(), function(plugin) {
    debug('server plugin:', plugin.inspect());
    require(plugin.path)(server);
  });

  u.each(opts.generatorPlugins.reverse(), function(plugin) {
    debug('generator plugin:', plugin.path, plugin.inspect());
    require(plugin.path)(generator);
  });

  var log = opts.log;

  //--//--//--//--//--//--//--//--//--//--//--//

  function run() {
    generator.load(function(err) {
      if (err) return log(err);

      if (opts.outputOnly) {
        generator.outputPages(function(err, result) {
          if (err) { log(err); }
          log('output %s generated pages', u.flatten(result).length);
        });

        var statics = require('./server/serve-statics')(opts, function(){
          statics.outputAll();
        });
        require('./server/serve-scripts')(opts).outputAll(generator);
        generator.unload();
        return;
      }

      if (opts.logPages) {
        generator.logPages();
        generator.unload();
        return;
      }

      require('./server/watch-sources')(generator);
      generator.listen(true);

      if (!opts['no-server']) { expressApp(); }
    });
  }

  function expressApp() {

    server.app =  require('express')();
    server.http = require('http').Server(server.app);
    require('./server/serve-sockets')(server);

    server.app.disable('x-powered-by');

    // log(err) shouldn't throw anymore
    log.logger.noErrors = true;

    // sessions come with optional redis logger
    server.sessions = require('pub-serve-sessions')(server);
    log('starting up', opts.appUrl);

    // other default middleware
    var bodyParser = require('body-parser');
    server.app.use(bodyParser.json());
    server.app.use(bodyParser.urlencoded({ extended: false }));
    server.app.use(require('compression')());

    server.emit('init-app-first');
    server.sessions.authorizeRoutes();

    if (!opts.staticOnly) {
      require('./server/serve-pages')(server);
      server.scripts = require('./server/serve-scripts')(opts).serveRoutes(server);
    }
    server.statics = require('./server/serve-statics')(opts).serveRoutes(server);

    server.emit('init-app-last');

    require('./server/handle-errors')(server);

    server.http.listen(opts.port);
    log('listening on port', opts.port);

    process.on('SIGTERM', function() {
      log('shutting down');
      server.http.close(function() {
        generator.unload();
        server.emit('shutdown');
        process.exit();
      });
    });

  }

}
648995
def create_authserver(self, domainid, data):
        """"""
        return self.api_call(
            ENDPOINTS['authservers']['new'],
            dict(domainid=domainid),
            body=data)
225688
function createSyncer (config, eventBus, web3, queue, eventsRegistry, indexer) {
  debug.enabled = config.debug

  const deferred = pDefer()
  const gotBestBlockPromise = deferred.promise

  let bestBlock

  const { getTransactions, getTransactionStream } = indexer

  eventBus.once('coin-block', function (header) {
    bestBlock = header.number
    debug('Got best block', bestBlock)
    deferred.resolve()
  })

  function subscribeCoinTransactions (fromBlock, address) {
    let shallResync = false
    let resyncing = false
    let bestSyncBlock = fromBlock

    const { symbol, displayName } = config

    getTransactionStream(address)
      .on('data', queue.addTransaction(address))
      .on('resync', function () {
        debug(`Shall resync ${symbol} transactions on next block`)
        shallResync = true
      })
      .on('error', function (err) {
        debug(`Shall resync ${symbol} transactions on next block`)
        shallResync = true
        eventBus.emit('wallet-error', {
          inner: err,
          message: `Failed to sync ${displayName} transactions`,
          meta: { plugin: 'explorer' }
        })
      })

    // Check if shall resync when a new block is seen, as that is the
    // indication of proper reconnection to the Ethereum node.
    eventBus.on('coin-block', function ({ number }) {
      if (shallResync && !resyncing) {
        resyncing = true
        shallResync = false
        // eslint-disable-next-line promise/catch-or-return
        getTransactions(bestSyncBlock, number, address)
          .then(function (transactions) {
            const { length } = transactions
            debug(`${length} past ${symbol} transactions retrieved`)
            transactions.forEach(queue.addTransaction(address))
            bestSyncBlock = number
          })
          .catch(function (err) {
            shallResync = true
            eventBus.emit('wallet-error', {
              inner: err,
              message: 'Failed to resync transactions',
              meta: { plugin: 'explorer' }
            })
          })
          .then(function () {
            resyncing = false
          })
      } else if (!resyncing) {
        bestSyncBlock = number
        bestBlock = number
      }
    })
  }

  function getPastCoinTransactions (fromBlock, toBlock, address) {
    const { symbol } = config

    return getTransactions(fromBlock, toBlock, address)
      .then(function (transactions) {
        debug(`${transactions.length} past ${symbol} transactions retrieved`)
        return Promise.all(transactions.map(queue.addTransaction(address)))
          .then(() => toBlock)
      })
  }

  const getPastEvents = (fromBlock, toBlock, address) =>
    Promise.all(eventsRegistry.getAll().map(function (registration) {
      const {
        contractAddress,
        abi,
        eventName,
        filter,
        metaParser,
        minBlock = 0
      } = registration(address)

      const contract = new web3.eth.Contract(abi, contractAddress)

      // Ignore missing events
      if (!contract.events[eventName]) {
        debug(`Could not get past events for ${eventName}`)
        return Promise.resolve()
      }

      return contract.getPastEvents(eventName, {
        fromBlock: Math.max(fromBlock, minBlock),
        toBlock: Math.max(toBlock, minBlock),
        filter
      })
        .then(function (events) {
          debug(`${events.length} past ${eventName} events retrieved`)
          return Promise.all(
            events.map(queue.addEvent(address, metaParser))
          )
        })
    }))

  const subscriptions = []

  function subscribeEvents (fromBlock, address) {
    eventsRegistry.getAll().forEach(function (registration) {
      let shallResync = false
      let resyncing = false
      let bestSyncBlock = fromBlock

      const {
        contractAddress,
        abi,
        eventName,
        filter,
        metaParser
      } = registration(address)

      const contract = new web3.eth.Contract(abi, contractAddress)

      // Ignore missing events
      if (!contract.events[eventName]) {
        debug('Could not subscribe: event not found', eventName)
        return
      }

      // Get past events and subscribe to incoming events
      const emitter = contract.events[eventName]({ fromBlock, filter })
        .on('data', queue.addEvent(address, metaParser))
        .on('changed', queue.addEvent(address, metaParser))
        .on('error', function (err) {
          debug('Shall resync events on next block')
          shallResync = true
          eventBus.emit('wallet-error', {
            inner: err,
            message: `Subscription to event ${eventName} failed`,
            meta: { plugin: 'explorer' }
          })
        })
      subscriptions.push(emitter)

      // Resync on new block or save it as best sync block
      eventBus.on('coin-block', function ({ number }) {
        if (shallResync && !resyncing) {
          resyncing = true
          shallResync = false
          // eslint-disable-next-line promise/catch-or-return
          contract.getPastEvents(
            eventName,
            { fromBlock: bestSyncBlock, filter }
          )
            .then(function (events) {
              debug(`${events.length} past ${eventName} events retrieved`)
              events.forEach(queue.addEvent(address, metaParser))
            })
            .catch(function (err) {
              shallResync = true
              eventBus.emit('wallet-error', {
                inner: err,
                message: `Failed to resync event ${eventName}`,
                meta: { plugin: 'explorer' }
              })
            })
            .then(function () {
              resyncing = false
            })
        } else if (!resyncing) {
          bestSyncBlock = number
          bestBlock = number
        }
      })
    })
  }

  const syncTransactions = (fromBlock, address) =>
    gotBestBlockPromise
      .then(function () {
        debug('Syncing', fromBlock, bestBlock)
        subscribeCoinTransactions(bestBlock, address)
        subscribeEvents(bestBlock, address)
        return Promise.all([
          getPastCoinTransactions(fromBlock, bestBlock, address),
          getPastEvents(fromBlock, bestBlock, address)
        ])
      })
      .then(function ([syncedBlock]) {
        bestBlock = syncedBlock
        return syncedBlock
      })

  const refreshAllTransactions = address =>
    gotBestBlockPromise
      .then(() =>
        Promise.all([
          getPastCoinTransactions(0, bestBlock, address),
          getPastEvents(0, bestBlock, address)
        ])
          .then(function ([syncedBlock]) {
            bestBlock = syncedBlock
            return syncedBlock
          })
      )

  function stop () {
    subscriptions.forEach(function (subscription) {
      subscription.unsubscribe(function (err) {
        if (err) {
          debug('Could not unsubscribe from event', err.message)
        }
      })
    })
  }

  return {
    getPastCoinTransactions,
    getPastEvents,
    refreshAllTransactions,
    stop,
    syncTransactions
  }
}
1349144
function createServer() {
  function app(req, res, next) {
    app.handle(req, res, next);
  }
  app.method = '*';
  merge(app, proto);
  merge(app, EventEmitter.prototype);
  app.stack = [];
  app.params = [];
  app._cachedEvents = [] ;
  app.routedMethods = {} ;
  app.locals = Object.create(null);
  for (var i = 0; i < arguments.length; ++i) {
    app.use(arguments[i]);
  }

  //create methods app.invite, app.register, etc..
  methods.forEach((method) => {
    app[method.toLowerCase()] = app.use.bind(app, method.toLowerCase()) ;
  }) ;

  //special handling for cdr events
  app.on = function(event, listener) {
    if (0 === event.indexOf('cdr:')) {
      if (app.client) {
        app.client.on(event, function() {
          var args = Array.prototype.slice.call(arguments) ;
          EventEmitter.prototype.emit.apply(app, [event].concat(args)) ;
        }) ;
      }
      else {
        this._cachedEvents.push(event) ;
      }
    }
    //delegate all others to standard EventEmitter prototype
    return EventEmitter.prototype.addListener.call(app, event, listener) ;
  } ;

  return app;
}
343940
function createServer(listen, opt) {

  if (!listen) {
    throw new TypeError('listen required');
  }
  var options = opt || Object.create(null);
  var my = {
    keepalive: Number(options.keepalive) || 2000,
    callback: typeof options.callback === 'function' ? options.callback : false,
    http: false,
    https: false
  };
  if (typeof options.http === 'object') {
    my.http = {
      port: Number(options.http.port) || 3000,
      host: String(options.http.host || '127.0.0.1')
    };
  }
  if (typeof options.https === 'object') {
    my.https = options.https;
    my.https.port = Number(options.https.port) || 3000;
    my.https.host = String(options.https.host || '127.0.0.1');
  }

  var hosts = Object.create(null);
  var server = net.createServer(function(sock) {

    sock.setKeepAlive(true, my.keepalive); // https://en.wikipedia.org/wiki/Keepalive
    sock.on('data', function(buff) {

      if (sock._id) {
        hosts[sock._id] = {
          state: sock.readyState,
          beat: Date.now()
        };
      } else if (buff.length > 1) { // set client id
        var _id = String(buff);
        hosts[_id] = {
          state: sock.readyState,
          beat: Date.now()
        };
        sock._id = _id;
      }
      return;

    }).on('close', function(had_error) {

      if (sock._id) {
        hosts[sock._id] = {
          state: sock.readyState,
          beat: Date.now()
        };
      }
      // error hook [with client id]
      return my.callback !== false ? my.callback(had_error, sock._id) : null;
    });
  });

  if (options.host && typeof listen === 'number') { // tpc only
    server.listen(listen, options.host);
  } else {
    server.listen(listen);
  }

  if (my.http || my.https) {
    var web = function(req, res) {

      var out = '';
      res.setHeader('Content-Type', 'application/json; charset=utf-8');
      var url = decodeURI(req.url);
      url = url.substr(1, url.length);
      if (url === '') {
        out = JSON.stringify(hosts);
      } else if (hosts[url] !== undefined) {
        out = JSON.stringify(hosts[url]);
      } else {
        res.statusCode = 404;
      }
      return res.end(out);
    };
    if (my.http) {
      require('http').createServer(web).listen(my.http.port, my.http.host);
    }
    if (my.https) {
      require('https').createServer(my.https, web).listen(my.https.port,
        my.https.host);
    }
  }

  server._hosts = hosts; // hosts reference
  return server;
}
1178973
def make_server(host, port, app=None, threaded=False, processes=1,
                request_handler=None, passthrough_errors=False,
                ssl_context=None):
    
    if threaded and processes > 1:
        raise ValueError("cannot have a multithreaded and "
                         "multi process server.")
    elif threaded:
        return ThreadedWSGIServer(host, port, app, request_handler,
                                  passthrough_errors, ssl_context)
    elif processes > 1:
        return ForkingWSGIServer(host, port, app, processes, request_handler,
                                 passthrough_errors, ssl_context)
    else:
        return BaseWSGIServer(host, port, app, request_handler,
                              passthrough_errors, ssl_context)
416627
def create_process(daemon, name, callback, *callbackParams):
    
    bp = Process(daemon=daemon, name=name, target=callback, args=callbackParams)
    return bp
780622
def objectify(func):
    

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        try:
            payload = func(*args, **kwargs)
        except requests.exceptions.ConnectionError as e:
            raise InternetConnectionError(e)
        return EventbriteObject.create(payload)
    return wrapper