_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q24400
Translation
train
function Translation(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": "" }
q24401
extractMDNProperties
train
function extractMDNProperties(mdnEntry) { if (mdnEntry.status === 'standard') { return { syntax: mdnEntry.syntax } } return { status: abbreviateStatus(mdnEntry.status), syntax: mdnEntry.syntax } }
javascript
{ "resource": "" }
q24402
convertEntry
train
function convertEntry(entry) { entry.description = entry.desc delete entry.desc if (entry.values) { entry.values.forEach(v => { v.description = v.desc delete v.desc if (v.browsers) { if (v.browsers === 'all') { delete v.browsers } else { v.browsers = entry.browsers.split(',') if (v.browsers.length === 1 && v.browsers[0] === "all") { delete v.browsers } } } }) } if (entry.browsers) { if (entry.browsers === 'all') { delete entry.browsers } else { entry.browsers = entry.browsers.split(',') } } if (entry.restriction) { entry.restrictions = entry.restriction.split(',').map((s) => { return s.trim(); }); if (entry.restrictions.length === 1 && entry.restrictions[0] === "none") { delete entry.restrictions } } else { delete entry.restrictions } delete entry.restriction if (entry.status) { entry.status = expandEntryStatus(entry.status) } }
javascript
{ "resource": "" }
q24403
childByName
train
function childByName(node, name) { var childNodes = node.childNodes; for (var childKey in childNodes) { var child = childNodes[childKey]; if (child.nodeName === name) { return child; } } }
javascript
{ "resource": "" }
q24404
resolveVastAdTagURI
train
function resolveVastAdTagURI(vastAdTagUrl, originalUrl) { if (!originalUrl) { return vastAdTagUrl; } if (vastAdTagUrl.indexOf('//') === 0) { var _location = location, protocol = _location.protocol; return '' + protocol + vastAdTagUrl; } if (vastAdTagUrl.indexOf('://') === -1) { // Resolve relative URLs (mainly for unit testing) var baseURL = originalUrl.slice(0, originalUrl.lastIndexOf('/')); return baseURL + '/' + vastAdTagUrl; } return vastAdTagUrl; }
javascript
{ "resource": "" }
q24405
mergeWrapperAdData
train
function mergeWrapperAdData(unwrappedAd, wrapper) { unwrappedAd.errorURLTemplates = wrapper.errorURLTemplates.concat(unwrappedAd.errorURLTemplates); unwrappedAd.impressionURLTemplates = wrapper.impressionURLTemplates.concat(unwrappedAd.impressionURLTemplates); unwrappedAd.extensions = wrapper.extensions.concat(unwrappedAd.extensions); unwrappedAd.creatives.forEach(function (creative) { if (wrapper.trackingEvents && wrapper.trackingEvents[creative.type]) { for (var eventName in wrapper.trackingEvents[creative.type]) { var urls = wrapper.trackingEvents[creative.type][eventName]; if (!Array.isArray(creative.trackingEvents[eventName])) { creative.trackingEvents[eventName] = []; } creative.trackingEvents[eventName] = creative.trackingEvents[eventName].concat(urls); } } }); if (wrapper.videoClickTrackingURLTemplates && wrapper.videoClickTrackingURLTemplates.length) { unwrappedAd.creatives.forEach(function (creative) { if (creative.type === 'linear') { creative.videoClickTrackingURLTemplates = creative.videoClickTrackingURLTemplates.concat(wrapper.videoClickTrackingURLTemplates); } }); } if (wrapper.videoCustomClickURLTemplates && wrapper.videoCustomClickURLTemplates.length) { unwrappedAd.creatives.forEach(function (creative) { if (creative.type === 'linear') { creative.videoCustomClickURLTemplates = creative.videoCustomClickURLTemplates.concat(wrapper.videoCustomClickURLTemplates); } }); } // VAST 2.0 support - Use Wrapper/linear/clickThrough when Inline/Linear/clickThrough is null if (wrapper.videoClickThroughURLTemplate) { unwrappedAd.creatives.forEach(function (creative) { if (creative.type === 'linear' && (creative.videoClickThroughURLTemplate === null || typeof creative.videoClickThroughURLTemplate === 'undefined')) { creative.videoClickThroughURLTemplate = wrapper.videoClickThroughURLTemplate; } }); } }
javascript
{ "resource": "" }
q24406
parseCreativeNonLinear
train
function parseCreativeNonLinear(creativeElement, creativeAttributes) { var creative = new CreativeNonLinear(creativeAttributes); parserUtils.childrenByName(creativeElement, 'TrackingEvents').forEach(function (trackingEventsElement) { var eventName = void 0, trackingURLTemplate = void 0; parserUtils.childrenByName(trackingEventsElement, 'Tracking').forEach(function (trackingElement) { eventName = trackingElement.getAttribute('event'); trackingURLTemplate = parserUtils.parseNodeText(trackingElement); if (eventName && trackingURLTemplate) { if (!Array.isArray(creative.trackingEvents[eventName])) { creative.trackingEvents[eventName] = []; } creative.trackingEvents[eventName].push(trackingURLTemplate); } }); }); parserUtils.childrenByName(creativeElement, 'NonLinear').forEach(function (nonlinearResource) { var nonlinearAd = new NonLinearAd(); nonlinearAd.id = nonlinearResource.getAttribute('id') || null; nonlinearAd.width = nonlinearResource.getAttribute('width'); nonlinearAd.height = nonlinearResource.getAttribute('height'); nonlinearAd.expandedWidth = nonlinearResource.getAttribute('expandedWidth'); nonlinearAd.expandedHeight = nonlinearResource.getAttribute('expandedHeight'); nonlinearAd.scalable = parserUtils.parseBoolean(nonlinearResource.getAttribute('scalable')); nonlinearAd.maintainAspectRatio = parserUtils.parseBoolean(nonlinearResource.getAttribute('maintainAspectRatio')); nonlinearAd.minSuggestedDuration = parserUtils.parseDuration(nonlinearResource.getAttribute('minSuggestedDuration')); nonlinearAd.apiFramework = nonlinearResource.getAttribute('apiFramework'); parserUtils.childrenByName(nonlinearResource, 'HTMLResource').forEach(function (htmlElement) { nonlinearAd.type = htmlElement.getAttribute('creativeType') || 'text/html'; nonlinearAd.htmlResource = parserUtils.parseNodeText(htmlElement); }); parserUtils.childrenByName(nonlinearResource, 'IFrameResource').forEach(function (iframeElement) { nonlinearAd.type = iframeElement.getAttribute('creativeType') || 0; nonlinearAd.iframeResource = parserUtils.parseNodeText(iframeElement); }); parserUtils.childrenByName(nonlinearResource, 'StaticResource').forEach(function (staticElement) { nonlinearAd.type = staticElement.getAttribute('creativeType') || 0; nonlinearAd.staticResource = parserUtils.parseNodeText(staticElement); }); var adParamsElement = parserUtils.childByName(nonlinearResource, 'AdParameters'); if (adParamsElement) { nonlinearAd.adParameters = parserUtils.parseNodeText(adParamsElement); } nonlinearAd.nonlinearClickThroughURLTemplate = parserUtils.parseNodeText(parserUtils.childByName(nonlinearResource, 'NonLinearClickThrough')); parserUtils.childrenByName(nonlinearResource, 'NonLinearClickTracking').forEach(function (clickTrackingElement) { nonlinearAd.nonlinearClickTrackingURLTemplates.push(parserUtils.parseNodeText(clickTrackingElement)); }); creative.variations.push(nonlinearAd); }); return creative; }
javascript
{ "resource": "" }
q24407
parseInLine
train
function parseInLine(inLineElement) { var childNodes = inLineElement.childNodes; var ad = new Ad(); ad.id = inLineElement.getAttribute('id') || null; ad.sequence = inLineElement.getAttribute('sequence') || null; for (var nodeKey in childNodes) { var node = childNodes[nodeKey]; switch (node.nodeName) { case 'Error': ad.errorURLTemplates.push(parserUtils.parseNodeText(node)); break; case 'Impression': ad.impressionURLTemplates.push(parserUtils.parseNodeText(node)); break; case 'Creatives': parserUtils.childrenByName(node, 'Creative').forEach(function (creativeElement) { var creativeAttributes = { id: creativeElement.getAttribute('id') || null, adId: parseCreativeAdIdAttribute(creativeElement), sequence: creativeElement.getAttribute('sequence') || null, apiFramework: creativeElement.getAttribute('apiFramework') || null }; for (var creativeTypeElementKey in creativeElement.childNodes) { var creativeTypeElement = creativeElement.childNodes[creativeTypeElementKey]; var parsedCreative = void 0; switch (creativeTypeElement.nodeName) { case 'Linear': parsedCreative = parseCreativeLinear(creativeTypeElement, creativeAttributes); if (parsedCreative) { ad.creatives.push(parsedCreative); } break; case 'NonLinearAds': parsedCreative = parseCreativeNonLinear(creativeTypeElement, creativeAttributes); if (parsedCreative) { ad.creatives.push(parsedCreative); } break; case 'CompanionAds': parsedCreative = parseCreativeCompanion(creativeTypeElement, creativeAttributes); if (parsedCreative) { ad.creatives.push(parsedCreative); } break; } } }); break; case 'Extensions': parseExtensions(ad.extensions, parserUtils.childrenByName(node, 'Extension')); break; case 'AdSystem': ad.system = { value: parserUtils.parseNodeText(node), version: node.getAttribute('version') || null }; break; case 'AdTitle': ad.title = parserUtils.parseNodeText(node); break; case 'Description': ad.description = parserUtils.parseNodeText(node); break; case 'Advertiser': ad.advertiser = parserUtils.parseNodeText(node); break; case 'Pricing': ad.pricing = { value: parserUtils.parseNodeText(node), model: node.getAttribute('model') || null, currency: node.getAttribute('currency') || null }; break; case 'Survey': ad.survey = parserUtils.parseNodeText(node); break; } } return ad; }
javascript
{ "resource": "" }
q24408
parseWrapper
train
function parseWrapper(wrapperElement) { var ad = parseInLine(wrapperElement); var wrapperURLElement = parserUtils.childByName(wrapperElement, 'VASTAdTagURI'); if (wrapperURLElement) { ad.nextWrapperURL = parserUtils.parseNodeText(wrapperURLElement); } else { wrapperURLElement = parserUtils.childByName(wrapperElement, 'VASTAdTagURL'); if (wrapperURLElement) { ad.nextWrapperURL = parserUtils.parseNodeText(parserUtils.childByName(wrapperURLElement, 'URL')); } } ad.creatives.forEach(function (wrapperCreativeElement) { if (['linear', 'nonlinear'].indexOf(wrapperCreativeElement.type) !== -1) { // TrackingEvents Linear / NonLinear if (wrapperCreativeElement.trackingEvents) { if (!ad.trackingEvents) { ad.trackingEvents = {}; } if (!ad.trackingEvents[wrapperCreativeElement.type]) { ad.trackingEvents[wrapperCreativeElement.type] = {}; } var _loop = function _loop(eventName) { var urls = wrapperCreativeElement.trackingEvents[eventName]; if (!Array.isArray(ad.trackingEvents[wrapperCreativeElement.type][eventName])) { ad.trackingEvents[wrapperCreativeElement.type][eventName] = []; } urls.forEach(function (url) { ad.trackingEvents[wrapperCreativeElement.type][eventName].push(url); }); }; for (var eventName in wrapperCreativeElement.trackingEvents) { _loop(eventName); } } // ClickTracking if (wrapperCreativeElement.videoClickTrackingURLTemplates) { if (!Array.isArray(ad.videoClickTrackingURLTemplates)) { ad.videoClickTrackingURLTemplates = []; } // tmp property to save wrapper tracking URLs until they are merged wrapperCreativeElement.videoClickTrackingURLTemplates.forEach(function (item) { ad.videoClickTrackingURLTemplates.push(item); }); } // ClickThrough if (wrapperCreativeElement.videoClickThroughURLTemplate) { ad.videoClickThroughURLTemplate = wrapperCreativeElement.videoClickThroughURLTemplate; } // CustomClick if (wrapperCreativeElement.videoCustomClickURLTemplates) { if (!Array.isArray(ad.videoCustomClickURLTemplates)) { ad.videoCustomClickURLTemplates = []; } // tmp property to save wrapper tracking URLs until they are merged wrapperCreativeElement.videoCustomClickURLTemplates.forEach(function (item) { ad.videoCustomClickURLTemplates.push(item); }); } } }); if (ad.nextWrapperURL) { return ad; } }
javascript
{ "resource": "" }
q24409
VASTParser
train
function VASTParser() { classCallCheck(this, VASTParser); var _this = possibleConstructorReturn(this, (VASTParser.__proto__ || Object.getPrototypeOf(VASTParser)).call(this)); _this.remainingAds = []; _this.parentURLs = []; _this.errorURLTemplates = []; _this.rootErrorURLTemplates = []; _this.maxWrapperDepth = null; _this.URLTemplateFilters = []; _this.fetchingOptions = {}; return _this; }
javascript
{ "resource": "" }
q24410
VASTClient
train
function VASTClient(cappingFreeLunch, cappingMinimumTimeInterval, customStorage) { classCallCheck(this, VASTClient); this.cappingFreeLunch = cappingFreeLunch || 0; this.cappingMinimumTimeInterval = cappingMinimumTimeInterval || 0; this.defaultOptions = { withCredentials: false, timeout: 0 }; this.vastParser = new VASTParser(); this.storage = customStorage || new Storage(); // Init values if not already set if (this.lastSuccessfulAd === undefined) { this.lastSuccessfulAd = 0; } if (this.totalCalls === undefined) { this.totalCalls = 0; } if (this.totalCallsTimeout === undefined) { this.totalCallsTimeout = 0; } }
javascript
{ "resource": "" }
q24411
VASTTracker
train
function VASTTracker(client, ad, creative) { var variation = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; classCallCheck(this, VASTTracker); var _this = possibleConstructorReturn(this, (VASTTracker.__proto__ || Object.getPrototypeOf(VASTTracker)).call(this)); _this.ad = ad; _this.creative = creative; _this.variation = variation; _this.muted = false; _this.impressed = false; _this.skippable = false; _this.trackingEvents = {}; // We need to save the already triggered quartiles, in order to not trigger them again _this._alreadyTriggeredQuartiles = {}; // Tracker listeners should be notified with some events // no matter if there is a tracking URL or not _this.emitAlwaysEvents = ['creativeView', 'start', 'firstQuartile', 'midpoint', 'thirdQuartile', 'complete', 'resume', 'pause', 'rewind', 'skip', 'closeLinear', 'close']; // Duplicate the creative's trackingEvents property so we can alter it for (var eventName in _this.creative.trackingEvents) { var events$$1 = _this.creative.trackingEvents[eventName]; _this.trackingEvents[eventName] = events$$1.slice(0); } // Nonlinear and companion creatives provide some tracking information at a variation level // While linear creatives provided that at a creative level. That's why we need to // differentiate how we retrieve some tracking information. if (_this.creative instanceof CreativeLinear) { _this._initLinearTracking(); } else { _this._initVariationTracking(); } // If the tracker is associated with a client we add a listener to the start event // to update the lastSuccessfulAd property. if (client) { _this.on('start', function () { client.lastSuccessfulAd = Date.now(); }); } return _this; }
javascript
{ "resource": "" }
q24412
parseExtensions
train
function parseExtensions(collection, extensions) { extensions.forEach(extNode => { const ext = new AdExtension(); const extNodeAttrs = extNode.attributes; const childNodes = extNode.childNodes; if (extNode.attributes) { for (const extNodeAttrKey in extNodeAttrs) { const extNodeAttr = extNodeAttrs[extNodeAttrKey]; if (extNodeAttr.nodeName && extNodeAttr.nodeValue) { ext.attributes[extNodeAttr.nodeName] = extNodeAttr.nodeValue; } } } for (const childNodeKey in childNodes) { const childNode = childNodes[childNodeKey]; const txt = parserUtils.parseNodeText(childNode); // ignore comments / empty value if (childNode.nodeName !== '#comment' && txt !== '') { const extChild = new AdExtensionChild(); extChild.name = childNode.nodeName; extChild.value = txt; if (childNode.attributes) { const childNodeAttributes = childNode.attributes; for (const extChildNodeAttrKey in childNodeAttributes) { const extChildNodeAttr = childNodeAttributes[extChildNodeAttrKey]; extChild.attributes[extChildNodeAttr.nodeName] = extChildNodeAttr.nodeValue; } } ext.children.push(extChild); } } collection.push(ext); }); }
javascript
{ "resource": "" }
q24413
resolveURLTemplates
train
function resolveURLTemplates(URLTemplates, variables = {}, options = {}) { const URLs = []; // Encode String variables, when given if (variables['ASSETURI']) { variables['ASSETURI'] = encodeURIComponentRFC3986(variables['ASSETURI']); } if (variables['CONTENTPLAYHEAD']) { variables['CONTENTPLAYHEAD'] = encodeURIComponentRFC3986( variables['CONTENTPLAYHEAD'] ); } // Set default value for invalid ERRORCODE if ( variables['ERRORCODE'] && !options.isCustomCode && !/^[0-9]{3}$/.test(variables['ERRORCODE']) ) { variables['ERRORCODE'] = 900; } // Calc random/time based macros variables['CACHEBUSTING'] = leftpad( Math.round(Math.random() * 1.0e8).toString() ); variables['TIMESTAMP'] = encodeURIComponentRFC3986(new Date().toISOString()); // RANDOM/random is not defined in VAST 3/4 as a valid macro tho it's used by some adServer (Auditude) variables['RANDOM'] = variables['random'] = variables['CACHEBUSTING']; for (const URLTemplateKey in URLTemplates) { let resolveURL = URLTemplates[URLTemplateKey]; if (typeof resolveURL !== 'string') { continue; } for (const key in variables) { const value = variables[key]; const macro1 = `[${key}]`; const macro2 = `%%${key}%%`; resolveURL = resolveURL.replace(macro1, value); resolveURL = resolveURL.replace(macro2, value); } URLs.push(resolveURL); } return URLs; }
javascript
{ "resource": "" }
q24414
copyNodeAttribute
train
function copyNodeAttribute(attributeName, nodeSource, nodeDestination) { const attributeValue = nodeSource.getAttribute(attributeName); if (attributeValue) { nodeDestination.setAttribute(attributeName, attributeValue); } }
javascript
{ "resource": "" }
q24415
parseDuration
train
function parseDuration(durationString) { if (durationString === null || typeof durationString === 'undefined') { return -1; } // Some VAST doesn't have an HH:MM:SS duration format but instead jus the number of seconds if (util.isNumeric(durationString)) { return parseInt(durationString); } const durationComponents = durationString.split(':'); if (durationComponents.length !== 3) { return -1; } const secondsAndMS = durationComponents[2].split('.'); let seconds = parseInt(secondsAndMS[0]); if (secondsAndMS.length === 2) { seconds += parseFloat(`0.${secondsAndMS[1]}`); } const minutes = parseInt(durationComponents[1] * 60); const hours = parseInt(durationComponents[0] * 60 * 60); if ( isNaN(hours) || isNaN(minutes) || isNaN(seconds) || minutes > 60 * 60 || seconds > 60 ) { return -1; } return hours + minutes + seconds; }
javascript
{ "resource": "" }
q24416
loadToken
train
async function loadToken (url) { let tokens try { const data = await readFile(credentialsPath) tokens = JSON.parse(data) } catch (err) {} return tokens && tokens[url] }
javascript
{ "resource": "" }
q24417
validateToken
train
function validateToken (token) { const header = jwt.decode(token) const now = Math.floor(Date.now() / 1000) return header && header.exp > now }
javascript
{ "resource": "" }
q24418
validateAskPermission
train
function validateAskPermission (token) { const header = jwt.decode(token) return validateToken(token) && header[ASK_CLAIM_KEY] }
javascript
{ "resource": "" }
q24419
getSession
train
async function getSession (url) { const token = await loadToken(url) if (!token) return null const header = jwt.decode(token) if (!header) return null const now = Math.floor(Date.now() / 1000) if (header.exp <= now) return null return header }
javascript
{ "resource": "" }
q24420
saveToken
train
async function saveToken (url, token) { let tokens try { const data = await readFile(credentialsPath) tokens = JSON.parse(data) } catch (err) {} // if it was empty or contained `null` for some reason if (typeof tokens !== 'object' || !tokens) { tokens = {} } tokens[url] = token await writeFile(credentialsPath, JSON.stringify(tokens, null, 2)) }
javascript
{ "resource": "" }
q24421
train
function( arg, type, defaultValue ) { 'use strict'; // If the argument being checked is an array, loop through // it and ensure all the values are of the correct type, // falling back to the defaultValue if any aren't. if ( Array.isArray( arg ) ) { for ( var i = arg.length - 1; i >= 0; --i ) { if ( typeof arg[ i ] !== type ) { return defaultValue; } } return arg; } // If the arg isn't an array then just fallback to // checking the type. return this.ensureTypedArg( arg, type, defaultValue ); }
javascript
{ "resource": "" }
q24422
train
function( arg, instance, defaultValue ) { 'use strict'; // If the argument being checked is an array, loop through // it and ensure all the values are of the correct type, // falling back to the defaultValue if any aren't. if ( Array.isArray( arg ) ) { for ( var i = arg.length - 1; i >= 0; --i ) { if ( instance !== undefined && arg[ i ] instanceof instance === false ) { return defaultValue; } } return arg; } // If the arg isn't an array then just fallback to // checking the type. return this.ensureInstanceOf( arg, instance, defaultValue ); }
javascript
{ "resource": "" }
q24423
train
function( value, randomise ) { 'use strict'; var epsilon = 0.00001, result = value; result = randomise ? Math.random() * epsilon * 10 : epsilon; if ( value < 0 && value > -epsilon ) { result = -result; } // if ( value === 0 ) { // result = randomise ? Math.random() * epsilon * 10 : epsilon; // } // else if ( value > 0 && value < epsilon ) { // result = randomise ? Math.random() * epsilon * 10 : epsilon; // } // else if ( value < 0 && value > -epsilon ) { // result = -( randomise ? Math.random() * epsilon * 10 : epsilon ); // } return result; }
javascript
{ "resource": "" }
q24424
train
function( start, end, delta ) { 'use strict'; var types = this.types, out; if ( typeof start === types.NUMBER && typeof end === types.NUMBER ) { return start + ( ( end - start ) * delta ); } else if ( start instanceof THREE.Vector2 && end instanceof THREE.Vector2 ) { out = start.clone(); out.x = this.lerp( start.x, end.x, delta ); out.y = this.lerp( start.y, end.y, delta ); return out; } else if ( start instanceof THREE.Vector3 && end instanceof THREE.Vector3 ) { out = start.clone(); out.x = this.lerp( start.x, end.x, delta ); out.y = this.lerp( start.y, end.y, delta ); out.z = this.lerp( start.z, end.z, delta ); return out; } else if ( start instanceof THREE.Vector4 && end instanceof THREE.Vector4 ) { out = start.clone(); out.x = this.lerp( start.x, end.x, delta ); out.y = this.lerp( start.y, end.y, delta ); out.z = this.lerp( start.z, end.z, delta ); out.w = this.lerp( start.w, end.w, delta ); return out; } else if ( start instanceof THREE.Color && end instanceof THREE.Color ) { out = start.clone(); out.r = this.lerp( start.r, end.r, delta ); out.g = this.lerp( start.g, end.g, delta ); out.b = this.lerp( start.b, end.b, delta ); return out; } else { console.warn( 'Invalid argument types, or argument types do not match:', start, end ); } }
javascript
{ "resource": "" }
q24425
train
function( n, multiple ) { 'use strict'; var remainder = 0; if ( multiple === 0 ) { return n; } remainder = Math.abs( n ) % multiple; if ( remainder === 0 ) { return n; } if ( n < 0 ) { return -( Math.abs( n ) - remainder ); } return n + multiple - remainder; }
javascript
{ "resource": "" }
q24426
train
function( attribute, index, base, radius, radiusSpread, radiusScale, radiusSpreadClamp, distributionClamp ) { 'use strict'; var depth = 2 * Math.random() - 1, t = 6.2832 * Math.random(), r = Math.sqrt( 1 - depth * depth ), rand = this.randomFloat( radius, radiusSpread ), x = 0, y = 0, z = 0; if ( radiusSpreadClamp ) { rand = Math.round( rand / radiusSpreadClamp ) * radiusSpreadClamp; } // Set position on sphere x = r * Math.cos( t ) * rand; y = r * Math.sin( t ) * rand; z = depth * rand; // Apply radius scale to this position x *= radiusScale.x; y *= radiusScale.y; z *= radiusScale.z; // Translate to the base position. x += base.x; y += base.y; z += base.z; // Set the values in the typed array. attribute.typedArray.setVec3Components( index, x, y, z ); }
javascript
{ "resource": "" }
q24427
taskProcessor
train
function taskProcessor(params, isTX) { if (typeof params.cb !== 'function') { return $p.reject(new TypeError('Callback function is required.')); } if (params.options.reusable) { return config.$npm.task.callback(obj.ctx, obj, params.cb, config); } const taskCtx = ctx.clone(); // task context object; if (isTX) { taskCtx.txLevel = taskCtx.txLevel >= 0 ? (taskCtx.txLevel + 1) : 0; } taskCtx.inTransaction = taskCtx.txLevel >= 0; taskCtx.level = taskCtx.level >= 0 ? (taskCtx.level + 1) : 0; taskCtx.cb = params.cb; // callback function; taskCtx.mode = params.options.mode; // transaction mode; if (this !== obj) { taskCtx.context = this; // calling context object; } const tsk = new config.$npm.task.Task(taskCtx, params.options.tag, isTX, config); taskCtx.taskCtx = tsk.ctx; extend(taskCtx, tsk); if (taskCtx.db) { // reuse existing connection; npm.utils.addReadProp(tsk.ctx, 'useCount', taskCtx.db.useCount); return config.$npm.task.execute(taskCtx, tsk, isTX, config); } // connection required; return config.$npm.connect.pool(taskCtx, dbThis) .then(db => { taskCtx.connect(db); npm.utils.addReadProp(tsk.ctx, 'useCount', db.useCount); return config.$npm.task.execute(taskCtx, tsk, isTX, config); }) .then(data => { taskCtx.disconnect(); return data; }) .catch(error => { taskCtx.disconnect(); return $p.reject(error); }); }
javascript
{ "resource": "" }
q24428
update
train
function update(start, success, result) { const c = ctx.ctx; if (start) { npm.utils.addReadProp(c, 'start', new Date()); } else { c.finish = new Date(); c.success = success; c.result = result; c.duration = c.finish - c.start; npm.utils.lock(c, true); } (isTX ? npm.events.transact : npm.events.task)(ctx.options, { client: ctx.db && ctx.db.client, // loss of connectivity is possible at this point dc: ctx.dc, ctx: c }); }
javascript
{ "resource": "" }
q24429
htmlParse
train
function htmlParse(value, config) { var allow if (Array.isArray(config)) { allow = config } else if (config) { allow = config.allow } return core( value, unified() .use(html) .use(rehype2retext, makeText(config)) .use(filter, {allow: allow}) ) }
javascript
{ "resource": "" }
q24430
noMarkdown
train
function noMarkdown(value, config) { var allow if (Array.isArray(config)) { allow = config } else if (config) { allow = config.allow } return core(value, makeText(config).use(filter, {allow: allow})) }
javascript
{ "resource": "" }
q24431
train
function (err, res) { if (err) { cb(err) } else { res.stats.includedFiles.forEach(function (file) { compiler.emit('dependency', file) }) cb(null, res.css.toString()) } }
javascript
{ "resource": "" }
q24432
sortFeatures
train
function sortFeatures({ stage: a, id: aa }, { stage: b, id: bb }) { return b - a || (aa < bb ? -1 : aa > bb ? 1 : 0); }
javascript
{ "resource": "" }
q24433
formatFeature
train
function formatFeature(feature) { return Object.assign({}, feature, { // format title using marked inline lexer title: marked.inlineLexer(feature.title, [], {}), // format description using marked inline lexer description: marked.inlineLexer(feature.description, [], {}), // format example as syntax-highlighted html example: postcss().process(feature.example, { stringifier: postcssToHTML }).css, caniuse: 'caniuse-compat' in feature ? { stats: feature['caniuse-compat'] } : feature.caniuse in caniuse.features ? trimCaniuseFeatures(caniuse.feature(caniuse.features[feature.caniuse])) : false, caniuseURL: feature.caniuse }); }
javascript
{ "resource": "" }
q24434
postcssToHTML
train
function postcssToHTML(root, builder) { function toString(node) { if ('atrule' === node.type) { return atruleToString(node); } if ('rule' === node.type) { return ruleToString(node); } else if ('decl' === node.type) { return declToString(node); } else if ('comment' === node.type) { return commentToString(node); } else { return node.nodes ? node.nodes.map(childNodes => toString(childNodes)).join('') : ''; } } function replaceVars(string) { return string .replace(/:?--[\w-]+/g, '<span class=css-var>$&</span>') } function replaceVarsAndFns(string) { return replaceVars(string) .replace(/(:?[\w-]+)\(/g, '<span class=css-function>$1</span>(') .replace(/"[^"]+"/g, '<span class=css-string>$&</span>') } function atruleToString(atrule) { return `${atrule.raws.before||''}<span class=css-atrule><span class=css-atrule-name>@${atrule.name}</span>${atrule.raws.afterName||''}<span class=css-atrule-params>${replaceVarsAndFns(atrule.params)}</span>${atrule.raws.between||''}${atrule.nodes?`<span class=css-block>{${atrule.nodes.map(node => toString(node)).join('')}${atrule.raws.after||''}}</span>`:';'}</span>`; } function ruleToString(rule) { return `${rule.raws.before||''}<span class=css-rule><span class=css-selector>${replaceVars(rule.selector)}</span>${rule.raws.between||''}<span class=css-block>{${rule.nodes.map(node => toString(node)).join('')}${rule.raws.after||''}}</span></span>`; } function declToString(decl) { return `${decl.raws.before || ''}<span class=css-declaration><span class=css-property>${decl.prop}</span>${decl.raws.between || ':'}<span class=css-value>${replaceVarsAndFns(decl.value)}</span>;</span>`; } function commentToString(comment) { return `${comment.raws.before}<span class=css-comment>/*${comment.raws.left}${comment.text}${comment.raws.right}*/</span>`; } builder( toString(root) ); }
javascript
{ "resource": "" }
q24435
_merge
train
function _merge(first, second) { var target = {}; [first, second].forEach(function(obj) { for (var prop in obj) { if (obj.hasOwnProperty(prop)) { target[prop] = obj[prop]; } } return target; }); return target; }
javascript
{ "resource": "" }
q24436
StackTrace$$get
train
function StackTrace$$get(opts) { var err = _generateError(); return _isShapedLikeParsableError(err) ? this.fromError(err, opts) : this.generateArtificially(opts); }
javascript
{ "resource": "" }
q24437
StackTrace$$fromError
train
function StackTrace$$fromError(error, opts) { opts = _merge(_options, opts); var gps = new StackTraceGPS(opts); return new Promise(function(resolve) { var stackframes = _filtered(ErrorStackParser.parse(error), opts.filter); resolve(Promise.all(stackframes.map(function(sf) { return new Promise(function(resolve) { function resolveOriginal() { resolve(sf); } gps.pinpoint(sf).then(resolve, resolveOriginal)['catch'](resolveOriginal); }); }))); }.bind(this)); }
javascript
{ "resource": "" }
q24438
StackTrace$$generateArtificially
train
function StackTrace$$generateArtificially(opts) { opts = _merge(_options, opts); var stackFrames = StackGenerator.backtrace(opts); if (typeof opts.filter === 'function') { stackFrames = stackFrames.filter(opts.filter); } return Promise.resolve(stackFrames); }
javascript
{ "resource": "" }
q24439
StackTrace$$instrument
train
function StackTrace$$instrument(fn, callback, errback, thisArg) { if (typeof fn !== 'function') { throw new Error('Cannot instrument non-function object'); } else if (typeof fn.__stacktraceOriginalFn === 'function') { // Already instrumented, return given Function return fn; } var instrumented = function StackTrace$$instrumented() { try { this.get().then(callback, errback)['catch'](errback); return fn.apply(thisArg || this, arguments); } catch (e) { if (_isShapedLikeParsableError(e)) { this.fromError(e).then(callback, errback)['catch'](errback); } throw e; } }.bind(this); instrumented.__stacktraceOriginalFn = fn; return instrumented; }
javascript
{ "resource": "" }
q24440
StackTrace$$report
train
function StackTrace$$report(stackframes, url, errorMsg, requestOptions) { return new Promise(function(resolve, reject) { var req = new XMLHttpRequest(); req.onerror = reject; req.onreadystatechange = function onreadystatechange() { if (req.readyState === 4) { if (req.status >= 200 && req.status < 400) { resolve(req.responseText); } else { reject(new Error('POST to ' + url + ' failed with status: ' + req.status)); } } }; req.open('post', url); // Set request headers req.setRequestHeader('Content-Type', 'application/json'); if (requestOptions && typeof requestOptions.headers === 'object') { var headers = requestOptions.headers; for (var header in headers) { if (headers.hasOwnProperty(header)) { req.setRequestHeader(header, headers[header]); } } } var reportPayload = {stack: stackframes}; if (errorMsg !== undefined && errorMsg !== null) { reportPayload.message = errorMsg; } req.send(JSON.stringify(reportPayload)); }); }
javascript
{ "resource": "" }
q24441
format
train
function format(str, args) { var keys = Object.keys(args), i; for (i=0; i<keys.length; i++) { str = str.replace(new RegExp("\\{" + keys[i] + "\\}", "gi"), args[keys[i]]); } return str; }
javascript
{ "resource": "" }
q24442
randomString
train
function randomString(holder) { var chars, randomstring, i; if (!holder) { throw new Error("cannot create a random attribute name for an undefined object"); } chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"; randomstring = ""; do { randomstring = ""; for (i = 0; i < 12; i++) { randomstring += chars[Math.floor(Math.random() * chars.length)]; } } while (holder[randomstring]); return randomstring; }
javascript
{ "resource": "" }
q24443
createNamedToNumberedLookup
train
function createNamedToNumberedLookup(items, radix) { var i, entity, lookup = {}, base10, base16; items = items.split(','); radix = radix || 10; // Map from named to numbered entities. for (i = 0; i < items.length; i += 2) { entity = '&' + items[i + 1] + ';'; base10 = parseInt(items[i], radix); lookup[entity] = '&#'+base10+';'; } //FF and IE need to create a regex from hex values ie &nbsp; == \xa0 lookup["\\xa0"] = '&#160;'; return lookup; }
javascript
{ "resource": "" }
q24444
train
function (vector) { var len = Math.sqrt(vector[0] * vector[0] + vector[1] * vector[1]); return [vector[0] / len, vector[1] / len]; }
javascript
{ "resource": "" }
q24445
train
function (passes, fails) { var _this = this; passes = passes || function () {}; fails = fails || function () {}; var failsOne = function (rule, message) { _this._addFailure(rule, message); }; var resolvedAll = function (allPassed) { if (allPassed) { passes(); } else { fails(); } }; var asyncResolvers = new AsyncResolvers(failsOne, resolvedAll); var validateRule = function (inputValue, ruleOptions, attribute, rule) { return function () { var resolverIndex = asyncResolvers.add(rule); rule.validate(inputValue, ruleOptions.value, attribute, function () { asyncResolvers.resolve(resolverIndex); }); }; }; for (var attribute in this.rules) { var attributeRules = this.rules[attribute]; var inputValue = this._objectPath(this.input, attribute); if (this._hasRule(attribute, ['sometimes']) && !this._suppliedWithData(attribute)) { continue; } for (var i = 0, len = attributeRules.length, rule, ruleOptions; i < len; i++) { ruleOptions = attributeRules[i]; rule = this.getRule(ruleOptions.name); if (!this._isValidatable(rule, inputValue)) { continue; } validateRule(inputValue, ruleOptions, attribute, rule)(); } } asyncResolvers.enableFiring(); asyncResolvers.fire(); }
javascript
{ "resource": "" }
q24446
train
function (rule) { var msg = this.messages.render(rule); this.errors.add(rule.attribute, msg); this.errorCount++; }
javascript
{ "resource": "" }
q24447
train
function (obj, path) { if (Object.prototype.hasOwnProperty.call(obj, path)) { return obj[path]; } var keys = path.replace(/\[(\w+)\]/g, ".$1").replace(/^\./, "").split("."); var copy = {}; for (var attr in obj) { if (Object.prototype.hasOwnProperty.call(obj, attr)) { copy[attr] = obj[attr]; } } for (var i = 0, l = keys.length; i < l; i++) { if (Object.hasOwnProperty.call(copy, keys[i])) { copy = copy[keys[i]]; } else { return; } } return copy; }
javascript
{ "resource": "" }
q24448
train
function (rulesArray) { var rules = []; for (var i = 0, len = rulesArray.length; i < len; i++) { if (typeof rulesArray[i] === 'object') { for (var rule in rulesArray[i]) { rules.push({ name: rule, value: rulesArray[i][rule] }); } } else { rules.push(rulesArray[i]); } } return rules; }
javascript
{ "resource": "" }
q24449
train
function (attribute, findRules) { var rules = this.rules[attribute] || []; for (var i = 0, len = rules.length; i < len; i++) { if (findRules.indexOf(rules[i].name) > -1) { return true; } } return false; }
javascript
{ "resource": "" }
q24450
train
function (rule, value) { if (Rules.isImplicit(rule.name)) { return true; } return this.getRule('required').validate(value); }
javascript
{ "resource": "" }
q24451
train
function (attribute, rulePassed) { var stopOnAttributes = this.stopOnAttributes; if (typeof stopOnAttributes === 'undefined' || stopOnAttributes === false || rulePassed === true) { return false; } if (stopOnAttributes instanceof Array) { return stopOnAttributes.indexOf(attribute) > -1; } return true; }
javascript
{ "resource": "" }
q24452
train
function(val, req, attribute) { if (val) { req = parseFloat(req); var size = this.getSize(); return size === req; } return true; }
javascript
{ "resource": "" }
q24453
train
function(inputValue, ruleValue, attribute, callback) { var fn = this.isMissed() ? missedRuleValidator : this.fn; return fn.apply(this, [inputValue, ruleValue, attribute, callback]); }
javascript
{ "resource": "" }
q24454
train
function() { var value = this.inputValue; if (value instanceof Array) { return value.length; } if (typeof value === 'number') { return value; } if (this.validator._hasNumericRule(this.attribute)) { return parseFloat(value, 10); } return value.length; }
javascript
{ "resource": "" }
q24455
train
function(passes, message) { this.passes = (passes === undefined || passes === true); this._customMessage = message; this.callback(this.passes, message); }
javascript
{ "resource": "" }
q24456
train
function(name, validator) { var async = this.isAsync(name); var rule = new Rule(name, rules[name], async); rule.setValidator(validator); return rule; }
javascript
{ "resource": "" }
q24457
train
function(name) { for (var i = 0, len = this.asyncRules.length; i < len; i++) { if (this.asyncRules[i] === name) { return true; } } return false; }
javascript
{ "resource": "" }
q24458
train
function(attribute, message) { if (!this.has(attribute)) { this.errors[attribute] = []; } if (this.errors[attribute].indexOf(message) === -1) { this.errors[attribute].push(message); } }
javascript
{ "resource": "" }
q24459
train
function(index) { var rule = this.resolvers[index]; if (rule.passes === true) { this.passed.push(rule); } else if (rule.passes === false) { this.failed.push(rule); this.onFailedOne(rule); } this.fire(); }
javascript
{ "resource": "" }
q24460
ancestors
train
function ancestors(first, second) { var path = []; for (var n in first.path) { if (first.path[n] !== second.path[n]) break; path.push(first.path[n]); } return path; }
javascript
{ "resource": "" }
q24461
equalForKeys
train
function equalForKeys(a, b, keys) { if (!keys) { keys = []; for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility } for (var i=0; i<keys.length; i++) { var k = keys[i]; if (a[k] != b[k]) return false; // Not '===', values aren't necessarily normalized } return true; }
javascript
{ "resource": "" }
q24462
filterByKeys
train
function filterByKeys(keys, values) { var filtered = {}; forEach(keys, function (name) { filtered[name] = values[name]; }); return filtered; }
javascript
{ "resource": "" }
q24463
indexBy
train
function indexBy(array, propName) { var result = {}; forEach(array, function(item) { result[item[propName]] = item; }); return result; }
javascript
{ "resource": "" }
q24464
pick
train
function pick(obj) { var copy = {}; var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1)); forEach(keys, function(key) { if (key in obj) copy[key] = obj[key]; }); return copy; }
javascript
{ "resource": "" }
q24465
omit
train
function omit(obj) { var copy = {}; var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1)); for (var key in obj) { if (indexOf(keys, key) == -1) copy[key] = obj[key]; } return copy; }
javascript
{ "resource": "" }
q24466
train
function(state) { var url = state.url, config = { params: state.params || {} }; if (isString(url)) { if (url.charAt(0) == '^') return $urlMatcherFactory.compile(url.substring(1), config); return (state.parent.navigable || root).url.concat(url, config); } if (!url || $urlMatcherFactory.isMatcher(url)) return url; throw new Error("Invalid url '" + url + "' in state '" + state + "'"); }
javascript
{ "resource": "" }
q24467
train
function(state) { var params = state.url && state.url.params || new $$UMFP.ParamSet(); forEach(state.params || {}, function(config, id) { if (!params[id]) params[id] = new $$UMFP.Param(id, null, config, "config"); }); return params; }
javascript
{ "resource": "" }
q24468
train
function(state) { var views = {}; forEach(isDefined(state.views) ? state.views : { '': state }, function (view, name) { if (name.indexOf('@') < 0) name += '@' + state.parent.name; views[name] = view; }); return views; }
javascript
{ "resource": "" }
q24469
handleRedirect
train
function handleRedirect(redirect, state, params, options) { /** * @ngdoc event * @name ui.router.state.$state#$stateNotFound * @eventOf ui.router.state.$state * @eventType broadcast on root scope * @description * Fired when a requested state **cannot be found** using the provided state name during transition. * The event is broadcast allowing any handlers a single chance to deal with the error (usually by * lazy-loading the unfound state). A special `unfoundState` object is passed to the listener handler, * you can see its three properties in the example. You can use `event.preventDefault()` to abort the * transition and the promise returned from `go` will be rejected with a `'transition aborted'` value. * * @param {Object} event Event object. * @param {Object} unfoundState Unfound State information. Contains: `to, toParams, options` properties. * @param {State} fromState Current state object. * @param {Object} fromParams Current state params. * * @example * * <pre> * // somewhere, assume lazy.state has not been defined * $state.go("lazy.state", {a:1, b:2}, {inherit:false}); * * // somewhere else * $scope.$on('$stateNotFound', * function(event, unfoundState, fromState, fromParams){ * console.log(unfoundState.to); // "lazy.state" * console.log(unfoundState.toParams); // {a:1, b:2} * console.log(unfoundState.options); // {inherit:false} + default options * }) * </pre> */ var evt = $rootScope.$broadcast('$stateNotFound', redirect, state, params); if (evt.defaultPrevented) { $urlRouter.update(); return TransitionAborted; } if (!evt.retry) { return null; } // Allow the handler to return a promise to defer state lookup retry if (options.$retry) { $urlRouter.update(); return TransitionFailed; } var retryTransition = $state.transition = $q.when(evt.retry); retryTransition.then(function() { if (retryTransition !== $state.transition) return TransitionSuperseded; redirect.options.$retry = true; return $state.transitionTo(redirect.to, redirect.toParams, redirect.options); }, function() { return TransitionAborted; }); $urlRouter.update(); return retryTransition; }
javascript
{ "resource": "" }
q24470
getSquashPolicy
train
function getSquashPolicy(config, isOptional) { var squash = config.squash; if (!isOptional || squash === false) return false; if (!isDefined(squash) || squash == null) return defaultSquashPolicy; if (squash === true || isString(squash)) return squash; throw new Error("Invalid squash policy: '" + squash + "'. Valid policies: false, true, or arbitrary string"); }
javascript
{ "resource": "" }
q24471
train
function (address) { var q = $q.defer(); $window.bluetoothSerial.connectInsecure(address, function () { q.resolve(); }, function (error) { q.reject(error); }); return q.promise; }
javascript
{ "resource": "" }
q24472
train
function (workout) { var q = $q.defer(); $window.plugins.healthkit.saveWorkout(workout, function (success) { q.resolve(success); }, function (err) { q.resolve(err); } ); return q.promise; }
javascript
{ "resource": "" }
q24473
train
function (promise){ promise.success = function (fn) { promise.then(fn); return promise; }; promise.error = function (fn) { promise.then(null, fn); return promise; }; }
javascript
{ "resource": "" }
q24474
train
function (key, value, dict) { var deferred = $q.defer(); var promise = deferred.promise; function ok(value){ deferred.resolve(value); } function errorCallback(error){ deferred.reject(new Error(error)); } if($window.plugins){ var storeResult; if(arguments.length === 3){ storeResult = $window.plugins.appPreferences.store(dict, key, value); } else { storeResult = $window.plugins.appPreferences.store(key, value); } storeResult.then(ok, errorCallback); } else { deferred.reject(new Error(this.pluginNotEnabledMessage)); } this.decoratePromise(promise); return promise; }
javascript
{ "resource": "" }
q24475
train
function () { var deferred = $q.defer(); var promise = deferred.promise; function ok(value){ deferred.resolve(value); } function errorCallback(error){ deferred.reject(new Error(error)); } if($window.plugins){ $window.plugins.appPreferences.show() .then(ok, errorCallback); } else { deferred.reject(new Error(this.pluginNotEnabledMessage)); } this.decoratePromise(promise); return promise; }
javascript
{ "resource": "" }
q24476
triggerEvent
train
function triggerEvent(gesture, eventData){ // create DOM event var event = ionic.Gestures.DOCUMENT.createEvent('Event'); event.initEvent(gesture, true, true); event.gesture = eventData; // trigger on the target if it is in the instance element, // this is for event delegation tricks var element = this.element; if(ionic.Gestures.utils.hasParent(eventData.target, element)) { element = eventData.target; } element.dispatchEvent(event); return this; }
javascript
{ "resource": "" }
q24477
getDirection
train
function getDirection(touch1, touch2) { var x = Math.abs(touch1.pageX - touch2.pageX), y = Math.abs(touch1.pageY - touch2.pageY); if(x >= y) { return touch1.pageX - touch2.pageX > 0 ? ionic.Gestures.DIRECTION_LEFT : ionic.Gestures.DIRECTION_RIGHT; } else { return touch1.pageY - touch2.pageY > 0 ? ionic.Gestures.DIRECTION_UP : ionic.Gestures.DIRECTION_DOWN; } }
javascript
{ "resource": "" }
q24478
isVertical
train
function isVertical(direction) { return (direction == ionic.Gestures.DIRECTION_UP || direction == ionic.Gestures.DIRECTION_DOWN); }
javascript
{ "resource": "" }
q24479
stopDefaultBrowserBehavior
train
function stopDefaultBrowserBehavior(element, css_class) { // changed from making many style changes to just adding a preset classname // less DOM manipulations, less code, and easier to control in the CSS side of things // hammer.js doesn't come with CSS, but ionic does, which is why we prefer this method if(element && element.classList) { element.classList.add(css_class); element.onselectstart = function() { return false; }; } }
javascript
{ "resource": "" }
q24480
detect
train
function detect(eventData) { if(!this.current || this.stopped) { return; } // extend event data with calculations about scale, distance etc eventData = this.extendEventData(eventData); // instance options var inst_options = this.current.inst.options; // call ionic.Gestures.gesture handlers for(var g=0,len=this.gestures.length; g<len; g++) { var gesture = this.gestures[g]; // only when the instance options have enabled this gesture if(!this.stopped && inst_options[gesture.name] !== false) { // if a handler returns false, we stop with the detection if(gesture.handler.call(gesture, eventData, this.current.inst) === false) { this.stopDetect(); break; } } } // store as previous event event if(this.current) { this.current.lastEvent = eventData; } // endevent, but not the last touch, so dont stop if(eventData.eventType == ionic.Gestures.EVENT_END && !eventData.touches.length-1) { this.stopDetect(); } return eventData; }
javascript
{ "resource": "" }
q24481
stopDetect
train
function stopDetect() { // clone current data to the store as the previous gesture // used for the double tap gesture, since this is an other gesture detect session this.previous = ionic.Gestures.utils.extend({}, this.current); // reset the current this.current = null; // stopped! this.stopped = true; }
javascript
{ "resource": "" }
q24482
extendEventData
train
function extendEventData(ev) { var startEv = this.current.startEvent; // if the touches change, set the new touches over the startEvent touches // this because touchevents don't have all the touches on touchstart, or the // user must place his fingers at the EXACT same time on the screen, which is not realistic // but, sometimes it happens that both fingers are touching at the EXACT same time if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) { // extend 1 level deep to get the touchlist with the touch objects startEv.touches = []; for(var i=0,len=ev.touches.length; i<len; i++) { startEv.touches.push(ionic.Gestures.utils.extend({}, ev.touches[i])); } } var delta_time = ev.timeStamp - startEv.timeStamp, delta_x = ev.center.pageX - startEv.center.pageX, delta_y = ev.center.pageY - startEv.center.pageY, velocity = ionic.Gestures.utils.getVelocity(delta_time, delta_x, delta_y); ionic.Gestures.utils.extend(ev, { deltaTime : delta_time, deltaX : delta_x, deltaY : delta_y, velocityX : velocity.x, velocityY : velocity.y, distance : ionic.Gestures.utils.getDistance(startEv.center, ev.center), angle : ionic.Gestures.utils.getAngle(startEv.center, ev.center), direction : ionic.Gestures.utils.getDirection(startEv.center, ev.center), scale : ionic.Gestures.utils.getScale(startEv.touches, ev.touches), rotation : ionic.Gestures.utils.getRotation(startEv.touches, ev.touches), startEvent : startEv }); return ev; }
javascript
{ "resource": "" }
q24483
train
function(obj) { var args = Array.prototype.slice.call(arguments, 1); for (var i = 0; i < args.length; i++) { var source = args[i]; if (source) { for (var prop in source) { obj[prop] = source[prop]; } } } return obj; }
javascript
{ "resource": "" }
q24484
train
function() { var index = uid.length; var digit; while (index) { index--; digit = uid[index].charCodeAt(0); if (digit == 57 /*'9'*/) { uid[index] = 'A'; return uid.join(''); } if (digit == 90 /*'Z'*/) { uid[index] = '0'; } else { uid[index] = String.fromCharCode(digit + 1); return uid.join(''); } } uid.unshift('0'); return uid.join(''); }
javascript
{ "resource": "" }
q24485
train
function(stepCallback, verifyCallback, completedCallback, duration, easingMethod, root) { var start = time(); var lastFrame = start; var percent = 0; var dropCounter = 0; var id = counter++; if (!root) { root = document.body; } // Compacting running db automatically every few new animations if (id % 20 === 0) { var newRunning = {}; for (var usedId in running) { newRunning[usedId] = true; } running = newRunning; } // This is the internal step method which is called every few milliseconds var step = function(virtual) { // Normalize virtual value var render = virtual !== true; // Get current time var now = time(); // Verification is executed before next animation step if (!running[id] || (verifyCallback && !verifyCallback(id))) { running[id] = null; completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, false); return; } // For the current rendering to apply let's update omitted steps in memory. // This is important to bring internal state variables up-to-date with progress in time. if (render) { var droppedFrames = Math.round((now - lastFrame) / (millisecondsPerSecond / desiredFrames)) - 1; for (var j = 0; j < Math.min(droppedFrames, 4); j++) { step(true); dropCounter++; } } // Compute percent value if (duration) { percent = (now - start) / duration; if (percent > 1) { percent = 1; } } // Execute step callback, then... var value = easingMethod ? easingMethod(percent) : percent; if ((stepCallback(value, now, render) === false || percent === 1) && render) { running[id] = null; completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, percent === 1 || duration == null); } else if (render) { lastFrame = now; zyngaCore.effect.Animate.requestAnimationFrame(step, root); } }; // Mark as running running[id] = true; // Init first step zyngaCore.effect.Animate.requestAnimationFrame(step, root); // Return unique animation ID return id; }
javascript
{ "resource": "" }
q24486
train
function() { // Use publish instead of scrollTo to allow scrolling to out of boundary position // We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled this.__publish(this.__scrollLeft, -this.__refreshHeight, this.__zoomLevel, true); var d = new Date(); this.refreshStartTime = d.getTime(); if (this.__refreshStart) { this.__refreshStart(); } }
javascript
{ "resource": "" }
q24487
train
function(level, animate, originLeft, originTop) { var self = this; if (!self.options.zooming) { throw new Error("Zooming is not enabled!"); } // Stop deceleration if (self.__isDecelerating) { zyngaCore.effect.Animate.stop(self.__isDecelerating); self.__isDecelerating = false; } var oldLevel = self.__zoomLevel; // Normalize input origin to center of viewport if not defined if (originLeft == null) { originLeft = self.__clientWidth / 2; } if (originTop == null) { originTop = self.__clientHeight / 2; } // Limit level according to configuration level = Math.max(Math.min(level, self.options.maxZoom), self.options.minZoom); // Recompute maximum values while temporary tweaking maximum scroll ranges self.__computeScrollMax(level); // Recompute left and top coordinates based on new zoom level var left = ((originLeft + self.__scrollLeft) * level / oldLevel) - originLeft; var top = ((originTop + self.__scrollTop) * level / oldLevel) - originTop; // Limit x-axis if (left > self.__maxScrollLeft) { left = self.__maxScrollLeft; } else if (left < 0) { left = 0; } // Limit y-axis if (top > self.__maxScrollTop) { top = self.__maxScrollTop; } else if (top < 0) { top = 0; } // Push values out self.__publish(left, top, level, animate); }
javascript
{ "resource": "" }
q24488
train
function(left, top, animate, zoom, wasResize) { var self = this; // Stop deceleration if (self.__isDecelerating) { zyngaCore.effect.Animate.stop(self.__isDecelerating); self.__isDecelerating = false; } // Correct coordinates based on new zoom level if (zoom != null && zoom !== self.__zoomLevel) { if (!self.options.zooming) { throw new Error("Zooming is not enabled!"); } left *= zoom; top *= zoom; // Recompute maximum values while temporary tweaking maximum scroll ranges self.__computeScrollMax(zoom); } else { // Keep zoom when not defined zoom = self.__zoomLevel; } if (!self.options.scrollingX) { left = self.__scrollLeft; } else { if (self.options.paging) { left = Math.round(left / self.__clientWidth) * self.__clientWidth; } else if (self.options.snapping) { left = Math.round(left / self.__snapWidth) * self.__snapWidth; } } if (!self.options.scrollingY) { top = self.__scrollTop; } else { if (self.options.paging) { top = Math.round(top / self.__clientHeight) * self.__clientHeight; } else if (self.options.snapping) { top = Math.round(top / self.__snapHeight) * self.__snapHeight; } } // Limit for allowed ranges left = Math.max(Math.min(self.__maxScrollLeft, left), 0); top = Math.max(Math.min(self.__maxScrollTop, top), 0); // Don't animate when no change detected, still call publish to make sure // that rendered position is really in-sync with internal data if (left === self.__scrollLeft && top === self.__scrollTop) { animate = false; } // Publish new values self.__publish(left, top, zoom, animate, wasResize); }
javascript
{ "resource": "" }
q24489
train
function() { var self = this; clearTimeout(self.__sizerTimeout); var sizer = function() { self.resize(); // if ((self.options.scrollingX && !self.__maxScrollLeft) || (self.options.scrollingY && !self.__maxScrollTop)) { // //self.__sizerTimeout = setTimeout(sizer, 1000); // } }; sizer(); self.__sizerTimeout = setTimeout(sizer, 1000); }
javascript
{ "resource": "" }
q24490
train
function(target) { while (target) { if (target.classList && target.classList.contains(ITEM_CLASS)) { return target; } target = target.parentNode; } return null; }
javascript
{ "resource": "" }
q24491
train
function(e) { var _this = this, content, buttons; if (Math.abs(e.gesture.deltaY) > 5) { this._didDragUpOrDown = true; } // If we get a drag event, make sure we aren't in another drag, then check if we should // start one if (!this.isDragging && !this._dragOp) { this._startDrag(e); } // No drag still, pass it up if (!this._dragOp) { //ionic.views.ListView.__super__._handleDrag.call(this, e); return; } e.gesture.srcEvent.preventDefault(); this._dragOp.drag(e); }
javascript
{ "resource": "" }
q24492
shallowCopy
train
function shallowCopy(src, dst) { if (isArray(src)) { dst = dst || []; for (var i = 0, ii = src.length; i < ii; i++) { dst[i] = src[i]; } } else if (isObject(src)) { dst = dst || {}; for (var key in src) { if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) { dst[key] = src[key]; } } } return dst || src; }
javascript
{ "resource": "" }
q24493
getter
train
function getter(obj, path, bindFnToScope) { if (!path) return obj; var keys = path.split('.'); var key; var lastInstance = obj; var len = keys.length; for (var i = 0; i < len; i++) { key = keys[i]; if (obj) { obj = (lastInstance = obj)[key]; } } if (!bindFnToScope && isFunction(obj)) { return bind(lastInstance, obj); } return obj; }
javascript
{ "resource": "" }
q24494
HashMap
train
function HashMap(array, isolatedUid) { if (isolatedUid) { var uid = 0; this.nextUid = function() { return ++uid; }; } forEach(array, this.put, this); }
javascript
{ "resource": "" }
q24495
directiveIsMultiElement
train
function directiveIsMultiElement(name) { if (hasDirectives.hasOwnProperty(name)) { for (var directive, directives = $injector.get(name + Suffix), i = 0, ii = directives.length; i < ii; i++) { directive = directives[i]; if (directive.multiElement) { return true; } } } return false; }
javascript
{ "resource": "" }
q24496
mergeTemplateAttributes
train
function mergeTemplateAttributes(dst, src) { var srcAttr = src.$attr, dstAttr = dst.$attr, $element = dst.$$element; // reapply the old attributes to the new element forEach(dst, function(value, key) { if (key.charAt(0) != '$') { if (src[key] && src[key] !== value) { value += (key === 'style' ? ';' : ' ') + src[key]; } dst.$set(key, value, true, srcAttr[key]); } }); // copy the new attributes on the old attrs object forEach(src, function(value, key) { if (key == 'class') { safeAddClass($element, value); dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value; } else if (key == 'style') { $element.attr('style', $element.attr('style') + ';' + value); dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value; // `dst` will never contain hasOwnProperty as DOM parser won't let it. // You will get an "InvalidCharacterError: DOM Exception 5" error if you // have an attribute like "has-own-property" or "data-has-own-property", etc. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) { dst[key] = value; dstAttr[key] = srcAttr[key]; } }); }
javascript
{ "resource": "" }
q24497
byPriority
train
function byPriority(a, b) { var diff = b.priority - a.priority; if (diff !== 0) return diff; if (a.name !== b.name) return (a.name < b.name) ? -1 : 1; return a.index - b.index; }
javascript
{ "resource": "" }
q24498
train
function(event) { // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have // it. In particular the event is not fired when backspace or delete key are pressed or // when cut operation is performed. // IE10+ implements 'input' event but it erroneously fires under various situations, // e.g. when placeholder changes, or a form is focused. if (event === 'input' && msie <= 11) return false; if (isUndefined(eventSupport[event])) { var divElm = document.createElement('div'); eventSupport[event] = 'on' + event in divElm; } return eventSupport[event]; }
javascript
{ "resource": "" }
q24499
urlIsSameOrigin
train
function urlIsSameOrigin(requestUrl) { var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl; return (parsed.protocol === originUrl.protocol && parsed.host === originUrl.host); }
javascript
{ "resource": "" }