_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q42000
train
function(levels) { for (var i = 0; i < levels.length; ++i) { var level = levels[i]; for (var j = 0; j < level.length; ++j) { if (level[j].factory) { _this.injectAndRegister(level[j].name, level[j].factory); } else if (level[j].obj) { _this.register(level[j].name, level[j].obj); } } } }
javascript
{ "resource": "" }
q42001
train
function(value, patterns, options, isPath) { // Parse patterns, match value per pattern, and return results. return planckmatch.match(value, planckmatch.parse(patterns, options, isPath)); }
javascript
{ "resource": "" }
q42002
noDups
train
function noDups (iterable = []) { return (errMsgPrefix = '') => { const dups = extractDuplicates(iterable) return dups.size === 0 ? [ true, [] ] : [ false, [ new Error(errMsgPrefix + Array.from(dups).join(', ')) ] ] } }
javascript
{ "resource": "" }
q42003
RegExpStringMapper
train
function RegExpStringMapper(options) { if (!(this instanceof RegExpStringMapper)) { return new RegExpStringMapper(options); } options = options || {}; this._formatters = []; this.addFormatter(createDefaultFormatter(options.serialize || getSerializeFn())); this.addFormatter(createMomentFormatter(options.moment)); this._separator = options.separator || '%'; this._regex = buildDefaultRegex(this._separator); this._magic = '@RegExpStringMapper'; this._separatorRegExp = RegExp(this._separator + this._separator, 'g'); this._magicRegExp = RegExp(this._magic, 'g'); }
javascript
{ "resource": "" }
q42004
merge
train
function merge (a, b, soft) { for (var k in b) if (!soft || !a.hasOwnProperty(k)) a[k] = b[k] return a }
javascript
{ "resource": "" }
q42005
inspect
train
function inspect (s) { return s .replace(/\\/g, '\\\\') .replace(/\n/g, '\\n') .replace(/\t/g, '\\t') .replace(/"/g, '\\"') .replace(/\r/g, '\\r') }
javascript
{ "resource": "" }
q42006
forwardEvent
train
function forwardEvent (event) { var n = Atok.events[event] , args = [] while (n > 0) args.push('a' + n--) args = args.join() return 'atok.on("' + event + '", function forwardEvent (' + args + ') { self.emit_' + event + '(' + args + ') })' }
javascript
{ "resource": "" }
q42007
train
function(log) { var date = this.date.toISOString().substring(0, 19); var duration = new Date() - this.date; log(date + ' ' + this.ip + ' "' + this.method + ' ' + this.path + '" ' + this.status + ' ' + this._length + ' ' + duration); }
javascript
{ "resource": "" }
q42008
train
function(fn) { var code = fn.toString(); var match = code.match(/^(?:(?:function)?[\s]*\(([^)]*)\)|([^\=\(]+))/); var args = (match[1] || match[2]); if (typeof args === 'undefined') { return []; } return args.split(',').map(function(item) { return item.trim(); }).filter(function(item) { return item; }); }
javascript
{ "resource": "" }
q42009
findTags
train
function findTags(code) { const tags = [] findTag(code, '\n', tags) findTag(code, '//', tags) findTag(code, '/*', tags) findTag(code, '*/', tags) return tags }
javascript
{ "resource": "" }
q42010
createLogger
train
function createLogger (writables, prefix, dateFormat) { if (!Array.isArray(writables)) writables = [ writables ] writables = writables.filter(w => isDefined(w) && isFunction(w.write)) debug(`There are ${writables.length} writables for this logger`) let pre = `[${prefix}]` // default timestamp format if (dateFormat === true) dateFormat = 'YYYY-MM-DD HH:mm:ss' if (typeof dateFormat === 'string') { pre += ` ${moment().format(dateFormat)}` } return msg => { writables.forEach(w => w.write(`${pre} ${msg}\n`)) } }
javascript
{ "resource": "" }
q42011
useDefaultLogger
train
function useDefaultLogger (opts) { const { infoFile, errFile, append = true, timestamp = true, // string for a date format or pass true to use default format } = opts // The value of `logToConsole` default to true in dev mode let logToConsole = opts.logToConsole if (isDev() && !isDefined(logToConsole)) { debug('In dev mode and `logToConsole` is set to true.') logToConsole = true } const flag = append ? 'a' : 'w' const infoStream = infoFile && fs.createWriteStream(infoFile, { flags: flag }) const errStream = errFile && fs.createWriteStream(errFile, { flags: flag }) const infoRecorder = streamRecorder() const errRecorder = streamRecorder() return { verbose () { let stream = infoRecorder(infoFile, name => fs.createWriteStream(name, { flags: flag })) if (logToConsole) stream = [ process.stdout, stream ] createLogger(stream, 'Verbose', timestamp).apply(this, arguments) }, info () { let stream = infoRecorder(infoFile, name => fs.createWriteStream(name, { flags: flag })) if (logToConsole) stream = [ process.stdout, stream ] createLogger(stream, 'Info', timestamp).apply(this, arguments) }, warning () { let stream = errRecorder(errFile, name => fs.createWriteStream(name, { flags: flag })) if (logToConsole) stream = [ process.stderr, stream ] createLogger(stream, 'Warning', timestamp).apply(this, arguments) }, error () { let stream = errRecorder(errFile, name => fs.createWriteStream(name, { flags: flag })) if (logToConsole) stream = [ process.stderr, stream ] createLogger(stream, 'Error', timestamp).apply(this, arguments) } } }
javascript
{ "resource": "" }
q42012
streamRecorder
train
function streamRecorder () { let lastKey, lastStream return (key, createStream) => { if (isFunction(key)) key = key.call() debug(`Recorder get key: ${key}`) if (key !== lastKey) { debug(`Recorder will return a new stream`) lastKey = key lastStream = createStream.call(null, key) } return lastStream } }
javascript
{ "resource": "" }
q42013
train
function(arr, iterator) { var i = arr.length - 1, index = null if(i >= 0){ do { if(iterator(arr[i])) { index = i break } } while(i--) } return index }
javascript
{ "resource": "" }
q42014
LongCon
train
function LongCon() { this.settings = { namespace: '', nlFirst: false, quiet: false, time: false, traceIndent: ' ', traceLanes: true }; this.stackDepth = 0; this.firstLine = true; }
javascript
{ "resource": "" }
q42015
promiseWithError
train
function promiseWithError( err, callback) { var deferred = Q.defer(); if ( err instanceof Error ) { deferred.reject( err); } else { deferred.reject(new Error(err)); } if ( typeof callback === 'function' ) { callback(err, null); } return deferred.promise; }
javascript
{ "resource": "" }
q42016
promiseWithError
train
function promiseWithError( result, callback) { var deferred = Q.defer(); deferred.resolve(result); if ( typeof callback === 'function' ) { callback(null, result); } return deferred.promise; }
javascript
{ "resource": "" }
q42017
promiseForCallback
train
function promiseForCallback( fun, callback) { var deferred = Q.defer(); fun( function( error, result) { callback(error, result, deferred); }); return deferred.promise; }
javascript
{ "resource": "" }
q42018
getDataSource
train
function getDataSource(projectConfig) { var api = {}; api.getDataForPath = function getDataForPath(requestedPath) { var templateData, dataPath; dataPath = path.resolve(projectConfig.paths.src.views.data, requestedPath + '.json'); try{ templateData = require(dataPath); } catch(err){ templateData = {}; } return templateData; }; api.getPaths = function getPaths() { return; }; return api; }
javascript
{ "resource": "" }
q42019
DefaultData
train
function DefaultData(projectConfig) { var defaultData = require(path.resolve(projectConfig.paths.src.views.data, '_default.json')); return { apply: function apply(data) { return merge.recursive(defaultData, data); } }; }
javascript
{ "resource": "" }
q42020
extend
train
function extend() { var result = {}; var objs = Array.prototype.slice.call(arguments,0); objs.forEach(function(props, index){ for(var prop in props) { if(props.hasOwnProperty(prop)) { result[prop] = props[prop] } } }); return result; }
javascript
{ "resource": "" }
q42021
train
function() { obj.mesh[ propertyName ].set( propertyObject.x, propertyObject.y, propertyObject.z ) }
javascript
{ "resource": "" }
q42022
train
function(point, curve) { var candidates = [], w = _convertToBezier(point, curve), degree = curve.length - 1, higherDegree = (2 * degree) - 1, numSolutions = _findRoots(w, higherDegree, candidates, 0), v = Vectors.subtract(point, curve[0]), dist = Vectors.square(v), t = 0.0; for (var i = 0; i < numSolutions; i++) { v = Vectors.subtract(point, _bezier(curve, degree, candidates[i], null, null)); var newDist = Vectors.square(v); if (newDist < dist) { dist = newDist; t = candidates[i]; } } v = Vectors.subtract(point, curve[degree]); newDist = Vectors.square(v); if (newDist < dist) { dist = newDist; t = 1.0; } return {location:t, distance:dist}; }
javascript
{ "resource": "" }
q42023
train
function(point, curve) { var td = _distanceFromCurve(point, curve); return {point:_bezier(curve, curve.length - 1, td.location, null, null), location:td.location}; }
javascript
{ "resource": "" }
q42024
train
function(w, degree, t, depth) { var left = [], right = [], left_count, right_count, left_t = [], right_t = []; switch (_getCrossingCount(w, degree)) { case 0 : { return 0; } case 1 : { if (depth >= maxRecursion) { t[0] = (w[0].x + w[degree].x) / 2.0; return 1; } if (_isFlatEnough(w, degree)) { t[0] = _computeXIntercept(w, degree); return 1; } break; } } _bezier(w, degree, 0.5, left, right); left_count = _findRoots(left, degree, left_t, depth+1); right_count = _findRoots(right, degree, right_t, depth+1); for (var i = 0; i < left_count; i++) t[i] = left_t[i]; for (var i = 0; i < right_count; i++) t[i+left_count] = right_t[i]; return (left_count+right_count); }
javascript
{ "resource": "" }
q42025
train
function(curve, location) { var cc = _getCurveFunctions(curve.length - 1), _x = 0, _y = 0; for (var i = 0; i < curve.length ; i++) { _x = _x + (curve[i].x * cc[i](location)); _y = _y + (curve[i].y * cc[i](location)); } return {x:_x, y:_y}; }
javascript
{ "resource": "" }
q42026
train
function(curve, location) { var p1 = _pointOnPath(curve, location), p2 = _pointOnPath(curve.slice(0, curve.length - 1), location), dy = p2.y - p1.y, dx = p2.x - p1.x; return dy == 0 ? Infinity : Math.atan(dy / dx); }
javascript
{ "resource": "" }
q42027
train
function(curve, location, distance) { var p = _pointAlongPath(curve, location, distance); if (p.location > 1) p.location = 1; if (p.location < 0) p.location = 0; return _gradientAtPoint(curve, p.location); }
javascript
{ "resource": "" }
q42028
train
function(kObj, scopes, map, fn) { _each(kObj, function(_kObj) { _unreg(_kObj, map); // deregister existing scopes _kObj[fn](scopes); // set scopes _reg(_kObj, map); // register new ones }); }
javascript
{ "resource": "" }
q42029
train
function (_e) { _draw(_e[0], uip); _currentInstance.removeClass(_e[0], "jsplumb-dragged"); _currentInstance.select({source: _e[0]}).removeClass(_currentInstance.elementDraggingClass + " " + _currentInstance.sourceElementDraggingClass, true); _currentInstance.select({target: _e[0]}).removeClass(_currentInstance.elementDraggingClass + " " + _currentInstance.targetElementDraggingClass, true); _currentInstance.getDragManager().dragEnded(_e[0]); }
javascript
{ "resource": "" }
q42030
train
function (p) { if (p) { for (var i = 0; i < p.childNodes.length; i++) { if (p.childNodes[i].nodeType != 3 && p.childNodes[i].nodeType != 8) { var cEl = jsPlumb.getElement(p.childNodes[i]), cid = _currentInstance.getId(p.childNodes[i], null, true); if (cid && _elementsWithEndpoints[cid] && _elementsWithEndpoints[cid] > 0) { var cOff = _currentInstance.getOffset(cEl); _delements[id][cid] = { id: cid, offset: { left: cOff.left - parentOffset.left, top: cOff.top - parentOffset.top } }; _draggablesForElements[cid] = id; } _oneLevel(p.childNodes[i]); } } } }
javascript
{ "resource": "" }
q42031
train
function (evt, el, zoom) { var box = typeof el.getBoundingClientRect !== "undefined" ? el.getBoundingClientRect() : { left: 0, top: 0, width: 0, height: 0 }, body = document.body, docElem = document.documentElement, scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop, scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft, clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, pst = 0, psl = 0, top = box.top + scrollTop - clientTop + (pst * zoom), left = box.left + scrollLeft - clientLeft + (psl * zoom), cl = jsPlumb.pageLocation(evt), w = box.width || (el.offsetWidth * zoom), h = box.height || (el.offsetHeight * zoom), x = (cl[0] - left) / w, y = (cl[1] - top) / h; return [ x, y ]; }
javascript
{ "resource": "" }
q42032
train
function (endpoint, placeholder, _jsPlumb) { var stopped = false; return { drag: function () { if (stopped) { stopped = false; return true; } if (placeholder.element) { var _ui = _jsPlumb.getUIPosition(arguments, _jsPlumb.getZoom()); jsPlumb.setPosition(placeholder.element, _ui); _jsPlumb.repaint(placeholder.element, _ui); // always repaint the source endpoint, because only continuous/dynamic anchors cause the endpoint // to be repainted, so static anchors need to be told (or the endpoint gets dragged around) endpoint.paint({anchorPoint:endpoint.anchor.getCurrentLocation({element:endpoint.element})}); } }, stopDrag: function () { stopped = true; } }; }
javascript
{ "resource": "" }
q42033
train
function (placeholder, _jsPlumb, ipco, ips) { var n = jsPlumb.createElement("div", { position : "absolute" }); _jsPlumb.appendElement(n); var id = _jsPlumb.getId(n); jsPlumb.setPosition(n, ipco); n.style.width = ips[0] + "px"; n.style.height = ips[1] + "px"; _jsPlumb.manage(id, n, true); // TRANSIENT MANAGE // create and assign an id, and initialize the offset. placeholder.id = id; placeholder.element = n; }
javascript
{ "resource": "" }
q42034
train
function (ep, elementWithPrecedence) { var idx = 0; if (elementWithPrecedence != null) { for (var i = 0; i < ep.connections.length; i++) { if (ep.connections[i].sourceId == elementWithPrecedence || ep.connections[i].targetId == elementWithPrecedence) { idx = i; break; } } } return ep.connections[idx]; }
javascript
{ "resource": "" }
q42035
train
function (a, b, c) { return c >= Math.min(a, b) && c <= Math.max(a, b); }
javascript
{ "resource": "" }
q42036
done
train
function done(req, next, err, obj) { if (err) { req.error = {error: err.error || err.message}; } else { req.provider = obj; } next(); }
javascript
{ "resource": "" }
q42037
check
train
function check(err, res, body) { if (err) { return this.machine(err); } var obj; try { obj = JSON.parse(body); } catch (e) { return this.machine(new Error('Failed to parse as JSON (' + e.message + ') the text: ' + body)); } if (res.statusCode !== 200) { return this.machine(obj); } this.machine(err, obj); }
javascript
{ "resource": "" }
q42038
renderTemplatesList
train
function renderTemplatesList( container, templatesDefinitions ) { // clear loading wait text. container.setHtml( '' ); for ( var i = 0, totalDefs = templatesDefinitions.length; i < totalDefs; i++ ) { var definition = CKEDITOR.getTemplates( templatesDefinitions[ i ] ), imagesPath = definition.imagesPath, templates = definition.templates, count = templates.length; for ( var j = 0; j < count; j++ ) { var template = templates[ j ], item = createTemplateItem( template, imagesPath ); item.setAttribute( 'aria-posinset', j + 1 ); item.setAttribute( 'aria-setsize', count ); container.append( item ); } } }
javascript
{ "resource": "" }
q42039
insertTemplate
train
function insertTemplate( html ) { var dialog = CKEDITOR.dialog.getCurrent(), isReplace = dialog.getValueOf( 'selectTpl', 'chkInsertOpt' ); if ( isReplace ) { editor.fire( 'saveSnapshot' ); // Everything should happen after the document is loaded (#4073). editor.setData( html, function() { dialog.hide(); // Place the cursor at the first editable place. var range = editor.createRange(); range.moveToElementEditStart( editor.editable() ); range.select(); setTimeout( function() { editor.fire( 'saveSnapshot' ); }, 0 ); } ); } else { editor.insertHtml( html ); dialog.hide(); } }
javascript
{ "resource": "" }
q42040
isProperty
train
function isProperty(name, value) { currentProperty = name; updateDescriptor({ 'value': value, 'writable': true, 'enumerable': true, 'configurable': true }); return this; }
javascript
{ "resource": "" }
q42041
train
function(cb){ serialport.list(function (err, ports) { if(err) return cb(err); var pinoccios = []; ports.forEach(function(port) { var pnpId = port.pnpId||port.manufacturer||""; if(pnpId.indexOf('Pinoccio') > -1){ pinoccios.push(port.comName); } }); cb(false,pinoccios,ports); }); }
javascript
{ "resource": "" }
q42042
train
function(fn, args, scope) { if (!ovy.isArray(args)) { if (ovy.isIterable(args)) { args = arrays.clone(args); } else { args = args !== undefined ? [args] : []; } } return function() { var fnArgs = [].concat(args); fnArgs.push.apply(fnArgs, arguments); return fn.apply(scope || this, fnArgs); }; }
javascript
{ "resource": "" }
q42043
assertLayout
train
function assertLayout(value, defaultLayout) { var isFalsey = require('falsey'); if (value === false || (value && isFalsey(value))) { return null; } else if (!value || value === true) { return defaultLayout || null; } else { return value; } }
javascript
{ "resource": "" }
q42044
go
train
function go(from, to){ var toStream; Step( function checkParams(){ _checkParams(from, to, this) }, function(err, checkResult){ var checkResultOfFrom; var checkResultOfTo; if(err){ log.error('invalid options'); throw err; return; } checkResultOfFrom = checkResult.from; checkResultOfTo = checkResult.to; if(!checkResultOfTo.isFile){ throw new Error('-t should specify a file but not a directory'); } Step( function resolveFrom(){ if(checkResultOfFrom.isFile){ return [checkResultOfFrom.path]; }else if(checkResultOfFrom.isDirectory){ utils.walk(checkResultOfFrom.path, function(file){ return path.extname(file) === '.js'; }, this); } }, function action(err, files){ var group; if(err){ throw err; } group = this.group(); toStream = fs.createWriteStream(to, {flags: 'a'}); for(var i = 0, l = files.length; i < l; i++){ goByFile(files[i], toStream, group()); } }, function showStats(err, numbers){ var totally = 0; if(err){ throw err; } toStream.end(); numbers.forEach(function(number){ totally = totally + number; }); if(totally > 0){ console.log('--------'); console.log('Totally ' + clc.red(totally) + ' messages have gone to ' + clc.green(to)); }else{ console.log(clc.red('No') + ' messages found in ' + clc.cyan(from)); } } ); } ) }
javascript
{ "resource": "" }
q42045
readOverlay
train
function readOverlay(application) { var possibleValues, value; if (Ember.testing) { // when in test mode, use the overlay specified in the application value = {from: 'test:startApp()', name: application.get('devFixtures.overlay')}; } else { // else try many locations possibleValues = []; location.href.replace(/(?:\?|&)FIXTURES_OVERLAY(?:=([^&#$]*))?(?:&|#|$)/, function (dummy, value) { value = value ? decodeURIComponent(value) : null; possibleValues.push({from: 'location.search:FIXTURES_OVERLAY', name: value}); }); possibleValues.push({ from: 'file:config/environment.js', name: application.get('devFixtures.overlay') }); possibleValues.push({ from: 'localStorage:' + STORAGE_KEY, name: window.localStorage.getItem(STORAGE_KEY) }); // grabbing the first one not undefined value = Ember.A(possibleValues).find(function (value) { return value !== undefined; }); // saving it in the localStorage if (value && value.name) { window.localStorage.setItem(STORAGE_KEY, value.name); } else { window.localStorage.removeItem(STORAGE_KEY); } } // no overlay found anywhere if (!value) { value = {from: 'default', name: null}; } return value; }
javascript
{ "resource": "" }
q42046
RangeReader
train
function RangeReader(options) { RangeReader.__super__.constructor.call(this); this.begin = options.begin; this.end = options.end; this.marker = null; this.limit = options.limit; this.reverse = options.reverse; this.streamingMode = options.streamingMode; this.nonTransactional = options.nonTransactional || false; this.snapshot = options.snapshot || false; debug(function(writer) { if (options.begin) { writer.buffer('begin', resolveKey(options.begin).toString('utf8')); } if (options.end) { writer.buffer('end', resolveKey(options.end).toString('utf8')); } writer.buffer('limit', options.limit); writer.buffer('reverse', options.reverse); writer.buffer('streamingMode', options.streamingMode); writer.buffer('nonTransactional', options.nonTransactional); return writer.buffer('snapshot', options.snapshot); }); this.on('data', (function(_this) { return function(data) { var kv, _i, _len; if (data instanceof Array) { for (_i = 0, _len = data.length; _i < _len; _i++) { kv = data[_i]; _this.marker = kv.key; } } else { _this.marker = data.key; } }; })(this)); }
javascript
{ "resource": "" }
q42047
resolveToken
train
function resolveToken(callback) { var crossDomainStorageAvailable = crossDomainStorage.isAvailable(); logger.info('Resolving token from OfferEngine'); if (crossDomainStorageAvailable) { initXDomainStorage(function () { crossDomainStorage.getItem(appSettings.tokenCookieKey, function (data) { if (data.value) { logger.info('Retrieved existing token: ' + data.value); callback(data.value); } else { setCrossDomainToken(callback); } }); }); } else { // If there is no cross domain storage, we just generate a random token. // In reality, cross domain storage will be available on pretty much all devices // Because they all support localStorage now var token = utils.generateToken(); callback(token); } }
javascript
{ "resource": "" }
q42048
handleMessage
train
function handleMessage(data) { const message = data; message.params = that.parser.parse(data); message.channel = ch; message.ack = ack; // Ack method for the msg function ack() { debug('ack delivery', data.fields.deliveryTag); ch.ack(data); } if (Array.isArray(message)) { that.options.handler(message[0]); } else { that.options.handler(message); } debug('queue', that.options.queue); if (that.options.autoAck) { debug('autoAck', 'true'); ack(); } }
javascript
{ "resource": "" }
q42049
proxy
train
function proxy(target, mapping) { return new Proxy(mapping, { get(map, key) { if (Reflect.has(map, key)) { return resolve(target, Reflect.get(map, key)) } }, set(map, key, value) { if (Reflect.has(map, key)) { return resolve(target, Reflect.get(map, key), value) } } }) }
javascript
{ "resource": "" }
q42050
splitPlatformInfo
train
function splitPlatformInfo(uaList) { for(var i = 0; i < uaList.length; ++i) { var item = uaList[i]; if (isEnclosedInParens(item)) { return removeEmptyElements(trimSpacesInEachElement(item.substr(1, item.length-2).split(';'))); } } }
javascript
{ "resource": "" }
q42051
findOS
train
function findOS(uaPlatformInfo) { var oses = ['Android', 'BSD', 'Linux', 'Windows', 'iPhone OS', 'Mac OS', 'BSD', 'CrOS', 'Darwin', 'Dragonfly', 'Fedora', 'Gentoo', 'Ubuntu', 'debian', 'HP-UX', 'IRIX', 'SunOS', 'Macintosh', 'Win 9x', 'Win98', 'Win95', 'WinNT']; for(var os in oses) { for(var i in uaPlatformInfo) { var item = uaPlatformInfo[i]; if (contains(item, oses[os])) return item; } } return 'Other'; }
javascript
{ "resource": "" }
q42052
train
function(filePath) { if( path.extname(filePath) === '.js' ) { filePath = path.dirname(filePath); } ////console.log(colors.gray('loading meta:'), filePath); this.filePath = filePath; var meta = require(filePath + '/meta'); //set the name of the class to the last name value this.name = meta.name; if( typeof this.meta === 'object' ) { this.meta = merge(meta, this.meta); } else { this.meta = meta; } }
javascript
{ "resource": "" }
q42053
train
function() { //if the name was not set by the last meta file set it based on the file path if( (!this.name || this.name === 'Class') && typeof this.filePath === 'string' ) { this.name = path.basename(this.filePath); } //make sure the meta object exists if( typeof this.meta !== 'object' ) { console.log(colors.gray('class meta:'), 'not found!'); this.meta = {}; } //make sure the meta methods object exists if( typeof this.meta.methods !== 'object' ) { console.log(colors.yellow('class meta:'), 'missing methods object!'); this.meta.methods = {}; } //loop through methods in the meta object for( var method in this.meta.methods ) { //delete any method from meta that does not actually exist on the class if( !(method in this) ) { console.log(colors.yellow('class missing method:'), {class: this.name, method: method}); delete this.meta.methods[method]; } } /* //loop through methods in the class for( var method in this ) { if( typeof this[method] === 'function' ) { //alert about methods missing from the meta data if (!(method in this.meta.methods)) { console.log(colors.yellow('meta missing method:'), {class: this.name, method: method}); } } } //*/ }
javascript
{ "resource": "" }
q42054
addListenersToEditable
train
function addListenersToEditable() { var editable = editor.editable(); // We'll be catching all pasted content in one line, regardless of whether // it's introduced by a document command execution (e.g. toolbar buttons) or // user paste behaviors (e.g. CTRL+V). editable.on( mainPasteEvent, function( evt ) { if ( CKEDITOR.env.ie && preventBeforePasteEvent ) return; // If you've just asked yourself why preventPasteEventNow() is not here, but // in listener for CTRL+V and exec method of 'paste' command // you've asked the same question we did. // // THE ANSWER: // // First thing to notice - this answer makes sense only for IE, // because other browsers don't listen for 'paste' event. // // What would happen if we move preventPasteEventNow() here? // For: // * CTRL+V - IE fires 'beforepaste', so we prevent 'paste' and pasteDataFromClipboard(). OK. // * editor.execCommand( 'paste' ) - we fire 'beforepaste', so we prevent // 'paste' and pasteDataFromClipboard() and doc.execCommand( 'Paste' ). OK. // * native context menu - IE fires 'beforepaste', so we prevent 'paste', but unfortunately // on IE we fail with pasteDataFromClipboard() here, because of... we don't know why, but // we just fail, so... we paste nothing. FAIL. // * native menu bar - the same as for native context menu. // // But don't you know any way to distinguish first two cases from last two? // Only one - special flag set in CTRL+V handler and exec method of 'paste' // command. And that's what we did using preventPasteEventNow(). pasteDataFromClipboard( evt ); } ); // It's not possible to clearly handle all four paste methods (ctrl+v, native menu bar // native context menu, editor's command) in one 'paste/beforepaste' event in IE. // // For ctrl+v & editor's command it's easy to handle pasting in 'beforepaste' listener, // so we do this. For another two methods it's better to use 'paste' event. // // 'paste' is always being fired after 'beforepaste' (except of weird one on opening native // context menu), so for two methods handled in 'beforepaste' we're canceling 'paste' // using preventPasteEvent state. // // 'paste' event in IE is being fired before getClipboardDataByPastebin executes its callback. // // QUESTION: Why didn't you handle all 4 paste methods in handler for 'paste'? // Wouldn't this just be simpler? // ANSWER: Then we would have to evt.data.preventDefault() only for native // context menu and menu bar pastes. The same with execIECommand(). // That would force us to mark CTRL+V and editor's paste command with // special flag, other than preventPasteEvent. But we still would have to // have preventPasteEvent for the second event fired by execIECommand. // Code would be longer and not cleaner. CKEDITOR.env.ie && editable.on( 'paste', function( evt ) { if ( preventPasteEvent ) return; // Cancel next 'paste' event fired by execIECommand( 'paste' ) // at the end of this callback. preventPasteEventNow(); // Prevent native paste. evt.data.preventDefault(); pasteDataFromClipboard( evt ); // Force IE to paste content into pastebin so pasteDataFromClipboard will work. if ( !execIECommand( 'paste' ) ) editor.openDialog( 'paste' ); } ); // [IE] Dismiss the (wrong) 'beforepaste' event fired on context/toolbar menu open. (#7953) if ( CKEDITOR.env.ie ) { editable.on( 'contextmenu', preventBeforePasteEventNow, null, null, 0 ); editable.on( 'beforepaste', function( evt ) { // Do not prevent event on CTRL+V and SHIFT+INS because it blocks paste (#11970). if ( evt.data && !evt.data.$.ctrlKey && !evt.data.$.shiftKey ) preventBeforePasteEventNow(); }, null, null, 0 ); } editable.on( 'beforecut', function() { !preventBeforePasteEvent && fixCut( editor ); } ); var mouseupTimeout; // Use editor.document instead of editable in non-IEs for observing mouseup // since editable won't fire the event if selection process started within // iframe and ended out of the editor (#9851). editable.attachListener( CKEDITOR.env.ie ? editable : editor.document.getDocumentElement(), 'mouseup', function() { mouseupTimeout = setTimeout( function() { setToolbarStates(); }, 0 ); } ); // Make sure that deferred mouseup callback isn't executed after editor instance // had been destroyed. This may happen when editor.destroy() is called in parallel // with mouseup event (i.e. a button with onclick callback) (#10219). editor.on( 'destroy', function() { clearTimeout( mouseupTimeout ); } ); editable.on( 'keyup', setToolbarStates ); }
javascript
{ "resource": "" }
q42055
createCutCopyCmd
train
function createCutCopyCmd( type ) { return { type: type, canUndo: type == 'cut', // We can't undo copy to clipboard. startDisabled: true, exec: function( data ) { // Attempts to execute the Cut and Copy operations. function tryToCutCopy( type ) { if ( CKEDITOR.env.ie ) return execIECommand( type ); // non-IEs part try { // Other browsers throw an error if the command is disabled. return editor.document.$.execCommand( type, false, null ); } catch ( e ) { return false; } } this.type == 'cut' && fixCut(); var success = tryToCutCopy( this.type ); if ( !success ) alert( editor.lang.clipboard[ this.type + 'Error' ] ); // Show cutError or copyError. return success; } }; }
javascript
{ "resource": "" }
q42056
tryToCutCopy
train
function tryToCutCopy( type ) { if ( CKEDITOR.env.ie ) return execIECommand( type ); // non-IEs part try { // Other browsers throw an error if the command is disabled. return editor.document.$.execCommand( type, false, null ); } catch ( e ) { return false; } }
javascript
{ "resource": "" }
q42057
execIECommand
train
function execIECommand( command ) { var doc = editor.document, body = doc.getBody(), enabled = false, onExec = function() { enabled = true; }; // The following seems to be the only reliable way to detect that // clipboard commands are enabled in IE. It will fire the // onpaste/oncut/oncopy events only if the security settings allowed // the command to execute. body.on( command, onExec ); // IE7: document.execCommand has problem to paste into positioned element. ( CKEDITOR.env.version > 7 ? doc.$ : doc.$.selection.createRange() )[ 'execCommand' ]( command ); body.removeListener( command, onExec ); return enabled; }
javascript
{ "resource": "" }
q42058
onKey
train
function onKey( event ) { if ( editor.mode != 'wysiwyg' ) return; switch ( event.data.keyCode ) { // Paste case CKEDITOR.CTRL + 86: // CTRL+V case CKEDITOR.SHIFT + 45: // SHIFT+INS var editable = editor.editable(); // Cancel 'paste' event because ctrl+v is for IE handled // by 'beforepaste'. preventPasteEventNow(); // Simulate 'beforepaste' event for all none-IEs. !CKEDITOR.env.ie && editable.fire( 'beforepaste' ); return; // Cut case CKEDITOR.CTRL + 88: // CTRL+X case CKEDITOR.SHIFT + 46: // SHIFT+DEL // Save Undo snapshot. editor.fire( 'saveSnapshot' ); // Save before cut setTimeout( function() { editor.fire( 'saveSnapshot' ); // Save after cut }, 50 ); // OSX is slow (#11416). } }
javascript
{ "resource": "" }
q42059
Peer
train
function Peer(options) { /* jshint maxstatements: 26 */ /* jshint maxcomplexity: 8 */ if (!(this instanceof Peer)) { return new Peer(options); } if (options.socket) { this.socket = options.socket; this.host = this.socket.remoteAddress; this.port = this.socket.remotePort; this.status = Peer.STATUS.CONNECTED; this._addSocketEventHandlers(); } else { this.host = options.host || 'localhost'; this.status = Peer.STATUS.DISCONNECTED; this.port = options.port; } this.network = Networks.get(options.network) || Networks.defaultNetwork; if (!this.port) { this.port = this.network.port; } this.messages = options.messages || new Messages({ network: this.network, Block: bitcore.Block, Transaction: bitcore.Transaction }); this.dataBuffer = new Buffers(); this.version = 0; this.bestHeight = 0; this.subversion = null; this.relay = options.relay === false ? false : true; this.versionSent = false; // set message handlers var self = this; this.on('verack', function() { self.status = Peer.STATUS.READY; self.emit('ready'); }); this.on('version', function(message) { self.version = message.version; self.subversion = message.subversion; self.bestHeight = message.startHeight; var verackResponse = self.messages.VerAck(); self.sendMessage(verackResponse); if(!self.versionSent) { self._sendVersion(); } }); this.on('ping', function(message) { self._sendPong(message.nonce); }); return this; }
javascript
{ "resource": "" }
q42060
Commit
train
function Commit(source, githubClient) { this.gh = githubClient; this.sha = source.sha; this.htmlUrl = source.html_url; this.author = source.author; this.committer = source.committer; this.message = source.message; this.treeSha = source.tree.sha; this.tree = undefined; }
javascript
{ "resource": "" }
q42061
train
function(obj, d) { var k; d = typeof d === 'undefined' ? 0 : d; d += 1; for (k in obj) { if (obj.hasOwnProperty(k) && _.isObject(obj[k])) { return depth(obj[k], d); } } return (d); }
javascript
{ "resource": "" }
q42062
train
function(year) { var yr; if (!year) { // initialize date "buckets" for year and month; year = [1900, 2100]; this._years = {}; for (yr = year[0]; yr <= year[1]; yr += 1) { this._years[yr] = new Year(yr); } } else { this.year = year; } return this; }
javascript
{ "resource": "" }
q42063
train
function() { var _findYear = function(years) { return _.toInt( _.reduce(years, function(res, year) { return res || ((this._years[year].sum() > 0) ? year : undefined); }, undefined, this) ); }; if (!_findYear.call(this, _.keys(this._years))) { return []; } return _.range( _findYear.call(this, _.keys(this._years)), (_findYear.call(this, _.keys(this._years).reverse() )+1) ); }
javascript
{ "resource": "" }
q42064
train
function(hash) { return function(row) { var testValue = function(value, rowValue) { if (value === '*' || value === '' || !value) { return true; } if (_.isString(rowValue)) { return (rowValue.toLowerCase() === value.toLowerCase()); } if (_.isArray(rowValue)) { return (_.contains(_.map(rowValue, function(tag) { return _.isString(tag) && tag.toLowerCase(); }), value.toLowerCase()) && true); } return false; }; // _.all makes sure all members of the hash pass return _.all(hash, function(value, key) { var rowValue = row.getAlias(key); if (rowValue) { // if the filter value is an array, then the rowValue must also be an array if (_.isArray(value) && _.isArray(rowValue)) { // expression is true if rowValue intersects completely with requested value. return _.intersection(value, rowValue).length === value.length; } // if the value is an array, but not the rowValue, only test the first index; return testValue(_.isArray(value) ? value[0] : value, rowValue) } return false; }); }; }
javascript
{ "resource": "" }
q42065
train
function(json) { return({ values: json, depth: 1, // map over all rows to get the set of properties available in each document series_list: _.reduce(json, function(res, row, key) { return _.uniq( res.concat( _.plain( row ).keys().value() ) ); }, []) }); }
javascript
{ "resource": "" }
q42066
logRoute
train
function logRoute(routeConfig, filters) { filters = filters ? filters.join(', ') : ""; $log.info( '{method="%s", path="%s", filters="%s"} bind on controller %s#%s', routeConfig.method, routeConfig.path, filters, routeConfig.controller, routeConfig.action ); }
javascript
{ "resource": "" }
q42067
generateGenericControllers
train
function generateGenericControllers(controllers, models) { var genericControllers = {}, genericRoute = []; models.forEach(function(model) { var persistence = $database.getPersistenceOfModel(model); if (null == persistence) { throw new Error(''); } var defaultController = {}; var modelRest = model + "Rest"; if (controllers.hasOwnProperty(modelRest)) { defaultController = controllers[modelRest]; } else if (controllers.hasOwnProperty(utils.camelizePath(modelRest))) { defaultController = controllers[utils.camelizePath(modelRest)]; } var generatorController = persistence.generatorController; genericControllers[modelRest] = _.defaults({}, defaultController, generatorController.generate(persistence.repositories[model], true)); //create genericRoute.push({ method: 'post', controller: modelRest, action: 'create', path: '/' + model }); genericRoute.push({ method: 'get', controller: modelRest, action: 'createQuery', path: '/' + model + '/create' }); //Read genericRoute.push({ method: 'get', controller: modelRest, action: 'index', path: '/' + model }); genericRoute.push({ method: 'get', controller: modelRest, action: 'findById', path: '/' + model + '/:id' }); genericRoute.push({ method: 'get', controller: modelRest, action: 'find', path: '/' + model + '/find' }); //update genericRoute.push({ method: 'put', controller: modelRest, action: 'update', path: '/' + model + '/:id' }); genericRoute.push({ method: 'get', controller: modelRest, action: 'updateQuery', path: '/' + model + '/update/:id' }); //update genericRoute.push({ method: 'delete', controller: modelRest, action: 'delete', path: '/' + model + '/:id' }); genericRoute.push({ method: 'get', controller: modelRest, action: 'delete', path: '/' + model + '/delete/:id' }); }); return [genericControllers, genericRoute] }
javascript
{ "resource": "" }
q42068
detailRange
train
function detailRange(cards) { if (cache.has(cards)) return cache.get(cards) var [ r1, r2, suitedness ] = cards if (r1 === r2) return addPairDetails(r1, new Set()) if (ranks.indexOf(r1) > ranks.indexOf(r2)) { const tmp = r1; r1 = r2; r2 = tmp } var res if (suitedness === 's') res = addSuitedDetails(r1, r2, new Set()) else if (suitedness === 'o') res = addOffsuitDetails(r1, r2, new Set()) else res = addOffsuitAndSuitedDetails(r1, r2, new Set()) cache.set(cards, res) return res }
javascript
{ "resource": "" }
q42069
rangeFromDetail
train
function rangeFromDetail(set) { const pairs = new Map() const suiteds = new Map() const offsuits = new Map() function updateMap(map, key, val) { if (!map.has(key)) map.set(key, new Set()) map.get(key).add(val) } for (const cards of set) { var [ r1, s1, r2, s2 ] = cards if (r1 === r2) { updateMap(pairs, r1 + r2, cards) continue } if (ranks.indexOf(r1) > ranks.indexOf(r2)) { const tmp = r1; r1 = r2; r2 = tmp } if (s1 === s2) { updateMap(suiteds, r1 + r2 + 's', cards) continue } updateMap(offsuits, r1 + r2 + 'o', cards) } const complete = new Set() const incomplete = new Set() const all = new Set() for (const [ k, v ] of pairs) { if (v.size < 6) incomplete.add(k); else complete.add(k) all.add(k) } for (const [ k, v ] of suiteds) { if (v.size < 4) incomplete.add(k); else complete.add(k) all.add(k) } for (const [ k, v ] of offsuits) { if (v.size < 12) incomplete.add(k); else complete.add(k) all.add(k) } return { pairs, suiteds, offsuits, complete, incomplete, all } }
javascript
{ "resource": "" }
q42070
fixArgs
train
function fixArgs (callee) { return (options, fn) => { if (typeof fn != 'function' && typeof options == 'function') { fn = options; options = {}; } else { options = options || {}; } options.asc = options.asc || options.asc == null; return callee(options, fn); }; }
javascript
{ "resource": "" }
q42071
compare
train
function compare (options, less, x, y) { const ifLess = options.asc ? -1 : 1; return less(x, y) ? ifLess : less(y, x) ? -ifLess : 0; }
javascript
{ "resource": "" }
q42072
overrideConfig
train
function overrideConfig() { _.merge(Elixir.config, require(path.join(process.cwd(), 'elixirConfig.js'))); }
javascript
{ "resource": "" }
q42073
overrideTasks
train
function overrideTasks() { function noop() { Elixir.log.heading.error('Quorra don\'t have php tests!') } Elixir.extend('phpSpec', noop); Elixir.extend('phpunit', noop); Elixir.extend('babel', function () { new Elixir.Task('babel', function () { Elixir.log.heading('Alert!').heading("'mix.babel()' is not supported in Quorra Elixir. " + "You'll want to instead call 'mix.rollup().'"); process.exit(1); }); }); }
javascript
{ "resource": "" }
q42074
getNpmData
train
function getNpmData(pkg, npmClient, callback) { callback = once(callback); // default to latest version if (!pkg.version || pkg.version === 'latest') { pkg.version = '*'; } npmClient.get(pkg.name, { staleOk: true }, errTo(callback, function(npmPackageInfo) { var version; version = semver.maxSatisfying(Object.keys(npmPackageInfo.versions), pkg.version); // if the version is not found, perhaps the cache is old, force load from registry if (!version) { npmClient.get(pkg.name, { staleOk: true }, errTo(callback, function(npmPackageInfo) { callback(null, npmPackageInfo.versions[version] || null); })); } else { callback(null, npmPackageInfo.versions[version] || null); } })); }
javascript
{ "resource": "" }
q42075
getBulkNpmData
train
function getBulkNpmData(pkgs, collection, npmClient, callback) { var next, results; results = []; next = after(pkgs.length, function(err) { return callback(err, results); }); pkgs.forEach(function(pkg) { // make sure not to make unnecessary queries to the registry if (isDuplicate(collection[pkg.name], pkg.version)) { return next(null); } getNpmData(pkg, npmClient, errTo(callback, function(found) { if (found) { results.push(found); } next(null, results); })); }); }
javascript
{ "resource": "" }
q42076
mapDependencies
train
function mapDependencies(dependencies) { var deps; deps = (dependencies) ? Object.keys(dependencies) : []; return deps.map(function(name) { return { name: name, version: dependencies[name] }; }); }
javascript
{ "resource": "" }
q42077
isDuplicate
train
function isDuplicate(pkg, version) { var versions; // no duplicates if (pkg) { versions = Object.keys(pkg); if (versions.length && semver.maxSatisfying(versions, version)) { return true; } } return false; }
javascript
{ "resource": "" }
q42078
addToQueue
train
function addToQueue(queue, packageInfo) { var exists; function matchesVersion(version, range) { var matches; try { matches = semver.satisfies(packageInfo.version, item.version); } catch (err) { matches = false; } return matches; } exists = queue.some(function(item) { var matches = false; if (item.name === packageInfo.name) { matches = matchesVersion(packageInfo.version, item.version); } return matches; }); if (!exists) { queue.push(packageInfo); } }
javascript
{ "resource": "" }
q42079
processDeps
train
function processDeps(queue, collection, callback, errBack) { return errTo(errBack, function(packages) { var deps; packages.forEach(function(pkg) { // add the package to the collection of processed packages addPackage(collection, pkg); // if the module has dependencies, add them to the processing queue // unless they have been already processed mapDependencies(pkg.dependencies).forEach(function(dep) { if (!isDuplicate(collection[dep.name], dep.version)) { addToQueue(queue, dep); } }); }); callback(queue); }); }
javascript
{ "resource": "" }
q42080
getGitFolder
train
function getGitFolder() { // Based on logic in Module._nodeModulePaths at // https://github.com/joyent/node/blob/master/lib/module.js var from = path.resolve('.'), parts = from.split(process.platform === 'win32' ? /[\/\\]/ : /\//), tip, dir for (tip = parts.length - 1; tip >= 0; tip--) { dir = parts.slice(0, tip + 1).concat('.git').join(path.sep) try { if (fs.statSync(dir).isDirectory()) { // Found a valid .git directory return dir } } catch (e) { // Let 'for' iterate } } return '' }
javascript
{ "resource": "" }
q42081
readRef
train
function readRef(gitFolder, refName) { var ref try { ref = fs.readFileSync(path.join(gitFolder, refName), 'utf8').trim() return isSHA1(ref) ? ref : '' } catch (e) { // Last chance: read from packed-refs return readPackedRef(gitFolder, refName) } }
javascript
{ "resource": "" }
q42082
readPackedRef
train
function readPackedRef(gitFolder, refName) { var packedRefs, i, each, match try { packedRefs = fs.readFileSync(path.join(gitFolder, 'packed-refs'), 'utf8').split(/\r?\n/) } catch (e) { return '' } for (i = 0; i < packedRefs.length; i++) { each = packedRefs[i].trim() // Look for lines like: // 1d6f5f98a254578e19b5eb163077170d45448c26 refs/heads/master match = each.match(/^(.{40}) (.*)$/) if (match && match[2] === refName && isSHA1(match[1])) { return match[1] } } return '' }
javascript
{ "resource": "" }
q42083
jsdocCommand
train
function jsdocCommand( jsdoc ) { var cmd = []; cmd.unshift( jsdoc.options ); if ( jsdoc.tutorials.length > 0 ) { cmd.push( "-u " + path.resolve( jsdoc.tutorials ) ); } cmd.push( "-d " + path.resolve( jsdoc.dest ) ); cmd.push( "-t " + path.resolve( jsdoc.template ) ); cmd.push( "-c " + path.resolve( jsdoc.config ) ); sys.each( jsdoc.src, function ( src ) { cmd.push( path.resolve( src ) ); } ); cmd.unshift( path.resolve( "./node_modules/jsdoc/jsdoc" ) ); cmd.unshift( "node" ); return cmd.join( " " ); }
javascript
{ "resource": "" }
q42084
getBootSwatchList
train
function getBootSwatchList( done ) { var options = { hostname : 'api.bootswatch.com', port : 80, path : '/', method : 'GET' }; var body = ""; var req = http.request( options, function ( res ) { res.setEncoding( 'utf8' ); res.on( 'data', function ( chunk ) { body += chunk; } ); res.on( 'end', function () { done( null, JSON.parse( body ) ); } ); res.on( 'error', function ( e ) { done( 'problem with response: ' + e.message ); } ); } ); req.on( 'error', function ( e ) { done( 'problem with request: ' + e.message ); } ); req.end(); }
javascript
{ "resource": "" }
q42085
getBootSwatchComponent
train
function getBootSwatchComponent( url, done ) { var body = ""; var req = http.request( url, function ( res ) { res.setEncoding( 'utf8' ); res.on( 'data', function ( chunk ) { body += chunk; } ); res.on( 'end', function () { done( null, body ); } ); res.on( 'error', function ( e ) { done( 'problem with response: ' + e.message ); } ); } ); req.on( 'error', function ( e ) { done( 'problem with request: ' + e.message ); } ); req.end(); }
javascript
{ "resource": "" }
q42086
getViewTag
train
function getViewTag(view, offset) { var tag = '', i; for (i = offset; i < offset + 4; i += 1) { tag += String.fromCharCode(view.getInt8(i)); } return tag; }
javascript
{ "resource": "" }
q42087
train
function() { // The last component to be unmounted uninstalls the event listener. if (components.length == 0) { document.removeEventListener(EVENT_TYPE, dispatchEvent); } components.splice(components.indexOf(this), 1); }
javascript
{ "resource": "" }
q42088
train
function(key, callback, options) { var binding; key = key.charCodeAt ? key.toUpperCase().charCodeAt() : key; options = assign({}, DEFAULT_OPTIONS, options || {}); binding = { callback: callback, options: options }; if (!this.keyBindings[key]) { this.keyBindings[key] = [binding]; } else { this.keyBindings[key].push(binding); } }
javascript
{ "resource": "" }
q42089
normalize
train
function normalize (url, opts, callback) { url = typeof url === 'string' ? {url: url} : url opts = extend(url, opts) if (typeof opts.url !== 'string') { throw new TypeError('request-all: missing request url') } if (typeof callback !== 'function') { throw new TypeError('request-all: expect a callback') } opts.url = normalizeUrl(opts.url) opts.json = typeof opts.json === 'boolean' ? opts.json : true opts.headers = extend({ 'accept': 'application/json', 'user-agent': 'https://github.com/tunnckoCore/request-all' }, opts.headers) return opts }
javascript
{ "resource": "" }
q42090
normalizeUrl
train
function normalizeUrl (url) { if (!url || /per_page=/.test(url)) return url /* istanbul ignore next */ if ((/&/.test(url) && !/&$/.test(url)) || (!/\?$/.test(url) && /\?/.test(url))) { return url + '&per_page=100' } return /\?$/.test(url) ? url + 'per_page=100' : url + '?per_page=100' }
javascript
{ "resource": "" }
q42091
tryParse
train
function tryParse (val) { var res = null try { res = JSON.parse(val.toString()) } catch (err) { res = err } return res }
javascript
{ "resource": "" }
q42092
connect
train
function connect (master) { if (_socket && _socket._master.name === master.name) { debug(`already connected to master ${master.name}`) return } if (_connectingMaster && _connectingMaster.name === master.name) { debug(`already connecting to master ${master.name}`) return } _connectingMaster = master let newSocket = _getSocket(master) debug(`connecting to ${master.name} at ${master.endpoint}`) let connectionStart = Date.now() const onSocketReceiving = timingoutCallback((err, ...args) => { newSocket.unmonitor() if ( err || !_connectingMaster || _connectingMaster.name === !master.name ) { newSocket.close() if (err) { debug(`failed to connect to ${master.name} at ${master.endpoint}`) disconnect() } return } _connectingMaster = null let previousSocket = _socket debug(`${previousSocket ? 'switched' : 'connected'} to ${master.name} at ${master.endpoint} in ${Date.now() - connectionStart} ms`) if (args.length) { _onSocketMessage(...args) } _socket = newSocket _socket.removeAllListeners() _subscribedChannels.forEach(channel => _socket.subscribe(channel)) _socket.on('message', _onSocketMessage) _lastHeartbeatReceivedTime = Date.now() _monitorHeartbeats() if (previousSocket) { setTimeout(() => { previousSocket.removeAllListeners() previousSocket.close() debug(`closed previous connection to ${previousSocket._master.name} at ${previousSocket._master.endpoint}`) }, 300) } else { connection.emit('connect') } }, 500) newSocket.once('connect', () => onSocketReceiving()) newSocket.once('message', (...args) => onSocketReceiving(null, ...args)) return connection }
javascript
{ "resource": "" }
q42093
subscribe
train
function subscribe (channels) { channels.forEach(channel => { if (~_subscribedChannels.indexOf(channel)) return _subscribedChannels.push(channel) if (_socket) _socket.subscribe(channel) }) return connection }
javascript
{ "resource": "" }
q42094
unsubscribe
train
function unsubscribe (channels) { pullAll(_subscribedChannels, channels) if (_socket) channels.forEach(channel => _socket.unsubscribe(channel)) return connection }
javascript
{ "resource": "" }
q42095
matcher
train
function matcher(match) { if (match instanceof RegExp) { return function(criteria) { return match.test(criteria); }; } return function(criteria) { return criteria === match; }; }
javascript
{ "resource": "" }
q42096
analyzeFunction
train
function analyzeFunction(node) { var comment = node.leadingComments[0]; if (comment.type !== 'Block') { return; } var data = doctrine.parse(comment.value, { unwrap: true }); var params = []; data.tags.forEach(function (tag) { if (tag.title === 'param') { params.push(tag.name); } }); var missing = []; node.params.forEach(function (param) { if (params.indexOf(param.name) < 0) { missing.push(param.name); } }); if (missing.length > 0) { var msg = ''; msg += 'In function ' + chalk.cyan(node.id.name) + ' (Line ' + node.loc.start.line + '):\n'; missing.forEach(function (m) { msg += ' Parameter ' + chalk.cyan(m) + ' is not documented.'; }); throw new Error(msg); } }
javascript
{ "resource": "" }
q42097
verify
train
function verify(node) { switch (node.type) { case esprima.Syntax.FunctionDeclaration: if (node.leadingComments && node.leadingComments.length === 1) { analyzeFunction(node); } break; default: break; } }
javascript
{ "resource": "" }
q42098
pathParse
train
function pathParse(fullPath){ var parsedPath = { ext: path.extname(fullPath), dir: path.dirname(fullPath), full: fullPath, base: path.basename(fullPath), }; parsedPath.name = path.basename(fullPath, parsedPath.ext); return parsedPath; }
javascript
{ "resource": "" }
q42099
pipe
train
function pipe () { var fns = [].slice.call(arguments) var end = fns.length var idx = -1 var out return function pipe (initialValue) { out = initialValue while (++idx < end) { out = fns[idx](out) } return out } }
javascript
{ "resource": "" }