_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q33500
train
function (options, fileExtension) { var getOptionsKey = function (options, fileExtension) { for (var prop in options) { var _prop = prop.toLowerCase(); if ((options[_prop].hasOwnProperty('allowed_file_extensions') && options[_prop].allowed_file_extensions.indexOf(fileExtension) > -1) || (!options[_prop].hasOwnProperty('allowed_file_extensions') && _prop === fileExtension)) { return prop; } } return null; }; if (isNestedStructure(options)) { var optionsKey = getOptionsKey(options, fileExtension); return optionsKey !== null ? options[optionsKey]: {}; } return options; }
javascript
{ "resource": "" }
q33501
train
function (source, fileExtension, globalOptions, beautify) { var path = rcFile.for(this.resourcePath) , options = globalOptions || {}; if (globalOptions === null && typeof path === "string") { this.addDependency(path); options = JSON.parse(stripJsonComments(fs.readFileSync(path, "utf8"))); } return beautify(source, getOptionsForExtension(options, fileExtension)); }
javascript
{ "resource": "" }
q33502
train
function (source, fileExtension, globalOptions, beautify, callback) { var _this = this; if (globalOptions === null) { rcFile.for(this.resourcePath, function (err, path) { if (!err) { if (typeof path === "string") { _this.addDependency(path); fs.readFile(path, "utf8", function (err, file) { if (!err) { var options = getOptionsForExtension(JSON.parse(stripJsonComments(file)), fileExtension); callback(null, beautify(source, options)); } else { callback(err); } }); } else { callback(null, beautify(source, {})); } } else { callback(err); } }); } else { callback(null, beautify(source, getOptionsForExtension(globalOptions, fileExtension))); } }
javascript
{ "resource": "" }
q33503
_extract
train
function _extract(keyStr, dataObj) { var altkey, _subKey, _splitPoint, _found = false, dataValue = null, _queryParts = []; if (dataObj && typeof dataObj === 'object') { dataValue = Object.create(dataObj); _queryParts = keyStr.split(/[\-\_\.]/); //console.warn("INIT:", keyStr, _queryParts); // test whole query first if (keyStr in dataValue) { dataValue = dataValue[keyStr]; _queryParts.length = 0; _found = true; } // search from smallest to largest possible keys while(_queryParts.length) { _splitPoint = _queryParts.shift(); _subKey = keyStr.split(new RegExp('('+_splitPoint+')')).slice(0,2).join(""); if (_subKey in dataValue) { dataValue = dataValue[_subKey]; keyStr = keyStr.split(new RegExp('('+_subKey+'[\-\_\.])')).slice(2).join(""); _found = true; } else { _found = false; } //console.warn(_found, _subKey, dataValue); } if (!_found) { // alternate support for delimiters in place of spaces as a key altkey = keyStr.replace(/[\-\_\.]/,' '); if (altkey in dataObj) { dataValue = dataObj[altkey]; _found = true; } } } return _found ? dataValue : NaN; }
javascript
{ "resource": "" }
q33504
renderData
train
function renderData(textString, options, data, doSpecials) { var replacer = function replacer(match, $1, $2) { var extracted, dataValue, key = String($1 || '').trim(), defaultValue = String($2 || '').trim(); // literal bracket excaping via \[ text ] if(match.substr(0, 1) === "\\") { return match.substr(1); } if (options && typeof options === 'object' && options.strictKeys) { extracted = _extract(key, data); dataValue = !Number.isNaN(extracted) ? extracted : match; } else { extracted = _extract(key, data); dataValue = !Number.isNaN(extracted) ? extracted : defaultValue; } if (defaultValue) { if (null === dataValue || typeof dataValue === 'object' || typeof dataValue === 'function' ) { dataValue = ''; } } return String(dataValue) || String(defaultValue); }; var pattern = new RegExp('\\\\?\\[(?:\\s*([\\w\\-\\.]+)\\s*)(?:\\:([^\\[\\]]+))?\\]', 'g'); var spPattern = new RegExp('\\\\?\\[(?:\\s*(KEY|INDEX|VALUE)\\s*)(?:\\:([^\\[\\]]+))?\\]', 'g'); if(typeof data === 'object' && data !== null) { if (options && typeof options === 'object' && options.prefix) { pattern = new RegExp('\\\\?\\[(?:\\s*'+rxquote(String(options.prefix))+'[\\.\\-\\_]([\\w\\-\\.]+)\\s*)(?:\\:([^\\[\\]]+))?\\]', 'g'); } if (doSpecials) { textString = textString.replace(spPattern, replacer); } textString = textString.replace(pattern, replacer); } else { throw new Error('No data to render!'); } // clean any uncaught bracket-escape sequences return textString.replace(/(?:\\+)\[(.+)(?:\\+)\]/g, "[$1]").replace(/(?:\\+)\[(.+)(?:\\*)\]/g, "[$1]"); }
javascript
{ "resource": "" }
q33505
getOptions
train
function getOptions(opts) { var obj = Object.create(_options); obj = util._extend(obj, opts); return obj; }
javascript
{ "resource": "" }
q33506
getCurrentState
train
function getCurrentState(systemID, authOpts) { return authenticatedGet(SYSTEM_URL + systemID, authOpts).then(res => { const rels = res.data.relationships const partTasks = rels.partitions.data.map(p => getPartition(p.id, authOpts) ) const sensorIDs = rels.sensors.data.map(s => s.id) return Promise.all([ Promise.all(partTasks), getSensors(sensorIDs, authOpts) ]).then(partitionsAndSensors => { const [partitions, sensors] = partitionsAndSensors return { id: res.data.id, attributes: res.data.attributes, partitions: partitions.map(p => p.data), sensors: sensors.data, relationships: rels } }) }) }
javascript
{ "resource": "" }
q33507
getSensors
train
function getSensors(sensorIDs, authOpts) { if (!Array.isArray(sensorIDs)) sensorIDs = [sensorIDs] const query = sensorIDs.map(id => `ids%5B%5D=${id}`).join('&') const url = `${SENSORS_URL}?${query}` return authenticatedGet(url, authOpts) }
javascript
{ "resource": "" }
q33508
train
function(key, defaultValue) { var value = window.localStorage.getItem(key); return value ? JSON.parse(value) : defaultValue; }
javascript
{ "resource": "" }
q33509
writeConfig
train
function writeConfig(filePath, data, fileFormat) { if (!filePath || !data) { throw new Error('No file/data to save!'); } const ext = rgxExt.exec(filePath) || []; const format = fileFormat || ext[1]; if (format === 'yaml' || format === 'yml') { return writeFileSync(filePath, yaml.safeDump(data), { encoding: 'utf8' }); } return outputJSONSync(filePath, data, { spaces: 2 }); }
javascript
{ "resource": "" }
q33510
readConfig
train
function readConfig(globPattern, fileFormat) { const filepath = findConfigFile(globPattern); if (!filepath) { this.settings = {}; return; } const ext = rgxExt.exec(filepath) || []; const format = fileFormat || ext[1]; const settings = (format === 'yaml' || format === 'yml') ? yaml.safeLoad(readFileSync(filepath, 'utf8')) : readJSONSync(filepath); this.filepath = filepath; this.settings = settings; }
javascript
{ "resource": "" }
q33511
createXMLHTTPObject
train
function createXMLHTTPObject () { var xmlhttp = false for (var i = 0; i < XMLHttpFactories.length; i++) { try { xmlhttp = XMLHttpFactories[i]() } catch (e) { continue } break } return xmlhttp }
javascript
{ "resource": "" }
q33512
optionString
train
function optionString(options) { return Object.keys(options).map(function (key) { var value = options[key]; if (value === null) { return '-' + key; } else if (typeof value === 'number') { value += ''; } else if (typeof value === 'string') { value = '"' + value.replace(/"/g, '\\"') + '"'; } return '-' + key + '=' + value.replace(/`/g, ''); }).join(' '); }
javascript
{ "resource": "" }
q33513
randomString
train
function randomString() { var str = '', length = 32; while (length--) { str += String.fromCharCode(Math.random() * 26 | 97); } return str; }
javascript
{ "resource": "" }
q33514
train
function() { var element = this.element, template = this.template, offset = element.offset(), width = element.outerWidth(), height = element.outerHeight(), position = this.options.position, alignment = this.options.alignment, styles = {}, self = this; template.show(); // Place the template switch (position) { case 'bottom': styles.top = offset.top + height; break; case 'right': styles.left = offset.left + width; break; case 'top': styles.top = offset.top - template.outerHeight(); break; case 'left': styles.left = offset.left - template.outerWidth(); break; } // Align the template arrow switch (alignment) { case 'left': styles.left = offset.left; break; case 'right': styles.left = offset.left + width - template.outerWidth(); break; } template.css(styles); }
javascript
{ "resource": "" }
q33515
train
function(view, delay) { var self = this; var raiseAfterShowHours = false; var raiseAfterShowMinutes = false; if (view === 'hours') { raiseCallback(this.options.beforeShowHours); raiseAfterShowHours = true; } if (view === 'minutes') { raiseCallback(this.options.beforeShowMinutes); raiseAfterShowMinutes = true; } var isHours = view === 'hours', nextView = isHours ? this.hoursView : this.minutesView, hideView = isHours ? this.minutesView : this.hoursView; this.currentView = view; this._checkTimeLimits(); this.hoursLabel.toggleClass('jqclockpicker-active', isHours); this.minutesLabel.toggleClass('jqclockpicker-active', !isHours); // Let's make transitions hideView.addClass('jqclockpicker-dial-out'); nextView.css('visibility', 'visible').removeClass('jqclockpicker-dial-out'); // Reset clock hand this.resetClock(delay); // After transitions ended clearTimeout(this.toggleViewTimer); this.toggleViewTimer = setTimeout(function() { hideView.css('visibility', 'hidden'); }, duration); if (raiseAfterShowHours) { raiseCallback(this.options.afterShowHours); } if (raiseAfterShowMinutes) { raiseCallback(this.options.afterShowMinutes); } }
javascript
{ "resource": "" }
q33516
train
function(delay) { var view = this.currentView, value = this[view], isHours = view === 'hours', unit = Math.PI / (isHours ? 6 : 30), radian = value * unit, radius = isHours && value > 0 && value < 13 ? innerRadius : outerRadius, x = Math.sin(radian) * radius, y = - Math.cos(radian) * radius, self = this; if (svgSupported && delay) { self.canvas.addClass('jqclockpicker-canvas-out'); setTimeout(function() { self.canvas.removeClass('jqclockpicker-canvas-out'); self.setHand(x, y); }, delay); } else { this.setHand(x, y); } }
javascript
{ "resource": "" }
q33517
train
function(timeObject) { this.hours = timeObject.hours; this.minutes = timeObject.minutes; this.amOrPm = timeObject.amOrPm; this._checkTimeLimits(); this._updateLabels(); this.resetClock(); }
javascript
{ "resource": "" }
q33518
train
function(str, methodDec, methodName, method, methodsMap, options){ var methodValue = getMethodValue(methodDec, methodName, method, methodsMap, options); if(str === methodDec) return methodValue; return str.replace(methodDec, function(){ return methodValue; }); }
javascript
{ "resource": "" }
q33519
renderNode
train
function renderNode(node, children = []) { [...children].forEach(child => { if (child && child.tag) { node.ele(child.tag, child.props); renderNode(node, child.children); node.end(); } else { node.text(child); } }); }
javascript
{ "resource": "" }
q33520
initialize
train
function initialize(server, callback) { source = new Backend(server, options); source.initialize(callback); }
javascript
{ "resource": "" }
q33521
replacementForNode
train
function replacementForNode (node) { var rule = this.rules.forNode(node) var content = process.call(this, node) var whitespace = node.flankingWhitespace if (whitespace.leading || whitespace.trailing) content = content.trim() return ( whitespace.leading + rule.replacement(content, node, this.options) + whitespace.trailing ) }
javascript
{ "resource": "" }
q33522
separatingNewlines
train
function separatingNewlines (output, replacement) { var newlines = [ output.match(trailingNewLinesRegExp)[0], replacement.match(leadingNewLinesRegExp)[0] ].sort() var maxNewlines = newlines[newlines.length - 1] return maxNewlines.length < 2 ? maxNewlines : '\n\n' }
javascript
{ "resource": "" }
q33523
quadratic_distance
train
function quadratic_distance(a, b, c, dpa, dpb, orientation) { var ab = new Array(3); var ac = new Array(3); var dab2 = 0.0; for(var i=0; i<3; ++i) { ab[i] = b[i] - a[i]; dab2 += ab[i] * ab[i]; ac[i] = c[i] - a[i]; } if(dab2 < EPSILON) { return 1e30; } //Transform c into triangle coordinate system var dab = Math.sqrt(dab2); var s = 1.0 / dab; var c0 = 0.0; for(var i=0; i<3; ++i) { ab[i] *= s; c0 += ab[i] * ac[i]; } var c1 = 0.0; for(var i=0; i<3; ++i) { c1 += Math.pow(ac[i] - c0 * ab[i], 2); } c1 = Math.sqrt(c1); //Compute center of distance field var dpa2 = dpa*dpa; var dpb2 = dpb*dpb; var p0 = (dpa2 - dpb2 + dab2) / (2.0 * dab); var p1 = dpa2 - p0*p0; if(p1 < 0.0) { return 1e30; } p1 = Math.sqrt(p1); if(orientation < 0) { p1 *= -1; } //Compute new distance bound var d = Math.sqrt(Math.pow(c0 - p0, 2) + Math.pow(c1 - p1, 2)); //Return min return d; }
javascript
{ "resource": "" }
q33524
geodesic_distance
train
function geodesic_distance(cells, positions, p, max_distance, tolerance, stars) { if(typeof(max_distance) === "undefined") { max_distance = Number.POSITIVE_INFINITY } if(typeof(tolerance) === "undefined") { tolerance = 1e-4 } if(typeof(dual) === "undefined") { stars = top.dual(cells, positions.length) } //First, run Dijkstra's algorithm to get an initial bound on the distance from each vertex // to the base point just using edge lengths var distances = dijkstra(p, stars, cells, positions, max_distance); //Then refine distances to acceptable threshold refine_distances(p, distances, positions, stars, cells, max_distance, tolerance); return distances; }
javascript
{ "resource": "" }
q33525
walk
train
function walk(node, output, previousNode) { // tag name validator.checkTagName(node, output) // attrs: id/class/style/if/repeat/append/event/attr var attrs = node.attrs || [] attrs.forEach(function switchAttr(attr) { var name = attr.name var value = attr.value var locationInfo = {line: 1, column: 1} if (node.__location) { locationInfo = { line: node.__location.line, column: node.__location.col } } switch (name) { case 'id': validator.checkId(value, output) break case 'class': validator.checkClass(value, output) break case 'style': validator.checkStyle(value, output, locationInfo) break case 'if': validator.checkIf(value, output) break case 'else': previousNode && previousNode.attrs.forEach(function (attr) { if (attr.name === 'if') { validator.checkIf(attr.value, output, true) } }) break case 'repeat': validator.checkRepeat(value, output) break case 'append': validator.checkAppend(value, output) break default: if (name.match(/^on/)) { validator.checkEvent(name, value, output) } else { validator.checkAttr(name, value, output, node.tagName, locationInfo) } } }) // children var originResult = output.result var childNodes = node.childNodes if (childNodes && childNodes.length) { var previous // FIXME: `parse5` has no previous sibling element information childNodes.forEach(function (child, i) { if (i > 0) { previous = childNodes[i - 1] } if (child.nodeName.match(/^#/)) { // special rules for text content in <text> if (child.nodeName === '#text' && child.value.trim()) { var tempResult = output.result output.result = originResult validator.checkAttr('value', child.value, output) output.result = tempResult } return } var childResult = {} output.result = childResult originResult.children = originResult.children || [] originResult.children.push(childResult) walk(child, output, previous) }) } output.result = originResult }
javascript
{ "resource": "" }
q33526
Cobertura
train
function Cobertura(runner) { var jade = require('jade') jade.doctypes.cobertura = '<!DOCTYPE coverage SYSTEM "http://cobertura.sourceforge.net/xml/coverage-03.dtd">' var file = __dirname + '/templates/cobertura.jade', str = fs.readFileSync(file, 'utf8'), fn = jade.compile(str, { filename: file }), self = this JSONCov.call(this, runner, false) runner.on('end', function(){ self.cov.src = __dirname.split('node_modules')[0] process.stdout.write(fn({ cov: self.cov })) }) }
javascript
{ "resource": "" }
q33527
deepReduce
train
function deepReduce(obj, reducer, reduced, path, thisArg) { if (reduced === void 0) { reduced = {}; } if (path === void 0) { path = ''; } if (thisArg === void 0) { thisArg = {}; } var pathArr = path === '' ? [] : path.split('.'); var root = obj; // keep value of root object, for recursion if (pathArr.length) { // called with path, traverse to that path for (var _i = 0, pathArr_1 = pathArr; _i < pathArr_1.length; _i++) { var key = pathArr_1[_i]; obj = obj[key]; if (obj === undefined) { throw new Error("Path " + path + " not found in object."); } } } for (var key in obj) { if (!obj.hasOwnProperty(key)) { continue; } pathArr.push(key); path = pathArr.join('.'); var value = obj[key]; reduced = reducer.call(thisArg, reduced, value, path, root); if (typeof value === 'object') { reduced = deepReduce(root, reducer, reduced, path, thisArg); } pathArr.pop(); } return reduced; }
javascript
{ "resource": "" }
q33528
evaluateID
train
function evaluateID(sub, element) { var id = element.id; return id && id.indexOf(sub) === 0; }
javascript
{ "resource": "" }
q33529
removeA
train
function removeA(arr) { var what, a = arguments, L = a.length, ax; while (L > 1 && arr.length) { what = a[--L]; while ((ax = arr.indexOf(what)) !== -1) { arr.splice(ax, 1); } } return arr; }
javascript
{ "resource": "" }
q33530
countWords
train
function countWords(s) { s = s.replace(/(^\s*)|(\s*$)/gi, ""); //exclude start and end white-space s = s.replace(/[ ]{2,}/gi, " "); //2 or more space to 1 s = s.replace(/\n /, "\n"); // exclude newline with a start spacing return s.split(" ").length; }
javascript
{ "resource": "" }
q33531
train
function(needle) { // Per spec, the way to identify NaN is that it is not equal to itself var findNaN = needle !== needle; var indexOf; if (!findNaN && typeof Array.prototype.indexOf === "function") { indexOf = Array.prototype.indexOf; } else { indexOf = function(needle) { var i = -1, index = -1; for (i = 0; i < this.length; i++) { var item = this[i]; if ((findNaN && item !== item) || item === needle) { index = i; break; } } return index; }; } return indexOf.call(this, needle) > -1; }
javascript
{ "resource": "" }
q33532
BreakpointController
train
function BreakpointController(options) { if (!(this instanceof BreakpointController)) { return new BreakpointController(options); } Emitter.mixin(this); var breakpointStream = BreakpointStream.create(options.breakpoints, { throttleMs: options.throttleMs, debounceMs: options.debounceMs }); var activeBreakpoints = {}; var self = this; Stream.onValue(breakpointStream, function(e) { activeBreakpoints[e[0]] = e[1]; var namedState = e[1] ? 'enter' : 'exit'; self.trigger('breakpoint', [e[0], namedState]); self.trigger('breakpoint:' + e[0], [e[0], namedState]); }); this.getActiveBreakpoints = function getActiveBreakpoints() { var isActive = Util.compose(Util.isTrue, Util.get(activeBreakpoints)); return Util.select(isActive, Util.objectKeys(activeBreakpoints)); }; }
javascript
{ "resource": "" }
q33533
train
function(x, y) { var array = this.getAllData(x, y); return array && array.length ? array[0] : undefined; }
javascript
{ "resource": "" }
q33534
train
function(x, y) { var maskX = this._getMaskX(x); var maskY = this._getMaskY(y); var key = this._getIndexKey(maskX, maskY); return this._dataIndex[key]; }
javascript
{ "resource": "" }
q33535
train
function(x, y, options) { var maskX = this._getMaskX(x); var maskY = this._getMaskY(y); var key = this._getIndexKey(maskX, maskY); return this._addDataToIndex(key, options); }
javascript
{ "resource": "" }
q33536
evaluateReactID
train
function evaluateReactID(sub, element) { var id = element.getAttribute && element.getAttribute('data-reactid'); return id && id.indexOf(sub) > -1; }
javascript
{ "resource": "" }
q33537
checkTagName
train
function checkTagName(node, output) { var result = output.result var deps = output.deps var log = output.log var tagName = node.tagName var childNodes = node.childNodes || [] var location = node.__location || {} // alias if (TAG_NAME_ALIAS_MAP[tagName]) { if (tagName !== 'img') { // FIXME: `parse5` autofixes image to img silently log.push({ line: location.line || 1, column: location.col || 1, reason: 'NOTE: tag name `' + tagName + '` is autofixed to `' + TAG_NAME_ALIAS_MAP[tagName] + '`' }) } tagName = TAG_NAME_ALIAS_MAP[tagName] } if (tagName === 'component') { var indexOfIs = -1 if (node.attrs) { node.attrs.forEach(function (attr, index) { if (attr.name === 'is') { indexOfIs = index result.type = tagName = exp(attr.value) } }) } if (indexOfIs > -1) { node.attrs.splice(indexOfIs, 1) // delete `is` } else { result.type = tagName = 'container' log.push({ line: location.line || 1, column: location.col || 1, reason: 'WARNING: tag `component` should have an `is` attribute, otherwise it will be regarded as a `container`' }) } } else { result.type = tagName } // deps if (deps.indexOf(tagName) < 0 && typeof tagName === 'string') { // FIXME: improve `require` to bundle dynamic binding components deps.push(tagName) } // parent (no any rules yet) // child (noChild, textContent) if (NO_CHILD_TAG_NAME_LIST.indexOf(tagName) >= 0) { if (childNodes.length > 0) { log.push({ line: location.line || 1, column: location.col || 1, reason: 'ERROR: tag `' + tagName + '` should not have children' }) } } if (TEXT_CONTENT_TAG_NAME_LIST.indexOf(tagName) >= 0) { if (childNodes.length > 1 || (childNodes[0] && childNodes[0].nodeName !== '#text')) { log.push({ line: location.line || 1, column: location.col || 1, reason: 'ERROR: tag name `' + tagName + '` should just have one text node only' }) } } // default attr if (TAG_DEFAULT_ATTR_MAP[tagName]) { Object.keys(TAG_DEFAULT_ATTR_MAP[tagName]).forEach(function (attr) { if (attr !== 'append') { result.attr = result.attr || {} result.attr[attr] = TAG_DEFAULT_ATTR_MAP[tagName][attr] } else { result[attr] = TAG_DEFAULT_ATTR_MAP[tagName][attr] } }) } }
javascript
{ "resource": "" }
q33538
_parse
train
function _parse(content, options, callback) { if(typeof options == 'function') { callback = options; options.test = false; } var on = outcome.error(callback), warnings, window; step( /** * load it. */ function() { jsdom.env({ html: content, scripts: [ __dirname + "/jquery-1.5.js" ], done: this }); }, /** * set it. */ on.success(function(win) { window = win; _copyStyles(window); this(); }), /** * test it. */ on.success(function() { if(!options.test) { return this(); } test(window, {}, this); }), /** * clean it. */ on.success(function(warn) { warnings = warn; //strip stuff that cannot be processed window.$('script, link, style').remove(); if (!options.comments) { //strip comments - sometimes gets rendered window.$('*').contents().each(function(node) { if(this.nodeType == 8) { window.$(this).remove(); } }); } this(); }), /** * finish it. */ function() { callback(null, window.document.documentElement.innerHTML, warnings || []); } ); }
javascript
{ "resource": "" }
q33539
attachListener_
train
function attachListener_() { if (isListening) { return; } isListening = true; unsubFunc = Events.eventListener(target, eventName, function() { if (outputStream.closed) { detachListener_(); } else { Util.apply(boundEmit, arguments); } }); onClose(outputStream, detachListener_); }
javascript
{ "resource": "" }
q33540
attach_
train
function attach_() { var i = 0; var intervalId = setInterval(function() { if (outputStream.closed) { clearInterval(intervalId); } else { boundEmit(i++); } }, ms); }
javascript
{ "resource": "" }
q33541
ScrollController
train
function ScrollController(options) { if (!(this instanceof ScrollController)) { return new ScrollController(options); } Emitter.mixin(this); options = options || {}; var scrollStream = ScrollStream.create({ scrollTarget: options.scrollTarget }); Stream.onValue(scrollStream, Util.partial(this.trigger, 'scroll')); var scrollEndStream = Stream.debounce( Util.getOption(options.debounceMs, 200), scrollStream ); Stream.onValue(scrollEndStream, Util.partial(this.trigger, 'scrollEnd')); }
javascript
{ "resource": "" }
q33542
arrayToWeb
train
function arrayToWeb(arr) { return new ReadableStream({ start(controller) { for (var i = 0; i < arr.length; i++) { controller.enqueue(arr[i]); } controller.close(); } }); }
javascript
{ "resource": "" }
q33543
copyone
train
function copyone (name) { if (metadata !== undefined) { //3/11/18 by DW var val = metadata [name]; if ((val !== undefined) && (val != null)) { theOutline [name] = val; } } }
javascript
{ "resource": "" }
q33544
train
function(image, position, options) { this._drawOnCanvasContext(options, function(g) { this._setImageStyles(g, options); g.drawImage(image, position[0], position[1]); return true; }); }
javascript
{ "resource": "" }
q33545
train
function(polygon, options) { // Create new canvas where the polygon should be drawn this._drawOnCanvasContext(options, function(g) { options = options || {}; g.beginPath(); for (var i = 0; i < polygon.length; i++) { var ring = this._simplify(polygon[i]); if (ring && ring.length) { var clockwise = (i === 0); if (GeometryUtils.isClockwise(ring) !== !!clockwise) { ring.reverse(); } } this._trace(g, ring); } g.closePath(); this._setFillStyles(g, options); g.fill(); this._setStrokeStyles(g, options); g.stroke(); return true; }); }
javascript
{ "resource": "" }
q33546
train
function(coords) { var tolerance = this.options.tolerance || 0.8; var enableHighQuality = !!this.options.highQuality; var points = GeometryUtils.simplify(coords, tolerance, enableHighQuality); return points; }
javascript
{ "resource": "" }
q33547
train
function(g, options) { var compositeOperation = options.compositeOperation || options.composition || 'source-over'; g.globalCompositeOperation = compositeOperation;// g.fillStyle = options.fillColor || options.color; if (options.fillImage) { g.fillStyle = g.createPattern(options.fillImage, "repeat"); } g.globalAlpha = options.fillOpacity || options.opacity || 0; }
javascript
{ "resource": "" }
q33548
train
function(g, options) { var compositeOperation = options.compositeOperation || options.composition || 'source-over'; g.globalCompositeOperation = compositeOperation;// g.globalAlpha = options.stokeOpacity || options.lineOpacity || options.opacity || 0; g.strokeStyle = options.lineColor || options.color; g.lineWidth = options.lineWidth || options.width || 0; g.lineCap = options.lineCap || 'round'; // 'butt|round|square' g.lineJoin = options.lineJoin || 'round'; // 'miter|round|bevel' }
javascript
{ "resource": "" }
q33549
train
function(g, options) { var compositeOperation = options.compositeOperation || options.composition || 'source-over'; g.globalCompositeOperation = compositeOperation;// }
javascript
{ "resource": "" }
q33550
ElementVisibleController
train
function ElementVisibleController(elem, options) { if (!(this instanceof ElementVisibleController)) { return new ElementVisibleController(elem, options); } Emitter.mixin(this); options = options || {}; this.elem = elem; this.buffer = Util.getOption(options.buffer, 0); this.isVisible = false; this.rect = null; this.scrollTarget = options.scrollTarget; // Auto trigger if the last value on the stream is what we're looking for. var oldOn = this.on; this.on = function wrappedOn(eventName, callback, scope) { oldOn.apply(this, arguments); if (('enter' === eventName) && this.isVisible) { scope ? callback.call(scope) : callback(); } }; var sc = new ScrollController({ scrollTarget: this.scrollTarget }); sc.on('scroll', this.didScroll, this); sc.on('scrollEnd', this.recalculatePosition, this); Stream.onValue(ResizeStream.create(), Util.functionBind(this.didResize, this)); this.viewportRect = { height: window.innerHeight, top: 0 }; this.recalculateOffsets(); setTimeout(Util.functionBind(this.recalculateOffsets, this), 100); }
javascript
{ "resource": "" }
q33551
deserialize
train
function deserialize(phcstr) { if (typeof phcstr !== 'string' || phcstr === '') { throw new TypeError('pchstr must be a non-empty string'); } if (phcstr[0] !== '$') { throw new TypeError('pchstr must contain a $ as first char'); } const fields = phcstr.split('$'); // Remove first empty $ fields.shift(); // Parse Fields let maxf = 5; if (!versionRegex.test(fields[1])) maxf--; if (fields.length > maxf) { throw new TypeError( `pchstr contains too many fileds: ${fields.length}/${maxf}` ); } // Parse Identifier const id = fields.shift(); if (!idRegex.test(id)) { throw new TypeError(`id must satisfy ${idRegex}`); } let version; // Parse Version if (versionRegex.test(fields[0])) { version = parseInt(fields.shift().match(versionRegex)[1], 10); } let hash; let salt; if (b64Regex.test(fields[fields.length - 1])) { if (fields.length > 1 && b64Regex.test(fields[fields.length - 2])) { // Parse Hash hash = Buffer.from(fields.pop(), 'base64'); // Parse Salt salt = Buffer.from(fields.pop(), 'base64'); } else { // Parse Salt salt = Buffer.from(fields.pop(), 'base64'); } } // Parse Parameters let params; if (fields.length > 0) { const parstr = fields.pop(); params = keyValtoObj(parstr); if (!objectKeys(params).every(p => nameRegex.test(p))) { throw new TypeError(`params names must satisfy ${nameRegex}`); } const pv = objectValues(params); if (!pv.every(v => valueRegex.test(v))) { throw new TypeError(`params values must satisfy ${valueRegex}`); } const pk = objectKeys(params); // Convert Decimal Strings into Numbers pk.forEach(k => { params[k] = decimalRegex.test(params[k]) ? parseInt(params[k], 10) : params[k]; }); } if (fields.length > 0) { throw new TypeError(`pchstr contains unrecognized fileds: ${fields}`); } // Build the output object const phcobj = {id}; if (version) phcobj.version = version; if (params) phcobj.params = params; if (salt) phcobj.salt = salt; if (hash) phcobj.hash = hash; return phcobj; }
javascript
{ "resource": "" }
q33552
train
function(options){ var _this = this; this.handlers = {}; if(!options){ options = {}; } if(!options.redis){ options.redis = {}; } this.options = { id: options.id || shortId.generate(), autoConfig: options.autoConfig || false, dataExpiry: options.dataExpiry || 30, redis: { port: options.redis.port || 6379, host: options.redis.host || '127.0.0.1', redis: options.redis.options || {} } }; //Create redis clients this.redisSub = redis.createClient(this.options.redis.port, this.options.redis.host, this.options.redis.options); this.redis = redis.createClient(this.options.redis.port, this.options.redis.host, this.options.redis.options); this.redisInstant = redis.createClient(this.options.redis.port, this.options.redis.host, this.options.redis.options); //Attempt auto config if(this.options.autoConfig){ var config = ''; this.redis.config("GET", "notify-keyspace-events", function(err, data){ if(data){ config = data[1]; } if(config.indexOf('E') == -1){ config += 'E' } if(config.indexOf('x') == -1){ config += 'x' } _this.redis.config("SET", "notify-keyspace-events", config) }); } //Listen to key expiry notifications and handle events var expiryListener = new RedisEvent(this.redisSub, 'expired', /redular:(.+):(.+):(.+)/); expiryListener.defineHandler(function(key){ var clientId = key[1]; var eventName = key[2]; var eventId = key[3]; _this.redis.get('redular-data:' + clientId + ':' + eventName + ':' + eventId, function(err, data){ if(data){ data = JSON.parse(data); } if(clientId == _this.options.id || clientId == 'global'){ _this.handleEvent(eventName, data); } }); }); //Listen to instant events and handle them this.redisInstant.subscribe('redular:instant'); this.redisInstant.on('message', function(channel, message){ try{ var parsedMessage = JSON.parse(message); } catch (e){ throw e; } if(parsedMessage.client == _this.options.id || parsedMessage.client == 'global') { _this.handleEvent(parsedMessage.event, parsedMessage.data); } }); }
javascript
{ "resource": "" }
q33553
rewrite
train
function rewrite (raw) { var c = raw.charAt(0) var path = raw.slice(1) if (allowedKeywordsRE.test(path)) { return raw } else { path = path.indexOf('"') > -1 ? path.replace(restoreRE, restore) : path return c + 'this.' + path } }
javascript
{ "resource": "" }
q33554
parseExpression
train
function parseExpression (exp) { exp = exp.trim() var res = isSimplePath(exp) && exp.indexOf('[') < 0 // optimized super simple getter ? 'this.' + exp // dynamic getter : compileGetter(exp) return res }
javascript
{ "resource": "" }
q33555
isSimplePath
train
function isSimplePath (exp) { return pathTestRE.test(exp) && // don't treat true/false as paths !booleanLiteralRE.test(exp) && // Math constants e.g. Math.PI, Math.E etc. exp.slice(0, 5) !== 'Math.' }
javascript
{ "resource": "" }
q33556
PromisePool
train
function PromisePool(opts) { this._opts = { // Configuration options name: opts.name || 'pool', idleTimeoutMillis: opts.idleTimeoutMillis || 30000, reapInterval: opts.reapIntervalMillis || 1000, drainCheckInterval: opts.drainCheckIntervalMillis || 100, refreshIdle: ('refreshIdle' in opts) ? opts.refreshIdle : true, returnToHead: opts.returnToHead || false, max: parseInt(opts.max, 10), min: parseInt(opts.min, 10), // Client management methods. create: opts.create, destroy: opts.destroy, validate: opts.validate || function(){ return true; }, onRelease: opts.onRelease }; this._availableObjects = []; this._waitingClients = new PriorityQueue(opts.priorityRange || 1); this._count = 0; this._removeIdleScheduled = false; this._removeIdleTimer = null; this._draining = false; // Prepare a logger function. if (opts.log instanceof Function) { this._log = opts.log; } else if (opts.log) { this._log = _logger.bind(this); } else { this._log = function(){}; } // Clean up some of the inputs. this._validate = opts.validate || function(){ return true; }; this._opts.max = Math.max(isNaN(this._opts.max) ? 1 : this._opts.max, 1); this._opts.min = Math.min(isNaN(this._opts.min) ? 0 : this._opts.min, this._opts.max-1); // Finally, ensure a minimum number of connections right out of the gate. _ensureMinimum.call(this); }
javascript
{ "resource": "" }
q33557
_ensureMinimum
train
function _ensureMinimum() { // Nothing to do if draining. if (this._draining) { return Promise.resolve(); } var diff = this._opts.min - this._count + this.availableLength; var promises = []; for (var i = 0; i < diff; ++i) { promises.push(this.acquire(function(client){ return Promise.resolve(); })); } return Promise.all(promises).then(function(){}); }
javascript
{ "resource": "" }
q33558
_createResource
train
function _createResource() { this._log( util.format( 'PromisePool._createResource() - creating client - count=%d min=%d max=%d', this._count, this._opts.min, this._opts.max ), 'verbose' ); return Promise.resolve(this._opts.create()); }
javascript
{ "resource": "" }
q33559
_scheduleRemoveIdle
train
function _scheduleRemoveIdle(){ if (!this._removeIdleScheduled) { this._removeIdleScheduled = true; this._removeIdleTimer = setTimeout(_removeIdle.bind(this), this._opts.reapInterval); } }
javascript
{ "resource": "" }
q33560
_objFilter
train
function _objFilter(obj, eql) { return function(objWithTimeout){ return (eql ? (obj === objWithTimeout.obj) : (obj !== objWithTimeout.obj)); }; }
javascript
{ "resource": "" }
q33561
_requireDirAll
train
function _requireDirAll(originalModule, absDir, options) { var modules = {}; var files = []; try { files = fs.readdirSync(absDir); } catch (e) { if (options.throwNoDir) { throw e; } } for (var length=files.length, i=0; i<length; ++i) { var reqModule = {}; reqModule.filename = files[i]; // full filename without path reqModule.ext = path.extname(reqModule.filename); // file extension reqModule.base = path.basename(reqModule.filename, reqModule.ext); // filename without extension reqModule.filepath = path.join(absDir, reqModule.filename); // full filename with absolute path //console.log('reqModule:', reqModule); // If this is subdirectory, then descend recursively into it (excluding matching patter excludeDirs) if (fs.statSync(reqModule.filepath).isDirectory() && options.recursive && ! isExcludedDir(reqModule, options.excludeDirs) ) { // use filename (with extension) instead of base name (without extension) // to keep complete directory name for directories with '.', like 'dir.1.2.3' reqModule.name = reqModule.filename; // go recursively into subdirectory //if (typeof modules === 'undefined') { // modules = {}; //} modules[reqModule.name] = _requireDirAll(originalModule, reqModule.filepath, options); } else if ( ! isExcludedFileRe(reqModule, options.includeFiles) && !isExcludedFileParent(reqModule, originalModule)) { reqModule.name = reqModule.base; reqModule.exports = require(reqModule.filepath); if (options.map) { options.map(reqModule); } var source = reqModule.exports; var target = (reqModule.name === 'index' && options.indexAsParent) ? modules : modules && modules[ reqModule.name ]; var sourceIsObject = (typeof source === 'object'); var targetIsObject = (typeof target === 'object'); //var targetUnassigned = (typeof target === 'undefined'); if (sourceIsObject && targetIsObject) { //if (Object.assign) { // Object.assign(target, source); //} else { deepAssign(target, source); //} } else //if ( //(!sourceIsObject && !targetIsObject) || // if source and target both are not objects or... //(targetUnassigned) // if target is not yet assigned, we may assign any type to it //) { target = source; //} else { // console.log('!!!! ' + // ' source:', source, // ' target:', target, // '; sourceIsObject:', sourceIsObject, // '; targetIsObject:', targetIsObject, // '; targetUnassigned:', targetUnassigned, // ''); // throw 'Not possible to mix objects with scalar or array values: ' + // 'filepath: '+ reqModule.filepath + '; ' + // 'modules: '+ JSON.stringify(modules) + '; ' + // 'exports: '+ JSON.stringify(reqModule.exports) // ; } if (reqModule.name === 'index' && options.indexAsParent) { modules = target; } else { //if (typeof modules === 'undefined') { // modules = {}; //} modules[ reqModule.name ] = target; } } } return modules; }
javascript
{ "resource": "" }
q33562
create
train
function create(options) { options = options || {}; var scrollParent = (options.scrollTarget && options.scrollTarget.parentNode) || window; var oldScrollY; var scrollDirty = true; var scrollEventsStream = Stream.createFromEvents(scrollParent, 'scroll'); Stream.onValue(scrollEventsStream, function onScrollSetDirtyBit_() { scrollDirty = true; }); var rAF = Stream.createFromRAF(); var didChangeOnRAFStream = Stream.filter(function filterDirtyFramesFromRAF_() { if (!scrollDirty) { return false; } scrollDirty = false; var newScrollY = DOM.documentScrollY(scrollParent); if (oldScrollY !== newScrollY) { oldScrollY = newScrollY; return true; } return false; }, rAF); // It's going to space, will you just give it a second! Util.defer(Util.partial(Events.dispatchEvent, scrollParent, 'scroll'), 10); return Stream.map(function getWindowPosition_() { return oldScrollY; }, didChangeOnRAFStream); }
javascript
{ "resource": "" }
q33563
train
function(image, x, y, options) { var result = false; var data = options.data; if (!data) return result; var mask = this._getImageMask(image, options); var imageMaskWidth = this._getMaskX(image.width); var maskShiftX = this._getMaskX(x); var maskShiftY = this._getMaskY(y); for (var i = 0; i < mask.length; i++) { if (!mask[i]) continue; var maskX = maskShiftX + (i % imageMaskWidth); var maskY = maskShiftY + Math.floor(i / imageMaskWidth); var key = this._getIndexKey(maskX, maskY); this._addDataToIndex(key, options); result = true; } return result; }
javascript
{ "resource": "" }
q33564
train
function(image, options) { var index = options.imageMaskIndex || this.options.imageMaskIndex; if (!index) return; if (typeof index === 'function') { index = index(image, options); } return index; }
javascript
{ "resource": "" }
q33565
train
function(image) { var maskWidth = this._getMaskX(image.width); var maskHeight = this._getMaskY(image.height); var buf = this._getResizedImageBuffer(image, maskWidth, maskHeight); var mask = new Array(maskWidth * maskHeight); for (var y = 0; y < maskHeight; y++) { for (var x = 0; x < maskWidth; x++) { var idx = (y * maskWidth + x); var filled = this._checkFilledPixel(buf, idx); mask[idx] = filled ? 1 : 0; } } return mask; }
javascript
{ "resource": "" }
q33566
train
function(image, width, height) { var g; if (image.tagName === 'CANVAS' && image.width === width && image.height === height) { g = image.getContext('2d'); } else { var canvas = this._newCanvas(width, height); canvas.width = width; canvas.height = height; g = canvas.getContext('2d'); g.drawImage(image, 0, 0, width, height); } var data = g.getImageData(0, 0, width, height).data; return data; }
javascript
{ "resource": "" }
q33567
applyAspectRatioPadding
train
function applyAspectRatioPadding(image) { var ratioPadding = (image.knownDimensions[1] / image.knownDimensions[0]) * 100.0; DOM.setStyle(image.element, 'paddingBottom', ratioPadding + '%'); }
javascript
{ "resource": "" }
q33568
getBreakpointSizes
train
function getBreakpointSizes(element) { var breakpointString = element.getAttribute('data-breakpoints'); var knownSizes = Util.map(function(s) { return Util.parseInteger(s); }, breakpointString ? breakpointString.split(',') : []); if (knownSizes.length <= 0) { return [0]; } else { return Util.sortBy(knownSizes, function sortAscending(a, b) { return b - a; }); } }
javascript
{ "resource": "" }
q33569
update
train
function update(image) { if (image.lazyLoad) { return; } var rect = DOM.getRect(image.element); var foundBreakpoint; for (var i = 0; i < image.knownSizes.length; i++) { var s = image.knownSizes[i]; if (rect.width <= s) { foundBreakpoint = s; } else { break; } } if (!foundBreakpoint) { foundBreakpoint = image.knownSizes[0]; } if (foundBreakpoint !== image.currentBreakpoint || !image.hasRunOnce) { image.currentBreakpoint = foundBreakpoint; loadImageForBreakpoint(image, image.currentBreakpoint); } }
javascript
{ "resource": "" }
q33570
loadImageForBreakpoint
train
function loadImageForBreakpoint(image, s) { var alreadyLoaded = image.loadedSizes[s]; if ('undefined' !== typeof alreadyLoaded) { setImage(image, alreadyLoaded); } else { var img = new Image(); img.onload = function() { image.loadedSizes[s] = img; setImage(image, img); update(image); image.hasRunOnce = true; }; // If requesting retina fails img.onerror = function() { if (image.hasRetina && !image.hasLoadedFallback) { image.hasLoadedFallback = true; var path = image.getPath(image, s, false); if (path) { img.src = path; } } else { image.trigger('error', img); } }; var path = image.getPath(image, s, image.hasRetina); if (path) { img.src = path; } } }
javascript
{ "resource": "" }
q33571
setImage
train
function setImage(image, img) { if (!image.hasLoaded) { image.hasLoaded = true; setTimeout(function() { image.element.className += ' loaded'; }, 100); } image.trigger('load', img); if (image.element.tagName.toLowerCase() === 'img') { return setImageTag(image, img); } else { return setDivTag(image, img); } }
javascript
{ "resource": "" }
q33572
setDivTag
train
function setDivTag(image, img) { var setElemStyle = DOM.setStyle(image.element); setElemStyle('backgroundImage', 'url(' + img.src + ')'); if (image.preserveAspectRatio) { var w, h; if (image.knownDimensions) { w = image.knownDimensions[0]; h = image.knownDimensions[1]; } else { w = img.width; h = img.height; } setElemStyle('backgroundSize', 'cover'); if (image.isFlexible) { setElemStyle('paddingBottom', ((h / w) * 100.0) + '%'); } else { setElemStyle('width', w + 'px'); setElemStyle('height', h + 'px'); } } }
javascript
{ "resource": "" }
q33573
getPath
train
function getPath(image, s, wantsRetina) { if (s === 0) { return image.src; } var parts = image.src.split('.'); var ext = parts.pop(); return parts.join('.') + '-' + s + (wantsRetina ? '@2x' : '') + '.' + ext; }
javascript
{ "resource": "" }
q33574
train
function(tableName, columnName, callback) { var cqlString = util.format('ALTER TABLE %s DROP %s', tableName, columnName); return this.runSql(cqlString, callback).nodeify(callback); }
javascript
{ "resource": "" }
q33575
train
function(callback) { var cqlString = 'SELECT * from migrations'; return this.runSql(cqlString) .then(function(data) { var sortedData = data.rows.map(function(item) { item.moment_time = moment(item.ran_on).valueOf(); return item }); // Order migration records in ascending order. return sortedData.sort(function(x,y) { if (x.moment_time > y.moment_time) return -1; if (x.moment_time < y.moment_time) return 1; return 0; }) }) .nodeify(callback); }
javascript
{ "resource": "" }
q33576
train
function (name, callback) { var formattedDate = name.split('-')[0].replace('/', ''); formattedDate = moment(formattedDate, 'YYYY-MM-DD HH:mm:ss'); formattedDate = moment(formattedDate).format('YYYY-MM-DD HH:mm:ss'); var command = util.format('INSERT INTO %s (name, ran_on) VALUES (\'%s\', \'%s\')', internals.migrationTable, name, formattedDate); return this.runSql(command).nodeify(callback); }
javascript
{ "resource": "" }
q33577
train
function(migrationName, callback) { var command = util.format('DELETE FROM %s where name = \'/%s\'', internals.migrationTable, migrationName); return this.runSql(command).nodeify(callback); }
javascript
{ "resource": "" }
q33578
train
function(callback) { var tableOptions = { 'name': 'varchar', 'ran_on': 'timestamp' }; var constraints = { 'primary_key': 'name' }; return this.createTable(internals.migrationTable, tableOptions, constraints).nodeify(callback); }
javascript
{ "resource": "" }
q33579
train
function(command, callback) { var self = this; return new Promise(function(resolve, reject) { var prCB = function(err, data) { if (err) { log.error(err.message); log.debug(command); } return (err ? reject('err') : resolve(data)); }; self.connection.execute(command, function(err, result) { prCB(err, result) }); }); }
javascript
{ "resource": "" }
q33580
_Markdown_formatOptions
train
function _Markdown_formatOptions(options) { function toHighlight(code, lang) { if (!lang && elm$core$Maybe$isJust(options.defaultHighlighting)) { lang = options.defaultHighlighting.a; } if ( typeof hljs !== "undefined" && lang && hljs.listLanguages().indexOf(lang) >= 0 ) { return hljs.highlight(lang, code, true).value; } return code; } var gfm = options.githubFlavored.a; return { highlight: toHighlight, gfm: gfm, tables: gfm && gfm.tables, breaks: gfm && gfm.breaks, sanitize: options.sanitize, smartypants: options.smartypants }; }
javascript
{ "resource": "" }
q33581
train
function(g, x, y, width, height, radius) { g.beginPath(); // a g.moveTo(x + width / 2, y); // b g.bezierCurveTo(// x + width / 2 + radius / 2, y, // x + width / 2 + radius, y + radius / 2, // x + width / 2 + radius, y + radius); // c g.bezierCurveTo( // x + width / 2 + radius, y + radius * 2, // x + width / 2, y + height / 2 + radius / 3, // x + width / 2, y + height); // d g.bezierCurveTo(// x + width / 2, y + height / 2 + radius / 3, // x + width / 2 - radius, y + radius * 2, // x + width / 2 - radius, y + radius); // e (a) g.bezierCurveTo(// x + width / 2 - radius, y + radius / 2, // x + width / 2 - radius / 2, y + 0, // x + width / 2, y + 0); g.closePath(); }
javascript
{ "resource": "" }
q33582
simplifyDouglasPeucker
train
function simplifyDouglasPeucker(points, sqTolerance) { var len = points.length; var MarkerArray = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; var markers = new MarkerArray(len); var first = 0; var last = len - 1; var stack = []; var newPoints = []; var i; var maxSqDist; var sqDist; var index; markers[first] = markers[last] = 1; while (last) { maxSqDist = 0; for (i = first + 1; i < last; i++) { sqDist = getSqSegDist(points[i], points[first], points[last]); if (sqDist > maxSqDist) { index = i; maxSqDist = sqDist; } } if (maxSqDist > sqTolerance) { markers[index] = 1; stack.push(first, index, index, last); } last = stack.pop(); first = stack.pop(); } for (i = 0; i < len; i++) { if (markers[i]) newPoints.push(points[i]); } return newPoints; }
javascript
{ "resource": "" }
q33583
simplify
train
function simplify(points, tolerance, highestQuality) { if (points.length <= 1) return points; var sqTolerance = tolerance !== undefined ? tolerance * tolerance : 1; points = highestQuality ? points : simplifyRadialDist(points, sqTolerance); points = simplifyDouglasPeucker(points, sqTolerance); return points; }
javascript
{ "resource": "" }
q33584
train
function(polygons, clipPolygon) { var result = []; for (var i = 0; i < polygons.length; i++) { var r = this.clipPolygon(polygons[i], clipPolygon); if (r && r.length) { result.push(r); } } return result; }
javascript
{ "resource": "" }
q33585
format
train
function format(node) { var ret = node.children.map(function (child) { var val = stringify(child) val = val.replace(/\"function\s*\(\)\s*{\s*return\s*(.*?)}\"/g, function ($0, $1) { return $1 }).replace(/\"([^,]*?)\":/g, function ($0, $1) { return $1 + ': ' }).replace(/(,)(\S)/g, function ($0, $1, $2) { return $1 + ' ' + $2 }).replace(/\"/g, '\'') var hasClassList = false val = val.replace(/classList:\s*\[(.*?)\]/g, function ($0, $1) { var styleMatch = val.match(/,\s*style:\s*({.*?})/) hasClassList = true var classArr = $1.trim().split(/\s*,\s*/).map(function (klass) { return '_s[' + klass + ']' }) classArr.unshift(styleMatch && styleMatch[1] ? styleMatch[1] : '{}') return 'style: (function () { var _s = this._css; return Object.assign(' + classArr.join(', ') + '); }).call(this)' }) if (hasClassList) { val = val.replace(/,\s*style:\s*({.*?})/g, '') } return val }); delete node.children node.attr = node.attr || {} node.attr.value = eval('(function () {return [' + ret.join(', ') + ']})') }
javascript
{ "resource": "" }
q33586
walkAndFormat
train
function walkAndFormat(node) { if (node) { if (node.append !== 'once') { if (node.children && node.children.length) { for (var i = 0, len = node.children.length; i < len; i++) { walkAndFormat(node.children[i]) } } } else { format(node) } } }
javascript
{ "resource": "" }
q33587
assetHashPath
train
function assetHashPath(url) { const parsedUrl = path.parse(url.getValue()); const asset = manifest.getAssetValue(parsedUrl.base); return compiler.types.String('url("' + asset + '")'); }
javascript
{ "resource": "" }
q33588
assetPath
train
function assetPath(url) { const parsedUrl = path.parse(url.getValue()); return compiler.types.String('url("' + parsedUrl.base + '")'); }
javascript
{ "resource": "" }
q33589
evaluateClassName
train
function evaluateClassName(sub, element) { var className = BLANK_STRING + element.className + BLANK_STRING; sub = BLANK_STRING + sub + BLANK_STRING; return className && className.indexOf(sub) > -1; }
javascript
{ "resource": "" }
q33590
train
function () { OptionsProcessor.apply(this, arguments) this._single = false this._cached = false this._resolved = true this._query = undefined this._fields = undefined this._options = { limit: 500 } }
javascript
{ "resource": "" }
q33591
indexOf
train
function indexOf(list, item) { if (NATIVE_ARRAY_INDEXOF) { return NATIVE_ARRAY_INDEXOF.call(list, item); } for (var i = 0; i < list.length; i++) { if (list[i] === item) { return i; } } return -1; }
javascript
{ "resource": "" }
q33592
throttle
train
function throttle(f, delay) { var timeoutId; var previous = 0; return function throttleExecute_() { var args = arguments; var now = +(new Date()); var remaining = delay - (now - previous); if (remaining <= 0) { clearTimeout(timeoutId); timeoutId = null; previous = now; f.apply(null, args); } else if (!timeoutId) { timeoutId = setTimeout(function() { previous = +(new Date()); timeoutId = null; f.apply(null, args); }, remaining); } }; }
javascript
{ "resource": "" }
q33593
debounce
train
function debounce(f, delay) { var timeoutId = null; return function debounceExecute_() { clearTimeout(timeoutId); var lastArgs = arguments; timeoutId = setTimeout(function() { timeoutId = null; f.apply(null, lastArgs); }, delay); }; }
javascript
{ "resource": "" }
q33594
forEach
train
function forEach(f, arr) { if (NATIVE_ARRAY_FOREACH) { if (arr) { NATIVE_ARRAY_FOREACH.call(arr, f); } return; } for (var i = 0; i < arr.length; i++) { f(arr[i], i, arr); } }
javascript
{ "resource": "" }
q33595
objectKeys
train
function objectKeys(obj) { if (!obj) { return null; } if (Object.keys) { return Object.keys(obj); } var out = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { out.push(key); } } return out; }
javascript
{ "resource": "" }
q33596
eq
train
function eq(a, b, aStack, bStack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). if (a === b) { return a !== 0 || 1 / a == 1 / b; } // A strict comparison is necessary because `null == undefined`. if (a == null || b == null) { return a === b; } // Compare `[[Class]]` names. var className = a.toString(); if (className != b.toString()) { return false; } switch (className) { // Strings, numbers, dates, and booleans are compared by value. case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `'5'` is // equivalent to `new String('5')`. return a == String(b); case '[object Number]': // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for // other numeric values. return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b); case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a == +b; // RegExps are compared by their source patterns and flags. case '[object RegExp]': return a.source == b.source && a.global == b.global && a.multiline == b.multiline && a.ignoreCase == b.ignoreCase; } if (typeof a != 'object' || typeof b != 'object') { return false; } // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted = require(ES 5.1 section 15.12.3, abstract operation `JO`. var length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (aStack[length] == a) { return bStack[length] == b; } } // Objects with different constructors are not equivalent, but `Object`s // = require(different frames are. var aCtor = a.constructor, bCtor = b.constructor; if (aCtor !== bCtor && !(isFunction(aCtor) && (aCtor instanceof aCtor) && isFunction(bCtor) && (bCtor instanceof bCtor)) && ('constructor' in a && 'constructor' in b)) { return false; } // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); var size = 0, result = true; // Recursively compare objects and arrays. if (className == '[object Array]') { // Compare array lengths to determine if a deep comparison is necessary. size = a.length; result = size == b.length; if (result) { // Deep compare the contents, ignoring non-numeric properties. while (size--) { if (!(result = eq(a[size], b[size], aStack, bStack))) { break; } } } } else { // Deep compare objects. for (var key in a) { if (has(a, key)) { // Count the expected number of properties. size++; // Deep compare each member. if (!(result = has(b, key) && eq(a[key], b[key], aStack, bStack))) { break; } } } // Ensure that both objects contain the same number of properties. if (result) { for (key in b) { if (has(b, key) && !(size--)) { break; } } result = !size; } } // Remove the first object = require(the stack of traversed objects. aStack.pop(); bStack.pop(); return result; }
javascript
{ "resource": "" }
q33597
functionBind
train
function functionBind(f, obj) { if (NATIVE_FUNCTION_BIND) { return NATIVE_FUNCTION_BIND.call(f, obj); } return function boundFunction_() { return f.apply(obj, arguments); }; }
javascript
{ "resource": "" }
q33598
partial
train
function partial(f /*, args*/) { var args = rest(arguments); if (NATIVE_FUNCTION_BIND) { args.unshift(undefined); return NATIVE_FUNCTION_BIND.apply(f, args); } return function partialExecute_() { var args2 = slice(arguments, 0); return f.apply(this, args.concat(args2)); }; }
javascript
{ "resource": "" }
q33599
train
function(options) { this.options = options || {}; if (typeof this.options.getGeometry === 'function') { this.getGeometry = this.options.getGeometry; } this.setData(this.options.data); }
javascript
{ "resource": "" }