_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q57600
|
loadSchemas
|
train
|
function loadSchemas(ajv) {
var metaSchema = helper.require('/lib/task-data/schemas/rackhd-task-schema.json');
ajv.addMetaSchema(metaSchema, 'rackhd-task-schema.json');
var fileNames = glob.sync(helper.relativeToRoot('/lib/task-data/schemas/*.json'));
_(fileNames).filter(function (filename) {
return path.basename(filename) !== 'rackhd-task-schema.json';
})
.forEach(function (filename) {
try {
var data = fs.readFileSync(filename).toString();
jsonlint.parse(data);
ajv.addSchema(JSON.parse(data), path.basename(filename));
}
catch(err) {
console.error('fail to add schema: ' + filename);
throw err;
}
})
.value();
return ajv;
}
|
javascript
|
{
"resource": ""
}
|
q57601
|
getSchema
|
train
|
function getSchema(ajv, name) {
var result = ajv.getSchema(name);
if (!result || !result.schema) {
throw new Error('cannot find the schema with name "' + name + '".');
}
return result.schema;
}
|
javascript
|
{
"resource": ""
}
|
q57602
|
validateData
|
train
|
function validateData(validator, schemaId, data, expected) {
var result = validator.validate(schemaId, data);
if (!result && expected || result && !expected) {
if (!result) {
return new Error(validator.errorsText());
}
else {
return new Error('expected schema violation, but get conformity.');
}
}
}
|
javascript
|
{
"resource": ""
}
|
q57603
|
getNumberOfTiles
|
train
|
function getNumberOfTiles(options) {
// Determine ground resolution if scale is only set
determineGroundResolution(options.tiles.resolutions);
// Counter of all tiles
let countOfAllTiles = 0;
// Calculate parameters of bbox
let widthM = options.task.area.bbox.xmax - options.task.area.bbox.xmin;
let heightM = options.task.area.bbox.ymax - options.task.area.bbox.ymin;
// Iterate over all resolutions
for (let int = 0; int < options.tiles.resolutions.length; int++) {
// Current resolution
let res = options.tiles.resolutions[int];
// Size of all tiles in sum
let widthPx = widthM / res.groundResolution;
let heightPx = heightM / res.groundResolution;
// Calculate tiles count of the current resolution
let tiles = {};
tiles.sizePx = options.tiles.maxSizePx - 2 * options.tiles.gutterPx;
tiles.xCount = Math.ceil(widthPx / tiles.sizePx);
tiles.yCount = Math.ceil(heightPx / tiles.sizePx);
// Note tiles count of current resolution
countOfAllTiles += tiles.xCount * tiles.yCount * options.wms.length;
}
return countOfAllTiles;
}
|
javascript
|
{
"resource": ""
}
|
q57604
|
handleTask
|
train
|
function handleTask(options, config, progress, callback) {
fs.ensureDir(options.task.workspace, (err) => {
if (err) {
// Call callback function with error.
callback(err);
} else {
// Workspace of this task
let ws = options.task.workspace + '/' + options.task.id;
// Create directory of task workspace
fs.ensureDir(ws, (err) => {
// Error
if (err) {
// Directory could not be created.
// Call callback function with error.
callback(err);
} else {
// No errors
// Handle all resolutions
handleResolution(options, ws, 0, config, progress, (err) => {
// Error
if (err) {
// It could not be handled all resolutions.
// Call callback function with error.
callback(err);
} else {
// No errors
// Call callback function without errors. Task was
// handled.
callback(null);
}
});
}
});
}
});
}
|
javascript
|
{
"resource": ""
}
|
q57605
|
load
|
train
|
function load(buf, file, cfg) {
if (typeof buf !== 'string') {
throw new TypeError('First argument must be a string.');
}
cfg = Object.assign({
maps: false,
lang: {script: 'js', template: 'html'},
plugins: {},
}, cfg);
let vue = {};
for (let section of extract(buf, ['script', 'template'])) {
let attrs = section.attrs;
let lang = has(attrs, 'lang') ? attrs.lang : cfg.lang[section.tag];
if (has(attrs, 'src')) {
let dir = file ? path.dirname(file) : process.cwd();
file = path.resolve(dir, attrs.src);
section.text = fs.readFileSync(file, 'utf8');
}
let transpiled = transpile(lang, section.text, {
file,
maps: cfg.maps,
offset: section.offset,
extra: Object.assign({}, cfg.plugins[lang]),
});
vue[section.tag] = transpiled.data;
if (cfg.maps && transpiled.map) {
sourceMapsCache.set(file, transpiled.map);
}
}
vue.script += injectTemplate(vue.template);
return vue.script;
}
|
javascript
|
{
"resource": ""
}
|
q57606
|
unregister
|
train
|
function unregister() {
let list = [];
// removes module and all its children from the node's require cache
let unload = (id) => {
let module = require.cache[id];
if (!module) return;
module.children.forEach((child) => unload(child.id));
delete require.cache[id];
list.push(id);
};
let sourceMapSupport = require.resolve('source-map-support');
Object.keys(require.cache).forEach((key) => {
if (path.extname(key) === VUE_EXT || key === sourceMapSupport) {
unload(key);
}
});
if (has(require.extensions, VUE_EXT)) {
delete require.extensions[VUE_EXT];
}
if (has(Error, 'prepareStackTrace')) {
delete Error.prepareStackTrace;
}
sourceMapsCache.clear();
return list;
}
|
javascript
|
{
"resource": ""
}
|
q57607
|
transpile
|
train
|
function transpile(lang, text, options) {
let plugin = `vuegister-plugin-${lang}`;
let langs = {
js() {
let map = (options.maps && options.offset > 0) ?
generateMap(text, options.file, options.offset) : null;
return {data: text, map};
},
html() {
return {data: text, map: null};
},
error(err) {
let error = `Plugin ${plugin} not found.` + os.EOL + err.message;
throw new Error(error);
},
};
// allows to override default html and js methods by plugins
try {
return require(plugin)(text, options);
} catch (err) {
return (langs[lang] || langs['error'](err))();
}
}
|
javascript
|
{
"resource": ""
}
|
q57608
|
generateMap
|
train
|
function generateMap(content, file, offset) {
if (offset <= 0) {
throw new RangeError('Offset parameter should be greater than zero.');
}
let generator = new sourceMap.SourceMapGenerator();
let options = {
locations: true,
sourceType: 'module',
};
for (let token of tokenizer(content, options)) {
let position = token.loc.start;
generator.addMapping({
source: file,
original: {line: position.line + offset, column: position.column},
generated: position,
name: token.value,
});
}
return generator.toJSON();
}
|
javascript
|
{
"resource": ""
}
|
q57609
|
installMapsSupport
|
train
|
function installMapsSupport() {
require('source-map-support').install({
environment: 'node',
handleUncaughtExceptions: false,
retrieveSourceMap: (source) => {
return sourceMapsCache.has(source) ?
{map: sourceMapsCache.get(source), url: source} :
null;
},
});
}
|
javascript
|
{
"resource": ""
}
|
q57610
|
kill
|
train
|
function kill (cb) {
if (!meteor) {
return cb();
}
meteor.once('exit', function (code) {
if (!code || code === 0 || code === 130) {
cb();
} else {
cb(new Error('exited with code ' + code));
}
});
meteor.kill('SIGINT');
meteor = null;
//--------------------------------------------
process.removeListener('exit', onProcessExit);
}
|
javascript
|
{
"resource": ""
}
|
q57611
|
getIgnoredFiles
|
train
|
function getIgnoredFiles () {
const filePath = path.join(process.cwd(), '.remarkignore')
const ignoredFilesSource = fs.existsSync(filePath) ? fs.readFileSync(filePath, {encoding: 'utf8'}) : ''
var ignoredFiles = ignoredFilesSource.split('\n')
ignoredFiles = ignoredFiles.filter(function (item) {
return item !== ''
})
return ignoredFiles
}
|
javascript
|
{
"resource": ""
}
|
q57612
|
train
|
function (err) {
"use strict";
var message = '';
if (typeof err === 'string') {
return new Error(err);
} else if (typeof err === 'object') {
if (err.cause) {
// probably a webdriver error
try {
message = JSON.parse(err.cause.value.message).errorMessage;
} catch ($) {
message = err.cause.value.message;
}
} else {
message = err.message || err.toString();
}
return new Error(message);
}
return new Error(err.toString());
}
|
javascript
|
{
"resource": ""
}
|
|
q57613
|
train
|
function () {
"use strict";
return new Promise(function (resolve, reject) {
var numberOfRetries = 5;
(function retry () {
var port = 4000 + Math.floor(Math.random() * 1000);
portscanner.checkPortStatus(port, 'localhost', function (err, status) {
if (err || status !== 'closed') {
if (--numberOfRetries > 0) {
setTimeout(retry);
} else {
reject('Cannot find a free port... giving up');
}
} else {
resolve(port);
}
});
})();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q57614
|
train
|
function (text, options) {
"use strict";
var marginX = options.marginX !== undefined ? options.marginX : 2;
var marginY = options.marginY !== undefined ? options.marginY : 1;
var margin = new Array(marginX+1).join(" ");
var indent = options.indent !== undefined ? options.indent : " ";
var maxLength = 0;
var linesOfText = text.split('\n');
var pattern = options.pattern || {
T: "/", B: "/", TR: "//", BR: "//", TL: "//", BL: "//", R: "//", L: "//"
};
linesOfText.forEach(function (line) {
maxLength = Math.max(maxLength, line.length);
});
var top = pattern.TL + new Array(2 * marginX + maxLength + 1).join(pattern.T) + pattern.TR;
var empty = pattern.L + new Array(2 * marginX + maxLength + 1).join(" ") + pattern.R;
var bottom = pattern.BL + new Array(2 * marginX + maxLength + 1).join(pattern.B) + pattern.BR;
linesOfText = linesOfText.map(function (line) {
while (line.length < maxLength) {
line += " ";
}
return pattern.L + margin + line + margin + pattern.R;
});
// vertical margin
for (var i=0; i<marginY; i++) {
linesOfText.unshift(empty);
linesOfText.push(empty);
}
// top and bottom lines
linesOfText.unshift(top);
linesOfText.push(bottom);
return linesOfText.map(function (line) {
return indent + line;
}).join('\n');
}
|
javascript
|
{
"resource": ""
}
|
|
q57615
|
resolveDeps
|
train
|
function resolveDeps(ast, result) {
const {
from: selfPath,
graph,
resolve,
rootPath,
rootTree,
} = result.opts;
const cwd = dirname(selfPath);
const rootDir = dirname(rootPath);
const processor = result.processor;
const self = graph[selfPath] = graph[selfPath] || {};
self.mark = TEMPORARY_MARK;
const moduleExports = {};
const translations = {};
ast.walkRules(moduleDeclaration, rule => {
if (importDeclaration.exec(rule.selector)) {
rule.walkDecls(decl => translations[decl.prop] = decl.value);
const dependencyPath = RegExp.$1.replace(/['"]/g, '');
const absDependencyPath = resolveModule(dependencyPath, {cwd, resolve});
if (!absDependencyPath) throw new Error(
'Can\'t resolve module path from `' +
cwd + '` to `' + dependencyPath + '`'
);
if (
graph[absDependencyPath] &&
graph[absDependencyPath].mark === TEMPORARY_MARK
) throw new Error(
'Circular dependency was found between `' +
selfPath + '` and `' + absDependencyPath + '`. ' +
'Circular dependencies lead to the unpredictable state and considered harmful.'
);
if (!(
graph[absDependencyPath] &&
graph[absDependencyPath].mark === PERMANENT_MARK
)) {
const css = readFileSync(absDependencyPath, 'utf8');
const lazyResult = processor.process(css, Object.assign({}, result.opts, {from: absDependencyPath}));
updateTranslations(translations, lazyResult.root.exports);
} else {
updateTranslations(translations, graph[absDependencyPath].exports);
}
return void rule.remove();
}
rule.walkDecls(decl => moduleExports[decl.prop] = decl.value);
rule.remove();
});
replaceSymbols(ast, translations);
for (const token in moduleExports)
for (const genericId in translations)
moduleExports[token] = moduleExports[token]
.replace(genericId, translations[genericId]);
self.mark = PERMANENT_MARK;
self.exports = ast.exports = moduleExports;
// resolve paths
if (cwd !== rootDir) resolvePaths(ast, cwd, rootDir);
const importNotes = comment({
parent: rootTree,
raws: {before: rootTree.nodes.length === 0 ? '' : '\n\n'},
text: ` imported from ${normalizeUrl(relative(rootDir, selfPath))} `,
});
const childNodes = ast.nodes.map(i => {
const node = i.clone({parent: rootTree});
if (
typeof node.raws.before === 'undefined' ||
node.raws.before === ''
) node.raws.before = '\n\n';
return node;
});
rootTree.nodes = rootTree.nodes.concat(importNotes, childNodes);
}
|
javascript
|
{
"resource": ""
}
|
q57616
|
Closure
|
train
|
function Closure (parent, listOfKeys, accessor) {
"use strict";
var closure = {};
listOfKeys = listOfKeys || [];
accessor = accessor || function () {};
parent && parent.__mixin__ && parent.__mixin__(closure);
listOfKeys.forEach(function (key) {
closure[key] = accessor.bind(null, key);
});
this.getValues = function () {
var values = {};
Object.keys(closure).forEach(function (key) {
values[key] = closure[key]();
if (values[key] === undefined) {
values[key] = null;
}
if (typeof values[key] === 'function') {
throw new Error('a closure variable must be serializable, so you cannot use a function');
}
});
return values;
}
this.setValues = function (values) {
Object.keys(values).forEach(function (key) {
closure[key](values[key]);
});
}
this.__mixin__ = function (object) {
Object.keys(closure).forEach(function (key) {
object[key] = closure[key];
});
}
}
|
javascript
|
{
"resource": ""
}
|
q57617
|
train
|
function(key, object) {
// Convert object to JSON and store in localStorage
var json = JSON.stringify(object);
persistenceStrategy.set(key, json);
// Then store it in the object cache
objectCache[key] = object;
}
|
javascript
|
{
"resource": ""
}
|
|
q57618
|
train
|
function(key) {
// First check to see if it's the object cache
var cached = objectCache[key];
if (cached) {
return cached;
}
// Deserialize the object from JSON
var json = persistenceStrategy.get(key);
// null or undefined --> return null.
if (json == null) {
return null;
}
try {
return JSON.parse(json);
} catch (err) {
return null;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q57619
|
train
|
function(lockKey, asyncFunction) {
var deferred = $q.defer();
// If the memory lock is set, error out.
if (memoryLocks[lockKey]) {
deferred.reject('in_progress');
return deferred.promise;
}
// If there is a stored lock but no memory lock, flag a persistence error
if (persistenceStrategy.get(lockKey) === 'locked') {
deferred.reject('last_call_interrupted');
deferred.promise.then(null, function() {
persistenceStrategy.remove(lockKey);
});
return deferred.promise;
}
// Set stored and memory locks
memoryLocks[lockKey] = true;
persistenceStrategy.set(lockKey, 'locked');
// Perform the async operation
asyncFunction().then(function(successData) {
deferred.resolve(successData);
// Remove stored and memory locks
delete memoryLocks[lockKey];
persistenceStrategy.remove(lockKey);
}, function(errorData) {
deferred.reject(errorData);
// Remove stored and memory locks
delete memoryLocks[lockKey];
persistenceStrategy.remove(lockKey);
}, function(notifyData) {
deferred.notify(notifyData);
});
return deferred.promise;
}
|
javascript
|
{
"resource": ""
}
|
|
q57620
|
train
|
function(key, value, isUnique) {
if(isUnique) {
return this._op(key, value, 'pushUnique');
} else {
return this._op(key, value, 'push');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q57621
|
BuildPromise
|
train
|
function BuildPromise(options) {
"use strict";
options = options || {};
var pathToApp = options.pathToApp || path.resolve('.');
var mongoUrl = options.mongoUrl || "http://localhost:27017";
var timeout = options.timeout || 120000;
var verbose = options.verbose !== undefined ? !!options.verbose : false;
var pathToMain = path.join(pathToApp, '.gagarin', 'local', 'bundle', 'main.js');
var pathToLocal = path.join(pathToApp, '.gagarin', 'local');
var env = Object.create(process.env);
return tools.getReleaseVersion(pathToApp).then(function (version) { return new Promise(function (resolve, reject) {
var args;
logs.system("detected METEOR@" + version);
if (version >= '1.0.0') {
args = [ 'build', '--debug', '--directory', pathToLocal ];
} else {
args = [ 'bundle', '--debug', '--directory', path.join(pathToLocal, 'bundle') ];
}
logs.system("spawning meteor process with the following args");
logs.system(JSON.stringify(args));
var buildTimeout = null;
var meteorBinary = tools.getMeteorBinary();
//make sure that platforms file contains only server and browser
//and cache this file under platforms.gagarin.backup
var platformsFilePath = path.join(pathToApp,'.meteor','platforms');
var platformsBackupPath = path.join(pathToApp,'.meteor','platforms.gagarin.backup');
fs.rename(platformsFilePath,platformsBackupPath,function(err,data){
fs.writeFile(platformsFilePath,'server\nbrowser\n',function(){
spawnMeteorProcess();
});
});
var output = "";
var meteor = null;
var spawnMeteorProcess = function(){
meteor = spawn(meteorBinary, args, {
cwd: pathToApp, env: env, stdio: verbose ? 'inherit' : 'ignore'
});
meteor.on('exit', function onExit (code) {
//switch back to initial content of platforms file
fs.rename(platformsBackupPath,platformsFilePath);
if (code) {
return reject(new Error('meteor build exited with code ' + code));
}
/*
var err = parseBuildErrors(output);
if (err) {
return reject(err);
}
*/
logs.system('linking node_modules');
linkNodeModules(pathToApp).then(function () {
logs.system('everything is fine');
resolve(pathToMain);
}).catch(reject);
buildTimeout = setTimeout(function () {
meteor.once('exit', function () {
reject(new Error('Timeout while waiting for meteor build to finish.'));
});
meteor.kill('SIGINT')
}, timeout);
clearTimeout(buildTimeout);
});
}
//-----------------------------------------------
/*
meteor.stdout.on('data', function onData (data) {
output += data.toString();
if (data.toString().match(/WARNING: The output directory is under your source tree./)) {
logMeteorOutput(' creating your test build in ' + path.join(pathToLocal, 'bundle') + '\n');
return;
}
logMeteorOutput(data);
});
meteor.stdout.on('error', function onError (data) {
console.log(chalk.red(data.toString()));
clearTimeout(buildTimeout);
});
*/
}); });
function logMeteorOutput(data) {
if (!verbose) {
return;
}
process.stdout.write(chalk.gray(stripAnsi(data)));
}
}
|
javascript
|
{
"resource": ""
}
|
q57622
|
ensureGagarinVersionsMatch
|
train
|
function ensureGagarinVersionsMatch(pathToApp, verbose) {
var pathToMeteorPackages = path.join(pathToApp, '.meteor', 'packages');
var nodeModuleVersion = require('../../package.json').version;
return new Promise(function (resolve, reject) {
utils.getGagarinPackageVersion(pathToApp).then(function (packageVersion) {
if (packageVersion === nodeModuleVersion) {
logs.system("node module and smart package versions match, " + packageVersion);
return resolve();
}
tools.getReleaseVersion(pathToApp).then(function (meteorReleaseVersion) {
if (meteorReleaseVersion < "0.9.0") {
// really, we can do nothing about package version
// without a decent package management system
logs.system("meteor version is too old to automatically fix package version");
return resolve();
}
logs.system("meteor add anti:gagarin@=" + nodeModuleVersion);
var meteor = spawn('meteor', [ 'add', 'anti:gagarin@=' + nodeModuleVersion ], {
stdio: verbose ? 'inherit' : 'ignore', cwd: pathToApp
});
/*
meteor.stdout.on('data', function (data) {
if (!verbose) {
return;
}
process.stdout.write(chalk.gray(stripAnsi(data)));
});
*/
meteor.on('error', reject);
meteor.on('exit', function (code) {
if (code > 0) {
return reject(new Error('meteor exited with code ' + code));
}
logs.system("anti:gagarin is now in version " + nodeModuleVersion);
resolve();
});
}).catch(reject);
}).catch(reject);
}); // Promise
}
|
javascript
|
{
"resource": ""
}
|
q57623
|
checkIfMeteorIsRunning
|
train
|
function checkIfMeteorIsRunning(pathToApp) {
var pathToMongoLock = path.join(pathToApp, '.meteor', 'local', 'db', 'mongod.lock');
return new Promise(function (resolve, reject) {
fs.readFile(pathToMongoLock, { encoding: 'utf8' }, function (err, data) {
if (err) {
// if the file does not exist, then we are ok anyway
return err.code !== 'ENOENT' ? reject(err) : resolve();
} else {
// isLocked iff the content is non empty
resolve(!!data);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q57624
|
smartJsonWarning
|
train
|
function smartJsonWarning(pathToApp) {
var pathToSmartJSON = path.join(pathToApp, 'smart.json');
return new Promise(function (resolve, reject) {
fs.readFile(pathToSmartJSON, { endcoding: 'urf8' }, function (err, data) {
if (err) {
// if the file does not exist, then we are ok anyway
return err.code !== 'ENOENT' ? reject(err) : resolve();
} else {
// since the file exists, first print a warning, then resolve ...
process.stdout.write(chalk.yellow(
tools.banner([
'we have detected a smart.json file in ' + pathToApp,
'since Gagarin no longer supports meteorite, this file will be ignored',
].join('\n'), {})
));
process.stdout.write('\n');
resolve();
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q57625
|
start
|
train
|
async function start() {
const mainRoute = server.addReactRoute(
"",
path.resolve(process.cwd(), "app/Routes.js")
);
await server.start(); //start server
console.log("started");
}
|
javascript
|
{
"resource": ""
}
|
q57626
|
providePlugins
|
train
|
function providePlugins(code) {
var chunks = [];
if (typeof code === 'string') {
code = code.split('\n');
}
chunks.push("function (" + Object.keys(plugins).join(', ') + ") {");
chunks.push(" return " + code[0]);
code.forEach(function (line, index) {
if (index === 0) return; // omit the first line
chunks.push(" " + line);
});
chunks.push("}");
return chunks;
}
|
javascript
|
{
"resource": ""
}
|
q57627
|
isolateScope
|
train
|
function isolateScope(code, closure) {
if (typeof code === 'string') {
code = code.split('\n');
}
var keys = Object.keys(closure).map(function (key) {
return stringify(key) + ": " + key;
});
var chunks = [];
chunks.push(
"function (" + Object.keys(closure).join(', ') + ") {",
" 'use strict';",
" return (function (userFunc, getClosure, action) {",
" try {",
" return action(userFunc, getClosure);",
" } catch (err) {",
// this should never happen ...
" return { error: err.message, closure: getClosure() };",
" }",
" })("
);
// the code provided by the user goes here
align(code).forEach(function (line) {
chunks.push(" " + line);
});
chunks[chunks.length-1] += ',';
chunks.push(
// the function returning current state of the closure
" function () {",
" return { " + keys.join(', ') + " };",
" },",
// the custom action
" arguments[arguments.length-1]",
" );",
"}"
);
return chunks;
}
|
javascript
|
{
"resource": ""
}
|
q57628
|
align
|
train
|
function align(code) {
if (typeof code === 'string') {
code = code.split('\n');
}
var match = code[code.length-1].match(/^(\s+)\}/);
var regex = null;
if (match && code[0].match(/^function/)) {
regex = new RegExp("^" + match[1]);
return code.map(function (line) {
return line.replace(regex, "");
});
}
return code;
}
|
javascript
|
{
"resource": ""
}
|
q57629
|
compile
|
train
|
function compile(code, closure) {
code = providePlugins(isolateScope(code, closure)).join('\n');
try {
return vm.runInThisContext('(' + code + ')').apply({}, values(plugins));
} catch (err) {
throw new Meteor.Error(400, err);
}
}
|
javascript
|
{
"resource": ""
}
|
q57630
|
Gagarin
|
train
|
function Gagarin (options) {
"use strict";
var write = process.stdout.write.bind(process.stdout);
var listOfFrameworks = [];
var numberOfLinesPrinted = 0;
// XXX gagarin user interface is defined here
require('./interface');
options.settings = tools.getSettings(options.settings);
options.ui = 'gagarin';
var factory = !options.parallel ? null : createParallelReporterFactory(function (allStats, elapsed) {
if (numberOfLinesPrinted > 0) {
write('\u001b[' + numberOfLinesPrinted + 'A')
}
write(' elapsed time: ' + Math.floor(elapsed / 100) / 10 + 's' + '\n\n');
numberOfLinesPrinted = 2 + table(allStats, write);
});
function getMocha() {
if (options.parallel === 0 && listOfFrameworks.length > 0) {
return listOfFrameworks[0];
}
var mocha = new Mocha(options);
if (factory) {
// overwrite the default reporter
mocha._reporter = factory(listOfFrameworks.length);
}
var reporter = mocha._reporter;
listOfFrameworks.push(mocha);
return mocha;
}; // getMocha
this.options = options;
this.addFile = function (file) {
getMocha().addFile(file);
}
this.runAllFrameworks = function (callback) {
var listOfErrors = [];
var pending = listOfFrameworks.slice(0);
var counter = 0;
var running = 0;
if (factory) {
// looks like parallel test runner, so make sure
// there are no logs which can break the table view
factory.reset();
process.stdout.write('\n\n');
write = logs2.block();
logs.setSilentBuild(true);
}
listOfFrameworks.forEach(function (mocha) {
mocha.loadFiles();
mocha.files = [];
});
function finish() {
if (factory) {
logs2.unblock();
factory.epilogue();
}
callback && callback(listOfErrors, counter);
}
function maybeFinish (action) {
if (running <= 0 && pending <= 0) {
finish();
} else {
action && action();
}
}
function update() {
var availableSlots = options.parallel > 0 ? options.parallel : 1;
if (running >= availableSlots) {
return false;
}
var next = pending.shift();
if (!next) {
maybeFinish();
return false;
}
running += 1;
try {
next.run(function (numberOfFailures) {
counter += numberOfFailures;
running -= 1;
maybeFinish(function () { // if not ...
while (update()); // run as many suites as you can
});
});
} catch (err) {
listOfErrors.push(err);
running -= 1;
maybeFinish();
return false;
}
return true;
}
while (update()); // run as many suites as you can
}
}
|
javascript
|
{
"resource": ""
}
|
q57631
|
getConfigFilePath
|
train
|
function getConfigFilePath () {
// Look for configuration file in current working directory
const files = fs.readdirSync(process.cwd())
const configFile = files.find((filePath) => {
return CONFIG_FILE_NAMES.find((configFileName) => filePath.indexOf(configFileName) !== -1)
})
// If no configuration file was found use recommend configuration
if (!configFile) {
return path.join(__dirname, '..', this.defaultConfig)
}
// Use configuration from current working directory
return path.join(process.cwd(), configFile)
}
|
javascript
|
{
"resource": ""
}
|
q57632
|
lintFile
|
train
|
function lintFile (linter, fileName) {
const fileContents = fs.readFileSync(fileName, {encoding: 'utf8'}).toString()
const report = linter.validate(fileContents)
const errors = report.error.count
const warnings = report.warn.count
if (errors || warnings) {
this.printFilePath(fileName)
report.error.data.forEach(logItem.bind(this))
report.warn.data.forEach(logItem.bind(this))
console.log('') // logging empty line
}
return report
}
|
javascript
|
{
"resource": ""
}
|
q57633
|
processByte
|
train
|
function processByte (stream, b) {
assert.equal(typeof b, 'number');
if (b === NEWLINE) {
stream.emit('newline');
}
}
|
javascript
|
{
"resource": ""
}
|
q57634
|
log
|
train
|
function log(fn, args, indent) {
if (args.length === 0) {
return;
}
// Assumes args are something you would pass into console.log
// Applies appropriate nesting
const indentation = _.repeat('\t', indent);
// Prepend tabs to first arg (if string)
if (_.isString(args[0])) {
args[0] = indentation + args[0];
} else {
args.splice(0, 0, indentation);
}
fn.apply(this, args);
}
|
javascript
|
{
"resource": ""
}
|
q57635
|
getFunction
|
train
|
function getFunction(name) {
return new Promise((resolve, reject) => {
lambda.getFunctionConfiguration({
FunctionName: name
}, function(err, data) {
if (err) return reject(err);
resolve(data);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q57636
|
getFunctionVersions
|
train
|
function getFunctionVersions(name, marker) {
// Grab functions
return new Promise((resolve, reject) => {
lambda.listVersionsByFunction({
FunctionName: name,
Marker: marker
}, function(err, data) {
if (err) return reject(err);
// Check if we can grab even more
if (data.NextMarker) {
return getFunctionVersions(name, data.NextMarker).then((versions) => {
resolve(data.Versions.concat(versions));
});
}
resolve(data.Versions);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q57637
|
functionPublishVersion
|
train
|
function functionPublishVersion(name, description, hash) {
return new Promise((resolve, reject) => {
lambda.publishVersion({
FunctionName: name,
Description: description,
CodeSha256: hash
}, function(err, data) {
if (err) return reject(err);
resolve(data);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q57638
|
getDirectoryTree
|
train
|
function getDirectoryTree(dir) {
const items = [];
return new Promise(function(resolve) {
fs.walk(dir)
.on('data', function (item) {
items.push(item.path);
})
.on('end', function () {
resolve(items);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q57639
|
replaceVariables
|
train
|
function replaceVariables(localPath, variables) {
return new Promise(function(resolve, reject) {
// Read the file
let body = fs.readFileSync(localPath, 'utf8');
// Do the replacement for all of the variables
const keys = Object.keys(variables);
keys.forEach(function(key) {
const value = variables[key];
const re = new RegExp(`"\\$${key}"`, 'g');
// Parse the value (to see if it is falsey)
try {
const parsed = JSON.parse(value);
body = body.replace(re, parsed ? `"${parsed}"` : `null`);
} catch (err) {
// Not valid JSON, treat it as a string
body = body.replace(re, `"${value}"`);
}
});
console.log('Variables replaced', body);
fs.writeFile(localPath, body, function(err) {
if (err) return reject(err);
resolve(localPath);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q57640
|
train
|
function(apiId) {
return APIG.getStages({
restApiId: apiId
}).promise().then(function(data) {
return data.item;
});
}
|
javascript
|
{
"resource": ""
}
|
|
q57641
|
train
|
function(apiId, stageName) {
return new Promise(function(resolve, reject) {
APIG.deleteStage({
restApiId: apiId,
stageName: stageName
}, function(err) {
if (err) {
// If no such stage, then success
if (err.code === 404 || err.code === 'NotFoundException') {
return resolve(apiId);
}
return reject(err);
}
resolve(apiId);
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q57642
|
train
|
function(apiId) {
return new Promise(function(resolve, reject) {
APIG.deleteRestApi({
restApiId: apiId
}, function(err) {
if (err) {
if (err.code === 404 || err.code === 'NotFoundException') {
// API didn't exist to begin with
return resolve(apiId);
}
return reject(err);
}
resolve(apiId);
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q57643
|
train
|
function(apiId) {
return module.exports.fetchExistingStages(apiId).then(function(stages) {
// If there are no stages, then delete the API
if (!stages || stages.length === 0) {
return module.exports.deleteAPI(apiId);
}
return apiId;
});
}
|
javascript
|
{
"resource": ""
}
|
|
q57644
|
train
|
function(apiName, swaggerPath) {
return new Promise(function(resolve, reject) {
fs.readFile(swaggerPath, function(err, data) {
if (err) return reject(err);
resolve(APIG.importRestApi({
body: data,
failOnWarnings: false
}).promise());
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q57645
|
train
|
function(apiId, swaggerPath) {
return new Promise(function(resolve, reject) {
fs.readFile(swaggerPath, function(err, data) {
if (err) return reject(err);
resolve(APIG.putRestApi({
restApiId: apiId,
body: data,
mode: 'overwrite'
}).promise());
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q57646
|
archiveDependencies
|
train
|
function archiveDependencies(cwd, pkg) {
let result = [];
if (pkg.path) {
result.push({
data: pkg.path,
type: 'directory',
name: path.relative(cwd, pkg.path)
});
}
pkg.dependencies.forEach(function(dep) {
if (dep.path) {
result.push({
data: dep.path,
type: 'directory',
name: path.relative(cwd, dep.path)
});
}
if (dep.dependencies) {
result = result.concat(archiveDependencies(cwd, dep));
}
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q57647
|
bundleLambda
|
train
|
function bundleLambda(lambda, exclude, environment, bundlePath, sourceMapPath) {
environment = environment || {};
exclude = exclude || [];
return new Promise(function(resolve, reject) {
const bundler = new Browserify(lambda.path, {
basedir: path.dirname(lambda.path),
standalone: lambda.name,
browserField: false,
builtins: false,
commondir: false,
ignoreMissing: true,
detectGlobals: true,
debug: !!sourceMapPath,
insertGlobalVars: {
process: function() {}
}
});
// AWS SDK should always be excluded
bundler.exclude('aws-sdk');
// Further things to exclude
[].concat(exclude).forEach(function(module) {
bundler.exclude(module);
});
// Envify (doesn't purge, as there are valid values
// that can be used in Lambda functions)
if (environment) {
bundler.transform(envify(environment), {
global: true
});
}
let stream = bundler.bundle();
if (sourceMapPath) {
stream = stream.pipe(exorcist(sourceMapPath));
}
stream.pipe(fs.createWriteStream(bundlePath));
stream.on('error', function(err) {
reject(err);
}).on('end', function() {
resolve();
});
});
}
|
javascript
|
{
"resource": ""
}
|
q57648
|
train
|
function(bucket, key, version, localPath) {
return S3.getObject({
Bucket: bucket,
Key: key,
VersionId: version
}).promise().then(function(data) {
return new Promise(function(resolve, reject) {
fs.writeFile(localPath, data.Body, function(err) {
if (err) return reject(err);
resolve(localPath);
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q57649
|
train
|
function(bucket, key, version) {
return S3.headObject({
Bucket: bucket,
Key: key,
VersionId: version
}).promise();
}
|
javascript
|
{
"resource": ""
}
|
|
q57650
|
cloudFormationDependencies
|
train
|
function cloudFormationDependencies(value) {
if (_.isString(value)) {
return [value];
}
if (!_.isObject(value)) {
return [];
}
const keys = _.keys(value);
if (keys.length !== 1) {
// CF functions always have a single key
return [];
}
const key = keys[0];
if (key === 'Fn::GetAtt') {
// Logical name of resource is the first value in array
return cloudFormationDependencies(value[key][0]);
}
if (key === 'Ref') {
// Value should be the logical name (but may be a further function)
return cloudFormationDependencies(value[key]);
}
if (key === 'Fn::Join') {
// Value is the combined string, meaning parts that are not
// string can all include dependencies
return _.flatten(value[key][1].filter(_.isObject).map(cloudFormationDependencies));
}
if (key === 'Fn::Select') {
// Value is picked from an array
const index = value[key][0];
const list = value[key][1];
return cloudFormationDependencies(list[index]);
}
// Unknown/Unhandled
return [];
}
|
javascript
|
{
"resource": ""
}
|
q57651
|
EE
|
train
|
function EE(fn, context, once) {
this.fn = fn;
this.context = context;
this.once = once || false;
}
|
javascript
|
{
"resource": ""
}
|
q57652
|
addListener
|
train
|
function addListener(emitter, event, fn, context, once) {
if (typeof fn !== 'function') {
throw new TypeError('The listener must be a function');
}
var listener = new EE(fn, context || emitter, once)
, evt = prefix ? prefix + event : event;
if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
else emitter._events[evt] = [emitter._events[evt], listener];
return emitter;
}
|
javascript
|
{
"resource": ""
}
|
q57653
|
clearEvent
|
train
|
function clearEvent(emitter, evt) {
if (--emitter._eventsCount === 0) emitter._events = new Events();
else delete emitter._events[evt];
}
|
javascript
|
{
"resource": ""
}
|
q57654
|
handleStream
|
train
|
function handleStream(target, encoding, cb) {
if (target.isNull()) {
return cb(null, target);
}
if (target.isStream()) {
return cb(error(target.path + ': Streams not supported for target templates!'));
}
try {
const tagsRegExp = getRegExpTags(opt, null);
target.contents = processContent(target, opt, tagsRegExp, [target.path]);
this.push(target);
return cb();
} catch (err) {
this.emit('error', err);
return cb();
}
}
|
javascript
|
{
"resource": ""
}
|
q57655
|
processContent
|
train
|
function processContent(target, opt, tagsRegExp, listOfFiles) {
let targetContent = String(target.contents);
const targetPath = target.path;
const files = extractFilePaths(targetContent, targetPath, opt, tagsRegExp);
// recursively process files
files.forEach(function (fileData) {
if (listOfFiles.indexOf(fileData.file.path) !== -1) {
throw error("Circular definition found. File: " + fileData.file.path + " referenced in a child file.");
}
listOfFiles.push(fileData.file.path);
const content = processContent(fileData.file, opt, tagsRegExp, listOfFiles);
listOfFiles.pop();
targetContent = inject(targetContent, String(content), opt, fileData.tags);
});
if (listOfFiles.length === 1 && !opt.quiet && files.length) {
log(
colors.cyan(files.length.toString()) +
' partials injected into ' +
colors.magenta(targetPath) +
'.');
}
return new Buffer.from(targetContent);
}
|
javascript
|
{
"resource": ""
}
|
q57656
|
inject
|
train
|
function inject(targetContent, sourceContent, opt, tagsRegExp) {
const startTag = tagsRegExp.start;
const endTag = tagsRegExp.end;
let startMatch;
let endMatch;
while ((startMatch = startTag.exec(targetContent)) !== null) {
// Take care of content length change
endTag.lastIndex = startTag.lastIndex;
endMatch = endTag.exec(targetContent);
if (!endMatch) {
throw error('Missing end tag for start tag: ' + startMatch[0]);
}
const toInject = [sourceContent];
// content part before start tag
let newContent = targetContent.slice(0, startMatch.index);
if (opt.removeTags) {
// Take care of content length change
startTag.lastIndex -= startMatch[0].length;
} else {
// <startMatch> + partial body + <endMatch>
toInject.unshift(startMatch[0]);
toInject.push(endMatch[0]);
}
const previousInnerContent = targetContent.substring(startTag.lastIndex, endMatch.index);
const indent = getLeadingWhitespace(previousInnerContent);
// add new content
newContent += toInject.join(indent);
// append rest of target file
newContent += targetContent.slice(endTag.lastIndex);
// replace old content with new
targetContent = newContent;
}
startTag.lastIndex = 0;
endTag.lastIndex = 0;
return targetContent;
}
|
javascript
|
{
"resource": ""
}
|
q57657
|
extractFilePaths
|
train
|
function extractFilePaths(content, targetPath, opt, tagsRegExp) {
const files = [];
const tagMatches = content.match(tagsRegExp.start);
if (tagMatches) {
tagMatches.forEach(function (tagMatch) {
const fileUrl = tagsRegExp.startex.exec(tagMatch)[1];
const filePath = setFullPath(targetPath, opt.prefix + fileUrl);
try {
const fileContent = stripBomBuf(fs.readFileSync(filePath));
files.push({
file: new File({
path: filePath,
cwd: __dirname,
base: path.resolve(__dirname, 'expected', path.dirname(filePath)),
contents: fileContent
}),
tags: getRegExpTags(opt, fileUrl)
});
} catch (e) {
if (opt.ignoreError) {
log(colors.red(filePath + ' not found.'));
} else {
throw error(filePath + ' not found.');
}
}
// reset the regex
tagsRegExp.startex.lastIndex = 0;
});
}
return files;
}
|
javascript
|
{
"resource": ""
}
|
q57658
|
train
|
function(child, parent) {
var ctor = function(){ };
ctor.prototype = parent.prototype;
child.__super__ = parent.prototype;
child.prototype = new ctor();
child.prototype.constructor = child;
child.fn = child.prototype
}
|
javascript
|
{
"resource": ""
}
|
|
q57659
|
consolidateFiles
|
train
|
function consolidateFiles (files, config) {
return Promise.resolve(files)
.then(files => {
var data = {};
files.forEach(file => {
var path = file.relative.split('.').shift().split(Path.sep);
if (path.length >= 2 && config.flattenIndex) {
var relPath = path.splice(-2, 2);
path = (relPath[0] === relPath[1] || relPath[1] === 'index')
? path.concat(relPath[0])
: path.concat(relPath);
}
data[path.join('.')] = JSON.parse(file.contents.toString());
});
data = sort(data);
const tree = expand(data);
const json = JSON.stringify(tree);
return Promise.resolve(new Vinyl({
base: '/',
cwd: '/',
path: '/' + (config.name || 'content.json'),
contents: new Buffer(json)
}));
});
}
|
javascript
|
{
"resource": ""
}
|
q57660
|
isBinary
|
train
|
function isBinary (file) {
return new Promise((resolve, reject) => {
isTextOrBinary.isText(Path.basename(file.path), file.contents, (err, isText) => {
if (err) return reject(err);
if (isText) file.isText = true;
resolve(file);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q57661
|
isJSON
|
train
|
function isJSON (file) {
try {
JSON.parse(file.contents.toString());
return true;
} catch (err) {
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q57662
|
toJSON
|
train
|
function toJSON (file, config) {
if (Path.extname(file.path) === '.json') {
if (!isJSON(file)) file.isInvalid = true;
return Promise.resolve(file);
}
let jsonFile = file.clone();
return Promise.resolve(file)
// parse YAML
.then(file => {
try {
let parsed = frontmatter(file.contents.toString());
return Promise.resolve(parsed);
} catch (err) {
return Promise.reject(err);
}
// parse and render Markdown
}).then(parsed => {
try {
let data = parsed.attributes;
data.body = config.renderer.call(config.context, parsed.body);
return Promise.resolve(data);
} catch (err) {
return Promise.reject(err);
}
// optional transforms and output
}).then(data => {
if (!data.title) {
let extracted = extractTitle(data.body, config.stripTitle);
if (typeof extracted === 'object') data = assign(data, extracted);
}
data.updatedAt = file.stat.mtime.toISOString();
if (config.transform) var transformedData = config.transform(data, file);
jsonFile.extname = '.json';
jsonFile.contents = new Buffer(JSON.stringify(transformedData || data));
return Promise.resolve(jsonFile);
});
}
|
javascript
|
{
"resource": ""
}
|
q57663
|
decorateEvents
|
train
|
function decorateEvents(comp) {
const prototype = /** @type {!Function} */(comp.constructor).prototype;
if (prototype.__events) return;
let events = {};
if (prototype.events) {
events = prototype.events;
}
Object.getOwnPropertyNames(prototype)
.map(propertyName => handlerMethodPattern.exec(propertyName))
.filter(x => x)
.forEach(([methodName, eventType, eventTarget]) => {
events[eventType] = events[eventType] || {};
/** @suppress {checkTypes} */
events[eventType][eventTarget] = comp[methodName];
})
prototype.__events = events;
}
|
javascript
|
{
"resource": ""
}
|
q57664
|
expectedFile
|
train
|
function expectedFile(file) {
const filePath = path.resolve(__dirname, 'expected', file);
return new File({
path: filePath,
cwd: __dirname,
base: path.resolve(__dirname, 'expected', path.dirname(file)),
contents: fs.readFileSync(filePath)
});
}
|
javascript
|
{
"resource": ""
}
|
q57665
|
encode
|
train
|
function encode(data, ch) {
if (!self.utfMouse) {
if (ch === 255) return data.push(0);
if (ch > 127) ch = 127;
data.push(ch);
} else {
if (ch === 2047) return data.push(0);
if (ch < 127) {
data.push(ch);
} else {
if (ch > 2047) ch = 2047;
data.push(0xC0 | (ch >> 6));
data.push(0x80 | (ch & 0x3F));
}
}
}
|
javascript
|
{
"resource": ""
}
|
q57666
|
_curry2
|
train
|
function _curry2 (fn) {
return function f2 (a, b) {
if (!arguments.length) {
return f2
}
if (arguments.length === 1) {
return function (_b) {
return fn(a, _b)
}
}
return fn(a, b)
}
}
|
javascript
|
{
"resource": ""
}
|
q57667
|
next
|
train
|
function next () {
let doNext = true
let decoded = false
const decodeCb = (err, msg) => {
decoded = true
if (err) {
p.end(err)
doNext = false
} else {
p.push(msg)
if (!doNext) {
next()
}
}
}
while (doNext) {
decoded = false
_decodeFromReader(reader, opts, decodeCb)
if (!decoded) {
doNext = false
}
}
}
|
javascript
|
{
"resource": ""
}
|
q57668
|
decodeFromReader
|
train
|
function decodeFromReader (reader, opts, cb) {
if (typeof opts === 'function') {
cb = opts
opts = {}
}
_decodeFromReader(reader, opts, function onComplete (err, msg) {
if (err) {
if (err === true) return cb(new Error('Unexpected end of input from reader.'))
return cb(err)
}
cb(null, msg)
})
}
|
javascript
|
{
"resource": ""
}
|
q57669
|
train
|
function(str){
var ret = new Array(str.length), len = str.length;
while(len--) ret[len] = str.charCodeAt(len);
return Uint8Array.from(ret);
}
|
javascript
|
{
"resource": ""
}
|
|
q57670
|
parseOption
|
train
|
function parseOption(nest, cons, name) {
if(name in options) {
var opt = options[name]
var prev = this[name]
var next
if(nest ? (Array.isArray(opt) && Array.isArray(opt[0])) :
Array.isArray(opt) ) {
this[name] = next = [ cons(opt[0]), cons(opt[1]), cons(opt[2]) ]
} else {
this[name] = next = [ cons(opt), cons(opt), cons(opt) ]
}
for(var i=0; i<3; ++i) {
if(next[i] !== prev[i]) {
return true
}
}
}
return false
}
|
javascript
|
{
"resource": ""
}
|
q57671
|
launchPlayground
|
train
|
function launchPlayground(){
$('.playground-item').playground();
// Eyedropper Helper Functions
$('.cp_eyedropper').on('click', function() {
if ($(this).next('.cp_grid').hasClass('visuallyhidden')) {
$(".cp_grid").addClass('visuallyhidden');
$(this).next(".cp_grid").removeClass('visuallyhidden');
} else {
$(this).next(".cp_grid").addClass('visuallyhidden');
}
})
// Hides eyedropper if you click outside eyedropper
$(document).on('click', function(event) {
if (!$(event.target).closest('.cp_eyedropper').length && !$(event.target).hasClass('playground-list_item')) {
$(".cp_grid").addClass('visuallyhidden');
}
});
// Playground Event Handler
$('body').on('playgroundUpdated', '.playground-item', function(){
var $input = $(this),
base = $input.data('playground'),
$playground = $input.closest('.playground'),
$codeEl, targetHtmlStr;
if ( !$playground.length ) $playground = $input.closest('article');
$codeEl = $playground.find('.exampleWithCode code');
if ( $playground.find('.copyable').length ) {
targetHtmlStr = $playground.find('.copyable')[0].outerHTML;
} else if ( $playground.find('.copyable-inner').length ) {
targetHtmlStr = $playground.find('.copyable-inner').html();
} else {
targetHtmlStr = base.$targetEl[0].outerHTML;
}
$codeEl.html(escapeHtml(targetHtmlStr));
Prism.highlightElement($codeEl[0]);
});
// Sets the code section on page load.
$('.playground-item').trigger('input');
}
|
javascript
|
{
"resource": ""
}
|
q57672
|
f
|
train
|
function f(x,y,z) {
return x*x + y*y + z*z - 2.0
}
|
javascript
|
{
"resource": ""
}
|
q57673
|
animate
|
train
|
function animate(animationName, configOrCallback) {
return this.each(function eachAnimate() {
return window.rb.animate.animate(this, animationName, configOrCallback);
});
}
|
javascript
|
{
"resource": ""
}
|
q57674
|
isFileOrDir
|
train
|
function isFileOrDir(filePath) {
let fsStat;
try {
fsStat = fs.statSync(filePath);
} catch (error) {
return error;
}
let r = 'file';
if (fsStat.isDirectory()) {
r = 'directory';
}
return r;
}
|
javascript
|
{
"resource": ""
}
|
q57675
|
_curry3
|
train
|
function _curry3 (fn) {
return function f3 (a, b, c) {
switch (arguments.length) {
case 0:
return f3
case 1:
return _curry2(function (_b, _c) {
return fn(a, _b, _c)
})
case 2:
return function (_c) {
return fn(a, b, _c)
}
default:
return fn(a, b, c)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q57676
|
qgen
|
train
|
function qgen(options) {
const defaultOptions = {
dest: DEFAULT_DESTINATION,
cwd: process.cwd(),
directory: 'qgen-templates',
config: './qgen.json',
helpers: undefined,
force: false,
preview: false
};
const configfilePath = createConfigFilePath(defaultOptions, options);
const configfileOptions = loadConfig(configfilePath);
const config = Object.assign(defaultOptions, configfileOptions, options);
/** Throw error if qgen template directory is missing */
if (isFileOrDir(config.directory) !== 'directory') {
throw new QGenError(`qgen templates directory '${config.directory}' not found.`);
}
/**
* Lists the available template names
*
* @return {Array} available template names
*/
const templates = () => {
return globby.sync(['*'], {
cwd: path.join(config.cwd, config.directory),
expandDirectories: false,
onlyFiles: false
});
};
/**
* Render the template file and save to the destination path
* @param {String} template The name of the template
* @param {String} destination Destination path
*/
const render = async (template, destination) => {
const templatePath = path.join(config.directory, template);
const templateType = isFileOrDir(path.join(config.cwd, templatePath));
const templateConfig = createTemplateConfig(config, template, DEFAULT_DESTINATION);
const filepathRenderer = templateRenderer({
helpers: config.helpers,
cwd: config.cwd
});
// Override config dest with passed destination
if (destination) {
templateConfig.dest = destination;
}
let fileObjects;
if (templateType === 'directory') {
const files = globby.sync(['**/*'], {
cwd: path.join(config.cwd, templatePath),
nodir: true
});
fileObjects = files.map(filePath => {
return {
src: path.join(templatePath, filePath),
dest: path.join(templateConfig.cwd, templateConfig.dest, filepathRenderer.render(filePath, config))
};
});
} else if (templateType === 'file') {
fileObjects = [{
src: templatePath,
dest: path.join(templateConfig.cwd, templateConfig.dest, template)
}];
} else {
throw new QGenError(`Template '${templatePath}' not found.`);
}
const filesForRender = config.preview ? fileObjects : await enquireToOverwrite(fileObjects, config.force);
if (!filesForRender.some(f => f.abort)) {
renderFiles(filesForRender, templateConfig, config.preview);
}
};
return Object.freeze({
templates,
render
});
}
|
javascript
|
{
"resource": ""
}
|
q57677
|
trapTabKey
|
train
|
function trapTabKey(node, event) {
var focusableChildren = getFocusableChildren(node);
var focusedItemIndex = focusableChildren.index($(document.activeElement));
if (event.shiftKey && focusedItemIndex === 0) {
focusableChildren[focusableChildren.length - 1].focus();
event.preventDefault();
} else if (!event.shiftKey && focusedItemIndex === focusableChildren.length - 1) {
focusableChildren[0].focus();
event.preventDefault();
}
}
|
javascript
|
{
"resource": ""
}
|
q57678
|
regexCache
|
train
|
function regexCache(fn, str, opts) {
var key = '_default_', regex, cached;
if (!str && !opts) {
if (typeof fn !== 'function') {
return fn;
}
return basic[key] || (basic[key] = fn(str));
}
var isString = typeof str === 'string';
if (isString) {
if (!opts) {
return basic[str] || (basic[str] = fn(str));
}
key = str;
} else {
opts = str;
}
cached = cache[key];
if (cached && equal(cached.opts, opts)) {
return cached.regex;
}
memo(key, opts, (regex = fn(str, opts)));
return regex;
}
|
javascript
|
{
"resource": ""
}
|
q57679
|
train
|
function () {
// check if the clients still exists
var peer = self.swr.webrtc.getPeers(uid)[0]
var success
if (peer) {
// success is true, if the message is successfully sent
success = peer.sendDirectly('simplewebrtc', 'yjs', message)
}
if (!success) {
// resend the message if it didn't work
setTimeout(send, 500)
}
}
|
javascript
|
{
"resource": ""
}
|
|
q57680
|
next
|
train
|
function next () {
shake.read(PING_LENGTH, (err, buf) => {
if (err === true) {
// stream closed
return
}
if (err) {
return log.error(err)
}
shake.write(buf)
return next()
})
}
|
javascript
|
{
"resource": ""
}
|
q57681
|
raw
|
train
|
function raw(obj) {
const result = {}
for (const key in obj) {
const value = obj[key]
if (value !== null && value !== undefined) {
result[key] = value.toString()
}
}
return result
}
|
javascript
|
{
"resource": ""
}
|
q57682
|
circularSectionsError
|
train
|
function circularSectionsError(sectionName, path) {
const joinedPath = path.join(' -> ')
const message = `Circular sections! Path: ${joinedPath} -> [${sectionName}]`
return new Error(message)
}
|
javascript
|
{
"resource": ""
}
|
q57683
|
circularImportsError
|
train
|
function circularImportsError(fileBeingImported, importTrail) {
const message =
`Circular import of "${fileBeingImported}".\r\n` +
'Import trace:\r\n' +
importTrail.map(f => ` -> ${f}`).join('\r\n')
return new Error(message)
}
|
javascript
|
{
"resource": ""
}
|
q57684
|
mapFiles
|
train
|
function mapFiles(files, relative, required) {
if (!files) {
return []
}
if (Array.isArray(files) === false) {
files = [files]
}
return files.map(f => ({
file: resolvePath(relative, f),
required: required
}))
}
|
javascript
|
{
"resource": ""
}
|
q57685
|
validate
|
train
|
function validate(property, validators) {
//console.log("validate", property, validators);
let errors = [], res, validator;
if (validators) {
for (let i = 0, _len = validators.length; i < _len; i++) {
validator = validators[i];
res = validateProperty(property, validator);
if (!isNull(res) && !isUndefined(res)) {
errors.push(res);
}
}
}
//Check what's the good type to return.
return {
name: property.name,
value: property.value,
isValid: 0 === errors.length,
errors: errors
};
}
|
javascript
|
{
"resource": ""
}
|
q57686
|
getErrorLabel
|
train
|
function getErrorLabel(type, fieldName, options = {}) {
options = options || {};
const translationKey = options.translationKey ? options.translationKey : `domain.validation.${type}`;
const opts = { fieldName: translate(fieldName), ...options };
return translate(translationKey, opts);
}
|
javascript
|
{
"resource": ""
}
|
q57687
|
orderAndSort
|
train
|
function orderAndSort(sortConf) {
return {
sortFieldName: sortConf.sortBy,
sortDesc: sortConf.sortAsc === undefined ? false : !sortConf.sortAsc
};
}
|
javascript
|
{
"resource": ""
}
|
q57688
|
pagination
|
train
|
function pagination(opts) {
let { isScroll, dataList, totalCount, nbElement } = opts;
if (isScroll) {
if (!isArray(dataList)) {
throw new Error('The data list options sould exist and be an array')
}
if (dataList.length < totalCount) {
return { top: nbElement, skip: dataList.length };
}
}
return {
top: nbElement,
skip: 0
}
}
|
javascript
|
{
"resource": ""
}
|
q57689
|
triggerPromise
|
train
|
function triggerPromise() {
var me = this;
var args = arguments;
var canHandlePromise =
this.children.indexOf("completed") >= 0 &&
this.children.indexOf("failed") >= 0;
var createdPromise = new PromiseFactory(function(resolve, reject) {
// If `listenAndPromise` is listening
// patch `promise` w/ context-loaded resolve/reject
if (me.willCallPromise) {
_.nextTick(function() {
var previousPromise = me.promise;
me.promise = function (inputPromise) {
inputPromise.then(resolve, reject);
// Back to your regularly schedule programming.
me.promise = previousPromise;
return me.promise.apply(me, arguments);
};
me.trigger.apply(me, args);
});
return;
}
if (canHandlePromise) {
var removeSuccess = me.completed.listen(function () {
var args = Array.prototype.slice.call(arguments);
removeSuccess();
removeFailed();
resolve(args.length > 1 ? args : args[0]);
});
var removeFailed = me.failed.listen(function () {
var args = Array.prototype.slice.call(arguments);
removeSuccess();
removeFailed();
reject(args.length > 1 ? args : args[0]);
});
}
_.nextTick(function () {
me.trigger.apply(me, args);
});
if (!canHandlePromise) {
resolve();
}
});
// Ensure that the promise does trigger "Uncaught (in promise)" errors in console if no error handler is added
// See: https://github.com/reflux/reflux-promise/issues/4
createdPromise.catch(function() {});
return createdPromise;
}
|
javascript
|
{
"resource": ""
}
|
q57690
|
promise
|
train
|
function promise(p) {
var me = this;
var canHandlePromise =
this.children.indexOf("completed") >= 0 &&
this.children.indexOf("failed") >= 0;
if (!canHandlePromise){
throw new Error("Publisher must have \"completed\" and \"failed\" child publishers");
}
p.then(function(response) {
return me.completed(response);
}, function(error) {
return me.failed(error);
});
}
|
javascript
|
{
"resource": ""
}
|
q57691
|
listenAndPromise
|
train
|
function listenAndPromise(callback, bindContext) {
var me = this;
bindContext = bindContext || this;
this.willCallPromise = (this.willCallPromise || 0) + 1;
var removeListen = this.listen(function() {
if (!callback) {
throw new Error("Expected a function returning a promise but got " + callback);
}
var args = arguments,
returnedPromise = callback.apply(bindContext, args);
return me.promise.call(me, returnedPromise);
}, bindContext);
return function () {
me.willCallPromise--;
removeListen.call(me);
};
}
|
javascript
|
{
"resource": ""
}
|
q57692
|
hasRole
|
train
|
function hasRole(role) {
role = isArray(role) ? role : [role];
return 0 < intersection(role, userBuiltInStore.getRoles()).length;
}
|
javascript
|
{
"resource": ""
}
|
q57693
|
check
|
train
|
function check(file, frontmatter) {
// Only process files that match the pattern
if (!match(file, pattern)[0]) {
return false;
}
// Don't process private files
if (get(frontmatter, privateProperty)) {
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q57694
|
buildUrl
|
train
|
function buildUrl(file, frontmatter) {
// Frontmatter settings take precedence
var canonicalUrl = get(frontmatter, urlProperty);
if (is.string(canonicalUrl)) {
return canonicalUrl;
}
// Remove index.html if necessary
var indexFile = 'index.html';
if (omitIndex && path.basename(file) === indexFile) {
return replaceBackslash(file.slice(0, 0 - indexFile.length));
}
// Remove extension if necessary
if (omitExtension) {
return replaceBackslash(file.slice(0, 0 - path.extname(file).length));
}
// Otherwise just use 'file'
return replaceBackslash(file);
}
|
javascript
|
{
"resource": ""
}
|
q57695
|
init
|
train
|
function init(format = DEFAULT_FORMAT, locale = 'fr') {
numeral.locale(locale);
numeral.defaultFormat(format);
}
|
javascript
|
{
"resource": ""
}
|
q57696
|
updateRequestStatus
|
train
|
function updateRequestStatus(request) {
if (!request || !request.id || !request.status) { return; }
dispatcher.handleViewAction({
data: { request: request },
type: 'update'
});
return request;
}
|
javascript
|
{
"resource": ""
}
|
q57697
|
getResponseContent
|
train
|
function getResponseContent(response, dataType) {
const { type, status, ok } = response;
// Handling errors
if (type === 'opaque') {
console.error('You tried to make a Cross Domain Request with no-cors options');
return Promise.reject({ status: status, globalErrors: ['error.noCorsOptsOnCors'] });
}
if (type === 'error') {
console.error('An unknown network issue has happened');
return Promise.reject({ status: status, globalErrors: ['error.unknownNetworkIssue'] });
}
if (!ok && dataType === 'json') {
return response.json().catch(err => Promise.reject({ globalErrors: [err] })).then(data => Promise.reject({ status, ...data }));
}
if (!ok) {
return response.text().then(text => Promise.reject({ status, globalErrors: [text] }));
}
// Handling success
if (ok && status === '204') {
return Promise.resolve(null);
}
return ['arrayBuffer', 'blob', 'formData', 'json'].includes(dataType) ? response[dataType]().catch(err => Promise.reject({ globalErrors: [err] })) : response.text();
}
|
javascript
|
{
"resource": ""
}
|
q57698
|
checkErrors
|
train
|
function checkErrors(response, xhrErrors) {
let { status, ok } = response;
if (!ok) {
if (xhrErrors[status]) {
xhrErrors[status](response);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q57699
|
wrappingFetch
|
train
|
function wrappingFetch({ url, method, data }, optionsArg) {
let requestStatus = createRequestStatus();
// Here we are using destruct to filter properties we do not want to give to fetch.
// CORS and isCORS are useless legacy code, xhrErrors is used only in error parsing
// eslint-disable-next-line no-unused-vars
let { CORS, isCORS, xhrErrors, ...config } = configGetter();
const { noStringify, ...options } = optionsArg || {};
const reqOptions = merge({ headers: {} }, config, options, { method, body: noStringify ? data : JSON.stringify(data) });
//By default, add json content-type
if (!reqOptions.noContentType && !reqOptions.headers['Content-Type']) {
reqOptions.headers['Content-Type'] = 'application/json';
}
// Set the requesting as pending
updateRequestStatus({ id: requestStatus.id, status: 'pending' });
// Do the request
return fetch(url, reqOptions)
// Catch the possible TypeError from fetch
.catch(error => {
updateRequestStatus({ id: requestStatus.id, status: 'error' });
return Promise.reject({ globalErrors: [error] });
}).then(response => {
updateRequestStatus({ id: requestStatus.id, status: response.ok ? 'success' : 'error' });
const contentType = response.headers.get('content-type');
return getResponseContent(response, reqOptions.dataType ? reqOptions.dataType : contentType && contentType.includes('application/json') ? 'json' : 'text');
}).catch(data => {
checkErrors(data, xhrErrors);
return Promise.reject(data);
});
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.