_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q31900
VogueClient
train
function VogueClient(clientSocket, watcher) { this.socket = clientSocket; this.watcher = watcher; this.watchedFiles = {}; clientSocket.on('watch', this.handleMessage.bind(this)); clientSocket.on('disconnect', this.disconnect.bind(this)); }
javascript
{ "resource": "" }
q31901
load
train
function load(context) { var files , layers , cacheKey ; // TODO: make it proper optional param context = context || {}; // create new context // in case if `load` called without context context = typeOf(context) == 'function' ? context : this.new(context); // fallback to defaults context.directories = context.directories || context.defaults.directories; // prepare cache key cacheKey = getCacheKey.call(context); // get config files names suitable for the situation files = getFiles.call(context, process.env); // load all available files layers = loadFiles.call(context, context.directories, files); // merge loaded layers this._cache[cacheKey] = mergeLayers.call(context, layers); // return immutable copy return clone.call({ useCustomTypeOf: clone.behaviors.useCustomTypeOf, 'typeof': context.mergeTypeOf }, this._cache[cacheKey]); }
javascript
{ "resource": "" }
q31902
transformChunk
train
function transformChunk(chunk, encoding, done) { if (chunk.isNull()) return done(); if (chunk.isStream()) return this.emit('error', new PluginError(logFlag, 'Streaming not supported')); if ( !(chunk.isMarkdown = options.regexpMarkdown.test(chunk.relative)) && !(chunk.isTemplate = options.regexpTemplate.test(chunk.relative)) && !(chunk.isHtml = options.regexpHtml.test(chunk.relative)) ) { return options.passThrough ? done(null, chunk) : done(); } transformChunkData(chunk); if (chunk.data.draft && process.env.NODE_ENV !== 'development') return done(); if (buffer.hasOwnProperty(chunk.relative)) { logDuplicate(chunk); return done(); } transformChunkContents.call(this, chunk); buffer[chunk.relative] = chunk; done(null, chunk); }
javascript
{ "resource": "" }
q31903
transformChunkData
train
function transformChunkData(chunk) { var matter = grayMatter(String(chunk.contents)), relPath = chunk.hasOwnProperty('data') && chunk.data.relativePath ? chunk.data.relativePath : getRelativePath(chunk.relative), absPath = path.normalize(path.join(options.basePath, relPath)); chunk.data = merge.recursive({}, options.data, { basePath: options.basePath, relativePath: relPath, path: absPath, urlPath: options.prettyUrls ? path.dirname(absPath) + '/' : absPath, srcBasePath: chunk.base, srcRelativePath: chunk.relative, srcPath: chunk.path, contents: '', draft: false, layout: options.defaultLayout }, chunk.data || {}, matter.data ); chunk.contents = new Buffer(matter.content); chunk.path = path.join(chunk.base, relPath); return chunk; }
javascript
{ "resource": "" }
q31904
transformChunkContents
train
function transformChunkContents(chunk) { var contents = String(chunk.contents); try { if (chunk.isMarkdown) { contents = options.renderMarkdown(contents); } if (chunk.isTemplate) { contents = options.renderTemplate(contents, chunk.data, chunk.data.srcPath); } chunk.contents = new Buffer(contents); if (chunk.data.layout) applyLayout(chunk); } catch (err) { this.emit('error', new PluginError(logFlag, err.stack || err)); } return chunk; }
javascript
{ "resource": "" }
q31905
renderTemplate
train
function renderTemplate(contents, data, filename) { if (!templateCache.hasOwnProperty(contents)) { var jadeOptions = merge.recursive({}, options.jadeOptions, {filename: filename}); templateCache[contents] = options.jade.compile(contents, jadeOptions); } var locals = merge.recursive({}, data, {locals: locals}); return templateCache[contents](data); }
javascript
{ "resource": "" }
q31906
applyLayout
train
function applyLayout(chunk) { chunk.data.contents = String(chunk.contents); var layout = getLayout(chunk.data.layout), contents = options.renderTemplate(layout.contents, chunk.data, layout.path); chunk.contents = new Buffer(contents); return chunk; }
javascript
{ "resource": "" }
q31907
getRelativePath
train
function getRelativePath(filePath) { var urlPath = path.join( path.dirname(filePath), path.basename(filePath, path.extname(filePath)) ); if (options.slugify) { urlPath = urlPath.split('/').map(function(part) { return slug(part, options.slugOptions); }).join('/'); } urlPath += !options.prettyUrls || (/(^|\/)index$/i).test(urlPath) ? '.html' : '/index.html'; return urlPath; }
javascript
{ "resource": "" }
q31908
getLayout
train
function getLayout(layout) { if (!layoutCache.hasOwnProperty(layout)) { var layoutContents = false, layoutPath = path.join( path.isAbsolute(options.layoutPath) ? options.layoutPath : path.join(process.cwd(), options.layoutPath), layout ); try { layoutContents = fs.readFileSync(layoutPath, 'utf8'); } catch (err) { throw new PluginError(logFlag, 'Could not read layout: \'' + layoutPath + '\'\n'); } layoutCache[layout] = { contents: layoutContents, path: layoutPath }; } return layoutCache[layout]; }
javascript
{ "resource": "" }
q31909
logDuplicate
train
function logDuplicate(chunk) { log(logFlag, chalk.black.bgYellow('WARNING') + ' skipping ' + chalk.magenta(chunk.data.srcRelativePath) + ' as it would output to same path as ' + chalk.magenta(buffer[chunk.relative].data.srcRelativePath) ); }
javascript
{ "resource": "" }
q31910
includeFiles
train
function includeFiles(config, backRef) { backRef = backRef || []; Object.keys(config).forEach(function(key) { var value, oneOffContext; if (typeof config[key] == 'string') { // create temp context oneOffContext = merge.call(cloneFunction, this, { files: [config[key]] }); // try to load data from file value = this.load(oneOffContext); // keep the entry if something's been resolved // empty or unchanged value signal otherwise if (isEmpty(value)) { delete config[key]; } else { config[key] = value; } } else if (isObject(config[key])) { includeFiles.call(this, config[key], backRef.concat(key)); } // Unsupported entry type else { throw new Error('Illegal key type for custom-include-files at ' + backRef.concat(key).join('.') + ': ' + Object.prototype.toString.call(config[key])); } }.bind(this)); return config; }
javascript
{ "resource": "" }
q31911
GulpEmail
train
function GulpEmail(opts, cb) { this.fullContent = ''; this.default = {}; this.cb = cb || this.callback; this.options = extend(this.default, opts); this.stream = new Transform({objectMode: true}); this.stream._transform = function(chunk, encoding, callback){ var fullPath = null, file = {}, relative = chunk.relative; file.base = chunk.base; file.contents = chunk.contents; file.extname = Path.extname(relative); file.basename = Path.basename(relative, file.extname); file.dirname = Path.dirname(relative); file.newDirname = utils.fixDirName(file.dirname); fullPath = file.newDirname + file.basename + file.extname; file.path = Path.join(chunk.base, fullPath); callback(null, self.readContent(file)); }; this.stream.on('end', function() { //console.log(self.fullContent); self.sendEmail(self.prepareCurl(self.fullContent)); }); var self = this; return this.stream; }
javascript
{ "resource": "" }
q31912
Cell
train
function Cell (node, content) { let index = 0 if (node.parentNode && node.parentNode.childNodes) { index = Util.arrayIndexOf(node.parentNode.childNodes, node) } const prefix = (index === 0 ? '| ' : ' ') return prefix + content + ' |' }
javascript
{ "resource": "" }
q31913
getVar
train
function getVar(token, env) { var modifiers = token.split(/\s+/) , name = modifiers.pop() , result = '' ; if (typeof env[name] == 'string' && env[name].length > 0) { result = env[name]; // process value with modifiers, right to left result = modifiers.reverse().reduce(function(accumulatedValue, modifierName) { if (typeOf(this.modifiers[modifierName]) != 'function') { throw new Error('Unable to find requested modifier `' + modifierName + '` among available modifiers: [' + Object.keys(this.modifiers).join('], [') + '].'); } return this.modifiers[modifierName](accumulatedValue); }.bind(this), result); } return result; }
javascript
{ "resource": "" }
q31914
train
function(config, env) { return env.grunt.util._.extend({ banner: '', compress: { warnings: false }, mangle: {}, beautify: false, report: false }, env.task.options(config.uglify || {})); }
javascript
{ "resource": "" }
q31915
train
function(files, config, catalog, env) { var uglifyConfig = this.uglifyConfig(config, env); var grunt = env.grunt; var _ = grunt.util._; files.forEach(function(f) { var src = validFiles(f.src, grunt, config); var dest = utils.fileInfo(f.dest, config); grunt.log.write('Processing ' + dest.catalogPath.cyan); // check if current file should be compiled if (!shouldProcess(dest, src, config, catalog)) { grunt.log.writeln(' [skip]'.grey); return false; } grunt.verbose.writeln(''); if (config.minify) { grunt.verbose.writeln('Minifying JS files'); var uglified = uglify.minify(_.pluck(src, '_path'), dest.absPath, uglifyConfig); dest.content = uglified.code; } else { dest.content = _.pluck(src, '_path') .map(function(src) { return grunt.file.read(src); }) .join(''); } if (config.postProcess) { dest.content = config.postProcess(dest.content, dest); } grunt.file.write(dest.absPath, dest.content); // Otherwise, print a success message.... grunt.log.writeln(' [save]'.green); // update catalog entry catalog[dest.catalogPath] = { hash: dest.hash, date: utils.timestamp(), versioned: dest.versionedUrl(config), files: src.map(function(f) { return { file: f.catalogPath, hash: f.hash, versioned: f.versionedUrl(config) }; }, this) }; }); return catalog; }
javascript
{ "resource": "" }
q31916
getCacheKey
train
function getCacheKey() { // use the one from the context var directories = this.directories || this.defaults.directories; return resolveDir(directories) + ':' + getFiles.call(this, process.env).join(',') + ':' + resolveExts.call(this).join(',') ; }
javascript
{ "resource": "" }
q31917
resolveDir
train
function resolveDir(directories) { var directoriesAbsPath; if (typeOf(directories) == 'array') { directoriesAbsPath = directories.map(function(d) { return path.resolve(d); }).join('|'); } else { directoriesAbsPath = path.resolve(directories); } return directoriesAbsPath; }
javascript
{ "resource": "" }
q31918
train
function(href) { var url = extract(href) var queryObj = omit(url.qs, this.config.excludeRequestParams) var desiredUrlParams = Object.keys(queryObj).map(function(paramName) { return paramName + '=' + encodeURIComponent(queryObj[paramName]) }).join('&') return desiredUrlParams ? url.url + '?' + desiredUrlParams : url.url }
javascript
{ "resource": "" }
q31919
train
function(envelope) { var filePath = this._getFileName(envelope) filendir.writeFile(filePath, JSON.stringify(envelope), function(err) { if (err) { log('File could not be saved in ' + this.config.cacheDir) throw err } }.bind(this)) }
javascript
{ "resource": "" }
q31920
train
function(req, returnReference) { getRawBody(req).then(function(bodyBuffer) { returnReference.requestBody = bodyBuffer.toString() }).catch(function() { log('Unhandled error in getRawBody', arguments) }) }
javascript
{ "resource": "" }
q31921
createNew
train
function createNew(options) { var copy = cloneFunction(configly) , instance = copy.bind(copy) ; // enrich copy with helper methods // mind baked-in context of the copies applyProps.call(this, copy, options); // get fresh list of filenames // if needed copy.files = copy.files || getFilenames.call(copy); // expose public methods on the outside // mind baked in context of the copies copyProps.call(copy, instance); return instance; }
javascript
{ "resource": "" }
q31922
copyProps
train
function copyProps(target) { Object.keys(this).forEach(function(key) { target[key] = typeof this[key] == 'function' ? this[key].bind(this) : this[key]; }.bind(this)); return target; }
javascript
{ "resource": "" }
q31923
getFilenames
train
function getFilenames() { var hostname = getHostname() , host = hostname.split('.')[0] ; return [ 'default', '', // allow suffixes as a basename (e.g. `environment`) host, hostname, 'local', this.defaults.customIncludeFiles, this.defaults.customEnvVars, 'runtime' ]; }
javascript
{ "resource": "" }
q31924
deepMerge
train
function deepMerge (base, custom) { Object.keys(custom).forEach(function (key) { if (!base.hasOwnProperty(key) || typeof base[key] !== 'object') { base[key] = custom[key] } else { base[key] = deepMerge(base[key], custom[key]) } }) return base }
javascript
{ "resource": "" }
q31925
iterateFiles
train
function iterateFiles (dir, options, cb) { var iterateOptions = { ext: [], // extensions to look for dirs: false, // do callback for dirs too skip_: true, // skip files & dirs starting with _ recursive: true // do a recursive find } options = deepMerge(iterateOptions, options) // console.log('options: ' + JSON.stringify(options)) iterateRecurse(dir, options, cb) }
javascript
{ "resource": "" }
q31926
iterateRecurse
train
function iterateRecurse (dir, options, cb) { try { var files = fs.readdirSync(dir) files.forEach(function (file, index) { var parsedPath = path.parse(file) var name = parsedPath.name var ext = parsedPath.ext var srcpath = path.join(dir, file) if (options.skip_ && name.charAt(0) === '_') { logger.debug('Skipping file/folder: ' + srcpath) } else { if (fs.lstatSync(srcpath).isDirectory()) { if (options.dirs) { cb(srcpath, name) } // Do recursive search when needed if (options.recursive) { iterateRecurse(srcpath, options, cb) } } else { for (var i = 0; i < options.ext.length; i++) { if (ext === options.ext[i]) { cb(srcpath, name, ext) } } } } }) } catch (e) { logger.debug('Error iterating files: ' + e) } }
javascript
{ "resource": "" }
q31927
innertext
train
function innertext (html) { // Drop everything inside <...> (i.e., tags/elements), and keep the text. // Unlike browser innerText, this removes newlines; it also doesn't handle // un-encoded `<` or `>` characters very well, so don't feed it malformed HTML return entities.decode(html.split(/<[^>]+>/) .map(function (chunk) { return chunk.trim() }) .filter(function (trimmedChunk) { return trimmedChunk.length > 0 }) .join(' ') ); }
javascript
{ "resource": "" }
q31928
existsSync
train
function existsSync (path) { try { Fs.accessSync(Path.resolve(path), Fs.F_OK) return true } catch (err) { return false } }
javascript
{ "resource": "" }
q31929
getFiles
train
function getFiles(env) { var files = [] , environment = env['NODE_ENV'] || this.defaults.environment , appInstance = env['NODE_APP_INSTANCE'] ; // generate config files variations this.files.forEach(function(baseName) { // check for variables // keep baseName if no variables found baseName = parseTokens(baseName, env) || baseName; // add base name with available suffixes addWithSuffixes.call(this, files, baseName, appInstance); addWithSuffixes.call(this, files, baseName, environment, appInstance); }.bind(this)); return files; }
javascript
{ "resource": "" }
q31930
mergeLayers
train
function mergeLayers(layers) { var _instance = this , result = null ; layers.forEach(function(layer) { layer.exts.forEach(function(ext) { ext.dirs.forEach(function(cfg) { // have customizable's array merge function result = merge.call({ useCustomAdapters: merge.behaviors.useCustomAdapters, 'array': _instance.arrayMerge, useCustomTypeOf: merge.behaviors.useCustomTypeOf, 'typeof': _instance.mergeTypeOf }, result || {}, cfg.config); }); }); }); // return `null` if noting found // and let downstream layers to make the decision return result; }
javascript
{ "resource": "" }
q31931
train
function() { cfg = this.config.get('pluginsConfig.localized-footer'), _this = this; try { fs.statSync(this.resolve(cfg.filename)); hasFooterFile = true; } catch (e) { hasFooterFile = false; return; } deprecationWarning(this); this.readFileAsString(cfg.filename) .then(function(data) { return _this.renderBlock('markdown', data); }, this.log.error) .then(function(html) { footerString = html; }, this.log.error); }
javascript
{ "resource": "" }
q31932
applyHooks
train
function applyHooks(config, filename) { // sort hooks short first + alphabetically Object.keys(this.hooks).sort(compareHooks).forEach(function(hook) { // in order to match hook should either the same length // as the filename or smaller if (filename.substr(0, hook.length) === hook) { config = this.hooks[hook].call(this, config); } }.bind(this)); return config; }
javascript
{ "resource": "" }
q31933
compareHooks
train
function compareHooks(a, b) { return a.length < b.length ? -1 : (a.length > b.length ? 1 : (a < b ? -1 : (a > b ? 1 : 0))); }
javascript
{ "resource": "" }
q31934
hasValue
train
function hasValue(value) { if (typeOf(value) === 'string') { return value.length > 0; } else { return typeOf(value) !== 'undefined' && typeOf(value) !== 'nan'; } }
javascript
{ "resource": "" }
q31935
watchAllStylesheets
train
function watchAllStylesheets() { var href; for (href in stylesheets) { if (hop.call(stylesheets, href)) { socket.emit("watch", { href: href }); } } }
javascript
{ "resource": "" }
q31936
reloadStylesheet
train
function reloadStylesheet(href) { var newHref = stylesheets[href].href + (href.indexOf("?") >= 0 ? "&" : "?") + "_vogue_nocache=" + (new Date).getTime(), stylesheet; // Check if the appropriate DOM Node is there. if (!stylesheets[href].setAttribute) { // Create the link. stylesheet = document.createElement("link"); stylesheet.setAttribute("rel", "stylesheet"); stylesheet.setAttribute("href", newHref); head.appendChild(stylesheet); // Update the reference to the newly created link. stylesheets[href] = stylesheet; } else { // Update the href to the new URL. stylesheets[href].href = newHref; } }
javascript
{ "resource": "" }
q31937
getLocalStylesheets
train
function getLocalStylesheets() { /** * Checks if the stylesheet is local. * * @param {Object} link The link to check for. * @returns {Boolean} */ function isLocalStylesheet(link) { var href, i, isExternal = true; if (link.getAttribute("rel") !== "stylesheet") { return false; } href = link.href; for (i = 0; i < script.bases.length; i += 1) { if (href.indexOf(script.bases[i]) > -1) { isExternal = false; break; } } return !(isExternal && href.match(/^https?:/)); } /** * Checks if the stylesheet's media attribute is 'print' * * @param (Object) link The stylesheet element to check. * @returns (Boolean) */ function isPrintStylesheet(link) { return link.getAttribute("media") === "print"; } /** * Get the link's base URL. * * @param {String} href The URL to check. * @returns {String|Boolean} The base URL, or false if no matches found. */ function getBase(href) { var base, j; for (j = 0; j < script.bases.length; j += 1) { base = script.bases[j]; if (href.indexOf(base) > -1) { return href.substr(base.length); } } return false; } function getProperty(property) { return this[property]; } var stylesheets = {}, reImport = /@import\s+url\(["']?([^"'\)]+)["']?\)/g, links = document.getElementsByTagName("link"), link, href, matches, content, i, m; // Go through all the links in the page, looking for stylesheets. for (i = 0, m = links.length; i < m; i += 1) { link = links[i]; if (isPrintStylesheet(link)) continue; if (!isLocalStylesheet(link)) continue; // Link is local, get the base URL. href = getBase(link.href); if (href !== false) { stylesheets[href] = link; } } // Go through all the style tags, looking for @import tags. links = document.getElementsByTagName("style"); for (i = 0, m = links.length; i < m; i += 1) { if (isPrintStylesheet(links[i])) continue; content = links[i].text || links[i].textContent; while ((matches = reImport.exec(content))) { link = { rel: "stylesheet", href: matches[1], getAttribute: getProperty }; if (isLocalStylesheet(link)) { // Link is local, get the base URL. href = getBase(link.href); if (href !== false) { stylesheets[href] = link; } } } } return stylesheets; }
javascript
{ "resource": "" }
q31938
isLocalStylesheet
train
function isLocalStylesheet(link) { var href, i, isExternal = true; if (link.getAttribute("rel") !== "stylesheet") { return false; } href = link.href; for (i = 0; i < script.bases.length; i += 1) { if (href.indexOf(script.bases[i]) > -1) { isExternal = false; break; } } return !(isExternal && href.match(/^https?:/)); }
javascript
{ "resource": "" }
q31939
getBase
train
function getBase(href) { var base, j; for (j = 0; j < script.bases.length; j += 1) { base = script.bases[j]; if (href.indexOf(base) > -1) { return href.substr(base.length); } } return false; }
javascript
{ "resource": "" }
q31940
loadScript
train
function loadScript(src, loadedCallback) { var script = document.createElement("script"); script.setAttribute("type", "text/javascript"); script.setAttribute("src", src); // Call the callback when the script is loaded. script.onload = loadedCallback; script.onreadystatechange = function () { if (this.readyState === "complete" || this.readyState === "loaded") { loadedCallback(); } }; head.appendChild(script); }
javascript
{ "resource": "" }
q31941
loadScripts
train
function loadScripts(scripts, loadedCallback) { var srcs = [], property, count, i, src, countDown = function () { count -= 1; if (!count) { loadedCallback(); } }; for (property in scripts) { if (!(property in window)) { srcs.push(scripts[property]); } } count = srcs.length; if (!count) { loadedCallback(); } for (i = 0; i < srcs.length; i += 1) { src = srcs[i]; loadScript(src, countDown); } }
javascript
{ "resource": "" }
q31942
getScriptInfo
train
function getScriptInfo() { var bases = [ document.location.protocol + "//" + document.location.host ], scripts, src, rootUrl, baseMatch; if (typeof window.__vogue__ === "undefined") { scripts = document.getElementsByTagName("script"); for (var i=0; i < scripts.length; i++) { src = scripts[i].getAttribute("src"); if (src && src.slice(-15) === 'vogue-client.js') break; } rootUrl = src.match(/^https?\:\/\/(.*?)\//)[0]; // There is an optional base argument, that can be used. baseMatch = src.match(/\bbase=(.*)(&|$)/); if (baseMatch) { bases = bases.concat(baseMatch[1].split(",")); } return { rootUrl: rootUrl, bases: bases }; } else { window.__vogue__.bases = bases; return window.__vogue__; } }
javascript
{ "resource": "" }
q31943
getPort
train
function getPort(url) { // URL may contain the port number after the second colon. // http://domain:1234/ var index = url.indexOf(":", 6); // skipping 6 characters to ignore first colon return index < 0 ? 80 : parseInt(url.substr(index + 1), 10); }
javascript
{ "resource": "" }
q31944
nodeInjectmd
train
function nodeInjectmd (opts) { const inBuf = bl() assert.equal(typeof opts, 'object', 'opts should be an object') assert.equal(typeof opts.in, 'string', 'opts.in should be a string') assert.equal(typeof opts.tag, 'string', 'opts.tag should be a string') const inFile = opts.in const tag = opts.tag const startTag = new RegExp('<!--\\s*START ' + tag + '\\s*-->') const endTag = new RegExp('<!--\\s*END ' + tag + '\\s*-->') assert.equal(typeof opts, 'object', 'opts must be an object') const rs = new stream.PassThrough() rs.pipe(inBuf) rs.on('end', function () { var tagMode = false const mdPath = path.join(process.cwd(), inFile) const irs = fs.createReadStream(mdPath) const its = split(parse) const tmpBuf = bl() irs.pipe(its).pipe(tmpBuf) tmpBuf.on('finish', function () { const ws = fs.createWriteStream(inFile, { flags: 'w' }) const rs = tmpBuf.duplicate() rs.pipe(ws) }) function parse (line) { if (startTag.test(line.trim())) { tagMode = true const res = line + EOL + String(inBuf) + EOL return res } else if (endTag.test(line.trim())) { tagMode = false return line + EOL } else if (!tagMode) { return line + EOL } } }) return rs }
javascript
{ "resource": "" }
q31945
wrap
train
function wrap (str, quote) { if (this.typecheck) t.typecheck('wrap', [str, quote]); if (!quote||quote=="'") return "'"+str+"'"; if (quote == '"') return '"'+str+'"'; return quote+str+quote; }
javascript
{ "resource": "" }
q31946
string
train
function string (str, quote) { if (this.typecheck) t.typecheck('string', [str, quote]); return this.wrap(this.escape(str), quote); }
javascript
{ "resource": "" }
q31947
train
function(files, config, catalog, env) { var grunt = env.grunt; var that = this; files.forEach(function(f) { var file = utils.fileInfo(f.dest, config); grunt.log.write('Processing ' + file.catalogPath.cyan); var src = f.src.map(function(src) { return utils.fileInfo(src, {cwd: config.srcWebroot}); }); file.content = src.map(function(src) { return that.processFile(src, config, catalog, env).content; }).join(''); if ( !config.force && file.catalogPath in catalog && catalog[file.catalogPath].hash === file.hash && fs.existsSync(file.absPath)) { grunt.log.writeln(' [skip]'.grey); return; } // save result grunt.log.writeln(' [save]'.green); grunt.file.write(file.absPath, file.content); catalog[file.catalogPath] = { hash: file.hash, date: utils.timestamp(), versioned: file.versionedUrl(config), files: src.map(function(f) { return { file: f.catalogPath, hash: f.hash, versioned: f.versionedUrl(config) }; }) }; }); }
javascript
{ "resource": "" }
q31948
Task
train
function Task(phase, name, func) { if (typeof name === 'function') { func = name; name = 'anonymous'; } if (phases.indexOf(phase) < 0) { throw new Error('Phase ' + phase + ' is not valid.'); } if (typeof func !== 'function') { throw new TypeError('Expected function, got ' + typeof func); } /** * The unique identifier for this task * @member {string} * @public */ this.name = name; /** * The phase under which this task is to be run * @member {string} * @public */ this.phase = phase; /** * The wrapped task function (func) * @member {Function} * @public * @returns Promise */ this.func = function () { var wheel = new Pinwheel('TASK: '+this.name+' ('+this.phase+')') , task = this; return new Promise(function (done, fail) { if (process.env.ENV !== 'test') wheel.start(); func.call(task, function (err) { if (err) return fail(err); return done(); }); }) .then(function () { if (process.env.ENV !== 'test') wheel.stop(); }) .catch(function (err) { if (process.env.ENV !== 'test') wheel.stop(err); return console.error(err); }); }; }
javascript
{ "resource": "" }
q31949
train
function(content) { if (typeof content != 'string') { content = JSON.stringify(content, null, '\t'); } fs.writeFileSync(catalogFile, content); }
javascript
{ "resource": "" }
q31950
train
function( callback ) { var self = this // Close a previously opened handle if( this.fd != null ) { return this.close( function( error ) { if( error != null ) return callback.call( self, error ) self.open( callback ) }) } // Open a new fd handle debug( 'fs:open', this.mode, this.path ) this.fs.open( this.path, this.mode, function( error, fd ) { if( error != null ) return callback.call( self, error, fd ) // Set file descriptor self.fd = fd // If no blockSize has been set, attempt to // detect it after opening the device if( self.blockSize == null || self.blockSize <= 0 ) { self.detectBlockSize( 0, 0, 0, function( error, blockSize ) { self.blockSize = blockSize || -1 callback.call( self, error, self.fd ) }) } else { callback.call( self, error, fd ) } }) return this }
javascript
{ "resource": "" }
q31951
train
function( size, step, limit, callback ) { var args = [].slice.call( arguments ) callback = args.pop() if( this.fd == null ) return callback.call( this, new Error( 'Invalid file descriptor' ) ) limit = args.pop() || 0x2000 step = args.pop() || 0x80 size = args.pop() || 0x200 var self = this var readBlock = function() { var block = Buffer.allocUnsafe( size ) self.fs.read( self.fd, block, 0, size, 0, function( error, bytesRead ) { if( error != null ) { // EINVAL tells us that the block size // ain't just right (yet); everything // else is probably user error if( error.code !== 'EINVAL' ) return callback.call( self, error ) // Increase the blocksize by `step` size += step // Attempt next size read return readBlock() } // Check if bytes read correspond // to current block size if( size !== bytesRead ) { error = new Error( 'Size and bytes read mismatch: ' + size + ', ' + bytesRead ) return callback.call( self, error ) } // Check if the limit has been reached, // and terminate with error, if so if( size > limit ) { error = new Error( 'Reached limit of ' + limit + ' bytes' ) return callback.call( self, error ) } // We've successfully found the // smallest readable block size; // stop looking... self.blockSize = size callback.call( self, null, size ) }) } // Start reading blocks readBlock() return this }
javascript
{ "resource": "" }
q31952
train
function( cylinder, head, sector ) { if( this.headsPerTrack < 0 || this.sectorsPerTrack < 0 ) throw new Error( 'Unspecified device geometry' ) return ( cylinder * this.headsPerTrack + head ) * this.sectorsPerTrack + ( sector - 1 ) }
javascript
{ "resource": "" }
q31953
train
function( fromLBA, toLBA, buffer, callback ) { fromLBA = fromLBA || 0 toLBA = toLBA || ( fromLBA + 1 ) if( fromLBA > toLBA ) { var swap = fromLBA fromLBA = toLBA toLBA = swap swap = void 0 } if( typeof buffer === 'function' ) { callback = buffer buffer = null } var self = this var from = this.blockSize * fromLBA var to = this.blockSize * toLBA debug( 'read_blocks', fromLBA, toLBA, buffer && buffer.length ) this._read( from, to - from, buffer, callback ) return this }
javascript
{ "resource": "" }
q31954
envVars
train
function envVars(config, backRef) { backRef = backRef || []; Object.keys(config).forEach(function(key) { var value; if (typeof config[key] == 'string') { // try simple match first, for non-empty value value = getVar.call(this, config[key], process.env); // if not, try parsing for variables if (!hasValue(value)) { value = parseTokens.call(this, config[key], process.env); } // keep the entry if something's been resolved // empty or unchanged value signal otherwise if (hasValue(value)) { config[key] = value; } else { delete config[key]; } } else if (isObject(config[key])) { envVars.call(this, config[key], backRef.concat(key)); } // Unsupported entry type else { throw new Error('Illegal key type for custom-environment-variables at ' + backRef.concat(key).join('.') + ': ' + Object.prototype.toString.call(config[key])); } }.bind(this)); return config; }
javascript
{ "resource": "" }
q31955
name
train
function name (column, table, schema) { if (this.typecheck) t.typecheck('name', [column, table, schema]); var result = []; schema && result.push(this.quotes(schema)); table && result.push(this.quotes(table)); column && result.push(this.quotes(column)); return result.join('.'); }
javascript
{ "resource": "" }
q31956
names
train
function names (columns, table, schema) { if (this.typecheck) t.typecheck('names', [columns, table, schema]); var result = []; for (var i=0; i < columns.length; i++) { result.push(this.name(columns[i],table,schema)); } return result.join(','); }
javascript
{ "resource": "" }
q31957
as
train
function as (column, name) { if (this.typecheck) t.typecheck('as', [column, name]); return [column,'as',name].join(' '); }
javascript
{ "resource": "" }
q31958
select
train
function select (args) { if (this.typecheck) t.typecheck('select', [args]); if ('string'===typeof args) args = [args]; return 'select '+args.join(); }
javascript
{ "resource": "" }
q31959
join
train
function join (table, args, type) { this.typecheck && t.typecheck('join', [table, args, type]); if ('string'===typeof args) args = [args]; var result = ['join',table,'on',args.join(' and ')]; if (type) result.splice(0,0,type); return result.join(' '); }
javascript
{ "resource": "" }
q31960
eq
train
function eq (a, b) { if (this.typecheck) t.typecheck('eq', [a, b]); return a+'='+b; }
javascript
{ "resource": "" }
q31961
eqv
train
function eqv (column, value) { if (this.typecheck) t.typecheck('eqv', [column, value]); if (value===undefined||value===null) value = null; if ('string'===typeof value) value = this.string(value); if ('boolean'===typeof value) value = (this.dialect == 'pg') ? ((value == false) ? this.wrap('f') : this.wrap('t')) : ((value == false) ? 0 : 1); return column+'='+value; }
javascript
{ "resource": "" }
q31962
groupby
train
function groupby (args) { if (this.typecheck) t.typecheck('groupby', [args]); if ('string'===typeof args) args = [args]; return 'group by '+args.join(); }
javascript
{ "resource": "" }
q31963
orderby
train
function orderby (args, order) { if (this.typecheck) t.typecheck('orderby', [args, order]); var o = (order&&'string'===typeof order) ? order : ''; var result = []; if ('string'===typeof args) { result = o ? [args+' '+o] : [args]; } else if (args instanceof Array) { for (var i=0; i < args.length; i++) { if ('string'===typeof args[i]) { o ? result.push(args[i]+' '+o) : result.push(args[i]); } else if ('object'===typeof args[i]) { var key = Object.keys(args[i])[0]; result.push(key+' '+args[i][key]); } } } else if (args instanceof Object) { var key = Object.keys(args)[0]; result = [key+' '+args[key]]; } return 'order by '+result.join(); }
javascript
{ "resource": "" }
q31964
limit
train
function limit (a, b) { if (this.typecheck) t.typecheck('limit', [a, b]); return (this.dialect == 'pg') ? ['limit',b,'offset',a].join(' ') : 'limit '+[a,b].join(); }
javascript
{ "resource": "" }
q31965
between
train
function between (a, b) { if (this.typecheck) t.typecheck('between', [a, b]); return ['between',a,'and',b].join(' '); }
javascript
{ "resource": "" }
q31966
where
train
function where (expr, operator) { if (this.typecheck) t.typecheck('where', [expr, operator]); if ('string'===typeof expr) return 'where '+expr; return 'where ' + expr.join(' '+(operator||'and')+' '); }
javascript
{ "resource": "" }
q31967
update
train
function update (table, columns, values) { if (this.typecheck) t.typecheck('update', [table, columns, values]); if ('string'===typeof columns) { columns = [columns]; values = [values]; } var result = []; for (var i=0; i < columns.length; i++) { var value = ('string'===typeof values[i] // X\'blob\' \'\\xblob\' && values[i].indexOf("X\'") != 0 && values[i].indexOf("\'\\x") != 0) ? this.string(values[i]) : values[i]; result.push(columns[i]+'='+value); } return ['update',table,'set',result.join()].join(' '); }
javascript
{ "resource": "" }
q31968
loadFiles
train
function loadFiles(directories, files) { // sort extensions to provide deterministic order of loading var _instance = this , extensions = resolveExts.call(this) , layers = [] ; // treat all inputs as list of directories directories = (typeOf(directories) == 'array') ? directories : [directories]; files.forEach(function(filename) { var layer = {file: filename, exts: []}; extensions.forEach(function(ext) { var layerExt = {ext: ext, dirs: []}; directories.forEach(function(dir) { var cfg, file = path.resolve(dir, filename + '.' + ext); if (fs.existsSync(file)) { cfg = loadContent.call(_instance, file, _instance.parsers[ext]); // check if any hooks needed to be applied cfg = applyHooks.call(_instance, cfg, filename); } if (cfg) { layerExt.dirs.push({ dir : dir, config: cfg }); } }); // populate with non-empty layers only if (layerExt.dirs.length) { layer.exts.push(layerExt); } }); // populate with non-empty layers only if (layer.exts.length) { layers.push(layer); } }); return layers; }
javascript
{ "resource": "" }
q31969
Watch
train
function Watch(patterns, ids) { if (typeof patterns === 'undefined') { throw new Error('Watch constructor requires a patterns argument'); } if (typeof ids === 'undefined') { throw new Error('Watch constructor requires an ids argument'); } patterns = Array.isArray(patterns) ? patterns : [patterns]; ids = Array.isArray(ids) ? ids : [ids]; /** * The patterns/globs to be watched * @member {Array} * @public */ this.patterns = patterns; /** * Registered tasks namespace * @member {Object} * @public */ this.tasks = { /** * All 'read' phase tasks associated with this watch * @property {Array} * @public */ read: [] /** * A single 'write' task associated with this watch * @property {Task} */ , write: null }; // add the initial set of tasks this.add(ids); }
javascript
{ "resource": "" }
q31970
queue
train
function queue(runner) { if (running < tasks) { ++running; runner(release); } else { pending.push(runner); } }
javascript
{ "resource": "" }
q31971
removeUselessStackLines
train
function removeUselessStackLines(stack) { let pretty = stack.split('\n'); pretty = pretty.filter((line) => { return !line.includes('node_modules') && !line.includes('Error'); }); pretty = pretty.join('\n'); return pretty; }
javascript
{ "resource": "" }
q31972
formatErrors
train
function formatErrors (results) { return ''; var failCount = results.fail.length; var past = (failCount === 1) ? 'was' : 'were'; var plural = (failCount === 1) ? 'failure' : 'failures'; var out = '\n' + pad(format.red.bold('Failed Tests:') + ' There ' + past + ' ' + format.red.bold(failCount) + ' ' + plural + '\n'); out += formatFailedAssertions(results); return out; }
javascript
{ "resource": "" }
q31973
_checkUpdate
train
function _checkUpdate(){ var notifier = updateNotifier({ pkg: pkg, updateCheckInterval: 1000 * 60 * 60 * 24 * 7 }) if (notifier.update) notifier.notify() }
javascript
{ "resource": "" }
q31974
_detectComment
train
function _detectComment(argv){ var comment = '' if(argv._.length == 1){ if(argv.m && typeof argv.m == 'string') comment = argv.m else if (argv.message && typeof argv.message == 'string') comment = argv.message return comment } else { console.log(chalk.red.bold('Invalid command: use stamplay deploy -m "YOUR MESSAGE"')) process.exit(1) } }
javascript
{ "resource": "" }
q31975
renderView
train
function renderView(view, layout, partials, context) { let options = { partials: partials }; // Handle dynamically-defined content tag let renderedView = {}; renderedView[opts.contentTag] = view(context, options); return layout(Object.assign({}, context, renderedView), options); }
javascript
{ "resource": "" }
q31976
train
function (nm) { el = d3.select(nm).append("svg") .attr("width", config.width + 2 * config.margin) .attr("height", config.height + 2 * config.margin) .append("g") .attr("transform", "translate(" + config.margin + ", " + config.margin + ")"); return xkcd; }
javascript
{ "resource": "" }
q31977
makeGetterSetter
train
function makeGetterSetter(name) { xkcd[name] = function (value) { if (arguments.length === 0) { return config[name]; } config[name] = value; return xkcd; }; }
javascript
{ "resource": "" }
q31978
lineplot
train
function lineplot(data, x, y, opts) { var line = d3.svg.line().x(x).y(y).interpolate(xinterp), bgline = d3.svg.line().x(x).y(y), strokeWidth = _get(opts, "stroke-width", 3), color = _get(opts, "stroke", "steelblue"); el.append("svg:path").attr("d", bgline(data)) .style("stroke", "white") .style("stroke-width", 2 * strokeWidth + "px") .style("fill", "none") .attr("class", "bgline"); el.append("svg:path").attr("d", line(data)) .style("stroke", color) .style("stroke-width", strokeWidth + "px") .style("fill", "none"); }
javascript
{ "resource": "" }
q31979
_get
train
function _get(d, k, def) { if (typeof d === "undefined") return def; if (typeof d[k] === "undefined") return def; return d[k]; }
javascript
{ "resource": "" }
q31980
StackMapper
train
function StackMapper(sourcemap) { if (!(this instanceof StackMapper)) return new StackMapper(sourcemap); if (typeof sourcemap !== 'object') throw new Error('sourcemap needs to be an object, please use convert-source-map module to convert it from any other format\n' + 'See: https://github.com/thlorenz/stack-mapper#obtaining-the-source-map'); this._sourcemap = sourcemap; this._prepared = false; }
javascript
{ "resource": "" }
q31981
compileTemplate
train
function compileTemplate(baseDir, filePath, type) { return new options.Promise((resolve, reject) => { let now = timestamp(); let name = filePath.substring(baseDir.length + 1).replace(/\\/g, '/'); name = name.substring(0, name.indexOf('.')); // A cached template is only invalidated if the environment is something // other than `development` and the time-to-live has been exceeded. if (cache[type][name] && (env !== 'development' || cache[type][name]._cached + expires > now)) { return resolve(cache[type][name]); } fs.readFile(filePath, 'utf-8', (error, contents) => { if (error) { return reject(error); } cache[type][name] = hbs.compile(contents.trim()); // Decorate the cached function with private members. The underscore // is necessary to avoid conflict with function's name to prevent all // compiled templates from being named `ret` in the cache. cache[type][name]._name = name; cache[type][name]._cached = timestamp(); return resolve(cache[type][name]); }); }); }
javascript
{ "resource": "" }
q31982
compileTemplates
train
function compileTemplates(dir, type) { return getPaths(dir, ext, options).then(paths => { return options.Promise.all(paths.map(filePath => { return compileTemplate(dir, filePath, type); })).then(templates => { return templates.reduce((all, current) => { all[current._name] = current; return all; }, {}); }); }); }
javascript
{ "resource": "" }
q31983
jsCompile
train
function jsCompile(content, file) { // make it as a child of this module // Would be nice to actually make it transparent // and pretend it to be child of the caller module // but there is no obvious way, yet var jsMod = new Module(file, module); // override parents to exclude configly from the chain // it's like this js file is included directly // from the file that included `configly` while (jsMod.parent && typeof jsMod.parent.id === 'string' && jsMod.parent.id.match(/\/node_modules\/configly\//) && jsMod.parent.parent) { /* istanbul ignore next */ jsMod.parent = jsMod.parent.parent; } // generate node_modules paths for the file jsMod.paths = Module._nodeModulePaths(path.dirname(file)); // execute the module jsMod._compile(content, file); // return just exported object return jsMod.exports; }
javascript
{ "resource": "" }
q31984
train
function(dt) { dt = dt || new Date(); return [dt.getFullYear(), padNumber(dt.getMonth() + 1), padNumber(dt.getDate()), padNumber(dt.getHours()), padNumber(dt.getMinutes()), padNumber(dt.getSeconds()) ].join(''); }
javascript
{ "resource": "" }
q31985
train
function(file, options) { file = this.absPath(file); var cwd = (options && options.cwd) || ''; if (file.substring(0, cwd.length) == cwd) { file = file.substring(cwd.length); if (file.charAt(0) != '/') { file = '/' + file; } } return file; }
javascript
{ "resource": "" }
q31986
train
function(grunt, task) { var config = task.options(grunt.config.getRaw('frontend') || {}); if (!config.webroot) { return grunt.fail.fatal('You should specify "webroot" property in frontend config', 100); } var cwd = this.absPath(config.cwd || config.webroot); var force = false; if ('force' in config) { force = !!config.force; } return grunt.util._.extend(config, { force: force, cwd: this.absPath(config.cwd || config.webroot), webroot: this.absPath(config.webroot), srcWebroot: this.absPath(config.srcWebroot || config.webroot) }); }
javascript
{ "resource": "" }
q31987
train
function(url, version, config) { if (!config.rewriteScheme) { return url; } var basename = path.basename(url); var ext = path.extname(url).substr(1); var filename = basename.replace(new RegExp('\\.' + ext + '$'), ''); var data = { url: url, dirname: path.dirname(url), basename: basename, ext: ext, filename: filename, version: version }; if (typeof config.rewriteScheme == 'string') { return _.template(config.rewriteScheme, data); } return config.rewriteScheme(data); }
javascript
{ "resource": "" }
q31988
train
function(x, y, silent) { if('number' != typeof x) { silent = y; y = x.y; x = x.x; } if(this.x === x && this.y === y) return this; this.x = Vec2.clean(x); this.y = Vec2.clean(y); if(silent !== false) return this.change(); }
javascript
{ "resource": "" }
q31989
train
function(vec2, returnNew) { if (!returnNew) { this.x += vec2.x; this.y += vec2.y; return this.change(); } else { // Return a new vector if `returnNew` is truthy return new Vec2( this.x + vec2.x, this.y + vec2.y ); } }
javascript
{ "resource": "" }
q31990
train
function(vec2, returnNew) { var x,y; if ('number' !== typeof vec2) { //.x !== undef) { x = vec2.x; y = vec2.y; // Handle incoming scalars } else { x = y = vec2; } if (!returnNew) { return this.set(this.x * x, this.y * y); } else { return new Vec2( this.x * x, this.y * y ); } }
javascript
{ "resource": "" }
q31991
train
function(r, inverse, returnNew) { var x = this.x, y = this.y, cos = Math.cos(r), sin = Math.sin(r), rx, ry; inverse = (inverse) ? -1 : 1; rx = cos * x - (inverse * sin) * y; ry = (inverse * sin) * x + cos * y; if (returnNew) { return new Vec2(rx, ry); } else { return this.set(rx, ry); } }
javascript
{ "resource": "" }
q31992
train
function(vec2) { var x = this.x - vec2.x; var y = this.y - vec2.y; return Math.sqrt(x*x + y*y); }
javascript
{ "resource": "" }
q31993
train
function(returnNew) { var length = this.length(); // Collect a ratio to shrink the x and y coords var invertedLength = (length < Number.MIN_VALUE) ? 0 : 1/length; if (!returnNew) { // Convert the coords to be greater than zero // but smaller than or equal to 1.0 return this.set(this.x * invertedLength, this.y * invertedLength); } else { return new Vec2(this.x * invertedLength, this.y * invertedLength); } }
javascript
{ "resource": "" }
q31994
train
function(v, w) { if (w === undef) { w = v.y; v = v.x; } return (Vec2.clean(v) === this.x && Vec2.clean(w) === this.y); }
javascript
{ "resource": "" }
q31995
train
function(returnNew) { var x = Math.abs(this.x), y = Math.abs(this.y); if (returnNew) { return new Vec2(x, y); } else { return this.set(x, y); } }
javascript
{ "resource": "" }
q31996
train
function(v, returnNew) { var tx = this.x, ty = this.y, vx = v.x, vy = v.y, x = tx < vx ? tx : vx, y = ty < vy ? ty : vy; if (returnNew) { return new Vec2(x, y); } else { return this.set(x, y); } }
javascript
{ "resource": "" }
q31997
train
function(low, high, returnNew) { var ret = this.min(high, true).max(low); if (returnNew) { return ret; } else { return this.set(ret.x, ret.y); } }
javascript
{ "resource": "" }
q31998
train
function(vec2, returnNew) { var x,y; if ('number' !== typeof vec2) { x = vec2.x; y = vec2.y; // Handle incoming scalars } else { x = y = vec2; } if (x === 0 || y === 0) { throw new Error('division by zero') } if (isNaN(x) || isNaN(y)) { throw new Error('NaN detected'); } if (returnNew) { return new Vec2(this.x / x, this.y / y); } return this.set(this.x / x, this.y / y); }
javascript
{ "resource": "" }
q31999
json
train
function json(value) { var parsedPojo; try { parsedPojo = JSON.parse(value); } catch(e) { return throwModifierError('json', value, e); } return parsedPojo; }
javascript
{ "resource": "" }