_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q36000 | clearBars | train | function clearBars() {
var bars = editor.dom.select('.' + RESIZE_BAR_CLASS, getBody());
Tools.each(bars, function (bar) {
editor.dom.remove(bar);
});
} | javascript | {
"resource": ""
} |
q36001 | generateBar | train | function generateBar(classToAdd, cursor, left, top, height, width, indexAttr, index) {
var bar = {
'data-mce-bogus': 'all',
'class': RESIZE_BAR_CLASS + ' ' + classToAdd,
'unselectable': 'on',
'data-mce-resize': false,
style: 'cursor: ' + cursor + '; ' +
'margin: 0; ' +
'padding: 0; ' +
'position: absolute; ' +
'left: ' + left + 'px; ' +
'top: ' + top + 'px; ' +
'height: ' + height + 'px; ' +
'width: ' + width + 'px; '
};
bar[indexAttr] = index;
return bar;
} | javascript | {
"resource": ""
} |
q36002 | drawRows | train | function drawRows(rowPositions, tableWidth, tablePosition) {
Tools.each(rowPositions, function (rowPosition) {
var left = tablePosition.x,
top = rowPosition.y - RESIZE_BAR_THICKNESS / 2,
height = RESIZE_BAR_THICKNESS,
width = tableWidth;
editor.dom.add(getBody(), 'div',
generateBar(RESIZE_BAR_ROW_CLASS, RESIZE_BAR_ROW_CURSOR_STYLE,
left, top, height, width, RESIZE_BAR_ROW_DATA_ATTRIBUTE, rowPosition.index));
});
} | javascript | {
"resource": ""
} |
q36003 | drawCols | train | function drawCols(cellPositions, tableHeight, tablePosition) {
Tools.each(cellPositions, function (cellPosition) {
var left = cellPosition.x - RESIZE_BAR_THICKNESS / 2,
top = tablePosition.y,
height = tableHeight,
width = RESIZE_BAR_THICKNESS;
editor.dom.add(getBody(), 'div',
generateBar(RESIZE_BAR_COL_CLASS, RESIZE_BAR_COL_CURSOR_STYLE,
left, top, height, width, RESIZE_BAR_COL_DATA_ATTRIBUTE, cellPosition.index));
});
} | javascript | {
"resource": ""
} |
q36004 | getTableDetails | train | function getTableDetails(table) {
return Tools.map(table.rows, function (row) {
var cells = Tools.map(row.cells, function (cell) {
var rowspan = cell.hasAttribute('rowspan') ? parseInt(cell.getAttribute('rowspan'), 10) : 1;
var colspan = cell.hasAttribute('colspan') ? parseInt(cell.getAttribute('colspan'), 10) : 1;
return {
element: cell,
rowspan: rowspan,
colspan: colspan
};
});
return {
element: row,
cells: cells
};
});
} | javascript | {
"resource": ""
} |
q36005 | getTableGrid | train | function getTableGrid(tableDetails) {
function key(rowIndex, colIndex) {
return rowIndex + ',' + colIndex;
}
function getAt(rowIndex, colIndex) {
return access[key(rowIndex, colIndex)];
}
function getAllCells() {
var allCells = [];
Tools.each(rows, function (row) {
allCells = allCells.concat(row.cells);
});
return allCells;
}
function getAllRows() {
return rows;
}
var access = {};
var rows = [];
var maxRows = 0;
var maxCols = 0;
Tools.each(tableDetails, function (row, rowIndex) {
var currentRow = [];
Tools.each(row.cells, function (cell) {
var start = 0;
while (access[key(rowIndex, start)] !== undefined) {
start++;
}
var current = {
element: cell.element,
colspan: cell.colspan,
rowspan: cell.rowspan,
rowIndex: rowIndex,
colIndex: start
};
for (var i = 0; i < cell.colspan; i++) {
for (var j = 0; j < cell.rowspan; j++) {
var cr = rowIndex + j;
var cc = start + i;
access[key(cr, cc)] = current;
maxRows = Math.max(maxRows, cr + 1);
maxCols = Math.max(maxCols, cc + 1);
}
}
currentRow.push(current);
});
rows.push({
element: row.element,
cells: currentRow
});
});
return {
grid: {
maxRows: maxRows,
maxCols: maxCols
},
getAt: getAt,
getAllCells: getAllCells,
getAllRows: getAllRows
};
} | javascript | {
"resource": ""
} |
q36006 | getColumnBlocks | train | function getColumnBlocks(tableGrid) {
var cols = range(0, tableGrid.grid.maxCols);
var rows = range(0, tableGrid.grid.maxRows);
return Tools.map(cols, function (col) {
function getBlock() {
var details = [];
for (var i = 0; i < rows.length; i++) {
var detail = tableGrid.getAt(i, col);
if (detail && detail.colIndex === col) {
details.push(detail);
}
}
return details;
}
function isSingle(detail) {
return detail.colspan === 1;
}
function getFallback() {
var item;
for (var i = 0; i < rows.length; i++) {
item = tableGrid.getAt(i, col);
if (item) {
return item;
}
}
return null;
}
return decide(getBlock, isSingle, getFallback);
});
} | javascript | {
"resource": ""
} |
q36007 | getRowBlocks | train | function getRowBlocks(tableGrid) {
var cols = range(0, tableGrid.grid.maxCols);
var rows = range(0, tableGrid.grid.maxRows);
return Tools.map(rows, function (row) {
function getBlock() {
var details = [];
for (var i = 0; i < cols.length; i++) {
var detail = tableGrid.getAt(row, i);
if (detail && detail.rowIndex === row) {
details.push(detail);
}
}
return details;
}
function isSingle(detail) {
return detail.rowspan === 1;
}
function getFallback() {
return tableGrid.getAt(row, 0);
}
return decide(getBlock, isSingle, getFallback);
});
} | javascript | {
"resource": ""
} |
q36008 | getWidths | train | function getWidths(tableGrid, isPercentageBased, table) {
var cols = getColumnBlocks(tableGrid);
var backups = Tools.map(cols, function (col) {
return getInnerEdge(col.colIndex, col.element).x;
});
var widths = [];
for (var i = 0; i < cols.length; i++) {
var span = cols[i].element.hasAttribute('colspan') ? parseInt(cols[i].element.getAttribute('colspan'), 10) : 1;
// Deduce if the column has colspan of more than 1
var width = span > 1 ? deduceSize(backups, i) : getWidth(cols[i].element, isPercentageBased, table);
// If everything's failed and we still don't have a width
width = width ? width : RESIZE_MINIMUM_WIDTH;
widths.push(width);
}
return widths;
} | javascript | {
"resource": ""
} |
q36009 | getPixelHeight | train | function getPixelHeight(element) {
var heightString = getStyleOrAttrib(element, 'height');
var heightNumber = parseInt(heightString, 10);
if (isPercentageBasedSize(heightString)) {
heightNumber = 0;
}
return !isNaN(heightNumber) && heightNumber > 0 ?
heightNumber : getComputedStyleSize(element, 'height');
} | javascript | {
"resource": ""
} |
q36010 | getPixelHeights | train | function getPixelHeights(tableGrid) {
var rows = getRowBlocks(tableGrid);
var backups = Tools.map(rows, function (row) {
return getTopEdge(row.rowIndex, row.element).y;
});
var heights = [];
for (var i = 0; i < rows.length; i++) {
var span = rows[i].element.hasAttribute('rowspan') ? parseInt(rows[i].element.getAttribute('rowspan'), 10) : 1;
var height = span > 1 ? deduceSize(backups, i) : getPixelHeight(rows[i].element);
height = height ? height : RESIZE_MINIMUM_HEIGHT;
heights.push(height);
}
return heights;
} | javascript | {
"resource": ""
} |
q36011 | determineDeltas | train | function determineDeltas(sizes, column, step, min, isPercentageBased) {
var result = sizes.slice(0);
function generateZeros(array) {
return Tools.map(array, function () {
return 0;
});
}
function onOneColumn() {
var deltas;
if (isPercentageBased) {
// If we have one column in a percent based table, that column should be 100% of the width of the table.
deltas = [100 - result[0]];
} else {
var newNext = Math.max(min, result[0] + step);
deltas = [newNext - result[0]];
}
return deltas;
}
function onLeftOrMiddle(index, next) {
var startZeros = generateZeros(result.slice(0, index));
var endZeros = generateZeros(result.slice(next + 1));
var deltas;
if (step >= 0) {
var newNext = Math.max(min, result[next] - step);
deltas = startZeros.concat([step, newNext - result[next]]).concat(endZeros);
} else {
var newThis = Math.max(min, result[index] + step);
var diffx = result[index] - newThis;
deltas = startZeros.concat([newThis - result[index], diffx]).concat(endZeros);
}
return deltas;
}
function onRight(previous, index) {
var startZeros = generateZeros(result.slice(0, index));
var deltas;
if (step >= 0) {
deltas = startZeros.concat([step]);
} else {
var size = Math.max(min, result[index] + step);
deltas = startZeros.concat([size - result[index]]);
}
return deltas;
}
var deltas;
if (sizes.length === 0) { // No Columns
deltas = [];
} else if (sizes.length === 1) { // One Column
deltas = onOneColumn();
} else if (column === 0) { // Left Column
deltas = onLeftOrMiddle(0, 1);
} else if (column > 0 && column < sizes.length - 1) { // Middle Column
deltas = onLeftOrMiddle(column, column + 1);
} else if (column === sizes.length - 1) { // Right Column
deltas = onRight(column - 1, column);
} else {
deltas = [];
}
return deltas;
} | javascript | {
"resource": ""
} |
q36012 | recalculateWidths | train | function recalculateWidths(tableGrid, widths) {
var allCells = tableGrid.getAllCells();
return Tools.map(allCells, function (cell) {
var width = total(cell.colIndex, cell.colIndex + cell.colspan, widths);
return {
element: cell.element,
width: width,
colspan: cell.colspan
};
});
} | javascript | {
"resource": ""
} |
q36013 | recalculateCellHeights | train | function recalculateCellHeights(tableGrid, heights) {
var allCells = tableGrid.getAllCells();
return Tools.map(allCells, function (cell) {
var height = total(cell.rowIndex, cell.rowIndex + cell.rowspan, heights);
return {
element: cell.element,
height: height,
rowspan: cell.rowspan
};
});
} | javascript | {
"resource": ""
} |
q36014 | recalculateRowHeights | train | function recalculateRowHeights(tableGrid, heights) {
var allRows = tableGrid.getAllRows();
return Tools.map(allRows, function (row, i) {
return {
element: row.element,
height: heights[i]
};
});
} | javascript | {
"resource": ""
} |
q36015 | adjustWidth | train | function adjustWidth(table, delta, index) {
var tableDetails = getTableDetails(table);
var tableGrid = getTableGrid(tableDetails);
function setSizes(newSizes, styleExtension) {
Tools.each(newSizes, function (cell) {
editor.dom.setStyle(cell.element, 'width', cell.width + styleExtension);
editor.dom.setAttrib(cell.element, 'width', null);
});
}
function getNewTablePercentWidth() {
return index < tableGrid.grid.maxCols - 1 ? getCurrentTablePercentWidth(table) :
getCurrentTablePercentWidth(table) + getTablePercentDelta(table, delta);
}
function getNewTablePixelWidth() {
return index < tableGrid.grid.maxCols - 1 ? getComputedStyleSize(table, 'width') :
getComputedStyleSize(table, 'width') + delta;
}
function setTableSize(newTableWidth, styleExtension, isPercentBased) {
if (index == tableGrid.grid.maxCols - 1 || !isPercentBased) {
editor.dom.setStyle(table, 'width', newTableWidth + styleExtension);
editor.dom.setAttrib(table, 'width', null);
}
}
var percentageBased = isPercentageBasedSize(table.width) ||
isPercentageBasedSize(table.style.width);
var widths = getWidths(tableGrid, percentageBased, table);
var step = percentageBased ? getCellPercentDelta(table, delta) : delta;
// TODO: change the min for percentage maybe?
var deltas = determineDeltas(widths, index, step, RESIZE_MINIMUM_WIDTH, percentageBased, table);
var newWidths = [];
for (var i = 0; i < deltas.length; i++) {
newWidths.push(deltas[i] + widths[i]);
}
var newSizes = recalculateWidths(tableGrid, newWidths);
var styleExtension = percentageBased ? '%' : 'px';
var newTableWidth = percentageBased ? getNewTablePercentWidth() :
getNewTablePixelWidth();
editor.undoManager.transact(function () {
setSizes(newSizes, styleExtension);
setTableSize(newTableWidth, styleExtension, percentageBased);
});
} | javascript | {
"resource": ""
} |
q36016 | adjustHeight | train | function adjustHeight(table, delta, index) {
var tableDetails = getTableDetails(table);
var tableGrid = getTableGrid(tableDetails);
var heights = getPixelHeights(tableGrid);
var newHeights = [], newTotalHeight = 0;
for (var i = 0; i < heights.length; i++) {
newHeights.push(i === index ? delta + heights[i] : heights[i]);
newTotalHeight += newTotalHeight[i];
}
var newCellSizes = recalculateCellHeights(tableGrid, newHeights);
var newRowSizes = recalculateRowHeights(tableGrid, newHeights);
editor.undoManager.transact(function () {
Tools.each(newRowSizes, function (row) {
editor.dom.setStyle(row.element, 'height', row.height + 'px');
editor.dom.setAttrib(row.element, 'height', null);
});
Tools.each(newCellSizes, function (cell) {
editor.dom.setStyle(cell.element, 'height', cell.height + 'px');
editor.dom.setAttrib(cell.element, 'height', null);
});
editor.dom.setStyle(table, 'height', newTotalHeight + 'px');
editor.dom.setAttrib(table, 'height', null);
});
} | javascript | {
"resource": ""
} |
q36017 | innerText | train | function innerText(html) {
var schema = new Schema(), domParser = new DomParser({}, schema), text = '';
var shortEndedElements = schema.getShortEndedElements();
var ignoreElements = Tools.makeMap('script noscript style textarea video audio iframe object', ' ');
var blockElements = schema.getBlockElements();
function walk(node) {
var name = node.name, currentNode = node;
if (name === 'br') {
text += '\n';
return;
}
// img/input/hr
if (shortEndedElements[name]) {
text += ' ';
}
// Ingore script, video contents
if (ignoreElements[name]) {
text += ' ';
return;
}
if (node.type == 3) {
text += node.value;
}
// Walk all children
if (!node.shortEnded) {
if ((node = node.firstChild)) {
do {
walk(node);
} while ((node = node.next));
}
}
// Add \n or \n\n for blocks or P
if (blockElements[name] && currentNode.next) {
text += '\n';
if (name == 'p') {
text += '\n';
}
}
}
html = filter(html, [
/<!\[[^\]]+\]>/g // Conditional comments
]);
walk(domParser.parse(html));
return text;
} | javascript | {
"resource": ""
} |
q36018 | pasteHtml | train | function pasteHtml(html, internalFlag) {
var args, dom = editor.dom, internal;
internal = internalFlag || InternalHtml.isMarked(html);
html = InternalHtml.unmark(html);
args = editor.fire('BeforePastePreProcess', { content: html, internal: internal }); // Internal event used by Quirks
args = editor.fire('PastePreProcess', args);
html = args.content;
if (!args.isDefaultPrevented()) {
// User has bound PastePostProcess events then we need to pass it through a DOM node
// This is not ideal but we don't want to let the browser mess up the HTML for example
// some browsers add to P tags etc
if (editor.hasEventListeners('PastePostProcess') && !args.isDefaultPrevented()) {
// We need to attach the element to the DOM so Sizzle selectors work on the contents
var tempBody = dom.add(editor.getBody(), 'div', { style: 'display:none' }, html);
args = editor.fire('PastePostProcess', { node: tempBody, internal: internal });
dom.remove(tempBody);
html = args.node.innerHTML;
}
if (!args.isDefaultPrevented()) {
SmartPaste.insertContent(editor, html);
}
}
} | javascript | {
"resource": ""
} |
q36019 | createPasteBin | train | function createPasteBin() {
var dom = editor.dom, body = editor.getBody();
var viewport = editor.dom.getViewPort(editor.getWin()), scrollTop = viewport.y, top = 20;
var scrollContainer;
lastRng = editor.selection.getRng();
if (editor.inline) {
scrollContainer = editor.selection.getScrollContainer();
// Can't always rely on scrollTop returning a useful value.
// It returns 0 if the browser doesn't support scrollTop for the element or is non-scrollable
if (scrollContainer && scrollContainer.scrollTop > 0) {
scrollTop = scrollContainer.scrollTop;
}
}
/**
* Returns the rect of the current caret if the caret is in an empty block before a
* BR we insert a temporary invisible character that we get the rect this way we always get a proper rect.
*
* TODO: This might be useful in core.
*/
function getCaretRect(rng) {
var rects, textNode, node, container = rng.startContainer;
rects = rng.getClientRects();
if (rects.length) {
return rects[0];
}
if (!rng.collapsed || container.nodeType != 1) {
return;
}
node = container.childNodes[lastRng.startOffset];
// Skip empty whitespace nodes
while (node && node.nodeType == 3 && !node.data.length) {
node = node.nextSibling;
}
if (!node) {
return;
}
// Check if the location is |<br>
// TODO: Might need to expand this to say |<table>
if (node.tagName == 'BR') {
textNode = dom.doc.createTextNode('\uFEFF');
node.parentNode.insertBefore(textNode, node);
rng = dom.createRng();
rng.setStartBefore(textNode);
rng.setEndAfter(textNode);
rects = rng.getClientRects();
dom.remove(textNode);
}
if (rects.length) {
return rects[0];
}
}
// Calculate top cordinate this is needed to avoid scrolling to top of document
// We want the paste bin to be as close to the caret as possible to avoid scrolling
if (lastRng.getClientRects) {
var rect = getCaretRect(lastRng);
if (rect) {
// Client rects gets us closes to the actual
// caret location in for example a wrapped paragraph block
top = scrollTop + (rect.top - dom.getPos(body).y);
} else {
top = scrollTop;
// Check if we can find a closer location by checking the range element
var container = lastRng.startContainer;
if (container) {
if (container.nodeType == 3 && container.parentNode != body) {
container = container.parentNode;
}
if (container.nodeType == 1) {
top = dom.getPos(container, scrollContainer || body).y;
}
}
}
}
// Create a pastebin
pasteBinElm = dom.add(editor.getBody(), 'div', {
id: "mcepastebin",
contentEditable: true,
"data-mce-bogus": "all",
style: 'position: absolute; top: ' + top + 'px;' +
'width: 10px; height: 10px; overflow: hidden; opacity: 0'
}, pasteBinDefaultContent);
// Move paste bin out of sight since the controlSelection rect gets displayed otherwise on IE and Gecko
if (Env.ie || Env.gecko) {
dom.setStyle(pasteBinElm, 'left', dom.getStyle(body, 'direction', true) == 'rtl' ? 0xFFFF : -0xFFFF);
}
// Prevent focus events from bubbeling fixed FocusManager issues
dom.bind(pasteBinElm, 'beforedeactivate focusin focusout', function (e) {
e.stopPropagation();
});
pasteBinElm.focus();
editor.selection.select(pasteBinElm, true);
} | javascript | {
"resource": ""
} |
q36020 | getCaretRect | train | function getCaretRect(rng) {
var rects, textNode, node, container = rng.startContainer;
rects = rng.getClientRects();
if (rects.length) {
return rects[0];
}
if (!rng.collapsed || container.nodeType != 1) {
return;
}
node = container.childNodes[lastRng.startOffset];
// Skip empty whitespace nodes
while (node && node.nodeType == 3 && !node.data.length) {
node = node.nextSibling;
}
if (!node) {
return;
}
// Check if the location is |<br>
// TODO: Might need to expand this to say |<table>
if (node.tagName == 'BR') {
textNode = dom.doc.createTextNode('\uFEFF');
node.parentNode.insertBefore(textNode, node);
rng = dom.createRng();
rng.setStartBefore(textNode);
rng.setEndAfter(textNode);
rects = rng.getClientRects();
dom.remove(textNode);
}
if (rects.length) {
return rects[0];
}
} | javascript | {
"resource": ""
} |
q36021 | removePasteBin | train | function removePasteBin() {
if (pasteBinElm) {
var pasteBinClone;
// WebKit/Blink might clone the div so
// lets make sure we remove all clones
// TODO: Man o man is this ugly. WebKit is the new IE! Remove this if they ever fix it!
while ((pasteBinClone = editor.dom.get('mcepastebin'))) {
editor.dom.remove(pasteBinClone);
editor.dom.unbind(pasteBinClone);
}
if (lastRng) {
editor.selection.setRng(lastRng);
}
}
pasteBinElm = lastRng = null;
} | javascript | {
"resource": ""
} |
q36022 | getPasteBinHtml | train | function getPasteBinHtml() {
var html = '', pasteBinClones, i, clone, cloneHtml;
// Since WebKit/Chrome might clone the paste bin when pasting
// for example: <img style="float: right"> we need to check if any of them contains some useful html.
// TODO: Man o man is this ugly. WebKit is the new IE! Remove this if they ever fix it!
pasteBinClones = editor.dom.select('div[id=mcepastebin]');
for (i = 0; i < pasteBinClones.length; i++) {
clone = pasteBinClones[i];
// Pasting plain text produces pastebins in pastebinds makes sence right!?
if (clone.firstChild && clone.firstChild.id == 'mcepastebin') {
clone = clone.firstChild;
}
cloneHtml = clone.innerHTML;
if (html != pasteBinDefaultContent) {
html += cloneHtml;
}
}
return html;
} | javascript | {
"resource": ""
} |
q36023 | pasteImageData | train | function pasteImageData(e, rng) {
var dataTransfer = e.clipboardData || e.dataTransfer;
function processItems(items) {
var i, item, reader, hadImage = false;
if (items) {
for (i = 0; i < items.length; i++) {
item = items[i];
if (/^image\/(jpeg|png|gif|bmp)$/.test(item.type)) {
var blob = item.getAsFile ? item.getAsFile() : item;
reader = new FileReader();
reader.onload = pasteImage.bind(null, rng, reader, blob);
reader.readAsDataURL(blob);
e.preventDefault();
hadImage = true;
}
}
}
return hadImage;
}
if (editor.settings.paste_data_images && dataTransfer) {
return processItems(dataTransfer.items) || processItems(dataTransfer.files);
}
} | javascript | {
"resource": ""
} |
q36024 | isBrokenAndroidClipboardEvent | train | function isBrokenAndroidClipboardEvent(e) {
var clipboardData = e.clipboardData;
return navigator.userAgent.indexOf('Android') != -1 && clipboardData && clipboardData.items && clipboardData.items.length === 0;
} | javascript | {
"resource": ""
} |
q36025 | isNumericList | train | function isNumericList(text) {
var found, patterns;
patterns = [
/^[IVXLMCD]{1,2}\.[ \u00a0]/, // Roman upper case
/^[ivxlmcd]{1,2}\.[ \u00a0]/, // Roman lower case
/^[a-z]{1,2}[\.\)][ \u00a0]/, // Alphabetical a-z
/^[A-Z]{1,2}[\.\)][ \u00a0]/, // Alphabetical A-Z
/^[0-9]+\.[ \u00a0]/, // Numeric lists
/^[\u3007\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d]+\.[ \u00a0]/, // Japanese
/^[\u58f1\u5f10\u53c2\u56db\u4f0d\u516d\u4e03\u516b\u4e5d\u62fe]+\.[ \u00a0]/ // Chinese
];
text = text.replace(/^[\u00a0 ]+/, '');
Tools.each(patterns, function (pattern) {
if (pattern.test(text)) {
found = true;
return false;
}
});
return found;
} | javascript | {
"resource": ""
} |
q36026 | removeExplorerBrElementsAfterBlocks | train | function removeExplorerBrElementsAfterBlocks(html) {
// Only filter word specific content
if (!WordFilter.isWordContent(html)) {
return html;
}
// Produce block regexp based on the block elements in schema
var blockElements = [];
Tools.each(editor.schema.getBlockElements(), function (block, blockName) {
blockElements.push(blockName);
});
var explorerBlocksRegExp = new RegExp(
'(?:<br> [\\s\\r\\n]+|<br>)*(<\\/?(' + blockElements.join('|') + ')[^>]*>)(?:<br> [\\s\\r\\n]+|<br>)*',
'g'
);
// Remove BR:s from: <BLOCK>X</BLOCK><BR>
html = Utils.filter(html, [
[explorerBlocksRegExp, '$1']
]);
// IE9 also adds an extra BR element for each soft-linefeed and it also adds a BR for each word wrap break
html = Utils.filter(html, [
[/<br><br>/g, '<BR><BR>'], // Replace multiple BR elements with uppercase BR to keep them intact
[/<br>/g, ' '], // Replace single br elements with space since they are word wrap BR:s
[/<BR><BR>/g, '<br>'] // Replace back the double brs but into a single BR
]);
return html;
} | javascript | {
"resource": ""
} |
q36027 | getPatterns | train | function getPatterns() {
if (isPatternsDirty) {
patterns.sort(function (a, b) {
if (a.start.length > b.start.length) {
return -1;
}
if (a.start.length < b.start.length) {
return 1;
}
return 0;
});
isPatternsDirty = false;
}
return patterns;
} | javascript | {
"resource": ""
} |
q36028 | findPattern | train | function findPattern(text) {
var patterns = getPatterns();
for (var i = 0; i < patterns.length; i++) {
if (text.indexOf(patterns[i].start) !== 0) {
continue;
}
if (patterns[i].end && text.lastIndexOf(patterns[i].end) != text.length - patterns[i].end.length) {
continue;
}
return patterns[i];
}
} | javascript | {
"resource": ""
} |
q36029 | findEndPattern | train | function findEndPattern(text, offset, delta) {
var patterns, pattern, i;
// Find best matching end
patterns = getPatterns();
for (i = 0; i < patterns.length; i++) {
pattern = patterns[i];
if (pattern.end && text.substr(offset - pattern.end.length - delta, pattern.end.length) == pattern.end) {
return pattern;
}
}
} | javascript | {
"resource": ""
} |
q36030 | interpret | train | function interpret(source) {
var tree = parser.parse(source);
var js = [
'module.exports = function (out, globals) {',
' var end = false;',
' if (Object.getPrototypeOf(out) !== module.xjs.XjsStream.prototype) {',
' out = new module.xjs.XjsStream(out);',
' end = true;',
' }',
' if (globals && typeof globals.length === "number" && typeof globals !== "string") {',
' var callee = arguments.callee;',
' for (var i in globals) {',
' callee.call(this, out, globals[i]);',
' }',
' return;',
' }',
' globals = globals || {};',
' with (globals) {'
];
interpretChildren(js, tree, ' ');
js.push(
' }',
' if (end) {',
' out.end();',
' }',
'}'
);
js = js.join('\n');
return js;
} | javascript | {
"resource": ""
} |
q36031 | getMapOption | train | function getMapOption(from) {
if (typeof options.map === 'string') {
var mapPath = options.map + path.basename(from) + '.map';
if (grunt.file.exists(mapPath)) {
return grunt.file.read(mapPath);
}
}
return options.map;
} | javascript | {
"resource": ""
} |
q36032 | setBanner | train | function setBanner(text) {
return function(css) {
css.prepend(postcss.comment({ text: text }));
// New line after banner
if (css.rules[1]) {
css.rules[1].before = '\n';
}
};
} | javascript | {
"resource": ""
} |
q36033 | move | train | function move(fs, a, b, method, cb) {
var parentA = path.dirname(a);
var parentB = path.dirname(b);
var nameA = path.basename(a);
var nameB = path.basename(b)
fs.metadata(a)
.then(function(metadata) {
return this.metadata(b)
.then(function(metadata) {
throw fs.error('EEXIST', 'Cannot move because target path already exist: ' + b);
}, function(err) {
if (err.code === 'ENOENT') {
return this.mkdir(parentB);
} else {
throw err;
}
});
})
.then(function() {
return this._promise(method, a, b);
})
.done(function() {
cb();
}, function(err) {
cb(err);
});
} | javascript | {
"resource": ""
} |
q36034 | Replacement | train | function Replacement(nodePath, nodes) {
this.queue = [];
if (nodePath && nodes) {
this.queue.push([nodePath, nodes]);
}
} | javascript | {
"resource": ""
} |
q36035 | consoleReporter | train | function consoleReporter(reports, options = {}) {
var hide = options.hide || {};
(function _consoleReporter(reports) {
reports.forEach(
({children, desc, status, counts, time, code, error}) => {
let countStr = makeCounts(counts);
let color = statusInfo[status].color;
let colorStr = `color: ${color}`;
if (children) {
let msg = desc;
let collapse = hide.children || hide.passed && status === 'pass';
if (!hide.counts) { msg = `${msg} (${countStr})`; }
console[collapse ? 'groupCollapsed' : 'group']('%c' + msg, colorStr);
_consoleReporter(children);
console.groupEnd();
} else {
if (error) console.log('%c %s (%O)', colorStr, desc, error);
else console.log('%c %s', colorStr, desc);
}
}
);
})(reports);
} | javascript | {
"resource": ""
} |
q36036 | htmlReporter | train | function htmlReporter(reports, options = {}) {
var {hide} = options;
hide = hide || {};
function htmlReporterOne({children, desc, status, counts, time, code}) {
var text = T(desc);
var attrs = {class: {[status]: true}};
if (children) {
return E('details') .
has([
E('summary') . has([text, !hide.counts && T(` (${makeCounts(counts)})`)]) . is(attrs),
E('div') . has(htmlReporter(children, options))
]) .
is(hide.children ? {} : {open: true});
} else {
return E('div') . has(text) . is(attrs);
}
}
return M(reports, htmlReporterOne);
} | javascript | {
"resource": ""
} |
q36037 | emitEvent | train | function emitEvent(emitter, event, data) {
process.nextTick(function() {
emitter.emit(event, data);
});
} | javascript | {
"resource": ""
} |
q36038 | train | function (arr) {
var out = [], bl = sjcl.bitArray.bitLength(arr), i, tmp;
for (i=0; i<bl/8; i++) {
if ((i&3) === 0) {
tmp = arr[i/4];
}
out.push(tmp >>> 24);
tmp <<= 8;
}
return out;
} | javascript | {
"resource": ""
} | |
q36039 | train | function (bytes) {
var out = [], i, tmp=0;
for (i=0; i<bytes.length; i++) {
tmp = tmp << 8 | bytes[i];
if ((i&3) === 3) {
out.push(tmp);
tmp = 0;
}
}
if (i&3) {
out.push(sjcl.bitArray.partial(8*(i&3), tmp));
}
return out;
} | javascript | {
"resource": ""
} | |
q36040 | createStyleContext | train | function createStyleContext(actors, hooks) {
var context;
/**
* Composes a context.
*
* @param {function) styling - Styling function from styler.
* @param {function} reducer - Reducer function to run actions
*/
return function composeContext(styling, reducer) {
var latestState = context ? context.getState() : {};
context && context.dispose();
context = (0, _Context2.default)(actors, function contextUpdater(context, action, target) {
var state = context.getState(),
newState = state;
if (target || action.type == _Context.INIT_CONTEXT_ACTION_TYPE) {
newState = reducer(state, context.actors, action, target);
// state is not changed
if (newState === state) {
// return current state instance
return state;
}
}
Object.keys(context.actors).forEach(function setInitialStyles(name) {
var comp = context.actors[name];
if (comp.isUgly === true || action.type === _Context.INIT_CONTEXT_ACTION_TYPE) {
var className = context.actors[name].getClassName();
var beforeHook = hooks("beforeAssignComponentStyles");
beforeHook && (className = beforeHook(name, className));
var styles = styling(className + " #" + name)();
context.actors[name].setStyles(styles);
comp.isUgly = false;
}
});
latestState = newState;
return newState;
}, latestState);
Object.keys(context.actors).forEach(function assignContext(name) {
context.actors[name].isUgly = true;
context.actors[name].setContext(context);
});
return context;
};
} | javascript | {
"resource": ""
} |
q36041 | configure | train | function configure(proto, nameOrConfigs, actionConfig) {
if (!proto.__configs) proto.__configs = {};
if (typeof nameOrConfigs === 'string') {
// Set new configs
if (typeof actionConfig === 'object') {
proto.__configs = _.assign(
proto.__configs,
{ [nameOrConfigs]: actionConfig }
);
}
// Get config
else {
return proto.__configs[nameOrConfigs];
}
}
// Overwrite all configs
else if (typeof nameOrConfigs === 'object') {
proto.__configs = nameOrConfigs;
}
} | javascript | {
"resource": ""
} |
q36042 | detectConflictActions | train | function detectConflictActions(instance) {
// Get all props and check reserved words
let propNames = Object.getOwnPropertyNames(instance.__proto__);
// Check internal action conflicts
_.each(propNames, function(name) {
assert(
!~RESERVED_METHODS.indexOf(name),
`Action: \`${name}\` is reserved by baiji.Controller, please rename it`
);
});
} | javascript | {
"resource": ""
} |
q36043 | unique | train | function unique(value) {
return value.reduce((memo, current) => {
return memo.indexOf(current) !== -1 ? memo : memo.concat(current);
}, []);
} | javascript | {
"resource": ""
} |
q36044 | cleanClassNames | train | function cleanClassNames(value) {
const classNamesArray = isString(value) ? splitString(value) : value;
const trimmedNamesArray = trimClassNames(classNamesArray);
const uniqueNamesArray = unique(trimmedNamesArray);
return uniqueNamesArray;
} | javascript | {
"resource": ""
} |
q36045 | ChickadeeServer | train | function ChickadeeServer(options) {
options = options || {};
var specifiedHttpPort = options.httpPort || HTTP_PORT;
var httpPort = process.env.PORT || specifiedHttpPort;
var app = express();
app.use(bodyParser.json());
var instance = new Chickadee(options);
options.app = app;
instance.configureRoutes(options);
app.listen(httpPort, function() {
console.log('chickadee is listening on port', httpPort);
});
return instance;
} | javascript | {
"resource": ""
} |
q36046 | getTypesFromHandlers | train | function getTypesFromHandlers(handlers) {
var types = keys(handlers);
types = types.map(k => k.replace(/_.*/, ''));
if (types.indexOf('end') !== -1) {
types.push('add', 'update', 'delete');
}
return types;
} | javascript | {
"resource": ""
} |
q36047 | makeObserver | train | function makeObserver(handlers) {
console.assert(handlers && typeof handlers === 'object', "Argument to makeObserver must be hash.");
var handler = assign(create(observerPrototype), handlers);
var observer = handler.handle.bind(handler);
observer.keys = getTypesFromHandlers(handlers);
return observer;
} | javascript | {
"resource": ""
} |
q36048 | observeObject | train | function observeObject(o, observer) {
return o && typeof o === 'object' && observe(o, observer, observer.keys);
} | javascript | {
"resource": ""
} |
q36049 | notifyRetroactively | train | function notifyRetroactively(object) {
if (object && typeof object === 'object') {
const type = 'add';
var notifier = Object.getNotifier(object);
keys(object).forEach(name => notifier.notify({type, name, object}));
}
return object;
} | javascript | {
"resource": ""
} |
q36050 | observeOnce | train | function observeOnce(object, observer, types) {
function _observer(changes) {
observer(changes);
unobserve(object, _observer);
}
observe(object, _observer, types);
} | javascript | {
"resource": ""
} |
q36051 | mirrorProperties | train | function mirrorProperties(src, dest = {}) {
function set(name) { dest[name] = src[name]; }
function _delete(name) { delete dest[name]; }
var handlers = { add: set, update: set, delete: _delete};
assign(dest, src);
observe(src, makeObserver(handlers));
return dest;
} | javascript | {
"resource": ""
} |
q36052 | Observer | train | function Observer(object, observer, types) {
return {
observe(_types) {
types = _types || types;
if (isObject(object)) observe(object, observer, types);
return this;
},
unobserve() {
if (isObject(object)) unobserve(object, observer);
return this;
},
reobserve(_object) {
this.unobserve();
object = _object;
return this.observe();
}
};
} | javascript | {
"resource": ""
} |
q36053 | train | function(method){
var parent, result;
parent = this._parent || this.constructor.parent;
this._parent = parent.constructor.parent;
result = attempt(parent[method], slice(arguments, 1) , this );
this._parent = parent;
if( result[0] ){
throw result[0];
}
return result[1];
} | javascript | {
"resource": ""
} | |
q36054 | throttle | train | function throttle(options) {
assert.object(options, 'options');
assert.number(options.burst, 'options.burst');
assert.number(options.rate, 'options.rate');
if (!xor(options.ip, options.xff, options.username)) {
throw new Error('(ip ^ username ^ xff)');
}
for (key in options.overrides) {
var override = options.overrides[key];
try {
var block = new Netmask(key);
// Non-/32 blocks only
if (block.first !== block.last) {
override.block = block;
}
}
catch(err) {
// The key may be a username, which would raise but should
// be ignored
}
}
var message = options.message || 'You have exceeded your request rate of %s r/s.';
var table = options.tokensTable || new TokenTable({size: options.maxKeys});
function rateLimit(req, res, next) {
var attr;
var burst = options.burst;
var rate = options.rate;
if (options.ip) {
attr = req.connection.remoteAddress;
} else if (options.xff) {
attr = req.headers['x-forwarded-for'];
} else if (options.username) {
attr = req.username;
}
// Before bothering with overrides, see if this request
// even matches
if (!attr) {
return next(new Error('Invalid throttle configuration'));
}
// If the attr is a comma-delimited list of IPs, get the first
attr = attr.split(',')[0];
// Check the overrides
if (options.overrides) {
var override = options.overrides[attr];
// If the rate limit attribute matches an override key, apply it
if (override) {
if (override.burst !== undefined && override.rate !== undefined) {
burst = override.burst;
rate = override.rate;
}
}
// Otherwise, see if the rate limit attribute matches any CIDR
// block overrides
else {
for (key in options.overrides) {
override = options.overrides[key];
var contained = false;
try {
contained = override.block && override.block.contains(attr);
}
catch(err) {
// attr may be a username, which would raise but should
// be ignored
}
if (contained) {
burst = override.burst;
rate = override.rate;
break;
}
}
}
}
if (!rate || !burst) {
return next();
}
var bucket = table.get(attr);
if (!bucket) {
bucket = new TokenBucket({
capacity: burst,
fillRate: rate
});
table.put(attr, bucket);
}
if (!bucket.consume(1)) {
var msg = sprintf(message, rate);
var err = new Error(msg);
err.status = 429; // Too Many Requests
return next(err);
}
return next();
}
return rateLimit;
} | javascript | {
"resource": ""
} |
q36055 | Collector | train | function Collector(series, uri) {
if (!(this instanceof Collector)) {
return new Collector(series, uri);
}
var self = this;
if (!uri) {
return;
}
if (!series) {
throw new Error('series name must be specified');
}
var parsed = url.parse(uri, true /* parse query args */);
var username = undefined;
var password = undefined;
if (parsed.auth) {
var parts = parsed.auth.split(':');
username = parts.shift();
password = parts.shift();
}
self._client = influx({
host : parsed.hostname,
port : parsed.port,
protocol : parsed.protocol,
username : username,
password : password,
database : parsed.pathname.slice(1) // remove leading '/'
})
self._points = [];
var opt = parsed.query || {};
self._series_name = series;
self._instant_flush = opt.instantFlush == 'yes';
self._time_precision = opt.time_precision;
// no automatic flush
if (opt.autoFlush == 'no' || self._instant_flush) {
return;
}
var flush_interval = opt.flushInterval || 5000;
// flush on an interval
// or option to auto_flush=false
setInterval(function() {
self.flush();
}, flush_interval).unref();
} | javascript | {
"resource": ""
} |
q36056 | fetchAncestor | train | function fetchAncestor(type, ids, includePath, req) {
return router.actions["get" + util.toCapitalisedCamelCase(type)](ids, {include: includePath, parentRequest: req});
} | javascript | {
"resource": ""
} |
q36057 | mergeLinked | train | function mergeLinked(source, target, pathArr, ancestorType) {
var linked, type, res;
if (pathArr.length) {
// the external is referenced by the ancestor
if (source.links && source.linked && source.links[ancestorType + "." + pathArr.join(".")]) {
type = source.links[ancestorType + "." + pathArr.join(".")].type;
linked = source.linked[type];
}
} else {
// ancestor is the sought external
type = ancestorType;
linked = source[ancestorType] || [];
}
target.linked[type] = _.isArray(res = target.linked[type]) ? _.uniq(res.concat(linked), function(i){ return i.id}) : linked;
} | javascript | {
"resource": ""
} |
q36058 | mergeLinks | train | function mergeLinks(source, target, pathArr, ancestorType) {
var refType = ancestorType + ((pathArr.length > 1) ? "." + _.rest(pathArr).join(".") : "");
var link = source.links && source.links[refType];
if (link) target.links[rootName(target) + "." + pathArr.join(".")] = link;
} | javascript | {
"resource": ""
} |
q36059 | mergeAncestorData | train | function mergeAncestorData(target, pathArr, type, source) {
mergeLinked(source, target, _.rest(pathArr), type);
mergeLinks(source, target , pathArr, type);
} | javascript | {
"resource": ""
} |
q36060 | groupIncludes | train | function groupIncludes(includes, body) {
var root = rootName(body);
var requestsByType = {};
_.each(includes, function(include) {
var type = ((body.links && body.links[root + "." + include]) || {}).type,
split = include.split(".");
if (_.isUndefined(body.links) || _.isUndefined(body.links[root + "." + split[0]])) {
return;
}
if (type && body.linked[type] && body.linked[type] !== "external") {
// The type exists but is not an external reference exit.
return;
}
var ancestorType = body.links[root + "." + split[0]].type;
var ids = linkedIds(body[root], split[0]);
if (ids.length) {
var requestData = requestsByType[ancestorType] || {ids: [], includes: []};
requestData.ids = requestData.ids.concat(ids);
requestData.includes.push(split);
requestsByType[ancestorType] = requestData;
}
});
return requestsByType;
} | javascript | {
"resource": ""
} |
q36061 | fetchExternals | train | function fetchExternals(request, body) {
var includes = parseIncludes(request);
var user = request.user;
var requestsByType = groupIncludes(includes, body);
return when.all(_.map(requestsByType, function(requestData, ancestorType) {
var ids = _.uniq(requestData.ids);
return fetchAncestor(ancestorType, ids, _.compact(_.map(requestData.includes, function(i) { return _.rest(i).join("."); })).join(","), request)
.then(function(response){
return response;
})
.then(function(data) {
_.each(requestData.includes, function(split) {
mergeAncestorData(body, split, ancestorType, data);
});
})
.catch(function(err) { console.trace(err.stack || err); });
})).then(function() {
return body;
});
} | javascript | {
"resource": ""
} |
q36062 | getMonth | train | function getMonth(moment, service, dt) {
const dateService = new service(moment, dt);
return {
longName: dateService.monthLong(),
shortName: dateService.monthShort(),
daysCount: dateService.daysCount(),
startDayOfMonth: dateService.startDayOfMonth(),
};
} | javascript | {
"resource": ""
} |
q36063 | generateActions | train | function generateActions({ generate, ...actions }) {
return !generate
? actions
: Object.assign(
generate.reduce((obj, name) => {
obj[name] = forwardValue;
return obj;
}, {}),
actions
);
} | javascript | {
"resource": ""
} |
q36064 | TransIP | train | function TransIP(login, privateKey) {
this.version = 5.1;
this.mode = 'readwrite';
this.endpoint = 'api.transip.nl';
this.login = (login ? login : config.transip.login);
this.privateKey = (privateKey ? privateKey : config.transip.privateKey);
this.domainService = new domainService(this);
} | javascript | {
"resource": ""
} |
q36065 | train | function(defaults, options) {
options = options || {};
for (var option in defaults) {
if (defaults.hasOwnProperty(option) && !options.hasOwnProperty(option)) {
options[option] = defaults[option];
}
}
return options;
} | javascript | {
"resource": ""
} | |
q36066 | MSPassportStrategy | train | function MSPassportStrategy(options) {
Strategy.call(this);
this.name = "mspassport";
var default_options = {
protocol : "querystring",
protocolHandler : function() { self.fail("protocolHandler must be implemented if protocol === 'custom'") }
};
this.options = _defaults(default_options, options);
} | javascript | {
"resource": ""
} |
q36067 | runGame | train | function runGame() {
var totalReward = 0;
var environment = new exampleWorld.Environment();
var lastReward = null;
function tick() {
//Tell the agent about the current environment state and have it choose an action to take
var action = sarsaAgent.decide(lastReward, environment.getCurrentState());
//Tell the environment the agent's action and have it calculate a reward
lastReward = environment.takeAction(action);
//Log the total reward
totalReward += lastReward;
}
for (var i = 0; i < 100; i++) {
tick();
}
return totalReward;
} | javascript | {
"resource": ""
} |
q36068 | objectToString | train | function objectToString(o) {
return '{' + keys(o).map(k => `${k}: ${o[k]}`).join(', ') + '}';
} | javascript | {
"resource": ""
} |
q36069 | mapObjectInPlace | train | function mapObjectInPlace(o, fn, ctxt) {
for (let key in o) {
if (o.hasOwnProperty(key)) {
o[key] = fn.call(ctxt, o[key], key, o);
}
}
return o;
} | javascript | {
"resource": ""
} |
q36070 | copyOf | train | function copyOf(o) {
if (Array.isArray(o)) return o.slice();
if (isObject(o)) return assign({}, o);
return o;
} | javascript | {
"resource": ""
} |
q36071 | copyOntoArray | train | function copyOntoArray(a1, a2) {
for (let i = 0; i < a2.length; i++) {
a1[i] = a2[i];
}
a1.length = a2.length;
return a1;
} | javascript | {
"resource": ""
} |
q36072 | copyOntoObject | train | function copyOntoObject(o1, o2) {
assign(o1, o2);
keys(o1)
.filter(key => !(key in o2))
.forEach(key => (delete o1[key]));
return o1;
} | javascript | {
"resource": ""
} |
q36073 | copyOnto | train | function copyOnto(a1, a2) {
if (Array.isArray(a1) && Array.isArray(a2)) return copyOntoArray (a1, a2);
if (isObject (a1) && isObject (a2)) return copyOntoObject(a1, a2);
return (a1 = a2);
} | javascript | {
"resource": ""
} |
q36074 | invertObject | train | function invertObject(o) {
var result = {};
for (let pair of objectPairs(o)) {
let [key, val] = pair;
result[val] = key;
}
return result;
} | javascript | {
"resource": ""
} |
q36075 | objectFromLists | train | function objectFromLists(keys, vals) {
var result = {};
for (let i = 0, len = keys.length; i < len; i++) {
result[keys[i]] = vals[i];
}
return result;
} | javascript | {
"resource": ""
} |
q36076 | addHooks | train | function addHooks(fn, value) {
// Upcast val to an array
var values = value;
if (!Array.isArray(values)) {
values = [value];
}
// Call each of the functions with hook
values.forEach(fn);
} | javascript | {
"resource": ""
} |
q36077 | addHookByType | train | function addHookByType(ctx, type, methodNames, fn) {
let i = methodNames.length;
// If no hook specified, add wildcard
if (i === 0) {
methodNames = ['*'];
i = 1;
}
let hookType = `${type}Hooks`;
if (!ctx[hookType]) ctx[hookType] = {};
while (i--) {
let methodName = methodNames[i];
// for array method names
if (Array.isArray(methodName)) {
addHookByType(ctx, type, methodName, fn);
} else {
if (!ctx[hookType][methodName]) {
ctx[hookType][methodName] = [fn];
} else {
ctx[hookType][methodName].push(fn);
}
}
}
} | javascript | {
"resource": ""
} |
q36078 | viewStream | train | function viewStream(view) {
return function() {
var stream = utils.through.obj();
stream.setMaxListeners(0);
setImmediate(function(item) {
stream.write(item);
stream.end();
}, this);
return outStream(stream, view);
};
} | javascript | {
"resource": ""
} |
q36079 | parseJson | train | function parseJson(text) {
try {
var o = JSON.parse(text);
if (o && typeof o === "object" && o !== null)
return o;
}
catch (e) {}
return text;
} | javascript | {
"resource": ""
} |
q36080 | substiteVariable | train | function substiteVariable(variable, options, cb) {
var value;
var err = null;
var s = variable.split(':', 2);
if (s.length == 2) {
value = options.env[s[0]];
if (typeof value == 'function') {
value = value();
}
if (s[1][0] == '+') {
// Substitute replacement, but only if variable is defined and nonempty. Otherwise, substitute nothing
value = value ? s[1].substring(1) : '';
} else if (s[1][0] == '-') {
// Substitute the value of variable, but if that is empty or undefined, use default instead
value = value || s[1].substring(1);
} else if (s[1][0] == '#') {
// Substitute with the length of the value of the variable
value = value !== undefined ? String(value).length : 0;
} else if (s[1][0] == '=') {
// Substitute the value of variable, but if that is empty or undefined, use default instead and set the variable to default
if (!value) {
value = s[1].substring(1);
options.env[s[0]] = value;
}
} else if (s[1][0] == '?') {
// If variable is defined and not empty, substitute its value. Otherwise, print message as an error message.
if (!value) {
if (s[1].length > 1) {
throw new Error();
// return cb(s[0] + ': ' + s[1].substring(1));
} else {
throw new Error();
// return cb(s[0] + ': parameter null or not set');
}
}
}
} else {
value = options.env[variable];
if (typeof value == 'function') {
value = value();
}
}
return value;
} | javascript | {
"resource": ""
} |
q36081 | UnidataHeaders | train | function UnidataHeaders(d,m,e) {
if(!d) {
d = new Date();
}
if(!m) {
m = d;
}
if(!e) {
const year = 1000 * 60 * 60 * 24 * 365;
e = new Date(m.valueOf() + year);
} else if(typeof(e) === 'number') {
e = new Date(m.valueOf() + e);
}
/**
* Date the database was downloaded.
*
* @type {Date}
*/
this.date = d;
/**
* Date the database was last updated on the server.
*
* @type {Date}
*/
this.modified = m;
/**
* Date the cached copy of the database is presumed to expire.
*
* @type {Date}
*/
this.expires = e;
} | javascript | {
"resource": ""
} |
q36082 | Fraction | train | function Fraction(n, d) {
if(typeof(d) === "number") {
this.denominator = d;
} else {
this.denominator = 1;
}
if(typeof(n) === "number") {
this.numerator = n;
} else if(typeof(n) === "string") {
let slash = n.indexOf('/');
if(slash > 0) {
/**
* The numerator of the fraction.
*
* @type {number}
*/
this.numerator = Number.parseInt(n.substring(0, slash));
/**
* The denominator of the fraction.
*
* @type {number}
* @defaultvalue 1
*/
this.denominator = Number.parseInt(n.substring(slash + 1));
} else {
this.numerator = Number.parseFloat(n);
}
} else if((typeof(n) === "object") && (n instanceof Fraction)) {
this.numerator = n.numerator;
this.denominator = n.denominator;
} else {
throw new TypeError(`${n} must be a number or a string`);
}
/**
* The numeric value of the fraction i.e., numerator divided by denominator.
*
* @type {number}
*/
this.value = this.numerator / this.denominator;
} | javascript | {
"resource": ""
} |
q36083 | render | train | function render (files, baseDir, renderLabelFn, options = {}) {
baseDir = baseDir.replace(/\/$/, '/')
const strippedFiles = files.map(file => {
/* istanbul ignore else: Else-case should never happen */
if (file.lastIndexOf(baseDir, 0) === 0) {
return file.substr(baseDir.length)
}
/* istanbul ignore next: Should never happen */
throw new Error('Basedir ' + baseDir + ' must be a prefix of ' + file)
})
const rootNode = treeFromPaths(strippedFiles, baseDir, renderLabelFn, options)
const condensed = condense(rootNode)
return archy(condensed)
} | javascript | {
"resource": ""
} |
q36084 | childNodesFromPaths | train | function childNodesFromPaths (files, parent, renderLabelFn, originalFiles, baseDir) {
// Group by first path element
var groups = _.groupBy(files, file => file.match(/^[^/]*\/?/))
return Object.keys(groups).map(function (groupKey) {
const group = groups[groupKey]
// Is this group explicitly part of the result, or
// just implicit through its children
const explicit = group.indexOf(groupKey) >= 0
let index = -1
if (explicit) {
index = originalFiles.indexOf(parent.replace(baseDir, '') + groupKey)
}
return {
label: renderLabelFn(parent, groupKey, explicit, explicit ? index : -1),
nodes: childNodesFromPaths(
// Remove parent directory from file paths
group
.map(node => node.substr(groupKey.length))
// Skip the empty path
.filter(node => node),
// New parent..., normalize to one trailing slash
parent + groupKey,
renderLabelFn,
originalFiles,
baseDir
)
}
})
} | javascript | {
"resource": ""
} |
q36085 | msgBox | train | function msgBox(messageHTML) {
var msgEl = document.querySelector('.msg-box'),
rect = this.getBoundingClientRect();
msgEl.style.top = window.scrollY + rect.bottom + 8 + 'px';
msgEl.style.left = window.scrollX + rect.left + 8 + 'px';
msgEl.style.display = 'block';
msgEl.querySelector('.msg-box-close').addEventListener('click', closeMsgBox);
msgEl.querySelector('.msg-box-content').innerHTML = messageHTML;
this.classList.add('filter-box-warn');
} | javascript | {
"resource": ""
} |
q36086 | captureExpressions | train | function captureExpressions(expressionChain, booleans) {
var expressions, re;
if (booleans) {
re = new RegExp(PREFIX + booleans.join(INFIX) + POSTFIX, 'i');
expressions = expressionChain.match(re);
expressions.shift(); // discard [0] (input)
} else {
expressions = [expressionChain];
}
return expressions;
} | javascript | {
"resource": ""
} |
q36087 | observeArgs | train | function observeArgs(args, run) {
function observeArg(arg, i, args) {
var observer = Observer(
arg,
function argObserver(changes) {
changes.forEach(({type, newValue}) => {
if (type === 'upward') {
args[i] = newValue;
observer.reobserve(newValue);
}
});
run();
},
// @TODO: consider whether to check for D/A/U here, or use 'modify' change type
['upward', 'delete', 'add', 'update'] // @TODO: check all these are necessary
);
observer.observe();
}
args.forEach(observeArg);
} | javascript | {
"resource": ""
} |
q36088 | _setState | train | function _setState (lattice, size) {
for (var num = 0; num < size; num++) {
var cell = {}
cell.state = getRandomState()
lattice.push(cell)
}
return lattice
} | javascript | {
"resource": ""
} |
q36089 | _getRule | train | function _getRule (neighbourhood) {
var currentState = null
var currentRule = [...rule]
neighbourhoods.forEach(function (hood, index) {
if (hood === neighbourhood) {
currentState = currentRule[index]
}
})
return currentState
} | javascript | {
"resource": ""
} |
q36090 | addLocalIceCandidate | train | function addLocalIceCandidate(event) {
if (event && event.candidate) {
// Add the ICE candidate only if we haven't already seen it
var serializedCandidate = JSON.stringify(event.candidate);
if (!storedIceCandidates.hasOwnProperty(serializedCandidate)) {
storedIceCandidates[serializedCandidate] = true;
localIceCandidates.push(event.candidate);
}
}
// Emit an iceCandidates event containing all the candidates
// gathered since the last event if we are emitting
if (emittingIceCandidates && localIceCandidates.length > 0) {
self.emit("iceCandidates", localIceCandidates);
localIceCandidates = [];
}
} | javascript | {
"resource": ""
} |
q36091 | train | function() {
var self = this;
if (typeof CompilerInitialized !== "undefined") return true;
oldPrepend = $.fn.prepend;
$.fn.prepend = function()
{
var isFragment =
arguments[0][0] && arguments[0][0].parentNode
&& arguments[0][0].parentNode.nodeName == "#document-fragment";
var result = oldPrepend.apply(this, arguments);
if (isFragment)
AngularCompile(arguments[0]);
return result;
};
oldAppend = $.fn.append;
$.fn.append = function()
{
var isFragment =
arguments[0][0] && arguments[0][0].parentNode
&& arguments[0][0].parentNode.nodeName == "#document-fragment";
var result = oldAppend.apply(this, arguments);
if (isFragment)
AngularCompile(arguments[0]);
return result;
};
AngularCompile = function(root)
{
var injector = angular.element($('[ng-app]')[0]).injector();
var $compile = injector.get('$compile');
var $rootScope = injector.get('$rootScope');
var result = $compile(root)($rootScope);
$rootScope.$digest();
return result;
}
CompilerInitialized = true;
} | javascript | {
"resource": ""
} | |
q36092 | Vertex | train | function Vertex(pkGloballyUniqueId, id, state, data)
{
var self = this;
var pkGuid = pkGloballyUniqueId;
var serviceStartMethod;
if(VALID_STATES.indexOf(state) > -1)
{
this.id = id;
this.state = state;
this.data = data;
}
else
{
throw new Error("Invalid State", "Invalid initial state: " + state);
}
/**
* Set state of the vertex
*
* @param {VALID_STATES} newState - The new state
*/
this.setState = function (newState)
{
if(VALID_STATES.indexOf(newState) > -1)
{
this.state = newState;
if(newState == "IN_PROGRESS")
{
if(self.parent.parent.isRunning())
{
self.emit(pkGuid + ":" + "start");
}
else
{
// Ignore state changes when PK has stopped running
}
}
}
else
{
throw new Error("Invalid State", "Invalid state: " + newState);
}
};
/**
* Method that PK calls when associated service is to be started
*
* @param {Function} serviceStart - Method that PK will call
*/
this.setServiceStartMethod = function (serviceStart)
{
serviceStartMethod = serviceStart;
};
/**
* Called by PK when associated process is successful
*
* @param {*} data - Data returned by process
*/
this.processSuccessful = function (data)
{
this.data = data;
self.parent.parent.setState(id, "SUCCESS");
};
/**
* Called by PK when process fails
*
* @param {*} err - Error object
*/
this.processFailed = function (err)
{
self.parent.parent.setState(id, "FAIL");
};
} | javascript | {
"resource": ""
} |
q36093 | train | function () {
var config = sails.config[this.configKey];
// the ship drawing looks pretty silly in JSON
sails.config.log.noShip = true;
// as do color codes
sails.config.log.colors = false;
// setup some defaults
config.logger.name = config.logger.name || 'sails';
config.logger.serializers =
config.logger.serializers || bunyan.stdSerializers;
this.reqSerializer = config.logger.serializers.req ||
function (x) { return x; };
this.logger = bunyan.createLogger(config.logger);
} | javascript | {
"resource": ""
} | |
q36094 | train | function (done) {
var config = sails.config[this.configKey];
_this = this;
// If a rotationSignal is given, listen for it
if (config.rotationSignal) {
process.on(config.rotationSignal, function () {
_this.logger.reopenFileStreams();
});
}
// If logUncaughtException is set, log those, too
if (config.logUncaughtException) {
process.on('uncaughtException', function (err) {
_this.logger.fatal({ err: err }, 'Uncaught exception');
process.exit(1);
});
}
// save off injectRequestLogger for middleware route
injectRequestLogger = sails.config[this.configKey].injectRequestLogger;
// Inject log methods
var log = sails.log = this.logger.debug.bind(this.logger);
Object.keys(logLevels).forEach(function (sailsLevel) {
var bunyanLevel = logLevels[sailsLevel];
if (bunyanLevel) {
log[sailsLevel] = function () {
var logger = config.getLogger();
logger[bunyanLevel].apply(logger, arguments);
};
} else {
// no-op
log[sailsLevel] = function () {};
}
});
done();
} | javascript | {
"resource": ""
} | |
q36095 | urlize | train | function urlize(worker, text) {
if (!linkify.test(text)) return escape(text)
var matches = linkify.match(text)
var lastIndex = 0;
var buf = []
for (var i = 0, match; (match = matches[i++]); ) {
buf.push(escape(text.slice(lastIndex, match.index)))
var link = {tag: true, name: 'a',
attrs: {href: match.url},
value: escape(match.type === 'hashtag' ? match.text : truncateUrl(match.text))}
if (match.type === 'hashtag') {
link.attrs['class'] = 'p-category'
}
else {
link.attrs.rel = 'nofollow'
link.attrs.target = '_blank'
}
buf = buf.concat(tagBuffer(worker, link, true))
lastIndex = match.lastIndex
}
buf.push(escape(text.slice(lastIndex)))
debug('urlize', matches, buf)
return buf.join('')
} | javascript | {
"resource": ""
} |
q36096 | compile | train | function compile(ast, opts) {
opts = assign({}, config.defaultOpts, opts)
debug('compile', opts, ast)
var worker = makeWorker(opts)
for (var i = 0, text = ast.value, len = text.length; i < len; i++) {
compileLine(text[i], worker)
}
return worker.buf.join('')
} | javascript | {
"resource": ""
} |
q36097 | findComponents | train | function findComponents(nodes, callback) {
nodes = toArray(nodes);
nodes = [].slice.call(nodes);
var node;
for (var i = 0, l = nodes.length; i < l; i++) {
node = nodes[i];
if (node && node.hasAttribute && node.hasAttribute('data-component')) {
callback(node);
} else if (node.childNodes && node.childNodes.length) {
findComponents([].slice.call(node.childNodes), callback);
}
}
} | javascript | {
"resource": ""
} |
q36098 | train | function () {
count = 100;
this.updateCount(count);
var self = this;
$timeout(function () {
self.hide();
$timeout(function () {
count = 0;
self.updateCount(count);
}, 500);
}, 1000);
return count;
} | javascript | {
"resource": ""
} | |
q36099 | promisify | train | function promisify(f) { // given an underlying function,
return function _promisify(...args) { // return a function which
return new Promise( // returns a promise
resolve => Promise.all([this, ...args]) // which, when all args are resolved,
.then(
parms => resolve(f.call(...parms)) // resolves to the function result
)
);
};
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.