_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q50600 | train | function(fun) {
var funLength = fun.length;
if (funLength < 1) {
return fun;
}
else if (funLength === 1) {
return function () {
return fun.call(this, __slice.call(arguments, 0));
};
}
else {
return function () {
var numberOfArgs = arguments.length,
namedArgs = __slice.call(arguments, 0, funLength - 1),
numberOfMissingNamedArgs = Math.max(funLength - numberOfArgs - 1, 0),
argPadding = new Array(numberOfMissingNamedArgs),
variadicArgs = __slice.call(arguments, fun.length - 1);
return fun.apply(this, namedArgs.concat(argPadding).concat([variadicArgs]));
};
}
} | javascript | {
"resource": ""
} | |
q50601 | train | function(/* funs */) {
var funs = arguments;
return function(/* args */) {
var args = arguments;
return _.map(funs, function(f) {
return f.apply(this, args);
}, this);
};
} | javascript | {
"resource": ""
} | |
q50602 | train | function(fun /*, defaults */) {
var defaults = _.rest(arguments);
return function(/*args*/) {
var args = _.toArray(arguments);
var sz = _.size(defaults);
for(var i = 0; i < sz; i++) {
if (!existy(args[i]))
args[i] = defaults[i];
}
return fun.apply(this, args);
};
} | javascript | {
"resource": ""
} | |
q50603 | train | function(fun) {
return function(/* args */) {
var flipped = __slice.call(arguments);
flipped[0] = arguments[1];
flipped[1] = arguments[0];
return fun.apply(this, flipped);
};
} | javascript | {
"resource": ""
} | |
q50604 | train | function(object, method) {
if (object == null) return void 0;
var func = object[method];
var args = slice.call(arguments, 2);
return _.isFunction(func) ? func.apply(object, args) : void 0;
} | javascript | {
"resource": ""
} | |
q50605 | unfoldWithReturn | train | function unfoldWithReturn (seed, unaryFn) {
var state = seed,
pair,
value;
return function () {
if (state != null) {
pair = unaryFn.call(state, state);
value = pair[1];
state = value != null ? pair[0] : void 0;
return value;
}
else return void 0;
};
} | javascript | {
"resource": ""
} |
q50606 | train | function() {
var count = _.size(arguments);
if (count === 1) return true;
if (count === 2) return arguments[0] < arguments[1];
for (var i = 1; i < count; i++) {
if (arguments[i-1] >= arguments[i]) {
return false;
}
}
return true;
} | javascript | {
"resource": ""
} | |
q50607 | train | function(obj, kobj) {
return _.reduce(kobj, function(o, nu, old) {
if (existy(obj[old])) {
o[nu] = obj[old];
return o;
}
else
return o;
},
_.omit.apply(null, concat.call([obj], _.keys(kobj))));
} | javascript | {
"resource": ""
} | |
q50608 | train | function(obj, fun, ks, defaultValue) {
if (!isAssociative(obj)) throw new TypeError("Attempted to update a non-associative object.");
if (!existy(ks)) return fun(obj);
var deepness = _.isArray(ks);
var keys = deepness ? ks : [ks];
var ret = deepness ? _.snapshot(obj) : _.clone(obj);
var lastKey = _.last(keys);
var target = ret;
_.each(_.initial(keys), function(key) {
if (defaultValue && !_.has(target, key)) {
target[key] = _.clone(defaultValue);
}
target = target[key];
});
target[lastKey] = fun(target[lastKey]);
return ret;
} | javascript | {
"resource": ""
} | |
q50609 | train | function(obj, value, ks, defaultValue) {
if (!existy(ks)) throw new TypeError("Attempted to set a property at a null path.");
return _.updatePath(obj, function() { return value; }, ks, defaultValue);
} | javascript | {
"resource": ""
} | |
q50610 | train | function (obj, ks) {
return _.pick.apply(null, concat.call([obj], ks));
} | javascript | {
"resource": ""
} | |
q50611 | train | function(str) {
var parameters = str.split('&'),
obj = {},
parameter,
key,
match,
lastKey,
subKey,
depth;
// Iterate over key/value pairs
_.each(parameters, function(parameter) {
parameter = parameter.split('=');
key = urlDecode(parameter[0]);
lastKey = key;
depth = obj;
// Reset so we don't have issues when matching the same string
bracketRegex.lastIndex = 0;
// Attempt to extract nested values
while ((match = bracketRegex.exec(key)) !== null) {
if (!_.isUndefined(match[1])) {
// If we're at the top nested level, no new object needed
subKey = match[1];
} else {
// If we're at a lower nested level, we need to step down, and make
// sure that there is an object to place the value into
subKey = match[2];
depth[lastKey] = depth[lastKey] || (subKey ? {} : []);
depth = depth[lastKey];
}
// Save the correct key as a hash or an array
lastKey = subKey || _.size(depth);
}
// Assign value to nested object
depth[lastKey] = urlDecode(parameter[1]);
});
return obj;
} | javascript | {
"resource": ""
} | |
q50612 | variaderize | train | function variaderize(func) {
return function (args) {
var allArgs = isArrayLike(args) ? args : arguments;
return func(allArgs);
};
} | javascript | {
"resource": ""
} |
q50613 | train | function(options) {
this.ble = noble;
var membership = (typeof options === 'string' ? options : undefined);
options = options || {};
this.targets = membership || options.membership;
this.peripherals = [];
this.members = [];
this.timeout = (options.timeout || 30) * 1000; // in seconds
//define membership
if (this.targets && !util.isArray(this.targets)) {
this.targets = this.targets.split(',');
} else {
this.targets = [];
}
this.logger = options.logger || debug; //use debug instead of console.log
this.discovering = false;
this.active = false;
// handle disconnect gracefully
this.ble.on('warning', function(message) {
this.onDisconnect();
}.bind(this));
return this;
} | javascript | {
"resource": ""
} | |
q50614 | train | function(options) {
EventEmitter.call(this);
var uuid = (typeof options === 'string' ? options : undefined);
options = options || {};
this.uuid = null;
this.targets = uuid || options.uuid;
if (this.targets && !util.isArray(this.targets)) {
this.targets = this.targets.split(',');
}
this.logger = options.logger || debug; //use debug instead of console.log
this.forceConnect = options.forceConnect || false;
this.connected = false;
this.discovered = false;
this.ble = noble;
this.peripheral = null;
this.takenOff = false;
this.driveStepsRemaining = 0;
this.speeds = {
yaw: 0, // turn
pitch: 0, // forward/backward
roll: 0, // left/right
altitude: 0 // up/down
};
/**
* Used to store the 'counter' that's sent to each characteristic
*/
this.steps = {
'fa0a': 0,
'fa0b': 0,
'fa0c': 0
};
this.status = {
stateValue: 0,
flying: false,
battery: 100
};
// handle disconnect gracefully
this.ble.on('warning', function(message) {
this.onDisconnect();
}.bind(this));
} | javascript | {
"resource": ""
} | |
q50615 | takeOff | train | function takeOff(options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
this.logger('RollingSpider#takeOff');
if (this.status.battery < 10) {
this.logger('!!! BATTERY LEVEL TOO LOW !!!');
}
if (!this.status.flying) {
this.writeTo(
'fa0b',
new Buffer([0x02, ++this.steps.fa0b & 0xFF, 0x02, 0x00, 0x01, 0x00])
);
this.status.flying = true;
}
this.on('flyingStatusChange', function(newStatus) {
if (newStatus === 2) {
if (typeof callback === 'function') {
callback();
}
}
});
} | javascript | {
"resource": ""
} |
q50616 | wheelOn | train | function wheelOn(options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
this.logger('RollingSpider#wheelOn');
this.writeTo(
'fa0b',
new Buffer([0x02, ++this.steps.fa0b & 0xFF, 0x02, 0x01, 0x02, 0x00, 0x01])
);
if (callback) {
callback();
}
} | javascript | {
"resource": ""
} |
q50617 | wheelOff | train | function wheelOff(options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
this.logger('RollingSpider#wheelOff');
this.writeTo(
'fa0b',
new Buffer([0x02, ++this.steps.fa0b & 0xFF, 0x02, 0x01, 0x02, 0x00, 0x00])
);
if (callback) {
callback();
}
} | javascript | {
"resource": ""
} |
q50618 | land | train | function land(options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
this.logger('RollingSpider#land');
if (this.status.flying) {
this.writeTo(
'fa0b',
new Buffer([0x02, ++this.steps.fa0b & 0xFF, 0x02, 0x00, 0x03, 0x00])
);
this.on('flyingStatusChange', function(newStatus) {
if (newStatus === 0) {
this.status.flying = false;
if (typeof callback === 'function') {
callback();
}
}
});
} else {
this.logger('Calling RollingSpider#land when it\'s not in the air isn\'t going to do anything');
if (callback) {
callback();
}
}
} | javascript | {
"resource": ""
} |
q50619 | cutOff | train | function cutOff(options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
this.logger('RollingSpider#cutOff');
this.status.flying = false;
this.writeTo(
'fa0c',
new Buffer([0x02, ++this.steps.fa0c & 0xFF, 0x02, 0x00, 0x04, 0x00])
, callback);
} | javascript | {
"resource": ""
} |
q50620 | flatTrim | train | function flatTrim(options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
this.logger('RollingSpider#flatTrim');
this.writeTo(
'fa0b',
new Buffer([0x02, ++this.steps.fa0b & 0xFF, 0x02, 0x00, 0x00, 0x00]),
callback
);
} | javascript | {
"resource": ""
} |
q50621 | frontFlip | train | function frontFlip(options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
this.logger('RollingSpider#frontFlip');
if (this.status.flying) {
this.writeTo(
'fa0b',
new Buffer([0x02, ++this.steps.fa0b & 0xFF, 0x02, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]),
callback
);
} else {
this.logger('Calling RollingSpider#frontFlip when it\'s not in the air isn\'t going to do anything');
if (typeof callback === 'function') {
callback();
}
}
if (callback) {
callback();
}
} | javascript | {
"resource": ""
} |
q50622 | mergeMessages | train | function mergeMessages(data) {
lastSync = (new Date()).getTime();
if (messages.length == 0) {
messages = data;
} else {
var i = data.length - 1;
var j = messages.length - 1;
while (i >= 0 && j >= 0) {
if (data[i].timestamp < messages[j].timestamp) {
j--;
} else {
messages.splice(j + 1, 0, data[i--]);
}
}
}
} | javascript | {
"resource": ""
} |
q50623 | sendCumulativeMessages | train | function sendCumulativeMessages(timestamp, clientSync, res) {
if (timestamp == null) timestamp = 0;
if (clientSync == null) clientSync = 0;
var data = getCumulativeMessages(timestamp, clientSync);
res.send(data);
} | javascript | {
"resource": ""
} |
q50624 | getCumulativeMessages | train | function getCumulativeMessages(timestamp, clientSync) {
var msgs = [];
if (lastSync > clientSync) {
msgs = messages;
} else {
var newMsgs = messages.length;
while (newMsgs > 0 && messages[newMsgs - 1].timestamp > timestamp) {
newMsgs--;
}
for (var i = newMsgs; i < messages.length; i++) {
msgs.push(messages[i]);
}
}
var data = {};
data.msgs = msgs;
data.lastSync = lastSync;
return data;
} | javascript | {
"resource": ""
} |
q50625 | synchronize | train | function synchronize() {
if (syncPointer != -1) {
log.logMessage("verbose", "redis synchronization!");
var syncMessage = {};
syncMessage.data = messages.splice(syncPointer, messages.length - syncPointer);
setTimeout(function () {
pub.publish("message", JSON.stringify(syncMessage));
}, 200);
syncPointer = -1;
}
} | javascript | {
"resource": ""
} |
q50626 | _xdr | train | function _xdr(url) {
return new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.open('get', url);
req.onerror = reject;
req.onreadystatechange = function onreadystatechange() {
if (req.readyState === 4) {
if ((req.status >= 200 && req.status < 300) ||
(url.substr(0, 7) === 'file://' && req.responseText)) {
resolve(req.responseText);
} else {
reject(new Error('HTTP status: ' + req.status + ' retrieving ' + url));
}
}
};
req.send();
});
} | javascript | {
"resource": ""
} |
q50627 | cleanDeep | train | function cleanDeep(object) {
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
_ref$emptyArrays = _ref.emptyArrays,
emptyArrays = _ref$emptyArrays === undefined ? true : _ref$emptyArrays,
_ref$emptyObjects = _ref.emptyObjects,
emptyObjects = _ref$emptyObjects === undefined ? true : _ref$emptyObjects,
_ref$emptyStrings = _ref.emptyStrings,
emptyStrings = _ref$emptyStrings === undefined ? true : _ref$emptyStrings,
_ref$nullValues = _ref.nullValues,
nullValues = _ref$nullValues === undefined ? true : _ref$nullValues,
_ref$undefinedValues = _ref.undefinedValues,
undefinedValues = _ref$undefinedValues === undefined ? true : _ref$undefinedValues;
return (0, _lodash6.default)(object, function (result, value, key) {
// Recurse into arrays and objects.
if (Array.isArray(value) || (0, _lodash4.default)(value)) {
value = cleanDeep(value, { emptyArrays: emptyArrays, emptyObjects: emptyObjects, emptyStrings: emptyStrings, nullValues: nullValues, undefinedValues: undefinedValues });
}
// Exclude empty objects.
if (emptyObjects && (0, _lodash4.default)(value) && (0, _lodash2.default)(value)) {
return;
}
// Exclude empty arrays.
if (emptyArrays && Array.isArray(value) && !value.length) {
return;
}
// Exclude empty strings.
if (emptyStrings && value === '') {
return;
}
// Exclude null values.
if (nullValues && value === null) {
return;
}
// Exclude undefined values.
if (undefinedValues && value === undefined) {
return;
}
// Append when recursing arrays.
if (Array.isArray(result)) {
return result.push(value);
}
result[key] = value;
});
} | javascript | {
"resource": ""
} |
q50628 | incrementCounter | train | function incrementCounter() {
for (var i = innerLen-1; i >= innerLen-4; i--) {
inner[i]++;
if (inner[i] <= 0xff) return;
inner[i] = 0;
}
} | javascript | {
"resource": ""
} |
q50629 | blockxor | train | function blockxor(S, Si, D, len) {
for (var i = 0; i < len; i++) {
D[i] ^= S[Si + i]
}
} | javascript | {
"resource": ""
} |
q50630 | train | function() {
if (stop) {
return callback(new Error('cancelled'), currentOp / totalOps);
}
switch (state) {
case 0:
// for (var i = 0; i < p; i++)...
Bi = i0 * 32 * r;
arraycopy(B, Bi, XY, 0, Yi); // ROMix - 1
state = 1; // Move to ROMix 2
i1 = 0;
// Fall through
case 1:
// Run up to 1000 steps of the first inner smix loop
var steps = N - i1;
if (steps > limit) { steps = limit; }
for (var i = 0; i < steps; i++) { // ROMix - 2
arraycopy(XY, 0, V, (i1 + i) * Yi, Yi) // ROMix - 3
blockmix_salsa8(XY, Yi, r, x, _X); // ROMix - 4
}
// for (var i = 0; i < N; i++)
i1 += steps;
currentOp += steps;
// Call the callback with the progress (optionally stopping us)
var percent10 = parseInt(1000 * currentOp / totalOps);
if (percent10 !== lastPercent10) {
stop = callback(null, currentOp / totalOps);
if (stop) { break; }
lastPercent10 = percent10;
}
if (i1 < N) {
break;
}
i1 = 0; // Move to ROMix 6
state = 2;
// Fall through
case 2:
// Run up to 1000 steps of the second inner smix loop
var steps = N - i1;
if (steps > limit) { steps = limit; }
for (var i = 0; i < steps; i++) { // ROMix - 6
var offset = (2 * r - 1) * 16; // ROMix - 7
var j = XY[offset] & (N - 1);
blockxor(V, j * Yi, XY, Yi); // ROMix - 8 (inner)
blockmix_salsa8(XY, Yi, r, x, _X); // ROMix - 9 (outer)
}
// for (var i = 0; i < N; i++)...
i1 += steps;
currentOp += steps;
// Call the callback with the progress (optionally stopping us)
var percent10 = parseInt(1000 * currentOp / totalOps);
if (percent10 !== lastPercent10) {
stop = callback(null, currentOp / totalOps);
if (stop) { break; }
lastPercent10 = percent10;
}
if (i1 < N) {
break;
}
arraycopy(XY, 0, B, Bi, Yi); // ROMix - 10
// for (var i = 0; i < p; i++)...
i0++;
if (i0 < p) {
state = 0;
break;
}
b = [];
for (var i = 0; i < B.length; i++) {
b.push((B[i] >> 0) & 0xff);
b.push((B[i] >> 8) & 0xff);
b.push((B[i] >> 16) & 0xff);
b.push((B[i] >> 24) & 0xff);
}
var derivedKey = PBKDF2_HMAC_SHA256_OneIter(password, b, dkLen);
// Done; don't break (which would reschedule)
return callback(null, 1.0, derivedKey);
}
// Schedule the next steps
nextTick(incrementalSMix);
} | javascript | {
"resource": ""
} | |
q50631 | compressible | train | function compressible (type) {
if (!type || typeof type !== 'string') {
return false
}
// strip parameters
var match = EXTRACT_TYPE_REGEXP.exec(type)
var mime = match && match[1].toLowerCase()
var data = db[mime]
// return database information
if (data && data.compressible !== undefined) {
return data.compressible
}
// fallback to regexp or unknown
return COMPRESSIBLE_TYPE_REGEXP.test(mime) || undefined
} | javascript | {
"resource": ""
} |
q50632 | train | function(dream) {
const newListItem = document.createElement('li');
newListItem.innerHTML = dream;
dreamsList.appendChild(newListItem);
} | javascript | {
"resource": ""
} | |
q50633 | onDragOver | train | function onDragOver() {
mainContainer.style.border = '7px solid #98a90f';
mainContainer.style.background = '#ffff13';
mainContainer.style.borderRadisu = '16px';
} | javascript | {
"resource": ""
} |
q50634 | first | train | function first (stuff, done) {
if (!Array.isArray(stuff)) {
throw new TypeError('arg must be an array of [ee, events...] arrays')
}
var cleanups = []
for (var i = 0; i < stuff.length; i++) {
var arr = stuff[i]
if (!Array.isArray(arr) || arr.length < 2) {
throw new TypeError('each array member must be [ee, events...]')
}
var ee = arr[0]
for (var j = 1; j < arr.length; j++) {
var event = arr[j]
var fn = listener(event, callback)
// listen to the event
ee.on(event, fn)
// push this listener to the list of cleanups
cleanups.push({
ee: ee,
event: event,
fn: fn
})
}
}
function callback () {
cleanup()
done.apply(null, arguments)
}
function cleanup () {
var x
for (var i = 0; i < cleanups.length; i++) {
x = cleanups[i]
x.ee.removeListener(x.event, x.fn)
}
}
function thunk (fn) {
done = fn
}
thunk.cancel = cleanup
return thunk
} | javascript | {
"resource": ""
} |
q50635 | listener | train | function listener (event, done) {
return function onevent (arg1) {
var args = new Array(arguments.length)
var ee = this
var err = event === 'error'
? arg1
: null
// copy args to prevent arguments escaping scope
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i]
}
done(err, ee, event, args)
}
} | javascript | {
"resource": ""
} |
q50636 | encodeAddressName | train | function encodeAddressName(name) {
if (!/^[\w ']*$/.test(name)) {
if (/^[\x20-\x7e]*$/.test(name)) {
return '"' + name.replace(/([\\"])/g, '\\$1') + '"';
} else {
return (0, _emailjsMimeCodec.mimeWordEncode)(name, 'Q');
}
}
return name;
} | javascript | {
"resource": ""
} |
q50637 | convertAddresses | train | function convertAddresses() {
var addresses = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var uniqueList = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var values = [];[].concat(addresses).forEach(function (address) {
if (address.address) {
address.address = address.address.replace(/^.*?(?=@)/, function (user) {
return (0, _emailjsMimeCodec.mimeWordsEncode)(user, 'Q');
}).replace(/@.+$/, function (domain) {
return '@' + (0, _punycode.toASCII)(domain.substr(1));
});
if (!address.name) {
values.push(address.address);
} else if (address.name) {
values.push(encodeAddressName(address.name) + ' <' + address.address + '>');
}
if (uniqueList.indexOf(address.address) < 0) {
uniqueList.push(address.address);
}
} else if (address.group) {
values.push(encodeAddressName(address.name) + ':' + (address.group.length ? convertAddresses(address.group, uniqueList) : '').trim() + ';');
}
});
return values.join(', ');
} | javascript | {
"resource": ""
} |
q50638 | encodeHeaderValue | train | function encodeHeaderValue(key) {
var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
key = normalizeHeaderKey(key);
switch (key) {
case 'From':
case 'Sender':
case 'To':
case 'Cc':
case 'Bcc':
case 'Reply-To':
return convertAddresses(parseAddresses(value));
case 'Message-Id':
case 'In-Reply-To':
case 'Content-Id':
value = value.replace(/\r?\n|\r/g, ' ');
if (value.charAt(0) !== '<') {
value = '<' + value;
}
if (value.charAt(value.length - 1) !== '>') {
value = value + '>';
}
return value;
case 'References':
value = [].concat.apply([], [].concat(value).map(function () {
var elm = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
return elm.replace(/\r?\n|\r/g, ' ').trim().replace(/<[^>]*>/g, function (str) {
return str.replace(/\s/g, '');
}).split(/\s+/);
})).map(function (elm) {
if (elm.charAt(0) !== '<') {
elm = '<' + elm;
}
if (elm.charAt(elm.length - 1) !== '>') {
elm = elm + '>';
}
return elm;
});
return value.join(' ').trim();
default:
return (0, _emailjsMimeCodec.mimeWordsEncode)((value || '').toString().replace(/\r?\n|\r/g, ' '), 'B');
}
} | javascript | {
"resource": ""
} |
q50639 | normalizeHeaderKey | train | function normalizeHeaderKey() {
var key = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
return key.replace(/\r?\n|\r/g, ' ') // no newlines in keys
.trim().toLowerCase().replace(/^MIME\b|^[a-z]|-[a-z]/ig, function (c) {
return c.toUpperCase();
}); // use uppercase words, except MIME
} | javascript | {
"resource": ""
} |
q50640 | buildHeaderValue | train | function buildHeaderValue(structured) {
var paramsArray = [];
Object.keys(structured.params || {}).forEach(function (param) {
// filename might include unicode characters so it is a special case
if (param === 'filename') {
(0, _emailjsMimeCodec.continuationEncode)(param, structured.params[param], 50).forEach(function (encodedParam) {
// continuation encoded strings are always escaped, so no need to use enclosing quotes
// in fact using quotes might end up with invalid filenames in some clients
paramsArray.push(encodedParam.key + '=' + encodedParam.value);
});
} else {
paramsArray.push(param + '=' + escapeHeaderArgument(structured.params[param]));
}
});
return structured.value + (paramsArray.length ? '; ' + paramsArray.join('; ') : '');
} | javascript | {
"resource": ""
} |
q50641 | NodeMqttTransport | train | function NodeMqttTransport(options) {
Transport.call(this, options);
this._options = options;
this._client = null;
this._sendTimer = null;
this._buf = [];
this._status = '';
this._connHandler = onConnect.bind(this);
this._messageHandler = onMessage.bind(this);
this._sendOutHandler = sendOut.bind(this);
this._disconnHandler = onDisconnect.bind(this);
this._errorHandler = onError.bind(this);
init(this);
} | javascript | {
"resource": ""
} |
q50642 | train | function(error, substitutions) {
var text = error.text;
if (substitutions) {
var field,start;
for (var i=0; i<substitutions.length; i++) {
field = "{"+i+"}";
start = text.indexOf(field);
if(start > 0) {
var part1 = text.substring(0,start);
var part2 = text.substring(start+field.length);
text = part1+substitutions[i]+part2;
}
}
}
return text;
} | javascript | {
"resource": ""
} | |
q50643 | UTF8Length | train | function UTF8Length(input) {
var output = 0;
for (var i = 0; i<input.length; i++)
{
var charCode = input.charCodeAt(i);
if (charCode > 0x7FF)
{
// Surrogate pair means its a 4 byte character
if (0xD800 <= charCode && charCode <= 0xDBFF)
{
i++;
output++;
}
output +=3;
}
else if (charCode > 0x7F)
output +=2;
else
output++;
}
return output;
} | javascript | {
"resource": ""
} |
q50644 | callback | train | function callback(ctx, err, result) {
if (typeof ctx.custom === 'function') {
var cust = function () {
// Bind the callback to itself, so the resolve and reject
// properties that we bound are available to the callback.
// Then we push it onto the end of the arguments array.
return ctx.custom.apply(cust, arguments);
};
cust.resolve = ctx.resolve;
cust.reject = ctx.reject;
cust.call(null, err, result);
} else {
if (err) {
return ctx.reject(err);
}
ctx.resolve(result);
}
} | javascript | {
"resource": ""
} |
q50645 | MqttTransport | train | function MqttTransport(options) {
Transport.call(this, options);
this._options = options;
this._client = null;
this._timer = null;
this._sendTimer = null;
this._buf = [];
this._status = '';
this._connHandler = onConnect.bind(this);
this._connFailedHandler = onConnectFailed.bind(this);
this._messageHandler = onMessage.bind(this);
this._sendOutHandler = sendOut.bind(this);
this._disconnHandler = onDisconnect.bind(this);
init(this);
} | javascript | {
"resource": ""
} |
q50646 | Board | train | function Board(options) {
EventEmitter.call(this);
this._options = options;
this._buf = [];
this._digitalPort = [];
this._numPorts = 0;
this._analogPinMapping = [];
this._digitalPinMapping = [];
this._i2cPins = [];
this._ioPins = [];
this._totalPins = 0;
this._totalAnalogPins = 0;
this._samplingInterval = 19;
this._isReady = false;
this._firmwareName = '';
this._firmwareVersion = 0;
this._capabilityQueryResponseReceived = false;
this._numPinStateRequests = 0;
this._numDigitalPortReportRequests = 0;
this._transport = null;
this._pinStateEventCenter = new EventEmitter();
this._logger = new Logger('Board');
this._initialVersionResultHandler = onInitialVersionResult.bind(this);
this._openHandler = onOpen.bind(this);
this._reOpenHandler = onReOpen.bind(this);
this._messageHandler = onMessage.bind(this);
this._errorHandler = onError.bind(this);
this._closeHandler = onClose.bind(this);
this._cleanupHandler = cleanup.bind(this);
attachCleanup(this);
this._setTransport(this._options.transport);
} | javascript | {
"resource": ""
} |
q50647 | Led | train | function Led(board, pin, driveMode) {
Module.call(this);
this._board = board;
this._pin = pin;
this._driveMode = driveMode || Led.SOURCE_DRIVE;
this._supportsPWM = undefined;
this._blinkTimer = null;
this._board.on(BoardEvent.BEFOREDISCONNECT, this._clearBlinkTimer.bind(this));
this._board.on(BoardEvent.ERROR, this._clearBlinkTimer.bind(this));
if (this._driveMode === Led.SOURCE_DRIVE) {
this._onValue = 1;
this._offValue = 0;
} else if (this._driveMode === Led.SYNC_DRIVE) {
this._onValue = 0;
this._offValue = 1;
} else {
throw new Error('driveMode should be Led.SOURCE_DRIVE or Led.SYNC_DRIVE');
}
if (pin.capabilities[Pin.PWM]) {
board.setDigitalPinMode(pin.number, Pin.PWM);
this._supportsPWM = true;
} else {
board.setDigitalPinMode(pin.number, Pin.DOUT);
this._supportsPWM = false;
}
} | javascript | {
"resource": ""
} |
q50648 | RGBLed | train | function RGBLed(board, redLedPin, greenLedPin, blueLedPin, driveMode) {
Module.call(this);
if (driveMode === undefined) {
driveMode = RGBLed.COMMON_ANODE;
}
this._board = board;
this._redLed = new Led(board, redLedPin, driveMode);
this._greenLed = new Led(board, greenLedPin, driveMode);
this._blueLed = new Led(board, blueLedPin, driveMode);
this.setColor(0, 0, 0);
} | javascript | {
"resource": ""
} |
q50649 | Button | train | function Button(board, pin, buttonMode, sustainedPressInterval) {
Module.call(this);
this._board = board;
this._pin = pin;
this._repeatCount = 0;
this._timer = null;
this._timeout = null;
this._buttonMode = buttonMode || Button.PULL_DOWN;
this._sustainedPressInterval = sustainedPressInterval || 1000;
this._debounceInterval = 20;
this._pressHandler = onPress.bind(this);
this._releaseHandler = onRelease.bind(this);
this._sustainedPressHandler = onSustainedPress.bind(this);
board.setDigitalPinMode(pin.number, Pin.DIN);
if (this._buttonMode === Button.INTERNAL_PULL_UP) {
board.enablePullUp(pin.number);
this._pin.value = Pin.HIGH;
} else if (this._buttonMode === Button.PULL_UP) {
this._pin.value = Pin.HIGH;
}
this._pin.on(PinEvent.CHANGE, onPinChange.bind(this));
} | javascript | {
"resource": ""
} |
q50650 | Ultrasonic | train | function Ultrasonic(board, trigger, echo) {
Module.call(this);
this._type = 'HC-SR04';
this._board = board;
this._trigger = trigger;
this._echo = echo;
this._distance = null;
this._lastRecv = null;
this._pingTimer = null;
this._pingCallback = function () {};
this._board.on(BoardEvent.BEFOREDISCONNECT, this.stopPing.bind(this));
this._messageHandler = onMessage.bind(this);
this._board.on(BoardEvent.ERROR, this.stopPing.bind(this));
} | javascript | {
"resource": ""
} |
q50651 | Dht | train | function Dht(board, pin) {
Module.call(this);
this._type = 'DHT11';
this._board = board;
this._pin = pin;
this._humidity = null;
this._temperature = null;
this._lastRecv = null;
this._readTimer = null;
this._readCallback = function () {};
this._board.on(BoardEvent.BEFOREDISCONNECT, this.stopRead.bind(this));
this._messageHandler = onMessage.bind(this);
this._board.on(BoardEvent.ERROR, this.stopRead.bind(this));
} | javascript | {
"resource": ""
} |
q50652 | Buzzer | train | function Buzzer(board, pin) {
Module.call(this);
this._board = board;
this._pin = pin;
this._timer = null;
this._sequence = null;
this._state = BUZZER_STATE.STOPPED;
this._board.on(BoardEvent.BEFOREDISCONNECT, this.stop.bind(this));
this._board.on(BoardEvent.ERROR, this.stop.bind(this));
} | javascript | {
"resource": ""
} |
q50653 | Max7219 | train | function Max7219(board, din, cs, clk) {
Module.call(this);
this._board = board;
this._din = din;
this._cs = cs;
this._clk = clk;
this._intensity = 0;
this._data = 'ffffffffffffffff';
this._board.on(BoardEvent.BEFOREDISCONNECT, this.animateStop.bind(this));
this._board.on(BoardEvent.ERROR, this.animateStop.bind(this));
this._board.send([0xf0, 4, 8, 0, din.number, cs.number, clk.number, 0xf7]);
} | javascript | {
"resource": ""
} |
q50654 | ADXL345 | train | function ADXL345(board) {
Module.call(this);
this._board = board;
this._baseAxis = 'z';
this._sensitive = 10;
this._detectTime = 50;
this._messageHandler = onMessage.bind(this);
this._init = false;
this._info = {
x: 0,
y: 0,
z: 0,
fXg: 0,
fYg: 0,
fZg: 0
};
this._callback = function () {};
this._board.send([0xf0, 0x04, 0x0b, 0x00, 0xf7]);
} | javascript | {
"resource": ""
} |
q50655 | HX711 | train | function HX711(board, sckPin, dtPin) {
Module.call(this);
this._board = board;
this._dt = !isNaN(dtPin) ? board.getDigitalPin(dtPin) : dtPin;
this._sck = !isNaN(sckPin) ? board.getDigitalPin(sckPin) : sckPin;
this._init = false;
this._weight = 0;
this._callback = function() {};
this._messageHandler = onMessage.bind(this);
this._board.send([0xf0, 0x04, 0x15, 0x00,
this._sck._number, this._dt._number, 0xf7
]);
} | javascript | {
"resource": ""
} |
q50656 | Barcode | train | function Barcode(board, rxPin, txPin) {
Module.call(this);
this._board = board;
this._rx = !isNaN(rxPin) ? board.getDigitalPin(rxPin) : rxPin;
this._tx = !isNaN(txPin) ? board.getDigitalPin(txPin) : txPin;
this._init = false;
this._scanData = '';
this._callback = function () {};
this._messageHandler = onMessage.bind(this);
this._board.send([0xf0, 0x04, 0x16, 0x00,
this._rx._number, this._tx._number, 0xf7
]);
} | javascript | {
"resource": ""
} |
q50657 | IRLed | train | function IRLed(board, encode) {
Module.call(this);
this._board = board;
this._encode = encode;
this._board.send([0xf4, 0x09, 0x03, 0xe9, 0x00, 0x00]);
} | javascript | {
"resource": ""
} |
q50658 | IRRecv | train | function IRRecv(board, pin) {
Module.call(this);
this._board = board;
this._pin = pin;
this._messageHandler = onMessage.bind(this);
this._recvCallback = function () {};
this._recvErrorCallback = function () {};
this._board.send([0xf0, 0x04, 0x0A, 0x01, 0xf7]);
} | javascript | {
"resource": ""
} |
q50659 | RFID | train | function RFID(board) {
Module.call(this);
this._board = board;
this._isReading = false;
this._enterHandlers = [];
this._leaveHandlers = [];
this._messageHandler = onMessage.bind(this);
this._board.on(BoardEvent.BEFOREDISCONNECT, this.destroy.bind(this));
this._board.on(BoardEvent.ERROR, this.destroy.bind(this));
this._board.send([0xf0, 0x04, 0x0f, 0x00, 0xf7]);
} | javascript | {
"resource": ""
} |
q50660 | setup | train | function setup(check) {
if (!check) {
throw new Error('Data to match is not defined')
} else if (!check.jsonBody) {
throw new Error('jsonBody is not defined')
} else if (!check.jsonTest) {
throw new Error('jsonTest is not defined')
}
// define the defaults
const defaults = {
isNot: false,
path: undefined,
// jsonBody will be present
// jsonTest will be present
}
// merge the passed in values with the defaults
return _.merge(defaults, check)
} | javascript | {
"resource": ""
} |
q50661 | train | function(jsonBody, lengthSegments) {
let len = 0
if (_.isObject(jsonBody)) {
len = Object.keys(jsonBody).length
} else {
len = jsonBody.length
}
let msg // message for expectation result
//TODO: in the future, use expect(jsonBody).to.have.length.below(lengthSegments.count + 1); or similar for non-objects to get better assertion messages
switch (lengthSegments.sign) {
case '<=':
msg =
'Expected length to be less than or equal to ' +
lengthSegments.count +
', but got ' +
len
expect(len).to.be.lessThan(lengthSegments.count + 1, msg)
break
case '<':
msg =
'Expected length to be less than ' +
lengthSegments.count +
', but got ' +
len
expect(len).to.be.lessThan(lengthSegments.count, msg)
break
case '>=':
msg =
'Expected length to be greater than or equal ' +
lengthSegments.count +
', but got ' +
len
expect(len).to.be.greaterThan(lengthSegments.count - 1, msg)
break
case '>':
msg =
'Expected length to be greater than ' +
lengthSegments.count +
', but got ' +
len
expect(len).to.be.greaterThan(lengthSegments.count, msg)
break
case null:
msg = 'Expected length to be ' + lengthSegments.count + ', but got ' + len
expect(len).to.equal(lengthSegments.count, msg)
break
} //end switch
} | javascript | {
"resource": ""
} | |
q50662 | _jsonParse | train | function _jsonParse(body) {
let json = ''
try {
json = typeof body === 'object' ? body : JSON.parse(body)
} catch (e) {
throw new Error(
'Error parsing JSON string: ' + e.message + '\n\tGiven: ' + body
)
}
return json
} | javascript | {
"resource": ""
} |
q50663 | train | function(url) {
var prevHref = location.href;
var prevTitle = document.title;
// Change the history
history.pushState({ scrollFrame: true, href: location.href }, '', url);
// Create the wrapper & iframe modal
var body = document.getElementsByTagName('body')[0];
var iOS = navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false;
var attributes = [
'position: fixed', 'top: 0', 'left: 0','width: 100%', 'height: 100%',
'z-index: 10000000', 'background-color: white', 'border: 0'
];
//only add scrolling fix for ios devices
if (iOS){
attributes.push('overflow-y: scroll');
attributes.push('-webkit-overflow-scrolling: touch');
}
//create wrapper for iOS scroll fix
var wrapper = document.createElement("div");
wrapper.setAttribute('style',attributes.join(';'));
var iframe = document.createElement("iframe");
iframe.className = 'scroll-frame-iframe'
iframe.setAttribute('style', [
'width: 100%', 'height: 100%', 'position:absolute',
'border: 0'
].join(';'));
// Lock the body from scrolling & hide the body's scroll bars.
body.setAttribute('style', 'overflow: hidden;' +
(body.getAttribute('style') || ''));
// Add a class to the body while the iframe loads then append it
body.className += ' scroll-frame-loading';
iframe.onload = function() {
body.className = body.className.replace(' scroll-frame-loading', '');
document.title = iframe.contentDocument.title;
}
wrapper.appendChild(iframe);
body.appendChild(wrapper);
iframe.contentWindow.location.replace(url);
// On back-button remove the wrapper
var onPopState = function(e) {
if (location.href != prevHref) return;
wrapper.removeChild(iframe);
document.title = prevTitle;
body.removeChild(wrapper);
body.setAttribute('style',
body.getAttribute('style').replace('overflow: hidden;', ''));
removeEventListener('popstate', onPopState);
}
addEventListener('popstate', onPopState);
} | javascript | {
"resource": ""
} | |
q50664 | train | function(e) {
if (location.href != prevHref) return;
wrapper.removeChild(iframe);
document.title = prevTitle;
body.removeChild(wrapper);
body.setAttribute('style',
body.getAttribute('style').replace('overflow: hidden;', ''));
removeEventListener('popstate', onPopState);
} | javascript | {
"resource": ""
} | |
q50665 | internal | train | function internal(obj) {
if (!privateMap.has(obj)) {
privateMap.set(obj, {});
}
return privateMap.get(obj);
} | javascript | {
"resource": ""
} |
q50666 | train | function (object, descriptors) {
for(var key in descriptors) {
if (hasOwnProperty.call(descriptors, key)) {
try {
defineProperty(object, key, descriptors[key]);
} catch(o_O) {
if (window.console) {
console.log(key + ' failed on object:', object, o_O.message);
}
}
}
}
} | javascript | {
"resource": ""
} | |
q50667 | truncateObj | train | function truncateObj(obj, level) {
var dst = {};
for (var attr in obj) {
if (Object.prototype.hasOwnProperty.call(obj, attr)) {
dst[attr] = module.exports.truncate(obj[attr], level);
}
}
return dst;
} | javascript | {
"resource": ""
} |
q50668 | shallowMerge | train | function shallowMerge(o1, o2) {
var o = {},
k;
for (k in o1) o[k] = o1[k];
for (k in o2) o[k] = o2[k];
return o;
} | javascript | {
"resource": ""
} |
q50669 | isPlainObject | train | function isPlainObject(v) {
return v &&
typeof v === 'object' &&
!Array.isArray(v) &&
!(v instanceof Function) &&
!(v instanceof RegExp);
} | javascript | {
"resource": ""
} |
q50670 | forIn | train | function forIn(object, fn, scope) {
var symbols,
k,
i,
l;
for (k in object)
fn.call(scope || null, k, object[k]);
if (Object.getOwnPropertySymbols) {
symbols = Object.getOwnPropertySymbols(object);
for (i = 0, l = symbols.length; i < l; i++)
fn.call(scope || null, symbols[i], object[symbols[i]]);
}
} | javascript | {
"resource": ""
} |
q50671 | filter | train | function filter(target, fn) {
target = target || [];
var a = [],
l,
i;
for (i = 0, l = target.length; i < l; i++)
if (target[i].fn !== fn)
a.push(target[i]);
return a;
} | javascript | {
"resource": ""
} |
q50672 | generateModelOpenApiSchema | train | function generateModelOpenApiSchema(schema, definitionName) {
var oaSchema = {
required: [],
properties: {}
};
mergePaths(oaSchema, schema.paths, definitionName);
mergePaths(oaSchema, schema.virtuals, definitionName);
//remove empty arrays -> OpenAPI 3.0 validates
if (oaSchema.required.length === 0) {
delete(oaSchema.required);
}
if (oaSchema.properties.length === 0) {
delete(oaSchema.properties);
}
return oaSchema;
} | javascript | {
"resource": ""
} |
q50673 | generateResourceListing | train | function generateResourceListing(options) {
var controllers = options.controllers;
var opts = options.options || {};
var listing = {
openapi: '3.0.0',
info: buildInfo(opts),
servers: opts.servers || buildDefaultServers(),
tags: buildTags(opts, controllers),
paths: buildPaths(opts, controllers),
components: buildComponents(opts, controllers)
};
mergeIn(listing.paths, opts.paths);
if (opts.security) {
listing.security = opts.security;
}
if (opts.externalDocs) {
listing.externalDocs = opts.externalDocs;
}
return listing;
} | javascript | {
"resource": ""
} |
q50674 | fixHttpMethod | train | function fixHttpMethod (fn, name) {
if (fn.http && fn.http.verb && fn.http.verb.toLowerCase() === 'put') {
fn.http.verb = 'patch'
}
} | javascript | {
"resource": ""
} |
q50675 | convertNullToNotFoundError | train | function convertNullToNotFoundError (toModelName, ctx, cb) {
if (ctx.result !== null) return cb()
var fk = ctx.getArgByName('fk')
var msg = 'Unknown "' + toModelName + '" id "' + fk + '".'
var error = new Error(msg)
error.statusCode = error.status = statusCodes.NOT_FOUND
error.code = 'MODEL_NOT_FOUND'
cb(error)
} | javascript | {
"resource": ""
} |
q50676 | hasOneRemoting | train | function hasOneRemoting (relationName, relation, define) {
var pathName = (relation.options.http && relation.options.http.path) ||
relationName
var toModelName = relation.modelTo.modelName
define('__get__' + relationName, {
isStatic: false,
accessType: 'READ',
description: 'Fetches hasOne relation ' + relationName + '.',
http: {
verb: 'get',
path: '/' + pathName
},
accepts: {
arg: 'refresh',
type: 'boolean',
http: {
source: 'query'
}
},
returns: {
arg: relationName,
type: relation.modelTo.modelName,
root: true
}
})
var findHasOneRelationshipsFunc = function (cb) {
this['__get__' + pathName](cb)
}
define(
'__findRelationships__' + relationName,
{
isStatic: false,
accessType: 'READ',
description: 'Find relations for ' + relationName + '.',
http: {
verb: 'get',
path: '/relationships/' + pathName
},
returns: {
arg: 'result',
type: toModelName,
root: true
}
},
findHasOneRelationshipsFunc
)
} | javascript | {
"resource": ""
} |
q50677 | hasManyRemoting | train | function hasManyRemoting (relationName, relation, define) {
var pathName = (relation.options.http && relation.options.http.path) ||
relationName
var toModelName = relation.modelTo.modelName
var findHasManyRelationshipsFunc = function (cb) {
this['__get__' + pathName](cb)
}
define(
'__findRelationships__' + relationName,
{
isStatic: false,
accessType: 'READ',
description: 'Find relations for ' + relationName + '.',
http: {
verb: 'get',
path: '/relationships/' + pathName
},
returns: {
arg: 'result',
type: toModelName,
root: true
},
rest: {
after: convertNullToNotFoundError.bind(null, toModelName)
}
},
findHasManyRelationshipsFunc
)
// var createRelationshipFunc = function (cb) {
// TODO: implement this
// this is where we need to implement
// POST /:model/:id/relationships/:relatedModel
//
// this['__get__' + pathName](cb)
// }
// define('__createRelationships__' + relationName, {
// isStatic: false,
// accessType: 'READ',
// description: 'Create relations for ' + relationName + '.',
// http: {
// verb: 'post',
// path: '/relationships/' + pathName
// },
// returns: {
// arg: 'result',
// type: toModelName,
// root: true
// },
// rest: {
// after: convertNullToNotFoundError.bind(null, toModelName)
// }
// }, createRelationshipFunc)
// var updateRelationshipsFunc = function (cb) {
// TODO: implement this
// this is where we need to implement
// PATCH /:model/:id/relationships/:relatedModel
//
// this['__get__' + pathName](cb)
// }
// define('__updateRelationships__' + relationName, {
// isStatic: false,
// accessType: 'READ',
// description: 'Update relations for ' + relationName + '.',
// http: {
// verb: 'patch',
// path: '/relationships/' + pathName
// },
// returns: {
// arg: 'result',
// type: toModelName,
// root: true
// },
// rest: {
// after: convertNullToNotFoundError.bind(null, toModelName)
// }
// }, updateRelationshipsFunc)
// var deleteRelationshipsFunc = function (cb) {
// TODO: implement this
// this is where we need to implement
// DELETE /:model/:id/relationships/:relatedModel
//
// this['__get__' + pathName](cb)
// }
// define('__deleteRelationships__' + relationName, {
// isStatic: false,
// accessType: 'READ',
// description: 'Delete relations for ' + relationName + '.',
// http: {
// verb: 'delete',
// path: '/relationships/' + pathName
// },
// returns: {
// arg: 'result',
// type: toModelName,
// root: true
// },
// rest: {
// after: convertNullToNotFoundError.bind(null, toModelName)
// }
// }, deleteRelationshipsFunc)
if (relation.modelThrough || relation.type === 'referencesMany') {
var modelThrough = relation.modelThrough || relation.modelTo
var accepts = []
if (relation.type === 'hasMany' && relation.modelThrough) {
// Restrict: only hasManyThrough relation can have additional properties
accepts.push({
arg: 'data',
type: modelThrough.modelName,
http: {
source: 'body'
}
})
}
}
} | javascript | {
"resource": ""
} |
q50678 | scopeRemoting | train | function scopeRemoting (scopeName, scope, define) {
var pathName = (scope.options &&
scope.options.http &&
scope.options.http.path) ||
scopeName
var isStatic = scope.isStatic
var toModelName = scope.modelTo.modelName
// https://github.com/strongloop/loopback/issues/811
// Check if the scope is for a hasMany relation
var relation = this.relations[scopeName]
if (relation && relation.modelTo) {
// For a relation with through model, the toModelName should be the one
// from the target model
toModelName = relation.modelTo.modelName
}
define('__get__' + scopeName, {
isStatic: isStatic,
accessType: 'READ',
description: 'Queries ' + scopeName + ' of ' + this.modelName + '.',
http: {
verb: 'get',
path: '/' + pathName
},
accepts: {
arg: 'filter',
type: 'object'
},
returns: {
arg: scopeName,
type: [toModelName],
root: true
}
})
} | javascript | {
"resource": ""
} |
q50679 | JSONAPIErrorHandler | train | function JSONAPIErrorHandler (err, req, res, next) {
debug('Handling error(s) using custom jsonapi error handler')
debug('Set Content-Type header to `application/vnd.api+json`')
res.set('Content-Type', 'application/vnd.api+json')
var errors = []
var statusCode = err.statusCode ||
err.status ||
statusCodes.INTERNAL_SERVER_ERROR
debug('Raw error object:', err)
if (err.details && err.details.messages) {
debug('Handling error as a validation error.')
// This block is for handling validation errors.
// Build up an array of validation errors.
errors = Object.keys(err.details.messages).map(function (key) {
return buildErrorResponse(
statusCode,
err.details.messages[key][0],
err.details.codes[key][0],
err.name,
{ pointer: 'data/attributes/' + key }
)
})
} else if (err.message) {
// convert specific errors below to validation errors.
// These errors are from checks on the incoming payload to ensure it is
// JSON API compliant. If we switch to being able to use the Accept header
// to decide whether to handle the request as JSON API, these errors would
// need to only be applied when the Accept header is `application/vnd.api+json`
var additionalValidationErrors = [
'JSON API resource object must contain `data` property',
'JSON API resource object must contain `data.type` property',
'JSON API resource object must contain `data.id` property'
]
if (additionalValidationErrors.indexOf(err.message) !== -1) {
debug('Recasting error as a validation error.')
statusCode = statusCodes.UNPROCESSABLE_ENTITY
err.code = 'presence'
err.name = 'ValidationError'
}
debug('Handling invalid relationship specified in url')
if (/Relation (.*) is not defined for (.*) model/.test(err.message)) {
statusCode = statusCodes.BAD_REQUEST
err.message = 'Bad Request'
err.code = 'INVALID_INCLUDE_TARGET'
err.name = 'BadRequest'
}
var errorSource = err.source && typeof err.source === 'object'
? err.source
: {}
if (errorStackInResponse) {
// We do not want to mutate err.source, so we clone it first
errorSource = _.clone(errorSource)
errorSource.stack = err.stack
}
errors.push(
buildErrorResponse(
statusCode,
err.message,
err.code,
err.name,
errorSource,
err.meta
)
)
} else {
debug(
'Unable to determin error type. Treating error as a general 500 server error.'
)
// catch all server 500 error if we were unable to understand the error.
errors.push(
buildErrorResponse(
statusCodes.INTERNAL_SERVER_ERROR,
'Internal Server error',
'GENERAL_SERVER_ERROR'
)
)
}
// send the errors and close out the response.
debug('Sending error response')
debug('Response Code:', statusCode)
debug('Response Object:', { errors: errors })
res.status(statusCode).send({ errors: errors }).end()
} | javascript | {
"resource": ""
} |
q50680 | buildErrorResponse | train | function buildErrorResponse (
httpStatusCode,
errorDetail,
errorCode,
errorName,
errorSource,
errorMeta
) {
var out = {
status: httpStatusCode || statusCodes.INTERNAL_SERVER_ERROR,
source: errorSource || {},
title: errorName || '',
code: errorCode || '',
detail: errorDetail || ''
}
if (errorMeta && typeof errorMeta === 'object') {
out.meta = errorMeta
}
return out
} | javascript | {
"resource": ""
} |
q50681 | parseResource | train | function parseResource (type, data, relations, options) {
var resource = {}
var attributes = {}
var relationships
resource.type = type
relationships = parseRelations(data, relations, options)
if (!_.isEmpty(relationships)) {
resource.relationships = relationships
}
if (options.foreignKeys !== true) {
// Remove any foreign keys from this resource
options.app.models().forEach(function (model) {
_.each(model.relations, function (relation) {
var fkModel = relation.modelTo
var fkName = relation.keyTo
if (utils.relationFkOnModelFrom(relation)) {
fkModel = relation.modelFrom
fkName = relation.keyFrom
}
if (fkModel === options.model && fkName !== options.primaryKeyField) {
// check options and decide whether to remove foreign keys.
if (
options.foreignKeys !== false && Array.isArray(options.foreignKeys)
) {
for (var i = 0; i < options.foreignKeys.length; i++) {
// if match on model
if (options.foreignKeys[i].model === fkModel.sharedClass.name) {
// if no method specified
if (!options.foreignKeys[i].method) return
// if method match
if (options.foreignKeys[i].method === options.method) return
}
}
}
delete data[fkName]
}
})
})
}
_.each(data, function (value, property) {
if (property === options.primaryKeyField) {
resource.id = _(value).toString()
} else {
if (
!options.attributes[type] ||
_.includes(options.attributes[type], property)
) {
attributes[property] = value
}
}
})
if (_.isUndefined(resource.id)) {
return null
}
// if it's a relationship request
if (options.isRelationshipRequest) {
return resource
}
resource.attributes = attributes
if (options.dataLinks) {
resource.links = makeLinks(options.dataLinks, resource)
}
return resource
} | javascript | {
"resource": ""
} |
q50682 | parseCollection | train | function parseCollection (type, data, relations, options) {
var result = []
_.each(data, function (value) {
result.push(parseResource(type, value, relations, options))
})
return result
} | javascript | {
"resource": ""
} |
q50683 | parseRelations | train | function parseRelations (data, relations, options) {
var relationships = {}
_.each(relations, function (relation, name) {
var fkName = relation.keyTo
// If relation is belongsTo then fk is the other way around
if (utils.relationFkOnModelFrom(relation)) {
fkName = relation.keyFrom
}
var pk = data[options.primaryKeyField]
var fk = data[fkName]
var toType = ''
if (relation.polymorphic && utils.relationFkOnModelFrom(relation)) {
var discriminator = relation.polymorphic.discriminator
var model = options.app.models[data[discriminator]]
toType = utils.pluralForModel(model)
} else {
toType = utils.pluralForModel(relation.modelTo)
}
// Relationship `links` should always be defined unless this is a
// relationship request
if (!options.isRelationshipRequest) {
relationships[name] = {
links: {
related: options.host +
options.restApiRoot +
'/' +
options.modelPath +
'/' +
pk +
'/' +
name
}
}
}
var relationship = null
if (!_.isUndefined(fk) && relation.modelTo !== relation.modelFrom) {
if (_.isArray(fk)) {
relationship = makeRelations(toType, fk, options)
} else {
relationship = makeRelation(toType, fk, options)
}
}
// No `data` key should be present unless there is actual relationship data.
if (relationship) {
relationships[name].data = relationship
} else if (relation.type === 'belongsTo') {
relationships[name].data = null
}
})
return relationships
} | javascript | {
"resource": ""
} |
q50684 | makeRelation | train | function makeRelation (type, id, options) {
if (!_.includes(['string', 'number'], typeof id) || !id) {
return null
}
return {
type: type,
id: id
}
} | javascript | {
"resource": ""
} |
q50685 | makeRelations | train | function makeRelations (type, ids, options) {
var res = []
_.each(ids, function (id) {
res.push(makeRelation(type, id, options))
})
return res
} | javascript | {
"resource": ""
} |
q50686 | makeLinks | train | function makeLinks (links, item) {
var retLinks = {}
_.each(links, function (value, name) {
if (_.isFunction(value)) {
retLinks[name] = value(item)
} else {
retLinks[name] = _(value).toString()
}
})
return retLinks
} | javascript | {
"resource": ""
} |
q50687 | handleIncludes | train | function handleIncludes (resp, includes, relations, options) {
var app = options.app
relations = utils.setIncludedRelations(relations, app)
var resources = _.isArray(resp.data) ? resp.data : [resp.data]
if (typeof includes === 'string') {
includes = [includes]
}
if (!_.isArray(includes)) {
throw RelUtils.getInvalidIncludesError(
'JSON API unable to detect valid includes'
)
}
var embedded = resources.map(function subsituteEmbeddedForIds (resource) {
return includes.map(function (include) {
var relation = relations[include]
var includedRelations = relations[include].relations
var propertyKey = relation.keyFrom
var plural = ''
if (relation.polymorphic && utils.relationFkOnModelFrom(relation)) {
var descriminator = relation.polymorphic.discriminator
var discriminator = resource.attributes[descriminator]
plural = utils.pluralForModel(app.models[discriminator])
} else {
plural = utils.pluralForModel(relation.modelTo)
}
var embeds = []
// If relation is belongsTo then pk and fk are the other way around
if (utils.relationFkOnModelFrom(relation)) {
propertyKey = relation.keyTo
}
if (!relation) {
throw RelUtils.getInvalidIncludesError(
'Can\'t locate relationship "' + include + '" to include'
)
}
resource.relationships[include] = resource.relationships[include] || {}
if (resource.relationships[include] && resource.attributes[include]) {
if (_.isArray(resource.attributes[include])) {
embeds = resource.attributes[include].map(function (rel) {
rel = utils.clone(rel)
return createCompoundIncludes(
rel,
propertyKey,
relation.keyTo,
plural,
includedRelations,
options
)
})
embeds = _.compact(embeds)
const included = resource.attributes[include]
resource.relationships[include].data = included.map(relData => {
return {
id: String(relData[propertyKey]),
type: plural
}
})
} else {
var rel = utils.clone(resource.attributes[include])
var compoundIncludes = createCompoundIncludes(
rel,
propertyKey,
relation.keyFrom,
plural,
includedRelations,
options
)
resource.relationships[include].data = {
id: String(resource.attributes[include][propertyKey]),
type: plural
}
embeds.push(compoundIncludes)
}
delete resource.attributes[relation.keyFrom]
delete resource.attributes[relation.keyTo]
delete resource.attributes[include]
}
return embeds
})
})
if (embedded.length) {
// This array may contain duplicate models if the same item is referenced multiple times in 'data'
var duplicate = _.flattenDeep(embedded)
// So begin with an empty array that will only contain unique items
var unique = []
// Iterate through each item in the first array
duplicate.forEach(function (d) {
// Count the number of items in the unique array with matching 'type' AND 'id'
// Since we're adhering to the JSONAPI spec, both 'type' and 'id' can assumed to be present
// Both 'type' and 'id' are needed for comparison because we could theoretically have objects of different
// types who happen to have the same 'id', and those would not be considered duplicates
var count = unique.filter(function (u) {
return u.type === d.type && u.id === d.id
}).length
// If there are no matching entries, then add the item to the unique array
if (count === 0) {
unique.push(d)
}
})
resp.included = unique
}
} | javascript | {
"resource": ""
} |
q50688 | createCompoundIncludes | train | function createCompoundIncludes (
relationship,
key,
fk,
type,
includedRelations,
options
) {
var compoundInclude = makeRelation(type, String(relationship[key]))
if (options && !_.isEmpty(includedRelations)) {
var defaultModelPath = options.modelPath
options.modelPath = type
compoundInclude.relationships = parseRelations(
relationship,
includedRelations,
options
)
options.modelPath = defaultModelPath
}
// remove the id key since its part of the base compound document, not part of attributes
delete relationship[key]
delete relationship[fk]
// The rest of the data goes in the attributes
compoundInclude.attributes = relationship
return compoundInclude
} | javascript | {
"resource": ""
} |
q50689 | pluralForModel | train | function pluralForModel (model) {
if (model.pluralModelName) {
return model.pluralModelName
}
if (model.settings && model.settings.plural) {
return model.settings.plural
}
if (
model.definition &&
model.definition.settings &&
model.definition.settings.plural
) {
return model.definition.settings.plural
}
return inflection.pluralize(model.sharedClass.name)
} | javascript | {
"resource": ""
} |
q50690 | httpPathForModel | train | function httpPathForModel (model) {
if (model.settings && model.settings.http && model.settings.http.path) {
return model.settings.http.path
}
return pluralForModel(model)
} | javascript | {
"resource": ""
} |
q50691 | urlFromContext | train | function urlFromContext (context) {
return context.req.protocol +
'://' +
context.req.get('host') +
context.req.originalUrl
} | javascript | {
"resource": ""
} |
q50692 | getModelFromContext | train | function getModelFromContext (context, app) {
var type = getTypeFromContext(context)
if (app.models[type]) return app.models[type]
var name = modelNameFromContext(context)
return app.models[name]
} | javascript | {
"resource": ""
} |
q50693 | getTypeFromContext | train | function getTypeFromContext (context) {
if (!context.method.returns) return undefined
const returns = [].concat(context.method.returns)
for (var i = 0, l = returns.length; i < l; i++) {
if (typeof returns[i] !== 'object' || returns[i].root !== true) continue
return returns[i].type
}
} | javascript | {
"resource": ""
} |
q50694 | buildModelUrl | train | function buildModelUrl (protocol, host, apiRoot, modelName, id) {
var result
try {
result = url.format({
protocol: protocol,
host: host,
pathname: url.resolve('/', [apiRoot, modelName, id].join('/'))
})
} catch (e) {
return ''
}
return result
} | javascript | {
"resource": ""
} |
q50695 | validateRequest | train | function validateRequest (data, requestMethod) {
if (!data.data) {
return 'JSON API resource object must contain `data` property'
}
if (!data.data.type) {
return 'JSON API resource object must contain `data.type` property'
}
if (['PATCH', 'PUT'].indexOf(requestMethod) > -1 && !data.data.id) {
return 'JSON API resource object must contain `data.id` property'
}
return false
} | javascript | {
"resource": ""
} |
q50696 | getInvalidIncludesError | train | function getInvalidIncludesError (message) {
var error = new Error(
message || 'JSON API resource does not support `include`'
)
error.statusCode = statusCodes.BAD_REQUEST
error.code = statusCodes.BAD_REQUEST
error.status = statusCodes.BAD_REQUEST
return error
} | javascript | {
"resource": ""
} |
q50697 | getIncludesArray | train | function getIncludesArray (query) {
var relationships = query.include.split(',')
return relationships.map(function (val) {
return val.trim()
})
} | javascript | {
"resource": ""
} |
q50698 | isIdentifierPart | train | function isIdentifierPart(ch) {
// Generated by `tools/generate-identifier-regex.js`.
var NonAsciiIdentifierPartOnly = /[0-9_\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD801[\uDCA0-\uDCA9]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD803[\uDD24-\uDD27\uDD30-\uDD39\uDF46-\uDF50]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC66-\uDC6F\uDC7F-\uDC82\uDCB0-\uDCBA\uDCF0-\uDCF9\uDD00-\uDD02\uDD27-\uDD34\uDD36-\uDD3F\uDD45\uDD46\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDDC9-\uDDCC\uDDD0-\uDDD9\uDE2C-\uDE37\uDE3E\uDEDF-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF3B\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC35-\uDC46\uDC50-\uDC59\uDC5E\uDCB0-\uDCC3\uDCD0-\uDCD9\uDDAF-\uDDB5\uDDB8-\uDDC0\uDDDC\uDDDD\uDE30-\uDE40\uDE50-\uDE59\uDEAB-\uDEB7\uDEC0-\uDEC9\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDC2C-\uDC3A\uDCE0-\uDCE9\uDE01-\uDE0A\uDE33-\uDE39\uDE3B-\uDE3E\uDE47\uDE51-\uDE5B\uDE8A-\uDE99]|\uD807[\uDC2F-\uDC36\uDC38-\uDC3F\uDC50-\uDC59\uDC92-\uDCA7\uDCA9-\uDCB6\uDD31-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD45\uDD47\uDD50-\uDD59\uDD8A-\uDD8E\uDD90\uDD91\uDD93-\uDD97\uDDA0-\uDDA9\uDEF3-\uDEF6]|\uD81A[\uDE60-\uDE69\uDEF0-\uDEF4\uDF30-\uDF36\uDF50-\uDF59]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD82F[\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDCD0-\uDCD6\uDD44-\uDD4A\uDD50-\uDD59]|\uDB40[\uDD00-\uDDEF]/;
return isIdentifierStart(ch) ||
(ch >= 48 && ch <= 57) || // 0..9
((ch >= 0x80) && NonAsciiIdentifierPartOnly.test(fromCodePoint(ch)));
} | javascript | {
"resource": ""
} |
q50699 | Logger | train | function Logger ({
minimumLogLevel = null,
formatter = JsonFormatter,
useBearerRedactor = true,
useGlobalErrorHandler = true,
forceGlobalErrorHandler = false,
redactors = []
} = {}) {
const context = {
minimumLogLevel,
formatter,
events: new EventEmitter(),
contextPath: [],
keys: new Map()
}
if (useBearerRedactor) {
redactors.push(bearerRedactor(context))
}
if (useGlobalErrorHandler) {
registerErrorHandlers(context, forceGlobalErrorHandler)
}
context.redact = wrapRedact(context, redactors)
context.logger = {
handler: wrapHandler(context),
setMinimumLogLevel: wrapSetMinimumLogLevel(context),
events: context.events,
setKey: wrapSetKey(context),
...createLogger(context)
}
return context.logger
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.