_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q27800 | getHeadingObject | train | function getHeadingObject (heading) {
var obj = {
id: heading.id,
children: [],
nodeName: heading.nodeName,
headingLevel: getHeadingLevel(heading),
textContent: heading.textContent.trim()
}
if (options.includeHtml) {
obj.childNodes = heading.childNodes
}
return obj
} | javascript | {
"resource": ""
} |
q27801 | addNode | train | function addNode (node, nest) {
var obj = getHeadingObject(node)
var level = getHeadingLevel(node)
var array = nest
var lastItem = getLastItem(array)
var lastItemLevel = lastItem
? lastItem.headingLevel
: 0
var counter = level - lastItemLevel
while (counter > 0) {
lastItem = getLastItem(array)
if (lastItem && lastItem.children !== undefined) {
array = lastItem.children
}
counter--
}
if (level >= options.collapseDepth) {
obj.isCollapsed = true
}
array.push(obj)
return array
} | javascript | {
"resource": ""
} |
q27802 | selectHeadings | train | function selectHeadings (contentSelector, headingSelector) {
var selectors = headingSelector
if (options.ignoreSelector) {
selectors = headingSelector.split(',')
.map(function mapSelectors (selector) {
return selector.trim() + ':not(' + options.ignoreSelector + ')'
})
}
try {
return document.querySelector(contentSelector)
.querySelectorAll(selectors)
} catch (e) {
console.warn('Element not found: ' + contentSelector); // eslint-disable-line
return null
}
} | javascript | {
"resource": ""
} |
q27803 | nestHeadingsArray | train | function nestHeadingsArray (headingsArray) {
return reduce.call(headingsArray, function reducer (prev, curr) {
var currentHeading = getHeadingObject(curr)
addNode(currentHeading, prev.nest)
return prev
}, {
nest: []
})
} | javascript | {
"resource": ""
} |
q27804 | createEl | train | function createEl (d, container) {
var link = container.appendChild(createLink(d))
if (d.children.length) {
var list = createList(d.isCollapsed)
d.children.forEach(function (child) {
createEl(child, list)
})
link.appendChild(list)
}
} | javascript | {
"resource": ""
} |
q27805 | render | train | function render (selector, data) {
var collapsed = false
var container = createList(collapsed)
data.forEach(function (d) {
createEl(d, container)
})
var parent = document.querySelector(selector)
// Return if no parent is found.
if (parent === null) {
return
}
// Remove existing child if it exists.
if (parent.firstChild) {
parent.removeChild(parent.firstChild)
}
// Just return the parent and don't append the list if no links are found.
if (data.length === 0) {
return parent
}
// Append the Elements that have been created
return parent.appendChild(container)
} | javascript | {
"resource": ""
} |
q27806 | createLink | train | function createLink (data) {
var item = document.createElement('li')
var a = document.createElement('a')
if (options.listItemClass) {
item.setAttribute('class', options.listItemClass)
}
if (options.onClick) {
a.onclick = options.onClick
}
if (options.includeHtml && data.childNodes.length) {
forEach.call(data.childNodes, function (node) {
a.appendChild(node.cloneNode(true))
})
} else {
// Default behavior.
a.textContent = data.textContent
}
a.setAttribute('href', '#' + data.id)
a.setAttribute('class', options.linkClass +
SPACE_CHAR + 'node-name--' + data.nodeName +
SPACE_CHAR + options.extraLinkClasses)
item.appendChild(a)
return item
} | javascript | {
"resource": ""
} |
q27807 | createList | train | function createList (isCollapsed) {
var listElement = (options.orderedList) ? 'ol' : 'ul'
var list = document.createElement(listElement)
var classes = options.listClass +
SPACE_CHAR + options.extraListClasses
if (isCollapsed) {
classes += SPACE_CHAR + options.collapsibleClass
classes += SPACE_CHAR + options.isCollapsedClass
}
list.setAttribute('class', classes)
return list
} | javascript | {
"resource": ""
} |
q27808 | updateFixedSidebarClass | train | function updateFixedSidebarClass () {
if (options.scrollContainer && document.querySelector(options.scrollContainer)) {
var top = document.querySelector(options.scrollContainer).scrollTop
} else {
var top = document.documentElement.scrollTop || body.scrollTop
}
var posFixedEl = document.querySelector(options.positionFixedSelector)
if (options.fixedSidebarOffset === 'auto') {
options.fixedSidebarOffset = document.querySelector(options.tocSelector).offsetTop
}
if (top > options.fixedSidebarOffset) {
if (posFixedEl.className.indexOf(options.positionFixedClass) === -1) {
posFixedEl.className += SPACE_CHAR + options.positionFixedClass
}
} else {
posFixedEl.className = posFixedEl.className.split(SPACE_CHAR + options.positionFixedClass).join('')
}
} | javascript | {
"resource": ""
} |
q27809 | getHeadingTopPos | train | function getHeadingTopPos (obj) {
var position = 0
if (obj != document.querySelector(options.contentSelector && obj != null)) {
position = obj.offsetTop
if (options.hasInnerContainers)
position += getHeadingTopPos(obj.offsetParent)
}
return position
} | javascript | {
"resource": ""
} |
q27810 | updateToc | train | function updateToc (headingsArray) {
// If a fixed content container was set
if (options.scrollContainer && document.querySelector(options.scrollContainer)) {
var top = document.querySelector(options.scrollContainer).scrollTop
} else {
var top = document.documentElement.scrollTop || body.scrollTop
}
// Add fixed class at offset
if (options.positionFixedSelector) {
updateFixedSidebarClass()
}
// Get the top most heading currently visible on the page so we know what to highlight.
var headings = headingsArray
var topHeader
// Using some instead of each so that we can escape early.
if (currentlyHighlighting &&
document.querySelector(options.tocSelector) !== null &&
headings.length > 0) {
some.call(headings, function (heading, i) {
if (getHeadingTopPos(heading) > top + options.headingsOffset + 10) {
// Don't allow negative index value.
var index = (i === 0) ? i : i - 1
topHeader = headings[index]
return true
} else if (i === headings.length - 1) {
// This allows scrolling for the last heading on the page.
topHeader = headings[headings.length - 1]
return true
}
})
// Remove the active class from the other tocLinks.
var tocLinks = document.querySelector(options.tocSelector)
.querySelectorAll('.' + options.linkClass)
forEach.call(tocLinks, function (tocLink) {
tocLink.className = tocLink.className.split(SPACE_CHAR + options.activeLinkClass).join('')
})
var tocLis = document.querySelector(options.tocSelector)
.querySelectorAll('.' + options.listItemClass)
forEach.call(tocLis, function (tocLi) {
tocLi.className = tocLi.className.split(SPACE_CHAR + options.activeListItemClass).join('')
})
// Add the active class to the active tocLink.
var activeTocLink = document.querySelector(options.tocSelector)
.querySelector('.' + options.linkClass +
'.node-name--' + topHeader.nodeName +
'[href="#' + topHeader.id + '"]')
if (activeTocLink.className.indexOf(options.activeLinkClass) === -1) {
activeTocLink.className += SPACE_CHAR + options.activeLinkClass
}
var li = activeTocLink.parentNode
if (li && li.className.indexOf(options.activeListItemClass) === -1) {
li.className += SPACE_CHAR + options.activeListItemClass
}
var tocLists = document.querySelector(options.tocSelector)
.querySelectorAll('.' + options.listClass + '.' + options.collapsibleClass)
// Collapse the other collapsible lists.
forEach.call(tocLists, function (list) {
if (list.className.indexOf(options.isCollapsedClass) === -1) {
list.className += SPACE_CHAR + options.isCollapsedClass
}
})
// Expand the active link's collapsible list and its sibling if applicable.
if (activeTocLink.nextSibling && activeTocLink.nextSibling.className.indexOf(options.isCollapsedClass) !== -1) {
activeTocLink.nextSibling.className = activeTocLink.nextSibling.className.split(SPACE_CHAR + options.isCollapsedClass).join('')
}
removeCollapsedFromParents(activeTocLink.parentNode.parentNode)
}
} | javascript | {
"resource": ""
} |
q27811 | removeCollapsedFromParents | train | function removeCollapsedFromParents (element) {
if (element.className.indexOf(options.collapsibleClass) !== -1 && element.className.indexOf(options.isCollapsedClass) !== -1) {
element.className = element.className.split(SPACE_CHAR + options.isCollapsedClass).join('')
return removeCollapsedFromParents(element.parentNode.parentNode)
}
return element
} | javascript | {
"resource": ""
} |
q27812 | disableTocAnimation | train | function disableTocAnimation (event) {
var target = event.target || event.srcElement
if (typeof target.className !== 'string' || target.className.indexOf(options.linkClass) === -1) {
return
}
// Bind to tocLink clicks to temporarily disable highlighting
// while smoothScroll is animating.
currentlyHighlighting = false
} | javascript | {
"resource": ""
} |
q27813 | raise | train | function raise (runCallback, identifier) {
$overlay.fadeOut(100);
$overhang.slideUp(attributes.speed, function () {
if (runCallback) {
attributes.callback(identifier !== null ? $element.data(identifier) : "");
}
});
} | javascript | {
"resource": ""
} |
q27814 | buildSrcCheckMinifiedSizeTask | train | async function buildSrcCheckMinifiedSizeTask() {
const stats = await fs.stat( './dist/Autolinker.min.js' );
const sizeInKb = stats.size / 1000;
const maxExpectedSizeInKb = 46;
if( sizeInKb > maxExpectedSizeInKb ) {
throw new Error( `
Minified file size of ${sizeInKb.toFixed( 2 )}kb is greater than max
expected minified size of ${maxExpectedSizeInKb}kb
This check is to make sure that a dependency is not accidentally
added which significantly inflates the size of Autolinker. If
additions to the codebase have been made though and a higher size
is expected, bump the 'maxExpectedSizeInKb' number in gulpfile.js
`.trim().replace( /^\t*/gm, '' ) );
}
} | javascript | {
"resource": ""
} |
q27815 | train | function(ndefMessageAsString) {
"use strict";
var ndefMessage = JSON.parse(ndefMessageAsString);
cordova.fireDocumentEvent("ndef", {
type: "ndef",
tag: {
ndefMessage: ndefMessage
}
});
} | javascript | {
"resource": ""
} | |
q27816 | train | function(pluginResult, payloadString) {
var payload = JSON.parse(payloadString),
ndefObjectAsString = JSON.stringify(decode(b64toArray(payload.data)));
pluginResult.callbackOk(ndefObjectAsString, true);
} | javascript | {
"resource": ""
} | |
q27817 | formatValues | train | function formatValues(values) {
var formatted = {};
for (var key in values) {
if (values.hasOwnProperty(key)) {
if (typeof values[key] === 'boolean') {
var position = key.indexOf('{');
if (position !== -1) {
if (values[key] === true) {
// Each options of SelectWidget are stored as boolean and grouped using '{' and '}'
// eg:
// gender{male} = true
// gender{female} = false
var newKey = key.substr(0, position);
var newValue = key.substr(position);
newValue = newValue.replace('{', '');
newValue = newValue.replace('}', '');
if (!Array.isArray(formatted[newKey])) {
formatted[newKey] = [];
}
formatted[newKey].push(newValue);
}
} else {
formatted[key] = values[key];
}
} else {
if (typeof values[key] === 'string') {
formatted[key] = values[key].trim();
} else {
formatted[key] = values[key];
}
}
}
}
return formatted;
} | javascript | {
"resource": ""
} |
q27818 | encodeRfc3986 | train | function encodeRfc3986(urlEncodedString) {
return urlEncodedString.replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase()
})
} | javascript | {
"resource": ""
} |
q27819 | getTemplate | train | function getTemplate(message, ec_level) {
var i = 1;
var len;
if (message.data1) {
len = Math.ceil(message.data1.length / 8);
} else {
i = 10;
}
for (/* i */; i < 10; i++) {
var version = versions[i][ec_level];
if (version.data_len >= len) {
return _deepCopy(version);
}
}
if (message.data10) {
len = Math.ceil(message.data10.length / 8);
} else {
i = 27;
}
for (/* i */; i < 27; i++) {
var version = versions[i][ec_level];
if (version.data_len >= len) {
return _deepCopy(version);
}
}
len = Math.ceil(message.data27.length / 8);
for (/* i */; i < 41; i++) {
var version = versions[i][ec_level];
if (version.data_len >= len) {
return _deepCopy(version);
}
}
throw new Error("Too much data");
} | javascript | {
"resource": ""
} |
q27820 | fillTemplate | train | function fillTemplate(message, template) {
var blocks = new Buffer(template.data_len);
blocks.fill(0);
if (template.version < 10) {
message = message.data1;
} else if (template.version < 27) {
message = message.data10;
} else {
message = message.data27;
}
var len = message.length;
for (var i = 0; i < len; i += 8) {
var b = 0;
for (var j = 0; j < 8; j++) {
b = (b << 1) | (message[i + j] ? 1 : 0);
}
blocks[i / 8] = b;
}
var pad = 236;
for (var i = Math.ceil((len + 4) / 8); i < blocks.length; i++) {
blocks[i] = pad;
pad = (pad == 236) ? 17 : 236;
}
var offset = 0;
template.blocks = template.blocks.map(function(n) {
var b = blocks.slice(offset, offset + n);
offset += n;
template.ec.push(calculateEC(b, template.ec_len));
return b;
});
return template;
} | javascript | {
"resource": ""
} |
q27821 | QR | train | function QR(text, ec_level, parse_url) {
ec_level = EC_LEVELS.indexOf(ec_level) > -1 ? ec_level : 'M';
var message = encode(text, parse_url);
var data = fillTemplate(message, getTemplate(message, ec_level));
return matrix.getMatrix(data);
} | javascript | {
"resource": ""
} |
q27822 | encode_8bit | train | function encode_8bit(data) {
var len = data.length;
var bits = [];
for (var i = 0; i < len; i++) {
pushBits(bits, 8, data[i]);
}
var res = {};
var d = [0, 1, 0, 0];
pushBits(d, 16, len);
res.data10 = res.data27 = d.concat(bits);
if (len < 256) {
var d = [0, 1, 0, 0];
pushBits(d, 8, len);
res.data1 = d.concat(bits);
}
return res;
} | javascript | {
"resource": ""
} |
q27823 | encode_numeric | train | function encode_numeric(str) {
var len = str.length;
var bits = [];
for (var i = 0; i < len; i += 3) {
var s = str.substr(i, 3);
var b = Math.ceil(s.length * 10 / 3);
pushBits(bits, b, parseInt(s, 10));
}
var res = {};
var d = [0, 0, 0, 1];
pushBits(d, 14, len);
res.data27 = d.concat(bits);
if (len < 4096) {
var d = [0, 0, 0, 1];
pushBits(d, 12, len);
res.data10 = d.concat(bits);
}
if (len < 1024) {
var d = [0, 0, 0, 1];
pushBits(d, 10, len);
res.data1 = d.concat(bits);
}
return res;
} | javascript | {
"resource": ""
} |
q27824 | encode_url | train | function encode_url(str) {
var slash = str.indexOf('/', 8) + 1 || str.length;
var res = encode(str.slice(0, slash).toUpperCase(), false);
if (slash >= str.length) {
return res;
}
var path_res = encode(str.slice(slash), false);
res.data27 = res.data27.concat(path_res.data27);
if (res.data10 && path_res.data10) {
res.data10 = res.data10.concat(path_res.data10);
}
if (res.data1 && path_res.data1) {
res.data1 = res.data1.concat(path_res.data1);
}
return res;
} | javascript | {
"resource": ""
} |
q27825 | encode | train | function encode(data, parse_url) {
var str;
var t = typeof data;
if (t == 'string' || t == 'number') {
str = '' + data;
data = new Buffer(str);
} else if (Buffer.isBuffer(data)) {
str = data.toString();
} else if (Array.isArray(data)) {
data = new Buffer(data);
str = data.toString();
} else {
throw new Error("Bad data");
}
if (/^[0-9]+$/.test(str)) {
if (data.length > 7089) {
throw new Error("Too much data");
}
return encode_numeric(str);
}
if (/^[0-9A-Z \$%\*\+\.\/\:\-]+$/.test(str)) {
if (data.length > 4296) {
throw new Error("Too much data");
}
return encode_alphanum(str);
}
if (parse_url && /^https?:/i.test(str)) {
return encode_url(str);
}
if (data.length > 2953) {
throw new Error("Too much data");
}
return encode_8bit(data);
} | javascript | {
"resource": ""
} |
q27826 | init | train | function init(version) {
var N = version * 4 + 17;
var matrix = [];
var zeros = new Buffer(N);
zeros.fill(0);
zeros = [].slice.call(zeros);
for (var i = 0; i < N; i++) {
matrix[i] = zeros.slice();
}
return matrix;
} | javascript | {
"resource": ""
} |
q27827 | fillFinders | train | function fillFinders(matrix) {
var N = matrix.length;
for (var i = -3; i <= 3; i++) {
for (var j = -3; j <= 3; j++) {
var max = Math.max(i, j);
var min = Math.min(i, j);
var pixel = (max == 2 && min >= -2) || (min == -2 && max <= 2) ? 0x80 : 0x81;
matrix[3 + i][3 + j] = pixel;
matrix[3 + i][N - 4 + j] = pixel;
matrix[N - 4 + i][3 + j] = pixel;
}
}
for (var i = 0; i < 8; i++) {
matrix[7][i] = matrix[i][7] =
matrix[7][N - i - 1] = matrix[i][N - 8] =
matrix[N - 8][i] = matrix[N - 1 - i][7] = 0x80;
}
} | javascript | {
"resource": ""
} |
q27828 | fillAlignAndTiming | train | function fillAlignAndTiming(matrix) {
var N = matrix.length;
if (N > 21) {
var len = N - 13;
var delta = Math.round(len / Math.ceil(len / 28));
if (delta % 2) delta++;
var res = [];
for (var p = len + 6; p > 10; p -= delta) {
res.unshift(p);
}
res.unshift(6);
for (var i = 0; i < res.length; i++) {
for (var j = 0; j < res.length; j++) {
var x = res[i], y = res[j];
if (matrix[x][y]) continue;
for (var r = -2; r <=2 ; r++) {
for (var c = -2; c <=2 ; c++) {
var max = Math.max(r, c);
var min = Math.min(r, c);
var pixel = (max == 1 && min >= -1) || (min == -1 && max <= 1) ? 0x80 : 0x81;
matrix[x + r][y + c] = pixel;
}
}
}
}
}
for (var i = 8; i < N - 8; i++) {
matrix[6][i] = matrix[i][6] = i % 2 ? 0x80 : 0x81;
}
} | javascript | {
"resource": ""
} |
q27829 | fillStub | train | function fillStub(matrix) {
var N = matrix.length;
for (var i = 0; i < 8; i++) {
if (i != 6) {
matrix[8][i] = matrix[i][8] = 0x80;
}
matrix[8][N - 1 - i] = 0x80;
matrix[N - 1 - i][8] = 0x80;
}
matrix[8][8] = 0x80;
matrix[N - 8][8] = 0x81;
if (N < 45) return;
for (var i = N - 11; i < N - 8; i++) {
for (var j = 0; j < 6; j++) {
matrix[i][j] = matrix[j][i] = 0x80;
}
}
} | javascript | {
"resource": ""
} |
q27830 | getMatrix | train | function getMatrix(data) {
var matrix = init(data.version);
fillFinders(matrix);
fillAlignAndTiming(matrix);
fillStub(matrix);
var penalty = Infinity;
var bestMask = 0;
for (var mask = 0; mask < 8; mask++) {
fillData(matrix, data, mask);
fillReserved(matrix, data.ec_level, mask);
var p = calculatePenalty(matrix);
if (p < penalty) {
penalty = p;
bestMask = mask;
}
}
fillData(matrix, data, bestMask);
fillReserved(matrix, data.ec_level, bestMask);
return matrix.map(function(row) {
return row.map(function(cell) {
return cell & 1;
});
});
} | javascript | {
"resource": ""
} |
q27831 | getPackageExportNames | train | function getPackageExportNames(packagePath) {
const packageMeta = getPackageMeta(packagePath);
const packageModulePath = path.join(packagePath, packageMeta.module);
const moduleFileSource = fs.readFileSync(packageModulePath, "utf8");
const { body } = esprima.parseModule(moduleFileSource);
return body.reduce((result, statement) => {
if (statement.type === "ExportDefaultDeclaration") {
return result.concat(["default"]);
}
if (statement.type === "ExportNamedDeclaration") {
return result.concat(getNamesFromDeclaration(statement));
}
return result;
}, []);
} | javascript | {
"resource": ""
} |
q27832 | offsetContainerProperty | train | function offsetContainerProperty(offsetProperty, coordinates, diff) {
return {
...coordinates,
containerPosition: {
...coordinates.containerPosition,
[offsetProperty]: coordinates.containerPosition[offsetProperty] + diff
}
};
} | javascript | {
"resource": ""
} |
q27833 | createViewportDeterminer | train | function createViewportDeterminer(props) {
const { viewportRect, panelRect, actionRect } = props;
return function isInViewport({ containerPosition }) {
const containerTop = actionRect.top + containerPosition.top;
const containerLeft = actionRect.left + containerPosition.left;
const containerRight = containerLeft + panelRect.width;
const containerBottom = containerTop + panelRect.height;
const result =
containerLeft >= viewportRect.left &&
containerTop >= viewportRect.top &&
containerRight <= viewportRect.right &&
containerBottom <= viewportRect.bottom;
return result;
};
} | javascript | {
"resource": ""
} |
q27834 | throwSassError | train | function throwSassError(sassError) {
throw new gutil.PluginError({
plugin: 'sass',
message: util.format("Sass error: '%s' on line %s of %s", sassError.message, sassError.line, sassError.file)
});
} | javascript | {
"resource": ""
} |
q27835 | Insert | train | function Insert (str, position) {
if (!this || this.constructor !== SimpleTextOperation) {
// => function was called without 'new'
return new Insert(str, position);
}
this.str = str;
this.position = position;
} | javascript | {
"resource": ""
} |
q27836 | Delete | train | function Delete (count, position) {
if (!this || this.constructor !== SimpleTextOperation) {
return new Delete(count, position);
}
this.count = count;
this.position = position;
} | javascript | {
"resource": ""
} |
q27837 | UndoManager | train | function UndoManager (maxItems) {
this.maxItems = maxItems || 50;
this.state = NORMAL_STATE;
this.dontCompose = false;
this.undoStack = [];
this.redoStack = [];
} | javascript | {
"resource": ""
} |
q27838 | getEmojiForWord | train | function getEmojiForWord(word) {
let translations = getAllEmojiForWord(word);
return translations[Math.floor(Math.random() * translations.length)];
} | javascript | {
"resource": ""
} |
q27839 | translate | train | function translate(sentence, onlyEmoji) {
let translation = '';
let words = sentence.split(' ');
for (let i = 0; i < words.length; i++ ) {
// Punctuation blows. Get all the punctuation at the start and end of the word.
// TODO: stop copy pasting this.
let firstSymbol = '';
let lastSymbol = '';
var word = words[i];
while (SYMBOLS.indexOf(word[0]) != -1) {
firstSymbol += word[0];
word = word.slice(1, word.length);
}
while (SYMBOLS.indexOf(word[word.length - 1]) != -1) {
lastSymbol += word[word.length - 1];
word = word.slice(0, word.length - 1);
}
if (onlyEmoji) {
firstSymbol = lastSymbol = ''
}
let translated = getEmojiForWord(word);
if (translated) {
translation += firstSymbol + translated + lastSymbol + ' ';
} else if (!onlyEmoji){
translation += firstSymbol + word + lastSymbol + ' '
}
}
return translation;
} | javascript | {
"resource": ""
} |
q27840 | train | function() {
var udpServer = dgram.createSocket('udp4');
// binding required for getting responses
udpServer.bind();
udpServer.on('error', function () {});
getUdpServer = function() {
return udpServer;
};
return getUdpServer();
} | javascript | {
"resource": ""
} | |
q27841 | UdpPoller | train | function UdpPoller(target, timeout, callback) {
UdpPoller.super_.call(this, target, timeout, callback);
} | javascript | {
"resource": ""
} |
q27842 | train | function(callback) {
console.log('Removing Checks');
async.series([
function(cb) { CheckEvent.collection.remove(cb); },
function(cb) { Check.collection.remove(cb); }
], callback);
} | javascript | {
"resource": ""
} | |
q27843 | HttpsPoller | train | function HttpsPoller(target, timeout, callback) {
HttpsPoller.super_.call(this, target, timeout, callback);
} | javascript | {
"resource": ""
} |
q27844 | HttpPoller | train | function HttpPoller(target, timeout, callback) {
HttpPoller.super_.call(this, target, timeout, callback);
} | javascript | {
"resource": ""
} |
q27845 | BasePoller | train | function BasePoller(target, timeout, callback) {
this.target = target;
this.timeout = timeout || 5000;
this.callback = callback;
this.isDebugEnabled = false;
this.initialize();
} | javascript | {
"resource": ""
} |
q27846 | train | function(req, res, next) {
Check
.find({ _id: req.params.id })
.select({qos: 0})
.findOne(function(err, check) {
if (err) return next(err);
if (!check) return res.json(404, { error: 'failed to load check ' + req.params.id });
req.check = check;
next();
});
} | javascript | {
"resource": ""
} | |
q27847 | train | function(req, res, next) {
Tag.findOne({ name: req.params.name }, function(err, tag) {
if (err) return next(err);
if (!tag) return res.json(404, { error: 'failed to load tag ' + req.params.name });
req.tag = tag;
next();
});
} | javascript | {
"resource": ""
} | |
q27848 | BaseHttpPoller | train | function BaseHttpPoller(target, timeout, callback) {
BaseHttpPoller.super_.call(this, target, timeout, callback);
} | javascript | {
"resource": ""
} |
q27849 | shallowCompare | train | function shallowCompare(instance, nextProps, nextState) {
return (
!shallowEqual(instance.props, nextProps) ||
!shallowEqual(instance.state, nextState)
);
} | javascript | {
"resource": ""
} |
q27850 | getIteratorFn | train | function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (
(ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL]) ||
maybeIterable[FAUX_ITERATOR_SYMBOL]
);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
} | javascript | {
"resource": ""
} |
q27851 | train | function(component, funcReturningState) {
return function(a, b, c, d, e, f) {
var partialState = funcReturningState.call(component, a, b, c, d, e, f);
if (partialState) {
component.setState(partialState);
}
};
} | javascript | {
"resource": ""
} | |
q27852 | train | function(component, key) {
// Memoize the setters.
var cache = component.__keySetters || (component.__keySetters = {});
return cache[key] || (cache[key] = createStateKeySetter(component, key));
} | javascript | {
"resource": ""
} | |
q27853 | kill | train | async function kill(pid) {
try {
process.kill(pid, 'SIGTERM')
} catch (err) {
if (err.code !== 'ESRCH') throw err
}
} | javascript | {
"resource": ""
} |
q27854 | cancelableify | train | function cancelableify(promise) {
promise.cancel = cancel;
var then = promise.then;
promise.then = function() {
var newPromise = then.apply(this, arguments);
return cancelableify(newPromise);
};
return promise;
} | javascript | {
"resource": ""
} |
q27855 | train | function(common, walletAccount, algo) {
// Errors
if(!common || !walletAccount || !algo) throw new Error('Missing argument !');
let r = undefined;
if (algo === "trezor") { // HW wallet
r = { 'priv': '' };
common.isHW = true;
} else if (!common.password) {
throw new Error('Missing argument !');
}
// Processing
if (algo === "pass:6k") { // Brain wallets
if (!walletAccount.encrypted && !walletAccount.iv) {
// Account private key is generated simply using a passphrase so it has no encrypted and iv
r = derivePassSha(common.password, 6000);
} else if (!walletAccount.encrypted || !walletAccount.iv) {
// Else if one is missing there is a problem
//console.log("Account might be compromised, missing encrypted or iv");
return false;
} else {
// Else child accounts have encrypted and iv so we decrypt
let pass = derivePassSha(common.password, 20);
let obj = {
ciphertext: CryptoJS.enc.Hex.parse(walletAccount.encrypted),
iv: convert.hex2ua(walletAccount.iv),
key: convert.hex2ua(pass.priv)
};
let d = decrypt(obj);
r = { 'priv': d };
}
} else if (algo === "pass:bip32") { // Wallets from PRNG
let pass = derivePassSha(common.password, 20);
let obj = {
ciphertext: CryptoJS.enc.Hex.parse(walletAccount.encrypted),
iv: convert.hex2ua(walletAccount.iv),
key: convert.hex2ua(pass.priv)
};
let d = decrypt(obj);
r = { 'priv': d };
} else if (algo === "pass:enc") { // Private Key wallets
let pass = derivePassSha(common.password, 20);
let obj = {
ciphertext: CryptoJS.enc.Hex.parse(walletAccount.encrypted),
iv: convert.hex2ua(walletAccount.iv),
key: convert.hex2ua(pass.priv)
};
let d = decrypt(obj);
r = { 'priv': d };
} else if (!r) {
//console.log("Unknown wallet encryption method");
return false;
}
// Result
common.privateKey = r.priv;
return true;
} | javascript | {
"resource": ""
} | |
q27856 | train | function(priv, network, _expectedAddress) {
// Errors
if (!priv || !network || !_expectedAddress) throw new Error('Missing argument !');
if (!Helpers.isPrivateKeyValid(priv)) throw new Error('Private key is not valid !');
//Processing
let expectedAddress = _expectedAddress.toUpperCase().replace(/-/g, '');
let kp = KeyPair.create(priv);
let address = Address.toAddress(kp.publicKey.toString(), network);
// Result
return address === expectedAddress;
} | javascript | {
"resource": ""
} | |
q27857 | train | function(data, key) {
// Errors
if (!data || !key) throw new Error('Missing argument !');
// Processing
let iv = nacl.randomBytes(16)
let encKey = convert.ua2words(key, 32);
let encIv = {
iv: convert.ua2words(iv, 16)
};
let encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Hex.parse(data), encKey, encIv);
// Result
return {
ciphertext: encrypted.ciphertext,
iv: iv,
key: key
};
} | javascript | {
"resource": ""
} | |
q27858 | train | function(privateKey, password) {
// Errors
if (!privateKey || !password) throw new Error('Missing argument !');
if (!Helpers.isPrivateKeyValid(privateKey)) throw new Error('Private key is not valid !');
// Processing
let pass = derivePassSha(password, 20);
let r = encrypt(privateKey, convert.hex2ua(pass.priv));
// Result
return {
ciphertext: CryptoJS.enc.Hex.stringify(r.ciphertext),
iv: convert.ua2hex(r.iv)
};
} | javascript | {
"resource": ""
} | |
q27859 | train | function(senderPriv, recipientPub, msg) {
// Errors
if (!senderPriv || !recipientPub || !msg) throw new Error('Missing argument !');
if (!Helpers.isPrivateKeyValid(senderPriv)) throw new Error('Private key is not valid !');
if (!Helpers.isPublicKeyValid(recipientPub)) throw new Error('Public key is not valid !');
// Processing
let iv = nacl.randomBytes(16)
//console.log("IV:", convert.ua2hex(iv));
let salt = nacl.randomBytes(32)
let encoded = _encode(senderPriv, recipientPub, msg, iv, salt);
// Result
return encoded;
} | javascript | {
"resource": ""
} | |
q27860 | train | function(recipientPrivate, senderPublic, _payload) {
// Errors
if(!recipientPrivate || !senderPublic || !_payload) throw new Error('Missing argument !');
if (!Helpers.isPrivateKeyValid(recipientPrivate)) throw new Error('Private key is not valid !');
if (!Helpers.isPublicKeyValid(senderPublic)) throw new Error('Public key is not valid !');
// Processing
let binPayload = convert.hex2ua(_payload);
let salt = new Uint8Array(binPayload.buffer, 0, 32);
let iv = new Uint8Array(binPayload.buffer, 32, 16);
let payload = new Uint8Array(binPayload.buffer, 48);
let sk = convert.hex2ua_reversed(recipientPrivate);
let pk = convert.hex2ua(senderPublic);
let shared = new Uint8Array(32);
let r = key_derive(shared, salt, sk, pk);
let encKey = r;
let encIv = {
iv: convert.ua2words(iv, 16)
};
let encrypted = {
'ciphertext': convert.ua2words(payload, payload.length)
};
let plain = CryptoJS.AES.decrypt(encrypted, encKey, encIv);
// Result
let hexplain = CryptoJS.enc.Hex.stringify(plain);
return hexplain;
} | javascript | {
"resource": ""
} | |
q27861 | updateFee | train | function updateFee() {
// Check for amount errors
if(undefined === $("#amount").val() || !nem.utils.helpers.isTextAmountValid($("#amount").val())) return alert('Invalid amount !');
// Set the cleaned amount into transfer transaction object
transferTransaction.amount = nem.utils.helpers.cleanTextAmount($("#amount").val());
// Set the message into transfer transaction object
transferTransaction.message = $("#message").val();
// Prepare the updated transfer transaction object
var transactionEntity = nem.model.transactions.prepare("transferTransaction")(common, transferTransaction, nem.model.network.data.testnet.id);
// Format fee returned in prepared object
var feeString = nem.utils.format.nemValue(transactionEntity.fee)[0] + "." + nem.utils.format.nemValue(transactionEntity.fee)[1];
//Set fee in view
$("#fee").html(feeString);
} | javascript | {
"resource": ""
} |
q27862 | send | train | function send() {
// Check form for errors
if(!$("#privateKey").val() || !$("#recipient").val()) return alert('Missing parameter !');
if(undefined === $("#amount").val() || !nem.utils.helpers.isTextAmountValid($("#amount").val())) return alert('Invalid amount !');
if (!nem.model.address.isValid(nem.model.address.clean($("#recipient").val()))) return alert('Invalid recipent address !');
// Set the private key in common object
common.privateKey = $("#privateKey").val();
// Check private key for errors
if (common.privateKey.length !== 64 && common.privateKey.length !== 66) return alert('Invalid private key, length must be 64 or 66 characters !');
if (!nem.utils.helpers.isHexadecimal(common.privateKey)) return alert('Private key must be hexadecimal only !');
// Set the cleaned amount into transfer transaction object
transferTransaction.amount = nem.utils.helpers.cleanTextAmount($("#amount").val());
// Recipient address must be clean (no hypens: "-")
transferTransaction.recipient = nem.model.address.clean($("#recipient").val());
// Set message
transferTransaction.message = $("#message").val();
// Prepare the updated transfer transaction object
var transactionEntity = nem.model.transactions.prepare("transferTransaction")(common, transferTransaction, nem.model.network.data.testnet.id);
// Serialize transfer transaction and announce
nem.model.transactions.send(common, transactionEntity, endpoint).then(function(res){
// If code >= 2, it's an error
if (res.code >= 2) {
alert(res.message);
} else {
alert(res.message);
}
}, function(err) {
alert(err);
});
} | javascript | {
"resource": ""
} |
q27863 | create | train | function create() {
// Check form for errors
if(!$("#privateKey").val() || !$("#recipient").val()) return alert('Missing parameter !');
if(undefined === $("#amount").val() || !nem.utils.helpers.isTextAmountValid($("#amount").val())) return alert('Invalid amount !');
if (!nem.model.address.isValid(nem.model.address.clean($("#recipient").val()))) return alert('Invalid recipent address !');
// Set the private key in common object
common.privateKey = $("#privateKey").val();
// Check private key for errors
if (common.privateKey.length !== 64 && common.privateKey.length !== 66) return alert('Invalid private key, length must be 64 or 66 characters !');
if (!nem.utils.helpers.isHexadecimal(common.privateKey)) return alert('Private key must be hexadecimal only !');
// Set the cleaned amount into transfer transaction object
transferTransaction.amount = nem.utils.helpers.cleanTextAmount($("#amount").val());
// Recipient address must be clean (no hypens: "-")
transferTransaction.recipient = nem.model.address.clean($("#recipient").val());
// Set message
transferTransaction.message = $("#message").val();
// Prepare the updated transfer transaction object
var transactionEntity = nem.model.transactions.prepare("transferTransaction")(common, transferTransaction, nem.model.network.data.testnet.id);
// Create a key pair object from private key
var kp = nem.crypto.keyPair.create(nem.utils.helpers.fixPrivateKey(common.privateKey));
// Serialize the transaction
var serialized = nem.utils.serialization.serializeTransaction(transactionEntity);
// Sign the serialized transaction with keypair object
var signature = kp.sign(serialized);
// Build the object to send
var result = {
'data': nem.utils.convert.ua2hex(serialized),
'signature': signature.toString()
};
// Show the object to send in view
$("#result").val(JSON.stringify(result));
} | javascript | {
"resource": ""
} |
q27864 | showTransactions | train | function showTransactions(height) {
// Set the block height in modal title
$('#txsHeight').html(height);
// Get the transactions for that block
var txs = transactions[height];
// Reset the modal body
$('#txs').html('');
// Loop transactions
for(var i = 0; i < txs.length; i++) {
// Add stringified transaction object to the modal body
$('#txs').append('<pre>'+JSON.stringify(txs[i])+'</pre>');
}
// Open modal
$('#myModal').modal('show');
} | javascript | {
"resource": ""
} |
q27865 | isFloating | train | function isFloating(item) {
return (
/left|right/.test(item.css('float')) ||
/inline|table-cell/.test(item.css('display'))
);
} | javascript | {
"resource": ""
} |
q27866 | train | function(e, ui) {
var logEntry = {
ID: $scope.sortingLog.length + 1,
Text: 'Moved element: ' + ui.item.scope().item.text
};
$scope.sortingLog.push(logEntry);
} | javascript | {
"resource": ""
} | |
q27867 | fakeTargetTask | train | function fakeTargetTask(prefix){
return function(){
if (this.args.length !== 1) {
return grunt.log.fail('Just give the name of the ' + prefix + ' you want like :\ngrunt ' + prefix + ':bower');
}
var done = this.async();
var spawn = require('child_process').spawn;
spawn('./node_modules/.bin/gulp', [ prefix, '--branch='+this.args[0] ].concat(grunt.option.flags()), {
cwd : './node_modules/angular-ui-publisher',
stdio: 'inherit'
}).on('close', done);
};
} | javascript | {
"resource": ""
} |
q27868 | train | function(configFile, customOptions) {
var options = { configFile: configFile, singleRun: true };
var travisOptions = process.env.TRAVIS && {
browsers: ['Chrome', 'Firefox'],
reporters: ['dots', 'coverage', 'coveralls'],
preprocessors: { 'src/*.js': ['coverage'] },
coverageReporter: {
reporters: [{
type: 'text'
}, {
type: 'lcov',
dir: 'coverage/'
}]
},
};
return grunt.util._.extend(options, customOptions, travisOptions);
} | javascript | {
"resource": ""
} | |
q27869 | train | function(message, parsedLine, snippet, parsedFile){
this.rawMessage = message;
this.parsedLine = (parsedLine !== undefined) ? parsedLine : -1;
this.snippet = (snippet !== undefined) ? snippet : null;
this.parsedFile = (parsedFile !== undefined) ? parsedFile : null;
this.updateRepr();
this.message = message;
} | javascript | {
"resource": ""
} | |
q27870 | train | function(file /* String */, callback /* Function */)
{
if ( callback == null )
{
var input = this.getFileContents(file);
var ret = null;
try
{
ret = this.parse(input);
}
catch ( e )
{
if ( e instanceof YamlParseException ) {
e.setParsedFile(file);
}
throw e;
}
return ret;
}
this.getFileContents(file, function(data)
{
callback(new Yaml().parse(data));
});
} | javascript | {
"resource": ""
} | |
q27871 | train | function(array, inline, spaces)
{
if ( inline == null ) inline = 2;
var yaml = new YamlDumper();
if (spaces) {
yaml.numSpacesForIndentation = spaces;
}
return yaml.dump(array, inline);
} | javascript | {
"resource": ""
} | |
q27872 | train | function(value)
{
var result = null;
value = this.trim(value);
if ( 0 == value.length )
{
return '';
}
switch ( value.charAt(0) )
{
case '[':
result = this.parseSequence(value);
break;
case '{':
result = this.parseMapping(value);
break;
default:
result = this.parseScalar(value);
}
// some comment can end the scalar
if ( value.substr(this.i+1).replace(/^\s*#.*$/, '') != '' ) {
console.log("oups "+value.substr(this.i+1));
throw new YamlParseException('Unexpected characters near "'+value.substr(this.i)+'".');
}
return result;
} | javascript | {
"resource": ""
} | |
q27873 | train | function(value)
{
if ( undefined == value || null == value )
return 'null';
if ( value instanceof Date)
return value.toISOString();
if ( typeof(value) == 'object')
return this.dumpObject(value);
if ( typeof(value) == 'boolean' )
return value ? 'true' : 'false';
if ( /^\d+$/.test(value) )
return typeof(value) == 'string' ? "'"+value+"'" : parseInt(value);
if ( this.isNumeric(value) )
return typeof(value) == 'string' ? "'"+value+"'" : parseFloat(value);
if ( typeof(value) == 'number' )
return value == Infinity ? '.Inf' : ( value == -Infinity ? '-.Inf' : ( isNaN(value) ? '.NAN' : value ) );
var yaml = new YamlEscaper();
if ( yaml.requiresDoubleQuoting(value) )
return yaml.escapeWithDoubleQuotes(value);
if ( yaml.requiresSingleQuoting(value) )
return yaml.escapeWithSingleQuotes(value);
if ( '' == value )
return '""';
if ( this.getTimestampRegex().test(value) )
return "'"+value+"'";
if ( this.inArray(value.toLowerCase(), ['null','~','true','false']) )
return "'"+value+"'";
// default
return value;
} | javascript | {
"resource": ""
} | |
q27874 | train | function(value)
{
var keys = this.getKeys(value);
var output = null;
var i;
var len = keys.length;
// array
if ( value instanceof Array )
/*( 1 == len && '0' == keys[0] )
||
( len > 1 && this.reduceArray(keys, function(v,w){return Math.floor(v+w);}, 0) == len * (len - 1) / 2) )*/
{
output = [];
for ( i = 0; i < len; i++ )
{
output.push(this.dump(value[keys[i]]));
}
return '['+output.join(', ')+']';
}
// mapping
output = [];
for ( i = 0; i < len; i++ )
{
output.push(this.dump(keys[i])+': '+this.dump(value[keys[i]]));
}
return '{ '+output.join(', ')+' }';
} | javascript | {
"resource": ""
} | |
q27875 | train | function(scalar, delimiters, stringDelimiters, i, evaluate)
{
if ( delimiters == undefined ) delimiters = null;
if ( stringDelimiters == undefined ) stringDelimiters = ['"', "'"];
if ( i == undefined ) i = 0;
if ( evaluate == undefined ) evaluate = true;
var output = null;
var pos = null;
var matches = null;
if ( this.inArray(scalar[i], stringDelimiters) )
{
// quoted scalar
output = this.parseQuotedScalar(scalar, i);
i = this.i;
if (null !== delimiters) {
var tmp = scalar.substr(i).replace(/^\s+/, '');
if (!this.inArray(tmp.charAt(0), delimiters)) {
throw new YamlParseException('Unexpected characters ('+scalar.substr(i)+').');
}
}
}
else
{
// "normal" string
if ( !delimiters )
{
output = (scalar+'').substring(i);
i += output.length;
// remove comments
pos = output.indexOf(' #');
if ( pos != -1 )
{
output = output.substr(0, pos).replace(/\s+$/g,'');
}
}
else if ( matches = new RegExp('^(.+?)('+delimiters.join('|')+')').exec((scalar+'').substring(i)) )
{
output = matches[1];
i += output.length;
}
else
{
throw new YamlParseException('Malformed inline YAML string ('+scalar+').');
}
output = evaluate ? this.evaluateScalar(output) : output;
}
this.i = i;
return output;
} | javascript | {
"resource": ""
} | |
q27876 | train | function(scalar, i)
{
var matches = null;
//var item = /^(.*?)['"]\s*(?:[,:]|[}\]]\s*,)/.exec((scalar+'').substring(i))[1];
if ( !(matches = new RegExp('^'+YamlInline.REGEX_QUOTED_STRING).exec((scalar+'').substring(i))) )
{
throw new YamlParseException('Malformed inline YAML string ('+(scalar+'').substring(i)+').');
}
var output = matches[0].substr(1, matches[0].length - 2);
var unescaper = new YamlUnescaper();
if ( '"' == (scalar+'').charAt(i) )
{
output = unescaper.unescapeDoubleQuotedString(output);
}
else
{
output = unescaper.unescapeSingleQuotedString(output);
}
i += matches[0].length;
this.i = i;
return output;
} | javascript | {
"resource": ""
} | |
q27877 | train | function(sequence, i)
{
if ( i == undefined ) i = 0;
var output = [];
var len = sequence.length;
i += 1;
// [foo, bar, ...]
while ( i < len )
{
switch ( sequence.charAt(i) )
{
case '[':
// nested sequence
output.push(this.parseSequence(sequence, i));
i = this.i;
break;
case '{':
// nested mapping
output.push(this.parseMapping(sequence, i));
i = this.i;
break;
case ']':
this.i = i;
return output;
case ',':
case ' ':
break;
default:
var isQuoted = this.inArray(sequence.charAt(i), ['"', "'"]);
var value = this.parseScalar(sequence, [',', ']'], ['"', "'"], i);
i = this.i;
if ( !isQuoted && (value+'').indexOf(': ') != -1 )
{
// embedded mapping?
try
{
value = this.parseMapping('{'+value+'}');
}
catch ( e )
{
if ( !(e instanceof YamlParseException ) ) throw e;
// no, it's not
}
}
output.push(value);
i--;
}
i++;
}
throw new YamlParseException('Malformed inline YAML string "'+sequence+'"');
} | javascript | {
"resource": ""
} | |
q27878 | train | function(mapping, i)
{
if ( i == undefined ) i = 0;
var output = {};
var len = mapping.length;
i += 1;
var done = false;
var doContinue = false;
// {foo: bar, bar:foo, ...}
while ( i < len )
{
doContinue = false;
switch ( mapping.charAt(i) )
{
case ' ':
case ',':
i++;
doContinue = true;
break;
case '}':
this.i = i;
return output;
}
if ( doContinue ) continue;
// key
var key = this.parseScalar(mapping, [':', ' '], ['"', "'"], i, false);
i = this.i;
// value
done = false;
while ( i < len )
{
switch ( mapping.charAt(i) )
{
case '[':
// nested sequence
output[key] = this.parseSequence(mapping, i);
i = this.i;
done = true;
break;
case '{':
// nested mapping
output[key] = this.parseMapping(mapping, i);
i = this.i;
done = true;
break;
case ':':
case ' ':
break;
default:
output[key] = this.parseScalar(mapping, [',', '}'], ['"', "'"], i);
i = this.i;
done = true;
i--;
}
++i;
if ( done )
{
doContinue = true;
break;
}
}
if ( doContinue ) continue;
}
throw new YamlParseException('Malformed inline YAML string "'+mapping+'"');
} | javascript | {
"resource": ""
} | |
q27879 | train | function(scalar)
{
scalar = this.trim(scalar);
var raw = null;
var cast = null;
if ( ( 'null' == scalar.toLowerCase() ) ||
( '' == scalar ) ||
( '~' == scalar ) )
return null;
if ( (scalar+'').indexOf('!str ') == 0 )
return (''+scalar).substring(5);
if ( (scalar+'').indexOf('! ') == 0 )
return parseInt(this.parseScalar((scalar+'').substr(2)));
if ( /^\d+$/.test(scalar) )
{
raw = scalar;
cast = parseInt(scalar);
return '0' == scalar.charAt(0) ? this.octdec(scalar) : (( ''+raw == ''+cast ) ? cast : raw);
}
if ( 'true' == (scalar+'').toLowerCase() )
return true;
if ( 'false' == (scalar+'').toLowerCase() )
return false;
if ( this.isNumeric(scalar) )
return '0x' == (scalar+'').substr(0, 2) ? this.hexdec(scalar) : parseFloat(scalar);
if ( scalar.toLowerCase() == '.inf' )
return Infinity;
if ( scalar.toLowerCase() == '.nan' )
return NaN;
if ( scalar.toLowerCase() == '-.inf' )
return -Infinity;
if ( /^(-|\+)?[0-9,]+(\.[0-9]+)?$/.test(scalar) )
return parseFloat(scalar.split(',').join(''));
if ( this.getTimestampRegex().test(scalar) )
return new Date(this.strtotime(scalar));
//else
return ''+scalar;
} | javascript | {
"resource": ""
} | |
q27880 | train | function(value /* String */)
{
this.currentLineNb = -1;
this.currentLine = '';
this.lines = this.cleanup(value).split("\n");
var data = null;
var context = null;
while ( this.moveToNextLine() )
{
if ( this.isCurrentLineEmpty() )
{
continue;
}
// tab?
if ( this.currentLine.charAt(0) == '\t' )
{
throw new YamlParseException('A YAML file cannot contain tabs as indentation.', this.getRealCurrentLineNb() + 1, this.currentLine);
}
var isRef = false;
var isInPlace = false;
var isProcessed = false;
var values = null;
var matches = null;
var c = null;
var parser = null;
var block = null;
var key = null;
var parsed = null;
var len = null;
var reverse = null;
if ( values = /^\-((\s+)(.+?))?\s*$/.exec(this.currentLine) )
{
if (context && 'mapping' == context) {
throw new YamlParseException('You cannot define a sequence item when in a mapping', this.getRealCurrentLineNb() + 1, this.currentLine);
}
context = 'sequence';
if ( !this.isDefined(data) ) data = [];
//if ( !(data instanceof Array) ) throw new YamlParseException("Non array entry", this.getRealCurrentLineNb() + 1, this.currentLine);
values = {leadspaces: values[2], value: values[3]};
if ( this.isDefined(values.value) && ( matches = /^&([^ ]+) *(.*)/.exec(values.value) ) )
{
matches = {ref: matches[1], value: matches[2]};
isRef = matches.ref;
values.value = matches.value;
}
// array
if ( !this.isDefined(values.value) || '' == this.trim(values.value) || values.value.replace(/^ +/,'').charAt(0) == '#' )
{
c = this.getRealCurrentLineNb() + 1;
parser = new YamlParser(c);
parser.refs = this.refs;
data.push(parser.parse(this.getNextEmbedBlock()));
this.refs = parser.refs;
}
else
{
if ( this.isDefined(values.leadspaces) &&
' ' == values.leadspaces &&
( matches = new RegExp('^('+YamlInline.REGEX_QUOTED_STRING+'|[^ \'"\{\[].*?) *\:(\\s+(.+?))?\\s*$').exec(values.value) )
) {
matches = {key: matches[1], value: matches[3]};
// this is a compact notation element, add to next block and parse
c = this.getRealCurrentLineNb();
parser = new YamlParser(c);
parser.refs = this.refs;
block = values.value;
if ( !this.isNextLineIndented() )
{
block += "\n"+this.getNextEmbedBlock(this.getCurrentLineIndentation() + 2);
}
data.push(parser.parse(block));
this.refs = parser.refs;
}
else
{
data.push(this.parseValue(values.value));
}
}
}
else if ( values = new RegExp('^('+YamlInline.REGEX_QUOTED_STRING+'|[^ \'"\[\{].*?) *\:(\\s+(.+?))?\\s*$').exec(this.currentLine) )
{
if ( !this.isDefined(data) ) data = {};
if (context && 'sequence' == context) {
throw new YamlParseException('You cannot define a mapping item when in a sequence', this.getRealCurrentLineNb() + 1, this.currentLine);
}
context = 'mapping';
//if ( data instanceof Array ) throw new YamlParseException("Non mapped entry", this.getRealCurrentLineNb() + 1, this.currentLine);
values = {key: values[1], value: values[3]};
try {
key = new YamlInline().parseScalar(values.key);
} catch (e) {
if ( e instanceof YamlParseException ) {
e.setParsedLine(this.getRealCurrentLineNb() + 1);
e.setSnippet(this.currentLine);
}
throw e;
}
if ( '<<' == key )
{
if ( this.isDefined(values.value) && '*' == (values.value+'').charAt(0) )
{
isInPlace = values.value.substr(1);
if ( this.refs[isInPlace] == undefined )
{
throw new YamlParseException('Reference "'+value+'" does not exist', this.getRealCurrentLineNb() + 1, this.currentLine);
}
}
else
{
if ( this.isDefined(values.value) && values.value != '' )
{
value = values.value;
}
else
{
value = this.getNextEmbedBlock();
}
c = this.getRealCurrentLineNb() + 1;
parser = new YamlParser(c);
parser.refs = this.refs;
parsed = parser.parse(value);
this.refs = parser.refs;
var merged = [];
if ( !this.isObject(parsed) )
{
throw new YamlParseException("YAML merge keys used with a scalar value instead of an array", this.getRealCurrentLineNb() + 1, this.currentLine);
}
else if ( this.isDefined(parsed[0]) )
{
// Numeric array, merge individual elements
reverse = this.reverseArray(parsed);
len = reverse.length;
for ( var i = 0; i < len; i++ )
{
var parsedItem = reverse[i];
if ( !this.isObject(reverse[i]) )
{
throw new YamlParseException("Merge items must be arrays", this.getRealCurrentLineNb() + 1, this.currentLine);
}
merged = this.mergeObject(reverse[i], merged);
}
}
else
{
// Associative array, merge
merged = this.mergeObject(merged, parsed);
}
isProcessed = merged;
}
}
else if ( this.isDefined(values.value) && (matches = /^&([^ ]+) *(.*)/.exec(values.value) ) )
{
matches = {ref: matches[1], value: matches[2]};
isRef = matches.ref;
values.value = matches.value;
}
if ( isProcessed )
{
// Merge keys
data = isProcessed;
}
// hash
else if ( !this.isDefined(values.value) || '' == this.trim(values.value) || this.trim(values.value).charAt(0) == '#' )
{
// if next line is less indented or equal, then it means that the current value is null
if ( this.isNextLineIndented() && !this.isNextLineUnIndentedCollection() )
{
data[key] = null;
}
else
{
c = this.getRealCurrentLineNb() + 1;
parser = new YamlParser(c);
parser.refs = this.refs;
data[key] = parser.parse(this.getNextEmbedBlock());
this.refs = parser.refs;
}
}
else
{
if ( isInPlace )
{
data = this.refs[isInPlace];
}
else
{
data[key] = this.parseValue(values.value);
}
}
}
else
{
// 1-liner followed by newline
if ( 2 == this.lines.length && this.isEmpty(this.lines[1]) )
{
try {
value = new YamlInline().parse(this.lines[0]);
} catch (e) {
if ( e instanceof YamlParseException ) {
e.setParsedLine(this.getRealCurrentLineNb() + 1);
e.setSnippet(this.currentLine);
}
throw e;
}
if ( this.isObject(value) )
{
var first = value[0];
if ( typeof(value) == 'string' && '*' == first.charAt(0) )
{
data = [];
len = value.length;
for ( var i = 0; i < len; i++ )
{
data.push(this.refs[value[i].substr(1)]);
}
value = data;
}
}
return value;
}
throw new YamlParseException('Unable to parse.', this.getRealCurrentLineNb() + 1, this.currentLine);
}
if ( isRef )
{
if ( data instanceof Array )
this.refs[isRef] = data[data.length-1];
else
{
var lastKey = null;
for ( var k in data )
{
if ( data.hasOwnProperty(k) ) lastKey = k;
}
this.refs[isRef] = data[k];
}
}
}
return this.isEmpty(data) ? null : data;
} | javascript | {
"resource": ""
} | |
q27881 | train | function(indentation)
{
this.moveToNextLine();
var newIndent = null;
var indent = null;
if ( !this.isDefined(indentation) )
{
newIndent = this.getCurrentLineIndentation();
var unindentedEmbedBlock = this.isStringUnIndentedCollectionItem(this.currentLine);
if ( !this.isCurrentLineEmpty() && 0 == newIndent && !unindentedEmbedBlock )
{
throw new YamlParseException('Indentation problem A', this.getRealCurrentLineNb() + 1, this.currentLine);
}
}
else
{
newIndent = indentation;
}
var data = [this.currentLine.substr(newIndent)];
var isUnindentedCollection = this.isStringUnIndentedCollectionItem(this.currentLine);
var continuationIndent = -1;
if (isUnindentedCollection === true) {
continuationIndent = 1 + /^\-((\s+)(.+?))?\s*$/.exec(this.currentLine)[2].length;
}
while ( this.moveToNextLine() )
{
if (isUnindentedCollection && !this.isStringUnIndentedCollectionItem(this.currentLine) && this.getCurrentLineIndentation() != continuationIndent) {
this.moveToPreviousLine();
break;
}
if ( this.isCurrentLineEmpty() )
{
if ( this.isCurrentLineBlank() )
{
data.push(this.currentLine.substr(newIndent));
}
continue;
}
indent = this.getCurrentLineIndentation();
var matches;
if ( matches = /^( *)$/.exec(this.currentLine) )
{
// empty line
data.push(matches[1]);
}
else if ( indent >= newIndent )
{
data.push(this.currentLine.substr(newIndent));
}
else if ( 0 == indent )
{
this.moveToPreviousLine();
break;
}
else
{
throw new YamlParseException('Indentation problem B', this.getRealCurrentLineNb() + 1, this.currentLine);
}
}
return data.join("\n");
} | javascript | {
"resource": ""
} | |
q27882 | train | function(value)
{
if ( '*' == (value+'').charAt(0) )
{
if ( this.trim(value).charAt(0) == '#' )
{
value = (value+'').substr(1, value.indexOf('#') - 2);
}
else
{
value = (value+'').substr(1);
}
if ( this.refs[value] == undefined )
{
throw new YamlParseException('Reference "'+value+'" does not exist', this.getRealCurrentLineNb() + 1, this.currentLine);
}
return this.refs[value];
}
var matches = null;
if ( matches = /^(\||>)(\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?( +#.*)?$/.exec(value) )
{
matches = {separator: matches[1], modifiers: matches[2], comments: matches[3]};
var modifiers = this.isDefined(matches.modifiers) ? matches.modifiers : '';
return this.parseFoldedScalar(matches.separator, modifiers.replace(/\d+/g, ''), Math.abs(parseInt(modifiers)));
}
try {
return new YamlInline().parse(value);
} catch (e) {
if ( e instanceof YamlParseException ) {
e.setParsedLine(this.getRealCurrentLineNb() + 1);
e.setSnippet(this.currentLine);
}
throw e;
}
} | javascript | {
"resource": ""
} | |
q27883 | train | function(separator, indicator, indentation)
{
if ( indicator == undefined ) indicator = '';
if ( indentation == undefined ) indentation = 0;
separator = '|' == separator ? "\n" : ' ';
var text = '';
var diff = null;
var notEOF = this.moveToNextLine();
while ( notEOF && this.isCurrentLineBlank() )
{
text += "\n";
notEOF = this.moveToNextLine();
}
if ( !notEOF )
{
return '';
}
var matches = null;
if ( !(matches = new RegExp('^('+(indentation ? this.strRepeat(' ', indentation) : ' +')+')(.*)$').exec(this.currentLine)) )
{
this.moveToPreviousLine();
return '';
}
matches = {indent: matches[1], text: matches[2]};
var textIndent = matches.indent;
var previousIndent = 0;
text += matches.text + separator;
while ( this.currentLineNb + 1 < this.lines.length )
{
this.moveToNextLine();
if ( matches = new RegExp('^( {'+textIndent.length+',})(.+)$').exec(this.currentLine) )
{
matches = {indent: matches[1], text: matches[2]};
if ( ' ' == separator && previousIndent != matches.indent )
{
text = text.substr(0, text.length - 1)+"\n";
}
previousIndent = matches.indent;
diff = matches.indent.length - textIndent.length;
text += this.strRepeat(' ', diff) + matches.text + (diff != 0 ? "\n" : separator);
}
else if ( matches = /^( *)$/.exec(this.currentLine) )
{
text += matches[1].replace(new RegExp('^ {1,'+textIndent.length+'}','g'), '')+"\n";
}
else
{
this.moveToPreviousLine();
break;
}
}
if ( ' ' == separator )
{
// replace last separator by a newline
text = text.replace(/ (\n*)$/g, "\n$1");
}
switch ( indicator )
{
case '':
text = text.replace(/\n+$/g, "\n");
break;
case '+':
break;
case '-':
text = text.replace(/\n+$/g, '');
break;
}
return text;
} | javascript | {
"resource": ""
} | |
q27884 | train | function(value)
{
value = value.split("\r\n").join("\n").split("\r").join("\n");
if ( !/\n$/.test(value) )
{
value += "\n";
}
// strip YAML header
var count = 0;
var regex = /^\%YAML[: ][\d\.]+.*\n/;
while ( regex.test(value) )
{
value = value.replace(regex, '');
count++;
}
this.offset += count;
// remove leading comments
regex = /^(#.*?\n)+/;
if ( regex.test(value) )
{
var trimmedValue = value.replace(regex, '');
// items have been removed, update the offset
this.offset += this.subStrCount(value, "\n") - this.subStrCount(trimmedValue, "\n");
value = trimmedValue;
}
// remove start of the document marker (---)
regex = /^\-\-\-.*?\n/;
if ( regex.test(value) )
{
trimmedValue = value.replace(regex, '');
// items have been removed, update the offset
this.offset += this.subStrCount(value, "\n") - this.subStrCount(trimmedValue, "\n");
value = trimmedValue;
// remove end of the document marker (...)
value = value.replace(/\.\.\.\s*$/g, '');
}
return value;
} | javascript | {
"resource": ""
} | |
q27885 | train | function(value)
{
value = value + '';
var len = YamlEscaper.escapees.length;
var maxlen = YamlEscaper.escaped.length;
var esc = YamlEscaper.escaped;
for (var i = 0; i < len; ++i)
if ( i >= maxlen ) esc.push('');
var ret = '';
ret = value.replace(new RegExp(YamlEscaper.escapees.join('|'),'g'), function(str){
for(var i = 0; i < len; ++i){
if( str == YamlEscaper.escapees[i] )
return esc[i];
}
});
return '"' + ret + '"';
} | javascript | {
"resource": ""
} | |
q27886 | train | function(value)
{
var callback = function(m) {
return new YamlUnescaper().unescapeCharacter(m);
};
// evaluate the string
return value.replace(new RegExp(YamlUnescaper.REGEX_ESCAPED_CHARACTER, 'g'), callback);
} | javascript | {
"resource": ""
} | |
q27887 | train | function(value)
{
switch (value.charAt(1)) {
case '0':
return String.fromCharCode(0);
case 'a':
return String.fromCharCode(7);
case 'b':
return String.fromCharCode(8);
case 't':
return "\t";
case "\t":
return "\t";
case 'n':
return "\n";
case 'v':
return String.fromCharCode(11);
case 'f':
return String.fromCharCode(12);
case 'r':
return String.fromCharCode(13);
case 'e':
return "\x1b";
case ' ':
return ' ';
case '"':
return '"';
case '/':
return '/';
case '\\':
return '\\';
case 'N':
// U+0085 NEXT LINE
return "\x00\x85";
case '_':
// U+00A0 NO-BREAK SPACE
return "\x00\xA0";
case 'L':
// U+2028 LINE SEPARATOR
return "\x20\x28";
case 'P':
// U+2029 PARAGRAPH SEPARATOR
return "\x20\x29";
case 'x':
return this.pack('n', new YamlInline().hexdec(value.substr(2, 2)));
case 'u':
return this.pack('n', new YamlInline().hexdec(value.substr(2, 4)));
case 'U':
return this.pack('N', new YamlInline().hexdec(value.substr(2, 8)));
}
} | javascript | {
"resource": ""
} | |
q27888 | train | function(input, inline, indent)
{
if ( inline == null ) inline = 0;
if ( indent == null ) indent = 0;
var output = '';
var prefix = indent ? this.strRepeat(' ', indent) : '';
var yaml;
if (!this.numSpacesForIndentation) this.numSpacesForIndentation = 2;
if ( inline <= 0 || !this.isObject(input) || this.isEmpty(input) )
{
yaml = new YamlInline();
output += prefix + yaml.dump(input);
}
else
{
var isAHash = !this.arrayEquals(this.getKeys(input), this.range(0,input.length - 1));
var willBeInlined;
for ( var key in input )
{
if ( input.hasOwnProperty(key) )
{
willBeInlined = inline - 1 <= 0 || !this.isObject(input[key]) || this.isEmpty(input[key]);
if ( isAHash ) yaml = new YamlInline();
output +=
prefix + '' +
(isAHash ? yaml.dump(key)+':' : '-') + '' +
(willBeInlined ? ' ' : "\n") + '' +
this.dump(input[key], inline - 1, (willBeInlined ? 0 : indent + this.numSpacesForIndentation)) + '' +
(willBeInlined ? "\n" : '');
}
}
}
return output;
} | javascript | {
"resource": ""
} | |
q27889 | register | train | function register(handlebars) {
handlebars.registerHelper('escape', function(variable) {
return variable.replace(/['"]/g, '\\"').replace(/[\n]/g, '\\n');
});
} | javascript | {
"resource": ""
} |
q27890 | strategyInterceptor | train | function strategyInterceptor(strategy) {
var interceptor = function(layout) {
var start = new Date().getMilliseconds();
var finalLayout = strategy(data);
var time = new Date().getMilliseconds() - start;
// record some statistics on this strategy
if (!interceptor.time) {
Object.defineProperty(interceptor, 'time', { enumerable: false, writable: true });
}
interceptor.time = time;
return finalLayout;
};
interceptor.bucketSize = function() {
return strategy.bucketSize.apply(this, arguments);
};
return interceptor;
} | javascript | {
"resource": ""
} |
q27891 | basePick | train | function basePick(object, props) {
object = Object(object);
const { length } = props;
const result = {};
let index = -1;
while (++index < length) {
const key = props[index];
if (key in object) {
result[key] = object[key];
}
}
return result;
} | javascript | {
"resource": ""
} |
q27892 | baseValues | train | function baseValues(object, props) {
const { length } = props;
const result = Array(length);
let index = -1;
while (++index < length) {
result[index] = object[props[index]];
}
return result;
} | javascript | {
"resource": ""
} |
q27893 | isArrayLike | train | function isArrayLike(value) {
return (
value != null &&
value.length &&
!(
typeof value === "function" &&
Object.prototype.toString.call(value) === "[object Function]"
) &&
typeof value === "object"
);
} | javascript | {
"resource": ""
} |
q27894 | deepEq | train | function deepEq(a, b, aStack, bStack) {
// Compare `[[Class]]` names.
var className = Object.prototype.toString.call(a);
if (className !== Object.prototype.toString.call(b)) {
return false;
}
/* eslint-disable no-fallthrough */
switch (className) {
// Strings, numbers, regular expressions, dates, and booleans are compared by value.
case "[object RegExp]":
// RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
case "[object String]":
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return "" + a === "" + b;
case "[object Number]":
// `NaN`s are equivalent, but non-reflexive.
// Object(NaN) is equivalent to NaN
if (+a !== +a) {
return +b !== +b;
}
// An `egal` comparison is performed for other numeric values.
return +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;
/* eslint-enable no-fallthrough */
}
var areArrays = className === "[object Array]";
if (!areArrays) {
if (typeof a != "object" || typeof b != "object") {
return false;
}
// Objects with different constructors are not equivalent, but `Object`s or `Array`s
// from different frames are.
var aCtor = a.constructor,
bCtor = b.constructor;
if (
aCtor !== bCtor &&
!(
isFunction(aCtor) &&
aCtor instanceof aCtor &&
isFunction(bCtor) &&
bCtor instanceof bCtor
) &&
("constructor" in a && "constructor" in b)
) {
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`.
// Initializing stack of traversed objects.
// It's done here since we only need them for objects and arrays comparison.
aStack = aStack || [];
bStack = bStack || [];
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (aStack[length] === a) {
return bStack[length] === b;
}
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
// Recursively compare objects and arrays.
if (areArrays) {
// Compare array lengths to determine if a deep comparison is necessary.
length = a.length;
if (length !== b.length) {
return false;
}
// Deep compare the contents, ignoring non-numeric properties.
while (length--) {
if (!eq(a[length], b[length], aStack, bStack)) {
return false;
}
}
} else {
// Deep compare objects.
var keys = Object.keys(a),
key;
length = keys.length;
// Ensure that both objects contain the same number of properties before comparing deep equality.
if (Object.keys(b).length !== length) {
return false;
}
while (length--) {
// Deep compare each member
key = keys[length];
if (!(has(b, key) && eq(a[key], b[key], aStack, bStack))) {
return false;
}
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return true;
} | javascript | {
"resource": ""
} |
q27895 | clone | train | function clone(object) {
if (object === null || typeof object != "object") {
return object;
}
const copy = object.constructor();
for (const attr in object) {
if (Object.prototype.hasOwnProperty.call(object, attr)) {
copy[attr] = object[attr];
}
}
return copy;
} | javascript | {
"resource": ""
} |
q27896 | exclude | train | function exclude(object, props) {
const newObject = {};
Object.keys(object).forEach(function(prop) {
if (props.indexOf(prop) === -1) {
newObject[prop] = object[prop];
}
});
return newObject;
} | javascript | {
"resource": ""
} |
q27897 | findFieldOption | train | function findFieldOption(options, field) {
const flattenedOptions = Util.flatten(options);
return Util.find(flattenedOptions, function(fieldOption) {
var isField = fieldOption.name === field;
if (fieldOption.fieldType === "object" && !isField) {
return findFieldOption(fieldOption.definition, field);
}
return isField;
});
} | javascript | {
"resource": ""
} |
q27898 | eslintFn | train | function eslintFn() {
return gulp
.src([config.files.docs.srcJS])
.pipe(eslint())
.pipe(eslint.formatEach("stylish", process.stderr));
} | javascript | {
"resource": ""
} |
q27899 | isInferrable | train | function isInferrable(node, init) {
if (node.type !== "TSTypeAnnotation" || !node.typeAnnotation) {
return false;
}
if (!init) {
return false;
}
const annotation = node.typeAnnotation;
if (annotation.type === "TSStringKeyword") {
return (
(init.type === "Literal" &&
typeof init.value === "string") ||
(init.type === "TemplateElement" &&
(!init.expressions || init.expressions.length === 0))
);
}
if (annotation.type === "TSBooleanKeyword") {
return init.type === "Literal";
}
if (annotation.type === "TSNumberKeyword") {
// Infinity is special
if (
(init.type === "UnaryExpression" &&
init.operator === "-" &&
init.argument.type === "Identifier" &&
init.argument.name === "Infinity") ||
(init.type === "Identifier" && init.name === "Infinity")
) {
return true;
}
return (
init.type === "Literal" && typeof init.value === "number"
);
}
return false;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.