_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q54200
train
function() { var hookPath = path.resolve(this.options.dest, this.hookName); var existingCode = this.getHookContent(hookPath); if (existingCode) { this.validateScriptLanguage(existingCode); } var hookContent; if(this.hasMarkers(existingCode)) { hookContent = this.insertBindingCode(existingCode); } else { hookContent = this.appendBindingCode(existingCode); } fs.writeFileSync(hookPath, hookContent); fs.chmodSync(hookPath, '755'); }
javascript
{ "resource": "" }
q54201
train
function () { var template = this.loadTemplate(this.options.template); var bindingCode = template({ hook: this.hookName, command: this.options.command, task: this.taskNames, preventExit: this.options.preventExit, args: this.options.args, gruntfileDirectory: process.cwd(), options: this.options }); return this.options.startMarker + '\n' + bindingCode + '\n' + this.options.endMarker; }
javascript
{ "resource": "" }
q54202
merge
train
function merge(o) { if (!isPlainObject(o)) { return {}; } var args = arguments; var len = args.length - 1; for (var i = 0; i < len; i++) { var obj = args[i + 1]; if (isPlainObject(obj)) { for (var key in obj) { if (hasOwn(obj, key)) { if (isPlainObject(obj[key])) { o[key] = merge(o[key], obj[key]); } else { o[key] = obj[key]; } } } } } return o; }
javascript
{ "resource": "" }
q54203
train
function(obj) { const keys = Object.keys(obj).sort(function(key1, key2) { return key1 === 'id' ? false : key1 > key2; }); return keys; }
javascript
{ "resource": "" }
q54204
unfilled
train
function unfilled(cube) { const tuples = Cube.cartesian(cube); const unfilled = []; tuples.forEach(tuple => { const members = this.dice(tuple).getFacts(tuple); if (members.length === 0) { unfilled.push(tuple) } }); return unfilled; }
javascript
{ "resource": "" }
q54205
resolveFieldNames
train
function resolveFieldNames (pattern) { if(!pattern) { return; } var nestLevel = 0; var inRangeDef = 0; var matched; while ((matched = nestedFieldNamesRegex.exec(pattern.resolved)) !== null) { switch(matched[0]) { case '(': { if(!inRangeDef) { ++nestLevel; pattern.fields.push(null); } break; } case '\\(': break; // can be ignored case '\\)': break; // can be ignored case ')': { if(!inRangeDef) { --nestLevel; } break; } case '[': { ++inRangeDef; break; } case '\\[': break; // can be ignored case '\\]': break; // can be ignored case ']': { --inRangeDef; break; } case '(?:': // fallthrough // group not captured case '(?>': // fallthrough // atomic group case '(?!': // fallthrough // negative look-ahead case '(?<!': { if(!inRangeDef) { ++nestLevel; } break; } // negative look-behind default: { ++nestLevel; pattern.fields.push(matched[2]); break; } } } return pattern; }
javascript
{ "resource": "" }
q54206
setDefaultOptions
train
function setDefaultOptions (options) { const defaultOptions = { src: '**/*.php', globOpts: {}, destFile: 'translations.pot', commentKeyword: 'translators:', headers: { 'X-Poedit-Basepath': '..', 'X-Poedit-SourceCharset': 'UTF-8', 'X-Poedit-SearchPath-0': '.', 'X-Poedit-SearchPathExcluded-0': '*.js' }, defaultHeaders: true, noFilePaths: false, writeFile: true, gettextFunctions: [ { name: '__' }, { name: '_e' }, { name: '_ex', context: 2 }, { name: '_n', plural: 2 }, { name: '_n_noop', plural: 2 }, { name: '_nx', plural: 2, context: 4 }, { name: '_nx_noop', plural: 2, context: 3 }, { name: '_x', context: 2 }, { name: 'esc_attr__' }, { name: 'esc_attr_e' }, { name: 'esc_attr_x', context: 2 }, { name: 'esc_html__' }, { name: 'esc_html_e' }, { name: 'esc_html_x', context: 2 } ] }; if (options.headers === false) { options.defaultHeaders = false; } options = Object.assign({}, defaultOptions, options); if (!options.package) { options.package = options.domain || 'unnamed project'; } const functionCalls = { valid: [], contextPosition: {}, pluralPosition: {} }; options.gettextFunctions.forEach(function (methodObject) { functionCalls.valid.push(methodObject.name); if (methodObject.plural) { functionCalls.pluralPosition[ methodObject.name ] = methodObject.plural; } if (methodObject.context) { functionCalls.contextPosition[ methodObject.name ] = methodObject.context; } }); options.functionCalls = functionCalls; return options; }
javascript
{ "resource": "" }
q54207
keywordsListStrings
train
function keywordsListStrings (gettextFunctions) { const methodStrings = []; for (const getTextFunction of gettextFunctions) { let methodString = getTextFunction.name; if (getTextFunction.plural || getTextFunction.context) { methodString += ':1'; } if (getTextFunction.plural) { methodString += `,${getTextFunction.plural}`; } if (getTextFunction.context) { methodString += `,${getTextFunction.context}c`; } methodStrings.push(methodString); } return methodStrings; }
javascript
{ "resource": "" }
q54208
train
function(app/*, parentAddon*/) { this._super.included.apply(this, arguments); this._options = app.options.newVersion || {}; if (this._options.enabled === true) { this._options.fileName = this._options.fileName || 'VERSION.txt'; this._options.prepend = this._options.prepend || ''; this._options.useAppVersion = this._options.useAppVersion || false; } }
javascript
{ "resource": "" }
q54209
train
function() { let detectedVersion; if (this._options.useAppVersion && this._appVersion) { detectedVersion = this._appVersion; } if (!detectedVersion) { detectedVersion = this.parent.pkg.version; } if (detectedVersion && this._options.enabled) { const fileName = this._options.fileName; this.ui.writeLine(`Created ${fileName} with ${detectedVersion}`); return writeFile(fileName, detectedVersion); } }
javascript
{ "resource": "" }
q54210
train
function (budget_id, data, options) { var localVarFetchArgs = TransactionsApiFetchParamCreator(configuration).createTransaction(budget_id, data, options); return function (fetchFunction) { if (fetchFunction === void 0) { fetchFunction = fetch; } return fetchFunction(configuration.basePath + localVarFetchArgs.url, localVarFetchArgs.options).then(function (response) { if (response.status >= 200 && response.status < 300) { return response.json(); } else { return response.json().then(function (e) { return Promise.reject(e); }); } }); }; }
javascript
{ "resource": "" }
q54211
train
function (budget_id, account_id, since_date, type, last_knowledge_of_server, options) { return TransactionsApiFp(configuration).getTransactionsByAccount(budget_id, account_id, since_date, type, last_knowledge_of_server, options)(); }
javascript
{ "resource": "" }
q54212
train
function (budget_id, category_id, since_date, type, last_knowledge_of_server, options) { return TransactionsApiFp(configuration).getTransactionsByCategory(budget_id, category_id, since_date, type, last_knowledge_of_server, options)(); }
javascript
{ "resource": "" }
q54213
bundle
train
function bundle(srcFiles, destDir, optionsFn) { return gulp.src(srcFiles, { read: false }) .pipe(tap(function(file) { var options = {}; if (optionsFn) options = optionsFn(file); var fileName = options.fileName || path.basename(file.path); if (options.standalone) console.log(`Creating ${options.standalone} in ${destDir}/${fileName}`); else console.log(`Creating ${destDir}/${fileName}`); file.contents = browserify(file.path, options) .ignore("buffer") .ignore("dotenv") .bundle() .on("error", function (err) { console.log(err); }); file.path = path.join(file.base, fileName); })) .pipe(buffer()) .pipe(sourcemaps.init({ loadMaps: true })) .pipe(uglify({ preserveComments: function(node, comment) { return comment.value.includes("Copyright Arm"); } })) .pipe(sourcemaps.write(".", { sourceRoot: path.relative(destDir, nodeDir) })) .pipe(gulp.dest(destDir)); }
javascript
{ "resource": "" }
q54214
subscribe
train
function subscribe() { // starts to receive values after device regsiters connect.subscribe.resourceValues({ resourcePaths: ["/3200/0/5501"] }) .addListener((res) => logData(res, "OnRegistration")) .addLocalFilter(res => res.payload >= 20); // starts to reveive values immediatley connect.subscribe.resourceValues({ resourcePaths: ["/3200/0/5501"] }, "OnValueUpdate") .addListener((res) => logData(res, "OnValueUpdate")); }
javascript
{ "resource": "" }
q54215
parseCommandLine
train
function parseCommandLine() { var commands = process.argv.slice(2); var args = {}; for (var i = 0; i < commands.length; i++) { var match = commands[i].match(/^--(.+)=(.+)$/); if (match) args[match[1]] = match[2]; else if (i < commands.length - 1 && commands[i].substr(0, 1) === "-") { args[commands[i].substr(1)] = commands[i + 1]; i++; } else if (i === 0) args[commandKey] = commands[i]; else if (i === 1) args[commandHost] = commands[i]; } return args; }
javascript
{ "resource": "" }
q54216
checkCertificate
train
function checkCertificate() { return certificates.listCertificates({ filter: { type: "developer" } }) .then(certs => { var certificate = certs.data.find(cert => { return cert.name === certificateName; }); if (certificate) { return new Promise((resolve, reject) => { var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question("Developer certificate already exists, overwrite? [y/N] ", answer => { rl.close(); if (answer === "y") { return certificate.delete() .then(() => { resolve(); }); } else { reject(); } }); }); } }); }
javascript
{ "resource": "" }
q54217
extendConfig
train
function extendConfig(defaults, config) { var key; // plugins if (config.plugins) { config.plugins.forEach(function(item) { // {} if (typeof item === 'object') { key = Object.keys(item)[0]; // custom if (typeof item[key] === 'object' && item[key].fn && typeof item[key].fn === 'function') { defaults.plugins.push(setupCustomPlugin(key, item[key])); } else { defaults.plugins.forEach(function(plugin) { if (plugin.name === key) { // name: {} if (typeof item[key] === 'object') { plugin.params = EXTEND({}, plugin.params || {}, item[key]); plugin.active = true; // name: false } else if (item[key] === false) { plugin.active = false; // name: true } else if (item[key] === true) { plugin.active = true; } } }); } } }); } defaults.multipass = config.multipass; // svg2js if (config.svg2js) { defaults.svg2js = config.svg2js; } // js2svg if (config.js2svg) { defaults.js2svg = config.js2svg; } return defaults; }
javascript
{ "resource": "" }
q54218
setupCustomPlugin
train
function setupCustomPlugin(name, plugin) { plugin.active = true; plugin.params = EXTEND({}, plugin.params || {}); plugin.name = name; return plugin; }
javascript
{ "resource": "" }
q54219
optimizePluginsArray
train
function optimizePluginsArray(plugins) { var prev; return plugins.reduce(function(plugins, item) { if (prev && item.type == prev[0].type) { prev.push(item); } else { plugins.push(prev = [item]); } return plugins; }, []); }
javascript
{ "resource": "" }
q54220
buildDocsTasks
train
function buildDocsTasks() { if(npmArgs.remain.indexOf('gentics-ui-core') === -1) { return new Promise(gulp.series( cleanDocsFolder, copyDocsFiles, copyJekyllConfig )); } return resolvePromiseDummy(); }
javascript
{ "resource": "" }
q54221
buildUiCoreTasks
train
function buildUiCoreTasks() { if(npmArgs.remain.indexOf('gentics-ui-core') !== -1) { return new Promise(gulp.series(compileDistStyles, copyDistReadme)); } return resolvePromiseDummy(); }
javascript
{ "resource": "" }
q54222
copyJekyllConfig
train
function copyJekyllConfig() { return streamToPromise( gulp.src(paths.src.jekyll) .pipe(rename('_config.yaml')) .pipe(gulp.dest(paths.out.docs.base)) ); }
javascript
{ "resource": "" }
q54223
copyToTemp
train
function copyToTemp () { fs.readFile(inPath, function (err, inFile) { if (err) return cb(err) var tmpPath = path.join(os.tmpdir(), 'cross-zip-' + Date.now()) fs.mkdir(tmpPath, function (err) { if (err) return cb(err) fs.writeFile(path.join(tmpPath, path.basename(inPath)), inFile, function (err) { if (err) return cb(err) inPath = tmpPath doZip() }) }) }) }
javascript
{ "resource": "" }
q54224
getAttachment
train
function getAttachment(binaryKey) { // console.log('Adding binary attachment', binaryKey); const index = attachments.findIndex((att) => (att.key === binaryKey)); if (index !== -1) { const result = attachments[index].data; // TODO if attachment is sent mulitple times, we shouldn't remove it yet. attachments.splice(index, 1); return result; } console.error('Binary attachment key found without matching attachment'); return null; }
javascript
{ "resource": "" }
q54225
train
function( socket ) { var self = this; this.buffers = []; this.readers = []; this.length = 0; this.socket = socket; // Register the data callback to receive data from Mumble server. socket.on( 'data', function( data ) { self.receiveData( data ); } ); }
javascript
{ "resource": "" }
q54226
train
function( data, client ) { this.client = client; /** * @summary Linked channels * * @name Channel#links * @type Channel[] */ this.links = []; /** * @summary Child channels * * @name Channel#children * @type Channel[] */ this.children = []; /** * @summary Users in the channel * * @name Channel#users * @type User[] */ this.users = []; this._checkParent( data ); // Needs to be done seperate this._applyProperties( data ); // TODO: Description }
javascript
{ "resource": "" }
q54227
parseMissingResources
train
function parseMissingResources(response) { return response.body.data && response.body.data.relationships && response.body.data.relationships['missing-resources'] && response.body.data.relationships['missing-resources'].data || []; }
javascript
{ "resource": "" }
q54228
train
function(buildOutputDirectory) { createPercyBuildInvoked = true; var token = process.env.PERCY_TOKEN; var apiUrl = process.env.PERCY_API; // Optional. // Disable if Percy is explicitly disabled or if this is not an 'ember test' run. if (process.env.PERCY_ENABLE == '0' || process.env.EMBER_ENV !== 'test') { isPercyEnabled = false; } if (token && isPercyEnabled) { console.warn('[percy] Percy is running.'); percyClient = new PercyClient({ token: token, apiUrl: apiUrl, clientInfo: this._clientInfo(), environmentInfo: this._environmentInfo(), }); } else { isPercyEnabled = false; if (!token) { console.warn( '[percy][WARNING] Percy is disabled, no PERCY_TOKEN environment variable found.') } } if (!isPercyEnabled) { return; } var resources = percyClient.gatherBuildResources(buildOutputDirectory, { baseUrlPath: percyConfig.baseUrlPath, skippedPathRegexes: SKIPPED_ASSETS, }); // Initialize the percy client and a new build. percyBuildPromise = percyClient.createBuild({resources: resources}); // Return a promise and only resolve when all build resources are uploaded, which // ensures that the output build dir is still available to be read from before deleted. return new Promise(function(resolve) { percyBuildPromise.then( function(buildResponse) { var percyBuildData = buildResponse.body.data; console.log('\n[percy] Build created:', percyBuildData.attributes['web-url']); // Upload all missing build resources. var missingResources = parseMissingResources(buildResponse); if (missingResources && missingResources.length > 0) { // Note that duplicate resources with the same SHA will get clobbered here into this // hash, but that is ok since we only use this to access the content below for upload. var hashToResource = {}; resources.forEach(function(resource) { hashToResource[resource.sha] = resource; }); var missingResourcesIndex = 0; var promiseGenerator = function() { var missingResource = missingResources[missingResourcesIndex]; missingResourcesIndex++; if (missingResource) { var resource = hashToResource[missingResource.id]; var content = fs.readFileSync(resource.localPath); // Start the build resource upload and add it to a collection we can block on later // because build resources must be fully uploaded before snapshots are finalized. var promise = percyClient.uploadResource(percyBuildData.id, content); promise.then(function() { console.log('\n[percy] Uploaded new build resource: ' + resource.resourceUrl); }, handlePercyFailure); buildResourceUploadPromises.push(promise); return promise; } else { // Trigger the pool to end. return null; } } // We do this in a promise pool for two reasons: 1) to limit the number of files that // are held in memory concurrently, and 2) without a pool, all upload promises are // created at the same time and request-promise timeout settings begin immediately, // which timeboxes ALL uploads to finish within one timeout period. With a pool, we // defer creation of the upload promises, which makes timeouts apply more individually. var concurrency = 2; var pool = new PromisePool(promiseGenerator, concurrency); // Wait for all build resource uploads before we allow the addon build step to complete. // If an upload failed, resolve anyway to unblock the building process. pool.start().then(resolve, resolve); } else { // No missing resources. resolve(); } }, function(error) { handlePercyFailure(error); // If Percy build creation fails, resolve anyway to unblock the building process. resolve(); } ); }); }
javascript
{ "resource": "" }
q54229
setAttributeValues
train
function setAttributeValues(dom) { // List of input types here https://www.w3.org/TR/html5/forms.html#the-input-element // Limit scope to inputs only as textareas do not retain their value when cloned let elems = dom.find( `input[type=text], input[type=search], input[type=tel], input[type=url], input[type=email], input[type=password], input[type=number], input[type=checkbox], input[type=radio]` ); percyJQuery(elems).each(function() { let elem = percyJQuery(this); switch(elem.attr('type')) { case 'checkbox': case 'radio': if (elem.is(':checked')) { elem.attr('checked', ''); } break; default: elem.attr('value', elem.val()); } }); return dom; }
javascript
{ "resource": "" }
q54230
makeNormalizer
train
function makeNormalizer(load, options) { if (options && (options.normalizeMap || options.normalize)) { return function(name) { return optionsNormalize(options, name, load.name, load.address); }; } else { return function(name) { return name; }; } }
javascript
{ "resource": "" }
q54231
getAst
train
function getAst(load, sourceMapFileName){ if(load.ast) { return load.ast; } var fileName = sourceMapFileName || load.map && load.map.file; load.ast = esprima.parse(load.source.toString(), { loc: true, source: fileName || load.address }); if(load.map) { sourceMapToAst(load.ast, load.map); } return load.ast; }
javascript
{ "resource": "" }
q54232
visitRequireArgument
train
function visitRequireArgument(ast, cb) { types.visit(ast, { visitCallExpression: function(path) { if (this.isRequireExpression(path.node)) { var arg = path.getValueProperty("arguments")[0]; if (n.Literal.check(arg)) { cb(arg); } } this.traverse(path); }, isRequireExpression(node) { return n.Identifier.check(node.callee) && node.callee.name === "require"; } }); }
javascript
{ "resource": "" }
q54233
collectDependenciesIds
train
function collectDependenciesIds(ast) { var ids = []; visitRequireArgument(ast, function(argument) { ids.push(argument.value); }); return ids; }
javascript
{ "resource": "" }
q54234
endsWith
train
function endsWith(source, dest, path) { return ( path[path.length - 2] === source && path[path.length - 1] === dest ); }
javascript
{ "resource": "" }
q54235
train
function(from, to) { var path; bfs(from || "es6", formatsTransformsGraph, function(cur) { if (cur.node === to) { path = cur.path; return false; } }); return path; }
javascript
{ "resource": "" }
q54236
hasNestedDefine
train
function hasNestedDefine(ast) { var result = false; types.visit(ast, { visitCallExpression: function(path) { if (this.isDefineExpression(path)) { result = true; this.abort(); } this.traverse(path); }, // whether a non top level `define(` is call in the AST isDefineExpression: function(path) { return ( n.Identifier.check(path.node.callee) && path.node.callee.name === "define" && !n.Program.check(path.parent.parent.node) ); } }); return result; }
javascript
{ "resource": "" }
q54237
train
function(path) { return ( n.Identifier.check(path.node.callee) && path.node.callee.name === "define" && !n.Program.check(path.parent.parent.node) ); }
javascript
{ "resource": "" }
q54238
hasDefineAmdReference
train
function hasDefineAmdReference(ast) { var result = false; types.visit(ast, { visitMemberExpression: function(path) { if (this.isDefineAmd(path.node)) { result = true; this.abort(); } this.traverse(path); }, isDefineAmd: function(node) { return ( n.Identifier.check(node.object) && node.object.name === "define" && n.Identifier.check(node.property) && node.property.name === "amd" ); } }); return result; }
javascript
{ "resource": "" }
q54239
train
function(path) { return ( this.isDefineExpression(path.node) && n.Program.check(path.parent.parent.node) && n.ExpressionStatement.check(path.parent.node) ); }
javascript
{ "resource": "" }
q54240
train
function(args) { var result = { id: null, factory: null, dependencies: [] }; switch (args.length) { // define(factory); case 1: result.factory = getFactory(args[0]); break; // define(id || dependencies, factory); case 2: if (this.isNamed(args)) { assign(result, { id: args[0], factory: getFactory(args[1]) }); } else { assign(result, { dependencies: args[0], factory: getFactory(args[1]) }); } break; // define(id, dependencies, factory); case 3: assign(result, { id: args[0], dependencies: args[1], factory: getFactory(args[2]) }); break; default: throw new Error("Invalid `define` function signature"); } // set the `isCjsWrapper` flag result.isCjsWrapper = n.ArrayExpression.check(result.dependencies) && result.dependencies.elements.length ? this.usesCjsRequireExports(result.dependencies) : this.isCjsSimplifiedWrapper(result.factory); return result; }
javascript
{ "resource": "" }
q54241
getFactory
train
function getFactory(arg) { return n.ObjectExpression.check(arg) ? slimBuilder.makeFactoryFromObject(arg) : arg; }
javascript
{ "resource": "" }
q54242
valueStrim
train
function valueStrim(value, cutoff) { var strimLimit = typeof cutoff === 'undefined' ? 60 : cutoff; var t = typeof value; if (t === 'function') { return '[function]'; } if (t === 'object') { value = JSON.stringify(value); if (value.length > strimLimit) { value = value.substr(0, strimLimit) + '...'; } return value; } if (t === 'string') { if (value.length > strimLimit) { return JSON.stringify(value.substr(0, strimLimit)) + '...'; } return JSON.stringify(value); } return '' + value; }
javascript
{ "resource": "" }
q54243
train
function (error, data, schema, indent) { var schemaValue; var dataValue; var schemaLabel; // assemble error string var ret = ''; ret += '\n' + indent + error.message; schemaLabel = extractSchemaLabel(schema, 60); if (schemaLabel) { ret += '\n' + indent + ' schema: ' + schemaLabel; } if (error.schemaPath) { schemaValue = jsonpointer.get(schema, error.schemaPath); ret += '\n' + indent + ' rule: ' + error.schemaPath + ' -> ' + valueStrim(schemaValue); } if (error.dataPath) { dataValue = jsonpointer.get(data, error.dataPath); ret += '\n' + indent + ' field: ' + error.dataPath + ' -> ' + utils.type(dataValue) + ': ' + valueStrim(dataValue); } // sub errors are not implemented (yet?) // https://github.com/chaijs/chai-json-schema/issues/3 /*if (error.subErrors) { forEachI(error.subErrors, function (error) { ret += formatResult(error, data, schema, indent + indent); }); }*/ return ret; }
javascript
{ "resource": "" }
q54244
initFlags
train
function initFlags(flags, dispatch) { var flagValues = { isLDReady: false }; for (var flag in flags) { var camelCasedKey = (0, _lodash2.default)(flag); flagValues[camelCasedKey] = flags[flag]; } dispatch((0, _actions.setFlags)(flagValues)); }
javascript
{ "resource": "" }
q54245
setFlags
train
function setFlags(flags, dispatch) { var flagValues = { isLDReady: true }; for (var flag in flags) { var camelCasedKey = (0, _lodash2.default)(flag); flagValues[camelCasedKey] = ldClient.variation(flag, flags[flag]); } dispatch((0, _actions.setFlags)(flagValues)); }
javascript
{ "resource": "" }
q54246
obj
train
function obj(/*key,value, key,value ...*/) { var result = {} for(var n=0; n<arguments.length; n+=2) { result[arguments[n]] = arguments[n+1] } return result }
javascript
{ "resource": "" }
q54247
addOperator
train
function addOperator(obj, field, operator, operand) { if(obj[field] === undefined) { obj[field] = {} } obj[field][operator] = operand }
javascript
{ "resource": "" }
q54248
mongoEqual
train
function mongoEqual(documentValue,queryOperand) { if(documentValue instanceof Array) { if(!(queryOperand instanceof Array)) return false if(documentValue.length !== queryOperand.length) { return false } else { return documentValue.reduce(function(previousValue, currentValue, index) { return previousValue && mongoEqual(currentValue,queryOperand[index]) }, true) } } else if(documentValue instanceof Object) { if(!(queryOperand instanceof Object)) return false var aKeys = Object.keys(documentValue) var bKeys = Object.keys(queryOperand) if(aKeys.length !== bKeys.length) { return false } else { for(var n=0; n<aKeys.length; n++) { if(aKeys[n] !== bKeys[n]) return false var key = aKeys[n] var aVal = documentValue[key] var bVal = queryOperand[key] if(!mongoEqual(aVal,bVal)) { return false } } // else return true } } else { if(queryOperand === null) { return documentValue === undefined || documentValue === null } else { return documentValue===queryOperand } } }
javascript
{ "resource": "" }
q54249
sortCompare
train
function sortCompare(a,b,sortProperty) { var aVal = DotNotationPointers(a, sortProperty)[0].val // todo: figure out what mongo does with multiple matching sort properties var bVal = DotNotationPointers(b, sortProperty)[0].val if(aVal > bVal) { return 1 } else if(aVal < bVal) { return -1 } else { return 0 } }
javascript
{ "resource": "" }
q54250
parseFieldOperator
train
function parseFieldOperator(field, operator, operand) { if(operator === '$elemMatch') { var elemMatchInfo = parseElemMatch(operand) var innerParts = elemMatchInfo.parts var implicitField = elemMatchInfo.implicitField } else if(operator === '$not') { var innerParts = parseNot(field, operand) } else { var innerParts = [] } return new Part(field, operator, operand, innerParts, implicitField) }
javascript
{ "resource": "" }
q54251
addBasicInfoWrapper
train
function addBasicInfoWrapper(basicInfo) { Yamaha.prototype[basicInfo] = function(zone) { return this.getBasicInfo(zone).then(function(result) { return result[basicInfo](); }); }; }
javascript
{ "resource": "" }
q54252
formatDate
train
function formatDate(date) { date = new Date(date); var monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]; return ( monthNames[date.getMonth()] + ' ' + date.getDate() + ', ' + date.getFullYear() ); }
javascript
{ "resource": "" }
q54253
formatDatetime
train
function formatDatetime(date) { date = new Date(date); var hour = date.getHours(); var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes().toString() : date.getMinutes(); return formatDate(date) + ' ' + hour + ':' + minutes; }
javascript
{ "resource": "" }
q54254
Forwarded
train
function Forwarded(ip, port, secured) { this.ip = ip || '127.0.0.1'; this.secure = !!secured; this.port = +port || 0; }
javascript
{ "resource": "" }
q54255
forwarded
train
function forwarded(headers, whitelist) { var ports, port, proto, ips, ip, length = proxies.length, i = 0; for (; i < length; i++) { if (!(proxies[i].ip in headers)) continue; ports = (headers[proxies[i].port] || '').split(','); ips = (headers[proxies[i].ip] || '').match(pattern); proto = (headers[proxies[i].proto] || 'http'); // // As these headers can potentially be set by a 1337H4X0R we need to ensure // that all supplied values are valid IP addresses. If we receive a none // IP value inside the IP header field we are going to assume that this // header has been compromised and should be ignored // if (!ips || !ips.every(net.isIP)) return; port = ports.shift(); // Extract the first port as it's the "source" port. ip = ips.shift(); // Extract the first IP as it's the "source" IP. // // If we were given a white list, we need to ensure that the proxies that // we're given are known and allowed. // if (whitelist && whitelist.length && !ips.every(function every(ip) { return ~whitelist.indexOf(ip); })) return; // // Shift the most recently found proxy header to the front of the proxies // array. This optimizes future calls, placing the most commonly found headers // near the front of the array. // if (i !== 0) { proxies.unshift(proxies.splice(i, 1)[0]); } // // We've gotten a match on a HTTP header, we need to parse it further as it // could consist of multiple hops. The pattern for multiple hops is: // // client, proxy, proxy, proxy, etc. // // So extracting the first IP should be sufficient. There are SSL // terminators like the once's that is used by `fastly.com` which set their // HTTPS header to `1` as an indication that the connection was secure. // (This reduces bandwidth) // return new Forwarded(ip, port, proto === '1' || proto === 'https'); } }
javascript
{ "resource": "" }
q54256
parse
train
function parse(obj, headers, whitelist) { var proxied = forwarded(headers || {}, whitelist) , connection = obj.connection , socket = connection ? connection.socket : obj.socket; // // We should always be testing for HTTP headers as remoteAddress would point // to proxies. // if (proxied) return proxied; // Check for the property on our given object. if ('object' === typeof obj) { if ('remoteAddress' in obj) { return new Forwarded( obj.remoteAddress, obj.remotePort, 'secure' in obj ? obj.secure : obj.encrypted ); } // Edge case for Socket.IO 0.9 if ('object' === typeof obj.address && obj.address.address) { return new Forwarded( obj.address.address, obj.address.port, 'secure' in obj ? obj.secure : obj.encrypted ); } } if ('object' === typeof connection && 'remoteAddress' in connection) { return new Forwarded( connection.remoteAddress, connection.remotePort, 'secure' in connection ? connection.secure : connection.encrypted ); } if ('object' === typeof socket && 'remoteAddress' in socket) { return new Forwarded( socket.remoteAddress, socket.remoteAddress, 'secure' in socket ? socket.secure : socket.encrypted ); } return new Forwarded(); }
javascript
{ "resource": "" }
q54257
parse_partial_number
train
function parse_partial_number(value, country_code, metadata) { // "As you type" formatter const formatter = new as_you_type(country_code, metadata) // Input partially entered phone number formatter.input('+' + getPhoneCode(country_code) + value) // Return the parsed partial phone number // (has `.national_number`, `.country`, etc) return formatter }
javascript
{ "resource": "" }
q54258
e164
train
function e164(value, country_code, metadata) { if (!value) { return undefined } // If the phone number is being input in an international format if (value[0] === '+') { // If it's just the `+` sign if (value.length === 1) { return undefined } // If there are some digits, the `value` is returned as is return value } // For non-international phone number a country code is required if (!country_code) { return undefined } // The phone number is being input in a country-specific format const partial_national_number = parse_partial_number(value, country_code).national_number if (!partial_national_number) { return undefined } // The value is converted to international plaintext return format(partial_national_number, country_code, 'International_plaintext', metadata) }
javascript
{ "resource": "" }
q54259
get_country_option_icon
train
function get_country_option_icon(countryCode, { flags, flagsPath, flagComponent }) { if (flags === false) { return undefined } if (flags && flags[countryCode]) { return flags[countryCode] } return React.createElement(flagComponent, { countryCode, flagsPath }) }
javascript
{ "resource": "" }
q54260
should_add_international_option
train
function should_add_international_option(properties) { const { countries, international } = properties // If this behaviour is explicitly set, then do as it says. if (international !== undefined) { return international } // If `countries` is empty, // then only "International" option is available, so add it. if (countries.length === 0) { return true } // If `countries` is a single allowed country, // then don't add the "International" option // because it would make no sense. if (countries.length === 1) { return false } // Show the "International" option by default return true }
javascript
{ "resource": "" }
q54261
could_phone_number_belong_to_country
train
function could_phone_number_belong_to_country(phone_number, country_code, metadata) { // Strip the leading `+` const phone_number_digits = phone_number.slice('+'.length) for (const country_phone_code of Object.keys(metadata.country_phone_code_to_countries)) { const possible_country_phone_code = phone_number_digits.substring(0, country_phone_code.length) if (country_phone_code.indexOf(possible_country_phone_code) === 0) { // This country phone code is possible. // Does the given country correspond to this country phone code. if (metadata.country_phone_code_to_countries[country_phone_code].indexOf(country_code) >= 0) { return true } } } }
javascript
{ "resource": "" }
q54262
normalize_country_code
train
function normalize_country_code(country, dictionary) { // Normalize `country` if it's an empty string if (country === '') { country = undefined } // No country is selected ("International") if (country === undefined || country === null) { return country } // Check that `country` code exists if (dictionary[country] || default_dictionary[country]) { return country } throw new Error(`Unknown country: "${country}"`) }
javascript
{ "resource": "" }
q54263
train
function (instance, sourceFields) { var slugParts = sourceFields.map(function (slugSourceField) { return instance[slugSourceField]; }); var options = (slugOptions && slugOptions.slugOptions) || { lower: true}; return slug(slugParts.join(' '), options); }
javascript
{ "resource": "" }
q54264
train
function (slug) { var query = { where: {} }; query.where[slugColumn] = slug; return Model.findOne(query).then(function (model) { return model === null; }); }
javascript
{ "resource": "" }
q54265
train
function (instance, sourceFields, suffixFields) { return (function suffixHelper(instance, sourceFields, suffixFields, suffixCount) { if (!suffixFields || !Array.isArray(suffixFields)) { return Promise.resolve(null); } if (suffixCount > suffixFields.length) { return Promise.resolve(slugifyFields(instance, slugOptions.source.concat(suffixFields.slice(0)))); } var slug = slugifyFields(instance, slugOptions.source.concat(suffixFields.slice(0, suffixCount))); return checkSlug(slug).then(function (isUnique) { if (isUnique) { return slug; } return suffixHelper(instance, sourceFields, suffixFields, suffixCount + 1); }); })(instance, sourceFields, suffixFields, 1); }
javascript
{ "resource": "" }
q54266
renameFiles
train
function renameFiles(destinationPath, moduleName) { const Module = pascalize(moduleName); // change to destination directory shell.cd(destinationPath); // rename files shell.ls('-Rl', '.').forEach(entry => { if (entry.isFile()) { shell.mv(entry.name, entry.name.replace('Module', Module)); } }); // replace module names shell.ls('-Rl', '.').forEach(entry => { if (entry.isFile()) { shell.sed('-i', /\$module\$/g, moduleName, entry.name); shell.sed('-i', /\$_module\$/g, decamelize(moduleName), entry.name); shell.sed('-i', /\$Module\$/g, Module, entry.name); shell.sed('-i', /\$MoDuLe\$/g, startCase(moduleName), entry.name); shell.sed('-i', /\$MODULE\$/g, moduleName.toUpperCase(), entry.name); } }); }
javascript
{ "resource": "" }
q54267
train
function (f, cont) { var result = f(); if (result && typeof result.always === 'function') { result.always(cont); } else { cont(); } }
javascript
{ "resource": "" }
q54268
train
function (arr, pred) { for (var i = 0; i < arr.length; i++) { var value = arr[i]; if (pred(value, i, arr)) { return value; } } return null; }
javascript
{ "resource": "" }
q54269
train
function (path1, path2) { return path1.length === 0 ? path2 : (path2.length === 0 ? path1 : path1.concat(path2)); }
javascript
{ "resource": "" }
q54270
train
function (target, firstSource) { if (target === undefined || target === null) { throw new TypeError('Cannot convert first argument to object'); } var to = Object(target); var hasPendingException = false; var pendingException; for (var i = 1; i < arguments.length; i++) { var nextSource = arguments[i]; if (nextSource === undefined || nextSource === null) continue; var keysArray = Object.keys(Object(nextSource)); for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) { var nextKey = keysArray[nextIndex]; try { var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey); if (desc !== undefined && desc.enumerable) to[nextKey] = nextSource[nextKey]; } catch (e) { if (!hasPendingException) { hasPendingException = true; pendingException = e; } } } if (hasPendingException) throw pendingException; } return to; }
javascript
{ "resource": "" }
q54271
train
function (binding, subpath, f) { var args = Util.resolveArgs( arguments, 'binding', function (x) { return Util.canRepresentSubpath(x) ? 'subpath' : null; }, '?f' ); return function (event) { var value = event.target.value; binding.set(args.subpath, args.f ? args.f(value) : value); }; }
javascript
{ "resource": "" }
q54272
train
function (binding, subpath, pred) { var args = Util.resolveArgs( arguments, 'binding', function (x) { return Util.canRepresentSubpath(x) ? 'subpath' : null; }, '?pred' ); return function (event) { var value = event.target.value; if (!args.pred || args.pred(value)) { binding.remove(args.subpath); } }; }
javascript
{ "resource": "" }
q54273
train
function (cb, key, shiftKey, ctrlKey) { var effectiveShiftKey = shiftKey || false; var effectiveCtrlKey = ctrlKey || false; return function (event) { var keyMatched = typeof key === 'string' ? event.key === key : Util.find(key, function (k) { return k === event.key; }); if (keyMatched && event.shiftKey === effectiveShiftKey && event.ctrlKey === effectiveCtrlKey) { cb(event); } }; }
javascript
{ "resource": "" }
q54274
train
function (binding) { var historyBinding = getHistoryBinding(binding); var undo = historyBinding.get('undo'); return !!undo && !undo.isEmpty(); }
javascript
{ "resource": "" }
q54275
train
function (binding) { var historyBinding = getHistoryBinding(binding); var redo = historyBinding.get('redo'); return !!redo && !redo.isEmpty(); }
javascript
{ "resource": "" }
q54276
train
function (binding) { var historyBinding = getHistoryBinding(binding); var listenerId = historyBinding.get('listenerId'); var undoBinding = historyBinding.sub('undo'); var redoBinding = historyBinding.sub('redo'); return revert(binding, undoBinding, redoBinding, listenerId, 'oldValue'); }
javascript
{ "resource": "" }
q54277
normalizeAttributes
train
function normalizeAttributes(selector) { selector.walkAttributes((node) => { if (node.value) { // remove quotes node.value = node.value.replace(/'|\\'|"|\\"/g, ''); } }); }
javascript
{ "resource": "" }
q54278
sortGroups
train
function sortGroups(selector) { selector.each((subSelector) => { subSelector.nodes.sort((a, b) => { // different types cannot be sorted if (a.type !== b.type) { return 0; } // sort alphabetically return a.value < b.value ? -1 : 1; }); }); selector.sort((a, b) => (a.nodes.join('') < b.nodes.join('') ? -1 : 1)); }
javascript
{ "resource": "" }
q54279
removeDupProperties
train
function removeDupProperties(selector) { // Remove duplicated properties from bottom to top () for (let actIndex = selector.nodes.length - 1; actIndex >= 1; actIndex--) { for (let befIndex = actIndex - 1; befIndex >= 0; befIndex--) { if (selector.nodes[actIndex].prop === selector.nodes[befIndex].prop) { selector.nodes[befIndex].remove(); actIndex--; } } } }
javascript
{ "resource": "" }
q54280
train
function (path, sharedInternals) { /** @private */ this._path = path || EMPTY_PATH; /** @protected * @ignore */ this._sharedInternals = sharedInternals || {}; if (!this._sharedInternals.listeners) { this._sharedInternals.listeners = {}; } if (!this._sharedInternals.cache) { this._sharedInternals.cache = {}; } }
javascript
{ "resource": "" }
q54281
train
function (newBackingValue) { var newSharedInternals = {}; Util.assign(newSharedInternals, this._sharedInternals); newSharedInternals.backingValue = newBackingValue; return new Binding(this._path, newSharedInternals); }
javascript
{ "resource": "" }
q54282
train
function (alternativeBackingValue, compare) { var value = this.get(); var alternativeValue = alternativeBackingValue ? alternativeBackingValue.getIn(this._path) : undefined; return compare ? !compare(value, alternativeValue) : !(value === alternativeValue || (Util.undefinedOrNull(value) && Util.undefinedOrNull(alternativeValue))); }
javascript
{ "resource": "" }
q54283
train
function (subpath) { if (!this._sharedInternals.metaBinding) { var metaBinding = Binding.init(Imm.Map()); linkMeta(this, metaBinding); this._sharedInternals.metaBinding = metaBinding; } var effectiveSubpath = subpath ? Util.joinPaths([Util.META_NODE], asArrayPath(subpath)) : [Util.META_NODE]; var thisPath = this.getPath(); var absolutePath = thisPath.length > 0 ? Util.joinPaths(thisPath, effectiveSubpath) : effectiveSubpath; return this._sharedInternals.metaBinding.sub(absolutePath); }
javascript
{ "resource": "" }
q54284
train
function (subpath) { var value = this.sub(subpath).get(); return Imm.Iterable.isIterable(value) ? value.toJS() : value; }
javascript
{ "resource": "" }
q54285
train
function (subpath) { var pathAsArray = asArrayPath(subpath); var absolutePath = Util.joinPaths(this._path, pathAsArray); if (absolutePath.length > 0) { var absolutePathAsString = asStringPath(absolutePath); var cached = this._sharedInternals.cache[absolutePathAsString]; if (cached) { return cached; } else { var subBinding = new Binding(absolutePath, this._sharedInternals); this._sharedInternals.cache[absolutePathAsString] = subBinding; return subBinding; } } else { return this; } }
javascript
{ "resource": "" }
q54286
train
function (subpath, cb) { var args = Util.resolveArgs( arguments, function (x) { return Util.canRepresentSubpath(x) ? 'subpath' : null; }, 'cb' ); var listenerId = generateListenerId(); var pathAsString = asStringPath(Util.joinPaths(this._path, asArrayPath(args.subpath || ''))); var samePathListeners = this._sharedInternals.listeners[pathAsString]; var listenerDescriptor = { cb: args.cb, disabled: false }; if (samePathListeners) { samePathListeners[listenerId] = listenerDescriptor; } else { var listeners = {}; listeners[listenerId] = listenerDescriptor; this._sharedInternals.listeners[pathAsString] = listeners; } return listenerId; }
javascript
{ "resource": "" }
q54287
train
function (subpath, cb) { var args = Util.resolveArgs( arguments, function (x) { return Util.canRepresentSubpath(x) ? 'subpath' : null; }, 'cb' ); var self = this; var listenerId = self.addListener(args.subpath, function () { self.removeListener(listenerId); args.cb(); }); return listenerId; }
javascript
{ "resource": "" }
q54288
train
function (listenerId, f) { var samePathListeners = findSamePathListeners(this, listenerId); if (samePathListeners) { var descriptor = samePathListeners[listenerId]; descriptor.disabled = true; Util.afterComplete(f, function () { descriptor.disabled = false; }); } else { f(); } return this; }
javascript
{ "resource": "" }
q54289
train
function (binding, promise) { /** @private */ this._binding = binding; /** @private */ this._queuedUpdates = []; /** @private */ this._finishedUpdates = []; /** @private */ this._committed = false; /** @private */ this._cancelled = false; /** @private */ this._hasChanges = false; /** @private */ this._hasMetaChanges = false; if (promise) { var self = this; promise.then(Util.identity, function () { if (!self.isCancelled()) { self.cancel(); } }); } }
javascript
{ "resource": "" }
q54290
train
function (binding, subpath) { var args = Util.resolveArgs( arguments, function (x) { return x instanceof Binding ? 'binding' : null; }, '?subpath' ); addDeletion(this, args.binding || this._binding, asArrayPath(args.subpath)); return this; }
javascript
{ "resource": "" }
q54291
train
function (binding, metaBinding, options) { /** @private */ this._initialMetaState = metaBinding.get(); /** @private */ this._previousMetaState = null; /** @private */ this._metaBinding = metaBinding; /** @protected * @ignore */ this._metaChanged = false; /** @private */ this._initialState = binding.get(); /** @protected * @ignore */ this._previousState = null; /** @private */ this._stateBinding = binding; /** @protected * @ignore */ this._stateChanged = false; /** @private */ this._options = options; /** @private */ this._renderQueued = false; /** @private */ this._fullUpdateQueued = false; /** @protected * @ignore */ this._fullUpdateInProgress = false; /** @private */ this._componentQueue = []; /** @private */ this._lastComponentQueueId = 0; }
javascript
{ "resource": "" }
q54292
train
function (subpath, options) { var args = Util.resolveArgs( arguments, function (x) { return Util.canRepresentSubpath(x) ? 'subpath' : null; }, '?options' ); var pathAsArray = args.subpath ? Binding.asArrayPath(args.subpath) : []; var tx = this.getBinding().atomically(); tx.set(pathAsArray, this._initialState.getIn(pathAsArray)); var effectiveOptions = args.options || {}; if (effectiveOptions.resetMeta !== false) { tx.set(this.getMetaBinding(), pathAsArray, this._initialMetaState.getIn(pathAsArray)); } tx.commit({ notify: effectiveOptions.notify }); }
javascript
{ "resource": "" }
q54293
train
function (newState, newMetaState, options) { var args = Util.resolveArgs( arguments, 'newState', function (x) { return Imm.Map.isMap(x) ? 'newMetaState' : null; }, '?options' ); var effectiveOptions = args.options || {}; var tx = this.getBinding().atomically(); tx.set(newState); if (args.newMetaState) tx.set(this.getMetaBinding(), args.newMetaState); tx.commit({ notify: effectiveOptions.notify }); }
javascript
{ "resource": "" }
q54294
train
function (binding, subpath, compare) { var args = Util.resolveArgs( arguments, 'binding', function (x) { return Util.canRepresentSubpath(x) ? 'subpath' : null; }, '?compare' ); return args.binding.sub(args.subpath).isChanged(this._previousState, args.compare || Imm.is); }
javascript
{ "resource": "" }
q54295
train
function (rootComp, reactContext) { var ctx = this; var effectiveReactContext = reactContext || {}; effectiveReactContext.morearty = ctx; return React.createClass({ displayName: 'Bootstrap', childContextTypes: { morearty: React.PropTypes.instanceOf(Context).isRequired }, getChildContext: function () { return effectiveReactContext; }, componentWillMount: function () { ctx.init(this); }, render: function () { var effectiveProps = Util.assign({}, {binding: ctx.getBinding()}, this.props); return React.createFactory(rootComp)(effectiveProps); } }); }
javascript
{ "resource": "" }
q54296
train
function (name) { var ctx = this.getMoreartyContext(); return getBinding(this.props, name).withBackingValue(ctx._previousState).get(); }
javascript
{ "resource": "" }
q54297
train
function (binding, cb) { if (!this.observedBindings) { this.observedBindings = []; } var bindingPath = binding.getPath(); if (!Util.find(this.observedBindings, function (b) { return b.getPath() === bindingPath; })) { this.observedBindings.push(binding); setupObservedBindingListener(this, binding); } return cb ? cb(binding.get()) : undefined; }
javascript
{ "resource": "" }
q54298
train
function (binding, subpath, cb) { var args = Util.resolveArgs( arguments, function (x) { return x instanceof Binding ? 'binding' : null; }, function (x) { return Util.canRepresentSubpath(x) ? 'subpath' : null; }, 'cb' ); if (!this._bindingListenerRemovers) { this._bindingListenerRemovers = []; } var effectiveBinding = args.binding || this.getDefaultBinding(); if (!effectiveBinding) { return console.warn('Morearty: cannot attach binding listener to a component without default binding'); } var listenerId = effectiveBinding.addListener(args.subpath, args.cb); this._bindingListenerRemovers.push(function () { effectiveBinding.removeListener(listenerId); }); return listenerId; }
javascript
{ "resource": "" }
q54299
train
function (spec) { var initialState, initialMetaState, options; if (arguments.length <= 1) { var effectiveSpec = spec || {}; initialState = effectiveSpec.initialState; initialMetaState = effectiveSpec.initialMetaState; options = effectiveSpec.options; } else { console.warn( 'Passing multiple arguments to createContext is deprecated. Use single object form instead.' ); initialState = arguments[0]; initialMetaState = arguments[1]; options = arguments[2]; } var ensureImmutable = function (state) { return Imm.Iterable.isIterable(state) ? state : Imm.fromJS(state); }; var state = ensureImmutable(initialState || {}); var metaState = ensureImmutable(initialMetaState || {}); var metaBinding = Binding.init(metaState); var binding = Binding.init(state, metaBinding); var effectiveOptions = options || {}; return new Context(binding, metaBinding, { requestAnimationFrameEnabled: effectiveOptions.requestAnimationFrameEnabled !== false, renderOnce: effectiveOptions.renderOnce || false, stopOnRenderError: effectiveOptions.stopOnRenderError || false, logger: effectiveOptions.logger || defaultLogger }); }
javascript
{ "resource": "" }