_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q43300
train
function (item) { if($.isEmptyObject(item)){ var tempObj={ id: $('input:first', el).val(), name: $('input:first', el).val()}; return [tempObj]; }else{ return item; } }
javascript
{ "resource": "" }
q43301
train
function (item) { // Check if it already exists in the suggestions list. Duplicates aren't allowed. var exists = false; for(var j = 0; j < suggestions.length; j++){ if(suggestions[j].attr('name').toLowerCase() === item.name.toLowerCase()){ exists=true; break; } } // If it didn't exist, add it to the list of suggestions and the searchTerms. if(!exists){ suggestions.push(item); } // We are using searchTerms's setter to execute the filter, so have to set the property (not just update): var searchTerms = self.viewModel.attr('searchTerms').attr().concat(item.name); self.viewModel.attr('searchTerms', searchTerms); }
javascript
{ "resource": "" }
q43302
train
function (item) { var searchTerms = self.viewModel.attr('searchTerms').attr(), searchTerm = item && (item.id || item.name || item); searchTerms.splice(searchTerms.indexOf(searchTerm), 1); // We are using searchTerms's setter to execute the filter, so have to set the property (not just update): self.viewModel.attr('searchTerms', searchTerms); }
javascript
{ "resource": "" }
q43303
xPath
train
function xPath(xPathString) { var xResult = document.evaluate(xPathString, document, null, 0, null); var xNodes = []; var xRes = xResult.iterateNext(); while (xRes) { xNodes.push(xRes); xRes = xResult.iterateNext(); } return xNodes; }
javascript
{ "resource": "" }
q43304
execWaitReadyFunctions
train
function execWaitReadyFunctions() { if (isReady()) { logger.info('Page is ready. Executing ' + callbacksOnReady.length + ' functions that are waiting.'); for (var i = 0; i < callbacksOnReady.length; i++) { var callback = callbacksOnReady[i]; callback(); } } }
javascript
{ "resource": "" }
q43305
whenReady
train
function whenReady(funcToExecute) { if (isReady()) { logger.info('Page is already loaded, instantly executing!'); funcToExecute(); return; } logger.info('Waiting for page to be ready'); callbacksOnReady.push(funcToExecute); }
javascript
{ "resource": "" }
q43306
train
function (adUnitSettings) { var containers = adUnitSettings.containers; var adContainers = []; for (var i = 0; i < containers.length; i++) { var container = containers[i]; var containerXPath = container.xPath; var adContainerElements = xPath(containerXPath); if (!adContainerElements.length) { logger.warn("Ad container with xPath: \"" + containerXPath + "\" could not be found on page"); continue; } if (adContainerElements.length > 1) { logger.warn("Ad container with xPath: \"" + containerXPath + "\" has multiple matches"); } adContainers.push(new AdContainer(container, adContainerElements[0])); } return adContainers; }
javascript
{ "resource": "" }
q43307
render
train
function render(expr, traverse, path, state) { if (isString(expr)) { utils.append(expr, state); } else if (Array.isArray(expr)) { expr.forEach(function(w) { render(w, traverse, path, state); }); } else { utils.move(expr.range[0], state); traverse(expr, path, state); utils.catchup(expr.range[1], state); } }
javascript
{ "resource": "" }
q43308
renderExpressionMemoized
train
function renderExpressionMemoized(expr, traverse, path, state) { var evaluated; if (expr.type === Syntax.Identifier) { evaluated = expr.name; } else if (isString(expr)) { evaluated = expr; } else { evaluated = genID('var'); utils.append(evaluated + ' = ', state); render(expr, traverse, path, state); utils.append(', ', state); } return evaluated; }
javascript
{ "resource": "" }
q43309
renderDesructuration
train
function renderDesructuration(pattern, expr, traverse, path, state) { utils.catchupNewlines(pattern.range[1], state); var id; if (pattern.type === Syntax.ObjectPattern && pattern.properties.length === 1) { id = expr; } else if (pattern.type === Syntax.ArrayPattern && pattern.elements.length === 1) { id = expr; } else { id = renderExpressionMemoized(expr, traverse, path, state); } if (pattern.type === Syntax.ObjectPattern) { pattern.properties.forEach(function(prop, idx) { var comma = (idx !== pattern.properties.length - 1) ? ', ' : ''; if (isPattern(prop.value)) { renderDesructuration(prop.value, [id, '.', prop.key.name], traverse, path, state); } else { utils.append(prop.value.name + ' = ', state); render([id, '.' + prop.key.name], traverse, path, state); utils.append(comma, state); } }); } else { pattern.elements.forEach(function(elem, idx) { // null means skip if (elem === null) { return; } var comma = (idx !== pattern.elements.length - 1) ? ', ' : ''; if (isPattern(elem)) { renderDesructuration(elem, [id, '[' + idx + ']'], traverse, path, state); } else if (elem.type === Syntax.SpreadElement) { utils.append(elem.argument.name + ' = ', state); render([id, '.slice(' + idx + ')'], traverse, path, state); utils.append(comma, state); } else { utils.append(elem.name + ' = ', state); render([id, '[' + idx + ']'], traverse, path, state); utils.append(comma, state); } }); } }
javascript
{ "resource": "" }
q43310
train
function(inPositions) { var p = inPositions; // yay math!, rad -> deg var a = Math.asin(p.y / p.h) * (180 / Math.PI); // fix for range limits of asin (-90 to 90) // Quadrants II and III if (p.x < 0) { a = 180 - a; } // Quadrant IV if (p.x > 0 && p.y < 0) { a += 360; } return a; }
javascript
{ "resource": "" }
q43311
train
function(inPositions) { // the least recent touch and the most recent touch determine the bounding box of the gesture event var p = inPositions; // center the first touch as 0,0 return { magnitude: p.h, xcenter: Math.abs(Math.round(p.fx + (p.x / 2))), ycenter: Math.abs(Math.round(p.fy + (p.y / 2))) }; }
javascript
{ "resource": "" }
q43312
train
function(inInfos, inCommonInfo) { if (inInfos) { var cs = []; for (var i=0, ci; (ci=inInfos[i]); i++) { cs.push(this._createComponent(ci, inCommonInfo)); } return cs; } }
javascript
{ "resource": "" }
q43313
train
function(inMethodName, inEvent, inSender) { var fn = inMethodName && this[inMethodName]; if (fn) { return fn.call(this, inSender || this, inEvent); } }
javascript
{ "resource": "" }
q43314
train
function(inMessageName, inMessage, inSender) { //this.log(inMessageName, (inSender || this).name, "=>", this.name); if (this.dispatchEvent(inMessageName, inMessage, inSender)) { return true; } this.waterfallDown(inMessageName, inMessage, inSender || this); }
javascript
{ "resource": "" }
q43315
restoreState
train
function restoreState(top_err) { if (previous_state === true) { that.pause(function madePaused(err) { // Ignore errors? callback(top_err); }); } else { callback(top_err); } }
javascript
{ "resource": "" }
q43316
done
train
function done(err) { that._gcw = 'done_get_creatures'; bomb.defuse(); // Unsee the 'getting_creatures' event that.unsee('getting_creatures'); // Call next on the next tick (in case we call back with an error) Blast.nextTick(next); if (err) { that.log('error', 'Error getting creatures: ' + err) callback(err); } else { let result = []; for (let id in that.creatures_by_id) { if (that.creatures_by_id[id]) { result.push(that.creatures_by_id[id]); } } callback(null, result); that.emit('_got_creatures', err, result); } }
javascript
{ "resource": "" }
q43317
flux
train
function flux (path) { return function (done) { fs.createReadStream(resolve(__dirname, path)) .pipe(docflux()) .pipe(docflux.markdown({depth: DEPTH, indent: INDENT})) .pipe(concat(function (data) { done(null, data.toString()) })) } }
javascript
{ "resource": "" }
q43318
PushInitiator
train
function PushInitiator(applicationId, password, contentProviderId, evaluation) { this.applicationId = applicationId; this.authToken = new Buffer(applicationId + ':' + password).toString('base64'); this.contentProviderId = contentProviderId; this.isEvaluation = evaluation || false; }
javascript
{ "resource": "" }
q43319
findById
train
function findById(id, cb) { db.getClient(function(err, client, done) { client.query(SELECT_ID, [id], function(err, r) { var result = r && r.rows[0]; if(!err && !result) err = new exceptions.NotFound(); if(err) { cb(err); done(err); } else { cb(null, result); done(); } }); }); }
javascript
{ "resource": "" }
q43320
create
train
function create(body, cb) { var validates = Schema(body); if(!validates) { return cb(new exceptions.BadRequest()); } body.slug = string.slugify(body.title); var q = qb.insert(body); db.getClient(function(err, client, done) { client.query(q[0], q[1], function(err, r) { if(err) { if(err.code == 23505) { err = new exceptions.AlreadyExists(); } cb(err); done(err); } else { cb(null, r.rows[0]); done(); } }); }); }
javascript
{ "resource": "" }
q43321
all
train
function all(options, cb) { var q , page = Number(options.page) || 1 , limit = Number(options.limit) || conf.objects_by_page , offset = (page - 1) * limit; count(function(err, count) { if(err) { return cb(err); } q = select('LEFT JOIN'); q += ' LIMIT ' + limit + ' OFFSET ' + offset; db.getClient(function(err, client, done) { client.query(q, function(err, r) { if(err) { cb(err); done(err); } else { cb(null, { rows: r.rows, count: count, limit: limit, offset: offset, page: page }); done(); } }); }); }); }
javascript
{ "resource": "" }
q43322
nodeJsGlobalResolverFn
train
function nodeJsGlobalResolverFn(normalizedId) { var globalId = normalizedId.id; var x = global[globalId]; if (!x) { var msg = 'Could not find global Node module [' + globalId + ']'; throw new Error(buildMissingDepMsg(msg, globalId, Object.keys(global))); } return x; }
javascript
{ "resource": "" }
q43323
nodeModulesResolverFn
train
function nodeModulesResolverFn(normalizedId) { if (!nodeModulesAt) { throw new Error('Before you can load external dependencies, you must specify where node_modules can be found by ' + 'setting the \'nodeModulesAt\' option when creating the context'); } var extId = normalizedId.id; var modulePath = path.join(nodeModulesAt, extId); if (!externalDepExists[modulePath]) { // yes I know the docs don't like this method. // But it's a little better user experience than trying to require a file that isn't there. if (fs.existsSync(modulePath)) { externalDepExists[modulePath] = true; // cache it so we avoid the lookup next time } else { var msg = 'Could not find external dependency [' + extId + '] at path [' + modulePath + ']'; throw new Error(buildMissingDepMsg(msg, extId, allExternalIds())); } } return require(modulePath); }
javascript
{ "resource": "" }
q43324
idbReadableStream
train
function idbReadableStream(db, storeName, opts) { if (typeof db !== 'object') throw new TypeError('db must be an object') if (typeof storeName !== 'string') throw new TypeError('storeName must be a string') if (opts == null) opts = {} if (typeof opts !== 'object') throw new TypeError('opts must be an object') // use transform stream for buffering and back pressure var transformer = new stream.Transform(xtend(opts, { objectMode: true, transform: function(obj, enc, cb) { cb(null, obj) } })) opts = xtend({ snapshot: false }, opts) var lastIteratedKey = null transformer._cursorsOpened = 0 function startCursor() { var lower, upper, lowerOpen, upperOpen var direction = opts.direction || 'next' var range = opts.range || {} lower = range.lower upper = range.upper lowerOpen = !!range.lowerOpen upperOpen = !!range.upperOpen // if this is not the first iteration, use lastIteratedKey if (lastIteratedKey) { if (direction === 'next') { lowerOpen = true // exclude the last iterated key itself lower = lastIteratedKey } else { upperOpen = true // exclude the last iterated key itself upper = lastIteratedKey } } var keyRange if (lower && upper) keyRange = IDBKeyRange.bound(lower, upper, lowerOpen, upperOpen) else if (lower) keyRange = IDBKeyRange.lowerBound(lower, lowerOpen) else if (upper) keyRange = IDBKeyRange.upperBound(upper, upperOpen) var tx = db.transaction(storeName, 'readonly') var store = tx.objectStore(storeName) transformer._cursorsOpened++ var req = store.openCursor(keyRange, opts.direction) function proceed(cursor) { try { cursor.continue() // throws a TransactionInactiveError if the cursor timed out } catch(err) { // either reopen a cursor or propagate the error if (err.name === 'TransactionInactiveError' && !opts.snapshot) startCursor() // IndexedDB timed out the cursor else transformer.emit('error', err) } } req.onsuccess = function() { var cursor = req.result if (cursor) { lastIteratedKey = cursor.key var go = transformer.write({ key: cursor.key, value: cursor.value }) if (opts.snapshot || go) proceed(cursor) else transformer.once('drain', function() { proceed(cursor) }) } else transformer.end() } tx.onabort = function() { transformer.emit('error', tx.error) } tx.onerror = function() { transformer.emit('error', tx.error) } } startCursor() return transformer }
javascript
{ "resource": "" }
q43325
bin
train
function bin(argv) { var uri = argv[2] if (!uri) { console.error('uri is required') } shell.ls(uri, function(err, arr) { for (i=0; i<arr.length; i++) { console.log(arr[i]) } }) }
javascript
{ "resource": "" }
q43326
fileExist
train
function fileExist(fileName) { return new Promise((resolve, reject) => { fs.stat(fileName, (err, stats) => { if (err === null && stats.isFile()) { resolve(fileName); } else { resolve(false); } }); }); }
javascript
{ "resource": "" }
q43327
SQL
train
function SQL(strs) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var values = []; var text = strs.reduce(function (prev, curr, i) { var arg = args[i - 1]; if (arg instanceof InsertValue) { return prev + arg.value + curr; } else { values.push(arg); return prev + '$' + values.length + curr; } }); return { text: text, values: values }; }
javascript
{ "resource": "" }
q43328
AsyncSimpleIterator
train
function AsyncSimpleIterator (options) { if (!(this instanceof AsyncSimpleIterator)) { return new AsyncSimpleIterator(options) } this.defaultOptions(options) AppBase.call(this) this.on = utils.emitter.compose.call(this, 'on', this.options) this.off = utils.emitter.compose.call(this, 'off', this.options) this.once = utils.emitter.compose.call(this, 'once', this.options) this.emit = utils.emitter.compose.call(this, 'emit', this.options) }
javascript
{ "resource": "" }
q43329
checkMediaProfileSpecType
train
function checkMediaProfileSpecType(key, value) { if(typeof value != 'string') throw SyntaxError(key+' param should be a String, not '+typeof value); if(!value.match('WEBM|MP4|WEBM_VIDEO_ONLY|WEBM_AUDIO_ONLY|MP4_VIDEO_ONLY|MP4_AUDIO_ONLY')) throw SyntaxError(key+' param is not one of [WEBM|MP4|WEBM_VIDEO_ONLY|WEBM_AUDIO_ONLY|MP4_VIDEO_ONLY|MP4_AUDIO_ONLY] ('+value+')'); }
javascript
{ "resource": "" }
q43330
createApplication
train
function createApplication(options) { options = options || {}; var sapp = new Application(); sapp.sycle = sycle; if (options.loadBuiltinModels) { sapp.phase(require('./boot/builtin-models')()); } return sapp; }
javascript
{ "resource": "" }
q43331
enqueueAll
train
function enqueueAll() { for (let i = 0; i < count - 1; i++) { enqueue(); } return enqueue(); function enqueue() { return queue.enqueue(() => new Date()); } }
javascript
{ "resource": "" }
q43332
bakeFolder
train
function bakeFolder(source, dest) { var args = createArgs(source, dest, {}); wrapFunction('BakeFolder', args, function () { args.files = fs.readdirSync(args.source); args.filters = [filterHidden]; wrapFunction('FilterFiles', args, function () { args.filters.forEach(function (filter) { args.files = args.files.filter(filter); }); }); delete args.filters; wrapFunction('BakeFiles', args, function () { var files = [], dirs = []; // seperate the files from the directories args.files.forEach(function (file) { var stats = fs.statSync(path.join(args.source, file)); if (stats.isDirectory()) { dirs.push(file); } else { files.push(file); } }); // process all the files first files.forEach(function (file) { bakeFile(path.join(args.source, file), path.join(args.dest, file)); }); // and then process the sub directories dirs.forEach(function (file) { bakeFolder(path.join(args.source, file), path.join(args.dest, file)); }); }); }); function filterHidden(file) { return !(/^\.|~$/).test(file); } }
javascript
{ "resource": "" }
q43333
defaults
train
function defaults(route, name, handle) { if (typeof route === 'function') { handle = route; name = handle.name; route = '/'; } else if (typeof name === 'function') { handle = name; name = handle.name; } // A name needs to be provided if (!name) throw new NameError(); // wrap sub-apps if ('function' == typeof handle.handle) { var server = handle; handle.route = route; handle = function(req, res, next){ server.handle(req, res, next); }; } // wrap vanilla http.Servers if (handle instanceof http.Server) { handle = handle.listeners('request')[0]; } // strip trailing slash if ('/' == route[route.length - 1]) { route = route.slice(0, -1); } return {route: route, name: name, handle: handle}; }
javascript
{ "resource": "" }
q43334
NameError
train
function NameError(message) { Error.call(this); Error.captureStackTrace(this, arguments.callee); this.name = 'Middleware Name Error'; this.message = message || 'The argument must be a named function or supply a name'; }
javascript
{ "resource": "" }
q43335
ExistsError
train
function ExistsError(name, message) { Error.call(this); Error.captureStackTrace(this, arguments.callee); this.name = 'Middleware Exists Error'; this.message = message || 'Middleware named ' + name + ' already exists. Provide an alternative name.'; }
javascript
{ "resource": "" }
q43336
NotFoundError
train
function NotFoundError(name) { Error.call(this); Error.captureStackTrace(this, arguments.callee); this.name = 'Middleware Not Found Error'; this.message = name + ' not found in the current stack'; }
javascript
{ "resource": "" }
q43337
Process
train
function Process(settings) { // save arguments this.settings = settings; // build args this.args = [settings.file].concat(settings.args || []); // build env this.env = helpers.mergeObject({}, settings.env || process.env); if (settings.options) { this.env.spawnOptions = JSON.stringify(settings.options); } // defaults properties this.closed = !!settings.close; this.suicide = false; this.pid = null; this.alive = false; // this streams will relay data from and to the process this.stderr = new streams.RelayStream({ paused: false }); this.stdout = new streams.RelayStream({ paused: false }); this.stdin = new streams.RelayStream({ paused: false }); // relay io if (this.settings.ipc && helpers.support.pipeFork) { this.send = function () { this.process.send.apply(this.process, arguments); }; this.flush = function () {}; } }
javascript
{ "resource": "" }
q43338
train
function () { var suicide = self.suicide; self.suicide = false; self.alive = false; self.emit('stop', suicide); }
javascript
{ "resource": "" }
q43339
forceClose
train
function forceClose(channel) { if (!channel) return; var destroyer = setTimeout(function () { channel.destroy(); }, 200); channel.once('close', function () { clearTimeout(destroyer); }); }
javascript
{ "resource": "" }
q43340
interceptDeath
train
function interceptDeath(process, events) { var closeEvent = helpers.support.close; // all channels are closed process.once(closeEvent ? 'close' : 'exit', events.close); // the process died if (closeEvent) { process.once('exit', events.exit); } else { // intercept internal onexit call var internalHandle = process._internal.onexit; process._internal.onexit = function () { events.exit(); internalHandle.apply(this, arguments); }; } }
javascript
{ "resource": "" }
q43341
hashsum
train
function hashsum(hash, str) { // you have to convert from string to array buffer var ab // you have to represent the algorithm as an object , algo = { name: algos[hash] } ; if ('string' === typeof str) { ab = str2ab(str); } else { ab = str; } // All crypto digest methods return a promise return crypto.subtle.digest(algo, ab).then(function (digest) { // you have to convert the ArrayBuffer to a DataView and then to a hex String return ab2hex(digest); }).catch(function (e) { // if you specify an unsupported digest algorithm or non-ArrayBuffer, you'll get an error console.error('sha1sum ERROR'); console.error(e); throw e; }); }
javascript
{ "resource": "" }
q43342
ab2hex
train
function ab2hex(ab) { var dv = new DataView(ab) , i , len , hex = '' , c ; for (i = 0, len = dv.byteLength; i < len; i += 1) { c = dv.getUint8(i).toString(16); if (c.length < 2) { c = '0' + c; } hex += c; } return hex; }
javascript
{ "resource": "" }
q43343
str2ab
train
function str2ab(stringToEncode, insertBom) { stringToEncode = stringToEncode.replace(/\r\n/g,"\n"); var utftext = [] , n , c ; if (true === insertBom) { utftext[0] = 0xef; utftext[1] = 0xbb; utftext[2] = 0xbf; } for (n = 0; n < stringToEncode.length; n += 1) { c = stringToEncode.charCodeAt(n); if (c < 128) { utftext[utftext.length]= c; } else if((c > 127) && (c < 2048)) { utftext[utftext.length] = (c >> 6) | 192; utftext[utftext.length] = (c & 63) | 128; } else { utftext[utftext.length] = (c >> 12) | 224; utftext[utftext.length] = ((c >> 6) & 63) | 128; utftext[utftext.length] = (c & 63) | 128; } } return new Uint8Array(utftext).buffer; }
javascript
{ "resource": "" }
q43344
escapeCurly
train
function escapeCurly (text, escapes) { var newText = text.slice (0, escapes[0]); for (var i = 0; i < escapes.length; i += 3) { var from = escapes[i]; var to = escapes[i + 1]; var type = escapes[i + 2]; // Which escape do we have here? if (type === 0) { newText += '{{'; } else { newText += '}}'; } newText += text.slice (to, escapes[i+3]); } return newText; }
javascript
{ "resource": "" }
q43345
train
function(input, output, literal, cb) { var text = ''; input.on ('data', function gatherer (data) { text += '' + data; // Converting to UTF-8 string. }); input.on ('end', function writer () { try { var write = function(data) { output.write(data); }; template(text)(write, literal); } catch (e) { if (cb) { cb (e); } } finally { // There are streams you cannot end. try { output.end (); } catch (e) {} finally { if (cb) { cb (null); } } } }); }
javascript
{ "resource": "" }
q43346
train
function(input) { var code = 'var $_isidentifier = ' + $_isidentifier.toString() + ';\n' + // FIXME: could we remove that eval? 'eval((' + literaltovar.toString() + ')($_scope));\n'; code += 'var $_parsers = {\n'; var parsernames = Object.keys(parsers); for (var i = 0; i < parsernames.length; i++) { code += ' ' + JSON.stringify(parsernames[i]) + ': ' + parsers[parsernames[i]].toString() + ',\n'; }; code += '}\n'; code += 'var $_written = "";\n' + 'var $_write = function(data) { $_written += data; };\n'; code += compile(input); code += '$_written\n'; return function($_write, $_scope, timeout, cb) { var res; try { res = vm.runInNewContext(code, {$_scope: $_scope}, {timeout: timeout || 1000}); } catch(err) { console.error(err); $_write(''); if (cb) { cb(err); } return; } $_write(res); if (cb) { cb(null); } }; }
javascript
{ "resource": "" }
q43347
train
function(input) { var code = 'var $_parsers = {\n'; var parsernames = Object.keys(parsers); for (var i = 0; i < parsernames.length; i++) { code += ' ' + JSON.stringify(parsernames[i]) + ': ' + parsers[parsernames[i]].toString() + ',\n'; }; code += '}\n'; code += compile(input) + '\nif (typeof $_end === "function") {$_end();}'; var script = new vm.Script(code, {timeout: 4 * 60 * 1000}); var runner = function(scope) { var output = ''; var pipeOpen = false; var ended = false; var stream = new Readable({ encoding: 'utf8', read: function() { pipeOpen = true; if (ended && output === '') { pipeOpen = this.push(null); } else if (output !== '') { pipeOpen = this.push(output); output = ''; } }, }); scope.$_scope = scope; scope.$_write = function(data) { output += '' + data; if (pipeOpen && output !== '') { pipeOpen = stream.push(output); output = ''; } }; scope.$_end = function() { ended = true; if (pipeOpen) { stream.push(null); } }; script.runInNewContext(scope) return stream; }; runner.code = code; return runner; }
javascript
{ "resource": "" }
q43348
train
function (applicationId, deviceDetails, environment) { if(!applicationId) { logger.wtf('No applicationID specified'); } this.applicationId = applicationId; this.deviceDetails = deviceDetails; this.environment = environment; this._currentAds = []; this._loadingAds = []; this._adsWithoutImages = []; }
javascript
{ "resource": "" }
q43349
getNewToken
train
function getNewToken(credentials, oauth2Client, callback) { var authUrl = oauth2Client.generateAuthUrl({ access_type: 'offline', scope: SCOPES }); console.log('Authorize this app by visiting this url: ', authUrl); var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question('Enter the code from that page here: ', function(code) { rl.close(); oauth2Client.getToken(code, function(err, token) { if (err) { console.log('Error while trying to retrieve access token', err); return; } oauth2Client.credentials = token; storeToken(credentials, token); callback(oauth2Client); }); }); }
javascript
{ "resource": "" }
q43350
listLabels
train
function listLabels(auth) { var gmail = google.gmail('v1'); gmail.users.labels.list({ auth: auth, userId: 'me', }, function(err, response) { if (err) { console.log('The API returned an error: ' + err); return; } var labels = response.labels; if (labels.length === 0) { console.log('No labels found.'); } else { console.log('Labels:'); for (var i = 0; i < labels.length; i++) { var label = labels[i]; console.log('- %s', label.name); } } }); }
javascript
{ "resource": "" }
q43351
processDeltas
train
function processDeltas(deltas) { let updates = { changed: {}, removed: {} }; deltas.forEach(delta => { const entityType = delta[0]; const changeType = delta[1]; const entity = delta[2]; const key = _getEntityKey(entityType, entity); if (!key) { // We don't know how to manage this entity, so ignore it. return; } const entityGroup = _getEntityGroup(entityType); const updateCollection = updates[changeType + 'd']; if (!updateCollection[entityGroup]) { updateCollection[entityGroup] = {}; } updateCollection[entityGroup][key] = _parseEntity(entityType, entity); }); return updates; }
javascript
{ "resource": "" }
q43352
_getEntityKey
train
function _getEntityKey(entityType, entity) { switch (entityType) { case 'remote-application': case 'application': case 'unit': return entity.name; case 'machine': case 'relation': return entity.id; case 'annotation': return entity.tag; default: // This is an unknown entity type so ignore it as we don't know how to // handle it. return null; } }
javascript
{ "resource": "" }
q43353
_parseEntity
train
function _parseEntity(entityType, entity) { switch (entityType) { case 'remote-application': return parsers.parseRemoteApplication(entity); case 'application': return parsers.parseApplication(entity); case 'unit': return parsers.parseUnit(entity); case 'machine': return parsers.parseMachine(entity); case 'relation': return parsers.parseRelation(entity); case 'annotation': return parsers.parseAnnotation(entity); default: // This is an unknown entity type so ignore it as we don't know how to // handle it. return null; } }
javascript
{ "resource": "" }
q43354
getMilliseconds
train
function getMilliseconds( time ) { if ( typeof time == 'number' ) { return time; } var matches = time.match( /(^\d*\.?\d*)(\w*)/ ); var num = matches && matches[1]; var unit = matches && matches[2]; if ( !num.length ) { return 0; } num = parseFloat( num ); var mult = msUnits[ unit ] || 1; return num * mult; }
javascript
{ "resource": "" }
q43355
compileFile
train
function compileFile(srcFullPath, saveOutFullPath, onlyCopy) { var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; var content = fs.readFileSync(srcFullPath, 'utf8'); //when get file content empty, maybe file is locked if (!content) { return; } // only copy file content if (onlyCopy) { fse.copySync(srcFullPath, saveOutFullPath); return; } try { var startTime = Date.now(); var data = compileByBabel(content, { filename: srcFullPath // sourceMaps: true, // sourceFileName: relativePath }); var endTime = Date.now(); if (options.debug) { console.log('Compile file ' + srcFullPath, 'Babel cost ' + (endTime - startTime) + ' ms'); } // save file fse.outputFileSync(saveOutFullPath, data.code); return true; } catch (e) { console.error('compile file ' + srcFullPath + ' error', e); } return false; }
javascript
{ "resource": "" }
q43356
getFiles
train
function getFiles(paths) { var result = fileUtil.getAllFiles(paths); var files = result.map(function (item) { return item.relativePath; // return path.join(item.basePath, item.relativePath); }); return files; }
javascript
{ "resource": "" }
q43357
TypedOneOf
train
function TypedOneOf (config) { const oneOf = this; // validate oneOf if (!config.hasOwnProperty('oneOf')) { throw Error('Invalid configuration. Missing required one-of property: oneOf. Must be an array of schema configurations.'); } if (!Array.isArray(config.oneOf) || config.oneOf.filter(v => !v || typeof v !== 'object').length) { throw Error('Invalid configuration value for property: oneOf. Must be an array of schema configurations.'); } // create each unique schema const hashes = {}; const schemas = config.oneOf .map(item => FullyTyped(item)) .filter(schema => { const hash = schema.hash(); if (hashes[hash]) return false; hashes[hash] = true; return true; }); // define properties Object.defineProperties(oneOf, { oneOf: { /** * @property * @name TypedOneOf#oneOf * @type {object} */ value: schemas, writable: false } }); return oneOf; }
javascript
{ "resource": "" }
q43358
bin
train
function bin (argv) { program.version(pkg.version) .usage('[options] <sourceURI> <destURI>') .parse(argv) var sourceURI = program.args[0] var destURI = program.args[1] if (!sourceURI || !destURI) { program.help() } shell.mv(sourceURI, destURI, function (err, res, uri) { if (!err) { debug(res) } else { console.error(err) } }) }
javascript
{ "resource": "" }
q43359
train
function(evt) { if (evt !== 'change' && evt !== 'rename') { return; } fs.stat(file, function(err, current) { if (err) { self.logger_.error(err.message); self.emit('error.watch', err.message); return; } if (current.size !== prev.size || +current.mtime > +prev.mtime) { prev = current; // save new stats self.logger_.debug(util.format('%s has been modified', file)); self.emit('watch'); } }); }
javascript
{ "resource": "" }
q43360
train
function(fn, syntheticArgs) { var $this = this; syntheticArgs = syntheticArgs || []; /** * Ensure to have it in the next event loop for better async */ var processResponder = function() { try { if (fn) { /** * Insert a done() or ok() argument to other needed arguments */ syntheticArgs.unshift(function() { /** * Call the next in queue */ $this.next.apply($this, arguments); }); /** * Call the function finally */ fn.apply(this, syntheticArgs); } else { syntheticArgs = syntheticArgs || []; /** * If no function passed, call the next in queue */ $this.next.apply(this, syntheticArgs); } } catch(e) { /** * An error caught is thrown directly to the catch handler, if any */ if (this.onCatch) { this.onCatch(e); } else { throw e; } } }; if (typeof process === "undefined") { processResponder(); } else { process.nextTick(processResponder); } /** * Return self for chaining */ return this; }
javascript
{ "resource": "" }
q43361
train
function() { try { if (fn) { /** * Insert a done() or ok() argument to other needed arguments */ syntheticArgs.unshift(function() { /** * Call the next in queue */ $this.next.apply($this, arguments); }); /** * Call the function finally */ fn.apply(this, syntheticArgs); } else { syntheticArgs = syntheticArgs || []; /** * If no function passed, call the next in queue */ $this.next.apply(this, syntheticArgs); } } catch(e) { /** * An error caught is thrown directly to the catch handler, if any */ if (this.onCatch) { this.onCatch(e); } else { throw e; } } }
javascript
{ "resource": "" }
q43362
train
function(err) { /** * If err is an Error object, break the chain and call catch */ if (err && (err.constructor.name === "Error" || err.constructor.name === "TypeError") && this.onCatch) { this.onCatch(err); return; } var nextFn = this.fnStack.shift(); if (nextFn) { /** * Ensure arguments are passed as an Array */ var args = Array.prototype.slice.call(arguments); return this.execute(nextFn.fn, args); } }
javascript
{ "resource": "" }
q43363
train
function(xml, command, version) { var formatVersion = version || JSDAS.Formats.current; var format = JSDAS.Formats[formatVersion][command]; var json = JSDAS.Parser.parseElement(xml, format); return json; }
javascript
{ "resource": "" }
q43364
train
function(xml, format) { var out = {}; //The Document object does not have all the functionality of a standard node (i.e. it can't have attributes). //So, if we are in the Document element, move to its ¿¿only?? child, the root. if(xml.nodeType == 9) { //detect the Document node type xml = xml.firstChild; while(xml.nodeType != 1 && xml.nextSibling) //Document nodes (9) can't have text (3) nodes as children. Test only for elements (1) xml = xml.nextSibling; } //get properties if (format.properties) { var props = format.properties; for (var nprop = 0, lenprop = props.length; nprop < lenprop; ++nprop) { var f = props[nprop]; var name = f.jsname || f.name; out[name] = this.parseProperty(xml, f); } } //get childs if (format.childs) { var ch = format.childs; if (ch === 'text') { //if thextual child /* * Due to browser compatibility the textContent may come from this 3 different methods: * xml.innerText = IE * xml.textContent = Firefox * xml.text = IE */ out['textContent'] = xml.innerText || xml.textContent || xml.text; } else { //childs different than text for (var i = 0, len = ch.length; i < len; ++i) { var f = ch[i]; //var els = xml.getElementsByTagName(f.tagname); //Hack: since getElementsByTagName is case sensitive for XML documents and DAS XMLs can be found //in different casing, use a regular expresion tofilter the elements. //FIX: This is an unefficient parsing method. Other ways should be explored. var els = []; var all_els = xml.getElementsByTagName('*'); for(var iael=0, lenael=all_els.length; iael<lenael; ++iael) { var curr_node = all_els[iael]; if(new RegExp('^'+f.tagname+'$', 'i').test(curr_node.nodeName)) { els.push(curr_node); } } //End of tag casing hack if (f.mandatory && this.checkMandatoryElements && (!els || els.length == 0)) { //if a mandatory element is not present... //JSDAS.Console.log("Mandatory element is not present."); } if (els.length>0) { //if there are elements of the given tagName var name = f.jsname || f.tagname; if (f.multiple) { //if its a multiple instance child, create an array and push all instances out[name] = []; for (var iel = 0, lenel = els.length; iel < lenel; ++iel) { out[name].push(this.parseElement(els[iel], f)); } } else { out[name] = this.parseElement(els[0], f); } } } } } return out; }
javascript
{ "resource": "" }
q43365
train
function(url, callback, errorcallback){ if (!this.initialized) { this.initialize(); } var xmlloader = JSDAS.XMLLoader; //get a reference to myself var usingCORS = true; var xhr = this.xhrCORS('GET', url); if(!xhr) { //if the browser is not CORS capable, fallback to proxy if available if(this.proxyURL) { var xhr = this.xhr(); xhr.open('GET', this.proxyURL+'?url='+url, true); usingCORS = false; } else { errorcallback && errorcallback({id: 'no_proxy', msg: "Cross-Origin requests are not supported but no proxy has been defined"}); } } //At this point, we've got a valid XHR //xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); //xhr.setRequestHeader("Accept", "application/xml, text/xml"); var xmlloader = this; //necessary so the closures get the variable var change = function(xhr){ if (xhr && (xhr.readyState == 4)) { if (xmlloader.httpSuccess(xhr)) { processResponse(xhr); } else { //if it failed, it mighht be that the source has no CORS enabled. In such case, fallback to proxy before erroring if(usingCORS && xmlloader.proxyURL) { //if it failed when using CORS and we've got a proxy, try to get the data via the proxy xhr=undefined; usingCORS = false; var new_xhr = xmlloader.xhr(); new_xhr.open('GET', xmlloader.proxyURL+'?url='+url, true); new_xhr.onreadystatechange = function() {change(new_xhr);} new_xhr.send(null); } else { errorcallback && errorcallback({id: "xmlhttprequest_error", msg: xhr.status}); } } //to prevent IE memory leaks xhr = undefined; } }; var processResponse = function(xhr) { //WARNING: Since Uniprot (and maybe others) do not respond with a correct content-type, we cannot check it here. Should be reactivated as soon as the servers are updated. //var ct = xhr.getResponseHeader("content-type"); //var xml = ct && ct.indexOf("xml") >= 0; //if (xml) { var data = xhr.responseXML; if(!data) { //This block is here since we cannot rely on content type headers errorcallback && errorcallback({id: 'not_xml', msg: "The response was not XML"}); } if(data.documentElement.nodeName != 'parsererror') { callback(data); return; } //} //if anything went wrong, the document was not XML //errorcallback && errorcallback({id: 'not_xml', msg: "The response was not XML"}); }; xhr.onreadystatechange = function() {change(xhr);}; // Send the data try { xhr.send(null); } catch(e) { //This code will rarely be called. Only when there's a problem on sernding the request. if(usingCORS && this.proxyURL) { //if it failed when using CORS and we've got a proxy, try to get the data via the proxy var xhr = this.xhr(); xhr.open('GET', this.proxyURL+'?url='+url, true); xhr.onreadystatechange = function() {change(xhr);} try { xhr.send(null); } catch(e) { errorcallback && errorcallback({id: 'sending_error', msg: "There was an error when sending the request"}); } } else { errorcallback && errorcallback({id: 'sending_error', msg: "There was an error when sending the request"}); } } }
javascript
{ "resource": "" }
q43366
train
function(xhr){ if (xhr && (xhr.readyState == 4)) { if (xmlloader.httpSuccess(xhr)) { processResponse(xhr); } else { //if it failed, it mighht be that the source has no CORS enabled. In such case, fallback to proxy before erroring if(usingCORS && xmlloader.proxyURL) { //if it failed when using CORS and we've got a proxy, try to get the data via the proxy xhr=undefined; usingCORS = false; var new_xhr = xmlloader.xhr(); new_xhr.open('GET', xmlloader.proxyURL+'?url='+url, true); new_xhr.onreadystatechange = function() {change(new_xhr);} new_xhr.send(null); } else { errorcallback && errorcallback({id: "xmlhttprequest_error", msg: xhr.status}); } } //to prevent IE memory leaks xhr = undefined; } }
javascript
{ "resource": "" }
q43367
writeLaunchCode
train
function writeLaunchCode(config) { var { name, stub } = config.holder if (!name || !stub) { throw new Error('invalid name or stub') } var code = ` ;(function () { var root = document.getElementById('${name}'); if (!root) throw new Error('undefined ${stub} root'); var view = window.${stub}.entry; if (!view) throw new Error('undefined ${stub} view'); ReactDOM.render(React.createElement(view), root); }()); `.replace(/\n|(\s{2})/g, '') var output = path.join(config.$path.target.client, 'launch.js') fs.writeFileSync(output, code, 'utf8') logger.done('view ::', 'launch code generated') }
javascript
{ "resource": "" }
q43368
NoiseSampler
train
function NoiseSampler(size) { if (!size) throw "no size specified to NoiseSampler"; this.size = size; this.scale = 1; this.offset = 0; this.smooth = true; this.seamless = false; // this.scales = [ // 10, 0.1, 0.2, 1 // ]; // this.strengths = [ // 0.1, 0.3, 0.2, 1 // ]; this.scales = [ 1, 20, 0.5 ]; this.strengths = [ 1, 0.1, 0.5 ]; this.data = new Float32Array(this.size * this.size); }
javascript
{ "resource": "" }
q43369
train
function(x, y) { //avoid negatives if (this.seamless) { x = (x%this.size + this.size)%this.size y = (y%this.size + this.size)%this.size } else { x = clamp(x, 0, this.size) y = clamp(y, 0, this.size) } if (this.smooth) return sampling.bilinear(this.data, this.size, this.size, x, y); else return sampling.nearest(this.data, this.size, this.size, x, y); }
javascript
{ "resource": "" }
q43370
is
train
function is (constructor, value) { return value !== null && (value.constructor === constructor || value instanceof constructor); }
javascript
{ "resource": "" }
q43371
isDataBinaryRobust
train
function isDataBinaryRobust(data) { // console.log('data is binary ?') var patternVertex = /vertex[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g; var text = ensureString(data); var isBinary = patternVertex.exec(text) === null; return isBinary; }
javascript
{ "resource": "" }
q43372
train
function(err, r) { if (err) { numberOfValidConnections = numberOfValidConnections - 1; errorObject = err; return false; } else if (r.result['$err']) { errorObject = r.result; return false; } else if (r.result['errmsg']) { errorObject = r.result; return false; } else { numberOfValidConnections = numberOfValidConnections + 1; } return true; }
javascript
{ "resource": "" }
q43373
train
function(options) { Configurable.call(this); this._resources = []; this._serializer = require(__dirname + '/lib/Serializer'); this.setAll( _.extend({}, defaults, options) ); // List of IDs used to find duplicate handlers fast this._ids = { // id: handler }; // List of names for handlers set by the user this._names = { // name: handler }; }
javascript
{ "resource": "" }
q43374
makeValidation
train
function makeValidation(name, exp, parser) { return function (input) { if (typeof input !== 'string') { throw new TypeError('Cannot validate ' + name + '. Input must be a string.'); } var validate = function () { return input.match(exp) ? true : false; }; return { valid: validate(), parse: function () { if (!validate()) { return false; } var captures = exp.exec(input); return parser(captures); } }; }; }
javascript
{ "resource": "" }
q43375
pipeEvents
train
function pipeEvents(source, destination, event) { source.on(event, function (data) { destination.emit(event, data); }); }
javascript
{ "resource": "" }
q43376
get
train
function get(key) { let val = process.env[key]; return val in types ? types[val] : util.isNumeric(val) ? parseFloat(val) : val; }
javascript
{ "resource": "" }
q43377
set
train
function set(key, val) { return process.env[key] = (process.env[key] === undefined ? val : process.env[key]); }
javascript
{ "resource": "" }
q43378
load
train
function load(file) { let contents = null; file = path.resolve(file); // handle .env files if (constants.REGEX.envfile.test(file)) { contents = util.parse(fs.readFileSync(file, 'utf8')); // handle .js/.json files } else { contents = require(file); } return env(contents); }
javascript
{ "resource": "" }
q43379
init
train
function init(){ // set NODE_ENV to --env value if (argv.env) { set('NODE_ENV', argv.env); } // load evironment files ['./.env', './config/.env', './env', './config/env'].map(file => { try { load(file); } catch(err) { if (env('DEBUG')) { console.error(`Env: ${err.message}`); } } }); // set default vars set('NODE_ENV', 'development'); ['DEVELOPMENT', 'PRODUCTION'].map(str => { set(str, get('NODE_ENV') === str.toLowerCase()); }); }
javascript
{ "resource": "" }
q43380
_expandParentsForNode
train
function _expandParentsForNode(node) { // get the actual parent nodes in the editor var parents = []; $(node).parentsUntil('#tinymce').each(function(index, el) { parents.push(el.id); }); parents.reverse(); // TODO handling for readonly mode where only headings are in the tree // expand the corresponding nodes in the tree for (var i = 0; i < parents.length; i++) { var parentId = parents[i]; var parentNode = $('[name="'+parentId+'"]', $tree); var isOpen = $tree.jstree('is_open', parentNode); if (!isOpen) { $tree.jstree('open_node', parentNode, null, false); } } }
javascript
{ "resource": "" }
q43381
selectNode
train
function selectNode($node, selectContents, multiselect, external) { var id = $node.attr('name'); _removeCustomClasses(); // clear other selections if not multiselect if (!multiselect) { if (tree.currentlySelectedNodes.indexOf(id) != -1) { tree.currentlySelectedNodes = [id]; } else { tree.currentlySelectedNodes = []; } } if (id) { var isEntity = w.entitiesManager.getEntity(id) !== undefined; var aChildren = $node.children('a'); if (isEntity) { tree.currentlySelectedNodes = []; aChildren.addClass('nodeSelected').removeClass('contentsSelected'); if (tree.currentlySelectedEntity !== id) { tree.currentlySelectedEntity = id; tree.selectionType = null; if (!external) { ignoreSelect = true; w.entitiesManager.highlightEntity(id, null, true); } } } else if (w.structs[id] != null) { tree.currentlySelectedEntity = null; if (tree.currentlySelectedNodes.indexOf(id) != -1 && !external) { // already selected node, toggle selection type selectContents = !selectContents; } else { tree.currentlySelectedNodes.push(id); } if (selectContents) { aChildren.addClass('contentsSelected').removeClass('nodeSelected'); } else { aChildren.addClass('nodeSelected').removeClass('contentsSelected'); } tree.selectionType = selectContents ? tree.CONTENTS_SELECTED : tree.NODE_SELECTED; if (!external) { if (w.structs[id]._tag == w.header) { w.dialogManager.show('header'); } else { ignoreSelect = true; // set to true so tree.highlightNode code isn't run by editor's onNodeChange handler w.selectStructureTag(tree.currentlySelectedNodes, selectContents); } } } } }
javascript
{ "resource": "" }
q43382
resolveCapabilities
train
function resolveCapabilities(capabilities, capabilitiesDictionary) { if (typeof capabilities !== "string") { // we do not know how to parse non string capabilities, let's assume it // is selenium compliant capabilities and return it. return capabilities; } // try to parse as a JSON string try { return JSON.parse(capabilities); } catch (e) { } // No luck with JSON assumption. // Try to read from configuration. if (capabilities in capabilitiesDictionary) { return capabilitiesDictionary[capabilities]; } // still no luck ? // assume this is browserName... return { browserName: capabilities }; }
javascript
{ "resource": "" }
q43383
sinonDoublistFs
train
function sinonDoublistFs(test) { if (module.exports.trace) { nodeConsole = require('long-con').create(); log = nodeConsole .set('nlFirst', true) .set('time', false) .set('traceDepth', true) .create(null, console.log); // eslint-disable-line no-console nodeConsole.traceMethods('FileStub', FileStub, log, null, /^prototype$/); nodeConsole.traceMethods('FileStub', FileStub.prototype, log, null, /^(get|set)$/); nodeConsole.traceMethods('wrapFs', wrapFs, log); nodeConsole.traceMethods('mixin', mixin, log); } else { log = function noOpLogger() {}; } if (is.string(test)) { globalInjector[test](); return; } // Ex. 'mocha' if (is.fn(realFs.exists)) { return; } // Already doubled // Mix in stubFile(), stubTree(), etc. Object.keys(mixin).forEach(function forEachMixinMethod(method) { test[method] = mixin[method].bind(test); }); // Replace a selection of `fs` Object.keys(wrapFs).forEach(function forEachWrapFsMethod(method) { realFs[method] = fs[method]; fs[method] = wrapFs[method]; }); fileStubMap = {}; context = test; }
javascript
{ "resource": "" }
q43384
FileStub
train
function FileStub() { this.settings = { name: '', buffer: new Buffer(0), readdir: false, parentName: '', stats: { dev: 2114, ino: 48064969, mode: 33188, nlink: 1, uid: 85, gid: 100, rdev: 0, size: 0, blksize: 4096, blocks: 0, atime: 'Mon, 10 Oct 2011 23:24:11 GMT', mtime: 'Mon, 10 Oct 2011 23:24:11 GMT', ctime: 'Mon, 10 Oct 2011 23:24:11 GMT' } }; }
javascript
{ "resource": "" }
q43385
intermediatePaths
train
function intermediatePaths(sparse) { const dense = {}; [].concat(sparse).forEach(function forEachPath(path) { path = rtrimSlash(path); dense[path] = {}; // Store as keys to omit dupes const curParts = trimSlash(path).split('/'); const gapParts = []; curParts.forEach(function forEachPart(part) { const parent = '/' + gapParts.join('/'); gapParts.push(part); // Incrementally include all parts to collect gaps const intermediate = '/' + gapParts.join('/'); if (!dense[intermediate]) { dense[intermediate] = {}; } // Collect gap if (!dense[parent]) { dense[parent] = {}; } // Store its relatinship if (parent === '/') { dense[parent][trimSlash(intermediate.slice(1))] = 1; } else { // Guard against '' child name from sparse path w/ trailing slash const childName = intermediate.replace(parent + '/', ''); if (childName) { dense[parent][childName] = 1; } } }); }); Object.keys(dense).forEach(function forEachDensePath(name) { dense[name] = Object.keys(dense[name]); }); return dense; }
javascript
{ "resource": "" }
q43386
withOptions
train
function withOptions(scope, defaultOptions) { return function(plugin, options) { return scope.use(this, scope, plugin, scope.combine(defaultOptions, options)) } }
javascript
{ "resource": "" }
q43387
train
function (o) { var r = []; for (var i in o) { if (o.hasOwnProperty(i)) { r.push(i); } } return r; }
javascript
{ "resource": "" }
q43388
splitKeys
train
function splitKeys (keys) { if (typeof(keys) === 'string') { return keys.replace(/^\s*\.\s*/,'') .replace(/(?:\s*\.\s*)+/g, '.') .split('.'); } else if (Array.isArray(keys)) { return [].concat(keys); } return; }
javascript
{ "resource": "" }
q43389
Ops
train
function Ops (ref, key) { this.ref = ref; this.key = key; if (this.ref[this.key] === undefined) { this.ref[this.key] = 0; } this._toNumber(); this.isNumber = (typeof this.ref[this.key] === 'number'); this.isBoolean = (typeof this.ref[this.key] === 'boolean'); this.isString = (typeof this.ref[this.key] === 'string'); this.isArray = Array.isArray(this.ref[this.key]); this.isObject = (!this.isArray && typeof this.ref[this.key] === 'object'); }
javascript
{ "resource": "" }
q43390
_createList
train
function _createList(list) { var listContent = []; if(list) { listContent.push("<table>"); Ember.$.each(list, function (property, value) { listContent.push( "<tr><td>", property, "</td><td>", value, "</td></tr>" ); }); listContent.push("</table>"); return listContent.join(""); } }
javascript
{ "resource": "" }
q43391
_setData
train
function _setData(data) { _element.find('.tip-title').html(data.title || ""); _element.find('.tip-text').html(data.text || ""); _element.find('.tip-text')[data.text ? 'show' : 'hide'](); _element.find('.tip-list').html(_createList(data.kvList) || ""); }
javascript
{ "resource": "" }
q43392
train
function (tipElement, svg) { _element = tipElement; _bubble = _element.find('.bubble'); _svg = svg; _svgPoint = svg[0].createSVGPoint(); }
javascript
{ "resource": "" }
q43393
train
function (node, data, event) { var point = data.position || (node.getScreenCTM ? _svgPoint.matrixTransform( node.getScreenCTM() ) : { x: event.x, y: event.y }), windMid = _window.height() >> 1, winWidth = _window.width(), showAbove = point.y < windMid, offsetX = 0, width = 0; if(_data !== data) { _data = data; _node = node; _setData(data); } if(showAbove) { _element.removeClass('below'); _element.addClass('above'); } else { _element.removeClass('above'); _element.addClass('below'); point.y -= _element.height(); } width = _element.width(); offsetX = (width - 11) >> 1; if(point.x - offsetX < 0) { offsetX = point.x - 20; } else if(point.x + offsetX > winWidth) { offsetX = point.x - (winWidth - 10 - width); } _bubble.css({ left: -offsetX }); Ember.run.debounce(Tip, "showTip", 500); _element.css({ left: point.x, top: point.y }); }
javascript
{ "resource": "" }
q43394
report
train
function report(test) { return { test_file: test.file + ': ' + test.fullTitle(), start: test.start, end: test.end, exit_code: test.exit_code, elapsed: test.duration / 1000, error: errorJSON(test.err || {}), url: test.url, status: test.state }; }
javascript
{ "resource": "" }
q43395
writeLogs
train
function writeLogs(test, dirName) { var logs = test.fullTitle() + '\n' + test.file + '\nStart: ' + test.start + '\nEnd: ' + test.end + '\nElapsed: ' + test.duration + '\nStatus: ' + test.state; if (test.state === 'fail') { logs += '\nError: ' + test.err.stack; } mkdirp.sync(testDir(test, dirName)); fs.writeFileSync(testURL(test, dirName), logs); test.url = testURL(test, dirName); }
javascript
{ "resource": "" }
q43396
generateFileName
train
function generateFileName(className) { return className .replace(/component/gi, '') .replace(/system/gi, '') .replace('2D', '2d') .replace('3D', '3d') .replace(/^[A-Z]/, function(c) { return c.toLowerCase(); }) .replace(/[A-Z]/g, function(c) { return '-' + c.toLowerCase(); }) + '.js'; }
javascript
{ "resource": "" }
q43397
train
function(ast, reporter, version) { this.ast = ast; this.reporter = reporter; this.psykickVersion = 'psykick' + version; // Store the Templates so the Systems can access them later this._templatesByName = {}; }
javascript
{ "resource": "" }
q43398
CoreEvent
train
function CoreEvent(typeArg, detail) { if (detail == undefined) { detail = {}; } /** * Error: * Failed to construct 'CustomEvent': Please use the 'new' operator, this * DOM object constructor cannot be called as a function. * * In reason of that the browser did not allow to extend CustomEvent in * common way, we use our event class only as constant holder. */ return new CustomEvent(typeArg, { detail: detail }); }
javascript
{ "resource": "" }
q43399
Ajax
train
function Ajax(method, url, sendData) { DOMEventListener.call(this); /** * Request object. * * @access protected * @type {XMLHttpRequest} */ this._request = new Ajax.XHRSystem(); /** * Method of the request. * * @access protected * @type {String} */ this._method = method; /** * Address of request. * * @access protected * @type {String} */ this._url = url; /** * Data to send. * * @access protected * @type {(Object|String)} */ this._sendData = sendData; /** * The content type of sending data. * * @access public * @type {String} */ this.contentType = "application/binary"; /** * Context conatiner. * @access private */ var self = this; /** * Override onload of XMLHTTPRequest. * Convert callback function into `Event`. */ this._request.onload = function (event) { self.dispatchEvent( new Ajax.Event(Ajax.Event.LOAD, { response: self._request.response, responseText: self._request.responseText, responseType: self._request.responseType, responseURL: self._request.responseURL, responseXML: self._request.responseXML, status: self._request.status, lengthComputable: event.lengthComputable, loaded: event.loaded, total: event.total }) ); }; /** * Override onprogress of XMLHTTPRequest. * Convert callback function into `Event`. */ this._request.onprogress = function (event) { self.dispatchEvent( new Ajax.Event(Ajax.Event.PROGRESS, { lengthComputable: event.lengthComputable, loaded: event.loaded, total: event.total }) ); }; }
javascript
{ "resource": "" }