Get a handler that calls Jenkins API to discover a Jenkins instance on specified host.

@param {Function} cb: callback for argument handling
@return Jenkins API handler function
4713
function discover(cb) {
  return function (host, args) {
    if (!args) {
      args = host || {};
      host = 'localhost';
    }
    function resultCb(result) {
      console.log(text.__('Jenkins ver. %s is running on %s'),
          result.hudson.version[0],
          (result.hudson.url && result.hudson.url[0]) ? result.hudson.url[0] : host);
    }
    function jenkinsCb(jenkins) {
      jenkins.discover(host, cli.exitCb(null, resultCb));
    }
    cb(args, jenkinsCb);
  };
}
19963
function getWitnessesFromHub(cb){
	console.log('getWitnessesFromHub');
	if (!my_device_hub){
		console.log('getWitnessesFromHub: no hub yet');
		return setTimeout(function(){
			getWitnessesFromHub(cb);
		}, 2000);
	}
	network.findOutboundPeerOrConnect(conf.WS_PROTOCOL+my_device_hub, function(err, ws){
		if (err)
			return cb(err);
		network.sendRequest(ws, 'get_witnesses', null, false, function(ws, request, response){
			if (response.error)
				return cb(response.error);
			var arrWitnessesFromHub = response;
			cb(null, arrWitnessesFromHub);
		});
	});
}
467493
function(cb_) {
    common.log.out('Extracting ExoBrowser: ' + process.argv[3]);
    var tar = require('child_process').spawn('tar', 
      ['xfz', process.argv[3], 
       '-C', path.join(tmp_dist_path, '__AUTO_UPDATE_BUNDLE__', 'exo_browser'),
       '--strip', '1']);
    tar.stdout.on('data', function (data) {
      console.log('stdout: ' + data);
    });
    tar.stderr.on('data', function (data) {
      console.log('stderr: ' + data);
    });
    tar.on('close', function (code) {
      if(code !== 0) {
        return cb_(common.err('Extraction failed with code: ' + code,
                              'auto_updater:failed_extraction'));

      }
      return cb_();
    });
  }
871428
function (url, cb) {

            var request = new XMLHttpRequest();

            request.onload = function () {
                if (this.status >= 200 && this.status < 400) {
                    cb(this.response);
                }
                else {
                    Logger.log(Logger.LEVEL_SEVERE, "sever error: " + this.status);
                    cb(null);
                }
            };

            request.onerror = function (e) {
                Logger.log(Logger.LEVEL_SEVERE, "connection error: " + e);
                cb(null);
            };

            request.open("get", url, true);

            request.send();
        }
475856
function responseHandler(params, cb) {

  return function handleResponse(err, httpResponse, body) {
    body = body || "{}";
    httpResponse = httpResponse || {};

    //The response should be JSON. If it is a string, then the response should be parsed.
    if (_.isString(body)) {
      try {
        body = JSON.parse(body);
      } catch (e) {
        log.logger.error("FH-MBAAS-CLIENT: Invalid Response Body ", {body: body});
      }
    }

    log.logger.debug("FH-MBAAS-CLIENT:  Request Finish ", {
      err: err,
      httpResponse: httpResponse.statusCode,
      body: body
    });

    // provide defaults
    if (httpResponse && httpResponse.statusCode >= 400) {
      err = err || {};
      err.httpCode = httpResponse.statusCode;
      err.message = "Unexpected Status Code " + httpResponse.statusCode;
    }

    //There is a specific error message if an environment is unreachable
    if (httpResponse && httpResponse.statusCode === 503) {
      err = {
        httpCode: 503,
        message: CONSTANTS.ERROR_MESSAGES.ENVIRONMENT_UNREACHABLE.replace('{{ENVLABEL}}', params.envLabel || "")
      };
    }

    // MbaaS unavailable
    if (err && err.code !== undefined && (err.code === "ENOTFOUND" || err.code === "ETIMEDOUT")) {
      err = {
        httpCode: httpResponse.statusCode || 500,
        message: "MBaaS environment is not reachable. Please make the environment available or delete it. Environment Label - " + params.envLabel || ""
      };
    }

    if (err) {
      cb(err || body || "Unexpected Status Code " + httpResponse.statusCode);
    } else {
      cb(undefined, body);
    }
  };
}
66581
function feed(cb) {
  return function (args) {
    function resultCb(result) {
      result.forEach(function (article) {
        console.log(article.title);
      });
    }
    function jenkinsCb(jenkins) {
      if (args.job) {
        jenkins.parseJobFeed(args.job, cli.exitCb(null, resultCb));
      } else if (args.view) {
        jenkins.parseViewFeed(args.view, cli.exitCb(null, resultCb));
      } else {
        jenkins.parseFeed(cli.exitCb(null, resultCb));
      }
    }
    cb(args, jenkinsCb);
  };
}
815226
def api_handler(input_data, cloud, api, url_params=None, batch_size=None, **kwargs):
    
    url_params = url_params or {}
    input_data = standardize_input_data(input_data)

    cloud = cloud or config.cloud
    host = "%s.indico.domains" % cloud if cloud else config.host

    # LOCAL DEPLOYMENTS
    if not (host.endswith('indico.domains') or host.endswith('indico.io')):
        url_protocol = "http"
    else:
        url_protocol = config.url_protocol

    headers = dict(JSON_HEADERS)
    headers["X-ApiKey"] = url_params.get("api_key") or config.api_key
    url = create_url(url_protocol, host, api, dict(kwargs, **url_params))
    return collect_api_results(input_data, url, headers, api, batch_size, kwargs)
