_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q11900
getMetaData
train
function getMetaData (data) { if (typeof data !== 'string') { throw new MeowError ('data is not a string'); } data = data || ''; data = data.split('\n'); if (('' + data[0]).trim() !== '<!--') { throw new MeowError ("Incorrect format : Missing '<!--' in the beginning of the file"); } var index = 1, metaData = [], dataLen = data.length; while (index < dataLen && ('' + data[index]).trim() !== '-->' ) { metaData.push(data[index]); index++; } if (index == dataLen) { throw new MeowError ("Incorrect format : Missing closing '-->' for metadata comment"); } metaData = metaData.join('\n'); metaData = yaml.parse(metaData); if (!metaData.tags || typeof metaData.tags !== 'string') { metaData.tags = ''; } metaData.tags = metaData.tags.split(','); metaData.tags = _.map(metaData.tags, function (tag) { return tag.trim(); }); if (!metaData.keywords || typeof metaData.keywords !== 'string') { metaData.keywords = ''; } metaData.keywords = metaData.keywords.split(','); metaData.keywords = _.map(metaData.keywords, function (tag) { return tag.trim(); }); return metaData; }
javascript
{ "resource": "" }
q11901
generateSlug
train
function generateSlug (title) { if (typeof title !== 'string') { throw new MeowError ('title is not a string'); } title = title || ''; title = title.toLocaleLowerCase().replace(/[\W]/g, '-').replace(/[\-]{2,}/g, '-'); return title; }
javascript
{ "resource": "" }
q11902
sortPostsByPublishedDate
train
function sortPostsByPublishedDate (pPosts) { if (! (pPosts instanceof Array) ) { throw new MeowError ("pPosts is not an array"); } pPosts.sort(function (pFirst, pSecond) { pFirst = pFirst || {}; pSecond = pSecond || {}; var pFirstPublishedDate = pFirst['published-date'], pSecondPublishedDate = pSecond['published-date']; if (moment(pFirstPublishedDate).isAfter(pSecondPublishedDate)) { return -1; } else if (moment(pFirstPublishedDate).isBefore(pSecondPublishedDate)) { return 1; } else { return pFirst.title.localeCompare(pSecond.title); } }); return pPosts; }
javascript
{ "resource": "" }
q11903
getFilePathRelativeToAppRoot
train
function getFilePathRelativeToAppRoot (pPath) { // go to meow-blog directory var projectBaseDirectory = path.resolve(__dirname, '..'); if (projectBaseDirectory.indexOf('node_modules') !== -1) { // from meow-blog, go up to node_modules, then go to base directory projectBaseDirectory = path.resolve(projectBaseDirectory, '..', '..'); } return path.resolve(projectBaseDirectory, pPath); }
javascript
{ "resource": "" }
q11904
set
train
function set(app, prop, val) { var data = app.cache.data.project; if (typeof val !== 'undefined') { data[prop] = val; } else if (typeof app.cache.data[prop] !== 'undefined') { data[prop] = app.cache.data[prop]; } }
javascript
{ "resource": "" }
q11905
assertPublisherOptions
train
function assertPublisherOptions(options) { mod_assert.object(options, 'options'); mod_assert.object(options.log, 'options.log'); mod_assert.object(options.moray, 'options.moray'); mod_assert.string(options.moray.bucketName, 'options.moray.bucketName'); mod_assert.optionalObject(options.backoff, 'options.backoff'); mod_assert.optionalObject(options.moray.client, 'options.moray.client'); mod_assert.optionalObject(options.restifyServer, 'options.restifyServer'); if (options.moray.client === undefined || options.moray.client === null) { mod_assert.string(options.moray.host, 'options.moray.host'); mod_assert.number(options.moray.port, 'options.moray.port'); } else { mod_assert.equal(options.moray.host, undefined, 'options.moray.host'); mod_assert.equal(options.moray.port, undefined, 'options.moray.port'); } }
javascript
{ "resource": "" }
q11906
_bucketInit
train
function _bucketInit() { morayClient.getBucket(self.morayBucket.name, function _gb(err) { if (isBucketNotFoundError(err)) { var name = self.morayBucket.name; var config = self.morayBucket.config; morayClient.createBucket(name, config, function _cb(err2) { log.info({ n: name, c: config }, 'cf: creating bucket'); if (err2) { log.error({ cErr: err2 }, 'cf: Bucket not created'); expBackoff.backoff(); } else { log.info('cf: Bucket successfully setup'); self.emit('moray-ready'); expBackoff.reset(); } }); } else if (err) { log.error({ cErr: err }, 'cf: Bucket was not loaded'); expBackoff.backoff(); } else { log.info('cf: Bucket successfully setup'); self.emit('moray-ready'); expBackoff.reset(); } }); }
javascript
{ "resource": "" }
q11907
removePendingReq
train
function removePendingReq() { var idx = indexOf($http.pendingRequests, config); if (idx !== -1) { $http.pendingRequests.splice(idx, 1); config.$iframeTransportForm.remove(); delete config.$iframeTransportForm; } }
javascript
{ "resource": "" }
q11908
parse_domain
train
function parse_domain (line) { debug.assert(line).is('string'); // -S-G-J ==> "tili-lii.fi 2017-06-02" // +S-G-J ==> "tili-lii.fi 2017-06-02 lock" // +S+G-J ==> "tili-lii.fi 2017-06-02 lock @creator true 0 undef" // -S+G-J ==> "tili-lii.fi 2017-06-02 @creator true 0 undef" // -S-G+J ==> "tili-lii.fi 2017-06-02 0" // +S+G+J ==> "tili-lii.fi 2017-06-02 lock @creator true 0 undef 0" //debug.log('line = "' + line + '"'); var tmp = line.split(' '); //debug.log('tmp = ', tmp); var domain = tmp.shift(); var exp_date = tmp.shift(); var obj = { 'domain': domain, 'expiration': exp_date }; debug.assert(obj.domain).is('string'); debug.assert(obj.expiration).is('string'); if (showstatus) { obj.status = tmp.shift().split(','); debug.assert(obj.status).is('array'); } if (showjokerns) { obj.jokerns = parse_jokerns(tmp.pop()); debug.assert(obj.jokerns).is('boolean'); } if (showgrants) { obj.grants = tmp.join(' '); debug.assert(obj.grants).is('string'); } if (tmp.length !== 0) { throw new TypeError("Failed to parse everything: " + tmp.join(',')); } //debug.log("obj = ", obj); return obj; }
javascript
{ "resource": "" }
q11909
processData
train
function processData(err, data) { if (enc) { file.text = data.toString(enc); } else { file.buffer = data; } if (entry.sha) { file.sha = entry.sha; } append(err, file); readDone(); }
javascript
{ "resource": "" }
q11910
handleReject
train
function handleReject(carousel) { $element.css({ 'height': carousel.getOuterHeight() + 'px' }); vm.isLoading = false; vm.isSuccessful = false; }
javascript
{ "resource": "" }
q11911
create
train
function create(stylesObject) { const stylesToClasses = {}; const styleNames = Object.keys(stylesObject); const sharedState = globalCache.get(GLOBAL_CACHE_KEY) || {}; const { namespace = '' } = sharedState; styleNames.forEach((styleName) => { const className = getClassName(namespace, styleName); stylesToClasses[styleName] = className; }); return stylesToClasses; }
javascript
{ "resource": "" }
q11912
resolve
train
function resolve(stylesArray) { const flattenedStyles = flat(stylesArray, Infinity); const { classNames, hasInlineStyles, inlineStyles } = separateStyles(flattenedStyles); const specificClassNames = classNames.map((name, index) => `${name} ${name}_${index + 1}`); const className = specificClassNames.join(' '); const result = { className }; if (hasInlineStyles) result.style = inlineStyles; return result; }
javascript
{ "resource": "" }
q11913
train
function(file, done){ process.nextTick(function () { terra.render(file, function(error, body){ if(error){ done(error); }else{ if(body){ var dest = path.resolve(outputPath, ssr.helpers.outputPath(file)); fs.mkdirp(path.dirname(dest), function(err){ fs.writeFile(dest, body, done); }); }else{ done(); } } }); }); }
javascript
{ "resource": "" }
q11914
search
train
function search(db, origin, destination, departure, options, callback) { _log("====== STARTING SEARCH ======"); _log("ORIGIN: " + origin.name); _log("DESTINATION: " + destination.name); _log("DATE/TIME: " + departure.toString()); _log("OPTIONS: " + JSON.stringify(options, null, 2)); // List of Results let RESULTS = []; // Get the initial Trip Search Dates _getTripSearchDates(db, departure, options.preDepartureHours*60, options.postDepartureHours*60, function(err, tripSearchDates) { _log("===== SEARCH TIME RANGE ====="); for ( let i = 0; i < tripSearchDates.length; i++ ) { _log(JSON.stringify(tripSearchDates[i], null, 2)); } // Database Query Error if ( err ) { return callback(err); } // Get the Initial Trips _getTripsFromStop(db, origin, destination, origin, tripSearchDates, [], function(err, direct, indirect) { _log("======= INITIAL TRIPS ======="); _log("DIRECT TRIPS: " + direct.length); _log("INDIRECT TRIPS: " + indirect.length); // Database Query Error if ( err ) { return callback(err); } // Process Direct Trips for ( let i = 0; i < direct.length; i++ ) { let trip = direct[i]; // Create a new Trip Search Result Segment let segment = new TripSearchResultSegment(trip, origin, destination); // Create new Trip Search Result let result = new TripSearchResult(segment); // Add Result to List RESULTS.push(result); } // Process Indirect Trips, if transfers are allowed if ( indirect.length > 0 && options.allowTransfers ) { _log("====== TRANSFER SEARCH ======"); // Process the Indirect Trips _processTrips(db, options, origin, destination, origin, indirect, [], function(err, results) { _log("=== TRANSFER SEARCH RETURN =="); // Add results to final list RESULTS = RESULTS.concat(results); // Finish _finish(); }); } // No transfers required or disabled, finish else { _finish(); } }); }); /** * Finished processing all trips, get Results ready to return * @private */ function _finish() { _log("============================="); // Clean the Results RESULTS = _cleanResults(RESULTS); // Return the Results return callback(null, RESULTS); } }
javascript
{ "resource": "" }
q11915
_cleanDepartures
train
function _cleanDepartures(results) { // List of Departures to Keep let departures = []; // Get unique departures let departureTimes = []; for ( let i = 0; i < results.length; i++ ) { if ( departureTimes.indexOf(results[i].origin.departure.toTimestamp()) === -1 ) { departureTimes.push(results[i].origin.departure.toTimestamp()); } } // Pick best Trip for each departure for ( let i = 0; i < departureTimes.length; i++ ) { let departureTime = departureTimes[i]; let departure = undefined; // Get Trips with departure time for ( let j = 0; j < results.length; j++ ) { let result = results[j]; if ( result.origin.departure.toTimestamp() === departureTime ) { if ( departure === undefined ) { departure = result; } else if ( result.destination.arrival.toTimestamp() < departure.destination.arrival.toTimestamp() ) { departure = result; } else if ( result.destination.arrival.toTimestamp() === departure.destination.arrival.toTimestamp() && result.length < departure.length ) { departure = result; } } } // Add departure to list departures.push(departure); } // Return departures return departures; }
javascript
{ "resource": "" }
q11916
_cleanArrivals
train
function _cleanArrivals(results) { // List of Arrivals to Keep let arrivals = []; // Get unique arrivals let arrivalTimes = []; for ( let i = 0; i < results.length; i++ ) { if ( arrivalTimes.indexOf(results[i].destination.arrival.toTimestamp()) === -1 ) { arrivalTimes.push(results[i].destination.arrival.toTimestamp()); } } // Pick best Trip for each arrival for ( let i = 0; i < arrivalTimes.length; i++ ) { let arrivalTime = arrivalTimes[i]; let arrival = undefined; // Get Trips with arrival time for ( let j = 0; j < results.length; j++ ) { let result = results[j]; if ( result.destination.arrival.toTimestamp() === arrivalTime ) { if ( arrival === undefined ) { arrival = result; } else if ( result.origin.departure.toTimestamp() > arrival.origin.departure.toTimestamp() ) { arrival = result; } else if ( result.origin.departure.toTimestamp() === arrival.origin.departure.toTimestamp() && result.length < arrival.length ) { arrival = result; } } } // Add arrival to list arrivals.push(arrival); } // Return arrivals return arrivals; }
javascript
{ "resource": "" }
q11917
_processTrips
train
function _processTrips(db, options, origin, destination, enter, trips, segments, callback) { // Display function logs _info(); // Results to Return let RESULTS = []; // Set up counters let done = 0; let count = trips.length; // Finish when there are no trips to process if ( trips.length === 0 ) { _finish(); } // Process each of the Trips for ( let i = 0; i < trips.length; i++ ) { _processTrip(db, options, origin, destination, enter, trips[i], segments, function(err, results) { // Database Query Error if ( err ) { return callback(err); } // Add Results to final list RESULTS = RESULTS.concat(results); // Finish _finish(); }) } /** * Finished Processing the Trips * @private */ function _finish() { done++; if ( count === 0 || done === count ) { return callback(null, RESULTS); } } /** * Display function logging info * @private */ function _info() { if ( LOG ) { let p = ""; for ( let i = 0; i < segments.length * 2; i++ ) { p = p + " "; } let tripIds = []; for ( let i = 0; i < trips.length; i++ ) { tripIds.push(trips[i].id); } _log(p + "Trips From " + enter.name + ": " + trips.length + " ('" + tripIds.join("', '") + "')"); _log(p + " Segments: " + segments.length); _printSegments(segments, p + " "); } } }
javascript
{ "resource": "" }
q11918
_info
train
function _info() { if ( LOG ) { let p = ""; for ( let i = 0; i < segments.length * 2; i++ ) { p = p + " "; } let tripIds = []; for ( let i = 0; i < trips.length; i++ ) { tripIds.push(trips[i].id); } _log(p + "Trips From " + enter.name + ": " + trips.length + " ('" + tripIds.join("', '") + "')"); _log(p + " Segments: " + segments.length); _printSegments(segments, p + " "); } }
javascript
{ "resource": "" }
q11919
_info
train
function _info(stops) { if ( LOG ) { let p = ""; for ( let i = 0; i < segments.length * 2; i++ ) { p = p + " "; } _log(p + "...Trip " + trip.id); _log(p + " Stop: " + enter.name + " @ " + trip.getStopTime(enter).departure.getTimeReadable()); _log(p + " Segments: " + segments.length); _printSegments(segments, p + " "); let stopNames = []; for ( let i = 0; i < stops.length; i++ ) { stopNames.push(stops[i].name); } _log(p + " Transfer Stops: " + stops.length + " (" + stopNames.join(', ') + ")"); } }
javascript
{ "resource": "" }
q11920
_getTransferStops
train
function _getTransferStops(db, origin, destination, stop, trip, callback) { // List of Transfer Stops let rtn = []; // Get Next Stops from this Stop LineGraphTable.getNextStops(db, origin.id, destination.id, stop.id, function(err, nextStops) { // Database Query Error if ( err ) { return callback(err); } // Get Remaining Stops on Trip let remainingStops = []; let stopFound = false; for ( let i = 0; i < trip.stopTimes.length; i++ ) { if ( !stopFound && trip.stopTimes[i].stop.id === stop.id ) { stopFound = true; } else if ( stopFound ) { remainingStops.push(trip.stopTimes[i].stop.id); } } // Get Next Stops that are remaining on this Trip for ( let i = 0; i < nextStops.length; i++ ) { if ( remainingStops.indexOf(nextStops[i]) > -1 ) { rtn.push( trip.getStopTime(nextStops[i]).stop ); } } // Return only the top 3 transfer Stops if ( rtn.length > 3 ) { rtn = [rtn[0], rtn[1], rtn[2]]; } return callback(null, rtn); }); }
javascript
{ "resource": "" }
q11921
_getTripsFromStop
train
function _getTripsFromStop(db, origin, destination, stop, tripSearchDates, excludeTrips, callback) { // Get all possible following stops LineGraphTable.getNextStops(db, origin.id, destination.id, stop.id, function(err, nextStops) { // Database Query Error if ( err ) { return callback(err); } // Get Trips from Stop query.getTripsFromStop(db, stop, tripSearchDates, nextStops, function(err, trips) { // Database Query Error if ( err ) { return callback(err); } // List of Direct and Indirect Trips let direct = []; let indirect = []; // Sort Trips for ( let i = 0; i < trips.length; i++ ) { if ( excludeTrips.indexOf(trips[i].id) === -1 ) { if ( _tripGoesTo(trips[i], stop, destination) ) { direct.push(trips[i]); } else { indirect.push(trips[i]); } } } // Return the Trips return callback(null, direct, indirect); }); }); }
javascript
{ "resource": "" }
q11922
_getTripSearchDates
train
function _getTripSearchDates(db, datetime, preMins, postMins, callback) { // Get pre and post dates let preDateTime = datetime.clone().deltaMins(-1*preMins); let postDateTime = datetime.clone().deltaMins(postMins); // List of TripSearchDates to return let rtn = []; // Counters let done = 0; let count = 0; // ==== PRE AND POST DATES ARE SAME DAY ==== // if ( preDateTime.getDateInt() === postDateTime.getDateInt() ) { count = 1; // Get Effective Services CalendarTable.getServicesEffective(db, datetime.getDateInt(), function(err, services) { // Database Query Error if ( err ) { return callback(err); } // Create new TripSearchDate let tsd = new TripSearchDate( preDateTime.getDateInt(), preDateTime.getTimeSeconds(), postDateTime.getTimeSeconds(), services ); // Add to List rtn.push(tsd); // Finish _finish(); }); } // ==== PRE AND POST DATES ARE DIFFERENT DAYS ==== // else { count = 2; // Get Effective Services for Prev Day CalendarTable.getServicesEffective(db, preDateTime.getDateInt(), function(err, services) { // Database Query Error if ( err ) { return callback(err); } // Create new TripSearchDate let tsd = new TripSearchDate( preDateTime.getDateInt(), preDateTime.getTimeSeconds(), postDateTime.getTimeSeconds() + 86400, services ); // Add to List rtn.push(tsd); // Finish _finish(); }); // Get Effective Services for Post Day CalendarTable.getServicesEffective(db, postDateTime.getDateInt(), function(err, services) { // Database Query Error if ( err ) { return callback(err); } // Create new TripSearchDate let tsd = new TripSearchDate( postDateTime.getDateInt(), 0, postDateTime.getTimeSeconds(), services ); // Add to List rtn.push(tsd); // Finish _finish(); }); } // Finish processing a Trip Search Date function _finish() { done++; if ( done === count ) { return callback(null, rtn); } } }
javascript
{ "resource": "" }
q11923
train
function (db, options, cb) { this.db = db; this.cb = cb; this.updateQueryMaker = options.update; this.insertQueryMaker = options.insert; this.maxUpdateAttemptsCount = options.maxUpdateAttemptsCount || 2; this.transform = options.transform; this.insertFirst = !!options.insertFirst; this.nonQuery = !!options.nonQuery; var self = this; this.updateAttemptsCount = 0; this.updateOrInsertBound = function () { self.updateOrInsert(); }; }
javascript
{ "resource": "" }
q11924
clientConnects
train
function clientConnects(p) { var pList; var nPlayers; var waitTime; var widgetConfig; node.remoteSetup('page', p.id, { clearBody: true, title: { title: 'Welcome!', addToBody: true } }); node.remoteSetup('widgets', p.id, { destroyAll: true, append: { 'WaitingRoom': {} } }); if (waitRoom.isRoomOpen()) { console.log('Client connected to waiting room: ', p.id); // Mark code as used. channel.registry.markInvalid(p.id); pList = waitRoom.clients.player; nPlayers = pList.size(); if (waitRoom.START_DATE) { waitTime = new Date(waitRoom.START_DATE).getTime() - (new Date().getTime()); } else if (waitRoom.MAX_WAIT_TIME) { waitTime = waitRoom.MAX_WAIT_TIME; } else { waitTime = null; // Widget won't start timer. } // Send the number of minutes to wait and all waitRoom settings. widgetConfig = waitRoom.makeWidgetConfig(); widgetConfig.waitTime = waitTime; node.remoteSetup('waitroom', p.id, widgetConfig); console.log('NPL ', nPlayers); // Notify all players of new connection. node.say('PLAYERSCONNECTED', 'ROOM', nPlayers); // Start counting a timeout for max stay in waiting room. waitRoom.makeTimeOut(p.id, waitTime); // Wait for all players to connect. if (nPlayers < waitRoom.POOL_SIZE) return; if (waitRoom.EXECUTION_MODE === 'WAIT_FOR_N_PLAYERS') { waitRoom.dispatch({ action: 'AllPlayersConnected', exit: 0 }); } } else { node.say('ROOM_CLOSED', p.id); } }
javascript
{ "resource": "" }
q11925
getServicesEffective
train
function getServicesEffective(db, date, callback) { // Check Cache for Effective Services let cacheKey = db.id + "-" + date; let cache = cache_servicesEffectiveByDate.get(cacheKey); if ( cache !== null ) { return callback(null, cache); } // Get the Default Services getServicesDefault(db, date, function(defaultError, defaultServices) { // Get the Service Exceptions getServiceExceptions(db, date, function(exceptionsError, serviceExceptions) { // Check for Default Services Error if ( defaultError ) { return callback(defaultError); } // Check for Service Exceptions Error if ( exceptionsError ) { return callback(exceptionsError); } // List of Service IDs to Add to Default Services let serviceIdsToAdd = []; // Parse the exceptions for ( let i = 0; i < serviceExceptions.length; i++ ) { let serviceException = serviceExceptions[i]; // Exception Type: Added if ( serviceException.exceptionType === ServiceException.SERVICE_ADDED ) { // Make sure service isn't already in list let found = false; for ( let j = 0; j < defaultServices.length; j++ ) { if ( defaultServices[j].id === serviceException.serviceId ) { found = true; } } // Flag Service ID to add if ( !found ) { serviceIdsToAdd.push(serviceException.serviceId); } } // Exception Type: Removed else if ( serviceException.exceptionType === ServiceException.SERVICE_REMOVED ) { // Find matching default service let removeIndex = -1; for ( let j = 0; j < defaultServices.length; j++ ) { if ( defaultServices[j].id === serviceException.serviceId ) { removeIndex = j; } } // Remove the matching service from default services list if ( removeIndex !== -1 ) { defaultServices.splice(removeIndex, 1); } } } // Add services, if we need to if ( serviceIdsToAdd.length > 0 ) { getService(db, serviceIdsToAdd, function(err, services) { // Error Getting Services if ( err ) { return callback(err); } // Add Services to list for (let i = 0; i < services.length; i++) { let service = services[i]; defaultServices.push(service); } // Add Services to Cache cache_servicesEffectiveByDate.put(cacheKey, defaultServices); // Return Services return callback(null, defaultServices); }); } // Return Default Services else { // Add Services to Cache cache_servicesEffectiveByDate.put(cacheKey, defaultServices); return callback(null, defaultServices); } }); }); }
javascript
{ "resource": "" }
q11926
train
function(db, date, callback) { // Check cache for services let cacheKey = db.id + "-" + date; let cache = cache_servicesDefaultByDate.get(cacheKey); if ( cache !== null ) { return callback(null, cache); } // Array of default services to return let rtn = []; // Get day of week let dt = DateTime.createFromDate(date); let dow = dt.getDateDOW(); // Get default services let select = "SELECT service_id, monday, tuesday, wednesday, thursday, friday, " + "saturday, sunday, start_date, end_date FROM gtfs_calendar WHERE " + dow + "=" + Service.SERVICE_AVAILABLE + " AND start_date<=" + date + " AND " + "end_date>=" + date + ";"; // Query the database db.select(select, function(err, results) { // Database Query Error if ( err ) { return callback(err); } // Parse each row in the results... for ( let i = 0; i < results.length; i++ ) { let row = results[i]; let service = new Service( row.service_id, row.monday, row.tuesday, row.wednesday, row.thursday, row.friday, row.saturday, row.sunday, row.start_date, row.end_date ); rtn.push(service); } // Add Services to Cache cache_servicesDefaultByDate.put(cacheKey, rtn); // Return the default services with provided callback return callback(null, rtn); }); }
javascript
{ "resource": "" }
q11927
train
function(db, date, callback) { // Check cache for service exceptions let cacheKey = db.id + "-" + date; let cache = cache_serviceExceptionsByDate.get(cacheKey); if ( cache !== null ) { return callback(null, cache); } // Array of Service Exceptions to return let rtn = []; // Get service exceptions from calendar_dates let select = "SELECT service_id, date, exception_type " + "FROM gtfs_calendar_dates WHERE date=" + date + ";"; // Query the database db.select(select, function(err, results) { // Database Query Error if ( err ) { return callback(err); } // Parse each row in the results for ( let i = 0; i < results.length; i++ ) { let row = results[i]; // Create Service Exception let se = new ServiceException( row.service_id, row.date, row.exception_type ); // Add Service Exception to return list rtn.push(se); } // Add Service Exceptions to cache cache_serviceExceptionsByDate.put(cacheKey, rtn); // Return service exceptions with provided callback return callback(null, rtn); }); }
javascript
{ "resource": "" }
q11928
getTransform
train
function getTransform(options) { if (typeof options === 'string' || options instanceof String) { return options } if (typeof options === 'object' && options.engine) { return options.engine } throw new Error('options.engine not found.') }
javascript
{ "resource": "" }
q11929
constructTransformer
train
function constructTransformer(options) { const transform = getTransform(options) if (transform && typeof transform === 'object') { return jstransformer(transform) } return jstransformer(require('jstransformer-' + transform)) }
javascript
{ "resource": "" }
q11930
makeInterfaceValidator
train
function makeInterfaceValidator(interfacePropArrays) { var props = flatten(interfacePropArrays); return function(base) { var missingProps = props.reduce(function(missing, prop) { return prop in base ? missing : missing.concat(prop); }, []); return missingProps.length ? {message:"missing expected properties", related: missingProps} : undefined; }; }
javascript
{ "resource": "" }
q11931
getLinks
train
function getLinks(db, callback) { // Check cache for links let cacheKey = db.id + "-" + 'links'; let cache = cache_links.get(cacheKey); if ( cache !== null ) { return callback(null, cache); } // Build select statement let select = "SELECT link_category_title, link_title, link_description, link_url FROM rt_links;"; // Query the database db.select(select, function(err, results) { // Database Query Error if ( err ) { return callback(err); } // List of links to return let rtn = []; // Parse each row for ( let i = 0; i < results.length; i++ ) { let row = results[i]; // Build the link let link = new Link( row.link_category_title, row.link_title, row.link_description, row.link_url ); // Add link to list rtn.push(link); } // Add links to cache cache_links.put(cacheKey, rtn); // Return the links with the callback return callback(null, rtn); }); }
javascript
{ "resource": "" }
q11932
train
function () { /** * Get a valid file path for a template file from a set of directories * @param {Object} opts Configurable options (see periodicjs.core.protocols for more details) * @param {string} [opts.extname] Periodic extension that may contain view file * @param {string} opts.viewname Name of the template file * @param {string} [opts.themefileext="periodicjs.theme.default"] Periodic theme that may contain view file * @param {string} [opts.viewfileext=".ejs"] File extension type * @param {Function} callback Callback function * @return {Object} Returns a Promise which resolves with file path if cb argument is not passed */ let fn = function getPluginViewDefaultTemplate (opts = {}, callback) { let { extname, viewname, themefileext, viewfileext } = opts; let themename = this.theme; let fileext = (typeof themefileext === 'string') ? themefileext : viewfileext; return this._utility_responder.render({}, Object.assign(opts, { themename, fileext, resolve_filepath: true }), callback); }; let message = 'CoreController.getPluginViewDefaultTemplate: Use CoreController.responder.render with a HTML adapter or CoreController._utility_responder.render instead'; return wrapWithDeprecationWarning.call(this, fn, message); }
javascript
{ "resource": "" }
q11933
respondInKind
train
function respondInKind (opts = {}, callback) { let { req, res, responseData, err } = opts; opts.callback = (typeof opts.callback === 'function') ? opts.callback : callback; if ((path.extname(req.originalUrl) === '.html' || req.is('html') || req.is('text/html') || path.extname(req.originalUrl) === '.htm') || typeof opts.callback === 'function') { return this.protocol.respond(req, res, { data: responseData, err, return_response_data: true }) .try(result => { if (typeof opts.callback === 'function') opts.callback(req, res, result); else return Promisie.resolve(result); }) .catch(e => { if (typeof opts.callback === 'function') callback(e); else return Promisie.reject(e); }); } else if (req.redirecturl) { req.redirectpath = (!req.redirectpath && req.redirecturl) ? req.redirecturl : req.redirectpath; return this.protocol.redirect(req, res); } else { let settings = (this.protocol && this.protocol.settings) ? this.protocol.settings : false; if (settings && settings.sessions && settings.sessions.enabled && req.session) req.flash = req.flash.bind(req); else req.flash = null; return this.protocol.respond(req, res, { data: responseData, err }); } }
javascript
{ "resource": "" }
q11934
train
function () { /** * Renders a view from template and sends data to client * @param {Object} opts Configurable options (see periodicjs.core.responder for more details) * @param {string} opts.extname Periodic extension which may have template in view folder * @param {string} opts.viewname Name of template file * @param {string} opts.themefileext Periodic theme which may have template in view folder * @param {string} opts.viewfileext The file extension of the view file * @param {Object} opts.req Express request object * @param {Object} opts.res Express response object * @param {Function} [callback] Optional callback function * @return {Function} If callback is not defined returns a Promise which resolves with rendered template */ let fn = function handleDocumentQueryRender (opts = {}, callback) { let { extname, viewname, themefileext, viewfileext, responseData } = opts; let themename = this.theme; let fileext = (typeof themefileext === 'string') ? themefileext : viewfileext; return this._utility_responder.render(responseData || {}, Object.assign(opts, { themename, fileext, skip_response: true })) .then(result => { this.protocol.respond(opts.req, opts.res, { responder_override: result }); if (typeof callback === 'function') callback(null, result); else return Promisie.resolve(result); }) .catch(e => { this.protocol.error(opts.req, opts.res, { err: e }); if (typeof callback === 'function') callback(e); else return Promisie.reject(e); }); }; let message = 'CoreController.handleDocumentQueryRender: Use CoreController.responder.render with an HTML adapter or CoreController._utility_responder.render instead'; return wrapWithDeprecationWarning.call(this, fn, message); }
javascript
{ "resource": "" }
q11935
train
function () { /** * Renders an error view from a template and sends data to client * @param {Object} opts Configurable options (see periodicjs.core.responder for more details) * @param {string|Object} opts.err Error details for response * @param {Object} opts.req Express request object * @param {Object} opts.res Express response object * @param {Function} [callback] Optional callback function * @return {Object} If callback is not defined returns a Promise which resolves after response has been sent */ let fn = function handleDocumentQueryErrorResponse (opts = {}, callback) { let { err, req, res } = opts; if (opts.use_warning) this.protocol.warn(req, res, { err }); else this.protocol.error(req, res, { err }); if (req.query.format === 'json' || req.params.ext === 'json' || path.extname(req.originalUrl) === '.json' || req.is('json') || req.params.callback || req.is('application/json')) { return this.protocol.respond(req, res, { err }); } else if (typeof callback === 'function') { return this.responder.error(err) .then(result => callback(null, result)) .catch(callback); } else if (req.redirecturl) { req.redirectpath = (!req.redirectpath && req.redirecturl) ? req.redirecturl : req.redirectpath; return this.protocol.redirect(req, res); } else { return this._utility_responder.error(err, {}) .then(result => { return this.protocol.respond(req, res, { responder_override: result }); }, err => { return this.protocol.exception(req, res, { err }); }); } }; let message = 'CoreController.handleDocumentQueryErrorResponse: Use CoreController.responder.error with an HTML adapter or CoreController._utility_responder.error instead'; return wrapWithDeprecationWarning.call(this, fn, message); }
javascript
{ "resource": "" }
q11936
train
function () { /** * Returns inflected values from a string ie. application => applications, Application, etc. * @param {Object} options Configurable options * @param {string} options.model_name String that should be inflected * @return {Object} Object containing inflected values indexed by type of inflection */ return function getViewModelProperties (options = {}) { let model_name = options.model_name; let viewmodel = { name: model_name, name_plural: pluralize(model_name) }; return Object.assign(viewmodel, { capital_name: capitalize(model_name), page_plural_title: capitalize(viewmodel.name_plural), page_plural_count: `${ viewmodel.name_plural }count`, page_plural_query: `${ viewmodel.name_plural }query`, page_single_count: `${ model_name }count`, page_pages: `${ model_name }pages` }); }; }
javascript
{ "resource": "" }
q11937
train
function(url, data, type) { assert(Login.app, "You must set Login.app = my-app-name-as-registered-with-you-again"); data.app = Login.app; data.withCredentials = true; // let the server know this is a with-credentials call data.caller = ""+document.location; // provide some extra info // add in local cookie auth const cookies = Cookies.get(); let cbase = cookieBase(); for(let c in cookies) { if (c.substr(0, cbase.length)===cbase) { let cv = Cookies.get(c); data[c] = cv; } } return $.ajax({ dataType: "json", // not really needed but harmless url: url, data: data, type: type || 'GET', xhrFields: {withCredentials: true} }); }
javascript
{ "resource": "" }
q11938
getTripsFromStop
train
function getTripsFromStop(db, stop, tripSearchDates, nextStops, callback) { // List of Trips to Return let rtn = []; // Counters let done = 0; let count = tripSearchDates.length; // Parse each TripSearchDate separately for ( let i = 0; i < tripSearchDates.length; i++ ) { _getTripsFromStop(db, stop, tripSearchDates[i], function(err, trips) { // Database Query Error if ( err ) { return callback(err); } // Check each of the Trips to add for ( let j = 0; j < trips.length; j++ ) { _addTrip(trips[j]); } // Finish the TSD _finish(); }); } /** * Add the specified Trip to the return list, if it is not * already present and it continues to one of the next stops * @param {Trip} trip Trip to add * @private */ function _addTrip(trip) { // Make sure trip isn't already in list let found = false; for ( let i = 0; i < rtn.length; i++ ) { if ( rtn[i].id === trip.id ) { found = true; } } // Process new trip if ( !found ) { // Make sure the trip stops at any of the next stops, after the current stop let stopFound = false; let add = false; for ( let i = 0; i < trip.stopTimes.length; i++ ) { let stopId = trip.stopTimes[i].stop.id; if ( !stopFound && stopId === stop.id ) { stopFound = true; } else if ( stopFound ) { if ( nextStops.indexOf(stopId) > -1 ) { add = true; i = trip.stopTimes.length; } } } // Add Trip if ( add ) { rtn.push(trip); } } } /** * Finish processing the Trip Search Dates * @private */ function _finish() { done++; if ( done === count ) { return callback(null, rtn); } } }
javascript
{ "resource": "" }
q11939
_addTrip
train
function _addTrip(trip) { // Make sure trip isn't already in list let found = false; for ( let i = 0; i < rtn.length; i++ ) { if ( rtn[i].id === trip.id ) { found = true; } } // Process new trip if ( !found ) { // Make sure the trip stops at any of the next stops, after the current stop let stopFound = false; let add = false; for ( let i = 0; i < trip.stopTimes.length; i++ ) { let stopId = trip.stopTimes[i].stop.id; if ( !stopFound && stopId === stop.id ) { stopFound = true; } else if ( stopFound ) { if ( nextStops.indexOf(stopId) > -1 ) { add = true; i = trip.stopTimes.length; } } } // Add Trip if ( add ) { rtn.push(trip); } } }
javascript
{ "resource": "" }
q11940
_getTripsFromStop
train
function _getTripsFromStop(db, stop, tripSearchDate, callback) { // List of trips to return let rtn = []; // Set counters let done = 0; let count = 0; // Build Service ID String let serviceIdString = "'" + tripSearchDate.serviceIds.join("', '") + "'"; // Get Trip IDs let select = "SELECT gtfs_stop_times.trip_id " + "FROM gtfs_stop_times " + "INNER JOIN gtfs_trips ON gtfs_stop_times.trip_id=gtfs_trips.trip_id " + "WHERE stop_id='" + stop.id + "' AND " + "departure_time_seconds >= " + tripSearchDate.preSeconds + " AND departure_time_seconds <= " + tripSearchDate.postSeconds + " AND " + "pickup_type <> " + StopTime.PICKUP_TYPE_NONE + " AND " + "gtfs_trips.service_id IN (" + serviceIdString + ")"; // Select the Trip IDs db.select(select, function(err, results) { // Database Query Error if ( err ) { return callback( new Error('Could not get Trip(s) from database') ); } // No Results if ( results.length === 0 ) { return callback(null, rtn); } // Set the counter count = results.length; // Build the Trips for ( let i = 0; i < results.length; i++ ) { TripsTable.getTrip(db, results[i].trip_id, tripSearchDate.date, function(err, trip) { // Database Query Error if ( err ) { return callback(err); } // Add trip to list rtn.push(trip); // Finish Process the Trip _finish(); }); } }); /** * Finished Processing Trip * @private */ function _finish() { done++; if ( done === count ) { return callback(null, rtn); } } }
javascript
{ "resource": "" }
q11941
getHoliday
train
function getHoliday(db, date, callback) { // Check cache for Holiday let cacheKey = db.id + "-" + date; let cache = cache_holidayByDate.get(cacheKey); if ( cache !== null ) { return callback(null, cache); } // Build the select statement let select = "SELECT date, holiday_name, peak, service_info " + "FROM rt_holidays WHERE date=" + date; // Query the database db.get(select, function(err, result) { // Database Query Error if ( err ) { return callback(err); } // Holiday to return let holiday = undefined; // Holiday was found... if ( result !== undefined ) { // Build the Holiday holiday = new Holiday( result.date, result.holiday_name, result.peak === 1, result.service_info ); } // Add holiday to cache cache_holidayByDate.put(cacheKey, holiday); // Return the holiday return callback(null, holiday); }) }
javascript
{ "resource": "" }
q11942
isHoliday
train
function isHoliday(db, date, callback) { // Check cache for is holiday let cacheKey = db.id + "-" + date; let cache = cache_isHolidayByDate.get(cacheKey); if ( cache !== null ) { return callback(null, cache); } // Get matching holiday let select = "SELECT date, holiday_name, peak, service_info " + "FROM rt_holidays WHERE date=" + date; // Query the database db.get(select, function(err, result) { // Database Query Error if ( err ) { return callback(err); } // Add result to cache cache_isHolidayByDate.put(cacheKey, result !== undefined); // Return if holiday is found with callback return callback(null, result !== undefined); }); }
javascript
{ "resource": "" }
q11943
train
function(src, noEscape) { var attrLen, newKey; if (helper.isArray(src)) { var attrLen = src.length; for (var i = 0; i < attrLen; i++) { src[i] = helper.pasteurize(src[i], noEscape); } } else if (this.isString(src)) { src = helper.scrub(src, noEscape); } else if (helper.isObject(src)) { var newSrc = {}; for (key in src) { newKey = helper.scrub(key); newSrc[newKey] = helper.pasteurize(src[key], noEscape); } src = newSrc; } return src; }
javascript
{ "resource": "" }
q11944
train
function(host, whitelist, next) { var blacklist = this.options.blacklist; helper.resolveHost(host, function(err, aRecords, resolvedHost) { var inBlacklist = false; if (!err) { if (whitelist) { if (_.intersection(aRecords, whitelist).length ) { next(err, [], aRecords); return; } else { for (var i = 0; i < whitelist.length; i++) { if (resolvedHost === whitelist[i]) { next(err, [], aRecords); return; } } } } inBlacklist = _.intersection(aRecords, blacklist) } next(err, inBlacklist, aRecords); }); }
javascript
{ "resource": "" }
q11945
train
function(id, period, callback) { var self = this; if (this.$resource.cron) { if (!this.crons[id]) { self._logger.call(self, 'POD:Registering Cron:' + self.getName() + ':' + id); self.crons[id] = new self.$resource.cron.CronJob( period, callback, null, true, self.options.timezone ); } } }
javascript
{ "resource": "" }
q11946
train
function(message, channel, level) { if (helper.isObject(message)) { this._logger.call(this, channel.action + ':' + (channel.owner_id ? channel.owner_id : 'system'), level); if (message.message) { message = message; } this._logger.call(this, message, level); } else { this._logger.call(this, channel.action + ':' + (channel.owner_id ? channel.owner_id : 'system') + ':' + message, level); } }
javascript
{ "resource": "" }
q11947
train
function(owner_id, next) { var self = this, podName = this.getName(), filter = { owner_id : owner_id, type : this.getAuthType(), oauth_provider : this.getName() }; this._dao.find('account_auth', filter, function(err, result) { var model, authStruct; if (result) { // normalize oauth representation authStruct = { oauth_provider : result.oauth_provider, repr : self._profileRepr(result) } } next(err, podName, filter.type, authStruct); }); }
javascript
{ "resource": "" }
q11948
train
function(channel, next) { var filter = { channel_id : channel.id }, modelName = this.getDataSourceName('dup'); this._dao.removeFilter(modelName, filter, next); }
javascript
{ "resource": "" }
q11949
train
function(action, channel, accountInfo, auth, next) { var self = this, config = this.getConfig(); if (!next && 'function' === typeof auth) { next = auth; } else { if (self.isOAuth()) { if (!auth.oauth) { auth.oauth = {}; } _.each(config.oauth, function(value, key) { auth.oauth[key] = value; }); } accountInfo._setupAuth = auth; } if (this.actions[action] && this.actions[action].teardown) { if (this.getTrackDuplicates()) { // confirm teardown and drop any dup tracking from database this.actions[action].teardown(channel, accountInfo, function(err) { if (err) { self.log(err, channel, 'error'); } next(err); self._dupTeardown(channel); }); } else { this.actions[action].teardown(channel, accountInfo, function(err) { if (err) { self.log(err, channel, 'error'); } next(err); }); } } else { if (this.getTrackDuplicates()) { self._dupTeardown(channel); } next(false); } }
javascript
{ "resource": "" }
q11950
train
function(action, method, sysImports, options, channel, req, res) { var self = this; if (this.actions[action] && (this.actions[action].rpc || 'invoke' === method)) { if ('invoke' === method) { var imports = (req.method === 'GET' ? req.query : req.body); // @todo add files support this.actions[action].invoke(imports, channel, sysImports, [], function(err, exports) { if (err) { self.log(err, channel, 'error'); } res.contentType(DEFS.CONTENTTYPE_JSON); if (err) { res.send(err, 500); } else { res.send(exports); } }); } else { this.actions[action].rpc(method, sysImports, options, channel, req, res); } } else { res.send(404); } }
javascript
{ "resource": "" }
q11951
train
function(accountInfo) { var self = this, rpcs = this.getRPCs(), schema = { 'name' : this.getName(), 'title' : this.getTitle(), 'description' : this.getDescription(), 'icon' : this.getIcon(accountInfo), 'auth' : this.getAuth(), 'rpcs' : this.getRPCs(), 'url' : this.getBPMAttr('url'), 'actions' : this.formatActions(), 'tags' : this.getTags() }, authType = this.getAuth().strategy; // attach auth binders if (authType == 'oauth') { schema.auth.scopes = this.getConfig().oauth.scopes || []; schema.auth._href = self.options.baseUrl + '/rpc/oauth/' + this.getName() + '/auth'; } else if (authType == 'issuer_token') { schema.auth._href = self.options.baseUrl + '/rpc/issuer_token/' + this.getName() + '/set'; } schema.auth.properties = this.getAuthProperties(); return schema; }
javascript
{ "resource": "" }
q11952
train
function(channel, next) { var filter = { channel_id : channel.id, owner_id : channel.owner_id }; this._dao.findFilter('channel_pod_tracking', filter, function(err, result) { next(err || !result, result && result.length > 0 ? result[0].last_poll : null); }); }
javascript
{ "resource": "" }
q11953
train
function(channel, next) { var filter = { channel_id : channel.id, owner_id : channel.owner_id }, self = this, props = { last_poll : helper.nowUTCSeconds() } this._dao.updateColumn( 'channel_pod_tracking', filter, props, function(err) { if (err) { self.log(err, 'error'); } next(err, props.last_poll); } ); }
javascript
{ "resource": "" }
q11954
getStopByName
train
function getStopByName(db, name, callback) { // Check cache for Stop let cacheKey = db.id + "-" + name; let cache = cache_stopByName.get(cacheKey); if ( cache !== null ) { return callback(null, cache); } // Different queries to lookup stop by name let queries = [ "SELECT stop_id FROM gtfs_stops WHERE stop_name='" + name + "' COLLATE NOCASE;", "SELECT stop_id FROM rt_alt_stop_names WHERE alt_stop_name='" + name + "' COLLATE NOCASE;", "SELECT stop_id FROM rt_stops_extra WHERE display_name='" + name + "' COLLATE NOCASE;" ]; // Test each query for the stop name let found = false; let count = 0; for ( let i = 0; i < queries.length; i++ ) { // Perform the specified query _queryForStopByName(db, queries[i], function(stop) { // Return the result: if not already found and the query was successful if ( !found && stop !== undefined ) { found = true; cache_stopByName.put(cacheKey, stop); return callback(null, stop); } // Return after all queries have finished count ++; if ( count === queries.length ) { return callback(null, undefined); } }); } }
javascript
{ "resource": "" }
q11955
_queryForStopByName
train
function _queryForStopByName(db, query, callback) { // Perform the search query db.get(query, function(err, result) { // No stop found, return undefined if ( result === undefined ) { return callback(undefined); } // Stop found, return the Stop from it's ID getStop(db, result.stop_id, function(err, stop) { return callback(stop); }); }); }
javascript
{ "resource": "" }
q11956
getStopByStatusId
train
function getStopByStatusId(db, statusId, callback) { // Make sure statusId is not -1 if ( statusId === "-1" ) { return callback( new Error('Stop does not have a valid Status ID') ); } // Check cache for stop let cacheKey = db.id + "-" + statusId; let cache = cache_stopByStatusId.get(cacheKey); if ( cache !== null ) { return callback(null, cache); } // Build select statement let select = "SELECT gtfs_stops.stop_id, stop_name, stop_desc, stop_lat, stop_lon, stop_url, " + "gtfs_stops.zone_id AS gtfs_zone_id, stop_code, wheelchair_boarding, location_type, parent_station, stop_timezone, " + "rt_stops_extra.status_id, display_name, transfer_weight, rt_stops_extra.zone_id AS rt_zone_id " + "FROM gtfs_stops, rt_stops_extra " + "WHERE gtfs_stops.stop_id=rt_stops_extra.stop_id AND " + "rt_stops_extra.status_id='" + statusId + "';"; // Query the database db.get(select, function(err, result) { // Database Error if ( err ) { return callback(err); } // No Stop found... if ( result === undefined ) { return callback(null, undefined); } // Use rt display_name if provided let final_name = result.stop_name; if ( result.display_name !== undefined && result.display_name !== "" ) { final_name = result.display_name; } // Get zone_id from rt_stops_extra if not defined in gtfs_stops let zone_id = result.gtfs_zone_id; if ( zone_id === null || zone_id === undefined ) { zone_id = result.rt_zone_id; } // build the Stop let stop = new Stop( result.stop_id, final_name, result.stop_lat, result.stop_lon, { code: result.stop_code, description: result.stop_desc, zoneId: zone_id, url: result.stop_url, locationType: result.location_type, parentStation: result.parent_station, timezone: result.stop_timezone, wheelchairBoarding: result.wheelchair_boarding, statusId: result.status_id, transferWeight: result.transfer_weight } ); // Add Stop to cache cache_stopByStatusId.put(cacheKey, stop); // return the Stop in the callback return callback(null, stop); }); }
javascript
{ "resource": "" }
q11957
_parseStopsByLocation
train
function _parseStopsByLocation(stops, lat, lon, count, distance, callback) { // Calc distance to/from each stop for ( let i = 0; i < stops.length; i++ ) { stops[i].setDistance(lat, lon); } // Sort by distance stops.sort(Stop.sortByDistance); // Filter the stops to return let rtn = []; // Return 'count' stops if ( count !== -1 ) { for ( let i = 0; i < count; i++ ) { if ( stops.length > i ) { rtn.push(stops[i]); } } } // No 'count' specified, add all stops else { rtn = stops; } // Filter by distance if ( distance !== -1 ) { let temp = []; for ( let i = 0; i < rtn.length; i++ ) { if ( rtn[i].distance <= distance ) { temp.push(rtn[i]); } } rtn = temp; } // Return the Stops return callback(null, rtn); }
javascript
{ "resource": "" }
q11958
clearCache
train
function clearCache() { cache_stopById.clear(); cache_stopByName.clear(); cache_stopByStatusId.clear(); cache_stops.clear(); cache_stopsByRoute.clear(); }
javascript
{ "resource": "" }
q11959
distance
train
function distance(lat1, lon1, lat2, lon2) { let R = 6371; // Radius of the earth in km let dLat = _deg2rad(lat2-lat1); // deg2rad below let dLon = _deg2rad(lon2-lon1); let a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(_deg2rad(lat1)) * Math.cos(_deg2rad(lat2)) * Math.sin(dLon/2) * Math.sin(dLon/2) ; let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); let d = R * c; // Distance in km return d * 0.621371; // Return distance in miles }
javascript
{ "resource": "" }
q11960
getPaths
train
function getPaths(db, originId, destinationId, callback) { // Get Graph buildGraph(db, function(err, graph) { if ( err ) { return callback(err); } // Paths to return let rtn = []; // Search the Graph for ( let it = graph.paths(originId, destinationId), kv; !(kv = it.next()).done;) { let path = []; for ( let i = 0; i < kv.value.length; i++ ) { let stop = graph.vertexValue(kv.value[i]); path.push({ id: stop.id, weight: stop.transferWeight }); } rtn.push(path); } // Return the paths return callback(null, rtn); }); }
javascript
{ "resource": "" }
q11961
buildGraph
train
function buildGraph(db, callback) { // Check cache for graph let cacheKey = db.id + "-graph"; let cache = cache_graph.get(cacheKey); if ( cache !== null ) { return callback(null, cache); } // Build Graph let graph = new Graph(); // Add the Vertices _addGraphVertices(db, graph, function(err, graph) { // Database Query Error if ( err ) { return callback(err); } // Add Graph Edges _addGraphEdges(db, graph, function(err, graph) { // Database Query Error if ( err ) { return callback(err); } // Return the finished graph cache_graph.put(cacheKey, graph); return callback(null, graph); }); }); }
javascript
{ "resource": "" }
q11962
_addGraphVertices
train
function _addGraphVertices(db, graph, callback) { // Get all Stops StopsTable.getStops(db, function(err, stops) { // Database Query Error if ( err ) { return callback(err); } // Add each Stop as a Vertex for ( let i = 0; i < stops.length; i++ ) { graph.addNewVertex(stops[i].id, stops[i]); } // Return the Graph return callback(null, graph); }); }
javascript
{ "resource": "" }
q11963
_addGraphEdges
train
function _addGraphEdges(db, graph, callback) { // Counters let done = 0; let count = graph.vertexCount(); // Loop through each Vertex in the Graph for ( let [stopId, stop] of graph ) { // Get the Edges for the Vertex _getStopEdges(db, stopId, function(err, edges) { // Database Query Error if ( err ) { return callback(err); } // Add each edge to the Graph for ( let i = 0; i < edges.length; i++ ) { graph.ensureEdge(stopId, edges[i]); graph.ensureEdge(edges[i], stopId); } // Finish the Vertex _finish(); }); } // Keep track of finished vertices function _finish() { done++; if ( done === count ) { return callback(null, graph); } } }
javascript
{ "resource": "" }
q11964
createZoneSocket
train
function createZoneSocket(options, callback) { if (!options) throw new TypeError('options required'); if (!(options instanceof Object)) { throw new TypeError('options must be an Object'); } if (!options.zone) throw new TypeError('options.zone required'); if (!options.path) throw new TypeError('options.path required'); if (!callback) throw new TypeError('callback required'); if (!(callback instanceof Function)) { throw new TypeError('callback must be a Function'); } var backlog = options.backlog ? options.backlog : 5; bindings.zsocket(options.zone, options.path, backlog, callback); }
javascript
{ "resource": "" }
q11965
getStopTimeByTripStop
train
function getStopTimeByTripStop(db, tripId, stopId, date, callback) { // Cache Cache for StopTimes let cacheKey = db.id + "-" + tripId + "-" + stopId + "-" + date; let cache = cache_stoptimesByTripStop.get(cacheKey); if ( cache !== null ) { return callback(null, cache); } // Build the select statement let select = "SELECT " + "gtfs_stop_times.arrival_time, departure_time, stop_sequence, pickup_type, drop_off_type, stop_headsign, shape_dist_traveled, timepoint, " + "gtfs_stops.stop_id, stop_name, stop_desc, stop_lat, stop_lon, stop_url, " + "gtfs_stops.zone_id AS gtfs_zone_id, stop_code, wheelchair_boarding, location_type, parent_station, stop_timezone, " + "rt_stops_extra.status_id, display_name, transfer_weight, rt_stops_extra.zone_id AS rt_zone_id " + "FROM gtfs_stop_times " + "INNER JOIN gtfs_stops ON gtfs_stop_times.stop_id=gtfs_stops.stop_id " + "INNER JOIN rt_stops_extra ON gtfs_stops.stop_id=rt_stops_extra.stop_id " + "WHERE gtfs_stop_times.trip_id='" + tripId + "' " + "AND gtfs_stop_times.stop_id='" + stopId + "';"; // Query the database db.get(select, function(err, result) { // Database Query Error if ( err ) { return callback(err); } // Stop Not Found if ( result === undefined ) { return callback(null, undefined); } // Use the stop_name by default unless display_name is set let stop_name = result.stop_name; if ( result.display_name !== undefined && result.display_name !== null && result.display_name !== "" ) { stop_name = result.display_name; } // Get zone_id from rt_stops_extra if not defined if gtfs_stops let zone_id = result.gtfs_zone_id; if ( zone_id === null || zone_id === undefined ) { zone_id = result.rt_zone_id; } // Build Stop let stop = new Stop( result.stop_id, stop_name, result.stop_lat, result.stop_lon, { code: result.stop_code, description: result.stop_desc, zoneId: zone_id, url: result.stop_url, locationType: result.location_type, parentStation: result.parent_station, timezone: result.stop_timezone, wheelchairBoarding: result.wheelchair_boarding, statusId: result.status_id, transferWeight: result.transfer_weight } ); // Build StopTime let stopTime = new StopTime( stop, result.arrival_time, result.departure_time, result.stop_sequence, { headsign: result.stop_headsign, pickupType: result.pickup_type, dropOffType: result.drop_off_type, shapeDistanceTraveled: result.shape_dist_traveled, timepoint: result.timepoint, date: date } ); // Add StopTimes to Cache cache_stoptimesByTripStop.put(cacheKey, stopTime); // Return the StopTimes with the callback return callback(null, stopTime); }); }
javascript
{ "resource": "" }
q11966
getTripByShortName
train
function getTripByShortName(db, shortName, date, callback) { // Check Cache for Trip let cacheKey = db.id + "-" + shortName + "-" + date; let cache = cache_tripsByShortName.get(cacheKey); if ( cache !== null ) { return callback(null, cache); } // Get effective service ids _buildEffectiveServiceIDString(db, date, function(err, serviceIdString) { if ( err ) { return callback(err); } // Get Trip ID let select = "SELECT trip_id FROM gtfs_trips WHERE trip_short_name = '" + shortName + "' AND service_id IN " + serviceIdString + ";"; // Query database db.get(select, function(err, result) { if ( err ) { return callback(err); } // No Trip Found if ( result === undefined ) { return callback(null, undefined); } // Get the Trip getTrip(db, result.trip_id, date, function(err, trip) { // Add Trip to Cache cache_tripsByShortName.put(cacheKey, trip); // Return Trip return callback(err, trip); }); }); }); }
javascript
{ "resource": "" }
q11967
getTripByDeparture
train
function getTripByDeparture(db, originId, destinationId, departure, callback) { // Check cache for trip let cacheKey = db.id + "-" + originId + "-" + destinationId + "-" + departure.getTimeSeconds() + "-" + departure.getDateInt(); let cache = cache_tripsByDeparture.get(cacheKey); if ( cache !== null ) { return callback(null, cache); } // Check to make sure both origin and destination have IDs set if ( originId === "" || originId === undefined || destinationId === "" || destinationId === undefined ) { return callback( new Error('Could not get Trip, origin and/or destination id not set') ); } // ORIGINAL DEPARTURE DATE _getTripByDeparture(db, originId, destinationId, departure, function(err, trip) { if ( err ) { return callback(err); } // Trip Found... if ( trip !== undefined ) { cache_tripsByDeparture.put(cacheKey, trip); return callback(null, trip); } // PREVIOUS DEPARTURE DATE, +24 HOUR TIME let prev = DateTime.create( departure.getTimeSeconds() + 86400, departure.clone().deltaDays(-1).getDateInt() ); _getTripByDeparture(db, originId, destinationId, prev, function(err, trip) { // Return results cache_tripsByDeparture.put(cacheKey, trip); return callback(err, trip); }); }); }
javascript
{ "resource": "" }
q11968
_getTripByDeparture
train
function _getTripByDeparture(db, originId, destinationId, departure, callback) { // Get Effective Services for departure date _buildEffectiveServiceIDString(db, departure.getDateInt(), function(err, serviceIdString) { if ( err ) { return callback(err); } // Find a matching trip _getMatchingTripId(db, originId, destinationId, departure, serviceIdString, function(err, tripId) { if ( err ) { return callback(err); } // --> No matching trip found if ( tripId === undefined ) { return callback(null, undefined); } // Build the matching trip... getTrip(db, tripId, departure.getDateInt(), function(err, trip) { if ( err ) { return callback(err); } // --> Return the matching trip return callback(err, trip); }); }); }); }
javascript
{ "resource": "" }
q11969
_buildEffectiveServiceIDString
train
function _buildEffectiveServiceIDString(db, date, callback) { // Query the Calendar for effective services CalendarTable.getServicesEffective(db, date, function(err, services) { // Database Query Error if ( err ) { return callback(err); } // Build Service ID String let serviceIds = []; for ( let i = 0; i < services.length; i++ ) { serviceIds.push(services[i].id); } let serviceIdString = "('" + serviceIds.join("', '") + "')"; // Return Service ID String return callback(null, serviceIdString); }); }
javascript
{ "resource": "" }
q11970
_getMatchingTripId
train
function _getMatchingTripId(db, originId, destinationId, departure, serviceIdString, callback) { // Find a matching trip in the gtfs_stop_times table let select = "SELECT trip_id FROM gtfs_trips " + "WHERE service_id IN " + serviceIdString + " " + "AND trip_id IN (" + "SELECT trip_id FROM gtfs_stop_times WHERE stop_id='" + destinationId + "' " + "AND trip_id IN (" + "SELECT trip_id FROM gtfs_stop_times " + "WHERE stop_id='" + originId + "' AND departure_time_seconds=" + departure.getTimeSeconds() + "));"; // Query the database db.select(select, function(err, results) { // Database Query Error if ( err ) { return callback(err); } // No results found if ( results.length === 0 ) { return callback(null, undefined); } // Find the best match let found = false; let count = 0; for ( let j = 0; j < results.length; j++ ) { let row = results[j]; // Get StopTimes for origin and destination StopTimesTable.getStopTimeByTripStop(db, row.trip_id, originId, departure.getDateInt(), function(orErr, originStopTime) { StopTimesTable.getStopTimeByTripStop(db, row.trip_id, destinationId, departure.getDateInt(), function(deErr, destinationStopTime) { if ( orErr ) { return callback(orErr); } if ( deErr ) { return callback(deErr); } // Check stop sequence // If origin comes before destination, use that trip if ( originStopTime.stopSequence <= destinationStopTime.stopSequence ) { found = true; return callback(null, row.trip_id); } // No match found count ++; if ( !found && count === results.length ) { return callback(null, undefined); } }); }); } }); }
javascript
{ "resource": "" }
q11971
getTripsByDate
train
function getTripsByDate(db, date, opts, callback) { // Parse Args if ( callback === undefined && typeof opts === 'function' ) { callback = opts; opts = {} } // Check cache for trips let cacheKey = db.id + "-" + date + "-" + opts.routeId + "-" + opts.stopId; let cache = cache_tripsByDate.get(cacheKey); if ( cache !== null ) { return callback(null, cache); } // List of Trips to return let rtn = []; // Counters let done = 0; let count = 0; // Get the Effective Service IDs _buildEffectiveServiceIDString(db, date, function(err, serviceIdString) { // Database Query Error if ( err ) { return callback(err); } // Build Select Statement let select = ""; // Get Trips By Stop if ( opts.stopId !== undefined ) { select = select + "SELECT trip_id FROM gtfs_stop_times WHERE stop_id='" + opts.stopId + "' AND trip_id IN ("; } // Get Trips By Date select = select + "SELECT DISTINCT trip_id FROM gtfs_trips WHERE service_id IN " + serviceIdString; // Filter By Route, if provided if ( opts.routeId !== undefined ) { select = select + " AND route_id='" + opts.routeId + "'"; } // Close Outer Select if ( opts.stopId !== undefined ) { select = select + ")"; } // Query the DB db.select(select, function(err, results) { // Database Query Error if ( err ) { return callback(err); } // Set the counter count = results.length; // No Stops Found if ( results.length === 0 ) { _finish(); } // Build the Trips for ( let i = 0; i < results.length; i++ ) { getTrip(db, results[i].trip_id, date, function(err, trip) { // Database Query Error if ( err ) { return callback(err); } // Add reference stop, if provided if ( opts.stopId ) { trip._referenceStopId = opts.stopId; } // Add Trip to Result rtn.push(trip); // Finish _finish(); }); } }); }); /** * Finish Parsing Trip * @private */ function _finish() { done++; if ( count === 0 || done === count ) { rtn.sort(Trip.sortByDepartureTime); return callback(null, rtn); } } }
javascript
{ "resource": "" }
q11972
_finish
train
function _finish() { done++; if ( count === 0 || done === count ) { rtn.sort(Trip.sortByDepartureTime); return callback(null, rtn); } }
javascript
{ "resource": "" }
q11973
simplyfy
train
function simplyfy(val){ switch(val[0]){ case 'z': // shorthand line to start case 'Z': val[0] = 'L' val[1] = this.start[0] val[2] = this.start[1] break case 'H': // shorthand horizontal line val[0] = 'L' val[2] = this.pos[1] break case 'V': // shorthand vertical line val[0] = 'L' val[2] = val[1] val[1] = this.pos[0] break case 'T': // shorthand quadratic beziere val[0] = 'Q' val[3] = val[1] val[4] = val[2] val[1] = this.reflection[1] val[2] = this.reflection[0] break case 'S': // shorthand cubic beziere val[0] = 'C' val[6] = val[4] val[5] = val[3] val[4] = val[2] val[3] = val[1] val[2] = this.reflection[1] val[1] = this.reflection[0] break } return val }
javascript
{ "resource": "" }
q11974
setPosAndReflection
train
function setPosAndReflection(val){ var len = val.length this.pos = [ val[len-2], val[len-1] ] if('SCQT'.indexOf(val[0]) != -1) this.reflection = [ 2 * this.pos[0] - val[len-4], 2 * this.pos[1] - val[len-3] ] return val }
javascript
{ "resource": "" }
q11975
toBeziere
train
function toBeziere(val){ var retVal = [val] switch(val[0]){ case 'M': // special handling for M this.pos = this.start = [val[1], val[2]] return retVal case 'L': val[5] = val[3] = val[1] val[6] = val[4] = val[2] val[1] = this.pos[0] val[2] = this.pos[1] break case 'Q': val[6] = val[4] val[5] = val[3] val[4] = val[4] * 1/3 + val[2] * 2/3 val[3] = val[3] * 1/3 + val[1] * 2/3 val[2] = this.pos[1] * 1/3 + val[2] * 2/3 val[1] = this.pos[0] * 1/3 + val[1] * 2/3 break case 'A': retVal = arcToBeziere(this.pos, val) val = retVal[0] break } val[0] = 'C' this.pos = [val[5], val[6]] this.reflection = [2 * val[5] - val[3], 2 * val[6] - val[4]] return retVal }
javascript
{ "resource": "" }
q11976
findNextM
train
function findNextM(arr, offset){ if(offset === false) return false for(var i = offset, len = arr.length;i < len;++i){ if(arr[i][0] == 'M') return i } return false }
javascript
{ "resource": "" }
q11977
getFriendlyBrowser
train
function getFriendlyBrowser(browserName) { browserName = browserName || ""; if (typeof browserName === "string" && browserName) { if (browserName === "MicrosoftEdge") { browserName = "edge"; } if (browserName === "internet explorer") { browserName = "ie"; } else if (browserName === "iphone") { browserName = "safari"; } else if (browserName === "android") { browserName = "browser"; } } return browserName; }
javascript
{ "resource": "" }
q11978
Glob
train
function Glob(options) { if (!(this instanceof Glob)) { return new Glob(options); } Emitter.call(this); this.handler = new Handler(this); this.init(options); }
javascript
{ "resource": "" }
q11979
train
function (opts) { this.options = opts || {}; this.pattern = null; this.middleware = {}; this.includes = {}; this.excludes = {}; this.files = []; this.fns = []; options(this); iterators(this); symlinks(this); readers(this); }
javascript
{ "resource": "" }
q11980
train
function (glob, opts) { if (opts.ignore) { this.map('exclude', opts.ignore, opts); } if (opts.exclude) { this.map('exclude', opts.exclude, opts); } if (opts.include) { this.map('include', opts.include, opts); } // if not disabled by the user, run the built-ins if (!this.disabled('builtins')) { if (!this.disabled('npm')) { this.use(npm(opts)); } if (!this.disabled('dotfiles')) { this.use(dotfiles()(opts)); } if (!this.disabled('gitignore')) { this.use(gitignore()(opts)); } } }
javascript
{ "resource": "" }
q11981
train
function (pattern, options) { options = options || {}; this.pattern = new Pattern(pattern, options); this.recurse = this.shouldRecurse(this.pattern, options); // if middleware are registered, use the glob, otherwise regex var glob = this.fns.length ? this.pattern.glob : this.pattern.regex; this.defaults(glob, options); this.include(glob, options); return this; }
javascript
{ "resource": "" }
q11982
train
function (file) { return new File({ pattern: this.pattern, recurse: this.recurse, dirname: file.dirname, segment: file.segment, path: file.path }); }
javascript
{ "resource": "" }
q11983
train
function(pattern, options) { var opts = this.setDefaults(options); if (typeof opts.recurse === 'boolean') { return opts.recurse; } return pattern.isGlobstar; }
javascript
{ "resource": "" }
q11984
train
function(method, arr/*, arguments*/) { var args = [].slice.call(arguments, 2); utils.arrayify(arr || []).forEach(function (obj) { this[method](obj, args); }.bind(this)); return this; }
javascript
{ "resource": "" }
q11985
train
function(pattern, options, cb) { if (typeof options === 'function') { return this.readdir(pattern, {}, options); } this.emit('read'); this.setPattern(pattern, options); this.iteratorAsync(this.pattern.base, function (err) { if (err) return cb(err); this.emit('end', this.files); cb.call(this, null, this.files); }.bind(this)); return this; }
javascript
{ "resource": "" }
q11986
train
function(pattern, options) { this.emit('read'); this.setPattern(pattern, options); this.iteratorSync(this.pattern.base); this.emit('end', this.files); return this.files; }
javascript
{ "resource": "" }
q11987
train
function(pattern, options) { this.emit('read'); this.setPattern(pattern, options); var res = this.iteratorStream(this.pattern.base); this.emit('end', this.files); return res; }
javascript
{ "resource": "" }
q11988
File
train
function File(file) { this.cache = new Map(); this.history = []; this.pattern = file.pattern; this.recurse = file.recurse; this.dirname = file.dirname; this.segment = file.segment; this.path = file.path; this.orig = file.path; }
javascript
{ "resource": "" }
q11989
Pattern
train
function Pattern(glob, options, isNegated) { utils.defineProp(this, 'cache', new Map()); this.negated = !!isNegated; this.options = options || {}; this.parse(glob); return this; }
javascript
{ "resource": "" }
q11990
train
function(str){ if(_.isUndefined(str)) str = '00'; return String(str).length % 2 ? '0' + String(str) : String(str); }
javascript
{ "resource": "" }
q11991
train
function(num){ if(_.isUndefined(num) || num == 0) num = '00'; if(_.isString(num) || _.isNumber(num)) num = new BigNumber(String(num)); if(isBigNumber(num)) num = num.toString(16); return formatHex(num); }
javascript
{ "resource": "" }
q11992
train
function(addr, format){ if(_.isUndefined(format) || !_.isString(format)) format = 'hex'; if(_.isUndefined(addr) || !_.isString(addr)) addr = '0000000000000000000000000000000000000000'; if(addr.substr(0, 2) == '0x' && format == 'raw') addr = addr.substr(2); if(addr.substr(0, 2) != '0x' && format == 'hex') addr = '0x' + addr; return addr; }
javascript
{ "resource": "" }
q11993
train
function(length) { var charset = "abcdef0123456789"; var i; var result = ""; var isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]'; if(window.crypto && window.crypto.getRandomValues) { values = new Uint32Array(length); window.crypto.getRandomValues(values); for(i=0; i<length; i++) { result += charset[values[i] % charset.length]; } return result; } else if(isOpera) {//Opera's Math.random is secure, see http://lists.w3.org/Archives/Public/public-webcrypto/2013Jan/0063.html for(i=0; i<length; i++) { result += charset[Math.floor(Math.random()*charset.length)]; } return result; } else throw new Error("Your browser sucks and can't generate secure random numbers"); }
javascript
{ "resource": "" }
q11994
train
function(value){ if(_.isUndefined(value) || !_.isObject(value)) return false; return (value instanceof BigNumber) ? true : false; }
javascript
{ "resource": "" }
q11995
train
function(context){ Object.defineProperty(context, 'length', { get: function() { var count = 0; // count valid accounts in browser storage _.each(this.get(), function(account, accountIndex){ if(_.isUndefined(account) || !_.isObject(account) || _.isString(account)) return; if(!_.has(account, 'encrypted') || !_.has(account, 'private')) return; count += 1; }); return count; } }); }
javascript
{ "resource": "" }
q11996
pipe
train
function pipe(funcs) { return function pipeRewire(config) { const args = Array.prototype.slice.call(arguments, 1); (funcs || []).forEach(func => { if (func && typeof func === 'function') { // slice the first argument "config" config = func.apply(this, [config].concat(args)); } }); return config; }; }
javascript
{ "resource": "" }
q11997
mergeScripts
train
function mergeScripts(crsScripts) { const scripts = { build: path.join(__dirname, 'scripts/build.js'), start: path.join(__dirname, 'scripts/start.js'), test: path.join(__dirname, 'scripts/test.js'), }; crsScripts.forEach(scriptSet => { Object.assign(scripts, scriptSet || {}); }); return scripts; }
javascript
{ "resource": "" }
q11998
compose
train
function compose(...args) { // convert pipe to compose by reverse the array const crsConfigs = args.slice(0).reverse(); const crsConfig = { env: pipe(crsConfigs.map(c => c.env)), paths: pipe(crsConfigs.map(c => c.paths)), webpack: pipe(crsConfigs.map(c => c.webpack)), devServer: pipe(crsConfigs.map(c => c.devServer)), jest: pipe(crsConfigs.map(c => c.jest)), scripts: mergeScripts(crsConfigs.map(c => c.scripts)), }; return crsConfig; }
javascript
{ "resource": "" }
q11999
createReactScripts
train
function createReactScripts(scriptsDir) { // obtain the crs.config path // we allow user to use crs.config under app directory instead if scriptsDir is not provided // in this case, we do not allow customize new scripts and template const crsConfigPath = path.join(scriptsDir || process.cwd(), 'crs.config.js'); // append args so we can extract the argument after --crs-config // this is needed as we need to require the config inside script which is run by 'spawn' const crsConfigArgs = ['--crs-config']; // if crs-config exists, append to after --crs-config if (fs.existsSync(crsConfigPath)) { crsConfigArgs.push(crsConfigPath); } const spawn = require('react-dev-utils/crossSpawn'); const args = process.argv.slice(2); // should support customize scripts let crsConfig = {}; if (fs.existsSync(crsConfigPath)) { crsConfig = require(crsConfigPath); } // here eject is removed from the scripts. // it is not expected user to 'eject' while using this library. const scriptsMap = { build: path.join(__dirname, 'scripts/build.js'), start: path.join(__dirname, 'scripts/start.js'), test: path.join(__dirname, 'scripts/test.js'), }; // obtain all allowed scripts Object.assign(scriptsMap, (crsConfig || {}).scripts || {}); const scripts = Object.keys(scriptsMap); // find the script index const scriptIndex = args.findIndex(x => scripts.indexOf(x) !== -1); // obtain the script const script = scriptIndex === -1 ? args[0] : args[scriptIndex]; // extract out the node arguments const nodeArgs = scriptIndex > 0 ? args.slice(0, scriptIndex) : []; // if script is valid if (scriptsMap[script]) { // the js file path of script const scriptPath = scriptsMap[script]; // try to validate the script path is resolvable if (!fs.existsSync(scriptPath)) { console.log('Unknown script "' + script + '".'); } // execute the script like what reac-scripts do const result = spawn.sync( 'node', nodeArgs .concat(require.resolve(scriptPath)) .concat(args.slice(scriptIndex + 1)) .concat(crsConfigArgs), { stdio: 'inherit' } ); if (result.signal) { if (result.signal === 'SIGKILL') { console.log( 'The build failed because the process exited too early. ' + 'This probably means the system ran out of memory or someone called ' + '`kill -9` on the process.' ); } else if (result.signal === 'SIGTERM') { console.log( 'The build failed because the process exited too early. ' + 'Someone might have called `kill` or `killall`, or the system could ' + 'be shutting down.' ); } process.exit(1); } process.exit(result.status); return; } console.log('Unknown script "' + script + '".'); console.log('Perhaps you need to update react-scripts?'); console.log( 'See: https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#updating-to-new-releases' ); }
javascript
{ "resource": "" }