_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q34100
remove_script_tags
train
function remove_script_tags(){ html = html.replace(/<script[^>]*>.*?<\/script>/g, function(str){ if (str.match(/ type=/) && ! str.match(/text\/javascript/)) { return str; } else if (str.match(/src=['"]?(https?)/)) { return str; } else if (str.match(/src=['"]?\/\//)) { return str; } ...
javascript
{ "resource": "" }
q34101
remove_stylesheet_tags
train
function remove_stylesheet_tags() { // We can remove the style tag with impunity, it is always inlining. html = html.replace(/<style.+?<\/style>/g, ""); // External style resources use the link tag, check again for externals. if (options.clean_stylesheets) { html = html.replace(/<link[^...
javascript
{ "resource": "" }
q34102
remove_comments
train
function remove_comments(){ if (options.clean_comments) { html = html.replace(/<!--[\s\S]*?-->/g, function(str){ if (str.match(/<!--\[if /)) { return str; } if (str.match(/\n/)) { return str; } else { return ""; } }); } }
javascript
{ "resource": "" }
q34103
inject
train
function inject (tag, shims){ var added = shims.some(function(shim){ var i = html.lastIndexOf(shim); if (i !== -1) { html = html.substr(0, i) + tag + html.substr(i); return true; } return false; }); // Failing that, just append it. if (! added)...
javascript
{ "resource": "" }
q34104
inject_script_shim
train
function inject_script_shim () { if (options.include_js) { var script_tag = '<script type="text/javascript" src="' + options.include_js + '"></script>'; if (options.js_insert_marker && html.indexOf(options.js_insert_marker) !== -1) { html = html.replace(options.js_insert_marker, script_t...
javascript
{ "resource": "" }
q34105
inject_stylesheet_shim
train
function inject_stylesheet_shim () { if (options.include_css) { var style_tag = '<link rel="stylesheet" type="text/css" href="' + options.include_css + '">'; if (options.css_insert_marker && html.indexOf(options.css_insert_marker) !== -1) { html = html.replace(options.css_insert_marker, ...
javascript
{ "resource": "" }
q34106
write_css
train
function write_css () { if (dest.dest_css) { grunt.file.write(dest.dest_css, strip_whitespace(styles.join("\n"))); grunt.log.writeln('Stylesheet ' + dest.dest_css + '" extracted.'); } }
javascript
{ "resource": "" }
q34107
write_js
train
function write_js () { if (dest.dest_js) { grunt.file.write(dest.dest_js, strip_whitespace(scripts.join(";\n"))); grunt.log.writeln('Script "' + dest.dest_js + '" extracted.'); } }
javascript
{ "resource": "" }
q34108
write_html
train
function write_html () { if (dest.dest_html) { grunt.file.write(dest.dest_html, strip_whitespace(html)); grunt.log.writeln('Document "' + dest.dest_html + '" extracted.'); } }
javascript
{ "resource": "" }
q34109
run_dentist
train
function run_dentist() { if (load_files() && parse_html()) { if (dest.dest_html) { if (dest.dest_js) { remove_inline_scripts(); remove_script_tags(); inject_script_shim(); } if (dest.dest_css) { remove_inline_stylesheets(); ...
javascript
{ "resource": "" }
q34110
scrapeEnergies
train
function scrapeEnergies(el, $, func) { const $el = $(el); $el.find("li").each(function (i, val) { const $val = $(val); const type = $val.attr("title"); func(type, $val); }); }
javascript
{ "resource": "" }
q34111
scrapeAll
train
function scrapeAll(query, scrapeDetails) { return co(function *() { //By default, scrape the card details scrapeDetails = scrapeDetails === undefined ? true : scrapeDetails; //Load the HTML page const scrapeURL = makeUrl(SCRAPE_URL, query); const search = yield scrapeSearch...
javascript
{ "resource": "" }
q34112
matchSQLFilter
train
function matchSQLFilter(tableSchema, whereCol) { for (var i in whereCol) { var col = whereCol[i], schema = tableSchema[col.tbName]; if (!schema) throw new Error('A filter column refers to an unknown table [' + col.tbName + ']'); if (schema.columns.indexOf(col.col) < 0) return false; } return ...
javascript
{ "resource": "" }
q34113
collectFilterColumns
train
function collectFilterColumns(dftTable, filter, col) { var isLogical = false; if (filter.op === 'AND' || filter.op === 'and' || filter.op === 'OR' || filter.op === 'or') { filter.op = filter.op.toLowerCase(); isLogical = true; } if (isLogical) { filter.filters.forEach(function(f) { collectFilterColum...
javascript
{ "resource": "" }
q34114
buildSqlFilter
train
function buildSqlFilter(filter, columns) { if (filter.op === 'and') { var clones = []; filter.filters.forEach(function(f) { var cf = buildSqlFilter(f, columns); if (cf) clones.push( cf ); }); var len = clones.length; if (len < 1) return null; else return len > 1 ? {op: 'and', fi...
javascript
{ "resource": "" }
q34115
writeFile
train
function writeFile(file, content) { fs.writeFileSync(file, content); files.push(path.relative(app.components.get('path'), file)); }
javascript
{ "resource": "" }
q34116
configureComponent
train
function configureComponent(configPath, component, componentPath) { let config; try { config = require(configPath); // If this is the default variant if (!component.variant) { config.title = component.name; config.status = component.status; config.con...
javascript
{ "resource": "" }
q34117
createCollection
train
function createCollection(dirPrefix, dirPath, dirConfigs) { const dir = dirPath.shift(); const dirConfig = dirConfigs.shift() || {}; const absDir = path.join(dirPrefix, dir); // Create the collection directory try { if (!fs.statSync(absDir).isDirectory()) { throw new Error('1');...
javascript
{ "resource": "" }
q34118
registerComponent
train
function registerComponent(component) { const componentName = dashify(component.name); const componentLocalConfig = (component.local instanceof Array) ? component.local : []; while (componentLocalConfig.length < component.path.length) { componentLocalConfig.push([]); } const componentPath = ...
javascript
{ "resource": "" }
q34119
update
train
function update(args, done) { app = this.fractal; let typo3cli = path.join(typo3path, '../vendor/bin/typo3'); let typo3args = ['extbase', 'component:discover']; try { if (fs.statSync(typo3cli).isFile()) { typo3args.shift(); } } catch (e) { typo3cli = path.join(ty...
javascript
{ "resource": "" }
q34120
encodeURIParams
train
function encodeURIParams(params, prefix) { let parts = []; for (const name in params) { if (Object.prototype.hasOwnProperty.call(params, name)) { const paramName = prefix ? (`${prefix}[${encodeURIComponent(name)}]`) : encodeURIComponent(name); if (typeof params[name] === 'object'...
javascript
{ "resource": "" }
q34121
componentGraphUrl
train
function componentGraphUrl(component) { const context = ('variants' in component) ? component.variants().default().context : component.context; const graphUrl = url.parse(context.typo3); graphUrl.search = `?${encodeURIParams(Object.assign(context.request.arguments, { tx_twcomponentlibrary_component:...
javascript
{ "resource": "" }
q34122
configure
train
function configure(t3path, t3url, t3theme) { typo3path = t3path; typo3url = t3url; // If a Fractal theme is given if ((typeof t3theme === 'object') && (typeof t3theme.options === 'function')) { t3theme.addLoadPath(path.resolve(__dirname, 'lib', 'views')); // Add the graph panel ...
javascript
{ "resource": "" }
q34123
engine
train
function engine() { return { register(source, gapp) { const typo3Engine = require('./lib/typo3.js'); const handlebars = require('@frctl/handlebars'); typo3Engine.handlebars = handlebars({}).register(source, gapp); typo3Engine.handlebars.load(); ret...
javascript
{ "resource": "" }
q34124
drawUpperTriangle
train
function drawUpperTriangle(d, loc) { if (d == "r") { var first = {x: 50, y: 0}; var second = {x: 50, y: 50}; } else { var first = {x: 50, y: 0}; var second = {x: 0, y: 50}; } context.beginPath(); context.moveTo(loc.x, loc.y); context.lineTo(loc.x + fir...
javascript
{ "resource": "" }
q34125
drawBadCells
train
function drawBadCells(cells) { var context = c.getContext('2d'); var canvas = c; // from global. // Drawing bad cells var draw_loc = {x: 0, y: 0}; for (var i = 0; i < cells.length; i++) { var cell_info = cells[i]; var cell = cell_info[0]; var matched_entrances = cell_info[1]; var matched_exits...
javascript
{ "resource": "" }
q34126
getIndexForLoc
train
function getIndexForLoc(loc) { var col = Math.floor(loc.x / total_width); var row = Math.floor(loc.y / total_width); var index = col + (row * 5); return index; }
javascript
{ "resource": "" }
q34127
handleIncomingMessage
train
function handleIncomingMessage(event, message, source) { var blocks = event.split(':'), id = blocks[2] || blocks[1]; if (id in self.transactions && source in self.transactions[id]) { self.transactions[id][source].resolve([message, source]); } }
javascript
{ "resource": "" }
q34128
handleControlConnection
train
function handleControlConnection(connection) { connection.on('data', function (data) { console.log('Got command:', data.toString().trim()); var request = data.toString().trim().split(' '), cmd = request[0], target = request[1], newline = '\r\n', response; console.log('Command is:', cmd); s...
javascript
{ "resource": "" }
q34129
handleWorkerRestart
train
function handleWorkerRestart(worker, code, signal) { delete self.workers[worker.id]; if (self.reviveWorkers) { var zombie = cluster.fork({ config: JSON.stringify(self.config) }); self.workers[zombie.id] = zombie; } }
javascript
{ "resource": "" }
q34130
wait
train
function wait(id, callback) { var promises = []; self.transactions[id] = {}; lib.each(self.workers, function (worker) { var deferred = Q.defer(); self.transactions[id][worker.id] = deferred; promises.push(deferred.promise); }); Q.spread(promises, callback); }
javascript
{ "resource": "" }
q34131
pton
train
function pton(af, addr, dest, index) { switch (af) { case IPV4_OCTETS: return pton4(addr, dest, index) case IPV6_OCTETS: return pton6(addr, dest, index) default: throw new Error('Unsupported ip address.') } }
javascript
{ "resource": "" }
q34132
copycontext
train
function copycontext(context) { var t = {}; var keys = context.keys(); var i = keys.length; var k, v, j; while (i--) { k = keys[i]; if (k[0] == '_') continue; v = context.get(k); if (v && {}.toString.call(v) === '[object Function]') continue; try { ...
javascript
{ "resource": "" }
q34133
parseLine
train
function parseLine(line) { // except for the command, no field has a space, so we split by that and piece the command back together var parts = line.split(/ +/); return { user : parts[0] , pid : parseInt(parts[1]) , '%cpu' : parseFloat(parts[2]) , '%mem' : parseFloat(parts[3]) , vsz...
javascript
{ "resource": "" }
q34134
proxiedMethod
train
function proxiedMethod(params, path) { // Get the arguments that should be passed to the server var payload = Array.prototype.slice.call(arguments).slice(2); // Save the callback function for later use var callback = util.firstFunction(payload); // Transform the callback function in the arguments into a ...
javascript
{ "resource": "" }
q34135
doRequest
train
function doRequest(endpoint, payload, params, callback) { debug('Calling API endpoint: ' + endpoint + '.'); request .post(endpoint) .send({ payload: payload }) .set('Accept', 'application/json') .end(function(err, res) { if ((!res || !res.body) && !err) { err = new Error('No response ...
javascript
{ "resource": "" }
q34136
buildEndpoint
train
function buildEndpoint(config, path) { var host = config.host; var port = config.port; if (!host) throw new Error('No host is specified in proxied method config'); var base = host + (port ? ':' + port : ''); var fullpath = '/isomorphine/' + path; var endpoint = base + fullpath; debug('Built endpoint: '...
javascript
{ "resource": "" }
q34137
some
train
function some (list, test, cb) { assert("length" in list, "array must be arraylike") assert.equal(typeof test, "function", "predicate must be callable") assert.equal(typeof cb, "function", "callback must be callable") var array = slice(list) , index = 0 , length = array.length , hecomes = deza...
javascript
{ "resource": "" }
q34138
slice
train
function slice(args) { var l = args.length, a = [], i for (i = 0; i < l; i++) a[i] = args[i] return a }
javascript
{ "resource": "" }
q34139
Column
train
function Column (table, header, i) { this._table = table, this._header = header, this._i = i }
javascript
{ "resource": "" }
q34140
train
function (file, enc, cb) { var yaml_files = options.src; if (typeof yaml_files === 'string') { yaml_files = [yaml_files]; } var yaml_data = {}; // Read all files in order, and override if later files contain same values. for (var i = 0; i < yaml_files.lengt...
javascript
{ "resource": "" }
q34141
GLTFDracoMeshCompressionExtension
train
function GLTFDracoMeshCompressionExtension( json, dracoLoader ) { if ( !dracoLoader ) { throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' ); } this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION; this.json = json; this.dracoLoader = dracoLoader; THREE.DRACOLoader.getDecoderModule(...
javascript
{ "resource": "" }
q34142
train
function(iteratee, context) { context = context || this; for (var x = this.origin.x, x2 = this.corner.x; x < x2; x++) { for (var y = this.origin.y, y2 = this.corner.y; y < y2; y++) { iteratee.call(context, x, y); } } }
javascript
{ "resource": "" }
q34143
makeRouter
train
function makeRouter() { // Solving arguments var args = [].slice.call(arguments); var beforeMiddlewares = args.slice(0, -1), routes = args[args.length - 1]; var router = express.Router(); routes.forEach(function(route) { if (!route.url) throw Error('dolman.router: one route...
javascript
{ "resource": "" }
q34144
specs
train
function specs() { var routes = {}; // Reducing the app's recursive stack function reduceStack(path, items, item) { var nextPath; if (item.handle && item.handle.stack) { nextPath = join(path, (item.path || helpers.unescapeRegex(item.regexp) || '')); return items.concat(item.han...
javascript
{ "resource": "" }
q34145
reduceStack
train
function reduceStack(path, items, item) { var nextPath; if (item.handle && item.handle.stack) { nextPath = join(path, (item.path || helpers.unescapeRegex(item.regexp) || '')); return items.concat(item.handle.stack.reduce(reduceStack.bind(null, nextPath), [])); } if (item.route)...
javascript
{ "resource": "" }
q34146
GruntHorde
train
function GruntHorde(grunt) { this.cwd = process.cwd(); this.config = { initConfig: {}, loadNpmTasks: {}, loadTasks: {}, registerMultiTask: {}, registerTask: {} }; this.frozenConfig = {}; this.grunt = grunt; this.lootBatch = []; }
javascript
{ "resource": "" }
q34147
createRouter
train
function createRouter(modules) { debug('Creating a new router. Modules: ' + JSON.stringify(modules, null, 3)); var router = express(); router.use(bodyParser.json()); // Map the requested entity path with the actual serverside entity router.use('/isomorphine', methodLoader(modules)); // Proxy request pipe...
javascript
{ "resource": "" }
q34148
methodLoader
train
function methodLoader(modules) { return function(req, res, next) { if (req.path === '/') return next(); var path = req.path.substr(1).split('/'); var currModule = modules; var isLastIndex, p, method; debug('Looking for isomorphine entity in: ' + path.join('.')); for (var i = 0, len = path.l...
javascript
{ "resource": "" }
q34149
checkFallback
train
function checkFallback(obj) { var props = []; var hasFallback = []; var values = []; for (var prop in obj) { if (obj.hasOwnProperty(prop)) { var pro = obj[prop].prop; if (obj[prop].type === 'comment') { continue; } if (props.indexOf(...
javascript
{ "resource": "" }
q34150
train
function () { if (this.auth_url) { return this.auth_url; } var self = this, destination = { protocol: 'https', host: 'www.box.com', pathname: '/api/oauth2/authorize', search: querystring.stringify({ response_type: 'code', ...
javascript
{ "resource": "" }
q34151
getAbcKey
train
function getAbcKey(fifths, mode) { if (typeof mode === 'undefined' || mode === null) mode = 'major'; return circleOfFifths[mode][fifths]; }
javascript
{ "resource": "" }
q34152
getJSONId
train
function getJSONId(data) { var lines = data.split('\n'); for (var i = 0; i < lines.length; i++) { if (lines[i].indexOf('T:') > -1) { return lines[i].substr(lines[i].indexOf(':') + 1, lines[i].length); } } throw new Error('Could not determine "T:" field'); }
javascript
{ "resource": "" }
q34153
train
function(tune) { var ret = { attributes: { divisions: 1 /tune.getBeatLength(), clef: { line: 2 }, key: {}, time: {} } }; var measures = []; var measureCounter = 0; var barlineCounter = 0; // parse lines for (var l = 0; l < tune.lines.length; l++) { for (v...
javascript
{ "resource": "" }
q34154
train
function() { var attributes = { repeat: { left: false, right: false } }; var notes = []; /** * Set repeat left for measure */ this.setRepeatLeft = function () { attributes.repeat.left = true; }; /** * Set repeat right for measure */ this.setRepeatRight = function ()...
javascript
{ "resource": "" }
q34155
HeadCornerChartParser
train
function HeadCornerChartParser(grammar) { this.grammar = grammar; this.grammar.computeHCRelation(); logger.debug("HeadCornerChartParser: " + JSON.stringify(grammar.hc)); }
javascript
{ "resource": "" }
q34156
requireMethods
train
function requireMethods(dir) { if (!dir) dir = getCallerDirname(); var modules = {}; fs .readdirSync(dir) .filter(function(filename) { return filename !== 'index.js'; }) .forEach(function(filename) { var filePath = path.join(dir, filename); var Stats = fs.lstatSync(filePath); ...
javascript
{ "resource": "" }
q34157
getCallerDirname
train
function getCallerDirname() { var orig = Error.prepareStackTrace; Error.prepareStackTrace = function(_, stack){ return stack; }; var err = new Error(); Error.captureStackTrace(err, arguments.callee); var stack = err.stack; Error.prepareStackTrace = orig; var requester = stack[2].getFileName(); return p...
javascript
{ "resource": "" }
q34158
train
function (name, parent_id, done, config) { if (!_.isString(name) || !_.isNumber(parseInt(parent_id, 10))) { return done(new Error('Invalid params. Required - name: string, parent_id: number')); } this._request(['folders'], 'POST', done, null, { name: name, parent: {...
javascript
{ "resource": "" }
q34159
NixAttrReference
train
function NixAttrReference(args) { this.attrSetExpr = args.attrSetExpr; this.refExpr = args.refExpr; this.orExpr = args.orExpr; }
javascript
{ "resource": "" }
q34160
throwUnexpected
train
function throwUnexpected (attr, obj) { var e = Unexpected(attr, obj); Error.captureStackTrace(e, throwUnexpected); throw e; }
javascript
{ "resource": "" }
q34161
targz
train
function targz(stream, opts) { return exports.tar(stream.pipe(zlib.createGunzip()), opts); }
javascript
{ "resource": "" }
q34162
train
function( state ) { var key, clonedState = {}; for( key in state ) { if( key !== LOCAL ) { clonedState[ key ] = state[ key ]; } } return clonedState; }
javascript
{ "resource": "" }
q34163
train
function() { if( this.dsRecord && this.dsRecord.isReady && Object.keys( this.dsRecord.get() ).length === 0 && this.state ) { this.dsRecord.set( this.state ); } }
javascript
{ "resource": "" }
q34164
encrypt
train
function encrypt(salt, password) { var hash = crypto.createHash('sha256').update(salt + password).digest('base64'); return salt + hash; }
javascript
{ "resource": "" }
q34165
_toCamelCase
train
function _toCamelCase(str) { var newString = ''; var insideParens = false; newString += str[0].toLowerCase(); for (var i = 1; i < str.length; i++) { var char = str[i]; switch (char) { case ')': case '_': break; case '(': insideParens = true; break; default...
javascript
{ "resource": "" }
q34166
GithubBot
train
function GithubBot(options) { if (!(this instanceof GithubBot)) { return new GithubBot(options); } BaseBot.call(this, options); this.handlers(events); this.define('events', events); }
javascript
{ "resource": "" }
q34167
train
function () { var self = this; async.waterfall([ function (next) { if (!self.events) { self.events = new Datastore(); self.events.ensureIndex({ fieldName: 'event_id', unique: true }); self.eve...
javascript
{ "resource": "" }
q34168
train
function (query, opts, done, config) { if (!_.isString(query)) { return done(new Error('query must be a string.')); } opts = opts || {}; opts.query = query; this._request(['search'], 'GET', done, opts, null, null, null, null, config); }
javascript
{ "resource": "" }
q34169
hasExample
train
function hasExample ({ optional, example, details } = {}) { if (optional || example !== undefined) { return true; } if (details !== undefined) { const values = Object.keys(details).map((key) => details[key]); return values.every(hasExample); } return false; }
javascript
{ "resource": "" }
q34170
getExample
train
function getExample (obj) { if (isArray(obj)) { return removeOptionalWithoutExamples(obj).map(getExample); } const { example, details } = obj; if (example === undefined && details !== undefined) { const nested = {}; Object.keys(details).forEach((key) => { nested[key] = getExample(details[ke...
javascript
{ "resource": "" }
q34171
methodComparator
train
function methodComparator (a, b) { const sectionA = spec[a].section || ''; const sectionB = spec[b].section || ''; return sectionA.localeCompare(sectionB) || a.localeCompare(b); }
javascript
{ "resource": "" }
q34172
group
train
function group (frame) { let v, name, op; const entries = fields.map((field, index) => { name = ops[index]; op = scalar_operations.get('count'); if (name) { op = scalar_operations.get(name); if (!op) { op = scalar_op...
javascript
{ "resource": "" }
q34173
train
function(func, name) { return proxy.createProxy(func, handlers.beforeFunc, handlers.afterFunc, {attachMonitor: true}, name); }
javascript
{ "resource": "" }
q34174
train
function(name, args) { var callInstance = {name: name}; handlers.beforeFunc({name: name}, null, args, callInstance); return callInstance; }
javascript
{ "resource": "" }
q34175
train
function(args, callInstance) { handlers.afterFunc({name: callInstance.name}, null, args, callInstance); }
javascript
{ "resource": "" }
q34176
UploadButton
train
function UploadButton(props) { var onClick = function onClick() { var inputStyle = 'display:block;visibility:hidden;width:0;height:0'; var input = $('<input style="' + inputStyle + '" type="file" name="somename" size="chars">'); input.appendTo($('body')); input.change(function () { console.log('...
javascript
{ "resource": "" }
q34177
createProxies
train
function createProxies(config, map, parentPath) { parentPath = parentPath || []; var isBase = parentPath.length === 0; var proxies = {}; var path; for (var key in map) { if (map.hasOwnProperty(key)) { if (isObject(map[key])) { proxies[key] = createProxies(config, map[key], parentPath.conca...
javascript
{ "resource": "" }
q34178
getConfigFromBrowser
train
function getConfigFromBrowser() { var defaultLocation = { port: '80', hostname: 'localhost', protocol: 'http:' }; var wLocation = (global.location) ? global.location : defaultLocation; var location = { port: wLocation.port, host: wLocation.protocol + '//' + wLocation.hostname }; ...
javascript
{ "resource": "" }
q34179
withPreamble
train
function withPreamble (preamble, spec) { Object.defineProperty(spec, '_preamble', { value: preamble.trim(), enumerable: false }); return spec; }
javascript
{ "resource": "" }
q34180
withComment
train
function withComment (example, comment) { const constructor = example == null ? null : example.constructor; if (constructor === Object || constructor === Array) { Object.defineProperty(example, '_comment', { value: comment, enumerable: false }); return example; } // Convert primitives...
javascript
{ "resource": "" }
q34181
getDelay
train
function getDelay(start, interval) { const delta = process.hrtime(start); const nanosec = (delta[0] * 1e9) + delta[1]; /* eslint no-bitwise: ["error", { "int32Hint": true }] */ return Math.max((nanosec / 1e6 | 0) - interval, 0); }
javascript
{ "resource": "" }
q34182
format
train
function format(value, unitInfo) { const unit = unitInfo.unit; const precision = unitInfo.precision || 0; let v = 0; switch (unit) { case 'GB': v = value / GB; break; case 'MB': v = value / MB; break; default: v = value; break; } v = parseFloat(Number(v).toFix...
javascript
{ "resource": "" }
q34183
getHeapStatistics
train
function getHeapStatistics(unitInfo) { const data = v8.getHeapStatistics(); const keys = Object.keys(data); const result = {}; keys.forEach((key) => { result[key] = format(data[key], unitInfo); }); return result; }
javascript
{ "resource": "" }
q34184
getHeapSpaceStatistics
train
function getHeapSpaceStatistics(unitInfo) { const arr = v8.getHeapSpaceStatistics(); const result = {}; arr.forEach((item) => { const data = {}; const keys = Object.keys(item); keys.forEach((key) => { if (key === 'space_name') { return; } // replace the space_ key prefix ...
javascript
{ "resource": "" }
q34185
getMemoryUsage
train
function getMemoryUsage(unitInfo) { const data = process.memoryUsage(); const keys = Object.keys(data); const result = {}; keys.forEach((key) => { result[key] = format(data[key], unitInfo); }); return result; }
javascript
{ "resource": "" }
q34186
get
train
function get(arr, filter, defaultValue) { let result; arr.forEach((tmp) => { if (tmp && filter(tmp)) { result = tmp; } }); return result || defaultValue; }
javascript
{ "resource": "" }
q34187
convertUnit
train
function convertUnit(str) { const reg = /\.\d*/; const result = reg.exec(str); if (result && result[0]) { return { precision: result[0].length - 1, unit: str.substring(result[0].length + 1), }; } return { unit: str, }; }
javascript
{ "resource": "" }
q34188
getCpuUsage
train
function getCpuUsage(previousValue, start) { if (!previousValue) { return null; } const usage = process.cpuUsage(previousValue); const delta = process.hrtime(start); const total = Math.ceil(((delta[0] * 1e9) + delta[1]) / 1000); const usedPercent = Math.round(((usage.user + usage.system) / total) * 100)...
javascript
{ "resource": "" }
q34189
camelCaseData
train
function camelCaseData(data) { const result = {}; const keys = Object.keys(data); keys.forEach((k) => { const key = camelCase(k); const value = data[k]; if (isObject(value)) { result[key] = camelCaseData(value); } else { result[key] = value; } }); return result; }
javascript
{ "resource": "" }
q34190
flatten
train
function flatten(data, pre) { const prefix = pre || ''; const keys = Object.keys(data); const result = {}; keys.forEach((k) => { const value = data[k]; const key = [prefix, k].join('-'); if (isObject(value)) { Object.assign(result, flatten(value, key)); } else { result[key] = value; ...
javascript
{ "resource": "" }
q34191
performance
train
function performance() { /* eslint prefer-rest-params: 0 */ const args = Array.from(arguments); const interval = get(args, isNumber, 100); const fn = get(args, isFunction, noop); const unitInfo = convertUnit(get(args, isString, 'B').toUpperCase()); let start = process.hrtime(); let cpuUsage = process.cpuU...
javascript
{ "resource": "" }
q34192
consoleProxy
train
function consoleProxy(ob){ // list from http://nodejs.org/api/stdio.html var methods = ["dir", "time", "timeEnd", "trace", "assert"]; methods.forEach(function(method){ if (ob[method]) return; ob[method] = function(){ return console[method].apply(console, arguments); }; }); }
javascript
{ "resource": "" }
q34193
getOveruse
train
function getOveruse(duplicates, limit) { var duplicate; for (duplicate in duplicates) { if (duplicates[duplicate] < limit) { delete duplicates[duplicate] } } return keys(duplicates); }
javascript
{ "resource": "" }
q34194
use
train
function use (filepath, destination) { var startTime = Date.now(); var text = read(filepath); if (text !== false) { fs.writeFile(destination, jsx(text), function (err) { if (err) { throw err; } var endTime = Date.now(); log('[Finished in ' + (endTime - startTime) + 'ms]'); }); } else...
javascript
{ "resource": "" }
q34195
envar
train
function envar(key) { var i, value; // be extra paranoid if (typeof key != 'string' || !key) return undefined; // lookup according to the order for (i=0; i<state.order.length; i++) { if ((value = lookup[state.order[i]](key)) !== undefined) { return value; } } // nothing found retu...
javascript
{ "resource": "" }
q34196
roundedCorners
train
function roundedCorners(side, radius) { if (!radius) { radius = side || 10; side = 'all'; } if (side == 'all') { if (browserInfo().msie) { return { 'border-radius': radius, behavior: 'url(border-radius-ie.htc)', visibility: 'hidden' } } else if (br...
javascript
{ "resource": "" }
q34197
transpose
train
function transpose(matrix) { // For NxN matrix var n = matrix[0].length; var temp; // Walk through columns for (var i = 0, j = 0; i < n; i++) { j = i; // Walk through rows while (j < n) { if (i !== j) { temp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = temp; } j++; } }...
javascript
{ "resource": "" }
q34198
getConfig
train
function getConfig(react) { const loaders = [{ test: /\.js$/, exclude: /node_modules/, loader: 'babel', query: _util.babelFEOptions }, { test: /\.json$/, loader: 'json' }, { test: /jsdom/, loader: 'null' }]; if (react) { loaders.unshift({ test: /\.js$/, exclude...
javascript
{ "resource": "" }
q34199
getCompiler
train
function getCompiler(inPath, outPath, { library, libraryTarget }) { const compiler = (0, _webpack2.default)(_extends({}, getConfig(false), { devtool: _util.isProduction ? 'source-map' : 'eval-source-map', entry: ['babel-polyfill', inPath], output: { path: (0, _path.dirname)(outPath), filename: (0, _path.b...
javascript
{ "resource": "" }