_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q31100 | train | function(arr) {
return new stats.init(arguments.length > 1 ?
Array.prototype.slice.call(arguments, 0) :
arr);
} | javascript | {
"resource": ""
} | |
q31101 | train | function(fn) {
var arr = this.arr;
if (arr.length === undefined) {
// The wrapped array is a JSON object
for (var key in arr) {
this.arr[key] = fn.call(arr[key], arr[key], key, arr);
}
} else {
// The wrapped array is an array
for (var i = 0, l = this.arr.length; i < l; i++) {
this.arr[i] = fn.call(arr[i], arr[i], i, arr);
}
}
return this;
} | javascript | {
"resource": ""
} | |
q31102 | train | function(attr) {
var newArr = [];
if (this.arr.length === undefined) {
// The wrapped array is a JSON object
for (var key in arr) {
newArr.push(this.arr[key][attr]);
}
} else {
// The wrapped array is an array
for (var i = 0, l = this.arr.length; i < l; i++) {
newArr.push(this.arr[i][attr]);
}
}
return stats(newArr);
} | javascript | {
"resource": ""
} | |
q31103 | train | function(attr) {
// Get the numbers
var arr = this.arr;
// Go through each of the numbers and find the minimum
var minimum = attr == null ? arr[0] : arr[0][attr];
var minimumEl = attr == null ? arr[0] : arr[0];
stats(arr).each(function(num, index) {
if ((attr == null ? num : num[attr]) < minimum) {
minimum = attr == null ? num : num[attr];
minimumEl = num;
}
});
return minimumEl;
} | javascript | {
"resource": ""
} | |
q31104 | train | function(attr) {
// Get the numbers
var arr = this.arr;
// Go through each of the numbers and find the maximum
var maximum = attr == null ? arr[0] : arr[0][attr];
var maximumEl = attr == null ? arr[0] : arr[0];
stats(arr).each(function(num, index) {
if ((attr == null ? num : num[attr]) > maximum) {
maximum = attr == null ? num : num[attr];
maximumEl = num;
}
});
return maximumEl;
} | javascript | {
"resource": ""
} | |
q31105 | train | function() {
// Sort the numbers
var arr = this.clone().sort().toArray();
if (arr.length % 2 === 0) {
// There are an even number of elements in the array; the median
// is the average of the middle two
return (arr[arr.length / 2 - 1] + arr[arr.length / 2]) / 2;
} else {
// There are an odd number of elements in the array; the median
// is the middle one
return arr[(arr.length - 1) / 2];
}
} | javascript | {
"resource": ""
} | |
q31106 | train | function() {
// Handle the single element case
if (this.length == 1) {
return this.arr[0];
}
// Sort the numbers
var nums = this.clone().sort();
// The third quartile is the median of the upper half of the numbers
return nums.slice(Math.ceil(nums.size() / 2)).median();
} | javascript | {
"resource": ""
} | |
q31107 | train | function() {
// Get the mean
var mean = this.mean();
// Get a new stats object to work with
var nums = this.clone();
// Map each element of nums to the square of the element minus the
// mean
nums.map(function(num) {
return Math.pow(num - mean, 2);
});
// Return the standard deviation
return Math.sqrt(nums.sum() / (nums.size() - 1));
} | javascript | {
"resource": ""
} | |
q31108 | train | function() {
// Get the x and y coordinates
var xCoords = this.pluck('x');
var yCoords = this.pluck('y');
// Get the means for the x and y coordinates
var meanX = xCoords.mean();
var meanY = yCoords.mean();
// Get the standard deviations for the x and y coordinates
var stdDevX = xCoords.stdDev();
var stdDevY = yCoords.stdDev();
// Map each element to the difference of the element and the mean
// divided by the standard deviation
xCoords.map(function(num) {
return (num - meanX) / stdDevX;
});
yCoords.map(function(num) {
return (num - meanY) / stdDevY;
});
// Multiply each element in the x by the corresponding value in
// the y
var nums = this.clone().map(function(num, index) {
return xCoords.get(index) * yCoords.get(index);
});
// r is the sum of xCoords over the number of points minus 1
return nums.sum() / (nums.size() - 1);
} | javascript | {
"resource": ""
} | |
q31109 | train | function() {
// Get the x and y coordinates
var xCoords = this.pluck('x');
var yCoords = this.pluck('y');
// Get the means for the x and y coordinates
var meanX = xCoords.mean();
var meanY = yCoords.mean();
// Get the standard deviations for the x and y coordinates
var stdDevX = xCoords.stdDev();
var stdDevY = yCoords.stdDev();
// Calculate the correlation coefficient
var r = this.r();
// Calculate the slope
var slope = r * (stdDevY / stdDevX);
// Calculate the y-intercept
var yIntercept = meanY - slope * meanX;
return {
slope: slope,
yIntercept: yIntercept,
r: r
};
} | javascript | {
"resource": ""
} | |
q31110 | train | function() {
// Get y coordinates
var yCoords = this.pluck('y');
// Do a semi-log transformation of the coordinates
yCoords.map(function(num) {
return Math.log(num);
});
// Get a new stats object to work with that has the transformed data
var nums = this.clone().map(function(coord, index) {
return {
x: coord.x,
y: yCoords.get(index)
};
});
// Calculate the linear regression for the linearized data
var linReg = nums.linReg();
// Calculate the coefficient for the exponential equation
var coefficient = Math.pow(Math.E, linReg.yIntercept);
// Calculate the base for the exponential equation
var base = Math.pow(Math.E, linReg.slope);
return {
coefficient: coefficient,
base: base,
r: linReg.r
};
} | javascript | {
"resource": ""
} | |
q31111 | train | function() {
// Get y coordinates
var xCoords = this.pluck('x');
var yCoords = this.pluck('y');
// Do a log-log transformation of the coordinates
xCoords.map(function(num) {
return Math.log(num);
});
yCoords.map(function(num) {
return Math.log(num);
});
// Get a new stats object to work with that has the transformed data
var nums = this.clone().map(function(coord, index) {
return {
x: xCoords.get(index),
y: yCoords.get(index)
};
});
// Calculate the linear regression for the linearized data
var linReg = nums.linReg();
// Calculate the coefficient for the power equation
var coefficient = Math.pow(Math.E, linReg.yIntercept);
// Calculate the exponent for the power equation
var exponent = linReg.slope;
return {
coefficient: coefficient,
exponent: exponent,
r: linReg.r
};
} | javascript | {
"resource": ""
} | |
q31112 | train | function() {
// Create a new stats object to work with
var nums = this.clone();
// Go through each element and make the element the gcd of it
// and the element to its left
for (var i = 1; i < nums.size(); i++) {
nums.set(i, gcd(nums.get(i - 1), nums.get(i)));
}
// The gcd of all the numbers is now in the final element
return nums.get(nums.size() - 1);
} | javascript | {
"resource": ""
} | |
q31113 | train | function() {
// Create a new stats object to work with
var nums = this.clone();
// Go through each element and make the element the lcm of it
// and the element to its left
for (var i = 1; i < nums.size(); i++) {
nums.set(i, lcm(nums.get(i - 1), nums.get(i)));
}
// The lcm of all the numbers if now in the final element
return nums.get(nums.size() - 1);
} | javascript | {
"resource": ""
} | |
q31114 | gcd | train | function gcd(a, b) {
if (b === 0) {
return a;
}
return gcd(b, a - b * Math.floor(a / b));
} | javascript | {
"resource": ""
} |
q31115 | lcm | train | function lcm(a, b) {
// The least common multiple is the absolute value of the product of
// the numbers divided by the greatest common denominator
return Math.abs(a * b) / gcd(a, b);
} | javascript | {
"resource": ""
} |
q31116 | train | function (win) {
if (win == null) {
return null;
}
while ((win.API == null) && (win.parent != null) && (win.parent != win)) {
findAPITries++;
if (findAPITries > 7) {
return null;
}
win = win.parent;
}
return win.API;
} | javascript | {
"resource": ""
} | |
q31117 | dequeue | train | function dequeue(queue, item) {
queue[SIZE] -= 1
let done = false
item.action(() => {
if (done) {
return
}
done = true
if (item.next) {
dequeue(queue, item.next)
}
else {
assert(queue[TAIL] === item, "BROKEN")
queue[TAIL] = null
}
})
} | javascript | {
"resource": ""
} |
q31118 | _stdNormDensity | train | function _stdNormDensity(x)
{
return Math.pow(Math.E, -1 * Math.pow(x, 2) / 2) / Math.sqrt(2 * Math.PI);
} | javascript | {
"resource": ""
} |
q31119 | getDelta | train | function getDelta(s, k, t, v, r, callPut)
{
if(callPut === "call")
{
return _callDelta(s, k, t, v, r);
}
else // put
{
return _putDelta(s, k, t, v, r);
}
} | javascript | {
"resource": ""
} |
q31120 | _callDelta | train | function _callDelta(s, k, t, v, r)
{
var w = bs.getW(s, k, t, v, r);
var delta = null;
if(!isFinite(w))
{
delta = (s > k) ? 1 : 0;
}
else
{
delta = bs.stdNormCDF(w);
}
return delta;
} | javascript | {
"resource": ""
} |
q31121 | _putDelta | train | function _putDelta(s, k, t, v, r)
{
var delta = _callDelta(s, k, t, v, r) - 1;
return (delta == -1 && k == s) ? 0 : delta;
} | javascript | {
"resource": ""
} |
q31122 | getRho | train | function getRho(s, k, t, v, r, callPut, scale)
{
scale = scale || 100;
if(callPut === "call")
{
return _callRho(s, k, t, v, r) / scale;
}
else // put
{
return _putRho(s, k, t, v, r) / scale;
}
} | javascript | {
"resource": ""
} |
q31123 | _putRho | train | function _putRho(s, k, t, v, r)
{
var w = bs.getW(s, k, t, v, r);
if(!isNaN(w))
{
return -1 * k * t * Math.pow(Math.E, -1 * r * t) * bs.stdNormCDF(v * Math.sqrt(t) - w);
}
else
{
return 0;
}
} | javascript | {
"resource": ""
} |
q31124 | getVega | train | function getVega(s, k, t, v, r)
{
var w = bs.getW(s, k, t, v, r);
return (isFinite(w)) ? (s * Math.sqrt(t) * _stdNormDensity(w) / 100) : 0;
} | javascript | {
"resource": ""
} |
q31125 | getTheta | train | function getTheta(s, k, t, v, r, callPut, scale)
{
scale = scale || 365;
if(callPut === "call")
{
return _callTheta(s, k, t, v, r) / scale;
}
else // put
{
return _putTheta(s, k, t, v, r) / scale;
}
} | javascript | {
"resource": ""
} |
q31126 | _callTheta | train | function _callTheta(s, k, t, v, r)
{
var w = bs.getW(s, k, t, v, r);
if(isFinite(w))
{
return -1 * v * s * _stdNormDensity(w) / (2 * Math.sqrt(t)) - k * r * Math.pow(Math.E, -1 * r * t) * bs.stdNormCDF(w - v * Math.sqrt(t));
}
else
{
return 0;
}
} | javascript | {
"resource": ""
} |
q31127 | train | function() {
var sitemap = sm.createSitemap({
cacheTime: 600000,
hostname: url.resolve(this.config.get('pluginsConfig.sitemap.hostname'), '/'),
urls: urls
});
var xml = sitemap.toString();
return this.output.writeFile('sitemap.xml', xml);
} | javascript | {
"resource": ""
} | |
q31128 | Connection | train | function Connection (gridModule) {
try {
Connection.super_.apply(this, arguments);
RbnUtil.__copyProperties(this, gridModule);
this.validate();
this.connectionStub = '/' + this.endpoint + '/' + this.identifier;
} catch (err) {
throw err;
}
} | javascript | {
"resource": ""
} |
q31129 | train | function (spaceIdentifier, params) {
var path = this.constructPath(constants.SPACES, spaceIdentifier);
return this.Core.GET(path, params);
} | javascript | {
"resource": ""
} | |
q31130 | train | function (spaceIdentifier, data) {
var path;
if (data) {
path = this.constructPath(constants.SPACES, spaceIdentifier);
return this.Core.PATCH(path, data);
} else {
return this.rejectRequest('Bad Request: Space data is required');
}
} | javascript | {
"resource": ""
} | |
q31131 | train | function (spaceIdentifier, deviceIdentifier, params) {
var path;
if (spaceIdentifier) {
path = this.constructPath(constants.SPACES, spaceIdentifier, constants.DEVICES, deviceIdentifier);
return this.Core.GET(path, params);
} else {
return this.rejectRequest('Bad Request: A space identifier is required.');
}
} | javascript | {
"resource": ""
} | |
q31132 | train | function (spaceIdentifier, data) {
var path;
if (spaceIdentifier && data) {
path = this.constructPath(constants.SPACES, spaceIdentifier, constants.DEVICES);
return this.Core.POST(path, data);
} else {
return this.rejectRequest('Bad Request: A space identifier and device data are required');
}
} | javascript | {
"resource": ""
} | |
q31133 | train | function (spaceIdentifier, params) {
var path;
if (spaceIdentifier) {
path = this.constructPath(constants.SPACES, spaceIdentifier, constants.PRESENCE);
return this.Core.GET(path, params);
} else {
return this.rejectRequest('Bad Request: A space identifier is required.');
}
} | javascript | {
"resource": ""
} | |
q31134 | train | function (html) {
var sep = '----------------------------------------------------------';
console.log('\n' + sep);
console.log('markedejs: HTML OUT (markedejs.DEBUG = false to silence)');
console.log(sep);
console.log(html);
console.log(sep + '\n');
} | javascript | {
"resource": ""
} | |
q31135 | ifIsectAddToOutput | train | function ifIsectAddToOutput(ring0, edge0, ring1, edge1) {
var start0 = coord[ring0][edge0];
var end0 = coord[ring0][edge0+1];
var start1 = coord[ring1][edge1];
var end1 = coord[ring1][edge1+1];
var isect = intersect(start0, end0, start1, end1);
if (isect == null) return; // discard parallels and coincidence
frac0, frac1;
if (end0[0] != start0[0]) {
var frac0 = (isect[0]-start0[0])/(end0[0]-start0[0]);
} else {
var frac0 = (isect[1]-start0[1])/(end0[1]-start0[1]);
};
if (end1[0] != start1[0]) {
var frac1 = (isect[0]-start1[0])/(end1[0]-start1[0]);
} else {
var frac1 = (isect[1]-start1[1])/(end1[1]-start1[1]);
};
// There are roughly three cases we need to deal with.
// 1. If at least one of the fracs lies outside [0,1], there is no intersection.
if (isOutside(frac0) || isOutside(frac1)) {
return; // require segment intersection
}
// 2. If both are either exactly 0 or exactly 1, this is not an intersection but just
// two edge segments sharing a common vertex.
if (isBoundaryCase(frac0) && isBoundaryCase(frac1)){
if(! options.reportVertexOnVertex) return;
}
// 3. If only one of the fractions is exactly 0 or 1, this is
// a vertex-on-edge situation.
if (isBoundaryCase(frac0) || isBoundaryCase(frac1)){
if(! options.reportVertexOnEdge) return;
}
var key = isect;
var unique = !seen[key];
if (unique) {
seen[key] = true;
}
if (filterFn) {
output.push(filterFn(isect, ring0, edge0, start0, end0, frac0, ring1, edge1, start1, end1, frac1, unique));
} else {
output.push(isect);
}
} | javascript | {
"resource": ""
} |
q31136 | rbushTreeItem | train | function rbushTreeItem(ring, edge) {
var start = coord[ring][edge];
var end = coord[ring][edge+1];
if (start[0] < end[0]) {
var minX = start[0], maxX = end[0];
} else {
var minX = end[0], maxX = start[0];
};
if (start[1] < end[1]) {
var minY = start[1], maxY = end[1];
} else {
var minY = end[1], maxY = start[1];
}
return {minX: minX, minY: minY, maxX: maxX, maxY: maxY, ring: ring, edge: edge};
} | javascript | {
"resource": ""
} |
q31137 | padEnd | train | function padEnd(str, length) {
/* istanbul ignore next */
if (str.length >= length) return str;
return str + ' '.repeat(length - str.length);
} | javascript | {
"resource": ""
} |
q31138 | tableDimensions | train | function tableDimensions(metrics) {
const pointPad = UNIT.length + 2;
let name = 6;
let point = 5;
for (let i = 0; i < metrics.length; i++) {
const metric = metrics[i];
name = Math.max(name, metric.label.length + 2);
point = Math.max(
point,
numDigits(metric.avg) + pointPad,
numDigits(metric.min) + pointPad,
numDigits(metric.max) + pointPad
);
}
return {
name,
avg: point,
min: point,
max: point,
};
} | javascript | {
"resource": ""
} |
q31139 | divider | train | function divider(dimensions, type) {
let left = BORDER_RUD;
let right = BORDER_LUD;
let line = BORDER_HORZ;
let joint = BORDER_LRUD;
switch (type) {
case 'top':
left = BORDER_RD;
right = BORDER_LD;
joint = BORDER_LRD;
break;
case 'bottom':
left = BORDER_RU;
right = BORDER_LU;
joint = BORDER_LRU;
break;
case 'header':
left = BORDER_UD_DBL_R;
right = BORDER_UD_DBL_L;
line = BORDER_DBL_HORZ;
joint = BORDER_UD_DBL_LR;
break;
default: break;
}
const {
name,
avg,
min,
max,
} = dimensions;
return left
+ line.repeat(name)
+ joint
+ line.repeat(avg)
+ joint
+ line.repeat(min)
+ joint
+ line.repeat(max)
+ right
+ '\n';
} | javascript | {
"resource": ""
} |
q31140 | header | train | function header(dimensions) {
return divider(dimensions, 'top')
+ BORDER_VERT
+ BOLD + padEnd(' NAME', dimensions.name) + RESET
+ BORDER_VERT
+ BOLD + padEnd(' AVG', dimensions.avg) + RESET
+ BORDER_VERT
+ BOLD + padEnd(' MIN', dimensions.min) + RESET
+ BORDER_VERT
+ BOLD + padEnd(' MAX', dimensions.max) + RESET
+ BORDER_VERT
+ '\n'
+ divider(dimensions, 'header');
} | javascript | {
"resource": ""
} |
q31141 | row | train | function row(metric, dimensions, isTarget) {
let left = '';
let right = '';
if (isTarget) {
left = HIGHLIGHT;
right = RESET;
}
return BORDER_VERT
+ left + padEnd(' ' + metric.label, dimensions.name) + right
+ BORDER_VERT
+ left + padEnd(' ' + metric.avg + UNIT, dimensions.avg) + right
+ BORDER_VERT
+ left + padEnd(' ' + metric.min + UNIT, dimensions.min) + right
+ BORDER_VERT
+ left + padEnd(' ' + metric.max + UNIT, dimensions.max) + right
+ BORDER_VERT
+ '\n';
} | javascript | {
"resource": ""
} |
q31142 | report | train | function report(stream, metrics, thresholds) {
const target = (!elv(thresholds)) ? -1 : thresholds.target;
const dimensions = tableDimensions(metrics);
const border = divider(dimensions);
let value = header(dimensions);
for (let i = 0; i < metrics.length; i++) {
if (i > 0) value += border;
const metric = metrics[i];
value += row(metric, dimensions, i === target);
}
value += divider(dimensions, 'bottom');
value += '\n';
stream.write(value);
} | javascript | {
"resource": ""
} |
q31143 | findMany | train | function findMany(repository, options) {
const entityColumns = repository.metadata.columns.map((columnMetadata) => columnMetadata.propertyName);
const entityManyToOneRelationColumns = repository
.metadata
.relations
.filter((relationMetadata) => relationMetadata.relationType === 'many-to-one' || relationMetadata.relationType === 'one-to-one')
.map((relationMetadata) => relationMetadata.propertyName);
return function (source, args, context, info) {
return __awaiter(this, void 0, void 0, function* () {
const selectedColumns = Object.keys(graphqlFields(info));
const selectQueryBuilder = repository.createQueryBuilder(repository.metadata.name.toLowerCase());
/** Select **/
const selectFactory = new select_factory_1.SelectFactory(selectQueryBuilder);
selectFactory
.select(selectedColumns.filter((select) => entityColumns.includes(select)));
/** Where **/
const whereFactory = new where_factory_1.WhereFactory(selectQueryBuilder, entityManyToOneRelationColumns);
whereFactory
.where(lodash_1.get(args, 'filter', {}));
/** Joins **/
const joinsFactory = new joins_factory_1.JoinsFactory(selectQueryBuilder);
joinsFactory
.join(selectedColumns
.filter((select) => entityManyToOneRelationColumns.includes(select))
.reduce((selectedRelationColumns, selectedRelationColumn) => {
selectedRelationColumns[selectQueryBuilder.alias] = selectedRelationColumn;
return selectedRelationColumns;
}, {}))
.join(whereFactory.selectedManyToOneOrOneToOneRelationColumns);
/** Pagination **/
const paginateFactory = new paginate_factory_1.PaginateFactory(selectQueryBuilder);
paginateFactory
.paginate(lodash_1.get(args, 'pagination', {}));
/** Order by **/
const orderFactory = new order_factory_1.OrderFactory(selectQueryBuilder);
orderFactory
.order(lodash_1.get(args, 'orderBy', []));
/** Extend **/
if (lodash_1.get(options, 'extend')) {
yield options.extend(selectQueryBuilder);
}
/** Execute get many method **/
return yield selectQueryBuilder.getMany();
});
};
} | javascript | {
"resource": ""
} |
q31144 | train | function (data) {
var path;
if (data) {
path = this.constructPath(constants.EVENTS);
return this.Places.POST(path, data);
} else {
return this.rejectRequest('Bad Request: A data object is required.');
}
} | javascript | {
"resource": ""
} | |
q31145 | listenEmpty | train | function listenEmpty( handler, isFunction, emitter ){
const errors = [];
if( isFunction ){
try {
handler.call( emitter );
} catch( error ){
errors.push( error );
}
} else {
const length = handler.length,
listeners = handler.slice();
let index = 0;
for( ; index < length; index += 1 ){
try {
listeners[ index ].call( emitter );
} catch( error ){
errors.push( error );
}
}
}
if( errors.length ){
emitErrors( emitter, errors );
}
} | javascript | {
"resource": ""
} |
q31146 | toEmitter | train | function toEmitter( selection, target ){
// Apply the entire Emitter API
if( selection === API ){
asEmitter.call( target );
// Apply only the selected API methods
} else {
let index, key, mapping, names, value;
if( typeof selection === 'string' ){
names = selection.split( ' ' );
mapping = API;
} else {
names = Object.keys( selection );
mapping = selection;
}
index = names.length;
while( index-- ){
key = names[ index ];
value = mapping[ key ];
target[ key ] = typeof value === 'function' ?
value :
API[ value ];
}
}
} | javascript | {
"resource": ""
} |
q31147 | train | function (identifier, params) {
var path = this.constructPath(constants.DEVICE_MANIFESTS, identifier);
return this.Core.GET(path, params);
} | javascript | {
"resource": ""
} | |
q31148 | train | function (data) {
var path;
if (data) {
path = this.constructPath(constants.DEVICE_MANIFESTS);
return this.Core.POST(path, data);
} else {
return this.rejectRequest('Bad Request: A data object is required');
}
} | javascript | {
"resource": ""
} | |
q31149 | train | function (identifier, data) {
var path;
if (identifier && data) {
path = this.constructPath(constants.DEVICE_MANIFESTS, identifier);
return this.Core.PATCH(path, data);
} else {
return this.rejectRequest('Bad Request: A device manifest identifier and a data object are required.');
}
} | javascript | {
"resource": ""
} | |
q31150 | train | function (identifier) {
var path;
if (identifier) {
path = this.constructPath(constants.DEVICE_MANIFESTS, identifier);
return this.Core.DELETE(path);
} else {
return this.rejectRequest('Bad Request: A device manifest identifier is required.');
}
} | javascript | {
"resource": ""
} | |
q31151 | train | function (deviceManifestIdentifier, feedIdentifier, params) {
var path;
if (deviceManifestIdentifier) {
path = this.constructPath(constants.DEVICE_MANIFESTS, deviceManifestIdentifier,
constants.FEEDS, feedIdentifier);
return this.Core.GET(path, params);
} else {
return this.rejectRequest('Bad Request: A device manifest identifier is required.');
}
} | javascript | {
"resource": ""
} | |
q31152 | train | function (deviceManifestIdentifier, data) {
var path;
if (deviceManifestIdentifier) {
path = this.constructPath(constants.DEVICE_MANIFESTS, deviceManifestIdentifier, constants.FEEDS);
return this.Core.POST(path, data);
} else {
return this.rejectRequest('Bad Request: A device manifest identifier and a data object are required.');
}
} | javascript | {
"resource": ""
} | |
q31153 | train | function (deviceManifestIdentifier, feedIdentifier, data) {
var path,
rejectMsg;
if (deviceManifestIdentifier && feedIdentifier && data) {
path = this.constructPath(constants.DEVICE_MANIFESTS, deviceManifestIdentifier,
constants.FEEDS, feedIdentifier);
return this.Core.PATCH(path, data);
} else {
rejectMsg = 'Bad Request: A device manifest identifier, a feed identifier and a data object are required.';
return this.rejectRequest(rejectMsg);
}
} | javascript | {
"resource": ""
} | |
q31154 | train | function (deviceManifestIdentifier, feedIdentifier) {
var path;
if (deviceManifestIdentifier && feedIdentifier) {
path = this.constructPath(constants.DEVICE_MANIFESTS, deviceManifestIdentifier,
constants.FEEDS, feedIdentifier);
return this.Core.DELETE(path);
} else {
return this.rejectRequest('Bad Request: A device manifest identifier and a feed identifier are required.');
}
} | javascript | {
"resource": ""
} | |
q31155 | train | function (deviceManifestIdentifier, deviceIdentifier, params) {
var path;
if (deviceManifestIdentifier) {
path = this.constructPath(constants.DEVICE_MANIFESTS, deviceManifestIdentifier,
constants.DEVICES, deviceIdentifier);
return this.Core.GET(path, params);
} else {
return this.rejectRequest('Bad Request: A device manifest identifier is required.');
}
} | javascript | {
"resource": ""
} | |
q31156 | train | function (identifier, params) {
var path = this.constructPath(constants.DEVICES, identifier);
return this.Core.GET(path, params);
} | javascript | {
"resource": ""
} | |
q31157 | train | function (identifier) {
var path;
if (identifier) {
path = this.constructPath(constants.DEVICES, identifier);
return this.Core.DELETE(path);
} else {
return this.rejectRequest('Bad Request: A device identifier is required.');
}
} | javascript | {
"resource": ""
} | |
q31158 | train | function (deviceIdentifier, identifierURN, params) {
var path;
if (deviceIdentifier) {
path = this.constructPath(constants.DEVICES, deviceIdentifier, constants.IDENTIFIERS, identifierURN);
return this.Core.GET(path, params);
} else {
return this.rejectRequest('Bad Request: A device identifier is required.');
}
} | javascript | {
"resource": ""
} | |
q31159 | train | function (deviceIdentifier, data) {
var path;
if (deviceIdentifier) {
path = this.constructPath(constants.DEVICES, deviceIdentifier, constants.IDENTIFIERS);
return this.Core.POST(path, data);
} else {
return this.rejectRequest('Bad Request: A device identifier and a data object are required.');
}
} | javascript | {
"resource": ""
} | |
q31160 | train | function (deviceIdentifier, identifierUrn, data) {
var path;
if (deviceIdentifier) {
path = this.constructPath(constants.DEVICES, deviceIdentifier, constants.IDENTIFIERS, identifierUrn);
return this.Core.PATCH(path, data);
} else {
return this.rejectRequest('Bad Request: A device identifier, an identifier id and a data object are required.');
}
} | javascript | {
"resource": ""
} | |
q31161 | train | function (deviceIdentifier, identifierUrn) {
var path;
if (deviceIdentifier && identifierUrn) {
path = this.constructPath(constants.DEVICES, deviceIdentifier, constants.IDENTIFIERS, identifierUrn);
return this.Core.DELETE(path);
} else {
return this.rejectRequest('Bad Request: A device identifier and an identifier id are required.');
}
} | javascript | {
"resource": ""
} | |
q31162 | train | function (deviceIdentifier, channelIdentifier, params) {
var path;
if (deviceIdentifier) {
path = this.constructPath(constants.DEVICES, deviceIdentifier, constants.CHANNELS, channelIdentifier);
return this.Core.GET(path, params);
} else {
return this.rejectRequest('Bad Request: A device identifier is required.');
}
} | javascript | {
"resource": ""
} | |
q31163 | train | function (deviceIdentifier, channelIdentifier, data) {
var path,
rejectMsg;
if (deviceIdentifier && channelIdentifier && data) {
path = this.constructPath(constants.DEVICES, deviceIdentifier, constants.CHANNELS, channelIdentifier);
return this.Core.PATCH(path, data);
} else {
rejectMsg = 'Bad Request: A device identifier, a feed identifier and a data object are required.';
return this.rejectRequest(rejectMsg);
}
} | javascript | {
"resource": ""
} | |
q31164 | train | function (deviceIdentifier, channelIdentifier) {
var path;
if (deviceIdentifier && channelIdentifier) {
path = this.constructPath(constants.DEVICES, deviceIdentifier, constants.CHANNELS, channelIdentifier);
return this.Core.DELETE(path);
} else {
return this.rejectRequest('Bad Request: A device identifier and a channel identifier are required.');
}
} | javascript | {
"resource": ""
} | |
q31165 | train | function (identifier, params) {
var path = this.constructPath(constants.CHANNELS, identifier);
return this.Core.GET(path, params);
} | javascript | {
"resource": ""
} | |
q31166 | train | function (data) {
var path;
if (data) {
path = this.constructPath(constants.CHANNELS);
return this.Core.POST(path, data);
} else {
return this.rejectRequest('Bad Request: A data object is required.');
}
} | javascript | {
"resource": ""
} | |
q31167 | train | function (identifier) {
var path;
if (identifier) {
path = this.constructPath(constants.CHANNELS, identifier);
return this.Core.DELETE(path);
} else {
return this.rejectRequest('Bad Request: A channel identifier is required.');
}
} | javascript | {
"resource": ""
} | |
q31168 | train | function (channelIdentifier, dataIdentifier, params) {
var path;
if (channelIdentifier) {
path = this.constructPath(constants.CHANNELS, channelIdentifier, constants.DATA, dataIdentifier);
return this.Core.GET(path, params);
} else {
return this.rejectRequest('Bad Request: A channel identifier is required.');
}
} | javascript | {
"resource": ""
} | |
q31169 | train | function (channelIdentifier, dataIdentifier) {
var path;
if (channelIdentifier && dataIdentifier) {
path = this.constructPath(constants.CHANNELS, channelIdentifier, constants.DATA, dataIdentifier);
return this.Core.DELETE(path);
} else {
return this.rejectRequest('Bad Request: A channel identifier and a data point identifier are required.');
}
} | javascript | {
"resource": ""
} | |
q31170 | train | function (channelIdentifier, triggerIdentifier, params) {
var path;
if (channelIdentifier) {
path = this.constructPath(constants.CHANNELS, channelIdentifier, constants.TRIGGERS, triggerIdentifier);
return this.Core.GET(path, params);
} else {
return this.rejectRequest('Bad Request: A channel identifier is required.');
}
} | javascript | {
"resource": ""
} | |
q31171 | train | function (channelIdentifier, data) {
var path;
if (channelIdentifier) {
path = this.constructPath(constants.CHANNELS, channelIdentifier, constants.TRIGGERS);
return this.Core.POST(path, data);
} else {
return this.rejectRequest('Bad Request: A channel identifier and a data object are required.');
}
} | javascript | {
"resource": ""
} | |
q31172 | train | function (channelIdentifier, triggerIdentifier, data) {
var path,
rejectMsg;
if (channelIdentifier && triggerIdentifier && data) {
path = this.constructPath(constants.CHANNELS, channelIdentifier, constants.TRIGGERS, triggerIdentifier);
return this.Core.PATCH(path, data);
} else {
rejectMsg = 'Bad Request: A channel identifier, a feed identifier and a trigger object are required.';
return this.rejectRequest(rejectMsg);
}
} | javascript | {
"resource": ""
} | |
q31173 | train | function (channelIdentifier, triggerIdentifier) {
var path;
if (channelIdentifier && triggerIdentifier) {
path = this.constructPath(constants.CHANNELS, channelIdentifier, constants.TRIGGERS, triggerIdentifier);
return this.Core.DELETE(path);
} else {
return this.rejectRequest('Bad Request: A channel identifier and a trigger identifier are required.');
}
} | javascript | {
"resource": ""
} | |
q31174 | train | function (orgIdOrSlug, params) {
var path = this.constructPath(constants.ORGANIZATIONS, orgIdOrSlug);
return this.Core.GET(path, params);
} | javascript | {
"resource": ""
} | |
q31175 | train | function (orgIdOrSlug, data) {
var path;
if (orgIdOrSlug && data) {
path = this.constructPath(constants.ORGANIZATIONS, orgIdOrSlug);
return this.Core.PATCH(path, data);
} else {
return this.rejectRequest('Bad Request: An organization id or slug and a data object are required.');
}
} | javascript | {
"resource": ""
} | |
q31176 | train | function (orgIdOrSlug) {
var path;
if (orgIdOrSlug) {
path = this.constructPath(constants.ORGANIZATIONS, orgIdOrSlug);
return this.Core.DELETE(path);
} else {
return this.rejectRequest('Bad Request: An organization id or slug is required.');
}
} | javascript | {
"resource": ""
} | |
q31177 | train | function (orgIdOrSlug, userId, params) {
var path;
if (orgIdOrSlug) {
path = this.constructPath(constants.ORGANIZATIONS, orgIdOrSlug, constants.USERS, userId);
return this.Core.GET(path);
} else {
return this.rejectRequest('Bad Request: An organization id or slug is required.');
}
} | javascript | {
"resource": ""
} | |
q31178 | train | function (orgIdOrSlug, userId, data) {
var path,
rejectMsg;
if (orgIdOrSlug && userId && data) {
path = this.constructPath(constants.ORGANIZATIONS, orgIdOrSlug, constants.USERS, userId);
return this.Core.PATCH(path, data);
} else {
rejectMsg = 'Bad Request: An organization id or slug and a user id and data is required.';
return this.rejectRequest(rejectMsg);
}
} | javascript | {
"resource": ""
} | |
q31179 | train | function (orgIdOrSlug, data) {
var path,
rejectMsg;
if (orgIdOrSlug && data) {
path = this.constructPath(constants.ORGANIZATIONS, orgIdOrSlug, constants.USERS);
return this.Core.POST(path, data);
} else {
rejectMsg = 'Bad Request: An organization id or slug and data is required.';
return this.rejectRequest(rejectMsg);
}
} | javascript | {
"resource": ""
} | |
q31180 | _bytes | train | function _bytes (n, fn) {
assert(!this._parserCallback, 'there is already a "callback" set!');
assert(isFinite(n) && n > 0, 'can only buffer a finite number of bytes > 0, got "' + n + '"');
if (!this._parserInit) init(this);
debug('buffering %o bytes', n);
this._parserBytesLeft = n;
this._parserCallback = fn;
this._parserState = BUFFERING;
} | javascript | {
"resource": ""
} |
q31181 | _skipBytes | train | function _skipBytes (n, fn) {
assert(!this._parserCallback, 'there is already a "callback" set!');
assert(n > 0, 'can only skip > 0 bytes, got "' + n + '"');
if (!this._parserInit) init(this);
debug('skipping %o bytes', n);
this._parserBytesLeft = n;
this._parserCallback = fn;
this._parserState = SKIPPING;
} | javascript | {
"resource": ""
} |
q31182 | _passthrough | train | function _passthrough (n, fn) {
assert(!this._parserCallback, 'There is already a "callback" set!');
assert(n > 0, 'can only pass through > 0 bytes, got "' + n + '"');
if (!this._parserInit) init(this);
debug('passing through %o bytes', n);
this._parserBytesLeft = n;
this._parserCallback = fn;
this._parserState = PASSTHROUGH;
} | javascript | {
"resource": ""
} |
q31183 | process | train | function process (stream, chunk, output, fn) {
stream._parserBytesLeft -= chunk.length;
debug('%o bytes left for stream piece', stream._parserBytesLeft);
if (stream._parserState === BUFFERING) {
// buffer
stream._parserBuffers.push(chunk);
stream._parserBuffered += chunk.length;
} else if (stream._parserState === PASSTHROUGH) {
// passthrough
output(chunk);
}
// don't need to do anything for the SKIPPING case
if (0 === stream._parserBytesLeft) {
// done with stream "piece", invoke the callback
var cb = stream._parserCallback;
if (cb && stream._parserState === BUFFERING && stream._parserBuffers.length > 1) {
chunk = Buffer.concat(stream._parserBuffers, stream._parserBuffered);
}
if (stream._parserState !== BUFFERING) {
chunk = null;
}
stream._parserCallback = null;
stream._parserBuffered = 0;
stream._parserState = INIT;
stream._parserBuffers.splice(0); // empty
if (cb) {
var args = [];
if (chunk) {
// buffered
args.push(chunk);
} else {
// passthrough
}
if (output) {
// on a Transform stream, has "output" function
args.push(output);
}
var async = cb.length > args.length;
if (async) {
args.push(trampoline(fn));
}
// invoke cb
var rtn = cb.apply(stream, args);
if (!async || fn === rtn) return fn;
}
} else {
// need more bytes
return fn;
}
} | javascript | {
"resource": ""
} |
q31184 | trampoline | train | function trampoline (fn) {
return function () {
var result = fn.apply(this, arguments);
while ('function' == typeof result) {
result = result();
}
return result;
};
} | javascript | {
"resource": ""
} |
q31185 | RobinApi | train | function RobinApi (accessToken, coreUrl, placesUrl) {
if (accessToken) {
RobinApi.super_.apply(this, arguments);
this.setAccessToken(accessToken);
this.setupCore(coreUrl);
this.setupPlaces(placesUrl);
this.loadApiModules();
} else {
throw new TypeError('The access token is missing or malformed');
}
} | javascript | {
"resource": ""
} |
q31186 | train | function (appIdOrSlug, params) {
var path = this.constructPath(constants.APPS, appIdOrSlug);
return this.Core.GET(path, params);
} | javascript | {
"resource": ""
} | |
q31187 | train | function (appIdOrSlug, data) {
var path;
if (appIdOrSlug && data) {
path = this.constructPath(constants.APPS, appIdOrSlug);
return this.Core.POST(path, data);
} else {
return this.rejectRequest('Bad Request: An app id or slug and a data object are required.');
}
} | javascript | {
"resource": ""
} | |
q31188 | train | function (appIdOrSlug) {
var path;
if (appIdOrSlug) {
path = this.constructPath(constants.APPS, appIdOrSlug);
return this.Core.DELETE(path);
} else {
return this.rejectRequest('Bad Request: An app id or slug is required.');
}
} | javascript | {
"resource": ""
} | |
q31189 | getType | train | function getType (val) {
if (val === null) {
return 'null'
} else if (val === void 0) {
return 'undefined'
}
return Object.prototype.toString.call(val)
.replace(/^\[.+\s(.+?)]$/, '$1')
.toLowerCase()
} | javascript | {
"resource": ""
} |
q31190 | Value | train | function Value (val, parent, opts) {
var obj = Object.create(Value.prototype)
opts = opts || {}
obj.value = val
obj.parent = parent
obj.type = getType(val)
obj.key = opts.key
obj.length = opts.length !== undefined ? opts.length : (val && val.length)
return obj
} | javascript | {
"resource": ""
} |
q31191 | traverse | train | function traverse (value, v) {
var state = {}
var visitor = v.visitor
var seen = []
/**
* Recursively walk the value, dispatching visitor methods as values are encountered.
*
* @param {*} val Value
* @param {Value|null} parent Parent value
* @param {object} [opts] Additional options
*/
function traverseValue (val, parent, opts) {
var wrapper = Value(val, parent, opts)
var enterFn = wrapper.type + 'Enter'
var exitFn = wrapper.type + 'Exit'
var keys
if (wrapper.type === 'object' || wrapper.type === 'array') {
if (seen.indexOf(wrapper.value) >= 0) {
wrapper.isCircularRef = true
}
seen.push(wrapper.value)
}
if (wrapper.type === 'object') {
keys = Object.keys(wrapper.value).sort()
wrapper.length = keys.length
}
if (visitor[enterFn]) {
visitor[enterFn](wrapper, state)
} else if (visitor.otherEnter) {
visitor.otherEnter(wrapper, state)
}
switch (wrapper.type) {
case 'array':
if (!wrapper.isCircularRef) {
wrapper.value.forEach(function (child, i) {
traverseValue(child, wrapper, { key: i })
})
}
break
case 'object':
if (!wrapper.isCircularRef) {
keys.forEach(function (key) {
traverseValue(wrapper.value[key], wrapper, { key: key })
})
}
break
default:
/* do nothing */
break
}
if (visitor[exitFn]) {
visitor[exitFn](wrapper, state)
}
if (wrapper.type === 'object' || wrapper.type === 'array') {
seen.pop()
}
}
if (v.pre) { v.pre.call(null, state) }
traverseValue(value, null, null)
if (v.post) { v.post.call(null, state) }
} | javascript | {
"resource": ""
} |
q31192 | prettyPrintVisitor | train | function prettyPrintVisitor (pp, spaces) {
var visitor = {}
visitor.pre = function (state) {
state.result = ''
state.depth = 0
}
visitor.visitor = {
arrayEnter: function (val, state) {
if (val.key !== undefined) {
state.result += repeat(state.depth * spaces, ' ')
if (val.parent.type === 'object') {
state.result += "'" + val.key + "': "
}
}
if (val.isCircularRef) {
state.result += '[Circular]\n'
return
} else if (val.length === 0) {
state.result += '[]\n'
return
}
state.result += '[\n'
state.depth += 1
},
arrayExit: function (val, state) {
if (val.length === 0 || val.isCircularRef) { return }
state.depth -= 1
state.result += repeat(state.depth * spaces, ' ') + ']\n'
},
objectEnter: function (val, state) {
if (val.key !== undefined) {
state.result += repeat(state.depth * spaces, ' ')
if (val.parent.type === 'object') {
state.result += "'" + val.key + "': "
}
}
if (val.isCircularRef) {
state.result += '[Circular]\n'
return
} else if (val.length === 0) {
state.result += '{}\n'
return
}
state.result += '{\n'
state.depth += 1
},
objectExit: function (val, state) {
if (val.length === 0 || val.isCircularRef) { return }
state.depth -= 1
state.result += repeat(state.depth * spaces, ' ') + '}\n'
},
stringEnter: function (val, state) {
if (val.parent === null) {
state.result += pp(val.value).slice(1, -1)
return
}
state.result += repeat(state.depth * spaces, ' ')
if (val.parent.type === 'object') {
state.result += "'" + val.key + "': "
}
state.result += pp(val.value) + '\n'
},
otherEnter: function (val, state) {
state.result += repeat(state.depth * spaces, ' ')
if (val.key !== undefined && val.parent.type === 'object') {
state.result += "'" + val.key + "': "
}
state.result += pp(val.value) + '\n'
}
}
visitor.post = function (state) {
visitor.result = state.result.trim()
}
return visitor
} | javascript | {
"resource": ""
} |
q31193 | createStringifier | train | function createStringifier (pp, spaces) {
return function stringify (value) {
var visitor = prettyPrintVisitor(pp, spaces)
traverse(value, visitor)
return visitor.result
}
} | javascript | {
"resource": ""
} |
q31194 | isDiffable | train | function isDiffable (val) {
switch (getType(val)) {
case 'array':
case 'object':
return true
case 'string':
return val.length >= 40 || (val.trim().match(/\n/g) || []).length >= 1
default:
return false
}
} | javascript | {
"resource": ""
} |
q31195 | lpad | train | function lpad (str, width) {
while (String(str).length < width) {
str = ' ' + str
}
return str
} | javascript | {
"resource": ""
} |
q31196 | unifiedDiff | train | function unifiedDiff (actual, expected, formatAdd, formatRem) {
return [
formatAdd('+ expected'),
formatRem('- actual'),
''
]
.concat(
diff.createPatch('string', actual, expected)
.split('\n')
.slice(4)
.filter(function (line) {
return line[0] === '+' || line[0] === '-'
})
.map(function (line) {
return line[0] === '+' ? formatAdd(line) : formatRem(line)
})
)
.join('\n')
} | javascript | {
"resource": ""
} |
q31197 | formatLinesWith | train | function formatLinesWith (formatter, str) {
return str
.split('\n')
.map(function (line) {
return line.length ? formatter(line) : ''
})
.join('\n')
} | javascript | {
"resource": ""
} |
q31198 | inlineDiff | train | function inlineDiff (actual, expected, formatAdd, formatRem) {
var result = diff.diffWordsWithSpace(actual, expected)
.map(function (line, idx) {
if (line.added) { return formatLinesWith(formatAdd, line.value) }
return line.removed
? formatLinesWith(formatRem, line.value)
: line.value
})
.join('')
var lines = result.split('\n')
if (lines.length > 4) {
result = lines
.map(function (line, idx) {
return lpad(idx + 1, String(lines.length).length) + ' | ' + line
})
.join('\n')
}
return formatRem('actual') + ' ' + formatAdd('expected') + '\n\n' + result
} | javascript | {
"resource": ""
} |
q31199 | Mql | train | function Mql(query, values){
var self = this;
if(dynamicMatch){
var mql = dynamicMatch.call(window, query);
this.matches = mql.matches;
this.media = mql.media;
// TODO: is there a time it makes sense to remove this listener?
mql.addListener(update);
} else {
this.matches = staticMatch(query, values);
this.media = query;
}
this.addListener = addListener;
this.removeListener = removeListener;
this.dispose = dispose;
function addListener(listener){
if(mql){
mql.addListener(listener);
}
}
function removeListener(listener){
if(mql){
mql.removeListener(listener);
}
}
// update ourselves!
function update(evt){
self.matches = evt.matches;
self.media = evt.media;
}
function dispose(){
mql.removeListener(update);
}
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.