_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
27
233k
language
stringclasses
1 value
meta_information
dict
q5100
ensureArray
train
function ensureArray(object, key) { if (!object[key]) { object[key] = []; } if (!Array.isArray(object[key])) {
javascript
{ "resource": "" }
q5101
registerHook
train
function registerHook(className, hookType, hookFn) { if (!hooks[className])
javascript
{ "resource": "" }
q5102
getHook
train
function getHook(className, hookType) { if (hooks[className] &&
javascript
{ "resource": "" }
q5103
extractOps
train
function extractOps(data) { const ops = {}; _.forIn(data, (attribute, key) =>
javascript
{ "resource": "" }
q5104
applyOps
train
function applyOps(data, ops, className) { debugPrint('OPS', ops); _.forIn(ops, (value, key) => { const operator = value.__op; if (operator in UPDATE_OPERATORS) { UPDATE_OPERATORS[operator](data, key, value, className); } else {
javascript
{ "resource": "" }
q5105
queryFilter
train
function queryFilter(where) { if (where.$or) { return object => _.reduce(where.$or, (result, subclause) => result || queryFilter(subclause)(object), false); } // Go through each key in where clause return
javascript
{ "resource": "" }
q5106
fetchObjectByPointer
train
function fetchObjectByPointer(pointer) { const collection = getCollection(pointer.className); const storedItem = collection[pointer.objectId]; if (storedItem === undefined) { return undefined; }
javascript
{ "resource": "" }
q5107
includePaths
train
function includePaths(object, pathsRemaining) { debugPrint('INCLUDE', { object, pathsRemaining }); const path = pathsRemaining.shift(); const target = object && object[path]; if (target) { if (Array.isArray(target)) { object[path] = target.map(pointer => { const fetched = fetchObjectByPointer(pointer); includePaths(fetched, _.cloneDeep(pathsRemaining)); return fetched;
javascript
{ "resource": "" }
q5108
sortQueryresults
train
function sortQueryresults(matches, order) { const orderArray = order.split(',').map(k => { let dir = 'asc'; let key = k; if (k.charAt(0) === '-') { key = k.substring(1); dir = 'desc'; } return [item => deserializeQueryParam(item[key]), dir]; });
javascript
{ "resource": "" }
q5109
runHook
train
function runHook(className, hookType, data) { let hook = getHook(className, hookType); if (hook) { const hydrate = (rawData) => { const modelData = Object.assign({}, rawData, { className }); const modelJSON = _.mapValues(modelData, // Convert dates into JSON loadable representations value => ((value instanceof Date) ? value.toJSON() : value) ); return Parse.Object.fromJSON(modelJSON); }; const model = hydrate(data, className); hook = hook.bind(model); const collection = getCollection(className); let original; if (collection[model.id]) { original = hydrate(collection[model.id]); } // TODO Stub out Parse.Cloud.useMasterKey() so that we can report the correct 'master' // value here. return hook(makeRequestObject(original, model, false)).then((beforeSaveOverrideValue) => {
javascript
{ "resource": "" }
q5110
compareWebhooks
train
function compareWebhooks(webhook, name, targetUrl, resource, event, filter, secret) { if ((webhook.name !== name) || (webhook.targetUrl !== targetUrl) || (webhook.resource !== resource) || (webhook.event !== event)) { return false; } // they look pretty identifty, let's check optional fields if (filter) { if (filter !== webhook.filter) { fine("webhook look pretty similar BUT filter is different"); return false; } } else { if (webhook.filter) { fine("webhook look
javascript
{ "resource": "" }
q5111
HTTPError
train
function HTTPError(statusCode, data) { Error.call(this); Error.captureStackTrace(this, this.constructor); /** * Human-readable error name. * * @type {String} */ this.name = http.STATUS_CODES[statusCode]; /** * HTTP status code. * * @type {Number} */ this.statusCode = statusCode; /**
javascript
{ "resource": "" }
q5112
train
function (config) { return _.map(config.features, function(featureDef) { var feature = null , featurePath = null; var featureId = featureDef.$featureId || featureDef.feature; // Try to require the feature from each path listed in `config.featurePaths`. for (var i = 0; i < config.featurePaths.length; ++i) { featurePath = path.join(config.featurePaths[i], featureDef.feature); if (fs.existsSync(featurePath) || fs.existsSync(featurePath + '.js')) { feature = require(featurePath); break; } } if (!feature) {
javascript
{ "resource": "" }
q5113
randomHexString
train
function randomHexString(size) { if (size === 0) { throw new Error('Zero-length randomHexString is useless.'); } if (size % 2 !== 0) { throw new
javascript
{ "resource": "" }
q5114
train
function () { var defaultMinLength = 2, config = {}; if(!this.props.bloodhound) this.props.bloodhound = {}; if(!this.props.typeahead) this.props.typeahead = {}; if(!this.props.datasource) this.props.datasource = {}; var defaults = { bloodhound: { datumTokenizer: Bloodhound.tokenizers.whitespace, queryTokenizer: Bloodhound.tokenizers.whitespace }, typeahead: { minLength: defaultMinLength, hint: true, highlight: true }, datasource: { displayProperty: 'value',
javascript
{ "resource": "" }
q5115
train
function () { var self = this, options = this.initOptions(); var remoteCall = new Bloodhound(options.bloodhound); options.datasource.source = remoteCall;
javascript
{ "resource": "" }
q5116
readFileOrError
train
function readFileOrError(uri) { var content; try { content = fs.readFileSync(uri, 'utf8');
javascript
{ "resource": "" }
q5117
DocumentGraph
train
function DocumentGraph(options) { this.options = object.extend(defaultOptions, options || {}); this._gloss = new Glossary(); // Parse redis cluster configuration in the form of: // "host:port,host:port,host:port" if (this.options.redisCluster) { var addresses = this.options.redisCluster.split(','); var config = []; for (var i = 0; i < addresses.length; i++) { var items = addresses[i].split(':'); var host = "0.0.0.0"; var port = 6379; if (items.length == 1) { port = parseInt(items[0]); } else { if (items[0].length > 0) { host = items[0]; } port = parseInt(items[1]); }
javascript
{ "resource": "" }
q5118
train
function(err, results) { if (err) { callback(err); return; } var keyFrequency = parseInt(results[0]); var docFrequency = parseInt(results[1]); var keyDocFrequency = results[2]; // ensure that key frequency is relative to the given document (when appropriate) if (id && results.length == 4) { keyFrequency = parseInt(results[3]); } var tf = 1 + (Math.log(keyFrequency) / Math.LN10); var idf = Math.log(docFrequency / keyDocFrequency) / Math.LN10;
javascript
{ "resource": "" }
q5119
onError
train
function onError(e) { if (!inBrowser) { return {}; } let response = {}; if (e.response) { response = e.response.data; }
javascript
{ "resource": "" }
q5120
train
function(config) { var app = null; try { app = module.exports.createApp(config); } catch (err) {
javascript
{ "resource": "" }
q5121
train
function(app) { var config = app.config; var testing = config.profile === 'testing'; var starterPromise =
javascript
{ "resource": "" }
q5122
recover
train
function recover(rawTx, v, r, s) { const rawTransaction = typeof(rawTx) === 'string' ? new Buffer(stripHexPrefix(rawTx), 'hex') : rawTx; const signedTransaction = rlp.decode(rawTransaction); const raw = []; transactionFields.forEach((fieldInfo, fieldIndex) => { raw[fieldIndex] = signedTransaction[fieldIndex];
javascript
{ "resource": "" }
q5123
sign
train
function sign(transaction, privateKey, toObject) { if (typeof transaction !== 'object' || transaction === null) { throw new Error(`[ethjs-signer] transaction input must be a type 'object', got '${typeof(transaction)}'`); } if (typeof privateKey !== 'string') { throw new Error('[ethjs-signer] private key input must be a string'); } if (!privateKey.match(/^(0x)[0-9a-fA-F]{64}$/)) { throw new Error('[ethjs-signer] invalid private key value, private key must be a prefixed hexified 32 byte string (i.e. "0x..." 64 chars long).'); } const raw = []; transactionFields.forEach((fieldInfo) => { var value = new Buffer(0); // eslint-disable-line // shim for field name gas const txKey = (fieldInfo.name === 'gasLimit' && transaction.gas) ? 'gas' : fieldInfo.name; if (typeof transaction[txKey] !== 'undefined') { if (fieldInfo.number === true) {
javascript
{ "resource": "" }
q5124
insertCollection
train
function insertCollection(modelName, data, db, callback) { callback = callback || {}; //Counters for managing callbacks var tasks = { total: 0, done: 0 }; //Load model var Model = db.model(modelName); //Clear existing collection Model.collection.remove(function(err) { if (err) return callback(err); //Convert object to array var items = []; if (Array.isArray(data)) { items = data; } else { for (var i in data) { items.push(data[i]); } } //Check number of tasks to run if (items.length == 0) { return callback(); } else { tasks.total = items.length; }
javascript
{ "resource": "" }
q5125
loadObject
train
function loadObject(data, db, callback) { callback = callback || function() {}; var iterator = function(modelName, next){
javascript
{ "resource": "" }
q5126
loadFile
train
function loadFile(file, db, callback) { callback = callback || function() {}; if (file.substr(0, 1) !== '/') { var parentPath = module.parent.filename.split('/');
javascript
{ "resource": "" }
q5127
loadDir
train
function loadDir(dir, db, callback) { callback = callback || function() {}; //Get the absolute dir path if a relative path was given if (dir.substr(0, 1) !== '/') { var parentPath = module.parent.filename.split('/'); parentPath.pop(); dir = parentPath.join('/') + '/' + dir; } //Load each file
javascript
{ "resource": "" }
q5128
tagElmRelease
train
async function tagElmRelease(config, context) { function exec(command) { context.logger.log(`Running: ${command}`); execSync(command); } const elmPackageJson = JSON.parse(fs.readFileSync('elm.json')); await tag(elmPackageJson.version); const repositoryUrl = await getGitAuthUrl(config); await push(repositoryUrl, config.branch);
javascript
{ "resource": "" }
q5129
Entry
train
function Entry (content, name, parent) { if (!(this instanceof Entry)) return new Entry(content, name, parent); this._parent = parent; // parent can be a Document or ArrayField this._schema = parent._schema; // the root Document this._name = name; // the field name supplied
javascript
{ "resource": "" }
q5130
remove
train
function remove (state, prefix, objectsOrIds, change) { if (Array.isArray(objectsOrIds)) { return Promise.all(objectsOrIds.map(markAsDeleted.bind(null, state, change)))
javascript
{ "resource": "" }
q5131
Field
train
function Field (field, name, parent) { if (!(this instanceof Field)) return new Field(field, name, parent); debug('field <%s> being built from <%s>', name, field); Entry.call(this, field, name, parent); this._context = parent._context; this._this = parent._this; if (typeof
javascript
{ "resource": "" }
q5132
train
function(results) { var globalScoreSum = 0; var globalScoreCount = 0; var rulesScoresSum = {}; var rulesScoresCount = {}; var rulesValuesSum = {}; var rulesValuesCount = {}; results.forEach(function(result) { // Global score globalScoreSum += result.scoreProfiles.generic.globalScore; globalScoreCount ++; // Rules for (var ruleName in result.rules) { if (!rulesScoresCount[ruleName]) { rulesScoresSum[ruleName] = 0; rulesScoresCount[ruleName] = 0; rulesValuesSum[ruleName] = 0; rulesValuesCount[ruleName] = 0; } rulesScoresSum[ruleName] += result.rules[ruleName].score; rulesScoresCount[ruleName] ++; rulesValuesSum[ruleName] += result.rules[ruleName].value; rulesValuesCount[ruleName] ++; } }); // Calculate averages var averageObject = { scoreProfiles: { generic: {
javascript
{ "resource": "" }
q5133
train
function(phrasesArray) { var deferred = Q.defer(); if (phrasesArray === undefined) { phrasesArray = []; } // Default conditionsObject var conditionsObject = { atLeastOneUrl: { ruleScores: [], ruleValues: [], ignoredRules: [] } }; // Parse each phrase var errorFound = phrasesArray.some(function(phrase) { // Test if phrase is about global score var globalScore = extractGlobalScore(phrase); // or about a rule score var ruleScore = extractRuleScore(phrase); // or about "any rule" var anyRule = extractAnyRule(phrase); // about ignoring a rule score var ignoreRule = extractIgnoreRule(phrase); // about a rule value var ruleValue = extractRuleValue(phrase); if (globalScore !== null) { conditionsObject.atLeastOneUrl.globalScore = globalScore; } else if (anyRule !== null) { conditionsObject.atLeastOneUrl.anyRule = anyRule; } else if (ruleScore !== null) {
javascript
{ "resource": "" }
q5134
train
function(bucket, key, cb){ contract(arguments) .params('string', 'string|number', 'function') .end() ; var table = ''; if (bucket.indexOf('allows') != -1) { table = this.prefix + this.buckets.permissions; this.db .select('key', 'value') .from(table) .where({'key': bucket})
javascript
{ "resource": "" }
q5135
train
function(bucket, keys, cb){ contract(arguments) .params('string', 'array', 'function') .end() ; var table = ''; if (bucket.indexOf('allows') != -1) { table = this.prefix + this.buckets.permissions; this.db .select('key', 'value') .from(table) .where({'key': bucket}) .then(function(results) { if (results.length && results[0].value) { var keyArrays = []; _.each(keys, function(key) { keyArrays.push.apply(keyArrays, results[0].value[key]); }); cb(undefined, _.union(keyArrays)); } else { cb(undefined, []); } }) ; } else { table =
javascript
{ "resource": "" }
q5136
train
function(transaction, bucket, key, values){ contract(arguments) .params('array', 'string', 'string|number','string|array|number') .end() ; var self = this; var table = ''; values = Array.isArray(values) ? values : [values]; // we always want to have an array for values transaction.push(function(cb){ if (bucket.indexOf('allows') != -1) { table = self.prefix + self.buckets.permissions; self.db .select('key', 'value') .from(table) .where({'key': bucket}) .then(function(result) { var json = {}; if (result.length === 0) { // if no results found do a fresh insert json[key] = values; return self.db(table) .insert({key: bucket, value: json}) ; } else { // if we have found the key in the table then lets refresh the data if (_.has(result[0].value, key)) { result[0].value[key] = _.union(values, result[0].value[key]); } else { result[0].value[key] = values; } return self.db(table) .where('key', bucket) .update({key: bucket, value: result[0].value}) ;
javascript
{ "resource": "" }
q5137
train
function(transaction, bucket, key, values){ contract(arguments) .params('array', 'string', 'string|number','string|array') .end() ; var self = this; var table = ''; values = Array.isArray(values) ? values : [values]; // we always want to have an array for values transaction.push(function(cb){ if (bucket.indexOf('allows') != -1) { table = self.prefix + self.buckets.permissions; self.db .select('key', 'value') .from(table) .where({'key': bucket}) .then(function(result) { if(result.length === 0) {return;} // update the permissions for the role by removing what was requested _.each(values, function(value) { result[0].value[key] = _.without(result[0].value[key], value); }); // if no more permissions in the role then remove the role if (!result[0].value[key].length) { result[0].value = _.omit(result[0].value, key); } return self.db(table) .where('key', bucket) .update({value: result[0].value}) ; }) .then(function() { cb(undefined); }) ; } else {
javascript
{ "resource": "" }
q5138
findAll
train
function findAll (state, prefix, filter) { var options = { include_docs: true } if (prefix) { options.startkey = prefix options.endkey = prefix + '\uffff' } return state.db.allDocs(options) .then(function (res) { var objects = res.rows
javascript
{ "resource": "" }
q5139
getRefSchema
train
function getRefSchema (refVal, refType, parent, options, state) { const loader = getLoader(refType, options) if (refType && loader) { let newVal let oldBasePath let loaderValue let filePath let fullRefFilePath if (refType === 'file') { filePath = utils.getRefFilePath(refVal) fullRefFilePath = utils.isAbsolute(filePath) ? filePath : path.resolve(state.cwd, filePath) if (cache[fullRefFilePath]) { loaderValue = cache[fullRefFilePath] } } if (!loaderValue) { loaderValue = loader(refVal, options) if (loaderValue) { // adjust base folder if needed so that we can handle paths in nested folders if (refType === 'file') { let dirname = path.dirname(filePath) if (dirname === '.') { dirname = '' } if (dirname) { oldBasePath = state.cwd const newBasePath = path.resolve(state.cwd, dirname) options.baseFolder = state.cwd = newBasePath } } loaderValue =
javascript
{ "resource": "" }
q5140
addToHistory
train
function addToHistory (state, type, value) { let dest if (type === 'file') { dest = utils.getRefFilePath(value) } else { if (value === '#') {
javascript
{ "resource": "" }
q5141
setCurrent
train
function setCurrent (state, type, value) { let dest if (type ===
javascript
{ "resource": "" }
q5142
checkLocalCircular
train
function checkLocalCircular (schema) { const dag = new DAG() const locals = traverse(schema).reduce(function (acc, node) { if (!_.isNull(node) && !_.isUndefined(null) && typeof node.$ref === 'string') { const refType = utils.getRefType(node) if (refType === 'local') { const value = utils.getRefValue(node) if (value) { const path = this.path.join('/') acc.push({ from: path, to: value }) } } } return acc }, []) if (!locals || !locals.length) { return
javascript
{ "resource": "" }
q5143
MyLdapAuth
train
function MyLdapAuth(opts) { this.opts = opts; assert.ok(opts.url); assert.ok(opts.searchBase); assert.ok(opts.searchFilter); // optional
javascript
{ "resource": "" }
q5144
push
train
function push (state, docsOrIds) { var pushedObjects = [] var errors = state.db.constructor.Errors return Promise.resolve(state.remote) .then(function (remote) { return new Promise(function (resolve, reject) { if (Array.isArray(docsOrIds)) { docsOrIds = docsOrIds.map(toId) } else { docsOrIds = docsOrIds && [toId(docsOrIds)] } if (docsOrIds && docsOrIds.filter(Boolean).length !== docsOrIds.length) { return Promise.reject(errors.NOT_AN_OBJECT) } var replication = state.db.replicate.to(remote, { create_target: true, doc_ids: docsOrIds, include_docs: true }) /* istanbul ignore next */
javascript
{ "resource": "" }
q5145
withIdPrefix
train
function withIdPrefix (state, prefix) { var emitter = new EventEmitter() var api = { add: require('./add').bind(null, state, prefix), find: require('./find').bind(null, state, prefix), findAll: require('./find-all').bind(null, state, prefix), findOrAdd: require('./find-or-add').bind(null, state, prefix), update: require('./update').bind(null, state, prefix), updateOrAdd: require('./update-or-add').bind(null, state, prefix), updateAll: require('./update-all').bind(null, state, prefix), remove: require('./remove').bind(null, state, prefix), removeAll: require('./remove-all').bind(null, state, prefix), withIdPrefix: function (moarPrefix) {
javascript
{ "resource": "" }
q5146
getRefValue
train
function getRefValue (ref) { const thing = ref ? (ref.value ? ref.value : ref) : null if (thing &&
javascript
{ "resource": "" }
q5147
getRefPathValue
train
function getRefPathValue (schema, refPath) { let rpath = refPath const hashIndex = refPath.indexOf('#') if (hashIndex >= 0) { rpath = refPath.substring(hashIndex) if (rpath.length > 1) { rpath = refPath.substring(1) } else { rpath = '' } } // Walk through each /-separated path
javascript
{ "resource": "" }
q5148
pruneModules
train
function pruneModules(bundle, doneBundles, registry, generator) { const {groups} = generator.options; groups.forEach(group => { const bundles = group.map(bundleId => {
javascript
{ "resource": "" }
q5149
find
train
function find (state, prefix, objectsOrIds) { return Array.isArray(objectsOrIds)
javascript
{ "resource": "" }
q5150
getCredentials
train
function getCredentials(gruntOptions) { if (gruntOptions.authKey && grunt.file.exists('.ftpauth')) { return JSON.parse(grunt.file.read('.ftpauth'))[gruntOptions.authKey]; } else if (gruntOptions.username && gruntOptions.password) { return { username: gruntOptions.username, password: gruntOptions.password };
javascript
{ "resource": "" }
q5151
pushDirectories
train
function pushDirectories(directories, callback) { var index = 0; /** * Recursive helper used as callback for server.raw(mkd) * @param {error} err - Error message if something went wrong */ var processDir = function processDir (err) { // Fail if any error other then 550 is present, 550 is Directory Already Exists // these directories must exist to continue if (err) { if (err.code !== 550) { grunt.fail.warn(err); } } else { grunt.log.ok(messages.directoryCreated(directories[index])); } ++index; // If there is more directories to process then keep
javascript
{ "resource": "" }
q5152
uploadFiles
train
function uploadFiles(files) { var index = 0, file = files[index]; /** * Recursive helper used as callback for server.raw(put) * @param {error} err - Error message if something went wrong */ var processFile = function processFile (err) { if (err) { grunt.log.warn(messages.fileTransferFail(file.dest, err)); } else { grunt.log.ok(messages.fileTransferSuccess(file.dest)); } ++index; // If there are more files, then keep pushing if (index < files.length) { file = files[index]; server.put(grunt.file.read(file.src, { encoding: null }), file.dest, processFile); } else { // Close the
javascript
{ "resource": "" }
q5153
getLicenseFromUrl
train
function getLicenseFromUrl (url) { var regex = { opensource: /(http(s)?:\/\/)?(www.)?opensource.org\/licenses\/([A-Za-z0-9\-._]+)$/, spdx: /(http(s)?:\/\/)?(www.)?spdx.org\/licenses\/([A-Za-z0-9\-._]+)$/ } for (var re in regex) { var tokens = url.match(regex[re]) if (tokens) { var license = tokens[tokens.length - 1] // remove .html, .php, etc. from license name
javascript
{ "resource": "" }
q5154
prepareElmRelease
train
async function prepareElmRelease(config, context) { function exec(command) { context.logger.log(`Running:
javascript
{ "resource": "" }
q5155
update
train
function update (state, prefix, objectsOrIds, change) { if (typeof objectsOrIds !== 'object' && !change) { return Promise.reject( new Error('Must provide change') ) }
javascript
{ "resource": "" }
q5156
getColourAt
train
function getColourAt(gradient, p) { p = clamp(p, 0, 0.9999); // FIXME let r = Math.floor(p * (gradient.length - 1)); let q =
javascript
{ "resource": "" }
q5157
matchLicense
train
function matchLicense (licenseString) { // Find all textual matches on license text. var normalized = normalizeText(licenseString) var matchingLicenses = [] var license // Check matches of normalized license content against signatures. for (var i = 0; i < licenses.length; i++) { license = licenses[i] var match = false for (var j = 0; j < license.signatures.length; j++) { if (normalized.indexOf(license.signatures[j]) >= 0) { match = true break } } if (match) { matchingLicenses.push(license)
javascript
{ "resource": "" }
q5158
getJsonLicense
train
function getJsonLicense (json) { var license = 'nomatch' if (typeof json === 'string') { license = matchLicense(json) || 'nomatch' } else { if (json.url) {
javascript
{ "resource": "" }
q5159
off
train
function off (state, eventName, handler) { sta
javascript
{ "resource": "" }
q5160
calculateScaledFontSize
train
function calculateScaledFontSize(width, height) { return Math.round(Math.max(12,
javascript
{ "resource": "" }
q5161
updateOrAdd
train
function updateOrAdd (state, prefix, idOrObjectOrArray, newObject) { return Array.isArray(idOrObjectOrArray)
javascript
{ "resource": "" }
q5162
sendFrame
train
function sendFrame(socket, _frame) { var frame = _frame; if (!_frame.hasOwnProperty('toString')) { frame = new Frame({ 'command': _frame.command, 'headers': _frame.headers,
javascript
{ "resource": "" }
q5163
parseCommand
train
function parseCommand(data) { var command, str = data.toString('utf8', 0, data.length);
javascript
{ "resource": "" }
q5164
updateAll
train
function updateAll (state, prefix, changedProperties) { var type = typeof changedProperties var docs if (type !== 'object' && type !== 'function') { return Promise.reject(new Error('Must provide object or function')) } var options = { include_docs: true } if (prefix) { options.startkey = prefix options.endkey = prefix + '\uffff'
javascript
{ "resource": "" }
q5165
add
train
function add (state, prefix, properties) { return Array.isArray(properties)
javascript
{ "resource": "" }
q5166
removeAll
train
function removeAll (state, prefix, filter) { var docs var options = { include_docs: true } if (prefix) { options.startkey = prefix options.endkey = prefix + '\uffff' } return state.db.allDocs(options) .then(function (res) { docs = res.rows .filter(isntDesignDoc) .map(function (row) { return row.doc
javascript
{ "resource": "" }
q5167
visitBundle
train
function visitBundle(file) { if (visitedIndexes[file]) { return; } visitedIndexes[file] = true; // walk deps var bundle = manifest.bundles[manifest.indexes[file]]; bundle.data.forEach(function(module) { Object.keys(module.deps).forEach(function(key) {
javascript
{ "resource": "" }
q5168
ArrayField
train
function ArrayField (array, name, parent) { if (!(this instanceof ArrayField)) return new ArrayField(array, name, parent); debug('array <%s> being built', name); Entry.call(this, array, name, parent); this._context = parent._context; this._this = parent._this; this._currVal = {}; var data = this._content; this._config = { size: function () { return 1; } }; if (this._content.length > 0 && this._content[0] === '{{_$config}}') { data = this._content.slice(2); debug('array <%s> is configured with options <%s>', name, this._content[1]); var opts = _.defaults(this._content[1], DEFAULTS); if (Array.isArray(opts.size)) { this._config.size = function () { return _.random(opts.size[0], opts.size[1]); }; } else { this._config.size = function () { return Number(opts.size);
javascript
{ "resource": "" }
q5169
findOrAdd
train
function findOrAdd (state, prefix, idOrObjectOrArray, properties) { return Array.isArray(idOrObjectOrArray)
javascript
{ "resource": "" }
q5170
pull
train
function pull (state, docsOrIds) { var pulledObjects = [] var errors = state.db.constructor.Errors return Promise.resolve(state.remote) .then(function (remote) { return new Promise(function (resolve, reject) { if (Array.isArray(docsOrIds)) { docsOrIds = docsOrIds.map(toId) } else { docsOrIds = docsOrIds && [toId(docsOrIds)] } if (docsOrIds && docsOrIds.filter(Boolean).length !== docsOrIds.length) { return Promise.reject(errors.NOT_AN_OBJECT) } var replication = state.db.replicate.from(remote, { doc_ids: docsOrIds }) /* istanbul ignore next */ replication.catch(function () {
javascript
{ "resource": "" }
q5171
Schema
train
function Schema (sc, size) { if (!(this instanceof Schema)) return new Schema(sc); debug('======BUILDING PHASE======'); helpers.validate(sc); debug('schema size=%d being built', size); this._schema = this; this._document = helpers.build(sc, '$root', this);
javascript
{ "resource": "" }
q5172
reload
train
function reload(moduleName) { var id = require.resolve(moduleName); var mod = require.cache[id]; if (mod) { var base = path.dirname(mod.filename); // expunge each module cache entry beneath this folder var stack = [mod]; while (stack.length) { var mod = stack.pop(); if (beneathBase(mod.filename)) { delete require.cache[mod.id]; } stack.push.apply(stack, mod.children); } } // expunge each path cache entry beneath the folder for (var cacheKey in module.constructor._pathCache) {
javascript
{ "resource": "" }
q5173
extractConnectionInfo
train
function extractConnectionInfo(opts) { var params = {}; var defaultServer = opts.secureCommands ? { hostname: '127.0.0.1', port: 4445 } : { hostname: 'ondemand.saucelabs.com', port: 80 }; params.hostname = opts.hostname || defaultServer.hostname; params.port = opts.port || defaultServer.port; if (opts.key) {
javascript
{ "resource": "" }
q5174
initBrowser
train
function initBrowser(browserOpts, opts, mode, fileGroup, cb) { var funcName = opts.usePromises ? 'promiseChainRemote': 'remote'; var browser = wd[funcName](extractConnectionInfo(opts)); browser.browserTitle = browserOpts.browserTitle; browser.mode = mode; browser.mode = mode; if (opts.testName) { browserOpts.name = opts.testName; } if (opts.testTags) { browserOpts.tags = opts.testTags; } if (opts.build) { browserOpts.build = opts.build; } if (opts.identifier && opts.tunneled) { browserOpts['tunnel-identifier'] = opts.identifier; } browser.init(browserOpts, function (err) { if (err) { grunt.log.error(err);
javascript
{ "resource": "" }
q5175
getLargestCount
train
function getLargestCount(domain, type) { var retVal = 1; for (var i = 0; i < domain.length; i++)
javascript
{ "resource": "" }
q5176
mapValues
train
function mapValues (obj, fn) { return Object.keys(obj).reduce(function (res, key) { res[key] =
javascript
{ "resource": "" }
q5177
formatParameters
train
function formatParameters(params) { var sortedKeys = [], formattedParams = '' // sort the properties of the parameters sortedKeys = _.keys(params).sort() // create a string of key value pairs separated by '&' with '=' assignement for (i = 0; i < sortedKeys.length; i++) { if
javascript
{ "resource": "" }
q5178
Device
train
function Device(options) { EventEmitter.call(this); // Check required fields. if(!options || !options.id) { throw new Error('ID is required.'); } this.options = options; this.id = options.id; // Default the options and remove whitespace. options.id = (options.id || '').replace(/ /g, ''); options.key = (options.key || '').replace(/ /g, ''); options.secret = (options.secret || '').replace(/ /g, ''); // The MQTT topics that this device will use. this.commandTopic = util.format(config.topicFormatCommand, options.id); this.stateTopic = util.format(config.topicFormatState, options.id); this.mqtt = options.mqtt || new MQTT(); this.mqtt.on('message', this.handleMessage.bind(this)); // Only want 'connect' to be emitted the first time. Every time after // will only emit the reconnected event. var firstConnect = true; this.mqtt.on('connect', (function() { this.handleConnect(); if(firstConnect) { firstConnect = false;
javascript
{ "resource": "" }
q5179
setTemplateContext
train
function setTemplateContext(contextArray) { var newTemplateContext = {}; contextArray.forEach(function(item) { var cleanString = item.slice(options.contextBinderMark.length, -options.contextBinderMark.length), separatedPairs = cleanString.split(':');
javascript
{ "resource": "" }
q5180
getTemplateContext
train
function getTemplateContext(file) { var sourceFile = grunt.file.read(file), hasTemplateContext = checkTemplateContext(sourceFile), pattern = new RegExp('(' + options.contextBinderMark + ')(.*?)(' + options.contextBinderMark + ')', 'g'), contextArray;
javascript
{ "resource": "" }
q5181
getWorkingPath
train
function getWorkingPath(file) { var completePath = JSON.stringify(file).slice(2,-2).split('/'), lastPathElement = completePath.pop(),
javascript
{ "resource": "" }
q5182
getTemplate
train
function getTemplate(workingPath) { var templateFile = grunt.file.expand({}, workingPath + '/*.' +
javascript
{ "resource": "" }
q5183
DisplayProps
train
function DisplayProps(visible, alpha, shadow, compositeOperation, matrix) { this.setValues(visible, alpha, shadow, compositeOperation, matrix); // public properties: // assigned in the setValues method. /** * Property representing the alpha that will be applied to a display object. * @property alpha * @type Number **/ /** * Property representing the shadow that will be applied to a display object. * @property shadow * @type Shadow **/ /** * Property representing the compositeOperation that will be applied to a display object. * You can
javascript
{ "resource": "" }
q5184
Bitmap
train
function Bitmap(imageOrUri) { this.DisplayObject_constructor(); // public properties: /** * The image to render. This can be an Image, a Canvas, or a Video. Not all browsers (especially * mobile browsers) support drawing video to a canvas. * @property image * @type HTMLImageElement | HTMLCanvasElement | HTMLVideoElement **/ if (typeof imageOrUri == "string") { this.image = document.createElement("img"); this.image.src = imageOrUri; } else { this.image = imageOrUri;
javascript
{ "resource": "" }
q5185
train
function( target ) { $.extend( target, Audio.Busses ) $.extend( target, Audio.Oscillators ) $.extend( target, Audio.Synths ) $.extend( target, Audio.Percussion ) $.extend( target, Audio.Envelopes ) $.extend( target, Audio.FX ) $.extend( target, Audio.Seqs ) $.extend( target, Audio.Samplers ) var __clear__ = target.clear $.extend( target, Audio.PostProcessing ) target.clear = __clear__ $.extend( target, Audio.Vocoder ) target.Theory = Audio.Theory $.extend( target, Audio.Analysis ) // target.future = Gibber.Utilities.future // target.solo = Gibber.Utilities.solo target.Score = Audio.Score target.Clock = Audio.Clock target.Seq = Audio.Seqs.Seq target.Arp = Audio.Arp // move Arp to sequencers? target.ScaleSeq = Audio.Seqs.ScaleSeq target.SoundFont = Audio.SoundFont target.Speak = Audio.Speak target.Additive = Audio.Additive target.Ugen = Audio.Ugen target.Rndi = Audio.Core.Rndi
javascript
{ "resource": "" }
q5186
train
function(key, initValue, obj) { var isTimeProp = Audio.Clock.timeProperties.indexOf( key ) > -1, prop = obj.properties[ key ] = { value: isTimeProp ? Audio.Clock.time( initValue ) : initValue, binops: [], parent : obj, name : key, }, mappingName = key.charAt(0).toUpperCase() + key.slice(1); Object.defineProperty(obj, key, { configurable: true, get: function() { return prop.value }, set: function(val) { if( obj[ mappingName ] && obj[ mappingName ].mapping ) {
javascript
{ "resource": "" }
q5187
train
function(ugen) { ugen.mod = ugen.polyMod; ugen.removeMod = ugen.removePolyMod; for( var key in ugen.polyProperties ) { (function( _key ) { var value = ugen.polyProperties[ _key ], isTimeProp = Audio.Clock.timeProperties.indexOf( _key ) > -1
javascript
{ "resource": "" }
q5188
train
function( bus, position ) { if( typeof bus === 'undefined' ) bus = Audio.Master if( this.destinations.indexOf( bus ) === -1 ){ bus.addConnection( this, 1, position )
javascript
{ "resource": "" }
q5189
findTab
train
function findTab(patternlab, pattern) { //read the filetypes from the configuration const fileTypes = patternlab.config.plugins['plugin-node-tab'].options.tabsToAdd; //exit if either of these two parameters are missing if (!patternlab) { console.error('plugin-node-tab: patternlab object not provided to findTab'); process.exit(1); } if (!pattern) { console.error('plugin-node-tab: pattern object not provided to findTab'); process.exit(1); } //derive the custom filetype paths from the pattern relPath var customFileTypePath = path.join(patternlab.config.paths.source.patterns, pattern.relPath); //loop through all configured types for (let i = 0; i < fileTypes.length; i++) { const fileType = fileTypes[i].toLowerCase(); customFileTypePath = customFileTypePath.substr(0, customFileTypePath.lastIndexOf(".")) + '.' + fileType; var customFileTypeOutputPath = patternlab.config.paths.public.patterns + pattern.getPatternLink(patternlab, 'custom', '.' + fileType); //look for a custom filetype for this template try { var tabFileName = path.resolve(customFileTypePath); try { var tabFileNameStats = fs.statSync(tabFileName);
javascript
{ "resource": "" }
q5190
VideoLoader
train
function VideoLoader(loadItem, preferXHR) { this.AbstractMediaLoader_constructor(loadItem, preferXHR, createjs.AbstractLoader.VIDEO); if (createjs.RequestUtils.isVideoTag(loadItem) || createjs.RequestUtils.isVideoTag(loadItem.src)) {
javascript
{ "resource": "" }
q5191
powerSpectrum
train
function powerSpectrum(amplitudes) { var N = amplitudes.length; return
javascript
{ "resource": "" }
q5192
updateHeader
train
function updateHeader(fileInfo, data, type, headerLineRegex, options) { const contents = fs.readFileSync(fileInfo.path, 'utf8') || '' const body = contents.split('\n') // assumes all comments at top of template are the header block const preheader = [] while (body.length && !body[0].trim().match(headerLineRegex)) preheader.push(body.shift()) while (body.length && body[0].trim().match(headerLineRegex)) body.shift() const template = renderTemplate(data, type, options)
javascript
{ "resource": "" }
q5193
train
function(){ $('.entry-content').each(function(i){ var _i = i; $(this).find('img').each(function(){ var alt = this.alt; if (alt != ''){ $(this).after('<span class="caption">'+alt+'</span>'); }
javascript
{ "resource": "" }
q5194
init
train
function init(options) { //Prep and extend the options if (options && (options.allowPageScroll === undefined && (options.swipe !== undefined || options.swipeStatus !== undefined))) { options.allowPageScroll = NONE; } //Check for deprecated options //Ensure that any old click handlers are assigned to the new tap, unless we have a tap if(options.click!==undefined && options.tap===undefined) {
javascript
{ "resource": "" }
q5195
touchStart
train
function touchStart(jqEvent) { //If we already in a touch event (a finger already in use) then ignore subsequent ones.. if( getTouchInProgress() ) return; //Check if this element matches any in the excluded elements selectors, or its parent is excluded, if so, DON'T swipe if( $(jqEvent.target).closest( options.excludedElements, $element ).length>0 ) return; //As we use Jquery bind for events, we need to target the original event object //If these events are being programmatically triggered, we don't have an original event object, so use the Jq one. var event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent; var ret, touches = event.touches, evt = touches ? touches[0] : event; phase = PHASE_START; //If we support touches, get the finger count if (touches) { // get the total number of fingers touching the screen fingerCount = touches.length; } //Else this is the desktop, so stop the browser from dragging content else { jqEvent.preventDefault(); //call this on jq event so we are cross browser } //clear vars.. distance = 0; direction = null; pinchDirection=null; duration = 0; startTouchesDistance=0; endTouchesDistance=0; pinchZoom = 1; pinchDistance = 0; fingerData=createAllFingerData(); maximumsMap=createMaximumsData(); cancelMultiFingerRelease(); // check the number of fingers is what we are looking for, or we are capturing pinches if (!touches || (fingerCount === options.fingers || options.fingers === ALL_FINGERS) || hasPinches()) { // get the coordinates of the touch createFingerData( 0, evt ); startTime = getTimeStamp(); if(fingerCount==2) { //Keep track of the initial pinch distance, so we can calculate the diff
javascript
{ "resource": "" }
q5196
touchMove
train
function touchMove(jqEvent) { //As we use Jquery bind for events, we need to target the original event object //If these events are being programmatically triggered, we don't have an original event object, so use the Jq one. var event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent; //If we are ending, cancelling, or within the threshold of 2 fingers being released, don't track anything.. if (phase === PHASE_END || phase === PHASE_CANCEL || inMultiFingerRelease()) return; var ret, touches = event.touches, evt = touches ? touches[0] : event; //Update the finger data var currentFinger = updateFingerData(evt); endTime = getTimeStamp(); if (touches) { fingerCount = touches.length; } if (options.hold) clearTimeout(holdTimeout); phase = PHASE_MOVE; //If we have 2 fingers get Touches distance as well if(fingerCount==2) { //Keep track of the initial pinch distance, so we can calculate the diff later //We do this here as well as the start event, in case they start with 1 finger, and the press 2 fingers if(startTouchesDistance==0) { //Create second finger if this is the first time... createFingerData( 1, touches[1] ); startTouchesDistance = endTouchesDistance = calculateTouchesDistance(fingerData[0].start, fingerData[1].start); } else { //Else just update the second finger updateFingerData(touches[1]); endTouchesDistance = calculateTouchesDistance(fingerData[0].end, fingerData[1].end); pinchDirection = calculatePinchDirection(fingerData[0].end, fingerData[1].end); } pinchZoom = calculatePinchZoom(startTouchesDistance, endTouchesDistance); pinchDistance = Math.abs(startTouchesDistance - endTouchesDistance); } if ( (fingerCount === options.fingers || options.fingers === ALL_FINGERS) || !touches || hasPinches() ) { direction = calculateDirection(currentFinger.start, currentFinger.end); //Check if we need to prevent default event (page scroll / pinch zoom) or not validateDefaultEvent(jqEvent, direction); //Distance and duration are all off the main finger distance = calculateDistance(currentFinger.start, currentFinger.end);
javascript
{ "resource": "" }
q5197
touchEnd
train
function touchEnd(jqEvent) { //As we use Jquery bind for events, we need to target the original event object //If these events are being programmatically triggered, we don't have an original event object, so use the Jq one. var event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent, touches = event.touches; //If we are still in a touch with another finger return //This allows us to wait a fraction and see if the other finger comes up, if it does within the threshold, then we treat it as a multi release, not a single release. if (touches) { if(touches.length) { startMultiFingerRelease(); return true; } } //If a previous finger has been released, check how long ago, if within the threshold, then assume it was a multifinger release. //This is used to allow 2 fingers to release fractionally after each other, whilst maintainig the event as containg 2 fingers, not 1 if(inMultiFingerRelease()) { fingerCount=previousTouchFingerCount; } //Set end of swipe endTime = getTimeStamp(); //Get duration incase move was never fired duration = calculateDuration(); //If we trigger handlers at end of swipe OR, we trigger during, but they didnt trigger and we are still in the move phase if(didSwipeBackToCancel() || !validateSwipeDistance()) { phase = PHASE_CANCEL; triggerHandler(event, phase); } else if (options.triggerOnTouchEnd || (options.triggerOnTouchEnd == false && phase === PHASE_MOVE)) { //call
javascript
{ "resource": "" }
q5198
touchCancel
train
function touchCancel() { // reset the variables back to default values fingerCount = 0; endTime = 0; startTime = 0; startTouchesDistance=0; endTouchesDistance=0; pinchZoom=1; //If we were
javascript
{ "resource": "" }
q5199
touchLeave
train
function touchLeave(jqEvent) { var event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent; //If we have the trigger on leave property set....
javascript
{ "resource": "" }