_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q49000
serializeCommandResult
train
function serializeCommandResult(result) { const out = []; out.push(result.errorCode || 'null'); out.push(result.response || 'null'); if (result.myEvents && result.myEvents.length) { out.push('[' + result.myEvents.join(',') + ']'); } return '[' + out.join(',') + ']'; }
javascript
{ "resource": "" }
q49001
generateCommandPromise
train
function generateCommandPromise(cmdInfo, state, paramList) { const mod = cmdInfo.mod; const execute = () => mod.execute.apply(mod, paramList); if (cmdInfo.isAsync) { // Async user commands will need to take the response value, and feed it // to `state.respond` const isJson = mod.serialize === false; return...
javascript
{ "resource": "" }
q49002
createTimerPromise
train
function createTimerPromise(commandName, timeout) { let timer; const promise = new Promise((resolve, reject) => { if (timeout) { timer = setTimeout(() => reject(new UserCommandExecutionTimeout(commandName)), timeout); } }); promise.clear = () => clearTimeout(timer); return promise; }
javascript
{ "resource": "" }
q49003
processBatchHeader
train
function processBatchHeader(state, batch, cb) { if (messageHooks.length === 0) { return cb(); } var hookData = {}; for (var i = 0; i < batch.header.length; i += 1) { var header = batch.header[i]; if (header.name) { hookData[header.name] = header; } } async.eachSeries( messageHooks, function (hook...
javascript
{ "resource": "" }
q49004
respond
train
function respond(options, content, cache) { // cache the response var cached = that.responseCache.set(state, queryId, options, cache); // send the response back to the client cb(null, content, options); // log the execution time var msg = cached ? 'Executed and cached user command batc...
javascript
{ "resource": "" }
q49005
runCommand
train
function runCommand(output, cache, cmdIndex) { var cmd = batch.commands[cmdIndex]; if (cmd) { if (cacheContent.length !== 0 && isCachedCommand(cmd)) { logger.warning .data({ cmd: cmd.cmdName }) .log('Re-sending cached command response'); output += (output ? ',' : '[') + cacheCont...
javascript
{ "resource": "" }
q49006
MysqlVault
train
function MysqlVault(name, logger) { var that = this; // required exposed properties this.name = name; // the unique vault name this.archive = new Archive(this); // archivist bindings // internals this.mysql = null; // node-mysql library this.config = null; ...
javascript
{ "resource": "" }
q49007
setupModules
train
function setupModules(callback) { if (mage.core.processManager.isMaster) { return callback(); } mage.setupModules(callback); }
javascript
{ "resource": "" }
q49008
createApps
train
function createApps(callback) { if (mage.core.processManager.isMaster) { return callback(); } try { mage.core.app.createApps(); } catch (error) { return callback(error); } return callback(); }
javascript
{ "resource": "" }
q49009
MsgStream
train
function MsgStream(cfg) { assert(cfg, 'Cannot set up a message stream without configuration'); assert(cfg.transports, 'Cannot set up a message stream without transports configured'); EventEmitter.call(this); this.cfg = cfg; this.addressMap = {}; this.closing = false; }
javascript
{ "resource": "" }
q49010
lookupAddresses
train
function lookupAddresses(state, actorIds, cb) { if (!mage.session) { return cb(new StateError('Cannot find actors without the "session" module set up.', { actorIds: actorIds })); } mage.session.getActorAddresses(state, actorIds, cb); }
javascript
{ "resource": "" }
q49011
normalizeHost
train
function normalizeHost(host) { if (!host) { return host; } if (host[host.length - 1] === '.') { host = host.substring(0, host.length - 1); } return host; }
javascript
{ "resource": "" }
q49012
getUniqueName
train
function getUniqueName(service) { return service.name + service.type.name + service.type.protocol + service.replyDomain; }
javascript
{ "resource": "" }
q49013
MDNSService
train
function MDNSService(name, type, options) { var that = this; this.name = name; this.type = type; this.options = options; this.advertisement = null; this.browser = new mdns.Browser(mdns.makeServiceType(this.name, this.type)); this.browser.on('serviceUp', function (service) { // we know that node, don't re-an...
javascript
{ "resource": "" }
q49014
RedisVault
train
function RedisVault(name, logger) { // required exposed properties this.name = name; // the unique vault name this.archive = new Archive(this); // archivist bindings this.client = null; // node-redis instance this.logger = logger; }
javascript
{ "resource": "" }
q49015
getLanguageFromQueryString
train
function getLanguageFromQueryString() { if (location.search.length >= 1) { var language = parseURL(location.search).language if (language) { return language; } else if (jQuery.inArray(location.search.substr(1), languages) != -1) { return location.search.substr(1); } } ...
javascript
{ "resource": "" }
q49016
generateNewQueryString
train
function generateNewQueryString(language) { var url = parseURL(location.search); if (url.language) { url.language = language; return stringifyURL(url); } return language; }
javascript
{ "resource": "" }
q49017
pushURL
train
function pushURL(language) { if (!history) { return; } var hash = window.location.hash; if (hash) { hash = hash.replace(/^#+/, ''); } history.pushState({}, '', '?' + generateNewQueryString(language) + '#' + hash); // save language as next default localStorage.setItem("language", langu...
javascript
{ "resource": "" }
q49018
bindToFile
train
function bindToFile(filePath, cb) { // resolve the path and shorten it to avoid long-path bind errors // NOTE: only do so on non-windows systems if (process.platform !== 'win32') { filePath = pathRelative(process.cwd(), pathResolve(filePath)); } function callback(error) { server.removeListener('error', callb...
javascript
{ "resource": "" }
q49019
makePasswordHash
train
function makePasswordHash(password, cb) { try { const hash = hashes.create(exports.getHashConfiguration()); hash.fill(password, function (error) { cb(error, hash); }); } catch (error) { return cb(error); } }
javascript
{ "resource": "" }
q49020
pushIps
train
function pushIps(addresses, announced, useInternalAddresses) { if (!useInternalAddresses) { addresses = addresses.filter((address) => address.internal === false); } addresses = addresses .filter((address) => address.family === 'IPv4') .map((address) => address.address); return announced.concat(addresses); }
javascript
{ "resource": "" }
q49021
getAnnouncedIpsForInterface
train
function getAnnouncedIpsForInterface(ifaceName) { const addresses = interfaces[ifaceName]; if (!addresses) { throw new Error('Interface ' + ifaceName + ' could not be found'); } const announced = pushIps(addresses, [], true); assertNotEmpty(announced, 'Interface ' + ifaceName + ' does not define any IP address...
javascript
{ "resource": "" }
q49022
sortIndexes
train
function sortIndexes(indexes, sort) { function compare(a, b) { return a > b ? -1 : (b > a ? 1 : 0); } // format: [{ name: 'colName', direction: 'asc' }, { name: 'colName2', direction: 'desc' }] // direction is 'asc' by default indexes.sort(function (a, b) { var result = 0; for (var i = 0; i < sort.length ...
javascript
{ "resource": "" }
q49023
objMerge
train
function objMerge(a, b) { var obj = {}; Object.keys(a).forEach(function (key) { obj[key] = a[key]; }); Object.keys(b).forEach(function (key) { obj[key] = b[key]; }); return obj; }
javascript
{ "resource": "" }
q49024
lockAndLoad
train
function lockAndLoad() { // lock command execution if (!setFilePid(CMD_LOCK_FILE)) { err(chalk.red.bold('A command is already running, aborting...')); process.exit(EXIT_LOCKED); // abort the normal code flow return interrupt(); } process.once('exit', function () { // using "exit" ensures that it gets...
javascript
{ "resource": "" }
q49025
assertMsgServerIsEnabled
train
function assertMsgServerIsEnabled() { assert(cfgMmrp.bind, 'No MMRP bindings configured'); assert(cfgMsgStream, 'The message stream has been disabled.'); assert(cfgMsgStream.transports, 'The message stream has no configured transports.'); assert(serviceDiscovery.isEnabled(), 'Service discovery has not been configur...
javascript
{ "resource": "" }
q49026
lintJson
train
function lintJson(content) { try { jsonlint.parse(content); } catch (lintError) { if (typeof lintError.message === 'string') { lintError.message = lintError.message.replace(/\t/g, ' '); } throw lintError; } }
javascript
{ "resource": "" }
q49027
loadConfigFile
train
function loadConfigFile(configPath) { logger.debug('Loading configuration file at:', configPath); function loadConfig() { return fs.readFileSync(configPath, { encoding: 'utf8' }); } function parseConfig(content, extension) { switch (extension) { case '.js': return require(configPath); case '.yaml': ...
javascript
{ "resource": "" }
q49028
loadConfig
train
function loadConfig(dir, name, warn, defaultEmpty, isEnvironment) { var extensionlessSource = path.join(dir, name); var rawSource; var rawConfig; for (var i = 0; i < supportedTypes.length && !rawConfig; i++) { rawSource = extensionlessSource + supportedTypes[i]; if (fs.existsSync(rawSource)) { rawConfig = ...
javascript
{ "resource": "" }
q49029
MmrpNode
train
function MmrpNode(role, cfg) { EventEmitter.call(this); this.isRelay = (role === 'relay' || role === 'both'); this.isClient = (role === 'client' || role === 'both'); assert(this.isRelay || this.isClient, 'MmrpNode must be relay, client or both'); // keeping track of who we're connected to this.relays = {}; ...
javascript
{ "resource": "" }
q49030
exposePanopticonMethod
train
function exposePanopticonMethod(method) { exports[method] = function () { for (var i = 0; i < panoptica.length; i++) { var panopticon = panoptica[i]; panopticon[method].apply(panopticon, arguments); } }; }
javascript
{ "resource": "" }
q49031
transformer
train
function transformer(data, id) { function checkValue(obj) { if (!obj || typeof obj !== 'object') { return; } var keys = Object.keys(obj); if (keys.indexOf('value') !== -1) { obj.values = {}; obj.values[id] = obj.value; delete obj.value; return; } for (var i = 0; i < keys.length; i++) { ...
javascript
{ "resource": "" }
q49032
delivery
train
function delivery(data) { var name = data.name; // Update the gatheredData object with the new data for this panopticon and emit its update. // This emission fires for every delivery, and contains the complete data across all panoptica. // This means that data may appear to be repeated (unless you check time stamp...
javascript
{ "resource": "" }
q49033
pathToQuery
train
function pathToQuery(pathname) { if (typeof pathname !== 'string') { throw new Error('Invalid path: ' + pathname); } var path = pathname.split('/'); // Remove the useless '' (zeroth) element and the 'sampler' (first) element. var samplerPos = path.indexOf('sampler'); if (samplerPos !== -1) { path = path.sl...
javascript
{ "resource": "" }
q49034
requestResponseHandler
train
function requestResponseHandler(req, res, path) { if (panoptica.length === 0) { // not set up res.writeHead(500, { 'content-type': 'text/plain' }); res.end('Sampler has not been configured with any intervals'); return; } var queryPath; try { queryPath = pathToQuery(path); } catch (error) { // bad re...
javascript
{ "resource": "" }
q49035
prettifyStackTrace
train
function prettifyStackTrace(appName, clientConfig, stack) { if (!appName || !clientConfig || !Array.isArray(stack)) { return; } var app = mage.core.app.get(appName); if (!app) { return; } var responses = app.getResponsesForClientConfig(app.getBestConfig(clientConfig)); // On the client side, stacktrace.js...
javascript
{ "resource": "" }
q49036
replacer
train
function replacer(match, file, line, col) { line = parseInt(line, 10); col = parseInt(col, 10); for (var i = 0; i < responses.length; i++) { var meta = responses[i].meta; var sourcemap = meta && meta.sourcemaps && meta.sourcemaps[file]; if (!sourcemap) { continue; } var smc = new SourceMapCo...
javascript
{ "resource": "" }
q49037
ServiceNode
train
function ServiceNode(host, port, addresses, metadata) { this.host = host; this.port = port; this.addresses = addresses; this.data = metadata || {}; }
javascript
{ "resource": "" }
q49038
resolveFilesInParams
train
function resolveFilesInParams(params, files) { var fileIds = Object.keys(files || {}); var fileCount = fileIds.length; if (fileCount === 0) { return; } // scan all members for files, and collect children function addMembers(list, obj) { var keys = Object.keys(obj || {}); for (var i = 0; i < keys.length;...
javascript
{ "resource": "" }
q49039
addMembers
train
function addMembers(list, obj) { var keys = Object.keys(obj || {}); for (var i = 0; i < keys.length; i++) { list.push({ owner: obj, key: keys[i], value: obj[keys[i]] }); } }
javascript
{ "resource": "" }
q49040
parseBatchData
train
function parseBatchData(fullPath, req, rawData, files) { assert.equal(typeof fullPath, 'string', 'invalidPath'); var commandNames = fullPath.substr(fullPath.lastIndexOf('/') + 1).split(','); var commandCount = commandNames.length; var commands = new Array(commandCount); // split the string into lines var cmdDa...
javascript
{ "resource": "" }
q49041
parseMultipart
train
function parseMultipart(req, boundary, cb) { // multipart, the first part has to be the same format as single part post data var parser = MultipartParser.create(boundary); var files = {}; var cmdData = ''; parser.on('part', function (part) { var m, disp, partName, fileName, isCmdData; disp = part.headers['c...
javascript
{ "resource": "" }
q49042
parseSinglepart
train
function parseSinglepart(req, cb) { // single part req.setEncoding('utf8'); var cmdData = ''; req.on('data', function (chunk) { cmdData += chunk; }); req.on('end', function () { logger.verbose('Finished reading', req.method, 'request.'); cb(null, cmdData, null); }); }
javascript
{ "resource": "" }
q49043
parseHttpBody
train
function parseHttpBody(req, cb) { // check for multipart streams that can contain file uploads var contentType = req.headers['content-type']; var m = contentType && contentType.match(/^multipart\/form-data; boundary=(.+)$/); if (m && m[1]) { parseMultipart(req, m[1], cb); } else { parseSinglepart(req, cb); ...
javascript
{ "resource": "" }
q49044
mgetAggregate
train
function mgetAggregate(queries, options, retriever, cb) { // queries: [{ topic: 'foo', index: { id: 1 } }, { topic: 'bar', index: { id: 'abc' } }] // OR: // queries: { uniqueID: { topic: 'foo', index: { id: 1 } }, uniqueID2: { etc } const getQueryOptions = (query) => Object.assign({}, options, query.options); ...
javascript
{ "resource": "" }
q49045
wash
train
function wash(obj) { if (!obj) { return {}; } var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (obj[key] === undefined) { delete obj[key]; } } return obj; }
javascript
{ "resource": "" }
q49046
ClientVault
train
function ClientVault(name, logger) { this.name = name; this.archive = new Archive(this); // archivist bindings this.state = null; this.logger = logger; }
javascript
{ "resource": "" }
q49047
FileVault
train
function FileVault(name, logger) { this.name = name; this.archive = new Archive(this); // archivist bindings this.allowExpire = true; this.path = undefined; this.logger = logger; this._timers = {}; }
javascript
{ "resource": "" }
q49048
createKeyFolders
train
function createKeyFolders(key, fullPath, cb) { // NOTE: We check after first character, since a leading slash will be omitted by path.join if (key.indexOf(path.sep) <= 0) { return cb(); } mkdirp(path.dirname(fullPath), cb); }
javascript
{ "resource": "" }
q49049
createZooKeeperClient
train
function createZooKeeperClient(options) { options = options || {}; if (!options.hosts) { throw new Error('Missing configuration server.discoveryService.options.hosts for ZooKeeper'); } // client options, with better defaults than node-zookeeper-client provides var clientOpts = options.options || {}; clientO...
javascript
{ "resource": "" }
q49050
ZooKeeperService
train
function ZooKeeperService(name, type, options) { this.name = name; this.type = type; this.options = options; this.closed = false; this.announcing = false; this.discovering = false; // this is the base path we will use to announce this service this.baseAnnouncePath = ['/mage', this.name, this.type].join('/'); ...
javascript
{ "resource": "" }
q49051
Store
train
function Store() { this.cache = new LocalStash(30); this.ttl = getTTL(); this._forward = function () { logger.error('No forwarder defined'); }; logger.verbose('Messages will expire after', this.ttl, 'seconds.'); }
javascript
{ "resource": "" }
q49052
proxy
train
function proxy(req, endpoint) { var source = req.connection; var target; source.pause(); target = net.connect(endpoint, function proxyHandler() { // the header has already been consumed, so we must recreate it and send it first target.write(recreateRequestHeader(req)); target.pipe(source); source.pipe(t...
javascript
{ "resource": "" }
q49053
Messenger
train
function Messenger(namespace) { assert(namespace, 'A namespace is required to use the process messenger.'); assert(Object.prototype.toString.call(namespace) === '[object String]', 'The namespace must be a string.'); this.namespace = namespace; this.setupWorker(); this.setupMaster(); }
javascript
{ "resource": "" }
q49054
bindMessageListener
train
function bindMessageListener(worker) { worker.on('message', function (msg) { // Ignore the message if it doesn't belong to the namespace if (msg.namespace !== that.namespace) { return; } // If the address is '*', it's a broadcast message // Send the message to all the workers if (msg.to === '*'...
javascript
{ "resource": "" }
q49055
getIdsFromPayload
train
function getIdsFromPayload(payload, conf, path) { return payload.map(function (payloadPiece) { return getId(payloadPiece, conf, path, payload); }); }
javascript
{ "resource": "" }
q49056
setDeepValue
train
function setDeepValue(target, path, value) { var keys = getKeysFromPath(path); var lastKey = keys.pop(); var deepRef = getDeepRef(target, keys.join('.')); if (deepRef && deepRef.hasOwnProperty(lastKey)) { deepRef[lastKey] = value; } return target; }
javascript
{ "resource": "" }
q49057
pushDeepValue
train
function pushDeepValue(target, path, value) { var deepRef = getDeepRef(target, path); if (!isWhat.isArray(deepRef)) return; return deepRef.push(value); }
javascript
{ "resource": "" }
q49058
popDeepValue
train
function popDeepValue(target, path) { var deepRef = getDeepRef(target, path); if (!isWhat.isArray(deepRef)) return; return deepRef.pop(); }
javascript
{ "resource": "" }
q49059
shiftDeepValue
train
function shiftDeepValue(target, path) { var deepRef = getDeepRef(target, path); if (!isArray(deepRef)) return; return deepRef.shift(); }
javascript
{ "resource": "" }
q49060
getId
train
function getId(payloadPiece, conf, path, fullPayload) { if (isObject(payloadPiece)) { if (payloadPiece.id) return payloadPiece.id; if (Object.keys(payloadPiece).length === 1) return Object.keys(payloadPiece)[0]; } if (isString(payloadPiece)) return payloadPiece; error('wildcardFormatWrong', conf, path,...
javascript
{ "resource": "" }
q49061
checkIdWildcardRatio
train
function checkIdWildcardRatio(ids, path, conf) { var match = path.match(/\*/g); var idCount = isArray(match) ? match.length : 0; if (ids.length === idCount) return true; error('mutationSetterPropPathWildcardIdCount', conf); return false; }
javascript
{ "resource": "" }
q49062
getDeepRef
train
function getDeepRef() { var target = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var path = arguments.length > 1 ? arguments[1] : undefined; var keys = getKeysFromPath(path); if (!keys.length) return target; var obj = target; while (obj && keys.length > 1) { obj = obj[keys.s...
javascript
{ "resource": "" }
q49063
sortCssDecls
train
function sortCssDecls (cssDecls, sortOrder) { if (sortOrder === 'alphabetically') { timsort(cssDecls, (a, b) => { if (a.type === 'decl' && b.type === 'decl') { return comparator(a.prop, b.prop); } else { return compareDifferentType(a, b); } }); } else { timsort(cssDecls...
javascript
{ "resource": "" }
q49064
shouldHide
train
function shouldHide(schema, options, target, doc, transformed, pathname) { let hideTarget = hide + target // Is hiding turned off? if (options[hideTarget] === false) { return false } // Test hide by option or schema return ( testOptions(options, pathname) || testSchema(schema, hide, doc, trans...
javascript
{ "resource": "" }
q49065
shouldCopyVirtual
train
function shouldCopyVirtual(schema, key, options, target) { return ( schema.pathType(key) === 'virtual' && [hide, `hide${target}`].indexOf(options.virtuals[key]) === -1 ) }
javascript
{ "resource": "" }
q49066
pathsFromTree
train
function pathsFromTree(obj, parentPath) { if (Array.isArray(obj)) { return parentPath } if (typeof obj === 'object' && obj.constructor.name === 'VirtualType') { return obj.path } if (obj.constructor.name === 'Schema') { obj = obj.tree } return Object.keys(obj).reduce((paths, key) => { if...
javascript
{ "resource": "" }
q49067
getPathnames
train
function getPathnames(options, schema) { let paths = pathsFromTree(schema.tree) Object.keys(options['defaultHidden']).forEach(path => { if (paths.indexOf(path) === -1) { paths.push(path) } }) return paths }
javascript
{ "resource": "" }
q49068
prepOptions
train
function prepOptions(options, defaults) { let _options = (options = options || {}) // Set defaults from options and default let ensure = ensureOption(options) options = { hide: ensure(hide, defaults.autoHide), hideJSON: ensure(hideJSON, defaults.autoHideJSON), hideObject: ensure(hideObject, default...
javascript
{ "resource": "" }
q49069
train
function(parts, value) { if (parts.length === 0) { return value } let obj = {} obj[parts[0]] = partsToValue(parts.slice(1), value) return obj }
javascript
{ "resource": "" }
q49070
train
function(obj, path, value) { const parts = path.split('.') /* traverse existing path to nearest object */ while (parts.length > 1 && typeof obj[parts[0]] === 'object') { obj = obj[parts.shift()] } /* set value */ obj[parts[0]] = partsToValue(parts.slice(1), value) }
javascript
{ "resource": "" }
q49071
InvalidValidationRuleParameter
train
function InvalidValidationRuleParameter(ruleParameter, reason) { var defaultMessage = sprintf('%s is not a valid rule parameter.', ruleParameter); this.message = reason ? sprintf('%s. %s', defaultMessage, reason) : defaultMessage; this.name = 'InvalidValidationRuleParameter'; Error.captureStackTrace(this, Inva...
javascript
{ "resource": "" }
q49072
downloadCode
train
function downloadCode(db, codePath) { return mkdir(codePath) .then(() => db.code.loadModules()) .then((modules) => Promise.all(modules.map(module => downloadCodeModule(db, module, codePath)))); }
javascript
{ "resource": "" }
q49073
downloadCodeModule
train
function downloadCodeModule(db, module, codePath) { const moduleName = module.replace(/^\/code\//, '').replace(/\/module$/, ''); const fileName = `${moduleName}.js`; const filePath = path.join(codePath, fileName); return db.code.loadCode(moduleName, 'module', false) .then((file) => writeFile(filePath, file...
javascript
{ "resource": "" }
q49074
mkdir
train
function mkdir(dir) { return new Promise((resolve, reject) => { fs.lstat(dir, (err, stats) => { // Resolve, when already is directory if (!err) return stats.isDirectory() ? resolve() : reject(new Error(`${dir} is not a direcotry.`)); // Try to create directory fs.mkdir(dir, (err) => { ...
javascript
{ "resource": "" }
q49075
writeFile
train
function writeFile(filePath, contents) { return new Promise((resolve, reject) => { fs.writeFile(filePath, contents, 'utf-8', (err, file) => { err ? reject(err) : resolve(); }) }); }
javascript
{ "resource": "" }
q49076
createDir
train
function createDir(dir) { const splitPath = dir.split('/'); splitPath.reduce((path, subPath) => { let currentPath; if(subPath != '.'){ currentPath = path + '/' + subPath; if (!fs.existsSync(currentPath)){ fs.mkdirSync(currentPath); } } else{ currentPath = subPath; ...
javascript
{ "resource": "" }
q49077
copy
train
function copy(args) { // TODO: Split arguments with destructure in the future const source = splitArg(args.source); const sourceApp = source[0]; const sourcePath = source[1]; const dest = splitArg(args.dest); const destApp = dest[0]; const destPath = dest[1]; return login(sourceApp, destApp).then((dbs)...
javascript
{ "resource": "" }
q49078
assertAlgorithms
train
function assertAlgorithms({name, iv, tagLength}){ if(Object.keys(params.ciphers).indexOf(name) < 0) throw new Error('UnsupportedAlgorithm'); if(params.ciphers[name].ivLength){ if(!(iv instanceof Uint8Array)) throw new Error('InvalidArguments'); if(iv.byteLength < 2 || iv.byteLength > 16) throw new Error('In...
javascript
{ "resource": "" }
q49079
assertSignVerify
train
function assertSignVerify(msg, jwkey, hash, algorithm, mode){ if (algorithm.name !== 'RSA-PSS' && algorithm.name !== 'RSASSA-PKCS1-v1_5') throw new Error('InvalidAlgorithm'); if (Object.keys(params.hashes).indexOf(hash) < 0) throw new Error('UnsupportedHash'); if (!(msg instanceof Uint8Array)) throw new Error('In...
javascript
{ "resource": "" }
q49080
setRDNSequence
train
function setRDNSequence(options) { const encodedArray = Object.keys(options).map((k) => { if (Object.keys(attributeTypeOIDMap).indexOf(k) < 0) throw new Error('InvalidOptionSpecification'); const type = attributeTypeOIDMap[k]; let value; if (['dnQualifier, countryName, serialNumber'].indexOf(k) >= 0)...
javascript
{ "resource": "" }
q49081
assertPbkdf
train
function assertPbkdf(p, s, c, dkLen, hash){ if (typeof p !== 'string' && !(p instanceof Uint8Array)) throw new Error('PasswordIsNotUint8ArrayNorString'); if (!(s instanceof Uint8Array)) throw new Error('SaltMustBeUint8Array'); if (typeof c !== 'number' || c <= 0)throw new Error('InvalidIterationCount'); if (typ...
javascript
{ "resource": "" }
q49082
rfc5869
train
async function rfc5869(master, hash, length, info, salt){ const len = params.hashes[hash].hashSize; // RFC5869 Step 1 (Extract) const prk = await hmac.compute(salt, master, hash); // RFC5869 Step 2 (Expand) let t = new Uint8Array([]); const okm = new Uint8Array(Math.ceil(length / len) * len); const uint...
javascript
{ "resource": "" }
q49083
compileWASM
train
function compileWASM (config) { // check that emscripten path is correct if (!fs.existsSync(config.emscripten_path)) { return process.stdout.write(colors.red(`Error: Could not find emscripten directory at ${config.emscripten_path}\n`)); } const shellScript = getShellScript(config); // format exported...
javascript
{ "resource": "" }
q49084
insertEventListener
train
function insertEventListener (config) { let outFile = path.join(process.cwd(), config.outputfile); let tempFile = `${outFile.slice(0, outFile.lastIndexOf('.'), 0)}.temp${outFile.slice(outFile.lastIndexOf('.'))}`; // read in generated emscripten file fs.readFile(outFile, 'utf-8', (err1, data) => { if (err1) ...
javascript
{ "resource": "" }
q49085
cleanDistDir
train
function cleanDistDir(dir) { /* istanbul ignore else */ if (dir !== process.cwd()) { fs.stat(dir, (err) => { if (!err) { del.sync([dir]); } fs.mkdirSync(dir); }); } }
javascript
{ "resource": "" }
q49086
processCss
train
async function processCss({ from, to, banner }) { const src = await readFile(from, 'utf8'); const { plugins, options } = await postcssLoadConfig({ from, to, map: { inline: false }, }); const sourceCss = banner + src; const result = await postcss(plugins).process(sourceCss, options); compileWa...
javascript
{ "resource": "" }
q49087
humanizeSize
train
function humanizeSize(bytes) { const index = Math.floor(Math.log(bytes) / Math.log(1024)); if (index < 0) return ''; return `${+((bytes / 1024) ** index).toFixed(2)} ${units[index]}`; }
javascript
{ "resource": "" }
q49088
gitDescribe
train
function gitDescribe() { try { const reference = execSync( 'git describe --always --dirty="-dev"', ).toString().trim(); return reference; } catch (error) { /* eslint-disable-next-line no-console */ /* tslint:disable-next-line no-console */ console.log(error); } }
javascript
{ "resource": "" }
q49089
makeHtml
train
function makeHtml({ file, basePath = '/', content = '%CSS%\n%JS%', exclude, include = ['**/*.css'], inlineCss = false, onCss = css => css, scriptAttr = 'defer', template = path.join(__dirname, 'template.html'), title, ...data }) { const filter = createFilter(include, exclude); // if `template...
javascript
{ "resource": "" }
q49090
postcssRollup
train
function postcssRollup({ content = [ '__sapper__/build/*.html', '__sapper__/build/*.js', // FIXME: Using `dist` is the most reliable but requires 2 builds // 'dist/**/*.html', // 'dist/**/*.js', 'src/**/*.html', 'src/**/*.js', ], context = {}, exclude = [], include = ['**/*.css'], ...
javascript
{ "resource": "" }
q49091
VirtualStats
train
function VirtualStats(config) { for (var key in config) { if (!config.hasOwnProperty(key)) { continue; } this[key] = config[key]; } }
javascript
{ "resource": "" }
q49092
HerokuAddonStrategy
train
function HerokuAddonStrategy(options) { if (!options || !options.sso_salt) throw new Error('Passport Heroku Addon strategy requires a sso_salt'); passport.Strategy.call(this); this.name = 'heroku-addon'; this._sso_salt = options.sso_salt; this._passReqToCallback = options.passReqToCallback; }
javascript
{ "resource": "" }
q49093
reportSuccess
train
function reportSuccess(message) { const chalk = require('chalk'); console.log(chalk.green(message)); console.log(''); }
javascript
{ "resource": "" }
q49094
reportSucceededProcess
train
function reportSucceededProcess(_message) { const emoji = require('node-emoji').emoji; console.log(''); console.log(emoji.tada, emoji.tada, emoji.tada); }
javascript
{ "resource": "" }
q49095
reportRunningTask
train
function reportRunningTask(taskname) { const icon = require('./ci-icon'); function done(success) { success ? console.log(`${icon.success()} ${taskname}`) : console.log(`${icon.error()} ${taskname}`); } return done; }
javascript
{ "resource": "" }
q49096
processResult
train
function processResult(result) { return { whenErrorIs: (errorCode) => { if ( errorCode === EAUDITNOLOCK && packageLockHasNotBeenFound(result) ) { const summary = result.error.summary || ''; result.error.summary = `packag...
javascript
{ "resource": "" }
q49097
removePackageLockFrom
train
function removePackageLockFrom(projectDir, response) { try { const file = pathJoin(projectDir, 'package-lock.json'); unlink(file); return response; } catch (error) { if (error.code === 'ENOENT') { return response; } if (response) { response...
javascript
{ "resource": "" }
q49098
removeIgnoredVulnerabilities
train
function removeIgnoredVulnerabilities(response, options) { try { const ignoredVulnerabilities = getIgnoredVulnerabilities(options); if (ignoredVulnerabilities && ignoredVulnerabilities.length === 0) { return response; } const filteredResponse = JSON.parse(JSON.stringify(r...
javascript
{ "resource": "" }
q49099
getLevelsToAudit
train
function getLevelsToAudit(options) { const auditOptions = getNpmAuditOptions(options); const auditLevelOption = auditOptions && auditOptions['--audit-level'] ? auditOptions['--audit-level'] : auditLevel.low; const filteredLevels = []; // prettier-ignore switch (audit...
javascript
{ "resource": "" }