_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q41700
getCssSelectorClasses
train
function getCssSelectorClasses(selector) { var list = [] var ast = cssSelector.parse(selector) visitRules(ast, function(ruleSet) { if (ruleSet.classNames) { list = list.concat(ruleSet.classNames) } }) return uniq(list) }
javascript
{ "resource": "" }
q41701
loadScript
train
function loadScript(url) { s = document.createElement('script'); s.src =url; document.body.appendChild(s); }
javascript
{ "resource": "" }
q41702
Texture
train
function Texture(context, options) { if (!(this instanceof Texture)) return new Texture(context, options); //sets up base Kami object.. BaseObject.call(this, context); /** * When a texture is created, we keep track of the arguments provided to * its constructor. On context loss and restore, these arguments are re-supplied * to the Texture, so as to re-create it in its correct form. * * This is mainly useful if you are procedurally creating textures and passing * their data directly (e.g. for generic lookup tables in a shader). For image * or media based textures, it would be better to use an AssetManager to manage * the asynchronous texture upload. * * Upon destroying a texture, a reference to this is also lost. * * @property managedArgs * @type {Object} the options given to the Texture constructor, or undefined */ this.managedArgs = options; /** * The WebGLTexture which backs this Texture object. This * can be used for low-level GL calls. * * @type {WebGLTexture} */ this.id = null; //initialized in create() /** * The target for this texture unit, i.e. TEXTURE_2D. Subclasses * should override the create() method to change this, for correct * usage with context restore. * * @property target * @type {GLenum} * @default gl.TEXTURE_2D */ this.target = this.context.gl.TEXTURE_2D; /** * The width of this texture, in pixels. * * @property width * @readOnly * @type {Number} the width */ this.width = 0; //initialized on texture upload /** * The height of this texture, in pixels. * * @property height * @readOnly * @type {Number} the height */ this.height = 0; //initialized on texture upload this.__shape = [0, 0]; /** * The S wrap parameter. * @property {GLenum} wrapS */ this.wrapS = Texture.DEFAULT_WRAP; /** * The T wrap parameter. * @property {GLenum} wrapT */ this.wrapT = Texture.DEFAULT_WRAP; /** * The minifcation filter. * @property {GLenum} minFilter */ this.minFilter = Texture.DEFAULT_FILTER; /** * The magnification filter. * @property {GLenum} magFilter */ this.magFilter = Texture.DEFAULT_FILTER; //manage if we're dealing with a kami-context this.context.addManagedObject(this); this.create(); }
javascript
{ "resource": "" }
q41703
train
function(options) { var gl = this.gl; //If no options is provided... this method does nothing. if (!options) return; // width, height, format, dataType, data, genMipmaps //If 'src' is provided, try to load the image from a path... if (options.src && typeof options.src==="string") { var img = new Image(); var path = options.src; var crossOrigin = options.crossOrigin; var successCB = typeof options.onLoad === "function" ? options.onLoad : null; var failCB = typeof options.onError === "function" ? options.onError : null; var genMipmaps = options.genMipmaps; var self = this; //If you try to render a texture that is not yet "renderable" (i.e. the //async load hasn't completed yet, which is always the case in Chrome since requestAnimationFrame //fires before img.onload), WebGL will throw us errors. So instead we will just upload some //dummy data until the texture load is complete. Users can disable this with the global flag. if (Texture.USE_DUMMY_1x1_DATA) { self.uploadData(1, 1); this.width = this.height = 0; } img.crossOrigin = crossOrigin; img.onload = function(ev) { self.uploadImage(img, undefined, undefined, genMipmaps); if (typeof successCB === "function") successCB.call(self, ev, self); } img.onerror = function(ev) { if (genMipmaps) //we still need to gen mipmaps on the 1x1 dummy gl.generateMipmap(gl.TEXTURE_2D); if (typeof failCB === "function") failCB.call(self, ev, self); } img.onabort = function(ev) { if (genMipmaps) gl.generateMipmap(gl.TEXTURE_2D); if (typeof failCB === "function") failCB.call(self, ev, self); } img.src = path; } //otherwise see if we have an 'image' specified else if (options.image) { this.uploadImage(options.image, options.format, options.dataType, options.data, options.genMipmaps); } //otherwise assume our regular list of width/height arguments are passed else { this.uploadData(options.width, options.height, options.format, options.dataType, options.data, options.genMipmaps); } }
javascript
{ "resource": "" }
q41704
train
function() { if (this.id && this.gl) this.gl.deleteTexture(this.id); if (this.context) this.context.removeManagedObject(this); this.width = this.height = 0; this.id = null; this.managedArgs = null; this.context = null; this.gl = null; }
javascript
{ "resource": "" }
q41705
train
function(s, t, ignoreBind) { //TODO: support R wrap mode if (s && t) { this.wrapS = s; this.wrapT = t; } else this.wrapS = this.wrapT = s; //enforce POT rules.. this._checkPOT(); if (!ignoreBind) this.bind(); var gl = this.gl; gl.texParameteri(this.target, gl.TEXTURE_WRAP_S, this.wrapS); gl.texParameteri(this.target, gl.TEXTURE_WRAP_T, this.wrapT); }
javascript
{ "resource": "" }
q41706
train
function(min, mag, ignoreBind) { if (min && mag) { this.minFilter = min; this.magFilter = mag; } else this.minFilter = this.magFilter = min; //enforce POT rules.. this._checkPOT(); if (!ignoreBind) this.bind(); var gl = this.gl; gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, this.minFilter); gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, this.magFilter); }
javascript
{ "resource": "" }
q41707
train
function(width, height, format, type, data, genMipmaps) { var gl = this.gl; format = format || gl.RGBA; type = type || gl.UNSIGNED_BYTE; data = data || null; //make sure falsey value is null for texImage2D this.width = (width || width==0) ? width : this.width; this.height = (height || height==0) ? height : this.height; this._checkPOT(); this.bind(); gl.texImage2D(this.target, 0, format, this.width, this.height, 0, format, type, data); if (genMipmaps) gl.generateMipmap(this.target); }
javascript
{ "resource": "" }
q41708
train
function(domObject, format, type, genMipmaps) { var gl = this.gl; format = format || gl.RGBA; type = type || gl.UNSIGNED_BYTE; this.width = domObject.width; this.height = domObject.height; this._checkPOT(); this.bind(); gl.texImage2D(this.target, 0, format, format, type, domObject); if (genMipmaps) gl.generateMipmap(this.target); }
javascript
{ "resource": "" }
q41709
train
function() { if (!Texture.FORCE_POT) { //If minFilter is anything but LINEAR or NEAREST //or if wrapS or wrapT are not CLAMP_TO_EDGE... var wrongFilter = (this.minFilter !== Texture.Filter.LINEAR && this.minFilter !== Texture.Filter.NEAREST); var wrongWrap = (this.wrapS !== Texture.Wrap.CLAMP_TO_EDGE || this.wrapT !== Texture.Wrap.CLAMP_TO_EDGE); if ( wrongFilter || wrongWrap ) { if (!isPowerOfTwo(this.width) || !isPowerOfTwo(this.height)) throw new Error(wrongFilter ? "Non-power-of-two textures cannot use mipmapping as filter" : "Non-power-of-two textures must use CLAMP_TO_EDGE as wrap"); } } }
javascript
{ "resource": "" }
q41710
ReportParameter
train
function ReportParameter(name, type, value) { this.parameterTypes = [ "string", "number", "boolean", "datetime", "date", "time" ]; this.name = name; this.type = type; this.value = value; this.dependsOn = null; //use when you need cascading values this.label = null; // display label this.displayControl = null; // display control }
javascript
{ "resource": "" }
q41711
sha2
train
function sha2(str) { var md = forge.md.sha256.create(); md.update(str); return md.digest().toHex() }
javascript
{ "resource": "" }
q41712
hashToInts
train
function hashToInts(hash) { var arr = [] var num = 4 for (var i = 0; i < 4; i++) { var part = hash.substr(i*8,8) var n = parseInt(part, 16) & 0x7fffffff arr.push(n) } return arr }
javascript
{ "resource": "" }
q41713
mnemonicToPubKey
train
function mnemonicToPubKey(str) { var m = new Mnemonic(str); var xpriv1 = m.toHDPrivateKey(); // no passphrase var xpub1 = xpriv1.hdPublicKey; return xpub1 }
javascript
{ "resource": "" }
q41714
webidAndPubKeyToAddress
train
function webidAndPubKeyToAddress(webid, pubKey, testnet) { if (typeof(pubKey) === 'string') { pubKey = new bitcore.HDPublicKey(pubKey) } var hash = sha2(webid) var ints = hashToInts(hash) var dep2 = pubKey.derive(ints[0]).derive(ints[1]).derive(ints[2]).derive(ints[3]) //console.log(dep2); if (testnet) { var address2 = new bitcore.Address(dep2.publicKey, bitcore.Networks.testnet) } else { var address2 = new bitcore.Address(dep2.publicKey) } //console.log(address1); //console.log(address2); return address2 }
javascript
{ "resource": "" }
q41715
webidAndPrivKeyToAddress
train
function webidAndPrivKeyToAddress(webid, privKey, testnet) { if (typeof(privKey) === 'string') { privKey = new bitcore.HDPrivateKey(privKey) } var hash = sha2(webid) var ints = hashToInts(hash) var dep2 = privKey.derive(ints[0]).derive(ints[1]).derive(ints[2]).derive(ints[3]) //console.log(dep2); if (testnet) { var address2 = dep2.privateKey } else { var address2 = dep2.privateKey } //console.log(address1); //console.log(address2); return address2 }
javascript
{ "resource": "" }
q41716
train
function(server, opts) { EventEmitter.call(this); this.server = server; this.wsprocessor = new WSProcessor(); this.tcpprocessor = new TCPProcessor(opts.closeMethod); this.id = 1; this.timeout = (opts.timeout || DEFAULT_TIMEOUT) * 1000; this.setNoDelay = opts.setNoDelay; if (!opts.ssl) { this.server.on('connection', this.newSocket.bind(this)); } else { this.server.on('secureConnection', this.newSocket.bind(this)); this.server.on('clientError', function(e, tlsSo) { logger.warn('an ssl error occured before handshake established: ', e); tlsSo.destroy(); }); } this.wsprocessor.on('connection', this.emit.bind(this, 'connection')); this.tcpprocessor.on('connection', this.emit.bind(this, 'connection')); this.state = ST_STARTED; }
javascript
{ "resource": "" }
q41717
Namespace
train
function Namespace(path, hex) { this.hex = !!hex this.keyEncoding = hex ? 'utf8' : 'binary' this.path = path this.buffer = bytewise.encode(path) this.prehooks = [] this.posthooks = [] }
javascript
{ "resource": "" }
q41718
csv
train
function csv(input, delimiter) { if (!input) return [] delimiter = delimiter || ',' var lines = toArray(input, /\r?\n/) var first = lines.shift() var header = toArray(first, delimiter) var data = lines.map(function(line) { var row = toArray(line, delimiter) return toObject(row, header) }) return data }
javascript
{ "resource": "" }
q41719
toArray
train
function toArray(line, delimiter) { var arr = line .split(delimiter) .filter(Boolean) return arr }
javascript
{ "resource": "" }
q41720
toObject
train
function toObject(row, header) { var obj = {} row.forEach(function(value, key) { obj[header[key]] = value }) return obj }
javascript
{ "resource": "" }
q41721
writeContractsFile
train
function writeContractsFile(contractsFilePath, contractsObject, callback) { // eslint-disable-line if (typeof contractsFilePath !== 'string') { return callback(); } if (utils.filenameExtension(contractsFilePath) !== 'json') { throw new Error('Your contracts output file must be a JSON file (i.e. --output ./contracts.json)'); } fs.writeFile(path.resolve(contractsFilePath), JSON.stringify(contractsObject), (writeContractsFileError) => { if (writeContractsFileError) { throw new Error(`while writting output JSON file ${contractsFilePath}: ${writeContractsFileError}`); } callback(); }); }
javascript
{ "resource": "" }
q41722
writeStatsFile
train
function writeStatsFile(statsFilePath, statsObject, callback) { // eslint-disable-line if (typeof statsFilePath !== 'string') { return callback(); } if (utils.filenameExtension(statsFilePath) !== 'json') { throw new Error('Your stats output file must be a JSON file (i.e. --stats ./stats.json)'); } fs.writeFile(path.resolve(statsFilePath), JSON.stringify(statsObject, null, 2), (writeStatsFileError) => { if (writeStatsFileError) { throw new Error(`while writting stats JSON file ${statsFilePath}: ${writeStatsFileError}`); } callback(); }); }
javascript
{ "resource": "" }
q41723
makeCycleReactDriver
train
function makeCycleReactDriver(element, querySelector) { if (typeof element === 'undefined') { throw Error('Missing or invalid react element'); } if (typeof querySelector !== 'string') { throw new Error('Missing or invalid querySelector'); } const source$ = new Rx.ReplaySubject(); const callback = (componentName) => (event) => { source$.next({ event, componentName, }); }; function cycleReactDriver(sink) { const tree = ( <CycleWrapper observable={sink} callback={callback}> {element} </CycleWrapper> ); ReactDOM.render(tree, document.querySelector(querySelector)); return { // Select function: use information passed in event to filter the stream then // map to the actual event. select: comp => source$.filter(e => e.componentName === comp.name).map(e => e.event), }; } cycleReactDriver.streamAdapter = RxJSAdapter; return cycleReactDriver; }
javascript
{ "resource": "" }
q41724
train
function (callback, source, dest) { compressor.compress( // Source can either be a file path or source code source, // Options { charset: 'utf8', type: 'js', nomunge: true, 'preserve-semi': true }, // Compressor callback function (error, data, extra) { if (error) { grunt.warn(error); return callback(); } if (extra) grunt.log.writeln(extra); grunt.file.write(dest, data); callback(); } ); }
javascript
{ "resource": "" }
q41725
train
function(task, pid) { this.task = task; this.pid = pid; this.failedCount = 0; this.buffer = ''; this.exitCode = -1; this.insertTag = true; }
javascript
{ "resource": "" }
q41726
get_db
train
function get_db (ent, done) { var folder = internals.makefolderpath(opts.folder, ent) var db = dbmap[folder] if (db) { return done(null, db) } internals.ensurefolder(folder, internals.error(done, function () { db = dbmap[folder] if (db) { return done(null, db) } try { db = dbmap[folder] = LevelQuery(Levelup(folder, opts)) db.query.use(JsonqueryEngine()) } catch (e) { db = dbmap[folder] if (db) { return done(null, db) } return done(e) } return done(null, db) })) }
javascript
{ "resource": "" }
q41727
crosshair
train
function crosshair(g) { var group = g.selectAll('g.data.top').data([change], function(d) { return d; }), groupEnter = group.enter(), dataEnter = groupEnter.append('g').attr('class', 'data top').style('display', 'none'); group.exit().remove(); dataEnter.append('path').attr('class', 'horizontal wire'); dataEnter.append('path').attr('class', 'vertical wire'); plot.annotation.append(dataEnter, xAnnotation, 'x'); plot.annotation.append(dataEnter, yAnnotation, 'y'); g.selectAll('rect').data([0]).enter().append('rect').style({ fill: 'none', 'pointer-events': 'all' }); crosshair.refresh(g); }
javascript
{ "resource": "" }
q41728
Component
train
function Component (props) { this._parent = null this._collector = { refs: [], components: [] } /** * > Contains all component properties and children. <br> * > Do not modify it directly, but recreate a new component using `cloneElement` instead * @type {object} * @category Properties */ this.props = props || {} /** * > HTMLElement used as "base" for the component instance. Can also be an array of elements if `template` return an array. * @type {(VNode|HTMLElement|array)} * @category Properties */ this.base = null /** * Set to true when component is mounted * @type {boolean} * @category Properties */ this.mounted = false }
javascript
{ "resource": "" }
q41729
Jusibe
train
function Jusibe(publicKey, accessToken) { if (!(publicKey || accessToken)) { throw new Error('Provide both Jusibe PUBLIC_KEY and ACCESS_TOKEN'); } if (!(this instanceof Jusibe)) { return new Jusibe(publicKey, accessToken); } this.options = { auth: { user: publicKey, pass: accessToken }, json: true }; }
javascript
{ "resource": "" }
q41730
train
function(opts){ //setup options this.opts = new ObjectManage({ username: '', password: '', domain: 'cdn.oose.io', prism: { host: null, port: 5971 } }) this.opts.$load(opts) //set properties this.api = {} this.authenticated = false this.connected = false this.session = {} }
javascript
{ "resource": "" }
q41731
ensureTimestamps
train
function ensureTimestamps(columns, allowSyncedAt) { var now = Date.now(); if (!allowSyncedAt || !columns.syncedAt) { columns.syncedAt = now; } if (!columns.createdAt) { // Take the value from the client, if present: columns.createdAt = columns.updatedAt; } }
javascript
{ "resource": "" }
q41732
_queryForTargetSessions
train
function _queryForTargetSessions(url, minDbSeq) { var where = { isConnected: true }; if (minDbSeq) { where.connectedAtDbSeq = { gt: minDbSeq }; } return Session.findAll({ where: where, attributes: [ 'sessionId', 'connectedAtDbSeq', ], include: [{ model: Route, where: { routeUrl: url, weight: { gt: 0 } }, attributes: [] }], group: '`Session`.`sessionId`', }, { raw: true }) .then(function(sessions) { var sessionIds = []; var dbSeq = -1; for (var i = 0; i < sessions.length; i++) { var session = sessions[i]; var sessionId = session['sessionId']; sessionIds.push(sessionId); dbSeq = Math.max(session['connectedAtDbSeq'], dbSeq); } return { sessionIds: sessionIds, dbSeq: dbSeq }; }) }
javascript
{ "resource": "" }
q41733
_filter
train
function _filter(data, schema) { if (typeof data !== 'object' || data === null || schema === null) { return data; } if (schema instanceof Array) { return _filterByArraySchema(data, schema); } if (typeof schema === 'object') { return _filterByObjectSchema(data, schema); } return data; }
javascript
{ "resource": "" }
q41734
_filterByArraySchema
train
function _filterByArraySchema(data, schema) { return Object .keys(data) .filter(function (key) { return !!~schema.indexOf(key); }) .reduce(function (memo, key) { memo[key] = data[key]; return memo; }, {}); }
javascript
{ "resource": "" }
q41735
_filterByObjectSchema
train
function _filterByObjectSchema(data, schema) { return Object .keys(data) .filter(function (key) { return schema.hasOwnProperty(key); }) .reduce(function (memo, key) { var value = data[key]; var schemaPart = schema[key]; if (typeof schemaPart === 'object') { memo[key] = _filter(value, schemaPart); } else { memo[key] = value; } return memo; }, {}); }
javascript
{ "resource": "" }
q41736
Fixed2DArray
train
function Fixed2DArray(rows, cols, defaultValue) { if(rows <= 0 || cols <= 0){ throw new Error('fixed-2d-array: Must have more then 0 rows and 0 columns.'); } this._width = cols; this._height = rows; this._grid = []; for (var i = 0; i < rows; i++) { this._grid[i] = []; for (var j = 0; j < cols; j++) { this._grid[i][j] = defaultValue; } } }
javascript
{ "resource": "" }
q41737
exec
train
function exec() { var actions = { commands: { init: { action: _init }, run : { action: _run } } }; cli.command(__dirname, actions); }
javascript
{ "resource": "" }
q41738
parse
train
function parse(content, options) { options = options || {}; options = defaults(options, { addEsprimaInfo: false, parseJsDocTags: true, hideJsDocTags: true, trim: true }); var comments = []; var ast = esprima.parse(content, { tolerant: true, comment: true, tokens: true, range: true, loc: true }).comments; for (var i = 0; i < ast.length; i++) { var node = ast[i]; var lines = node.value.replace(/\r\n/g,'\n').split('\n'); var comment = { start: node.loc.start.line, end: node.loc.end.line }; if (options.addEsprimaInfo) { comment.node = node; } comment.jsDoc = !!(lines[0] && lines[0].trim && '*' === lines[0].trim()); comment.lines = formatLines(lines, comment.jsDoc, options.trim); comment.tags = []; if (options.parseJsDocTags) { applyJsDocTags(comment, options.hideJsDocTags); if (options.hideJsDocTags) { comment.lines = arrayTrim(comment.lines); } } comments.push(comment); } return comments; }
javascript
{ "resource": "" }
q41739
formatLines
train
function formatLines(lines, jsDoc, trim) { jsDoc = undefined === jsDoc || true; trim = undefined === trim || true; lines = lines.slice(); for (var i = 0; i < lines.length; i++) { var line = lines[i] + ''; if (jsDoc) { line = line.replace(/^\s*\*/, ''); } if ('right' === trim) { line = line.replace(/\s+$/, ''); } else if (trim) { line = line.trim(); } lines[i] = line; } lines = arrayTrim(lines); return lines; }
javascript
{ "resource": "" }
q41740
applyJsDocTags
train
function applyJsDocTags(comment, removeTagLine) { removeTagLine = (undefined !== removeTagLine) ? removeTagLine : true; var lines = []; comment.tags = []; for (var i = 0; i < comment.lines.length; i++) { var line = comment.lines[i]; if ('@' === line.charAt(0)) { var spacePos = line.indexOf(' '); if (-1 === spacePos) { spacePos = line.length; } var tag = line.substr(1, spacePos).trim(); var value = line.substr(spacePos).trim(); comment.tags.push({ name: tag, value: value || true }); } else { lines.push(line); } } if (removeTagLine) { comment.lines = lines; } }
javascript
{ "resource": "" }
q41741
defaults
train
function defaults(object, options) { object = object || {}; for (var i in options) { if (undefined === object[i] && options.hasOwnProperty(i)) { object[i] = options[i]; } } return object; }
javascript
{ "resource": "" }
q41742
matter
train
function matter(str, opts) { str = formatString(str); opts = formatOptions(opts); var result = {src: str, data: null, body: str}; if (!str) { return result; } var strict = !opts.loose; var header = opts.delims[0]; var footer = opts.delims[1]; var dataStart, dataEnd; // Front matter must start from the first byte. if (str.substr(0, header.length) !== header || // Whether the delimiter is followed by a strange character. (!opts.loose && header.length < str.length && str[header.length] !== '\n' && str[header.length] === header[header.length-1]) || // Metadata and delimiters should be separated with linefeeds. (dataStart = str.indexOf('\n', header.length)) < 0 || (dataEnd = str.indexOf('\n' + footer, dataStart)) < 0) { return result; } var bodyStart = dataEnd + 1 + footer.length; // Whether the delimiter is followed by strange characters. if (strict && bodyStart < str.length) { if (str[bodyStart] !== '\n' && str[bodyStart] === footer[footer.length-1]) { return result; } while (bodyStart < str.length && str[bodyStart] !== '\n') { if (/^[^\s]$/.test(str[bodyStart])) { return result; } bodyStart++; } } // else: Tolerate the case that a linefeed is missing: <end-delimiter><body> if (str[bodyStart] === '\r') { bodyStart++; } if (str[bodyStart] === '\n') { bodyStart++; } var data; if (dataStart < dataEnd && (data = str.substr(dataStart, dataEnd - dataStart).trim())) { var lang = str.substr(header.length, dataStart - header.length) .trim().toLowerCase() || opts.lang; var parse; if (typeof opts.parsers === 'function') { parse = opts.parsers; } else if (opts.parsers != null && opts.parsers[lang]) { parse = opts.parsers[lang]; } else { parse = matter.parsers[lang]; } if (typeof parse === 'function') { result.data = parse(data, {loose: opts.loose}); } else { throw new Error(message('No parser found for the language: ' + lang)); } } result.body = result.body.substr(bodyStart); return result; }
javascript
{ "resource": "" }
q41743
train
function (classesSource) { this.e.log&&this.e.log('Importing core classes...','system'); var classesSource = classesSource||global.wns.coreClasses; var classBuilder = new process.wns.wnBuild(classesSource,this); this.setComponent('classBuilder',classBuilder); classBuilder.build(); return this; }
javascript
{ "resource": "" }
q41744
train
function () { var nmPath = this.modulePath + 'node_modules/'; var pkgJson; var pkgName; var pkgInfo; var packageList = {}; var validScript = /[\w|\W]+\.[js|coffee]+$/; if (fs.existsSync(nmPath)) { this.e.log&&this.e.log('Importing packages...','system'); var packages = fs.readdirSync(nmPath); for (p in packages) { try { if (packages[p].indexOf('wns')!==-1 && (packages[p].indexOf('pkg') !== -1 || packages[p].indexOf('package') !== -1)) { pkgName = packages[p]; pkgDir = nmPath + pkgName; pkgJson = pkgDir + '/package.json'; if (fs.existsSync(pkgJson)) { pkgInfo = JSON.parse(fs.readFileSync(pkgJson)); pkgInfo.require = pkgInfo.require||{}; Object.defineProperty(pkgInfo,'classes',{ value: {}, enumerable: false }) var files = fs.readdirSync(pkgDir); for (f in files) { var fileName = files[f].split('/').pop(); if (validScript.test(fileName)) { var className = fileName.split('.'); className.splice(-1); pkgInfo.classes[className] = pkgDir+'/'+fileName; } } packageList[pkgInfo.name]=pkgInfo; } } } catch (e) { console.error('Error on loading package `'+pkgName+"`.") throw e; } } } this.removeInvalidPackages(packageList); this.loadPackages(packageList); }
javascript
{ "resource": "" }
q41745
train
function (packageList) { if (!_.isObject(packageList)) return false; var pkgList = _.keys(packageList); var pkgRequire; var pkgName; var pkgInfo; var depName; var depVersion; var i=0; var valid; var error; while (pkgList.length > 0) { valid=true; error=[]; pkgName=pkgList[i]; pkgInfo=packageList[pkgName]; pkgRequire=pkgInfo.require; for (p in pkgRequire) { depName = p; depVersion = pkgRequire[p]; if (packageList[depName]==undefined) { error.push(depName+'@'+depVersion+' is not installed.'); continue; } if (depVersion!=="*" && packageList[depName].version!=depVersion) { error.push(depName+' needs to be '+depVersion); } } if (valid||error.length>0) { if (error.length>0) { delete packageList[pkgName]; for (e in error) self.e.log('Error on loading `'+pkgName+'`: '+error[e],'error'); } pkgList.splice(i,1); } i++; if (i>=pkgList.length) i=0; } }
javascript
{ "resource": "" }
q41746
train
function (packageList) { var classes; var className; var classSource; var classBuilder = this.getComponent('classBuilder'); for (p in packageList) { classes = packageList[p].classes; for (c in classes) { className = c; classBuilder.addSource(className,classes[c],true); } } classBuilder.load(); classBuilder.build(); }
javascript
{ "resource": "" }
q41747
train
function () { this.e.log&&this.e.log('Importing from config...','system'); var importConfig = this.getConfig('import'); var cb = this.getComponent('classBuilder'); var validScript = /[\w|\W]+\.[js|coffee]+$/; for (i in importConfig) { var path = this.modulePath+importConfig[i]; if (fs.existsSync(path)) { this.e.log&&this.e.log('Importing '+path+'...','system'); var classes = fs.readdirSync(path); for (c in classes) { if (!validScript.test(classes[c])) continue; var className = classes[c].split('.')[0]; cb.addSource(className,path+classes[c]); cb.classes[c]=cb.buildClass(className); } } } }
javascript
{ "resource": "" }
q41748
train
function () { for (c in this.c) { if (this.c[c].build && this.c[c].build.extend && this.c[c].build.extend.indexOf('wnActiveRecord')!=-1) { this.prepareModel(c); } } }
javascript
{ "resource": "" }
q41749
train
function (model) { var c = this.c, s = this; this.m[model]=function () { var modelClass = c[model]; return new modelClass({ autoInit: true }, s.c, s, s.db); }; }
javascript
{ "resource": "" }
q41750
train
function (file) { if (!_.isString(file)) return false; var file = file+''; this.e.log&&this.e.log('Loading module configuration from file: '+file,'system'); if (fs.statSync(file).isFile() && path.extname(file) == '.json') { var _data = (fs.readFileSync(file,'utf8').toString()) .replace(/\\/g,function () { return "\\"+arguments[0]; }) .replace(/\/\/.+?(?=\n|\r|$)|\/\*[\s\S]+?\*\//g,''); if(_data = JSON.parse(_data)) { this.setConfig(_data,true); return true; } } return false; }
javascript
{ "resource": "" }
q41751
train
function (components) { for (c in components) { _componentsConfig[c]=_.merge({}, components[c]); if (this.hasComponent(c)) _.merge(_componentsConfig[c],this.getComponentsConfig[c]); } return this; }
javascript
{ "resource": "" }
q41752
train
function (className,config) { var component = this.createClass(className,config); if (component) component.setParent(this); return component; }
javascript
{ "resource": "" }
q41753
train
function () { this.setConfig({components: this.preload}); var preload = this.getConfig().components; if (preload != undefined) { this.setComponents(preload); } return this; }
javascript
{ "resource": "" }
q41754
train
function () { var cps=this.getComponentsConfig(); for (c in cps) { var cpnt=this.getComponent(c); if (cpnt) this.e.log&&this.e.log('- Started component: '+cps[c].class+(cpnt.getConfig('alias')?' (as '+cpnt.getConfig('alias')+')':''),'system'); } return this; }
javascript
{ "resource": "" }
q41755
train
function (modules) { for (m in modules) { _modulesConfig[m]=_.merge({}, modules[m]); if (this.hasModule(m)) _.merge(_modulesConfig[m],this.getModulesConfig[m]); } return this; }
javascript
{ "resource": "" }
q41756
train
function (id,onLoad) { if (_modules[id] != undefined) return _modules[id]; else if (this.hasComponent('classBuilder')) { try { var config = _modulesConfig[id] || {}, modulePath = config.modulePath || id, className = config.class; if (fs.existsSync(this.modulePath+modulePath) && className != undefined) { config.id = id; config.autoInit = !(config.autoInit == false); var npmPath = []; for (n in self.npmPath) npmPath.push(self.npmPath[n]); npmPath.unshift(this.modulePath+modulePath+'/node_modules/'); var module = this.createModule(className,config,modulePath,npmPath); if (module) { _modules[id] = module; this.attachModuleEvents(id); onLoad&&onLoad(module); self.e.loadModule(id,module); process.nextTick(function () { module.e.ready(modulePath,config); }); return _modules[id]; } return false; } else return false; } catch (e) { this.e.log&& this.e.log('wnModule.getModule: Error at loading `'+id+'`'); this.e.exception&& this.e.exception(e); } } }
javascript
{ "resource": "" }
q41757
train
function (className,config,modulePath,npmPath) { var module = this.createClass(className,config,modulePath,npmPath); return module; }
javascript
{ "resource": "" }
q41758
train
function (id) { if (!_.isString(id)) return false; var module = this.getModule(id), events; this.e.log&&this.e.log("Attaching module's events...",'system'); if (module != undefined && (events=module.getEvents()) && !_.isEmpty(events)) { for (e in events) { var evtConfig = {}, eventName = 'module.'+e.split('-').pop(), evtCnf = events[e].getConfig(), event = events[e], eventClass; if (!this.hasEvent(eventName) && evtCnf.bubble && e.indexOf('event-module') == -1) { evtConfig[eventName]=_.merge({},evtCnf); evtConfig[eventName].listenEvent=null; evtConfig[eventName].handler=null; this.setEvents(evtConfig); this.getEvent(eventName); } if (this.hasEvent(eventName) && e.indexOf('event-module') == -1) { eventClass = this.getEvent(eventName); event.prependListener(function (e) { if (typeof e == 'object' && e.stopPropagation == true) return false; eventClass.emit.apply(eventClass,arguments); }); } } this.attachEventsHandlers(); } return this; }
javascript
{ "resource": "" }
q41759
train
function (scripts) { var script = {}; for (s in scripts) { var ref=scripts[s], scriptName = s.substr(0,1).toUpperCase()+s.substr(1).toLowerCase(), s = 'script-'+s.replace('-','.'); script[s]=ref; script[s].class='wnScript'+scriptName || 'wnScript'; _componentsConfig[s]=_.merge({}, script[s]); } return this; }
javascript
{ "resource": "" }
q41760
train
function (value) { if (value != undefined && fs.statSync(value).isDirectory()) { this.modulePath = value; this.setConfig('modulePath',value); } return this; }
javascript
{ "resource": "" }
q41761
MicroserviceClient
train
function MicroserviceClient(settings) { var self = this; self.settings = settings; self.get = bind(self.get, self); self.post = bind(self.post, self); self.put = bind(self.put, self); self.delete = bind(self.delete, self); self.search = bind(self.search, self); self._request = bind(self._request, self); }
javascript
{ "resource": "" }
q41762
buildHandler
train
function buildHandler(overrides) { const parseError = buildHandler.parseError; const buildError = buildHandler.buildError; /** * . */ return function handler(error) { const found = parseError.apply(this, arguments); if (!found) { if (error instanceof Error) { Error.captureStackTrace(error, handler); throw error; } return sliced(arguments); } error = buildError.apply(this, found); if (notEmptyObject(overrides)) { Object.assign(error, overrides); } Error.captureStackTrace(error, handler); throw error; }; }
javascript
{ "resource": "" }
q41763
train
function (string) { color = chalk.cyan; if (args.verbose) { if (typeof string === "string") { console.log(color(string)); } if (isArray(string)) { console.log(color(arrayToString(string))); } } return this; }
javascript
{ "resource": "" }
q41764
addListener
train
function addListener(name) { if (name !== 'collect') { return; } if (this._collecting) { // Don't add more than once return; } debug('adding collect method', this._readableState.objectMode, this._readableState.encoding); let collected; if (this._readableState.objectMode) { collected = []; } else if (this._readableState.encoding === null) { collected = Buffer.from(''); } else { collected = ''; } this .on('readable', () => { let chunk; while ((chunk = this.read()) !== null) { debug('data', chunk); if (chunk !== null) { if (this._readableState.objectMode) { collected.push(chunk); } else if (this._readableState.encoding === null) { collected = Buffer.concat([collected, chunk]); } else { collected += chunk; } } } }) .on('end', () => this.emit('collect', collected)); this._collecting = true; }
javascript
{ "resource": "" }
q41765
addToStream
train
function addToStream(stream) { // Don't add more than once if (stream.listeners('addListener').includes(addListener)) { return stream; } stream.on('newListener', addListener); return stream; }
javascript
{ "resource": "" }
q41766
collect
train
function collect(stream, encoding, cb = () => {}) { if (typeof encoding === 'function') { cb = encoding; encoding = null; } return stream .pipe(new Collect({ encoding, objectMode: stream._readableState.objectMode })) .collect() .then((data) => { cb(null, data); return data; }) .catch((e) => { cb(e); throw e; }); }
javascript
{ "resource": "" }
q41767
ObiCallerID
train
function ObiCallerID() { this.fromRegex = /^INVITE[\S\s]*From:\s*"?([\w\s\.\+\?\$]*?)"?<sip:((.*)@)?(.*)>;.*/; this.cidRegex = /<7> \[SLIC\] CID to deliver: '([\w\s\.\+\?\$]*?)' (\d*).*/; this.cnams = {}; this.lastSentTime = new Date(); this.outlookImported = false; this.addressbookImported = false; this.lastGrowlName = ""; this.lastGrowlNumber = ""; }
javascript
{ "resource": "" }
q41768
SallyWriter
train
function SallyWriter(opts) { this.sally = require('./sally'); opts = opts || {}; this.path = opts.path || 'sally.log'; this.prefix = opts.prefix || ''; this.digest = undefined; this.onLog = this.onLog.bind(this); this.onEpochStart = this.onEpochStart.bind(this); this.onEpochEnd = this.onEpochEnd.bind(this); this.onCycleStart = this.onCycleStart.bind(this); this.onCycleEnd = this.onCycleEnd.bind(this); this.sally .on('log', this.onLog) .on('epochStart', this.onEpochStart) .on('epochEnd', this.onEpochEnd) .on('cycleStart', this.onCycleStart) .on('cycleEnd', this.onCycleEnd) .configure(opts); }
javascript
{ "resource": "" }
q41769
train
function(client, app, sinfos) { let item; for (let i = 0, l = sinfos.length; i < l; i++) { item = sinfos[i]; if (hasProxy(client, item)) { continue; } client.addProxies(getProxyRecords(app, item)); } }
javascript
{ "resource": "" }
q41770
train
function(client, sinfo) { let proxy = client.proxies; return !!proxy.sys && !! proxy.sys[sinfo.serverType]; }
javascript
{ "resource": "" }
q41771
train
function(app, sinfo) { let records = [], appBase = app.getBase(), record; // sys remote service path record if (app.isFrontend(sinfo)) { record = pathUtil.getSysRemotePath('frontend'); } else { record = pathUtil.getSysRemotePath('backend'); } if (record) { records.push(pathUtil.remotePathRecord('sys', sinfo.serverType, record)); } // user remote service path record record = pathUtil.getUserRemotePath(appBase, sinfo.serverType); if (record) { records.push(pathUtil.remotePathRecord('user', sinfo.serverType, record)); } return records; }
javascript
{ "resource": "" }
q41772
snapToWord
train
function snapToWord() { if (isHighlighted()) { throw new Error("Can't modify range after highlighting"); } var start = selection.range.startOffset; var startNode = selection.range.startContainer; while (startNode.textContent.charAt(start) != ' ' && start > 0) { start--; } if (start != 0 && start != selection.range.startOffset) { start++; } var end = selection.range.endOffset; var endNode = selection.range.endContainer; while (endNode.textContent.charAt(end) != ' ' && end < endNode.length) { end++; } selection.range.setStart(startNode, start); selection.range.setEnd(endNode, end); selection.text = selection.range.toString(); }
javascript
{ "resource": "" }
q41773
removeHighlight
train
function removeHighlight() { for (var h in selection._highlighter) { var highlighter = selection._highlighter[h]; var parent = highlighter.parentNode; while (highlighter.firstChild) { parent.insertBefore(highlighter.firstChild, highlighter); } parent.removeChild(highlighter); } selection._highlighter = undefined; }
javascript
{ "resource": "" }
q41774
shard
train
function shard() { var treeNode = new RangeTreeNode(); treeNode.setStart(range.startContainer, range.startOffset); var current = range.startContainer; var distance = 0; while (current != range.endContainer && distance < 50) { var last = current; if (current.firstChild) { current = current.firstChild; treeNode.setEnd(last, last.length - 1); treeNode = treeNode.createNewChild(); } else if (current.nextSibling) { current = current.nextSibling; if (current.nodeType != 3) { treeNode.setEnd(last, last.length - 1); treeNode = treeNode.getNextSibling(); } } else if (current.parentNode.nextSibling) { current = current.parentNode.nextSibling; treeNode.setEnd(last, last.length - 1); treeNode = treeNode.getParent().getNextSibling(); } if (current.nodeType == 3 && !treeNode.start) { treeNode.setStart(current, 0); } distance++; } treeNode.setEnd(range.endContainer, range.endOffset ); return treeNode.toRanges(); }
javascript
{ "resource": "" }
q41775
getFingerprintsForAnimal
train
function getFingerprintsForAnimal(animalDir) { if (!fs.existsSync(animalDir) || !fs.statSync(animalDir).isDirectory()) { return false; } var fgpFiles = fs.readdirSync(animalDir).filter(function (entry) { return entry.split('.').pop().toLowerCase() == 'fgp'; }); var fgps = []; fgpFiles.forEach(function (fgpFile) { fgpFile = path.join(animalDir, fgpFile); var fgpData = fgpReader(fgpFile); fgps.push({ id: path.basename(fgpFile, '.fgp'), fgp: fgpData, img64: 'data:image/jpeg;base64,' + fs.readFileSync(getFGPImageName(fgpFile)).toString('base64') }); }); return fgps; }
javascript
{ "resource": "" }
q41776
getAllFingerprints
train
function getAllFingerprints(dir) { var ids = getAnimals(); var fgps = ids.map(function (id) { return getFingerprintsForAnimal(path.join(dir, id)); }).filter(function (fgp) { return fgp; }); return fgps; }
javascript
{ "resource": "" }
q41777
getAnimals
train
function getAnimals(dir) { var ids = fs.readdirSync(dir).filter(function (id) { return fs.statSync(path.join(dir, id)).isDirectory(); }); return ids; }
javascript
{ "resource": "" }
q41778
moveCursorRelative
train
function moveCursorRelative(stream, dx, dy) { if (dx < 0) { stream.write('\x1b[' + (-dx) + 'D'); } else if (dx > 0) { stream.write('\x1b[' + dx + 'C'); } if (dy < 0) { stream.write('\x1b[' + (-dy) + 'A'); } else if (dy > 0) { stream.write('\x1b[' + dy + 'B'); } }
javascript
{ "resource": "" }
q41779
createValidationErrorMessages
train
function createValidationErrorMessages(base, subjDef) { if (!subjDef.validationErrorMessages && (base !== standard.VALIDATION_ERROR_MESSAGES)) return base; const validationErrorMessages = Object.create(base); for (let messageId in subjDef.validationErrorMessages) { const messageDef = subjDef.validationErrorMessages[messageId]; const existingMessageDef = validationErrorMessages[messageId]; let newMessageDef; if (existingMessageDef && (typeof existingMessageDef) === 'object' && (typeof messageDef) === 'object') { newMessageDef = Object.create(existingMessageDef); for (let lang in messageDef) newMessageDef[lang] = messageDef[lang]; } else { newMessageDef = messageDef; } validationErrorMessages[messageId] = newMessageDef; } return validationErrorMessages; }
javascript
{ "resource": "" }
q41780
createValidatorFuncs
train
function createValidatorFuncs(base, subjDef, subjDescription) { if (!subjDef.validatorDefs && (base !== standard.VALIDATOR_DEFS)) return base; const validatorFuncs = Object.create(base); for (let validatorId in subjDef.validatorDefs) { const validatorFunc = subjDef.validatorDefs[validatorId]; if ((typeof validatorFunc) !== 'function') throw new common.X2UsageError( 'Validator definition "' + validatorId + '" on ' + subjDescription + ' is not a function.'); validatorFuncs[validatorId] = validatorFunc; } return validatorFuncs; }
javascript
{ "resource": "" }
q41781
train
function (num, uppercase) { var digits = String(+num).split(""), key = ["","c","cc","ccc","cd","d","dc","dcc","dccc","cm", "","x","xx","xxx","xl","l","lx","lxx","lxxx","xc", "","i","ii","iii","iv","v","vi","vii","viii","ix"], roman = "", i = 3; while (i--) roman = (key[+digits.pop() + (i * 10)] || "") + roman; var index = Array(+digits.join("") + 1).join("m") + roman; return uppercase ? index.toUpperCase() : index; }
javascript
{ "resource": "" }
q41782
getMimeType
train
function getMimeType (media) { return new Promise((resolve, reject) => { if (isFile(media)) { typechecker.detectFile(media, (err, result) => { err && reject(err) resolve(result) }) } else if (isBuffer(media)) { typechecker.detect(media, (err, result) => { err && reject(err) resolve(result) }) } else if (isBase64(media)) { return getMimeType(toBuffer(media)) } else if (isURL(media)) { return getMimeType(toBuffer(media)) } else { reject('media is not a file') } }) }
javascript
{ "resource": "" }
q41783
isImage
train
function isImage (path) { return new Promise((resolve, reject) => { getMimeType(path) .then((type) => { ;(type.indexOf('image') > -1) ? resolve(true) : resolve(false) }) .catch(err => reject(err)) }) }
javascript
{ "resource": "" }
q41784
urlToBase64
train
function urlToBase64 (url) { return new Promise((resolve, reject) => { request.get(url, (err, response, body) => { err && reject(err) resolve(body.toString('base64')) }) }) }
javascript
{ "resource": "" }
q41785
toBase64
train
function toBase64 (media) { return new Promise((resolve, reject) => { if (isBase64(media)) { resolve(media) } else if (isURL(media)) { urlToBase64(media) .then(data => resolve(data)) .catch(error => reject(error)) } else if (isFile(media)) { fileToBase64(media) .then(data => resolve(data)) .catch(error => reject(error)) } else if (isBuffer(media)) { const base64 = media.toString('base64') resolve(base64) } else { reject('Error: toBase64(): cannot convert media') } }) }
javascript
{ "resource": "" }
q41786
toBuffer
train
function toBuffer (media) { return new Promise((resolve, reject) => { if (isURL(media)) { toBase64(media) .then(data => { toBuffer(data) .then(data => resolve(data)) .catch(error => reject(error)) }) .catch(error => reject(error)) } else if (isBase64(media)) { try { resolve(Buffer.from(media)) } catch (ex) { reject(ex) } } else if (isFile(media)) { fs.readFile(media, (err, data) => { err && reject(err) resolve(data) }) } else { reject('Error: toBuffer(): argument must be file, url or file') } }) }
javascript
{ "resource": "" }
q41787
translateDateTimestamp
train
function translateDateTimestamp(timestamp) { if (!timestamp) { LOG.warn("Received an invalid timestamp: {}", timestamp); return Date.now(); } return new Date(timestamp); }
javascript
{ "resource": "" }
q41788
translateRole
train
function translateRole(role) { switch (role) { case "5615fa9ae596154a5c000000": return Types.UserRole.COOWNER; case "5615fd84e596150061000003": return Types.UserRole.MANAGER; case "52d1ce33c38a06510c000001": return Types.UserRole.MOD; case "5615fe1ee596154fc2000001": return Types.UserRole.VIP; case "5615feb8e596154fc2000002": return Types.UserRole.RESIDENT_DJ; case "564435423f6ba174d2000001": return Types.UserRole.DJ; default: return Types.UserRole.NONE; } }
javascript
{ "resource": "" }
q41789
Basic
train
function Basic(client, channel, done){ EE.call(this); this.client = client; this.channel = channel; this.id = channel.$getId(); this.publishCallbackMethod = DEFAULT_PUBLISH_ANSWER_WAIT_MECHANISM; this.timeout = DEFAULT_WAIT_TIMEOUT; this.lastConfirmSendId = 1; this.lastMessageId = 1; this.done = done; this.lastError = null; return this; }
javascript
{ "resource": "" }
q41790
getJSFiles
train
function getJSFiles(folder = srcFolder){ let all = []; let f = fs.readdirSync(folder); for(file of f){ all.push(path.join(folder,file)) if(fs.lstatSync(path.join(folder,file)).isDirectory()){ all = all.concat(getJSFiles(path.join(folder,file))); } } return all.filter(x => x.endsWith('.js')); }
javascript
{ "resource": "" }
q41791
Sweep
train
function Sweep(actor, context) { this.actor = actor; this.context = context; this.prev = context.actors[actor] || {}; this.resources = context.actors[actor] = {}; }
javascript
{ "resource": "" }
q41792
session
train
function session(options) { options = options || {}; DEBUG && debug('configure http session middleware', options); if (options.store) { try { var storeModule = options.store.module; var SessionStore = require(storeModule)(express); // replace store options with store object options.store = new SessionStore(options.store.options); return expressSession(options); } catch (e) { console.error('failed to configure http session store', e); //process.exit(1); } } console.warn('**fallback** use default session middleware'); return expressSession(options); }
javascript
{ "resource": "" }
q41793
forEachDesc
train
function forEachDesc(obj, fn) { var names = Object.getOwnPropertyNames(obj); for (var i$0 = 0; i$0 < names.length; ++i$0) fn(names[i$0], Object.getOwnPropertyDescriptor(obj, names[i$0])); names = Object.getOwnPropertySymbols(obj); for (var i$1 = 0; i$1 < names.length; ++i$1) fn(names[i$1], Object.getOwnPropertyDescriptor(obj, names[i$1])); return obj; }
javascript
{ "resource": "" }
q41794
mergeProperty
train
function mergeProperty(target, name, desc, enumerable) { if (desc.get || desc.set) { var d$0 = { configurable: true }; if (desc.get) d$0.get = desc.get; if (desc.set) d$0.set = desc.set; desc = d$0; } desc.enumerable = enumerable; Object.defineProperty(target, name, desc); }
javascript
{ "resource": "" }
q41795
mergeProperties
train
function mergeProperties(target, source, enumerable) { forEachDesc(source, function(name, desc) { return mergeProperty(target, name, desc, enumerable); }); }
javascript
{ "resource": "" }
q41796
buildClass
train
function buildClass(base, def) { var parent; if (def === void 0) { // If no base class is specified, then Object.prototype // is the parent prototype def = base; base = null; parent = Object.prototype; } else if (base === null) { // If the base is null, then then then the parent prototype is null parent = null; } else if (typeof base === "function") { parent = base.prototype; // Prototype must be null or an object if (parent !== null && Object(parent) !== parent) parent = void 0; } if (parent === void 0) throw new TypeError; // Create the prototype object var proto = Object.create(parent), statics = {}; function __(target, obj) { if (!obj) mergeProperties(proto, target, false); else mergeProperties(target, obj, false); } __.static = function(obj) { return mergeProperties(statics, obj, false); }; __.super = parent; __.csuper = base || Function.prototype; // Generate method collections, closing over super bindings def(__); var ctor = proto.constructor; // Set constructor's prototype ctor.prototype = proto; // Set class "static" methods forEachDesc(statics, function(name, desc) { return Object.defineProperty(ctor, name, desc); }); // Inherit from base constructor if (base && ctor.__proto__) Object.setPrototypeOf(ctor, base); return ctor; }
javascript
{ "resource": "" }
q41797
train
function(target) { for (var i$2 = 1; i$2 < arguments.length; i$2 += 3) { var desc$0 = Object.getOwnPropertyDescriptor(arguments[i$2 + 1], "_"); mergeProperty(target, arguments[i$2], desc$0, true); if (i$2 + 2 < arguments.length) mergeProperties(target, arguments[i$2 + 2], true); } return target; }
javascript
{ "resource": "" }
q41798
train
function(iter) { var front = null, back = null; return _esdown.computed({ next: function(val) { return send("next", val) }, throw: function(val) { return send("throw", val) }, return: function(val) { return send("return", val) }, }, Symbol.asyncIterator, { _: function() { return this }, }); function send(type, value) { return new Promise(function(resolve, reject) { var x = { type: type, value: value, resolve: resolve, reject: reject, next: null }; if (back) { // If list is not empty, then push onto the end back = back.next = x; } else { // Create new list and resume generator front = back = x; resume(type, value); } }); } function fulfill(type, value) { switch (type) { case "return": front.resolve({ value: value, done: true }); break; case "throw": front.reject(value); break; default: front.resolve({ value: value, done: false }); break; } front = front.next; if (front) resume(front.type, front.value); else back = null; } function awaitValue(result) { var value = result.value; if (typeof value === "object" && "_esdown_await" in value) { if (result.done) throw new Error("Invalid async generator return"); return value._esdown_await; } return null; } function resume(type, value) { // HACK: If the generator does not support the "return" method, then // emulate it (poorly) using throw. (V8 circa 2015-02-13 does not support // generator.return.) if (type === "return" && !(type in iter)) { type = "throw"; value = { value: value, __return: true }; } try { var result$1 = iter[type](value), awaited$0 = awaitValue(result$1); if (awaited$0) { Promise.resolve(awaited$0).then( function(x) { return resume("next", x); }, function(x) { return resume("throw", x); }); } else { Promise.resolve(result$1.value).then( function(x) { return fulfill(result$1.done ? "return" : "normal", x); }, function(x) { return fulfill("throw", x); }); } } catch (x) { // HACK: Return-as-throw if (x && x.__return === true) return fulfill("return", x.value); fulfill("throw", x); } } }
javascript
{ "resource": "" }
q41799
train
function(initial) { return { a: initial || [], // Add items s: function() { for (var i$3 = 0; i$3 < arguments.length; ++i$3) this.a.push(arguments[i$3]); return this; }, // Add the contents of iterables i: function(list) { if (Array.isArray(list)) { this.a.push.apply(this.a, list); } else { for (var __$0 = (list)[Symbol.iterator](), __$1; __$1 = __$0.next(), !__$1.done;) { var item$0 = __$1.value; this.a.push(item$0); } } return this; } }; }
javascript
{ "resource": "" }