_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) { re...
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 viol...
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 hei...
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 direc...
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'])...
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 ...
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, ...
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))...
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; //----------------...
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...
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; ...
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 !== 'clo...
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 : ...
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 = TEM...
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); }); t...
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 n...
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...
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 : fa...
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 (packag...
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...
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...
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 ...
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...
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, "...
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 = '...
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 w...
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.d...
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])) { a...
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 gr...
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); ...
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) { ...
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...
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...
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...
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, ...
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.pu...
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), standal...
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...
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]...
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, e...
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, ...
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(fileDa...
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; endMatc...
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 + fileU...
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); ...
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.conten...
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 => handlerMeth...
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 ...
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() } } } whi...
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(nul...
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]) ] ...
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('visua...
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: ...
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 = load...
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(); ...
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] || (b...
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) {...
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); ...
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...
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 `listen...
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"); ...
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 ret...
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....
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...
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-un...
javascript
{ "resource": "" }