_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q5100
|
ensureArray
|
train
|
function ensureArray(object, key) {
if (!object[key]) {
object[key] = [];
}
if (!Array.isArray(object[key])) {
throw new Error("Can't perform array operation on non-array field");
}
}
|
javascript
|
{
"resource": ""
}
|
q5101
|
registerHook
|
train
|
function registerHook(className, hookType, hookFn) {
if (!hooks[className]) {
hooks[className] = {};
}
hooks[className][hookType] = hookFn;
}
|
javascript
|
{
"resource": ""
}
|
q5102
|
getHook
|
train
|
function getHook(className, hookType) {
if (hooks[className] && hooks[className][hookType]) {
return hooks[className][hookType];
}
return undefined;
}
|
javascript
|
{
"resource": ""
}
|
q5103
|
extractOps
|
train
|
function extractOps(data) {
const ops = {};
_.forIn(data, (attribute, key) => {
if (isOp(attribute)) {
ops[key] = attribute;
delete data[key];
}
});
return ops;
}
|
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 {
throw new Error(`Unknown update operator: ${key}`);
}
if (MASKED_UPDATE_OPS.has(operator)) {
getMask(className).add(key);
}
});
}
|
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 object => _.reduce(where, (result, whereParams, key) => {
const match = evaluateObject(object, whereParams, key);
return result && match;
}, true);
}
|
javascript
|
{
"resource": ""
}
|
q5106
|
fetchObjectByPointer
|
train
|
function fetchObjectByPointer(pointer) {
const collection = getCollection(pointer.className);
const storedItem = collection[pointer.objectId];
if (storedItem === undefined) {
return undefined;
}
return Object.assign(
{ __type: 'Object', className: pointer.className },
_.cloneDeep(storedItem)
);
}
|
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;
});
} else {
if (object[path].__type === 'Pointer') {
object[path] = fetchObjectByPointer(target);
}
includePaths(object[path], pathsRemaining);
}
}
return object;
}
|
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];
});
const keys = orderArray.map(_.first);
const orders = orderArray.map(_.last);
return _.orderBy(matches, keys, orders);
}
|
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) => {
debugPrint('HOOK', { beforeSaveOverrideValue });
// Unlike BeforeDeleteResponse, BeforeSaveResponse might specify
let objectToProceedWith = model;
if (hookType === 'beforeSave' && beforeSaveOverrideValue) {
objectToProceedWith = beforeSaveOverrideValue.toJSON();
}
return Parse.Promise.as(objectToProceedWith);
});
}
return Parse.Promise.as(data);
}
|
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 pretty similar BUT filter is different");
return false;
}
}
if (secret) {
if (secret !== webhook.secret) {
fine("webhook look pretty similar BUT secret is different");
return false;
}
}
else {
if (webhook.secret) {
fine("webhook look pretty similar BUT secret is different");
return false;
}
}
return true;
}
|
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;
/**
* Any additional data.
*
* @type {*}
*/
this.data = data;
if (data) {
// Property of Error.
this.message = JSON.stringify(data);
}
}
|
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) {
var errorMsg =
'Cannot find feature: ' + util.inspect(featureDef.feature) +
' from featurePaths: ' + util.inspect(config.featurePaths);
throw new Error(errorMsg);
}
var featureTasks = _.get(feature, 'tasks', []);
return {
featureId: featureId,
featureDef: featureDef,
featureConstructor : feature,
tasks: featureTasks
};
});
}
|
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 Error('randomHexString size must be divisible by 2.');
}
return crypto.randomBytes(size / 2).toString('hex');
}
|
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',
queryStr: '%QUERY'
}
};
config.bloodhound = extend(true, {}, defaults.bloodhound, this.props.bloodhound);
config.typeahead = extend(true, {}, defaults.typeahead, this.props.typeahead);
config.datasource = extend(true, {}, defaults.datasource, this.props.datasource);
return config;
}
|
javascript
|
{
"resource": ""
}
|
|
q5115
|
train
|
function () {
var self = this,
options = this.initOptions();
var remoteCall = new Bloodhound(options.bloodhound);
options.datasource.source = remoteCall;
var typeaheadInput = React.findDOMNode(self);
if(typeaheadInput)
this.typeahead = $(typeaheadInput).typeahead(options.typeahead, options.datasource);
this.bindCustomEvents();
}
|
javascript
|
{
"resource": ""
}
|
|
q5116
|
readFileOrError
|
train
|
function readFileOrError(uri) {
var content;
try {
content = fs.readFileSync(uri, 'utf8');
} catch (err) {
return Result.Err(err);
}
return Result.Ok(content);
}
|
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]);
}
config.push({ port: port, host: host });
}
this._redisCluster = RedisCluster.create(config, { return_buffers: true });
} else {
this._redisClient = redis.createClient(this.options.redisPort, this.options.redisHost, { return_buffers: true });
this._redisClient.select(this.options.redisDb);
this._redisStream = RedisStream(this.options.redisPort, this.options.redisHost, this.options.redisDb);
}
this._k_Total = this._fmt(TOTAL);
this._k_TotalTerms = this._fmt(TOTAL, TERMS);
}
|
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;
var result = {};
result.key = key;
result.rawtf = keyFrequency;
result.df = keyDocFrequency;
result.n = docFrequency;
result.idf = idf;
result.tf = tf;
result.tfidf = tf * idf;
callback(null, result);
}
|
javascript
|
{
"resource": ""
}
|
|
q5119
|
onError
|
train
|
function onError(e) {
if (!inBrowser) {
return {};
}
let response = {};
if (e.response) {
response = e.response.data;
}
throw Object.assign({
statusCode: 500,
message: 'Request error'
}, response);
}
|
javascript
|
{
"resource": ""
}
|
q5120
|
train
|
function(config) {
var app = null;
try {
app = module.exports.createApp(config);
} catch (err) {
// wrap also synchronous error to promise to have consistent API for catching all errors
return Promise.reject(err);
}
return module.exports.startApp(app);
}
|
javascript
|
{
"resource": ""
}
|
|
q5121
|
train
|
function(app) {
var config = app.config;
var testing = config.profile === 'testing';
var starterPromise = startServer(app).then(logStartup);
if (!testing) {
starterPromise = starterPromise.catch(logError);
}
return 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];
});
const publicKey = secp256k1.recoverPubKey((new Buffer(keccak256(rlp.encode(raw)), 'hex')), { r, s }, v - 27);
return (new Buffer(publicKey.encode('hex', false), 'hex')).slice(1);
}
|
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) {
value = bnToBuffer(numberToBN(transaction[txKey]));
} else {
value = new Buffer(padToEven(stripHexPrefix(transaction[txKey])), 'hex');
}
}
// Fixed-width field
if (fieldInfo.length && value.length !== fieldInfo.length && value.length > 0) {
throw new Error(`[ethjs-signer] while signing raw transaction, invalid '${fieldInfo.name}', invalid length should be '${fieldInfo.length}' got '${value.length}'`);
}
// Variable-width (with a maximum)
if (fieldInfo.maxLength) {
value = stripZeros(value);
if (value.length > fieldInfo.maxLength) {
throw new Error(`[ethjs-signer] while signing raw transaction, invalid '${fieldInfo.name}' length, the max length is '${fieldInfo.maxLength}', got '${value.length}'`);
}
}
raw.push(value);
});
// private key is not stored in memory
const signature = secp256k1.keyFromPrivate(new Buffer(privateKey.slice(2), 'hex'))
.sign((new Buffer(keccak256(rlp.encode(raw)), 'hex')), { canonical: true });
raw.push(new Buffer([27 + signature.recoveryParam]));
raw.push(bnToBuffer(signature.r));
raw.push(bnToBuffer(signature.s));
return toObject ? raw : `0x${rlp.encode(raw).toString('hex')}`;
}
|
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;
}
//Insert each item individually so we get Mongoose validation etc.
items.forEach(function(item) {
var doc = new Model(item);
doc.save(function(err) {
if (err) return callback(err);
//Check if task queue is complete
tasks.done++;
if (tasks.done == tasks.total) callback();
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
q5125
|
loadObject
|
train
|
function loadObject(data, db, callback) {
callback = callback || function() {};
var iterator = function(modelName, next){
insertCollection(modelName, data[modelName], db, next);
};
async.forEachSeries(Object.keys(data), iterator, callback);
}
|
javascript
|
{
"resource": ""
}
|
q5126
|
loadFile
|
train
|
function loadFile(file, db, callback) {
callback = callback || function() {};
if (file.substr(0, 1) !== '/') {
var parentPath = module.parent.filename.split('/');
parentPath.pop();
file = parentPath.join('/') + '/' + file;
}
load(require(file), db, callback);
}
|
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 in directory
fs.readdir(dir, function(err, files){
if (err) return callback(err);
var iterator = function(file, next){
loadFile(dir + '/' + file, db, next);
};
async.forEach(files, iterator, callback);
});
}
|
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);
exec(`elm publish`);
return {
name: 'Elm release',
url:
'http://package.elm-lang.org/packages/cultureamp/elm-css-modules-loader/' +
elmPackageJson.version,
};
}
|
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 by the user
this._hidden = isHidden(name); // visibility in the output
this._prevVal = undefined;
this._currVal = undefined; // generated value in the current next() call
this._content = content; // the original content supplied by the user
this._context = null; // Context object used as compiled()'s argument
this._this = null; // 'this' object user has access to
}
|
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)))
.then(function (docs) {
return updateMany(state, docs, null, prefix)
})
}
return markAsDeleted(state, change, objectsOrIds)
.then(function (doc) {
return updateOne(state, doc, null, prefix)
})
}
|
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 this._content !== 'string') {
this._compiled = function () {
return this._content;
}.bind(this);
} else {
this._compiled = _.template(this._content);
}
}
|
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: {
globalScore: globalScoreSum / globalScoreCount
}
},
rules: {}
};
for (var ruleName in rulesScoresCount) {
var score = rulesScoresSum[ruleName] / rulesScoresCount[ruleName];
var value = rulesValuesSum[ruleName] / rulesValuesCount[ruleName];
averageObject.rules[ruleName] = {
score: score
};
if (!isNaN(value)) {
averageObject.rules[ruleName].value = value;
}
}
return averageObject;
}
|
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) {
conditionsObject.atLeastOneUrl.ruleScores.push(ruleScore);
} else if (ignoreRule !== null) {
conditionsObject.atLeastOneUrl.ignoredRules.push(ignoreRule);
} else if (ruleValue !== null) {
conditionsObject.atLeastOneUrl.ruleValues.push(ruleValue);
} else {
deferred.reject('Failed to parse this failCondition: ' + phrase);
return true;
}
});
if (!errorFound) {
deferred.resolve(conditionsObject);
}
return deferred.promise;
}
|
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})
.then(function(result) {
if (result.length) {
cb(undefined, (result[0].value[key] ? result[0].value[key] : []));
} else {
cb(undefined, []);
}
})
;
} else {
table = this.prefix + bucket;
this.db
.select('key', 'value')
.from(table)
.where({'key': key})
.then(function(result) {
cb(undefined, (result.length ? result[0].value : []));
})
;
}
}
|
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 = this.prefix + bucket;
this.db
.select('key', 'value')
.from(table)
.whereIn('key', keys)
.then(function(results) {
if (results.length) {
var keyArrays = [];
_.each(results, function(result) {
keyArrays.push.apply(keyArrays, result.value);
});
cb(undefined, _.union(keyArrays));
} else {
cb(undefined, []);
}
})
;
}
}
|
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})
;
}
})
.then(function() {
cb(undefined);
})
;
} else {
table = self.prefix + bucket;
self.db
.select('key', 'value')
.from(table)
.where({'key': key})
.then(function(result) {
if (result.length === 0) {
// if no results found do a fresh insert
return self.db(table)
.insert({key: key, value: values})
;
} else {
// if we have found the key in the table then lets refresh the data
return self.db(table)
.where('key', key)
.update({value: _.union(values, result[0].value)})
;
}
})
.then(function() {
cb(undefined);
})
;
}
});
}
|
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 {
table = self.prefix + bucket;
self.db
.select('key', 'value')
.from(table)
.where({'key': key})
.then(function(result) {
if(result.length === 0) {return;}
var resultValues = result[0].value;
// if we have found the key in the table then lets remove the values from it
_.each(values, function(value) {
resultValues = _.without(resultValues, value);
});
return self.db(table)
.where('key', key)
.update({value: resultValues})
;
})
.then(function() {
cb(undefined);
})
;
}
});
}
|
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
.filter(isntDesignDoc)
.map(function (row) {
return row.doc
})
return typeof filter === 'function'
? objects.filter(filter)
: objects
})
}
|
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 = derefSchema(loaderValue, options, state)
// reset
if (oldBasePath) {
options.baseFolder = state.cwd = oldBasePath
}
}
}
if (loaderValue) {
if (refType === 'file' && fullRefFilePath && !cache[fullRefFilePath]) {
cache[fullRefFilePath] = loaderValue
}
if (refVal.indexOf('#') >= 0) {
const refPaths = refVal.split('#')
const refPath = refPaths[1]
const refNewVal = utils.getRefPathValue(loaderValue, refPath)
if (refNewVal) {
newVal = refNewVal
}
} else {
newVal = loaderValue
}
}
return newVal
} else if (refType === 'local') {
return utils.getRefPathValue(parent, refVal)
}
}
|
javascript
|
{
"resource": ""
}
|
q5140
|
addToHistory
|
train
|
function addToHistory (state, type, value) {
let dest
if (type === 'file') {
dest = utils.getRefFilePath(value)
} else {
if (value === '#') {
return false
}
dest = state.current.concat(`:${value}`)
}
if (dest) {
dest = dest.toLowerCase()
if (state.history.indexOf(dest) >= 0) {
return false
}
state.history.push(dest)
}
return true
}
|
javascript
|
{
"resource": ""
}
|
q5141
|
setCurrent
|
train
|
function setCurrent (state, type, value) {
let dest
if (type === 'file') {
dest = utils.getRefFilePath(value)
}
if (dest) {
state.current = dest
}
}
|
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
}
if (_.some(locals, elem => elem.to === '#')) {
return new Error('Circular self reference')
}
const check = _.find(locals, elem => {
const fromEdge = elem.from.concat('/')
const dest = elem.to.substring(2).concat('/')
try {
dag.addEdge(fromEdge, dest)
} catch (e) {
return elem
}
if (fromEdge.indexOf(dest) === 0) {
return elem
}
})
if (check) {
return new Error(`Circular self reference from ${check.from} to ${check.to}`)
}
}
|
javascript
|
{
"resource": ""
}
|
q5143
|
MyLdapAuth
|
train
|
function MyLdapAuth(opts) {
this.opts = opts;
assert.ok(opts.url);
assert.ok(opts.searchBase);
assert.ok(opts.searchFilter);
// optional option: tls_ca
this.log = opts.log4js && opts.log4js.getLogger('ldapauth');
var clientOpts = {url: opts.url};
if (opts.log4js && opts.verbose) {
clientOpts.log4js = opts.log4js;
}
}
|
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 */
replication.catch(function () {
// handled trough 'error' event
})
replication.on('complete', function () {
resolve(pushedObjects)
})
replication.on('error', reject)
replication.on('change', function (change) {
pushedObjects = pushedObjects.concat(change.docs)
for (var i = 0; i < change.docs.length; i++) {
state.emitter.emit('push', change.docs[i])
}
})
})
})
}
|
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) {
return withIdPrefix(state, prefix + moarPrefix)
}
}
var prefixState = {
api: api,
isListening: false,
parentEmitter: state.emitter,
emitter: emitter
}
api.on = require('./on').bind(null, prefixState)
api.one = require('./one').bind(null, prefixState)
api.off = require('./off').bind(null, prefixState)
prefixEventHandler(prefix, prefixState)
return api
}
|
javascript
|
{
"resource": ""
}
|
q5146
|
getRefValue
|
train
|
function getRefValue (ref) {
const thing = ref ? (ref.value ? ref.value : ref) : null
if (thing && thing.$ref && typeof thing.$ref === 'string') {
return thing.$ref
}
}
|
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 component, and get
// the value for that key (ignoring empty keys)
const keys = rpath.split('/').filter(k => !!k)
return keys.reduce(function (value, key) {
return value[key]
}, schema)
}
|
javascript
|
{
"resource": ""
}
|
q5148
|
pruneModules
|
train
|
function pruneModules(bundle, doneBundles, registry, generator) {
const {groups} = generator.options;
groups.forEach(group => {
const bundles = group.map(bundleId => {
return doneBundles.find(b => b.id === bundleId);
}).filter(Boolean);
pruneGroup(bundles);
});
}
|
javascript
|
{
"resource": ""
}
|
q5149
|
find
|
train
|
function find (state, prefix, objectsOrIds) {
return Array.isArray(objectsOrIds)
? findMany(state, objectsOrIds, prefix)
: findOne(state, objectsOrIds, prefix)
}
|
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 };
} else {
// Warn the user we are attempting an anonymous login
grunt.log.warn(messages.anonymousLogin);
return { username: null, password: null };
}
}
|
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 going
if (index < directories.length) {
server.raw('mkd', directories[index], processDir);
} else {
callback();
}
};
// Start processing dirs or end if none are present
if (index < directories.length) {
server.raw('mkd', directories[index], processDir);
} else {
callback();
}
}
|
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 connection, we are complete
server.raw('quit', function(quitErr) {
if (quitErr) {
grunt.log.error(quitErr);
done(false);
}
server.destroy();
grunt.log.ok(messages.connectionClosed);
done();
});
}
};
// Start uploading files
server.put(grunt.file.read(file.src, { encoding: null }), file.dest, processFile);
}
|
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
var extensions = ['.html', '.php', '-license']
for (var i in extensions) {
if (license.slice(-extensions[i].length) === extensions[i]) {
license = license.slice(0, -extensions[i].length)
}
}
return license
}
}
return false
}
|
javascript
|
{
"resource": ""
}
|
q5154
|
prepareElmRelease
|
train
|
async function prepareElmRelease(config, context) {
function exec(command) {
context.logger.log(`Running: ${command}`);
execSync(command, { shell: '/bin/bash' });
}
exec(`yarn elm diff`);
exec(`yes | yarn elm bump`);
}
|
javascript
|
{
"resource": ""
}
|
q5155
|
update
|
train
|
function update (state, prefix, objectsOrIds, change) {
if (typeof objectsOrIds !== 'object' && !change) {
return Promise.reject(
new Error('Must provide change')
)
}
return Array.isArray(objectsOrIds)
? updateMany(state, objectsOrIds, change, prefix)
: updateOne(state, objectsOrIds, change, prefix)
}
|
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 = p * (gradient.length - 1) - r;
return Colour.mix(gradient[r + 1], gradient[r], 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)
}
}
// For single-line license, check if it's a known license id.
if (matchingLicenses.length === 0 && !/[\n\f\r]/.test(licenseString) && licenseString.length < 100) {
var licenseName = normalizeText(licenseString)
// If there's an extra "license" on the end of the name, drop it ("MIT License" -> "MIT").
license = licenseIndex[licenseName] || licenseIndex[licenseName.replace(/ licen[sc]e$/, '')]
if (!license) {
license = {name: licenseName, id: null}
}
matchingLicenses.push(license)
}
if (matchingLicenses.length === 0) {
return null
}
if (matchingLicenses.length > 1) {
console.warn('Multiple matching licenses: ' + matchingLicenses.length, [licenseString, matchingLicenses])
}
return matchingLicenses[0]
}
|
javascript
|
{
"resource": ""
}
|
q5158
|
getJsonLicense
|
train
|
function getJsonLicense (json) {
var license = 'nomatch'
if (typeof json === 'string') {
license = matchLicense(json) || 'nomatch'
} else {
if (json.url) {
license = { name: json.type, url: json.url }
} else {
license = matchLicense(json.type)
}
}
return license
}
|
javascript
|
{
"resource": ""
}
|
q5159
|
off
|
train
|
function off (state, eventName, handler) {
state.emitter.removeListener(eventName, handler)
return state.api
}
|
javascript
|
{
"resource": ""
}
|
q5160
|
calculateScaledFontSize
|
train
|
function calculateScaledFontSize(width, height) {
return Math.round(Math.max(12, Math.min(Math.min(width, height) * 0.75, (0.75 * Math.max(width, height)) / 12)));
}
|
javascript
|
{
"resource": ""
}
|
q5161
|
updateOrAdd
|
train
|
function updateOrAdd (state, prefix, idOrObjectOrArray, newObject) {
return Array.isArray(idOrObjectOrArray)
? updateOrAddMany(state, idOrObjectOrArray, prefix)
: updateOrAddOne(state, idOrObjectOrArray, newObject, prefix)
}
|
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,
'body': _frame.body
});
}
socket.send(frame.toStringOrBuffer());
return true;
}
|
javascript
|
{
"resource": ""
}
|
q5163
|
parseCommand
|
train
|
function parseCommand(data) {
var command,
str = data.toString('utf8', 0, data.length);
command = str.split('\n');
return command[0];
}
|
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'
}
return state.db.allDocs(options)
.then(function (res) {
docs = res.rows
.filter(isntDesignDoc)
.map(function (row) {
return row.doc
})
docs.forEach(addTimestamps)
if (type === 'function') {
docs.forEach(changedProperties)
return docs
}
return docs.map(function (doc) {
assign(doc, changedProperties, {_id: doc._id, _rev: doc._rev, hoodie: doc.hoodie})
return doc
})
})
.then(bulkDocs.bind(null, state))
}
|
javascript
|
{
"resource": ""
}
|
q5165
|
add
|
train
|
function add (state, prefix, properties) {
return Array.isArray(properties)
? addMany(state, properties, prefix)
: addOne(state, properties, prefix)
}
|
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
})
if (typeof filter === 'function') {
docs = docs.filter(filter)
}
return docs.map(function (doc) {
doc._deleted = true
return addTimestamps(doc)
})
})
.then(bulkDocs.bind(null, state))
}
|
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) {
var value = module.deps[key];
if (visitedIndexes.hasOwnProperty(value)) {
visitBundle(value);
}
});
});
}
|
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);
};
}
}
this._children = [];
data.forEach(function (child, index) {
this._children.push(helpers.build(child, index, this));
(function (method) {
var child = this._children[method];
Object.defineProperty(this._currVal, method, {
enumerable: true,
get: function () {
if (child._currVal === undefined)
return child.next();
return child._currVal; // doc and array's currval never empty
}
});
}).call(this, index);
}, this);
debug('array <%s> build complete', name);
}
|
javascript
|
{
"resource": ""
}
|
q5169
|
findOrAdd
|
train
|
function findOrAdd (state, prefix, idOrObjectOrArray, properties) {
return Array.isArray(idOrObjectOrArray)
? findOrAddMany(state, idOrObjectOrArray, prefix)
: findOrAddOne(state, idOrObjectOrArray, properties, prefix)
}
|
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 () {
// handled trough 'error' event
})
replication.on('complete', function () {
resolve(pulledObjects)
})
replication.on('error', reject)
replication.on('change', function (change) {
pulledObjects = pulledObjects.concat(change.docs)
for (var i = 0; i < change.docs.length; i++) {
state.emitter.emit('pull', change.docs[i])
}
})
})
})
}
|
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);
this._state = { // serve as global state
index: -1,
size: size,
counter: []
};
debug('======BUILDING ENDS======');
}
|
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) {
if (cacheKey.indexOf(moduleName) > 0 && beneathBase(cacheKey)) {
delete module.constructor._pathCache[cacheKey];
}
}
// re-require the module
return require(moduleName);
function beneathBase(file) {
return base === undefined
|| (file.length > base.length
&& file.substr(0, base.length + 1) === base + path.sep);
}
}
|
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) {
params.accessKey = opts.key;
}
['auth', 'username'].forEach(function(prop) {
if (opts[prop]) {
params[prop] = opts[prop];
}
});
return params;
}
|
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);
grunt.log.error('Could not initialize browser - ' + mode);
grunt.log.error('Make sure Sauce Labs supports the following browser/platform combo' +
' on ' + color('bright yellow', 'saucelabs.com/platforms') + ': ' + browserOpts.browserTitle);
return cb(false);
}
runTestsForBrowser(opts, fileGroup, browser, cb);
});
}
|
javascript
|
{
"resource": ""
}
|
q5175
|
getLargestCount
|
train
|
function getLargestCount(domain, type) {
var retVal = 1;
for (var i = 0; i < domain.length; i++) {
retVal = Math.max(retVal, type === 'cnv' ? domain[i].cnv : domain[i].count);
}
return retVal;
}
|
javascript
|
{
"resource": ""
}
|
q5176
|
mapValues
|
train
|
function mapValues (obj, fn) {
return Object.keys(obj).reduce(function (res, key) {
res[key] = fn(obj[key], key, obj)
return res
}, {})
}
|
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 (i !== 0) {
formattedParams += '&'
}
formattedParams += sortedKeys[i] + '=' + params[sortedKeys[i]]
}
return formattedParams
}
|
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;
this.emit('connect');
}
else {
this.emit('reconnected');
}
}).bind(this));
this.mqtt.on('reconnect', (function() {
this.emit('reconnect');
}).bind(this));
this.mqtt.on('close', (function() {
this.emit('close');
}).bind(this));
this.mqtt.on('offline', (function() {
this.emit('offline');
}).bind(this));
this.mqtt.on('error', (function(err) {
this.emit('error', err);
}).bind(this));
}
|
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(':');
newTemplateContext[separatedPairs[0]] = separatedPairs[1];
});
options.templateContext = newTemplateContext;
}
|
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;
if (!hasTemplateContext) {
return;
}
contextArray = sourceFile.match(pattern);
setTemplateContext(contextArray);
}
|
javascript
|
{
"resource": ""
}
|
q5181
|
getWorkingPath
|
train
|
function getWorkingPath(file) {
var completePath = JSON.stringify(file).slice(2,-2).split('/'),
lastPathElement = completePath.pop(),
fileDirectory = completePath.splice(lastPathElement).join('/');
return fileDirectory;
}
|
javascript
|
{
"resource": ""
}
|
q5182
|
getTemplate
|
train
|
function getTemplate(workingPath) {
var templateFile = grunt.file.expand({}, workingPath + '/*.' + options.autoTemplateFormat);
return templateFile[0];
}
|
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 find a list of valid composite operations at:
* <a href="https://developer.mozilla.org/en/Canvas_tutorial/Compositing">https://developer.mozilla.org/en/Canvas_tutorial/Compositing</a>
* @property compositeOperation
* @type String
**/
/**
* Property representing the value for visible that will be applied to a display object.
* @property visible
* @type Boolean
**/
/**
* The transformation matrix that will be applied to a display object.
* @property matrix
* @type Matrix2D
**/
}
|
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;
}
/**
* Specifies an area of the source image to draw. If omitted, the whole image will be drawn.
* Note that video sources must have a width / height set to work correctly with `sourceRect`.
* @property sourceRect
* @type Rectangle
* @default null
*/
this.sourceRect = null;
}
|
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
target.Rndf = Audio.Core.Rndf
target.rndi = Audio.Core.rndi
target.rndf = Audio.Core.rndf
target.Input = Audio.Input
target.Freesound = Audio.Freesound
target.Freesoundjs2 = Audio.Freesoundjs2
target.Scale = Audio.Theory.Scale
target.Ensemble = Audio.Ensemble
target.module = Gibber.import
// target.ms = Audio.Time.ms
// target.seconds = target.sec = Audio.Time.seconds
// target.minutes = target.min = Audio.Time.minutes
Audio.Core.Time.export( target )
Audio.Clock.export( target )
//target.sec = target.seconds
Audio.Core.Binops.export( target )
target.Master = Audio.Master
}
|
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 ) {
if( obj[ mappingName ].mapping.remove )
obj[ mappingName ].mapping.remove( true ) // pass true to avoid setting property inside of remove method
}
// if( isTimeProp ) {
// if( typeof val === 'object' && val.mode ==='absolute' ) { // ms, seconds
// prop.value = val.value
// }else{
// prop.value = Audio.Core.Binops.Mul( Audio.Clock.time( val ), Audio.Core.Binops.Div( 1, Audio.Clock.rate ) )
// }
// }else{
// prop.value = val
// }
//
prop.value = isTimeProp ? Audio.Clock.time( val ) : val
Audio.Core.dirty( obj )
return prop.value
},
});
obj[key] = prop.value
}
|
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
Object.defineProperty(ugen, _key, {
get : function() { return value; },
set : function( val ) {
for( var i = 0; i < ugen.children.length; i++ ) {
ugen.children[ i ][ _key ] = isTimeProp ? Audio.Clock.time( val ) : val;
}
},
});
})( key );
}
}
|
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 )
if( position !== 0 ) {
this.destinations.push( bus )
}
}
return this
}
|
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);
} catch (err) {
//not a file - move on quietly
}
if (tabFileNameStats && tabFileNameStats.isFile()) {
if (patternlab.config.debug) {
console.log('plugin-node-tab: copied pattern-specific custom file for ' + pattern.patternPartial);
}
//copy the file to our output target if found
fs.copySync(tabFileName, customFileTypeOutputPath);
} else {
//otherwise write nothing to the same location - this prevents GET errors on the tab.
fs.outputFileSync(customFileTypeOutputPath, '');
}
}
catch (err) {
console.log('plugin-node-tab:There was an error parsing sibling JSON for ' + pattern.relPath);
console.log(err);
}
}
}
|
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)) {
this.setTag(createjs.RequestUtils.isVideoTag(loadItem)?loadItem:loadItem.src);
// We can't use XHR for a tag that's passed in.
this._preferXHR = false;
} else {
this.setTag(this._createTag());
}
}
|
javascript
|
{
"resource": ""
}
|
q5191
|
powerSpectrum
|
train
|
function powerSpectrum(amplitudes) {
var N = amplitudes.length;
return amplitudes.map(function (a) {
return (a * a) / N;
});
}
|
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)
const header = []
for (let hline of template.split('\n')) {
if (!hline.trim().match(headerLineRegex)) break
else header.push(hline)
}
const newContents = preheader.concat(header).concat(body).join('\n')
fs.writeFileSync(fileInfo.path, newContents)
}
|
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>');
}
$(this).wrap('<a href="'+this.src+'" title="'+alt+'" class="fancybox" rel="gallery'+_i+'" />');
});
});
}
|
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) {
options.tap = options.click;
}
if (!options) {
options = {};
}
//pass empty object so we dont modify the defaults
options = $.extend({}, $.fn.swipe.defaults, options);
//For each element instantiate the plugin
return this.each(function () {
var $this = $(this);
//Check we havent already initialised the plugin
var plugin = $this.data(PLUGIN_NS);
if (!plugin) {
plugin = new TouchSwipe(this, options);
$this.data(PLUGIN_NS, plugin);
}
});
}
|
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 later
//Store second finger data as start
createFingerData( 1, touches[1] );
startTouchesDistance = endTouchesDistance = calculateTouchesDistance(fingerData[0].start, fingerData[1].start);
}
if (options.swipeStatus || options.pinchStatus) {
ret = triggerHandler(event, phase);
}
}
else {
//A touch with more or less than the fingers we are looking for, so cancel
ret = false;
}
//If we have a return value from the users handler, then return and cancel
if (ret === false) {
phase = PHASE_CANCEL;
triggerHandler(event, phase);
return ret;
}
else {
if (options.hold) {
holdTimeout = setTimeout($.proxy(function() {
//Trigger the event
$element.trigger('hold', [event.target]);
//Fire the callback
if(options.hold) {
ret = options.hold.call($element, event, event.target);
}
}, this), options.longTapThreshold );
}
setTouchInProgress(true);
}
return null;
}
|
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);
duration = calculateDuration();
//Cache the maximum distance we made in this direction
setMaxDistance(direction, distance);
if (options.swipeStatus || options.pinchStatus) {
ret = triggerHandler(event, phase);
}
//If we trigger end events when threshold are met, or trigger events when touch leaves element
if(!options.triggerOnTouchEnd || options.triggerOnTouchLeave) {
var inBounds = true;
//If checking if we leave the element, run the bounds check (we can use touchleave as its not supported on webkit)
if(options.triggerOnTouchLeave) {
var bounds = getbounds( this );
inBounds = isInBounds( currentFinger.end, bounds );
}
//Trigger end handles as we swipe if thresholds met or if we have left the element if the user has asked to check these..
if(!options.triggerOnTouchEnd && inBounds) {
phase = getNextPhase( PHASE_MOVE );
}
//We end if out of bounds here, so set current phase to END, and check if its modified
else if(options.triggerOnTouchLeave && !inBounds ) {
phase = getNextPhase( PHASE_END );
}
if(phase==PHASE_CANCEL || phase==PHASE_END) {
triggerHandler(event, phase);
}
}
}
else {
phase = PHASE_CANCEL;
triggerHandler(event, phase);
}
if (ret === false) {
phase = PHASE_CANCEL;
triggerHandler(event, phase);
}
}
|
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 this on jq event so we are cross browser
jqEvent.preventDefault();
phase = PHASE_END;
triggerHandler(event, phase);
}
//Special cases - A tap should always fire on touch end regardless,
//So here we manually trigger the tap end handler by itself
//We dont run trigger handler as it will re-trigger events that may have fired already
else if (!options.triggerOnTouchEnd && hasTap()) {
//Trigger the pinch events...
phase = PHASE_END;
triggerHandlerForGesture(event, phase, TAP);
}
else if (phase === PHASE_MOVE) {
phase = PHASE_CANCEL;
triggerHandler(event, phase);
}
setTouchInProgress(false);
return null;
}
|
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 in progress of tracking a possible multi touch end, then re set it.
cancelMultiFingerRelease();
setTouchInProgress(false);
}
|
javascript
|
{
"resource": ""
}
|
q5199
|
touchLeave
|
train
|
function touchLeave(jqEvent) {
var event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent;
//If we have the trigger on leave property set....
if(options.triggerOnTouchLeave) {
phase = getNextPhase( PHASE_END );
triggerHandler(event, phase);
}
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.