_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q53700
train
function(name) { var args = _.toArray(arguments).slice(1); var results = eventsApi(this, 'request', name, args); if (results) { return results; } var channelName = this.channelName; var requests = this._requests; // Check if we should log the request, and if so, do it if (channelName && this._tunedIn) { Radio.log.apply(this, [channelName, name].concat(args)); } // If the request isn't handled, log it in DEBUG mode and exit if (requests && (requests[name] || requests['default'])) { var handler = requests[name] || requests['default']; args = requests[name] ? args : arguments; return callHandler(handler.callback, handler.context, args); } else { Radio.debugLog('An unhandled request was fired', name, channelName); } }
javascript
{ "resource": "" }
q53701
train
function(name, callback, context) { if (eventsApi(this, 'replyOnce', name, [callback, context])) { return this; } var self = this; var once = _.once(function() { self.stopReplying(name); return makeCallback(callback).apply(this, arguments); }); return this.reply(name, once, context); }
javascript
{ "resource": "" }
q53702
isDelimiter
train
function isDelimiter(code) { return code === 0x22 // '"' || code === 0x28 // '(' || code === 0x29 // ')' || code === 0x2C // ',' || code === 0x2F // '/' || code >= 0x3A && code <= 0x40 // ':', ';', '<', '=', '>', '?' '@' || code >= 0x5B && code <= 0x5D // '[', '\', ']' || code === 0x7B // '{' || code === 0x7D; // '}' }
javascript
{ "resource": "" }
q53703
isTokenChar
train
function isTokenChar(code) { return code === 0x21 // '!' || code >= 0x23 && code <= 0x27 // '#', '$', '%', '&', ''' || code === 0x2A // '*' || code === 0x2B // '+' || code === 0x2D // '-' || code === 0x2E // '.' || code >= 0x30 && code <= 0x39 // 0-9 || code >= 0x41 && code <= 0x5A // A-Z || code >= 0x5E && code <= 0x7A // '^', '_', '`', a-z || code === 0x7C // '|' || code === 0x7E; // '~' }
javascript
{ "resource": "" }
q53704
ParseError
train
function ParseError(message, input) { Error.captureStackTrace(this, ParseError); this.name = this.constructor.name; this.message = message; this.input = input; }
javascript
{ "resource": "" }
q53705
extractPath
train
function extractPath(schemaPath) { const subNames = schemaPath.path.split('.'); return reduceRight(subNames, (fields, name, key) => { const obj = {}; if (schemaPath instanceof mongoose.Schema.Types.DocumentArray) { const subSchemaPaths = schemaPath.schema.paths; const fields = extractPaths(subSchemaPaths, { name }); // eslint-disable-line no-use-before-define obj[name] = { name, fields, nonNull: false, type: 'Array', subtype: 'Object' }; } else if (schemaPath instanceof mongoose.Schema.Types.Embedded) { schemaPath.modelName = schemaPath.schema.options.graphqlTypeName || name; // embedded model must be unique Instance const embeddedModel = embeddedModels.hasOwnProperty(schemaPath.modelName) ? embeddedModels[schemaPath.modelName] : getModel(schemaPath); // eslint-disable-line no-use-before-define embeddedModels[schemaPath.modelName] = embeddedModel; obj[name] = { ...getField(schemaPath), embeddedModel }; } else if (key === subNames.length - 1) { obj[name] = getField(schemaPath); } else { obj[name] = { name, fields, nonNull: false, type: 'Object' }; } return obj; }, {}); }
javascript
{ "resource": "" }
q53706
extractPaths
train
function extractPaths(schemaPaths, model) { return reduce(schemaPaths, (fields, schemaPath) => ( merge(fields, extractPath(schemaPath, model)) ), {}); }
javascript
{ "resource": "" }
q53707
getModel
train
function getModel(model) { const schemaPaths = model.schema.paths; const name = model.modelName; const fields = extractPaths(schemaPaths, { name }); return { name, fields, model }; }
javascript
{ "resource": "" }
q53708
getIdFetcher
train
function getIdFetcher(graffitiModels) { return function idFetcher(obj, { id: globalId }, context, info) { const { type, id } = fromGlobalId(globalId); if (type === 'Viewer') { return viewer; } else if (graffitiModels[type]) { const Collection = graffitiModels[type].model; return getOne(Collection, { id }, context, info); } return null; }; }
javascript
{ "resource": "" }
q53709
emptyConnection
train
function emptyConnection() { return { count: 0, edges: [], pageInfo: { startCursor: null, endCursor: null, hasPreviousPage: false, hasNextPage: false } }; }
javascript
{ "resource": "" }
q53710
connectionFromModel
train
async function connectionFromModel(graffitiModel, args, context, info) { const Collection = graffitiModel.model; if (!Collection) { return emptyConnection(); } const { before, after, first, last, id, orderBy = { _id: 1 }, ...selector } = args; const begin = getId(after); const end = getId(before); const offset = (first - last) || 0; const limit = last || first; if (id) { selector.id = id; } if (begin) { selector._id = selector._id || {}; selector._id.$gt = begin; } if (end) { selector._id = selector._id || {}; selector._id.$lt = end; } const result = await getList(Collection, selector, { limit, skip: offset, sort: orderBy }, context, info); const count = await getCount(Collection, selector); if (result.length === 0) { return emptyConnection(); } const edges = result.map((value) => ({ cursor: idToCursor(value._id), node: value })); const firstElement = await getFirst(Collection); return { count, edges, pageInfo: { startCursor: edges[0].cursor, endCursor: edges[edges.length - 1].cursor, hasPreviousPage: cursorToId(edges[0].cursor) !== firstElement._id.toString(), hasNextPage: result.length === limit } }; }
javascript
{ "resource": "" }
q53711
stringToGraphQLType
train
function stringToGraphQLType(type) { switch (type) { case 'String': return GraphQLString; case 'Number': return GraphQLFloat; case 'Date': return GraphQLDate; case 'Buffer': return GraphQLBuffer; case 'Boolean': return GraphQLBoolean; case 'ObjectID': return GraphQLID; default: return GraphQLGeneric; } }
javascript
{ "resource": "" }
q53712
listToGraphQLEnumType
train
function listToGraphQLEnumType(list, name) { const values = reduce(list, (values, val) => { values[val] = { value: val }; return values; }, {}); return new GraphQLEnumType({ name, values }); }
javascript
{ "resource": "" }
q53713
getTypeFields
train
function getTypeFields(type) { const fields = type._typeConfig.fields; return isFunction(fields) ? fields() : fields; }
javascript
{ "resource": "" }
q53714
getOrderByType
train
function getOrderByType({ name }, fields) { if (!orderByTypes[name]) { // save new enum orderByTypes[name] = new GraphQLEnumType({ name: `orderBy${name}`, values: reduce(fields, (values, field) => { if (field.type instanceof GraphQLScalarType) { const upperCaseName = field.name.toUpperCase(); values[`${upperCaseName}_ASC`] = { name: `${upperCaseName}_ASC`, value: { [field.name]: 1 } }; values[`${upperCaseName}_DESC`] = { name: `${upperCaseName}_DESC`, value: { [field.name]: -1 } }; } return values; }, {}) }); } return orderByTypes[name]; }
javascript
{ "resource": "" }
q53715
getArguments
train
function getArguments(type, args = {}) { const fields = getTypeFields(type); return reduce(fields, (args, field) => { // Extract non null fields, those are not required in the arguments if (field.type instanceof GraphQLNonNull && field.name !== 'id') { field.type = field.type.ofType; } if (field.type instanceof GraphQLScalarType) { args[field.name] = field; } return args; }, { ...args, orderBy: { name: 'orderBy', type: getOrderByType(type, fields) } }); }
javascript
{ "resource": "" }
q53716
getTypeFieldName
train
function getTypeFieldName(typeName, fieldName) { const fieldNameCapitalized = fieldName.charAt(0).toUpperCase() + fieldName.slice(1); return `${typeName}${fieldNameCapitalized}`; }
javascript
{ "resource": "" }
q53717
getFields
train
function getFields(graffitiModels, { hooks = {}, mutation = true, allowMongoIDMutation = false, customQueries = {}, customMutations = {} } = {}) { const types = type.getTypes(graffitiModels); const { viewer, singular } = hooks; const viewerFields = reduce(types, (fields, type, key) => { type.name = type.name || key; const graffitiModel = graffitiModels[type.name]; return { ...fields, ...getConnectionField(graffitiModel, type, hooks), ...getSingularQueryField(graffitiModel, type, hooks) }; }, { id: globalIdField('Viewer') }); setTypeFields(GraphQLViewer, viewerFields); const viewerField = { name: 'Viewer', type: GraphQLViewer, resolve: addHooks(() => viewerInstance, viewer) }; const { queries, mutations } = reduce(types, ({ queries, mutations }, type, key) => { type.name = type.name || key; const graffitiModel = graffitiModels[type.name]; return { queries: { ...queries, ...getQueryField(graffitiModel, type, hooks) }, mutations: { ...mutations, ...getMutationField(graffitiModel, type, viewerField, hooks, allowMongoIDMutation) } }; }, { queries: isFunction(customQueries) ? customQueries(mapValues(types, (type) => createInputObject(type)), types) : customQueries, mutations: isFunction(customMutations) ? customMutations(mapValues(types, (type) => createInputObject(type)), types) : customMutations }); const RootQuery = new GraphQLObjectType({ name: 'RootQuery', fields: { ...queries, viewer: viewerField, node: { name: 'node', description: 'Fetches an object given its ID', type: nodeInterface, args: { id: { type: new GraphQLNonNull(GraphQLID), description: 'The ID of an object' } }, resolve: addHooks(getIdFetcher(graffitiModels), singular) } } }); const RootMutation = new GraphQLObjectType({ name: 'RootMutation', fields: mutations }); const fields = { query: RootQuery }; if (mutation) { fields.mutation = RootMutation; } return fields; }
javascript
{ "resource": "" }
q53718
getSchema
train
function getSchema(mongooseModels, options) { if (!isArray(mongooseModels)) { mongooseModels = [mongooseModels]; } const graffitiModels = model.getModels(mongooseModels); const fields = getFields(graffitiModels, options); return new GraphQLSchema(fields); }
javascript
{ "resource": "" }
q53719
train
function (name) { var dotPos = name.indexOf('.'); if (dotPos > -1) { name = name.substring(0, dotPos); } return name; }
javascript
{ "resource": "" }
q53720
detectDependencies
train
function detectDependencies(config) { var allDependencies = {}; if (config.get('dependencies')) { $._.assign(allDependencies, config.get('bower.json').dependencies); } if (config.get('dev-dependencies')) { $._.assign(allDependencies, config.get('bower.json').devDependencies); } if (config.get('include-self')) { allDependencies[config.get('bower.json').name] = config.get('bower.json').version; } $._.each(allDependencies, gatherInfo(config)); config.set('global-dependencies-sorted', filterExcludedDependencies( config.get('detectable-file-types'). reduce(function (acc, fileType) { if (!acc[fileType]) { acc[fileType] = prioritizeDependencies(config, '.' + fileType); } return acc; }, {}), config.get('exclude') )); return config; }
javascript
{ "resource": "" }
q53721
injectDependencies
train
function injectDependencies(globalConfig) { config = globalConfig; var stream = config.get('stream'); globalDependenciesSorted = config.get('global-dependencies-sorted'); ignorePath = config.get('ignore-path'); fileTypes = config.get('file-types'); if (stream.src) { config.set('stream', { src: injectScriptsStream(stream.path, stream.src, stream.fileType), fileType: stream.fileType }); } else { config.get('src').forEach(injectScripts); } return config; }
javascript
{ "resource": "" }
q53722
uiTagOffset
train
function uiTagOffset(corners) { return { top: corners.top + corners.height / 2 - 10, left: corners.right - 6 }; }
javascript
{ "resource": "" }
q53723
filterDomElement
train
function filterDomElement(domElement, names, labels) { /* Where we look to find a match, in this order: name, id, <label> tags, placeholder, title Our searches first conduct fairly liberal "contains" searches: if the attribute even contains the name or label, we map it. The names and labels we choose to find are very particular. */ var name = lowercase(domElement.name); var id = lowercase(domElement.id); var selectorSafeID = id.replace(/[\[|\]|\(|\)|\:|\'|\"|\=|\||\#|\.|\!|\||\@|\^|\&|\*]/g, "\\\\$&"); var placeholder = lowercase(domElement.placeholder); var title = lowercase(domElement.title); // First look through name and id attributes of the element, the most common for (var i = 0; i < names.length; i++) if (name.indexOf(names[i]) > -1 || id.indexOf(names[i]) > -1) return true; // If we can't find it in name or id, look at labels associated to the element. // Webkit automatically associates labels with form elements for us. But for other // browsers, we have to find them manually, which this next block does. if (!("labels" in domElement)) { var lbl = $("label[for=\"" + selectorSafeID + "\"]")[0] || $(domElement).parents("label")[0]; domElement.labels = !lbl ? [] : [lbl]; } // Iterate through the <label> tags now to search for a match. for (var i = 0; i < domElement.labels.length; i++) { // This inner loop compares each label value with what we're looking for for (var j = 0; j < labels.length; j++) if ($(domElement.labels[i]).text().toLowerCase().indexOf(labels[j]) > -1) return true; } // Still not found? Then look in "placeholder" or "title"... for (var i = 0; i < labels.length; i++) if (placeholder.indexOf(labels[i]) > -1 || title.indexOf(labels[i]) > -1) return true; // Got all the way to here? Probably not a match then. return false; }
javascript
{ "resource": "" }
q53724
turnOffAllClicks
train
function turnOffAllClicks(selectors) { if (Array.isArray(selectors) || typeof selectors == "object") { for (var selector in selectors) { if (selectors.hasOwnProperty(selector)) { $("body").off("click", selectors[selector]); } } } else if (typeof selectors === "string") { $("body").off("click", selectors); } else { alert("ERROR: Not an array, string, or object passed in to turn off all clicks"); } }
javascript
{ "resource": "" }
q53725
train
function (invokeOn, invokeFunction) { if (invokeOn && typeof invokeOn !== "function" && invokeFunction) { if (invokeFunction == "click") { setTimeout(function () { $(invokeOn).click(); // Very particular: we MUST fire the native "click" event! }, 5); } else if (invokeFunction == "submit") $(invokeOn).submit(); // For submit(), we have to use jQuery's, so that all its submit handlers fire. } }
javascript
{ "resource": "" }
q53726
train
function (options, patterns) { // Return all matching filepaths. var matches = processPatterns(patterns, function (pattern) { // Find all matching files for this pattern. return glob.sync(pattern, options); }); // Filter result set? if (options.filter) { matches = matches.filter(function (filepath) { filepath = path.join(options.cwd || '', filepath); try { if (typeof options.filter === 'function') { return options.filter(filepath); } else { // If the file is of the right type and exists, this should work. return fs.statSync(filepath)[options.filter](); } } catch (e) { // Otherwise, it's probably not the right type. return false; } }); } return matches; }
javascript
{ "resource": "" }
q53727
FusionPoseSensor
train
function FusionPoseSensor(kFilter, predictionTime, yawOnly, isDebug) { this.yawOnly = yawOnly; this.accelerometer = new MathUtil.Vector3(); this.gyroscope = new MathUtil.Vector3(); this.filter = new ComplementaryFilter(kFilter, isDebug); this.posePredictor = new PosePredictor(predictionTime, isDebug); this.isFirefoxAndroid = Util.isFirefoxAndroid(); this.isIOS = Util.isIOS(); // Chrome as of m66 started reporting `rotationRate` in degrees rather // than radians, to be consistent with other browsers. // https://github.com/immersive-web/cardboard-vr-display/issues/18 let chromeVersion = Util.getChromeVersion(); this.isDeviceMotionInRadians = !this.isIOS && chromeVersion && chromeVersion < 66; // In Chrome m65 there's a regression of devicemotion events. Fallback // to using deviceorientation for these specific builds. More information // at `Util.isChromeWithoutDeviceMotion`. this.isWithoutDeviceMotion = Util.isChromeWithoutDeviceMotion(); this.filterToWorldQ = new MathUtil.Quaternion(); // Set the filter to world transform, depending on OS. if (Util.isIOS()) { this.filterToWorldQ.setFromAxisAngle(new MathUtil.Vector3(1, 0, 0), Math.PI / 2); } else { this.filterToWorldQ.setFromAxisAngle(new MathUtil.Vector3(1, 0, 0), -Math.PI / 2); } this.inverseWorldToScreenQ = new MathUtil.Quaternion(); this.worldToScreenQ = new MathUtil.Quaternion(); this.originalPoseAdjustQ = new MathUtil.Quaternion(); this.originalPoseAdjustQ.setFromAxisAngle(new MathUtil.Vector3(0, 0, 1), -window.orientation * Math.PI / 180); this.setScreenTransform_(); // Adjust this filter for being in landscape mode. if (Util.isLandscapeMode()) { this.filterToWorldQ.multiply(this.inverseWorldToScreenQ); } // Keep track of a reset transform for resetSensor. this.resetQ = new MathUtil.Quaternion(); this.orientationOut_ = new Float32Array(4); this.start(); }
javascript
{ "resource": "" }
q53728
DeviceInfo
train
function DeviceInfo(deviceParams, additionalViewers) { this.viewer = Viewers.CardboardV2; this.updateDeviceParams(deviceParams); this.distortion = new Distortion(this.viewer.distortionCoefficients); for (var i = 0; i < additionalViewers.length; i++) { var viewer = additionalViewers[i]; Viewers[viewer.id] = new CardboardViewer(viewer); } }
javascript
{ "resource": "" }
q53729
CardboardDistorter
train
function CardboardDistorter(gl, cardboardUI, bufferScale, dirtySubmitFrameBindings) { this.gl = gl; this.cardboardUI = cardboardUI; this.bufferScale = bufferScale; this.dirtySubmitFrameBindings = dirtySubmitFrameBindings; this.ctxAttribs = gl.getContextAttributes(); this.meshWidth = 20; this.meshHeight = 20; this.bufferWidth = gl.drawingBufferWidth; this.bufferHeight = gl.drawingBufferHeight; // Patching support this.realBindFramebuffer = gl.bindFramebuffer; this.realEnable = gl.enable; this.realDisable = gl.disable; this.realColorMask = gl.colorMask; this.realClearColor = gl.clearColor; this.realViewport = gl.viewport; if (!Util.isIOS()) { this.realCanvasWidth = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'width'); this.realCanvasHeight = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'height'); } this.isPatched = false; // State tracking this.lastBoundFramebuffer = null; this.cullFace = false; this.depthTest = false; this.blend = false; this.scissorTest = false; this.stencilTest = false; this.viewport = [0, 0, 0, 0]; this.colorMask = [true, true, true, true]; this.clearColor = [0, 0, 0, 0]; this.attribs = { position: 0, texCoord: 1 }; this.program = Util.linkProgram(gl, distortionVS, distortionFS, this.attribs); this.uniforms = Util.getProgramUniforms(gl, this.program); this.viewportOffsetScale = new Float32Array(8); this.setTextureBounds(); this.vertexBuffer = gl.createBuffer(); this.indexBuffer = gl.createBuffer(); this.indexCount = 0; this.renderTarget = gl.createTexture(); this.framebuffer = gl.createFramebuffer(); this.depthStencilBuffer = null; this.depthBuffer = null; this.stencilBuffer = null; if (this.ctxAttribs.depth && this.ctxAttribs.stencil) { this.depthStencilBuffer = gl.createRenderbuffer(); } else if (this.ctxAttribs.depth) { this.depthBuffer = gl.createRenderbuffer(); } else if (this.ctxAttribs.stencil) { this.stencilBuffer = gl.createRenderbuffer(); } this.patch(); this.onResize(); }
javascript
{ "resource": "" }
q53730
PosePredictor
train
function PosePredictor(predictionTimeS, isDebug) { this.predictionTimeS = predictionTimeS; this.isDebug = isDebug; // The quaternion corresponding to the previous state. this.previousQ = new MathUtil.Quaternion(); // Previous time a prediction occurred. this.previousTimestampS = null; // The delta quaternion that adjusts the current pose. this.deltaQ = new MathUtil.Quaternion(); // The output quaternion. this.outQ = new MathUtil.Quaternion(); }
javascript
{ "resource": "" }
q53731
CardboardVRDisplay
train
function CardboardVRDisplay(config) { var defaults = Util.extend({}, Options); config = Util.extend(defaults, config || {}); VRDisplay.call(this, { wakelock: config.MOBILE_WAKE_LOCK, }); this.config = config; this.displayName = 'Cardboard VRDisplay'; this.capabilities = new VRDisplayCapabilities({ hasPosition: false, hasOrientation: true, hasExternalDisplay: false, canPresent: true, maxLayers: 1 }); this.stageParameters = null; // "Private" members. this.bufferScale_ = this.config.BUFFER_SCALE; this.poseSensor_ = new PoseSensor(this.config); this.distorter_ = null; this.cardboardUI_ = null; this.dpdb_ = new Dpdb(this.config.DPDB_URL, this.onDeviceParamsUpdated_.bind(this)); this.deviceInfo_ = new DeviceInfo(this.dpdb_.getDeviceParams(), config.ADDITIONAL_VIEWERS); this.viewerSelector_ = new ViewerSelector(config.DEFAULT_VIEWER); this.viewerSelector_.onChange(this.onViewerChanged_.bind(this)); // Set the correct initial viewer. this.deviceInfo_.setViewer(this.viewerSelector_.getCurrentViewer()); if (!this.config.ROTATE_INSTRUCTIONS_DISABLED) { this.rotateInstructions_ = new RotateInstructions(); } if (Util.isIOS()) { // Listen for resize events to workaround this awful Safari bug. window.addEventListener('resize', this.onResize_.bind(this)); } }
javascript
{ "resource": "" }
q53732
ViewerSelector
train
function ViewerSelector(defaultViewer) { // Try to load the selected key from local storage. try { this.selectedKey = localStorage.getItem(VIEWER_KEY); } catch (error) { console.error('Failed to load viewer profile: %s', error); } //If none exists, or if localstorage is unavailable, use the default key. if (!this.selectedKey) { this.selectedKey = defaultViewer || DEFAULT_VIEWER; } this.dialog = this.createDialog_(DeviceInfo.Viewers); this.root = null; this.onChangeCallbacks_ = []; }
javascript
{ "resource": "" }
q53733
ComplementaryFilter
train
function ComplementaryFilter(kFilter, isDebug) { this.kFilter = kFilter; this.isDebug = isDebug; // Raw sensor measurements. this.currentAccelMeasurement = new SensorSample(); this.currentGyroMeasurement = new SensorSample(); this.previousGyroMeasurement = new SensorSample(); // Set default look direction to be in the correct direction. if (Util.isIOS()) { this.filterQ = new MathUtil.Quaternion(-1, 0, 0, 1); } else { this.filterQ = new MathUtil.Quaternion(1, 0, 0, 1); } this.previousFilterQ = new MathUtil.Quaternion(); this.previousFilterQ.copy(this.filterQ); // Orientation based on the accelerometer. this.accelQ = new MathUtil.Quaternion(); // Whether or not the orientation has been initialized. this.isOrientationInitialized = false; // Running estimate of gravity based on the current orientation. this.estimatedGravity = new MathUtil.Vector3(); // Measured gravity based on accelerometer. this.measuredGravity = new MathUtil.Vector3(); // Debug only quaternion of gyro-based orientation. this.gyroIntegralQ = new MathUtil.Quaternion(); }
javascript
{ "resource": "" }
q53734
addInstallation
train
async function addInstallation (installations, name, instPath) { var fileExists = await exists(instPath); if (fileExists) { Object.keys(ALIASES).some(alias => { var { nameRe, cmd, macOpenCmdTemplate, path } = ALIASES[alias]; if (nameRe.test(name)) { installations[alias] = { path: path || instPath, cmd, macOpenCmdTemplate }; return true; } return false; }); } }
javascript
{ "resource": "" }
q53735
setClass
train
function setClass(dom, cls, on) { if (on) dom.classList.add(cls) else dom.classList.remove(cls) }
javascript
{ "resource": "" }
q53736
selectionIsInverted
train
function selectionIsInverted(selection) { if (selection.anchorNode == selection.focusNode) return selection.anchorOffset > selection.focusOffset return selection.anchorNode.compareDocumentPosition(selection.focusNode) == Node.DOCUMENT_POSITION_FOLLOWING }
javascript
{ "resource": "" }
q53737
Select
train
function Select(el, options) { _classCallCheck(this, Select); // Don't init if browser default version var _this16 = _possibleConstructorReturn(this, (Select.__proto__ || Object.getPrototypeOf(Select)).call(this, Select, el, options)); if (_this16.$el.hasClass('browser-default')) { return _possibleConstructorReturn(_this16); } _this16.el.M_Select = _this16; /** * Options for the select * @member Select#options */ _this16.options = $.extend({}, Select.defaults, options); _this16.isMultiple = _this16.$el.prop('multiple'); // Setup _this16.el.tabIndex = -1; _this16._keysSelected = {}; _this16._valueDict = {}; // Maps key to original and generated option element. _this16._setupDropdown(); _this16._setupEventHandlers(); return _this16; }
javascript
{ "resource": "" }
q53738
vPaneController
train
function vPaneController ($scope) { var ctrl = this; ctrl.isExpanded = function isExpanded () { return $scope.isExpanded; }; ctrl.toggle = function toggle () { if (!$scope.isAnimating && !$scope.isDisabled) { $scope.accordionCtrl.toggle($scope); } }; ctrl.expand = function expand () { if (!$scope.isAnimating && !$scope.isDisabled) { $scope.accordionCtrl.expand($scope); } }; ctrl.collapse = function collapse () { if (!$scope.isAnimating && !$scope.isDisabled) { $scope.accordionCtrl.collapse($scope); } }; ctrl.focusPane = function focusPane () { $scope.isFocused = true; }; ctrl.blurPane = function blurPane () { $scope.isFocused = false; }; $scope.internalControl = { toggle: ctrl.toggle, expand: ctrl.expand, collapse: ctrl.collapse, isExpanded: ctrl.isExpanded }; }
javascript
{ "resource": "" }
q53739
maxDurationMsPerTimelinePx
train
function maxDurationMsPerTimelinePx(earliestTimestamp) { const durationMsLowerBound = minDurationMsPerTimelinePx(); const durationMsUpperBound = moment.duration(3, 'days').asMilliseconds(); const durationMs = availableTimelineDurationMs(earliestTimestamp) / 400.0; return clamp(durationMs, durationMsLowerBound, durationMsUpperBound); }
javascript
{ "resource": "" }
q53740
isSubComponent
train
function isSubComponent(resource) { const [dir, module] = resource.split('/').filter(n => n !== '.'); return dir !== module; }
javascript
{ "resource": "" }
q53741
ENS
train
function ENS (provider, address, Web3js) { if (Web3js !== undefined) { Web3 = Web3js; } if (!!/^0\./.exec(Web3.version || (new Web3(provider)).version.api)) { return utils.construct(ENS_0, [provider, address]); } else { return utils.construct(ENS_1, [provider, address]); } }
javascript
{ "resource": "" }
q53742
initJasmineWd
train
function initJasmineWd(scheduler, webdriver) { if (jasmine.JasmineWdInitialized) { throw Error('JasmineWd already initialized when init() was called'); } jasmine.JasmineWdInitialized = true; // Pull information from webdriver instance if (webdriver) { WebElement = webdriver.WebElement || WebElement; idleEventName = ( webdriver.promise && webdriver.promise.ControlFlow && webdriver.promise.ControlFlow.EventType && webdriver.promise.ControlFlow.EventType.IDLE ) || idleEventname; } // Default to mock scheduler if (!scheduler) { scheduler = { execute: function(fn) { return Promise.resolve().then(fn); } }; } // Figure out how we're getting new promises var newPromise; if (typeof scheduler.promise == 'function') { newPromise = scheduler.promise.bind(scheduler); } else if (webdriver && webdriver.promise && webdriver.promise.ControlFlow && (scheduler instanceof webdriver.promise.ControlFlow) && (webdriver.promise.USE_PROMISE_MANAGER !== false)) { newPromise = function(resolver) { return new webdriver.promise.Promise(resolver, scheduler); }; } else { newPromise = function(resolver) { return new Promise(resolver); }; } // Wrap functions global.it = wrapInScheduler(scheduler, newPromise, global.it, 'it'); global.fit = wrapInScheduler(scheduler, newPromise, global.fit, 'fit'); global.beforeEach = wrapInScheduler(scheduler, newPromise, global.beforeEach, 'beforeEach'); global.afterEach = wrapInScheduler(scheduler, newPromise, global.afterEach, 'afterEach'); global.beforeAll = wrapInScheduler(scheduler, newPromise, global.beforeAll, 'beforeAll'); global.afterAll = wrapInScheduler(scheduler, newPromise, global.afterAll, 'afterAll'); // Reset API if (scheduler.reset) { // On timeout, the flow should be reset. This will prevent webdriver tasks // from overflowing into the next test and causing it to fail or timeout // as well. This is done in the reporter instead of an afterEach block // to ensure that it runs after any afterEach() blocks with webdriver tasks // get to complete first. jasmine.getEnv().addReporter(new OnTimeoutReporter(function() { console.warn('A Jasmine spec timed out. Resetting the WebDriver Control Flow.'); scheduler.reset(); })); } }
javascript
{ "resource": "" }
q53743
compareDone
train
function compareDone(pass) { var message = ''; if (!pass) { if (!result.message) { args.unshift(expectation.isNot); args.unshift(name); message = expectation.util.buildFailureMessage.apply(null, args); } else { if (Object.prototype.toString.apply(result.message) === '[object Function]') { message = result.message(expectation.isNot); } else { message = result.message; } } } if (expected.length == 1) { expected = expected[0]; } var res = { matcherName: name, passed: pass, message: message, actual: actual, expected: expected, error: matchError }; expectation.addExpectationResult(pass, res); }
javascript
{ "resource": "" }
q53744
train
function() { var w = 0; // IE if (typeof( window.innerWidth ) != 'number') { if (!(document.documentElement.clientWidth === 0)) { // strict mode w = document.documentElement.clientWidth; } else { // quirks mode w = document.body.clientWidth; } } else { // w3c w = window.innerWidth; } return w; }
javascript
{ "resource": "" }
q53745
train
function(elm) { if (elm.length === undefined) { addToStack(elm); } else { for (var i = 0; i < elm.length; i++) { addToStack(elm[i]); } } }
javascript
{ "resource": "" }
q53746
train
function(elm) { var brkpt = elm['breakpoint']; var entr = elm['enter'] || undefined; // add function to stack mediaListeners.push(elm); // add corresponding entry to mediaInit mediaInit.push(false); if (testForCurr(brkpt)) { if (entr !== undefined) { entr.call(null, {entering : curr, exiting : prev}); } mediaInit[(mediaListeners.length - 1)] = true; } }
javascript
{ "resource": "" }
q53747
train
function() { var enterArray = []; var exitArray = []; for (var i = 0; i < mediaListeners.length; i++) { var brkpt = mediaListeners[i]['breakpoint']; var entr = mediaListeners[i]['enter'] || undefined; var exit = mediaListeners[i]['exit'] || undefined; if (brkpt === '*') { if (entr !== undefined) { enterArray.push(entr); } if (exit !== undefined) { exitArray.push(exit); } } else if (testForCurr(brkpt)) { if (entr !== undefined && !mediaInit[i]) { enterArray.push(entr); } mediaInit[i] = true; } else { if (exit !== undefined && mediaInit[i]) { exitArray.push(exit); } mediaInit[i] = false; } } var eventObject = { entering : curr, exiting : prev }; // loop through exit functions to call for (var j = 0; j < exitArray.length; j++) { exitArray[j].call(null, eventObject); } // then loop through enter functions to call for (var k = 0; k < enterArray.length; k++) { enterArray[k].call(null, eventObject); } }
javascript
{ "resource": "" }
q53748
train
function(width) { var foundBrkpt = false; // look for existing breakpoint based on width for (var i = 0; i < mediaBreakpoints.length; i++) { // if registered breakpoint found, break out of loop if (width >= mediaBreakpoints[i]['enter'] && width <= mediaBreakpoints[i]['exit']) { foundBrkpt = true; break; } } // if breakpoint is found and it's not the current one if (foundBrkpt && curr !== mediaBreakpoints[i]['label']) { prev = curr; curr = mediaBreakpoints[i]['label']; // run the loop cycleThrough(); // or if no breakpoint applies } else if (!foundBrkpt && curr !== '') { curr = ''; // run the loop cycleThrough(); } }
javascript
{ "resource": "" }
q53749
train
function() { // get current width var w = winWidth(); // if there is a change speed up the timer and fire the returnBreakpoint function if (w !== resizeW) { resizeTmrSpd = resizeTmrFast; returnBreakpoint(w); // otherwise keep on keepin' on } else { resizeTmrSpd = resizeTmrSlow; } resizeW = w; // calls itself on a setTimeout setTimeout(checkResize, resizeTmrSpd); }
javascript
{ "resource": "" }
q53750
isNotAPattern
train
function isNotAPattern(pattern) { let set = new Minimatch(pattern).set; if (set.length > 1) { return false; } for (let j = 0; j < set[0].length; j++) { if (typeof set[0][j] !== 'string') { return false; } } return true; }
javascript
{ "resource": "" }
q53751
Deckgrid
train
function Deckgrid (scope, element) { var self = this, watcher, mql; this.$$elem = element; this.$$watchers = []; this.$$scope = scope; this.$$scope.columns = []; // // The layout configuration will be parsed from // the pseudo "before element." There you have to save all // the column configurations. // this.$$scope.layout = this.$$getLayout(); this.$$createColumns(); // // Register model change. // watcher = this.$$scope.$watchCollection('model', this.$$onModelChange.bind(this)); this.$$watchers.push(watcher); // // Register media query change events. // angular.forEach(self.$$getMediaQueries(), function onIteration (rule) { var handler = self.$$onMediaQueryChange.bind(self); function onDestroy () { rule.removeListener(handler); } rule.addListener(handler); self.$$watchers.push(onDestroy); }); mql = $window.matchMedia('(orientation: portrait)'); mql.addListener(self.$$onMediaQueryChange.bind(self)); }
javascript
{ "resource": "" }
q53752
buildRequiredAssets
train
function buildRequiredAssets(self, context) { var paths = context.__requiredPaths__.concat([ self.pathname ]), assets = resolveDependencies(self, paths), stubs = resolveDependencies(self, context.__stubbedAssets__); if (stubs.length > 0) { // exclude stubbed assets if any assets = _.filter(assets, function (path) { return stubs.indexOf(path) === -1; }); } prop(self, '__requiredAssets__', assets); }
javascript
{ "resource": "" }
q53753
computeDependencyDigest
train
function computeDependencyDigest(self) { return _.reduce(self.requiredAssets, function (digest, asset) { return digest.update(asset.digest); }, self.environment.digest).digest('hex'); }
javascript
{ "resource": "" }
q53754
sassError
train
function sassError(ctx /*, options*/) { if (ctx.line && ctx.message) { // libsass 3.x error object return new Error('Line ' + ctx.line + ': ' + ctx.message); } if (typeof ctx === 'string') { // libsass error string format: path:line: error: message var error = _.zipObject( [ 'path', 'line', 'level', 'message' ], ctx.split(':', 4).map(function (str) { return str.trim(); }) ); if (error.line && error.level && error.message) { return new Error('Line ' + error.line + ': ' + error.message); } } return new Error(ctx); }
javascript
{ "resource": "" }
q53755
importArgumentRelativeToSearchPaths
train
function importArgumentRelativeToSearchPaths(importer, importArgument, searchPaths) { var importAbsolutePath = path.resolve(path.dirname(importer), importArgument); var importSearchPath = _.find(searchPaths, function (path) { return importAbsolutePath.indexOf(path) === 0; }); if (importSearchPath) { return path.relative(importSearchPath, importAbsolutePath); } }
javascript
{ "resource": "" }
q53756
flattenDepth
train
function flattenDepth (array, depth) { if (!Array.isArray(array)) { throw new TypeError('Expected value to be an array') } return flattenFromDepth(array, depth) }
javascript
{ "resource": "" }
q53757
flattenDown
train
function flattenDown (array, result) { for (var i = 0; i < array.length; i++) { var value = array[i] if (Array.isArray(value)) { flattenDown(value, result) } else { result.push(value) } } return result }
javascript
{ "resource": "" }
q53758
flattenDownDepth
train
function flattenDownDepth (array, result, depth) { depth-- for (var i = 0; i < array.length; i++) { var value = array[i] if (depth > -1 && Array.isArray(value)) { flattenDownDepth(value, result, depth) } else { result.push(value) } } return result }
javascript
{ "resource": "" }
q53759
matches_filter
train
function matches_filter(filters, logicalPath, filename) { if (filters.length === 0) { return true; } return _.some(filters, function (filter) { if (_.isRegExp(filter)) { return filter.test(logicalPath); } if (_.isFunction(filter)) { return filter(logicalPath, filename); } // prepare string to become RegExp. // mimics shell's globbing filter = filter.toString().replace(/\*\*|\*|\?|\\.|\./g, function (m) { if (m[0] === '*') { return m === '**' ? '.+?' : '[^/]+?'; } if (m[0] === '?') { return '[^/]?'; } if (m[0] === '.') { return '\\.'; } // handle `\\.` part return m; }); // prepare RegExp filter = new RegExp('^' + filter + '$'); return filter.test(logicalPath); }); }
javascript
{ "resource": "" }
q53760
logical_path_for_filename
train
function logical_path_for_filename(self, filename, filters) { var logical_path = self.attributesFor(filename).logicalPath; if (matches_filter(filters, logical_path, filename)) { return logical_path; } // If filename is an index file, retest with alias if (path.basename(filename).split('.').shift() === 'index') { logical_path = logical_path.replace(/\/index\./, '.'); if (matches_filter(filters, logical_path, filename)) { return logical_path; } } }
javascript
{ "resource": "" }
q53761
rewrite_extension
train
function rewrite_extension(source, ext) { var source_ext = path.extname(source); return (source_ext === ext) ? source : (source + ext); }
javascript
{ "resource": "" }
q53762
configuration
train
function configuration(self, name) { if (!self.__configurations__[name]) { throw new Error('Unknown configuration: ' + name); } return self.__configurations__[name]; }
javascript
{ "resource": "" }
q53763
stub_getter
train
function stub_getter(name) { getter(Asset.prototype, name, function () { // this should never happen, as Asset is an abstract class and not // supposed to be used directly. subclasses must override this getters throw new Error(this.constructor.name + '#' + name + ' getter is not implemented.'); }); }
javascript
{ "resource": "" }
q53764
end
train
function end(res, code) { if (code >= 400) { // check res object contains connect/express request and next structure if (res.req && res.req.next) { var error = new Error(http.STATUS_CODES[code]); error.status = code; return res.req.next(error); } // write human-friendly error message res.writeHead(code); res.end('[' + code + '] ' + http.STATUS_CODES[code]); return; } // just end with no body for 304 responses and such res.writeHead(code); res.end(); }
javascript
{ "resource": "" }
q53765
log_event
train
function log_event(req, code, message, elapsed) { return { code: code, message: message, elapsed: elapsed, request: req, url: req.originalUrl || req.url, method: req.method, headers: req.headers, httpVersion: req.httpVersion, remoteAddress: req.connection.remoteAddress }; }
javascript
{ "resource": "" }
q53766
getModuleVersionFromConfig
train
function getModuleVersionFromConfig(config) { if (config.moduleVersion === undefined && config.nodePackageName == CORDOVA) { // If no version is set, try to get the version from taco.json // This check is specific to the Cordova module if (utilities.fileExistsSync(path.join(config.projectPath, 'taco.json'))) { var version = require(path.join(config.projectPath, 'taco.json'))['cordova-cli']; if (version) { console.log('Cordova version set to ' + version + ' based on the contents of taco.json'); return version; } } } return config.moduleVersion || process.env[makeDefaultEnvironmentVariable(config.nodePackageName)]; }
javascript
{ "resource": "" }
q53767
cacheModule
train
function cacheModule(config) { config = utilities.parseConfig(config); var moduleCache = utilities.getCachePath(); console.log('Module cache at ' + moduleCache); var version = getModuleVersionFromConfig(config); var pkgStr = config.nodePackageName + (version ? '@' + version : ''); return utilities.getVersionForNpmPackage(pkgStr).then(function (versionString) { // Install correct cordova version if not available var packagePath = path.join(moduleCache, config.nodePackageName || CORDOVA); var versionPath = path.join(packagePath, version ? version : versionString); var targetModulePath = path.join(versionPath, 'node_modules', config.nodePackageName) if (!utilities.fileExistsSync(targetModulePath)) { // Fix: Check module is there not just root path if (!utilities.fileExistsSync(packagePath)) { fs.mkdirSync(packagePath); } if (!utilities.fileExistsSync(versionPath)) { fs.mkdirSync(versionPath); fs.mkdirSync(path.join(versionPath, 'node_modules')); // node_modules being present ensures correct install loc } console.log('Installing ' + pkgStr + ' to ' + versionPath + '. (This may take a few minutes.)'); var cmd = 'npm install --force ' + pkgStr + ' 2>&1'; return exec(cmd, { cwd: versionPath }) .then(utilities.handleExecReturn) .then(function () { return { version: version, path: targetModulePath }; }); } else { console.log(pkgStr + ' already installed.'); return Q({ version: version, path: targetModulePath }); } }); }
javascript
{ "resource": "" }
q53768
loadModule
train
function loadModule(modulePath) { // Setup environment if (loadedModule === undefined || loadedModulePath != modulePath) { loadedModule = require(modulePath); loadedModulePath = modulePath; return Q(loadedModule); } else { return Q(loadedModule); } }
javascript
{ "resource": "" }
q53769
getCallArgs
train
function getCallArgs(platforms, args, cordovaVersion) { // Processes single platform string (or array of length 1) and an array of args or an object of args per platform args = args || []; if (typeof (platforms) == 'string') { platforms = [platforms]; } // If only one platform is specified, check if the args is an object and use the args for this platform if so var options = args; if (platforms.length == 1 && !(args instanceof Array)) { options = args[platforms[0]]; } // 5.4.0 changes the way arguments are passed to build. Rather than just having an array // of options, it needs to be an object with an "argv" member for the arguments. // A change was added in 6.0.0 that required the new format to be more complete. // Workaround for now is to use the old way that 6.0.0 has a fallback for. if (semver.valid(cordovaVersion) && semver.gte(cordovaVersion, '5.4.0') && semver.lt(cordovaVersion, '6.0.0')) { return { platforms: platforms, options: { argv: options } }; } else { return { platforms: platforms, options: options }; } }
javascript
{ "resource": "" }
q53770
isCompatibleNpmPackage
train
function isCompatibleNpmPackage(pkgName) { if (pkgName !== 'cordova' && pkgName.indexOf('cordova@') !== 0) { return Q(NodeCompatibilityResult.Compatible); } // Get the version of npm and the version of cordova requested. If the // cordova version <= 5.3.3, and the Node version is 5.0.0, the build // is going to fail, but silently, so we need to be loud now. return getVersionForNpmPackage(pkgName).then(function (cordovaVersion) { if (!semver.valid(cordovaVersion)) { // Assume true, since we don't know what version this is and the npm install will probably fail anyway return Q(NodeCompatibilityResult.Compatible); } var nodeVersion = process.version; if (!semver.valid(nodeVersion)) { return Q(NodeCompatibilityResult.Compatible); } if (semver.lt(cordovaVersion, '5.4.0') && semver.gte(nodeVersion, '5.0.0')) { return Q(NodeCompatibilityResult.IncompatibleVersion5); } else if (process.platform == 'darwin' && semver.lt(cordovaVersion, '5.3.3') && semver.gte(nodeVersion, '4.0.0')) { return Q(NodeCompatibilityResult.IncompatibleVersion4Ios); } else { return Q(NodeCompatibilityResult.Compatible); } }); }
javascript
{ "resource": "" }
q53771
applyExecutionBitFix
train
function applyExecutionBitFix(platforms) { // Only bother if we're on OSX and are after platform add for iOS itself (still need to run for other platforms) if (process.platform !== "darwin" && process.platform !== 'linux') { return Q(); } // Disable -E flag for non-OSX platforms var regex_flag = process.platform == 'darwin' ? '-E' : ''; // Generate the script to set execute bits for installed platforms var script = ""; platforms.forEach(function (platform) { var platformCordovaDir = "platforms/" + platform + "/cordova"; if (utilities.fileExistsSync(platformCordovaDir)) { script += "find " + regex_flag + " " + platformCordovaDir + " -type f -regex \"[^.(LICENSE)]*\" -exec chmod +x {} +\n"; } }); var hooksCordovaDir = "hooks"; if (utilities.fileExistsSync(hooksCordovaDir)) { script += "find " + regex_flag + " " + hooksCordovaDir + " -type f -exec chmod +x {} +\n"; } script += "find " + regex_flag + " . -name '*.sh' -type f -exec chmod +x {} +\n"; // Run script return exec(script); }
javascript
{ "resource": "" }
q53772
prepareProject
train
function prepareProject(cordovaPlatforms, args, /* optional */ projectPath) { if (typeof (cordovaPlatforms) == "string") { cordovaPlatforms = [cordovaPlatforms]; } if (!projectPath) { projectPath = defaultConfig.projectPath; } var appendedVersion = cache.getModuleVersionFromConfig(defaultConfig); if (appendedVersion) { appendedVersion = '@' + appendedVersion; } else { appendedVersion = ''; } return utilities.isCompatibleNpmPackage(defaultConfig.nodePackageName + appendedVersion).then(function (compatibilityResult) { switch (compatibilityResult) { case utilities.NodeCompatibilityResult.IncompatibleVersion4Ios: throw new Error('This Cordova version does not support Node.js 4.0.0 for iOS builds. Either downgrade to an earlier version of Node.js or move to Cordova 5.3.3 or later. See http://go.microsoft.com/fwlink/?LinkID=618471'); case utilities.NodeCompatibilityResult.IncompatibleVersion5: throw new Error('This Cordova version does not support Node.js 5.0.0 or later. Either downgrade to an earlier version of Node.js or move to Cordova 5.4.0 or later. See http://go.microsoft.com/fwlink/?LinkID=618471'); } return setupCordova(); }).then(function (cordova) { return addSupportPluginIfRequested(cordova, defaultConfig); }).then(function (cordova) { // Add platforms if not done already var promise = _addPlatformsToProject(cordovaPlatforms, projectPath, cordova); //Build each platform with args in args object cordovaPlatforms.forEach(function (platform) { promise = promise.then(function () { // Build app with platform specific args if specified var callArgs = utilities.getCallArgs(platform, args); var argsString = _getArgsString(callArgs.options); console.log('Queueing prepare for platform ' + platform + ' w/options: ' + argsString); return cordova.raw.prepare(callArgs); }); }); return promise; }); }
javascript
{ "resource": "" }
q53773
buildProject
train
function buildProject(cordovaPlatforms, args, /* optional */ projectPath) { if (typeof (cordovaPlatforms) == 'string') { cordovaPlatforms = [cordovaPlatforms]; } if (!projectPath) { projectPath = defaultConfig.projectPath; } var appendedVersion = cache.getModuleVersionFromConfig(defaultConfig); if (appendedVersion) { appendedVersion = '@' + appendedVersion; } else { appendedVersion = ''; } var cordovaVersion = defaultConfig.moduleVersion; return utilities.isCompatibleNpmPackage(defaultConfig.nodePackageName + appendedVersion).then(function (compatibilityResult) { switch (compatibilityResult) { case utilities.NodeCompatibilityResult.IncompatibleVersion4Ios: throw new Error('This Cordova version does not support Node.js 4.0.0 for iOS builds. Either downgrade to an earlier version of Node.js or move to Cordova 5.3.3 or later. See http://go.microsoft.com/fwlink/?LinkID=618471'); case utilities.NodeCompatibilityResult.IncompatibleVersion5: throw new Error('This Cordova version does not support Node.js 5.0.0 or later. Either downgrade to an earlier version of Node.js or move to Cordova 5.4.0 or later. See http://go.microsoft.com/fwlink/?LinkID=618471'); } return utilities.getVersionForNpmPackage(defaultConfig.nodePackageName + appendedVersion); }).then(function (version) { cordovaVersion = version; return setupCordova(); }).then(function (cordova) { return applyExecutionBitFix(cordovaPlatforms).then(function () { return Q(cordova); }, function (err) { return Q(cordova); }); }).then(function (cordova) { return addSupportPluginIfRequested(cordova, defaultConfig); }).then(function (cordova) { // Add platforms if not done already var promise = _addPlatformsToProject(cordovaPlatforms, projectPath, cordova); //Build each platform with args in args object cordovaPlatforms.forEach(function (platform) { promise = promise.then(function () { // Build app with platform specific args if specified var callArgs = utilities.getCallArgs(platform, args, cordovaVersion); return ensureProjectXcode8Compatibility(projectPath, platform, callArgs); }).then(function() { var callArgs = utilities.getCallArgs(platform, args, cordovaVersion); var argsString = _getArgsString(callArgs.options); console.log('Queueing build for platform ' + platform + ' w/options: ' + argsString); return cordova.raw.build(callArgs); }); }); return promise; }); }
javascript
{ "resource": "" }
q53774
_addPlatformsToProject
train
function _addPlatformsToProject(cordovaPlatforms, projectPath, cordova) { var promise = Q(); cordovaPlatforms.forEach(function (platform) { if (!utilities.fileExistsSync(path.join(projectPath, 'platforms', platform))) { promise = promise.then(function () { return cordova.raw.platform('add', platform); }); } else { console.log('Platform ' + platform + ' already added.'); } }); return promise; }
javascript
{ "resource": "" }
q53775
packageProject
train
function packageProject(cordovaPlatforms, args, /* optional */ projectPath) { if (typeof (cordovaPlatforms) == 'string') { cordovaPlatforms = [cordovaPlatforms]; } if (!projectPath) { projectPath = defaultConfig.projectPath; } return setupCordova().then(function (cordova) { var promise = Q(cordova); cordovaPlatforms.forEach(function (platform) { if (platform == 'ios') { promise = promise.then(function () { return _createIpa(projectPath, args); }); } else { console.log('Platform ' + platform + ' does not require a separate package step.'); } }); return promise; }); }
javascript
{ "resource": "" }
q53776
_createIpa
train
function _createIpa(projectPath, args) { return utilities.getInstalledPlatformVersion(projectPath, 'ios').then(function (version) { if (semver.lt(version, '3.9.0')) { var deferred = Q.defer(); glob(projectPath + '/platforms/ios/build/device/*.app', function (err, matches) { if (err) { deferred.reject(err); } else { if (matches.length != 1) { console.warn('Skipping packaging. Expected one device .app - found ' + matches.length); } else { var cmdString = 'xcrun -sdk iphoneos PackageApplication \'' + matches[0] + '\' -o \'' + path.join(path.dirname(matches[0]), path.basename(matches[0], '.app')) + '.ipa\' '; // Add additional command line args passed var callArgs = utilities.getCallArgs('ios', args); callArgs.options.forEach(function (arg) { cmdString += ' ' + arg; }); console.log('Exec: ' + cmdString); return exec(cmdString) .then(utilities.handleExecReturn) .fail(function (err) { deferred.reject(err); }) .done(function () { deferred.resolve(); }); } } }); return deferred.promise; } else { console.log('Skipping packaging. Detected cordova-ios verison that auto-creates ipa.'); } }); }
javascript
{ "resource": "" }
q53777
Collection
train
function Collection(nameOrExisting, options) { if (nameOrExisting instanceof Mongo.Collection) { this._collection = nameOrExisting; } else { this._collection = new Mongo.Collection(nameOrExisting, options); } }
javascript
{ "resource": "" }
q53778
IntegrationType
train
function IntegrationType(required, optional = []) { //convert parameter string values to object this.required = required.map(transformProps); this.optional = optional.map(transformProps); }
javascript
{ "resource": "" }
q53779
train
function(filePaths, importRegexp, System) { var moduleNames = []; for (var filePath in filePaths) { if (filePaths.hasOwnProperty(filePath) && importRegexp.test(filePath)) { moduleNames.push(adapter.getModuleNameFromPath(filePath, System.baseURL, System)); } } return moduleNames; }
javascript
{ "resource": "" }
q53780
train
function(System, Promise, files, importRegexps, strictImportSequence) { if (strictImportSequence) { return adapter.sequentialImportFiles(System, Promise, files, importRegexps) } else { return adapter.parallelImportFiles(System, Promise, files, importRegexps) } }
javascript
{ "resource": "" }
q53781
train
function(karma, System, Promise) { // Fail fast if any of the dependencies are undefined if (!karma) { (console.error || console.log)('Error: Not setup properly. window.__karma__ is undefined'); return; } if (!System) { (console.error || console.log)('Error: Not setup properly. window.System is undefined'); return; } if (!Promise) { (console.error || console.log)('Error: Not setup properly. window.Promise is undefined'); return; } // Stop karma from starting automatically on load karma.loaded = function() { // Load SystemJS configuration from karma config // And update baseURL with '/base', where Karma serves files from if (karma.config.systemjs.config) { // SystemJS config is converted to a JSON string by the framework // https://github.com/rolaveric/karma-systemjs/issues/44 karma.config.systemjs.config = JSON.parse(karma.config.systemjs.config); karma.config.systemjs.config.baseURL = adapter.updateBaseURL(karma.config.systemjs.config.baseURL); System.config(karma.config.systemjs.config); // Exclude bundle configurations if useBundles option is not specified if (!karma.config.systemjs.useBundles) { System.bundles = []; } } else { System.config({baseURL: '/base/'}); } // Convert the 'importPatterns' into 'importRegexps' var importPatterns = karma.config.systemjs.importPatterns; var importRegexps = []; for (var x = 0; x < importPatterns.length; x++) { importRegexps.push(new RegExp(importPatterns[x])); } // Import each test suite using SystemJS var testSuitePromise; try { testSuitePromise = adapter.importFiles(System, Promise, karma.files, importRegexps, karma.config.systemjs.strictImportSequence); } catch (e) { karma.error(adapter.decorateErrorWithHints(e, System)); return; } // Once all imports are complete... testSuitePromise.then(function () { karma.start(); }, function (e) { karma.error(adapter.decorateErrorWithHints(e, System)); }); }; }
javascript
{ "resource": "" }
q53782
train
function(err, System) { err = String(err); // Look for common issues in the error message, and try to add hints to them switch (true) { // Some people use ".es6" instead of ".js" for ES6 code case /^Error loading ".*\.es6" at .*\.es6\.js/.test(err): return err + '\nHint: If you use ".es6" as an extension, ' + 'add this to your SystemJS paths config: {"*.es6": "*.es6"}'; case /^TypeError: Illegal module name "\/base\//.test(err): return err + '\nHint: Is the working directory different when you run karma?' + '\nYou may need to change the baseURL of your SystemJS config inside your karma config.' + '\nIt\'s currently checking "' + System.baseURL + '"' + '\nNote: "/base/" is where karma serves files from.'; } return err; }
javascript
{ "resource": "" }
q53783
Integration
train
function Integration(options) { if (options && options.addIntegration) { // plugin return options.addIntegration(Integration); } this.debug = debug('analytics:integration:' + slug(name)); var clonedOpts = {}; extend(true, clonedOpts, options); // deep clone options this.options = defaults(clonedOpts || {}, this.defaults); this._queue = []; this.once('ready', bind(this, this.flush)); Integration.emit('construct', this); this.ready = bind(this, this.ready); this._wrapInitialize(); this._wrapPage(); this._wrapTrack(); }
javascript
{ "resource": "" }
q53784
isMixed
train
function isMixed(item) { if (!is.object(item)) return false; if (!is.string(item.key)) return false; if (!has.call(item, 'value')) return false; return true; }
javascript
{ "resource": "" }
q53785
toggleCss
train
function toggleCss() { if (!cssOpen) { exampleCss.classList.remove(hiddenClass); showCssBtn.innerHTML = hideText; cssOpen = true; } else { exampleCss.classList.add(hiddenClass); exampleScss.scrollIntoView(); showCssBtn.innerHTML = showText; cssOpen = false; } }
javascript
{ "resource": "" }
q53786
getSnowflakeIdFromUint8Array
train
function getSnowflakeIdFromUint8Array(Uint8Arr) { // packaged lib uses base64 not base64URL, so swap the different chars return base64js.fromByteArray(Uint8Arr).substring(0, 11).replace(/\+/g, '-').replace(/\//g, '_'); }
javascript
{ "resource": "" }
q53787
extractBinaryFields
train
function extractBinaryFields(target, spec, data) { var offset = 0; for (var x = 0; x < spec.length; x++) { var item = spec[x]; if (item.label) { if (item.type === 'string') { var bytes = new DataView(data.buffer, offset, item.size); var str = textDecoder.decode(bytes); target[item.label] = str.replace(/\0/g, ''); } else { target[item.label] = data['get' + item.type + (item.size * 8)](offset); } } offset += item.size; } return offset; }
javascript
{ "resource": "" }
q53788
parseBinaryMessage
train
function parseBinaryMessage(data, knownComputations) { var msg = {}; var header = new DataView(data, 0, binaryHeaderLength); var version = header.getUint8(0); extractBinaryFields(msg, binaryHeaderFormats[version], header); var type = binaryMessageTypes[msg.type]; if (type === undefined) { console.warn('Unknown binary message type ' + msg.type); return null; } msg.type = type; var bigNumberRequested = false; if (typeof knownComputations[msg.channel] !== 'undefined' && knownComputations[msg.channel].params) { bigNumberRequested = knownComputations[msg.channel].params.bigNumber; } var compressed = msg.flags & (1 << 0); var json = msg.flags & (1 << 1); if (compressed) { // Decompress the message body if necessary. data = new DataView(pako.ungzip(new Uint8Array(data, binaryHeaderLength)).buffer); } else { data = new DataView(data, binaryHeaderLength); } if (json) { var decoded = textDecoder.decode(data); var body = JSON.parse(decoded); Object.keys(body).forEach(function (k) { msg[k] = body[k]; }); return msg; } switch (msg['type']) { case 'data': return parseBinaryDataMessage(msg, data, bigNumberRequested); default: console.warn('Unsupported binary "' + msg['type'] + '" message'); return null; } }
javascript
{ "resource": "" }
q53789
parseBinaryDataMessage
train
function parseBinaryDataMessage(msg, data, bigNumberRequested) { var offset = extractBinaryFields(msg, binaryDataMessageFormats[msg['version']], data); msg.logicalTimestampMs = (msg.timestampMs1 * hiMult) + msg.timestampMs2; delete msg.timestampMs1; delete msg.timestampMs2; if (typeof msg.maxDelayMs1 !== 'undefined' && typeof msg.maxDelayMs2 !== 'undefined') { msg.maxDelayMs = (msg.maxDelayMs1 * hiMult) + msg.maxDelayMs2; delete msg.maxDelayMs1; delete msg.maxDelayMs2; } var values = []; msg.data = values; for (var dataPointCount = 0; dataPointCount < msg.count; dataPointCount++) { var type = data.getUint8(offset); offset++; var tsidBytes = []; for (var tsidByteIndex = 0; tsidByteIndex < 8; tsidByteIndex++) { tsidBytes.push(data.getUint8(offset)); offset++; } var tsId = getSnowflakeIdFromUint8Array(tsidBytes); var val = null; if (type === 0) { // NULL_TYPE, nothing to do } else if (type === 1) { // LONG_TYPE // get MSB for twos complement to determine sign var isNegative = data.getUint32(offset) >>> 31 > 0; if (isNegative) { // twos complement manual handling, because we cannot do Int64. // must do >>> 0 to prevent bit flips from turning into signed integers. val = (new BigNumber(hiMult) .times(~data.getUint32(offset) >>> 0) .plus(~data.getUint32(offset + 4) >>> 0) .plus(1) .times(-1)); } else { val = (new BigNumber(data.getUint32(offset)) .times(hiMult) .plus(data.getUint32(offset + 4))); } if (!bigNumberRequested) { val = val.toNumber(); } } else if (type === 2) { // DOUBLE_TYPE val = data.getFloat64(offset); if (bigNumberRequested) { val = new BigNumber(val); } } else if (type === 3) { // INT_TYPE val = data.getUint32(offset + 4); if (bigNumberRequested) { val = new BigNumber(val); } } offset += 8; values.push({tsId: tsId, value: val}); } delete msg.count; return msg; }
javascript
{ "resource": "" }
q53790
train
function (msg, knownComputations) { if (msg.data && msg.data.byteLength) { // The presence of byteLength indicates data is an ArrayBuffer from a WebSocket data frame. return parseBinaryMessage(msg.data, knownComputations); } else if (msg.type) { // Otherwise it's JSON in a WebSocket text frame. return JSON.parse(msg.data); } else { console.warn('Unrecognized websocket message.'); return null; } }
javascript
{ "resource": "" }
q53791
SignalFxClient
train
function SignalFxClient(apiToken, options) { var _this = this; this.apiToken = apiToken; var params = options || {}; this.ingestEndpoint = params.ingestEndpoint || conf.DEFAULT_INGEST_ENDPOINT; this.timeout = params.timeout || conf.DEFAULT_TIMEOUT; this.batchSize = Math.max(1, (params.batchSize ? params.batchSize : conf.DEFAULT_BATCH_SIZE)); this.userAgents = params.userAgents || null; this.globalDimensions = params.dimensions || {}; this.enableAmazonUniqueId = params.enableAmazonUniqueId || false; this.proxy = params.proxy || null; this.rawData = []; this.rawEvents = []; this.queue = []; this.loadAWSUniqueId = new Promise(function (resolve) { if (!_this.enableAmazonUniqueId) { resolve(); return; } else { if (_this.AWSUniqueId !== undefined && _this.AWSUniqueId !== '') { resolve(); return; } } _this._retrieveAWSUniqueId(function (isSuccess, AWSUniqueId) { if (isSuccess) { _this.AWSUniqueId = AWSUniqueId; _this.globalDimensions[_this.AWSUniqueId_DIMENTION_NAME] = AWSUniqueId; } else { _this.enableAmazonUniqueId = false; _this.AWSUniqueId = ''; delete _this.globalDimensions[_this.AWSUniqueId_DIMENTION_NAME]; } resolve(); }); }); }
javascript
{ "resource": "" }
q53792
Datum
train
function Datum(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q53793
Dimension
train
function Dimension(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q53794
DataPoint
train
function DataPoint(properties) { this.dimensions = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q53795
DataPointUploadMessage
train
function DataPointUploadMessage(properties) { this.datapoints = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q53796
PointValue
train
function PointValue(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q53797
Property
train
function Property(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q53798
PropertyValue
train
function PropertyValue(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q53799
Event
train
function Event(properties) { this.dimensions = []; this.properties = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }