_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q10400
train
function (expressServer, settings) { return new Promise((resolve, reject) => { autoloader.run(expressServer, settings).then((success) => { resolve(success); }, (error) => { reject(error); }); }); }
javascript
{ "resource": "" }
q10401
execute
train
function execute (str, { cwd }) { // command = replace(command, options); // command = prepend(command, options); let args = str.split(' ') const command = args.shift() args = [args.join(' ')] const subprocess = spawn(command, args, { detached: true, stdio: 'ignore', cwd }) subprocess.unref() return subprocess.pid }
javascript
{ "resource": "" }
q10402
train
function() { var editDataSource = this.getProperty( 'editDataSource' ); var destinationDataSource = this.getProperty( 'destinationDataSource' ); var destinationProperty = this.getProperty( 'destinationProperty' ) || ''; if( !destinationDataSource ) { return; } if( this._isObjectDataSource( editDataSource ) ) { var newItem = editDataSource.getSelectedItem(); if( this._isRootElementPath( destinationProperty ) ) { destinationDataSource._includeItemToModifiedSet( newItem ); destinationDataSource.saveItem( newItem, function() { destinationDataSource.updateItems(); } ); } else { var items = destinationDataSource.getProperty( destinationProperty ) || []; items = _.clone( items ); items.push( newItem ); destinationDataSource.setProperty( destinationProperty, items ); } } else { destinationDataSource.updateItems(); } }
javascript
{ "resource": "" }
q10403
train
function(capture) { // If compareTo{Page|Viewport} option is set, gets the filepath corresponding // to the capture index (page, capture, viewport): if (options.compareToViewport || options.compareToPage) { var pageReference = options.compareToPage || capture.page.name; var viewportReference = options.compareToViewport || capture.viewport.name; return createCaptureState(pageReference, capture.name, viewportReference).filePath; } else { return capture.filePath; } }
javascript
{ "resource": "" }
q10404
Class
train
function Class(name, superClasses, attributes, references, flexible) { /** The generic class instances Class * @constructor * @param {Object} attr The initial values of the instance */ function ClassInstance(attr) { Object.defineProperties(this, { __jsmf__: {value: elementMeta(ClassInstance)} }) createAttributes(this, ClassInstance) createReferences(this, ClassInstance) _.forEach(attr, (v,k) => {this[k] = v}) } Object.defineProperties(ClassInstance.prototype, { conformsTo: {value: function () { return conformsTo(this) }, enumerable: false}, getAssociated : {value: getAssociated, enumerable: false} }) superClasses = superClasses || [] superClasses = _.isArray(superClasses) ? superClasses : [superClasses] Object.assign(ClassInstance, {__name: name, superClasses, attributes: {}, references: {}}) ClassInstance.errorCallback = flexible ? onError.silent : onError.throw Object.defineProperty(ClassInstance, '__jsmf__', {value: classMeta()}) populateClassFunction(ClassInstance) if (attributes !== undefined) { ClassInstance.addAttributes(attributes)} if (references !== undefined) { ClassInstance.addReferences(references)} return ClassInstance }
javascript
{ "resource": "" }
q10405
ClassInstance
train
function ClassInstance(attr) { Object.defineProperties(this, { __jsmf__: {value: elementMeta(ClassInstance)} }) createAttributes(this, ClassInstance) createReferences(this, ClassInstance) _.forEach(attr, (v,k) => {this[k] = v}) }
javascript
{ "resource": "" }
q10406
getInheritanceChain
train
function getInheritanceChain() { return _(this.superClasses) .reverse() .reduce((acc, v) => v.getInheritanceChain().concat(acc), [this]) }
javascript
{ "resource": "" }
q10407
getAllReferences
train
function getAllReferences() { return _.reduce( this.getInheritanceChain(), (acc, cls) => _.reduce(cls.references, (acc2, v, k) => {acc2[k] = v; return acc2}, acc), {}) }
javascript
{ "resource": "" }
q10408
getAllAttributes
train
function getAllAttributes() { return _.reduce( this.getInheritanceChain(), (acc, cls) => _.reduce(cls.attributes, (acc2, v, k) => {acc2[k] = v; return acc2}, acc), {}) }
javascript
{ "resource": "" }
q10409
getAssociated
train
function getAssociated(name) { const path = ['__jsmf__', 'associated'] if (name !== undefined) { path.push(name) } return _.get(this, path) }
javascript
{ "resource": "" }
q10410
addReferences
train
function addReferences(descriptor) { _.forEach(descriptor, (desc, k) => this.addReference( k, desc.target || desc.type, desc.cardinality, desc.opposite, desc.oppositeCardinality, desc.associated, desc.errorCallback, desc.oppositeErrorCallback) ) }
javascript
{ "resource": "" }
q10411
addReference
train
function addReference(name, target, sourceCardinality, opposite, oppositeCardinality, associated, errorCallback, oppositeErrorCallback) { this.references[name] = { type: target || Type.JSMFAny , cardinality: Cardinality.check(sourceCardinality) } if (opposite !== undefined) { this.references[name].opposite = opposite target.references[opposite] = { type: this , cardinality: oppositeCardinality === undefined && target.references[opposite] !== undefined ? target.references[opposite].cardinality : Cardinality.check(oppositeCardinality) , opposite: name , errorCallback: oppositeErrorCallback === undefined && target.references[opposite] !== undefined ? target.references[opposite].oppositeErrorCallback : this.errorCallback } } if (associated !== undefined) { this.references[name].associated = associated if (opposite !== undefined) { target.references[opposite].associated = associated } } this.references[name].errorCallback = errorCallback || this.errorCallback }
javascript
{ "resource": "" }
q10412
removeReference
train
function removeReference(name, opposite) { const ref = this.references[name] _.unset(this.references, name) if (ref.opposite !== undefined) { if (opposite) { _.unset(ref.type.references, ref.opposite) } else { _.unset(ref.type.references[ref.opposite], 'opposite') } } }
javascript
{ "resource": "" }
q10413
setSuperType
train
function setSuperType(s) { const ss = _.isArray(s) ? s : [s] this.superClasses = _.uniq(this.superClasses.concat(ss)) }
javascript
{ "resource": "" }
q10414
addAttribute
train
function addAttribute(name, type, mandatory, errorCallback) { this.attributes[name] = { type: Type.normalizeType(type) , mandatory: mandatory || false , errorCallback: errorCallback || this.errorCallback } }
javascript
{ "resource": "" }
q10415
addAttributes
train
function addAttributes(attrs) { _.forEach(attrs, (v, k) => { if (v.type !== undefined) { this.addAttribute(k, v.type, v.mandatory, v.errorCallback) } else { this.addAttribute(k, v) } }) }
javascript
{ "resource": "" }
q10416
setFlexible
train
function setFlexible(b) { this.errorCallback = b ? onError.silent : onError.throw _.forEach(this.references, r => r.errorCallback = this.errorCallback) _.forEach(this.attributes, r => r.errorCallback = this.errorCallback) }
javascript
{ "resource": "" }
q10417
ResultSet
train
function ResultSet(conn, query, values, options, rs) { this.query = query; this.metadata = rs.metadata; this.rows = rs.rows; this._conn = conn; this._values = values; this._options = options; }
javascript
{ "resource": "" }
q10418
train
function(client, method, url, payload, query) { // Add query to url if present if (query) { query = querystring.stringify(query); if (query.length > 0) { url += '?' + query; } } // Construct request object var req = request(method.toUpperCase(), url); // Set the http agent for this request, if supported in the current // environment (browser environment doesn't support http.Agent) if (req.agent) { req.agent(client._httpAgent); } // Timeout for each individual request. req.timeout(client._timeout); // Send payload if defined if (payload !== undefined) { req.send(payload); } // Authenticate, if credentials are provided if (client._options.credentials && client._options.credentials.clientId && client._options.credentials.accessToken) { // Create hawk authentication header var header = hawk.client.header(url, method.toUpperCase(), { credentials: { id: client._options.credentials.clientId, key: client._options.credentials.accessToken, algorithm: 'sha256', }, ext: client._extData, }); req.set('Authorization', header.field); } // Return request return req; }
javascript
{ "resource": "" }
q10419
train
function (attr, expr, context, data) { var val = this.exprEvaluator(expr, context, data); if (val || typeof val === 'string' || typeof val === 'number') { return " " + attr + '=' + this.generateAttribute(val + ''); } else { //else if undefined, null, false then don't render attribute. return ''; } }
javascript
{ "resource": "" }
q10420
train
function (dom) { var html = ''; dom.forEach(function (node) { if (node.type === 'tag') { var tag = node.name; html += '<' + tag; Object.keys(node.attribs).forEach(function (attr) { html += ' ' + attr + '=' + this.generateAttribute(node.attribs[attr]); }, this); html += (voidTags[tag] ? '/>' : '>'); if (!voidTags[tag]) { html += this.vdomToHtml(node.children); html += '</' + tag + '>'; } } else if (node.type === 'text') { var text = node.data || ''; html += this.htmlEncode(text); //escape <,> and &. } else if (node.type === 'comment') { html += '<!-- ' + node.data.trim() + ' -->'; } else if (node.type === 'script' || node.type === 'style') { //No need to escape text inside script or style tag. html += '<' + node.name; Object.keys(node.attribs).forEach(function (attr) { html += ' ' + attr + '=' + this.generateAttribute(node.attribs[attr]); }, this); html += '>' + ((node.children[0] || {}).data || '') + '</' + node.name + '>'; } else if (node.type === 'directive') { html += '<' + node.data + '>'; } }, this); return html; }
javascript
{ "resource": "" }
q10421
train
function (nodes, parent) { var copy = nodes.map(function (node, index) { var clone = {}; //Shallow copy Object.keys(node).forEach(function (prop) { clone[prop] = node[prop]; }); return clone; }); copy.forEach(function (cur, i) { cur.prev = copy[i - 1]; cur.next = copy[i + 1]; cur.parent = parent; if (cur.children) { cur.children = this.makeNewFragment(cur.children, cur); } }, this); return copy; }
javascript
{ "resource": "" }
q10422
train
function (objectLiteral, callback, scope) { if (objectLiteral) { parseObjectLiteral(objectLiteral).some(function (tuple) { return (callback.call(scope, tuple[0], tuple[1]) === true); }); } }
javascript
{ "resource": "" }
q10423
funcToString
train
function funcToString(func) { var str = func.toString(); return str.slice(str.indexOf('{') + 1, str.lastIndexOf('}')); }
javascript
{ "resource": "" }
q10424
traverse
train
function traverse(object, visitor) { let child; if (!object) return; let r = visitor.call(null, object); if (r === STOP) return STOP; // stop whole traverse immediately if (r === SKIP_BRANCH) return; // skip going into AST branch for (let i = 0, keys = Object.keys(object); i < keys.length; i++) { let key = keys[i]; if (IGNORED_KEYS.indexOf(key) !== -1) continue; child = object[key]; if (typeof child === 'object' && child !== null) { if (traverse(child, visitor) === STOP) { return STOP; } } } }
javascript
{ "resource": "" }
q10425
extract
train
function extract(pattern, part) { if (!pattern) throw new Error('missing pattern'); // no match if (!part) return STOP; let term = matchTerm(pattern); if (term) { // if single __any if (term.type === ANY) { if (term.name) { // if __any_foo // get result {foo: astNode} let r = {}; r[term.name] = part; return r; } // always match return {}; // if single __str_foo } else if (term.type === STR) { if (part.type === 'Literal') { if (term.name) { // get result {foo: value} let r = {}; r[term.name] = part.value; return r; } // always match return {}; } // no match return STOP; } } if (Array.isArray(pattern)) { // no match if (!Array.isArray(part)) return STOP; if (pattern.length === 1) { let arrTerm = matchTerm(pattern[0]); if (arrTerm) { // if single __arr_foo if (arrTerm.type === ARR) { // find all or partial Literals in an array let arr = part.filter(function(it) { return it.type === 'Literal'; }) .map(function(it) { return it.value; }); if (arr.length) { if (arrTerm.name) { // get result {foo: array} let r = {}; r[arrTerm.name] = arr; return r; } // always match return {}; } // no match return STOP; } else if (arrTerm.type === ANL) { if (arrTerm.name) { // get result {foo: nodes array} let r = {}; r[arrTerm.name] = part; return r; } // always match return {}; } } } if (pattern.length !== part.length) { // no match return STOP; } } let allResult = {}; for (let i = 0, keys = Object.keys(pattern); i < keys.length; i++) { let key = keys[i]; if (IGNORED_KEYS.indexOf(key) !== -1) continue; let nextPattern = pattern[key]; let nextPart = part[key]; if (!nextPattern || typeof nextPattern !== 'object') { // primitive value. string or null if (nextPattern === nextPart) continue; // no match return STOP; } const result = extract(nextPattern, nextPart); // no match if (result === STOP) return STOP; if (result) Object.assign(allResult, result); } return allResult; }
javascript
{ "resource": "" }
q10426
compilePattern
train
function compilePattern(pattern) { // pass estree syntax tree obj if (pattern && pattern.type) return pattern; if (typeof pattern !== 'string') { throw new Error('input pattern is neither a string nor an estree node.'); } let exp = parser(pattern); if (exp.type !== 'Program' || !exp.body) { throw new Error(`Not a valid expression: "${pattern}".`); } if (exp.body.length === 0) { throw new Error(`There is no statement in pattern "${pattern}".`); } if (exp.body.length > 1) { throw new Error(`Multiple statements is not supported "${pattern}".`); } exp = exp.body[0]; // get the real expression underneath if (exp.type === 'ExpressionStatement') exp = exp.expression; return exp; }
javascript
{ "resource": "" }
q10427
tock
train
function tock() { var tockPeriod = process.hrtime(tickTime); var tockPeriodMs = hrtimeAsMs(tockPeriod); process.send({ cmd: 'CLUSTER_PULSE', load: tockPeriodMs - pulse, memoryUsage: process.memoryUsage() }); tick(); }
javascript
{ "resource": "" }
q10428
train
function( id, text, order, path, hidden, umbel ) { MenuProto.call( this, id, text, order, hidden ); /** * Gets the paths of the menu item. * @type {Array.<string>} */ this.paths = createPathList( path ); /** * Gets whether the menu item is umbrella for more items. * @type {MenuStock} */ this.umbel = umbel; }
javascript
{ "resource": "" }
q10429
Ping
train
function Ping(url, driver) { if (!(this instanceof Ping)) { return new Ping(url, driver); } driver = driver || request; this.url = url; this.driver = driver; this.successCodes = SUCCESS; this.started = false; this.validators = []; var self = this; var textCheck = function(err, res, body) { if (!self._text) return true; return ~body.indexOf(self._text); }; var errorCheck = function(err, res) { return !err; }; var statusCheck = function(err, res, body) { // If there is no result from the server, assume site is down. if (!res){ return false; } else { return ~self.successCodes.indexOf(res.statusCode); } }; var perfCheck = function(err, res, body, info) { if (typeof self._maxDuration !== 'number') return true; return info.duration <= self._maxDuration; }; this.register(errorCheck, statusCheck, textCheck, perfCheck); }
javascript
{ "resource": "" }
q10430
loadEnv
train
function loadEnv(name) { var fullEnvPath = path.resolve(applicationRoot, './configs/' + name); try { debug('Loaded environment: ' + fullEnvPath); fs.statSync(fullEnvPath); dotenv.config({ path: fullEnvPath }); } catch (e) { debug('Could not load environment "' + fullEnvPath + '"'); } }
javascript
{ "resource": "" }
q10431
field
train
function field(x, y) { var ux = 0; var uy = 0; for(var a = 0; a < attractors.length; a++) { var attractor = attractors[a]; var d2 = (x - attractor.x) * (x - attractor.x) + (y - attractor.y) * (y - attractor.y); var d = Math.sqrt(d2); var weight = attractor.weight * Math.exp( -1 * d2 / (attractor.radius * attractor.radius) ); ux += weight * (x - attractor.x) / d; uy += weight * (y - attractor.y) / d; } var norm = Math.sqrt(ux * ux + uy * uy); ux = ux / norm; uy = uy / norm; // If we are near a special attractor, add its contribution to the field if(isNearSpecialAttractor(x,y)) { var closestTextPoint = findClosestPointOnSpecialAttractor(x,y); var textUx = (closestTextPoint.specialAttractor.direction || 1) * (x - closestTextPoint.originX); var textUy = (closestTextPoint.specialAttractor.direction || 1) * (y - closestTextPoint.originY); var norm = Math.sqrt(textUx*textUx + textUy*textUy); textUx = textUx / norm; textUy = textUy / norm; // Combine fields if(closestTextPoint.specialAttractor.type == 'cos') { if(closestTextPoint.distance < closestTextPoint.specialAttractor.impactDistance) { textWeight = 0.5 * (1 + Math.cos(Math.PI * closestTextPoint.distance / (closestTextPoint.specialAttractor.impactDistance))); } else { textWeight = 0; } } else { textWeight = Math.exp( -1 * closestTextPoint.distance * closestTextPoint.distance / (closestTextPoint.specialAttractor.impactDistance * D * D) ); } ux = (1-textWeight)*ux + textWeight * textUx; uy = (1-textWeight)*uy + textWeight * textUy; } return [ux, uy]; }
javascript
{ "resource": "" }
q10432
createNoGoCircleSpecialAttractors
train
function createNoGoCircleSpecialAttractors(x, y, radius, impactDistance, type, direction) { var circleSubDiv = radius * SUBDIVISE_NOGO / 20; for( var i = 0; i < circleSubDiv; i++ ) { var specialAttractor = {}; specialAttractor.x1 = (x + radius * Math.cos(2*Math.PI / circleSubDiv * i)) * pixelRatio; specialAttractor.y1 = (y + radius * Math.sin(2*Math.PI / circleSubDiv * i)) * pixelRatio; specialAttractor.x2 = (x + radius * Math.cos(2*Math.PI / circleSubDiv * (i+1))) * pixelRatio; specialAttractor.y2 = (y + radius * Math.sin(2*Math.PI / circleSubDiv * (i+1))) * pixelRatio; specialAttractor.impactDistance = impactDistance * pixelRatio; specialAttractor.type = type; specialAttractor.direction = direction; specialAttractors.push(specialAttractor); if(DEBUG_FLAG) { drawHelperCircle(specialAttractor.x1, specialAttractor.y1, 1); } } var bbox = { topLeft: { x: (x - radius) * pixelRatio, y: (y - radius) * pixelRatio, }, bottomRight: { x: (x + radius) * pixelRatio, y: (y + radius) * pixelRatio, }, }; specialAttractorsBoundingBoxes.push(bbox); noGoBBoxes.push(bbox); }
javascript
{ "resource": "" }
q10433
findClosestPointOnSpecialAttractor
train
function findClosestPointOnSpecialAttractor(x,y) { var nSpecialAttractor = specialAttractors.length; var currentMinDistance = 0; var currentSpecialAttractor; var ox = 0; var oy = 0; for(var a=0; a<nSpecialAttractor; a++) { var specialAttractor = specialAttractors[a]; var closestSegmentPoint = distanceToSegment(specialAttractor.x1, specialAttractor.y1, specialAttractor.x2, specialAttractor.y2, x, y); if(a == 0 || (closestSegmentPoint.distance) < currentMinDistance) { currentMinDistance = closestSegmentPoint.distance; currentSpecialAttractor = specialAttractor; ox = closestSegmentPoint.originX; oy = closestSegmentPoint.originY; } } return { distance: currentMinDistance, specialAttractor: currentSpecialAttractor, originX: ox, originY: oy } }
javascript
{ "resource": "" }
q10434
initPopupForm
train
function initPopupForm(){ var popUpIsAlreadyVisible = $('#ep_email_form_popup').is(":visible"); if(!popUpIsAlreadyVisible){ // if the popup isn't already visible var cookieVal = pad.getPadId() + "email"; if(cookie.getPref(cookieVal) !== "true"){ // if this user hasn't already subscribed askClientToEnterEmail(); // ask the client to register TODO uncomment me for a pop up } } }
javascript
{ "resource": "" }
q10435
train
function(e){ $('#ep_email_form_popup').submit(function(){ sendEmailToServer('ep_email_form_popup'); return false; }); // Prepare subscription before submit form $('#ep_email_form_popup [name=ep_email_subscribe]').on('click', function(e) { $('#ep_email_form_popup [name=ep_email_option]').val('subscribe'); checkAndSend(e); }); // Prepare unsubscription before submit form $('#ep_email_form_popup [name=ep_email_unsubscribe]').on('click', function(e) { $('#ep_email_form_popup [name=ep_email_option]').val('unsubscribe'); checkAndSend(e); }); if (optionsAlreadyRecovered == false) { getDataForUserId('ep_email_form_popup'); } else { // Get datas from form in mysettings menu $('#ep_email_form_popup [name=ep_email]').val($('#ep_email_form_mysettings [name=ep_email]').val()); $('#ep_email_form_popup [name=ep_email_onStart]').prop('checked', $('#ep_email_form_mysettings [name=ep_email_onStart]').prop('checked')); $('#ep_email_form_popup [name=ep_email_onEnd]').prop('checked', $('#ep_email_form_mysettings [name=ep_email_onEnd]').prop('checked')); } }
javascript
{ "resource": "" }
q10436
checkAndSend
train
function checkAndSend(e) { var formName = $(e.currentTarget.parentNode).attr('id'); var email = $('#' + formName + ' [name=ep_email]').val(); if (email && $('#' + formName + ' [name=ep_email_option]').val() == 'subscribe' && !$('#' + formName + ' [name=ep_email_onStart]').is(':checked') && !$('#' + formName + ' [name=ep_email_onEnd]').is(':checked')) { $.gritter.add({ // (string | mandatory) the heading of the notification title: window._('ep_email_notifications.titleGritterError'), // (string | mandatory) the text inside the notification text: window._('ep_email_notifications.msgOptionsNotChecked'), // (string | optional) add a class name to the gritter msg class_name: "emailNotificationsSubscrOptionsMissing" }); } else if (email) { $('#' + formName).submit(); } return false; }
javascript
{ "resource": "" }
q10437
sendEmailToServer
train
function sendEmailToServer(formName){ var email = $('#' + formName + ' [name=ep_email]').val(); var userId = pad.getUserId(); var message = {}; message.type = 'USERINFO_UPDATE'; message.userInfo = {}; message.padId = pad.getPadId(); message.userInfo.email = email; message.userInfo.email_option = $('#' + formName + ' [name=ep_email_option]').val(); message.userInfo.email_onStart = $('#' + formName + ' [name=ep_email_onStart]').is(':checked'); message.userInfo.email_onEnd = $('#' + formName + ' [name=ep_email_onEnd]').is(':checked'); message.userInfo.formName = formName; message.userInfo.userId = userId; if(email){ pad.collabClient.sendMessage(message); } }
javascript
{ "resource": "" }
q10438
getDataForUserId
train
function getDataForUserId(formName) { var userId = pad.getUserId(); var message = {}; message.type = 'USERINFO_GET'; message.padId = pad.getPadId(); message.userInfo = {}; message.userInfo.userId = userId; message.userInfo.formName = formName; pad.collabClient.sendMessage(message); }
javascript
{ "resource": "" }
q10439
showAlreadyRegistered
train
function showAlreadyRegistered(type){ if (type == "malformedEmail") { var msg = window._('ep_email_notifications.msgEmailMalformed'); } else if (type == "alreadyRegistered") { var msg = window._('ep_email_notifications.msgAlreadySubscr'); } else { var msg = window._('ep_email_notifications.msgUnknownErr'); } $.gritter.add({ // (string | mandatory) the heading of the notification title: window._('ep_email_notifications.titleGritterSubscr'), // (string | mandatory) the text inside the notification text: msg, // (int | optional) the time you want it to be alive for before fading out time: 7000, // (string | optional) add a class name to the gritter msg class_name: "emailNotificationsSubscrResponseBad" }); }
javascript
{ "resource": "" }
q10440
resolveBase
train
function resolveBase(app) { const paths = [ { name: 'base', path: path.resolve(cwd, 'node_modules/base') }, { name: 'base-app', path: path.resolve(cwd, 'node_modules/base-app') }, { name: 'assemble-core', path: path.resolve(cwd, 'node_modules/assemble-core') }, { name: 'assemble', path: path.resolve(cwd, 'node_modules/assemble') }, { name: 'generate', path: path.resolve(cwd, 'node_modules/generate') }, { name: 'update', path: path.resolve(cwd, 'node_modules/update') }, { name: 'verb', path: path.resolve(cwd, 'node_modules/verb') }, { name: 'core', path: path.resolve(__dirname, '..') } ]; for (const file of paths) { if (opts.app && file.name === opts.app && (app = resolveApp(file))) { return app; } } if (opts.app) { app = resolveApp({ name: opts.app, path: path.resolve(cwd, 'node_modules', opts.app) }); } return app; }
javascript
{ "resource": "" }
q10441
resolveApp
train
function resolveApp(file) { if (fs.existsSync(file.path)) { const Base = require(file.path); const base = new Base(null, opts); base.define('log', log); if (typeof base.name === 'undefined') { base.name = file.name; } // if this is not an instance of base-app, load // app-base plugins onto the instance // if (file.name !== 'core') { // Core.plugins(base); // } return base; } }
javascript
{ "resource": "" }
q10442
train
function(svg, options) { // the svg element to render charts to this._svg = svg; this._attributes = options || {}; // outer margins this._margin = { top: 20, bottom: 75, left: this._attributes.yScales.primary.displayOnAxis === 'left' ? 75 : 25, right: this._attributes.yScales.primary.displayOnAxis === 'left' ? 25 : 75 }; }
javascript
{ "resource": "" }
q10443
allStars
train
function allStars (query) { if (typeof query === 'string') return lookupString(query) else if (Array.isArray(query)) return lookupArray(query) else if (typeof query === 'object') return lookupObject(query) return null }
javascript
{ "resource": "" }
q10444
ParseOfflineRequest
train
function ParseOfflineRequest (requestType, options) { if (!(this instanceof ParseOfflineRequest)) { return new ParseOfflineRequest(requestType, options); } this.requestType = requestType; this.options = options; this.requestMethod = this.httpGETPUTorPOST(requestType); this.params = ''; return this; }
javascript
{ "resource": "" }
q10445
requireJslint
train
function requireJslint(jslintFileName) { /*jslint stupid: true */// JSLint doesn't like "*Sync" functions, but in this require-like function async would be overkill var jslintCode = bufferToScript( fs.readFileSync( path.join(__dirname, jslintFileName) ) ); /*jslint stupid: false */ var sandbox = {}; vm.runInNewContext(jslintCode, sandbox, jslintFileName); return sandbox.JSLINT; }
javascript
{ "resource": "" }
q10446
unpckItem
train
function unpckItem(reader) { const bitSet0 = pck.readU8(reader); const time = pck.readU32(reader); const descendants = pck.readUVar(reader); const id = pck.readUVar(reader); const score = pck.readUVar(reader); const by = pck.readUtf8(reader); const title = pck.readUtf8(reader); const url = (bitSet0 & (1 << 1)) !== 0 ? pck.readUtf8(reader) : ""; const kids = (bitSet0 & (1 << 0)) !== 0 ? pck.readArray(reader, pck.readUVar) : null; return new Item( by, descendants, id, kids, score, time, title, url, ); }
javascript
{ "resource": "" }
q10447
AccessContext
train
function AccessContext(context, app) { if (!(this instanceof AccessContext)) { return new AccessContext(context, app); } context = context || {}; this.app = app; this.principals = context.principals || []; var model = context.model; model = ('string' === typeof model) ? app.model(model) : model; this.model = model; this.modelName = model && model.modelName; this.modelId = context.id || context.modelId; this.property = context.property || AccessContext.ALL; this.method = context.method; this.sharedMethod = context.sharedMethod; this.sharedClass = this.sharedMethod && this.sharedMethod.sharedClass; if(this.sharedMethod) { this.methodNames = this.sharedMethod.aliases.concat([this.sharedMethod.name]); } else { this.methodNames = []; } if(this.sharedMethod) { this.accessType = sec.getAccessTypeForMethod(this.sharedMethod); } this.accessType = context.accessType || AccessContext.ALL; this.accessToken = context.accessToken || app.model('AccessToken').ANONYMOUS; var principalType = context.principalType || Principal.USER; var principalId = context.principalId || undefined; var principalName = context.principalName || undefined; if (principalId) { this.addPrincipal(principalType, principalId, principalName); } var token = this.accessToken || {}; if (token.userId) { this.addPrincipal(Principal.USER, token.userId); } if (token.appId) { this.addPrincipal(Principal.APPLICATION, token.appId); } this.remoteContext = context.remoteContext; }
javascript
{ "resource": "" }
q10448
Principal
train
function Principal(type, id, name) { if (!(this instanceof Principal)) { return new Principal(type, id, name); } this.type = type; this.id = id; this.name = name; }
javascript
{ "resource": "" }
q10449
AccessRequest
train
function AccessRequest(model, property, accessType, permission, methodNames) { if (!(this instanceof AccessRequest)) { return new AccessRequest(model, property, accessType, permission, methodNames); } if (arguments.length === 1 && typeof model === 'object') { // The argument is an object that contains all required properties var obj = model || {}; this.model = obj.model || AccessContext.ALL; this.property = obj.property || AccessContext.ALL; this.accessType = obj.accessType || AccessContext.ALL; this.permission = obj.permission || AccessContext.DEFAULT; this.methodNames = methodNames || []; } else { this.model = model || AccessContext.ALL; this.property = property || AccessContext.ALL; this.accessType = accessType || AccessContext.ALL; this.permission = permission || AccessContext.DEFAULT; this.methodNames = methodNames || []; } }
javascript
{ "resource": "" }
q10450
ChangeRecord
train
function ChangeRecord(object, type, name, oldValue) { this.object = object; this.type = type; this.name = name; this.oldValue = oldValue; }
javascript
{ "resource": "" }
q10451
Splice
train
function Splice(object, index, removed, addedCount) { ChangeRecord.call(this, object, 'splice', String(index)); this.index = index; this.removed = removed; this.addedCount = addedCount; }
javascript
{ "resource": "" }
q10452
diffBasic
train
function diffBasic(value, oldValue) { if (value && oldValue && typeof value === 'object' && typeof oldValue === 'object') { // Allow dates and Number/String objects to be compared var valueValue = value.valueOf(); var oldValueValue = oldValue.valueOf(); // Allow dates and Number/String objects to be compared if (typeof valueValue !== 'object' && typeof oldValueValue !== 'object') { return diffBasic(valueValue, oldValueValue); } } // If a value has changed call the callback if (typeof value === 'number' && typeof oldValue === 'number' && isNaN(value) && isNaN(oldValue)) { return false; } else { return value !== oldValue; } }
javascript
{ "resource": "" }
q10453
sharedPrefix
train
function sharedPrefix(current, old, searchLength) { for (var i = 0; i < searchLength; i++) { if (diffBasic(current[i], old[i])) { return i; } } return searchLength; }
javascript
{ "resource": "" }
q10454
readControls
train
function readControls( controlPath, filingCabinet ) { logger.showInfo( '*** Reading controls...' ); // Initialize the store - engine controls. logger.showInfo( 'Engine controls:' ); getControls( '/node_modules/md-site-engine/controls', '', filingCabinet.controls ); // Initialize the store - user controls. logger.showInfo( 'Site controls:' ); getControls( controlPath, '', filingCabinet.controls ); }
javascript
{ "resource": "" }
q10455
stopSeries
train
function stopSeries(err) { if(err instanceof Error || (typeof err === 'object' && (err.code || err.error))) { stopErr = err; } isStopped = true; }
javascript
{ "resource": "" }
q10456
train
function() { var editDataSource = this.getProperty( 'editDataSource' ); var destinationDataSource = this.getProperty( 'destinationDataSource' ); var destinationProperty = this.getProperty( 'destinationProperty' ); if( this._isObjectDataSource( editDataSource ) ) { var editedItem = editDataSource.getSelectedItem(); var originItem = destinationDataSource.getProperty( destinationProperty ); if( this._isRootElementPath( destinationProperty ) ) { this._overrideOriginItem( originItem, editedItem ); destinationDataSource._includeItemToModifiedSet( originItem ); destinationDataSource.saveItem( originItem, function() { destinationDataSource.updateItems(); } ); } else { destinationDataSource.setProperty( destinationProperty, editedItem ); } } else { destinationDataSource.updateItems(); } }
javascript
{ "resource": "" }
q10457
getContent
train
function getContent( contentFile, source ) { // Determine the path. var contentPath = path.join( process.cwd(), contentFile ); // Get the file content. var html = fs.readFileSync( contentPath, { encoding: 'utf-8' } ); // Find tokens. var re = /(\{\{\s*[=#.]?[\w-\/]+\s*}})/g; var tokens = [ ]; var j = 0; for (var matches = re.exec( html ); matches !== null; matches = re.exec( html )) { tokens[ j++ ] = new Token( matches[ 1 ] ); } // Create and return the content. return new Content( html, tokens, source ); }
javascript
{ "resource": "" }
q10458
train
function(uri, _method){ if (!(this instanceof Verity)) { return new Verity(uri, _method); } this.uri = urlgrey(uri || 'http://localhost:80'); this._method = _method || 'GET'; this._body = ''; this.cookieJar = request.jar(); this.client = request.defaults({ timeout:3000, jar: this.cookieJar }); this.headers = {}; this.cookies = {}; this.shouldLog = true; this.expectedBody = null; this.jsonModeOn = false; this._expectedHeaders = {}; this._expectedCookies = {}; this._expectations = {}; this._unnamedExpectationCount = 0; }
javascript
{ "resource": "" }
q10459
type
train
function type(filename, opts) { opts = opts || {}; if (opts.parse && typeof opts.parse === 'string') { return opts.parse; } var ext = path.extname(filename); return ext || 'json'; }
javascript
{ "resource": "" }
q10460
startServer
train
function startServer() { var defer = q.defer(); var serverConfig = { server: { baseDir: wpath, directory: true }, startPath: 'docs/index.html', // browser: "google chrome", logPrefix: 'SERVER' }; browserSync.init(serverConfig, defer.resolve); return defer.promise; }
javascript
{ "resource": "" }
q10461
ChunkedStreamManager_requestRange
train
function ChunkedStreamManager_requestRange( begin, end, callback) { end = Math.min(end, this.length); var beginChunk = this.getBeginChunk(begin); var endChunk = this.getEndChunk(end); var chunks = []; for (var chunk = beginChunk; chunk < endChunk; ++chunk) { chunks.push(chunk); } this.requestChunks(chunks, callback); }
javascript
{ "resource": "" }
q10462
ChunkedStreamManager_groupChunks
train
function ChunkedStreamManager_groupChunks(chunks) { var groupedChunks = []; var beginChunk = -1; var prevChunk = -1; for (var i = 0; i < chunks.length; ++i) { var chunk = chunks[i]; if (beginChunk < 0) { beginChunk = chunk; } if (prevChunk >= 0 && prevChunk + 1 !== chunk) { groupedChunks.push({ beginChunk: beginChunk, endChunk: prevChunk + 1 }); beginChunk = chunk; } if (i + 1 === chunks.length) { groupedChunks.push({ beginChunk: beginChunk, endChunk: chunk + 1 }); } prevChunk = chunk; } return groupedChunks; }
javascript
{ "resource": "" }
q10463
PDFDocument_checkHeader
train
function PDFDocument_checkHeader() { var stream = this.stream; stream.reset(); if (find(stream, '%PDF-', 1024)) { // Found the header, trim off any garbage before it. stream.moveStart(); // Reading file format version var MAX_VERSION_LENGTH = 12; var version = '', ch; while ((ch = stream.getByte()) > 0x20) { // SPACE if (version.length >= MAX_VERSION_LENGTH) { break; } version += String.fromCharCode(ch); } if (!this.pdfFormatVersion) { // removing "%PDF-"-prefix this.pdfFormatVersion = version.substring(5); } return; } // May not be a PDF file, continue anyway. }
javascript
{ "resource": "" }
q10464
Dict
train
function Dict(xref) { // Map should only be used internally, use functions below to access. this.map = Object.create(null); this.xref = xref; this.objId = null; this.__nonSerializable__ = nonSerializable; // disable cloning of the Dict }
javascript
{ "resource": "" }
q10465
Dict_get
train
function Dict_get(key1, key2, key3) { var value; var xref = this.xref; if (typeof (value = this.map[key1]) !== 'undefined' || key1 in this.map || typeof key2 === 'undefined') { return xref ? xref.fetchIfRef(value) : value; } if (typeof (value = this.map[key2]) !== 'undefined' || key2 in this.map || typeof key3 === 'undefined') { return xref ? xref.fetchIfRef(value) : value; } value = this.map[key3] || null; return xref ? xref.fetchIfRef(value) : value; }
javascript
{ "resource": "" }
q10466
Dict_getAll
train
function Dict_getAll() { var all = Object.create(null); var queue = null; var key, obj; for (key in this.map) { obj = this.get(key); if (obj instanceof Dict) { if (isRecursionAllowedFor(obj)) { (queue || (queue = [])).push({target: all, key: key, obj: obj}); } else { all[key] = this.getRaw(key); } } else { all[key] = obj; } } if (!queue) { return all; } // trying to take cyclic references into the account var processed = Object.create(null); while (queue.length > 0) { var item = queue.shift(); var itemObj = item.obj; var objId = itemObj.objId; if (objId && objId in processed) { item.target[item.key] = processed[objId]; continue; } var dereferenced = Object.create(null); for (key in itemObj.map) { obj = itemObj.get(key); if (obj instanceof Dict) { if (isRecursionAllowedFor(obj)) { queue.push({target: dereferenced, key: key, obj: obj}); } else { dereferenced[key] = itemObj.getRaw(key); } } else { dereferenced[key] = obj; } } if (objId) { processed[objId] = dereferenced; } item.target[item.key] = dereferenced; } return all; }
javascript
{ "resource": "" }
q10467
readToken
train
function readToken(data, offset) { var token = '', ch = data[offset]; while (ch !== 13 && ch !== 10) { if (++offset >= data.length) { break; } token += String.fromCharCode(ch); ch = data[offset]; } return token; }
javascript
{ "resource": "" }
q10468
convertToRgb
train
function convertToRgb(cs, src, srcOffset, maxVal, dest, destOffset) { // XXX: Lab input is in the range of [0, 100], [amin, amax], [bmin, bmax] // not the usual [0, 1]. If a command like setFillColor is used the src // values will already be within the correct range. However, if we are // converting an image we have to map the values to the correct range given // above. // Ls,as,bs <---> L*,a*,b* in the spec var Ls = src[srcOffset]; var as = src[srcOffset + 1]; var bs = src[srcOffset + 2]; if (maxVal !== false) { Ls = decode(Ls, maxVal, 0, 100); as = decode(as, maxVal, cs.amin, cs.amax); bs = decode(bs, maxVal, cs.bmin, cs.bmax); } // Adjust limits of 'as' and 'bs' as = as > cs.amax ? cs.amax : as < cs.amin ? cs.amin : as; bs = bs > cs.bmax ? cs.bmax : bs < cs.bmin ? cs.bmin : bs; // Computes intermediate variables X,Y,Z as per spec var M = (Ls + 16) / 116; var L = M + (as / 500); var N = M - (bs / 200); var X = cs.XW * fn_g(L); var Y = cs.YW * fn_g(M); var Z = cs.ZW * fn_g(N); var r, g, b; // Using different conversions for D50 and D65 white points, // per http://www.color.org/srgb.pdf if (cs.ZW < 1) { // Assuming D50 (X=0.9642, Y=1.00, Z=0.8249) r = X * 3.1339 + Y * -1.6170 + Z * -0.4906; g = X * -0.9785 + Y * 1.9160 + Z * 0.0333; b = X * 0.0720 + Y * -0.2290 + Z * 1.4057; } else { // Assuming D65 (X=0.9505, Y=1.00, Z=1.0888) r = X * 3.2406 + Y * -1.5372 + Z * -0.4986; g = X * -0.9689 + Y * 1.8758 + Z * 0.0415; b = X * 0.0557 + Y * -0.2040 + Z * 1.0570; } // clamp color values to [0,1] range then convert to [0,255] range. dest[destOffset] = r <= 0 ? 0 : r >= 1 ? 255 : Math.sqrt(r) * 255 | 0; dest[destOffset + 1] = g <= 0 ? 0 : g >= 1 ? 255 : Math.sqrt(g) * 255 | 0; dest[destOffset + 2] = b <= 0 ? 0 : b >= 1 ? 255 : Math.sqrt(b) * 255 | 0; }
javascript
{ "resource": "" }
q10469
getTransfers
train
function getTransfers(queue) { var transfers = []; var fnArray = queue.fnArray, argsArray = queue.argsArray; for (var i = 0, ii = queue.length; i < ii; i++) { switch (fnArray[i]) { case OPS.paintInlineImageXObject: case OPS.paintInlineImageXObjectGroup: case OPS.paintImageMaskXObject: var arg = argsArray[i][0]; // first param in imgData if (!arg.cached) { transfers.push(arg.data.buffer); } break; } } return transfers; }
javascript
{ "resource": "" }
q10470
isProblematicUnicodeLocation
train
function isProblematicUnicodeLocation(code) { if (code <= 0x1F) { // Control chars return true; } if (code >= 0x80 && code <= 0x9F) { // Control chars return true; } if ((code >= 0x2000 && code <= 0x200F) || // General punctuation chars (code >= 0x2028 && code <= 0x202F) || (code >= 0x2060 && code <= 0x206F)) { return true; } if (code >= 0xFFF0 && code <= 0xFFFF) { // Specials Unicode block return true; } switch (code) { case 0x7F: // Control char case 0xA0: // Non breaking space case 0xAD: // Soft hyphen case 0x2011: // Non breaking hyphen case 0x205F: // Medium mathematical space case 0x25CC: // Dotted circle (combining mark) return true; } if ((code & ~0xFF) === 0x0E00) { // Thai/Lao chars (with combining mark) return true; } return false; }
javascript
{ "resource": "" }
q10471
type1FontGlyphMapping
train
function type1FontGlyphMapping(properties, builtInEncoding, glyphNames) { var charCodeToGlyphId = Object.create(null); var glyphId, charCode, baseEncoding; if (properties.baseEncodingName) { // If a valid base encoding name was used, the mapping is initialized with // that. baseEncoding = Encodings[properties.baseEncodingName]; for (charCode = 0; charCode < baseEncoding.length; charCode++) { glyphId = glyphNames.indexOf(baseEncoding[charCode]); if (glyphId >= 0) { charCodeToGlyphId[charCode] = glyphId; } else { charCodeToGlyphId[charCode] = 0; // notdef } } } else if (!!(properties.flags & FontFlags.Symbolic)) { // For a symbolic font the encoding should be the fonts built-in // encoding. for (charCode in builtInEncoding) { charCodeToGlyphId[charCode] = builtInEncoding[charCode]; } } else { // For non-symbolic fonts that don't have a base encoding the standard // encoding should be used. baseEncoding = Encodings.StandardEncoding; for (charCode = 0; charCode < baseEncoding.length; charCode++) { glyphId = glyphNames.indexOf(baseEncoding[charCode]); if (glyphId >= 0) { charCodeToGlyphId[charCode] = glyphId; } else { charCodeToGlyphId[charCode] = 0; // notdef } } } // Lastly, merge in the differences. var differences = properties.differences; if (differences) { for (charCode in differences) { var glyphName = differences[charCode]; glyphId = glyphNames.indexOf(glyphName); if (glyphId >= 0) { charCodeToGlyphId[charCode] = glyphId; } else { charCodeToGlyphId[charCode] = 0; // notdef } } } return charCodeToGlyphId; }
javascript
{ "resource": "" }
q10472
Type1Font
train
function Type1Font(name, file, properties) { // Some bad generators embed pfb file as is, we have to strip 6-byte headers. // Also, length1 and length2 might be off by 6 bytes as well. // http://www.math.ubc.ca/~cass/piscript/type1.pdf var PFB_HEADER_SIZE = 6; var headerBlockLength = properties.length1; var eexecBlockLength = properties.length2; var pfbHeader = file.peekBytes(PFB_HEADER_SIZE); var pfbHeaderPresent = pfbHeader[0] === 0x80 && pfbHeader[1] === 0x01; if (pfbHeaderPresent) { file.skip(PFB_HEADER_SIZE); headerBlockLength = (pfbHeader[5] << 24) | (pfbHeader[4] << 16) | (pfbHeader[3] << 8) | pfbHeader[2]; } // Get the data block containing glyphs and subrs informations var headerBlock = new Stream(file.getBytes(headerBlockLength)); var headerBlockParser = new Type1Parser(headerBlock); headerBlockParser.extractFontHeader(properties); if (pfbHeaderPresent) { pfbHeader = file.getBytes(PFB_HEADER_SIZE); eexecBlockLength = (pfbHeader[5] << 24) | (pfbHeader[4] << 16) | (pfbHeader[3] << 8) | pfbHeader[2]; } // Decrypt the data blocks and retrieve it's content var eexecBlock = new Stream(file.getBytes(eexecBlockLength)); var eexecBlockParser = new Type1Parser(eexecBlock, true); var data = eexecBlockParser.extractFontProgram(); for (var info in data.properties) { properties[info] = data.properties[info]; } var charstrings = data.charstrings; var type2Charstrings = this.getType2Charstrings(charstrings); var subrs = this.getType2Subrs(data.subrs); this.charstrings = charstrings; this.data = this.wrap(name, type2Charstrings, this.charstrings, subrs, properties); this.seacs = this.getSeacs(data.charstrings); }
javascript
{ "resource": "" }
q10473
CFFDict_setByKey
train
function CFFDict_setByKey(key, value) { if (!(key in this.keyToNameMap)) { return false; } // ignore empty values if (value.length === 0) { return true; } var type = this.types[key]; // remove the array wrapping these types of values if (type === 'num' || type === 'sid' || type === 'offset') { value = value[0]; } this.values[key] = value; return true; }
javascript
{ "resource": "" }
q10474
handleImageData
train
function handleImageData(handler, xref, res, image) { if (image instanceof JpegStream && image.isNativelyDecodable(xref, res)) { // For natively supported jpegs send them to the main thread for decoding. var dict = image.dict; var colorSpace = dict.get('ColorSpace', 'CS'); colorSpace = ColorSpace.parse(colorSpace, xref, res); var numComps = colorSpace.numComps; var decodePromise = handler.sendWithPromise('JpegDecode', [image.getIR(), numComps]); return decodePromise.then(function (message) { var data = message.data; return new Stream(data, 0, data.length, image.dict); }); } else { return Promise.resolve(image); } }
javascript
{ "resource": "" }
q10475
formatName
train
function formatName(input, noCamelCase){ input = input.replace(/^-+/, ""); // Convert kebab-case to camelCase if(!noCamelCase && /-/.test(input)) input = input.toLowerCase().replace(/([a-z])-+([a-z])/g, (_, a, b) => a + b.toUpperCase()); return input; }
javascript
{ "resource": "" }
q10476
match
train
function match(input, patterns = []){ if(!patterns || 0 === patterns.length) return false; input = String(input); patterns = arrayify(patterns).filter(Boolean); for(const pattern of patterns) if((pattern === input && "string" === typeof pattern) || (pattern instanceof RegExp) && pattern.test(input)) return true; return false; }
javascript
{ "resource": "" }
q10477
uniqueStrings
train
function uniqueStrings(input){ const output = {}; for(let i = 0, l = input.length; i < l; ++i) output[input[i]] = true; return Object.keys(output); }
javascript
{ "resource": "" }
q10478
unstringify
train
function unstringify(input){ input = String(input || ""); const tokens = []; const {length} = input; let quoteChar = ""; // Quote-type enclosing current region let tokenData = ""; // Characters currently being collected let isEscaped = false; // Flag identifying an escape sequence for(let i = 0; i < length; ++i){ const char = input[i]; // Previous character was a backslash if(isEscaped){ tokenData += char; isEscaped = false; continue; } // Whitespace: terminate token unless quoted if(!quoteChar && /[ \t\n]/.test(char)){ tokenData && tokens.push(tokenData); tokenData = ""; continue; } // Backslash: escape next character if("\\" === char){ isEscaped = true; // Swallow backslash if it escapes a metacharacter const next = input[i + 1]; if(quoteChar && (quoteChar === next || "\\" === next) || !quoteChar && /[- \t\n\\'"`]/.test(next)) continue; } // Quote marks else if((!quoteChar || char === quoteChar) && /['"`]/.test(char)){ quoteChar = quoteChar === char ? "" : char; continue; } tokenData += char; } if(tokenData) tokens.push(tokenData); return tokens; }
javascript
{ "resource": "" }
q10479
autoOpts
train
function autoOpts(input, config = {}){ const opts = new Object(null); const argv = []; let argvEnd; // Bail early if passed a blank string if(!input) return opts; // Stop parsing options after a double-dash const stopAt = input.indexOf("--"); if(stopAt !== -1){ argvEnd = input.slice(stopAt + 1); input = input.slice(0, stopAt); } for(let i = 0, l = input.length; i < l; ++i){ let name = input[i]; // Appears to be an option if(/^-/.test(name)){ // Equals sign is used, should it become the option's value? if(!config.ignoreEquals && /=/.test(name)){ const split = name.split(/=/); name = formatName(split[0], config.noCamelCase); opts[name] = split.slice(1).join("="); } else{ name = formatName(name, config.noCamelCase); // Treat a following non-option as this option's value const next = input[i + 1]; if(next != null && !/^-/.test(next)){ // There's another option after this one. Collect multiple non-options into an array. const nextOpt = input.findIndex((s, I) => I > i && /^-/.test(s)); if(nextOpt !== -1){ opts[name] = input.slice(i + 1, nextOpt); // There's only one value to store; don't wrap it in an array if(nextOpt - i < 3) opts[name] = opts[name][0]; i = nextOpt - 1; } // We're at the last option. Don't touch argv; assume it's a boolean-type option else opts[name] = true; } // No arguments defined. Assume it's a boolean-type option. else opts[name] = true; } } // Non-option: add to argv else argv.push(name); } // Add any additional arguments that were found after a "--" delimiter if(argvEnd) argv.push(...argvEnd); return { options: opts, argv: argv, }; }
javascript
{ "resource": "" }
q10480
resolveDuplicate
train
function resolveDuplicate(option, name, value){ switch(duplicates){ // Use the first value (or set of values); discard any following duplicates case "use-first": return result.options[name]; // Use the last value (or set of values); discard any preceding duplicates. Default. case "use-last": default: return result.options[name] = value; // Use the first/last options; treat any following/preceding duplicates as argv items respectively case "limit-first": case "limit-last": result.argv.push(option.prevMatchedName, ...arrayify(value)); break; // Throw an exception case "error": const error = new TypeError(`Attempting to reassign option "${name}" with value(s) ${JSON.stringify(value)}`); error.affectedOption = option; error.affectedValue = value; throw error; // Add parameters of duplicate options to the argument list of the first case "append": const oldValues = arrayify(result.options[name]); const newValues = arrayify(value); result.options[name] = oldValues.concat(newValues); break; // Store parameters of duplicated options in a multidimensional array case "stack": { let oldValues = result.options[name]; const newValues = arrayify(value); // This option hasn't been "stacked" yet if(!option.stacked){ oldValues = arrayify(oldValues); result.options[name] = [oldValues, newValues]; option.stacked = true; } // Already "stacked", so just shove the values onto the end of the array else result.options[name].push(arrayify(newValues)); break; } // Store each duplicated value in an array using the order they appear case "stack-values": { let values = result.options[name]; // First time "stacking" this option (nesting its value/s inside an array) if(!option.stacked){ const stack = []; for(const value of arrayify(values)) stack.push([value]); values = stack; option.stacked = true; } arrayify(value).forEach((v, i) => { // An array hasn't been created at this index yet, // because an earlier option wasn't given enough parameters. if(undefined === values[i]) values[i] = Array(values[0].length - 1); values[i].push(v); }); result.options[name] = values; break; } } }
javascript
{ "resource": "" }
q10481
setValue
train
function setValue(option, value){ // Assign the value only to the option name it matched if(noAliasPropagation){ let name = option.lastMatchedName; // Special alternative: // In lieu of using the matched option name, use the first --long-name only if("first-only" === noAliasPropagation) name = option.longNames[0] || option.shortNames[0]; // camelCase? name = formatName(name, noCamelCase); // This option's already been set before if(result.options[name]) resolveDuplicate(option, name, value); else result.options[name] = value; } // Copy across every alias this option's recognised by else{ const {names} = option; for(let name of names){ // Decide whether to camelCase this option name name = formatName(name, noCamelCase); // Ascertain if this option's being duplicated if(result.options[name]) resolveDuplicate(option, name, value); result.options[name] = value; } } }
javascript
{ "resource": "" }
q10482
wrapItUp
train
function wrapItUp(){ let optValue = currentOption.values; // Don't store solitary values in an array. Store them directly as strings if(1 === currentOption.arity && !currentOption.variadic) optValue = optValue[0]; setValue(currentOption, optValue); currentOption.values = []; currentOption = null; }
javascript
{ "resource": "" }
q10483
flip
train
function flip(input){ input = input.reverse(); // Flip any options back into the right order for(let i = 0, l = input.length; i < l; ++i){ const arg = input[i]; const opt = shortNames[arg] || longNames[arg]; if(opt){ const from = Math.max(0, i - opt.arity); const to = i + 1; const extract = input.slice(from, to).reverse(); input.splice(from, extract.length, ...extract); } } return input; }
javascript
{ "resource": "" }
q10484
readReferences
train
function readReferences( componentPath, referenceFile, filingCabinet ) { logger.showInfo( '*** Reading references...' ); // Initialize the store. getReferences( componentPath, 0, '', referenceFile, filingCabinet.references ); }
javascript
{ "resource": "" }
q10485
getReferences
train
function getReferences( componentDir, level, levelPath, referenceFile, referenceDrawer ) { // Read directory items. var componentPath = path.join( process.cwd(), componentDir ); var items = fs.readdirSync( componentPath ); items.forEach( function ( item ) { var itemPath = path.join( componentDir, item ); var prefix = levelPath === '' ? '' : levelPath + '/'; // Get item info. var stats = fs.statSync( path.join( process.cwd(), itemPath ) ); if (stats.isDirectory()) { // Get language specific references. if (level === 0) getReferences( itemPath, level + 1, prefix + item, referenceFile, referenceDrawer ); } else if (stats.isFile()) { var ext = path.extname( item ); if (ext === '.txt' && path.basename( item ) === referenceFile) { // Read reference file. var componentPath = prefix + path.basename( item, ext ); referenceDrawer.add( componentPath, getReference( itemPath ) ); logger.fileProcessed( 'Reference', itemPath ); } } } ) }
javascript
{ "resource": "" }
q10486
train
function() { this.addController(jsCow.res.controller.buttongroup); this.addModel(jsCow.res.model.buttongroup); this.addView(jsCow.res.view.buttongroup); return this; }
javascript
{ "resource": "" }
q10487
fetchAuthors
train
function fetchAuthors (forPackages, opts) { opts = normalizeOpts(opts) // start with npmUser and email from registry return fetchRegistry(forPackages, {}, opts) .then(persons => { // reduce duplicates and add pre-known aliases return reduceDuplicates(persons, opts) }) .then(persons => { // add name, githubUser, and twitter from npm profile return fetchProfiles(persons, opts) }) .then(persons => { // finish with name and email from github return fetchGithub(persons, opts) }) }
javascript
{ "resource": "" }
q10488
train
function (color, func) { exports[color] = function(str) { return func.apply(str); }; String.prototype.__defineGetter__(color, func); }
javascript
{ "resource": "" }
q10489
create
train
function create(r, g, b, a) { return [r || 0, g || 0, b || 0, (a === undefined) ? 1 : a]; }
javascript
{ "resource": "" }
q10490
setRGB
train
function setRGB(color, r, g, b, a) { color[0] = r; color[1] = g; color[2] = b; color[3] = (a !== undefined) ? a : 1; return color; }
javascript
{ "resource": "" }
q10491
fromHSV
train
function fromHSV(h, s, v, a) { var color = create(); setHSV(color, h, s, v, a) return color; }
javascript
{ "resource": "" }
q10492
setHSV
train
function setHSV(color, h, s, v, a) { a = a || 1; var i = Math.floor(h * 6); var f = h * 6 - i; var p = v * (1 - s); var q = v * (1 - f * s); var t = v * (1 - (1 - f) * s); switch (i % 6) { case 0: color[0] = v; color[1] = t; color[2] = p; break; case 1: color[0] = q; color[1] = v; color[2] = p; break; case 2: color[0] = p; color[1] = v; color[2] = t; break; case 3: color[0] = p; color[1] = q; color[2] = v; break; case 4: color[0] = t; color[1] = p; color[2] = v; break; case 5: color[0] = v; color[1] = p; color[2] = q; break; } color[3] = a; return color; }
javascript
{ "resource": "" }
q10493
fromHSL
train
function fromHSL(h, s, l, a) { var color = create(); setHSL(color, h, s, l, a); return color; }
javascript
{ "resource": "" }
q10494
setHSL
train
function setHSL(color, h, s, l, a) { a = a || 1; function hue2rgb(p, q, t) { if (t < 0) { t += 1; } if (t > 1) { t -= 1; } if (t < 1/6) { return p + (q - p) * 6 * t; } if (t < 1/2) { return q; } if (t < 2/3) { return p + (q - p) * (2/3 - t) * 6; } return p; } if (s === 0) { color[0] = color[1] = color[2] = l; // achromatic } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; color[0] = hue2rgb(p, q, h + 1/3); color[1] = hue2rgb(p, q, h); color[2] = hue2rgb(p, q, h - 1/3); } color[3] = a; return color; }
javascript
{ "resource": "" }
q10495
getHex
train
function getHex(color) { var c = [ color[0], color[1], color[2] ].map(function(val) { return Math.floor(val * 255); }); return "#" + ((c[2] | c[1] << 8 | c[0] << 16) | 1 << 24) .toString(16) .slice(1) .toUpperCase(); }
javascript
{ "resource": "" }
q10496
fromXYZ
train
function fromXYZ(x, y, z) { var color = create(); setXYZ(color, x, y, z); return color; }
javascript
{ "resource": "" }
q10497
setXYZ
train
function setXYZ(color, x, y, z) { var r = x * 3.2406 + y * -1.5372 + z * -0.4986; var g = x * -0.9689 + y * 1.8758 + z * 0.0415; var b = x * 0.0557 + y * -0.2040 + z * 1.0570; color[0] = fromXYZValue(r); color[1] = fromXYZValue(g); color[2] = fromXYZValue(b); color[3] = 1.0; return color; }
javascript
{ "resource": "" }
q10498
getXYZ
train
function getXYZ(color) { var r = toXYZValue(color[0]); var g = toXYZValue(color[1]); var b = toXYZValue(color[2]); return [ r * 0.4124 + g * 0.3576 + b * 0.1805, r * 0.2126 + g * 0.7152 + b * 0.0722, r * 0.0193 + g * 0.1192 + b * 0.9505 ] }
javascript
{ "resource": "" }
q10499
fromLab
train
function fromLab(l, a, b) { var color = create(); setLab(color, l, a, b); return color; }
javascript
{ "resource": "" }