Get the first inbound flight between two airports
@param {Object} options - see [.connections()]{@link FlightStats#connections}
@param {Function} callback
@return {Request}
515314
function( options, callback ) {
    options = Object.assign({ type: 'firstflightin', verb: '/arriving_before/' }, options )
    return this.connections( options, callback )
  }
1319873
function GhostRouter(options) {
    const router = express.Router(options);

    function innerRouter(req, res, next) {
        return innerRouter.handle(req, res, next);
    }

    Object.setPrototypeOf(innerRouter, router);

    Object.defineProperty(innerRouter, 'name', {
        value: options.parent.name,
        writable: false
    });

    innerRouter.parent = options.parent;
    return innerRouter;
}
438027
def search(query, parent, options):
        
        # Extend the default max number of tickets to be fetched
        query = "{0}&max={1}".format(query, MAX_TICKETS)
        log.debug("Search query: {0}".format(query))
        try:
            result = parent.proxy.ticket.query(query)
        except xmlrpclib.Fault as error:
            log.error("An error encountered, while searching for tickets.")
            raise ReportError(error)
        except xmlrpclib.ProtocolError as error:
            log.debug(error)
            log.error("Trac url: {0}".format(parent.url))
            raise ReportError(
                "Unable to contact Trac server. Is the url above correct?")
        log.debug("Search result: {0}".format(result))
        # Fetch tickets and their history using multicall
        multicall = xmlrpclib.MultiCall(parent.proxy)
        for ticket_id in sorted(result):
            multicall.ticket.get(ticket_id)
            multicall.ticket.changeLog(ticket_id)
        log.debug(u"Fetching trac tickets and their history")
        result = list(multicall())
        tickets = result[::2]
        changelogs = result[1::2]
        # Print debugging info
        for ticket, changelog in zip(tickets, changelogs):
            log.debug("Fetched ticket #{0}".format(ticket[0]))
            log.debug(pretty(ticket))
            log.debug("Changelog:")
            log.debug(pretty(changelog))
        # Return the list of ticket objects
        return [
            Trac(ticket, changelg, parent=parent, options=options)
            for ticket, changelg in zip(tickets, changelogs)]
353173
function combineSearch(tp1, tp2) {
  return tp1.map(travelPlan => {
    let arrival = new Date(travelPlan.legs[travelPlan.legs.length - 1].arrival)
    let bestWaitTime = Infinity
    let bestTravelPlan2 = tp2[0]
    // Find the most appropriate corresponding second travel plan.
    for (let i = 0; i < tp2.length; i++) {
      let travelPlan2 = tp2[i]
      let departure = new Date(travelPlan2.legs[0].departure)
      let waitTime = departure - arrival
      if (waitTime > 0) {
        if (waitTime < bestWaitTime) {
          bestWaitTime = waitTime
          bestTravelPlan2 = travelPlan2
        }
      }
    }
    return {
      fares: combineFares(travelPlan.fares, bestTravelPlan2.fares),
      legs: travelPlan.legs.slice().concat(bestTravelPlan2.legs.slice()),
    }
  })
}
305117
function loginCallback(options) {
  return async function loginCallbackHandler(ctx) {
    let referer;
    // customize how to get redirect target
    if (options.getRedirectTarget) {
      referer = options.getRedirectTarget(ctx);
    }
    if (!referer) referer = ctx.session.userauthLoginReferer || options.rootPath;

    debug('loginReferer in session: %j', ctx.session.userauthLoginReferer);
    // cleanup the userauthLoginReferer on session
    ctx.session.userauthLoginReferer = undefined;
    let user = ctx.session[options.userField];
    if (user) {
      // already login
      return redirect(ctx, referer);
    }
    user = await options.getUser(ctx);
    if (!user) {
      return redirect(ctx, referer);
    }

    const res = await options.loginCallback(ctx, user);
    const loginUser = res[0];
    const redirectURL = res[1];
    ctx.session[options.userField] = loginUser;
    if (redirectURL) {
      referer = redirectURL;
    }
    redirect(ctx, referer);
  };
}
508690
function get( opts, clbk ) {
	var ratelimit;
	var scount;
	var fcount;
	var count;
	var users;
	var eFLG;
	var out;
	var idx;
	var len;
	var i;

	// Output data store:
	out = {};
	out.meta = {};
	out.data = {};
	out.failures = {};

	// Number of completed requests:
	count = 0;
	scount = 0; // success
	fcount = 0; // failures

	// Request id:
	idx = 0;

	users = opts.usernames;
	len = users.length;

	debug( 'Number of usernames: %d.', len );
	out.meta.total = len;

	debug( 'Beginning queries...' );
	for ( i = 0; i < NUM_CONCURRENT_REQUESTS; i++ ) {
		next();
	}
	/**
	* FUNCTION: next()
	*	Requests user details data for the next username in the queue. Once requests for all desired usernames have completed, invokes the provided callback.
	*
	* @private
	* @returns {Void}
	*/
	function next() {
		var u;
		if ( count === len ) {
			debug( 'Finished all queries.' );
			out.meta.success = scount;
			out.meta.failure = fcount;
			return clbk( null, out, ratelimit );
		}
		if ( idx < len ) {
			u = users[ idx ];
			debug( 'Querying for username: `%s` (%d).', u, idx );
			opts.pathname = '/users/' + u;
			request( opts, onResponse( u, idx ) );
			idx += 1;
		}
	} // end FUNCTION next()

	/**
	* FUNCTION: onResponse( username, idx )
	*	Returns a response callback.
	*
	* @private
	* @param {String} username - username
	* @param {Number} idx - request index
	* @returns {Function} response callback
	*/
	function onResponse( username, idx ) {
		/**
		* FUNCTION: onResponse( error, details, info )
		*	Callback invoked upon receiving a request response.
		*
		* @private
		* @param {Error|Null} error - error object
		* @param {Object} details - response data
		* @param {Object} info - rate limit info
		* @returns {Void}
		*/
		return function onResponse( error, details, info ) {
			if ( eFLG ) {
				return;
			}
			debug( 'Response received for username: `%s` (%d).', username, idx );
			if ( arguments.length === 1 ) {
				eFLG = true;
				debug( 'Encountered an application-level error for username `%s` (%d): %s', username, idx, error.message );
				return clbk( error );
			}
			ratelimit = updateRateLimit( ratelimit, info );
			if ( error ) {
				debug( 'Failed to resolve username `%s` (%d): %s', username, idx, error.message );
				out.failures[ username ] = error.message;
				fcount += 1;
			} else {
				debug( 'Successfully resolved username `%s` (%d).', username, idx );
				out.data[ username ] = details;
				scount += 1;
			}
			count += 1;
			debug( 'Request %d of %d complete.', count, len );
			next();
		}; // end FUNCTION onResponse()
	} // end FUNCTION onResponse()
}
670112
function (tryReload, options) {                                        // 139
  tryReload = tryReload || function () {};                                                 // 140
  options = options || {};                                                                 // 141
                                                                                           // 142
  var migrationData = {};                                                                  // 143
  var remaining = _.clone(providers);                                                      // 144
  var allReady = true;                                                                     // 145
  while (remaining.length) {                                                               // 146
    var p = remaining.shift();                                                             // 147
    var status = p.callback(tryReload, options);                                           // 148
    if (!status[0])                                                                        // 149
      allReady = false;                                                                    // 150
    if (status.length > 1 && p.name)                                                       // 151
      migrationData[p.name] = status[1];                                                   // 152
  };                                                                                       // 153
  if (allReady || options.immediateMigration)                                              // 154
    return migrationData;                                                                  // 155
  else                                                                                     // 156
    return null;                                                                           // 157
}
73651
function(options, callback) {
    // Create a promise to defer to later
    var deferred = Bluebird.defer();

    // Fire the request
    request(this._buildRequestOptions(options), function(err, response, body) {
      // Handle Errors
      if (err) {
        // Usually a connection error (server unresponsive)
        err = new MuniError(err.message || 'Internal Server Error', err.code || 500);
      } else if (response.statusCode >= 400) {
        // Usually an intentional error from the server
        err = new MuniError(this._extractError(body), response.statusCode);
      }
      if (err) {
        debug.warn('Adapter Request Error with Code: %d', err.code);
        callback && callback(err);
        return deferred.reject(err);
      }

      // Handle Success
      debug.info('Adapter Request Sent with code: %d', response.statusCode);
      callback && callback(null, body);
      return deferred.resolve(body);
    }.bind(this));

    return deferred.promise;
  }
1041838
function request( opts, clbk ) {
	var body;
	var req;
	var res;
	var err;
	var r;

	// debug( 'Query options: %s', JSON.stringify( opts ) );

	if ( RE.test( opts.protocol ) ) {
		req = https.request;
	} else {
		req = http.request;
	}
	body = '';
	r = req( opts, onResponse );
	r.on( 'error', onError );
	r.end();

	/**
	* FUNCTION: onError( error )
	*	Event listener invoked after encountering an error.
	*
	* @private
	* @param {Error} error - error object
	* @returns {Void}
	*/
	function onError( error ) {
		debug( 'Error encountered while querying endpoint: %s', error.message );
		if ( error instanceof Error ) {
			err = {
				'status': 500,
				'message': 'Request error: ' + error.message
			};
			return clbk( err );
		}
		return clbk( error, res, body );
	} // end FUNCTION onError()

	/**
	* FUNCTION: onResponse( response )
	*	Callback invoked after receiving an HTTP response.
	*
	* @private
	* @param {Object} response - HTTP response object
	* @returns {Void}
	*/
	function onResponse( response ) {
		res = response;
		if ( res.statusCode !== 200 ) {
			err = {
				'status': res.statusCode,
				'message': ''
			};
		}
		debug( 'Received a response from query endpoint.' );
		debug( 'Response status: %s.', res.statusCode );

		debug( 'Response headers: %s', JSON.stringify( res.headers ) );

		res.setEncoding( 'utf8' );
		res.on( 'data', onData );
		res.on( 'end', onEnd );
	} // end FUNCTION onResponse()

	/**
	* FUNCTION: onData( chunk )
	*	Event listener invoked upon receiving response data.
	*
	* @private
	* @param {String} chunk - data chunk
	* @returns {Void}
	*/
	function onData( chunk ) {
		body += chunk;
	} // end FUNCTION onData()

	/**
	* FUNCTION: onEnd()
	*	Event listener invoked upon a response end.
	*
	* @private
	* @returns {Void}
	*/
	function onEnd() {
		var data;
		if ( err ) {
			err.message = body;
			return onError( err );
		}
		// debug( 'Response body: %s', body );

		data = parse( body );
		if ( data instanceof Error ) {
			err = {
				'status': 502,
				'message': 'unable to parse endpoint response data as JSON: ' + data.message
			};
			return onError( err );
		}
		clbk( null, res, data );
	} // end FUNCTION onEnd()
}
1072503
function(options, callback, opt_data) {
  var request = http.request(options, function(response) {
    if (response.statusCode == 302 || response.statusCode == 303) {
      try {
        var location = url.parse(response.headers['location']);
      } catch (ex) {
        callback(Error(
            'Failed to parse "Location" header for server redirect: ' +
            ex.message + '\nResponse was: \n' +
            new HttpResponse(response.statusCode, response.headers, '')));
        return;
      }

      if (!location.hostname) {
        location.hostname = options.host;
        location.port = options.port;
      }

      request.abort();
      sendRequest({
        method: 'GET',
        host: location.hostname,
        path: location.pathname + (location.search || ''),
        port: location.port,
        headers: {
          'Accept': 'application/json; charset=utf-8'
        }
      }, callback);
      return;
    }

    var body = [];
    response.on('data', body.push.bind(body));
    response.on('end', function() {
      var resp = new HttpResponse(response.statusCode,
          response.headers, body.join('').replace(/\0/g, ''));
      callback(null, resp);
    });
  });

  request.on('error', function(e) {
    if (e.code === 'ECONNRESET') {
      setTimeout(function() {
        sendRequest(options, callback, opt_data);
      }, 15);
    } else {
      var message = e.message;
      if (e.code) {
        message = e.code + ' ' + message;
      }
      callback(new Error(message));
    }
  });

  if (opt_data) {
    request.write(opt_data);
  }

  request.end();
}
374470
function( options, callback ) {

    debug( 'schedule', options )

    var self = this

    var protocol = options.protocol || 'rest'
    var format = options.format || 'json'
    var baseUrl = 'schedules/' + protocol + '/v1/' + format + '/flight'

    var carrier = options.airlineCode
    var flightNumber = options.flightNumber
    var year = options.date.getFullYear()
    var month = options.date.getMonth() + 1
    var day = options.date.getDate()
    var direction = /^dep/i.test( options.direction ) ?
      'departing' : 'arriving'

    var extensions = [
      'includeDirects',
      'includeCargo',
      'useInlinedReferences'
    ]

    if( Array.isArray( options.extendedOptions ) ) {
      extensions = extensions.concat( options.extendedOptions )
    }

    return this._clientRequest({
      url: baseUrl + '/' + carrier + '/' + flightNumber + '/' + direction + '/' + year + '/' + month + '/' + day,
      extendedOptions: extensions,
    }, function( error, data ) {

      if( data != null ) {
        data = FlightStats.formatSchedule( data )
        if( options.airport && data.flights ) {
          data.flights = FlightStats.filterByAirport( data.flights, options.airport, options.direction )
        }
      }

      callback.call( self, error, data )

    })

  }
530426
function (option, handler, trace) {
    return function (req, res, next) {

        if (option.v) {
            if (req.version != option.v) {
                if(trace){
                    logger(colors.yellow('SKIP ROUTE: %s {v:%s, c:%s} %s'), req.method, option.v, option.c, req.route.path);
                }
                return next();
            }
        }

        if (option.c) {
            if (req.channel != option.c) {
                if(trace){
                    logger(colors.yellow('SKIP ROUTE: %s {v:%s, c:%s} %s'), req.method, option.v, option.c, req.route.path);
                }
                return next();
            }
        }

        if(trace){
            logger(colors.green('MATCH ROUTE: %s {v:%s, c:%s} %s'), req.method, option.v, option.c, req.route.path);
        }

        handler(req, res, next);
    };
}
847908
public TransportApiResult<List<Stop>> getStops(StopQueryOptions options)
    {
    	if (options == null)
    	{
    		options = StopQueryOptions.defaultQueryOptions();
    	}
    	
    	return TransportApiClientCalls.getStops(tokenComponent, settings, options, null, null, null);
    }
123205
function(params, headers, callback) {
        var url;
        url = this.client.url(false);
        return this.client.get(url, params, headers, callback);
      }
508033
function getStatus(options, callback) {
  if (typeof options === 'function') {
      callback = options;
  }
  if (typeof callback !== 'function') {
      callback = function() {};
  }
  if (!core.session) {
    throw new Error('You must call init() before getStatus()');
  }

  if (options && options.force) {
    updateSession(function(err, session) {
      callback(err, makeSession(session || core.session));
    });
  } else {
    callback(null, makeSession(core.session));
  }
}
437200
function checkConnection(options, cb) {
    if (count < options.attempts) {
        connectServer(options, callback);
    } else {
        var avg = results.reduce(function(prev, curr) { return prev + curr.time; }, 0);
        var max = results.reduce(function(prev, curr) { return (prev > curr.time) ? prev : curr.time; }, results[0].time);
        var min = results.reduce(function(prev, curr) { return (prev < curr.time) ? prev : curr.time; }, results[0].time);

        avg = avg / results.length;
        var out = {
            address:  options.address,
            port:     options.port,
            attempts: options.attempts,
            avg:      avg,
            max:      max,
            min:      min,
            results:  results
        };

        cb(undefined, out);
    }
}
407377
function getClient(callback) {
  if (!connectionOptions) {
    callback('Connection options missing. Please call db.connect before any other database functions to configure the database configuration');
  }

  if (activeBackend === 'mysql') {
    if (activeDb) {
      return callback(null, activeDb);
    }
    else {
      connect(connectionOptions);
      return callback(null, activeDb);
    }
  }
  else if (activeBackend === 'pgsql') {
    return pg.connect(connectionOptions, callback);
  }
}