_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 =... | 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.a... | 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(ob... | 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('=');
ke... | 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 member... | 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 = ... | 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',
n... | 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('flyingS... | 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, 0... | 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) {
... | 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 = newM... | 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(sync... | 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) {
... | 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 =... | 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,... | 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) {
ret... | 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 memb... | 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]
}... | 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... | 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(... | 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 MI... | 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)... | 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(th... | 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);
... | 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++;
}
... | 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.
re... | 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(th... | 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._totalAnalogPin... | 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._b... | 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);
... | 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 = sustainedPressIn... | 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(Boar... | 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.BEFOREDISCONN... | 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.... | 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: ... | 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._me... | 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._m... | 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... | 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,
... | 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-... | 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.userAgen... | 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_... | 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... | 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.requ... | 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... | 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... | 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 relatio... | 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(
'__findRelatio... | 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 fo... | 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 ||
status... | 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 || ''
}
... | 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 !== tru... | 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 ... | 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... | 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
compoundInclud... | 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.defini... | 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) {
re... | 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\u... | 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 M... | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.