sandbox.stub(wctLocalBrowsers, 'supported', function() { return _.keys(LOCAL_BROWSERS); });
/** * return an array containing all the missing required * properties */ function getMissingProps(data) { var containsKey = _.partial(_.includes, _.keys(data)); return _.filter(required, function (req) { return !containsKey(req); }); }
function _callOr(record, criteria, cb){ var boundFunc = _.bind(_checkTrue, {record: record, criteria: criteria}); async.detect(_.keys(criteria), boundFunc, function(innerResult){ return cb(innerResult); }); }
function recursiveParse(obj, parentAttr) { // Return if no object if (!obj) return; // Handle array of types for findOrCreateEach if (_.isString(obj)) { if (hasOwnProperty(self._transformations, obj)) { values = self._transformations[obj]; return; } return; } _.keys(obj).forEach(function(property) { // Just a double check to exit if hasOwnProperty fails if (!hasOwnProperty(obj, property)) return; // Schema must be serialized in first level only if (behavior === 'schema') { if (hasOwnProperty(self._transformations, property)) { obj[self._transformations[property]] = _.clone(obj[property]); delete obj[property]; } return; } // If the property === SELECT check for any transformation keys if (_.isArray(obj[property]) && property === 'select') { obj[property].forEach(function(selector, index) { if (self._transformations[selector]) { obj[property][index] = self._transformations[selector]; } }); } // Handle Agregate if (( ['sum', 'average', 'min', 'max', 'groupBy'].indexOf(property) >= 0 ) && self._transformations[obj[property]]) { obj[property] = self._transformations[obj[property]]; } // Detect attribute parentAttr = self.attributes[property] || self.attributes[self._transformations[property]] || parentAttr; var type = parentAttr ? parentAttr.type || parentAttr : null; // Recursively parse `OR` and `AND` criteria objects to transform keys if (_.isArray(obj[property]) && (property === 'or' || property === 'and')) return recursiveParse(obj[property], parentAttr); // If Nested Object check it's not a json attribute property if (type !== 'json' && _.isPlainObject(obj[property])) { // check if object key is in the transformations if (hasOwnProperty(self._transformations, property)) { obj[self._transformations[property]] = _.clone(obj[property]); delete obj[property]; return recursiveParse(obj[self._transformations[property]], parentAttr); } return recursiveParse(obj[property], parentAttr); } // Check if property is a transformation key if (hasOwnProperty(self._transformations, property)) { obj[self._transformations[property]] = obj[property]; delete obj[property]; property = self._transformations[property]; } // Cast types if (_.isString(obj[property]) && (type === 'date' || type === 'datetime')) { obj[property] = new Date(obj[property]); } }); }
var f = function(context, callback) { let method = _.keys(requestSpec)[0].toUpperCase(); let params = requestSpec[method.toLowerCase()]; let uri = maybePrependBase(template(params.url, context), config); let tls = config.tls || {}; let timeout = config.timeout || 10; let requestParams = _.cloneDeep(params); requestParams = _.extend(requestParams, { uri: uri, method: method, headers: { }, timeout: timeout * 1000, jar: context._jar }); requestParams = _.extend(requestParams, tls); if (params.json) { requestParams.json = template(params.json, context); } else if (params.body) { requestParams.body = template(params.body, context); } // Assign default headers then overwrite as needed let defaultHeaders = lowcaseKeys( (config.defaults && config.defaults.headers) ? config.defaults.headers : {'user-agent': USER_AGENT}); requestParams.headers = _.extend(defaultHeaders, lowcaseKeys(params.headers)); let headers = _.foldl(requestParams.headers, function(acc, v, k) { acc[k] = template(v, context); return acc; }, {}); requestParams.headers = headers; let defaultCookie = config.defaults ? config.defaults.cookie || {} : {}; let cookie = _.foldl( params.cookie, function(acc, v, k) { acc[k] = v; return acc; }, defaultCookie); if (cookie) { _.each(cookie, function(v, k) { context._jar.setCookie(k + '=' + template(v, context), uri); }); } if (config.http2) { requestParams.http2 = true; } else { requestParams.agent = context._agent; } debug('request: %j', requestParams); request(requestParams, function requestCallback(err, res, body) { if (err) { let errCode = err.code || err.message; ee.emit('error', errCode); debug(err); // this aborts the scenario return callback(err, context); } debugResponse(res.headers); debugResponse(res.body); if (params.capture || params.match) { let parser; let extractor; if (isJSON(res)) { parser = parseJSON; extractor = extractJSONPath; } else if (isXML(res)) { parser = parseXML; extractor = extractXPath; } else if ((params.capture && params.capture.json) || (params.match && params.match.json)) { // TODO: We might want to issue some kind of a warning here parser = parseJSON; extractor = extractJSONPath; } else if ((params.capture && params.capture.xpath) || (params.match && params.match.xpath)) { // TODO: As above parser = parseXML; extractor = extractXPath; } else { // We really don't know what to do here. parser = parseJSON; extractor = extractJSONPath; } parser(res.body, function(err2, doc) { if (err2) { return callback(err2, null); } if (params.match) { let expr = params.match.json || params.match.xpath; let result = extractor(doc, expr); let expected = template(params.match.value, context); debug('match: %s, expected: %s, got: %s', expr, expected, result); if (result !== expected) { ee.emit('match', false, { expected: expected, got: result, request: requestParams }); if (params.match.strict) { // it's not an error but we finish the scenario return callback(null, context); } } else { ee.emit('match', true); } } if (params.capture) { let expr = params.capture.json || params.capture.xpath; let result = extractor(doc, expr); context.vars[params.capture.as] = result; debug('capture: %s = %s', params.capture.as, result); if (params.capture.transform) { let result2 = engineUtil.evil( context.vars, params.capture.transform); context.vars[params.capture.as] = result2; debug('transform: %s = %s', params.capture.as, context.vars[params.capture.as]); } } debug('context.vars.$ = %j', doc); context.vars.$ = doc; context._successCount++; context._pendingRequests--; return callback(null, context); }); } else { context.vars.$ = res.body; context._successCount++; context._pendingRequests--; return callback(null, context); } }) .on('request', function(req) { ee.emit('request'); const startedAt = process.hrtime(); req.on('response', function updateLatency(res) { let code = res.statusCode; const endedAt = process.hrtime(startedAt); let delta = (endedAt[0] * 1e9) + endedAt[1]; ee.emit('response', delta, code, context._uid); }); }).on('end', function() { }); };
fi.tr = function tr(s, o, d) { return ( o = o || L1.Translations.getCurrent(ctx) || {}, ~ _.keys(o).indexOf(s) ? o[s] : typeof d !== 'undefined' ? d : s ); };
hasFilters: function () { return (this.filters && _.keys(this.filters).length); },
let filter = _.find(filters, function (obj) { let key = _.keys(obj.range)[0]; return key === indexPattern.timeFieldName; });
it("ontology add/remove", function() { var data = new $N.nobject(); assert(data, "new nobject"); $N.add(data); { assert($N.object[data.id].id === data.id, "object inserted"); assert($N.instance[data.id].id === data.id, "object identified as instance"); assert($N.class[data.id] === undefined, "object not a class"); assert($N.property[data.id] === undefined, "object not a property"); } $N.remove(data); { assert($N.object[data.id] === undefined, "object removed"); } $N.add(data); $N.add({id: data.id, removed: true}); { assert($N.object[data.id] === undefined, "object removed via removal object"); } var prop1 = { id: 'testProperty', description: 'A test property', extend: 'integer', minArity: 1, maxArity: 2, default: 0, strength: 1.0, readonly: true }; assert( util.objIsProperty(prop1), "detect property as a property"); $N.add(prop1); { assert($N.property[prop1.id].id === prop1.id, "property present in ontology"); } $N.add(class1); { assert($N.class[class1.id].id === class1.id, "class present in ontology"); assert(class1.property['testProperty'], "class linked to previously defined test property"); assert($N.classRoot['Class1'], "class identified as a root"); //ok($N.property['embeddedProperty'], "embedded property present in ontology"); //ok(class1.property['embeddedProperty'], "class linked to newly defined embedded property"); } var class2 = { id: 'Class2', description: 'A test class, with value in hash form', extend: "Class1", value: { "testProperty2": { name: '2nd Embedded property, which adds to the ontology', extend: 'integer' } } }; $N.add(class2); { assert($N.property['testProperty2'], "embedded property present in ontology"); assert(class2.property['testProperty2'], "class linked to previously defined test property"); assert(!$N.classRoot['Class2'], "class2 not identified as a root"); } var subclass1 = { id: 'SubClass1', extend: ['Class1'] }; $N.add(subclass1); { assert($N.class[subclass1.id].id === subclass1.id, "subclass present in ontology"); assert(subclass1.class['Class1'] === class1, "subclass .class field"); assert(class1.subclass['SubClass1'] === subclass1, "class .subclass field"); assert(!$N.classRoot['SubClass1'], "class identified as a root"); } //test tag indexing var data2 = new $N.nobject().addTag('Class1'); $N.add(data2); { assert( _.keys($N.tagged['Class1'])[0] === data2.id, "adding instance indexes by its tags" ); } $N.remove(data2); { assert( _.keys($N.tagged['Class1']).length === 0, "removing instance unindexes by its tags" ); } $N.clear(); assert(0 == $N.dgraph.order(), "Dgraph empty after clear()"); assert(0 == $N.ugraph.order(), "Ugraph empty after clear()"); });
const dragDropZone = ( state = defaultState, action ) => { switch ( action.type ) { case types.APPEND_OBS_CARDS: { return update( state, { obsCards: { $merge: action.obsCards } } ); } case types.UPDATE_OBS_CARD: { if ( state.obsCards[action.obsCard.id] === undefined ) { return state; } const attrs = action.attrs; // reset the gallery to the first photo when a new photo is added if ( action.attrs.files ) { attrs.galleryIndex = 1; } const keys = _.keys( attrs ); if ( _.difference( keys, ["save_state"] ).length > 0 && attrs.modified !== false ) { attrs.modified = true; } attrs.updatedAt = new Date( ).getTime( ); let newState = update( state, { obsCards: { [action.obsCard.id]: { $merge: attrs } } } ); if ( state.selectedObsCards[action.obsCard.id] ) { newState = update( newState, { selectedObsCards: { [action.obsCard.id]: { $set: newState.obsCards[action.obsCard.id] } } } ); } return newState; } case types.UPDATE_OBS_CARD_FILE: { if ( state.obsCards[action.obsCard.id] === undefined || state.obsCards[action.obsCard.id].files[action.file.id] === undefined ) { return state; } let newState = update( state, { obsCards: { [action.obsCard.id]: { files: { [action.file.id]: { $merge: action.attrs } } } } } ); if ( state.selectedObsCards[action.obsCard.id] ) { newState = update( newState, { selectedObsCards: { [action.obsCard.id]: { $set: newState.obsCards[action.obsCard.id] } } } ); } return newState; } case types.UPDATE_SELECTED_OBS_CARDS: { action.attrs.updatedAt = new Date( ).getTime( ); let modified = Object.assign( { }, state.obsCards ); _.each( state.selectedObsCards, c => { modified = update( modified, { [c.id]: { $merge: action.attrs } } ); } ); return Object.assign( { }, state, { obsCards: modified, selectedObsCards: _.pick( modified, _.keys( state.selectedObsCards ) ) } ); } case types.SELECT_OBS_CARDS: { let modified = Object.assign( { }, state.obsCards ); for ( const k in modified ) { if ( action.ids[modified[k].id] ) { if ( !modified[k].selected ) { modified = update( modified, { [k]: { $merge: { selected: true } } } ); } } else if ( modified[k].selected ) { modified = update( modified, { [k]: { $merge: { selected: false } } } ); } } return Object.assign( { }, state, { obsCards: modified, selectedObsCards: _.pick( modified, _.keys( action.ids ) ) } ); } case types.SELECT_ALL: { let modified = Object.assign( { }, state.obsCards ); _.each( modified, c => ( modified = update( modified, { [c.id]: { $merge: { selected: true } } } ) ) ); return Object.assign( { }, state, { obsCards: modified, selectedObsCards: modified } ); } case types.REMOVE_OBS_CARD: { const cards = Object.assign( { }, state.obsCards ); const ids = Object.assign( { }, state.selectedIDs ); delete cards[action.obsCard.id]; delete ids[action.obsCard.id]; return Object.assign( { }, state, { obsCards: cards, selectedIDs: ids } ); } case types.REMOVE_SELECTED: { const modified = Object.assign( { }, state.obsCards ); _.each( state.selectedObsCards, ( v, id ) => ( delete modified[id] ) ); return Object.assign( { }, state, { obsCards: modified, selectedObsCards: { } } ); } case types.CREATE_BLANK_OBS_CARD: { const obsCard = new ObsCard( ); return update( state, { obsCards: { [obsCard.id]: { $set: obsCard } } } ); } case types.SET_STATE: { let modified = Object.assign( { }, state ); _.each( action.attrs, ( val, attr ) => { modified = update( modified, { [attr]: { $set: val } } ); } ); return modified; } case types.UPDATE_STATE: { let modified = Object.assign( { }, state ); _.each( action.attrs, ( val, attr ) => { modified = update( modified, { [attr]: { $merge: val } } ); } ); return modified; } default: return state; } };
Deferred.prototype.populate = function(keyName, criteria) { var self = this; var joins = []; var pk = 'id'; var attr; var join; // Normalize sub-criteria try { criteria = normalize.criteria(criteria); //////////////////////////////////////////////////////////////////////// // TODO: // instead of doing this, target the relevant pieces of code // with weird expectations and teach them a lesson // e.g. `lib/waterline/query/finders/operations.js:665:12` // (delete userCriteria.sort) // // Except make sure `where` exists criteria.where = criteria.where === false ? false : (criteria.where || {}); //////////////////////////////////////////////////////////////////////// } catch (e) { throw new Error( 'Could not parse sub-criteria passed to ' + util.format('`.populate("%s")`', keyName) + '\nSub-criteria:\n' + util.inspect(criteria, false, null) + '\nDetails:\n' + util.inspect(e, false, null) ); } try { // Set the attr value to the generated schema attribute attr = this._context.waterline.schema[this._context.identity].attributes[keyName]; // Get the current collection's primary key attribute Object.keys(this._context._attributes).forEach(function(key) { if (hasOwnProperty(self._context._attributes[key], 'primaryKey') && self._context._attributes[key].primaryKey) { pk = self._context._attributes[key].columnName || key; } }); if (!attr) { throw new Error( 'In ' + util.format('`.populate("%s")`', keyName) + ', attempting to populate an attribute that doesn\'t exist' ); } ////////////////////////////////////////////////////////////////////// // (there has been significant progress made towards both of these /// // goals-- contact @mikermcneil if you want to help) ///////////////// ////////////////////////////////////////////////////////////////////// // TODO: // Create synonym for `.populate()` syntax using criteria object // syntax. i.e. instead of using `joins` key in criteria object // at the app level. ////////////////////////////////////////////////////////////////////// // TODO: // Support Mongoose-style `foo.bar.baz` syntax for nested `populate`s. // (or something comparable.) // One solution would be: // .populate({ // friends: { // where: { name: 'mike' }, // populate: { // dentist: { // where: { name: 'rob' } // } // } // } // }, optionalCriteria ) //////////////////////////////////////////////////////////////////// // Grab the key being populated to check if it is a has many to belongs to // If it's a belongs_to the adapter needs to know that it should replace the foreign key // with the associated value. var parentKey = this._context.waterline.collections[this._context.identity].attributes[keyName]; // Build the initial join object that will link this collection to either another collection // or to a junction table. join = { parent: this._context.identity, parentKey: attr.columnName || pk, child: attr.references, childKey: attr.on, select: Object.keys(this._context.waterline.schema[attr.references].attributes), alias: keyName, removeParentKey: !!parentKey.model, model: !!hasOwnProperty(parentKey, 'model'), collection: !!hasOwnProperty(parentKey, 'collection') }; // Build select object to use in the integrator var select = []; Object.keys(this._context.waterline.schema[attr.references].attributes).forEach(function(key) { var obj = self._context.waterline.schema[attr.references].attributes[key]; if (!hasOwnProperty(obj, 'columnName')) { select.push(key); return; } select.push(obj.columnName); }); join.select = select; // If linking to a junction table the attributes shouldn't be included in the return value if (this._context.waterline.schema[attr.references].junctionTable) join.select = false; joins.push(join); // If a junction table is used add an additional join to get the data if (this._context.waterline.schema[attr.references].junctionTable && hasOwnProperty(attr, 'on')) { // clone the reference attribute so we can mutate it var reference = _.clone(this._context.waterline.schema[attr.references].attributes); // Find the other key in the junction table Object.keys(reference).forEach(function(key) { var attribute = reference[key]; if (!hasOwnProperty(attribute, 'references')) { delete reference[key]; return; } if (hasOwnProperty(attribute, 'columnName') && attribute.columnName === attr.on) { delete reference[key]; return; } if (hasOwnProperty(attribute, 'columnName') && attribute.columnName !== attr.on) { return; } if (key !== attr.on) delete reference[key]; }); // Get the only remaining key left var ref = Object.keys(reference)[0]; if (ref) { // Build out the second join object that will link a junction table with the // values being populated var selects = _.map(_.keys(this._context.waterline.schema[reference[ref].references].attributes), function(attr) { var expandedAttr = self._context.waterline.schema[reference[ref].references].attributes[attr]; return expandedAttr.columnName || attr; }); join = { parent: attr.references, parentKey: reference[ref].columnName, child: reference[ref].references, childKey: reference[ref].on, select: selects, alias: keyName, junctionTable: true, removeParentKey: !!parentKey.model, model: false, collection: true }; joins.push(join); } } // Append the criteria to the correct join if available if (criteria && joins.length > 1) { joins[1].criteria = criteria; } else if (criteria) { joins[0].criteria = criteria; } // Set the criteria joins this._criteria.joins = Array.prototype.concat(this._criteria.joins || [], joins); return this; } catch (e) { throw new Error( 'Encountered unexpected error while building join instructions for ' + util.format('`.populate("%s")`', keyName) + '\nDetails:\n' + util.inspect(e, false, null) ); } };
function _queryIntersection(a, b) { if (!a || !b) { throw NO_MATCH; } if (Tyr.isEqual(a, b)) { return a; } if (isOpObject(a) && isValue(b)) { b = { $eq: b }; } else if (isOpObject(b) && isValue(a)) { a = { $eq: a }; } if (isValue(a) || isValue(b) || Array.isArray(a) || Array.isArray(b)) { throw NO_MATCH; } const obj = {}; for (const n in a) { const av = a[n], bv = b[n]; if (av === undefined) { obj[n] = bv; } else if (bv === undefined) { obj[n] = av; } else { switch (n) { case '$in': if (Array.isArray(av)) { if (Array.isArray(bv)) { const rslt = arrayIntersection(av, bv); if (!rslt.length) throw NO_MATCH; obj[n] = rslt; } else if (arrayIncludes(av, bv)) { obj[n] = bv; } else { throw NO_MATCH; } } break; default: obj[n] = _queryIntersection(av, bv); } } } for (const n in b) { if (a[n] === undefined) { obj[n] = b[n]; } } // simplification if (obj.$eq) { if (obj.$in) { if (arrayIncludes(obj.$in, obj.$eq)) { delete obj.$in; } else { throw NO_MATCH; } } if (obj.$lt) { if (obj.$eq < obj.$lt) { delete obj.$lt; } else { throw NO_MATCH; } } if (obj.$gt) { if (obj.$eq > obj.$gt) { delete obj.$gt; } else { throw NO_MATCH; } } if (obj.$lte) { if (obj.$eq <= obj.$lte) { delete obj.$lt; } else { throw NO_MATCH; } } if (obj.$gte) { if (obj.$eq >= obj.$gte) { delete obj.$gt; } else { throw NO_MATCH; } } } const objKeys = _.keys(obj); if (objKeys.length === 1) { switch (objKeys[0]) { case '$in': if (!Array.isArray(obj.$in)) { return obj.$in; } break; case '$eq': return obj.$eq; break; } } return obj; }
fakeVat.dbStart({schemasFolder: __dirname + "/testModels"}, function (err) { _.keys(fakeVat.dbmodels).length.should.equal(1); done() })
function isTest(f) { return (/\.test\.html$/).test(f); } function isExpectation(f) { return (/\.expectation\.html$/).test(f); } var casefiles = fs.readdirSync(casedir), tests = _.filter(casefiles, isTest), expectations = _.filter(casefiles, isExpectation), cases = _.groupBy(tests.concat(expectations), function (f) { return f.split('.')[0]; }), keys = _.keys(cases); describe('bin/swig -v', function () { it('shows the version number', function (done) { exec('node ' + bin + ' -v', function (err, stdout, stderr) { expect((/^\d+\.\d+\.\d+/).test(stdout)).to.equal(true); done(); }); }); }); describe('bin/swig render', function () { var locals = fixPath(bindir + '/bin.locals.json'), key = keys[_.random(keys.length - 1)], testcase = cases[key], test = fixPath(casedir + _.find(testcase, isTest)),
it('should return an object of unique keys', function () { expect(_.uniq(_.keys(results)).length).to.be(_.keys(results).length); });
it('should have a task named \''+task+'\'', function(done){ assert(_.indexOf(_.keys(gulp.tasks),task)>=0); done(); });
var isValidParams = function (params) { return _.every(_.keys(params), function (key) { return _.contains(put_params, key); }); };
function tick() { const time = Date.now(); _.forEach(_.keys(blocks), key => { blocks[key].tick(time); }); }
return result; }); }; lodashExtras.is = is; /** * Generate `ensure` methods- Ensure that value is of type x * * @method ensure{Type} * @param {*} value: To check * @param {*} [valueDefault=defaults[condition]: What to default to * @return {*} Ensured value */ _.forEach( _.keys(lodashUtils.typeDefaults()), (type) => { lodashExtras[`ensure${type}`] = lodashUtils.makeEnsureType(type); } ); /** * Javascript `typeof` alias * * @method typeOf * @param {*} value: Value to check * @return {String} The type of `value` */ export var typeOf = (value) => typeof value; lodashExtras.typeOf = typeOf;
var checkGenerator = function(options) { if (!generators[options.generator]) { return Q.reject(new Error("Invalid generator (availables are: "+_.keys(generators).join(", ")+")")); } return Q(); };
function setStartingOrder(tree) { var out = 'ok', type, err; var containerNames = _.keys(tree.containers); var starterCandidates = []; var leftContainers = _.clone(containerNames); var counter = 0; do { for(var containerIdx in leftContainers) { var containerName = leftContainers[containerIdx]; var container = tree.containers[containerName]; var canStart = true; for (var linkIdx in container.links) { var link = container.links[linkIdx]; if (!_.contains(containerNames, link.containerId)) { out = 'nok'; type = 'error'; var kuberBrokenDependencies = resourceBundle.Errors.Kuber.BrokenDependencies; err = { msg: format(kuberBrokenDependencies.msg, { containerName: containerName, containerId: link.containerId }), mitigation: kuberBrokenDependencies.mitigation }; } canStart = canStart && _.contains(starterCandidates, link.containerId); } if (canStart) { starterCandidates.push(containerName); _.remove(containerNames, function(cname) { return cname === containerIdx }); } } leftContainers = _.difference(containerNames, starterCandidates); counter++; } while (leftContainers.length > 0 && counter < containerNames.length); if (starterCandidates.length !== containerNames.length) { out = 'nok'; type = 'error'; var kuberCircularDependencies =resourceBundle.Errors.Kuber.CircularDependencies; err = { msg: format(kuberCircularDependencies, { containers: leftContainers.join('", "') }), mitigation: kuberCircularDependencies.mitigation }; } msg.delayedItemEnd(out, type); if (type === 'warn' && err) { msg.warn(err); } if (type === 'error') { throw(err); } if (out === 'ok') { tree.startingOrder = _.clone(starterCandidates); msg.item('Starting order', '"' + starterCandidates.join('", "') + '"'); } return tree; };
constructor(name, config) { // Additional arguments that every dataSource take config.args.push({ name: 'offset', types: ['string', 'null'], help: 'Offset the series retrieval by a date expression. Eg -1M to make events from one month ago appear as if they are happening now' }); config.args.push({ name: 'fit', types: ['string', 'null'], help: 'Algorithm to use for fitting series to the target time span and interval. Available: ' + _.keys(fitFunctions).join(', ') }); // Wrap the original function so we can modify inputs/outputs with offset & fit const originalFunction = config.fn; config.fn = function (args, tlConfig) { const config = _.clone(tlConfig); if (args.byName.offset) { config.time = _.cloneDeep(tlConfig.time); config.time.from = offsetTime(config.time.from, args.byName.offset); config.time.to = offsetTime(config.time.to, args.byName.offset); } return Promise.resolve(originalFunction(args, config)).then(function (seriesList) { seriesList.list = _.map(seriesList.list, function (series) { if (series.data.length === 0) throw new Error(name + '() returned no results'); series.data = offsetSeries(series.data, args.byName.offset); series.fit = args.byName.fit || series.fit || 'nearest'; return series; }); return seriesList; }); }; super(name, config); // You need to call timelionFn if calling up a datasource from another datasource, // otherwise teh series will end up being offset twice. this.timelionFn = originalFunction; this.datasource = true; this.cacheKey = function (item) { return item.text; }; Object.freeze(this); }
module.exports = function (sandbox) { var N = sandbox.N , knownLocales = [] , serverI18n = null , serverI18nAccum = [] , clientI18n = null , clientI18nAccum = [] , clientI18nPackages = [] , tmpdir = sandbox.tmpdir , timer = stopwatch(); function addServerI18n(locale, apiPath, phrases) { serverI18nAccum.push({ apiPath: apiPath, locale: locale, phrases: phrases }); if (!_.contains(knownLocales, locale)) { knownLocales.push(locale); } } function addClientI18n(locale, pkgName, apiPath, phrases) { serverI18nAccum.push({ apiPath: apiPath, locale: locale, phrases: phrases }); clientI18nAccum.push({ apiPath: apiPath, locale: locale, phrases: phrases }); if (!_.isEmpty(phrases) && !_.contains(clientI18nPackages, pkgName)) { clientI18nPackages.push(pkgName); } if (!_.contains(knownLocales, locale)) { knownLocales.push(locale); } } // Collect translations of all packages (in modules tree). _.forEach(sandbox.config.packages, function (pkgConfig, pkgName) { findPaths(pkgConfig.i18n_client, function (fsPath, apiPath) { _.forEach(require(fsPath), function (phrases, locale) { addClientI18n(locale, pkgName, apiPath, phrases); }); }); findPaths(pkgConfig.i18n_server, function (fsPath, apiPath) { _.forEach(require(fsPath), function (phrases, locale) { addServerI18n(locale, apiPath, phrases); }); }); }); // Collect global translations. _.forEach(N.runtime.apps, function (app) { var directory = path.join(app.root, 'config', 'locales'); fstools.walkSync(directory, /\.yml$/, function (file) { _.forEach(require(file).i18n, function (data, locale) { _.forEach(data, function (phrases, pkgName) { addClientI18n(locale, pkgName, pkgName, phrases); }); }); }); }); // Correct the application config if needed and initialize BabelFishes. initLocalesConfig(N, knownLocales); serverI18n = new BabelFish(N.config.locales['default']); clientI18n = new BabelFish(N.config.locales['default']); _.forEach(serverI18nAccum, function (data) { serverI18n.addPhrase(data.locale, data.apiPath, data.phrases); }); _.forEach(clientI18nAccum, function (data) { clientI18n.addPhrase(data.locale, data.apiPath, data.phrases); }); // Write client-side i18n bundles for each package and locale. _.keys(sandbox.config.packages).forEach(function (pkgName) { var outdir = path.join(tmpdir, 'i18n', pkgName); fstools.mkdirSync(outdir); _.forEach(N.config.locales['enabled'], function (locale) { var result, outfile = path.join(outdir, locale + '.js'); result = WRAPPER_TEMPLATE({ locale: locale , data: jetson.serialize(clientI18n.getCompiledData(locale)) }); fs.writeFileSync(outfile, result, 'utf8'); }); }); // Expose server locales. N.runtime.i18n = serverI18n; // Expose list of packages with client-side i18n. sandbox.clientI18nPackages = clientI18nPackages; N.logger.info('Processed i18_* sections %s', timer.elapsed); };
mergeGlobal: function ({val, key, globalData, context}) { //if key of true it means asing the global data to key if (val === true) { return globalData; } /** * Helpers that gets based on path, formates into array, and pull, or defualts */ const getFormatPull = function (obj, paths = [], defaultRtn = undefined) { //to array helper const toArr = function (_val) { return _val && !_.isArray(_val) ? [_val] : _val; }; //loop to get for (let i = 0; i < paths.length; i++) { const res = _.get(obj, paths[i]); if (res) { //remove/return _.unset(obj, paths[i]); return {obj, res: toArr(res)}; } } return {obj, res: toArr(defaultRtn)}; }; //check for target array that specifies the "targets" to merge into const {res: globalTarget, obj: _globalData} = getFormatPull( _.cloneDeep(globalData), ['target', 'option.target'] ); //check omit option, omits props from the merge let omitList; ({res: omitList, obj: val} = getFormatPull(val, ['omit', 'option.omit'])); //if true we want to omit all the common data omitList = _.first(omitList) === true ? _.keys(_globalData) : omitList; //check pick list, opposit of ommit let pickList; ({res: pickList, obj: val} = getFormatPull(val, ['pick', 'option.pick'])); //helper to defaultsDeep, based on if there is a pick, omit, of neither const defaultIn = function (_val, _global) { //removes context need be const rmContext = (d) => context ? d[context] : d; _global = context ? {[context]: _global} : _global; //-> return pickList //pick and merge, reducing to deepPick -> set(x.a.c, val) ? _.defaultsDeep(_val, _.reduce(pickList, function (prv, _key, i, col) { prv = !_.has(_global, _key) ? prv //partial is needed other wise it treats numbers as arrays, as in 'timeline.44' //will create 44 undefined arrays : _.defaultsDeep(prv, _.setWith({}, _key, _.get(_global, _key), _.partial(Object, null))); //on last time around we need the reomve the context for finial res return i === (col.length - 1) ? rmContext(prv) : prv; }, {})) : omitList //omitlist pull and merge ? _.forEach(omitList, (o)=> _.unset(_global, o)) && _.defaultsDeep(_val, rmContext(_global)) //default, reg merge : _.defaultsDeep(_val, rmContext(_global)); }; //-> return !globalTarget ? defaultIn(val, _globalData) : _.includes(globalTarget, key) ? defaultIn(val, _globalData) : val; },
function(cb2){ mongoose.models.User.update({_id:{$in: _.keys(group.quest.members)}}, {$inc:{'stats.hp':down, _v:1}}, {multi:true}, cb2); }
}, windows: () => WindowsDriver, mac: () => MacDriver, tizen: () => TizenDriver, }; const desiredCapabilityConstraints = { automationName: { presence: false, isString: true, inclusionCaseInsensitive: _.values(AUTOMATION_NAMES), }, platformName: { presence: true, isString: true, inclusionCaseInsensitive: _.keys(PLATFORMS_MAP), }, }; const sessionsListGuard = new AsyncLock(); const pendingDriversGuard = new AsyncLock(); class AppiumDriver extends BaseDriver { constructor (args) { super(); this.desiredCapConstraints = desiredCapabilityConstraints; // the main Appium Driver has no new command timeout this.newCommandTimeoutMs = 0;
function _doEvery(record, criteria, cb){ var boundFunc = _.bind(_checkTrue, {record: record, criteria: criteria}); async.every(_.keys(criteria), boundFunc, function(result){ return cb(result); }); }
const sessionIdsToDelete = await sessionsListGuard.acquire(AppiumDriver.name, () => _.keys(this.sessions));
function _checkTrue(key, keyCallback){ var currCriteria = this.criteria[key]; if (currCriteria instanceof Array){ if (key === '$and'){ return _doEvery(this.record, currCriteria, keyCallback); } else if (key === '$or'){ return _callOr(this.record, currCriteria, keyCallback); } else if (key === '$nor'){ return _callNor(this.record, currCriteria, keyCallback); } } else if (key === '$where'){ var contextCode = ''; var recordKeys = _.keys(this.record); for (var k = 0; k < recordKeys.length; k++){ contextCode += 'var ' + recordKeys[k] + '=' + JSON.stringify(this.record[recordKeys[k]]) + ';'; } var retValue = false; try { retValue = vm.runInNewContext(contextCode + this.criteria[key]); } catch(e){ //console.log('Error in $where clause: ' + e); } keyCallback(retValue); } else if (typeof currCriteria === 'object'){ var currCriteriaLength = _.keys(currCriteria).length; var noMatch = false; if (currCriteriaLength == 1){ var retValue = false; switch (_.keys(currCriteria)[0]){ case '$exists': var isDef = (typeof _objAccessor(this.record, key) != 'undefined'); retValue = currCriteria['$exists'] ? isDef : !isDef; break; case '$lt': retValue = (_objAccessor(this.record, key) < currCriteria['$lt']); break; case '$lte': retValue = (_objAccessor(this.record, key) <= currCriteria['$lte']); break; case '$gt': retValue = (_objAccessor(this.record, key) > currCriteria['$gt']); break; case '$gte': retValue = (_objAccessor(this.record, key) >= currCriteria['$gte']); break; case '$ne': retValue = (_objAccessor(this.record, key) != currCriteria['$ne']); break; case '$in': var toMatch = _objAccessor(this.record, key); for (var i = 0; i < currCriteria['$in'].length; i++){ if (currCriteria['$in'][i] == toMatch){ retValue = true; break; } } break; case '$nin': var toMatch = _objAccessor(this.record, key); for (var i = 0; i < currCriteria['$in'].length; i++){ if (currCriteria['$in'][i] == toMatch){ retValue = true; break; } } // reverse value since "not in" retValue = !retValue; break; default: noMatch = true; break; } if (!noMatch){ keyCallback(retValue); } } if (currCriteriaLength > 1 || noMatch){ return _doEvery(this.record, currCriteria, keyCallback); } } else{ var retValue = (_objAccessor(this.record, key) == currCriteria); keyCallback(retValue); } }
WhereBuilder.prototype.single = function single(queryObject, options) { if(!queryObject) return ''; var self = this; var queryString = ''; var addSpace = false; // Add any hasFK strategy joins to the main query _.keys(queryObject.instructions).forEach(function(attr) { var strategy = queryObject.instructions[attr].strategy.strategy; var population = queryObject.instructions[attr].instructions[0]; var parentAlias = _.find(_.values(self.schema), {tableName: population.parent}).identity; // Handle hasFK if(strategy === 1) { // Set outer join logic queryString += 'LEFT OUTER JOIN ' + utils.escapeName(population.child, self.escapeCharacter) + self.tableAs + utils.escapeName(self.prefixAlias + population.alias, self.escapeCharacter) + ' ON '; queryString += utils.escapeName(parentAlias, self.escapeCharacter) + '.' + utils.escapeName(population.parentKey, self.escapeCharacter); queryString += ' = ' + utils.escapeName(self.prefixAlias + population.alias, self.escapeCharacter) + '.' + utils.escapeName(population.childKey, self.escapeCharacter); addSpace = true; } }); if(addSpace) { queryString += ' '; } var tmpCriteria = _.cloneDeep(queryObject); delete tmpCriteria.instructions; // Ensure a sort is always set so that we get back consistent results if(!hop(queryObject, 'sort')) { var childPK; _.keys(this.schema[this.currentTable].attributes).forEach(function(attr) { var expandedAttr = self.schema[self.currentTable].attributes[attr]; if(!hop(expandedAttr, 'primaryKey')) return; childPK = expandedAttr.columnName || attr; }); queryObject.sort = {}; queryObject.sort[childPK] = -1; } // Read the queryObject and get back a query string and params // Use the tmpCriteria here because all the joins have been removed var parsedCriteria = {}; // Build up a WHERE queryString if(tmpCriteria.where) { queryString += 'WHERE '; } // Mixin the parameterized flag into options var _options = _.assign({ parameterized: this.parameterized, caseSensitive: this.caseSensitive, escapeCharacter: this.escapeCharacter, stringDelimiter: this.stringDelimiter, rownum: this.rownum }, options); this.criteriaParser = new CriteriaParser(this.currentTable, this.schema, _options); parsedCriteria = this.criteriaParser.read(tmpCriteria); queryString += parsedCriteria.query; // Remove trailing AND if it exists if(queryString.slice(-4) === 'AND ') { queryString = queryString.slice(0, -5); } // Remove trailing OR if it exists if(queryString.slice(-3) === 'OR ') { queryString = queryString.slice(0, -4); } var values; if(parsedCriteria && _.isArray(parsedCriteria.values)) { values = parsedCriteria.values; } else { values = []; } return { query: queryString, values: values }; };