_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q25200
RuleSet
train
function RuleSet(language) { var data = englishRuleSet; DEBUG && console.log(data); switch (language) { case 'EN': data = englishRuleSet; break; case 'DU': data = dutchRuleSet; break; } if (data.rules) { this.rules = {}; var that = this; data.rules.forEach(function(ruleString) { that.addRule(TF_Parser.parse(ruleString)); }) } DEBUG && console.log(this.rules); DEBUG && console.log('Brill_POS_Tagger.read_transformation_rules: number of transformation rules read: ' + Object.keys(this.rules).length); }
javascript
{ "resource": "" }
q25201
train
function(docs) { setTimeout(function() { self.events.emit('processedBatch', { size: docs.length, docs: totalDocs, batches: numThreads, index: finished }); }); for (var j = 0; j < docs.length; j++) { docFeatures[docs[j].index] = docs[j].features; } }
javascript
{ "resource": "" }
q25202
train
function(err) { if (err) { threadPool.destroy(); return callback(err); } for (var j = self.lastAdded; j < totalDocs; j++) { self.classifier.addExample(docFeatures[j], self.docs[j].label); self.events.emit('trainedWithDocument', { index: j, total: totalDocs, doc: self.docs[j] }); self.lastAdded++; } self.events.emit('doneTraining', true); self.classifier.train(); threadPool.destroy(); callback(null); }
javascript
{ "resource": "" }
q25203
train
function(batchJson) { if (abort) return; threadPool.any.eval('docsToFeatures(' + batchJson + ');', function(err, docs) { if (err) { return onError(err); } finished++; if (docs) { docs = JSON.parse(docs); setTimeout(onFeaturesResult.bind(null, docs)); } if (finished >= obsBatches.length) { setTimeout(onFinished); } setTimeout(sendNext); }); }
javascript
{ "resource": "" }
q25204
isEncoding
train
function isEncoding(encoding) { if (typeof Buffer.isEncoding !== 'undefined') return Buffer.isEncoding(encoding); switch ((encoding + '').toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; } return false; }
javascript
{ "resource": "" }
q25205
train
function(options) { var options = options || {}; this._pattern = options.pattern || this._pattern; this.discardEmpty = options.discardEmpty || true; // Match and split on GAPS not the actual WORDS this._gaps = options.gaps; if (this._gaps === undefined) { this._gaps = true; } }
javascript
{ "resource": "" }
q25206
setListener
train
function setListener(callback) { if (onFinish) { throw new Error('thenDo/finally called more than once'); } if (finished) { onFinish = function() {}; callback(finished.err, finished.result); } else { onFinish = function() { callback(finished.err, finished.result); }; } }
javascript
{ "resource": "" }
q25207
formatRequestUrl
train
function formatRequestUrl(path, query, useClientId) { if (channel) { query.channel = channel; } if (useClientId) { query.client = clientId; } else if (key && key.indexOf('AIza') == 0) { query.key = key; } else { throw 'Missing either a valid API key, or a client ID and secret'; } var requestUrl = url.format({pathname: path, query: query}); // When using client ID, generate and append the signature param. if (useClientId) { var secret = new Buffer(clientSecret, 'base64'); var payload = url.parse(requestUrl).path; var signature = computeSignature(secret, payload); requestUrl += '&signature=' + encodeURIComponent(signature); } return requestUrl; }
javascript
{ "resource": "" }
q25208
train
function (key) { return containsIC(this.userAgents(), key) || equalIC(key, this.os()) || equalIC(key, this.phone()) || equalIC(key, this.tablet()) || containsIC(impl.findMatches(impl.mobileDetectRules.utils, this.ua), key); }
javascript
{ "resource": "" }
q25209
isPlainSafe
train
function isPlainSafe(c) { // Uses a subset of nb-char - c-flow-indicator - ":" - "#" // where nb-char ::= c-printable - b-char - c-byte-order-mark. return isPrintable(c) && c !== 0xFEFF // - c-flow-indicator && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET // - ":" - "#" && c !== CHAR_COLON && c !== CHAR_SHARP; }
javascript
{ "resource": "" }
q25210
isPlainSafeFirst
train
function isPlainSafeFirst(c) { // Uses a subset of ns-char - c-indicator // where ns-char = nb-char - s-white. return isPrintable(c) && c !== 0xFEFF && !isWhitespace(c) // - s-white // - (c-indicator ::= // β€œ-” | β€œ?” | β€œ:” | β€œ,” | β€œ[” | β€œ]” | β€œ{” | β€œ}” && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET // | β€œ#” | β€œ&” | β€œ*” | β€œ!” | β€œ|” | β€œ>” | β€œ'” | β€œ"” && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE // | β€œ%” | β€œ@” | β€œ`”) && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT; }
javascript
{ "resource": "" }
q25211
Point
train
function Point(x, y, z) { this.klass = 'Point'; this.x = x; this.y = y; this.z = z; }
javascript
{ "resource": "" }
q25212
isValidLatLng
train
function isValidLatLng(elem) { return elem !== null && (typeof elem === 'undefined' ? 'undefined' : _typeof(elem)) === 'object' && elem.hasOwnProperty('lat') && elem.hasOwnProperty('lng'); }
javascript
{ "resource": "" }
q25213
commify
train
function commify(value) { var comps = String(value).split('.'); if (comps.length > 2 || !comps[0].match(/^-?[0-9]*$/) || (comps[1] && !comps[1].match(/^[0-9]*$/)) || value === '.' || value === '-.') { errors.throwError('invalid value', errors.INVALID_ARGUMENT, { argument: 'value', value: value }); } // Make sure we have at least one whole digit (0 if none) var whole = comps[0]; var negative = ''; if (whole.substring(0, 1) === '-') { negative = '-'; whole = whole.substring(1); } // Make sure we have at least 1 whole digit with no leading zeros while (whole.substring(0, 1) === '0') { whole = whole.substring(1); } if (whole === '') { whole = '0'; } var suffix = ''; if (comps.length === 2) { suffix = '.' + (comps[1] || '0'); } var formatted = []; while (whole.length) { if (whole.length <= 3) { formatted.unshift(whole); break; } else { var index = whole.length - 3; formatted.unshift(whole.substring(index)); whole = whole.substring(0, index); } } return negative + formatted.join(',') + suffix; }
javascript
{ "resource": "" }
q25214
resolveAddresses
train
function resolveAddresses(provider, value, paramType) { if (Array.isArray(paramType)) { var promises_1 = []; paramType.forEach(function (paramType, index) { var v = null; if (Array.isArray(value)) { v = value[index]; } else { v = value[paramType.name]; } promises_1.push(resolveAddresses(provider, v, paramType)); }); return Promise.all(promises_1); } if (paramType.type === 'address') { return provider.resolveName(value); } if (paramType.type === 'tuple') { return resolveAddresses(provider, value, paramType.components); } // Strips one level of array indexing off the end to recuse into var isArrayMatch = paramType.type.match(/(.*)(\[[0-9]*\]$)/); if (isArrayMatch) { if (!Array.isArray(value)) { throw new Error('invalid value for array'); } var promises = []; var subParamType = { components: paramType.components, type: isArrayMatch[1], }; value.forEach(function (v) { promises.push(resolveAddresses(provider, v, subParamType)); }); return Promise.all(promises); } return Promise.resolve(value); }
javascript
{ "resource": "" }
q25215
HDNode
train
function HDNode(constructorGuard, privateKey, publicKey, parentFingerprint, chainCode, index, depth, mnemonic, path) { errors.checkNew(this, HDNode); if (constructorGuard !== _constructorGuard) { throw new Error('HDNode constructor cannot be called directly'); } if (privateKey) { var keyPair = new secp256k1_1.KeyPair(privateKey); properties_1.defineReadOnly(this, 'privateKey', keyPair.privateKey); properties_1.defineReadOnly(this, 'publicKey', keyPair.compressedPublicKey); } else { properties_1.defineReadOnly(this, 'privateKey', null); properties_1.defineReadOnly(this, 'publicKey', bytes_1.hexlify(publicKey)); } properties_1.defineReadOnly(this, 'parentFingerprint', parentFingerprint); properties_1.defineReadOnly(this, 'fingerprint', bytes_1.hexDataSlice(sha2_1.ripemd160(sha2_1.sha256(this.publicKey)), 0, 4)); properties_1.defineReadOnly(this, 'address', secp256k1_1.computeAddress(this.publicKey)); properties_1.defineReadOnly(this, 'chainCode', chainCode); properties_1.defineReadOnly(this, 'index', index); properties_1.defineReadOnly(this, 'depth', depth); properties_1.defineReadOnly(this, 'mnemonic', mnemonic); properties_1.defineReadOnly(this, 'path', path); properties_1.setType(this, 'HDNode'); }
javascript
{ "resource": "" }
q25216
normalize
train
function normalize(word) { var result = ''; for (var i = 0; i < word.length; i++) { var kana = word[i]; var target = transform[kana]; if (target === false) { continue; } if (target) { kana = target; } result += kana; } return result; }
javascript
{ "resource": "" }
q25217
sortJapanese
train
function sortJapanese(a, b) { a = normalize(a); b = normalize(b); if (a < b) { return -1; } if (a > b) { return 1; } return 0; }
javascript
{ "resource": "" }
q25218
searchPath
train
function searchPath(object, path) { var currentChild = object; var comps = path.toLowerCase().split('/'); for (var i = 0; i < comps.length; i++) { // Search for a child object with a case-insensitive matching key var matchingChild = null; for (var key in currentChild) { if (key.toLowerCase() === comps[i]) { matchingChild = currentChild[key]; break; } } // Didn't find one. :'( if (matchingChild === null) { return null; } // Now check this child... currentChild = matchingChild; } return currentChild; }
javascript
{ "resource": "" }
q25219
setType
train
function setType(object, type) { Object.defineProperty(object, '_ethersType', { configurable: false, value: type, writable: false }); }
javascript
{ "resource": "" }
q25220
extractString_
train
function extractString_(full, start, end) { var i = (start === '') ? 0 : full.indexOf(start); var e = end === '' ? full.length : full.indexOf(end, i + start.length); return full.substring(i + start.length, e); }
javascript
{ "resource": "" }
q25221
augmentObject_
train
function augmentObject_(src, dest, force) { if (src && dest) { var p; for (p in src) { if (force || !(p in dest)) { dest[p] = src[p]; } } } return dest; }
javascript
{ "resource": "" }
q25222
handleErr_
train
function handleErr_(errback, json) { if (errback && json && json.error) { errback(json.error); } }
javascript
{ "resource": "" }
q25223
formatTimeString_
train
function formatTimeString_(time, endTime) { var ret = ''; if (time) { ret += (time.getTime() - time.getTimezoneOffset() * 60000); } if (endTime) { ret += ', ' + (endTime.getTime() - endTime.getTimezoneOffset() * 60000); } return ret; }
javascript
{ "resource": "" }
q25224
setNodeOpacity_
train
function setNodeOpacity_(node, op) { // closure compiler removed? op = Math.min(Math.max(op, 0), 1); if (node) { var st = node.style; if (typeof st.opacity !== 'undefined') { st.opacity = op; } if (typeof st.filters !== 'undefined') { st.filters.alpha.opacity = Math.floor(100 * op); } if (typeof st.filter !== 'undefined') { st.filter = "alpha(opacity:" + Math.floor(op * 100) + ")"; } } }
javascript
{ "resource": "" }
q25225
getLayerDefsString_
train
function getLayerDefsString_(defs) { var strDefs = ''; for (var x in defs) { if (defs.hasOwnProperty(x)) { if (strDefs.length > 0) { strDefs += ';'; } strDefs += (x + ':' + defs[x]); } } return strDefs; }
javascript
{ "resource": "" }
q25226
isOverlay_
train
function isOverlay_(obj) { var o = obj; if (isArray_(obj) && obj.length > 0) { o = obj[0]; } if (isArray_(o) && o.length > 0) { o = o[0]; } if (o instanceof G.LatLng || o instanceof G.Marker || o instanceof G.Polyline || o instanceof G.Polygon || o instanceof G.LatLngBounds) { return true; } return false; }
javascript
{ "resource": "" }
q25227
fromGeometryToJSON_
train
function fromGeometryToJSON_(geom) { function fromPointsToJSON(pts) { var arr = []; for (var i = 0, c = pts.length; i < c; i++) { arr.push('[' + pts[i][0] + ',' + pts[i][1] + ']'); } return '[' + arr.join(',') + ']'; } function fromLinesToJSON(lines) { var arr = []; for (var i = 0, c = lines.length; i < c; i++) { arr.push(fromPointsToJSON(lines[i])); } return '[' + arr.join(',') + ']'; } var json = '{'; if (geom.x) { json += 'x:' + geom.x + ',y:' + geom.y; } else if (geom.xmin) { json += 'xmin:' + geom.xmin + ',ymin:' + geom.ymin + ',xmax:' + geom.xmax + ',ymax:' + geom.ymax; } else if (geom.points) { json += 'points:' + fromPointsToJSON(geom.points); } else if (geom.paths) { json += 'paths:' + fromLinesToJSON(geom.paths); } else if (geom.rings) { json += 'rings:' + fromLinesToJSON(geom.rings); } json += '}'; return json; }
javascript
{ "resource": "" }
q25228
formatRequestString_
train
function formatRequestString_(o) { var ret; if (typeof o === 'object') { if (isArray_(o)) { ret = []; for (var i = 0, I = o.length; i < I; i++) { ret.push(formatRequestString_(o[i])); } return '[' + ret.join(',') + ']'; } else if (isOverlay_(o)) { return fromOverlaysToJSON_(o); } else if (o.toJSON) { return o.toJSON(); } else { ret = ''; for (var x in o) { if (o.hasOwnProperty(x)) { if (ret.length > 0) { ret += ', '; } ret += x + ':' + formatRequestString_(o[x]); } } return '{' + ret + '}'; } } return o.toString(); }
javascript
{ "resource": "" }
q25229
formatParams_
train
function formatParams_(params) { var query = ''; if (params) { params.f = params.f || 'json'; for (var x in params) { if (params.hasOwnProperty(x) && params[x] !== null && params[x] !== undefined) { // wont sent undefined. //jslint complaint about escape cause NN does not support it. var val = formatRequestString_(params[x]); query += (query.length > 0?'&':'')+(x + '=' + (escape ? escape(val) : encodeURIComponent(val))); } } } return query; }
javascript
{ "resource": "" }
q25230
callback_
train
function callback_(fn, obj) { var args = []; for (var i = 2, c = arguments.length; i < c; i++) { args.push(arguments[i]); } return function() { fn.apply(obj, args); }; }
javascript
{ "resource": "" }
q25231
setCopyrightInfo_
train
function setCopyrightInfo_(map) { var div = null; if (map) { var mvc = map.controls[G.ControlPosition.BOTTOM_RIGHT]; if (mvc) { for (var i = 0, c = mvc.getLength(); i < c; i++) { if (mvc.getAt(i).id === 'agsCopyrights') { div = mvc.getAt(i); break; } } } //var callback = callback_(setCopyrightInfo_, null, map); if (!div) { div = document.createElement('div'); div.style.fontFamily = 'Arial,sans-serif'; div.style.fontSize = '10px'; div.style.textAlign = 'right'; div.id = 'agsCopyrights'; map.controls[G.ControlPosition.BOTTOM_RIGHT].push(div); G.event.addListener(map, 'maptypeid_changed', function() { setCopyrightInfo_(map); }); } var ovs = map.agsOverlays; var cp = []; var svc, type; if (ovs) { for (var i = 0, c = ovs.getLength(); i < c; i++) { addCopyrightInfo_(cp, ovs.getAt(i).mapService_, map); } } var ovTypes = map.overlayMapTypes; if (ovTypes) { for (var i = 0, c = ovTypes.getLength(); i < c; i++) { type = ovTypes.getAt(i); if (type instanceof MapType) { for (var j = 0, cj = type.tileLayers_.length; j < cj; j++) { addCopyrightInfo_(cp, type.tileLayers_[j].mapService_, map); } } } } type = map.mapTypes.get(map.getMapTypeId()); if (type instanceof MapType) { for (var i = 0, c = type.tileLayers_.length; i < c; i++) { addCopyrightInfo_(cp, type.tileLayers_[i].mapService_, map); } if (type.negative) { div.style.color = '#ffffff'; } else { div.style.color = '#000000'; } } div.innerHTML = cp.join('<br/>'); } }
javascript
{ "resource": "" }
q25232
updateTOC
train
function updateTOC() { if (ov && svc.hasLoaded()) { var toc = ''; var scale = 591657527.591555 / (Math.pow(2, map.getZoom()));//591657527.591555 is the scale at level 0 var layers = svc.layers; for (var i = 0; i < layers.length; i++) { var layer = layers[i]; var inScale = layer.isInScale(scale); toc += '<div style="color:' + (inScale ? 'black' : 'gray') + '">'; if (layer.subLayerIds) { toc += layer.name + '(group)<br/>'; } else { if (layer.parentLayer) { toc += '&nbsp;&nbsp;&nbsp;&nbsp;'; } toc += '<input type="checkbox" id="layer' + layer.id + '"'; if (layer.visible) { toc += ' checked="checked"'; } if (!inScale || svc.singleFusedMapCache) { toc += ' disabled="disabled"'; } toc += ' onclick="setLayerVisibility()">' + layer.name + '<br/>'; } toc += '</div>'; } document.getElementById('toc').innerHTML = toc; } }
javascript
{ "resource": "" }
q25233
setLayerVisibility
train
function setLayerVisibility() { var layers = svc.layers; for (var i = 0; i < layers.length; i++) { var el = document.getElementById('layer' + layers[i].id); if (el) { layers[i].visible = (el.checked === true); } } ov.refresh(); }
javascript
{ "resource": "" }
q25234
mouseMove_
train
function mouseMove_(ev) { var e=ev||event; currentX_ = formerX_+((e.pageX||(e.clientX+document.body.scrollLeft+document.documentElement.scrollLeft))-formerMouseX_); currentY_ = formerY_+((e.pageY||(e.clientY+document.body.scrollTop+document.documentElement.scrollTop))-formerMouseY_); formerX_ = currentX_; formerY_ = currentY_; formerMouseX_ = e.pageX||(e.clientX+document.body.scrollLeft+document.documentElement.scrollLeft); formerMouseY_ = e.pageY||(e.clientY+document.body.scrollTop+document.documentElement.scrollTop); if (moving_) { moveTo_(currentX_,currentY_, preventDefault_); event_.trigger(me, "drag", {mouseX: formerMouseX_, mouseY: formerMouseY_, startLeft: originalX_, startTop: originalY_, event:e}); } }
javascript
{ "resource": "" }
q25235
mouseDown_
train
function mouseDown_(ev) { var e=ev||event; setCursor_(true); event_.trigger(me, "mousedown", e); if (src.style.position !== "absolute") { src.style.position = "absolute"; return; } formerMouseX_ = e.pageX||(e.clientX+document.body.scrollLeft+document.documentElement.scrollLeft); formerMouseY_ = e.pageY||(e.clientY+document.body.scrollTop+document.documentElement.scrollTop); originalX_ = src.offsetLeft; originalY_ = src.offsetTop; formerX_ = originalX_; formerY_ = originalY_; mouseMoveEvent_ = event_.addDomListener(target_, "mousemove", mouseMove_); if (src.setCapture) { src.setCapture(); } if (e.preventDefault) { e.preventDefault(); e.stopPropagation(); } else { e.cancelBubble=true; e.returnValue=false; } moving_ = true; event_.trigger(me, "dragstart", {mouseX: formerMouseX_, mouseY: formerMouseY_, startLeft: originalX_, startTop: originalY_, event:e}); }
javascript
{ "resource": "" }
q25236
mouseUp_
train
function mouseUp_(ev) { var e=ev||event; if (moving_) { setCursor_(false); event_.removeListener(mouseMoveEvent_); if (src.releaseCapture) { src.releaseCapture(); } moving_ = false; event_.trigger(me, "dragend", {mouseX: formerMouseX_, mouseY: formerMouseY_, startLeft: originalX_, startTop: originalY_, event:e}); } currentX_ = currentY_ = null; event_.trigger(me, "mouseup", e); }
javascript
{ "resource": "" }
q25237
train
function (e) { e.returnValue = false; if (e.preventDefault) { e.preventDefault(); } if (!me.enableEventPropagation_) { cancelHandler(e); } }
javascript
{ "resource": "" }
q25238
isaTopLevelObject
train
function isaTopLevelObject($) {return ( ($.is("CONSTRUCTOR") && $.name.match(/^[A-Z][A-Za-z]+/)) || ($.is("FUNCTION") && $.name.match(/^[A-Z][A-Za-z]+/)) || $.comment.getTag("enum")[0] || $.comment.getTag("interface")[0] || $.isNamespace );}
javascript
{ "resource": "" }
q25239
isaSecondLevelObject
train
function isaSecondLevelObject ($) {return ( $.comment.getTag("property").length || ($.is("CONSTRUCTOR") && $.name.match(/^[A-Z][A-Za-z]+$/)) || ($.is("FUNCTION") && $.name.match(/^[a-z][A-Za-z]+$/)) || $.isConstant || ($.type == "Function" && $.is("OBJECT")) );}
javascript
{ "resource": "" }
q25240
Cluster
train
function Cluster(markerClusterer) { this.markerClusterer_ = markerClusterer; this.map_ = markerClusterer.getMap(); this.gridSize_ = markerClusterer.getGridSize(); this.minClusterSize_ = markerClusterer.getMinClusterSize(); this.averageCenter_ = markerClusterer.isAverageCenter(); this.center_ = null; this.markers_ = []; this.bounds_ = null; this.clusterIcon_ = new ClusterIcon(this, markerClusterer.getStyles(), markerClusterer.getGridSize()); }
javascript
{ "resource": "" }
q25241
ClusterIcon
train
function ClusterIcon(cluster, styles, opt_padding) { cluster.getMarkerClusterer().extend(ClusterIcon, google.maps.OverlayView); this.styles_ = styles; this.padding_ = opt_padding || 0; this.cluster_ = cluster; this.center_ = null; this.map_ = cluster.getMap(); this.div_ = null; this.sums_ = null; this.visible_ = false; this.setMap(this.map_); }
javascript
{ "resource": "" }
q25242
Cluster
train
function Cluster(mc) { this.markerClusterer_ = mc; this.map_ = mc.getMap(); this.gridSize_ = mc.getGridSize(); this.minClusterSize_ = mc.getMinimumClusterSize(); this.averageCenter_ = mc.getAverageCenter(); this.markers_ = []; this.center_ = null; this.bounds_ = null; this.clusterIcon_ = new ClusterIcon(this, mc.getStyles()); }
javascript
{ "resource": "" }
q25243
find
train
function find(q) { removeOverlays(); if (iw) iw.close(); document.getElementById('results').innerHTML = ''; var exact = document.getElementById('exact').checked; var params = { returnGeometry: true, searchText: q, contains: !exact, layerIds: [0, 2], // city, state searchFields: ["CITY_NAME", "NAME", "SYSTEM", "STATE_ABBR", "STATE_NAME"], sr: 4326 }; service.find(params, processFindResults); }
javascript
{ "resource": "" }
q25244
train
function (h) { var computedStyle; var bw = {}; if (document.defaultView && document.defaultView.getComputedStyle) { computedStyle = h.ownerDocument.defaultView.getComputedStyle(h, ""); if (computedStyle) { // The computed styles are always in pixel units (good!) bw.top = parseInt(computedStyle.borderTopWidth, 10) || 0; bw.bottom = parseInt(computedStyle.borderBottomWidth, 10) || 0; bw.left = parseInt(computedStyle.borderLeftWidth, 10) || 0; bw.right = parseInt(computedStyle.borderRightWidth, 10) || 0; return bw; } } else if (document.documentElement.currentStyle) { // MSIE if (h.currentStyle) { // The current styles may not be in pixel units so try to convert (bad!) bw.top = parseInt(toPixels(h.currentStyle.borderTopWidth), 10) || 0; bw.bottom = parseInt(toPixels(h.currentStyle.borderBottomWidth), 10) || 0; bw.left = parseInt(toPixels(h.currentStyle.borderLeftWidth), 10) || 0; bw.right = parseInt(toPixels(h.currentStyle.borderRightWidth), 10) || 0; return bw; } } // Shouldn't get this far for any modern browser bw.top = parseInt(h.style["border-top-width"], 10) || 0; bw.bottom = parseInt(h.style["border-bottom-width"], 10) || 0; bw.left = parseInt(h.style["border-left-width"], 10) || 0; bw.right = parseInt(h.style["border-right-width"], 10) || 0; return bw; }
javascript
{ "resource": "" }
q25245
train
function (e) { var posX = 0, posY = 0; e = e || window.event; if (typeof e.pageX !== "undefined") { posX = e.pageX; posY = e.pageY; } else if (typeof e.clientX !== "undefined") { // MSIE posX = e.clientX + scroll.x; posY = e.clientY + scroll.y; } return { left: posX, top: posY }; }
javascript
{ "resource": "" }
q25246
train
function (h) { var posX = h.offsetLeft; var posY = h.offsetTop; var parent = h.offsetParent; // Add offsets for all ancestors in the hierarchy while (parent !== null) { // Adjust for scrolling elements which may affect the map position. // // See http://www.howtocreate.co.uk/tutorials/javascript/browserspecific // // "...make sure that every element [on a Web page] with an overflow // of anything other than visible also has a position style set to // something other than the default static..." if (parent !== document.body && parent !== document.documentElement) { posX -= parent.scrollLeft; posY -= parent.scrollTop; } // See http://groups.google.com/group/google-maps-js-api-v3/browse_thread/thread/4cb86c0c1037a5e5 // Example: http://notebook.kulchenko.com/maps/gridmove var m = parent; // This is the "normal" way to get offset information: var moffx = m.offsetLeft; var moffy = m.offsetTop; // This covers those cases where a transform is used: if (!moffx && !moffy && window.getComputedStyle) { var matrix = document.defaultView.getComputedStyle(m, null).MozTransform || document.defaultView.getComputedStyle(m, null).WebkitTransform; if (matrix) { if (typeof matrix === "string") { var parms = matrix.split(","); moffx += parseInt(parms[4], 10) || 0; moffy += parseInt(parms[5], 10) || 0; } } } posX += moffx; posY += moffy; parent = parent.offsetParent; } return { left: posX, top: posY }; }
javascript
{ "resource": "" }
q25247
train
function (obj, vals) { if (obj && vals) { for (var x in vals) { if (vals.hasOwnProperty(x)) { obj[x] = vals[x]; } } } return obj; }
javascript
{ "resource": "" }
q25248
train
function (h, op) { if (typeof op !== "undefined") { h.style.opacity = op; } if (typeof h.style.opacity !== "undefined" && h.style.opacity !== "") { h.style.filter = "alpha(opacity=" + (h.style.opacity * 100) + ")"; } }
javascript
{ "resource": "" }
q25249
Touch
train
function Touch(target, identifier, pos, deltaX, deltaY) { deltaX = deltaX || 0; deltaY = deltaY || 0; this.identifier = identifier; this.target = target; this.clientX = pos.clientX + deltaX; this.clientY = pos.clientY + deltaY; this.screenX = pos.screenX + deltaX; this.screenY = pos.screenY + deltaY; this.pageX = pos.pageX + deltaX; this.pageY = pos.pageY + deltaY; }
javascript
{ "resource": "" }
q25250
fakeTouchSupport
train
function fakeTouchSupport() { var objs = [window, document.documentElement]; var props = ['ontouchstart', 'ontouchmove', 'ontouchcancel', 'ontouchend']; for(var o=0; o<objs.length; o++) { for(var p=0; p<props.length; p++) { if(objs[o] && objs[o][props[p]] == undefined) { objs[o][props[p]] = null; } } } }
javascript
{ "resource": "" }
q25251
hasTouchSupport
train
function hasTouchSupport() { return ("ontouchstart" in window) || // touch events (window.Modernizr && window.Modernizr.touch) || // modernizr (navigator.msMaxTouchPoints || navigator.maxTouchPoints) > 2; // pointer events }
javascript
{ "resource": "" }
q25252
getActiveTouches
train
function getActiveTouches(mouseEv, eventName) { // empty list if (mouseEv.type == 'mouseup') { return new TouchList(); } var touchList = createTouchList(mouseEv); if(isMultiTouch && mouseEv.type != 'mouseup' && eventName == 'touchend') { touchList.splice(1, 1); } return touchList; }
javascript
{ "resource": "" }
q25253
getChangedTouches
train
function getChangedTouches(mouseEv, eventName) { var touchList = createTouchList(mouseEv); // we only want to return the added/removed item on multitouch // which is the second pointer, so remove the first pointer from the touchList // // but when the mouseEv.type is mouseup, we want to send all touches because then // no new input will be possible if(isMultiTouch && mouseEv.type != 'mouseup' && (eventName == 'touchstart' || eventName == 'touchend')) { touchList.splice(0, 1); } return touchList; }
javascript
{ "resource": "" }
q25254
showTouches
train
function showTouches(ev) { var touch, i, el, styles; // first all visible touches for(i = 0; i < ev.touches.length; i++) { touch = ev.touches[i]; el = touchElements[touch.identifier]; if(!el) { el = touchElements[touch.identifier] = document.createElement("div"); document.body.appendChild(el); } styles = TouchEmulator.template(touch); for(var prop in styles) { el.style[prop] = styles[prop]; } } // remove all ended touches if(ev.type == 'touchend' || ev.type == 'touchcancel') { for(i = 0; i < ev.changedTouches.length; i++) { touch = ev.changedTouches[i]; el = touchElements[touch.identifier]; if(el) { el.parentNode.removeChild(el); delete touchElements[touch.identifier]; } } } }
javascript
{ "resource": "" }
q25255
make
train
function make (x, y, width, height) { return new Frame(x, y, width, height); }
javascript
{ "resource": "" }
q25256
clone
train
function clone (frame) { return make(frame.x, frame.y, frame.width, frame.height); }
javascript
{ "resource": "" }
q25257
intersection
train
function intersection (frame, otherFrame) { var x = Math.max(frame.x, otherFrame.x); var width = Math.min(frame.x + frame.width, otherFrame.x + otherFrame.width); var y = Math.max(frame.y, otherFrame.y); var height = Math.min(frame.y + frame.height, otherFrame.y + otherFrame.height); if (width >= x && height >= y) { return make(x, y, width - x, height - y); } return null; }
javascript
{ "resource": "" }
q25258
union
train
function union (frame, otherFrame) { var x1 = Math.min(frame.x, otherFrame.x); var x2 = Math.max(frame.x + frame.width, otherFrame.x + otherFrame.width); var y1 = Math.min(frame.y, otherFrame.y); var y2 = Math.max(frame.y + frame.height, otherFrame.y + otherFrame.height); return make(x1, y1, x2 - x1, y2 - y1); }
javascript
{ "resource": "" }
q25259
intersects
train
function intersects (frame, otherFrame) { return !(otherFrame.x > frame.x + frame.width || otherFrame.x + otherFrame.width < frame.x || otherFrame.y > frame.y + frame.height || otherFrame.y + otherFrame.height < frame.y); }
javascript
{ "resource": "" }
q25260
train
function (hash, data) { this.length++; this.elements[hash] = { hash: hash, // Helps identifying freq: 0, data: data }; }
javascript
{ "resource": "" }
q25261
train
function (src) { var image = _instancePool.get(src); if (!image) { // Awesome LRU image = new Img(src); if (_instancePool.length >= kInstancePoolLength) { _instancePool.popLeastUsed().destructor(); } _instancePool.push(image.getOriginalSrc(), image); } return image; }
javascript
{ "resource": "" }
q25262
drawGradient
train
function drawGradient(ctx, x1, y1, x2, y2, colorStops, x, y, width, height) { var grad; ctx.save(); grad = ctx.createLinearGradient(x1, y1, x2, y2); colorStops.forEach(function (colorStop) { grad.addColorStop(colorStop.position, colorStop.color); }); ctx.fillStyle = grad; ctx.fillRect(x, y, width, height); ctx.restore(); }
javascript
{ "resource": "" }
q25263
invalidateBackingStore
train
function invalidateBackingStore (id) { for (var i=0, len=_backingStores.length; i < len; i++) { if (_backingStores[i].id === id) { _backingStores.splice(i, 1); break; } } }
javascript
{ "resource": "" }
q25264
getBackingStoreAncestor
train
function getBackingStoreAncestor (layer) { while (layer) { if (layer.backingStoreId) { return layer; } layer = layer.parentLayer; } return null; }
javascript
{ "resource": "" }
q25265
layerContainsImage
train
function layerContainsImage (layer, imageUrl) { // Check the layer itself. if (layer.type === 'image' && layer.imageUrl === imageUrl) { return layer; } // Check the layer's children. if (layer.children) { for (var i=0, len=layer.children.length; i < len; i++) { if (layerContainsImage(layer.children[i], imageUrl)) { return layer.children[i]; } } } return false; }
javascript
{ "resource": "" }
q25266
layerContainsFontFace
train
function layerContainsFontFace (layer, fontFace) { // Check the layer itself. if (layer.type === 'text' && layer.fontFace && layer.fontFace.id === fontFace.id) { return layer; } // Check the layer's children. if (layer.children) { for (var i=0, len=layer.children.length; i < len; i++) { if (layerContainsFontFace(layer.children[i], fontFace)) { return layer.children[i]; } } } return false; }
javascript
{ "resource": "" }
q25267
handleImageLoad
train
function handleImageLoad (imageUrl) { _backingStores.forEach(function (backingStore) { if (layerContainsImage(backingStore.layer, imageUrl)) { invalidateBackingStore(backingStore.id); } }); }
javascript
{ "resource": "" }
q25268
handleFontLoad
train
function handleFontLoad (fontFace) { _backingStores.forEach(function (backingStore) { if (layerContainsFontFace(backingStore.layer, fontFace)) { invalidateBackingStore(backingStore.id); } }); }
javascript
{ "resource": "" }
q25269
loadFont
train
function loadFont (fontFace, callback) { var defaultNode; var testNode; var checkFont; // See if we've previously loaded it. if (_loadedFonts[fontFace.id]) { return callback(null); } // See if we've previously failed to load it. if (_failedFonts[fontFace.id]) { return callback(_failedFonts[fontFace.id]); } // System font: assume already loaded. if (!fontFace.url) { return callback(null); } // Font load is already in progress: if (_pendingFonts[fontFace.id]) { _pendingFonts[fontFace.id].callbacks.push(callback); return; } // Create the test <span>'s for measuring. defaultNode = createTestNode('Helvetica', fontFace.attributes); testNode = createTestNode(fontFace.family, fontFace.attributes); document.body.appendChild(testNode); document.body.appendChild(defaultNode); _pendingFonts[fontFace.id] = { startTime: Date.now(), defaultNode: defaultNode, testNode: testNode, callbacks: [callback] }; // Font watcher checkFont = function () { var currWidth = testNode.getBoundingClientRect().width; var defaultWidth = defaultNode.getBoundingClientRect().width; var loaded = currWidth !== defaultWidth; if (loaded) { handleFontLoad(fontFace, null); } else { // Timeout? if (Date.now() - _pendingFonts[fontFace.id].startTime >= kFontLoadTimeout) { handleFontLoad(fontFace, true); } else { requestAnimationFrame(checkFont); } } }; // Start watching checkFont(); }
javascript
{ "resource": "" }
q25270
layoutNode
train
function layoutNode (root) { var rootNode = createNode(root); computeLayout(rootNode); walkNode(rootNode); return rootNode; }
javascript
{ "resource": "" }
q25271
train
function (object) { if (typeof HTMLElement === 'object') { return object instanceof HTMLElement; } else { return object && typeof object === 'object' && 'nodeType' in object && object.nodeType === 1 && typeof object.nodeName === 'string'; } }
javascript
{ "resource": "" }
q25272
Plugin
train
function Plugin(option) { return this.each(function () { var $this = $(this); var options = typeof option == 'object' && option; if (this == window || this == document || $this.is('body')) { Parallax.configure(options); } else if (!$this.data('px.parallax')) { options = $.extend({}, $this.data(), options); $this.data('px.parallax', new Parallax(this, options)); } else if (typeof option == 'object') { $.extend($this.data('px.parallax'), options); } if (typeof option == 'string') { if(option == 'destroy'){ Parallax.destroy(this); }else{ Parallax[option](); } } }); }
javascript
{ "resource": "" }
q25273
train
async function(filename, compress) { const data = await readFile(filename + (compress ? ".gz" : "")); const content = compress ? await gunzip(data) : data; return JSON.parse(content.toString()); }
javascript
{ "resource": "" }
q25274
train
async function(filename, compress, result) { const content = JSON.stringify(result); const data = compress ? await gzip(content) : content; return await writeFile(filename + (compress ? ".gz" : ""), data); }
javascript
{ "resource": "" }
q25275
train
function(source, identifier, options) { const hash = crypto.createHash("md4"); const contents = JSON.stringify({ source, options, identifier }); hash.update(contents); return hash.digest("hex") + ".json"; }
javascript
{ "resource": "" }
q25276
train
async function(directory, params) { const { source, options = {}, cacheIdentifier, cacheDirectory, cacheCompression, } = params; const file = path.join(directory, filename(source, cacheIdentifier, options)); try { // No errors mean that the file was previously cached // we just need to return it return await read(file, cacheCompression); } catch (err) {} const fallback = typeof cacheDirectory !== "string" && directory !== os.tmpdir(); // Make sure the directory exists. try { await mkdirp(directory); } catch (err) { if (fallback) { return handleCache(os.tmpdir(), params); } throw err; } // Otherwise just transform the file // return it to the user asap and write it in cache const result = await transform(source, options); try { await write(file, cacheCompression, result); } catch (err) { if (fallback) { // Fallback to tmpdir if node_modules folder not writable return handleCache(os.tmpdir(), params); } throw err; } return result; }
javascript
{ "resource": "" }
q25277
train
function (renderer, camera) { var viewport = renderer.viewport; var dpr = viewport.devicePixelRatio || renderer.getDevicePixelRatio(); var width = viewport.width * dpr; var height = viewport.height * dpr; var offset = this._haltonSequence[this._frame % this._haltonSequence.length]; var translationMat = new Matrix4(); translationMat.array[12] = (offset[0] * 2.0 - 1.0) / width; translationMat.array[13] = (offset[1] * 2.0 - 1.0) / height; Matrix4.mul(camera.projectionMatrix, translationMat, camera.projectionMatrix); Matrix4.invert(camera.invProjectionMatrix, camera.projectionMatrix); }
javascript
{ "resource": "" }
q25278
intersectEdge
train
function intersectEdge(x0, y0, x1, y1, x, y) { if ((y > y0 && y > y1) || (y < y0 && y < y1)) { return -Infinity; } // Ignore horizontal line if (y1 === y0) { return -Infinity; } var dir = y1 < y0 ? 1 : -1; var t = (y - y0) / (y1 - y0); // Avoid winding error when intersection point is the connect point of two line of polygon if (t === 1 || t === 0) { dir = y1 < y0 ? 0.5 : -0.5; } var x_ = t * (x1 - x0) + x0; return x_; }
javascript
{ "resource": "" }
q25279
train
function (texture) { var pixels = texture.pixels; var width = texture.width; var height = texture.height; function fetchPixel(x, y, rg) { x = Math.max(Math.min(x, width - 1), 0); y = Math.max(Math.min(y, height - 1), 0); var idx = (y * (width - 1) + x) * 4; if (pixels[idx + 3] === 0) { return false; } rg[0] = pixels[idx]; rg[1] = pixels[idx + 1]; return true; } function addPixel(a, b, out) { out[0] = a[0] + b[0]; out[1] = a[1] + b[1]; } var center = [], left = [], right = [], top = [], bottom = []; var weight = 0; for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var idx = (y * (width - 1) + x) * 4; if (pixels[idx + 3] === 0) { weight = center[0] = center[1] = 0; if (fetchPixel(x - 1, y, left)) { weight++; addPixel(left, center, center); } if (fetchPixel(x + 1, y, right)) { weight++; addPixel(right, center, center); } if (fetchPixel(x, y - 1, top)) { weight++; addPixel(top, center, center); } if (fetchPixel(x, y + 1, bottom)) { weight++; addPixel(bottom, center, center); } center[0] /= weight; center[1] /= weight; // PENDING If overwrite. bilinear interpolation. pixels[idx] = center[0]; pixels[idx + 1] = center[1]; } pixels[idx + 3] = 1; } } }
javascript
{ "resource": "" }
q25280
train
function (el, width, height) { // FIXME Text element not consider textAlign and textVerticalAlign. // TODO, inner text, shadow var rect = el.getBoundingRect(); // FIXME aspect ratio if (width == null) { width = rect.width; } if (height == null) { height = rect.height; } width *= this.dpr; height *= this.dpr; this._fitElement(el, width, height); // var aspect = el.scale[1] / el.scale[0]; // Adjust aspect ratio to make the text more clearly // FIXME If height > width, width is useless ? // width = height * aspect; // el.position[0] *= aspect; // el.scale[0] = el.scale[1]; var x = this._x; var y = this._y; var canvasWidth = this.width * this.dpr; var canvasHeight = this.height * this.dpr; var gap = this.gap; if (x + width + gap > canvasWidth) { // Change a new row x = this._x = 0; y += this._rowHeight + gap; this._y = y; // Reset row height this._rowHeight = 0; } this._x += width + gap; this._rowHeight = Math.max(this._rowHeight, height); if (y + height + gap > canvasHeight) { // There is no space anymore return null; } // Shift the el el.position[0] += this.offsetX * this.dpr + x; el.position[1] += this.offsetY * this.dpr + y; this._zr.add(el); var coordsOffset = [ this.offsetX / this.width, this.offsetY / this.height ]; var coords = [ [x / canvasWidth + coordsOffset[0], y / canvasHeight + coordsOffset[1]], [(x + width) / canvasWidth + coordsOffset[0], (y + height) / canvasHeight + coordsOffset[1]] ]; return coords; }
javascript
{ "resource": "" }
q25281
train
function (el, spriteWidth, spriteHeight) { // TODO, inner text, shadow var rect = el.getBoundingRect(); var scaleX = spriteWidth / rect.width; var scaleY = spriteHeight / rect.height; el.position = [-rect.x * scaleX, -rect.y * scaleY]; el.scale = [scaleX, scaleY]; el.update(); }
javascript
{ "resource": "" }
q25282
train
function () { for (var i = 0; i < this._textureAtlasNodes.length; i++) { this._textureAtlasNodes[i].clear(); } this._currentNodeIdx = 0; this._zr.clear(); this._coords = {}; }
javascript
{ "resource": "" }
q25283
train
function () { var dpr = this._dpr; return [this._nodeWidth / this._canvas.width * dpr, this._nodeHeight / this._canvas.height * dpr]; }
javascript
{ "resource": "" }
q25284
train
function (idx) { var polygons = this._triangulationResults[idx - this._startIndex]; var sideVertexCount = 0; var sideTriangleCount = 0; for (var i = 0; i < polygons.length; i++) { sideVertexCount += polygons[i].points.length / 3; sideTriangleCount += polygons[i].indices.length / 3; } var vertexCount = sideVertexCount * 2 + sideVertexCount * 4; var triangleCount = sideTriangleCount * 2 + sideVertexCount * 2; return { vertexCount: vertexCount, triangleCount: triangleCount }; }
javascript
{ "resource": "" }
q25285
getIncludePath
train
function getIncludePath(path, options) { var includePath; var filePath; var views = options.views; // Abs path if (path.charAt(0) == '/') { includePath = exports.resolveInclude(path.replace(/^\/*/,''), options.root || '/', true); } // Relative paths else { // Look relative to a passed filename first if (options.filename) { filePath = exports.resolveInclude(path, options.filename); if (fs.existsSync(filePath)) { includePath = filePath; } } // Then look in any views directories if (!includePath) { if (Array.isArray(views) && views.some(function (v) { filePath = exports.resolveInclude(path, v, true); return fs.existsSync(filePath); })) { includePath = filePath; } } if (!includePath) { throw new Error('Could not find the include file "' + options.escapeFunction(path) + '"'); } } return includePath; }
javascript
{ "resource": "" }
q25286
rethrow
train
function rethrow(err, str, flnm, lineno, esc){ var lines = str.split('\n'); var start = Math.max(lineno - 3, 0); var end = Math.min(lines.length, lineno + 3); var filename = esc(flnm); // eslint-disable-line // Error context var context = lines.slice(start, end).map(function (line, i){ var curr = i + start + 1; return (curr == lineno ? ' >> ' : ' ') + curr + '| ' + line; }).join('\n'); // Alter exception message err.path = filename; err.message = (filename || 'ejs') + ':' + lineno + '\n' + context + '\n\n' + err.message; throw err; }
javascript
{ "resource": "" }
q25287
normalizeSourceSet
train
function normalizeSourceSet(data) { var sourceSet = data.srcSet || data.srcset; if (Array.isArray(sourceSet)) { return sourceSet.join(); } return sourceSet; }
javascript
{ "resource": "" }
q25288
generateCSS
train
function generateCSS(selector, styleTypes, stringHandlers, useImportant) { var merged = styleTypes.reduce(_util.recursiveMerge); var declarations = {}; var mediaQueries = {}; var pseudoStyles = {}; Object.keys(merged).forEach(function (key) { if (key[0] === ':') { pseudoStyles[key] = merged[key]; } else if (key[0] === '@') { mediaQueries[key] = merged[key]; } else { declarations[key] = merged[key]; } }); return generateCSSRuleset(selector, declarations, stringHandlers, useImportant) + Object.keys(pseudoStyles).map(function (pseudoSelector) { return generateCSSRuleset(selector + pseudoSelector, pseudoStyles[pseudoSelector], stringHandlers, useImportant); }).join("") + Object.keys(mediaQueries).map(function (mediaQuery) { var ruleset = generateCSS(selector, [mediaQueries[mediaQuery]], stringHandlers, useImportant); return mediaQuery + '{' + ruleset + '}'; }).join(""); }
javascript
{ "resource": "" }
q25289
generateCSSRuleset
train
function generateCSSRuleset(selector, declarations, stringHandlers, useImportant) { var handledDeclarations = runStringHandlers(declarations, stringHandlers); var prefixedDeclarations = (0, _inlineStylePrefixerStatic2['default'])(handledDeclarations); var prefixedRules = (0, _util.flatten)((0, _util.objectToPairs)(prefixedDeclarations).map(function (_ref) { var _ref2 = _slicedToArray(_ref, 2); var key = _ref2[0]; var value = _ref2[1]; if (Array.isArray(value)) { var _ret = (function () { // inline-style-prefix-all returns an array when there should be // multiple rules, we will flatten to single rules var prefixedValues = []; var unprefixedValues = []; value.forEach(function (v) { if (v.indexOf('-') === 0) { prefixedValues.push(v); } else { unprefixedValues.push(v); } }); prefixedValues.sort(); unprefixedValues.sort(); return { v: prefixedValues.concat(unprefixedValues).map(function (v) { return [key, v]; }) }; })(); if (typeof _ret === 'object') return _ret.v; } return [[key, value]]; })); var rules = prefixedRules.map(function (_ref3) { var _ref32 = _slicedToArray(_ref3, 2); var key = _ref32[0]; var value = _ref32[1]; var stringValue = (0, _util.stringifyValue)(key, value); var ret = (0, _util.kebabifyStyleName)(key) + ':' + stringValue + ';'; return useImportant === false ? ret : (0, _util.importantify)(ret); }).join(""); if (rules) { return selector + '{' + rules + '}'; } else { return ""; } }
javascript
{ "resource": "" }
q25290
fontFamily
train
function fontFamily(val) { if (Array.isArray(val)) { return val.map(fontFamily).join(","); } else if (typeof val === "object") { injectStyleOnce(val.fontFamily, "@font-face", [val], false); return '"' + val.fontFamily + '"'; } else { return val; } }
javascript
{ "resource": "" }
q25291
animationName
train
function animationName(val) { if (typeof val !== "object") { return val; } // Generate a unique name based on the hash of the object. We can't // just use the hash because the name can't start with a number. // TODO(emily): this probably makes debugging hard, allow a custom // name? var name = 'keyframe_' + (0, _util.hashObject)(val); // Since keyframes need 3 layers of nesting, we use `generateCSS` to // build the inner layers and wrap it in `@keyframes` ourselves. var finalVal = '@keyframes ' + name + '{'; Object.keys(val).forEach(function (key) { finalVal += (0, _generate.generateCSS)(key, [val[key]], stringHandlers, false); }); finalVal += '}'; injectGeneratedCSSOnce(name, finalVal); return name; }
javascript
{ "resource": "" }
q25292
injectAndGetClassName
train
function injectAndGetClassName(useImportant, styleDefinitions) { // Filter out falsy values from the input, to allow for // `css(a, test && c)` var validDefinitions = styleDefinitions.filter(function (def) { return def; }); // Break if there aren't any valid styles. if (validDefinitions.length === 0) { return ""; } var className = validDefinitions.map(function (s) { return s._name; }).join("-o_O-"); injectStyleOnce(className, '.' + className, validDefinitions.map(function (d) { return d._definition; }), useImportant); return className; }
javascript
{ "resource": "" }
q25293
murmurhash2_32_gc
train
function murmurhash2_32_gc(str) { var l = str.length; var h = l; var i = 0; var k = undefined; while (l >= 4) { k = str.charCodeAt(i) & 0xff | (str.charCodeAt(++i) & 0xff) << 8 | (str.charCodeAt(++i) & 0xff) << 16 | (str.charCodeAt(++i) & 0xff) << 24; k = (k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0x5bd1e995 & 0xffff) << 16); k ^= k >>> 24; k = (k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0x5bd1e995 & 0xffff) << 16); h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16) ^ k; l -= 4; ++i; } switch (l) { case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16; case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8; case 1: h ^= str.charCodeAt(i) & 0xff; h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16); } h ^= h >>> 13; h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16); h ^= h >>> 15; return (h >>> 0).toString(36); }
javascript
{ "resource": "" }
q25294
flush
train
function flush() { while (index < queue.length) { var currentIndex = index; // Advance the index before calling the task. This ensures that we will // begin flushing on the next task the task throws an error. index = index + 1; queue[currentIndex].call(); // Prevent leaking memory for long chains of recursive calls to `asap`. // If we call `asap` within tasks scheduled by `asap`, the queue will // grow, but to avoid an O(n) walk for every task we execute, we don't // shift tasks off the queue after they have been executed. // Instead, we periodically shift 1024 tasks off the queue. if (index > capacity) { // Manually shift all values starting at the index back to the // beginning of the queue. for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) { queue[scan] = queue[scan + index]; } queue.length -= index; index = 0; } } queue.length = 0; index = 0; flushing = false; }
javascript
{ "resource": "" }
q25295
makeRequestCallFromMutationObserver
train
function makeRequestCallFromMutationObserver(callback) { var toggle = 1; var observer = new BrowserMutationObserver(callback); var node = document.createTextNode(""); observer.observe(node, {characterData: true}); return function requestCall() { toggle = -toggle; node.data = toggle; }; }
javascript
{ "resource": "" }
q25296
makeRequestCallFromTimer
train
function makeRequestCallFromTimer(callback) { return function requestCall() { // We dispatch a timeout with a specified delay of 0 for engines that // can reliably accommodate that request. This will usually be snapped // to a 4 milisecond delay, but once we're flushing, there's no delay // between events. var timeoutHandle = setTimeout(handleTimer, 0); // However, since this timer gets frequently dropped in Firefox // workers, we enlist an interval handle that will try to fire // an event 20 times per second until it succeeds. var intervalHandle = setInterval(handleTimer, 50); function handleTimer() { // Whichever timer succeeds will cancel both timers and // execute the callback. clearTimeout(timeoutHandle); clearInterval(intervalHandle); callback(); } }; }
javascript
{ "resource": "" }
q25297
createMergedResultFunction
train
function createMergedResultFunction(one, two) { return function mergedResult() { var a = one.apply(this, arguments); var b = two.apply(this, arguments); if (a == null) { return b; } else if (b == null) { return a; } var c = {}; mergeIntoWithNoDuplicateKeys(c, a); mergeIntoWithNoDuplicateKeys(c, b); return c; }; }
javascript
{ "resource": "" }
q25298
createChainedFunction
train
function createChainedFunction(one, two) { return function chainedFunction() { one.apply(this, arguments); two.apply(this, arguments); }; }
javascript
{ "resource": "" }
q25299
prefixAll
train
function prefixAll(styles) { Object.keys(styles).forEach(function (property) { var value = styles[property]; if (value instanceof Object && !Array.isArray(value)) { // recurse through nested style objects styles[property] = prefixAll(value); } else { Object.keys(_prefixProps2.default).forEach(function (prefix) { var properties = _prefixProps2.default[prefix]; // add prefixes if needed if (properties[property]) { styles[prefix + (0, _capitalizeString2.default)(property)] = value; } }); } }); Object.keys(styles).forEach(function (property) { [].concat(styles[property]).forEach(function (value, index) { // resolve every special plugins plugins.forEach(function (plugin) { return assignStyles(styles, plugin(property, value)); }); }); }); return (0, _sortPrefixedStyle2.default)(styles); }
javascript
{ "resource": "" }