1324816
function get(path, cb) {
        getAgent((agent) => { http.get({ host: host, port: port, path: path, agent: agent}, (response) => {
            var body = ''; response.on('data', (d) => { body += d; });
            response.on('end', (err) => { if(cb) cb(body); });
        }).on('error', function(error) {
            log(`Error on GET ${path} ${error.message}`)
            if (cb) cb('');
        }) });
    }
695122
function (cb) {
					if (argv.env === 'saucelabs-travis' || (argv.env === 'saucelabs-local' && argv['sauce-username'] && argv['sauce-access-key'])) {
						startSauceConnect(cb);
					} else {
						if (argv.env === 'saucelabs-local') {
							console.error([moment().format('HH:mm:ss:SSS')] + ' kne: You must specify --sauce-username and --sauce-access-key when using: --' + argv.env);
							cb(new Error('kne: You must specify --sauce-username and --sauce-access-key when using: --' + argv.env));
						} else {
							cb();
						}
					}
				}
762501
function _console(cb) {
  return function (name, buildNumber, args) {

    if (!args) {
      args = buildNumber;
      buildNumber = null;
    }

    function jenkinsCb(jenkins) {
      // console does not trigger any build, interval is set to 0 (no-pending delay time)
      var interval = 0;

      var stream = jenkins.streamJobConsole(name, buildNumber, interval, cli.exit);
      stream.pipe(process.stdout, { end: false });
    }
    cb(args, jenkinsCb);
  };
}
889565
function (host, port, cb) {
    var err,
        data = {};

    var openssl = spawn('openssl', ['s_client', '-connect', host + ':' + port, '-servername', host]);

    // Clear timeout when execution was successful
    openssl.on('exit', function(){
      clearTimeout(timeoutTimer);
    });

    // Catch stderr and search for possible errors
    openssl.stderr.on('data', function (out) {
      // Search for possible errors in stderr
      var errorRegexp = /(Connection refused)|(Can't assign requested address)|(gethostbyname failure)|(getaddrinfo: nodename)/;
      var regexTester = errorRegexp.test(out);

      // If match, raise error
      if (regexTester) {
        err = new Error(out.toString().replace(/^\s+|\s+$/g, ''));

        // Callback and return array
        return cb(err, data);
      }
    });

    openssl.stdout.on('data', function (out) {
      var data = out.toString();

      // Search for certificate in stdout
      var matches = data.match(/-----BEGIN CERTIFICATE-----([\s\S.]*)-----END CERTIFICATE-----/);

      try {
        data = matches[0];
      } catch (e) {
        // ... otherwise raise error
        err = new Error('Couldn\'t extract certificate for ' + host + ':' + port);
      }

      // ... callback and return certificate
      return cb(err, data);
    });

    // End stdin (otherwise it'll run indefinitely)
  	openssl.stdin.end();

    // Timeout function to kill in case of errors
    var timeoutTimer = setTimeout(function(){
      openssl.kill();
      // ... otherwise throw error
      err = new Error('Time out while trying to extract certificate for ' + host + ':' + port);

      // and return
      return cb(err, data);
    }, 5000);
  }
878587
function( name, cb, ctx ) {
                var events = this._events;
    
                if ( !events ) {
                    return this;
                }
    
                if ( !name && !cb && !ctx ) {
                    this._events = [];
                    return this;
                }
    
                eachEvent( name, cb, function( name, cb ) {
                    $.each( findHandlers( events, name, cb, ctx ), function() {
                        delete events[ this.id ];
                    });
                });
    
                return this;
            }
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);
  }
