Get a handler that calls Jenkins API to display executors information per computer

@param {Function} cb: callback for argument handling
@return Jenkins API handler function
332859
function executor(cb) {
  return function (args) {
    function resultCb(result) {

      var computers = result.computer;

      if (_.isEmpty(computers)) {
        console.log(text.__('No executor found'));
      } else {

        var data = Jenkins.executorSummary(computers);

        _.keys(data).forEach(function (computer) {
          console.log('+ %s | %s', computer, data[computer].summary);
          data[computer].executors.forEach(function (executor) {
            if (!executor.idle) {
              console.log('  - %s | %s%%s', executor.name, executor.progress, (executor.stuck) ? text.__(' stuck!') : '');
            }
          });
        });

      }
    }
    function jenkinsCb(jenkins) {
      jenkins.computer(cli.exitCb(null, resultCb));
    }
    cb(args, jenkinsCb);
  };
}
1110885
function workerMessageHandler(e) {
  const msg = e.data;
  var cb;

  SHOULD_LOG && console.log("Worker received message: " + JSON.stringify(msg));

  switch (msg.event) {
    case "connInit":
      workerInitialized = true;
      workerQueue.forEach(workerInvoke);
      workerQueue = [];
      break;

    case "connStatus":
      const response = msg.data || {};
      const statusCode = response.status;
      if (connStatus[msg.conn]) {
        switch (statusCode) {
          case 200:
            connStatus[msg.conn].ready = true;
            break;
          case 401: // authorization error, need to log in
            connStatus[msg.conn].ready = false;
            connStatus[msg.conn].user = null;
            connStatus[msg.conn].anonymous = true;
            break;
          default:
            console.warn("Invalid connection response status: " + JSON.stringify(response));
            break;
        }
      }
      break;

    case "connClosed":
      cb = callbackRegistry[msg.ref];
      if (cb) {
        delete callbackRegistry[msg.ref];
        cb(msg.data);
      }
      break;

    case "connLogout":
      cb = callbackRegistry[msg.ref];
      if (cb) {
        delete callbackRegistry[msg.ref];
        cb(msg.data);
      }
      break;

    case "setState":
      const comp = componentIdx[msg.ref];
      if (comp) {
        comp.setState(msg.data);
      } else {
        SHOULD_LOG && console.warn("Component no longer registered: " + msg.ref);
      }
      break;

    case "remoteInvoke":
      // check for a callback
      cb = callbackRegistry[msg.ref];
      if (cb) {
        delete callbackRegistry[msg.ref];
        cb(msg.data);
      }
      break;

    case "login":
      // if login successful, update conn's connStatus
      if (msg.data.status === 200) {
        connStatus[msg.conn].token = msg.data.body.token;
        connStatus[msg.conn].user = msg.data.body.user;
        connStatus[msg.conn].anonymous = msg.data.body.anonymous;
      }
      // if there was a callback passed to login(), execute
      cb = callbackRegistry[msg.ref];
      if (cb) {
        delete callbackRegistry[msg.ref];
        cb(msg.data);
      }
      break;

    default:
      SHOULD_LOG && console.warn("Unreconized event from worker: " + msg.event + ". Full message: " + JSON.stringify(msg));
      break;
  }
  return;
}
376333
function isErrorHandler (cb) {
  var str = cb.toString()
  var args = str.split('(')[1].split(')')[0].split(',')
  return args.length === 4
}
1147749
function (cmd, callback) {
    debug('called a custom command handler');
    console.log('Is your use case not solvable without a custom command handling? Sagas? Micro-Services?');

    var self = this;

    function _handle (aggId) {
      var concatenatedId = self.getConcatenatedId(aggId, cmd);

      var isFirst = !self.getNextCommandInQueue(concatenatedId);

      self.queueCommand(concatenatedId, cmd, callback);

      if (!isFirst) {
        return;
      }

      (function handleNext (aggregateId, c) {
        var concId = self.getConcatenatedId(aggregateId, c);
        var cmdEntry = self.getNextCommandInQueue(concId);
        if (cmdEntry) {
          if (cmdEntry.callback.length > 2) {
            self.cmdHndlFn(aggregateId, cmdEntry.command, self, function (err, evts, aggData, meta) {
              self.removeCommandFromQueue(concId, cmdEntry.command);
              handleNext(aggregateId, cmdEntry.command);
              cmdEntry.callback(err, evts, aggData, meta);
            });
            return;
          }
          self.cmdHndlFn(aggregateId, cmdEntry.command, self, function (err, evts) {
            self.removeCommandFromQueue(concId, cmdEntry.command);
            handleNext(aggregateId, cmdEntry.command);
            cmdEntry.callback(err, evts);
          });
        }
      })(aggId, cmd);
    }

    if (dotty.exists(cmd, this.definitions.command.aggregateId)) {
      return _handle(dotty.get(cmd, this.definitions.command.aggregateId));
    }

    debug('no aggregateId in command, so generate a new one');

    this.getNewAggregateId(cmd, function (err, id) {
      if (err) {
        debug(err);
        return callback(err);
      }

      return _handle(id);
    });
  }
