_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q47900
|
global_names
|
train
|
function global_names(ctx, options) {
try {
var ans = vm.runInContext(options.enum_global, ctx);
ans = ans.concat(all_keywords);
ans.sort();
var seen = {};
ans.filter(function (item) {
if (Object.prototype.hasOwnProperty.call(seen, item)) return false;
seen[item] = true;
return true;
});
return ans;
} catch(e) {
console.log(e.stack || e.toString());
}
return [];
}
|
javascript
|
{
"resource": ""
}
|
q47901
|
train
|
function(element, type, handler) {
if(element.addEventListener) {
addEvent = function(element, type, handler) {
element.addEventListener(type, handler, false);
};
} else if(element.attachEvent) {
addEvent = function(element, type, handler) {
element.attachEvent('on' + type, handler);
};
} else {
addEvent = function(element, type, handler) {
element['on' + type] = handler;
};
}
addEvent(element, type, handler);
}
|
javascript
|
{
"resource": ""
}
|
|
q47902
|
train
|
function(arr) {
var key = 0;
var min = arr[0];
for(var i = 1, len = arr.length; i < len; i++) {
if(arr[i] < min) {
key = i;
min = arr[i];
}
}
return key;
}
|
javascript
|
{
"resource": ""
}
|
|
q47903
|
train
|
function(arr) {
var key = 0;
var max = arr[0];
for(var i = 1, len = arr.length; i < len; i++) {
if(arr[i] > max) {
key = i;
max = arr[i];
}
}
return key;
}
|
javascript
|
{
"resource": ""
}
|
|
q47904
|
train
|
function(event) {
clearTimeout(noticeDelay);
var e = event || window.event;
var target = e.target || e.srcElement;
if(target.tagName == 'SPAN') {
var targetTitle = target.parentNode.tagLine;
noticeContainer.innerHTML = (target.className == 'like' ? 'Liked ' : 'Marked ') + '<strong>' + targetTitle + '</strong>';
noticeContainer.className = 'on';
noticeDelay = setTimeout(function() {
noticeContainer.className = 'off';
}, 2000);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47905
|
train
|
function() {
return Math.max(MIN_COLUMN_COUNT, Math.floor((document.body.offsetWidth + GAP_WIDTH) / (COLUMN_WIDTH + GAP_WIDTH)));
}
|
javascript
|
{
"resource": ""
}
|
|
q47906
|
train
|
function(count) {
columnHeights = [];
for(var i = 0; i < count; i++) {
columnHeights.push(0);
}
cellsContainer.style.width = (count * (COLUMN_WIDTH + GAP_WIDTH) - GAP_WIDTH) + 'px';
}
|
javascript
|
{
"resource": ""
}
|
|
q47907
|
train
|
function(num) {
if(loading) {
// Avoid sending too many requests to get new cells.
return;
}
var xhrRequest = new XMLHttpRequest();
var fragment = document.createDocumentFragment();
var cells = [];
var images;
xhrRequest.open('GET', 'json.php?n=' + num, true);
xhrRequest.onreadystatechange = function() {
if(xhrRequest.readyState == 4 && xhrRequest.status == 200) {
images = JSON.parse(xhrRequest.responseText);
for(var j = 0, k = images.length; j < k; j++) {
var cell = document.createElement('div');
cell.className = 'cell pending';
cell.tagLine = images[j].title;
cells.push(cell);
front(cellTemplate, images[j], cell);
fragment.appendChild(cell);
}
cellsContainer.appendChild(fragment);
loading = false;
adjustCells(cells);
}
};
loading = true;
xhrRequest.send(null);
}
|
javascript
|
{
"resource": ""
}
|
|
q47908
|
train
|
function(num) {
if(loading) {
// Avoid sending too many requests to get new cells.
return;
}
var fragment = document.createDocumentFragment();
var cells = [];
var images = [0, 286, 143, 270, 143, 190, 285, 152, 275, 285, 285, 128, 281, 242, 339, 236, 157, 286, 259, 267, 137, 253, 127, 190, 190, 225, 269, 264, 272, 126, 265, 287, 269, 125, 285, 190, 314, 141, 119, 274, 274, 285, 126, 279, 143, 266, 279, 600, 276, 285, 182, 143, 287, 126, 190, 285, 143, 241, 166, 240, 190];
for(var j = 0; j < num; j++) {
var key = Math.floor(Math.random() * 60) + 1;
var cell = document.createElement('div');
cell.className = 'cell pending';
cell.tagLine = 'demo picture ' + key;
cells.push(cell);
front(cellTemplate, { 'title': 'demo picture ' + key, 'src': key, 'height': images[key], 'width': 190 }, cell);
fragment.appendChild(cell);
}
// Faking network latency.
setTimeout(function() {
loading = false;
cellsContainer.appendChild(fragment);
adjustCells(cells);
}, 2000);
}
|
javascript
|
{
"resource": ""
}
|
|
q47909
|
train
|
function(cells, reflow) {
var columnIndex;
var columnHeight;
for(var j = 0, k = cells.length; j < k; j++) {
// Place the cell to column with the minimal height.
columnIndex = getMinKey(columnHeights);
columnHeight = columnHeights[columnIndex];
cells[j].style.height = (cells[j].offsetHeight - CELL_PADDING) + 'px';
cells[j].style.left = columnIndex * (COLUMN_WIDTH + GAP_WIDTH) + 'px';
cells[j].style.top = columnHeight + 'px';
columnHeights[columnIndex] = columnHeight + GAP_HEIGHT + cells[j].offsetHeight;
if(!reflow) {
cells[j].className = 'cell ready';
}
}
cellsContainer.style.height = getMaxVal(columnHeights) + 'px';
manageCells();
}
|
javascript
|
{
"resource": ""
}
|
|
q47910
|
train
|
function() {
// Calculate new column count after resize.
columnCount = getColumnCount();
if(columnHeights.length != columnCount) {
// Reset array of column heights and container width.
resetHeights(columnCount);
adjustCells(cellsContainer.children, true);
} else {
manageCells();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47911
|
train
|
function() {
// Lock managing state to avoid another async call. See {Function} delayedScroll.
managing = true;
var cells = cellsContainer.children;
var viewportTop = (document.body.scrollTop || document.documentElement.scrollTop) - cellsContainer.offsetTop;
var viewportBottom = (window.innerHeight || document.documentElement.clientHeight) + viewportTop;
// Remove cells' contents if they are too far away from the viewport. Get them back if they are near.
// TODO: remove the cells from DOM should be better :<
for(var i = 0, l = cells.length; i < l; i++) {
if((cells[i].offsetTop - viewportBottom > THRESHOLD) || (viewportTop - cells[i].offsetTop - cells[i].offsetHeight > THRESHOLD)) {
if(cells[i].className === 'cell ready') {
cells[i].fragment = cells[i].innerHTML;
cells[i].innerHTML = '';
cells[i].className = 'cell shadow';
}
} else {
if(cells[i].className === 'cell shadow') {
cells[i].innerHTML = cells[i].fragment;
cells[i].className = 'cell ready';
}
}
}
// If there's space in viewport for a cell, request new cells.
if(viewportBottom > getMinVal(columnHeights)) {
// Remove the if/else statement in your project, just call the appendCells function.
if(isGithubDemo) {
appendCellsDemo(columnCount);
} else {
appendCells(columnCount);
}
}
// Unlock managing state.
managing = false;
}
|
javascript
|
{
"resource": ""
}
|
|
q47912
|
train
|
function() {
// Add other event listeners.
addEvent(cellsContainer, 'click', updateNotice);
addEvent(window, 'resize', delayedResize);
addEvent(window, 'scroll', delayedScroll);
// Initialize array of column heights and container width.
columnCount = getColumnCount();
resetHeights(columnCount);
// Load cells for the first time.
manageCells();
}
|
javascript
|
{
"resource": ""
}
|
|
q47913
|
train
|
function(time) {
if (this._queue.length === 0) return
var i = 0, line, oldLines
while ((line = this._queue[i++]) && time >= line.t2) 1
oldLines = this._queue.slice(0, i - 1)
this._queue = this._queue.slice(i - 1)
if (this._queue.length === 0)
this._lastValue = oldLines[oldLines.length - 1].v2
}
|
javascript
|
{
"resource": ""
}
|
|
q47914
|
train
|
function(t1, v2, duration) {
var i = 0, line, newLines = []
// Find the point in the queue where we should insert the new line.
while ((line = this._queue[i++]) && (t1 >= line.t2)) 1
this._queue = this._queue.slice(0)
if (this._queue.length) {
var lastLine = this._queue[this._queue.length - 1]
// If the new line interrupts the last in the queue, we have to interpolate
// a new line
if (t1 < lastLine.t2) {
this._queue = this._queue.slice(0, -1)
line = {
t1: lastLine.t1, v1: lastLine.v1,
t2: t1, v2: this._interpolate(lastLine, t1)
}
newLines.push(line)
this._queue.push(line)
// Otherwise, we have to fill-in the gap with a straight line
} else if (t1 > lastLine.t2) {
line = {
t1: lastLine.t2, v1: lastLine.v2,
t2: t1, v2: lastLine.v2
}
newLines.push(line)
this._queue.push(line)
}
// If there isn't any value in the queue yet, we fill in the gap with
// a straight line from `_lastValue` all the way to `t1`
} else {
line = {
t1: 0, v1: this._lastValue,
t2: t1, v2: this._lastValue
}
newLines.push(line)
this._queue.push(line)
}
// Finally create the line and add it to the queue
line = {
t1: t1, v1: this._queue[this._queue.length - 1].v2,
t2: t1 + duration, v2: v2
}
newLines.push(line)
this._queue.push(line)
return newLines
}
|
javascript
|
{
"resource": ""
}
|
|
q47915
|
train
|
function(array, ind) {
if (ind >= array.length || ind < 0)
throw new Error('$' + (ind + 1) + ': argument number out of range')
return array[ind]
}
|
javascript
|
{
"resource": ""
}
|
|
q47916
|
train
|
function(obj, type, name, nameIsUnique, oldName) {
var nameMap, objList
this._store[type] = nameMap = this._store[type] || {}
nameMap[name] = objList = nameMap[name] || []
// Adding new mapping
if (objList.indexOf(obj) === -1) {
if (nameIsUnique && objList.length > 0)
throw new Error('there is already a ' + type + ' with name "' + name + '"')
objList.push(obj)
}
// Removing old mapping
if (oldName) {
objList = nameMap[oldName]
objList.splice(objList.indexOf(obj), 1)
}
exports.emitter.emit('namedObjects:registered:' + type, obj)
}
|
javascript
|
{
"resource": ""
}
|
|
q47917
|
train
|
function(obj, type, name) {
var nameMap = this._store[type]
, objList = nameMap ? nameMap[name] : null
, ind
if (!objList) return
ind = objList.indexOf(obj)
if (ind === -1) return
objList.splice(ind, 1)
exports.emitter.emit('namedObjects:unregistered:' + type, obj)
}
|
javascript
|
{
"resource": ""
}
|
|
q47918
|
train
|
function(rate) {
if (!_.isNumber(rate))
return console.error('invalid [metro] rate ' + rate)
this.rate = Math.max(rate, 1)
}
|
javascript
|
{
"resource": ""
}
|
|
q47919
|
charCodesToString
|
train
|
function charCodesToString(charCodes) {
// Use these methods to be able to convert large strings
if (hasProperty('Buffer')) {
return Buffer.from(charCodes).toString(STR_ENCODING)
} else if (hasProperty('TextDecoder')) {
return new TextDecoder(STR_ENCODING) // eslint-disable-line no-undef
.decode(new Int8Array(charCodes))
}
// Fallback method
let str = ''
for (let i = 0; i < charCodes.length; i += STR_SLICE_SIZE) {
str += String.fromCharCode.apply(
null,
charCodes.slice(i, i + STR_SLICE_SIZE)
)
}
return str
}
|
javascript
|
{
"resource": ""
}
|
q47920
|
train
|
function() {
if ($(yasqe.getWrapperElement()).offset().top >= tooltip.offset().top) {
//shit, move the tooltip down. The tooltip now hovers over the top edge of the yasqe instance
tooltip.css("bottom", "auto");
tooltip.css("top", "26px");
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47921
|
setSideConditions
|
train
|
function setSideConditions(topSymbol) {
if (topSymbol === "prefixDecl") {
state.inPrefixDecl = true;
} else {
state.inPrefixDecl = false;
}
switch (topSymbol) {
case "disallowVars":
state.allowVars = false;
break;
case "allowVars":
state.allowVars = true;
break;
case "disallowBnodes":
state.allowBnodes = false;
break;
case "allowBnodes":
state.allowBnodes = true;
break;
case "storeProperty":
state.storeProperty = true;
break;
}
}
|
javascript
|
{
"resource": ""
}
|
q47922
|
train
|
function(yasqe) {
yasqe.cursor = $(".CodeMirror-cursor");
if (yasqe.buttons && yasqe.buttons.is(":visible") && yasqe.cursor.length > 0) {
if (utils.elementsOverlap(yasqe.cursor, yasqe.buttons)) {
yasqe.buttons.find("svg").attr("opacity", "0.2");
} else {
yasqe.buttons.find("svg").attr("opacity", "1.0");
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q47923
|
formatError
|
train
|
function formatError(e) {
if (!e.err) return e.message;
if (e.err.message) return e.err.message;
return JSON.stringify(e.err);
}
|
javascript
|
{
"resource": ""
}
|
q47924
|
main
|
train
|
function main(kayn) {
const config = {
query: 420,
champion: 67,
season: 7,
}
kayn.Summoner.by.name('Contractz').callback(function(error, summoner) {
// Note that the grabbing of a matchlist is currently limited by pagination.
// This API request only returns the first list.
kayn.Matchlist.by
.accountID(summoner.accountId)
.region('na')
.query(config)
.callback(function(error, matchlist) {
console.log(matchlist.totalGames, matchlist.matches.length)
})
})
}
|
javascript
|
{
"resource": ""
}
|
q47925
|
rangeToPattern
|
train
|
function rangeToPattern(start, stop, options) {
if (start === stop) {
return { pattern: start, count: [], digits: 0 };
}
let zipped = zip(start, stop);
let digits = zipped.length;
let pattern = '';
let count = 0;
for (let i = 0; i < digits; i++) {
let [startDigit, stopDigit] = zipped[i];
if (startDigit === stopDigit) {
pattern += startDigit;
} else if (startDigit !== '0' || stopDigit !== '9') {
pattern += toCharacterClass(startDigit, stopDigit, options);
} else {
count++;
}
}
if (count) {
pattern += options.shorthand === true ? '\\d' : '[0-9]';
}
return { pattern, count: [count], digits };
}
|
javascript
|
{
"resource": ""
}
|
q47926
|
logDiffText
|
train
|
function logDiffText(diff, options) {
var diffText = getDiffText(diff, options);
if (diffText) {
console.log(inverseGreen('+ expected'), inverseRed('- actual'), '\n', diffText);
}
}
|
javascript
|
{
"resource": ""
}
|
q47927
|
_concatNotDiffParts
|
train
|
function _concatNotDiffParts(diff) {
for (var i = 1; i < diff.length; i++) {
var currPart = diff[i],
prevPart = diff[i - 1];
if (!_isDiffPart(currPart) && !_isDiffPart(prevPart)) {
prevPart.value += currPart.value;
diff.splice(i--, 1);
}
}
return diff;
}
|
javascript
|
{
"resource": ""
}
|
q47928
|
modify
|
train
|
function modify(value, options) {
var modifiedValue = '',
parser;
parser = new SimpleApiParser({
/**
* @param {String} name
* @param {String} publicId
* @param {String} systemId
*/
doctype: function (name, publicId, systemId) {
modifiedValue += serialize.doctype(name, publicId, systemId);
},
/**
* @param {String} tagName
* @param {Array} attrs
* @param {Boolean} selfClosing
*/
startTag: function (tagName, attrs, selfClosing) {
if (options.ignoreDuplicateAttributes) {
attrs = utils.removeDuplicateAttributes(attrs);
}
attrs = utils.sortAttrs(attrs) &&
utils.sortCssClasses(attrs) &&
utils.sortAttrsValues(attrs, options.compareAttributesAsJSON) &&
utils.removeAttrsValues(attrs, options.ignoreAttributes);
modifiedValue += serialize.startTag(tagName, attrs, selfClosing);
},
/**
* @param {String} tagName
*/
endTag: function (tagName) {
!options.ignoreEndTags && (modifiedValue += serialize.endTag(tagName));
},
/**
* @param {String} text
*/
text: function (text) {
options.ignoreWhitespaces && (text = utils.removeWhitespaces(text));
modifiedValue += serialize.text(text);
},
/**
* @param {String} comment
*/
comment: function (comment) {
var conditionalComment = utils.getConditionalComment(comment, modify, options);
if (conditionalComment) {
modifiedValue += serialize.comment(conditionalComment);
} else if (!options.ignoreComments) {
modifiedValue += serialize.comment(comment);
}
}
});
// Makes 'parse5' handle duplicate attributes
parser._reset = function (html) {
SimpleApiParser.prototype._reset.call(this, html);
this.tokenizerProxy.tokenizer._isDuplicateAttr = function () {
return false;
};
};
parser.parse(value);
return modifiedValue;
}
|
javascript
|
{
"resource": ""
}
|
q47929
|
_getIndexesInArray
|
train
|
function _getIndexesInArray(attrs, attr) {
var res = [];
for (var i = 0; i < attrs.length; i++) {
if (attrs[i].name === attr) res.push(i);
}
return res;
}
|
javascript
|
{
"resource": ""
}
|
q47930
|
sortAttrs
|
train
|
function sortAttrs(attrs) {
return attrs.sort(function (a, b) {
if (a.name < b.name) {
return -1;
} else if (a.name > b.name) {
return 1;
} else if (a.value < b.value) {
return -1;
} else if (a.value > b.value) {
return 1;
}
return 0;
});
}
|
javascript
|
{
"resource": ""
}
|
q47931
|
sortCssClasses
|
train
|
function sortCssClasses(attrs) {
/**
* Sorts the given CSS class attribute
* @param {String} cssClasses
* @returns {String}
*/
function _sortCssClassesValues(cssClasses) {
var classList = (cssClasses || '').split(' ');
return _(classList)
.filter()
.uniq()
.sort()
.join(' ');
}
var classIndexes = _getIndexesInArray(attrs, 'class');
_.forEach(classIndexes, function (index) {
attrs[index].value = _sortCssClassesValues(attrs[index].value);
});
return attrs;
}
|
javascript
|
{
"resource": ""
}
|
q47932
|
_sortCssClassesValues
|
train
|
function _sortCssClassesValues(cssClasses) {
var classList = (cssClasses || '').split(' ');
return _(classList)
.filter()
.uniq()
.sort()
.join(' ');
}
|
javascript
|
{
"resource": ""
}
|
q47933
|
sortAttrsValues
|
train
|
function sortAttrsValues(attrs, compareAttributesAsJSON) {
/**
* Recursively sorts the given object by key
* @param {Object} obj
* @returns {Object}
*/
function _sortObj(obj) {
if (!_.isObject(obj)) {
return JSON.stringify(obj);
}
if (_.isArray(obj)) {
return '[' + _(obj).map(_sortObj).join(',') + ']';
}
return '{' +
_(obj)
.keys()
.sort()
.map(function (key) {
return JSON.stringify(key) + ':' + _sortObj(obj[key]);
})
.join(',') +
'}';
}
/**
* Parses the given in HTML attribute JSON
* @param {String} val
* @param {Boolean} [isClick]
* @returns {Object}
*/
function _parseAttr(val, isClick) {
try {
if (isClick) {
/*jshint evil: true */
var fn = Function(val);
return fn ? fn() : {};
}
return JSON.parse(val);
} catch (err) {
return undefined;
}
}
_.forEach(compareAttributesAsJSON, function (attr) {
if (typeof attr === 'string') {
var name = attr;
attr = {};
attr.name = name;
attr.isFunction = false;
}
var attrValue,
isFunction = (attr.isFunction),
attrIndexes = _getIndexesInArray(attrs, attr.name);
_.forEach(attrIndexes, function (index) {
attrValue = _parseAttr(attrs[index].value, isFunction);
attrValue = _sortObj(attrValue);
attrs[index].value = (isFunction && attrValue ? 'return ' : '') + attrValue;
});
});
return attrs;
}
|
javascript
|
{
"resource": ""
}
|
q47934
|
_sortObj
|
train
|
function _sortObj(obj) {
if (!_.isObject(obj)) {
return JSON.stringify(obj);
}
if (_.isArray(obj)) {
return '[' + _(obj).map(_sortObj).join(',') + ']';
}
return '{' +
_(obj)
.keys()
.sort()
.map(function (key) {
return JSON.stringify(key) + ':' + _sortObj(obj[key]);
})
.join(',') +
'}';
}
|
javascript
|
{
"resource": ""
}
|
q47935
|
_parseAttr
|
train
|
function _parseAttr(val, isClick) {
try {
if (isClick) {
/*jshint evil: true */
var fn = Function(val);
return fn ? fn() : {};
}
return JSON.parse(val);
} catch (err) {
return undefined;
}
}
|
javascript
|
{
"resource": ""
}
|
q47936
|
removeAttrsValues
|
train
|
function removeAttrsValues(attrs, ignoreAttributes) {
_.forEach(ignoreAttributes, function (attr) {
var attrIndexes = _getIndexesInArray(attrs, attr);
_.forEach(attrIndexes, function (index) {
attrs[index].value = '';
});
});
return attrs;
}
|
javascript
|
{
"resource": ""
}
|
q47937
|
removeDuplicateAttributes
|
train
|
function removeDuplicateAttributes(attrs) {
var attrsNames = [],
res = [];
_.forEach(attrs, function (attr) {
if (attrsNames.indexOf(attr.name) === -1) {
res.push(attr);
attrsNames.push(attr.name);
}
});
return res;
}
|
javascript
|
{
"resource": ""
}
|
q47938
|
getConditionalComment
|
train
|
function getConditionalComment(comment, modify, options) {
var START_IF = '^\\s*\\[if .*\\]>',
END_IF = '<!\\[endif\\]\\s*$',
matchedStartIF = comment.match(new RegExp(START_IF)),
matchedEndIF = comment.match(new RegExp(END_IF));
if (comment.match(new RegExp(START_IF + '\\s*$')) || comment.match(new RegExp(START_IF + '<!\\s*$')) ||
comment.match(new RegExp('^' + END_IF))) {
return comment.trim();
}
if (matchedStartIF && matchedEndIF) {
var start = matchedStartIF[0],
end = matchedEndIF[0],
modified = modify(comment.substring(start.length, matchedEndIF.index), options);
return (start + modified + end).trim();
}
}
|
javascript
|
{
"resource": ""
}
|
q47939
|
sortedByScoreDesc
|
train
|
function sortedByScoreDesc(players) {
return players.slice().sort(function(a, b) {
if (b.score == a.score)
return a.name.localeCompare(b.name); // stabalize the sort
return b.score - a.score;
});
}
|
javascript
|
{
"resource": ""
}
|
q47940
|
calcPlayerStyle
|
train
|
function calcPlayerStyle(player, delayed) {
// delayed
if (delayed)
return {transition: "250ms", transform: null};
// initial
else {
var offset = (lastPos.get(player) * 18) - (curPos.get(player) * 18);
return {
transform: "translateY(" + offset + "px)",
transition: null//offset == 0 ? "",
};
}
}
|
javascript
|
{
"resource": ""
}
|
q47941
|
buildDistTable
|
train
|
function buildDistTable() {
var builds = getBuilds();
var branch = getCurBranch();
var colWidths = {
build: 0,
"min / gz": 0,
contents: 0,
descr: 0,
};
var appendix = [];
builds.forEach(function(build, i) {
var buildName = build.build;
var path = "dist/" + buildName + "/domvm." + buildName + ".min.js";
appendix.push("["+(i+1)+"]: https://github.com/domvm/domvm/blob/" + branch + "/" + path);
var minified = fs.readFileSync("./" + path, 'utf8');
var gzipped = zlib.gzipSync(minified, {level: 6});
var minLen = (minified.length / 1024).toFixed(1);
var gzLen = (gzipped.length / 1024).toFixed(1);
build["min / gz"] = minLen + "k / " + gzLen + "k";
build.build = "[" + buildName + "][" + (i+1) + "]";
for (var colName in colWidths)
colWidths[colName] = Math.max(colWidths[colName], build[colName].length);
});
var table = '';
for (var colName in colWidths)
table += "| " + padRight(colName, " ", colWidths[colName] + 1);
table += "|\n";
for (var colName in colWidths)
table += "| " + padRight("", "-", colWidths[colName]) + " ";
table += "|\n";
builds.forEach(function(build, i) {
for (var colName in colWidths)
table += "| " + padRight(build[colName], " ", colWidths[colName] + 1);
table += "|\n";
});
table += "\n" + appendix.join("\n");
fs.writeFileSync("./dist/README.md", table, 'utf8');
}
|
javascript
|
{
"resource": ""
}
|
q47942
|
deepSet
|
train
|
function deepSet(targ, path, val) {
var seg;
while (seg = path.shift()) {
if (path.length === 0)
{ targ[seg] = val; }
else
{ targ[seg] = targ = targ[seg] || {}; }
}
}
|
javascript
|
{
"resource": ""
}
|
q47943
|
patchStyle
|
train
|
function patchStyle(n, o) {
var ns = (n.attrs || emptyObj).style;
var os = o ? (o.attrs || emptyObj).style : null;
// replace or remove in full
if (ns == null || isVal(ns))
{ n.el.style.cssText = ns; }
else {
for (var nn in ns) {
var nv = ns[nn];
if (os == null || nv != null && nv !== os[nn])
{ n.el.style[nn] = autoPx(nn, nv); }
}
// clean old
if (os) {
for (var on in os) {
if (ns[on] == null)
{ n.el.style[on] = ""; }
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q47944
|
ViewModel
|
train
|
function ViewModel(view, data, key, opts) {
var vm = this;
vm.view = view;
vm.data = data;
vm.key = key;
if (opts) {
vm.opts = opts;
vm.cfg(opts);
}
var out = isPlainObj(view) ? view : view.call(vm, vm, data, key, opts);
if (isFunc(out))
{ vm.render = out; }
else {
vm.render = out.render;
vm.cfg(out);
}
vm.init && vm.init.call(vm, vm, vm.data, vm.key, opts);
}
|
javascript
|
{
"resource": ""
}
|
q47945
|
VView
|
train
|
function VView(view, data, key, opts) {
this.view = view;
this.data = data;
this.key = key;
this.opts = opts;
}
|
javascript
|
{
"resource": ""
}
|
q47946
|
rendMonth
|
train
|
function rendMonth(year, month) {
var prevEnd = daysInMonth(year, month - 1),
start = firstDayOfMonth(year, month),
end = daysInMonth(year, month),
// if start of month day < start of week cfg, roll back 1 wk
wkOffs = start < wkStart ? -7 : 0;
return el("table.month", [
el("caption", months[month]),
el("tr", wkdays.map(function(day) {
return el("th", day.substr(0,3));
})),
range(rows).map(function(r) {
return el("tr.week", range(cols).map(function(c) {
var idx = (r * cols + c) + wkOffs + wkStart,
off = idx - start + 1,
date = year+"-"+month+"-"+off,
cellClass = (idx < start || off > end ? ".dim" : "") + (!!api.selected[date] ? ".sel" : ""),
cellText = idx < start ? prevEnd + off : off > end ? off - end : off;
return el("td.day" + cellClass, {onclick: [api.selectDate, date]}, cellText);
}));
})
]);
}
|
javascript
|
{
"resource": ""
}
|
q47947
|
rendYear
|
train
|
function rendYear(vm, args) {
var prevYear = args.year - 1,
nextYear = args.year + 1;
return el(".year", [
el("header", [
el("button.prev", {onclick: [api.loadYear, prevYear]}, "< " + prevYear),
el("strong", {style: {fontSize: "18pt"}}, args.year),
el("button.next", {onclick: [api.loadYear, nextYear]}, nextYear + " >"),
]),
range(12).map(function(month) {
return rendMonth(args.year, month);
}),
]);
}
|
javascript
|
{
"resource": ""
}
|
q47948
|
CommentReplyView
|
train
|
function CommentReplyView(vm, comment) {
var redraw = vm.redraw.bind(vm);
var status = prop(LOADED, redraw);
var error;
var tmpComment = prop("", redraw);
function toggleReplyMode(e) {
status(INTERACTING);
return false;
}
function postComment(e) {
status(SUBMITTING);
// TODO: flatten? dry?
endPoints.postComment(tmpComment(), comment.id)
.then(comment2 => {
tmpComment("", false);
status(RELOADING);
return endPoints.getComments(comment.id);
})
.then(c => {
comment.children = Object.values(c.lookup).slice(1); // have to slice off self
status(LOADED, false);
vm.parent().redraw();
})
.catch(e => {
error = e;
status(ERROR);
});
return false;
}
function previewReply(e, node) {
tmpComment(node.el.value);
}
return function() {
return (
status() == ERROR ? errorTpl(error)
: status() == SUBMITTING ? statusTpl("Submitting comment...")
: status() == RELOADING ? statusTpl("Submitted! Reloading comments...")
: el(".reply", [
status() == INTERACTING ?
el("form", {onsubmit: postComment}, [
el("textarea", {
value: tmpComment(),
onkeyup: [previewReply],
}),
el("input", {type: "submit", value: "Reply!"}),
el(".preview", {".innerHTML": T.previewComment(tmpComment())}),
])
: el("a", {href: "#", onclick: toggleReplyMode}, "Reply!")
])
);
}
}
|
javascript
|
{
"resource": ""
}
|
q47949
|
updateSync
|
train
|
function updateSync(newData, newParent, newIdx, withDOM, withRedraw) {
var vm = this;
if (newData != null) {
if (vm.data !== newData) {
{
devNotify("DATA_REPLACED", [vm, vm.data, newData]);
}
fireHook(vm.hooks, "willUpdate", vm, newData);
vm.data = newData;
}
}
return withRedraw ? vm._redraw(newParent, newIdx, withDOM) : vm;
}
|
javascript
|
{
"resource": ""
}
|
q47950
|
UInt8ArraySerializer
|
train
|
function UInt8ArraySerializer(array, buffer, bufferOffset, specArrayLen=null) {
const arrLen = array.length;
if (specArrayLen === null || specArrayLen < 0) {
bufferOffset = buffer.writeUInt32LE(arrLen, bufferOffset, true);
}
buffer.set(array, bufferOffset);
return bufferOffset + arrLen;
}
|
javascript
|
{
"resource": ""
}
|
q47951
|
hashMessage
|
train
|
function hashMessage(msg) {
const sha1 = crypto.createHash('sha1');
sha1.update(msg);
return sha1.digest('hex');
}
|
javascript
|
{
"resource": ""
}
|
q47952
|
buildMessageClass
|
train
|
function buildMessageClass(msgSpec) {
function Message(values) {
if (!(this instanceof Message)) {
return new Message(values);
}
var that = this;
if (msgSpec.fields) {
msgSpec.fields.forEach(function(field) {
if (!field.isBuiltin) {
// sub-message class
// is it an array?
if (values && typeof values[field.name] != "undefined") {
// values provided
if (field.isArray) {
that[field.name] = values[field.name].map(function(value) {
return new (getMessageFromRegistry(field.baseType, 'msg'))(value);
});
} else {
that[field.name] =
new (getMessageFromRegistry(field.baseType, 'msg'))(values[field.name]);
}
} else {
// use defaults
if (field.isArray) {
// it's an array
const length = field.arrayLen || 0;
that[field.name] = new Array(length).fill(new (getMessageFromRegistry(field.baseType, 'msg'))());
} else {
that[field.name] = new (getMessageFromRegistry(field.baseType, 'msg'))();
}
}
} else {
// simple type
that[field.name] =
(values && typeof values[field.name] != "undefined") ?
values[field.name] :
(field.value || fieldsUtil.getDefaultValue(field.type));
}
});
}
};
Message.messageType = msgSpec.getFullMessageName();
// TODO: bring these back?
// Message.packageName = details.packageName;
// Message.messageName = Message.prototype.messageName = details.messageName;
// Message.md5 = Message.prototype.md5 = details.md5;
const md5Sum = msgSpec.getMd5sum();
Message.md5sum = function() {
return md5Sum;
};
Message.Constants = (() => {
const ret = {};
msgSpec.constants.forEach((constant) => {
ret[constant.name.toUpperCase()] = constant.value;
});
return ret;
})();
Message.fields = msgSpec.fields;
Message.serialize = function(obj, buffer, offset) {
serializeInnerMessage(msgSpec, obj, buffer, offset);
};
Message.deserialize = function(buffer) {
var message = new Message();
message = deserializeInnerMessage(msgSpec, message, buffer, [0]);
return message;
};
Message.getMessageSize = function(msg) { return fieldsUtil.getMessageSize(msg, msgSpec); };
const fullMsgDefinition = msgSpec.computeFullText();
Message.messageDefinition = function() { return fullMsgDefinition; };
Message.datatype = function() { return msgSpec.getFullMessageName(); };
return Message;
}
|
javascript
|
{
"resource": ""
}
|
q47953
|
DefaultArrayDeserializer
|
train
|
function DefaultArrayDeserializer(deserializeFunc, buffer, bufferOffset, arrayLen=null) {
// interpret a negative array len as a variable length array
// so we need to parse its length ourselves
if (arrayLen === null || arrayLen < 0) {
arrayLen = getArrayLen(buffer, bufferOffset);
}
const array = new Array(arrayLen);
for (let i = 0; i < arrayLen; ++i) {
array[i] = deserializeFunc(buffer, bufferOffset, null);
}
return array;
}
|
javascript
|
{
"resource": ""
}
|
q47954
|
UInt8ArrayDeserializer
|
train
|
function UInt8ArrayDeserializer(buffer, bufferOffset, arrayLen=null) {
if (arrayLen === null || arrayLen < 0) {
arrayLen = getArrayLen(buffer, bufferOffset);
}
const array = buffer.slice(bufferOffset[0], bufferOffset[0] + arrayLen);
bufferOffset[0] += arrayLen;
return array;
}
|
javascript
|
{
"resource": ""
}
|
q47955
|
interpose
|
train
|
function interpose(coll, separator) {
if (arguments.length === 1) {
separator = coll;
return function(xform) {
return new Interpose(separator, xform);
};
}
return seq(coll, interpose(separator));
}
|
javascript
|
{
"resource": ""
}
|
q47956
|
repeat
|
train
|
function repeat(coll, n) {
if (arguments.length === 1) {
n = coll;
return function(xform) {
return new Repeat(n, xform);
};
}
return seq(coll, repeat(n));
}
|
javascript
|
{
"resource": ""
}
|
q47957
|
takeNth
|
train
|
function takeNth(coll, nth) {
if (arguments.length === 1) {
nth = coll;
return function(xform) {
return new TakeNth(nth, xform);
};
}
return seq(coll, takeNth(nth));
}
|
javascript
|
{
"resource": ""
}
|
q47958
|
toArray
|
train
|
function toArray(coll, xform) {
if(!xform) {
return reduce(coll, arrayReducer, []);
}
return transduce(coll, xform, arrayReducer, []);
}
|
javascript
|
{
"resource": ""
}
|
q47959
|
destroy_next
|
train
|
function destroy_next() {
if (old_retired_workers.length <= 0) {
return deferred.resolve();
}
destroyWorker.call(_self, old_retired_workers.shift().pid, reason, 0);
setTimeout(destroy_next, _self.options.spawn_delay);
}
|
javascript
|
{
"resource": ""
}
|
q47960
|
isWorkerCmd
|
train
|
function isWorkerCmd(cmd) {
cmd = cmd.concat(); // make a local copy of the array
// a worker has the same command line as the current process!
if (cmd.shift() !== process.execPath) return false; // execPath was used when spawning children
// workers *may* have more params, we care if all master params exist in the worker cli
for (var idx = 0; idx < master_args.length; idx++) {
if (cmd[idx] !== master_args[idx]) return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q47961
|
collect_worker_stats
|
train
|
function collect_worker_stats(worker, worker_type) {
var stats;
var band = ('band' in worker) ? worker.band : worker.xband;
stats = worker.getStats();
if (!('monitor_count' in stats))
stats.monitor_count = 1;
else
stats.monitor_count++;
// TODO: if a given stats object has been used to many times, something is wrong!
if (!collected[band]) {
collected[band] = {
live: null, retired: []
};
}
if (worker_type === 'live') {
collected[band].live = stats;
}
else {
collected[band].retired.push(stats);
}
var worker_rss = (stats && stats.mem && stats.mem.rss) || 0;
cluster_rss += worker_rss;
return worker_rss;
}
|
javascript
|
{
"resource": ""
}
|
q47962
|
rule
|
train
|
function rule(analyzer) {
var debug = require('debug');
analyzer.setMetric('propertyResets');
analyzer.on('selector', function(rule, selector) {
var declarations = rule.declarations || [],
properties;
// prepare the list of properties used in this selector
properties = declarations.
map(function(declaration) {
return (declaration.type === 'declaration') ? declaration.property : false;
}).
filter(function(item) {
return item !== false;
});
debug('%s: %j', selector, properties);
// iterate through all properties, expand shorthand properties and
// check if there's no expanded version of it earlier in the array
properties.forEach(function(property, idx) {
var expanded;
// skip if the current property is not the shorthand version
if (typeof shorthandProperties.shorthandProperties[property] === 'undefined') {
return;
}
// property = 'margin'
// expanded = [ 'margin-top', 'margin-right', 'margin-bottom', 'margin-left' ]
expanded = shorthandProperties.expand(property);
debug('%s: %s', property, expanded.join(', '));
expanded.forEach(function(expandedProperty) {
var propertyPos = properties.indexOf(expandedProperty);
if (propertyPos > -1 && propertyPos < idx) {
analyzer.incrMetric('propertyResets');
analyzer.addOffender('propertyResets', format('%s: "%s" resets "%s" property set earlier', selector, property, expandedProperty));
}
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
q47963
|
rule
|
train
|
function rule(analyzer) {
analyzer.setMetric('notMinified');
/**
* A simple CSS minification detector
*/
function isMinified(css) {
// analyze the first 1024 characters
css = css.trim().substring(0, 1024);
// there should be no newline in minified file
return /\n/.test(css) === false;
}
analyzer.on('css', function(css) {
analyzer.setMetric('notMinified', isMinified(css) ? 0 : 1);
});
}
|
javascript
|
{
"resource": ""
}
|
q47964
|
rule
|
train
|
function rule(analyzer) {
var re = {
property: /^(\*|-ms-filter)/,
selector: /^(\* html|html\s?>\s?body) /,
value: /progid:DXImageTransform\.Microsoft|!ie$/
};
analyzer.setMetric('oldIEFixes');
// * html // below IE7 fix
// html>body // IE6 excluded fix
// @see http://blogs.msdn.com/b/ie/archive/2005/09/02/460115.aspx
analyzer.on('selector', function(rule, selector) {
if (re.selector.test(selector)) {
analyzer.incrMetric('oldIEFixes');
analyzer.addOffender('oldIEFixes', selector);
}
});
// *foo: bar // IE7 and below fix
// -ms-filter // IE9 and below specific property
// !ie // IE 7 and below equivalent of !important
// @see http://www.impressivewebs.com/ie7-ie8-css-hacks/
analyzer.on('declaration', function(rule, property, value) {
if (re.property.test(property) || re.value.test(value)) {
analyzer.incrMetric('oldIEFixes');
analyzer.addOffender('oldIEFixes', format('%s {%s: %s}', rule.selectors.join(', '), property, value));
}
});
}
|
javascript
|
{
"resource": ""
}
|
q47965
|
request
|
train
|
function request(requestOptions, callback) {
var debug = require('debug')('analyze-css:http'),
fetch = require('node-fetch');
debug('GET %s', requestOptions.url);
debug('Options: %j', requestOptions);
fetch(requestOptions.url, requestOptions).
then(function(resp) {
debug('HTTP %d %s', resp.status, resp.statusText);
debug('Headers: %j', resp.headers._headers);
if (!resp.ok) {
var err = new Error('HTTP request failed: ' + (err ? err.toString() : 'received HTTP ' + resp.status + ' ' + resp.statusText));
callback(err);
} else {
return resp.text(); // a promise
}
}).
then(function(body) {
debug('Received %d bytes of CSS', body.length);
callback(null, body);
}).
catch(function(err) {
debug(err);
callback(err);
});
}
|
javascript
|
{
"resource": ""
}
|
q47966
|
runner
|
train
|
function runner(options, callback) {
// call CommonJS module
var analyzerOpts = {
'noOffenders': options.noOffenders,
'preprocessor': false,
};
function analyze(css) {
new analyzer(css, analyzerOpts, callback);
}
if (options.url) {
debug('Fetching remote CSS file: %s', options.url);
// @see https://www.npmjs.com/package/node-fetch#options
var agentOptions = {},
requestOptions = {
url: options.url,
headers: {
'User-Agent': getUserAgent()
}
};
// handle options
// @see https://github.com/bitinn/node-fetch/issues/15
// @see https://nodejs.org/api/https.html#https_https_request_options_callback
if (options.ignoreSslErrors) {
agentOptions.rejectUnauthorized = false;
}
// @see https://gist.github.com/cojohn/1772154
if (options.authUser && options.authPass) {
requestOptions.headers.Authorization = "Basic " + new Buffer(options.authUser + ":" + options.authPass, "utf8").toString("base64");
}
// @see https://nodejs.org/api/http.html#http_class_http_agent
var client = require(/^https:/.test(options.url) ? 'https' : 'http');
requestOptions.agent = new client.Agent(agentOptions);
// @see http://stackoverflow.com/a/5810547
options.proxy = options.proxy || process.env.HTTP_PROXY;
if (options.proxy) {
debug('Using HTTP proxy: %s', options.proxy);
requestOptions.agent = new(require('http-proxy-agent'))(options.proxy);
}
request(requestOptions, function(err, css) {
if (err) {
err.code = analyzer.EXIT_URL_LOADING_FAILED;
debug(err);
callback(err);
} else {
analyze(css);
}
});
} else if (options.file) {
// resolve to the full path
options.file = resolve(process.cwd(), options.file);
debug('Loading local CSS file: %s', options.file);
fs.readFile(options.file, {
encoding: 'utf-8'
}, function(err, css) {
if (err) {
err = new Error('Loading CSS file failed: ' + err.toString());
err.code = analyzer.EXIT_FILE_LOADING_FAILED;
debug(err);
callback(err);
} else {
// find the matching preprocessor and use it
if (analyzerOpts.preprocessor === false) {
analyzerOpts.preprocessor = preprocessors.findMatchingByFileName(options.file);
}
// pass the name of the file being analyzed
analyzerOpts.file = options.file;
analyze(css);
}
});
} else if (options.stdin) {
debug('Reading from stdin');
cli.withStdin(analyze);
}
}
|
javascript
|
{
"resource": ""
}
|
q47967
|
FileWriter
|
train
|
function FileWriter (path, opts) {
if (!(this instanceof FileWriter)) return new FileWriter(path, opts);
Writer.call(this, opts);
this.path = path;
this.file = fs.createWriteStream(path, opts);
this.pipe(this.file);
this.on('header', this._onHeader);
}
|
javascript
|
{
"resource": ""
}
|
q47968
|
checkUnique
|
train
|
async function checkUnique (options, identifyUser, ownId, meta) {
debug('checkUnique', identifyUser, ownId, meta);
const usersService = options.app.service(options.service);
const usersServiceIdName = usersService.id;
const allProps = [];
const keys = Object.keys(identifyUser).filter(
key => !isNullsy(identifyUser[key])
);
try {
for (let i = 0, ilen = keys.length; i < ilen; i++) {
const prop = keys[i];
const users = await usersService.find({ query: { [prop]: identifyUser[prop].trim() } });
const items = Array.isArray(users) ? users : users.data;
const isNotUnique = items.length > 1 ||
(items.length === 1 && items[0][usersServiceIdName] !== ownId);
allProps.push(isNotUnique ? prop : null);
}
} catch (err) {
throw new errors.BadRequest(meta.noErrMsg ? null : 'checkUnique unexpected error.',
{ errors: { msg: err.message, $className: 'unexpected' } }
);
}
const errProps = allProps.filter(prop => prop);
if (errProps.length) {
const errs = {};
errProps.forEach(prop => { errs[prop] = 'Already taken.'; });
throw new errors.BadRequest(meta.noErrMsg ? null : 'Values already taken.',
{ errors: errs }
);
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q47969
|
AuthManagement
|
train
|
function AuthManagement (app) { // eslint-disable-line no-unused-vars
if (!(this instanceof AuthManagement)) {
return new AuthManagement(app);
}
const authManagement = app.service('authManagement');
this.checkUnique = async (identifyUser, ownId, ifErrMsg) => await authManagement.create({
action: 'checkUnique',
value: identifyUser,
ownId,
meta: { noErrMsg: ifErrMsg }
}, {});
this.resendVerifySignup = async (identifyUser, notifierOptions) => await authManagement.create({
action: 'resendVerifySignup',
value: identifyUser,
notifierOptions
}, {});
this.verifySignupLong = async (verifyToken) => await authManagement.create({
action: 'verifySignupLong',
value: verifyToken
}, {});
this.verifySignupShort = async (verifyShortToken, identifyUser) => await authManagement.create({
action: 'verifySignupShort',
value: { user: identifyUser, token: verifyShortToken }
}, {});
this.sendResetPwd = async (identifyUser, notifierOptions) => await authManagement.create({
action: 'sendResetPwd',
value: identifyUser,
notifierOptions
}, {});
this.resetPwdLong = async (resetToken, password) => await authManagement.create({
action: 'resetPwdLong',
value: { token: resetToken, password }
}, {});
this.resetPwdShort = async (resetShortToken, identifyUser, password) => await authManagement.create({
action: 'resetPwdShort',
value: { user: identifyUser, token: resetShortToken, password }
}, {});
this.passwordChange = async (oldPassword, password, identifyUser) => await authManagement.create({
action: 'passwordChange',
value: { user: identifyUser, oldPassword, password }
}, {});
this.identityChange = async (password, changesIdentifyUser, identifyUser) => await authManagement.create({
action: 'identityChange',
value: { user: identifyUser, password, changes: changesIdentifyUser }
}, {});
this.authenticate = async (email, password, cb) => {
let cbCalled = false;
return app.authenticate({ type: 'local', email, password })
.then(result => {
const user = result.data;
if (!user || !user.isVerified) {
app.logout();
return cb(new Error(user ? 'User\'s email is not verified.' : 'No user returned.'));
}
if (cb) {
cbCalled = true;
return cb(null, user);
}
return user;
})
.catch((err) => {
if (!cbCalled) {
cb(err);
}
});
};
}
|
javascript
|
{
"resource": ""
}
|
q47970
|
write
|
train
|
function write(destPath, options) {
var debug = require('../debug').spawn('write');
debug(function() { return 'destPath'; });
debug(function() { return destPath; });
debug(function() { return 'original options';});
debug(function() { return options; });
if (options === undefined && typeof destPath !== 'string') {
options = destPath;
destPath = undefined;
}
options = options || {};
// set defaults for options if unset
if (options.includeContent === undefined) {
options.includeContent = true;
}
if (options.addComment === undefined) {
options.addComment = true;
}
if (options.charset === undefined) {
options.charset = 'utf8';
}
debug(function() { return 'derrived options'; });
debug(function() { return options; });
var internals = internalsInit(destPath, options);
function sourceMapWrite(file, encoding, callback) {
if (file.isNull() || !file.sourceMap) {
this.push(file);
return callback();
}
if (file.isStream()) {
return callback(new Error(utils.PLUGIN_NAME + '-write: Streaming not supported'));
}
// fix paths if Windows style paths
file.sourceMap.file = unixStylePath(file.relative);
internals.setSourceRoot(file);
internals.loadContent(file);
internals.mapSources(file);
internals.mapDestPath(file, this);
this.push(file);
callback();
}
return through.obj(sourceMapWrite);
}
|
javascript
|
{
"resource": ""
}
|
q47971
|
checkPortStatus
|
train
|
function checkPortStatus (port) {
var args, host, opts, callback
args = [].slice.call(arguments, 1)
if (typeof args[0] === 'string') {
host = args[0]
} else if (typeof args[0] === 'object') {
opts = args[0]
} else if (typeof args[0] === 'function') {
callback = args[0]
}
if (typeof args[1] === 'object') {
opts = args[1]
} else if (typeof args[1] === 'function') {
callback = args[1]
}
if (typeof args[2] === 'function') {
callback = args[2]
}
if (!callback) return promisify(checkPortStatus, arguments)
opts = opts || {}
host = host || opts.host || '127.0.0.1'
var timeout = opts.timeout || 400
var connectionRefused = false
var socket = new Socket()
var status = null
var error = null
// Socket connection established, port is open
socket.on('connect', function () {
status = 'open'
socket.destroy()
})
// If no response, assume port is not listening
socket.setTimeout(timeout)
socket.on('timeout', function () {
status = 'closed'
error = new Error('Timeout (' + timeout + 'ms) occurred waiting for ' + host + ':' + port + ' to be available')
socket.destroy()
})
// Assuming the port is not open if an error. May need to refine based on
// exception
socket.on('error', function (exception) {
if (exception.code !== 'ECONNREFUSED') {
error = exception
} else {
connectionRefused = true
}
status = 'closed'
})
// Return after the socket has closed
socket.on('close', function (exception) {
if (exception && !connectionRefused) { error = error || exception } else { error = null }
callback(error, status)
})
socket.connect(port, host)
}
|
javascript
|
{
"resource": ""
}
|
q47972
|
train
|
function (callback) {
checkPortStatus(port, host, opts, function (error, statusOfPort) {
numberOfPortsChecked++
if (statusOfPort === status) {
foundPort = true
callback(error)
} else {
port = portList ? portList[numberOfPortsChecked] : port + 1
callback(null)
}
})
}
|
javascript
|
{
"resource": ""
}
|
|
q47973
|
fullScreen
|
train
|
function fullScreen(state)
{
var e, func, doc;
// Do nothing when nothing was selected
if (!this.length) return this;
// We only use the first selected element because it doesn't make sense
// to fullscreen multiple elements.
e = (/** @type {Element} */ this[0]);
// Find the real element and the document (Depends on whether the
// document itself or a HTML element was selected)
if (e.ownerDocument)
{
doc = e.ownerDocument;
}
else
{
doc = e;
e = doc.documentElement;
}
// When no state was specified then return the current state.
if (state == null)
{
// When fullscreen mode is not supported then return null
if (!((/** @type {?Function} */ doc["exitFullscreen"])
|| (/** @type {?Function} */ doc["webkitExitFullscreen"])
|| (/** @type {?Function} */ doc["webkitCancelFullScreen"])
|| (/** @type {?Function} */ doc["msExitFullscreen"])
|| (/** @type {?Function} */ doc["mozCancelFullScreen"])))
{
return null;
}
// Check fullscreen state
state = !!doc["fullscreenElement"]
|| !!doc["msFullscreenElement"]
|| !!doc["webkitIsFullScreen"]
|| !!doc["mozFullScreen"];
if (!state) return state;
// Return current fullscreen element or "true" if browser doesn't
// support this
return (/** @type {?Element} */ doc["fullscreenElement"])
|| (/** @type {?Element} */ doc["webkitFullscreenElement"])
|| (/** @type {?Element} */ doc["webkitCurrentFullScreenElement"])
|| (/** @type {?Element} */ doc["msFullscreenElement"])
|| (/** @type {?Element} */ doc["mozFullScreenElement"])
|| state;
}
// When state was specified then enter or exit fullscreen mode.
if (state)
{
// Enter fullscreen
func = (/** @type {?Function} */ e["requestFullscreen"])
|| (/** @type {?Function} */ e["webkitRequestFullscreen"])
|| (/** @type {?Function} */ e["webkitRequestFullScreen"])
|| (/** @type {?Function} */ e["msRequestFullscreen"])
|| (/** @type {?Function} */ e["mozRequestFullScreen"]);
if (func)
{
func.call(e);
}
return this;
}
else
{
// Exit fullscreen
func = (/** @type {?Function} */ doc["exitFullscreen"])
|| (/** @type {?Function} */ doc["webkitExitFullscreen"])
|| (/** @type {?Function} */ doc["webkitCancelFullScreen"])
|| (/** @type {?Function} */ doc["msExitFullscreen"])
|| (/** @type {?Function} */ doc["mozCancelFullScreen"]);
if (func) func.call(doc);
return this;
}
}
|
javascript
|
{
"resource": ""
}
|
q47974
|
installFullScreenHandlers
|
train
|
function installFullScreenHandlers()
{
var e, change, error;
// Determine event name
e = document;
if (e["webkitCancelFullScreen"])
{
change = "webkitfullscreenchange";
error = "webkitfullscreenerror";
}
else if (e["msExitFullscreen"])
{
change = "MSFullscreenChange";
error = "MSFullscreenError";
}
else if (e["mozCancelFullScreen"])
{
change = "mozfullscreenchange";
error = "mozfullscreenerror";
}
else
{
change = "fullscreenchange";
error = "fullscreenerror";
}
// Install the event handlers
jQuery(document).bind(change, fullScreenChangeHandler);
jQuery(document).bind(error, fullScreenErrorHandler);
}
|
javascript
|
{
"resource": ""
}
|
q47975
|
saveRouteToTheList
|
train
|
function saveRouteToTheList(parsedUrl, action) {
// used to add options routes later
if (typeof allRoutesList[parsedUrl.url] === 'undefined') {
allRoutesList[parsedUrl.url] = [];
}
allRoutesList[parsedUrl.url].push(action);
}
|
javascript
|
{
"resource": ""
}
|
q47976
|
decorateClassDoc
|
train
|
function decorateClassDoc(classDoc) {
// Resolve all methods and properties from the classDoc. Includes inherited docs.
classDoc.methods = resolveMethods(classDoc);
classDoc.properties = resolveProperties(classDoc);
// Call decorate hooks that can modify the method and property docs.
classDoc.methods.forEach(doc => decorateMethodDoc(doc));
classDoc.properties.forEach(doc => decoratePropertyDoc(doc));
// Categorize the current visited classDoc into its Angular type.
if (isDirective(classDoc)) {
classDoc.isDirective = true;
classDoc.directiveExportAs = getDirectiveExportAs(classDoc);
} else if (isService(classDoc)) {
classDoc.isService = true;
} else if (isNgModule(classDoc)) {
classDoc.isNgModule = true;
}
}
|
javascript
|
{
"resource": ""
}
|
q47977
|
decorateMethodDoc
|
train
|
function decorateMethodDoc(methodDoc) {
normalizeMethodParameters(methodDoc);
// Mark methods with a `void` return type so we can omit show the return type in the docs.
methodDoc.showReturns = methodDoc.returnType && methodDoc.returnType != 'void';
}
|
javascript
|
{
"resource": ""
}
|
q47978
|
decoratePropertyDoc
|
train
|
function decoratePropertyDoc(propertyDoc) {
propertyDoc.isDirectiveInput = isDirectiveInput(propertyDoc);
propertyDoc.directiveInputAlias = getDirectiveInputAlias(propertyDoc);
propertyDoc.isDirectiveOutput = isDirectiveOutput(propertyDoc);
propertyDoc.directiveOutputAlias = getDirectiveOutputAlias(propertyDoc);
}
|
javascript
|
{
"resource": ""
}
|
q47979
|
resolveMethods
|
train
|
function resolveMethods(classDoc) {
let methods = classDoc.members.filter(member => member.hasOwnProperty('parameters'));
if (classDoc.inheritedDoc) {
methods = methods.concat(resolveMethods(classDoc.inheritedDoc));
}
return methods;
}
|
javascript
|
{
"resource": ""
}
|
q47980
|
resolveProperties
|
train
|
function resolveProperties(classDoc) {
let properties = classDoc.members.filter(member => !member.hasOwnProperty('parameters'));
if (classDoc.inheritedDoc) {
properties = properties.concat(resolveProperties(classDoc.inheritedDoc));
}
return properties;
}
|
javascript
|
{
"resource": ""
}
|
q47981
|
onPageStable
|
train
|
function onPageStable() {
AxeBuilder(browser.driver)
.configure(this.config || {})
.analyze(results => handleResults(this, results));
}
|
javascript
|
{
"resource": ""
}
|
q47982
|
handleResults
|
train
|
function handleResults(context, results) {
if (checkedPages.indexOf(results.url) === -1) {
checkedPages.push(results.url);
results.violations.forEach(violation => {
let specName = `${violation.help} (${results.url})`;
let message = '\n' + buildMessage(violation);
context.addFailure(message, {specName});
});
}
}
|
javascript
|
{
"resource": ""
}
|
q47983
|
contains
|
train
|
function contains(container, contained, className) {
var current = contained;
while (current && current.ownerDocument && current.nodeType !== 11) {
if (className) {
if (current === container) {
return false;
}
if (current.className.indexOf(className) >= 0) { //current.classList.contains(className) doesn't work in IE9
return true;
}
} else {
if (current === container) {
return true;
}
}
current = current.parentNode;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q47984
|
intersection
|
train
|
function intersection(xArr, yArr, xFilter, yFilter, invert) {
var i, j, n, filteredX, filteredY, out = invert ? [].concat(xArr) : [];
for (i = 0, n = xArr.length; i < xArr.length; i++) {
filteredX = xFilter ? xFilter(xArr[i]) : xArr[i];
for (j = 0; j < yArr.length; j++) {
filteredY = yFilter ? yFilter(yArr[j]) : yArr[j];
if (angular.equals(filteredX, filteredY, xArr, yArr, i, j)) {
invert ? out.splice(i + out.length - n, 1) : out.push(yArr[j]);
break;
}
}
}
return out;
}
|
javascript
|
{
"resource": ""
}
|
q47985
|
getAction
|
train
|
function getAction(key) {
const keyString = key.toString();
if (keyString.match(/CERTIFICATE\sREQUEST-{5}$/m)) {
return 'req';
}
else if (keyString.match(/(PUBLIC|PRIVATE)\sKEY-{5}$/m)) {
return 'rsa';
}
return 'x509';
}
|
javascript
|
{
"resource": ""
}
|
q47986
|
generateCsr
|
train
|
async function generateCsr(opts, csrConfig, key) {
let tempConfigFilePath;
/* Write key to disk */
const tempKeyFilePath = tempfile();
await fs.writeFileAsync(tempKeyFilePath, key);
opts.key = tempKeyFilePath;
/* Write config to disk */
if (csrConfig) {
tempConfigFilePath = tempfile();
await fs.writeFileAsync(tempConfigFilePath, csrConfig);
opts.config = tempConfigFilePath;
}
/* Create CSR */
const result = await openssl('req', opts);
/* Clean up */
await fs.unlinkAsync(tempKeyFilePath);
if (tempConfigFilePath) {
await fs.unlinkAsync(tempConfigFilePath);
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q47987
|
createCsrSubject
|
train
|
function createCsrSubject(opts) {
const data = {
C: opts.country,
ST: opts.state,
L: opts.locality,
O: opts.organization,
OU: opts.organizationUnit,
CN: opts.commonName || 'localhost',
emailAddress: opts.emailAddress
};
return Object.entries(data).map(([key, value]) => {
value = (value || '').replace(/[^\w .*,@'-]+/g, ' ').trim();
return value ? `/${key}=${value}` : '';
}).join('');
}
|
javascript
|
{
"resource": ""
}
|
q47988
|
verifyHttpChallenge
|
train
|
async function verifyHttpChallenge(authz, challenge, keyAuthorization, suffix = `/.well-known/acme-challenge/${challenge.token}`) {
debug(`Sending HTTP query to ${authz.identifier.value}, suffix: ${suffix}`);
const challengeUrl = `http://${authz.identifier.value}${suffix}`;
const resp = await axios.get(challengeUrl);
debug(`Query successful, HTTP status code: ${resp.status}`);
if (!resp.data || (resp.data !== keyAuthorization)) {
throw new Error(`Authorization not found in HTTP response from ${authz.identifier.value}`);
}
debug(`Key authorization match for ${challenge.type}/${authz.identifier.value}, ACME challenge verified`);
return true;
}
|
javascript
|
{
"resource": ""
}
|
q47989
|
verifyDnsChallenge
|
train
|
async function verifyDnsChallenge(authz, challenge, keyAuthorization, prefix = '_acme-challenge.') {
debug(`Resolving DNS TXT records for ${authz.identifier.value}, prefix: ${prefix}`);
let challengeRecord = `${prefix}${authz.identifier.value}`;
try {
/* Attempt CNAME record first */
debug(`Checking CNAME for record ${challengeRecord}`);
const cnameRecords = await dns.resolveCnameAsync(challengeRecord);
if (cnameRecords.length) {
debug(`CNAME found at ${challengeRecord}, new challenge record: ${cnameRecords[0]}`);
challengeRecord = cnameRecords[0];
}
}
catch (e) {
debug(`No CNAME found for record ${challengeRecord}`);
}
/* Read TXT record */
const result = await dns.resolveTxtAsync(challengeRecord);
const records = [].concat(...result);
debug(`Query successful, found ${records.length} DNS TXT records`);
if (records.indexOf(keyAuthorization) === -1) {
throw new Error(`Authorization not found in DNS TXT records for ${authz.identifier.value}`);
}
debug(`Key authorization match for ${challenge.type}/${authz.identifier.value}, ACME challenge verified`);
return true;
}
|
javascript
|
{
"resource": ""
}
|
q47990
|
challengeRemoveFn
|
train
|
async function challengeRemoveFn(authz, challenge, keyAuthorization) {
/* Do something here */
log(JSON.stringify(authz));
log(JSON.stringify(challenge));
log(keyAuthorization);
}
|
javascript
|
{
"resource": ""
}
|
q47991
|
b64encode
|
train
|
function b64encode(str) {
const buf = Buffer.isBuffer(str) ? str : Buffer.from(str);
return b64escape(buf.toString('base64'));
}
|
javascript
|
{
"resource": ""
}
|
q47992
|
getPemBody
|
train
|
function getPemBody(str) {
const pemStr = Buffer.isBuffer(str) ? str.toString() : str;
return pemStr.replace(/(\s*-----(BEGIN|END) ([A-Z0-9- ]+)-----|\r|\n)*/g, '');
}
|
javascript
|
{
"resource": ""
}
|
q47993
|
formatResponseError
|
train
|
function formatResponseError(resp) {
let result;
if (resp.data.error) {
result = resp.data.error.detail || resp.data.error;
}
else {
result = resp.data.detail || JSON.stringify(resp.data);
}
return result.replace(/\n/g, '');
}
|
javascript
|
{
"resource": ""
}
|
q47994
|
forgeObjectFromPem
|
train
|
function forgeObjectFromPem(input) {
const msg = forge.pem.decode(input)[0];
let key;
switch (msg.type) {
case 'PRIVATE KEY':
case 'RSA PRIVATE KEY':
key = forge.pki.privateKeyFromPem(input);
break;
case 'PUBLIC KEY':
case 'RSA PUBLIC KEY':
key = forge.pki.publicKeyFromPem(input);
break;
case 'CERTIFICATE':
case 'X509 CERTIFICATE':
case 'TRUSTED CERTIFICATE':
key = forge.pki.certificateFromPem(input).publicKey;
break;
case 'CERTIFICATE REQUEST':
key = forge.pki.certificationRequestFromPem(input).publicKey;
break;
default:
throw new Error('Unable to detect forge message type');
}
return key;
}
|
javascript
|
{
"resource": ""
}
|
q47995
|
createPrivateKey
|
train
|
async function createPrivateKey(size = 2048) {
let pemKey;
/* Native implementation */
if (nativeGenKeyPair) {
const result = await nativeGenKeyPair('rsa', {
modulusLength: size,
publicKeyEncoding: { type: 'spki', format: 'pem' },
privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
});
pemKey = result[1];
}
/* Forge implementation */
else {
const keyPair = await forgeGenKeyPair({ bits: size });
pemKey = forge.pki.privateKeyToPem(keyPair.privateKey);
}
return Buffer.from(pemKey);
}
|
javascript
|
{
"resource": ""
}
|
q47996
|
createCsrSubject
|
train
|
function createCsrSubject(subjectObj) {
return Object.entries(subjectObj).reduce((result, [shortName, value]) => {
if (value) {
result.push({ shortName, value });
}
return result;
}, []);
}
|
javascript
|
{
"resource": ""
}
|
q47997
|
transformMedia
|
train
|
function transformMedia(media, customMedias) {
const transpiledMedias = [];
for (const index in media.nodes) {
const { value, nodes } = media.nodes[index];
const key = value.replace(customPseudoRegExp, '$1');
if (key in customMedias) {
for (const replacementMedia of customMedias[key].nodes) {
// use the first available modifier unless they cancel each other out
const modifier = media.modifier !== replacementMedia.modifier
? media.modifier || replacementMedia.modifier
: '';
const mediaClone = media.clone({
modifier,
// conditionally use the raws from the first available modifier
raws: !modifier || media.modifier
? { ...media.raws }
: { ...replacementMedia.raws },
type: media.type || replacementMedia.type,
});
// conditionally include more replacement raws when the type is present
if (mediaClone.type === replacementMedia.type) {
Object.assign(mediaClone.raws, {
and: replacementMedia.raws.and,
beforeAnd: replacementMedia.raws.beforeAnd,
beforeExpression: replacementMedia.raws.beforeExpression
});
}
mediaClone.nodes.splice(index, 1, ...replacementMedia.clone().nodes.map(node => {
// use raws and spacing from the current usage
if (media.nodes[index].raws.and) {
node.raws = { ...media.nodes[index].raws };
}
node.spaces = { ...media.nodes[index].spaces };
return node;
}));
// remove the currently transformed key to prevent recursion
const nextCustomMedia = getCustomMediasWithoutKey(customMedias, key);
const retranspiledMedias = transformMedia(mediaClone, nextCustomMedia);
if (retranspiledMedias.length) {
transpiledMedias.push(...retranspiledMedias);
} else {
transpiledMedias.push(mediaClone);
}
}
return transpiledMedias;
} else if (nodes && nodes.length) {
transformMediaList(media.nodes[index], customMedias);
}
}
return transpiledMedias;
}
|
javascript
|
{
"resource": ""
}
|
q47998
|
train
|
function(options) {
this.options = {
"debug": false,
"verbose": false,
"socket": "/tmp/node-mpv.sock"
}
this.options = _.defaults(options || {}, this.options);
// intialize the event emitter
eventEmitter.call(this);
// socket object
this.socket = new net.Socket();
// partially "fixes" the EventEmitter leak
// the leaking listeners is "close", but I did not yet find any solution to fix it
this.socket.setMaxListeners(0);
// connect
this.socket.connect({path: this.options.socket}, function() {
if(this.options.debug){
console.log("Connected to socket " + this.options.socket);
}
}.bind(this));
// reestablish connection when lost
this.socket.on('close', function() {
if(this.options.debug){
console.log("Lost connection to socket. Atemping to reconnect");
}
// properly close the connection
this.socket.end();
// reconnect
this.socket.connect({path: this.options.socket}, function() {
if(this.options.verbose || this.options.debug){
console.log("Connected to socket " + this.options.socket);
}
}.bind(this));
}.bind(this));
// catch errors when occurrings
this.socket.on('error', function(error) {
if(this.options.debug){
console.log(error);
}
}.bind(this));
// received data is delivered upwards by an event
this.socket.on('data', function(data) {
// various messages might be fetched at once
var messages = data.toString().split('\n');
// each message is emitted seperately
messages.forEach(function (message) {
// empty messages may occur
if(message.length > 0){
this.emit('message', JSON.parse(message));
}
}.bind(this));
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
|
q47999
|
train
|
function(file, mode, options) {
mode = mode || "replace";
const args = options ? [file, mode].concat(util.formatOptions(options)) : [file, mode];
this.socket.command("loadfile", args);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.