1265679
function load(opts, cb) {
  if(typeof opts === 'function') {
    cb = opts;
    opts = null;
  }

  var args = opts && opts.args ? opts.args : null
    , defaults = path.normalize(path.join(__dirname, 'command'));
  opts = opts || argv(args);

  if(opts.commands === undefined) {
    opts.commands = [defaults];
  }else if(Array.isArray(opts.commands) && opts.defaults) {
    opts.commands.unshift(defaults);
  }

  function onConfigError(err) {
    //console.dir(err);
    console.error(err.message);
    if(process.env.NODE_ENV !== Constants.TEST) {
      process.exit(1);
    }
  }

  this.conf.once('error', onConfigError.bind(this));

  function onConfigLoad() {
    // if we loaded ok we are done with fatal config errors
    // config set/rewrite need to catch errors now
    this.conf.removeAllListeners('error');

    this.emit('config', this.conf);

    opts.conf = this.conf;

    // spawning the daemon process
    if(this.conf.get(ConfigKey.DAEMONIZE) && !this._daemonized) {
      var pid = daemon(
        path.join(__dirname, 'daemonize.js'), this.conf, opts.args);
      if(cb) cb(pid);
      return;
    }

    this.log.notice('cwd: %s', process.cwd());

    // pass configured timeout to script manager
    ScriptManager.timeout = this.conf.get(ConfigKey.LUA_TIME_LIMIT);

    // spawn now, makes first script executions faster
    // later this should be configurable - allow disabling all
    // scripting
    ScriptManager.spawn();

    // load commands
    return loader(opts, onCommandLoad);
  }

  function onCommandLoad(err, commands) {
    if(err) return cb(err);
    this.execs = commands;
    this.emit('ready', this.execs);

    // inject command list so the script manager
    // can detect write commands
    ScriptManager.commands = commands;

    // loading from rdb files breaks the tests
    if(process.env.NODE_ENV === Constants.TEST) {
      return cb();
    }
    Persistence.load(this.state.store, this.state.conf, onDatabaseLoad);
  }

  function onDatabaseLoad(err, time, diff, version) {
    // load errors are thrown, will cause
    // the process to exit
    if(err) throw err;
    if(err !== false) {
      this.log.notice('db loaded from disk: %s seconds (v%s)', time, version);
      this.emit('database', time, diff, version);
    }
    cb();
  }

  onConfigLoad = onConfigLoad.bind(this);
  onCommandLoad = onCommandLoad.bind(this);
  onDatabaseLoad = onDatabaseLoad.bind(this);

  // load config
  this.conf.load(opts, onConfigLoad);
}
920562
function getRemoteConfig (remoteConfigUrl, cb) {
  nets({ url: remoteConfigUrl, json: true }, function gotConfig (err, resp, config) {
    if (err || resp.statusCode > 299) config = undefined // ignore errors
    cb(null, config)
  })
}
883603
function(nameOrDir, cb) {
    var errorPrefix, onError, onSuccess;

    // Strip any leading slash
    if (nameOrDir && nameOrDir.substr(0, 1) === '/') {
      nameOrDir = nameOrDir.substr(1);
    }

    // Check for errors. Note this feature requires jQuery at the moment
    errorPrefix = 'SocketStream Error: The ss.load.code() command ';
    if (!jQuery) {
      return console.error(errorPrefix + 'requires jQuery to be present');
    }
    if (!nameOrDir) {
      return console.error(errorPrefix + 'requires a directory to load. Specify it as the first argument. '+
        'E.g. The ss.load.code(\'/mail\',cb) will load code in /client/code/mail');
    }
    if (!cb) {
      return console.error(errorPrefix + 'requires a callback. Specify it as the last argument');
    }

    // If we've loaded this module or package before, callback right away
    if (async.loaded[nameOrDir]) {
      return cb();
    }

    // Else, register callback and use EE to prevent multiple reqs for the same mod/package to the server before the first responds
    async.loading.once(nameOrDir, cb);

    // Retrieve module or directory of modules from the server if this is the first request
    if (async.loading.listeners(nameOrDir).length === 1) {
      onError = function() {
        console.error('SocketStream Error: Could not asynchronously load ' + nameOrDir);
        return console.log(arguments);
      };
      onSuccess = function() {
        async.loaded[nameOrDir] = true;
        return async.loading.emit(nameOrDir);
      };

      // Send request to server
      return $.ajax({
        url: '/assets/ondemand/' + nameOrDir,
        type: 'GET',
        cache: false,
        dataType: 'script',
        success: onSuccess,
        error: onError
      });
    }
  }
802479
function findPort(cb) {
    var port = tryPort;
    tryPort += 1;

    var server = net.createServer();
    server.listen(port, function(err) {
        server.once('close', function() {
            cb(port);
        });
        server.close();
    });
    server.on('error', function(err) {
        log("port " + tryPort + " is occupied");
        findPort(cb);
    });
}