_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...
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))...
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...
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 (...
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(logToCon...
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) ...
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); } ...
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 = {};...
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 < numSolut...
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 (_isFlat...
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]...
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[c...
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 = w...
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);...
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 MANA...
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.co...
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...
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.im...
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() { ...
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); } ...
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() { ...
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; } checkRes...
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 = []; loc...
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; th...
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 (dat...
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...
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...
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)...
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.nam...
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' ) { ...
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...
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 ) ...
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 // onpast...
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 ...
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 = Pe...
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...
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(rowVa...
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, ...
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(''); ...
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(...
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) { ...
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!...
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.maxSa...
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[p...
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) { ...
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 proc...
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,...
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: // 1d6f5f98...
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( jsd...
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; } );...
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 ) { do...
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]...
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'...
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 } _c...
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 = [];...
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": "" }