_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q44500
call
train
function call(method, key) { if (!exports.results.has(method)) create(method); // create as needed const methodCache = exports.results.get(method); let callResults; if (methodCache.has(key)) { log_1.logger.debug(`[${method}] Calling (cached): ${key}`); // return from cache if key has been used on method before callResults = methodCache.get(key); } else { // call and cache for next time, returning results log_1.logger.debug(`[${method}] Calling (caching): ${key}`); callResults = exports.instance.call(method, key).result; methodCache.set(key, callResults); } return Promise.resolve(callResults); }
javascript
{ "resource": "" }
q44501
get
train
function get(method, key) { if (exports.results.has(method)) return exports.results.get(method).get(key); }
javascript
{ "resource": "" }
q44502
getQueryString
train
function getQueryString(data) { if (!data || typeof data !== 'object' || !Object.keys(data).length) return ''; return '?' + Object.keys(data).map((k) => { const value = (typeof data[k] === 'object') ? JSON.stringify(data[k]) : encodeURIComponent(data[k]); return `${encodeURIComponent(k)}=${value}`; }).join('&'); }
javascript
{ "resource": "" }
q44503
getHeaders
train
function getHeaders(authRequired = false) { if (!authRequired) return exports.basicHeaders; if ((!('X-Auth-Token' in exports.authHeaders) || !('X-User-Id' in exports.authHeaders)) || exports.authHeaders['X-Auth-Token'] === '' || exports.authHeaders['X-User-Id'] === '') { throw new Error('Auth required endpoint cannot be called before login'); } return Object.assign({}, exports.basicHeaders, exports.authHeaders); }
javascript
{ "resource": "" }
q44504
success
train
function success(result, ignore) { return ((typeof result.error === 'undefined' && typeof result.status === 'undefined' && typeof result.success === 'undefined') || (result.status && result.status === 'success') || (result.success && result.success === true) || (ignore && result.error && !ignore.test(result.error))) ? true : false; }
javascript
{ "resource": "" }
q44505
get
train
function get(endpoint, data, auth = true, ignore) { return __awaiter(this, void 0, void 0, function* () { try { log_1.logger.debug(`[API] GET: ${endpoint}`, data); if (auth && !loggedIn()) yield login(); let headers = getHeaders(auth); const query = getQueryString(data); const result = yield new Promise((resolve, reject) => { exports.client.get(exports.url + endpoint + query, { headers }, (result) => { if (Buffer.isBuffer(result)) reject('Result was buffer (HTML, not JSON)'); else if (!success(result, ignore)) reject(result); else resolve(result); }).on('error', (err) => reject(err)); }); log_1.logger.debug('[API] GET result:', result); return result; } catch (err) { log_1.logger.error(`[API] GET error (${endpoint}):`, err); } }); }
javascript
{ "resource": "" }
q44506
login
train
function login(user = { username: settings.username, password: settings.password }) { return __awaiter(this, void 0, void 0, function* () { log_1.logger.info(`[API] Logging in ${user.username}`); if (exports.currentLogin !== null) { log_1.logger.debug(`[API] Already logged in`); if (exports.currentLogin.username === user.username) { return exports.currentLogin.result; } else { yield logout(); } } const result = yield post('login', user, false); if (result && result.data && result.data.authToken) { exports.currentLogin = { result: result, username: user.username, authToken: result.data.authToken, userId: result.data.userId }; setAuth(exports.currentLogin); log_1.logger.info(`[API] Logged in ID ${exports.currentLogin.userId}`); return result; } else { throw new Error(`[API] Login failed for ${user.username}`); } }); }
javascript
{ "resource": "" }
q44507
logout
train
function logout() { if (exports.currentLogin === null) { log_1.logger.debug(`[API] Already logged out`); return Promise.resolve(); } log_1.logger.info(`[API] Logging out ${exports.currentLogin.username}`); return get('logout', null, true).then(() => { clearHeaders(); exports.currentLogin = null; }); }
javascript
{ "resource": "" }
q44508
asyncCall
train
function asyncCall(method, params) { if (!Array.isArray(params)) params = [params]; // cast to array for apply log_1.logger.info(`[${method}] Calling (async): ${JSON.stringify(params)}`); return Promise.resolve(exports.asteroid.apply(method, params).result) .catch((err) => { log_1.logger.error(`[${method}] Error:`, err); throw err; // throw after log to stop async chain }) .then((result) => { (result) ? log_1.logger.debug(`[${method}] Success: ${JSON.stringify(result)}`) : log_1.logger.debug(`[${method}] Success`); return result; }); }
javascript
{ "resource": "" }
q44509
callMethod
train
function callMethod(name, params) { return (methodCache.has(name) || typeof params === 'undefined') ? asyncCall(name, params) : cacheCall(name, params); }
javascript
{ "resource": "" }
q44510
cacheCall
train
function cacheCall(method, key) { return methodCache.call(method, key) .catch((err) => { log_1.logger.error(`[${method}] Error:`, err); throw err; // throw after log to stop async chain }) .then((result) => { (result) ? log_1.logger.debug(`[${method}] Success: ${JSON.stringify(result)}`) : log_1.logger.debug(`[${method}] Success`); return result; }); }
javascript
{ "resource": "" }
q44511
logout
train
function logout() { return exports.asteroid.logout() .catch((err) => { log_1.logger.error('[Logout] Error:', err); throw err; // throw after log to stop async chain }); }
javascript
{ "resource": "" }
q44512
unsubscribe
train
function unsubscribe(subscription) { const index = exports.subscriptions.indexOf(subscription); if (index === -1) return; subscription.stop(); // asteroid.unsubscribe(subscription.id) // v2 exports.subscriptions.splice(index, 1); // remove from collection log_1.logger.info(`[${subscription.id}] Unsubscribed`); }
javascript
{ "resource": "" }
q44513
subscribeToMessages
train
function subscribeToMessages() { return subscribe(_messageCollectionName, _messageStreamName) .then((subscription) => { exports.messages = exports.asteroid.getCollection(_messageCollectionName); return subscription; }); }
javascript
{ "resource": "" }
q44514
respondToMessages
train
function respondToMessages(callback, options = {}) { const config = Object.assign({}, settings, options); // return value, may be replaced by async ops let promise = Promise.resolve(); // Join configured rooms if they haven't been already, unless listening to all // public rooms, in which case it doesn't matter if (!config.allPublic && exports.joinedIds.length === 0 && config.rooms && config.rooms.length > 0) { promise = joinRooms(config.rooms) .catch((err) => { log_1.logger.error(`[joinRooms] Failed to join configured rooms (${config.rooms.join(', ')}): ${err.message}`); }); } exports.lastReadTime = new Date(); // init before any message read reactToMessages((err, message, meta) => __awaiter(this, void 0, void 0, function* () { if (err) { log_1.logger.error(`[received] Unable to receive: ${err.message}`); callback(err); // bubble errors back to adapter } // Ignore bot's own messages if (message.u._id === exports.userId) return; // Ignore DMs unless configured not to const isDM = meta.roomType === 'd'; if (isDM && !config.dm) return; // Ignore Livechat unless configured not to const isLC = meta.roomType === 'l'; if (isLC && !config.livechat) return; // Ignore messages in un-joined public rooms unless configured not to if (!config.allPublic && !isDM && !meta.roomParticipant) return; // Set current time for comparison to incoming let currentReadTime = new Date(message.ts.$date); // Ignore edited messages if configured to if (!config.edited && message.editedAt) return; // Set read time as time of edit, if message is edited if (message.editedAt) currentReadTime = new Date(message.editedAt.$date); // Ignore messages in stream that aren't new if (currentReadTime <= exports.lastReadTime) return; // At this point, message has passed checks and can be responded to log_1.logger.info(`[received] Message ${message._id} from ${message.u.username}`); exports.lastReadTime = currentReadTime; // Processing completed, call callback to respond to message callback(null, message, meta); })); return promise; }
javascript
{ "resource": "" }
q44515
leaveRoom
train
function leaveRoom(room) { return __awaiter(this, void 0, void 0, function* () { let roomId = yield getRoomId(room); let joinedIndex = exports.joinedIds.indexOf(room); if (joinedIndex === -1) { log_1.logger.error(`[leaveRoom] failed because bot has not joined ${room}`); } else { yield asyncCall('leaveRoom', roomId); delete exports.joinedIds[joinedIndex]; } }); }
javascript
{ "resource": "" }
q44516
prepareMessage
train
function prepareMessage(content, roomId) { const message = new message_1.Message(content, exports.integrationId); if (roomId) message.setRoomId(roomId); return message; }
javascript
{ "resource": "" }
q44517
getControllerDir
train
function getControllerDir(isInstall) { var fs = require('fs'); // Find the js-controller location var controllerDir = __dirname.replace(/\\/g, '/'); controllerDir = controllerDir.split('/'); if (controllerDir[controllerDir.length - 3] === 'adapter') { controllerDir.splice(controllerDir.length - 3, 3); controllerDir = controllerDir.join('/'); } else if (controllerDir[controllerDir.length - 3] === 'node_modules') { controllerDir.splice(controllerDir.length - 3, 3); controllerDir = controllerDir.join('/'); if (fs.existsSync(controllerDir + '/node_modules/' + appName + '.js-controller')) { controllerDir += '/node_modules/' + appName + '.js-controller'; } else if (fs.existsSync(controllerDir + '/node_modules/' + appName.toLowerCase() + '.js-controller')) { controllerDir += '/node_modules/' + appName.toLowerCase() + '.js-controller'; } else if (!fs.existsSync(controllerDir + '/controller.js')) { if (!isInstall) { console.log('Cannot find js-controller'); process.exit(10); } else { process.exit(); } } } else if (fs.existsSync(__dirname + '/../../node_modules/' + appName.toLowerCase() + '.js-controller')) { controllerDir.splice(controllerDir.length - 2, 2); return controllerDir.join('/') + '/node_modules/' + appName.toLowerCase() + '.js-controller'; } else { if (!isInstall) { console.log('Cannot find js-controller'); process.exit(10); } else { process.exit(); } } return controllerDir; }
javascript
{ "resource": "" }
q44518
getConfig
train
function getConfig() { var fs = require('fs'); if (fs.existsSync(controllerDir + '/conf/' + appName + '.json')) { return JSON.parse(fs.readFileSync(controllerDir + '/conf/' + appName + '.json')); } else if (fs.existsSync(controllerDir + '/conf/' + appName.toLowerCase() + '.json')) { return JSON.parse(fs.readFileSync(controllerDir + '/conf/' + appName.toLowerCase() + '.json')); } else { throw new Error('Cannot find ' + controllerDir + '/conf/' + appName + '.json'); } }
javascript
{ "resource": "" }
q44519
train
function (remove) { if (!L.DomEvent) { return; } this._targets = {}; this._targets[L.stamp(this._container)] = this; var onOff = remove ? 'off' : 'on'; // @event click: MouseEvent // Fired when the user clicks (or taps) the map. // @event dblclick: MouseEvent // Fired when the user double-clicks (or double-taps) the map. // @event mousedown: MouseEvent // Fired when the user pushes the mouse button on the map. // @event mouseup: MouseEvent // Fired when the user releases the mouse button on the map. // @event mouseover: MouseEvent // Fired when the mouse enters the map. // @event mouseout: MouseEvent // Fired when the mouse leaves the map. // @event mousemove: MouseEvent // Fired while the mouse moves over the map. // @event contextmenu: MouseEvent // Fired when the user pushes the right mouse button on the map, prevents // default browser context menu from showing if there are listeners on // this event. Also fired on mobile when the user holds a single touch // for a second (also called long press). // @event keypress: Event // Fired when the user presses a key from the keyboard while the map is focused. L.DomEvent[onOff](this._container, 'click dblclick mousedown mouseup ' + 'mouseover mouseout mousemove contextmenu keypress', this._handleDOMEvent, this); if (this.options.trackResize) { L.DomEvent[onOff](window, 'resize', this._onResize, this); } if (L.Browser.any3d && this.options.transform3DLimit) { this[onOff]('moveend', this._onMoveEnd); } }
javascript
{ "resource": "" }
q44520
train
function (center, zoom, bounds) { if (!bounds) { return center; } var centerPoint = this.project(center, zoom), viewHalf = this.getSize().divideBy(2), viewBounds = new L.Bounds(centerPoint.subtract(viewHalf), centerPoint.add(viewHalf)), offset = this._getBoundsOffset(viewBounds, bounds, zoom); // If offset is less than a pixel, ignore. // This prevents unstable projections from getting into // an infinite loop of tiny offsets. if (offset.round().equals([0, 0])) { return center; } return this.unproject(centerPoint.add(offset), zoom); }
javascript
{ "resource": "" }
q44521
train
function (center) { var map = this._map; if (!map) { return; } var zoom = map.getZoom(); if (center === undefined) { center = map.getCenter(); } if (this._tileZoom === undefined) { return; } // if out of minzoom/maxzoom var pixelBounds = this._getTiledPixelBounds(center), tileRange = this._pxBoundsToTileRange(pixelBounds), tileCenter = tileRange.getCenter(), queue = [], margin = this.options.keepBuffer, noPruneRange = new L.Bounds(tileRange.getBottomLeft().subtract([margin, -margin]), tileRange.getTopRight().add([margin, -margin])); for (var key in this._tiles) { var c = this._tiles[key].coords; if (c.z !== this._tileZoom || !noPruneRange.contains(L.point(c.x, c.y))) { this._tiles[key].current = false; } } // _update just loads more tiles. If the tile zoom level differs too much // from the map's, let _setView reset levels and prune old tiles. if (Math.abs(zoom - this._tileZoom) > 1) { this._setView(center, zoom); return; } // create a queue of coordinates to load tiles from for (var j = tileRange.min.y; j <= tileRange.max.y; j++) { for (var i = tileRange.min.x; i <= tileRange.max.x; i++) { var coords = new L.Point(i, j); coords.z = this._tileZoom; if (!this._isValidTile(coords)) { continue; } var tile = this._tiles[this._tileCoordsToKey(coords)]; if (tile) { tile.current = true; } else { queue.push(coords); } } } // sort tile queue to load tiles in order of their distance to center queue.sort(function (a, b) { return a.distanceTo(tileCenter) - b.distanceTo(tileCenter); }); if (queue.length !== 0) { // if its the first batch of tiles to load if (!this._loading) { this._loading = true; // @event loading: Event // Fired when the grid layer starts loading tiles. this.fire('loading'); } // create DOM fragment to append tiles in one batch var fragment = document.createDocumentFragment(); for (i = 0; i < queue.length; i++) { this._addTile(queue[i], fragment); } this._level.el.appendChild(fragment); } }
javascript
{ "resource": "" }
q44522
train
function (coords) { var map = this._map, tileSize = this.getTileSize(), nwPoint = coords.scaleBy(tileSize), sePoint = nwPoint.add(tileSize), nw = map.wrapLatLng(map.unproject(nwPoint, coords.z)), se = map.wrapLatLng(map.unproject(sePoint, coords.z)); return new L.LatLngBounds(nw, se); }
javascript
{ "resource": "" }
q44523
train
function (key) { var k = key.split(':'), coords = new L.Point(+k[0], +k[1]); coords.z = +k[2]; return coords; }
javascript
{ "resource": "" }
q44524
train
function (latlngs) { var result = [], flat = L.Polyline._flat(latlngs); for (var i = 0, len = latlngs.length; i < len; i++) { if (flat) { result[i] = L.latLng(latlngs[i]); this._bounds.extend(result[i]); } else { result[i] = this._convertLatLngs(latlngs[i]); } } return result; }
javascript
{ "resource": "" }
q44525
train
function (latlngs, result, projectedBounds) { var flat = latlngs[0] instanceof L.LatLng, len = latlngs.length, i, ring; if (flat) { ring = []; for (i = 0; i < len; i++) { ring[i] = this._map.latLngToLayerPoint(latlngs[i]); projectedBounds.extend(ring[i]); } result.push(ring); } else { for (i = 0; i < len; i++) { this._projectLatlngs(latlngs[i], result, projectedBounds); } } }
javascript
{ "resource": "" }
q44526
train
function () { var bounds = this._renderer._bounds; this._parts = []; if (!this._pxBounds || !this._pxBounds.intersects(bounds)) { return; } if (this.options.noClip) { this._parts = this._rings; return; } var parts = this._parts, i, j, k, len, len2, segment, points; for (i = 0, k = 0, len = this._rings.length; i < len; i++) { points = this._rings[i]; for (j = 0, len2 = points.length; j < len2 - 1; j++) { segment = L.LineUtil.clipSegment(points[j], points[j + 1], bounds, j, true); if (!segment) { continue; } parts[k] = parts[k] || []; parts[k].push(segment[0]); // if segment goes out of screen, or it's the last one, it's the end of the line part if ((segment[1] !== points[j + 1]) || (j === len2 - 2)) { parts[k].push(segment[1]); k++; } } } }
javascript
{ "resource": "" }
q44527
train
function () { var parts = this._parts, tolerance = this.options.smoothFactor; for (var i = 0, len = parts.length; i < len; i++) { parts[i] = L.LineUtil.simplify(parts[i], tolerance); } }
javascript
{ "resource": "" }
q44528
train
function (layer) { var path = layer._path = L.SVG.create('path'); // @namespace Path // @option className: String = null // Custom class name set on an element. Only for SVG renderer. if (layer.options.className) { L.DomUtil.addClass(path, layer.options.className); } if (layer.options.interactive) { L.DomUtil.addClass(path, 'leaflet-interactive'); } this._updateStyle(layer); }
javascript
{ "resource": "" }
q44529
train
function (e, handler) { var timeStamp = (e.timeStamp || (e.originalEvent && e.originalEvent.timeStamp)), elapsed = L.DomEvent._lastClick && (timeStamp - L.DomEvent._lastClick); // are they closer together than 500ms yet more than 100ms? // Android typically triggers them ~300ms apart while multiple listeners // on the same event should be triggered far faster; // or check if click is simulated on the element, and if it is, reject any non-simulated events if ((elapsed && elapsed > 100 && elapsed < 500) || (e.target._simulatedClick && !e._simulated)) { L.DomEvent.stop(e); return; } L.DomEvent._lastClick = timeStamp; handler(e); }
javascript
{ "resource": "" }
q44530
train
function(config) { config.client .query(config.query.analysis_type, _.omit(config.query, 'analysis_type')) .then(function(res, err){ if (err) { config.error(err); } else { config.success(res); } if (config.complete) config.complete(err, res); }) .catch(config.error); }
javascript
{ "resource": "" }
q44531
_getDefaultFilterCoercionType
train
function _getDefaultFilterCoercionType(explorer, filter) { var propertyType = ProjectUtils.getPropertyType( ProjectStore.getProject(), explorer.query.event_collection, filter.property_name); var targetCoercionType = FormatUtils.coercionTypeForPropertyType(propertyType); return targetCoercionType; }
javascript
{ "resource": "" }
q44532
_prepareUpdates
train
function _prepareUpdates(explorer, updates) { // TODO: We're assigning the response object directly onto the model so we // don't have to loop through the (sometimes) massive response object. function customizer(objValue, srcValue, key) { if (_.isArray(objValue)) { return srcValue; } else if (key === 'time' && _.isPlainObject(objValue)) { return srcValue; } } var newModel = _.mergeWith({}, explorer, _.omit(updates, 'response'), customizer); if (updates.response) newModel.response = updates.response; // Check if the event collection has changed. Clear the property names if so. if (updates.query && updates.query.event_collection && updates.query.event_collection !== explorer.query.event_collection) { newModel.query.property_names = []; } if(newModel.query.analysis_type === 'funnel' && explorer.query.analysis_type !== 'funnel') { newModel = _migrateToFunnel(explorer, newModel); } else if(newModel.query.analysis_type !== 'funnel' && explorer.query.analysis_type === 'funnel') { newModel = _migrateFromFunnel(explorer, newModel); } newModel = _removeInvalidFields(newModel); return newModel; }
javascript
{ "resource": "" }
q44533
_migrateToFunnel
train
function _migrateToFunnel(explorer, newModel) { var firstStep = _defaultStep(); firstStep.active = true; _.each(SHARED_FUNNEL_STEP_PROPERTIES, function (key) { if(!_.isUndefined(explorer.query[key]) && !_.isNull(explorer.query[key])) { firstStep[key] = explorer.query[key] } newModel.query[key] = (key === 'filters') ? [] : null; }); if(!_.isUndefined(explorer.query.target_property) && !_.isNull(explorer.query.target_property)) { firstStep.actor_property = explorer.query.target_property; explorer.query.target_property = null; } newModel.query.steps = [firstStep]; return newModel; }
javascript
{ "resource": "" }
q44534
_migrateFromFunnel
train
function _migrateFromFunnel(explorer, newModel) { if (explorer.query.steps.length < 1) return newModel; var activeStep = _.find(explorer.query.steps, { active: true }) || explorer.query.steps[0]; _.each(SHARED_FUNNEL_STEP_PROPERTIES, function (key) { if (!_.isUndefined(activeStep[key])) { newModel.query[key] = activeStep[key]; } }); if (!_.isNull(activeStep.actor_property) && ExplorerUtils.shouldHaveTarget(newModel)) { newModel.query.target_property = activeStep.actor_property; } newModel.query.steps = []; return newModel; }
javascript
{ "resource": "" }
q44535
_removeInvalidFields
train
function _removeInvalidFields(newModel) { if (!ExplorerUtils.isEmailExtraction(newModel)) { newModel.query.latest = null; newModel.query.email = null; } if (newModel.query.analysis_type === 'extraction') { newModel.query.group_by = null; newModel.query.order_by = null; newModel.query.limit = null; newModel.query.interval = null; } if (newModel.query.analysis_type !== 'extraction') { newModel.query.latest = null; } if (newModel.query.analysis_type !== 'percentile') { newModel.query.percentile = null; } if (_.includes(['count', 'extraction', 'funnel'], newModel.query.analysis_type)) { newModel.query.target_property = null; } if (newModel.query.analysis_type !== 'funnel') { newModel.query.steps = []; } if(newModel.query.analysis_type === 'funnel') { newModel.query.filters = []; newModel.query.time = null; newModel.query.timezone = null; newModel.query.group_by = null; newModel.query.order_by = null; newModel.query.limit = null; newModel.query.timeframe = null; newModel.query.interval = null; } return newModel; }
javascript
{ "resource": "" }
q44536
_prepareFilterUpdates
train
function _prepareFilterUpdates(explorer, filter, updates) { if (updates.property_name && updates.property_name !== filter.property_name) { if (filter.operator === 'exists') { updates.coercion_type = 'Boolean'; } else { // No need to update the operator - we allow any operator for any property type right now. updates.coercion_type = _getDefaultFilterCoercionType(explorer, _.merge({}, filter, updates)); } } else if (updates.operator && updates.operator !== filter.operator) { var newOp = updates.operator; if (newOp === 'in') updates.coercion_type = 'List'; if (newOp === 'exists') updates.coercion_type = 'Boolean'; if (newOp === 'within') updates.coercion_type = 'Geo'; // If it's not any of these operators, we still need to make sure that the current coercion_type is available // as an option for this new operator. var coercionOptions = _.find(ProjectUtils.getConstant('FILTER_OPERATORS'), { value: updates.operator }).canBeCoeredTo; var coercion_type = updates.coercion_type || filter.coercion_type; if (!_.includes(coercionOptions, coercion_type)) { updates.coercion_type = coercionOptions[0]; } } if (updates.coercion_type === 'Geo' && filter.coercion_type !== 'Geo') { updates.property_value = _defaultGeoFilter(); } updates.property_value = FilterUtils.getCoercedValue(_.merge({}, filter, updates)); return updates; }
javascript
{ "resource": "" }
q44537
_migrateAddonInitializers
train
function _migrateAddonInitializers(project) { project.addons.forEach(addon => { const currentAddonPath = addon.root; _checkBrowserInitializers(currentAddonPath); _moveFastBootInitializers(project, currentAddonPath); }); }
javascript
{ "resource": "" }
q44538
_migrateHostAppInitializers
train
function _migrateHostAppInitializers(project) { const hostAppPath = path.join(project.root); _checkBrowserInitializers(hostAppPath); _moveFastBootInitializers(project, hostAppPath); }
javascript
{ "resource": "" }
q44539
train
function() { var editMode = $scope.editMode; if (angular.isUndefined(editMode) || (editMode === null)) return; //Set completed for all steps to the value of editMode angular.forEach($scope.steps, function (step) { step.completed = editMode; }); //If editMode is false, set ONLY ENABLED steps with index lower then completedIndex to completed if (!editMode) { var completedStepsIndex = $scope.currentStepNumber() - 1; angular.forEach($scope.getEnabledSteps(), function(step, stepIndex) { if(stepIndex < completedStepsIndex) { step.completed = true; } }); } }
javascript
{ "resource": "" }
q44540
unselectAll
train
function unselectAll() { //traverse steps array and set each "selected" property to false angular.forEach($scope.getEnabledSteps(), function (step) { step.selected = false; }); //set selectedStep variable to null $scope.selectedStep = null; }
javascript
{ "resource": "" }
q44541
train
function() { const bounds = this._pixelBounds(); const pixelSize = (bounds.max.x - bounds.min.x) / this._field.nCols; var stride = Math.max( 1, Math.floor(1.2 * this.options.vectorSize / pixelSize) ); const ctx = this._getDrawingContext(); ctx.strokeStyle = this.options.color; var currentBounds = this._map.getBounds(); for (var y = 0; y < this._field.height; y = y + stride) { for (var x = 0; x < this._field.width; x = x + stride) { let [lon, lat] = this._field._lonLatAtIndexes(x, y); let v = this._field.valueAt(lon, lat); let center = L.latLng(lat, lon); if (v !== null && currentBounds.contains(center)) { let cell = new Cell( center, v, this.cellXSize, this.cellYSize ); this._drawArrow(cell, ctx); } } } }
javascript
{ "resource": "" }
q44542
_drawParticles
train
function _drawParticles() { // Previous paths... let prev = ctx.globalCompositeOperation; ctx.globalCompositeOperation = 'destination-in'; ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height); //ctx.globalCompositeOperation = 'source-over'; ctx.globalCompositeOperation = prev; // fading paths... ctx.fillStyle = `rgba(0, 0, 0, ${self.options.fade})`; ctx.lineWidth = self.options.width; ctx.strokeStyle = self.options.color; // New paths paths.forEach(function(par) { self._drawParticle(viewInfo, ctx, par); }); }
javascript
{ "resource": "" }
q44543
updateLines
train
function updateLines(from, to, newText, selFrom, selTo) { if (suppressEdits) return; var old = []; doc.iter(from.line, to.line + 1, function(line) { old.push(newHL(line.text, line.markedSpans)); }); if (history) { history.addChange(from.line, newText.length, old); while (history.done.length > options.undoDepth) history.done.shift(); } var lines = updateMarkedSpans(hlSpans(old[0]), hlSpans(lst(old)), from.ch, to.ch, newText); updateLinesNoUndo(from, to, lines, selFrom, selTo); }
javascript
{ "resource": "" }
q44544
setSelection
train
function setSelection(from, to, oldFrom, oldTo) { goalColumn = null; if (oldFrom == null) {oldFrom = sel.from.line; oldTo = sel.to.line;} if (posEq(sel.from, from) && posEq(sel.to, to)) return; if (posLess(to, from)) {var tmp = to; to = from; from = tmp;} // Skip over hidden lines. if (from.line != oldFrom) { var from1 = skipHidden(from, oldFrom, sel.from.ch); // If there is no non-hidden line left, force visibility on current line if (!from1) setLineHidden(from.line, false); else from = from1; } if (to.line != oldTo) to = skipHidden(to, oldTo, sel.to.ch); if (posEq(from, to)) sel.inverted = false; else if (posEq(from, sel.to)) sel.inverted = false; else if (posEq(to, sel.from)) sel.inverted = true; if (options.autoClearEmptyLines && posEq(sel.from, sel.to)) { var head = sel.inverted ? from : to; if (head.line != sel.from.line && sel.from.line < doc.size) { var oldLine = getLine(sel.from.line); if (/^\s+$/.test(oldLine.text)) setTimeout(operation(function() { if (oldLine.parent && /^\s+$/.test(oldLine.text)) { var no = lineNo(oldLine); replaceRange("", {line: no, ch: 0}, {line: no, ch: oldLine.text.length}); } }, 10)); } } sel.from = from; sel.to = to; selectionChanged = true; }
javascript
{ "resource": "" }
q44545
restartBlink
train
function restartBlink() { clearInterval(blinker); var on = true; cursor.style.visibility = ""; blinker = setInterval(function() { cursor.style.visibility = (on = !on) ? "" : "hidden"; }, options.cursorBlinkRate); }
javascript
{ "resource": "" }
q44546
connect
train
function connect(node, type, handler, disconnect) { if (typeof node.addEventListener == "function") { node.addEventListener(type, handler, false); if (disconnect) return function() {node.removeEventListener(type, handler, false);}; } else { var wrapHandler = function(event) {handler(event || window.event);}; node.attachEvent("on" + type, wrapHandler); if (disconnect) return function() {node.detachEvent("on" + type, wrapHandler);}; } }
javascript
{ "resource": "" }
q44547
patchFetchForRelativeURLs
train
function patchFetchForRelativeURLs(instance) { const fastboot = instance.lookup('service:fastboot'); const request = fastboot.get('request'); // Prember is not sending protocol const protocol = request.protocol === 'undefined:' ? 'http:' : request.protocol; // host is cp setupFastboot(protocol, request.get('host')); }
javascript
{ "resource": "" }
q44548
ondata
train
function ondata(chunk) { packet.push(chunk); if (packet.isReady()) { if (self._state.sessionId !== packet.header.sessionId) { self._state.sessionId = packet.header.sessionId; self._state.packetCount = -1; } var buffer = packet.getData(); packet.clear(); var cb = self._state.receive; self._state.receive = undefined; self._state.messageType = undefined; self.receive(buffer, cb); } }
javascript
{ "resource": "" }
q44549
appendToHead
train
function appendToHead(document, tagName, attrs) { var elt = document.createElement(tagName); DOMDataUtils.addAttributes(elt, attrs || Object.create(null)); document.head.appendChild(elt); }
javascript
{ "resource": "" }
q44550
DOMPostOrder
train
function DOMPostOrder(root, visitFunc) { let node = root; while (true) { // Find leftmost (grand)child, and visit that first. while (node.firstChild) { node = node.firstChild; } visitFunc(node); while (true) { if (node === root) { return; // Visiting the root is the last thing we do. } /* Look for right sibling to continue traversal. */ if (node.nextSibling) { node = node.nextSibling; /* Loop back and visit its leftmost (grand)child first. */ break; } /* Visit parent only after we've run out of right siblings. */ node = node.parentNode; visitFunc(node); } } }
javascript
{ "resource": "" }
q44551
buildAsyncOutputBufferCB
train
function buildAsyncOutputBufferCB(cb) { function AsyncOutputBufferCB(cb2) { this.accum = []; this.targetCB = cb2; } AsyncOutputBufferCB.prototype.processAsyncOutput = function(res) { // * Ignore switch-to-async mode calls since // we are actually collapsing async calls. // * Accumulate async call results in an array // till we get the signal that we are all done // * Once we are done, pass everything to the target cb. if (res.async !== true) { // There are 3 kinds of callbacks: // 1. cb({tokens: .. }) // 2. cb({}) ==> toks can be undefined // 3. cb(foo) -- which means in some cases foo can // be one of the two cases above, or it can also be a simple string. // // Version 1. is the general case. // Versions 2. and 3. are optimized scenarios to eliminate // additional processing of tokens. // // In the C++ version, this is handled more cleanly. var toks = res.tokens; if (!toks && res.constructor === String) { toks = res; } if (toks) { if (Array.isArray(toks)) { for (var i = 0, l = toks.length; i < l; i++) { this.accum.push(toks[i]); } // this.accum = this.accum.concat(toks); } else { this.accum.push(toks); } } if (!res.async) { // we are done! this.targetCB(this.accum); } } }; var r = new AsyncOutputBufferCB(cb); return r.processAsyncOutput.bind(r); }
javascript
{ "resource": "" }
q44552
train
function(res, text, httpStatus) { processLogger.log('fatal/request', text); apiUtils.errorResponse(res, text, httpStatus || 404); }
javascript
{ "resource": "" }
q44553
train
function(doc, pb) { // Effectively, skip applying data-parsoid. Note that if we were to // support a pb2html downgrade, we'd need to apply the full thing, // but that would create complications where ids would be left behind. // See the comment in around `DOMDataUtils.applyPageBundle` DOMDataUtils.applyPageBundle(doc, { parsoid: { ids: {} }, mw: pb.mw }); // Now, modify the pagebundle to the expected form. This is important // since, at least in the serialization path, the original pb will be // applied to the modified content and its presence could cause lost // deletions. pb.mw = { ids: {} }; }
javascript
{ "resource": "" }
q44554
train
function(codepoint) { // U+000C is valid in HTML5 but not allowed in XML. // U+000D is valid in XML but not allowed in HTML5. // U+007F - U+009F are disallowed in HTML5 (control characters). return codepoint === 0x09 || codepoint === 0x0a || (codepoint >= 0x20 && codepoint <= 0x7e) || (codepoint >= 0xa0 && codepoint <= 0xd7ff) || (codepoint >= 0xe000 && codepoint <= 0xfffd) || (codepoint >= 0x10000 && codepoint <= 0x10ffff); }
javascript
{ "resource": "" }
q44555
Batcher
train
function Batcher(env) { this.env = env; this.itemCallbacks = {}; this.currentBatch = []; this.pendingBatches = []; this.resultCache = {}; this.numOutstanding = 0; this.forwardProgressTimer = null; this.maxBatchSize = env.conf.parsoid.batchSize; this.targetConcurrency = env.conf.parsoid.batchConcurrency; // Max latency before we give up on a batch response and terminate the req. this.maxResponseLatency = env.conf.parsoid.timeouts.mwApi.batch * (1 + env.conf.parsoid.retries.mwApi.all) + 5 * 1000; }
javascript
{ "resource": "" }
q44556
train
function(node) { if (node.code) { // remove trailing whitespace for single-line predicates var code = node.code.replace(/[ \t]+$/, ''); // wrap with a function, to prevent spurious errors caused // by redeclarations or multiple returns in a block. rulesSource += tab + '(function() {\n' + code + '\n' + tab + '})();\n'; } }
javascript
{ "resource": "" }
q44557
train
function(options) { if (!options) { options = {}; } Object.keys(options).forEach(function(k) { console.assert(supportedOptions.has(k), 'Invalid cacheKey option: ' + k); }); // default: not an include context if (options.isInclude === undefined) { options.isInclude = false; } // default: wrap templates if (options.expandTemplates === undefined) { options.expandTemplates = true; } return options; }
javascript
{ "resource": "" }
q44558
startsOnANewLine
train
function startsOnANewLine(node) { var name = node.nodeName.toUpperCase(); return Consts.BlockScopeOpenTags.has(name) && !WTUtils.isLiteralHTMLNode(node) && name !== "BLOCKQUOTE"; }
javascript
{ "resource": "" }
q44559
hasBlocksOnLine
train
function hasBlocksOnLine(node, first) { // special case for firstNode: // we're at sol so ignore possible \n at first char if (first) { if (node.textContent.substring(1).match(/\n/)) { return false; } node = node.nextSibling; } while (node) { if (DOMUtils.isElt(node)) { if (DOMUtils.isBlockNode(node)) { return !startsOnANewLine(node); } if (node.hasChildNodes()) { if (hasBlocksOnLine(node.firstChild, false)) { return true; } } } else { if (node.textContent.match(/\n/)) { return false; } } node = node.nextSibling; } return false; }
javascript
{ "resource": "" }
q44560
logTypeToString
train
function logTypeToString(logType) { var logTypeString; if (logType instanceof RegExp) { logTypeString = logType.source; } else if (typeof (logType) === 'string') { logTypeString = '^' + JSUtils.escapeRegExp(logType) + '$'; } else { throw new Error('logType is neither a regular expression nor a string.'); } return logTypeString; }
javascript
{ "resource": "" }
q44561
train
function(parsoidConfig, options) { options = options || {}; // page information this.page = new Page(); Object.assign(this, options); // Record time spent in various passes this.timeProfile = {}; this.ioProfile = {}; this.mwProfile = {}; this.timeCategories = {}; this.counts = {}; // execution state this.setCaches({}); // Configuration this.conf = { parsoid: parsoidConfig, wiki: null, }; // FIXME: This is temporary and will be replaced after the call to // `switchToConfig`. However, it may somehow be used in the // `ConfigRequest` along the way. Perhaps worth seeing if that can be // eliminated so `WikiConfig` can't be instantiated without a `resultConf`. console.assert(parsoidConfig.mwApiMap.has(options.prefix)); this.conf.wiki = new WikiConfig(parsoidConfig, null, options.prefix); this.configureLogging(); // FIXME: Continuing with the line above, we can't initialize a specific // page until we have the correct wiki config, since things like // namespace aliases may not be same as the baseconfig, which has an // effect on what are considered valid titles. At present, the only // consequence should be that failed config requests would all be // attributed to the mainpage, which doesn't seem so bad. this.initializeForPageName(this.conf.wiki.mainpage); this.pipelineFactory = new ParserPipelineFactory(this); // Outstanding page requests (for templates etc) this.requestQueue = {}; this.batcher = new Batcher(this); this.setResourceLimits(); // Fragments have had `storeDataAttribs` called on them this.fragmentMap = new Map(); this.fid = 1; }
javascript
{ "resource": "" }
q44562
TemplateRequest
train
function TemplateRequest(env, title, oldid, opts) { ApiRequest.call(this, env, title); // IMPORTANT: Set queueKey to the 'title' // since TemplateHandler uses it for recording listeners this.queueKey = title; this.reqType = "Template Fetch"; opts = opts || {}; // optional extra arguments var apiargs = { format: 'json', // XXX: should use formatversion=2 action: 'query', prop: 'info|revisions', rawcontinue: 1, // all revision properties which parsoid is interested in. rvprop: 'content|ids|timestamp|size|sha1|contentmodel', rvslots: 'main', }; if (oldid) { this.oldid = oldid; apiargs.revids = oldid; } else { apiargs.titles = title; } this.requestOptions = { method: 'GET', followRedirect: true, uri: env.conf.wiki.apiURI, qs: apiargs, timeout: env.conf.parsoid.timeouts.mwApi.srcFetch, }; this.request(this.requestOptions); }
javascript
{ "resource": "" }
q44563
PreprocessorRequest
train
function PreprocessorRequest(env, title, text, queueKey) { ApiRequest.call(this, env, title); this.queueKey = queueKey; this.text = text; this.reqType = "Template Expansion"; var apiargs = { format: 'json', formatversion: 2, action: 'expandtemplates', prop: 'wikitext|categories|properties|modules|jsconfigvars', text: text, }; // the empty string is an invalid title // default value is: API if (title) { apiargs.title = title; } if (env.page.meta.revision.revid) { apiargs.revid = env.page.meta.revision.revid; } this.requestOptions = { // Use POST since we are passing a bit of source, and GET has a very // limited length. You'll be greeted by "HTTP Error 414 Request URI // too long" otherwise ;) method: 'POST', form: apiargs, // The API arguments followRedirect: true, uri: env.conf.wiki.apiURI, timeout: env.conf.parsoid.timeouts.mwApi.preprocessor, }; this.request(this.requestOptions); }
javascript
{ "resource": "" }
q44564
PHPParseRequest
train
function PHPParseRequest(env, title, text, onlypst, queueKey) { ApiRequest.call(this, env, title); this.text = text; this.queueKey = queueKey || text; this.reqType = "Extension Parse"; var apiargs = { format: 'json', formatversion: 2, action: 'parse', text: text, disablelimitreport: 'true', contentmodel: 'wikitext', prop: 'text|modules|jsconfigvars|categories', wrapoutputclass: '', }; if (onlypst) { apiargs.onlypst = 'true'; } // Pass the page title to the API if (title) { apiargs.title = title; } if (env.page.meta.revision.revid) { apiargs.revid = env.page.meta.revision.revid; } this.requestOptions = { // Use POST since we are passing a bit of source, and GET has a very // limited length. You'll be greeted by "HTTP Error 414 Request URI // too long" otherwise ;) method: 'POST', form: apiargs, // The API arguments followRedirect: true, uri: env.conf.wiki.apiURI, timeout: env.conf.parsoid.timeouts.mwApi.extParse, }; this.request(this.requestOptions); }
javascript
{ "resource": "" }
q44565
BatchRequest
train
function BatchRequest(env, batchParams, key) { ApiRequest.call(this, env); this.queueKey = key; this.batchParams = batchParams; this.reqType = 'Batch request'; this.batchText = JSON.stringify(batchParams); var apiargs = { format: 'json', formatversion: 2, action: 'parsoid-batch', batch: this.batchText, }; this.requestOptions = { method: 'POST', followRedirect: true, uri: env.conf.wiki.apiURI, timeout: env.conf.parsoid.timeouts.mwApi.batch, }; // Use multipart form encoding to get more efficient transfer if the gain // will be larger than the typical overhead. if (encodeURIComponent(apiargs.batch).length - apiargs.batch.length > 600) { this.requestOptions.formData = apiargs; } else { this.requestOptions.form = apiargs; } this.request(this.requestOptions); }
javascript
{ "resource": "" }
q44566
train
function(env) { ApiRequest.call(this, env, null); this.queueKey = env.conf.wiki.apiURI; this.reqType = "Config Request"; var metas = [ 'siteinfo' ]; var siprops = [ 'namespaces', 'namespacealiases', 'magicwords', 'functionhooks', 'extensiontags', 'general', 'interwikimap', 'languages', 'languagevariants', // T153341 'protocols', 'specialpagealiases', 'defaultoptions', 'variables', ]; var apiargs = { format: 'json', // XXX: should use formatversion=2 action: 'query', meta: metas.join('|'), siprop: siprops.join('|'), rawcontinue: 1, }; this.requestOptions = { method: 'GET', followRedirect: true, uri: env.conf.wiki.apiURI, qs: apiargs, timeout: env.conf.parsoid.timeouts.mwApi.configInfo, }; this.request(this.requestOptions); }
javascript
{ "resource": "" }
q44567
ImageInfoRequest
train
function ImageInfoRequest(env, filename, dims, key) { ApiRequest.call(this, env, null); this.env = env; this.queueKey = key; this.reqType = "Image Info Request"; var conf = env.conf.wiki; var filenames = [ filename ]; var imgnsid = conf.canonicalNamespaces.image; var imgns = conf.namespaceNames[imgnsid]; var props = [ 'mediatype', 'mime', 'size', 'url', 'badfile', ]; // If the videoinfo prop is available, as determined by our feature // detection when initializing the wiki config, use that to fetch the // derivates for videos. videoinfo is just a wrapper for imageinfo, // so all our media requests should go there, and the response can be // disambiguated by the returned mediatype. var prop, prefix; if (conf.useVideoInfo) { prop = 'videoinfo'; prefix = 'vi'; props.push('derivatives', 'timedtext'); } else { prop = 'imageinfo'; prefix = 'ii'; } this.ns = imgns; for (var ix = 0; ix < filenames.length; ix++) { filenames[ix] = imgns + ':' + filenames[ix]; } var apiArgs = { action: 'query', format: 'json', formatversion: 2, prop: prop, titles: filenames.join('|'), rawcontinue: 1, }; apiArgs[prefix + 'prop'] = props.join('|'); apiArgs[prefix + 'badfilecontexttitle'] = env.page.name; if (dims) { if (dims.width !== undefined && dims.width !== null) { console.assert(typeof (dims.width) === 'number'); apiArgs[prefix + 'urlwidth'] = dims.width; if (dims.page !== undefined) { // NOTE: This format is specific to PDFs. Not sure how to // support this generally, though it seems common enough / // shared with other file types. apiArgs[prefix + 'urlparam'] = `page${dims.page}-${dims.width}px`; } } if (dims.height !== undefined && dims.height !== null) { console.assert(typeof (dims.height) === 'number'); apiArgs[prefix + 'urlheight'] = dims.height; } if (dims.seek !== undefined) { apiArgs[prefix + 'urlparam'] = `seek=${dims.seek}`; } } this.requestOptions = { method: 'GET', followRedirect: true, uri: env.conf.wiki.apiURI, qs: apiArgs, timeout: env.conf.parsoid.timeouts.mwApi.imgInfo, }; this.request(this.requestOptions); }
javascript
{ "resource": "" }
q44568
TemplateDataRequest
train
function TemplateDataRequest(env, template, queueKey) { ApiRequest.call(this, env, null); this.env = env; this.text = template; this.queueKey = queueKey; this.reqType = "TemplateData Request"; var apiargs = { format: 'json', // XXX: should use formatversion=2 action: 'templatedata', includeMissingTitles: '1', titles: template, }; this.requestOptions = { // Use GET so this request can be cached in Varnish method: 'GET', qs: apiargs, followRedirect: true, uri: env.conf.wiki.apiURI, timeout: env.conf.parsoid.timeouts.mwApi.templateData, }; this.request(this.requestOptions); }
javascript
{ "resource": "" }
q44569
LintRequest
train
function LintRequest(env, data, queueKey) { ApiRequest.call(this, env, null); this.queueKey = queueKey || data; this.reqType = 'Lint Request'; var apiargs = { data: data, page: env.page.name, revision: env.page.meta.revision.revid, action: 'record-lint', format: 'json', formatversion: 2, }; this.requestOptions = { method: 'POST', form: apiargs, followRedirect: true, uri: env.conf.wiki.apiURI, timeout: env.conf.parsoid.timeouts.mwApi.lint, }; this.request(this.requestOptions); }
javascript
{ "resource": "" }
q44570
ParamInfoRequest
train
function ParamInfoRequest(env, queueKey) { ApiRequest.call(this, env, null); this.reqType = 'ParamInfo Request'; var apiargs = { format: 'json', // XXX: should use formatversion=2 action: 'paraminfo', modules: 'query', rawcontinue: 1, }; this.queueKey = queueKey || JSON.stringify(apiargs); this.requestOptions = { method: 'GET', followRedirect: true, uri: env.conf.wiki.apiURI, qs: apiargs, timeout: env.conf.parsoid.timeouts.mwApi.paramInfo, }; this.request(this.requestOptions); }
javascript
{ "resource": "" }
q44571
getSepNlConstraints
train
function getSepNlConstraints(state, nodeA, aCons, nodeB, bCons) { const env = state.env; const nlConstraints = { min: aCons.min, max: aCons.max, force: aCons.force || bCons.force, }; // now figure out if this conflicts with the nlConstraints so far if (bCons.min !== undefined) { if (nlConstraints.max !== undefined && nlConstraints.max < bCons.min) { // Conflict, warn and let nodeB win. env.log("info/html2wt", "Incompatible constraints 1:", nodeA.nodeName, nodeB.nodeName, loggableConstraints(nlConstraints)); nlConstraints.min = bCons.min; nlConstraints.max = bCons.min; } else { nlConstraints.min = Math.max(nlConstraints.min || 0, bCons.min); } } if (bCons.max !== undefined) { if (nlConstraints.min !== undefined && nlConstraints.min > bCons.max) { // Conflict, warn and let nodeB win. env.log("info/html2wt", "Incompatible constraints 2:", nodeA.nodeName, nodeB.nodeName, loggableConstraints(nlConstraints)); nlConstraints.min = bCons.max; nlConstraints.max = bCons.max; } else if (nlConstraints.max !== undefined) { nlConstraints.max = Math.min(nlConstraints.max, bCons.max); } else { nlConstraints.max = bCons.max; } } if (nlConstraints.max === undefined) { // Anything more than two lines will trigger paragraphs, so default to // two if nothing is specified. nlConstraints.max = 2; } return nlConstraints; }
javascript
{ "resource": "" }
q44572
mergeConstraints
train
function mergeConstraints(env, oldConstraints, newConstraints) { const res = { min: Math.max(oldConstraints.min || 0, newConstraints.min || 0), max: Math.min( oldConstraints.max !== undefined ? oldConstraints.max : 2, newConstraints.max !== undefined ? newConstraints.max : 2 ), force: oldConstraints.force || newConstraints.force, }; if (res.min > res.max) { // If oldConstraints.force is set, older constraints win if (!oldConstraints.force) { // let newConstraints win, but complain if (newConstraints.max !== undefined && newConstraints.max > res.min) { res.max = newConstraints.max; } else if (newConstraints.min && newConstraints.min < res.min) { res.min = newConstraints.min; } } res.max = res.min; env.log("info/html2wt", 'Incompatible constraints (merge):', res, loggableConstraints(oldConstraints), loggableConstraints(newConstraints)); } return res; }
javascript
{ "resource": "" }
q44573
train
function(state, nodeA, sepHandlerA, nodeB, sepHandlerB) { let sepType, nlConstraints, aCons, bCons; if (nodeA.nextSibling === nodeB) { // sibling separator sepType = "sibling"; aCons = sepHandlerA.after(nodeA, nodeB, state); bCons = sepHandlerB.before(nodeB, nodeA, state); nlConstraints = getSepNlConstraints(state, nodeA, aCons, nodeB, bCons); } else if (nodeB.parentNode === nodeA) { // parent-child separator, nodeA parent of nodeB sepType = "parent-child"; aCons = sepHandlerA.firstChild(nodeA, nodeB, state); bCons = sepHandlerB.before(nodeB, nodeA, state); nlConstraints = getSepNlConstraints(state, nodeA, aCons, nodeB, bCons); } else if (nodeA.parentNode === nodeB) { // parent-child separator, nodeB parent of nodeA sepType = "child-parent"; aCons = sepHandlerA.after(nodeA, nodeB, state); bCons = sepHandlerB.lastChild(nodeB, nodeA, state); nlConstraints = getSepNlConstraints(state, nodeA, aCons, nodeB, bCons); } else { // sibling separator sepType = "sibling"; aCons = sepHandlerA.after(nodeA, nodeB, state); bCons = sepHandlerB.before(nodeB, nodeA, state); nlConstraints = getSepNlConstraints(state, nodeA, aCons, nodeB, bCons); } if (nodeA.nodeName === undefined) { console.trace(); } if (state.sep.constraints) { // Merge the constraints state.sep.constraints = mergeConstraints( state.env, state.sep.constraints, nlConstraints ); } else { state.sep.constraints = nlConstraints; } state.env.log('debug/wts/sep', function() { return 'constraint' + ' | ' + sepType + ' | <' + nodeA.nodeName + ',' + nodeB.nodeName + '>' + ' | ' + JSON.stringify(state.sep.constraints) + ' | ' + debugOut(nodeA) + ' | ' + debugOut(nodeB); }); state.sep.constraints.constraintInfo = { onSOL: state.onSOL, // force SOL state when separator is built/emitted forceSOL: sepHandlerB.forceSOL, sepType: sepType, nodeA: nodeA, nodeB: nodeB, }; }
javascript
{ "resource": "" }
q44574
train
function(node) { var dp = DOMDataUtils.getDataParsoid(node); var dsr = Util.clone(dp.dsr); if (dp.autoInsertedStart) { dsr[2] = null; } if (dp.autoInsertedEnd) { dsr[3] = null; } return dsr; }
javascript
{ "resource": "" }
q44575
train
function(diff) { var ret = []; diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier // Formats a given set of lines for printing as context lines in a patch function contextLines(lines) { return lines.map(function(entry) { return ' ' + entry; }); } var oldRangeStart = 0; var newRangeStart = 0; var curRange = []; var oldLine = 1; var newLine = 1; for (var i = 0; i < diff.length; i++) { var current = diff[i]; var lines = current.lines || current.value.replace(/\n$/, '').split('\n'); current.lines = lines; if (current.added || current.removed) { // If we have previous context, start with that if (!oldRangeStart) { var prev = diff[i - 1]; oldRangeStart = oldLine; newRangeStart = newLine; if (prev) { curRange = contextLines(prev.lines.slice(-4)); oldRangeStart -= curRange.length; newRangeStart -= curRange.length; } } // Output our changes curRange.push.apply(curRange, lines.map(function(entry) { return (current.added ? '+' : '-') + entry; })); // Track the updated file position if (current.added) { newLine += lines.length; } else { oldLine += lines.length; } } else { // Identical context lines. Track line changes if (oldRangeStart) { // Close out any changes that have been output (or join overlapping) if (lines.length <= 8 && i < diff.length - 2) { // Overlapping curRange.push.apply(curRange, contextLines(lines)); } else { // end the range and output var contextSize = Math.min(lines.length, 4); ret.push( '@@ -' + oldRangeStart + ',' + (oldLine - oldRangeStart + contextSize) + ' +' + newRangeStart + ',' + (newLine - newRangeStart + contextSize) + ' @@'); ret.push.apply(ret, curRange); ret.push.apply(ret, contextLines(lines.slice(0, contextSize))); oldRangeStart = 0; newRangeStart = 0; curRange = []; } } oldLine += lines.length; newLine += lines.length; } } return ret.join('\n') + '\n'; }
javascript
{ "resource": "" }
q44576
train
function(value) { var ret = []; var linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line if (!linesAndNewlines[linesAndNewlines.length - 1]) { linesAndNewlines.pop(); } // Merge the content and line separators into single tokens for (var i = 0; i < linesAndNewlines.length; i++) { var line = linesAndNewlines[i]; if (i % 2) { ret[ret.length - 1] += line; } else { ret.push(line); } } return ret; }
javascript
{ "resource": "" }
q44577
mergable
train
function mergable(a, b) { return a.nodeName === b.nodeName && similar(a, b); }
javascript
{ "resource": "" }
q44578
swappable
train
function swappable(a, b) { return DOMUtils.numNonDeletedChildNodes(a) === 1 && similar(a, DOMUtils.firstNonDeletedChild(a)) && mergable(DOMUtils.firstNonDeletedChild(a), b); }
javascript
{ "resource": "" }
q44579
train
function(parsoidOptions, cliOpts) { [ 'fetchConfig', 'fetchTemplates', 'fetchImageInfo', 'expandExtensions', 'rtTestMode', 'addHTMLTemplateParameters', ].forEach(function(c) { if (cliOpts[c] !== undefined) { parsoidOptions[c] = ScriptUtils.booleanOption(cliOpts[c]); } }); if (cliOpts.usePHPPreProcessor !== undefined) { parsoidOptions.usePHPPreProcessor = parsoidOptions.fetchTemplates && ScriptUtils.booleanOption(cliOpts.usePHPPreProcessor); } if (cliOpts.maxDepth !== undefined) { parsoidOptions.maxDepth = typeof (cliOpts.maxdepth) === 'number' ? cliOpts.maxdepth : parsoidOptions.maxDepth; } if (cliOpts.apiURL) { if (!Array.isArray(parsoidOptions.mwApis)) { parsoidOptions.mwApis = []; } parsoidOptions.mwApis.push({ prefix: 'customwiki', uri: cliOpts.apiURL }); } if (cliOpts.addHTMLTemplateParameters !== undefined) { parsoidOptions.addHTMLTemplateParameters = ScriptUtils.booleanOption(cliOpts.addHTMLTemplateParameters); } if (cliOpts.lint) { parsoidOptions.linting = true; if (!parsoidOptions.linter) { parsoidOptions.linter = {}; } parsoidOptions.linter.sendAPI = false; } if (cliOpts.useBatchAPI !== null) { parsoidOptions.useBatchAPI = ScriptUtils.booleanOption(cliOpts.useBatchAPI); } if (cliOpts.phpConfigFile) { parsoidOptions.phpConfigFile = cliOpts.phpConfigFile; } return parsoidOptions; }
javascript
{ "resource": "" }
q44580
train
function(options) { var colors = require('colors'); if (options.color === 'auto') { if (!process.stdout.isTTY) { colors.mode = 'none'; } } else if (!ScriptUtils.booleanOption(options.color)) { colors.mode = 'none'; } }
javascript
{ "resource": "" }
q44581
merge
train
function merge (inputs) { var output = { type: 'FeatureCollection', features: [] }; for (var i = 0; i < inputs.length; i++) { var normalized = normalize(inputs[i]); for (var j = 0; j < normalized.features.length; j++) { output.features.push(normalized.features[j]); } } return output; }
javascript
{ "resource": "" }
q44582
mergeFeatureCollectionStream
train
function mergeFeatureCollectionStream (inputs) { var out = geojsonStream.stringify(); inputs.forEach(function(file) { fs.createReadStream(file) .pipe(geojsonStream.parse()) .pipe(out); }); return out; }
javascript
{ "resource": "" }
q44583
onerror
train
function onerror(err) { if (!err) { return; } debug('[%s] [cfork:master:%s] master uncaughtException: %s', Date(), process.pid, err.stack); debug(err); debug('(total %d disconnect, %d unexpected exit)', disconnectCount, unexpectedCount); }
javascript
{ "resource": "" }
q44584
onUnexpected
train
function onUnexpected(worker, code, signal) { var exitCode = worker.process.exitCode; var err = new Error(util.format('worker:%s died unexpected (code: %s, signal: %s, exitedAfterDisconnect: %s, state: %s)', worker.process.pid, exitCode, signal, worker.exitedAfterDisconnect, worker.state)); err.name = 'WorkerDiedUnexpectedError'; debug('[%s] [cfork:master:%s] (total %d disconnect, %d unexpected exit) %s', Date(), process.pid, disconnectCount, unexpectedCount, err.stack); }
javascript
{ "resource": "" }
q44585
normalizeSlaveConfig
train
function normalizeSlaveConfig(opt) { // exec path if (typeof opt === 'string') { opt = { exec: opt }; } if (!opt.exec) { return null; } else { return opt; } }
javascript
{ "resource": "" }
q44586
forkWorker
train
function forkWorker(settings, env) { if (settings) { cluster.settings = settings; cluster.setupMaster(); } return cluster.fork(env); }
javascript
{ "resource": "" }
q44587
MouseEvent
train
function MouseEvent(eventType, params) { params = params || { bubbles: false, cancelable: false }; var mouseEvent = document.createEvent('MouseEvent'); mouseEvent.initMouseEvent(eventType, params.bubbles, params.cancelable, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); return mouseEvent; }
javascript
{ "resource": "" }
q44588
simulateMouseEvent
train
function simulateMouseEvent(e) { e.preventDefault(); const touch = e.changedTouches[0]; const eventMap = { 'touchstart': 'mousedown', 'touchmove': 'mousemove', 'touchend': 'mouseup' } touch.target.dispatchEvent(new MouseEvent(eventMap[e.type], { bubbles: true, cancelable: true, view: window, clientX: touch.clientX, clientY: touch.clientY, screenX: touch.screenX, screenY: touch.screenY, })); }
javascript
{ "resource": "" }
q44589
onCardHeaderClick
train
function onCardHeaderClick(e) { if (/** @type {!Element} */(e.target).nodeName == 'A') { return; } /** @type {?Node} */ const node = /** @type {!Element} */(e.currentTarget).parentNode; if (node && node.nodeType === NodeType.ELEMENT) { const card = /** @type {!Element} */(node); if (card.classList && card.classList.contains('property')) { card.classList.toggle('open'); } } }
javascript
{ "resource": "" }
q44590
parseMessage
train
function parseMessage(message) { const parts = message.content.split(' '); const command = parts[1]; const args = parts.slice(2); if (typeof Commands[command] === 'function') { // @TODO We could check the command validity here return { command, args }; } else { return null; } }
javascript
{ "resource": "" }
q44591
train
function (next) { console.log(chalk.yellow.bold('Publishing wiki...')); // create a location to clone repository // @todo - maybe do this outside in an os-level temp folder to avoid recursive .git mkdir('-p', WIKI_GIT_PATH); rm('-rf', WIKI_GIT_PATH); // @todo: Consider navigating to WIKI_GIT_PATH, setting up a new git repo there, point the remote // to WIKI_GIT_URL, // @todo: and push exec(`git clone ${WIKI_URL} ${WIKI_GIT_PATH} --quiet`, next); }
javascript
{ "resource": "" }
q44592
train
function (next) { var source = fs.readFileSync(path.join('out', 'wiki', 'REFERENCE.md')).toString(), home, sidebar; // extract sidebar from source sidebar = source.replace(/<a name="Collection"><\/a>[\s\S]+/g, ''); // remove sidebar data from home home = source.substr(sidebar.length); // add timestamp to sidebar sidebar += '\n\n ' + (new Date()).toUTCString(); async.each([{ path: path.join('.tmp', 'github-wiki', '_Sidebar.md'), data: sidebar }, { path: path.join('.tmp', 'github-wiki', 'Home.md'), data: home }], function (opts, next) { fs.writeFile(opts.path, opts.data, next); }, next); }
javascript
{ "resource": "" }
q44593
train
function (next) { // silence terminal output to prevent leaking sensitive information config.silent = true; pushd(WIKI_GIT_PATH); exec('git add --all'); exec('git commit -m "[auto] ' + WIKI_VERSION + '"'); exec('git push origin master', function (code) { popd(); next(code); }); }
javascript
{ "resource": "" }
q44594
train
function (obj, overrides, mutate) { var resolutionQueue = [], // we use this to store the queue of variable hierarchy // this is an intermediate object to stimulate a property (makes the do-while loop easier) variableSource = { variables: this, __parent: this.__parent }; do { // iterate and accumulate as long as you find `.variables` in parent tree variableSource.variables && resolutionQueue.push(variableSource.variables); variableSource = variableSource.__parent; } while (variableSource); variableSource = null; // cautious cleanup return Property.replaceSubstitutionsIn(obj, _.union(resolutionQueue, overrides), mutate); }
javascript
{ "resource": "" }
q44595
train
function (obj, track, prune) { var list = this, ops = track && { created: [], updated: [], deleted: [] }, indexer = list._postman_listIndexKey, tmp; if (!_.isObject(obj)) { return ops; } // ensure that all properties in the object is updated in this list _.forOwn(obj, function (value, key) { // we need to create new variable if exists or update existing if (list.has(key)) { list.one(key).set(value); ops && ops.updated.push(key); } else { tmp = { value: value }; tmp[indexer] = key; list.add(tmp); tmp = null; ops && ops.created.push(key); } }); // now remove any variable that is not in source object // @note - using direct `this.reference` list of keys here so that we can mutate the list while iterating // on it if (prune !== false) { _.forEach(list.reference, function (value, key) { if (obj.hasOwnProperty(key)) { return; } // de not delete if source obj has this variable list.remove(key); // use PropertyList functions to remove so that the .members array is cleared too ops && ops.deleted.push(key); }); } return ops; }
javascript
{ "resource": "" }
q44596
train
function (obj) { var list = this; // in case user did not provide an object to mutate, create a new one !_.isObject(obj) && (obj = {}); // delete extra variables from object that are not present in list _.forEach(obj, function (value, key) { !_.has(list.reference, key) && (delete obj[key]); }); // we first sync all variables in this list to the object list.each(function (variable) { obj[variable.key] = variable.valueOf(); }); return obj; }
javascript
{ "resource": "" }
q44597
train
function (obj) { return Boolean(obj) && ((obj instanceof VariableList) || _.inSuperChain(obj.constructor, '_postman_propertyName', VariableList._postman_propertyName)); }
javascript
{ "resource": "" }
q44598
train
function (url) { // url must be either string or an instance of url. if (!_.isString(url) && !Url.isUrl(url)) { return; } // find a certificate that can be applied to the url return this.find(function (certificate) { return certificate.canApplyTo(url); }); }
javascript
{ "resource": "" }
q44599
train
function (obj) { return Boolean(obj) && ((obj instanceof CertificateList) || _.inSuperChain(obj.constructor, '_postman_propertyName', CertificateList._postman_propertyName)); }
javascript
{ "resource": "" }