_.each(matchIndices,function (matchIndex) { resultSet.push(_.clone(data[collectionName][matchIndex])); });
it.skip('201 Created', function (done) { const expectedUsername = `valid${config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : ''}`; const expectedUserId = 'a1b2c3d4e5f6'; const expectedUserPhone = '111111111'; const expectedUserCountry = 'US'; const expectedPublicRequest = {}; expectedPublicRequest[config.passThroughEndpoint.username] = expectedUsername; expectedPublicRequest[config.passThroughEndpoint.password] = '12345678'; expectedPublicRequest.phone = expectedUserPhone; expectedPublicRequest.country = expectedUserCountry; const expectedPrivateResponse = _.clone(expectedPublicRequest); delete(expectedPrivateResponse[config.passThroughEndpoint.password]); nock(`http://${config.private_host}:${config.private_port}`) .post(config.passThroughEndpoint.path, expectedPrivateResponse) .reply(201, {id: expectedUserId}); const redisKey = config.redisKeys.user_phone_verify.key.replace('{userId}', expectedUsername).replace('{phone}', `+1${expectedUserPhone}`); const pin = 'xxxx'; redisMng.insertKeyValue(`${redisKey}.pin`, pin, config.redisKeys.user_phone_verify.expireInSec, function (err) { assert.equal(err, null); redisMng.insertKeyValue(`${redisKey}.attempts`, config.userPIN.attempts, config.redisKeys.user_phone_verify.expireInSec, function (err) { assert.equal(err, null); nock(`http://${config.private_host}:${config.private_port}`) .post(config.passThroughEndpoint.path, expectedPrivateResponse) .reply(201, {id: expectedUserId}); const options = { url: `http://${config.private_host}:${config.public_port}${config.passThroughEndpoint.path}`, headers: { 'Content-Type': 'application/json; charset=utf-8', 'x-otp-pin': pin, [config.version.header]: versionHeader }, method: 'POST', body: JSON.stringify(expectedPublicRequest) }; request(options, function (err, res, rawBody) { assert.equal(err, null); assert.equal(res.statusCode, 201, rawBody); const body = JSON.parse(rawBody); assert.equal(body.expiresIn, accessTokenSettings.tokenExpirationMinutes); assert.notEqual(body.accessToken, undefined); ciphertoken.getTokenSet(accessTokenSettings, body.accessToken, function (err, accessTokenInfo) { assert.equal(err, null); assert.equal(accessTokenInfo.userId, expectedUserId); assert.notEqual(body.refreshToken, undefined); ciphertoken.getTokenSet(refreshTokenSettings, body.refreshToken, function (err, refreshTokenInfo) { assert.equal(err, null); assert.equal(refreshTokenInfo.userId, expectedUserId); dao.getFromUsername(expectedUsername, function (err, foundUser) { assert.equal(err, null); assert.equal(foundUser.platforms, undefined); return done(); }); }); }); }); }); }); });
utils = require('./../build-utils'), StatementBloq = require('./../statementBloq'); /** * Bloq name: oscillator * * Bloq type: Statement * * Description: It sets a specific servo, selectable from a * drop-down, to oscillate around a given point * with a certain amplitude and velocity. * * Return type: none */ var oscillator = _.merge(_.clone(StatementBloq, true), { name: 'oscillator', bloqClass: 'bloq-oscillator', content: [ [{ alias: 'text', value: 'bloq-oscillator-oscillate' }, { id: 'OSCILLATOR', alias: 'dynamicDropdown', options: 'oscillators' }, { alias: 'text', value: 'bloq-oscillator-around' }, {
module.exports = function(grunt) { var s3Config = grunt.file.exists(S3_CONFIG_FILE) ? grunt.file.readJSON(S3_CONFIG_FILE) : {}; var config = { clean: ["./build", "./static"], concurrent: { dev: ["nodemon:dev", "webpack:dev"], options: { logConcurrentOutput: true } }, execute: { static: { options: { cwd: "./static" }, src: ["./app/static.js"] } }, copy: { static: { files: [{ expand: true, cwd: "app/assets/", src: ["**/*"], dest: "static/" }, { expand: true, cwd: "build/", src: "client.css*", dest: "static/" }] } }, nodemon: { dev: { script: "./app/server.js", options: { ignore: ["./build/**"], ext: "js,jsx" } } }, webpack: { dev: { resolve: { extensions: ["", ".js", ".jsx"] }, entry: "./app/client.js", output: { path: "./build", filename: "client.js" }, module: { loaders: [ {test: /\.css$/, loader: "style!css"}, // Use "css-loader?minimize!less-loader" for minification {test: /\.less$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader!less-loader")}, {test: /\.jsx$/, loader: "jsx-loader"} ] }, plugins: [new ExtractTextPlugin("client.css")], stats: { colors: true }, devtool: "source-map", watch: true, keepalive: true } }, uglify: { options: { }, static: { files: { "static/client.js": ["build/client.js"] } } }, s3: { options: { accessKeyId: s3Config.key, secretAccessKey: s3Config.secret, bucket: s3Config.bucket, region: s3Config.region || "us-west-2", access: "public-read", // important for pages without .html extension mimeDefault: "text/html" }, deploy: { cwd: "static/", src: "**" } }, eslint: { target: ["Gruntfile.js", "app/**/*.js", "app/**/*.jsx"] } }; // Copy the dev webpack configuration but don't watch config.webpack.static = _.clone(config.webpack.dev); config.webpack.static.watch = false; config.webpack.static.keepalive = false; grunt.initConfig(config); grunt.loadNpmTasks("grunt-concurrent"); grunt.loadNpmTasks("grunt-contrib-clean"); grunt.loadNpmTasks("grunt-contrib-copy"); grunt.loadNpmTasks("grunt-contrib-uglify"); grunt.loadNpmTasks("grunt-nodemon"); grunt.loadNpmTasks("grunt-webpack"); grunt.loadNpmTasks("grunt-execute"); grunt.loadNpmTasks("grunt-aws"); grunt.loadNpmTasks("grunt-npm-install"); grunt.loadNpmTasks("grunt-eslint"); // Run the node server and watch for changes grunt.registerTask("default", ["clean", "npm-install", "concurrent:dev"]); // Build the static site grunt.registerTask("static", ["clean", "npm-install", "webpack:static", "copy:static", "uglify:static", "execute:static"]); // Build and deploy the static site grunt.registerTask("deploy", ["static", "s3:deploy"]); // For testing, just execute the static script grunt.registerTask("static-only", ["execute:static"]); };
} = React import _ from "lodash"; import moment from "moment"; import Button from 'apsl-react-native-button'; import {LocalNumber, LocalSelect, LocalTextbox, LocalCalendar, LocalDate} from "../form/localComponents"; var Icon = require('react-native-vector-icons/FontAwesome'); var dh = Dimensions.get('window').height, dw = Dimensions.get('window').width; var localstyles = require("../localStyles"), t = require('tcomb-form-native'), numeral = require('numeral'), formstyles = _.clone(localstyles,true); formstyles.fieldset.flexDirection = "row"; t.form.Form.i18n = { optional: '', required: ' *' // inverting the behaviour: adding a postfix to the required fields }; var Form = t.form.Form; var model = t.struct({ eventDate : t.maybe(t.Date), eventNotes : t.maybe(t.String), }); var layout = (self) => { let tmpl = (locals) => { let inputs = locals.inputs;
function findMethod(metabase, cls, method, args, isInstance, node, nodefail) { var entry = metabase.classes[cls], methods = _.clone(entry && entry.methods), // clone so we don't end up copying superclass methods into global metabase in-memory argcount = args.length; // search for super classes if (!methods[method]) { entry = metabase.classes[entry.superClass]; while(entry) { entry.methods && Object.keys(entry.methods).forEach(function(name){ if (!(name in methods)) { methods[name] = entry.methods[name]; } }); entry = metabase.classes[entry.superClass]; } } // match up arg count as a first filtering mechanism // TODO Don't we need to handle varargs too? Looks like we don't record varargs in metabase var result = _.filter(methods[method], function(m){ return m.args.length == argcount && isInstance == m.instance; }); if (!result || result.length == 0) { return undefined; } if (result && result.length == 1) { return result[0]; } // Try matching up arg types to disambiguate further var refined = _.filter(result, function(m){ for (var i = 0, j = m.args.length; i < j; i++) { if (!typeMatches(m.args[i], args[i])) { return false; } } return true; }); if (refined && refined.length == 1) { return refined[0]; } var msg = "can't disambiguate arguments for method "+method.yellow, help = ' The following method signatures are available:\n\n'.yellow, guide = ''; result.forEach(function(m) { guide += '\tHyperloop.method('+util.sanitizeSymbolName(cls).toLowerCase()+', '; guide += '\''+method+'('; var argt = []; m.args.forEach(function(arg) { argt.push(arg.type); }); guide += argt.join(','); guide += ')\')\n'; }); help += guide.red.bold; nodefail(node, msg, help); }
/** * called to define a overloaded method */ function defineMethod(options,state,arch,node,dict,fail) { var varname = dict.method[0].value, callstr = dict.method[1].value, start = node.start.pos, distance = -Number.MAX_VALUE, match = callstr.match(/(.+)(\()(.+)(\))/), vardef, isConstructor = false, classname, entry; if (!match) { return fail(node,callstr+' of '+classname+' is not a valid method call'); } // look up the type for the definition Object.keys(state.node_map).forEach(function(key) { var def = JSON.parse(key); // check the distance from the definition, pick up negative nearest one if (def.type === 'name' && def.value === varname) { var d = def.endpos - start; if (d > distance) { distance = d; vardef = state.node_map[key]; } } }); if (vardef && (vardef.returnType || vardef['class'])) { classname = vardef.returnType || vardef['class']; } else { entry = state.metabase.classes[varname]; if (entry) { classname = varname; } else { throw new Error('failed to lookup definition of '+varname); } } // look up matching method var method = match[1], methodargs = match[3].split(','), methods = findMethods(state.metabase, classname, method); if (!methods) { return fail(node,"couldn't find method:",method.yellow,"for class:",classname.yellow); } isConstructor = (method == '<init>' || method == '<clinit>'); var signature, index; for (var i = 0; i < methods.length; i++) { var m = methods[i]; if (m.args.length == 0) continue; for (var j = 0; j < m.args.length; j++) { if (m.args[j].type != methodargs[j]) break; } // if all matched, this is the one if (j == m.args.length) { signature = library.mangleJavaSignature(m.signature); index = i; break; } } if (!signature) { return fail(node,"couldn't find method: "+method.yellow+" for class: "+classname.yellow); } var methodname = method, fn, methodObj = state.metabase.classes[classname].methods[methodname][index]; if (!methodObj) { return fail(node,"couldn't find method: "+methodname.yellow+" for class: "+classname.yellow); } if (isConstructor) { fn = jsgen.generateNewConstructorName(classname, "constructor")+signature; } else { fn = jsgen.generateMethodName(classname, methodname)+signature; } var key = state.obfuscate ? jsgen.obfuscate(fn) : fn, node_start = JSON.stringify(node.start); if (isConstructor) { var argcount = callstr.split(',').length+1; // register method symbol state.symbols[key] = {type:'constructor',metatype:'constructor',method:methodObj,name:method,symbolname:fn,class:classname,location:node.start,argcount:argcount,selector:callstr,returnType:classname}; state.node_map[node_start] = state.symbols[key]; // save constructor information to make it easy to search later on state.constructors = state.constructors || {}; state.constructors[classname] = state.constructors[classname] || {}; state.constructors[classname][key] = state.symbols[key]; } else { state.symbols[key] = {type:'method',metatype:'instance',symbolname:fn,instance:varname,returnType:methodObj.returnType, class:classname,name:methodname+signature,location:node.start,argcount:methodargs.length, method:_.clone(methodObj)}; // we need to place the instance name as the first parameter in the argument list if (library.isMethodInstance(options, state.metabase, state, methodObj)) { dict.call.unshift({type:'variable',value:varname}); } } // return the name and args to use return { start: JSON.parse(node_start), args: dict.call, name: key }; }
render() { const ac = this.state.artistCredit; const names = ac.names; let entity = _.clone(this.props.entity); entity.artistCredit = names.filter(n => hasArtist(n)).toJS(); // The single-artist lookup changes the credit boxes in the doc bubble, // and the credit boxes change the single-artist lookup. const complex = isComplexArtistCredit(ac); let singleArtistSelection = {name: ''}; let singleArtistIsEditable = true; if (complex || names.size > 1) { singleArtistSelection.name = reduceArtistCredit(ac); singleArtistIsEditable = false; } else { const firstName = names.get(0); if (firstName) { if (hasArtist(firstName)) { singleArtistSelection = firstName.artist; } else { singleArtistSelection.name = firstName.name; } } } return ( <frag> <table className="artist-credit-editor"> <tbody> <tr> <td> <Autocomplete currentSelection={singleArtistSelection} disabled={!singleArtistIsEditable} entity="artist" inputID={this.props.forLabel} isLookupPerformed={isCompleteArtistCredit(ac)} onChange={artist => { if (singleArtistIsEditable) { this.setState({ artistCredit: new ArtistCredit({ names: Immutable.List([ new ArtistCreditName({ artist, name: artist.name, joinPhrase: '', }) ]) }) }); } }} showStatus={false} /> </td> <td className="open-ac-cell"> <button className="open-ac" ref="button" type="button" onClick={this.toggleBubble}> {l('Edit')} </button> </td> </tr> </tbody> </table> <If condition={this.props.hiddenInputs}> <For each="data" of={this.getHiddenInputs()}> <input type="hidden" name={data.name} value={nonEmpty(data.value) ? data.value : ''} /> </For> </If> </frag> ); }
model: function (req, res) { var name = req.params.modelName, modelConfig = admin.models[name]; if (!modelConfig) throw new Error("No model named" + req.params.modelName); if (modelConfig.is_single) { return res.redirect(req.path.split('/model/')[0]); } // query var query = _.clone(req.query); var start = Number(query.start) || 0; delete query.start; //noinspection JSUnresolvedVariable var isDialog = Boolean(query._dialog); //noinspection JSUnresolvedVariable delete query._dialog; var count = Number(query.count) || DEFAULT_QUERY_COUNT_LIMIT; delete query.count; var sort = query.order_by; delete query.order_by; /** @namespace query.saved */ //var saved = query.saved; delete query.saved; /** @namespace query._search */ var search_value = query._search || ''; delete query._search; var filters = parseFilters(modelConfig, query, search_value); var sortable = typeof(modelConfig.options.sortable) == 'string' && req.admin_user.hasPermissions(name, 'order'); if (sortable) { start = 0; count = DEFAULT_QUERY_COUNT_LIMIT_SORTABLE; } return admin.modelCounts(name, filters, function (err, total_count) { if (err) throw err; return admin.listModelDocuments(name, start, count, filters, sort, function (err, documents) { if (err) throw err; var makeLink = function (key, value) { var query = _.clone(req.query); if (key) { query[key] = value; } return '?' + _(query).map(function (v, k) { if (!v || !k) return null; return encodeURIComponent(k) + '=' + encodeURIComponent(v); }).compact().join('&'); }; var orderLink = function (key) { if (req.query.order_by == key) { key = '-' + key; } return makeLink('order_by', key); }; //noinspection JSUnresolvedVariable var schema = modelConfig.model.schema.tree; var fieldLabel = function (field) { if (!field || !field.length) return ''; return schema[field] && schema[field].label ? schema[field].label : field[0].toUpperCase() + field.slice(1).replace(/_/g, ' '); }; return res.render('model.jade', { adminTitle: admin.options.title, pageTitle: 'Admin - ' + modelConfig.model.label, rootPath: admin.options.root, model_name: name, modelConfig: modelConfig, list_fields: modelConfig.options.list, documents: documents, total_count: total_count, start: start, count: count, makeLink: makeLink, orderLink: orderLink, fieldLabel: fieldLabel, filters: modelConfig.filters || [], current_filters: req.query, search: modelConfig.options.search, search_value: search_value, cloudinary: require('cloudinary'), actions: modelConfig.options.actions, editable: req.admin_user.hasPermissions(name, 'update'), sortable: sortable, cloneable: modelConfig.options.cloneable !== false && req.admin_user.hasPermissions(name, 'create'), creatable: modelConfig.options.creatable !== false && req.admin_user.hasPermissions(name, 'create'), isDialog: isDialog }); }); }); },
QueryInterface.prototype.createTable = function(tableName, attributes, options, model) { var keys = Object.keys(attributes) , keyLen = keys.length , self = this , sql = '' , i = 0; options = _.clone(options) || {}; attributes = Utils._.mapValues(attributes, function(attribute) { if (!Utils._.isPlainObject(attribute)) { attribute = { type: attribute, allowNull: true }; } attribute = self.sequelize.normalizeAttribute(attribute); return attribute; }); // Postgres requires a special SQL command for enums if (self.sequelize.options.dialect === 'postgres') { var promises = []; for (i = 0; i < keyLen; i++) { if (attributes[keys[i]].type instanceof DataTypes.ENUM) { sql = self.QueryGenerator.pgListEnums(tableName, attributes[keys[i]].field || keys[i], options); promises.push(self.sequelize.query( sql, _.assign({}, options, { plain: true, raw: true, type: QueryTypes.SELECT }) )); } } return Promise.all(promises).then(function(results) { var promises = [] , enumIdx = 0; for (i = 0; i < keyLen; i++) { if (attributes[keys[i]].type instanceof DataTypes.ENUM) { // If the enum type doesn't exist then create it if (!results[enumIdx]) { sql = self.QueryGenerator.pgEnum(tableName, attributes[keys[i]].field || keys[i], attributes[keys[i]], options); promises.push(self.sequelize.query( sql, _.assign({}, options, { raw: true }) )); } else if (!!results[enumIdx] && !!model) { var enumVals = self.QueryGenerator.fromArray(results[enumIdx].enum_value) , vals = model.rawAttributes[keys[i]].values; vals.forEach(function(value, idx) { // reset out after/before options since it's for every enum value var valueOptions = _.clone(options); valueOptions.before = null; valueOptions.after = null; if (enumVals.indexOf(value) === -1) { if (!!vals[idx + 1]) { valueOptions.before = vals[idx + 1]; } else if (!!vals[idx - 1]) { valueOptions.after = vals[idx - 1]; } valueOptions.supportsSearchPath = false; promises.push(self.sequelize.query(self.QueryGenerator.pgEnumAdd(tableName, keys[i], value, valueOptions), valueOptions)); } }); enumIdx++; } } } if (!tableName.schema && (options.schema || (!!model && model.$schema))) { tableName = self.QueryGenerator.addSchema({ tableName: tableName, $schema: (!!model && model.$schema) || options.schema }); } attributes = self.QueryGenerator.attributesToSQL(attributes, { context: 'createTable' }); sql = self.QueryGenerator.createTableQuery(tableName, attributes, options); return Promise.all(promises).then(function() { return self.sequelize.query(sql, options); }); }); } else { if (!tableName.schema && (options.schema || (!!model && model.$schema))) { tableName = self.QueryGenerator.addSchema({ tableName: tableName, $schema: (!!model && model.$schema) || options.schema }); } attributes = self.QueryGenerator.attributesToSQL(attributes, { context: 'createTable' }); sql = self.QueryGenerator.createTableQuery(tableName, attributes, options); return self.sequelize.query(sql, options); } };
it('should not modify the options passed', function () { var options = {width: 10, height: 20}, optionsCopy = _.clone(options) image.crop(options) options.should.eql(optionsCopy) })
QueryInterface.prototype.bulkInsert = function(tableName, records, options, attributes) { options = _.clone(options) || {}; options.type = QueryTypes.INSERT; var sql = this.QueryGenerator.bulkInsertQuery(tableName, records, options, attributes); return this.sequelize.query(sql, options); };
startCasper: function(queue, callback) { console.log("Starting CasperJS..."); var processQueue = async.queue(function(data, next) { // If the dummy boolean is hit then we're all done processing! if (data === true) { next(); callback(); } else { // Otherwise we need to keep processing the data this.processData(data, function(err) { if (err) { console.log("ERROR Processing Data:", JSON.stringify(err), JSON.stringify(data)); } next(); }); } }.bind(this), 1); var options = _.clone(this.options); options.dirname = __dirname; options.queue = queue; var settings = _.extend(this.pageSettings, this.options.pageSettings, this.scraper.pageSettings); var spooky = new Spooky({ child: { transport: "http" }, exec: { file: __dirname + "/src/casper-bootstrap.js", options: options }, casper: { logLevel: options.debug ? "debug" : "error", verbose: true, pageSettings: settings, exitOnError: false } }); spooky.on("error", function(e) { console.error(e); }); spooky.on("console", function(line) { console.log(line); }); spooky.on("log", function(log) { if (options.debug) { console.log(log.message.replace(/ \- .*/, "")); } }); spooky.on("action", function(data) { processQueue.push(data); }); spooky.on("done", function() { // Push on a dummy boolean to know when we've hit the // end of the queue processQueue.push(true); }); },
], function (vals) { let rows = vals[0]; const min = vals[1]; $el.empty(); if (!_.isArray(rows)) { rows = []; } if (isFinite(min) && rows.length < min) { // clone the rows so that we can add elements to it without upsetting the original rows = _.clone(rows); } rows.forEach(function (row) { if (row.length) { const rowScope = row[0].scope; const $tr = $(document.createElement('tr')).appendTo($el); if (rowScope && rowScope.mouseenterRow !== undefined && typeof rowScope.mouseenterRow === 'function') { // Add mousenter and mouseleave events to the row $tr.attr({ 'ng-mouseenter': 'mouseenterRow($event)' }); $tr.attr({ 'ng-mouseleave': 'mouseleaveRow($event)' }); $compile($tr)(rowScope); } row.forEach(function (cell) { addCell($tr, cell); }); if (rowScope && rowScope.expandable && rowScope.expandElement && // the tag name of the element which contains the expanded row's contents row.join('') !== '') { // empty rows are passed in as an array of empty cols, ie ['','',''] if (rowScope.open === undefined) { rowScope.open = false; } if (rowScope.rowInitialised === undefined) { rowScope.rowInitialised = false; } rowScope.toggleRow = function () { this.open = !this.open; if (this.initRow && this.rowInitialised === false) { this.rowInitialised = true; this.initRow(); } }; const $trExpand = $(document.createElement('tr')).appendTo($el); $trExpand.attr('ng-show', 'open'); $trExpand.addClass('row-expand'); const $td = $(document.createElement('td')).appendTo($trExpand); $td.attr('colspan', row.length); const expEl = rowScope.expandElement; const $exp = $(document.createElement(expEl)).appendTo($td); // if expand element already exits and has child elements, // copy them to the new expand element if (rowScope.$expandElement && rowScope.$expandElement.children().length) { $exp.append(rowScope.$expandElement.children()[0]); } $compile($trExpand)(rowScope); rowScope.$expandElement = $exp; } } }); });
CoffeeEngine.configure = function (opts) { options = _.clone(opts); };
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 ? true : false, model: hasOwnProperty(parentKey, 'model') ? true : false, collection: hasOwnProperty(parentKey, 'collection') ? true : false }; // 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 ? true : false, 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 scanSegment (segment) { var deferred = Q.defer(); var scanOneReq = _.clone(scanReq); if(scanOneReq.TotalSegments) { scanOneReq.Segment = segment; } if(options.ExclusiveStartKey) { scanOneReq.ExclusiveStartKey = options.ExclusiveStartKey[segment]; } debug('adding scan segement', scanOneReq); var models = {}, totalCount = 0, scannedCount = 0, timesScanned = 0, lastKey; if (!options.all) { options.all = {'delay': 0, 'max': 1}; } scanOne(); function scanOne() { debug('scan request', scanOneReq); Model.$__.base.ddb().scan(scanOneReq, function(err, data) { if(err) { debug('Error returned by scan', err); return deferred.reject(err); } debug('scan response', data); if(!Object.keys(data).length) { return deferred.resolve(); } try { if (options.count) { return deferred.resolve(data.Count); } if (options.counts) { var counts = { count: data.Count, scannedCount: data.ScannedCount }; return deferred.resolve(counts); } if (data.Items !== undefined) { if (!models.length || models.length === 0) { models = data.Items.map(toModel); } else { models = models.concat(data.Items.map(toModel)); } if(options.one) { if (!models || models.length === 0) { return deferred.resolve(); } return deferred.resolve(models[0]); } lastKey = data.LastEvaluatedKey; } totalCount += data.Count; scannedCount += data.ScannedCount; timesScanned++; if ((options.all.max === 0 || timesScanned < options.all.max) && lastKey) { // scan.all need to scan again scanOneReq.ExclusiveStartKey = lastKey; setTimeout(scanOne, options.all.delay); } else { // completed scan returning models models.lastKey = lastKey; models.count = totalCount; models.scannedCount = scannedCount; models.timesScanned = timesScanned; deferred.resolve(models); } } catch (err) { deferred.reject(err); } }); } return deferred.promise; }
options.sizes.forEach(function(s) { // consts var DEFAULT_SIZE_OPTIONS = { quality: 1 }; // variable var sizeOptions = _.clone(_.extend(DEFAULT_SIZE_OPTIONS, s)); var sizingMethod = 'resize'; if (!isValidSize(s.width, s.height)) { return grunt.fail.fatal('Size is invalid (' + s.width + ', ' + s.height + ')'); } // use crop if both width and height are specified. if (s.width && s.height) { sizingMethod = 'crop'; } // create a name for our image based on name, width, height sizeOptions.name = getName({ name: s.name, width: s.width, height: s.height }, options); // create an output name with prefix, suffix sizeOptions.outputName = addPrefixSuffix(sizeOptions.name, options.separator, s.suffix); tally[sizeOptions.name] = 0; if (task.files.length === 0) { grunt.fail.warn('Unable to compile; no valid source files were found.'); } else { // Iterate over all specified file groups. task.files.forEach(function(f) { var extName = '', srcPath = '', baseName = '', dirName = '', dstPath = '', imageOptions = {}; checkForValidTarget(f); extName = path.extname(f.dest); srcPath = f.src[0]; baseName = path.basename(srcPath, extName); // filename without extension if (f.custom_dest) { sizeOptions.path = f.src[0].replace(new RegExp(f.orig.cwd), "").replace(new RegExp(path.basename(srcPath)+"$"), ""); grunt.template.addDelimiters('size', '{%', '%}'); dirName = grunt.template.process(f.custom_dest, { delimiters: 'size', data: sizeOptions }); dstPath = path.join(dirName, baseName + extName); } else { dirName = path.dirname(f.dest); dstPath = path.join(dirName, baseName + sizeOptions.outputName + extName); } // more than 1 source. if (f.src.length > 1) { return grunt.fail.warn('Unable to resize more than one image in compact or files object format.\n'+ 'For multiple files please use the files array format.\nSee http://gruntjs.com/configuring-tasks'); } checkDirectoryExists(path.join(dirName)); imageOptions = { srcPath: srcPath, dstPath: dstPath, format: extName.replace('.', '') }; // remove pixels from the value so Imagemagick doesn't complain sizeOptions = removeCharsFromObjectValue(sizeOptions, ['width', 'height'], 'px'); // combine image options with size options. imageOptions = _.extend(imageOptions, sizeOptions); series.push(function(callback) { im[sizingMethod](imageOptions, function(error, stdout, stderr) { if (error) { grunt.fail.warn(error.message); } else { grunt.verbose.ok('Responsive Image: ' + srcPath + ' now '+ dstPath); tally[sizeOptions.name]++; } return callback(); }); }); }); series.push(function(callback) { outputResult(tally[sizeOptions.name], sizeOptions.name); return callback(); }); } });
function registerCustomClassForMetabase(options, state, metabase, classname, dict) { if (metabase.classes[classname]) { log.warn(classname+' is already defined in metabase. Skip.'); return; } function valueMapper(a) { return a.value; } var c = metabase.classes[classname] = {}; c.package = dict.package && dict.package[0].value || options.appid || ''; c.superClass = dict.extends && dict.extends[0].value || 'java.lang.Object'; c.attributes = dict.attributes ? _.clone(dict.attributes).map(valueMapper) : ['public']; c.metatype = c.attributes.indexOf('interface') < 0 ? 'class' : 'interface'; c.interfaces = dict.implements ? dict.implements.map(valueMapper) : []; c.annotations = dict.annotations ? _.clone(dict.annotations).map(valueMapper) : []; c.methods = {}; c.properties = {}; // constructor if (dict.init) { // TODO setup constructor args and signature } else { dict.method.push({type:'value',name:'<init>', signature:'()V'}); // default constructor } // methods dict.method && dict.method.forEach(function(m) { m = m.value ? m.value : m; var name = m.name && m.name.value || m.name; var entries = c.methods[name] || []; var entry = {}; entry.exceptions = []; entry.args = m.arguments ? _.clone(m.arguments.value).map(valueMapper) : []; entry.attributes = m.attributes ? _.clone(m.attributes.value).map(valueMapper) : []; entry.annotations = m.annotations ? _.clone(m.annotations.value).map(valueMapper) : []; entry.instance = m.attributes ? m.attributes.value.indexOf('static') < 0 : true; entry.returnType = m.returns && m.returns.value || 'void'; entry.hasAction = !!m.action; entry.action = m.action && m.action.value; entry.name = name; entry.shouldCallSuper = m.shouldCallSuper && m.shouldCallSuper.value || false; entry.args = entry.args.map(function(arg){ return { type: arg.type.value, name: arg.name && arg.name.value }; }); m.signature = m.signature && m.signature.value || library.getJavaMethodSignature(options,metabase,entry); entry.signature = m.signature; entries.push(entry); c.methods[name] = entries; }); // properties dict.property && dict.property.forEach(function(item) { var entry = {}; item = item.value; entry.name = item.name.value; entry.value = item.value.value; entry.attributes = item.attributes ? _.clone(item.attributes.value.map(valueMapper)) : []; entry.annotations = item.annotations ? _.clone(item.annotations.value.map(valueMapper)) : []; if (item.type.value == 'enum') { entry.type = classname+'$'+item.name.value; entry.metatype = 'enum'; registerCustomEnumForMetabase(options,state,metabase,classname,dict,entry); } else { // see if property type is innner class if (_.find(dict.property, function(p) {return p.value.name.value==item.type.value;})) { entry.type = classname+'$'+item.type.value; entry.innertype = item.type.value; } else { entry.type = item.type.value; } entry.metatype = item.attributes.value.indexOf('final') < 0 ? 'field' : 'constant'; } c.properties[item.name.value] = entry; }); state.custom_classes = state.custom_classes || {}; state.custom_classes[classname] = c; }
CocoEngine.prototype.evaluate = function (/*context, locals*/) { return coco.compile(this.data, _.clone(options)); };
seed: function(data, options, callback) { if(_.isFunction(options)) { // Set the correct callback function callback = options; options = {}; } // Create a deferred object for the promise var def = Q.defer(); // If no callback is provided, use a noop function callback = callback || function() {}; // Clear earlier results and options _this.result = {}; _this.options = {}; _this.sandbox = vm.createContext(); // Defaulting the options _this.options = _.extend(_.clone(DEFAULT_OPTIONS), options); switch(mongoose.connection.readyState) { case 0: //disconnected done("db not open"); break; case 1: //connected ready(); break; case 2: //connecting mongoose.connection.on('connected', function() { ready(); }); break; case 3: //disconnecting done("db disconnecting"); break; default: //any other state done("unknown db state"); break; } function ready() { if(_this.options.dropCollections === true && _this.options.dropDatabase === true) { // Only one of the two flags can be turned on. If both are true, this means the // user set the dropCollections itself and this should have higher priority then // the default values. _this.options.dropDatabase = false; } if(_this.options.dropDatabase === true) { // Make sure to drop the database first mongoose.connection.db.dropDatabase(function(err) { if(err) { // Stop seeding if an error occurred return done(err); } // Start seeding when the database is dropped _this._seed(_.cloneDeep(data), done); }); } else { // Do not drop the entire database, start seeding _this._seed(_.cloneDeep(data), done); } } /** * This method will be invoked when the seeding is completed or when something * went wrong. This method will then call the callback and rejects or resolves * the promise object. This way, users of the library can use both. * * @param {*} err [description] * @param {Object} result [description] */ function done(err, result) { if(err) { def.reject(err); callback(err); return; } def.resolve(result); callback(undefined, result); } // Return the promise return def.promise; }
extend: function(obj) { return _.extend(_.clone(SagaHandler.prototype), obj); }
export default function file(state = initialState, action = {}) { switch (action.type) { // 上傳檔案 => 新增 case types.FILE_LIST_ADD: let fileData = action.data; fileData.style = { itemStyle: itemStyle, nameStyle: nameStyle }; fileData.fid = new Date().getTime(); return objectAssign({}, state, {data: [fileData, ...state.data]}); // 刪除檔案 case types.FILE_LIST_DEL: let fidsDelete = action.data; let newDelData = state.data.filter((data) => { if(fidsDelete.indexOf(data.fid) === -1) { return data; } }); return objectAssign({}, state, { data: newDelData }); // 右鍵選單呈現, 消失 case types.FILE_CONTEXT_MENU_TOGGLE: let contextMenuToggle = _.clone(state.contextMenu); let data = { file: { fids: [], name: null, dataUrl: null}, style: { show: false, top: 0, left: 0 } }; // 選單呈現 if(action.data.style.show) { data.style.show = true; data.style.top = action.data.style.top; data.style.left = action.data.style.left; data.file.fids = action.data.file.fids; data.file.name = action.data.file.name; data.file.dataUrl = action.data.file.dataUrl; } return objectAssign({}, state, { contextMenu: data }); // 選擇檔案背景換色 case types.FILE_LIST_ITEM_SELECT: let fids = action.data; let itemSelected = []; let newData = state.data.map((data) => { if(fids.indexOf(data.fid) !== -1) { itemSelected.push(data.fid); data.style = { itemStyle: itemSelectedStyle, nameStyle: nameSelectedStyle }; } else { data.style = { itemStyle: itemStyle, nameStyle: nameStyle }; } return data; }); return objectAssign({}, state, { data: newData, itemSelected: itemSelected }); // 選擇檔案背景重設 case types.FILE_LIST_ITEM_SELECT_RESET: let resetData = state.data.map((data) => { data.style = { itemStyle: itemStyle, nameStyle: nameStyle }; return data; }); return objectAssign({}, state, { data: resetData, itemSelected: [] }); default: return state; } }
//Splice duplicate entries from input array. //Add source attribution to matched entries. function removeDuplicates(username, match, newRecord, baseRecord, recordID) { var newCloneRecord = _.clone(newRecord); var duplicateArray = []; var newMatch = {}; _.map(match, function (value, matchKey) { if (_.isArray(value)) { duplicateArray = _.where(value, { dest: 'dest', match: 'duplicate' }); var duplicateNewIndexArray = _.uniq(_.pluck(duplicateArray, 'src_id')); var duplicateBaseIndexArray = _.uniq(_.pluck(duplicateArray, 'dest_id')); if (matchKey === 'social_history') { //console.log(match); //console.log(newRecord.social_history[0]); //console.log(baseRecord.social_history[4]); } var attributionRecord = _.filter(baseRecord[matchKey], function (object, objectIndex) { if (_.contains(duplicateBaseIndexArray, objectIndex.toString())) { return true; } else { return false; } }); //Update Source attribution. async.each(attributionRecord, function (attribution, callback) { record.duplicateEntry(matchKey, username, attribution._id, recordID, function (err) { if (err) { callback(err); } else { callback(null); } }); }, function (err) { if (err) { console.log(err); //callback(err); } else { //console.log("updating source attribution - success"); //callback(); } }); //Remove Duplicates from Entry List. var returnRecord = _.filter(newCloneRecord[matchKey], function (object, objectIndex) { if (_.contains(duplicateNewIndexArray, objectIndex.toString())) { return false; } else { return true; } }); //Remove Duplicates from Match List. //use duplicate new index array to go through matches, and remove. var returnMatch = _.filter(match[matchKey], function (object, objectInex) { if (_.contains(duplicateNewIndexArray, object.src_id)) { return false; } else { return true; } }); //console.log(returnMatch); //console.log(returnRecord); newCloneRecord[matchKey] = returnRecord; if (returnMatch === undefined) { returnMatch = []; } if (returnRecord === undefined) { returnRecord = []; } newMatch[matchKey] = returnMatch; } else { if (value.match === 'duplicate' && matchKey === 'demographics') { var attributionRecord = baseRecord[matchKey]; async.each(attributionRecord, function (attribution, callback) { record .duplicateEntry(matchKey, username, attribution._id, recordID, function (err) { if (err) { callback(err); } else { callback(null); } }); }, function (err) { if (err) { //callback(err); console.log("err: " + err); } else { //callback(); } }); delete newCloneRecord[matchKey]; //delete newMatch[matchKey]; } else if (matchKey === 'demographics') { newMatch[matchKey] = value; } } }); _.map(newCloneRecord, function (value, field) { if (_.isArray(value)) { if (value.length === 0) { delete newCloneRecord[field]; } } }); //console.log(match); //console.log(JSON.stringify(newMatch, null, 10)); //This area can equal undefined on new_record entries for some reason. var returnObject = { new_record: newCloneRecord, new_match: newMatch }; return returnObject; }
}, function (err, sfToken) { expectedPublicRequest.sf = sfToken; const expectedPrivateResponse = _.clone(expectedPublicRequest); delete(expectedPrivateResponse[config.passThroughEndpoint.password]); nock(`http://${config.private_host}:${config.private_port}`) .post(config.passThroughEndpoint.path, expectedPrivateResponse) .reply(203, {id: expectedUserId}); const redisKey = config.redisKeys.user_phone_verify.key.replace('{userId}', expectedUsername).replace('{phone}', `+1${expectedUserPhone}`); const pin = 'xxxx'; redisMng.insertKeyValue(`${redisKey}.pin`, pin, config.redisKeys.user_phone_verify.expireInSec, function (err) { assert.equal(err, null); redisMng.insertKeyValue(`${redisKey}.attempts`, config.userPIN.attempts, config.redisKeys.user_phone_verify.expireInSec, function (err) { assert.equal(err, null); const options = { url: `http://${config.private_host}:${config.public_port}${config.passThroughEndpoint.path}`, headers: { 'Content-Type': 'application/json; charset=utf-8', 'x-otp-pin': pin, [config.version.header]: versionHeader }, method: 'POST', body: JSON.stringify(expectedPublicRequest) }; nock(notificationsServiceURL) .post('/notification/email') .reply(204); request(options, function (err, res, rawBody) { assert.equal(err, null); assert.equal(res.statusCode, 201); const body = JSON.parse(rawBody); assert.equal(body.expiresIn, accessTokenSettings.tokenExpirationMinutes); assert.notEqual(body.accessToken, undefined); ciphertoken.getTokenSet(accessTokenSettings, body.accessToken, function (err, accessTokenInfo) { assert.equal(err, null); assert.equal(accessTokenInfo.userId, expectedUserId); assert.notEqual(body.refreshToken, undefined); ciphertoken.getTokenSet(refreshTokenSettings, body.refreshToken, function (err, refreshTokenInfo) { assert.equal(err, null); assert.equal(refreshTokenInfo.userId, expectedUserId); dao.getFromUsername(expectedUsername, function (err, foundUser) { assert.equal(err, null); assert.notEqual(foundUser.platforms, undefined); assert.equal(foundUser.platforms.length, 1); assert.equal(foundUser.platforms[0].platform, 'sf'); assert.equal(foundUser.platforms[0].accessToken, 'acc'); assert.equal(foundUser.platforms[0].refreshToken, 'ref'); assert.notEqual(foundUser.platforms[0].expiry, undefined); return done(); }); }); }); }); }); }); });
playExperienceScenario: function (scenarioId) { var self = this, secondsChrono = 0, progressChrono = 0, scenario = null; if (this.$mobileNotification) { this.$mobileNotification.removeClass('action'); } if (scenarioId > 4) { if (this.musicExperience) { this.musicExperience.stop(); this.musicExperience = null; } } scenario = _.clone(_.first(this.getObjects(this.scenariosExperience, 'id', scenarioId))); // play video if (scenario.loop) { this.$video.prop('loop', true); _.delay(function () { self.sendQuestionToUser(scenario.question); }, scenario.delay * 1000); } else { this.$video.prop('loop', false); this.$video.on('ended', function () { self.sendQuestionToUser(scenario.question); self.$video.off(); }); } this.$videoSource.attr('src', '../' + scenario.video); this.$video.load(); // alzheimer steps timer var alzheimerSteps = function () { _.delay(function () { secondsChrono++; var newStep = _.first(scenario.steps); if (secondsChrono >= newStep.time) { app.Config.currentStep = newStep.step; var step = _.first(self.getObjects(self.stepsExpererience, 'id', app.Config.currentStep)); self.socket.emit('stepUpdated', step); scenario.steps = _.rest(scenario.steps); self.updateSteps(step); } if (scenario.steps.length > 0) { alzheimerSteps(); } }, 1000); }; alzheimerSteps(); // progressbar var progressbar = function () { _.delay(function () { progressChrono++; var newProgress = _.first(scenario.progress); if (progressChrono >= newProgress.time) { self.$timelineLineProgress.eq(app.Config.currentStep - 1).css('width', (9.2 * newProgress.value) / 100 + 'vw'); scenario.progress = _.rest(scenario.progress); } if (scenario.progress.length > 0) { progressbar(); } }, 1000); }; if (scenario.progress) { progressbar(); } },
it.skip('201 Created (Verify email)', function (done) { const expectedUsername = `valid${config.allowedDomains && config.allowedDomains[0] ? config.allowedDomains[0].replace('*', '') : ''}`; const expectedUserId = 'a1b2c3d4e5f6'; const expectedUserPhone = '111111111'; const expectedUserCountry = 'US'; const expectedPublicRequest = {}; expectedPublicRequest[config.passThroughEndpoint.username] = expectedUsername; expectedPublicRequest[config.passThroughEndpoint.password] = '12345678'; expectedPublicRequest.phone = expectedUserPhone; expectedPublicRequest.country = expectedUserCountry; const expectedPrivateResponse = _.clone(expectedPublicRequest); delete(expectedPrivateResponse[config.passThroughEndpoint.password]); nock(`http://${config.private_host}:${config.private_port}`) .post(config.passThroughEndpoint.path, expectedPrivateResponse) .times(2) .reply(201, {id: expectedUserId}); nock(notificationsServiceURL) .post('/notification/email') .reply(204); const redisKey = config.redisKeys.user_phone_verify.key.replace('{userId}', expectedUsername).replace('{phone}', `+1${expectedUserPhone}`); const pin = 'xxxx'; redisMng.insertKeyValue(`${redisKey}.pin`, pin, config.redisKeys.user_phone_verify.expireInSec, function (err) { assert.equal(err, null); redisMng.insertKeyValue(`${redisKey}.attempts`, config.userPIN.attempts, config.redisKeys.user_phone_verify.expireInSec, function (err) { assert.equal(err, null); const options = { url: `http://${config.private_host}:${config.public_port}${config.passThroughEndpoint.path}`, headers: { 'Content-Type': 'application/json; charset=utf-8', 'x-otp-pin': pin, [config.version.header]: versionHeader }, method: 'POST', body: JSON.stringify(expectedPublicRequest) }; request(options, function (err, res, rawBody) { assert.equal(err, null); assert.equal(res.statusCode, 200, rawBody); const body = JSON.parse(rawBody); assert.deepEqual(body, {des: expectedUsername}, body); //Check the redis transactionId for the user const redisKey = config.redisKeys.direct_login_transaction.key.replace('{username}', expectedUsername); redisMng.getKeyValue(redisKey, function (err, transactionId) { assert.equal(err, null); assert.notEqual(transactionId, null); assert.equal(transactionId.length, 24); return done(); }); }); }); }); });
beforeEach(function () { this.fixture = _.clone(fixtures.password); this.rl = new ReadlineStub(); });
Instance.prototype.set = function(key, value, options) { // testhint options:none var values , originalValue , keys , i , length; if (typeof key === 'object' && key !== null) { values = key; options = value || {}; if (options.reset) { this.dataValues = {}; } // If raw, and we're not dealing with includes or special attributes, just set it straight on the dataValues object if (options.raw && !(this.$options && this.$options.include) && !(options && options.attributes) && !this.Model._hasBooleanAttributes && !this.Model._hasDateAttributes) { if (Object.keys(this.dataValues).length) { this.dataValues = _.extend(this.dataValues, values); } else { this.dataValues = values; } // If raw, .changed() shouldn't be true this._previousDataValues = _.clone(this.dataValues); } else { // Loop and call set if (options.attributes) { keys = options.attributes; if (this.Model._hasVirtualAttributes) { keys = keys.concat(this.Model._virtualAttributes); } if (this.$options.includeNames) { keys = keys.concat(this.$options.includeNames); } for (i = 0, length = keys.length; i < length; i++) { if (values[keys[i]] !== undefined) { this.set(keys[i], values[keys[i]], options); } } } else { for (key in values) { this.set(key, values[key], options); } } if (options.raw) { // If raw, .changed() shouldn't be true this._previousDataValues = _.clone(this.dataValues); } } } else { if (!options) options = {}; if (!options.raw) { originalValue = this.dataValues[key]; } // If not raw, and there's a customer setter if (!options.raw && this._customSetters[key]) { this._customSetters[key].call(this, value, key); } else { // Check if we have included models, and if this key matches the include model names/aliases if (this.$options && this.$options.include && this.$options.includeNames.indexOf(key) !== -1) { // Pass it on to the include handler this._setInclude(key, value, options); return this; } else { // Bunch of stuff we won't do when its raw if (!options.raw) { // If attribute is not in model definition, return if (!this._isAttribute(key)) { if (key.indexOf('.') > -1 && this.Model._isJsonAttribute(key.split('.')[0])) { var previousDottieValue = Dottie.get(this.dataValues, key); if (!_.isEqual(previousDottieValue, value)) { Dottie.set(this.dataValues, key, value); this.changed(key.split('.')[0], true); } } return this; } // If attempting to set primary key and primary key is already defined, return if (this.Model._hasPrimaryKeys && originalValue && this.Model._isPrimaryKey(key)) { return this; } // If attempting to set read only attributes, return if (!this.isNewRecord && this.Model._hasReadOnlyAttributes && this.Model._isReadOnlyAttribute(key)) { return this; } // Convert date fields to real date objects if (this.Model._hasDateAttributes && this.Model._isDateAttribute(key) && !!value && !value._isSequelizeMethod) { if (!(value instanceof Date)) { value = new Date(value); } if (!(originalValue instanceof Date)) { originalValue = new Date(originalValue); } if (originalValue && value.getTime() === originalValue.getTime()) { return this; } } } // Convert boolean-ish values to booleans if (this.Model._hasBooleanAttributes && this.Model._isBooleanAttribute(key) && value !== null && value !== undefined && !value._isSequelizeMethod) { if (Buffer.isBuffer(value) && value.length === 1) { // Bit fields are returned as buffers value = value[0]; } if (_.isString(value)) { // Only take action on valid boolean strings. value = (value === 'true') ? true : (value === 'false') ? false : value; } else if (_.isNumber(value)) { // Only take action on valid boolean integers. value = (value === 1) ? true : (value === 0) ? false : value; } } if (!options.raw && ((!Utils.isPrimitive(value) && value !== null) || value !== originalValue)) { this._previousDataValues[key] = originalValue; this.changed(key, true); } this.dataValues[key] = value; } } } return this; };
_.each(matchIndices,function (matchIndex) { data[collectionName][matchIndex] = _.extend(data[collectionName][matchIndex], values); resultSet.push(_.clone(data[collectionName][matchIndex])); });