_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q5900
|
sortReceiversAndHighlight
|
train
|
function sortReceiversAndHighlight(receiverSignature) {
let trs = Array.from(tbody.getElementsByTagName('tr'));
let sortedFragment = document.createDocumentFragment();
trs.sort(sortFunction);
trs.forEach(function(tr) {
if(tr.id === receiverSignature) {
tr.setAttribute('class', 'monospace animated-highlight-reelyactive');
}
else {
tr.setAttribute('class', 'monospace');
}
sortedFragment.appendChild(tr);
});
tbody.appendChild(sortedFragment);
}
|
javascript
|
{
"resource": ""
}
|
q5901
|
train
|
function(ev, callback, context) {
var calls = this._callbacks || (this._callbacks = {});
var list = calls[ev] || (calls[ev] = []);
list.push([callback, context]);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q5902
|
train
|
function(ev, callback) {
var calls;
if (!ev) {
this._callbacks = {};
} else if (calls = this._callbacks) {
if (!callback) {
calls[ev] = [];
} else {
var list = calls[ev];
if (!list) return this;
for (var i = 0, l = list.length; i < l; i++) {
if (list[i] && callback === list[i][0]) {
list[i] = null;
break;
}
}
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q5903
|
train
|
function(eventName) {
var list, calls, ev, callback, args;
var both = 2;
if (!(calls = this._callbacks)) return this;
while (both--) {
ev = both ? eventName : 'all';
if (list = calls[ev]) {
for (var i = 0, l = list.length; i < l; i++) {
if (!(callback = list[i])) {
list.splice(i, 1); i--; l--;
} else {
args = both ? Array.prototype.slice.call(arguments, 1) : arguments;
callback[0].apply(callback[1] || this, args);
}
}
}
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q5904
|
train
|
function(options) {
options || (options = {});
if (this.isNew()) return this.trigger('destroy', this, this.collection, options);
var model = this;
var success = options.success;
options.success = function(resp) {
model.trigger('destroy', model, model.collection, options);
if (success) success(model, resp);
};
options.error = wrapError(options.error, model, options);
return (this.sync || Backbone.sync).call(this, 'delete', this, options);
}
|
javascript
|
{
"resource": ""
}
|
|
q5905
|
train
|
function(models, options) {
if (_.isArray(models)) {
for (var i = 0, l = models.length; i < l; i++) {
this._remove(models[i], options);
}
} else {
this._remove(models, options);
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q5906
|
train
|
function(models, options) {
models || (models = []);
options || (options = {});
this.each(this._removeReference);
this._reset();
this.add(models, {silent: true});
if (!options.silent) this.trigger('reset', this, options);
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q5907
|
train
|
function(model, options) {
var coll = this;
options || (options = {});
model = this._prepareModel(model, options);
if (!model) return false;
var success = options.success;
options.success = function(nextModel, resp, xhr) {
coll.add(nextModel, options);
if (success) success(nextModel, resp, xhr);
};
model.save(null, options);
return model;
}
|
javascript
|
{
"resource": ""
}
|
|
q5908
|
train
|
function(model, options) {
if (!(model instanceof Backbone.Model)) {
var attrs = model;
model = new this.model(attrs, {collection: this});
if (model.validate && !model._performValidation(attrs, options)) model = false;
} else if (!model.collection) {
model.collection = this;
}
return model;
}
|
javascript
|
{
"resource": ""
}
|
|
q5909
|
train
|
function(model, options) {
options || (options = {});
model = this.getByCid(model) || this.get(model);
if (!model) return null;
delete this._byId[model.id];
delete this._byCid[model.cid];
this.models.splice(this.indexOf(model), 1);
this.length--;
if (!options.silent) model.trigger('remove', model, this, options);
this._removeReference(model);
return model;
}
|
javascript
|
{
"resource": ""
}
|
|
q5910
|
train
|
function(fragment, triggerRoute) {
var frag = (fragment || '').replace(hashStrip, '');
if (this.fragment == frag || this.fragment == decodeURIComponent(frag)) return;
if (this._hasPushState) {
var loc = window.location;
if (frag.indexOf(this.options.root) != 0) frag = this.options.root + frag;
this.fragment = frag;
window.history.pushState({}, document.title, loc.protocol + '//' + loc.host + frag);
} else {
window.location.hash = this.fragment = frag;
if (this.iframe && (frag != this.getFragment(this.iframe.location.hash))) {
this.iframe.document.open().close();
this.iframe.location.hash = frag;
}
}
if (triggerRoute) this.loadUrl(fragment);
}
|
javascript
|
{
"resource": ""
}
|
|
q5911
|
train
|
function(object) {
if (!(object && object.url)) return null;
return _.isFunction(object.url) ? object.url() : object.url;
}
|
javascript
|
{
"resource": ""
}
|
|
q5912
|
train
|
function(string) {
return string.replace(/&(?!\w+;|#\d+;|#x[\da-f]+;)/gi, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''').replace(/\//g,'/');
}
|
javascript
|
{
"resource": ""
}
|
|
q5913
|
eq
|
train
|
function eq(a, b, stack) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
if (a === b) return a !== 0 || 1 / a == 1 / b;
// A strict comparison is necessary because `null == undefined`.
if (a == null || b == null) return a === b;
// Unwrap any wrapped objects.
if (a._chain) a = a._wrapped;
if (b._chain) b = b._wrapped;
// Invoke a custom `isEqual` method if one is provided.
if (a.isEqual && _.isFunction(a.isEqual)) return a.isEqual(b);
if (b.isEqual && _.isFunction(b.isEqual)) return b.isEqual(a);
// Compare `[[Class]]` names.
var className = toString.call(a);
if (className != toString.call(b)) return false;
switch (className) {
// Strings, numbers, dates, and booleans are compared by value.
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return a == String(b);
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
// other numeric values.
return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a == +b;
// RegExps are compared by their source patterns and flags.
case '[object RegExp]':
return a.source == b.source &&
a.global == b.global &&
a.multiline == b.multiline &&
a.ignoreCase == b.ignoreCase;
}
if (typeof a != 'object' || typeof b != 'object') return false;
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
var length = stack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (stack[length] == a) return true;
}
// Add the first object to the stack of traversed objects.
stack.push(a);
var size = 0, result = true;
// Recursively compare objects and arrays.
if (className == '[object Array]') {
// Compare array lengths to determine if a deep comparison is necessary.
size = a.length;
result = size == b.length;
if (result) {
// Deep compare the contents, ignoring non-numeric properties.
while (size--) {
// Ensure commutative equality for sparse arrays.
if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break;
}
}
} else {
// Objects with different constructors are not equivalent.
if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) return false;
// Deep compare objects.
for (var key in a) {
if (hasOwnProperty.call(a, key)) {
// Count the expected number of properties.
size++;
// Deep compare each member.
if (!(result = hasOwnProperty.call(b, key) && eq(a[key], b[key], stack))) break;
}
}
// Ensure that both objects contain the same number of properties.
if (result) {
for (key in b) {
if (hasOwnProperty.call(b, key) && !(size--)) break;
}
result = !size;
}
}
// Remove the first object from the stack of traversed objects.
stack.pop();
return result;
}
|
javascript
|
{
"resource": ""
}
|
q5914
|
updateNode
|
train
|
function updateNode(node, content, append) {
append = append || false;
while(!append && node.firstChild) {
node.removeChild(node.firstChild);
}
if(content instanceof Element) {
node.appendChild(content);
}
else if(content instanceof Array) {
content.forEach(function(element) {
node.appendChild(element);
});
}
else {
node.textContent = content;
}
}
|
javascript
|
{
"resource": ""
}
|
q5915
|
prepareEvents
|
train
|
function prepareEvents(raddec) {
let elements = [];
raddec.events.forEach(function(event) {
let i = document.createElement('i');
let space = document.createTextNode(' ');
i.setAttribute('class', EVENT_ICONS[event]);
elements.push(i);
elements.push(space);
});
return elements;
}
|
javascript
|
{
"resource": ""
}
|
q5916
|
prepareRecDecPac
|
train
|
function prepareRecDecPac(raddec) {
let maxNumberOfDecodings = 0;
raddec.rssiSignature.forEach(function(signature) {
if(signature.numberOfDecodings > maxNumberOfDecodings) {
maxNumberOfDecodings = signature.numberOfDecodings;
}
});
return raddec.rssiSignature.length + RDPS + maxNumberOfDecodings + RDPS +
raddec.packets.length;
}
|
javascript
|
{
"resource": ""
}
|
q5917
|
sortRaddecsAndHighlight
|
train
|
function sortRaddecsAndHighlight(transmitterId) {
let trs = Array.from(tbody.getElementsByTagName('tr'));
let sortedFragment = document.createDocumentFragment();
trs.sort(sortFunction);
trs.forEach(function(tr) {
if(tr.id === transmitterId) {
tr.setAttribute('class', 'monospace animated-highlight-reelyactive');
}
else {
tr.setAttribute('class', 'monospace');
}
sortedFragment.appendChild(tr);
});
tbody.appendChild(sortedFragment);
}
|
javascript
|
{
"resource": ""
}
|
q5918
|
makeGhostBuster
|
train
|
function makeGhostBuster() {
var coordinates = [];
var threshold = 25;
var timeout = 2500;
// no touch support
if(!mobileDetection.is()) {
return { add : function(){}, remove : function(){} };
}
/**
* prevent clicks if they're in a registered XY region
* @param {MouseEvent} event
*/
function preventGhostClick(event) {
var ev = event.originalEvent || event;
//don't prevent fastclicks
if (ev.fastclick) { return true; }
for (var i = 0; i < coordinates.length; i++) {
var x = coordinates[i][0];
var y = coordinates[i][1];
// within the range, so prevent the click
if (Math.abs(ev.clientX - x) < threshold && Math.abs(ev.clientY - y) < threshold) {
event.stopPropagation();
event.stopImmediatePropagation();
event.preventDefault();
return false;
}
}
}
/**
* reset the coordinates array
*/
function resetCoordinates() {
coordinates = [];
}
/**
* remove the first coordinates set from the array
*/
function popCoordinates() {
coordinates.splice(0, 1);
}
/**
* if it is an final touchend, we want to register it's place
* @param {TouchEvent} event
*/
function registerCoordinates(event) {
var ev = event.originalEvent || event;
// It seems that touchend is the cause for derived events like 'change' for
// checkboxes. Since we're creating fastclicks, which will also cause 'change'
// events to fire, we need to prevent default on touchend events, which has
// the effect of not causing these derived events to be created. I am not
// sure if this has any other negative consequences.
ev.preventDefault();
// touchend is triggered on every releasing finger
// changed touches always contain the removed touches on a touchend
// the touches object might contain these also at some browsers (firefox os)
// so touches - changedTouches will be 0 or lower, like -1, on the final touchend
if(ev.touches.length - ev.changedTouches.length <= 0) {
var touch = ev.changedTouches[0];
coordinates.push([touch.clientX, touch.clientY]);
setTimeout(popCoordinates, timeout);
}
}
/**
* prevent click events for the given element
* @param {EventTarget} $element jQuery object
*/
return {
add : Ember.run.bind(this, function ($element) {
$element.on("touchstart.ghost-click-buster", resetCoordinates);
$element.on("touchend.ghost-click-buster", registerCoordinates);
// register the click buster on with the selector, '*', which will
// cause it to fire on the first element that gets clicked on so that
// if this is a ghost click it will get killed immediately.
$element.on("click.ghost-click-buster", '*', preventGhostClick);
}),
remove : Ember.run.bind(this, function ($element) {
$element.off('.ghost-click-buster');
})
};
}
|
javascript
|
{
"resource": ""
}
|
q5919
|
registerCoordinates
|
train
|
function registerCoordinates(event) {
var ev = event.originalEvent || event;
// It seems that touchend is the cause for derived events like 'change' for
// checkboxes. Since we're creating fastclicks, which will also cause 'change'
// events to fire, we need to prevent default on touchend events, which has
// the effect of not causing these derived events to be created. I am not
// sure if this has any other negative consequences.
ev.preventDefault();
// touchend is triggered on every releasing finger
// changed touches always contain the removed touches on a touchend
// the touches object might contain these also at some browsers (firefox os)
// so touches - changedTouches will be 0 or lower, like -1, on the final touchend
if(ev.touches.length - ev.changedTouches.length <= 0) {
var touch = ev.changedTouches[0];
coordinates.push([touch.clientX, touch.clientY]);
setTimeout(popCoordinates, timeout);
}
}
|
javascript
|
{
"resource": ""
}
|
q5920
|
getKeyName
|
train
|
function getKeyName (property) {
if (!property.computed && property.key.type === 'Identifier') {
return property.key.name
}
if (property.key.type === 'Literal') {
return '' + property.key.value
}
if (property.key.type === 'TemplateLiteral' && property.key.quasis.length === 1) {
return property.key.quasis[0].value.cooked
}
return null
}
|
javascript
|
{
"resource": ""
}
|
q5921
|
getRuleInfo
|
train
|
function getRuleInfo (ast) {
const INTERESTING_KEYS = new Set(['create', 'meta'])
let exportsVarOverridden = false
let exportsIsFunction = false
const exportNodes = ast.body
.filter(statement => statement.type === 'ExpressionStatement')
.map(statement => statement.expression)
.filter(expression => expression.type === 'AssignmentExpression')
.filter(expression => expression.left.type === 'MemberExpression')
.reduce((currentExports, node) => {
if (
node.left.object.type === 'Identifier' && node.left.object.name === 'module' &&
node.left.property.type === 'Identifier' && node.left.property.name === 'exports'
) {
exportsVarOverridden = true
if (isNormalFunctionExpression(node.right)) {
// Check `module.exports = function () {}`
exportsIsFunction = true
return { create: node.right, meta: null }
} else if (node.right.type === 'ObjectExpression') {
// Check `module.exports = { create: function () {}, meta: {} }`
exportsIsFunction = false
return node.right.properties.reduce((parsedProps, prop) => {
const keyValue = getKeyName(prop)
if (INTERESTING_KEYS.has(keyValue)) {
parsedProps[keyValue] = prop.value
}
return parsedProps
}, {})
}
return {}
} else if (
!exportsIsFunction &&
node.left.object.type === 'MemberExpression' &&
node.left.object.object.type === 'Identifier' && node.left.object.object.name === 'module' &&
node.left.object.property.type === 'Identifier' && node.left.object.property.name === 'exports' &&
node.left.property.type === 'Identifier' && INTERESTING_KEYS.has(node.left.property.name)
) {
// Check `module.exports.create = () => {}`
currentExports[node.left.property.name] = node.right
} else if (
!exportsVarOverridden &&
node.left.object.type === 'Identifier' && node.left.object.name === 'exports' &&
node.left.property.type === 'Identifier' && INTERESTING_KEYS.has(node.left.property.name)
) {
// Check `exports.create = () => {}`
currentExports[node.left.property.name] = node.right
}
return currentExports
}, {})
return Object.prototype.hasOwnProperty.call(exportNodes, 'create') && isNormalFunctionExpression(exportNodes.create)
? Object.assign({ isNewStyle: !exportsIsFunction, meta: null }, exportNodes)
: null
}
|
javascript
|
{
"resource": ""
}
|
q5922
|
cookieToHeader
|
train
|
function cookieToHeader(cookies) {
const SEPARATOR = '; ';
return cookies.reduce(function (previous, current) {
return previous + current.name + '=' + current.value + SEPARATOR;
}, '');
}
|
javascript
|
{
"resource": ""
}
|
q5923
|
updateQuery
|
train
|
function updateQuery() {
let query = {};
switch(queryTemplates.value) {
case '0': // All raddecs
query = {
"size": 10,
"query": { "match_all": {} },
"_source": [ "transmitterId", "transmitterIdType", "receiverId",
"receiverIdType", "rssi", "timestamp",
"numberOfDecodings", "numberOfReceivers",
"numberOfPackets" ]
};
queryBox.value = JSON.stringify(query, null, 2);
break;
case '1': // Specific transmitterId
query = {
"size": 10,
"query": { "term": { "transmitterId": "" } },
"_source": [ "receiverId", "receiverIdType", "rssi", "timestamp",
"numberOfDecodings", "numberOfReceivers",
"numberOfPackets", "packets" ]
};
queryBox.value = JSON.stringify(query, null, 2);
break;
case '2': // Prefix transmitterId
query = {
"size": 10,
"query": { "prefix": { "transmitterId": "" } },
"_source": [ "transmitterId", "transmitterIdType", "receiverId",
"receiverIdType", "rssi", "timestamp",
"numberOfDecodings", "numberOfReceivers",
"numberOfPackets" ]
};
queryBox.value = JSON.stringify(query, null, 2);
break;
case '3': // Aggregate receiverId
query = {
"size": 0,
"aggs" : {
"receivers" : {
"terms" : {
"field" : "receiverId.keyword",
"order" : { "_count" : "desc" },
"size": 12
}
}
}
};
queryBox.value = JSON.stringify(query, null, 2);
break;
case '4': // Aggregate rec/dec/pac
query = {
"size": 0,
"aggs" : {
"numberOfReceivers" : {
"histogram" : {
"field" : "numberOfReceivers",
"interval" : 1
}
},
"numberOfDecodings" : {
"histogram" : {
"field" : "numberOfDecodings",
"interval" : 1,
"min_doc_count" : 1
}
},
"numberOfDistinctPackets" : {
"histogram" : {
"field" : "numberOfDistinctPackets",
"interval" : 1
}
}
}
};
queryBox.value = JSON.stringify(query, null, 2);
break;
case '5': // Auto-date histogram
query = {
"size": 0,
"aggs" : {
"periods" : {
"auto_date_histogram" : {
"field" : "timestamp",
"buckets" : 12
}
}
}
};
queryBox.value = JSON.stringify(query, null, 2);
break;
}
queryBox.rows = countNumberOfLines(queryBox.value);
parseQuery();
}
|
javascript
|
{
"resource": ""
}
|
q5924
|
parseQuery
|
train
|
function parseQuery() {
let query = {};
try { query = JSON.parse(queryBox.value); }
catch(error) {
queryError.textContent = 'Query must be valid JSON';
hide(queryButton);
hide(queryResults);
show(queryError);
return null;
}
hide(queryError);
show(queryButton);
return query;
}
|
javascript
|
{
"resource": ""
}
|
q5925
|
handleQuery
|
train
|
function handleQuery() {
let query = parseQuery();
let url = window.location.protocol + '//' + window.location.hostname + ':' +
window.location.port + ELASTICSEARCH_INTERFACE_ROUTE;
let httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if(httpRequest.readyState === XMLHttpRequest.DONE) {
if(httpRequest.status === 200) {
let response = JSON.parse(httpRequest.responseText);
updateResults(response);
updateHits(response);
updateAggregations(response);
show(queryResults);
}
else {
queryError.textContent = 'Query returned status ' +
httpRequest.status +
'. Is Elasticsearch connected and running?';
hide(queryResults);
hide(queryButton);
show(queryError);
}
}
};
httpRequest.open('POST', url);
httpRequest.setRequestHeader('Content-Type', 'application/json');
httpRequest.setRequestHeader('Accept', 'application/json');
httpRequest.send(JSON.stringify(query));
}
|
javascript
|
{
"resource": ""
}
|
q5926
|
updateResults
|
train
|
function updateResults(response) {
responseHits.textContent = response.hits.total;
responseTime.textContent = response.took;
}
|
javascript
|
{
"resource": ""
}
|
q5927
|
updateHits
|
train
|
function updateHits(response) {
if(!response.hits.hasOwnProperty('hits') ||
(response.hits.hits.length === 0)) {
hide(hitsCard);
}
else {
show(hitsCard);
hitsBox.textContent = JSON.stringify(response.hits.hits, null, 2);
}
}
|
javascript
|
{
"resource": ""
}
|
q5928
|
updateAggregations
|
train
|
function updateAggregations(response) {
if(response.hasOwnProperty('aggregations')) {
aggregationsBox.textContent = JSON.stringify(response.aggregations,
null, 2);
show(aggregationsCard);
}
else {
hide(aggregationsCard);
}
}
|
javascript
|
{
"resource": ""
}
|
q5929
|
implodeArray
|
train
|
function implodeArray(tokens) {
var message = "", i, l;
l = tokens.length;
for (i = 0; i < l; i++) {
message += (i > 0 ? globals.SEP : "") + tokens[i];
}
return message;
}
|
javascript
|
{
"resource": ""
}
|
q5930
|
implodeData
|
train
|
function implodeData(data) {
var dataArray = [], field;
for(field in data) {
dataArray.push(types.STRING);
dataArray.push(encodeString(field));
dataArray.push(types.STRING);
dataArray.push(encodeString(data[field]));
}
return implodeArray(dataArray);
}
|
javascript
|
{
"resource": ""
}
|
q5931
|
implodeDataArray
|
train
|
function implodeDataArray(data) {
var dataArray = [], i, l;
l = data.length;
for(i = 0; i < l; i++) {
dataArray.push(types.STRING);
dataArray.push(encodeString(data[i]));
}
return implodeArray(dataArray);
}
|
javascript
|
{
"resource": ""
}
|
q5932
|
encodeString
|
train
|
function encodeString(string) {
//it actually accepts any kind of object as input
if (string === null) {
return values.NULL;
} else if (string === "") {
return values.EMPTY;
} else {//0 false undefined NaN will pass from here
return encodeURIComponent(string)
.replace(/%20/g, "+");
}
}
|
javascript
|
{
"resource": ""
}
|
q5933
|
decodeString
|
train
|
function decodeString (string) {
if (string === values.EMPTY) {
return "";
} else if (string === values.NULL) {
return null;
} else {
return decodeURIComponent(
string.replace(/\+/g,"%20"));
}
}
|
javascript
|
{
"resource": ""
}
|
q5934
|
encodeInteger
|
train
|
function encodeInteger(value) {
if (value === null) {
return values.NULL;
} else if (!isNaN(value) && parseInt(value)==value) {
return value + "";
} else {
throw new Error('Invalid integer value "' + value + '"');
}
}
|
javascript
|
{
"resource": ""
}
|
q5935
|
encodeDouble
|
train
|
function encodeDouble(value) {
if (value === null) {
return values.NULL;
} else if (!isNaN(value)) {
return value + "";
} else {
throw new Error('Invalid double value "' + value + '"');
}
}
|
javascript
|
{
"resource": ""
}
|
q5936
|
encodeMetadataException
|
train
|
function encodeMetadataException(type) {
if (type === "metadata") {
return exceptions.METADATA;
} else if (type === "access") {
return exceptions.ACCESS;
} else if (type === "credits") {
return exceptions.CREDITS;
} else if (type === "conflictingSession") {
return exceptions.CONFLICTING_SESSION;
} else if (type === "items") {
return exceptions.ITEMS;
} else if (type === "schema") {
return exceptions.SCHEMA;
} else if (type === "notification") {
return exceptions.NOTIFICATION;
} else {
return exceptions.GENERIC;
}
}
|
javascript
|
{
"resource": ""
}
|
q5937
|
parse
|
train
|
function parse(data, initExpected) {
var lines, i, last;
data = tail + data;
data = data.replace(/\r*\n+/g, "\n");
lines = data.split("\n");
last = lines.length - 1;
for (i = 0; i < last; i++) {
messages.push(read(lines[i], initExpected));
}
tail = lines[lines.length - 1];
}
|
javascript
|
{
"resource": ""
}
|
q5938
|
bundleApp
|
train
|
function bundleApp(codeList, ns, domload, compile, before, npmTree, o) {
var l = []
, usedBuiltIns = npmTree._builtIns
, len = 0;
delete npmTree._builtIns;
// 1. construct the global namespace object
l.push("window." + ns + " = {data:{}, path:{}};");
// 2. attach path code to the namespace object so that require.js can efficiently resolve paths
l.push('\n// include npm::path');
var pathCode = read(join(builtInDir, 'path.posix.js'));
l.push('(function (exports) {\n ' + pathCode + '\n}(window.' + ns + '.path));');
// 3. pull in serialized data
Object.keys(o.data).forEach(function (name) {
return l.push(ns + ".data." + name + " = " + o.data[name] + ";");
});
// 4. attach require code
var config = {
namespace : ns
, domains : Object.keys(o.domains) // TODO: remove npm from here
, arbiters : o.arbiters
, logging : o.logLevel
, npmTree : npmTree
, builtIns : builtIns
, slash : '/' //TODO: figure out if different types can coexist, if so, determine in resolver, and on client
};
l.push(anonWrap(read(join(dir, 'require.js'))
.replace(/VERSION/, JSON.parse(read(join(dir, '..', 'package.json'))).version)
.replace(/REQUIRECONFIG/, JSON.stringify(config))
));
// 5. include CommonJS compatible code in the order they have to be defined
var defineWrap = function (exportName, domain, code) {
return ns + ".define('" + exportName + "','" + domain + "',function (require, module, exports) {\n" + code + "\n});";
};
// 6. harvest function splits code into app and non-app code and defineWraps
var harvest = function (onlyMain) {
codeList.forEach(function (pair) {
var dom = pair[0]
, file = pair[1]
, basename = file.split('.')[0];
if ((dom === 'app') !== onlyMain) {
return;
}
var code = before(compile(join(o.domains[dom], file)));
l.push(defineWrap(basename, dom, code));
});
};
// 7.a) include required builtIns
l.push("\n// node builtins\n");
len = l.length;
usedBuiltIns.forEach(function (b) {
if (b === 'path') { // already included
return;
}
l.push(defineWrap(b, 'npm', read(join(builtInDir, b + '.js'))));
});
if (l.length === len) {
l.pop();
}
// 7.b) include modules not on the app domain
l.push("\n// shared code\n");
len = l.length;
harvest(false);
if (l.length === len) {
l.pop();
}
// 7.c) include modules on the app domain, and wait for domloader if set
l.push("\n// app code - safety wrapped\n\n");
domload(harvest(true));
// 8. use a closure to encapsulate the private internal data and APIs
return anonWrap(l.join('\n'));
}
|
javascript
|
{
"resource": ""
}
|
q5939
|
train
|
function (onlyMain) {
codeList.forEach(function (pair) {
var dom = pair[0]
, file = pair[1]
, basename = file.split('.')[0];
if ((dom === 'app') !== onlyMain) {
return;
}
var code = before(compile(join(o.domains[dom], file)));
l.push(defineWrap(basename, dom, code));
});
}
|
javascript
|
{
"resource": ""
}
|
|
q5940
|
subscribe
|
train
|
function subscribe(message) {
reply(proto.writeSubscribe(message.id));
subscritions[message.itemName] = message.id;
if (!isSnapshotAvailable(message.itemName)) {
notify(proto.writeEndOfSnapshot(message.id, message.itemName));
}
dequeueSubUnsubRequest(message.itemName);
fireFirstSubUnsubEvent(message.itemName);
}
|
javascript
|
{
"resource": ""
}
|
q5941
|
subscribeError
|
train
|
function subscribeError(message, exceptionMessage, exceptionType) {
reply(proto.writeSubscribeException(
message.id, exceptionMessage, exceptionType));
dequeueSubUnsubRequest(message.itemName);
fireFirstSubUnsubEvent(message.itemName);
}
|
javascript
|
{
"resource": ""
}
|
q5942
|
unsubscribe
|
train
|
function unsubscribe(message) {
reply(proto.writeUnsubscribe(message.id));
subscritions[message.itemName] = undefined;
dequeueSubUnsubRequest(message.itemName);
handleLateSubUnsubRequests(message.itemName);
fireFirstSubUnsubEvent(message.itemName);
}
|
javascript
|
{
"resource": ""
}
|
q5943
|
unsubscribeError
|
train
|
function unsubscribeError(message, exceptionMessage, exceptionType) {
reply(proto.writeUnsubscribeException(
message.id, exceptionMessage, exceptionType));
dequeueSubUnsubRequest(message.itemName);
fireFirstSubUnsubEvent(message.itemName);
}
|
javascript
|
{
"resource": ""
}
|
q5944
|
fireFirstSubUnsubEvent
|
train
|
function fireFirstSubUnsubEvent(itemName) {
if (subUnsubQueue[itemName].length > 0) {
request = subUnsubQueue[itemName][0];
that.emit(request.message.verb, itemName, request.response);
}
}
|
javascript
|
{
"resource": ""
}
|
q5945
|
train
|
function(message) {
if (that.listeners(message.verb).length) {
var successHandler = function(msg) {
reply(proto.writeInit(msg.id));
};
var errorHandler = function(msg, exceptionMessage, exceptionType) {
reply(proto.writeInitException(msg.id, exceptionMessage, exceptionType));
};
var response = new DataResponse(message, successHandler, errorHandler);
that.emit("init", message, response);
} else {
reply(proto.writeInit(message.id));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q5946
|
train
|
function(message) {
var response = new DataResponse(message, subscribe, subscribeError);
if (queueSubUnsubRequest(message, response) === 1) {
fireFirstSubUnsubEvent(message.itemName);
} else {
that.emit("subscribeInQueue", message.itemName);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q5947
|
train
|
function(message) {
var response = new DataResponse(message, unsubscribe, unsubscribeError);
if (queueSubUnsubRequest(message, response) === 1) {
fireFirstSubUnsubEvent(message.itemName);
} else {
that.emit("unsubscribeInQueue", message.itemName);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q5948
|
update
|
train
|
function update(itemName, isSnapshot, data) {
var message, id = getIdFromItemName(itemName);
message = proto.writeUpdate(id, itemName, isSnapshot, data);
notify(message);
return that;
}
|
javascript
|
{
"resource": ""
}
|
q5949
|
endOfSnapshot
|
train
|
function endOfSnapshot(itemName) {
var message, id = getIdFromItemName(itemName);
message = proto.writeEndOfSnapshot(id, itemName);
notify(message);
return that;
}
|
javascript
|
{
"resource": ""
}
|
q5950
|
clearSnapshot
|
train
|
function clearSnapshot(itemName) {
var message, id = getIdFromItemName(itemName);
message = proto.writeClearSnapshot(id, itemName);
notify(message);
return that;
}
|
javascript
|
{
"resource": ""
}
|
q5951
|
failure
|
train
|
function failure(exception) {
var message;
message = proto.writeFailure(exception);
notify(message);
return that;
}
|
javascript
|
{
"resource": ""
}
|
q5952
|
train
|
function (array1, array2) {
if (array1.length !== array2.length) {
return false;
}
// Clone the second array
array2 = array2.concat();
let i;
for (i = 0; i < array1.length; i++) {
let index = array2.indexOf(array1[i]);
if (index === -1) {
return false;
}
array2.splice(index, 1);
}
if (array2.length === 0) {
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q5953
|
changeDropdownIndex
|
train
|
function changeDropdownIndex(page, ph, selectorAndIndex, callback) {
page.evaluate(function (selectorAndIndex) {
try {
var selector = selectorAndIndex[0];
var index = selectorAndIndex[1];
var element = document.querySelector(selector);
element.selectedIndex = index;
// event is needed because listeners to the change do not react to
// programmatic changes
var event = document.createEvent('Event');
event.initEvent('change', true, false);
element.dispatchEvent(event);
return null;
} catch (error) {
return error;
}
}, function (error) {
// do this because if there is no error, the error is still something so we can't simply do callback(error, page, ph);
if (error) {
callback(error, page, ph);
return;
}
callback(null, page, ph);
}, selectorAndIndex);
}
|
javascript
|
{
"resource": ""
}
|
q5954
|
clickElement
|
train
|
function clickElement(page, ph, selectorAndOptions, callback) {
var selector = selectorAndOptions[0];
var options = selectorAndOptions[1];
function clickSelector(selector) {
try {
var button = document.querySelector(selector);
var ev = document.createEvent("MouseEvent");
ev.initMouseEvent(
"click",
true /* bubble */, true /* cancelable */,
window, null,
0, 0, 0, 0, /* coordinates */
false, false, false, false, /* modifier keys */
0 /*left*/, null
);
button.dispatchEvent(ev);
} catch (error) {
return error
}
}
var oldUrl;
async.waterfall([
function (callback) {
page.get('url', function (url) {
oldUrl = url;
callback();
});
},
function (callback) {
page.evaluate(clickSelector, function (error) {
// do this because if there is no error, the error is still something so we can't simply do callback(error, page, ph);
if (error) {
callback(error, page, ph);
return;
}
checks.ajaxCallback(page, ph, oldUrl, options, callback);
}, selector);
}
], function (error, page, ph) {
callback(error, page, ph);
});
}
|
javascript
|
{
"resource": ""
}
|
q5955
|
setCheckboxState
|
train
|
function setCheckboxState(page, ph, selectorAndState, callback) {
page.evaluate(function (selectorAndState) {
try {
var selector = selectorAndState[0];
var state = selectorAndState[1];
var element = document.querySelector(selector);
element.checked = state;
// event is needed because listeners to the change do not react to
// programmatic changes
var event = document.createEvent('Event');
event.initEvent('change', true, false);
element.dispatchEvent(event);
return null;
} catch (error) {
return error;
}
}, function (error) {
// do this because if there is no error, the error is still something so we can't simply do callback(error, page, ph);
if (error) {
callback(error, page, ph);
return;
}
callback(null, page, ph);
}, selectorAndState);
}
|
javascript
|
{
"resource": ""
}
|
q5956
|
fillForm
|
train
|
function fillForm(page, ph, selectorAndValue, callback) {
page.evaluate(function (selectorAndValue) {
try {
var selector = selectorAndValue[0];
var value = selectorAndValue[1];
document.querySelector(selector).value = value;
return null;
} catch (error) {
return error;
}
}, function (error) {
// do this because if there is no error, the error is still something so we can't simply do callback(error, page, ph);
if (error) {
callback(error, page, ph);
return;
}
callback(null, page, ph);
}, selectorAndValue);
}
|
javascript
|
{
"resource": ""
}
|
q5957
|
submitForm
|
train
|
function submitForm(page, ph, callback) {
var oldUrl;
async.waterfall([
function (callback) {
page.get('url', function (url) {
oldUrl = url;
callback();
});
},
function (callback) {
page.evaluate(function () {
try {
document.forms[0].submit();
return null;
} catch (error) {
return error;
}
}, function (error) {
// do this because if there is no error, the error is still something so we can't simply do callback(error, page, ph);
if (error) {
callback(error);
return;
}
callback()
});
}, function (callback) {
checks.pageHasChanged(page, oldUrl, function (error) {
callback(error);
});
}
], function (error) {
callback(error, page, ph);
});
}
|
javascript
|
{
"resource": ""
}
|
q5958
|
validate
|
train
|
function validate(args) {
var meta = args.query;
if (! (args.query || args.infoHash)) return { code: 0, message: "query/infoHash required" };
if (meta && !meta.imdb_id) return { code: 1, message: "imdb_id required" };
if (meta && (meta.type == "series" && !(meta.hasOwnProperty("episode") && meta.hasOwnProperty("season"))))
return { code: 2, message: "season and episode required for series type" };
return false;
}
|
javascript
|
{
"resource": ""
}
|
q5959
|
LinkedinTokenStrategy
|
train
|
function LinkedinTokenStrategy(options, verify) {
options = options || {}
options.authorizationURL = options.authorizationURL || 'https://www.linkedin.com';
options.tokenURL = options.tokenURL || 'https://www.linkedin.com/uas/oauth2/accessToken';
options.scopeSeparator = options.scopeSeparator || ',';
this._passReqToCallback = options.passReqToCallback;
OAuth2Strategy.call(this, options, verify);
this.profileUrl = options.profileURL || 'https://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address,public-profile-url)?format=json';
this.name = 'linkedin-token';
}
|
javascript
|
{
"resource": ""
}
|
q5960
|
getProperty
|
train
|
function getProperty(style, name)
{
if(style[name] !== void 0)
{
return [name, style[name]];
}
if(name in propertyNames)
{
return [propertyNames[name], style[propertyNames[name]]];
}
name = name.substr(0, 1).toUpperCase() + name.substr(1);
var prefixes = ['webkit', 'moz', 'ms', 'o'], fullName;
for(var i = 0, end = prefixes.length; i < end; i++)
{
fullName = prefixes[i] + name;
if(style[fullName] !== void 0)
{
propertyNames[name] = fullName;
return [fullName, style[fullName]];
}
}
return [name, void 0];
}
|
javascript
|
{
"resource": ""
}
|
q5961
|
parse
|
train
|
function parse(str, options) {
var obj = options.object || 'obj'
, space = options.pretty ? 2 : 0
, space = options.spaces ? options.spaces : space
, js = str;
return ''
+ 'var ' + obj + ' = factory();\n'
+ (options.self
? 'var self = locals || {};\n' + js
: 'with (locals || {}) {\n' + js + '\n}\n')
+ 'return JSON.stringify(' + obj + ', null, ' + space + ')';
}
|
javascript
|
{
"resource": ""
}
|
q5962
|
Verifier
|
train
|
function Verifier(givenMasterKey) {
var masterKey = givenMasterKey || MASTER_KEY;
if (!masterKey) {
throw new errors.ValidationFailed('invalid master key');
}
this.masterKey = base64url.toBuffer(masterKey);
}
|
javascript
|
{
"resource": ""
}
|
q5963
|
inArray
|
train
|
function inArray(array, search)
{
if(!isArray(array))
{
throw 'expected an array as first param';
}
if(array.indexOf)
{
return array.indexOf(search);
}
for(var i = 0, end = array.length; i < end; i++)
{
if(array[i] === search)
{
return i;
}
}
return -1;
}
|
javascript
|
{
"resource": ""
}
|
q5964
|
toArray
|
train
|
function toArray(args, pos)
{
if(pos === void 0)
{
pos = 0;
}
return Array.prototype.slice.call(args, pos);
}
|
javascript
|
{
"resource": ""
}
|
q5965
|
convertTime
|
train
|
function convertTime(value, fromUnit, toUnit)
{
if(fromUnit != toUnit && value !== 0)
{
return value * (toUnit == 's'? 0.001 : 1000);
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
q5966
|
compoundMapping
|
train
|
function compoundMapping(name, value)
{
var parts, nameParts, prefix, suffix, dirs, values = {}, easing, i;
if(isArray(value))
{
value = value[0];
easing = value[1];
}
else
{
easing = null;
}
parts = String(value).split(/\s+/);
switch(parts.length)
{
case 1: parts = [parts[0], parts[0], parts[0], parts[0]]; break;
case 2: parts = [parts[0], parts[1], parts[0], parts[1]]; break;
case 3: parts = [parts[0], parts[1], parts[2], parts[1]]; break;
}
nameParts = decamelize(name).split('-');
prefix = nameParts[0];
suffix = nameParts.length > 1? nameParts[1].substr(0, 1).toUpperCase() + nameParts[1].substr(1) : '';
dirs = name == 'borderRadius'? radiusDirections : compoundDirections;
for(i = 0; i < 4; i++)
{
values[prefix + dirs[i] + suffix] = easing? [parts[i], easing] : parts[i];
}
return values;
}
|
javascript
|
{
"resource": ""
}
|
q5967
|
transformMapping
|
train
|
function transformMapping(name, value)
{
var easing, dirs = ['X', 'Y', 'Z'], values = {}, parts, baseName;
if(isArray(value))
{
value = value[0];
easing = value[1];
}
else
{
easing = null;
}
parts = String(value).split(/\s*,\s*/);
baseName = name.indexOf('3') !== -1? name.substr(0, name.length - 2) : name;
if(name == 'rotate3d')
{
if(parts.length == 4)
{
dirs = [parts[0] == '1'? 'X' : (parts[1] == '1'? 'Y' : 'Z')];
parts[0] = parts[3];
}
else
{
throw 'invalid rotate 3d value';
}
}
else
{
switch(parts.length)
{
// for rotations, a single value is passed as Z-value, while for other transforms it is applied to X and Y
case 1:
parts = baseName == 'rotate' || baseName == 'rotation'? [null, null, parts[0]] : [parts[0], parts[0], null];
break;
case 2:
parts = [parts[0], parts[1], null];
break;
}
}
for(var i = 0; i < dirs.length; i++)
{
if(parts[i] !== null)
{
values[baseName + dirs[i]] = easing? [parts[i], easing] : parts[i];
}
}
return values;
}
|
javascript
|
{
"resource": ""
}
|
q5968
|
parseSpeed
|
train
|
function parseSpeed(value)
{
if(value in speeds)
{
value = speeds[value];
}
value = parseFloat(value);
if(isNaN(value) || !value || value <= 0)
{
value = 1;
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
q5969
|
get
|
train
|
function get(target, path) {
var result = target;
for (var i = 0; i < path.length; i++) {
result = result ? result[path[i]] : result;
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q5970
|
findOneJsInArray
|
train
|
function findOneJsInArray(ary) {
var found,
count = 0;
ary.forEach(function(entry) {
if (jsExtRegExp.test(entry)) {
count += 1;
found = entry;
}
});
return count === 1 ? found : null;
}
|
javascript
|
{
"resource": ""
}
|
q5971
|
InvalidSignature
|
train
|
function InvalidSignature(reason) {
Error.captureStackTrace(this, this.constructor);
this.type = 'unauthorized';
this.statusCode = 401;
this.message = 'Invalid request signature';
this.reason = reason;
}
|
javascript
|
{
"resource": ""
}
|
q5972
|
ValidationFailed
|
train
|
function ValidationFailed(reason) {
Error.captureStackTrace(this, this.constructor);
this.type = 'bad_request';
this.statusCode = 400;
this.message = 'Request validation failed';
this.reason = reason;
}
|
javascript
|
{
"resource": ""
}
|
q5973
|
Signature
|
train
|
function Signature(req, buf) {
this.req = req;
this.rawBody = buf || req.rawBody;
this.xSignature = (req.headers['x-signature'] || '').split(' ');
this.signature = base64url.toBuffer(this.xSignature[0] || '');
this.publicKey = base64url.toBuffer(this.xSignature[1] || '');
this.endorsement = base64url.toBuffer(this.xSignature[2] || '');
this.date = Date.parse(req.headers.date);
}
|
javascript
|
{
"resource": ""
}
|
q5974
|
train
|
function (cb) {
get(SOLVENCY_SERVER + domain, function (roots) {
roots = roots || [];
roots.forEach(function (root) {
files.push({ path: 'root', type: 'root', content: root });
});
cb();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q5975
|
train
|
function (cb) {
files.forEach(function (file) {
var proof = file.content;
if (!proof) return;
if (!proof.id) {
errors.push(file.path + ' has no ID property.');
return;
}
res[proof.id] = res[proof.id] || {};
res[proof.id][file.type] = proof;
});
cb();
}
|
javascript
|
{
"resource": ""
}
|
|
q5976
|
throttle
|
train
|
function throttle(fn, timeout) {
var timer = null;
return function () {
if (!timer) {
timer = setTimeout(function() {
fn();
timer = null;
}, timeout);
}
};
}
|
javascript
|
{
"resource": ""
}
|
q5977
|
addEvent
|
train
|
function addEvent(node, event, fn, opt_useCapture) {
if (typeof node.addEventListener == 'function') {
node.addEventListener(event, fn, opt_useCapture || false);
}
else if (typeof node.attachEvent == 'function') {
node.attachEvent('on' + event, fn);
}
}
|
javascript
|
{
"resource": ""
}
|
q5978
|
removeEvent
|
train
|
function removeEvent(node, event, fn, opt_useCapture) {
if (typeof node.removeEventListener == 'function') {
node.removeEventListener(event, fn, opt_useCapture || false);
}
else if (typeof node.detatchEvent == 'function') {
node.detatchEvent('on' + event, fn);
}
}
|
javascript
|
{
"resource": ""
}
|
q5979
|
computeRectIntersection
|
train
|
function computeRectIntersection(rect1, rect2) {
var top = Math.max(rect1.top, rect2.top);
var bottom = Math.min(rect1.bottom, rect2.bottom);
var left = Math.max(rect1.left, rect2.left);
var right = Math.min(rect1.right, rect2.right);
var width = right - left;
var height = bottom - top;
return (width >= 0 && height >= 0) && {
top: top,
bottom: bottom,
left: left,
right: right,
width: width,
height: height
};
}
|
javascript
|
{
"resource": ""
}
|
q5980
|
getBoundingClientRect
|
train
|
function getBoundingClientRect(el) {
var rect;
try {
rect = el.getBoundingClientRect();
} catch (err) {
// Ignore Windows 7 IE11 "Unspecified error"
// https://github.com/WICG/IntersectionObserver/pull/205
}
if (!rect) return getEmptyRect();
// Older IE
if (!(rect.width && rect.height)) {
rect = {
top: rect.top,
right: rect.right,
bottom: rect.bottom,
left: rect.left,
width: rect.right - rect.left,
height: rect.bottom - rect.top
};
}
return rect;
}
|
javascript
|
{
"resource": ""
}
|
q5981
|
getParentNode
|
train
|
function getParentNode(node) {
var parent = node.parentNode;
if (parent && parent.nodeType == 11 && parent.host) {
// If the parent is a shadow root, return the host element.
return parent.host;
}
return parent;
}
|
javascript
|
{
"resource": ""
}
|
q5982
|
compact
|
train
|
function compact(list,typ) {
if(arguments.length === 1) {
if (Array.isArray(list)) {
// if the only one param is an array
return list.filter(x=>x);
} else {
// Curry it manually
typ = list;
return function (list) {return compact(list, typ)};
}
}
return list.filter(x=> typeof x === typeof typ);
}
|
javascript
|
{
"resource": ""
}
|
q5983
|
drop
|
train
|
function drop(list,dropCount=1,direction="left",fn=null) {
// If the first argument is not kind of `array`-like.
if (!(list && Array.isArray(list))) {
// Manually currying
let args = arguments;
return (list) => drop(list, ...args);
}
if(dropCount === 0 && !fn) {
return Array.prototype.slice.call(list, 0)
};
if(arguments.length === 1 || direction === "left") {
if (!fn) {
return Array.prototype.slice.call(list, +dropCount);
}
return (Array.prototype.slice.call(list, +dropCount)).filter(x=>fn(x));
}
if(direction === "right"){
if(!fn) {
return Array.prototype.slice.call(list, 0, list.length-(+dropCount));
}
if(dropCount === 0) {return (Array.prototype.slice.call(list, 0)).filter(x=>fn(x))};
return (Array.prototype.slice.call(list, 0, list.length-(+dropCount))).filter(x=>fn(x));
}
}
|
javascript
|
{
"resource": ""
}
|
q5984
|
fill
|
train
|
function fill(list, value, startIndex=0, endIndex=list.length){
if (!(list && Array.isArray(list))) {
// Manually currying
let args = arguments;
return (list) => fill(list, ...args);
}
return Array(...list).map((x,i)=> {
if(i>= startIndex && i <= endIndex) {
return x=value;
} else {
return x;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q5985
|
train
|
function (...values) {
let list = [];
let {main, follower} = reuseables.getMainAndFollower(values);
main.forEach(x=>{
if(list.indexOf(x) ==-1) {
if(follower.indexOf(x) >=0) {
if(list[x] ==undefined) list.push(x) }
}
})
return list;
}
|
javascript
|
{
"resource": ""
}
|
|
q5986
|
join
|
train
|
function join(joiner, ...values) {
if (values.length > 0) {
return concat([],...values).join(joiner);
}
// Manually currying
return (...values) => join(joiner, ...values);
}
|
javascript
|
{
"resource": ""
}
|
q5987
|
nth
|
train
|
function nth(list, indexNum) {
if (arguments.length == 1) {
// Manually currying
indexNum = list;
return (list) => nth(list, indexNum);
}
if(indexNum >= 0) {
return list[+indexNum]
};
return [...list].reverse()[list.length+indexNum];
}
|
javascript
|
{
"resource": ""
}
|
q5988
|
sortedIndex
|
train
|
function sortedIndex(list, value, valueIndex) {
if (!(list && Array.isArray(list))) {
// Manually currying
let args = arguments;
return (list) => sortedIndex(list, ...args);
}
return reuseables.sorter(list, value, valueIndex);
}
|
javascript
|
{
"resource": ""
}
|
q5989
|
train
|
function(list){
const listNoDuplicate = difference([],list);
if(typeof list[0] == "number") {
return listNoDuplicate.sort((a,b)=>a-b);
}
return listNoDuplicate.sort();
}
|
javascript
|
{
"resource": ""
}
|
|
q5990
|
union
|
train
|
function union(list1, list2, duplicate=false) {
if ( arguments.length < 2 ) {
// Manually currying
let args1 = arguments;
return (...args2) => union(...args1, ...args2);
} else if (arguments.length === 2 && (! Array.isArray(list2))) {
// curring union(_, list, duplicate) cases
// Manually currying
let args = arguments;
return (list) => union(list, ...args);
}
if(duplicate) {
return differenceWithDup([],list1.concat(list2));
}
return difference([],list1.concat(list2));
}
|
javascript
|
{
"resource": ""
}
|
q5991
|
merge
|
train
|
function merge(torrents)
{
// NOTE: here, on the merge logic, we can set properties that should always be set
// Or just rip out the model logic from LinvoDB into a separate module and use it
return torrents.reduce(function(a, b) {
return _.merge(a, b, function(x, y) {
// this is for the files array, and we want more complicated behaviour
if (_.isArray(a) && _.isArray(b)) return b;
})
})
}
|
javascript
|
{
"resource": ""
}
|
q5992
|
through
|
train
|
function through(transform, flush, objectMode) {
const stream = new TransformStream({objectMode})
stream._transform = transform || pass
if (flush) stream._flush = flush
return stream
}
|
javascript
|
{
"resource": ""
}
|
q5993
|
patchUser
|
train
|
function patchUser(user, patchToUser) {
return users.patch(user.id || user._id, patchToUser, {}) // needs users from closure
.then(() => Object.assign(user, patchToUser));
}
|
javascript
|
{
"resource": ""
}
|
q5994
|
injectForeignFields
|
train
|
function injectForeignFields(targetEntity) {
switch (type) {
case '1:1':
return entityModifier.readEntityProperty(targetEntity, 'fields').then(function(fields) {
fields.push(entity.primary);
entityModifier.modifyEntityProperty(targetEntity, 'fields', JSON.stringify(fields));
return targetEntity;
});
case '1:many':
break;
case 'many:1':
return entityModifier.readEntityProperty(targetEntity, 'fields').then(function(fields) {
fields.push(entity.primary);
entityModifier.modifyEntityProperty(targetEntity, 'fields', JSON.stringify(fields));
return targetEntity;
});
case 'many:many':
break;
}
}
|
javascript
|
{
"resource": ""
}
|
q5995
|
FA2LayoutSupervisor
|
train
|
function FA2LayoutSupervisor(graph, params) {
params = params || {};
// Validation
if (!isGraph(graph))
throw new Error('graphology-layout-forceatlas2/worker: the given graph is not a valid graphology instance.');
// Validating settings
var settings = helpers.assign({}, DEFAULT_SETTINGS, params.settings),
validationError = helpers.validateSettings(settings);
if (validationError)
throw new Error('graphology-layout-forceatlas2/worker: ' + validationError.message);
// Properties
this.worker = new Worker();
this.graph = graph;
this.settings = settings;
this.matrices = null;
this.running = false;
this.killed = false;
// Binding listeners
this.handleMessage = this.handleMessage.bind(this);
this.worker.addEventListener('message', this.handleMessage.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
q5996
|
StablePriorityQueue
|
train
|
function StablePriorityQueue(comparator) {
this.array = [];
this.size = 0;
this.runningcounter = 0;
this.compare = comparator || defaultcomparator;
this.stable_compare = function(a, b) {
var cmp = this.compare(a.value,b.value);
return (cmp < 0) || ( (cmp == 0) && (a.counter < b.counter) );
}
}
|
javascript
|
{
"resource": ""
}
|
q5997
|
train
|
function () {
// main code
var x = new StablePriorityQueue(function (a, b) {
return a.name < b.name ? -1 : (a.name > b.name ? 1 : 0) ;
});
x.add({name:"Jack", age:31});
x.add({name:"Anna", age:111});
x.add({name:"Jack", age:46});
x.add({name:"Jack", age:11});
x.add({name:"Abba", age:31});
x.add({name:"Abba", age:30});
while (!x.isEmpty()) {
console.log(x.poll());
}
x = new StablePriorityQueue(function(a, b) {
return a.energy - b.energy;
});
[{ name: 'player', energy: 10},
{ name: 'monster1', energy: 10},
{ name: 'monster2', energy: 10},
{ name: 'monster3', energy: 10}
].forEach(function(o){
x.add(o);
})
while (!x.isEmpty()) {
console.log(x.poll());
}
}
|
javascript
|
{
"resource": ""
}
|
|
q5998
|
train
|
function (obj) {
var toc = [],
tocTmpl = _.template("* [<%= heading %>](#<%= id %>)\n"),
sectionTmpl = _.template("### <%= summary %>\n\n<%= body %>\n");
// Finesse comment markdown data.
// Also, statefully create TOC.
var sections = _.chain(obj)
.filter(function (c) {
return !c.isPrivate && !c.ignore && _.any(c.tags, function (t) {
return t.type === "api" && t.visibility === "public";
});
})
.map(function (c) {
// Add to TOC.
toc.push(tocTmpl({
heading: c.description.summary,
id: _headingId(c.description.summary)
}));
return sectionTmpl(c.description);
})
.value()
.join("");
return "\n" + toc.join("") + "\n" + sections;
}
|
javascript
|
{
"resource": ""
}
|
|
q5999
|
abstractSynchronousLayout
|
train
|
function abstractSynchronousLayout(assign, graph, params) {
if (!isGraph(graph))
throw new Error('graphology-layout-forceatlas2: the given graph is not a valid graphology instance.');
if (typeof params === 'number')
params = {iterations: params};
var iterations = params.iterations;
if (typeof iterations !== 'number')
throw new Error('graphology-layout-forceatlas2: invalid number of iterations.');
if (iterations <= 0)
throw new Error('graphology-layout-forceatlas2: you should provide a positive number of iterations.');
// Validating settings
var settings = helpers.assign({}, DEFAULT_SETTINGS, params.settings),
validationError = helpers.validateSettings(settings);
if (validationError)
throw new Error('graphology-layout-forceatlas2: ' + validationError.message);
// Building matrices
var matrices = helpers.graphToByteArrays(graph),
i;
// Iterating
for (i = 0; i < iterations; i++)
iterate(settings, matrices.nodes, matrices.edges);
// Applying
if (assign) {
helpers.applyLayoutChanges(graph, matrices.nodes);
return;
}
return helpers.collectLayoutChanges(graph, matrices.nodes);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.