_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
27
233k
language
stringclasses
1 value
meta_information
dict
q14400
updateExistingItems
train
function updateExistingItems(groupUi) { let itemUi = groupUi.firstElementChild while (itemUi) {
javascript
{ "resource": "" }
q14401
addMissingItems
train
function addMissingItems(groupUi, options) { let nextItemUi = groupUi.firstElementChild let nextOption = options.firstElementChild while (nextOption) { if (!nextItemUi || nextItemUi._option !== nextOption) { const newItemUi = document.createElement('szn-') newItemUi._option = nextOptio...
javascript
{ "resource": "" }
q14402
_collectURLs
train
function _collectURLs ( token ) { var elem, isArrayElem; if ( Array.isArray( token ) ) { for ( var i = 0; i < token.length; i++ ) { elem = token[ i ];
javascript
{ "resource": "" }
q14403
train
function ( mask ) { if ( mask && ( mask instanceof RegExp ) !== true ) { throw { type: 'getURLs', message: 'First argument must be RegExp' }; } return urls.map( function ( value ) {
javascript
{ "resource": "" }
q14404
train
function ( from_value, to_value ) { var type; if ( from_value instanceof RegExp ) { type = 'RegExp'; } else if ( typeof from_value === 'string' ) { type = 'String'; } else { throw { type: 'changeURLContent', message: 'First argument must be RegE...
javascript
{ "resource": "" }
q14405
Blog
train
function Blog(loader, options) { this.slugs = {}; this.ids = {}; this.posts = []; this.length = 0; options = options || {}; if (typeof loader === 'string') { loader = new FileSystemLoader(loader, options); } else if (Array.isArray(loader)) { loader = new ArrayLoader(loader); ...
javascript
{ "resource": "" }
q14406
train
function( offset ) { // Saved the children count and text length beforehand. var parent = this.$.parentNode, count = parent.childNodes.length, length = this.getLength(); var doc = this.getDocument(); var retval = new CKEDITOR.dom.text( this.$.splitText( offset ), doc ); if ( parent.childNodes.length ...
javascript
{ "resource": "" }
q14407
train
function( indexA, indexB ) { // We need the following check due to a Firefox bug // https://bugzilla.mozilla.org/show_bug.cgi?id=458886 if ( typeof indexB != 'number' )
javascript
{ "resource": "" }
q14408
setTypeValueFromInstance
train
function setTypeValueFromInstance(node) { var val = node.instance; if(val === undefined) { node.type = "undefined"; node.value = "undefined"; } else if(val === null) { node.type = "null"; node.value = "null"; } else { var valType = typeof val; if(valType === "boole...
javascript
{ "resource": "" }
q14409
setInstanceFromTypeValue
train
function setInstanceFromTypeValue(node) { if(node.type == "undefined") { node.instance = undefined; } else if(node.type === "boolean") { node.instance = Boolean(node.value); } else if (node.type === "number") { node.instance = Number(node.value); } else if (node.type === "st...
javascript
{ "resource": "" }
q14410
ErroneousError
train
function ErroneousError(e, additional) { additional = additional || {}; this.line = e.lineno || e.lineNumber || additional.lineno; this.file = e.filename || e.fileName || additional.filename; this.msg = e.message || additional.message; this.time = e.timestamp || additional.timestamp || Date.now(); ...
javascript
{ "resource": "" }
q14411
_replaceMacros
train
function _replaceMacros(s, macros, obj) { var regex = null; for (var i = 0; i < macros.length; i++) { var macro = macros[i];
javascript
{ "resource": "" }
q14412
series
train
async function series(resolvers){ // buffer const results = []; // run resolvers in series for (const r of resolvers){
javascript
{ "resource": "" }
q14413
train
function (componentDescription) { var i = components.length, app; // Old-school declaration // > franky.Component.extend({ // id: 'hello', // init: function () { // console.log('hello'); ...
javascript
{ "resource": "" }
q14414
getPRsForRepo
train
function getPRsForRepo(repo) { print(['Fetching PRs for ', clc.yellow.bold(`${repo.owner.login}/${repo.name}`)], debug); return new Promise((resolve, reject) => { github.pullRequests.getAll({ user: repo.owner.login, repo: repo.name, state: 'open' }, (err, prs) => {
javascript
{ "resource": "" }
q14415
populateLabelsForPR
train
function populateLabelsForPR(pr) { print(['Get labels for PR ', clc.yellow.bold(`${pr.head.user.login}/${pr.head.repo.name}#${pr.number}`)], debug); return new Promise((resolve) => { github.issues.getIssueLabels({ user: pr.base.user.login, repo: pr.base.repo.name, number: pr.number }, func...
javascript
{ "resource": "" }
q14416
getLabels
train
function getLabels(prs) { return Promise.all(prs.reduce((flattenedPRs, pr)
javascript
{ "resource": "" }
q14417
analyzePatch
train
function analyzePatch(patch) { const patchLines = patch.split('\n').reduce((reducedPatch, currentLine) => { if (currentLine.match(/^[-+]/)) { return reducedPatch.concat(currentLine.replace(/^[-+]+\s*/, '')); }
javascript
{ "resource": "" }
q14418
extractDiffData
train
function extractDiffData(diff) { print(['Extract diff for ', clc.yellow.bold(`${diff.user}/${diff.repo}#${diff.number}`), clc.white.italic(` (${diff.title})`)], debug); return { user: diff.user, repo: diff.repo, title: diff.title, number: diff.number, link: diff.link, createdAt: diff.created...
javascript
{ "resource": "" }
q14419
getDiffForPR
train
function getDiffForPR(pr) { print(['Get diff for PR ', clc.yellow.bold(`${pr.head.user.login}/${pr.head.repo.name}#${pr.number}`)], debug); return new Promise((resolve) => { github.repos.compareCommits({ user: pr.head.user.login, repo: pr.head.repo.name, head: pr.head.ref, base: pr.base....
javascript
{ "resource": "" }
q14420
getDiffs
train
function getDiffs(prs) { print('Fetching diffs', debug); return Promise.all(prs.reduce((flattenedPRs, pr)
javascript
{ "resource": "" }
q14421
getOpenPRs
train
function getOpenPRs(auth, repo, debugEnabled) { setDebugMode(debugEnabled); return authenticate(auth) .then(function () { return getPRsForRepo(repo)
javascript
{ "resource": "" }
q14422
DoubleLast
train
function DoubleLast(input, letters) { var last = LastChar(input); if (!letters || ~letters.indexOf(last)) {
javascript
{ "resource": "" }
q14423
train
function(err, data, response) { // call the 'response' callback, if provided using 'node' style callback pattern if (options.complete) { options.complete.call(model, err, data, response, options); }
javascript
{ "resource": "" }
q14424
handleMongoWriteConcernError
train
function handleMongoWriteConcernError(batch, bulkResult, ordered, err, callback) { mergeBatchResults(ordered, batch, bulkResult, null, err.result); const wrappedWriteConcernError = new WriteConcernError({ errmsg: err.result.writeConcernError.errmsg, code: err.result.writeConcernError.result });
javascript
{ "resource": "" }
q14425
recordCursor
train
function recordCursor(records, id) { var record; id = coerceId(id); for (var i = 0, len = records.length; i
javascript
{ "resource": "" }
q14426
train
function (overlayName, modelName) { var key = (overlayName || BASE_OVERLAY) + '#' + modelName; if (!this.instances[key]) { this.instances[key] = DevFixturesFixtures.create({
javascript
{ "resource": "" }
q14427
Router
train
function Router(HandleConstructor) { if (!(this instanceof Router)) return new Router(HandleConstructor); this.Handle = DefaultHandle; this.router
javascript
{ "resource": "" }
q14428
done
train
function done(err) { if (err) return handle.error(err); // Evaluate all the attach methods for (const attachMethod of self.attachMethods) { attachMethod.call(handle); } // No match found, send 404 if (match.handler === null) { err = new Error('Not Found');
javascript
{ "resource": "" }
q14429
vsHash
train
function vsHash(text) { let codes = []; let pos = 0; let partPos = 0; for (let i = 0; i < text.length; i++) { if (!codes[pos]) codes[pos]=[]; let code = decodeCharCode2Int36(text.charCodeAt(i)); if (code !== null) { codes[pos][partPos] = code; partPos += 1...
javascript
{ "resource": "" }
q14430
getResult
train
function getResult(matcherName, pass, ...messageWithPlaceholderValues) { const formattedMessage = format.apply(this, messageWithPlaceholderValues); messages[matcherName] = formattedMessage; // Save {not} message
javascript
{ "resource": "" }
q14431
createPromiseWith
train
function createPromiseWith(actual, expected, verb) { assertPromise(actual); const success = jasmine.createSpy('Promise success callback'); const failure = jasmine.createSpy('Promise failure callback'); actual.then(success, failure); createScope().$digest(); const spy = verb === 'resolved' ? success : fail...
javascript
{ "resource": "" }
q14432
Bezierizer
train
function Bezierizer (container) { this.$el = $(container); this.$el.append($(HTML_TEMPLATE)); this._$canvasContainer = this.$el.find('.bezierizer-canvas-container'); this._$canvas = this._$canvasContainer.find('canvas'); this._$handleContainer = this.$el.find('.bezierizer-handle-container'); this._$handles...
javascript
{ "resource": "" }
q14433
train
function() { if (cache.styles) { return cache.styles; } cache.styles = {}; cache.styles[CONSTS.LOG] = chalk.white; cache.styles[CONSTS.INFO] = chalk.cyan; cache.styles[CONSTS.SUCCESS] =
javascript
{ "resource": "" }
q14434
train
function(type) { var t = '[' + type.toUpperCase()
javascript
{ "resource": "" }
q14435
train
function(type, messages) { if (type !== CONSTS.LOG) { messages.unshift(tag(type)); }
javascript
{ "resource": "" }
q14436
detectErrors
train
function detectErrors (err, responseSpec, next) { var callbackErr; if (err) { callbackErr = err; } else { var status = responseSpec.statusCode; if (status == 403) { callbackErr = new Charon.RequestForbiddenError(responseSpec); } else if (status =...
javascript
{ "resource": "" }
q14437
parseResource
train
function parseResource (err, responseSpec, next) { var resource = responseSpec ? responseSpec.body
javascript
{ "resource": "" }
q14438
train
function (propertyName) { var value = this.client[propertyName]; if (! _.isUndefined(this[propertyName])) { // pass, defer to resource manager prototype properties } else if (_.isFunction(value)) { // copy functions (including the error ctors) by direct reference this[pro...
javascript
{ "resource": "" }
q14439
ls
train
function ls(uri, callback) { if (!uri) { callback(new Error('uri is required')) } util.getAll(uri, function(err, val) { var res = {} for (var i=0; i<val.length; i++) { if (val[i].predicate.uri === 'http://www.w3.org/ns/ldp#contains') { if (! res[val[i].object.uri]) res[val[i].object.uri]...
javascript
{ "resource": "" }
q14440
train
function (name) { name = name || BASE_OVERLAY; if (!this.instances[name]) { this.instances[name] =
javascript
{ "resource": "" }
q14441
train
function(json) { var decoder = Parse.Op._opDecoderMap[json.__op]; if (decoder) { return
javascript
{ "resource": "" }
q14442
train
function() { var self = this; return _.map(this.relationsToRemove, function(objectId) {
javascript
{ "resource": "" }
q14443
train
function() { var adds = null; var removes = null; var self = this; var idToPointer = function(id) { return { __type: 'Pointer', className: self._targetClassName, objectId: id }; }; var pointers = null; if (this.relationsToAdd.length > 0...
javascript
{ "resource": "" }
q14444
blobToString
train
function blobToString (blob) { return blobUtil .blobToArrayBuffer(blob) .then(function (buffer) {
javascript
{ "resource": "" }
q14445
remakeBody
train
function remakeBody (body, bodyType) { return blobUtil .base64StringToBlob(body) .then(function (blob) { switch (bodyType) { case BodyTypes.ARRAY_BUFFER: return blobUtil.blobToArrayBuffer(blob) case BodyTypes.BLOB: return blob case BodyTypes.FORM_DATA:
javascript
{ "resource": "" }
q14446
serialiseRequest
train
function serialiseRequest (request, toObject) { if (!(request instanceof Request)) { throw new Error('Expecting request to be instance of Request') } var headers = [] var headerNames = request.headers.keys() for (var i = 0; i < headerNames.length; i++) { var headerName = headerNames[i] headers[he...
javascript
{ "resource": "" }
q14447
deserialiseRequest
train
function deserialiseRequest (serialised) { var options var url if (typeof serialised === 'string') { options = JSON.parse(serialised) url = options.url } else if (typeof serialised === 'object') { options = serialised url = options.url } else { throw new Error('Expecting serialised reques...
javascript
{ "resource": "" }
q14448
scrapePage
train
function scrapePage(cb, pages, links) { links = links || []; pages = pages || basePages.slice(); var url = pages.pop(); jsdom.env({ url: url, scripts: ['http://code.jquery.com/jquery.js'], done: function(err, window){ if (err) return cb(err);
javascript
{ "resource": "" }
q14449
_getLinks
train
function _getLinks (window, links) { var $ = window.$; $('a.lede__link').each(function(){
javascript
{ "resource": "" }
q14450
generateRandomClientId
train
function generateRandomClientId() { var length = 22; var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; var result = ''; for (var i = length; i
javascript
{ "resource": "" }
q14451
connectBrowser
train
function connectBrowser (subscriptions, backlog, host, done_cb, secure) { // Associate the right port var websocket_uri; if(secure == true) { websocket_uri ='wss://' + host + ':1885/mqtt'; } else { websocket_uri ='ws://' + host + ':1884/mqtt'; } // Create client var cli...
javascript
{ "resource": "" }
q14452
subscribeBrowser
train
function subscribeBrowser (client, subscriptions, backlog, channel, callback, done_callback) { if ( addToBacklog(client, backlog, subscribeBrowser, [client, subscriptions, backlog, channel, callback, done_callback]) ) return; if (subscriptions[channel]===undefined) { subscriptions[channel] = [callback];...
javascript
{ "resource": "" }
q14453
train
function(client, subscriptions, backlog, channel, callback, done_callback) { if ( addToBacklog(client, backlog, unsubscribeBrowser, [client, subscriptions, backlog, channel, callback, done_callback]) ) return; if (subscriptions[channel]===undefined) return; subscriptions[channel].splice(subscription...
javascript
{ "resource": "" }
q14454
train
function (client, backlog, channel, message) { if ( addToBacklog(client, backlog, publishBrowser, [client, backlog, channel, message]) ) return;
javascript
{ "resource": "" }
q14455
findCallbacks
train
function findCallbacks (subscriptions, channel) { // First try to see if a callback for the exact channel exists if(Object.keys(subscriptions).indexOf(channel)!==-1) return subscriptions[channel];
javascript
{ "resource": "" }
q14456
matchesWildcard
train
function matchesWildcard (subscriptions, channel) { var i; var subs = Object.keys(subscriptions); for (i=0; i < subs.length; i++) {
javascript
{ "resource": "" }
q14457
addToBacklog
train
function addToBacklog (client, backlog, method, parameters) { if (!client.isConnected() ) { backlog.push({ op : method,
javascript
{ "resource": "" }
q14458
printParsableCode
train
function printParsableCode(snippets) { // prints all lines, some of which were fixed to make
javascript
{ "resource": "" }
q14459
configure
train
function configure(cacheType, conf) { // Check for custom logging functions on cache (debug) if (conf && conf.logger) { logger_1.configureLogger(conf.logger);
javascript
{ "resource": "" }
q14460
Tasks
train
function Tasks() { this.tasks = []; this.add = function(task) { var commit = grunt.config.get('releasebot.commit'); if (commit.skipTaskCheck(task)) { grunt.log.writeln('Skipping "' + task + '" task'); return false;
javascript
{ "resource": "" }
q14461
Args
train
function Args() { if (argv._.length >= 1) { try { // Attempt to parse 1st argument as JSON string _.extend(this, JSON.parse(argv._[0]));
javascript
{ "resource": "" }
q14462
getLastResult
train
function getLastResult() { if (argv._.length >= 2) { try { return JSON.parse(argv._[1]); } catch
javascript
{ "resource": "" }
q14463
EStoreScraper
train
function EStoreScraper() { _.defaults(this, { logger: new logging.Logger(), cookieJar: new CookieJar(), maxConcurrency: 10, startPage: '', agent: new http.Agent()
javascript
{ "resource": "" }
q14464
closestNumber
train
function closestNumber(arr, num) { return arr.reduce((prev, curr) => (Math.abs(curr -
javascript
{ "resource": "" }
q14465
train
function(source, type) { var out = null; switch(type) { case Augmented.Utility.TransformerType.xString: if (typeof source === 'object') { out = JSON.stringify(source); } else { out = String(source); } break; case Augment...
javascript
{ "resource": "" }
q14466
train
function(source) { if (source === null) { return Augmented.Utility.TransformerType.xNull; } else if (typeof source === 'string') { return Augmented.Utility.TransformerType.xString; } else if (typeof source === 'number') { return Augmented.Utility.TransformerType.xNu...
javascript
{ "resource": "" }
q14467
train
function(type, level) { if (type === Augmented.Logger.Type.console) { return new consoleLogger(level); } else if (type === Augmented.Logger.Type.colorConsole) { return new colorConsoleLogger(level);
javascript
{ "resource": "" }
q14468
train
function(username, password) { var c = null; Augmented.ajax({ url: this.uri, method: "GET", user: username, password: password, success: function(data, status) { var p = new principal({ fullName: data.fullName, id:...
javascript
{ "resource": "" }
q14469
train
function(clientType) { if (clientType === Augmented.Security.ClientType.OAUTH2) { return new Augmented.Security.Client.OAUTH2Client();
javascript
{ "resource": "" }
q14470
train
function(message) { var key = ""; if (message) { var x = message.level && (key += message.level, message.kind && (key += this.delimiter + message.kind, message.rule && (key +=
javascript
{ "resource": "" }
q14471
train
function() { var myValidator; if (myValidator === undefined) { myValidator = new Validator(); } /** * Returns if the framework supports validation * @method supportsValidation * @returns {boolean} Returns true if the framework supports va...
javascript
{ "resource": "" }
q14472
train
function() { if (this.supportsValidation() && Augmented.ValidationFramework.supportsValidation()) { // validate from Validator this.validationMessages = Augmented.ValidationFramework.validate(this.toJSON(), this.schema);
javascript
{ "resource": "" }
q14473
train
function() { const messages = []; if (this.validationMessages && this.validationMessages.errors) { const l = this.validationMessages.errors.length; var i = 0; for (i = 0;
javascript
{ "resource": "" }
q14474
train
function(method, model, options) { if (!options) { options = {}; } if (this.crossOrigin === true) { options.crossDomain = true; } if (!options.xhrFields) { options.xhrFields = { withCredentials: true ...
javascript
{ "resource": "" }
q14475
train
function() { if (this.supportsValidation() && Augmented.ValidationFramework.supportsValidation()) { // validate from Validator var messages = []; this.validationMessages.messages = messages; this.validationMessages.valid = true; var a = ...
javascript
{ "resource": "" }
q14476
train
function(key) { if (key) { var data = this.toJSON(); if (data) { var
javascript
{ "resource": "" }
q14477
train
function(options) { options = (options) ? options : {}; var data = (options.data || {}); var p = this.paginationConfiguration; var d = {}; d[p.currentPageParam] = this.currentPage; d[p.pageSizeParam] = this.pageSize; options.data = d;
javascript
{ "resource": "" }
q14478
train
function(apiType, data) { var arg = (data) ? data : {}; var collection = null; if (!apiType) { apiType = paginationAPIType.github; } if (apiType === paginationAPIType.github) { collection = new paginatedCollection(arg); ...
javascript
{ "resource": "" }
q14479
train
function(permission, negative) { if (!negative) { negative = false; } if (permission !== null && !Array.isArray(permission)) {
javascript
{ "resource": "" }
q14480
train
function(permission, negative) { if (!negative) { negative = false; } if (permission !== null && !Array.isArray(permission)) {
javascript
{ "resource": "" }
q14481
train
function(permissions, negative) { if (!negative) { negative = false; } if (permissions !== null && Array.isArray(permissions)) { if (negative) { this.permissions.exclude =
javascript
{ "resource": "" }
q14482
train
function(match, negative) { if (!negative) { negative = false; } var p =
javascript
{ "resource": "" }
q14483
mix
train
function mix (r, s, or, cl) { if (!s || !r) { return r; } var i = 0, c, len; or = or || arguments.length === 2; if (cl && (len = cl.length)) { for (; i < len; i++) { c = cl[i]; if ((c in s) && (or || !(c in
javascript
{ "resource": "" }
q14484
pyre
train
function pyre(pattern, namedCaptures) { pattern = String(pattern || '').trim(); // populate namedCaptures array and removed named captures from the `pattern` namedCaptures = namedCaptures == undefined ? [] : namedCaptures; var numGroups = 0; pattern = replaceCaptureGroups(pattern, function (group) { if (...
javascript
{ "resource": "" }
q14485
unwrapAst
train
function unwrapAst (ast, prefix, suffix) { let fake_code = `${prefix}\nlet ${LONG_AND_WEIRED_STRING}\n${suffix}` let fake_ast = babylon.parse(fake_code, { sourceType: 'module' }) let selected_node let selected_index traverse(fake_ast, { enter: function (node, parent) { // removes the loc info...
javascript
{ "resource": "" }
q14486
train
function(datasetId) { if (syncSubscribers && datasetId && syncSubscribers[datasetId])
javascript
{ "resource": "" }
q14487
create_message
train
function create_message(req, data) { debug.assert(data).is('object'); if(!is.uuid(data.$id)) {
javascript
{ "resource": "" }
q14488
hookStdout
train
function hookStdout(callback) { process.stdout._oWrite = process.stdout.write; // take control process.stdout.write = function(string, encoding, fd) { callback(string, encoding, fd); };
javascript
{ "resource": "" }
q14489
Fume
train
function Fume(sources, config) { config = config || {}; config.nameTagPrefix = config.nameTagPrefix || NAME_TAG_PREFIX; config.preferTagPrefix = config.preferTagPrefix || PREFER_TAG_PREFIX; config.amdTagPrefix = config.amdTagPrefix || AMD_TAG_PREFIX; config.cjsTagPrefix = config...
javascript
{ "resource": "" }
q14490
amdWrap
train
function amdWrap(factoryCode, deps) { var deps = deps.map(function (dep) { return "'" + dep + "'"; }); return AMD_TEMPLATE.START + deps.join(',') +
javascript
{ "resource": "" }
q14491
cjsWrap
train
function cjsWrap(factoryCode, deps) { var requires = deps.map(function (dep) { return "require('" + dep + "')"; }); return CJS_TEMPLATE.START + factoryCode +
javascript
{ "resource": "" }
q14492
ensureFolderExists
train
function ensureFolderExists(file) { var folderName = path.dirname(file); if (fs.existsSync(folderName)) { return; } try { mkdirp.sync(folderName); } catch
javascript
{ "resource": "" }
q14493
mergeTypes
train
function mergeTypes(env, types, conf, ENV, fn) { fetch(conf, 'types', function(err, layout) { if (err) return fn(err); debug('# TYPES'); var batch = new Batch(); batch.concurrency(1); types.forEach(function(type) {
javascript
{ "resource": "" }
q14494
mergeApp
train
function mergeApp(env, app, conf, ENV, fn) { fetch(conf, 'apps', function(err, apps) { if (err) return fn(err); debug('# APP');
javascript
{ "resource": "" }
q14495
mergeConf
train
function mergeConf(env, conf, key, ENV, fn) { fetch(conf, key, function(err, layout) { if (err) return fn(err); fetch(layout, 'default', function(err, defaults) { if (err) return fn(err); debug(' default', defaults); merge(ENV, defaults); debug(' ', ENV);
javascript
{ "resource": "" }
q14496
fetch
train
function fetch(conf, key, fn) { getKey(conf, key, function(err,
javascript
{ "resource": "" }
q14497
get
train
function get(obj, fn) { if (typeof obj === 'object') return fn(null, obj); if (typeof obj === 'undefined') return fn(null, {}); if (typeof obj
javascript
{ "resource": "" }
q14498
getIndexOf
train
function getIndexOf(string, find) { // if regex then do it regex way if(XRegExp.isRegExp(find)) {
javascript
{ "resource": "" }
q14499
getStringWithLength
train
function getStringWithLength(string, find) { let obj; // if regex then do it regex way if(XRegExp.isRegExp(find)) { obj = { textValue: XRegExp.replace(string, find, '$1', 'one'), textLength: XRegExp.match(string, /class/g, 'one') .length };
javascript
{ "resource": "" }