212853
function getScript(url, async, cb) {
    if (typeof async === 'function') {
      cb = async;
      async = false;
    }

    var el = document.createElement('script');

    // Script attributes
    el.type = 'text/javascript';
    el.src = url;

    // Should the script be loaded asynchronously?
    if (async)
      el.async = true;

    // Defining callbacks
    el.onload = el.onreadystatechange = function() {
      if ((!this.readyState ||
            this.readyState == 'loaded' ||
            this.readyState == 'complete')) {
        el.onload = el.onreadystatechange = null;

        // Removing element from head
        artoo.mountNode.removeChild(el);

        if (typeof cb === 'function')
          cb();
      }
    };

    // Appending the script to head
    artoo.mountNode.appendChild(el);
  }
625132
function CBObserver() {
    
    var EVENT = 'interval',
        watched = [],
        listeners = [],
        intervals = {},
        self = this;
    
    /**
     * Watch a circuit breaker
     *
     * @param {CircuitBreaker} cb - The circuit breaker on which we'll listen the 'interval' event.
     */
    this.watch = function(cb) {
        if (watched.indexOf(cb) > -1) {
            return;
        }
        watched.push(cb);
        var name = cb.getName();
        if (!(name in intervals)) {
            intervals[name] = [];
        }
        var listener = buildOnInterval(name);
        listeners.push(listener);
        cb.on(EVENT, listener);
    };
    
    /**
     * Stop watching this circuit breaker
     *
     * @param {CircuitBreaker} cb
     */
    this.unwatch = function(cb) {
        var index = watched.indexOf(cb);
        if (index > -1) {
            watched.splice(index, 1);
            var arr = listeners.splice(index, 1);
            cb.removeListener(EVENT, arr[0]);
        }
    };

    function buildOnInterval(cb) {
        return function(interval) {
            intervals[cb].push(interval);
            emitIfNecessary();
        };
    }

    function emitIfNecessary() {
        for (var name in intervals) {
            var cnt = intervals[name].length;
            if (cnt > 1) {
                doEmit();
                return;
            } else if (cnt === 0) {
                return false;
            }
        }
        doEmit();
    }
    
    function doEmit() {
        var data = intervals;
        intervals = {};
        for (var name in data) {
            intervals[name] = [];
        }

        /**
         * Batch event.  The keys of the object are the names of the circuit breakers.
         * The values of the object are arrays of {@link CircuitBreaker#event:interval}.
         *
         * @event CBObserver#batch
         * @type object
         */
        self.emit('batch', data);
    }

}
430282
function (cmd, cb) {
  var internalCmd = internalCommand(cmd);
  if (internalCmd) {
    return cb(['info', internalCmd]);
  }
  $document.trigger('console:run', cmd);
}
643527
function(cb) {
    let serverDomain = domain.create();
    serverDomain.on('error', function(err) {
      console.error('Server domain caught an exception: ' + err);
      if (err) {
        console.error(err.stack);
      }
    });

    let web = this;
    serverDomain.run(function() {

      // Initialize the express server and routes.
      web.initServer();
      let http = require('http');

      let alwaysSecure = null;
      if (web.conf.https && web.conf.https.enabled) {
        if (web.conf.https.letsEncrypt) {
          //must do this manuall - npm install --global letsencrypt-cli
          let https = require('https');
          

          let lex = web.getLetsEncryptLex();

          let httpsPort = web.conf.https.port || 443;
          https.createServer(lex.httpsOptions, lex.middleware(web.app))
          .listen(httpsPort, web.conf.ipAddress, function(err, result) {
            if (err) {
              console.error(err);
            }
            console.log('%s: Node https server started on %s:%d ...',
                        Date(Date.now()), web.conf.ipAddress, httpsPort);

            if (cb) {
              cb(err, result);
            }
          });



        } else {
          let https = require('https');
          let privateKey = fs.readFileSync(web.conf.https.privateKey, 'utf8');
          let certificate = fs.readFileSync(web.conf.https.certificate, 'utf8');
          let credentials = {key: privateKey, cert: certificate};
          let httpsServer = https.createServer(credentials, web.app);

          httpsServer.listen(web.conf.https.port, web.conf.ipAddress, function(err, result) {
            if (err) {
              console.error(err);
            }
            console.log('%s: Node https server started on %s:%d ...',
                        Date(Date.now()), web.conf.ipAddress, web.conf.https.port);

            if (cb) {
              cb(err, result);
            }
          });
        }

        alwaysSecure = web.conf.https.alwaysSecure;
      }
      
      if (alwaysSecure && alwaysSecure.enabled) {
        let httpRedirecter = http.createServer(function(req, res) {

          if (alwaysSecure.redirectHandler) {
            alwaysSecure.redirectHandler(req, res);
          } else {  
            let nonStandardPort = '';
            if (web.conf.https.port != 443) {
              nonStandardPort = ':' + web.conf.https.port;
            }
            res.writeHead(302, {'Location': 'https://' + req.headers.host.split(':')[0] + nonStandardPort + req.url});
            res.end();
          }
        });

        httpRedirecter.listen(web.conf.port, web.conf.ipAddress, function(err, result) {
           if (err) {
              console.error(err);
            }
            
            console.log('%s: http redirecter server started on %s:%d ...',
                        Date(Date.now()), web.conf.ipAddress, web.conf.port);

            if (cb) {
              cb(err, result);
            }
        });
      } else {
        let httpServer = http.createServer(web.app);
        //  Start the app on the specific interface (and port).
        httpServer.listen(web.conf.port, web.conf.ipAddress, function(err, result) {
           if (err) {
              console.error(err);
            }
            
            console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now()), web.conf.ipAddress, web.conf.port);

            if (cb) {
              cb(err, result);
            }
        });
      }

    });
  }
