_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q23500 | fadeLinesBut | train | function fadeLinesBut(exceptionItemId) {
let classToFade = 'g.legend-entry';
let entryLine = svg.select(`[data-item="${exceptionItemId}"]`);
if (entryLine.nodes().length){
svg.select('.legend-group')
.selectAll(classToFade)
.cl... | javascript | {
"resource": ""
} |
q23501 | splitInLines | train | function splitInLines() {
let legendEntries = svg.selectAll('.legend-entry');
let numberOfEntries = legendEntries.size();
let lineHeight = (chartHeight / 2) * 1.7;
let newLine = svg.select('.legend-group')
.append('g')
.classed('legend-line',... | javascript | {
"resource": ""
} |
q23502 | writeEntryValues | train | function writeEntryValues() {
svg.select('.legend-group')
.selectAll('g.legend-line')
.selectAll('g.legend-entry')
.append('text')
.classed('legend-entry-value', true)
.text(getFormattedQuantity)
.attr('x', chartWi... | javascript | {
"resource": ""
} |
q23503 | cleanData | train | function cleanData({dataByTopic, dataByDate, data}) {
if (!dataByTopic && !data) {
throw new Error('Data needs to have a dataByTopic or data property. See more in http://eventbrite.github.io/britecharts/global.html#LineChartData__anchor');
}
// If dataByTopic or data... | javascript | {
"resource": ""
} |
q23504 | drawAxis | train | function drawAxis(){
svg.select('.x-axis-group .axis.x')
.attr('transform', `translate(0, ${chartHeight})`)
.call(xAxis);
if (xAxisFormat !== 'custom') {
svg.select('.x-axis-group .month-axis')
.attr('transform', `translate(0, ... | javascript | {
"resource": ""
} |
q23505 | drawLines | train | function drawLines(){
let lines,
topicLine;
topicLine = d3Shape.line()
.curve(curveMap[lineCurve])
.x(({date}) => xScale(date))
.y(({value}) => yScale(value));
lines = svg.select('.chart-group').selectAll('.line')
... | javascript | {
"resource": ""
} |
q23506 | drawAllDataPoints | train | function drawAllDataPoints() {
svg.select('.chart-group')
.selectAll('.data-points-container')
.remove();
const nodesById = paths.nodes().reduce((acc, node) => {
acc[node.id] = node
return acc;
}, {});
co... | javascript | {
"resource": ""
} |
q23507 | findOutNearestDate | train | function findOutNearestDate(x0, d0, d1){
return (new Date(x0).getTime() - new Date(d0.date).getTime()) > (new Date(d1.date).getTime() - new Date(x0).getTime()) ? d0 : d1;
} | javascript | {
"resource": ""
} |
q23508 | getPathYFromX | train | function getPathYFromX(x, path, name, error) {
const key = `${name}-${x}`;
if (key in pathYCache) {
return pathYCache[key];
}
error = error || 0.01;
const maxIterations = 100;
let lengthStart = 0;
let lengthEnd = pat... | javascript | {
"resource": ""
} |
q23509 | buildContainerGroups | train | function buildContainerGroups() {
let container = svg
.append('g')
.classed('container-group', true)
.attr('transform', `translate(${margin.left}, ${margin.top})`);
container
.append('g').classed('grid-lines-group', true);
... | javascript | {
"resource": ""
} |
q23510 | buildScales | train | function buildScales() {
const decidedRange = isReverse ? [chartWidth, 0] : [0, chartWidth];
xScale = d3Scale.scaleLinear()
.domain([0, Math.max(ranges[0], markers[0], measures[0])])
.rangeRound(decidedRange)
.nice();
// Derive width ... | javascript | {
"resource": ""
} |
q23511 | buildSVG | train | function buildSVG(container) {
if (!svg) {
svg = d3Selection.select(container)
.append('svg')
.classed('britechart bullet-chart', true);
buildContainerGroups();
}
svg
.attr('width', width)
... | javascript | {
"resource": ""
} |
q23512 | bulletWidth | train | function bulletWidth(x) {
const x0 = x(0);
return function (d) {
return Math.abs(x(d) - x0);
}
} | javascript | {
"resource": ""
} |
q23513 | drawBullet | train | function drawBullet() {
if (rangesEl) {
rangesEl.remove();
measuresEl.remove();
markersEl.remove();
}
rangesEl = svg.select('.chart-group')
.selectAll('rect.range')
.data(ranges)
.enter()
... | javascript | {
"resource": ""
} |
q23514 | drawTitles | train | function drawTitles() {
if (hasTitle()) {
// either use title provided from the data
// or customTitle provided via API method call
if (legendGroup) {
legendGroup.remove();
}
legendGroup = svg.select('.metad... | javascript | {
"resource": ""
} |
q23515 | sortData | train | function sortData(unorderedData) {
let {data, dataZeroed} = unorderedData;
if (orderingFunction) {
data.sort(orderingFunction);
dataZeroed.sort(orderingFunction)
}
return { data, dataZeroed };
} | javascript | {
"resource": ""
} |
q23516 | drawAxisLabels | train | function drawAxisLabels() {
if (yAxisLabel) {
if (yAxisLabelEl) {
yAxisLabelEl.remove();
}
yAxisLabelEl = svg.select('.y-axis-label')
.append('text')
.classed('y-axis-label-text', true)
... | javascript | {
"resource": ""
} |
q23517 | drawAnimatedHorizontalBars | train | function drawAnimatedHorizontalBars(bars) {
// Enter + Update
bars.enter()
.append('rect')
.classed('bar', true)
.attr('x', 0)
.attr('y', chartHeight)
.attr('height', yScale.bandwidth())
.attr('width', ... | javascript | {
"resource": ""
} |
q23518 | drawVerticalBars | train | function drawVerticalBars(bars) {
// Enter + Update
bars.enter()
.append('rect')
.classed('bar', true)
.attr('x', chartWidth)
.attr('y', ({value}) => yScale(value))
.attr('width', xScale.bandwidth())
.a... | javascript | {
"resource": ""
} |
q23519 | drawLabels | train | function drawLabels() {
let labelXPosition = isHorizontal ? _labelsHorizontalX : _labelsVerticalX;
let labelYPosition = isHorizontal ? _labelsHorizontalY : _labelsVerticalY;
let text = _labelsFormatValue
if (labelEl) {
svg.selectAll('.percentage-label-gro... | javascript | {
"resource": ""
} |
q23520 | drawBars | train | function drawBars() {
let bars;
if (isAnimated) {
bars = svg.select('.chart-group').selectAll('.bar')
.data(dataZeroed);
if (isHorizontal) {
drawHorizontalBars(bars);
} else {
drawVertic... | javascript | {
"resource": ""
} |
q23521 | drawHorizontalGridLines | train | function drawHorizontalGridLines() {
maskGridLines = svg.select('.grid-lines-group')
.selectAll('line.vertical-grid-line')
.data(xScale.ticks(xTicks).slice(1))
.enter()
.append('line')
.attr('class', 'vertical-grid-line')
... | javascript | {
"resource": ""
} |
q23522 | drawVerticalExtendedLine | train | function drawVerticalExtendedLine() {
baseLine = svg.select('.grid-lines-group')
.selectAll('line.extended-y-line')
.data([0])
.enter()
.append('line')
.attr('class', 'extended-y-line')
.attr('y1', (xAx... | javascript | {
"resource": ""
} |
q23523 | drawVerticalGridLines | train | function drawVerticalGridLines() {
maskGridLines = svg.select('.grid-lines-group')
.selectAll('line.horizontal-grid-line')
.data(yScale.ticks(yTicks).slice(1))
.enter()
.append('line')
.attr('class', 'horizontal-grid-line'... | javascript | {
"resource": ""
} |
q23524 | buildLayers | train | function buildLayers() {
layers = transformedData.map((item) => {
let ret = {};
groups.forEach((key) => {
ret[key] = item[key];
});
return assign({}, item, ret);
});
} | javascript | {
"resource": ""
} |
q23525 | cleanData | train | function cleanData(originalData) {
return originalData.reduce((acc, d) => {
d.value = +d[valueLabel];
d.group = d[groupLabel];
// for tooltip
d.topicName = getGroup(d);
d.name = d[nameLabel];
... | javascript | {
"resource": ""
} |
q23526 | drawHorizontalBars | train | function drawHorizontalBars(layersSelection) {
let layerJoin = layersSelection
.data(layers);
layerElements = layerJoin
.enter()
.append('g')
.attr('transform', ({key}) => `translate(0,${yScale(key)})`)
.c... | javascript | {
"resource": ""
} |
q23527 | handleBarsMouseOver | train | function handleBarsMouseOver(e, d) {
d3Selection.select(e)
.attr('fill', () => d3Color.color(categoryColorMap[d.group]).darker());
} | javascript | {
"resource": ""
} |
q23528 | handleBarsMouseOut | train | function handleBarsMouseOut(e, d) {
d3Selection.select(e)
.attr('fill', () => categoryColorMap[d.group])
} | javascript | {
"resource": ""
} |
q23529 | handleCustomClick | train | function handleCustomClick (e, d) {
let [mouseX, mouseY] = getMousePosition(e);
let dataPoint = isHorizontal ? getNearestDataPoint2(mouseY) : getNearestDataPoint(mouseX);
dispatcher.call('customClick', e, dataPoint, d3Selection.mouse(e));
} | javascript | {
"resource": ""
} |
q23530 | horizontalBarsTween | train | function horizontalBarsTween(d) {
let node = d3Selection.select(this),
i = d3Interpolate.interpolateRound(0, xScale(getValue(d))),
j = d3Interpolate.interpolateNumber(0, 1);
return function (t) {
node.attr('width', i(t))
.style... | javascript | {
"resource": ""
} |
q23531 | prepareData | train | function prepareData(data) {
groups = uniq(data.map((d) => getGroup(d)));
transformedData = d3Collection.nest()
.key(getName)
.rollup(function (values) {
let ret = {};
values.forEach((entry) => {
if ... | javascript | {
"resource": ""
} |
q23532 | verticalBarsTween | train | function verticalBarsTween(d) {
let node = d3Selection.select(this),
i = d3Interpolate.interpolateRound(0, chartHeight - yScale(getValue(d))),
y = d3Interpolate.interpolateRound(chartHeight, yScale(getValue(d))),
j = d3Interpolate.interpolateNumber(0, 1);
... | javascript | {
"resource": ""
} |
q23533 | jobNameValidator | train | function jobNameValidator(value) {
const response = { isValid: true, notification: { type: 'success', msg: '', title: '' } };
if (!value) {
response.isValid = false;
response.notification.type = 'error';
response.notification.msg = 'Value must be inserted';
response.notification.title = 'Requested V... | javascript | {
"resource": ""
} |
q23534 | getClearBonus | train | function getClearBonus(events, warriorScore, timeBonus) {
const lastEvent = getLastEvent(events);
if (!isFloorClear(lastEvent.floorMap)) {
return 0;
}
return Math.round((warriorScore + timeBonus) * 0.2);
} | javascript | {
"resource": ""
} |
q23535 | getLevelConfig | train | function getLevelConfig(tower, levelNumber, warriorName, epic) {
const level = tower.levels[levelNumber - 1];
if (!level) {
return null;
}
const levelConfig = cloneDeep(level);
const levels = epic ? tower.levels : tower.levels.slice(0, levelNumber);
const warriorAbilities = Object.assign(
{},
... | javascript | {
"resource": ""
} |
q23536 | parseArgs | train | function parseArgs(args) {
return yargs
.usage('Usage: $0 [options]')
.options({
d: {
alias: 'directory',
default: '.',
describe: 'Run under given directory',
type: 'string',
},
l: {
alias: 'level',
coerce: arg => {
const parsed = Num... | javascript | {
"resource": ""
} |
q23537 | printLogMessage | train | function printLogMessage(unit, message) {
const prompt = chalk.gray.dim('>');
const logMessage = getUnitStyle(unit)(`${unit.name} ${message}`);
printLine(`${prompt} ${logMessage}`);
} | javascript | {
"resource": ""
} |
q23538 | printLevelReport | train | function printLevelReport(
profile,
{ warrior: warriorScore, timeBonus, clearBonus },
totalScore,
grade,
) {
printLine(`Warrior Score: ${warriorScore}`);
printLine(`Time Bonus: ${timeBonus}`);
printLine(`Clear Bonus: ${clearBonus}`);
if (profile.isEpic()) {
printLine(`Level Grade: ${getGradeLetter(... | javascript | {
"resource": ""
} |
q23539 | verifyRelativeDirection | train | function verifyRelativeDirection(direction) {
if (!RELATIVE_DIRECTIONS.includes(direction)) {
throw new Error(
`Unknown direction: '${direction}'. Should be one of: '${FORWARD}', '${RIGHT}', '${BACKWARD}' or '${LEFT}'.`,
);
}
} | javascript | {
"resource": ""
} |
q23540 | loadAbilities | train | function loadAbilities(unit, abilities = {}) {
Object.entries(abilities).forEach(([abilityName, abilityCreator]) => {
const ability = abilityCreator(unit);
unit.addAbility(abilityName, ability);
});
} | javascript | {
"resource": ""
} |
q23541 | loadEffects | train | function loadEffects(unit, effects = {}) {
Object.entries(effects).forEach(([effectName, effectCreator]) => {
const effect = effectCreator(unit);
unit.addEffect(effectName, effect);
});
} | javascript | {
"resource": ""
} |
q23542 | loadWarrior | train | function loadWarrior(
{ name, character, color, maxHealth, abilities, effects, position },
floor,
playerCode,
) {
const warrior = new Warrior(name, character, color, maxHealth);
loadAbilities(warrior, abilities);
loadEffects(warrior, effects);
warrior.playTurn = playerCode ? loadPlayer(playerCode) : () =>... | javascript | {
"resource": ""
} |
q23543 | loadUnit | train | function loadUnit(
{
name,
character,
color,
maxHealth,
reward,
enemy,
bound,
abilities,
effects,
playTurn,
position,
},
floor,
) {
const unit = new Unit(
name,
character,
color,
maxHealth,
reward,
enemy,
bound,
);
loadAbilities(unit, a... | javascript | {
"resource": ""
} |
q23544 | loadLevel | train | function loadLevel(
{
number,
description,
tip,
clue,
floor: { size, stairs, warrior, units = [] },
},
playerCode,
) {
const { width, height } = size;
const stairsLocation = [stairs.x, stairs.y];
const floor = new Floor(width, height, stairsLocation);
loadWarrior(warrior, floor, playe... | javascript | {
"resource": ""
} |
q23545 | requestConfirmation | train | async function requestConfirmation(message, defaultAnswer = false) {
const answerName = 'requestConfirmation';
const answers = await inquirer.prompt([
{
message,
name: answerName,
type: 'confirm',
default: defaultAnswer,
},
]);
return answers[answerName];
} | javascript | {
"resource": ""
} |
q23546 | verifyAbsoluteDirection | train | function verifyAbsoluteDirection(direction) {
if (!ABSOLUTE_DIRECTIONS.includes(direction)) {
throw new Error(
`Unknown direction: '${direction}'. Should be one of: '${NORTH}', '${EAST}', '${SOUTH}' or '${WEST}'.`,
);
}
} | javascript | {
"resource": ""
} |
q23547 | printTurnHeader | train | function printTurnHeader(turnNumber) {
printRow(chalk.gray.dim(` ${String(turnNumber).padStart(3, '0')} `), {
position: 'middle',
padding: chalk.gray.dim('~'),
});
} | javascript | {
"resource": ""
} |
q23548 | printFloorMap | train | function printFloorMap(floorMap) {
printLine(
floorMap
.map(row =>
row
.map(({ character, unit }) => {
if (unit) {
return getUnitStyle(unit)(character);
}
return character;
})
.join(''),
)
.join('\n'),
);
... | javascript | {
"resource": ""
} |
q23549 | loadPlayer | train | function loadPlayer(playerCode) {
const sandbox = vm.createContext();
// Do not collect stack frames for errors in the player code.
vm.runInContext('Error.stackTraceLimit = 0;', sandbox);
try {
vm.runInContext(playerCode, sandbox, {
filename: playerCodeFilename,
timeout: playerCodeTimeout,
... | javascript | {
"resource": ""
} |
q23550 | printRow | train | function printRow(message, { position = 'start', padding = ' ' } = {}) {
const [screenWidth] = getScreenSize();
const rowWidth = screenWidth - 1; // Consider line break length.
const messageWidth = stringWidth(message);
const paddingWidth = (rowWidth - messageWidth) / 2;
const startPadding = padding.repeat(Ma... | javascript | {
"resource": ""
} |
q23551 | printTowerReport | train | function printTowerReport(profile) {
const averageGrade = profile.calculateAverageGrade();
if (!averageGrade) {
return;
}
const averageGradeLetter = getGradeLetter(averageGrade);
printLine(`Your average grade for this tower is: ${averageGradeLetter}\n`);
Object.keys(profile.currentEpicGrades)
.sor... | javascript | {
"resource": ""
} |
q23552 | getLevelScore | train | function getLevelScore({ passed, events }, { timeBonus }) {
if (!passed) {
return null;
}
const warriorScore = getWarriorScore(events);
const remainingTimeBonus = getRemainingTimeBonus(events, timeBonus);
const clearBonus = getClearBonus(events, warriorScore, remainingTimeBonus);
return {
clearBonu... | javascript | {
"resource": ""
} |
q23553 | getExternalTowersInfo | train | function getExternalTowersInfo() {
const cliDir = findUp.sync('@warriorjs/cli', { cwd: __dirname });
if (!cliDir) {
return [];
}
const cliParentDir = path.resolve(cliDir, '..');
const towerSearchDir = findUp.sync('node_modules', { cwd: cliParentDir });
const towerPackageJsonPaths = globby.sync(
[of... | javascript | {
"resource": ""
} |
q23554 | loadTowers | train | function loadTowers() {
const internalTowersInfo = getInternalTowersInfo();
const externalTowersInfo = getExternalTowersInfo();
return uniqBy(internalTowersInfo.concat(externalTowersInfo), 'id').map(
({ id, requirePath }) => {
const { name, description, levels } = require(requirePath); // eslint-disable... | javascript | {
"resource": ""
} |
q23555 | rotateRelativeOffset | train | function rotateRelativeOffset([forward, right], direction) {
verifyRelativeDirection(direction);
if (direction === FORWARD) {
return [forward, right];
}
if (direction === RIGHT) {
return [-right, forward];
}
if (direction === BACKWARD) {
return [-forward, -right];
}
return [right, -forwa... | javascript | {
"resource": ""
} |
q23556 | requestChoice | train | async function requestChoice(message, items) {
const answerName = 'requestChoice';
const answers = await inquirer.prompt([
{
message,
name: answerName,
type: 'list',
choices: getChoices(items),
},
]);
return answers[answerName];
} | javascript | {
"resource": ""
} |
q23557 | printBoard | train | function printBoard(floorMap, warriorStatus, offset) {
if (offset > 0) {
const floorMapRows = floorMap.length;
print(ansiEscapes.cursorUp(offset + floorMapRows + warriorStatusRows));
}
printWarriorStatus(warriorStatus);
printFloorMap(floorMap);
if (offset > 0) {
print(ansiEscapes.cursorDown(offs... | javascript | {
"resource": ""
} |
q23558 | getRemainingTimeBonus | train | function getRemainingTimeBonus(events, timeBonus) {
const turnCount = getTurnCount(events);
const remainingTimeBonus = timeBonus - turnCount;
return Math.max(remainingTimeBonus, 0);
} | javascript | {
"resource": ""
} |
q23559 | requestInput | train | async function requestInput(message, suggestions = []) {
const answerName = 'requestInput';
const answers = await inquirer.prompt([
{
message,
suggestions,
name: answerName,
type: suggestions.length ? 'suggest' : 'input',
},
]);
return answers[answerName];
} | javascript | {
"resource": ""
} |
q23560 | getLevel | train | function getLevel(levelConfig) {
const level = loadLevel(levelConfig);
return JSON.parse(JSON.stringify(level));
} | javascript | {
"resource": ""
} |
q23561 | printTotalScore | train | function printTotalScore(currentScore, addition) {
if (currentScore === 0) {
printLine(`Total Score: ${addition.toString()}`);
} else {
printLine(
`Total Score: ${currentScore} + ${addition} = ${currentScore + addition}`,
);
}
} | javascript | {
"resource": ""
} |
q23562 | printPlay | train | async function printPlay(events, delay) {
let turnNumber = 0;
let boardOffset = 0;
await sleep(delay);
// eslint-disable-next-line no-restricted-syntax
for (const turnEvents of events) {
turnNumber += 1;
boardOffset = 0;
printTurnHeader(turnNumber);
// eslint-disable-next-line no-restricted... | javascript | {
"resource": ""
} |
q23563 | isFloorClear | train | function isFloorClear(floorMap) {
const spaces = floorMap.reduce((acc, val) => acc.concat(val), []);
const unitCount = spaces.filter(space => !!space.unit).length;
return unitCount <= 1;
} | javascript | {
"resource": ""
} |
q23564 | printLevelHeader | train | function printLevelHeader(levelNumber) {
printRow(chalk.gray.dim(` level ${levelNumber} `), {
position: 'middle',
padding: chalk.gray.dim('~'),
});
} | javascript | {
"resource": ""
} |
q23565 | train | function(err, res) {
if (_.isFunction(callback)) {
try {
res = callback(err, res);
err = null;
} catch(e) {
err = e;
}
}
if (err) {
deferred.reject(err);
} else {
deferred.resolve(res);
}
} | javascript | {
"resource": ""
} | |
q23566 | train | function(params) {
params = _.extend({
response_type : "code",
client_id : this.clientId,
redirect_uri : this.redirectUri
}, params || {});
return this.authzServiceUrl +
(this.authzServiceUrl.indexOf('?') >= 0 ? "&" : "?") +
querystring.stringify(params);
} | javascript | {
"resource": ""
} | |
q23567 | train | function(token, callback) {
return this._transport.httpRequest({
method : 'POST',
url : this.revokeServiceUrl,
body: querystring.stringify({ token: token }),
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}).then(function(response) {
if (response.sta... | javascript | {
"resource": ""
} | |
q23568 | createCacheKey | train | function createCacheKey(namespace, args) {
args = Array.prototype.slice.apply(args);
return namespace + '(' + _.map(args, function(a){ return JSON.stringify(a); }).join(',') + ')';
} | javascript | {
"resource": ""
} |
q23569 | train | function(conn, options) {
options = options || {};
this._conn = conn;
this.on('resume', function(err) { conn.emit('resume', err); });
this._responseType = options.responseType;
this._transport = options.transport || conn._transport;
this._noContentResponse = options.noContentResponse;
} | javascript | {
"resource": ""
} | |
q23570 | injectBefore | train | function injectBefore(replServer, method, beforeFn) {
var _orig = replServer[method];
replServer[method] = function() {
var args = Array.prototype.slice.call(arguments);
var callback = args.pop();
beforeFn.apply(null, args.concat(function(err, res) {
if (err || res) {
callback(err, res);
... | javascript | {
"resource": ""
} |
q23571 | promisify | train | function promisify(err, value, callback) {
if (err) { throw err; }
if (isPromiseLike(value)) {
value.then(function(v) {
callback(null, v);
}, function(err) {
callback(err);
});
} else {
callback(null, value);
}
} | javascript | {
"resource": ""
} |
q23572 | outputToStdout | train | function outputToStdout(prettyPrint) {
if (prettyPrint && !_.isNumber(prettyPrint)) {
prettyPrint = 4;
}
return function(err, value, callback) {
if (err) {
console.error(err);
} else {
var str = JSON.stringify(value, null, prettyPrint);
console.log(str);
}
callback(err, value... | javascript | {
"resource": ""
} |
q23573 | train | function(path) {
const { node } = path;
if (node.declarations.length < 2) {
return;
}
const inits = [];
const empty = [];
for (const decl of node.declarations) {
if (!decl.init) {
empty.push(decl);
... | javascript | {
"resource": ""
} | |
q23574 | train | function(path) {
const { node } = path;
if (
!path.parentPath.parentPath.isFunction() ||
path.getSibling(path.key + 1).node
) {
return;
}
if (!node.argument) {
path.remove();
return;
... | javascript | {
"resource": ""
} | |
q23575 | train | function(path) {
const { node } = path;
// Need to be careful of side-effects.
if (!t.isIdentifier(node.discriminant)) {
return;
}
if (!node.cases.length) {
return;
}
const consTestPairs = [];
... | javascript | {
"resource": ""
} | |
q23576 | train | function(path) {
const { node } = path;
// Need to be careful of side-effects.
if (!t.isIdentifier(node.discriminant)) {
return;
}
if (!node.cases.length) {
return;
}
const exprTestPairs = [];
... | javascript | {
"resource": ""
} | |
q23577 | toGuardedExpression | train | function toGuardedExpression(path) {
const { node } = path;
if (
node.consequent &&
!node.alternate &&
node.consequent.type === "ExpressionStatement"
) {
let op = "&&";
if (t.isUnaryExpression(node.test, { operator: "!" })) {
node.test = node.test.argument;
op =... | javascript | {
"resource": ""
} |
q23578 | toTernary | train | function toTernary(path) {
const { node } = path;
if (
t.isExpressionStatement(node.consequent) &&
t.isExpressionStatement(node.alternate)
) {
path.replaceWith(
t.conditionalExpression(
node.test,
node.consequent.expression,
node.alternate.expression
... | javascript | {
"resource": ""
} |
q23579 | removeUnnecessaryElse | train | function removeUnnecessaryElse(path) {
const { node } = path;
const consequent = path.get("consequent");
const alternate = path.get("alternate");
if (
consequent.node &&
alternate.node &&
(consequent.isReturnStatement() ||
(consequent.isBlockStatement() &&
t.isReturn... | javascript | {
"resource": ""
} |
q23580 | switchConsequent | train | function switchConsequent(path) {
const { node } = path;
if (!node.alternate) {
return;
}
if (!t.isIfStatement(node.consequent)) {
return;
}
if (t.isIfStatement(node.alternate)) {
return;
}
node.test = t.unaryExpression("!", node.test, true);
[node.alternate, no... | javascript | {
"resource": ""
} |
q23581 | conditionalReturnToGuards | train | function conditionalReturnToGuards(path) {
const { node } = path;
if (
!path.inList ||
!path.get("consequent").isBlockStatement() ||
node.alternate
) {
return;
}
let ret;
let test;
const exprs = [];
const statements = node.consequent.body;
for (let i = 0, s... | javascript | {
"resource": ""
} |
q23582 | unpad | train | function unpad(str) {
const lines = str.split("\n");
const m = lines[1] && lines[1].match(/^\s+/);
if (!m) {
return str;
}
const spaces = m[0].length;
return lines
.map(line => line.slice(spaces))
.join("\n")
.trim();
} | javascript | {
"resource": ""
} |
q23583 | baseTypeStrictlyMatches | train | function baseTypeStrictlyMatches(left, right) {
let leftTypes, rightTypes;
if (t.isIdentifier(left)) {
leftTypes = customTypeAnnotation(left);
} else if (t.isIdentifier(right)) {
rightTypes = customTypeAnnotation(right);
}
// Early exit
if (t.isAnyTypeAnnotation(leftTypes) || t.isA... | javascript | {
"resource": ""
} |
q23584 | removeUseStrict | train | function removeUseStrict(block) {
if (!block.isBlockStatement()) {
throw new Error(
`Received ${block.type}. Expected BlockStatement. ` +
`Please report at ${newIssueUrl}`
);
}
const useStricts = getUseStrictDirectives(block);
// early exit
if (useStricts.length < 1) return;
// only... | javascript | {
"resource": ""
} |
q23585 | tableStyle | train | function tableStyle() {
return {
chars: {
top: "",
"top-mid": "",
"top-left": "",
"top-right": "",
bottom: "",
"bottom-mid": "",
"bottom-left": "",
"bottom-right": "",
left: "",
"left-mid": "",
mid: "",
"mid-mid": "",
right: "",
"... | javascript | {
"resource": ""
} |
q23586 | readStdin | train | async function readStdin() {
let code = "";
const stdin = process.stdin;
return new Promise(resolve => {
stdin.setEncoding("utf8");
stdin.on("readable", () => {
const chunk = process.stdin.read();
if (chunk !== null) code += chunk;
});
stdin.on("end", () => {
resolve(code);
}... | javascript | {
"resource": ""
} |
q23587 | shouldDeoptBasedOnScope | train | function shouldDeoptBasedOnScope(binding, refPath) {
if (binding.scope.path.isProgram() && refPath.scope !== binding.scope) {
return true;
}
return false;
} | javascript | {
"resource": ""
} |
q23588 | getSegmentedSubPaths | train | function getSegmentedSubPaths(paths) {
let segments = new Map();
// Get earliest Path in tree where paths intersect
paths[0].getDeepestCommonAncestorFrom(
paths,
(lastCommon, index, ancestries) => {
// found the LCA
if (!lastCommon.isProgram()) {
let fnParent;
... | javascript | {
"resource": ""
} |
q23589 | toObject | train | function toObject(value) {
if (!Array.isArray(value)) {
return value;
}
const map = {};
for (let i = 0; i < value.length; i++) {
map[value[i]] = true;
}
return map;
} | javascript | {
"resource": ""
} |
q23590 | train | function(path) {
if (!path.inList) {
return;
}
const { node } = path;
let sibling = path.getSibling(path.key + 1);
let declarations = [];
while (sibling.isVariableDeclaration({ kind: node.kind })) {
declarations = de... | javascript | {
"resource": ""
} | |
q23591 | train | function(path) {
if (!path.inList) {
return;
}
const { node } = path;
if (node.kind !== "var") {
return;
}
const next = path.getSibling(path.key + 1);
if (!next.isForStatement()) {
return;
... | javascript | {
"resource": ""
} | |
q23592 | authorize | train | function authorize(credentials, callback) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redire... | javascript | {
"resource": ""
} |
q23593 | train | function () {
var ambiguity_list = AMBIGUITIES[timezone_name],
length = ambiguity_list.length,
i = 0,
tz = ambiguity_list[0];
for (; i < length; i += 1) {
tz = ambiguity_list[i];
if (jstz.dat... | javascript | {
"resource": ""
} | |
q23594 | redirectToHttps | train | function redirectToHttps(req, res, target, ssl, log) {
req.url = req._url || req.url; // Get the original url since we are going to redirect.
var targetPort = ssl.redirectPort || ssl.port;
var hostname = req.headers.host.split(':')[0] + ( targetPort ? ':' + targetPort : '' );
var url = 'https://' + path.join(h... | javascript | {
"resource": ""
} |
q23595 | getFurthestAncestor | train | function getFurthestAncestor(node) {
var root = node;
while (root.parentNode != null) {
root = root.parentNode;
}
return root;
} | javascript | {
"resource": ""
} |
q23596 | isCollapsedLineBreak | train | function isCollapsedLineBreak(br) {
if (!isHtmlElement(br, "br")) {
return false;
}
// Add a zwsp after it and see if that changes the height of the nearest
// non-inline parent. Note: this is not actually reliable, because the
// parent might have a fixed height or... | javascript | {
"resource": ""
} |
q23597 | getEffectiveCommandValue | train | function getEffectiveCommandValue(node, context) {
var isElement = (node.nodeType == 1);
// "If neither node nor its parent is an Element, return null."
if (!isElement && (!node.parentNode || node.parentNode.nodeType != 1)) {
return null;
}
// "If node is not an Ele... | javascript | {
"resource": ""
} |
q23598 | doSubstituteBuildVars | train | function doSubstituteBuildVars(file, buildVars) {
var contents = fs.readFileSync(file, FILE_ENCODING);
contents = contents.replace(/%%build:([^%]+)%%/g, function(matched, buildVarName) {
return buildVars[buildVarName];
});
// Now do replacements specified by build dire... | javascript | {
"resource": ""
} |
q23599 | isAncestor | train | function isAncestor(ancestor, descendant) {
return ancestor
&& descendant
&& Boolean(ancestor.compareDocumentPosition(descendant) & Node.DOCUMENT_POSITION_CONTAINED_BY);
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.