_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q43400
use
train
function use(fullQualifiedClassName) { var container = use.getContainer(fullQualifiedClassName) ; if (container._loader === null) { use.loadCount++; container._loader = Ajax.factory( "get", container._path + use.fileExtension ); container._loader.addEventListener(Ajax.Event.LOAD, function(event) { var domains , className ; use.loadCount--; // Load into script ram container._class = new Function(event.detail.responseText); // Import into context domains = fullQualifiedClassName.split(use.classPathDelimiter); className = domains.pop(); namespace(domains.join(use.classPathDelimiter), function() { var contextBackup = null , property ; // Save old class name if(this.hasOwnProperty(className)) { contextBackup = this[className]; } // Run loaded code container._class.call(this); // Restore backup if (contextBackup === null) return; if (this[className] !== contextBackup) { for(property in contextBackup) { if(property == className) continue; if(this[className].hasOwnProperty(property)) { throw new Error( "CoreJs: " + "Overlapping namespace with class " + "property '" + fullQualifiedClassName +"."+property +"' detected." ); } else { this[className][property] = contextBackup[property]; } } } }); }); container._loader.addEventListener( Ajax.Event.LOAD, namespace.handleEvent ); container._loader.load(); } }
javascript
{ "resource": "" }
q43401
Client
train
function Client(endpointUrl, sourceId) { this.restClient = new restClient.Client(); this.endpointUrl = endpointUrl; if (this.endpointUrl) { // Remove the trailing slash if necessary if (this.endpointUrl.indexOf('/', this.endpointUrl.length - 1) !== -1) { this.endpointUrl = this.endpointUrl.substr(0, this.endpointUrl.length - 2); } // Add the default version if not present // TODO: The client should take care of the version in a better way if (this.endpointUrl.indexOf('/v1', this.endpointUrl.length - 3) === -1) { this.endpointUrl = this.endpointUrl + '/v1'; } } if (sourceId !== undefined) { this.sourceId = sourceId; } }
javascript
{ "resource": "" }
q43402
processChildren
train
function processChildren(ele, children) { if (children && children.constructor === Array) { for(var i = 0; i < children.length; i++) { processChildren(ele, children[i]); } } else if (children instanceof Node) { ele.appendChild(children); } else if (children) { ele.appendChild(document.createTextNode(children)); } }
javascript
{ "resource": "" }
q43403
getDrives
train
function getDrives() { return getDrivesNow().then(function(drives) { // if new drive events during scan, redo scan if (newEvents) return getDrives(); recordDrives(drives); if (self.options.scanInterval) self.scanTimer = setTimeout(updateDrives, self.options.scanInterval); // return drives array, cloned so not altered by future events return self.drives.slice(0); }); }
javascript
{ "resource": "" }
q43404
getDrivesNow
train
function getDrivesNow() { reading = true; newEvents = false; return fs.readdirAsync(drivesPath) .then(function(files) { var drives = files.filter(function(name) { return name != '.DS_Store'; }); return drives; }); }
javascript
{ "resource": "" }
q43405
onRead
train
function onRead (key) { if (key !== null) { if (cli.debug) console.log('Key:', key) // Exits on CTRL-C if (key === '\u0003') process.exit() // If enter is pressed and the program is waiting for the user to press enter // so that the emulator can step forward, then call the appropriate callback if (key.charCodeAt(0) === 13 && readingFn() && onReadCb) onReadCb(key.charCodeAt(0)) else if (cpu) { // Since the CPU is initialized and the program is not waiting for the user // to press enter, pass the pressed key to the LC-2 CPU Console. cpu.console.input(key) } readingFn(false) } }
javascript
{ "resource": "" }
q43406
end
train
function end () { console.log('\n=== REG DUMP ===\n' + cpu.regdump().join('\n')) if (options.memDump) console.log('\n\n=== MEM DUMP ===\n' + cpu.memdump(0, 65535).join('\n')) process.exit() // workaround for stdin event listener hanging }
javascript
{ "resource": "" }
q43407
processSimple
train
function processSimple( names, current, stopAt, collector, done ) { const name = names[current]; File.stat( Path.join( "node_modules", name, "hitchy.json" ), ( error, stat ) => { if ( error ) { if ( error.code === "ENOENT" ) { collector.push( name ); } else { done( error ); return; } } else if ( stat.isFile() ) { if ( !quiet ) { console.error( `${name} ... found` ); } } else { done( new Error( `dependency ${name}: not a folder` ) ); return; } if ( ++current < stopAt ) { processSimple( names, current, stopAt, collector, done ); } else { done( null, collector ); } } ); }
javascript
{ "resource": "" }
q43408
installMissing
train
function installMissing( error, collected ) { if ( error ) { console.error( `checking dependencies failed: ${error.message}` ); process.exit( 1 ); return; } if ( collected.length < 1 ) { postProcess( 0 ); } else { if ( !quiet ) { console.error( `installing missing dependencies:\n${collected.map( d => `* ${d}`).join( "\n" )}` ); } const npm = Child.exec( `npm install --no-save ${collected.join( " " )}`, { stdio: "pipe", } ); npm.stdout.pipe( process.stdout ); npm.stderr.pipe( process.stderr ); npm.on( "exit", postProcess ); } }
javascript
{ "resource": "" }
q43409
postProcess
train
function postProcess( errorCode ) { if ( errorCode ) { console.error( `running npm for installing missing dependencies ${collected.join( ", " )} exited on error (${errorCode})` ); } else if ( exec ) { const cmd = exec.join( " " ); if ( !quiet ) { console.error( `invoking follow-up command: ${cmd}` ); } const followup = Child.exec( cmd ); followup.stdout.pipe( process.stdout ); followup.stderr.pipe( process.stderr ); followup.on( "exit", code => { process.exit( code ); } ); return; } process.exit( errorCode ); }
javascript
{ "resource": "" }
q43410
train
function (fn) { var hasOK = (typeof btnOK !== "undefined"), hasCancel = (typeof btnCancel !== "undefined"), hasInput = (typeof input !== "undefined"), val = "", self = this, ok, cancel, common, key, reset; // ok event handler ok = function (event) { if (typeof event.preventDefault !== "undefined") event.preventDefault(); common(event); if (typeof input !== "undefined") val = input.value; if (typeof fn === "function") { if (typeof input !== "undefined") { fn(true, val); } else fn(true); } return false; }; // cancel event handler cancel = function (event) { if (typeof event.preventDefault !== "undefined") event.preventDefault(); common(event); if (typeof fn === "function") fn(false); return false; }; // common event handler (keyup, ok and cancel) common = function (event) { self.hide(); self.unbind(document.body, "keyup", key); self.unbind(btnReset, "focus", reset); if (hasInput) self.unbind(form, "submit", ok); if (hasOK) self.unbind(btnOK, "click", ok); if (hasCancel) self.unbind(btnCancel, "click", cancel); }; // keyup handler key = function (event) { var keyCode = event.keyCode; if (keyCode === keys.SPACE && !hasInput) ok(event); if (keyCode === keys.ESC && hasCancel) cancel(event); }; // reset focus to first item in the dialog reset = function (event) { if (hasInput) input.focus(); else if (!hasCancel || self.buttonReverse) btnOK.focus(); else btnCancel.focus(); }; // handle reset focus link // this ensures that the keyboard focus does not // ever leave the dialog box until an action has // been taken this.bind(btnReset, "focus", reset); // handle OK click if (hasOK) this.bind(btnOK, "click", ok); // handle Cancel click if (hasCancel) this.bind(btnCancel, "click", cancel); // listen for keys, Cancel => ESC this.bind(document.body, "keyup", key); // bind form submit if (hasInput) this.bind(form, "submit", ok); if (!this.transition.supported) { this.setFocus(); } }
javascript
{ "resource": "" }
q43411
train
function (item) { var html = "", type = item.type, message = item.message, css = item.cssClass || ""; html += "<div class=\"alertify-dialog\">"; if (_alertify.buttonFocus === "none") html += "<a href=\"#\" id=\"alertify-noneFocus\" class=\"alertify-hidden\"></a>"; if (type === "prompt") html += "<form id=\"alertify-form\">"; html += "<article class=\"alertify-inner\">"; html += dialogs.message.replace("{{message}}", message); if (type === "prompt") html += dialogs.input; html += dialogs.buttons.holder; html += "</article>"; if (type === "prompt") html += "</form>"; html += "<a id=\"alertify-resetFocus\" class=\"alertify-resetFocus\" href=\"#\">Reset Focus</a>"; html += "</div>"; switch (type) { case "confirm": html = html.replace("{{buttons}}", this.appendButtons(dialogs.buttons.cancel, dialogs.buttons.ok)); html = html.replace("{{ok}}", this.labels.ok).replace("{{cancel}}", this.labels.cancel); break; case "prompt": html = html.replace("{{buttons}}", this.appendButtons(dialogs.buttons.cancel, dialogs.buttons.submit)); html = html.replace("{{ok}}", this.labels.ok).replace("{{cancel}}", this.labels.cancel); break; case "alert": html = html.replace("{{buttons}}", dialogs.buttons.ok); html = html.replace("{{ok}}", this.labels.ok); break; default: break; } elDialog.className = "alertify alertify-" + type + " " + css; elCover.className = "alertify-cover"; return html; }
javascript
{ "resource": "" }
q43412
train
function (elem, wait) { // Unary Plus: +"2" === 2 var timer = (wait && !isNaN(wait)) ? +wait : this.delay, self = this, hideElement, transitionDone; // set click event on log messages this.bind(elem, "click", function () { hideElement(elem); }); // Hide the dialog box after transition // This ensure it doens't block any element from being clicked transitionDone = function (event) { event.stopPropagation(); // unbind event so function only gets called once self.unbind(this, self.transition.type, transitionDone); // remove log message elLog.removeChild(this); if (!elLog.hasChildNodes()) elLog.className += " alertify-logs-hidden"; }; // this sets the hide class to transition out // or removes the child if css transitions aren't supported hideElement = function (el) { // ensure element exists if (typeof el !== "undefined" && el.parentNode === elLog) { // whether CSS transition exists if (self.transition.supported) { self.bind(el, self.transition.type, transitionDone); el.className += " alertify-log-hide"; } else { elLog.removeChild(el); if (!elLog.hasChildNodes()) elLog.className += " alertify-logs-hidden"; } } }; // never close (until click) if wait is set to 0 if (wait === 0) return; // set timeout to auto close the log message setTimeout(function () { hideElement(elem); }, timer); }
javascript
{ "resource": "" }
q43413
train
function (message, type, fn, placeholder, cssClass) { // set the current active element // this allows the keyboard focus to be resetted // after the dialog box is closed elCallee = document.activeElement; // check to ensure the alertify dialog element // has been successfully created var check = function () { if ((elLog && elLog.scrollTop !== null) && (elCover && elCover.scrollTop !== null)) return; else check(); }; // error catching if (typeof message !== "string") throw new Error("message must be a string"); if (typeof type !== "string") throw new Error("type must be a string"); if (typeof fn !== "undefined" && typeof fn !== "function") throw new Error("fn must be a function"); // initialize alertify if it hasn't already been done if (typeof this.init === "function") { this.init(); check(); } queue.push({ type: type, message: message, callback: fn, placeholder: placeholder, cssClass: cssClass }); if (!isopen) this.setup(); return this; }
javascript
{ "resource": "" }
q43414
train
function () { var transitionDone, self = this; // remove reference from queue queue.splice(0,1); // if items remaining in the queue if (queue.length > 0) this.setup(true); else { isopen = false; // Hide the dialog box after transition // This ensure it doens't block any element from being clicked transitionDone = function (event) { event.stopPropagation(); elDialog.className += " alertify-isHidden"; // unbind event so function only gets called once self.unbind(elDialog, self.transition.type, transitionDone); }; // whether CSS transition exists if (this.transition.supported) { this.bind(elDialog, this.transition.type, transitionDone); elDialog.className = "alertify alertify-hide alertify-hidden"; } else { elDialog.className = "alertify alertify-hide alertify-hidden alertify-isHidden"; } elCover.className = "alertify-cover alertify-cover-hidden"; // set focus to the last element or body // after the dialog is closed elCallee.focus(); } }
javascript
{ "resource": "" }
q43415
train
function () { // ensure legacy browsers support html5 tags document.createElement("nav"); document.createElement("article"); document.createElement("section"); // cover elCover = document.createElement("div"); elCover.setAttribute("id", "alertify-cover"); elCover.className = "alertify-cover alertify-cover-hidden"; document.body.appendChild(elCover); // main element elDialog = document.createElement("section"); elDialog.setAttribute("id", "alertify"); elDialog.className = "alertify alertify-hidden"; document.body.appendChild(elDialog); // log element elLog = document.createElement("section"); elLog.setAttribute("id", "alertify-logs"); elLog.className = "alertify-logs alertify-logs-hidden"; document.body.appendChild(elLog); // set tabindex attribute on body element // this allows script to give it focus // after the dialog is closed document.body.setAttribute("tabindex", "0"); // set transition type this.transition = getTransitionEvent(); // clean up init method delete this.init; }
javascript
{ "resource": "" }
q43416
train
function (message, type, wait) { // check to ensure the alertify dialog element // has been successfully created var check = function () { if (elLog && elLog.scrollTop !== null) return; else check(); }; // initialize alertify if it hasn't already been done if (typeof this.init === "function") { this.init(); check(); } elLog.className = "alertify-logs"; this.notify(message, type, wait); return this; }
javascript
{ "resource": "" }
q43417
train
function (fromQueue) { var item = queue[0], self = this, transitionDone; // dialog is open isopen = true; // Set button focus after transition transitionDone = function (event) { event.stopPropagation(); self.setFocus(); // unbind event so function only gets called once self.unbind(elDialog, self.transition.type, transitionDone); }; // whether CSS transition exists if (this.transition.supported && !fromQueue) { this.bind(elDialog, this.transition.type, transitionDone); } // build the proper dialog HTML elDialog.innerHTML = this.build(item); // assign all the common elements btnReset = $("alertify-resetFocus"); btnOK = $("alertify-ok") || undefined; btnCancel = $("alertify-cancel") || undefined; btnFocus = (_alertify.buttonFocus === "cancel") ? btnCancel : ((_alertify.buttonFocus === "none") ? $("alertify-noneFocus") : btnOK), input = $("alertify-text") || undefined; form = $("alertify-form") || undefined; // add placeholder value to the input field if (typeof item.placeholder === "string" && item.placeholder !== "") input.value = item.placeholder; if (fromQueue) this.setFocus(); this.addListeners(item.callback); }
javascript
{ "resource": "" }
q43418
train
function (el, event, fn) { if (typeof el.removeEventListener === "function") { el.removeEventListener(event, fn, false); } else if (el.detachEvent) { el.detachEvent("on" + event, fn); } }
javascript
{ "resource": "" }
q43419
output
train
function output(sourceCode, filePath) { return new Promise(function (resolve, reject) { mkdirp(path.dirname(filePath), function (ioErr) { if (ioErr) { reject(ioErr); throw ioErr; } fs.writeFile(filePath, sourceCode, function (writeErr) { if (writeErr) { reject(writeErr); throw writeErr; } resolve(); }); }); }); }
javascript
{ "resource": "" }
q43420
ValueTemplate
train
function ValueTemplate(type, defaultValue, validator){ this.type = type; this.defaultValue = defaultValue; this.validator = validator; }
javascript
{ "resource": "" }
q43421
PropertyTemplate
train
function PropertyTemplate(name, required, nullable, template){ this.name = name; this.required = required; this.nullable = nullable; this.template = template; }
javascript
{ "resource": "" }
q43422
getByFirstImage
train
function getByFirstImage(file, attributes) { var $ = cheerio.load(file.contents.toString()), img = $('img').first(), obj = {}; if (img.length) { _.forEach(attributes, function(attribute) { obj[attribute] = img.attr(attribute); }); return obj; } else { return undefined; } }
javascript
{ "resource": "" }
q43423
train
function ( name, socket ) { var self = this; // check input if ( name && socket ) { log('ws', 'init', name, 'connection'); // main data structure pool[name] = { socket: socket, time: +new Date(), count: 0, active: true }; // disable link on close pool[name].socket.on('close', function () { self.remove(name); }); // await for an answer pool[name].socket.on('message', function ( message ) { // has link to talk back if ( pool[name].response ) { log('ws', 'get', name, message); pool[name].response.end(message); } }); return true; } // failure log('ws', 'init', name, 'fail to connect (wrong name or link)'); return false; }
javascript
{ "resource": "" }
q43424
train
function ( name ) { // valid connection if ( name in pool ) { log('ws', 'exit', name, 'close'); return delete pool[name]; } // failure log('ws', 'del', name, 'fail to remove (invalid connection)'); return false; }
javascript
{ "resource": "" }
q43425
train
function ( name ) { // valid connection if ( name in pool ) { return { active: pool[name].active, count: pool[name].count }; } // failure return {active: false}; }
javascript
{ "resource": "" }
q43426
train
function ( name, data, response ) { log('ws', 'send', name, data); // store link to talk back when ready pool[name].response = response; // actual post pool[name].socket.send(data); pool[name].count++; }
javascript
{ "resource": "" }
q43427
train
function(req, res) { if (res.locals.success) { options.success(model, response); } else { options.error(model, response); } }
javascript
{ "resource": "" }
q43428
train
function(s){ var currentState = history[historyIndex]; if(typeof s === 'function'){ s = s( history[historyIndex].toJS() ); } var newState = currentState.merge(s); history = history.slice(0,historyIndex + 1); history.push(newState); historyIndex++; return new Immutable.Map(history[historyIndex]).toJS(); }
javascript
{ "resource": "" }
q43429
train
function( name ) { var type = _.reduce( name.split('.'), function( memo, val ) { return memo[ val ]; }, exports); return type !== exports ? type: null; }
javascript
{ "resource": "" }
q43430
train
function( model ) { var coll = this.getCollection( model ); coll._onModelEvent( 'change:' + model.idAttribute, model, coll ); }
javascript
{ "resource": "" }
q43431
train
function() { Backbone.Relational.store.getCollection( this.instance ) .unbind( 'relational:remove', this._modelRemovedFromCollection ); Backbone.Relational.store.getCollection( this.relatedModel ) .unbind( 'relational:add', this._relatedModelAdded ) .unbind( 'relational:remove', this._relatedModelRemoved ); _.each( this.getReverseRelations(), function( relation ) { relation.removeRelated( this.instance ); }, this ); }
javascript
{ "resource": "" }
q43432
proxyVerifyCallback
train
function proxyVerifyCallback (fn, args, done) { const {callback, index} = findCallback(args); args[index] = function (err, user) { done(err, user, callback); }; fn.apply(null, args); }
javascript
{ "resource": "" }
q43433
SetOrGet
train
function SetOrGet(input, field, def) { return input[field] = Deffy(input[field], def); }
javascript
{ "resource": "" }
q43434
proxyEvent
train
function proxyEvent (emitter, event, optionalCallback) { emitter.on(event, function () { if (optionalCallback) { optionalCallback.apply(client, arguments) } client.emit(event) }) }
javascript
{ "resource": "" }
q43435
train
function(parent, app) { this.use(middleware.sanitizeHost(app)); this.use(middleware.bodyParser()); this.use(middleware.cookieParser()); this.use(middleware.fragmentRedirect()); }
javascript
{ "resource": "" }
q43436
Scope
train
function Scope(site, page, params) { this.site = site this.page = page this.params = params || {} this.status = 200 this._headers = {} this.locale = site.locales.default // Set default headers. this.header("Content-Type", "text/html; charset=utf-8") this.header("Connection", "close") this.header("Server", "Skira") }
javascript
{ "resource": "" }
q43437
train
function( option ) { if ( this._self === option.exporter ) { return; } if ( this._action && !this._action.test( option.action ) ) { return; } if ( this._path && !this._path.test( option.path ) ) { return; } if ( this._notePath || this._noteAction ) { if ( !(option instanceof EventPicker) || option.Test( this ) ) { return; } } utilTick( this._self, this._listen, option, this._async ); }
javascript
{ "resource": "" }
q43438
glupost
train
function glupost(configuration) { const tasks = configuration.tasks || {} const template = configuration.template || {} // Expand template object with defaults. expand(template, { transforms: [], dest: "." }) // Create tasks. const names = Object.keys(tasks) for (const name of names) { const task = retrieve(tasks, name) if (typeof task === "object") expand(task, template) gulp.task(name, compose(task)) } watch(tasks) }
javascript
{ "resource": "" }
q43439
compose
train
function compose(task) { // Already composed action. if (task.action) return task.action // 1. named task. if (typeof task === "string") return task // 2. a function directly. if (typeof task === "function") return task.length ? task : () => Promise.resolve(task()) // 3. task object. if (typeof task !== "object") throw new Error("A task must be a string, function, or object.") if (task.watch === true) { // Watching task without a valid path. if (!task.src) throw new Error("No path given to watch.") task.watch = task.src } let transform if (task.src) transform = () => pipify(task) // No transform function and no series/parallel. if (!transform && !task.series && !task.parallel) throw new Error("A task must do something.") // Both series and parallel. if (task.series && task.parallel) throw new Error("A task can't have both .series and .parallel properties.") // Only transform function. if (!task.series && !task.parallel) { task.action = transform } // Series/parallel sequence of tasks. else { const sequence = task.series ? "series" : "parallel" if (transform) task[sequence].push(transform) task.action = gulp[sequence](...task[sequence].map(compose)) } return task.action }
javascript
{ "resource": "" }
q43440
pipify
train
function pipify(task) { const options = task.base ? { base: task.base } : {} let stream = gulp.src(task.src, options) // This is used to abort any further transforms in case of error. const state = { error: false } for (const transform of task.transforms) stream = stream.pipe(transform.pipe ? transform : pluginate(transform, state)) if (task.rename) stream = stream.pipe(rename(task.rename)) if (task.dest) stream = stream.pipe(gulp.dest(task.dest)) return stream }
javascript
{ "resource": "" }
q43441
pluginate
train
function pluginate(transform, state) { return through.obj((file, encoding, done) => { // Nothing to transform. if (file.isNull() || state.error) { done(null, file) return } // Transform function returns a vinyl file or file contents (in form of a // stream, a buffer or a string), or a promise which resolves with those. new Promise((resolve, reject) => { try { resolve(transform(file.contents, file)) } catch (e) { reject(e) } }).then((result) => { if (!Vinyl.isVinyl(result)) { if (result instanceof Buffer) file.contents = result else if (typeof result === "string") file.contents = Buffer.from(result) else throw new Error("Transforms must return/resolve with a file, a buffer or a string.") } }).catch((e) => { console.error(e) state.error = true }).then(() => { done(null, file) }) }) }
javascript
{ "resource": "" }
q43442
watch
train
function watch(tasks) { if (tasks["watch"]) { console.warn("`watch` task redefined.") return } const names = Object.keys(tasks).filter((name) => tasks[name].watch) if (!names.length) return gulp.task("watch", () => { for (const name of names) { const glob = tasks[name].watch const watcher = gulp.watch(glob, gulp.task(name)) watcher.on("change", (path) => console.log(`${timestamp()} '${path}' was changed, running tasks...`)) } }) }
javascript
{ "resource": "" }
q43443
expand
train
function expand(to, from) { const keys = Object.keys(from) for (const key of keys) { if (!to.hasOwnProperty(key)) to[key] = from[key] } }
javascript
{ "resource": "" }
q43444
HostMapping
train
function HostMapping(settings) { settings.init("hostConfig", {}); settings.init("hostMapping", {}); settings.init("xdmConfig", {}); this.settings = settings; }
javascript
{ "resource": "" }
q43445
decorateWithCollation
train
function decorateWithCollation(command, target, options) { const topology = target.s && target.s.topology; if (!topology) { throw new TypeError('parameter "target" is missing a topology'); } const capabilities = target.s.topology.capabilities(); if (options.collation && typeof options.collation === 'object') { if (capabilities && capabilities.commandsTakeCollation) { command.collation = options.collation; } else { throw new MongoError(`server ${topology.s.coreTopology.name} does not support collation`); } } }
javascript
{ "resource": "" }
q43446
train
function(fn) { // Save off the existing spy method as __functionName var newName = '__' + fn; self[newName] = self[fn]; // This is the actual function that will be called when, // for example, calledWith() is invoked return function() { var func = self[newName]; // If this thing is a function, invoke it with all arguments; // otherwise, just grab the value of the property. var val = typeof func === 'function' ? func.apply(condition, arguments) : func; // Negate and return return !val; }; }
javascript
{ "resource": "" }
q43447
train
function (decorator, txt) { var decostr = "@" + decorator; var r = txt .replace(decostr, "") .trim() ; if (debug) console.log(`Cleaning deco: ${decorator} in ${txt} Result: ${r} `); return r; }
javascript
{ "resource": "" }
q43448
extractDecorator2
train
function extractDecorator2(text) { try { var email = text.match(reSTCDeco); // console.log("DEBUG: reSTCDeco:" + email); var deco = email[0].split('@')[1]; return deco; } catch (error) { return ""; } // return text.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi); }
javascript
{ "resource": "" }
q43449
train
function (err, req, res, next) { if (seminarjs.get('logger')) { if (err instanceof Error) { console.log((err.type ? err.type + ' ' : '') + 'Error thrown for request: ' + req.url); } else { console.log('Error thrown for request: ' + req.url); } console.log(err.stack || err); } var msg = ''; if (seminarjs.get('env') === 'development') { if (err instanceof Error) { if (err.type) { msg += '<h2>' + err.type + '</h2>'; } msg += utils.textToHTML(err.message); } else if ('object' === typeof err) { msg += '<code>' + JSON.stringify(err) + '</code>'; } else if (err) { msg += err; } } res.status(500).send(seminarjs.wrapHTMLError('Sorry, an error occurred loading the page (500)', msg)); }
javascript
{ "resource": "" }
q43450
Mutant
train
function Mutant(obj) { var triggered, i = 0; mutations = {}; if (!obj.addEventListener) { obj = EventTarget(obj); } function trigger() { i++; if (triggered) return; triggered = setTimeout(function() { var evt = new MutationEvent(mutations, i); triggered = null; mutations = {}; i = 0; obj.dispatchEvent(evt); }, 0); } return new Proxy(obj, { deleteProperty: function(target, property) { if (property in target) { if (!(property in mutations)) { mutations[property] = target[property]; } delete target[property]; trigger(); } return true; }, defineProperty: function(target, property, descriptor) { var value = target[property]; Object.defineProperty(target, property, descriptor); if (!(property in mutations)) { if (target[property] !== value) { mutations[property] = value; trigger(); } } }, set: function(target, property, value, receiver) { if (value !== target[property]) { if (!(property in mutations)) { mutations[property] = target[property]; } target[property] = value; trigger(); } } }); }
javascript
{ "resource": "" }
q43451
mutant
train
function mutant(obj) { if (!proxies.has(obj)) { proxies.set(obj, Mutant(obj)); } return proxies.get(obj); }
javascript
{ "resource": "" }
q43452
ask
train
function ask(question, validValues, message) { readline.setDefaultOptions({ limit: validValues, limitMessage: message }); return readline.question(question); }
javascript
{ "resource": "" }
q43453
color
train
function color(c, bold, msg) { return bold ? clic.xterm(c).bold(msg) : clic.xterm(c)(msg); }
javascript
{ "resource": "" }
q43454
renderState
train
function renderState(env, stateDir, nav, componentData, state) { const statePath = Path.join(stateDir, 'index.html'); const raw = env.render('component-raw.html', { navigation: nav, component: componentData, state: state, config: config, tokens: getTokens(), }); mkdirp.sync(stateDir); fs.writeFileSync(statePath, raw, 'utf-8'); }
javascript
{ "resource": "" }
q43455
renderDocs
train
function renderDocs(SITE_DIR, name) { const env = templates.configure(); const nav = navigation.getNavigation(); const components = _.find(nav.children, { id: name }); components.children.forEach(component => { const dirPath = Path.join(SITE_DIR, component.path); console.log(dirPath); const htmlPath = Path.join(dirPath, 'index.html'); const rawDir = Path.join(SITE_DIR, 'raw', component.id); const componentData = findComponent(component.id); componentData.template = pathTrimStart( Path.join(component.path, `${component.id}.html`), ); const html = env.render('component.html', { navigation: nav, component: componentData, config: config, tokens: getTokens(), }); mkdirp.sync(rawDir); mkdirp.sync(dirPath); fs.writeFileSync(htmlPath, html, 'utf-8'); if (componentData.flavours) { componentData.flavours.forEach(flavour => { if (flavour.states) { flavour.states.forEach(variant => { const state = getStateFromFlavour( componentData, flavour.id, variant.id, ); const stateDir = Path.join( rawDir, flavour.id, variant.id, ); renderState(env, stateDir, nav, componentData, state); }); } if (flavour.state) { const stateDir = Path.join(rawDir, flavour.id); renderState( env, stateDir, nav, componentData, flavour.state, ); } }); } }); }
javascript
{ "resource": "" }
q43456
train
function( string ) { var negated, matches, patterns = this.patterns, i = patterns.length; while ( i-- ) { negated = patterns[ i ].negated; matches = patterns[ i ].matcher( string ); if ( negated !== matches ) { return matches; } } return false; }
javascript
{ "resource": "" }
q43457
find
train
function find(param) { var fn, asInt = parseInt(param, 10); fn = isNaN(asInt) ? findByUsername : findById; fn.apply(null, arguments); }
javascript
{ "resource": "" }
q43458
findByCredentials
train
function findByCredentials(username, password, cb) { crypto.encode(password, function(err, encoded) { if(err) { return cb(err); } db.getClient(function(err, client, done) { client.query(SELECT_CREDENTIALS, [username, encoded], function(err, r) { var result = r && r.rows[0]; if(!err && !result) { err = new exceptions.AuthenticationFailed(); } if(err) { cb(err); done(err); } else { cb(null, result); done(); } }); }); }); }
javascript
{ "resource": "" }
q43459
findByUsername
train
function findByUsername(username, cb) { db.getClient(function(err, client, done) { client.query(SELECT_USERNAME, [username], 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": "" }
q43460
update
train
function update(id, body, cb) { if(body.password) { crypto.encode(body.password, function(err, encoded) { if(err) { return cb(err); } body.password = encoded; _update(id, body, cb); }); } else { _update(id, body, cb); } }
javascript
{ "resource": "" }
q43461
createPlaceHolder
train
function createPlaceHolder($page, type) { var placeHolders = { kittens : 'placekitten.com', bears: 'placebear.com', lorem: 'lorempixel.com', bacon: 'baconmockup.com', murray: 'www.fillmurray.com'}; var gallery = ''; for (var i = 0; i < getRandomInt(50,100); i++) { gallery += '<li class="photoClass" style="background:url(http://' + placeHolders[type] + '/' + getRandomInt(200,300) + '/' + getRandomInt(200,300) + ') 50% 50% no-repeat"></li>'; } $page.find('.photo-gallery').html(gallery); tt.refreshScroll(); // Refresh the scroller tt.scrollTo(0,0); // Move back to the top of the page... }
javascript
{ "resource": "" }
q43462
addToJSONRecursively
train
function addToJSONRecursively(contextNames, data, obj) { var currentContexName = contextNames.shift(); // last name if (!contextNames.length) { obj[currentContexName] = data; return; } if (!obj[currentContexName]) { obj[currentContexName] = {}; } addToJSONRecursively(contextNames, data, obj[currentContexName]); }
javascript
{ "resource": "" }
q43463
propertyToString
train
function propertyToString(property) { return property.comment + utils.addQuotes(property.name.split('.').pop()) + ': ' + ( typeof options.sourceProcessor === 'function' ? options.sourceProcessor(property.source, property) : property.source ); }
javascript
{ "resource": "" }
q43464
stringifyJSONProperties
train
function stringifyJSONProperties(obj) { var i, properties = []; for (i in obj) { properties.push( typeof obj[i] === 'string' ? obj[i] : utils.addQuotes(i) + ': ' + stringifyJSONProperties(obj[i]) ); } return '{\n' + properties.join(',\n\n') + '\n}'; }
javascript
{ "resource": "" }
q43465
addPropertiesToText
train
function addPropertiesToText(text, properties, filePath) { if (!properties.length) { return text; } var placeRegexp = patterns.getPlacePattern(properties[0].isFromPrototype), matchedData = placeRegexp.exec(text); // Can`t find properties place if (!matchedData) { grunt.log.error("No " + (properties[0].isFromPrototype ? "prototype" : "inline") + " properties place definition at " + filePath + ' (properties: ' + properties.map(function (p) {return p.name + ' at ' + p.filePath; }).join(', ') + ')'); return text; } // don`t use .replace with "$" at replacement text return text.replace(placeRegexp, function () { return (matchedData[1] ? matchedData[1] + ',' : '') + ('\n\n' + concatProperties(properties)) .replace(/\n(?!\r?\n)/g, '\n' + matchedData[2]); }); }
javascript
{ "resource": "" }
q43466
areArrays
train
function areArrays () { for (let i = 0; i < arguments.length; i++) { if (!Array.isArray(arguments[i])) { return false; } } return true; }
javascript
{ "resource": "" }
q43467
deepDiff
train
function deepDiff(obj1, obj2, path) { return merge_1(_deepDiff(obj1, obj2, path), _deepDiff(obj2, obj1, path)); }
javascript
{ "resource": "" }
q43468
checkFunctions
train
function checkFunctions (impl, schema) { const children = schema.describe().children const ret = { ok: true } for (let i in children) { if (impl.hasOwnProperty(i) && children.hasOwnProperty(i)) { if (children[ i ].flags && children[ i ].flags.func === true) { const func = impl[ i ] const funcSig = utils.parseFuncSig(func) let expectedArgs if (children[ i ].meta) { expectedArgs = children[ i ].meta[ 0 ].args if (!sameArray(funcSig, expectedArgs)) { ret.ok = false ret.message = errors.invalidSignature(i, expectedArgs, funcSig) } if (funcSig.length !== expectedArgs.length) { ret.ok = false ret.message = errors .unexpectedArgsLength(i, expectedArgs.length, funcSig.length) } } else { if (typeof impl[ i ] !== 'function') { ret.ok = false ret.message = `Property '${i}' is not a function!` } } if (!ret.ok) { return ret } } } } return ret }
javascript
{ "resource": "" }
q43469
_dot_inner
train
function _dot_inner(elem, make_digraph, names) { var builder = []; var name = hash_name_get(elem, names); // Only push graphs/clusters for chains if (elem instanceof fl.ChainBase) { if (make_digraph) builder.push('digraph '+name+' {'); else builder.push('subgraph cluster_'+name+' {'); builder.push('label = '+name+';'); // Get the graph content for this chain, then add it var nest = get_chain_content(elem, names); Array.prototype.push.apply(builder, nest[0]); var chain_entry = nest[1]; var chain_exit = nest[2]; // Also insert special header node to indicate entry if (make_digraph) { var header = hash_name_get({name : 'Global Start'}, names); builder.push(header+' [shape=doublecircle];'); builder.push(header+' -> '+chain_entry+';'); builder.push(chain_exit+' [shape=doublecircle];'); } builder.push('}'); return [builder, chain_entry, chain_exit]; } else { // Just a normal function, return it in our results return [[], name, name]; } }
javascript
{ "resource": "" }
q43470
get_chain_content
train
function get_chain_content(elem, names) { if (elem instanceof fl.Branch) { return handle_branch(elem, names); } else if (elem instanceof fl.ParallelChain) { return handle_parallel(elem, names); } else if (elem instanceof fl.LoopChain) { return handle_loop(elem, names); } else if (elem instanceof fl.Chain) { return handle_chain(elem, names); } else { // A chain type we don't handle yet...shouldn't happen hopefully return [[], hash_name_get({name : 'unidentified'}), hash_name_get({name : 'unidentified'})]; } }
javascript
{ "resource": "" }
q43471
handle_branch
train
function handle_branch(elem, names) { var cond = _dot_inner(elem.cond.fn, false, names); var if_true = _dot_inner(elem.if_true.fn, false, names); var if_false = _dot_inner(elem.if_false.fn, false, names); var terminator = hash_name_get({name : 'branch_end'}, names); var builder = []; Array.prototype.push.apply(builder, cond[0]); Array.prototype.push.apply(builder, if_true[0]); Array.prototype.push.apply(builder, if_false[0]); builder.push(cond[2]+' [shape=Mdiamond];'); builder.push(cond[2]+' -> '+if_true[1]+' [label = true];'); builder.push(cond[2]+' -> '+if_false[1]+' [label = false];'); builder.push(if_true[2]+' -> '+terminator+';'); builder.push(if_false[2]+' -> '+terminator+';'); builder.push(terminator+' [shape=octagon];'); return [builder, cond[1], terminator]; }
javascript
{ "resource": "" }
q43472
handle_parallel
train
function handle_parallel(elem, names) { var phead = hash_name_get({name : 'parallel_head'}, names); var ptail = hash_name_get({name : 'parallel_tail'}, names); var node; var builder = []; for (var i = 0; i < elem.fns.length; ++i) { node = _dot_inner(elem.fns[i].fn, false, names); Array.prototype.push.apply(builder, node[0]); builder.push(phead+' -> '+node[1]+';'); builder.push(node[2]+' -> '+ptail+';'); } builder.push(phead+' [shape=house];'); builder.push(ptail+' [shape=invhouse];'); return [builder, phead, ptail]; }
javascript
{ "resource": "" }
q43473
handle_loop
train
function handle_loop(elem, names) { var cond = _dot_inner(elem.cond.fn, false, names); var node1 = _dot_inner(elem.fns[0].fn, false, names); var builder = []; var node2 = node1; Array.prototype.push.apply(builder, cond[0]); Array.prototype.push.apply(builder, node1[0]); builder.push(cond[2]+' [shape=Mdiamond];'); builder.push(cond[2]+' -> '+node1[1]+' [label = true];'); for (var i = 1; i < elem.fns.length; ++i) { node2 = _dot_inner(elem.fns[i].fn, false, names); Array.prototype.push.apply(builder, node2[0]); builder.push(node1[2]+' -> '+node2[1]+';'); node1 = node2; } builder.push(node2[2]+' -> '+cond[1]+';'); return [builder, cond[1], cond[2]]; }
javascript
{ "resource": "" }
q43474
handle_chain
train
function handle_chain(elem, names) { // Make sure the chain does something if (elem.fns.length === 0) { return [[], hash_name_get({name : '__empty__'}), hash_name_get({name : '__empty__'})]; } var builder = []; var node1 = _dot_inner(elem.fns[0].fn, false, names); var first = node1; var node2; for (var i = 1; i < elem.fns.length; ++i) { Array.prototype.push.apply(builder, node1[0]); node2 = _dot_inner(elem.fns[i].fn, false, names); builder.push(node1[2]+' -> '+node2[1]+';'); node1 = node2; } Array.prototype.push.apply(builder, node1[0]); return [builder, first[1], node2[2]]; }
javascript
{ "resource": "" }
q43475
hash_name_get
train
function hash_name_get(elem, names) { var fname; if (elem.fn !== undefined) fname = format_name(helpers.fname(elem, elem.fn.name)); else fname = format_name(elem.name); var list = names[fname]; // First unique instance of a function gets to use its proper name if (list === undefined) { names[fname] = [{fn : elem, name : fname, count : 0}]; return fname; } // Search the linear chain for our element for (var i = 0; i < list.length; ++i) { if (list[i].fn === elem) { list[i].count += 1; return list[i].name+'__'+list[i].count; } } // Not in the list yet, add it with a unique name index fname = fname+'_'+list.length; list.push({fn : elem, name : fname, count : 0}); return fname; }
javascript
{ "resource": "" }
q43476
polylock
train
function polylock (params) { if (params === undefined) params = {}; this.queue = new polylock_ll(); this.ex_locks = {}; this.ex_reserved = {}; this.sh_locks = {}; this.op_num = 1; this.drain_for_writes = params.write_priority ? true : false; }
javascript
{ "resource": "" }
q43477
train
function (editor, message, callback) { var rng = editor.selection.getRng(); Delay.setEditorTimeout(editor, function () { editor.windowManager.confirm(message, function (state) { editor.selection.setRng(rng); callback(state); }); }); }
javascript
{ "resource": "" }
q43478
gruntYakTask
train
function gruntYakTask(grunt) { 'use strict'; /** * @type {!Array<string>} */ let filesToUpload = []; /** * @type {RequestSender} */ let requestSender; /** * Register task for grunt. */ grunt.registerMultiTask('yakjs', 'A grunt task to update the YAKjs via rest API.', function task() { /** * This tasks sends several http request asynchronous. * So let's get the done callback from the task runner. */ let done = this.async(); /** * @type {!TaskOptions} */ let options = this.options(new TaskOptions()); filesToUpload = []; this.files.forEach(file => { filesToUpload = filesToUpload.concat(file.src); }); let logger = { log: grunt.log.writeln, error: grunt.log.error }; uploadFiles(filesToUpload, options, logger) .then(() => { grunt.log.writeln(''); grunt.log.ok('All files uploaded.'); }) .then(() => { return clearModuleCache(options, logger); }) .then(() => { return startInstances(options, logger); }) .then(done) .catch((message, error) => { grunt.log.writeln(''); grunt.log.error(JSON.stringify(message, null, 4)); grunt.fatal('One or more files could not be uploaded.'); done(); }); }); }
javascript
{ "resource": "" }
q43479
request
train
function request (reqOptions, data) { const t = require('typical') if (!reqOptions) return Promise.reject(Error('need a URL or request options object')) if (t.isString(reqOptions)) { const urlUtils = require('url') reqOptions = urlUtils.parse(reqOptions) } else { reqOptions = Object.assign({ headers: {} }, reqOptions) } let transport const protocol = reqOptions.protocol if (protocol === 'http:') { transport = require('http') } else if (protocol === 'https:') { transport = require('https') } else { return Promise.reject(Error('Protocol missing from request: ' + JSON.stringify(reqOptions, null, ' '))) } const defer = require('defer-promise') const deferred = defer() const req = transport.request(reqOptions, function (res) { const pick = require('lodash.pick') if (/text\/event-stream/.test(res.headers['content-type'])) { const util = require('util') res[util.inspect.custom] = function (depth, options) { return options.stylize('[ SSE event-stream ]', 'special') } deferred.resolve({ data: res, res: pick(res, [ 'headers', 'method', 'statusCode', 'statusMessage', 'url' ]), req: reqOptions }) } else { const streamReadAll = require('stream-read-all') streamReadAll(res).then(data => { /* statusCode will be zero if the request was disconnected, so don't resolve */ if (res.statusCode !== 0) { deferred.resolve({ data: data, res: pick(res, [ 'headers', 'method', 'statusCode', 'statusMessage', 'url' ]), req: reqOptions }) } }) } }) req.on('error', function reqOnError (err) { /* failed to connect */ err.name = 'request-fail' err.request = req deferred.reject(err) }) req.end(data) if (reqOptions.controller) { reqOptions.controller.abort = function () { req.abort() const err = new Error('Aborted') err.name = 'aborted' deferred.reject(err) } } return deferred.promise }
javascript
{ "resource": "" }
q43480
Loader
train
function Loader(loadItem) { this.AbstractLoader_constructor(loadItem, true, createjs.AbstractLoader.SOUND); /** * A Media object used to determine if src exists and to get duration * @property _media * @type {Media} * @protected */ this._media = null; /** * A time counter that triggers timeout if loading takes too long * @property _loadTime * @type {number} * @protected */ this._loadTime = 0; /** * The frequency to fire the loading timer until duration can be retrieved * @property _TIMER_FREQUENCY * @type {number} * @protected */ this._TIMER_FREQUENCY = 100; }
javascript
{ "resource": "" }
q43481
train
function (f) { var separator , temp = []; [ '/', '-', ' '].forEach(function(sep) { if (temp.length < 2) { separator = sep; temp = f.split(separator); } }); return separator; }
javascript
{ "resource": "" }
q43482
train
function(username, password) { var restler_defaults = { baseURL: config.baseUrl }; var RestlerService = restler.service(default_init, restler_defaults, api); return new RestlerService(username, password); }
javascript
{ "resource": "" }
q43483
get_id
train
function get_id(val) { if ( typeof val === 'string' || typeof val === 'number' ) return val; if ( typeof val === 'object' && val.id ) return val.id; return false; }
javascript
{ "resource": "" }
q43484
default_init
train
function default_init(user, password) { this.defaults.username = user; this.defaults.password = password; this.defaults.headers = { Accept: 'application/json' }; this.defaults.headers['Content-Type'] = 'application/json'; }
javascript
{ "resource": "" }
q43485
LocalEnvironment
train
function LocalEnvironment(env, id) { Environment.call(this, {}, env._fm.$log); this._env = env; this._thread_id = id; }
javascript
{ "resource": "" }
q43486
StateManager
train
function StateManager(options) { // Initial state is pending this.state = states.pending; // If a state is passed in, then we go ahead and initialize the state manager with it if (options && options.state) { this.transition(options.state, options.value, options.context); } }
javascript
{ "resource": "" }
q43487
startDomAnimate
train
function startDomAnimate(selector, animationProps, interval, onDone){ let numberIndex = 0 const numbersLength = animationProps[0].numbers.length this.isDomRunning = true const tick = setInterval(() => { animationProps.forEach(prop => { setStyle(selector, prop.attr, prop.numbers[numberIndex], prop.unit) }) numberIndex ++ if(numberIndex >= numbersLength) { clearInterval(tick) this.isDomRunning = false if (onDone) onDone() } }, interval) }
javascript
{ "resource": "" }
q43488
encryptPassword
train
function encryptPassword(password, callback) { bcrypt.gen_salt(workFactor, function(err, salt) { if (err) callback(err); bcrypt.encrypt(password, salt, function(err, hashedPassword) { if (err) callback(err); callback(null, hashedPassword); }); }); }
javascript
{ "resource": "" }
q43489
ls
train
function ls (dir, cb) { if(!cb) cb = dir, dir = null dir = dir || process.cwd() pull( pfs.ancestors(dir), pfs.resolve('node_modules'), pfs.star(), pull.filter(Boolean), paramap(maybe(readPackage)), filter(), pull.unique('name'), pull.reduce(function (obj, val) { if(!obj[val.name]) obj[val.name] = val return obj }, {}, function (err, obj) { cb(err, obj) }) ) }
javascript
{ "resource": "" }
q43490
tree
train
function tree (dir, opts, cb) { var i = 0 findPackage(dir, function (err, pkg) { pull( pull.depthFirst(pkg, function (pkg) { pkg.tree = {} return pull( pfs.readdir(path.resolve(pkg.path, 'node_modules')), paramap(maybe(readPackage)), pull.filter(function (_pkg) { if(!_pkg) return _pkg.parent = pkg pkg.tree[_pkg.name] = _pkg return pkg }) ) }), opts.post ? paramap(function (data, cb) { //run a post install-style hook. opts.post(data, cb) }) : pull.through(), pull.drain(null, function (err) { cb(err === true ? null : err, clean(pkg)) }) ) }) }
javascript
{ "resource": "" }
q43491
train
function () { var args = arguments, argc = arguments.length; if (argc === 1) { if (args[0] === undefined || args[0] === null) { return undefined; } return args[0]; } else if (argc === 2) { if (args[0] === undefined || args[0] === null) { return args[1]; } return args[0]; } else { if (args[0][args[1]] === undefined || args[0][args[1]] === null) { return args[2]; } return args[0][args[1]]; } }
javascript
{ "resource": "" }
q43492
train
function (variable, isRecursive) { var property, result = 0; isRecursive = (typeof isRecursive !== "undefined" && isRecursive) ? true : false; if (variable === false || variable === null || typeof variable === "undefined" ) { return 0; } else if (variable.constructor !== Array && variable.constructor !== Object) { return 1; } for (property in variable) { if (variable.hasOwnProperty(property) && !$this.isFunc(variable[property])) { result++; if (isRecursive && variable[property] && ( variable[property].constructor === Array || variable[property].constructor === Object ) ) { result += this.count(variable[property], true); } } } return result; }
javascript
{ "resource": "" }
q43493
train
function (needle, haystack, strict) { var found = false; strict = !!strict; $this.each(haystack, function (key) { /* jshint -W116 */ if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) { found = true; return false; } /* jshint +W116 */ }); return found; }
javascript
{ "resource": "" }
q43494
train
function (value, precision, mode) { /* jshint -W016 */ /* jshint -W018 */ // Helper variables var base, floorNum, isHalf, sign; // Making sure precision is integer precision |= 0; base = Math.pow(10, precision); value *= base; // Sign of the number sign = (value > 0) | -(value < 0); isHalf = value % 1 === 0.5 * sign; floorNum = Math.floor(value); if (isHalf) { mode = mode ? mode.toUpperCase() : "DEFAULT"; switch (mode) { case "DOWN": // Rounds .5 toward zero value = floorNum + (sign < 0); break; case "EVEN": // Rouds .5 towards the next even integer value = floorNum + (floorNum % 2 * sign); break; case "ODD": // Rounds .5 towards the next odd integer value = floorNum + !(floorNum % 2); break; default: // Rounds .5 away from zero value = floorNum + (sign > 0); } } return (isHalf ? value : Math.round(value)) / base; /* jshint +W016 */ /* jshint +W018 */ }
javascript
{ "resource": "" }
q43495
train
function (glue, pieces) { var retVal = "", tGlue = ""; if (arguments.length === 1) { pieces = glue; glue = ""; } if (typeof pieces === "object") { if ($this.type(pieces) === "array") { return pieces.join(glue); } $this.each(pieces, function (i) { retVal += tGlue + pieces[i]; tGlue = glue; }); return retVal; } }
javascript
{ "resource": "" }
q43496
train
function (delimiter, string, limit) { if (arguments.length < 2 || typeof delimiter === "undefined" || typeof string === "undefined" ) { return null; } if (delimiter === "" || delimiter === false || delimiter === null ) { return false; } if (delimiter === true) { delimiter = "1"; } // Here we go... delimiter += ""; string += ""; var splited = string.split(delimiter); if (typeof limit === "undefined") { return splited; } // Support for limit if (limit === 0) { limit = 1; } // Positive limit if (limit > 0) { if (limit >= splited.length) { return splited; } return splited.slice(0, limit - 1) .concat([splited.slice(limit - 1) .join(delimiter) ]); } // Negative limit if (-limit >= splited.length) { return []; } splited.splice(splited.length + limit); return splited; }
javascript
{ "resource": "" }
q43497
authDetectionMiddleware
train
function authDetectionMiddleware(req, res, next) { logger.debug('Running Auth Detection Middleware...', req.body); if (req.headers['token']) { try { req.user = encryption.decode(req.headers['token'], config.secret); req.session = { user: req.user }; } catch (ex) { logger.logError('Unexpectedly could not decode a token.', ex); res.status(401).send(); // ensure no user is authenticated. req.user = null; req.session = { user: null }; } if (!req.user.id) throw 'AUTH FAILED:USER HAS NO MEMBER: id'; if (!req.user.tokenExpiry || req.user.tokenExpiry <= new Date().getTime()) { logger.log('Expired Token:', req.user); res.status(401).send({errorCode: 'expired token'}); } else { logger.log('Authenticated User:', req.user.id); next(); } } else { //logger.debug('Checking permissions to ', req.path); //if (config.routesNotRequiringAuthentication[req.path]) next(); //else if (m.isPublicRoute(req.path)) next(); //else { // logger.debug('Disallowing request to:', req.path); // res.status(401).send(); //} if (config.authenticatedRoutes[req.path] || !m.isPublicRoute(req.path)) res.status(401).send(); else next(); } }
javascript
{ "resource": "" }
q43498
createStorage
train
function createStorage(defaults, queue, unqueue, log) { if (typeof defaults !== "object") { log = unqueue; unqueue = queue; queue = defaults; defaults = {}; } /** * @constructor * @param {object} [opts] */ function Storage(opts) { mixin(mixin(this, opts), defaults); } /** * @name Storage#queue * @method * @param {object} task * @param {queueTaskCallback} [done] */ Storage.prototype.queue = function(task, done) { switch (arguments.length) { case 0: throw new TypeError("expected task"); case 1: arguments[1] = function() {}; } queue.apply(this, arguments); }; /** * @name Storage#unqueue * @method * @param {unqueueTaskCallback} [done] */ Storage.prototype.unqueue = function(done) { switch (arguments.length) { case 0: arguments[0] = function() {}; } unqueue.apply(this, arguments); }; /** * @name Storage#log * @method * @param {string} key * @param {object} result * @param {functon} [done] */ Storage.prototype.log = function(key, result, done) { switch (arguments.length) { case 0: throw new TypeError("expected key"); case 1: throw new TypeError("expected results"); case 2: arguments[2] = function() {}; } log.apply(this, arguments); }; // return new Storage class return Storage; }
javascript
{ "resource": "" }
q43499
train
function(callback) { var self = this; this.beet.client.getAllProcessInfo(function(err, processes) { if(processes) for(var i = processes.length; i--;) { var proc = processes[i], nameParts = proc.name.split('_'); if(nameParts[0] != self.name) { processes.splice(i, 1); } else { proc.group = nameParts[0]; proc.name = nameParts[1]; } } callback(err, processes); }); }
javascript
{ "resource": "" }