1330042
function CommandProcessor(conn) {
	events.EventEmitter.call(this);

	this.conn = conn;

	this.connected_at = +new Date();
	this.last_data_at = 0;
	this.last_ping_at = 0;

	p.data_timeout = -1; // disabled
	p.data_timeout_TID = null;

	p.ping_timeout = -1; // disabled
	p.ping_timeout_TID = null;

	this._request_id = 0;
	this._requests_in_flight = {};

	this.last_line   = '';

	// handling disconnection can only be done once
	var _handle_disconnection = _.once(this._handle_disconnection.bind(this));

	conn.on('data',  this.process_data.bind(this));
	conn.on('error', _handle_disconnection);
	conn.on('end',   _handle_disconnection); // Do we really need this?
	conn.on('close', _handle_disconnection);

	// bind some methods to current instance for easy reuse
	this._emit_data_timeout = this._emit_data_timeout .bind(this);
	this._emit_ping_timeout = this._emit_ping_timeout .bind(this);
	this.set_timeouts();
}
609793
function getTaskCallback(callback) {
  let result = null
  // Get the callback function; throw errors, because we can't log them
  // later until we have identified a task name
  if (typeof callback === 'function') {
    result = callback
  } else if (typeof callback === 'string') {
    let id = callback.trim()
    // treat like a local path if it looks like one
    if (
      id.startsWith('./') ||
      id.startsWith('../') ||
      id.endsWith('.js') ||
      (id.includes('/') && !id.startsWith('@'))
    ) {
      if (path.isAbsolute(id) === false) {
        id = path.join(process.cwd(), id)
      }
    }
    try {
      result = require(id)
    } catch (err) {
      throw new Error(`Could not load module '${id}':\n${err}`)
    }
    if (typeof result !== 'function') {
      throw new Error(
        `Expected module '${id}' to export a function, was ${typeof result}`
      )
    }
  } else {
    throw new Error(
      `Callback argument must be a string or a named function\n${USAGE_INFO}`
    )
  }
  const { displayName, name } = result || {}
  if (typeof displayName !== 'string' && typeof name !== 'string') {
    throw new Error(
      `Callback function cannot be anonymous\n(Use a function declaration or the displayName property.)\n${USAGE_INFO}`
    )
  }
  return result
}
260672
function dashboard(cb) {
  return function (args) {
    function resultCb(result) {
      var jobs = result.jobs;
      if (_.isEmpty(jobs)) {
        console.log(text.__('Jobless Jenkins'));
      } else {
        jobs.forEach(function (job) {
          var status = util.statusByColor(job.color);
          var color  = util.colorByStatus(status, job.color);
          console.log('%s - %s', text.__(status)[color], job.name);
        });
      }
    }
    function jenkinsCb(jenkins) {
      jenkins.info(cli.exitCb(null, resultCb));
    }
    cb(args, jenkinsCb);
  };
}
631624
function(handler, realm, cbauth) {
        var req = handler.httpRequest;
        this.init(realm, req);

        var username = this.digestParts["username"];
        // No username was given
        if (!username)
            return this.requireAuth(realm, "No digest authentication headers were found", cbauth);

        var self = this;
        this.getDigestHash(realm, username, function(err, hash) {
            // If this was false, the user account didn't exist
            if (err || !hash)
                return self.requireAuth(realm, err || "The supplied username was not on file", cbauth);

            if (typeof hash != "string") {
                handler.handleError(new Exc.jsDAV_Exception(
                    "The returned value from getDigestHash must be a string or null"));
                return cbauth(null, false);
            }

            // If this was false, the password or part of the hash was incorrect.
            self.validateA1(handler, hash, function(isValid) {
                if (!isValid)
                    return self.requireAuth(realm, "Incorrect username", cbauth);

                self.currentUser = username;
                cbauth(null, true);
            });
        });
    }
