_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 execute()
.then((response) => state.respond(response, isJson));
} else {
// Callback-based user commands are expected to call `state.respond`
// on their own; all we need to do is promisify
return new Promise((resolve) => paramList.push(resolve) && execute());
}
}
|
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, cb) {
var data = hookData[hook.name];
if (!data) {
// if the hook wasn't mentioned in the RPC call, and it's not required to be executed, ignore it
if (!hook.required) {
return cb();
}
data = { name: hook.name };
}
hook.fn(state, data, batch, cb);
},
function (error) {
if (error) {
// error while handling hooks (probably parse errors)
return cb(error);
}
// some hooks may have caused mutations (eg: session touch), so distribute these first
state.archivist.distribute(cb);
}
);
}
|
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 batch' :
'Executed user command batch (could not cache)';
logger.debug
.data({
batch: batch.commandNames,
queryId: queryId,
durationMsec: duration(),
options: options,
dataSize: content.length
})
.log(msg);
}
|
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 ? ',' : '[') + cacheContent.shift();
return setImmediate(runCommand, output, cache, cmdIndex + 1);
}
return that.executeCommand(cmd, session, metaData, function (error, response) {
if (error) {
// should never happen
return cb(error);
}
if (headerEvents && headerEvents.length) {
response.myEvents = response.myEvents || [];
response.myEvents = headerEvents.concat(response.myEvents);
headerEvents = null;
}
const serializedResponse = serializeCommandResult(response);
output += (output ? ',' : '[') + serializedResponse;
if (isCachedCommand(cmd)) {
cache += (cache ? ',' : '[') + JSON.stringify(serializedResponse);
}
setImmediate(runCommand, output, cache, cmdIndex + 1);
});
}
// close the output JSON array
output += ']';
if (cache === '') {
cache = '[]';
} else {
cache += ']';
}
// turn results array into a reportable response (possibly gzipped)
var options = {
mimetype: CONTENT_TYPE_JSON
};
if (!shouldCompress(output, acceptedEncodings)) {
return respond(options, output, cache);
}
return compress(output, function (error, compressed) {
if (error) {
// error during compression, send the original
respond(options, output, cache);
} else {
options.encoding = 'gzip';
respond(options, compressed, cache);
}
});
}
|
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; // the URI that connections will be established to
this.pool = null; // node-mysql connection pool
this.logger = logger;
/* jshint camelcase:false */
// connection is here for backward compat, please use pool from now on
this.__defineGetter__('connection', function () {
logger.debug('Accessing the "connection" property on the mysql vault is deprecated, please' +
' use the "pool" property');
return that.pool;
});
}
|
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-announce it
if (services[getUniqueName(service)]) {
return;
}
// this is our representation of a node, it contains the host, ips, port and metadata of a service
var node = new ServiceNode(normalizeHost(service.host), service.port, service.addresses, service.txtRecord);
services[getUniqueName(service)] = node;
that.emit('up', node);
});
this.browser.on('serviceDown', function (service) {
// retrieve the service object
var node = services[getUniqueName(service)];
// we never saw that node go up, don't emit a down
if (!node) {
return;
}
that.emit('down', node);
// remove the data we knew about it
delete services[getUniqueName(service)];
});
this.browser.on('error', function (error, service) {
that.emit('error', error, service);
});
}
|
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);
}
}
return false;
}
|
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", language);
}
|
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', callback);
if (error) {
if (error.code === 'EADDRINUSE') {
error.message =
filePath + ' already exists. Perhaps the server did not shut down ' +
'cleanly. Try removing the file and starting again. (' + error.code + ')';
} else {
error.message = 'Error while binding to ' + filePath + ' (' + error.code + ')';
}
return cb(error);
}
logger.notice('HTTP Server bound to', filePath);
return cb();
}
// listen() can throw, despite the error listener
// this happens in cluster mode if the stdio channels have been closed by the master
server.on('error', callback);
try {
server.listen(filePath, function (error) {
if (error) {
return callback(error);
}
fs.chmod(filePath, parseInt('777', 8), callback);
});
} catch (error) {
// listen() can throw, despite the error listener
// this happens in cluster mode if the stdio channels have been closed by the master
setImmediate(function () {
callback(error);
});
}
}
|
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 addresses');
return announced;
}
|
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 && result === 0; i++) {
var prop = sort[i].name;
var factor = sort[i].direction === 'desc' ? -1 : 1;
result = factor * compare(a[prop], b[prop]);
}
return result;
});
}
|
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 removed, even if there was an exception
destroyFilePid(CMD_LOCK_FILE);
});
return loadAppStatus();
}
|
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 configured');
}
|
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':
return jsYaml.safeLoad(content, { filename: configPath });
case '.json':
try {
return JSON.parse(content);
} catch (error) {
// Try to provide more specific syntax errors
lintJson(content);
// If no syntax errors are found, throw a generic error
throw new Error('There was a problem loading a configuration file: ' + configPath);
}
case '.json5':
return JSON5.parse(content);
default:
throw new Error(`Configuration file is an unsupported type [${supportedTypes.join(', ')}]: ` + configPath);
}
}
var extension = path.extname(configPath);
var content;
try {
content = loadConfig();
} catch (error) {
throw new ConfigurationError('Failed to read configuration file', configPath, error);
}
try {
return parseConfig(content, extension);
} catch (error) {
throw new ConfigurationError('Failed to parse configuration file', configPath, error);
}
}
|
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 = loadConfigFile(rawSource);
}
}
if (!rawConfig) {
if (warn) {
logger.info(
'No configuration content of name "' + name + '" was loaded from directory:',
configDir
);
}
if (!defaultEmpty) {
return;
}
rawSource = module.filename;
rawConfig = {};
}
if (rawConfig && isEnvironment) {
rawConfig = loadEnvironment(rawConfig);
}
return { source: rawSource, config: 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 = {}; // my peers, master-relay or both { identity: RelayConnection }
this.clients = {}; // my clients { identity: ClientConnection }
// router
this.routerPort = null;
this.router = null;
if (this.isRelay) {
this.router = createRouter(cfg);
var routerUri = this.router.getsockopt(zmq.ZMQ_LAST_ENDPOINT);
if (routerUri) {
this.routerPort = parseInt(routerUri.substr(routerUri.lastIndexOf(':') + 1), 10);
// Share MMRP master port through the environment
process.env[ENV_MAGE_MMRP_MASTER_PORT] = this.routerPort;
// Generate the cluster ID based on the port the master listens on
this.clusterId = serviceDiscovery.helpers.generateId(this.routerPort);
// Set the identity of the router socket to the cluster ID
this.router.setsockopt(zmq.ZMQ_IDENTITY, new Buffer(this.clusterId));
}
} else {
// Retrieve the cluster ID from the environment
const masterPort = parseInt(process.env[ENV_MAGE_MMRP_MASTER_PORT], 10);
// Generate the cluster ID based on the port the master listens on
this.clusterId = serviceDiscovery.helpers.generateId(masterPort);
}
// dealer
this.identity = this.isRelay ? this.clusterId : createDealerIdentity(this.clusterId);
this.dealer = createDealer(this.identity);
assert.equal(this.identity, this.dealer.getsockopt(zmq.ZMQ_IDENTITY));
// mmrp socket event handling
this._setupSocketEventHandling();
// mmrp internal message handling
this.on('delivery.mmrp.handshake', this._handleHandshake);
}
|
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++) {
checkValue(obj[keys[i]]);
}
}
checkValue(data);
return data;
}
|
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 stamps of course).
gatheredData[name] = data;
exports.emit('updatedData', gatheredData);
// The delivery is data for this panopticon only, the others are not emitted here. That's also
// how we keep the data in our buffer.
var obj = {};
obj[name] = data;
if (bufferLength > 0) {
bufferedData.push(obj);
}
exports.emit('panopticonDelivery', obj);
// Maintain a maximum buffer length for each panopticon (remove the oldest samples).
if (bufferedData.length > bufferLength) {
bufferedData.splice(0, bufferedData.length - bufferLength);
}
}
|
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.slice(samplerPos + 1);
}
// If the request had a trailing '/', remove the resulting empty final element in the path.
if (path[path.length - 1] === '') {
path.pop();
}
return path;
}
|
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 request
res.writeHead(400, { 'content-type': 'text/plain' });
res.end('Failed to parse query path: ' + path);
return;
}
var data = exports.query(queryPath);
if (data === undefined) {
logger.verbose('Could not find path', queryPath, 'in sampler. Available:', Object.keys(gatheredData));
res.writeHead(404, { 'content-type': 'text/plain' });
res.end('There is no data available at "' + queryPath.join('/') + '" at this time.');
return;
}
try {
data = JSON.stringify(data, null, ' ');
} catch (jsonError) {
logger.error('Error serializing sampler data:', jsonError);
res.writeHead(500, { 'content-type': 'text/plain' });
res.end('Error while serializing data');
return;
}
res.writeHead(200, { 'content-type': 'application/json' });
res.end(data);
}
|
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 has turned each entry into "symbol@file:line:col".
// Now try to source-map our way through it.
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 SourceMapConsumer(sourcemap);
var pos = smc.originalPositionFor({ line: line, column: col });
if (pos) {
return pos.name + ' (' + file + ':' + pos.line + ':' + pos.column + ')';
}
}
return match;
}
for (var i = 0; i < stack.length; i++) {
var frame = stack[i];
if (typeof frame === 'string') {
// rewrite the stack frame and put it back in the stack
stack[i] = frame.replace(/^.+?@(.+?):([0-9]+):([0-9]+)$/, replacer);
}
}
}
|
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 SourceMapConsumer(sourcemap);
var pos = smc.originalPositionFor({ line: line, column: col });
if (pos) {
return pos.name + ' (' + file + ':' + pos.line + ':' + pos.column + ')';
}
}
return match;
}
|
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; i++) {
list.push({
owner: obj,
key: keys[i],
value: obj[keys[i]]
});
}
}
var list = [];
addMembers(list, params);
for (var i = 0; i < list.length && fileCount > 0; i++) {
var member = list[i];
if (!member.value) {
continue;
}
var type = typeof member.value;
if (type === 'object') {
// append children to the end of the list
addMembers(list, member.value);
} else if (type === 'string' && files[member.value]) {
// file found for this property, so assign it
var file = files[member.value];
logger.verbose('Accepted file', '"' + file.partName + '":', file.fileName);
member.owner[member.key] = file;
delete files[member.value];
fileCount -= 1;
}
}
}
|
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 cmdData = rawData.split('\n');
// line 0 is the header
var header;
try {
header = JSON.parse(cmdData[0]);
} catch (error) {
logger.error
.data('data', cmdData[0])
.data('error', error.message)
.log('Error parsing command header.');
}
assert(Array.isArray(header), 'invalid command header');
for (var i = 0; i < commandCount; i++) {
var commandData = cmdData[i + 1]; // +1 to offset the header at index 0
var params;
try {
params = JSON.parse(commandData) || {};
} catch (e) {
logger.error.data(commandData).log('Error parsing command data.');
throw e;
}
if (files) {
resolveFilesInParams(params, files);
}
commands[i] = {
name: commandNames[i],
params: params
};
}
return {
transport: {
type: 'http',
req: req
},
rawData: rawData, // useful for hashing
header: header,
commands: commands,
commandNames: commandNames // useful for logging
};
}
|
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['content-disposition'];
if (!disp) {
// unidentifiable parts cannot be used
logger.warning.data('partHeaders', part.headers).log('Received an unidentifyable part, skipping.');
return;
}
m = disp.match(/name="(.+?)"/);
if (!m) {
// unnamed parts cannot be used
logger.warning.data('partHeaders', part.headers).log('Received an unnamed part, skipping.');
return;
}
partName = m[1];
logger.verbose('Receiving multipart-part:', partName);
isCmdData = (partName === 'cmddata');
m = disp.match(/filename="(.+?)"/);
if (m) {
// a filename is optional
fileName = m[1];
}
// the first part is ready and is expected to be the same format as single part post data
var data = [];
part.on('data', function (chunk) {
if (isCmdData) {
// treat as utf8
cmdData += chunk.toString('utf8');
} else {
data.push(chunk);
}
});
if (!isCmdData) {
part.on('end', function () {
// create the files object for the following files, the command center can take care of the rest
files[partName] = {
data: data,
partName: partName,
fileName: fileName,
type: part.headers['content-type']
};
});
}
});
// It has been observed that the "end" event on the parser would fire more than once. This might
// be related to Node.js 0.10 streams. To avoid the situation, we use once('end') instead of
// on('end').
parser.once('end', function () {
logger.verbose('Finished reading multipart', req.method, 'request.');
cb(null, cmdData, files);
});
// pipe all incoming data straight into the multipart parser
req.pipe(parser);
}
|
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);
const arrayQuery = () => async.mapSeries(queries, (query, callback) => {
retriever(query, getQueryOptions(query), callback);
}, cb);
function objectQuery() {
const queryIds = Object.keys(queries);
const result = {};
async.forEachSeries(
queryIds,
(queryId, callback) => {
const query = queries[queryId];
retriever(query, getQueryOptions(query), function (error, data) {
result[queryId] = data;
callback(error);
});
},
(error) => cb(error, error ? null : result)
);
}
if (Array.isArray(queries)) {
arrayQuery();
} else if (queries && typeof queries === 'object') {
objectQuery();
} else {
cb(new TypeError('mget queries must be an Array or an Object'));
}
}
|
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 || {};
clientOpts.sessionTimeout = clientOpts.hasOwnProperty('sessionTimeout') ? clientOpts.sessionTimeout : 30000;
clientOpts.spinDelay = clientOpts.hasOwnProperty('spinDelay') ? clientOpts.spinDelay : 1000;
clientOpts.retries = clientOpts.hasOwnProperty('retries') ? clientOpts.retries : 3;
// connect to the database
var client = zooKeeper.createClient(options.hosts, clientOpts);
client.on('connected', function () {
logger.verbose('ZooKeeper connection established');
});
client.on('connectedReadOnly', function () {
logger.error('ZooKeeper connection established to a read-only server');
});
client.on('disconnected', function () {
logger.verbose('ZooKeeper connection dropped');
});
client.on('expired', function () {
logger.verbose('ZooKeeper client session expired');
});
client.on('authenticationFailed', function () {
logger.error('ZooKeeper authentication failed');
});
return client;
}
|
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('/');
// those are the nodes we know on the given path
this.nodes = [];
// node data is stored apart
this.services = {};
this.connectTimer = null;
this.clearCredentialsTimer = null;
// Initial setup
this.reset();
}
|
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(target);
source.resume();
});
target.setTimeout(0);
target.setNoDelay(true);
target.setKeepAlive(true, 0);
return target;
}
|
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 === '*') {
that.broadcast(msg.name, msg.data, msg.from);
}
// If the address is 'master', emit an event with the message details
// If the message is a broadcast message, it should also emit an event
if (msg.to === 'master' || msg.to === '*') {
that.emit(msg.name, msg.data, msg.from);
return;
}
// If the master is not the recipient, forward the message
that.send(msg.to, msg.name, msg.data, msg.from);
});
}
|
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, payloadPiece);
return false;
}
|
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.shift()];
}
var key = keys.shift();
if (obj && obj.hasOwnProperty(key)) {
return obj[key];
}
}
|
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, (a, b) => {
if (a.type === 'decl' && b.type === 'decl') {
const aIndex = sortOrder.indexOf(a.prop);
const bIndex = sortOrder.indexOf(b.prop);
return comparator(aIndex, bIndex);
} else {
return compareDifferentType(a, b);
}
});
}
}
|
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, transformed)
|| testSchema(schema, hideTarget, doc, transformed)
)
}
|
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 (typeof obj[key] !== 'object' || typeof obj[key].type !== 'undefined') {
paths.push(joinKey(parentPath, key))
return paths
}
return [].concat(paths, pathsFromTree(obj[key], joinKey(parentPath, key)))
}, [])
}
|
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, defaults.autoHideObject),
defaultHidden: Object.assign({}, ensure(defaultHidden, defaults.defaultHidden)),
virtuals: ensure(virtuals, defaults.virtuals),
}
// Add to list of default hidden
if (typeof _options[hidden] === 'object') {
options[defaultHidden] = Object.assign(options[defaultHidden], _options[hidden])
}
if (options[hide] === false) {
options[hideJSON] = false
options[hideObject] = false
}
return options
}
|
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, InvalidValidationRuleParameter);
}
|
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))
.then(() => console.log(`Module ${moduleName} downloaded.`));
}
|
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) => {
err ? reject(err) : resolve();
});
})
})
}
|
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;
}
return currentPath
}, '')
}
|
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) => {
const sourceDB = dbs[0];
const destDB = dbs[1];
return normalizeArgs(sourceDB, sourcePath, destDB, destPath).then((paths) => {
const sourcePath = paths[0];
const destPath = paths[1];
return streamFrom(sourceDB, sourcePath).then((args) => {
const rs = args[0];
const size = args[1];
return streamTo(destDB, destPath, rs, size);
});
});
});
}
|
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('InvalidIVLength');
if(params.ciphers[name].staticIvLength && (params.ciphers[name].ivLength !== iv.byteLength)) throw new Error('InvalidIVLength');
}
if(params.ciphers[name].tagLength && tagLength){
if(!Number.isInteger(tagLength)) throw new Error('InvalidArguments');
if(tagLength < 4 || tagLength > 16) throw new Error('InvalidTagLength');
}
}
|
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('InvalidMessageFormat');
if (jwkey.kty !== 'RSA') throw new Error('InvalidJwkRsaKey');
if (algorithm.name === 'RSA-PSS'){
checkPssLength(mode, {k: jseu.encoder.decodeBase64Url(jwkey.n).length, hash, saltLength: algorithm.saltLength});
}
return true;
}
|
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) {
if (k === 'countryName' && options[k].length !== 2) throw new Error('InvalidCountryNameCode');
value = rfc5280.DirectoryString.encode({type: 'printableString', value: options[k]}, 'der');
}
else value = rfc5280.DirectoryString.encode({type: 'utf8String', value: options[k]}, 'der');
return {type, value};
});
return [encodedArray];
}
|
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 (typeof dkLen !== 'number' || dkLen <= 0) throw new Error('InvalidDerivedKeyLength');
if (Object.keys(params.hashes).indexOf(hash) < 0) throw new Error('UnsupportedHashAlgorithm');
return true;
}
|
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 uintInfo = new Uint8Array(info);
for(let i = 0; i < Math.ceil(length / len); i++){
const concat = new Uint8Array(t.length + uintInfo.length + 1);
concat.set(t);
concat.set(uintInfo, t.length);
concat.set(new Uint8Array([i+1]), t.length + uintInfo.length);
t = await hmac.compute(prk, concat, hash);
okm.set(t, len * i);
}
return okm.slice(0, length);
}
|
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 functions, if present, from config for shell script
let expFuncStr = '';
if (config.exported_functions && config.exported_functions.length > 0) {
let expFuncs = config.exported_functions.reduce((acc, val) => acc.concat('\'', val, '\'\,'), '[');
expFuncs = expFuncs.substring(0, expFuncs.length - 1).concat(']');
expFuncStr = `-s EXPORTED_FUNCTIONS="${expFuncs}" `;
}
// format flags from config for shell script
const flags = config.flags.reduce((acc, val) => acc.concat(' ', val), '');
// construct the default compile mode string.
let commandStr = `emcc -o ${config.outputfile} ${config.inputfile} ${expFuncStr} ${flags}`;
// generate a command string suitable for cmake
if(config.mode == "build") {
// assuming make
config.generator = config.generator ? config.generator : 'make';
switch(config.generator) {
case 'ninja':
config.gen_flag = 'Ninja';
default:
config.gen_flag = '"Unix Makefiles"';
break;
}
// need to triple escape double quotes
expFuncStr = expFuncStr.replace(/"/g, '\\\"');
let modFlags = flags.replace(/"/g, '\\\"');
let cxxFlagStr = `SET(WASM_CXXFLAGS "${modFlags} ${expFuncStr}" CACHE PATH "")`;
// pass through cmake configuration, inc. compiler flags, exported functions
commandStr = `cd wasm && emcmake cmake -G ${config.gen_flag} `+
`-DWASM_CXXFLAGS=\"${modFlags} ${expFuncStr}\" ` +
`.. && emmake ${config.generator} -j${cpuCount-1}`;
}
process.stdout.write(colors.cyan('Running emscripten...\n'));
// execute shell script
// exec(shellScript, (error, stdout, stderr) => {
exec(`
if [[ :$PATH: != *:"/emsdk":* ]]
then
# use path to emsdk folder, relative to project directory
BASEDIR="${config.emscripten_path}"
EMSDK_ENV=$(find "$BASEDIR" -type f -name "emsdk_env.sh")
source "$EMSDK_ENV"
fi
${commandStr}
`, { shell: '/bin/bash' }, (error, stdout, stderr) => {
// check for emcc compile errors
if (stderr) {
process.stderr.write(colors.red.bold('EMSCRIPTEN COMPILE ERROR\n'));
process.stderr.write(colors.white(stderr));
} else {
process.stdout.write(stdout);
insertEventListener(config);
process.stdout.write(colors.green.bold('Compiled C++ to WASM\n'));
}
});
}
|
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) process.stderr.write(colors.white(err1));
// insert eventListener
data = data.replace(/else\{doRun\(\)\}/g, 'else{doRun()}script.dispatchEvent(doneEvent);');
// write data to temporary file
fs.writeFile(tempFile, data, (err2) => {
if (err2) process.stderr.write(colors.white(err2));
// rename temporary file to original file name
fs.renameSync(tempFile, outFile);
});
});
}
|
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);
compileWarn('PostCSS', 'WARN', result.warnings());
// minify resulting CSS
const min = await new CleanCSS({
level: {
1: { all: true },
2: { all: true },
},
returnPromise: true,
sourceMap: true,
}).minify(result.css, result.map.toString());
compileWarn('CleanCSS', 'ERR', min.errors);
compileWarn('CleanCSS', 'WARN', min.warnings);
// clean-css removes the source map comment so we need to add it back in
min.styles = `${min.styles}\n/*# sourceMappingURL=${basename(
options.to,
)}.map */`;
writeFile(options.to, min.styles);
writeFile(`${options.to}.map`, min.sourceMap.toString());
return {
min,
result,
};
}
|
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` is a path and the file exists use its content otherwise
// assume that `template` is the actual template content itself
const htmlTemplate = existsSync(template)
? readFileSync(template, 'utf8')
: template;
/** @type {Object<string, string>} */
const styles = {};
return {
name: 'makeHtml',
transform(source, id) {
if (!filter(id)) return;
styles[id] = source;
return ''; // eslint-disable-line consistent-return
},
async generateBundle(outputOpts, bundle) {
// combine all style sheets
let css = '';
/* tslint:disable */
/* eslint-disable-next-line */
for (const id in styles) {
css += styles[id] || '';
}
/* tslint:enable */
if (typeof onCss === 'function') {
css = await Promise.resolve(onCss(css));
/* eslint-disable-next-line no-console */
if (!css) this.warn("onCss didn't return anything useful");
}
const jsFile = Object.values(bundle)[0].fileName || outputOpts.file;
const cssFile = jsFile.replace(/js$/, 'css');
/* eslint-disable-next-line no-nested-ternary */
const cssResult = !css.length
? ''
: inlineCss
? `<style>${css}</style>`
: `<link href=${basePath}${cssFile} rel=stylesheet>`;
let body = await Promise.resolve(content);
body = body.replace('%CSS%', cssResult);
body = body.replace(
'%JS%',
`<script src=${basePath}${jsFile} ${scriptAttr}></script>`,
);
const html = compileTemplate(htmlTemplate)({
title,
content: body,
...data,
}).trim();
if (!inlineCss) {
const cssOut = outputOpts.dir
? path.join(outputOpts.dir, cssFile)
: cssFile;
// write CSS file
writeFile(path.join(process.cwd(), cssOut), css, catchErr);
}
const fileOut = outputOpts.dir ? path.join(outputOpts.dir, file) : file;
// write HTML file
writeFile(path.join(process.cwd(), fileOut), html, catchErr);
},
};
}
|
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'],
optimize = process.env.NODE_ENV !== 'development',
whitelist = [],
} = {}) {
const filter = createFilter(include, exclude);
return {
name: 'postcss',
async transform(source, id) {
if (!filter(id)) return;
try {
const ctx = merge(
{ from: id, to: id, map: { inline: false, annotation: false } },
context,
);
const { plugins, options } = await postcssrc(ctx);
const result = await postcss(plugins).process(source, options);
result.warnings().forEach((warn) => {
this.warn(warn.toString(), { line: warn.line, column: warn.column });
});
// register sub-dependencies so rollup can monitor them for changes
if (result.map) {
const basePath = dirname(id);
// TODO: Don't use PostCSS private API
/* eslint-disable-next-line no-underscore-dangle */
result.map._sources._array.forEach((dep) => {
this.addWatchFile(join(basePath, dep));
});
}
if (!optimize) {
/* eslint-disable-next-line consistent-return */
return {
code: result.css,
map: result.map,
};
}
const purgecss = new Purgecss({
content,
whitelist,
css: [{ raw: result.css }],
keyframes: true,
});
const purged = purgecss.purge()[0];
/* eslint-disable-next-line consistent-return */
return {
code: purged.css,
map: purged.map,
};
} catch (err) {
if (err.name === 'CssSyntaxError') {
process.stderr.write(err.message + err.showSourceCode());
} else {
this.error(err);
}
}
},
};
}
|
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 = `package.json file is missing or is badly formatted. ${summary}`;
return result;
}
return result;
},
};
}
|
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.internalErrors = response.internalErrors || [];
response.internalErrors.push(error);
return response;
}
return 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(response, null, 2));
/* prettier-ignore */
filteredResponse.actions = filteredResponse.actions
? filteredResponse.actions
.map((action) => {
action.resolves = action.resolves.filter(
(resolve) =>
ignoredVulnerabilities.indexOf(`${resolve.id}`) < 0
);
return action;
})
.filter((action) => action.resolves.length > 0)
: [];
ignoredVulnerabilities.forEach(
(ignoredVulnerability) =>
delete filteredResponse.advisories[ignoredVulnerability]
);
const vulnerabilitiesMetadata = {
info: 0,
low: 0,
moderate: 0,
high: 0,
critical: 0,
};
const severities = {};
const advisories = filteredResponse.advisories;
for (const key in advisories) {
if (advisories.hasOwnProperty(key)) {
const advisory = advisories[key];
severities[`${advisory.id}`] = advisory.severity;
}
}
filteredResponse.actions.forEach((action) => {
action.resolves.forEach((resolve) => {
vulnerabilitiesMetadata[severities[`${resolve.id}`]] += 1;
});
});
filteredResponse.metadata.vulnerabilities = vulnerabilitiesMetadata;
return filteredResponse;
} catch (error) {
if (response) {
response.internalErrors = response.internalErrors || [];
response.internalErrors.push(error);
return response;
}
return response;
}
}
|
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 (auditLevelOption) {
case auditLevel.critical:
filteredLevels.push(auditLevel.critical);
break;
case auditLevel.high:
filteredLevels.push(auditLevel.high);
filteredLevels.push(auditLevel.critical);
break;
case auditLevel.moderate:
filteredLevels.push(auditLevel.moderate);
filteredLevels.push(auditLevel.high);
filteredLevels.push(auditLevel.critical);
break;
default:
filteredLevels.push(auditLevel.low);
filteredLevels.push(auditLevel.moderate);
filteredLevels.push(auditLevel.high);
filteredLevels.push(auditLevel.critical);
}
return filteredLevels;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.