_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q36300
recurseSrcDirectories
train
function recurseSrcDirectories (grunt, fileData, options) { let promises = []; // Ignore everything except directories and Javascript files. // Store function in array for recursive-readdir module. let ignoreCallback = [(file, stats) => !(stats.isDirectory() || path.extname(file) === '.js')]; for (let i = 0, max = fileData.src.length; i < max; i++) { promises.push(readDir(fileData.src[i], ignoreCallback).then((value) => value, (err) => err)); } Promise.all(promises) .then((values) => { streamMatches(grunt, fileData, options, values, values.flat()); }, throwAsyncError); }
javascript
{ "resource": "" }
q36301
streamMatches
train
function streamMatches (grunt, fileData, options, matches, flattenedMatches) { // Run optional tasks after we stream matches to dest. stream.createWriteStream(fileData.dest, () => { require('./dev/test')(grunt, fileData, options, throwAsyncError).performTests(); if (options.deploy) { require('./deploy/parse')(grunt, fileData, options, asyncDone, throwAsyncError, flattenedMatches); } else { // Never end task if watch option is true and there are src directories to watch. if (options.watch && fileData.src.length > 0) { require('./dev/watch')(grunt, fileData, options, throwAsyncError, matches, flattenedMatches); } else { asyncDone(true); } } }); // Place the flattened matches between the start wrapper and the end // wrapper into a single dimensional array. stream.pipeFileArray([fileData.tmpWrapStart, flattenedMatches, fileData.tmpWrapEnd].flat()); }
javascript
{ "resource": "" }
q36302
train
function (buildConfig) { var configFile; var suffix = 'karma'; if (buildConfig.nodeProject) { suffix = 'mocha'; } configFile = path.join(currentDirectory, '../lint/eslint/eslintrc-' + suffix + '.js'); return configFile; }
javascript
{ "resource": "" }
q36303
train
function (buildConfig, config) { var testConfig = extend(true, {}, config || {}, { nomen: true, unparam: true, predef: [ 'it', 'describe' ] }); if (!buildConfig.nodeProject) { testConfig.predef.push('angular'); } return testConfig; }
javascript
{ "resource": "" }
q36304
train
function (buildConfig, options) { options = options || {}; var includeLib = options.includeLib; if (includeLib === undefined) { includeLib = true; } var src = []; if (includeLib) { if (buildConfig.nodeProject) { src = src.concat([ '*.js', '<%=buildConfig.libDirectory%>/**/*.js' ]); } else if (buildConfig.bowerJSON && buildConfig.bowerJSON.main) { src.push(buildConfig.bowerJSON.main); } } if (options.includeBuild) { src.push('project/**/*.js'); } if (options.includeTest) { src.push('<%=buildConfig.testDirectory%>/**/*spec.js'); } return src; }
javascript
{ "resource": "" }
q36305
xml2json
train
function xml2json(method, body){ body = util.xml2json(body); if(body.return_code!=='SUCCESS'){ throw new Error(util.format('api error to call %s: %s', method, body.return_msg)); } if(body.result_code!=='SUCCESS'){ throw new Error(util.format('business error to call %s: %s %s', method, body.err_code, body.err_code_des)); } return body; }
javascript
{ "resource": "" }
q36306
referenceParentNode
train
function referenceParentNode () { // If nodeName is an empty string, then reference the parent of the root child. if (isEmptyString(nodeName)) { nodeName = this.$parentName; // Even though super might be invoked in different constructors, // the same instance will always be referenced. rootName is used // to know if the chain has been broken. rootName = this.$name; // Prevent instance from having parent properties applied more than once. if (this.$applied) { throwError(`Cannot invoke super more than once for ${this.$name} instance.`, 'SUPER'); } else { descriptor.value = true; Object.defineProperty(this, '$applied', descriptor); } // Otherwise just move to next parent. } else { // Error out if chain is broken. if (this.$name !== rootName) { throwError(`Chain started by ${rootName} instance is being broken by ${this.$name} instance.`, 'SUPER'); } nodeName = CLASS[nodeName].prototype.$parentName; } }
javascript
{ "resource": "" }
q36307
applyParentNode
train
function applyParentNode (args) { if (isEmptyString(nodeName)) { return undefined; } let nextParentName = CLASS[nodeName].prototype.$parentName; // Keep reference of the node's name just in case the chain gets reset. let tmpName = nodeName; // If there are no more parent nodes then reset the chain. if (isEmptyString(nextParentName)) { resetNames(); } CLASS[tmpName].apply(this, args); }
javascript
{ "resource": "" }
q36308
get
train
function get(resource, path) { const [head, ...tail] = path.split('.'); return resource && head ? get(resource[head], tail.join('.')) : resource; }
javascript
{ "resource": "" }
q36309
createIdentifierNode
train
function createIdentifierNode(name) { return (scope, opts) => { const property = get(opts.properties, name); return property ? property(scope) : get(scope, name); }; }
javascript
{ "resource": "" }
q36310
createOperatorNode
train
function createOperatorNode(operand, nodes = []) { return (scope, opts) => { const args = nodes.map(node => node(scope, opts)); if (typeof operand === 'function') { return operand(...args); } const operator = get(opts.functions, operand); if (!operator) { throw new ReferenceError(`Function '${operand}' isn't declared`); } return operator(...args); }; }
javascript
{ "resource": "" }
q36311
processLogicalOr
train
function processLogicalOr(tokenizer, scope) { let node = processLogicalAnd(tokenizer, scope); while (tokenizer.token.match(types.LOGICAL_OR)) { node = createOperatorNode(tokenizer.token.value, [node, processLogicalAnd(tokenizer.skipToken(), scope)]); } return node; }
javascript
{ "resource": "" }
q36312
processLogicalAnd
train
function processLogicalAnd(tokenizer, scope) { let node = processLogicalEquality(tokenizer, scope); while (tokenizer.token.match(types.LOGICAL_AND)) { node = createOperatorNode(tokenizer.token.value, [node, processLogicalEquality(tokenizer.skipToken(), scope)]); } return node; }
javascript
{ "resource": "" }
q36313
processAddSubtract
train
function processAddSubtract(tokenizer, scope) { let node = processMultiplyDivide(tokenizer, scope); while (tokenizer.token.match(types.ADD_SUBTRACT)) { node = createOperatorNode(tokenizer.token.value, [node, processMultiplyDivide(tokenizer.skipToken(), scope)]); } return node; }
javascript
{ "resource": "" }
q36314
processMultiplyDivide
train
function processMultiplyDivide(tokenizer, scope) { let node = processUnary(tokenizer, scope); while (tokenizer.token.match(types.MULTIPLY_DIVIDE)) { node = createOperatorNode(tokenizer.token.value, [node, processUnary(tokenizer.skipToken(), scope)]); } return node; }
javascript
{ "resource": "" }
q36315
processUnary
train
function processUnary(tokenizer, scope) { const unaryAddSubtract = { '-': value => -value, '+': value => value }; if (tokenizer.token.match(types.ADD_SUBTRACT)) { return createOperatorNode(unaryAddSubtract[tokenizer.token.lexeme], [processUnary(tokenizer.skipToken(), scope)]); } if (tokenizer.token.match(types.INCREASE_DECREASE) || tokenizer.token.match(types.LOGICAL_NEGATION)) { return createOperatorNode(tokenizer.token.value, [processUnary(tokenizer.skipToken(), scope)]); } return processIdentifiers(tokenizer, scope); }
javascript
{ "resource": "" }
q36316
processIdentifiers
train
function processIdentifiers(tokenizer, scope) { let params = []; if (tokenizer.token.match(types.IDENTIFIER)) { const keys = [tokenizer.token.value]; tokenizer.skipToken(); while (tokenizer.token.match(types.DOT, types.OPEN_SQUARE_BRACKET)) { const token = tokenizer.token; tokenizer.skipToken(); const isValidKey = token.match(types.OPEN_SQUARE_BRACKET) ? tokenizer.token.match(types.CONSTANT) : ( (tokenizer.token.match(types.CONSTANT) && (typeof tokenizer.token.value === 'number')) || tokenizer.token.match(types.IDENTIFIER) ); if (!isValidKey) { throw new SyntaxError('Unexpected object key notation'); } keys.push(tokenizer.token.value); tokenizer.skipToken(); if (token.match(types.OPEN_SQUARE_BRACKET)) { if (!tokenizer.token.match(types.CLOSE_SQUARE_BRACKET)) { throw new SyntaxError('Closing square bracket expected'); } tokenizer.skipToken(); } } const identifier = keys.join('.'); if (!tokenizer.token.match(types.OPEN_PARENTHESES)) { scope.identifiers.push(identifier); return createIdentifierNode(identifier); } params = []; tokenizer.skipToken(); if (!tokenizer.token.match(types.CLOSE_PARENTHESES)) { params.push(processLogicalOr(tokenizer, scope)); while (tokenizer.token.match(types.DELIMITER)) { params.push(processLogicalOr(tokenizer.skipToken(), scope)); } } if (!tokenizer.token.match(types.CLOSE_PARENTHESES)) { throw new SyntaxError('Unexpected end of expression'); } tokenizer.skipToken(); return createOperatorNode(identifier, params); } return processConstants(tokenizer, scope); }
javascript
{ "resource": "" }
q36317
processConstants
train
function processConstants(tokenizer, scope) { if (tokenizer.token.match(types.CONSTANT)) { const node = createConstantNode(tokenizer.token.value); tokenizer.skipToken(); return node; } return processParentheses(tokenizer, scope); }
javascript
{ "resource": "" }
q36318
processParentheses
train
function processParentheses(tokenizer, scope) { if (tokenizer.token.match(types.CLOSE_PARENTHESES)) { throw new SyntaxError('Unexpected end of expression'); } if (tokenizer.token.match(types.OPEN_PARENTHESES)) { const node = processLogicalOr(tokenizer.skipToken(), scope); if (!tokenizer.token.match(types.CLOSE_PARENTHESES)) { throw new SyntaxError('Unexpected end of expression'); } tokenizer.skipToken(); return node; } throw new SyntaxError('Unexpected end of expression'); }
javascript
{ "resource": "" }
q36319
makeMBTAPI
train
function makeMBTAPI( config ) { if ( ! config.apiKey || typeof config.apiKey !== 'string' ) { throw new Error( 'An MBTA API key must be provided' ); } config.apiRoot = config.apiRoot || 'http://realtime.mbta.com/developer/api/v2/'; return _.mapValues( methods, function( args, key ) { // makeQueryHandler's third argument is a config object: add it when applying return makeQueryHandler.apply( null, args.concat( config ) ); }); }
javascript
{ "resource": "" }
q36320
serialize
train
function serialize(path){ return path.reduce(function(str, seg){ return str + seg[0] + seg.slice(1).join(',') }, '') }
javascript
{ "resource": "" }
q36321
slice
train
function slice(str, beginSlice, endSlice) { return GraphemeBreaker.break(str) .slice(beginSlice, endSlice) .join(''); }
javascript
{ "resource": "" }
q36322
zipFolder
train
function zipFolder(zip, ffs, root, dir) { dir = dir || ''; let files = ffs.readdirSync(root + (dir ? '/' + dir : '')); files.forEach(file => { if (['.ts', '.js.map'].some(e => file.endsWith(e))) { return; } let stat = ffs.statSync(root + (dir ? '/' + dir : '') + '/' + file); if (stat.isFile()) { zipFile(zip, ffs, root, dir, file); } else if (stat.isDirectory()) { zipFolder(zip, ffs, root, dir ? dir + '/' + file : file); } }); }
javascript
{ "resource": "" }
q36323
zipFile
train
function zipFile(zip, ffs, root, dir, file) { dir = dir || ''; let zipfolder = dir ? zip.folder(dir) : zip; const data = ffs.readFileSync(root + (dir ? '/' + dir : '') + '/' + file); zipfolder.file(file, data); }
javascript
{ "resource": "" }
q36324
checkFolder
train
function checkFolder(ffs, fld) { let fldBits = fld.split('/'), mkfld = ''; fldBits.forEach(toBit => { mkfld = mkfld ? mkfld + '/' + toBit : toBit; if (mkfld && !ffs.existsSync(mkfld)) { ffs.mkdirSync(mkfld); } }); }
javascript
{ "resource": "" }
q36325
copyFolder
train
function copyFolder(ffs, from, to) { checkFolder(ffs, to); let tasks = []; ffs.readdirSync(from).forEach(child => { if (ffs.statSync(from + '/' + child).isDirectory()) { copyFolder(ffs, from + '/' + child, to + '/' + child); } else { copyFile(ffs, from + '/' + child, to + '/' + child); } }); }
javascript
{ "resource": "" }
q36326
_process
train
function _process(templates, params, cb) { var _templates = _.extend(templates, {}), // process template copies, not the originals tasks = {}; _.keys(_templates).forEach(function (key) { tasks[key] = function (cb) { _templates[key].process(params, function (data) { cb(null, data); }); }; }); async.parallel(tasks, function (err, results) { cb(results); }); }
javascript
{ "resource": "" }
q36327
train
function(node) { if (node.type !== 'AssignmentExpression') return false; return node.left.type === 'MemberExpression' && node.left.object.type === 'Identifier' && node.left.object.name === 'module' && node.left.property.type === 'Identifier' && node.left.property.name === 'exports'; // TODO: detect module.exports.foo = (or exports.foo =) property assignments, non-default exports }
javascript
{ "resource": "" }
q36328
train
function(rootNode) { // queue to compute de breadth first search var queue = [rootNode]; var nodes = [rootNode]; while (queue.length !== 0) { // fetch child nodes of the first node of the queue var currentNode = queue.shift(); for (var property in currentNode) { // compute only non-inherited properties if (currentNode.hasOwnProperty(property)) { if (Array.isArray(currentNode[property])) { var nodeArray = currentNode[property]; for (var i = 0, ii = nodeArray.length; i < ii; ++i) { // enqueue only if it is a Node instance if (nodeArray[i] instanceof rootNode.constructor) { queue.push(nodeArray[i]); nodes.push(nodeArray[i]); } } } else // enqueue only if it is a Node instance if (currentNode[property] instanceof rootNode.constructor) { queue.push(currentNode[property]); nodes.push(currentNode[property]); } } } } return nodes; }
javascript
{ "resource": "" }
q36329
train
function(nodes, methods) { var segmentsToBlank = []; for (var i = 0, ii = nodes.length; i < ii; ++i) { // checks if the statement is a CallExpression if (nodes[i].type === 'CallExpression' && nodes[i].callee.type === 'MemberExpression') { var nodeExpression = nodes[i]; // checks if the called function is a property of console or window.console if (nodeExpression.callee.object.name === 'console' || ( nodeExpression.callee.object.property !== undefined && nodeExpression.callee.object.object !== undefined && nodeExpression.callee.object.property.name === 'console' && nodeExpression.callee.object.object.name === 'window' )) { // push the node if the current function is within the methods array if (methods.indexOf(nodeExpression.callee.property.name) > -1) { segmentsToBlank.push(nodeExpression.range); } } } } // sort the range segments list segmentsToBlank.sort(function(a, b) { return a[0] - b[0]; }); // handle the case of nested segments : "console.log(console.log('foo'))" removeNestedSegments(segmentsToBlank); return segmentsToBlank; }
javascript
{ "resource": "" }
q36330
train
function(segments) { var previousSegment = [-1, -1]; var segmentIndicesToRemove = []; var cleanedSegmentArray = []; var i, ii; for (i = 0, ii = segments.length; i < ii; ++i) { if (!(previousSegment[0] <= segments[i][0] && previousSegment[1] >= segments[i][1])) { cleanedSegmentArray.push(segments[i]); } previousSegment = segments[i]; } segments.length = 0; for (i = 0, ii = cleanedSegmentArray.length; i < ii; ++i) { segments.push(cleanedSegmentArray[i]); } }
javascript
{ "resource": "" }
q36331
importModule
train
function importModule(module, scope, fn) { debug("Importing module: " + module); var imports = require(module), name = path.basename(module, path.extname(module)); if (isPlainObject(imports)) { var keys = Object.keys(imports), key, len = keys.length; for (var i = 0; i < len; i++) { key = keys[i]; if (imports.hasOwnProperty(key)) { scope[key] = imports[key]; if (fn) { fn(name, key, imports[key]); } } } } else { scope[name] = imports; if (fn) { fn(name, null, imports); } } }
javascript
{ "resource": "" }
q36332
load
train
function load(target, opts) { target = path.resolve(target); debug("Load enter: " + target); if (fs.statSync(target).isDirectory()) { var files = fs.readdirSync(target), len = files.length, file; for (var i = 0; i < len; i++) { file = files[i]; var fullPath = target + sep + file; if (fs.statSync(fullPath).isDirectory() && opts.recurse) { load(fullPath, opts); } else if (test(fullPath, opts.grep, opts.ungrep)) { importModule(fullPath, opts.scope, opts.fn); } } } else if (test(target, opts.grep, opts.ungrep)) { importModule(target, opts.scope, opts.fn); } }
javascript
{ "resource": "" }
q36333
asRegExps
train
function asRegExps(array) { var array = asArray(array), len = array.length; for (var i = 0; i < len; i++) { if (!(array[i] instanceof RegExp)) { array[i] = new RegExp(array[i]); } } return array; }
javascript
{ "resource": "" }
q36334
defaultOpts
train
function defaultOpts(opts, parentId) { var targets = opts.targets && opts.targets.length ? asArray(opts.targets) : [defaultTarget(parentId)]; return mixin({targets: targets, grep: [/\.js$/], ungrep: opts.ungrep && opts.ungrep.length ? asArray(opts.ungrep) : defaultUngrep(targets), scope: {}, recurse: true}, opts, true); }
javascript
{ "resource": "" }
q36335
defaultUngrep
train
function defaultUngrep(targets) { if (targets && targets.length) { var ungreps = [], target, len = targets.length; for (var i = 0; i < len; i++) { target = targets[i]; target = '(?:^' + path.dirname(target) + sep + '){1}'; target += '(?:/?.*/?)*' + NM_SEG; ungreps.push(new RegExp(escape(target))); } return ungreps; } return [new RegExp(escape(NM_SEG))]; }
javascript
{ "resource": "" }
q36336
compare
train
function compare(data, candidates, shim, at, mt) { var results = []; var i; for (i = 0; i < candidates.length; i++) { var candidate = candidates[i]; if (shim) { candidate = shim(candidate); } //compare candidate with patient var s = score(data, candidate); var m = evaluate(s, at, mt); // all candidates are returned, with score // and matching status var result = {}; result.pat_key = candidate.pat_key; result.match = m; result.score = s; results.push(result); } return results; }
javascript
{ "resource": "" }
q36337
newLineAfterCompositeExpressions
train
function newLineAfterCompositeExpressions(previous) { if (previous.type === 'ExpressionStatement') { var expression = previous.expression; switch (expression.type) { case 'AssignmentExpression': case 'BinaryExpression': return NEED_EXTRA_NEWLINE_AFTER[expression.right.type];}}}
javascript
{ "resource": "" }
q36338
getPrototype
train
function getPrototype(model) { if (model.__recordPrototype) return model.__recordPrototype; const mrProto = Object.assign({}, proto);// eslint-disable-line no-use-before-define const extraProperties = {}; Object.keys(model.def.fields).forEach((fieldName) => { extraProperties[fieldName] = { enumerable: true, get() { const value = getf.call(this, fieldName); return value; }, set(value) { return setf.call(this, fieldName, value); }, }; }); Object.defineProperties(mrProto, extraProperties); model.__recordPrototype = mrProto; return mrProto; }
javascript
{ "resource": "" }
q36339
normalizeUserData
train
function normalizeUserData() { function handler(req, res, next) { if (req.session && !req.session.user && req.session.auth && req.session.auth.loggedIn) { var user = {}; if (req.session.auth.github) { user.image = 'http://1.gravatar.com/avatar/'+req.session.auth.github.user.gravatar_id+'?s=48'; user.name = req.session.auth.github.user.name; user.id = 'github-'+req.session.auth.github.user.id; } if (req.session.auth.twitter) { user.image = req.session.auth.twitter.user.profile_image_url; user.name = req.session.auth.twitter.user.name; user.id = 'twitter-'+req.session.auth.twitter.user.id_str; } if (req.session.auth.facebook) { user.image = req.session.auth.facebook.user.picture; user.name = req.session.auth.facebook.user.name; user.id = 'facebook-'+req.session.auth.facebook.user.id; // Need to fetch the users image... https.get({ 'host': 'graph.facebook.com' , 'path': '/me/picture?access_token='+req.session.auth.facebook.accessToken }, function(response) { user.image = response.headers.location; req.session.user = user; next(); }).on('error', function(e) { req.session.user = user; next(); }); return; } req.session.user = user; } next(); } return handler; }
javascript
{ "resource": "" }
q36340
IntN
train
function IntN(bytes, unsigned) { /** * Represented byte values, least significant first. * @type {!Array.<number>} * @expose */ this.bytes = new Array(nBytes); for (var i=0, k=Math.min(nBytes, bytes.length); i<k; ++i) this.bytes[i] = bytes[i] & 0xff; for (; i<nBytes; ++i) this.bytes[i] = 0; /** * Whether unsigned or otherwise signed. * @type {boolean} * @expose */ this.unsigned = !!unsigned; }
javascript
{ "resource": "" }
q36341
createBuildConfig
train
function createBuildConfig(grunt, options, projectConfig) { var configType = 'grunt-web'; if (options.buildConfig.dualProject) { configType = 'grunt-dual'; } else if (options.buildConfig.nodeProject) { configType = 'grunt-node'; } var loader = require('./' + configType); return loader(grunt, options, projectConfig); }
javascript
{ "resource": "" }
q36342
echo
train
function echo(message) { return __awaiter(this, void 0, void 0, function* () { console.log('----------------'); console.log(message); console.log('----------------'); return Promise.resolve(); }); }
javascript
{ "resource": "" }
q36343
generateListItem
train
function generateListItem(result, hasBlankLine) { const content = [result[3]]; if (hasBlankLine) { content.unshift('\n'); } return { type: 'ListItem', checked: result[2] === '[x]' ? true : (result[2] === '[ ]' ? false : undefined), // true / false / undefined content, children: [] }; }
javascript
{ "resource": "" }
q36344
getHistory
train
function getHistory(context) { if (!historyMap.has(context)) { clear(context); } return historyMap.get(context); }
javascript
{ "resource": "" }
q36345
constructor
train
function constructor(models, options) { if (!Array.isArray(models)) { options = models; models = []; } options = options || {}; // // Set the database name if it was provided in the options. // if (options.url) this.url = options.url; if (options.database) this.database = options.database; // // Define restricted non-enumerated properties. // predefine(this, fossa); // // Call original Backbone Model constructor. // backbone.Collection.call(this, models, options); }
javascript
{ "resource": "" }
q36346
clone
train
function clone() { return new this.constructor(this.models, { url: 'function' === typeof this.url ? this.url() : this.url, model: this.model, database: this.database, comparator: this.comparator }); }
javascript
{ "resource": "" }
q36347
ShutdownManager
train
function ShutdownManager (params) { // Set State var that = this; this.isShuttingDown = false; this.actionChain = []; this.finalActionChain = []; // Set Parameters this.logger = (params && params.hasOwnProperty("logger")) ? params.logger : null; this.loggingPrefix = (params && params.hasOwnProperty("loggingPrefix")) ? params.loggingPrefix : DEFAULT_LOGGING_PREFIX; // Add Process Handlers process.on('SIGINT', function() { if (!that.emit('preShutdown', 'SIGINT')) { that._log("Received SIGINT, Beginning Shutdown Process"); } that._shutdown(128+2, params.timeout); }); process.on('SIGTERM', function() { if (!that.emit('preShutdown', 'SIGTERM')) { that._log("Received SIGTERM, Beginning Shutdown Process"); } that._shutdown(128+15, params.timeout); }); process.on('uncaughtException', function (err) { if (!that.emit('preShutdown', 'uncaughtException', err)) { that._log('Uncaught Exception Received, Beginning Shutdown Process'); that._log('Exception: '+err); } that._shutdown(255, params.timeout); }); process.on('exit', function() { // Just in case we are getting to exit without previous conditions being met // Not sure if this happens - will test. if(!that.isShuttingDown) { that.emit('preShutdown', 'exit'); that._log("Application Exiting for Undefined Reason, Beginning Shutdown Process"); that._shutdown(null, params.timeout); } }); EventEmitter.call(this); }
javascript
{ "resource": "" }
q36348
readAuth
train
function readAuth (path) { var auth; if (grunt.file.exists(path)) { auth = grunt.file.read(path).trim().split(/\s/); if (auth.length === 2 && auth[0].indexOf('@') !== -1) { return {email: auth[0], password: auth[1]}; } } return null; }
javascript
{ "resource": "" }
q36349
run
train
function run(command, auth, options, async, done, msgSuccess, msgSuccessAsync, msgFailure) { var args, flags, field, i, childProcess; // Pass auth. command = command.replace('{auth}', auth ? format('--email=%s --passin ', auth.email) : ''); // Evaluate arguments to pass. args = ''; for (field in options.args) { args += format('--%s=%s ', field, options.args[field]); } // Evaluate flags to pass. flags = ''; for (i = 0; i < options.flags.length; ++i) { flags += format('--%s ', options.flags[i]); } command = command.replace('{args}', args).replace('{flags}', flags).replace('{path}', options.path); // Passin. if (auth) { command = format('echo %s | %s', auth.password, command); } // Run it asynchronously if (async) { command = COMMAND_ASYNC. replace('{command}', command). replace('{redirect}', options.asyncOutput ? '' : REDIRECT_DEVNULL); } grunt.log.debug(command); // Run the command. childProcess = exec(command, {}, function () {}); // Listen to output if (options.stdout) { childProcess.stdout.on('data', function (d) { grunt.log.write(d); }); } // Listen to errors. if (options.stderr) { childProcess.stderr.on('data', function (d) { grunt.log.error(d); }); } // Listen to exit. childProcess.on('exit', function (code) { if (options.stdout) { if (code === 0 && async) { grunt.log.subhead( msgSuccessAsync || options.asyncOutput && 'Output from asynchronous operation follows.' || 'Unable to determine success of asynchronous operation. For debugging please disable async mode or enable asyncOutput.' ); } else if (code === 0) { grunt.log.ok(msgSuccess || 'Action executed successfully.'); } } if (options.stderr && code !== 0) { grunt.log.error(msgFailure || 'Error executing the action.'); } done(); }); }
javascript
{ "resource": "" }
q36350
depends
train
function depends (targets) { debug('Depends: start parse dependencies'); targets = prepare.targets(targets).filter(directories); debug('Depends: target : ' + targets); targets.forEach(parse_node_module); }
javascript
{ "resource": "" }
q36351
terminate
train
function terminate(control) { if (control && control._process && typeof control._process.kill == 'function') { control._process._executioner_killRequested = true; control._process.kill(); return true; } return false; }
javascript
{ "resource": "" }
q36352
getMtgJson
train
function getMtgJson(type, directory, opts) { //Setup input and output URIs const outFileName = getJsonFilename(type, opts); const url = `${BASE_URL}/${outFileName}`; const output = path.resolve(`${directory}/${outFileName}`); const outputStream = fs.createWriteStream(output); //Return a file path if they requested it, or it's a zip file const returnFile = !!(opts && (opts.returnFile || opts.zip)); //Return the json if it already exists try { //If it's a ZIP, it can't be json, throw an error to ensure we don't try require if (opts && opts.zip) throw new Error(); const json = require(output); return returnFile ? Promise.resolve(output) : Promise.resolve(json); } catch (ex) { //Pipe the downloaded file into the output file request(url) .pipe(outputStream); //Return a promise that's resolved when the file has downloaded return eventToPromise(outputStream, 'close') .then(()=> { //Return the new json file, parsed try { return returnFile ? Promise.resolve(output) : require(output); } catch (ex) { throw new Error(`Invalid json: ${ex.message}`); } }); } }
javascript
{ "resource": "" }
q36353
Data
train
function Data(properties) { this.custom = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q36354
Custom
train
function Custom(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q36355
Gateway
train
function Gateway(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q36356
Attitude
train
function Attitude(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q36357
Battery
train
function Battery(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q36358
Dronestatus
train
function Dronestatus(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q36359
GNSS
train
function GNSS(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q36360
Signal
train
function Signal(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q36361
Velocity
train
function Velocity(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q36362
Atmosphere
train
function Atmosphere(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
{ "resource": "" }
q36363
relativize
train
function relativize (dest, src) { // both of these are absolute paths. // find the shortest relative distance. src = src.split("/") var abs = dest dest = dest.split("/") var i = 0 while (src[i] === dest[i]) i++ if (i === 1) return abs // nothing in common, leave absolute src.splice(0, i + 1) var dots = [0, i, "."] for (var i = 0, l = src.length; i < l; i ++) dots.push("..") dest.splice.apply(dest, dots) dest = dest.join("/") return abs.length < dest.length ? abs : dest }
javascript
{ "resource": "" }
q36364
configure
train
function configure(obj, fossa) { function get(key, backup) { return key in obj ? obj[key] : backup; } // // Allow new options to be be merged in against the original object. // get.merge = function merge(properties) { return fossa.merge(obj, properties); }; return get; }
javascript
{ "resource": "" }
q36365
Fossa
train
function Fossa(options) { this.fuse(); // // Store the options. // this.writable('queue', []); this.writable('plugins', {}); this.writable('connecting', false); this.readable('options', configure(options || {}, this)); // // Prepare a default model and collection sprinkled with MongoDB proxy methods. // this.readable('Model', model(this)); this.readable('Collection', collection(this)); // // Provide reference to the orginal mongo module so it can be used easily. // this.readable('mongo', mongo); // // Prepare connection. // this.init( this.options('hostname', 'localhost'), this.options('port', 27017), this.options ); }
javascript
{ "resource": "" }
q36366
expandKey
train
function expandKey(key) { let tempWord = new Array(WORD_LENGTH); let rounds = getRoundsCount(key); let wordsCount = key.length / WORD_LENGTH; let keySchedule = new Array(COLUMNS * (rounds + 1)); for (let i = 0; i < wordsCount; i++) { keySchedule[i] = key.slice(WORD_LENGTH * i, WORD_LENGTH * i + WORD_LENGTH); } for (let i = wordsCount; i < keySchedule.length; i++) { tempWord = keySchedule[i - 1]; if (i % wordsCount === 0) { tempWord = a_u.xorWords(a_u.subWord(a_u.rotWordLeft(tempWord)), a_u.R_CON[i / wordsCount]); } else if (wordsCount > 6 && i % wordsCount === 4) { tempWord = a_u.subWord(tempWord); } keySchedule[i] = a_u.xorWords(keySchedule[i - wordsCount], tempWord); } return keySchedule; }
javascript
{ "resource": "" }
q36367
encryptBlock
train
function encryptBlock(block, keySchedule) { let state = splitToMatrix(block); state = a_u.addRoundKey(state, keySchedule.slice(0, 4)); let rounds = keySchedule.length / COLUMNS; for (let round = 1; round < rounds; round++){ state = a_u.subBytes(state); state = a_u.shiftRows(state); state = a_u.mixColumns(state); state = a_u.addRoundKey(state, keySchedule.slice(round * COLUMNS, (round + 1) * COLUMNS)); } state = a_u.subBytes(state); state = a_u.shiftRows(state); state = a_u.addRoundKey(state, keySchedule.slice(COLUMNS * (rounds-1), COLUMNS * rounds)); return getBlockFromState(state); }
javascript
{ "resource": "" }
q36368
train
function ( taskName ) { var task = grunt.config.get( "bundles" )[taskName]; var retVal = []; if ( task ) { var sources = task.modules; if ( !sys.isEmpty( sources ) && !sys.isEmpty( sources.src ) ) { grunt.log.writeln( "Adding sources for " + taskName ); retVal = sys.map( grunt.file.expand( sources, sources.src ), function ( item ) { return resolvePath( item ); } ); } } return retVal; }
javascript
{ "resource": "" }
q36369
train
function ( file ) { var resolved; var expanded = grunt.file.expand( file )[0]; if ( !expanded ) { resolved = require.resolve( file ); } else { resolved = "./" + expanded; } return resolved; }
javascript
{ "resource": "" }
q36370
train
function ( pkg ) { grunt.verbose.writeln( "Populating compiler" ); var copts = { noParse : pkg.noParse, entries : pkg.modules, externalRequireName : options.externalRequireName, pack : options.pack, bundleExternal : options.bundleExternal, // builtins : options.builtins, fullPaths : options.fullPaths, commondir : options.commondir, basedir : options.basedir, extensions : options.extensions } if ( !sys.isEmpty( options.builtins ) ) { copts.builtins = options.builtins; } var compiler = browsCompiler( copts ); sys.each( pkg.exec, function ( item ) { compiler.add( item ); } ); sys.each( pkg.aliases, function ( item, name ) { compiler.require( item, {expose : name} ); } ); sys.each( pkg.publish, function ( item ) { compiler.require( item ); } ); sys.each( pkg.externals, function ( item ) { compiler.external( item ); } ); sys.each( pkg.ignore, function ( item ) { compiler.ignore( item ); } ); return compiler; }
javascript
{ "resource": "" }
q36371
train
function ( pkg, compiler ) { if ( !sys.isEmpty( task.data.depends ) && options.resolveAliases && !sys.isEmpty( pkg.dependAliases ) ) { compiler.transform( function ( file ) { grunt.verbose.writeln( "Transforming " + file ); function write( buf ) { data += buf; } var data = ''; return through( write, function () { var __aliases = []; sys.each( pkg.dependAliases, function ( al ) { if ( data.indexOf( "'" + al + "'" ) !== -1 || data.indexOf( '"' + al + '"' ) !== -1 ) { __aliases.push( "'" + al + "' : '" + al + "'" ); data = data.replace( new RegExp( "'" + al + "'", "g" ), "__aliases['" + al + "']" ); data = data.replace( new RegExp( '"' + al + '"', "g" ), "__aliases['" + al + "']" ); } } ); if ( !sys.isEmpty( __aliases ) ) { var aliasDefinition = "var __aliases = {" + __aliases.join( ",\n" ) + "};\n"; data = aliasDefinition + data; } this.queue( data ); this.queue( null ); } ); } ); } }
javascript
{ "resource": "" }
q36372
dumpToFile
train
function dumpToFile(extension, regex) { return inspect(onComplete); function onComplete(filename, contents, done) { if (!regex || regex.test(filename)) { var newName = [filename, extension || 'gen'].join('.'); fs.writeFile(newName, contents, done); } else { done(); } } }
javascript
{ "resource": "" }
q36373
dbName
train
function dbName(str) { if (!str) return str; str = str.replace(/[A-Z]/g, $0 => `_${$0.toLowerCase()}`); if (str[0] === '_') return str.slice(1); return str; }
javascript
{ "resource": "" }
q36374
train
function () { bytes = str.substr(u, 45).split('') for (i in bytes) { bytes[i] = bytes[i].charCodeAt(0) } return bytes.length || 0 }
javascript
{ "resource": "" }
q36375
train
function(result, callback) { self.cache.put(result, function(err, doc) { if (err) return callback(err); callback(null, result, doc._id); }); }
javascript
{ "resource": "" }
q36376
train
function(result, cached, callback) { self.metacache.store(id, processor, cached, function(err) { if (err) return callback(err); callback(null, result); }); }
javascript
{ "resource": "" }
q36377
train
function(metacache, callback) { var funcs = []; for (var processor in metacache) { if (processor !== '_id') { var cached = metacache[processor]; funcs.push(function(callback) { self.cache.delete(cached, callback); }); } } async.parallel(funcs, callback); }
javascript
{ "resource": "" }
q36378
load
train
function load(file, options) { if (options.cache && rr.cache['rvc!' + file]) { return Promise.resolve(rr.cache['rvc!' + file]); } return requireJSAsync(file).then(function (Component) { // flush requireJS's cache _.forEach(requireJS.s.contexts._.defined, function (value, key, array) { if (key.substr(0, 4) === 'rvc!') { delete array[key]; } }); return utils.wrap(utils.selectTemplate(options, Component), options).then(function (template) { var basePath = path.relative(options.settings.views, path.dirname(file)); Component.defaults.template = options.template = template; return Promise.join(utils.buildComponentsRegistry(options), utils.buildPartialsRegistry(basePath, options), function (components, partials) { _.assign(Component.components, components); _.assign(Component.partials, partials); options.components = {}; options.partials = {}; if (options.cache) { rr.cache['rvc!' + file] = Component; } return Component; }); }); }); }
javascript
{ "resource": "" }
q36379
requireJSAsync
train
function requireJSAsync (file) { return new Promise(function (resolve, reject) { requireJS([ 'rvc!' + requireJSPath(file, '.html') ], resolve, reject); }); }
javascript
{ "resource": "" }
q36380
requireJSPath
train
function requireJSPath(file, extension) { return path.join(path.dirname(file), path.basename(file, extension)).replace(/\\/g, '/'); }
javascript
{ "resource": "" }
q36381
DetectMouseUser
train
function DetectMouseUser(event) { if(isMouseUser) { // collection throttle interval. setInterval(function() { trackData = true; }, 50); return true; } let current = movement; if(x && y){ movement = movement + Math.abs(x - event.pageX) + Math.abs(y - event.pageY); } x = event.pageX; y = event.pageY; if ((current + 10) > movement) { movementOkcount++; } if(movementOkcount > 5) { isMouseUser = true; } return false; }
javascript
{ "resource": "" }
q36382
startIdle
train
function startIdle() { var idleCount = 0; function idle() { coordinates.push({ t: 1, x: lastX, y: lastY }); idleCount++; if (idleCount > 10) { clearInterval(idleInterval); } } idle(); idleInterval = setInterval(idle, 1000); }
javascript
{ "resource": "" }
q36383
emitHeatmapCoordinates
train
function emitHeatmapCoordinates() { if(coordinates.length > 0) { ceddl.emitEvent('heatmap:update', { width: windowWidth, coordinates: coordinates.splice(0, coordinates.length) }); } windowWidth = Math.round(parseInt(window.innerWidth, 10)); }
javascript
{ "resource": "" }
q36384
isClickTarget
train
function isClickTarget(element) { return element.hasAttribute('ceddl-click') || (element.nodeType === 1 && element.tagName.toUpperCase() === 'BUTTON') || (element.nodeType === 1 && element.tagName.toUpperCase() === 'A'); }
javascript
{ "resource": "" }
q36385
delegate
train
function delegate(callback, el) { var currentElement = el; do { if (!isClickTarget(currentElement)) continue; callback(currentElement); return; } while(currentElement.nodeName.toUpperCase() !== 'BODY' && (currentElement = currentElement.parentNode)); }
javascript
{ "resource": "" }
q36386
ButtonGroup
train
function ButtonGroup({ children, className, ...rest }) { const classes = cx(buttonGroupClassName, className) return ( <div className={classes} {...rest}> {children} </div> ) }
javascript
{ "resource": "" }
q36387
hashDocument
train
function hashDocument(document) { var words; if (Buffer.isBuffer(document)) { words = Base64.parse(document.toString('base64')); } else if (typeof document === 'string') { words = Base64.parse(document); } else { throw new TypeError('Expected document to be Buffer or String'); } var hash = sha256(words); return hash.toString(Hex); }
javascript
{ "resource": "" }
q36388
publishProof
train
function publishProof(privateKeyHex, toAddress, hash, rpcUri) { if (!EthereumUtil.isValidAddress(EthereumUtil.addHexPrefix(toAddress))) { throw new Error('Invalid destination address.'); } if (!rpcUri) { rpcUri = localDefault; } var web3 = new Web3( new Web3.providers.HttpProvider(rpcUri) ); var tx = buildTransaction(privateKeyHex, toAddress, hash, web3); var serializedTx = EthereumUtil.addHexPrefix(tx.serialize().toString('hex')); var txHash = web3.eth.sendRawTransaction(serializedTx); console.log('Transaction hash:' + txHash); return txHash; }
javascript
{ "resource": "" }
q36389
buildTransaction
train
function buildTransaction(privateKeyHex, toAddress, hash, web3) { var privateKeyBuffer = Buffer.from(privateKeyHex, 'hex'); if (!EthereumUtil.isValidPrivate(privateKeyBuffer)) { throw new Error('Invalid private key.'); } var txParams = { nonce: '0x00', gasPrice: '0x09184e72a000', // How should we set this? gasLimit: '0x5A88', to: EthereumUtil.addHexPrefix(toAddress), value: '0x00', data: EthereumUtil.addHexPrefix(hash) }; if (web3 !== undefined) { var gas = web3.eth.estimateGas(txParams); var nonce = web3.eth.getTransactionCount( EthereumUtil.bufferToHex( EthereumUtil.privateToAddress(privateKeyBuffer) )); txParams.gasLimit = web3.toHex(gas); txParams.nonce = web3.toHex(nonce); txParams.gasPrice = web3.toHex(web3.eth.gasPrice); } var tx = new EthereumTx(txParams); tx.sign(privateKeyBuffer); return tx; }
javascript
{ "resource": "" }
q36390
toCsvValue
train
function toCsvValue(theValue, sDelimiter) { const t = typeof (theValue); let output, stringDelimiter ; if (typeof (sDelimiter) === "undefined" || sDelimiter === null) stringDelimiter = '"'; else stringDelimiter = sDelimiter; if (t === "undefined" || t === null) output = ''; else if (t === 'string') output = sDelimiter + theValue + sDelimiter; else output = String(theValue); return output; }
javascript
{ "resource": "" }
q36391
taskMinus
train
function taskMinus() { taskCounter-- if (taskCounter === 0) { // Time to respond if (files.length === 0) { res.send(200, { result: 'no files to upload', files }) } else { res.send(201, { result: 'upload OK', files }) } next() } }
javascript
{ "resource": "" }
q36392
train
function (tmr, timeout) { return new Promise((resolve, reject) => { /*eslint-disable no-return-assign */ return tmr = setTimeout(reject, timeout, httpError(408)); }); }
javascript
{ "resource": "" }
q36393
defineImmutable
train
function defineImmutable(target, values) { Object.keys(values).forEach(function(key){ Object.defineProperty(target, key, { configurable: false, enumerable: true, value: values[key] }); }); return target; }
javascript
{ "resource": "" }
q36394
train
function ( data ) { if ( !data ) return data; if ( typeof data !== 'object' ) return data; if ( 'entrySet' in data && typeof data.entrySet === 'function' ) { //var allowed_long_keys = ['utc_timestamp', 'duration', 'type', 'token']; var set = data.entrySet(); if ( !set ) return data; var obj = {}; var iter = set.iterator(); while ( iter.hasNext() ) { var entry = iter.next(); var val = entry.getValue(); if ( val && typeof val === 'object' && 'entrySet' in val && typeof val.entrySet === 'function' ) val = convertData(val); var key = entry.getKey(); if ( !key ) { throw( "Field key is not valid: " + key ); } obj[entry.getKey()] = val; } return obj; } else { if ( 'utc_timestamp' in data ) data.utc_timestamp = jsDateToTs(data.utc_timestamp); if ( 'created_at' in data ) data.created_at = jsDateToTs(data.created_at); } return data; }
javascript
{ "resource": "" }
q36395
evaluate
train
function evaluate(score, at, mt) { var automaticThreshold = at || 17.73; var manualThreshold = mt || 15.957; var result = "no match"; if (score >= automaticThreshold) { result = "automatic"; } else if (score >= manualThreshold) { result = "manual"; } return result; }
javascript
{ "resource": "" }
q36396
train
function(seneca, options, bases, next) { var add = []; var host = options.host; if (0 === bases.length) { if (null != host && host !== DEFAULT_HOST) { add.push(host + ":" + DEFAULT_PORT); } add.push(DEFAULT_HOST + ":" + DEFAULT_PORT); } next(add); }
javascript
{ "resource": "" }
q36397
maxSatisfying
train
function maxSatisfying (versions, range) { return versions .filter(function (v) { return satisfies(v, range) }) .sort(compare) .pop() }
javascript
{ "resource": "" }
q36398
train
function(item) { // Drop newline symbol in error string item.msg = (Array.isArray(item.msg) ? item.msg.join(' ') : item.msg).replace('\n', ''); // Using zero instead of undefined item.column = (item.column === undefined) ? 0 : item.column; // Drop `PUG:LINT_` prefix in error code item.code = chalk.grey(item.code.replace(/(PUG:|LINT_)/g, '')); // Formatting output var position = chalk.grey(item.line + ':' + item.column); return ['', position, chalk.red('error'), item.msg, item.code]; }
javascript
{ "resource": "" }
q36399
readFile
train
function readFile (file) { if (!isFileRegistered(file)) { return undefined; } fileRegistry[file].content = gruntIsFile(file) ? gruntRead(file) + '\x0A' : ''; }
javascript
{ "resource": "" }