835924
function enable(cb) {
  return function (name, args) {
    function resultCb(result) {
      console.log(text.__('Job %s was enabled successfully'), name);
    }
    function jenkinsCb(jenkins) {
      jenkins.enableJob(name, cli.exitCb(null, resultCb));
    }
    cb(args, jenkinsCb);
  };
}
646331
function Jenkins(url) {

  function _authFail(result, cb) {
    cb(new Error(text.__('Authentication failed - incorrect username and/or password')));
  }

  function _authRequire(result, cb) {
    cb(new Error(text.__('Jenkins requires authentication - please set username and password')));
  }

  this.url = url || process.env.JENKINS_URL || 'http://localhost:8080';

  // base URL is needed for functionalities that operate against base Jenkins path
  // this is needed for retrieving Jenkins crumb where the URL might contain paths to folders,
  // but the the Jenkins crumb retrieval still needs to be executed against the base Jenkins path
  let parsedUrl = _url.parse(this.url);
  this.baseUrl = this.url.replace(parsedUrl.path, '');

  var cert = process.env.JENKINS_CERT;
  var ca = process.env.JENKINS_CA;
  var key = process.env.JENKINS_KEY;
  this.opts = {
    handlers: {
      401: _authFail,
      403: _authRequire
    }
  };

  this.remoteAccessApi = new Swaggy.RemoteAccessApi();
  this.remoteAccessApi.apiClient.basePath = this.url;

  // a new Swaggy.ApiClient must be created here in order
  // to force baseApi to not share the same ApiClient as
  // remoteAccessApi
  // this is necessary because baseApi uses a URL that could be
  // different to remoteAccessApi
  this.baseApi = new Swaggy.BaseApi(new Swaggy.ApiClient());
  this.baseApi.apiClient.basePath = this.baseUrl;


  if (cert) {
    var key_path = key.split(':')[0];
    var passphrase = key.split(':')[1];
    this.opts.agentOptions = {
      passphrase: passphrase,
      secureProtocol: 'TLSv1_method'
    };
    if(cert && fs.statSync(cert)){
      this.opts.agentOptions.cert = fs.readFileSync(cert);
    }
    if(key_path && fs.statSync(key_path)){
      this.opts.agentOptions.key = fs.readFileSync(key_path);
    }
    if(ca && fs.statSync(ca)){
      this.opts.agentOptions.ca = fs.readFileSync(ca);
    }
  }
}
166573
protected void acquireAccessToken(final OAuthCallback cb) {
        if (isAccessTokenCached()) {
            // Execute the callback immediately with cached OAuth credentials
            if (VERBOSE) Log.d(TAG, "Access token cached");
            if (cb != null) {
                // Ensure networking occurs off the main thread
                // TODO: Use an ExecutorService and expose an application shutdown method to shutdown?
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        cb.onSuccess(getRequestFactoryFromCachedCredentials());
                    }
                }).start();
            }
        } else if (mOauthInProgress && cb != null) {
            // Add the callback to the queue for execution when outstanding OAuth negotiation complete
            mCallbackQueue.add(cb);
            if (VERBOSE) Log.i(TAG, "Adding cb to queue");
        } else {
            mOauthInProgress = true;
            // Perform an OAuth Client Credentials Request
            // TODO: Replace with new Thread()
            new AsyncTask<Void, Void, Void>() {

                @Override
                protected Void doInBackground(Void... params) {
                    TokenResponse response = null;
                    try {
                        if (VERBOSE)
                            Log.i(TAG, "Fetching OAuth " + mConfig.getAccessTokenRequestUrl());
                        response = new ClientCredentialsTokenRequest(new NetHttpTransport(), new JacksonFactory(), new GenericUrl(mConfig.getAccessTokenRequestUrl()))
                                .setGrantType("client_credentials")
                                .setClientAuthentication(new BasicAuthentication(mConfig.getClientId(), mConfig.getClientSecret()))
                                .execute();
                    } catch (IOException e) {
                        // TODO: Alert user Kickflip down
                        //       or client credentials invalid
                        if (cb != null) {
                            postExceptionToCallback(cb, e);
                        }
                        e.printStackTrace();
                    }
                    if (response != null) {
                        if (VERBOSE)
                            Log.i(TAG, "Got Access Token " + response.getAccessToken().substring(0, 5) + "...");
                        storeAccessToken(response);
                        mOauthInProgress = false;
                        if (cb != null)
                            cb.onSuccess(getRequestFactoryFromAccessToken(mStorage.getString(ACCESS_TOKEN_KEY, null)));
                        executeQueuedCallbacks();
                    } else {
                        mOauthInProgress = false;
                        Log.w(TAG, "Failed to get Access Token");
                    }
                    return null;
                }
            }.execute();
        }
    }
189100
def get_handler(progname, address=None, proto=None, facility=None,
                fmt=None, datefmt=None, **_):
    
    builder = SyslogHandlerBuilder(
        progname, address=address, proto=proto, facility=facility,
        fmt=fmt, datefmt=datefmt)
    return builder.get_handler()
244923
public static function proxy($cb, $name = null)
    {
        static $i = 0;
        $n = ++$i;
        Daemon::log('Debug::proxy #' . $n . ': SPAWNED (' . json_encode($name) . ')');
        return function (...$args) use ($cb, $name, $n) {
            Daemon::log('Debug::proxy #' . $n . ': CALLED (' . json_encode($name) . ')');
            $cb(...$args);
        };
    }