_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q200
extendedCallback
train
function extendedCallback(res) { timeline.mark(`end:${id}`); // add full response data moduleData[id].response = getResDataObject(res); // flatten object for easy transformation/filtering later moduleData[id] = flatten(moduleData[id], { maxDepth: 5 }); moduleData[id] = fi...
javascript
{ "resource": "" }
q201
train
function(func, scope, args) { var fixedArgs = Array.prototype.slice.call(arguments, 2); return function() { var args = fixedArgs.concat(Array.prototype.slice.call(arguments, 0)); (/** @type {Function} */ func).apply(scope, args); }; }
javascript
{ "resource": "" }
q202
train
function(args) { var i, max, match, log; // Convert argument list to real array args = Array.prototype.slice.call(arguments, 0); // First argument is the log method to call log = args.shift(); max = args.length; if (max > 1 && window...
javascript
{ "resource": "" }
q203
parseOptions
train
function parseOptions(options) { let separator let transformer if (2 === options.length) { [separator, transformer] = options if (defaultTransformers[transformer]) { transformer = defaultTransformers[transformer] /* Don't validate */ validate({ separator }) } else { validate({ separ...
javascript
{ "resource": "" }
q204
getWeight
train
function getWeight(labels, labelWeight) { const places = labels.map(label => labelWeight.indexOf(label.name)); let binary = ''; for (let i = 0; i < labelWeight.length; i++) { binary += places.includes(i) ? '1' : '0'; } return parseInt(binary, 2); }
javascript
{ "resource": "" }
q205
getReleaseInfo
train
async function getReleaseInfo(context, childTags) { const tagShas = []; const releasesBySha = await fetchAllReleases(context, release => { if (childTags.has(release.tag_name)) { // put in reverse order // later releases come first, // but we want to iterate beginning oldest releases first ...
javascript
{ "resource": "" }
q206
getType
train
function getType(value) { // inspired by http://techblog.badoo.com/blog/2013/11/01/type-checking-in-javascript/ // handle null in old IE if (value === null) { return 'null'; } // handle DOM elements if (value && (value.nodeType === 1 || value.nodeType === 9)...
javascript
{ "resource": "" }
q207
extendFormatExtensions
train
function extendFormatExtensions (extensionName, extensionValue) { if (typeof extensionName !== 'string' || !(extensionValue instanceof RegExp)) { throw new Error('extensionName or extensionValue undefined or not correct type'); } if (revalidator.validate.formats.hasOwnProperty(exten...
javascript
{ "resource": "" }
q208
getError
train
function getError (type, expected, actual) { return { attribute: type, expected: expected, actual: actual, message: getMsg(type, expected) }; }
javascript
{ "resource": "" }
q209
getResult
train
function getResult (err) { var res = { valid: true, errors: [] }; if (err !== null) { res.valid = false; res.errors.push(err); } return res; }
javascript
{ "resource": "" }
q210
uniqueArrayHelper
train
function uniqueArrayHelper (val) { var h = {}; for (var i = 0, l = val.length; i < l; i++) { var key = JSON.stringify(val[i]); if (h[key]) { return false; } h[key] = true; } return true; }
javascript
{ "resource": "" }
q211
getValidationFunction
train
function getValidationFunction (validationOptions) { validationOptions = validationOptions || {}; return function (doc, schema, options) { doc = doc || {}; options = options || {}; options.isUpdate = options.isUpdate || false; // check is update ...
javascript
{ "resource": "" }
q212
componentExists
train
function componentExists(componentPath) { const existsInExtensions = fs.existsSync(path.resolve(EXTENSIONS_PATH, componentPath)); const existsInWidgets = fs.existsSync(path.resolve(themes.getPath(), 'widgets', componentPath)); return !(!existsInExtensions && !existsInWidgets); }
javascript
{ "resource": "" }
q213
readConfig
train
function readConfig(options) { return new Promise((resolve, reject) => { const { type, config, importsStart = null, importsEnd = null, exportsStart = 'export default {', exportsEnd = '};', isArray = false, } = options; if (!config || !isPlainObject(config)) { ...
javascript
{ "resource": "" }
q214
getIndexLogTranslations
train
function getIndexLogTranslations(type = TYPE_WIDGETS) { const params = { type: t(`TYPE_${type}`) }; return { logStart: ` ${t('INDEXING_TYPE', params)}`, logEnd: ` ${t('INDEXED_TYPE', params)}`, logNotFound: ` ${t('NO_EXTENSIONS_FOUND_FOR_TYPE', params)}`, }; }
javascript
{ "resource": "" }
q215
validateExtensions
train
function validateExtensions(input) { return new Promise((resolve, reject) => { try { const extensionPath = getExtensionsPath(); if (!fs.existsSync(extensionPath)) { fs.mkdirSync(extensionPath); } if (!input.imports.length) { return resolve(null); } return res...
javascript
{ "resource": "" }
q216
createStrings
train
function createStrings(input) { return new Promise((resolve, reject) => { try { if (!input) { return resolve(null); } const importsString = input.imports.length ? `${input.imports.join('\n')}\n\n` : ''; const exportsString = input.exports.length ? `${input.exports.join('\n')}\n` :...
javascript
{ "resource": "" }
q217
writeExtensionFile
train
function writeExtensionFile(options) { return new Promise((resolve, reject) => { try { const { file, input, defaultContent, logNotFound, logEnd, } = options; const filePath = path.resolve(getExtensionsPath(), file); if (!input) { logger.warn...
javascript
{ "resource": "" }
q218
index
train
function index(options) { const { file, config, logStart, logNotFound, logEnd, defaultContent = defaultFileContent, } = options; logger.log(logStart); return readConfig(config) .then(input => validateExtensions(input)) .then(input => createStrings(input)) .then(input => wri...
javascript
{ "resource": "" }
q219
indexWidgets
train
function indexWidgets() { const { widgets = {} } = getComponentsSettings(); return index({ file: 'widgets.js', config: { type: TYPE_WIDGETS, config: widgets, }, ...getIndexLogTranslations(TYPE_WIDGETS), }); }
javascript
{ "resource": "" }
q220
indexTracking
train
function indexTracking() { const { tracking = {} } = getComponentsSettings(); return index({ file: 'tracking.js', config: { type: TYPE_TRACKERS, config: tracking, }, ...getIndexLogTranslations(TYPE_TRACKERS), }); }
javascript
{ "resource": "" }
q221
indexPortals
train
function indexPortals() { const { portals = {} } = getComponentsSettings(); return index({ file: 'portals.js', config: { type: TYPE_PORTALS, config: portals, importsStart: 'import portalCollection from \'@shopgate/pwa-common/helpers/portals/portalCollection\';', exportsStart: 'porta...
javascript
{ "resource": "" }
q222
indexReducers
train
function indexReducers() { const { reducers = {} } = getComponentsSettings(); return index({ file: 'reducers.js', config: { type: TYPE_REDUCERS, config: reducers, }, defaultContent: 'export default null;\n', ...getIndexLogTranslations(TYPE_REDUCERS), }); }
javascript
{ "resource": "" }
q223
indexSubscribers
train
function indexSubscribers() { const { subscribers = {} } = getComponentsSettings(); return index({ file: 'subscribers.js', config: { type: TYPE_SUBSCRIBERS, config: subscribers, exportsStart: 'export default [', exportsEnd: '];', isArray: true, }, defaultContent: 'expo...
javascript
{ "resource": "" }
q224
indexTranslations
train
function indexTranslations() { const { translations = {} } = getComponentsSettings(); return index({ file: 'translations.js', config: { type: TYPE_TRANSLATIONS, config: translations, }, defaultContent: 'export default null;\n', ...getIndexLogTranslations(TYPE_TRANSLATIONS), }); }
javascript
{ "resource": "" }
q225
search
train
function search(query, options = {}) { const { format = 'idCode', mode = 'substructure', flattenResult = true, keepMolecule = false, limit = Number.MAX_SAFE_INTEGER } = options; if (typeof query === 'string') { const getMoleculeCreators = require('./moleculeCreators'); const moleculeC...
javascript
{ "resource": "" }
q226
maybeApi
train
async function maybeApi ({ apiAddress, apiOpts, ipfsConnectionTest, IpfsApi }) { try { const ipfs = new IpfsApi(apiAddress, apiOpts) await ipfsConnectionTest(ipfs) return { ipfs, provider, apiAddress } } catch (error) { console.log('Failed to connect to ipfs-api', apiAddress) } }
javascript
{ "resource": "" }
q227
addMissingChirality
train
function addMissingChirality(molecule, esrType = Molecule.cESRTypeAnd) { for (let iAtom = 0; iAtom < molecule.getAllAtoms(); iAtom++) { let tempMolecule = molecule.getCompactCopy(); changeAtomForStereo(tempMolecule, iAtom); // After copy, helpers must be recalculated tempMolecule.ensureHelperArrays(Mo...
javascript
{ "resource": "" }
q228
markDiastereotopicAtoms
train
function markDiastereotopicAtoms(molecule) { // changed from markDiastereo(); TLS 9.Nov.2015 let ids = getAtomIDs(molecule); let analyzed = {}; let group = 0; for (let id of ids) { console.log(`${id} - ${group}`); if (!analyzed.contains(id)) { analyzed[id] = true; for (let iAtom = 0; iAtom...
javascript
{ "resource": "" }
q229
getContrastColor
train
function getContrastColor(bgColor, colors) { // We set a rather high cutoff to prefer light text if possible. const cutoff = 0.74; // Calculate the perceived luminosity (relative brightness) of the color. const perceivedLuminosity = Color(bgColor).luminosity(); return perceivedLuminosity >= cutoff ? colors....
javascript
{ "resource": "" }
q230
getFocusColor
train
function getFocusColor(colors) { if (Color(colors.primary).luminosity() >= 0.8) { return colors.accent; } return colors.primary; }
javascript
{ "resource": "" }
q231
applyContrastColors
train
function applyContrastColors(config) { const { colors } = config; return { ...config, colors: { ...colors, primaryContrast: getContrastColor(colors.primary, colors), accentContrast: getContrastColor(colors.accent, colors), focus: getFocusColor(colors), }, }; }
javascript
{ "resource": "" }
q232
applyCustomColors
train
function applyCustomColors(config) { const { colors } = getAppSettings(); if (!config.hasOwnProperty('colors')) { return { ...config, colors, }; } return { ...config, colors: { ...config.colors, ...colors, }, }; }
javascript
{ "resource": "" }
q233
module
train
function module(filename) { return function () { if (verbose.local) console.log(filename); response.write(fs.readFileSync(filename) + '\n/*:oxsep:*/\n'); }; }
javascript
{ "resource": "" }
q234
collecticonsBundle
train
async function collecticonsBundle (params) { const { dirPath, destFile } = params; await validateDirPath(dirPath); const resultFiles = await collecticonsCompile({ dirPath, styleFormats: ['css'], styleDest: './styles', fontDest: './', fontTypes: ['woff', 'woff2'], previewDest: '...
javascript
{ "resource": "" }
q235
train
function(errors) { //!steal-remove-start if (process.env.NODE_ENV !== 'production') { clearTimeout(asyncTimer); } //!steal-remove-end var stub = error && error.call(self, errors); // if 'validations' is on the page it will trigger // the error itself and we dont want to trigger // the event...
javascript
{ "resource": "" }
q236
train
function(map, attr, val) { var serializer = attr === "*" ? false : getPropDefineBehavior("serialize", attr, map.define); if (serializer === undefined) { return oldSingleSerialize.call(map, attr, val); } else if (serializer !== false) { return typeof serializer === "function" ? serializer.call(map, val, attr) : o...
javascript
{ "resource": "" }
q237
generateFonts
train
async function generateFonts (options = {}) { if (!options.fontName) throw new TypeError('Missing fontName argument'); if (!options.icons || !Array.isArray(options.icons) || !options.icons.length) { throw new TypeError('Invalid or empty icons argument'); } // Store created tasks to match dependencies. let genTa...
javascript
{ "resource": "" }
q238
renderSass
train
async function renderSass (opts = {}) { const tpl = await fs.readFile(path.resolve(__dirname, 'sass.ejs'), 'utf8'); return ejs.render(tpl, opts); }
javascript
{ "resource": "" }
q239
renderCatalog
train
async function renderCatalog (opts = {}) { if (!opts.fontName) throw new ReferenceError('fontName is undefined'); if (!opts.className) throw new ReferenceError('className is undefined'); if (!opts.icons || !opts.icons.length) throw new ReferenceError('icons is undefined or empty'); const fonts = opts.fonts ...
javascript
{ "resource": "" }
q240
Logger
train
function Logger () { const levels = [ 'fatal', // 1 'error', // 2 'warn', // 3 'info', // 4 'debug' // 5 ]; let verbosity = 3; levels.forEach((level, idx) => { this[level] = (...params) => { if (idx + 1 <= verbosity) console.log(...params); // eslint-disable-line }; }); t...
javascript
{ "resource": "" }
q241
userError
train
function userError (details = [], code) { const err = new Error('User error'); err.userError = true; err.code = code; err.details = details; return err; }
javascript
{ "resource": "" }
q242
time
train
function time (name) { const t = timers[name]; if (t) { let elapsed = Date.now() - t; if (elapsed < 1000) return `${elapsed}ms`; if (elapsed < 60 * 1000) return `${elapsed / 1000}s`; elapsed /= 1000; const h = Math.floor(elapsed / 3600); const m = Math.floor((elapsed % 3600) / 60); cons...
javascript
{ "resource": "" }
q243
validateDirPath
train
async function validateDirPath (dirPath) { try { const stats = await fs.lstat(dirPath); if (!stats.isDirectory()) { throw userError([ 'Source path must be a directory', '' ]); } } catch (error) { if (error.code === 'ENOENT') { throw userError([ 'No files or ...
javascript
{ "resource": "" }
q244
validateDirPathForCLI
train
async function validateDirPathForCLI (dirPath) { try { await validateDirPath(dirPath); } catch (error) { if (!error.userError) throw error; if (error.details[0].startsWith('Source path must be a directory')) { const args = process.argv.reduce((acc, o, idx) => { // Discard the first 2 argum...
javascript
{ "resource": "" }
q245
compileProgram
train
async function compileProgram (dirPath, command) { await validateDirPathForCLI(dirPath); const params = pick(command, [ 'fontName', 'sassPlaceholder', 'cssClass', 'fontTypes', 'styleFormats', 'styleDest', 'styleName', 'fontDest', 'authorName', 'authorUrl', 'className', ...
javascript
{ "resource": "" }
q246
bundleProgram
train
async function bundleProgram (dirPath, destFile) { await validateDirPathForCLI(dirPath); return collecticonsBundle({ dirPath, destFile }); }
javascript
{ "resource": "" }
q247
Connection
train
function Connection (options, clientOptions, label) { this.options = options; this.clientOptions = clientOptions; this.label = label; this.initialConnection = false; this.initialConnectionRetries = 0; this.maxConnectionRetries = 60; Object.defineProperty(this, 'e...
javascript
{ "resource": "" }
q248
resolveRef
train
function resolveRef(schemaObj, resolvedValues) { // the array store referenced value var refVal = schemaObj.refVal; // the map store full ref id and index of the referenced value in refVal // example: { 'test#definitions/option' : 1, 'test#definitions/repo' : 2 } ...
javascript
{ "resource": "" }
q249
assetFingerprint
train
function assetFingerprint(label, fingerprint, cacheInfo) { if(arguments.length > 1) { //Add a label var labelInfo = labels[label] = {"fingerprint": fingerprint}; if(cacheInfo) for(var i in cacheInfo) labelInfo[i] = cacheInfo[i]; } else { //Try to get a fingerprint from a registered label ...
javascript
{ "resource": "" }
q250
train
function() { var self = this; return waterline.catalogs.findOne({"node": self.id}) .then(function(catalog) { return !_.isEmpty(catalog); }); }
javascript
{ "resource": "" }
q251
train
function () { var waterline = this.injector.get('Services.Waterline'); return bluebird.all( _.map(waterline, function (collection) { if (typeof collection.destroy === 'function') { return bluebird.fromNode(collection.destroy.bind(collection)).then(functio...
javascript
{ "resource": "" }
q252
ChildProcess
train
function ChildProcess (command, args, env, code, maxBuffer) { var self = this; assert.string(command); assert.optionalArrayOfNumber(code); self.command = command; self.file = self._parseCommandPath(self.command); self.args = args; self.environment = env || {}; ...
javascript
{ "resource": "" }
q253
provideName
train
function provideName(obj, token){ if(!isString(token)) { throw new Error('Must provide string as name of module'); } di.annotate(obj, new di.Provide(token)); }
javascript
{ "resource": "" }
q254
providePromise
train
function providePromise(obj, providePromiseName) { if(!isString(providePromiseName)) { throw new Error('Must provide string as name of promised module'); } di.annotate(obj, new di.ProvidePromise(providePromiseName)); }
javascript
{ "resource": "" }
q255
resolveProvide
train
function resolveProvide(obj, override) { var provide = override || obj.$provide; if(isString(provide)) { return provideName(obj, provide); } if(isObject(provide)) { if (isString(provide.promise)) { return providePromise(obj, provide.promise); } else if (isString(provide.provi...
javascript
{ "resource": "" }
q256
addInject
train
function addInject(obj, inject) { if(!exists(inject)) { return; } var injectMe; if (inject === '$injector') { injectMe = new di.Inject(di.Injector); } else if (isObject(inject)) { if(isString(inject.inject)){ injectMe = new di.Inject(inject.inject); } else if(isStri...
javascript
{ "resource": "" }
q257
resolveInjects
train
function resolveInjects(obj, override){ var injects = obj.$inject || override; if (exists(injects)) { if (!Array.isArray(injects)) { injects = [injects]; } injects.forEach(function addInjects(element) { addInject(obj, element); }); } }
javascript
{ "resource": "" }
q258
injectableWrapper
train
function injectableWrapper(obj, provide, injects, isTransientScope) { // TODO(@davequick): discuss with @halfspiral whether isTransientScope might just better // be an array of Annotations var wrappedObject = function wrapOrCreateObject() { if(isFunction(obj) && (exists(obj.$provide) || exists(obj.$in...
javascript
{ "resource": "" }
q259
_requireFile
train
function _requireFile(requirable, directory) { var required; try{ var res = resolve.sync(requirable, { basedir: directory}); required = require(res); } catch(err) { required = (void 0); } return required; }
javascript
{ "resource": "" }
q260
_require
train
function _require(requireMe, provides, injects, currentDirectory, next) { var requireResult = _requireFile (requireMe, currentDirectory) || _requireFile (requireMe, defaultDirectory) || _requireFile (requireMe, __dirname) || _requireFile (...
javascript
{ "resource": "" }
q261
requireWrapper
train
function requireWrapper(requireMe, provides, injects, directory) { return _require(requireMe, provides, injects, directory, simpleWrapper); }
javascript
{ "resource": "" }
q262
requireGlob
train
function requireGlob(pattern) { return _.map(glob.sync(pattern), function (file) { var required = require(file); resolveProvide(required); resolveInjects(required); return required; }); }
javascript
{ "resource": "" }
q263
injectableFromFile
train
function injectableFromFile(requireMe, provides, injects, directory) { return _require(requireMe, provides, injects, directory, injectableWrapper); }
javascript
{ "resource": "" }
q264
requireOverrideInjection
train
function requireOverrideInjection(requireMe, provides, injects, directory) { return _require(requireMe, provides, injects, directory, overrideInjection); }
javascript
{ "resource": "" }
q265
env
train
function env(environment) { environment = environment || {}; if ('object' === typeof process && 'object' === typeof process.env) { env.merge(environment, process.env); } if ('undefined' !== typeof window) { if ('string' === window.name && window.name.length) { env.merge(environment, env.parse(wi...
javascript
{ "resource": "" }
q266
moveToDest
train
function moveToDest(srcDir, destDir) { if (!this.options.cleanOutput) { return srcDir; } var content, cssDir, src; var copiedCache = this.copiedCache || {}; var copied = {}; var options = this.options; var tree = this.walkDir(srcDir, {cache: this.cache}); var cache = tree.paths; var generated = tr...
javascript
{ "resource": "" }
q267
CompassCompiler
train
function CompassCompiler(inputTree, files, options) { options = arguments.length > 2 ? (options || {}) : (files || {}); if (arguments.length > 2) { console.log('[broccoli-compass] DEPRECATION: passing files to broccoli-compass constructor as second parameter is deprecated, ' + 'use options.files...
javascript
{ "resource": "" }
q268
addToCache
train
function addToCache(filename, obj) { if(cacheOn) { var x = cache[filename]; if(!x) x = cache[filename] = {}; x.mtime = obj.mtime || x.mtime; x.etag = obj.etag || x.etag; x.size = obj.size || x.size; } }
javascript
{ "resource": "" }
q269
train
function () { var self = this; var indexes = self.$indexes || []; return Promise.try (function() { assert.arrayOfObject(indexes, '$indexes should be an array of object'); //validate and assign default arguments before creating indexes ...
javascript
{ "resource": "" }
q270
train
function (criteria) { var identity = this.identity; return this.findOne(criteria).then(function (record) { if (!record) { throw new Errors.NotFoundError( 'Could not find %s with criteria %j.'.format( plurali...
javascript
{ "resource": "" }
q271
train
function (criteria, document) { var self = this; return this.needOne(criteria).then(function (target) { return self.update(target.id, document).then(function (documents) { return documents[0]; }); }); }
javascript
{ "resource": "" }
q272
train
function (criteria) { var self = this; return this.needOne(criteria).then(function (target) { return self.destroy(target.id).then(function (documents) { return documents[0]; }); }); }
javascript
{ "resource": "" }
q273
BaseError
train
function BaseError(message, context) { this.message = message; this.name = this.constructor.name; this.context = context || {}; Error.captureStackTrace(this, BaseError); }
javascript
{ "resource": "" }
q274
Subscription
train
function Subscription (queue, options) { assert.object(queue, 'queue'); assert.object(options, 'options'); this.MAX_DISPOSE_RETRIES = 3; this.retryDelay = 1000; this.queue = queue; this.options = options; this._disposed = false; }
javascript
{ "resource": "" }
q275
Perf
train
function Perf (stats, name, filter, rename) { this.stats = stats this.name = name this.filter = filter || function () { return true } this.rename = rename || function (name) { return name } }
javascript
{ "resource": "" }
q276
getMedian
train
function getMedian (args) { if (!args.length) return 0 var numbers = args.slice(0).sort(function (a, b) { return a - b }) var middle = Math.floor(numbers.length / 2) var isEven = numbers.length % 2 === 0 var res = isEven ? (numbers[middle] + numbers[middle - 1]) / 2 : numbers[middle] return Number(res.toFix...
javascript
{ "resource": "" }
q277
Message
train
function Message (data, headers, deliveryInfo) { assert.object(data); assert.object(headers); assert.object(deliveryInfo); this.data = Message.factory(data, deliveryInfo.type); this.headers = headers; this.deliveryInfo = deliveryInfo; }
javascript
{ "resource": "" }
q278
profileServiceFactory
train
function profileServiceFactory( Constants, Promise, _, DbRenderable, Util ) { Util.inherits(ProfileService, DbRenderable); /** * ProfileService is a singleton object which provides key/value store * access to profile files loaded from disk via FileLoader. * @constructor ...
javascript
{ "resource": "" }
q279
loggerFactory
train
function loggerFactory( events, Constants, assert, _, util, stack, nconf ) { var levels = _.keys(Constants.Logging.Levels); function getCaller (depth) { var current = stack.get()[depth]; var file = current.getFileName().replace( Constants.WorkingDirector...
javascript
{ "resource": "" }
q280
GraphProgress
train
function GraphProgress(graph, graphDescription) { assert.object(graph, 'graph'); assert.string(graphDescription, 'graphDescription'); this.graph = graph; this.data = { graphId: graph.instanceId, nodeId: graph.node, graphName: graph.name || 'Not availa...
javascript
{ "resource": "" }
q281
HttpTool
train
function HttpTool(){ this.settings = {}; this.urlObject = {}; this.dataToWrite = ''; // ********** Helper Functions/Members ********** var validMethods = ['GET', 'PUT', 'POST', 'DELETE', 'PATCH']; /** * Make sure that settings has at least proper...
javascript
{ "resource": "" }
q282
templateServiceFactory
train
function templateServiceFactory( Constants, Promise, _, DbRenderable, Util ) { Util.inherits(TemplateService, DbRenderable); /** * TemplateService is a singleton object which provides key/value store * access to template files loaded from disk via FileLoader. * @construct...
javascript
{ "resource": "" }
q283
normalizeFgArgs
train
function normalizeFgArgs(fgArgs) { var program, args, cb; var processArgsEnd = fgArgs.length; var lastFgArg = fgArgs[fgArgs.length - 1]; if (typeof lastFgArg === "function") { cb = lastFgArg; processArgsEnd -= 1; } else { cb = function(done) { done(); }; } if (Array.isArray(fgArgs[0])) { ...
javascript
{ "resource": "" }
q284
Conrec
train
function Conrec(drawContour) { if (!drawContour) { var c = this; c.contours = {}; /** * drawContour - interface for implementing the user supplied method to * render the countours. * * Draws a line between the start and end coordinates. * * @param startX ...
javascript
{ "resource": "" }
q285
failFirstRequest
train
function failFirstRequest(server) { var listeners = server.listeners("request"), existingListeners = []; for (var i = 0, l = listeners.length; i < l; i++) { existingListeners[i] = listeners[i]; } server.removeAllListeners("request"); server.on("request", function (req, res) { ...
javascript
{ "resource": "" }
q286
instrumental_send
train
function instrumental_send(payload) { var state = "cold"; var tlsOptionsVariation = selectTlsOptionsVariation(); var client = instrumental_connection(host, port, tlsOptionsVariation, function(_client){ state = "connected"; var cleanString = function(value) { return String(value).replace(/\s+/g, "_...
javascript
{ "resource": "" }
q287
getRoutes
train
function getRoutes(feature) { const targetPath = `src/features/${feature}/route.js`; //utils.mapFeatureFile(feature, 'route.js'); if (vio.fileNotExists(targetPath)) return []; const theAst = ast.getAst(targetPath); const arr = []; let rootPath = ''; let indexRoute = null; traverse(theAst, { ObjectExp...
javascript
{ "resource": "" }
q288
getKey
train
function getKey(context) { if (context.getModelKey) { return context.getModelKey(); } return context.props.name || context.props.key || context.props.ref; }
javascript
{ "resource": "" }
q289
modelOrCollectionOnOrOnce
train
function modelOrCollectionOnOrOnce(modelType, type, args, _this, _modelOrCollection) { var modelEvents = getModelAndCollectionEvents(modelType, _this); var ev = args[0]; var cb = args[1]; var ctx = args[2]; modelEvents[ev] = { type: type, ev: ev, ...
javascript
{ "resource": "" }
q290
getModelAndCollectionEvents
train
function getModelAndCollectionEvents(type, context) { var key = '__' + type + CAP_EVENTS, modelEvents = getState(key, context); if (!modelEvents) { modelEvents = {}; var stateVar = {}; stateVar[key] = modelEvents; setState(stateVar, context, fa...
javascript
{ "resource": "" }
q291
pushLoadingState
train
function pushLoadingState(xhrEvent, stateName, modelOrCollection, context, force) { var currentLoads = getState(stateName, context), currentlyLoading = currentLoads && currentLoads.length; if (!currentLoads) { currentLoads = []; } if (_.isArray(currentLoads)) { ...
javascript
{ "resource": "" }
q292
popLoadingState
train
function popLoadingState(xhrEvent, stateName, modelOrCollection, context) { var currentLoads = getState(stateName, context); if (_.isArray(currentLoads)) { var i = currentLoads.indexOf(xhrEvent); while (i >= 0) { currentLoads.splice(i, 1); i = curr...
javascript
{ "resource": "" }
q293
joinCurrentModelActivity
train
function joinCurrentModelActivity(method, stateName, modelOrCollection, context, force) { var xhrActivity = modelOrCollection[xhrModelLoadingAttribute]; if (xhrActivity) { _.each(xhrActivity, function(xhrEvent) { if (!method || method === ALL_XHR_ACTIVITY || xhrEvent.method =...
javascript
{ "resource": "" }
q294
train
function() { var keys = arguments.length > 0 ? Array.prototype.slice.call(arguments, 0) : undefined; return { getInitialState: function() { var self = this; modelOrCollectionEventHandler(typeData.type, keys || 'updateOn', this, '{key}', fun...
javascript
{ "resource": "" }
q295
train
function(type, attributes, isCheckable, classAttributes) { return React.createClass(_.extend({ mixins: ['modelAware'], render: function() { var props = {}; var defaultValue = getModelValue(this); if (isCheckable) { props...
javascript
{ "resource": "" }
q296
loadPlugin
train
function loadPlugin(pluginRoot, noUI) { // noUI flag is used for loading dev plugins whose ui is from webpack dev server try { // const pkgJson = require(paths.join(pluginRoot, 'package.json')); const pluginInstance = {}; // Core part const coreIndex = paths.join(pluginRoot, 'core/index.js'); if...
javascript
{ "resource": "" }
q297
addPlugin
train
function addPlugin(plugin) { if (!plugin) { return; } if (!needFilterPlugin) { console.warn('You are adding a plugin after getPlugins is called.'); } needFilterPlugin = true; if (!plugin.name) { console.log('plugin: ', plugin); throw new Error('Each plugin should have a name.'); } if (_....
javascript
{ "resource": "" }
q298
generate
train
function generate(targetPath, args) { if ( !args.template && (!args.templateFile || (args.templateFile && !vio.fileExists(args.templateFile))) ) { const err = new Error(`No template file found: ${args.templateFile}`); err.code = 'TEMPLATE_FILE_NOT_FOUND'; throw err; } const tpl = args.templa...
javascript
{ "resource": "" }
q299
train
function() { var data = {}; if (this.data && !isObject(this.data)) { return this.data; } // TODO - don't do this yet until virt properties are checked // var keys = Object.keys(this); var keys = Object.keys(this.data ? this.data : this); for (var i = 0, n = keys.length; i < n; i...
javascript
{ "resource": "" }