_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
27
233k
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] = filterData(config, moduleData[id]);
javascript
{ "resource": "" }
q201
train
function(func, scope, args) { var fixedArgs = Array.prototype.slice.call(arguments, 2); return function()
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["__consoleShimTest__"] !== false) { // When first parameter is not a string then add a format string to // the argument list so we are able to modify it in the next stop if (typeof(args[0]) != "string") { args.unshift("%o"); max += 1; } // For each additional parameter which has no placeholder in the
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({ separator, transformer }) } } else if (1 === options.length) { const option = options[0] if (false === option
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++) {
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
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(extensionName) || revalidator.validate.formats.hasOwnProperty(extensionName)) {
javascript
{ "resource": "" }
q208
getError
train
function getError (type, expected, actual) { return { attribute: type, expected: expected,
javascript
{ "resource": "" }
q209
getResult
train
function getResult (err) { var res = { valid: true, errors: [] }; if (err !== null) { res.valid
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]) {
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 if (options.isUpdate) { var i, keys = Object.keys(schema.properties), length = keys.length; for (i = 0; i < length; i++) { if (!doc.hasOwnProperty(keys[i])) { // set property required to false schema.properties[keys[i]].required = false; // remove property from required array if (Array.isArray(schema.required) && schema.required.indexOf(keys[i]) > -1) { schema.required.splice(schema.required.indexOf(keys[i]), 1);
javascript
{ "resource": "" }
q212
componentExists
train
function componentExists(componentPath) { const existsInExtensions = fs.existsSync(path.resolve(EXTENSIONS_PATH, componentPath)); const
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)) { return reject(new TypeError(t('SUPPLIED_CONFIG_IS_NOT_AN_OBJECT', { typeofConfig: typeof config, }))); } const imports = importsStart ? [importsStart] : []; // Holds the import strings. const exports = [exportsStart]; // Holds the export strings. // eslint-disable-next-line global-require, import/no-dynamic-require const themePackage = require(`${themes.getPath()}/package.json`); if ( (type === TYPE_PORTALS || type === TYPE_WIDGETS) && has(themePackage.dependencies, 'react-loadable') ) { imports.push('import Loadable from \'react-loadable\';'); imports.push('import Loading from \'@shopgate/pwa-common/components/Loading\';'); imports.push(''); } try { Object.keys(config).forEach((id) => { const component = config[id]; const componentPath = isDev ? component.path.replace('/dist/', '/src/') : component.path; if (!componentExists(componentPath)) { return; } const variableName = getVariableName(id); const isPortalsOrWidgets = ( (type === TYPE_PORTALS && component.target !== 'app.routes')
javascript
{ "resource": "" }
q214
getIndexLogTranslations
train
function getIndexLogTranslations(type = TYPE_WIDGETS) { const params = { type: t(`TYPE_${type}`) }; return {
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
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(logNotFound); fs.writeFileSync(filePath, defaultContent, { flag: 'w+' });
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 =>
javascript
{ "resource": "" }
q219
indexWidgets
train
function indexWidgets() { const { widgets = {} } = getComponentsSettings(); return index({ file: 'widgets.js', config: { type: TYPE_WIDGETS,
javascript
{ "resource": "" }
q220
indexTracking
train
function indexTracking() { const { tracking = {} } = getComponentsSettings(); return index({ file: 'tracking.js', config: { type: TYPE_TRACKERS,
javascript
{ "resource": "" }
q221
indexPortals
train
function indexPortals() { const { portals = {} } = getComponentsSettings(); return index({ file: 'portals.js', config: { type: TYPE_PORTALS, config: portals,
javascript
{ "resource": "" }
q222
indexReducers
train
function indexReducers() { const { reducers = {} } = getComponentsSettings(); return index({ file: 'reducers.js',
javascript
{ "resource": "" }
q223
indexSubscribers
train
function indexSubscribers() { const { subscribers = {} } = getComponentsSettings(); return index({ file: 'subscribers.js', config: { type: TYPE_SUBSCRIBERS,
javascript
{ "resource": "" }
q224
indexTranslations
train
function indexTranslations() { const { translations = {} } = getComponentsSettings(); return index({ file: 'translations.js',
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 moleculeCreators = getMoleculeCreators(this.OCL.Molecule); query = moleculeCreators.get(format.toLowerCase())(query); } else if (!(query instanceof this.OCL.Molecule)) { throw new TypeError('toSearch must be a Molecule or string'); } let result; switch (mode.toLowerCase()) { case 'exact': result = exactSearch(this.moleculeDB.db, query, limit); break; case 'substructure': result =
javascript
{ "resource": "" }
q226
maybeApi
train
async function maybeApi ({ apiAddress, apiOpts, ipfsConnectionTest, IpfsApi }) { try { const ipfs = new IpfsApi(apiAddress, apiOpts)
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(Molecule.cHelperParities); // We need to have >0 and not >1 because there could be unspecified chirality in racemate for (let i = 0; i < tempMolecule.getAtoms(); i++) { // changed from from handling below; TLS 9.Nov.2015 if ( tempMolecule.isAtomStereoCenter(i) && tempMolecule.getStereoBond(i) === -1 ) { let stereoBond = tempMolecule.getAtomPreferredStereoBond(i); if (stereoBond !== -1) {
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) {
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;
javascript
{ "resource": "" }
q230
getFocusColor
train
function getFocusColor(colors) { if (Color(colors.primary).luminosity()
javascript
{ "resource": "" }
q231
applyContrastColors
train
function applyContrastColors(config) { const { colors } = config; return { ...config, colors: { ...colors,
javascript
{ "resource": "" }
q232
applyCustomColors
train
function applyCustomColors(config) { const { colors } = getAppSettings(); if (!config.hasOwnProperty('colors')) { return { ...config, colors, }; } return {
javascript
{ "resource": "" }
q233
module
train
function module(filename) { return function () { if (verbose.local) console.log(filename);
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: './', noFileOutput: true }); if (resultFiles === null) return; // Create zip. let zip = new JSZip(); // Add generated files. resultFiles.forEach(file => { zip.file(file.path, file.contents); }); // Add the icons. const dir = await fs.readdir(dirPath); const svgs = await Promise.all(dir.map(async file => { return file.endsWith('.svg') ? ( {
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);
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
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 genTasks = {}; /** * First, creates tasks for dependent font types. * Then creates task for specified font type and chains it to dependencies promises. * If some task already exists, it reuses it. */ const makeGenTask = type => { // If already defined return. if (genTasks[type]) return genTasks[type]; // Get generator function. const gen = generators[type]; // Create dependent functions const depsTasks = (gen.deps || []).map(depType => makeGenTask(depType));
javascript
{ "resource": "" }
q238
renderSass
train
async function renderSass (opts = {}) { const tpl = await fs.readFile(path.resolve(__dirname,
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 ? Object.keys(opts.fonts).reduce((acc, name) => { return { ...acc,
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) => {
javascript
{ "resource": "" }
q241
userError
train
function userError (details = [], code) { const err = new Error('User
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);
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) {
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) => {
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', 'previewDest', 'preview', 'catalogDest', 'experimentalFontOnCatalog', 'experimentalDisableStyles' ]); try { return collecticonsCompile({ dirPath, ...params }); } catch (error) { if (!error.userError) throw error; // Capture some errors and convert to their command line alternative. const code = error.code; if (code === 'PLC_CLASS_EXC') { error.details = ['Error: --no-sass-placeholder and --no-css-class are mutually exclusive'];
javascript
{ "resource": "" }
q246
bundleProgram
train
async function bundleProgram (dirPath, destFile) { await validateDirPathForCLI(dirPath);
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, 'exchanges', { get: function () { if (this.connection) { return this.connection.exchanges;
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 } var refs = schemaObj.refs; // the map to store schema value with sub reference var subRefs = {}; _.forEach(refs, function (index, refId) { // if reference id already resolved then continue the loop if (refId in resolvedValues) { return true; // continue } var refValue = refVal[index]; // if no further nested reference, add to resolved map if (_.isEmpty(refValue.refs)) {
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 var info = labels[label]; if(info) { fingerprints[info.fingerprint] = info; return info.fingerprint; } else { info = {}; //Try to get a fingerprint using the specified cache strategy var fullPath = path.resolve(rootPath + "/" + (label || this.url) ); //Use the "cache strategy" to get a fingerprint //Prefer the use of etag over lastModified when generating fingerprints if(!fs.existsSync(fullPath) ) return label; if(strategy.lastModified) { var mdate =
javascript
{ "resource": "" }
q250
train
function() { var self = this; return waterline.catalogs.findOne({"node": self.id}) .then(function(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(function () { if (collection.adapterDictionary.define !== 'mongo') { return bluebird.fromNode(
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 || {}; self.exitCode = code || [0]; self.maxBuffer = maxBuffer || Constants.ChildProcess.MaxBuffer; if (!self.file) { throw new Error('Unable to locate command file (' + self.command +').'); } if (!_.isEmpty(self.args)) { try {
javascript
{ "resource": "" }
q253
provideName
train
function provideName(obj, token){ if(!isString(token)) { throw new Error('Must provide string as name of module');
javascript
{ "resource": "" }
q254
providePromise
train
function providePromise(obj, providePromiseName) { if(!isString(providePromiseName)) { throw new Error('Must provide string as name of
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)) {
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(isString(inject.promise)) { injectMe = new di.InjectPromise(inject.promise);
javascript
{ "resource": "" }
q257
resolveInjects
train
function resolveInjects(obj, override){ var injects = obj.$inject || override; if (exists(injects)) { if (!Array.isArray(injects)) { injects = [injects];
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.$inject) || provide || injects)){
javascript
{ "resource": "" }
q259
_requireFile
train
function _requireFile(requirable, directory) { var required; try{ var res = resolve.sync(requirable, {
javascript
{ "resource": "" }
q260
_require
train
function _require(requireMe, provides, injects, currentDirectory, next) { var requireResult = _requireFile (requireMe, currentDirectory) || _requireFile (requireMe, defaultDirectory) || _requireFile (requireMe, __dirname) || _requireFile (requireMe, process.cwd()) || _requireFile (requireMe, (void 0)); if(!exists(requireResult)) { var directories = 'directories:('; directories += exists(currentDirectory) ? currentDirectory + ', ' : ''; directories += exists(defaultDirectory) ? defaultDirectory + ', ' : ''; directories += __dirname + ')'; throw new Error('dihelper incapable of finding specified file for require filename:' + requireMe + ', ' + directories); } if (typeof
javascript
{ "resource": "" }
q261
requireWrapper
train
function requireWrapper(requireMe, provides, injects, directory)
javascript
{ "resource": "" }
q262
requireGlob
train
function requireGlob(pattern) { return _.map(glob.sync(pattern), function (file) { var required = require(file); resolveProvide(required);
javascript
{ "resource": "" }
q263
injectableFromFile
train
function injectableFromFile(requireMe, provides, injects, directory)
javascript
{ "resource": "" }
q264
requireOverrideInjection
train
function requireOverrideInjection(requireMe, provides, injects, directory)
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(window.name)); } if (window.localStorage) { try { env.merge(environment, env.parse(window.localStorage.env || window.localStorage.debug)); } catch (e) {} } if ( 'object' === typeof window.location && 'string' === typeof window.location.hash && window.location.hash.length ) { env.merge(environment, env.parse(window.location.hash.charAt(0) === '#'
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 = tree.changed; var linkedFiles = []; for (var i = 0; i < generated.length; i += 1) { file = generated[i]; if (cache[file].isDirectory || copiedCache[file] === cache[file].statsHash) { continue; } src = srcDir + '/' + file; if (file.substr(-4) === '.css') { content = fs.readFileSync(src); cssDir = path.dirname(file); while ((linkedFile = urlRe.exec(content))) { linkedFile = (linkedFile[1][0] === '/') ? linkedFile[1].substr(1) : path.normalize(cssDir + '/' + linkedFile[1]); linkedFiles.push(linkedFile); }
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 instead'); options.files = files; } if (!(this instanceof CompassCompiler)) { return new CompassCompiler(inputTree, options); } if (options.exclude) { console.log('[broccoli-compass] DEPRECATION:
javascript
{ "resource": "" }
q268
addToCache
train
function addToCache(filename, obj) { if(cacheOn) { var x = cache[filename]; if(!x)
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 //if necessary, convert the indexes format to fit for different database _.forEach(indexes, function(indexItem) { assert.object(indexItem.keys, 'Database index keys should be object'); if (indexItem.options) { assert.object(indexItem.options, 'Database index options should be object'); } else { indexItem.options = {}; }
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( pluralize.singular(identity), criteria
javascript
{ "resource": "" }
q271
train
function (criteria, document) { var self = this; return this.needOne(criteria).then(function (target) { return
javascript
{ "resource": "" }
q272
train
function (criteria) { var self = this; return this.needOne(criteria).then(function (target) { return
javascript
{ "resource": "" }
q273
BaseError
train
function BaseError(message, context) { this.message = message; this.name = this.constructor.name;
javascript
{ "resource": "" }
q274
Subscription
train
function Subscription (queue, options) { assert.object(queue, 'queue'); assert.object(options, 'options');
javascript
{ "resource": "" }
q275
Perf
train
function Perf (stats, name, filter, rename) { this.stats = stats this.name = name this.filter = filter || function ()
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
javascript
{ "resource": "" }
q277
Message
train
function Message (data, headers, deliveryInfo) { assert.object(data); assert.object(headers);
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 * @extends {FileLoader} */ function ProfileService () { DbRenderable.call(this, { directory: Constants.Profiles.Directory, collectionName: 'profiles' }); } ProfileService.prototype.get = function (name, raw, scope ) {
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.WorkingDirectory, '' ) + ':' + current.getLineNumber(); return file.replace(/^node_modules/, ''); } function Logger (module) { var provides = util.provides(module); if (provides !== undefined) { this.module = provides; } else { if (_.isFunction(module)) { this.module = module.name; } else { this.module = module || 'No Module'; } } } Logger.prototype.log = function (level, message, context) { assert.isIn(level, levels); assert.string(message, 'message'); // Exit if the log level of this message is less than the minimum log level. var minLogLevel = nconf.get('minLogLevel'); if ((minLogLevel === undefined) || (typeof minLogLevel !== 'number')) { minLogLevel = 0; } if (Constants.Logging.Levels[level] < minLogLevel) { return; } events.log({
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
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 property of url and method. * @return {boolean} whether settings is valid. */ this.isSettingValid = function(settings){ if (_.isEmpty(settings)) { return false; } if ( ! (settings.hasOwnProperty('url') && settings.hasOwnProperty('method'))) { return false; } if (_.isEmpty(settings.url) || _.isEmpty(settings.method)) { return false; } if (_.indexOf(validMethods, settings.method) === -1) { return false; } return true; }; /** * Parse and convert setting into a urlObject that suitable for * http/https module in NodeJs. * @return {object} - the object that suitable for Node http/https module. */ this.setupUrlOptions = function(settings) { var urlTool = require('url'); var urlObject = {}; // Parse the string into url options if (typeof (settings.url) === 'string') { urlObject = urlTool.parse(settings.url); } else {
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. * @constructor * @extends {FileLoader}
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])) { program = fgArgs[0][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 - start coordinate for X * @param startY - start coordinate for Y * @param endX - end coordinate for X * @param endY - end coordinate for Y * @param contourLevel - Contour level for line. */ this.drawContour = function(startX, startY, endX, endY, contourLevel, k) { var cb = c.contours[k]; if (!cb) { cb = c.contours[k] = new ContourBuilder(contourLevel); } cb.addSegment({x: startX, y: startY}, {x: endX, y: endY}); } this.contourList = function() { var l = []; var a = c.contours; for (var k in a) { var s = a[k].s; var
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) { var fireExisting = true; if (/^\/transport\/server\//.test(req.url)) { fireExisting = onTransportRequest(req, res); } if (fireExisting) { for (var i = 0, l = existingListeners.length; i < l; i++) {
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, "_"); } // Write the authentication header _client.write( "hello version node/statsd-instrumental-backend/" + cleanString(package.version) + " hostname " + cleanString(hostname) + " pid " + cleanString(process.pid) + " runtime " + cleanString("node/" + process.versions.node) + " platform " + cleanString(process.platform + "-" + process.arch) + "\n" + "authenticate " + key + "\n" ); }); // We need to handle the timeout. I think we should only care about read // timeouts. That is we write out data, if we don't hear back in timeout // seconds then the data probably hasn't reached the server. client.setTimeout(timeout, function() { // ZOMG FAILED WRITING WE ARE BAD AT COMPUTER SCIENCE if(state == "connected") { // We're waiting to hear back from the server and it has timed out. It's // unlikely that the server will suddenly wake up and send us our data so // lets disconnect and go shopping. client.end(); } }); // HOW WE HANDLE ERRORS. We should probably reconnect, maybe retry. client.addListener("error", function(exception){ if(debug) { log("Client error:", exception); } instrumentalStats.last_exception = Math.round(new Date().getTime() / 1000); });
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, { ObjectExpression(path) { const node = path.node; const props = node.properties; if (!props.length) return; const obj = {}; props.forEach(p => { if (_.has(p, 'key.name') && !p.computed) { obj[p.key.name] = p; } }); if (obj.path && obj.component) { // in a route config, if an object expression has both 'path' and 'component' property, then it's a route config arr.push({ path: _.get(obj.path, 'value.value'), // only string literal supported component: _.get(obj.component, 'value.name'), // only identifier supported isIndex: !!obj.isIndex && _.get(obj.isIndex, 'value.value'), // suppose to be boolean node: { start: node.start, end: node.end, }, }); } if (obj.isIndex && obj.component && !indexRoute) { // only find the first index route
javascript
{ "resource": "" }
q288
getKey
train
function getKey(context) { if (context.getModelKey) { return context.getModelKey(); }
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, cb: cb, ctx: ctx }; function _on(modelOrCollection) { _this[type === 'on'
javascript
{ "resource": "" }
q290
getModelAndCollectionEvents
train
function getModelAndCollectionEvents(type, context) { var key = '__' + type + CAP_EVENTS, modelEvents = getState(key, context); if (!modelEvents) { modelEvents = {};
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)) { if (_.indexOf(currentLoads, xhrEvent) >= 0) { if (!force) { return; } } else { currentLoads.push(xhrEvent); }
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 = currentLoads.indexOf(xhrEvent); }
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 === method) {
javascript
{ "resource": "" }
q294
train
function() { var keys = arguments.length > 0 ? Array.prototype.slice.call(arguments, 0) : undefined; return { getInitialState: function() { var self = this;
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.defaultChecked = defaultValue; } else { props.defaultValue = defaultValue; } return React.DOM[type](_.extend(props, attributes, this.props, {onChange: twoWayBinding(this)}), this.props.children); }, getValue: function() { if (this.isMounted()) { if (isCheckable) { var el = this.getDOMNode();
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 (fs.existsSync(coreIndex)) { Object.assign(pluginInstance, require(coreIndex)); } // UI part if (!noUI && fs.existsSync(path.join(pluginRoot, 'build/main.js'))) { pluginInstance.ui = { root: path.join(pluginRoot, 'build'), }; } // Plugin meta defined in package.json const pkgJsonPath = path.join(pluginRoot, 'package.json'); let pkgJson = null; if (fs.existsSync(pkgJsonPath)) { pkgJson = fs.readJsonSync(pkgJsonPath); ['appType', 'name', 'featureFiles'].forEach(key => { if (!pluginInstance.hasOwnProperty(key) && pkgJson.hasOwnProperty(key)) { if (key === 'name') {
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
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; }
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": "" }