Send an AJAX request.

@param  {Object}   opts [optional]
@param  {Function} cb
@return {XMLHttpRequest}
550368
function ajax(opts, cb) {
            opts = opts || {};
            var xmlhttp;

            if (typeof window === 'undefined') {
                // TODO: refactor node usage to live in here
                return cb();
            }

            if (window.XMLHttpRequest) {
                // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            } else {
                // code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }

            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    cb(xmlhttp.responseText);
                }
            };

            xmlhttp.open(opts.method, opts.url, true);
            xmlhttp.send();
            return xmlhttp;
        }
679043
function (opts, cb) {
            var self = this;
            cb = cb || function () {
                };
            opts = opts || {};
            var url = this._getlisturi(opts);
            this.client.get({
                uri: url,
                data:opts
            }, cb);
        }
1087352
function (group, opts) {
			if (!group) {
				return;
			}

			if (!$.isPlainObject(opts)) {
				opts = {};
			}

			// Close if already active
			if (false === F.close(true)) {
				return;
			}

			// Normalize group
			if (!$.isArray(group)) {
				group = isQuery(group) ? $(group).get() : [group];
			}

			// Recheck if the type of each element is `object` and set content type (image, ajax, etc)
			$.each(group, function(i, element) {
				var obj = {},
					href,
					title,
					content,
					type,
					rez,
					hrefParts,
					selector;

				if ($.type(element) === "object") {
					// Check if is DOM element
					if (element.nodeType) {
						element = $(element);
					}

					if (isQuery(element)) {
						obj = {
							href    : element.data('fancybox-href') || element.attr('href'),
							title   : element.data('fancybox-title') || element.attr('title'),
							isDom   : true,
							element : element
						};

						if ($.metadata) {
							$.extend(true, obj, element.metadata());
						}

					} else {
						obj = element;
					}
				}

				href  = opts.href  || obj.href || (isString(element) ? element : null);
				title = opts.title !== undefined ? opts.title : obj.title || '';

				content = opts.content || obj.content;
				type    = content ? 'html' : (opts.type  || obj.type);

				if (!type && obj.isDom) {
					type = element.data('fancybox-type');

					if (!type) {
						rez  = element.prop('class').match(/fancybox\.(\w+)/);
						type = rez ? rez[1] : null;
					}
				}

				if (isString(href)) {
					// Try to guess the content type
					if (!type) {
						if (F.isImage(href)) {
							type = 'image';

						} else if (F.isSWF(href)) {
							type = 'swf';

						} else if (href.charAt(0) === '#') {
							type = 'inline';

						} else if (isString(element)) {
							type    = 'html';
							content = element;
						}
					}

					// Split url into two pieces with source url and content selector, e.g,
					// "/mypage.html #my_id" will load "/mypage.html" and display element having id "my_id"
					if (type === 'ajax') {
						hrefParts = href.split(/\s+/, 2);
						href      = hrefParts.shift();
						selector  = hrefParts.shift();
					}
				}

				if (!content) {
					if (type === 'inline') {
						if (href) {
							content = $( isString(href) ? href.replace(/.*(?=#[^\s]+$)/, '') : href ); //strip for ie7

						} else if (obj.isDom) {
							content = element;
						}

					} else if (type === 'html') {
						content = href;

					} else if (!type && !href && obj.isDom) {
						type    = 'inline';
						content = element;
					}
				}

				$.extend(obj, {
					href     : href,
					type     : type,
					content  : content,
					title    : title,
					selector : selector
				});

				group[ i ] = obj;
			});

			// Extend the defaults
			F.opts = $.extend(true, {}, F.defaults, opts);

			// All options are merged recursive except keys
			if (opts.keys !== undefined) {
				F.opts.keys = opts.keys ? $.extend({}, F.defaults.keys, opts.keys) : false;
			}

			F.group = group;

			return F._start(F.opts.index);
		}
674221
function sendCommand(js,cb){
    if(!js) return stream.log('send command got no command!',js);
    var id = ++stream.inc;
    if(!js.id) js.id = 0;// default input id.

    var start = Date.now();
    var timeCallback = function(err,js){
      js.basetime = Date.now()-start;// decorate performance time.
      if(cb) cb(err,js)
    }

    if(js.timeout == undefined) js.timeout = 10000;
    else if(js.timeout < 0) {
      js.timeout = 60000;// 60 seconds max timeout
    } else if(js.timeout > 60000){
      js.timeout = 60000; 
    }
    
    var timeout = js.timeout;
    setTimeout(function(){
      if(stream.callbacks[id]) {
        // make reply js
        js.type = "reply";
        js.err = "base timeout in "+timeout+" ms";
        js.timeout = timeout;
        js.timeerror = true;
        js.from = js.to;
        delete js.to;
        timeCallback(true,js);
      }
    },timeout);

    stream.callbacks[id] = {id:js.id,cb:timeCallback};
    js.id = id;

    if(stream.inc > maxId) stream.inc = 1;

    js.type = "command";
    toBoard.write(js);
  
    return js;
  }
251363
function create (params, opts, cb) {
      if (!cb) {
        cb = opts
      }
      if (!opts || typeof opts === 'function') {
        opts = {}
      }

      let promise = null
      if (typeof cb !== 'function') [promise, cb] = asyncify()

      const { createOnly } = opts

      const tasks = [
        (job, next) => {
          const id = params.id || uuid()
          params.id = id
          const { name, description, metadata, user } = params

          Joi.validate({ id, name, description, metadata, user }, validationRules.create, (err) => {
            if (err) return next(Boom.badRequest(err))
            next()
          })
        },
        (job, next) => {
          job.params = params
          job.user = params.user
          next()
        },
        insertOrganization
      ]

      if (!createOnly) {
        tasks.push(
          createDefaultPolicies,
          insertOrgAdminUser
        )
      }

      db.withTransaction(tasks, (err, res) => {
        if (err) return cb(err)

        organizationOps.readById(res.organization.id, (err, organization) => {
          if (err) return cb(Boom.badImplementation(err))

          cb(null, { organization, user: res.user })
        })
      })

      return promise
    }
84931
function send(data, cb) {
    if (enabled) {
      var send_data = new Buffer(data);
      try {
        socket.send(send_data, 0, send_data.length, port, host, function(err, bytes) {
          if (cb) {
            return cb(err, bytes);
          }
        });
      } catch (x) {
        // Purposely ignored..
        cb();
      }
    } else {
      cb();
    }
  }
1190456
function _getToken(opts, cb) {
    assert.string(opts.indexName, 'opts.indexName'); // used for error messages
    assert.string(opts.realm, 'opts.realm');
    assert.optionalString(opts.service, 'opts.service');
    assert.optionalArrayOfString(opts.scopes, 'opts.scopes');
    assert.optionalString(opts.username, 'opts.username');
    assert.optionalString(opts.password, 'opts.password');
    // HTTP client opts:
    assert.object(opts.log, 'opts.log');
    assert.optionalObject(opts.agent, 'opts.agent');
    // assert.optional object or bool(opts.proxy, 'opts.proxy');
    assert.optionalBool(opts.insecure, 'opts.insecure');
    assert.optionalString(opts.userAgent, 'opts.userAgent');
    var log = opts.log;

    // - add https:// prefix (or http) if none on 'realm'
    var tokenUrl = opts.realm;
    var match = /^(\w+):\/\//.exec(tokenUrl);
    if (!match) {
        tokenUrl = (opts.insecure ? 'http' : 'https') + '://' + tokenUrl;
    } else if (['http', 'https'].indexOf(match[1]) === -1) {
        return cb(new Error(fmt('unsupported scheme for ' +
            'WWW-Authenticate realm "%s": "%s"', opts.realm, match[1])));
    }

    // - GET $realm
    //      ?service=$service
    //      (&scope=$scope)*
    //      (&account=$username)
    //   Authorization: Basic ...
    var headers = {};
    var query = {};
    if (opts.service) {
        query.service = opts.service;
    }
    if (opts.scopes && opts.scopes.length) {
        query.scope = opts.scopes;  // intentionally singular 'scope'
    }

    if (opts.username) {
        query.account = opts.username;
        _setAuthHeaderFromAuthInfo(headers, {
            username: opts.username,
            password: opts.password
        });
    }
    if (Object.keys(query).length) {
        tokenUrl += '?' + querystring.stringify(query);
    }
    log.trace({tokenUrl: tokenUrl}, '_getToken: url');

    var parsedUrl = mod_url.parse(tokenUrl);
    var client = new DockerJsonClient({
        url: parsedUrl.protocol + '//' + parsedUrl.host,
        log: log,
        agent: opts.agent,
        proxy: opts.proxy,
        rejectUnauthorized: !opts.insecure,
        userAgent: opts.userAgent || common.DEFAULT_USERAGENT
    });
    client.get({
        path: parsedUrl.path,
        headers: headers
    }, function (err, req, res, body) {
        client.close();
        if (err) {
            if (err.statusCode === 401) {
                // Convert *all* 401 errors to use a generic error constructor
                // with a simple error message.
                var errMsg = _getRegistryErrorMessage(err);
                return cb(new errors.UnauthorizedError(errMsg));
            }
            return cb(err);
        } else if (!body.token) {
            return cb(new errors.UnauthorizedError(err, 'authorization ' +
                'server did not include a token in the response'));
        }
        cb(null, body.token);
    });
}
723243
function _request(url, opt) {
      opt = opt || {};
      opt.method = (opt.method || 'GET').toUpperCase();
      opt.headers = opt.headers || {};
      if (matchUrl(url) && matchMethod(opt.method)) {
        const result = extend(true, {}, mockResult);
        const response = {
          status: result.status,
          statusCode: result.status,
          headers: result.headers,
          size: result.responseSize,
          aborted: false,
          rt: 1,
          keepAliveSocket: result.keepAliveSocket || false,
        };

        httpclient.emit('response', {
          error: null,
          ctx: opt.ctx,
          req: {
            url,
            options: opt,
            size: result.requestSize,
          },
          res: response,
        });
        if (opt.dataType === 'json') {
          try {
            result.data = JSON.parse(result.data);
          } catch (err) {
            err.name = 'JSONResponseFormatError';
            throw err;
          }
        } else if (opt.dataType === 'text') {
          result.data = result.data.toString();
        }
        return Promise.resolve(result);
      }
      return rawRequest.call(httpclient, url, opt);
    }
726257
function run(opts, cb){
  opts.extensions = opts.extensions ? opts.extensions + ',.jsx' : '.jsx';

  // glob-all fixes windows glob issues and provides array support
  // i.e. jsxhint ['jsx/**/*','!scripts/**/*','scripts/outlier.jsx']
  runGlob(opts.args, {nodir: true}, function(err, globbed) {
    if (err) return cb(err);

    // Reassign the globbed files back to opts.args, so it looks like we just
    // fed jshint a big list of files.
    opts.args = globbed;
    var files = jshintcli.gather(opts);

    if (opts.useStdin) {
      jsxhint.transformStream(process.stdin, jsxhintOptions, opts, cb);
    } else {
      jsxhint.transformFiles(files, jsxhintOptions, opts, cb);
    }
  });
}
579783
function (since, callback) {
      if (opts.aborted) {
        return;
      }
      params.since = since;
      // "since" can be any kind of json object in Coudant/CouchDB 2.x
      /* istanbul ignore next */
      if (typeof params.since === "object") {
        params.since = JSON.stringify(params.since);
      }

      if (opts.descending) {
        if (limit) {
          params.limit = leftToFetch;
        }
      } else {
        params.limit = (!limit || leftToFetch > batchSize) ?
          batchSize : leftToFetch;
      }

      // Set the options for the ajax call
      var xhrOpts = {
        method: method,
        url: genDBUrl(host, '_changes' + paramsToStr(params)),
        timeout: opts.timeout,
        body: body
      };
      lastFetchedSeq = since;

      /* istanbul ignore if */
      if (opts.aborted) {
        return;
      }

      // Get the changes
      setup().then(function () {
        xhr = ajax(opts, xhrOpts, callback);
      }).catch(callback);
    }
1055470
function BaseClient(opts) {
  this.opts = opts || {};
  var self = this;
  this.sendQConcurrency = opts.sendQueueConcurrency || 5;
  this.sendQ = async.queue(function(data, cb) {
    self.doSend(data, cb);
  }, this.sendQConcurrency);
}
43471
function(cb) {
        var timeout;
        this.chain(function(next) {
            function evaluate() {
                var ccb = cb.bind(api);
                var result = ccb();
                if (result) {
                    clearInterval(poll);
                    if (timeout !== undefined) clearTimeout(timeout);
                    next();
                }
            }
            var api = this;
            var poll = setInterval(evaluate, api._untilInterval || 30);
            // to set a timeout for condition to be met, set the _untilTimeout property to ms value
            if (api.untilTimeout) {
                timeout = setTimeout(function() {
                    if (poll !== undefined) {
                        clearInterval(poll);
                        // to catch timeout of until conditions, set onUntilTimeout handler
                        if (api.onUntilTimeout) api.onUntilTimeout(next);
                        // otherwise execution flow simply continues as if condition was met
                        else next();
                    }
                }, api.untilTimeout);
            }
        });
        return this;
    }
737743
function arrayApi(input, opts, cb) {
    var fd = new FormData(), files = [];
    [].slice.call(input.files).forEach(function(file) {
      fd.append(opts.name, file, file.webkitRelativePath || file.name);
      files.push(file.webkitRelativePath || file.name);
    });
    cb(fd, files);
  }
1201797
function request(uri, opt, callback) {
    if (typeof opt === 'function') {
        callback = opt;
        opt = {};
    }
    return hyperquest(uri, opt, callback);
}
1064345
function (info, cb) {
            // Default to a binary request
            var options = info.src;
            var dest = info.dest;

            // Request the url
            var req = request(options);

            // On error, callback
            req.on('error', cb);

            // On response, callback for writing out the stream
            req.on('response', function handleResponse (res) {
                // Assert the statusCode was good
                var statusCode = res.statusCode;
                if (statusCode < 200 || statusCode >= 300) {
                  return cb(new Error('Fetching ' + JSON.stringify(options) + ' failed with HTTP status code ' + statusCode));
                }

                // Otherwise, write out the content
                var destdir = path.dirname(dest);
                grunt.file.mkdir(destdir);
                var writeStream = fs.createWriteStream(dest);
                // Use `req` as the source of data https://github.com/request/request/blob/v2.51.1/request.js#L1255-L1267
                // DEV: This is to pipe out gunzipped data
                var dataStream = req;
                dataStream.pipe(writeStream);

                // When the stream errors or completes, exit
                writeStream.on('error', cb);
                writeStream.on('close', cb);
            });
        }
777133
function(server, port, options, cb) {
    return this.client.connect.call(this.client, server, port, options, cb);
  }
619225
function httpNdjson (req, res, opts, cb) {
  if (!cb) {
    cb = opts
    opts = {}
  }
  opts = opts || {}

  const start = Date.now()
  var size = null

  function setContentLength (nwSize) {
    size = nwSize
  }

  const headers = req.headers
  const request = {
    name: 'http',
    message: 'request',
    method: req.method,
    remoteAddress: req.connection.remoteAddress,
    url: req.url
  }
  if (headers['x-forwarded-for']) {
    request.xForwardedFor = headers['x-forwarded-for']
  }
  if (headers['x-real-ip']) {
    request.xRealIp = headers['x-real-ip']
  }
  if (headers['http-client-ip']) {
    request.httpClientIp = headers['http-client-ip']
  }
  if (opts.req) extend(request, value(opts.req))
  cb(request)

  eos(res, function (err) {
    if (err) cb({ name: 'error', message: err })

    const response = {
      name: 'http',
      message: 'response',
      method: req.method,
      url: req.url,
      statusCode: res.statusCode,
      elapsed: Date.now() - start
    }
    if (size !== null) response.contentLength = size
    if (opts.res) extend(response, value(opts.res))
    cb(response)
  })

  return setContentLength
}