_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q42700
train
function () { var prefix = '%(', suffix = ')', data = this.data, output = '', dataKey; output = this.__message__; for (dataKey in data) { if (data.hasOwnProperty(dataKey)) { output = output.replace(prefix + dataKey + suffix, '' + data[dataKey]); } } output = output.replace(prefix + 'code' + suffix, '' + this.code); output = output.replace(prefix + 'name' + suffix, '' + this.name); return output; }
javascript
{ "resource": "" }
q42701
train
function (full) { var output, data; output = this.name + '[' + this.code + ']: '; output += this.message; if (full) { output += '\n'; output += this.stack.toString(); } return output; }
javascript
{ "resource": "" }
q42702
setView
train
function setView({ action, config, route, routes, method }) { const ws = route.ws; return exports.getView(action, config).then(view => { routes[ws ? 'ws' : route.type].push({ action, method, view, match: new Route(route.url), }); }); }
javascript
{ "resource": "" }
q42703
train
function() { var rangeList = this, bookmark = CKEDITOR.dom.walker.bookmark(), bookmarks = [], current; return { /** * Retrieves the next range in the list. * * @member CKEDITOR.dom.rangeListIterator * @param {Boolean} [mergeConsequent=false] Whether join two adjacent * ranges into single, e.g. consequent table cells. */ getNextRange: function( mergeConsequent ) { current = current === undefined ? 0 : current + 1; var range = rangeList[ current ]; // Multiple ranges might be mangled by each other. if ( range && rangeList.length > 1 ) { // Bookmarking all other ranges on the first iteration, // the range correctness after it doesn't matter since we'll // restore them before the next iteration. if ( !current ) { // Make sure bookmark correctness by reverse processing. for ( var i = rangeList.length - 1; i >= 0; i-- ) bookmarks.unshift( rangeList[ i ].createBookmark( true ) ); } if ( mergeConsequent ) { // Figure out how many ranges should be merged. var mergeCount = 0; while ( rangeList[ current + mergeCount + 1 ] ) { var doc = range.document, found = 0, left = doc.getById( bookmarks[ mergeCount ].endNode ), right = doc.getById( bookmarks[ mergeCount + 1 ].startNode ), next; // Check subsequent range. while ( 1 ) { next = left.getNextSourceNode( false ); if ( !right.equals( next ) ) { // This could be yet another bookmark or // walking across block boundaries. if ( bookmark( next ) || ( next.type == CKEDITOR.NODE_ELEMENT && next.isBlockBoundary() ) ) { left = next; continue; } } else { found = 1; } break; } if ( !found ) break; mergeCount++; } } range.moveToBookmark( bookmarks.shift() ); // Merge ranges finally after moving to bookmarks. while ( mergeCount-- ) { next = rangeList[ ++current ]; next.moveToBookmark( bookmarks.shift() ); range.setEnd( next.endContainer, next.endOffset ); } } return range; } }; }
javascript
{ "resource": "" }
q42704
train
function(typeCode) { switch (typeCode) { case this.types.undefined: return this.Undefined; case this.types.string: return this.String; case this.types.integer: return this.Integer; case this.types.double: return this.Double; case this.types.boolean: return this.Boolean; case this.types["null"]: return this.Null; case this.types.datetime: return this.DateTime; case this.types.array: return this.Array; case this.types.object: return this.Object; case this.types["function"]: return this.Function; default: throw new Error("Unknown typeCode \"" + typeCode + "\"."); } }
javascript
{ "resource": "" }
q42705
addType
train
function addType(descriptor) { if (!(descriptor instanceof fs.Stats)) { return descriptor; } [ "isFile", "isDirectory", "isBlockDevice", "isCharacterDevice", "isSymbolicLink", "isFIFO", "isSocket", ].forEach(function(funcName) { if (descriptor[funcName]()) { descriptor[funcName] = true; } else { descriptor[funcName] = undefined; } }); if (_.isArray(descriptor.content)) { descriptor.content.forEach(function(obj) { addType(obj); }); } return descriptor; }
javascript
{ "resource": "" }
q42706
getArgs
train
function getArgs(userArgs, defaultArgs, userCallback) { let args = { }; let callback = userCallback || function() { }; defaultArgs.unshift(args); _.assign.apply(null, defaultArgs); if (_.isPlainObject(userArgs)) { _.merge(args, userArgs); } else { callback = userArgs; } return { options: args, callback, }; }
javascript
{ "resource": "" }
q42707
removeDuplicates
train
function removeDuplicates(files, duplicates) { var i; var ret = []; var found = {}; if (duplicates) { for (i=0; i < duplicates.length; i++) { found[duplicates[i].dst] = true; } } for (i=0; i < files.length; i++) { if (!found[files[i].dst]) { found[files[i].dst] = true; ret.push(files[i]); } } return ret; }
javascript
{ "resource": "" }
q42708
flatten
train
function flatten(files) { var ret = []; for (var i=0; i < files.length; i++) { ret.push(files[i].dst); } return ret; }
javascript
{ "resource": "" }
q42709
prefixDest
train
function prefixDest(prefix, files) { for (var i = 0; i < files.length; i++) { files[i].dst = prefix + files[i].dst; } return files; }
javascript
{ "resource": "" }
q42710
filesInRepository
train
function filesInRepository(dir) { var ignoreDirs = cog.getOption('ignore_dirs'); // TODO: Allow an array and move to config. var ignoreFiles = /~$/; var files = glob.sync(dir ? dir + '/*' : '*'); var ret = []; for (var i = 0; i < files.length; i++) { if (fs.lstatSync(files[i]).isDirectory()) { // Ignore standard directories of uninterest. if (!dir && ignoreDirs.indexOf(files[i]) >= 0) { continue; } ret = filesInRepository(files[i]).concat(ret); } else { if (!ignoreFiles.test(files[i])) { ret.push(files[i]); } } } return ret; }
javascript
{ "resource": "" }
q42711
excludeFiles
train
function excludeFiles(list, regex) { var ret = []; for (var i=0; i < list.length; i++) { if (!regex.test(list[i].dst)) { ret.push(list[i]); } } return ret; }
javascript
{ "resource": "" }
q42712
srcFiles
train
function srcFiles() { return removeDuplicates(configFiles().concat(libFiles()).concat(modelFiles()).concat(srcDataFiles()).concat(codeFiles())); }
javascript
{ "resource": "" }
q42713
otherNonJsFiles
train
function otherNonJsFiles() { return removeDuplicates(files(cog.getConfig('src.other'), 'other'), srcFiles().concat(otherJsFiles().concat(appIndexFiles()))); }
javascript
{ "resource": "" }
q42714
includeJsFiles
train
function includeJsFiles() { if (cog.getOption('include_only_external')) { return extLibFiles().concat(generatedJsFiles()); } if (cog.getOption('compile_typescript')) { return extLibFiles().concat(generatedJsFiles()); } return extLibFiles().concat(srcFiles()).concat(generatedJsFiles()); }
javascript
{ "resource": "" }
q42715
allJavascriptFiles
train
function allJavascriptFiles() { return srcFiles().concat(otherJsFiles()).concat(unitTestFiles()).concat(unitTestHelperFiles()).concat(taskFiles()).concat(commonJsFiles()); }
javascript
{ "resource": "" }
q42716
workTextFiles
train
function workTextFiles() { return indexFiles().concat(srcFiles()).concat(allTestFiles()).concat(otherJsFiles()).concat(otherNonJsFiles()).concat(taskFiles()).concat(cssFiles()) .concat(toolsShellFiles()).concat(commonJsFiles()).concat(htmlTemplateFiles()).concat(pythonFiles()).concat(textDataFiles()); }
javascript
{ "resource": "" }
q42717
generatedJsFiles
train
function generatedJsFiles(what) { var ret = []; if ((!what || what === 'templates') && cog.getOption('template')) { ret.push({src: null, dst: cog.getOption('template')}); } if (cog.getOption('compile_typescript')) { var src = srcTypescriptFiles(); for (var i = 0; i < src.length; i++) { if (src[i].src.substr(-3) === '.ts') { src[i].dst = src[i].src.substr(0, src[i].src.length - 3) + '.js'; ret.push(src[i]); } } } return ret; }
javascript
{ "resource": "" }
q42718
fileCategoryMap
train
function fileCategoryMap() { // Go over every file lookup function we export. var exports = module.exports(grunt); // This list of categories must contain all non-overlapping file categories. var categories = ['extLibFiles', 'extLibMapFiles', 'extCssFiles', 'extFontFiles', 'fontFiles', 'appIndexFiles', 'testIndexFiles', 'configFiles', 'libFiles', 'modelFiles', 'srcDataFiles', 'codeFiles', 'otherJsFiles', 'otherNonJsFiles', 'taskFiles', 'cssFiles', 'picFiles', 'soundFiles', 'unitTestFiles', 'commonJsFiles', 'commonOtherFiles', 'ignoredFiles', 'distUncompressedFiles', 'distLibFiles', 'distIndexFiles', 'distJsFiles', 'distCssFiles', 'toolsShellFiles', 'unitTestDataFiles', 'picSrcFiles', 'soundSrcFiles', 'htmlTemplateFiles', 'generatedJsFiles', 'otherMediaFiles', 'unitTestHelperFiles', 'pythonFiles', 'compiledPythonFiles', 'localizationDataFiles', 'developmentOtherDataFiles', 'developmentTextDataFiles']; // Construct the map by calling each function defined above. var map = {}; for (var i = 0; i < categories.length; i++) { var files = flatten(exports[categories[i]]()); for (var j = 0; j < files.length; j++) { if (map[files[j]]) { grunt.fail.warn("A file '" + files[j] + "' maps to category '" + categories[i] + "' in addition to '" + map[files[j]] + "' category."); } else { map[files[j]] = categories[i]; } } } return map; }
javascript
{ "resource": "" }
q42719
validateBemJson
train
function validateBemJson(bemJson, fileName) { let errors = []; if (Array.isArray(bemJson)) { bemJson.forEach((childBemJson) => { errors = errors.concat(validateBemJson(childBemJson, fileName)); }); } else if (bemJson instanceof Object) { Object.keys(bemJson).forEach((key) => { const childBemJson = bemJson[key]; errors = errors.concat(validateBemJson(childBemJson, fileName)); }); errors = errors.concat(validateBemJsonNode(bemJson, fileName)); // TODO } // TODO return errors; }
javascript
{ "resource": "" }
q42720
extractBemJsonNode
train
function extractBemJsonNode(bemJson) { let result = JSON.parse(JSON.stringify(bemJson)); Object.keys(result).forEach((key) => { result[key] = result[key].toString(); }); return JSON.stringify(result, null, 2); }
javascript
{ "resource": "" }
q42721
train
function(){ var copy = []; // Handle recursive loops if ( queue.running ) { queue.waiting = true; return; } // Mark queue as running, then search for queue.running = true; munit.each( queue.modules, function( assert, index ) { if ( ! queue.objects.length ) { return false; } else if ( ! munit.render.checkDepency( assert ) ) { return; } // Looking for specific key in queue object if ( munit.isString( assert.options.queue ) ) { munit.each( queue.objects, function( object, i ) { if ( object[ assert.options.queue ] ) { queue.modules[ index ] = null; queue.objects.splice( i, 1 ); assert.queue = object; assert.trigger(); return false; } }); } // Any queue will do else { queue.modules[ index ] = null; assert.queue = queue.objects.shift(); assert.trigger(); } }); // Clean out modules that completed (splicing causes iteration fails) queue.modules.forEach(function( assert ) { if ( assert !== null ) { copy.push( assert ); } }); queue.modules = copy; // Run again if check method was called during loop queue.running = false; if ( queue.waiting ) { queue.waiting = false; queue.check(); } }
javascript
{ "resource": "" }
q42722
recreate
train
function recreate(makeStream, options) { if (options === undefined && isObject(makeStream)) { options = makeStream; makeStream = options.makeStream; } options = options || {}; if (options.connect === undefined) { options.connect = true; } var connectedEvent = options.connectedEvent || 'open'; var stream = through(); stream.inverse = through(); stream.inverse.pause(); stream.write = function(chunk) { return stream.inverse.write(chunk); }; stream.connect = function() { stream.underlying = makeStream(); stream.inverse.pipe(stream.underlying, {end: false}); stream.underlying.on('data', function(chunk) { return stream.emit('data', chunk); }); stream.underlying.on(connectedEvent, function() { stream.backoff.reset(); stream.inverse.resume(); stream.emit('open'); stream.emit('underlying-open'); }); stream.underlying.on('end', function() { stream.inverse.pause(); if (!stream.preventBackoff) { stream.backoff.backoff(); } stream.emit('underlying-end'); }); stream.underlying.on('error', function(e) { stream.inverse.pause(); if (!stream.preventBackoff) { stream.backoff.backoff(); } stream.emit('underlying-error'); }); }; var origEnd = stream.end.bind(stream); stream.end = function() { stream.preventBackoff = true; stream.underlying.end(); return origEnd(); }; stream.backoff = options.backoff || backoff.exponential(options); stream.backoff.on('backoff', function(num, delay) { stream.emit('backoff-schedule', num, delay); }); stream.backoff.on('ready', function() { stream.connect(); stream.emit('backoff-ready'); }); stream.backoff.on('fail', function() { stream.emit('backoff-fail'); }); if (options.connect) { stream.connect(); } return stream; }
javascript
{ "resource": "" }
q42723
createServer
train
function createServer() { grunt.log.ok('Registered as a grunt-net server [' + host + ':' + port + '].'); dnode({ spawn: spawn }).listen(host, port); }
javascript
{ "resource": "" }
q42724
train
function (token) { var pp = new JavascriptPreprocessor(this.parser, this.compiler, this.actions, this.scope, this.state); if (token) { pp.code = this.get_code(this.code, token); } return pp; }
javascript
{ "resource": "" }
q42725
train
function (action) { if (action) { switch (action.type) { case "replace" : this.code = `${ this.code.substr(0, action.start) }${ action.value }${ this.code.substr(action.end) }`; return true; case "remove" : this.code = `${ this.code.substr(0, action.start) }${ this.code.substr(action.end) }`; return true; } } }
javascript
{ "resource": "" }
q42726
train
function (name, definition, is_return) { var pp = this.$new(), code = `PP.define("${ name }", ${ definition.toString() }, ${ is_return });`; pp.scope = this.scope; pp.process("[IN MEMORY]", code); }
javascript
{ "resource": "" }
q42727
train
function (code, tokens) { var actions = [], i = 0; this.code = code; for (; i < tokens.length; ++i) { actions[i] = this.actions.invoke(this, tokens[i]); } i = actions.length; while (i--) { this.action(actions[i]); } return this.code; }
javascript
{ "resource": "" }
q42728
train
function (code) { try { return this.parser.parse(code); } catch(e) { console.log("E", e); console.log(code); process.exit(); } }
javascript
{ "resource": "" }
q42729
callNew
train
function callNew(T, args) { return new (Function.prototype.bind.apply(T, [null].concat(args))); }
javascript
{ "resource": "" }
q42730
earley
train
function earley(tokens, grammar) { let states = Array.apply(null, Array(tokens.length + 1)).map(() => []); var i, j; let rulePairs = grammar.map((rule) => ({ name : rule.lhs.name, rule : rule, position: 0, origin : 0 })); [].push.apply(states[0], rulePairs); for (i = 0; i <= tokens.length; i += 1) { for (j = 0; j < states[i].length; j += 1) { predict(tokens, states, i, j, grammar); scan(tokens, states, i, j); complete(tokens, states, i, j); } } return swap(removeUnfinishedItems(states)); }
javascript
{ "resource": "" }
q42731
removeUnfinishedItems
train
function removeUnfinishedItems(states) { return states.map((state) => state.filter((earleyItem) => { return earleyItem.position >= earleyItem.rule.length; })); }
javascript
{ "resource": "" }
q42732
swap
train
function swap(states) { let newStates = Array.apply(null, Array(states.length)).map(() => []); states.forEach((state, i) => { state.forEach((earleyItem) => { newStates[earleyItem.origin].push(earleyItem); earleyItem.origin = i; }); }); return newStates; }
javascript
{ "resource": "" }
q42733
dfsHelper
train
function dfsHelper(states, root, state, depth, tokens) { var edges; // Base case: we finished the root rule if (state === root.origin && depth === root.rule.length) { return []; } // If the current production symbol is a terminal if (root.rule[depth] instanceof RegExp) { if (root.rule[depth].test(tokens[state])) { let subMatch = dfsHelper(states, root, state + 1, depth + 1, tokens); if (subMatch) { return [tokens[state]].concat(subMatch); } } return null; } else if (typeof root.rule[depth] === 'string') { if (root.rule[depth] === tokens[state]) { let subMatch = dfsHelper(states, root, state + 1, depth + 1, tokens); if (subMatch) { return [tokens[state]].concat(subMatch); } } return null; } // Otherwise, it must be a non-terminal edges = states[state] .filter((item) => item.rule.lhs === root.rule[depth]) .map((item) => { let subMatch = dfsHelper(states, root, item.origin, depth + 1, tokens); if (subMatch) { return [{ item : item.rule, children: dfsHelper(states, item, state, 0, tokens) }].concat(subMatch); } return null; }) .filter((list) => list); if (edges.length > 1) { let diffs = edges.filter( (tree) => JSON.stringify(tree) !== JSON.stringify(edges[0]) ); if (diffs.length > 0) { //console.log('Ambiguity\n' + JSON.stringify(edges, null, 2)); console.log('Ambiguous rules'); } } return edges[0]; }
javascript
{ "resource": "" }
q42734
remove
train
function remove(ddqBackendInstance, recordId, callback) { // Note, this is not what we want. // it does not handle the times when the // isProcessing flag is true. ddqBackendInstance.deleteData(recordId); ddqBackendInstance.checkAndEmitData(); callback(); }
javascript
{ "resource": "" }
q42735
requeue
train
function requeue(ddqBackendInstance, recordId, callback) { var record; record = ddqBackendInstance.getRecord(recordId); record.isProcessing = false; record.requeued = true; callback(); }
javascript
{ "resource": "" }
q42736
Command
train
function Command (name, cli, action) { if (!(this instanceof Command)) { return new Command(name, cli, action) } this.name = name this.cli = cli this.action = action }
javascript
{ "resource": "" }
q42737
sortedArray
train
function sortedArray(arr, comparator1, comparator2, comparator3) { var _ = {}; arr = arr || []; if (typeof arr._sortedArray === "object") { throw new Error("(sortedArray) Cannot extend array: Special key _sortedArray is already defined. Did you apply it twice?"); } arr._sortedArray = _; _.reversed = false; _.push = arr.push; arr.push = push; _.unshift = arr.unshift; _.splice = arr.splice; arr.splice = splice; arr.unshift = push; _.indexOf = arr.indexOf; arr.indexOf = indexOf; _.sort = arr.sort; arr.sort = sort; _.reverse = arr.reverse; arr.reverse = reverse; arr.sortedIndex = sortedIndex; if (arguments.length === 1) { arr.comparator = arr.comparator || defaultComparator; } else if (arguments.length === 2) { arr.comparator = comparator1; } else { arr.comparator = multipleComparators(slice.call(arguments, 1)); } if (arr.length > 0) { arr.sort(); } return arr; }
javascript
{ "resource": "" }
q42738
indexOf
train
function indexOf(element, fromIndex) { /* jshint validthis:true */ var arr = toArray(this), index; if (fromIndex) { arr = arr.slice(fromIndex); } index = binarySearch(arr, element, this.comparator); if (index < 0) { return -1; } else { return index; } }
javascript
{ "resource": "" }
q42739
reverse
train
function reverse() { /* jshint validthis:true */ var _ = this._sortedArray, reversed = _.reversed; if (reversed) { this.comparator = this.comparator.original; } else { this.comparator = getInversionOf(this.comparator); } _.reversed = !reversed; _.reverse.call(this); }
javascript
{ "resource": "" }
q42740
sortedIndex
train
function sortedIndex(element) { /* jshint validthis:true */ var index = binarySearch(toArray(this), element, this.comparator); if (index < 0) { // binarySearch decreases the negative index by one because otherwise the index 0 would stand for two results // @see https://github.com/darkskyapp/binary-search/issues/1 return Math.abs(index) - 1; } else { return index; } }
javascript
{ "resource": "" }
q42741
pushSingle
train
function pushSingle(arr, element) { var index = arr.sortedIndex(element), _ = arr._sortedArray; // original push and unshift are faster than splice if (index === 0) { _.unshift.call(arr, element); } else if (index === arr.length) { _.push.call(arr, element); } else { _.splice.call(arr, index, 0, element); } }
javascript
{ "resource": "" }
q42742
getInversionOf
train
function getInversionOf(comparator) { function inversion(a, b) { return -comparator(a, b); } inversion.original = comparator; return inversion; }
javascript
{ "resource": "" }
q42743
multipleComparators
train
function multipleComparators(comparators) { return function applyComparators(a, b) { var i, result; for (i = 0; i < comparators.length; i++) { result = comparators[i](a, b); if (result !== 0) { return result; } } return defaultComparator(a, b); }; }
javascript
{ "resource": "" }
q42744
train
function(inName, inValue) { this.attributes[inName] = inValue; if (this.hasNode()) { this.attributeToNode(inName, inValue); } this.invalidateTags(); }
javascript
{ "resource": "" }
q42745
train
function(inClass) { if (inClass && !this.hasClass(inClass)) { var c = this.getClassAttribute(); this.setClassAttribute(c + (c ? " " : "") + inClass); } }
javascript
{ "resource": "" }
q42746
train
function(inClass) { if (inClass && this.hasClass(inClass)) { var c = this.getClassAttribute(); c = (" " + c + " ").replace(" " + inClass + " ", " ").slice(1, -1); this.setClassAttribute(c); } }
javascript
{ "resource": "" }
q42747
train
function(inParentNode) { // clean up render flags and memoizations this.teardownRender(); // inParentNode can be a string id or a node reference var pn = enyo.dom.byId(inParentNode); if (pn == document.body) { this.setupBodyFitting(); } else if (this.fit) { this.addClass("enyo-fit enyo-clip"); } // generate our HTML pn.innerHTML = this.generateHtml(); // post-rendering tasks this.rendered(); // support method chaining return this; }
javascript
{ "resource": "" }
q42748
train
function(inBounds, inUnit) { var s = this.domStyles, unit = inUnit || "px"; var extents = ["width", "height", "left", "top", "right", "bottom"]; for (var i=0, b, e; e=extents[i]; i++) { b = inBounds[e]; if (b || b === 0) { s[e] = b + (!enyo.isString(b) ? unit : ''); } } this.domStylesChanged(); }
javascript
{ "resource": "" }
q42749
train
function(inName, inValue) { if (inValue === null || inValue === false || inValue === "") { this.node.removeAttribute(inName); } else { this.node.setAttribute(inName, inValue); } }
javascript
{ "resource": "" }
q42750
simpleGetStream
train
function simpleGetStream (opts) { var stream = through2() stream.req = simpleGet.call(this, opts, function callback (err, res) { stream.res = res if (err) return stream.emit('error', err) res.pipe(stream) }) return stream }
javascript
{ "resource": "" }
q42751
multiDimArrayIndex
train
function multiDimArrayIndex (dimensions, indices) { // Check that indices fit inside dimensions shape. for (var i = 0; i < dimensions.length; i++) { if (indices[i] > dimensions[i]) { throw new TypeError(error.outOfBoundIndex) } } var order = dimensions.length // Handle order 1 if (order === 1) return indices[0] //* index = i_n + i_(n-1) * d_n + i_(n-2) * d_n * d_(n-1) + ... + i_2 * d_n * d_(n-1) * ... * d_3 + i_1 * d_n * ... * d_2 var n = order - 1 var factor = dimensions[n] // d_n var index = indices[n] + factor * indices[n - 1] // i_n + i_(n-1) * d_n for (var j = 2; j < order; j++) { factor *= dimensions[n - j] index += factor * indices[n - j] } return index }
javascript
{ "resource": "" }
q42752
hasPositionByBoardSize
train
function hasPositionByBoardSize(boardSize, position) { return position && position.x >= 0 && position.y >= 0 && boardSize.y > position.y && boardSize.x > position.x; }
javascript
{ "resource": "" }
q42753
mapBoard
train
function mapBoard(board, func) { return board.map(function (col) { return col.map(function (p) { return func(p); }); }); }
javascript
{ "resource": "" }
q42754
getBoardWithPieces
train
function getBoardWithPieces(board, pieces) { return mapBoard(board, function (p) { var x = p.x, y = p.y; var piece = Position.getPositionFromPositions(pieces, p); return piece ? { x: x, y: y, isBlack: piece.isBlack } : { x: x, y: y }; }); }
javascript
{ "resource": "" }
q42755
getStartWhiteBlack
train
function getStartWhiteBlack(x, whiteY) { return [{ x: x, y: 0, isBlack: true }, { x: x, y: whiteY, isBlack: false }]; }
javascript
{ "resource": "" }
q42756
addStartPieces
train
function addStartPieces(x, whiteY, positions) { return x < 0 ? positions : addStartPieces(x - 1, whiteY, positions.concat(getStartWhiteBlack(x, whiteY))); }
javascript
{ "resource": "" }
q42757
getPositionFromBoard
train
function getPositionFromBoard(board, position) { try { return board[position.y][position.x]; } catch (e) { throw new Error('Error getting position'); } }
javascript
{ "resource": "" }
q42758
getAllNearPositions
train
function getAllNearPositions(position) { return [[-1, -1], [0, -1], [1, -1], [-1, 0], [1, 0], [-1, 1], [0, 1], [1, 1] // Below positions ].map(function (toAdd) { return { x: position.x + toAdd[0], y: position.y + toAdd[1] }; }); }
javascript
{ "resource": "" }
q42759
getNearPositions
train
function getNearPositions(board, position) { var nearPositions = _getNearPositions(getBoardSize(board), Position.getXAndY(position)); return getPositionsFromBoard(board, nearPositions); }
javascript
{ "resource": "" }
q42760
getEmptyNearPositions
train
function getEmptyNearPositions(board, position) { return getNearPositions(board, position).filter(function (p) { return Position.hasNoPiece(p); }); }
javascript
{ "resource": "" }
q42761
getNotEmptyNearPositions
train
function getNotEmptyNearPositions(board, position) { return getNearPositions(board, position).filter(function (p) { return Position.hasPiece(p); }); }
javascript
{ "resource": "" }
q42762
getJumpXY
train
function getJumpXY(from, toJump) { return { x: getJump(from.x, toJump.x), y: getJump(from.y, toJump.y) }; }
javascript
{ "resource": "" }
q42763
getBoardWhereCanIGo
train
function getBoardWhereCanIGo(board, from) { var positions = getPositionsWhereCanIGo(board, from); return mapBoard(board, function (position) { return Position.setICanGoHere(positions, position); }); }
javascript
{ "resource": "" }
q42764
getPiecesFromBoard
train
function getPiecesFromBoard(board) { var initialPieces = { white: [], black: [] }; return board.reduce(function (piecesRow, row) { return row.reduce(function (pieces, position) { if (Position.hasBlackPiece(position)) pieces.black = pieces.black.concat(position);else if (Position.hasWhitePiece(position)) pieces.white = pieces.white.concat(position); return pieces; }, piecesRow); }, initialPieces); }
javascript
{ "resource": "" }
q42765
train
function(sessionId) { if (sessionId) { if (sessionId.length < 24) { throw new CError('sid length undersized').log(); } if (sessionId.length > 128) { throw new CError('sid length exceeded').log(); } this._sid = sessionId; } }
javascript
{ "resource": "" }
q42766
getImageRaw
train
function getImageRaw(options, _onProgress = () => {}){ return new Promise((resolve, reject) => { var request = new XMLHttpRequest(); request.open('GET', options.url, true); request.responseType = options.responseType || 'blob'; function transferComplete(){ var result; switch (options.responseType){ case 'blob': result = new Blob([this.response], { type: options.mimeType || 'image/jpeg' }); resolve(result); break; case 'arraybuffer': result = this.response; resolve(result); break; default: result = this.response; resolve(result); break; } } var transferCanceled = reject; var transferFailed = reject; request.addEventListener('progress', _onProgress, false); request.addEventListener('load', transferComplete, false); request.addEventListener('error', transferFailed, false); request.addEventListener('abort', transferCanceled, false); request.send(null); }); }
javascript
{ "resource": "" }
q42767
JSONPRequest
train
function JSONPRequest(url, timeout = 3000){ var self = this; self.timeout = timeout; self.called = false; if (window.document) { var ts = Date.now(); self.scriptTag = window.document.createElement('script'); // url += '&callback=window.__jsonpHandler_' + ts; var _url = ''; if (url && url !== '') { _url = queryfy(url, { callback: `window.__jsonpHandler_${ts}` }); } self.scriptTag.src = _url; self.scriptTag.type = 'text/javascript'; self.scriptTag.async = true; self.prom = new Promise((resolve, reject) => { var functionName = `__jsonpHandler_${ts}`; window[functionName] = function(data){ self.called = true; resolve(data); self.scriptTag.parentElement.removeChild(self.scriptTag); delete window[functionName]; }; // reject after a timeout setTimeout(() => { if (!self.called){ reject('Timeout jsonp request ' + ts); self.scriptTag.parentElement.removeChild(self.scriptTag); delete window[functionName]; } }, self.timeout); }); // the append start the call window.document.getElementsByTagName('head')[0].appendChild(self.scriptTag); } }
javascript
{ "resource": "" }
q42768
copy
train
function copy(source, target) { for (var name in source) { if (source.hasOwnProperty(name)) { target[name] = source[name]; } } }
javascript
{ "resource": "" }
q42769
train
function(localPath, globalPath) { if (!(this instanceof HAControl)) { return new HAControl(localPath, globalPath); } this.localHa = true; this.globalHa = true; this.localPath = localPath; this.globalPath = globalPath; }
javascript
{ "resource": "" }
q42770
_keySourceHintFrom
train
function _keySourceHintFrom( method, source, environment ){ var hints = []; if( method ) hints.push( method ); if( source ) hints.push( source ); if( environment ) hints.push( "WHEN " + environment ); return hints.join(' '); }
javascript
{ "resource": "" }
q42771
isGoogCallExpression
train
function isGoogCallExpression(node, name) { const callee = node.callee; return callee && callee.type === 'MemberExpression' && callee.object.type === 'Identifier' && callee.object.name === 'goog' && callee.property.type === 'Identifier' && !callee.property.computed && callee.property.name === name; }
javascript
{ "resource": "" }
q42772
isGoogStatement
train
function isGoogStatement(node, name) { return node.expression && node.expression.type === 'CallExpression' && isGoogCallExpression(node.expression, name); }
javascript
{ "resource": "" }
q42773
train
function () { logger.info('Records sent to Tone Analyzer: ' + amaStats.processed_record_count); // these records could be fetched using other API calls logger.info('Records missing (no comment text available): ' + amaStats.missing_record_count); logger.info('Maximum processed comment thread depth: ' + amaStats.max_processed_level); if(amaStats.parser_warnings > 0) { // Potential issue with parser logic. If a non-zero value is reported, the base tree should be reviewed. logger.warn('Potential base tree parsing issues: ' + amaStats.parser_warnings); } logger.debug('AMA thread statistics: ' + util.inspect(amaStats.level_stats,3)); }
javascript
{ "resource": "" }
q42774
listFiles
train
function listFiles(dir, callback) { return new Promise((resolveThis, reject) => { walk.walk(dir, { followLinks: true }) .on('file', (root, stats, next) => { const destDir = relative(dir, root); const relativePath = destDir ? join(destDir, stats.name) : stats.name; resolve(relativePath).then(callback).then(next); }) .on('errors', reject) .on('end', resolveThis); }); }
javascript
{ "resource": "" }
q42775
symlinkOrCopySync
train
function symlinkOrCopySync(dir, target) { try { symlinkOrCopy.sync(dir, target); } catch (e) { if (existsSync(target)) { rimraf.sync(target); } symlinkOrCopy.sync(dir, target); } }
javascript
{ "resource": "" }
q42776
Tree
train
function Tree(source, parent, githubClient) { this.gh = githubClient; this.sha = source.sha; this.parent = parent; this.truncated = source.truncated; this.objects = _.cloneDeep(source.tree); this._source = source; }
javascript
{ "resource": "" }
q42777
task
train
function task() { // make sure the release task has been initialized init.apply(this, arguments); var name, desc, deps, cb; for (var i = 0; i < arguments.length; i++) { if (typeof arguments[i] === 'string') { if (name) { desc = arguments[i]; } else { name = arguments[i]; } } else if (typeof arguments[i] === 'function') { cb = taskCallback(arguments[i]); } else if (Array.isArray(arguments[i])) { deps = arguments[i]; } } if (rbot.env.usingGrunt) { if (name && desc) { return rbot.env.taskRunner.registerTask(name, desc, cb); } else if (name && deps) { return rbot.env.taskRunner.registerTask(name, deps); } throw new Error('Invalid grunt.registerTask() for: name = "' + name + '", desc = "' + desc + '", taskList = "' + deps + '", function = "' + cb + '"'); } else { if (name && deps && cb) { return rbot.env.taskRunner.task(name, deps, cb); } else if (name && cb) { return rbot.env.taskRunner.task(name, cb); } throw new Error('Invalid gulp.task() for: name = "' + name + '", deps = "' + deps + '", function = "' + cb + '"'); } }
javascript
{ "resource": "" }
q42778
taskCallback
train
function taskCallback(fn) { return fn.length ? taskAsyncCb : taskSyncCb; function taskAsyncCb(cb) { return taskCb(this || {}, arguments, fn, cb, true); } function taskSyncCb() { return taskCb(this || {}, arguments, fn, null, false); } function taskCb(cxt, args, fn, done, isAsync) { cxt.done = isAsync && typeof done === 'function' ? done : isAsync && typeof cxt.async === 'function' ? cxt .async() : taskSyncDone; if (!rbot.env.usingGrunt) { // set options using either a configuration value or the passed // default value cxt.options = function setOptions(defOpts) { Object.keys(defOpts).forEach(function it(k) { this.options[k] = rbot.config(k) || defOpts[k]; }.bind(this)); return this.options; }.bind(cxt); } var fna = args; if (cxt.done !== done && cxt.done !== taskSyncDone) { // ensure that the done function still gets passed as the 1st // argument even when the task runner doesn't pass it fna = args ? Array.prototype.slice.call(args, 0) : []; fna.unshift(cxt.done); } return fn.apply(cxt, fna); } function taskSyncDone(success) { rbot.log.verbose('Synchronous task ' + (success ? 'completed' : 'failed')); } }
javascript
{ "resource": "" }
q42779
processTemplate
train
function processTemplate(val, data) { if (rbot.env.usingGrunt) { return rbot.env.taskRunner.template.process(val, data); } // TODO : add gulp template processing if (!val) { return val; } return val; }
javascript
{ "resource": "" }
q42780
train
function (emits, message, daemonPid) { var monitor = new Monitor(message, options, daemonPid, shutdown, child, function () { // emit events before starting child Object.keys(emits).forEach(function (name) { // skip the process event until the child spawns if (name === 'process') return; monitor.emit.apply(monitor, [name].concat( emits[name] )); }); // spawn child when monitor is ready child.spawn(); // start pumping streams to monitor child.pump(monitor); }); // once the child has started emit the process event child.once('start', function () { monitor.pid.process = child.pid; monitor.emit.apply(monitor, ['process'].concat( emits.process )); }); // relay stop and restart to process event on monitor child.on('stop', function () { monitor.pid.process = null; // Do not emit if the deamon is in restart mode if (daemonInRestart) return; monitor.emit('process', 'stop'); }); child.on('restart', function () { monitor.pid.process = child.pid; monitor.emit('process', 'restart'); }); }
javascript
{ "resource": "" }
q42781
train
function(other) { if (other.getSessionToken()) { this._sessionToken = other.getSessionToken(); } Parse.User.__super__._mergeFromObject.call(this, other); }
javascript
{ "resource": "" }
q42782
train
function(attrs) { if (attrs.sessionToken) { this._sessionToken = attrs.sessionToken; delete attrs.sessionToken; } Parse.User.__super__._mergeMagicFields.call(this, attrs); }
javascript
{ "resource": "" }
q42783
train
function(provider, options) { var authType; if (_.isString(provider)) { authType = provider; provider = Parse.User._authProviders[provider]; } else { authType = provider.getAuthType(); } var newOptions = _.clone(options); var self = this; newOptions.authData = null; newOptions.success = function(model) { self._synchronizeAuthData(provider); if (options.success) { options.success.apply(this, arguments); } }; return this._linkWith(provider, newOptions); }
javascript
{ "resource": "" }
q42784
train
function(email, options) { options = options || {}; var request = Parse._request({ route: "requestPasswordReset", method: "POST", useMasterKey: options.useMasterKey, data: { email: email } }); return request._thenRunCallbacks(options); }
javascript
{ "resource": "" }
q42785
train
function() { if (Parse.User._currentUser) { return Parse.User._currentUser; } if (Parse.User._currentUserMatchesDisk) { return Parse.User._currentUser; } // Load the user from local storage. Parse.User._currentUserMatchesDisk = true; var userData = Parse.localStorage.getItem(Parse._getParsePath( Parse.User._CURRENT_USER_KEY)); if (!userData) { return null; } Parse.User._currentUser = Parse.Object._create("_User"); Parse.User._currentUser._isCurrentUser = true; var json = JSON.parse(userData); Parse.User._currentUser.id = json._id; delete json._id; Parse.User._currentUser._sessionToken = json._sessionToken; delete json._sessionToken; Parse.User._currentUser._finishFetch(json); Parse.User._currentUser._synchronizeAllAuthData(); Parse.User._currentUser._refreshCache(); Parse.User._currentUser._opSetQueue = [{}]; return Parse.User._currentUser; }
javascript
{ "resource": "" }
q42786
train
function(){ spy.history = []; spy.args = []; spy.count = 0; spy.scope = null; spy.trace = null; return spy; }
javascript
{ "resource": "" }
q42787
train
function(){ if ( spy.wrapped ) { spy._module[ spy._method ] = spy.original; spy.wrapped = false; } return spy; }
javascript
{ "resource": "" }
q42788
SpyCall
train
function SpyCall( scope, args, spy ) { var self = this; if ( ! ( self instanceof SpyCall ) ) { return new SpyCall( args ); } self.scope = scope; self.args = args; self.time = new Date(); self.order = spy.assert._spyOrder++; self.overall = Spy.overall++; self.trace = ( new Error( "" ) ).stack; }
javascript
{ "resource": "" }
q42789
translate
train
function translate(tx) { var ty = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; return { a: 1, c: 0, e: tx, b: 0, d: 1, f: ty }; }
javascript
{ "resource": "" }
q42790
log
train
function log(msg) { process.stdout.write(time + ' '); console.log(colors.log(msg)); }
javascript
{ "resource": "" }
q42791
mixInTo
train
function mixInTo(target) { var descriptor; for (var key in this) { if ((descriptor = Object.getOwnPropertyDescriptor(this, key))) { Object.defineProperty(target, key, descriptor); } } return target; }
javascript
{ "resource": "" }
q42792
mixIn
train
function mixIn(source) { var descriptor; for (var key in source) { if ((descriptor = Object.getOwnPropertyDescriptor(source, key))) { Object.defineProperty(this, key, descriptor); } } return this; }
javascript
{ "resource": "" }
q42793
cleanObject
train
function cleanObject(obj) { if (obj instanceof Object) { Object.keys(obj).forEach((key) => (obj[key] == null) && delete obj[key]); } return obj; }
javascript
{ "resource": "" }
q42794
getDockerfileContext
train
function getDockerfileContext(context) { const fs = require('fs'); let files = []; let dockerfile = exports.resolveDockerfile(context); let file = fs.readFileSync(dockerfile, {encoding: 'utf8'}); for (let line of file.split('\n')) { if (line.match(/^\s*(ADD|COPY).*$/)) { let entries = line.split(' ') .splice(1) .map(val => val.trim()) .filter(val => val !== '') .filter(val => !val.startsWith('http')); if (entries[0].startsWith('--chown')) { entries = entries.splice(1); } // Array mode if (line.indexOf('[') !== -1 && line.indexOf(']') !== -1) { let args = JSON.parse(entries.join(' ')); args.splice(-1); files = args } // Default mode else { entries.splice(-1); files = entries; } } } let resolvedFiles = []; for (let file of files) { resolvedFiles = resolvedFiles.concat(glob.sync(path.join(path.dirname(context), file))); } return { context, src: ['Dockerfile', ...resolvedFiles] }; }
javascript
{ "resource": "" }
q42795
tagOutput
train
function tagOutput(descriptor, innerDescriptor, name) { var out = '<' + name + innerDescriptor.attributes; if (innerDescriptor.style) out += ' style="' + innerDescriptor.style + '"'; if (innerDescriptor.classes) out += ' class="' + innerDescriptor.classes + '"'; if (innerDescriptor.children) descriptor.children += out + '>' + innerDescriptor.children + '</' + name + '>'; else if (openTags.test(name)) descriptor.children += out + '>'; else if (strictTags.test(name)) descriptor.children += out + '></' + name + '>'; else descriptor.children += out + '/>'; }
javascript
{ "resource": "" }
q42796
train
function(width, height){ var canvas = document.createElement("canvas"); canvas.width = width; canvas.height = height; var context = canvas.getContext("2d"); var imageData = context.getImageData(0, 0, width, height); var buffer = new ArrayBuffer(width*height*4); var buffer8 = new Uint8ClampedArray(buffer); var buffer32 = new Uint32Array(buffer); return { canvas: canvas, context: context, width: width, height: height, imageData: imageData, buffer8: buffer8, buffer32: buffer32}; }
javascript
{ "resource": "" }
q42797
FileEmitter
train
function FileEmitter(folder, opt_options) { if (!(this instanceof FileEmitter)) { return new FileEmitter(folder, opt_options); } events.EventEmitter.call(this); opt_options = opt_options || {}; this.root = path.resolve(process.cwd(), folder); // flags & options this.buffer = opt_options.buffer || false; this.incremental = opt_options.incremental || false; this.followSymLinks = opt_options.followSymLinks || false; this.recursive = opt_options.recursive === false ? false : true; this.maxBufferSize = opt_options.maxBufferSize || 10485760; // 10 MiB // file constructor this.File = opt_options.File || File; // filters this.include = opt_options.include || false; this.exclude = opt_options.exclude || false; this._minimatchOptions = opt_options.minimatchOptions || {matchBase: true}; // read, stat & readdir queues this._queues = [[], [], ['']]; // max number of open file descriptors (used for incremental EMFILE back-off) this._maxFDs = opt_options.maxFDs || Infinity; // UNDOCUMENTED OPTION // currently open file descriptors this._numFDs = 0; // incremental lock this._locked = false; this._hadError = false; var self = this; if (opt_options.autorun !== false) { setImmediate(function() { self.run(); }); } }
javascript
{ "resource": "" }
q42798
reportCoverage
train
function reportCoverage(cov) { // Stats print('\n [bold]{Test Coverage}\n'); var sep = ' +------------------------------------------+----------+------+------+--------+', lastSep = ' +----------+------+------+--------+'; result = sep+'\n'; result += ' | filename | coverage | LOC | SLOC | missed |\n'; result += sep+'\n'; for (var name in cov) { var file = cov[name]; if (Array.isArray(file)) { result += ' | ' + rpad(name, 40); result += ' | ' + lpad(file.coverage.toFixed(2), 8); result += ' | ' + lpad(file.LOC, 4); result += ' | ' + lpad(file.SLOC, 4); result += ' | ' + lpad(file.totalMisses, 6); result += ' |\n'; } } result += sep+'\n'; result += ' ' + rpad('', 40); result += ' | ' + lpad(cov.coverage.toFixed(2), 8); result += ' | ' + lpad(cov.LOC, 4); result += ' | ' + lpad(cov.SLOC, 4); result += ' | ' + lpad(cov.totalMisses, 6); result += ' |\n'; result += lastSep; console.log(result); for (var name in cov) { if (name.match(file_matcher)) { var file = cov[name]; var annotated = ''; annotated += colorize('\n [bold]{' + name + '}:'); annotated += colorize(file.source); annotated += '\n'; fs.writeFileSync('annotated/'+name, annotated); } } }
javascript
{ "resource": "" }
q42799
populateCoverage
train
function populateCoverage(cov) { cov.LOC = cov.SLOC = cov.totalFiles = cov.totalHits = cov.totalMisses = cov.coverage = 0; for (var name in cov) { var file = cov[name]; if (Array.isArray(file)) { // Stats ++cov.totalFiles; cov.totalHits += file.totalHits = coverage(file, true); cov.totalMisses += file.totalMisses = coverage(file, false); file.totalLines = file.totalHits + file.totalMisses; cov.SLOC += file.SLOC = file.totalLines; if (!file.source) file.source = []; cov.LOC += file.LOC = file.source.length; file.coverage = (file.totalHits / file.totalLines) * 100; // Source var width = file.source.length.toString().length; file.source = file.source.map(function(line, i){ ++i; var hits = file[i] === 0 ? 0 : (file[i] || ' '); if (hits === 0) { hits = '\x1b[31m' + hits + '\x1b[0m'; line = '\x1b[41m' + line + '\x1b[0m'; } else { hits = '\x1b[32m' + hits + '\x1b[0m'; } return '\n ' + lpad(i, width) + ' | ' + hits + ' | ' + line; }).join(''); } } cov.coverage = (cov.totalHits / cov.SLOC) * 100; }
javascript
{ "resource": "" }