var lena = imgUtils.rgb2gray(require('lena')); var lenaG = siftUtils.cacheGradient(lena); var width = lena.shape[0]; var height = lena.shape[1]; /** @type DetectedFeature */ var dfsample = { row: height*Math.random(), col: width*Math.random(), octave: 0, scale: 1.2, layer: 1 }; /** @type OrientedFeature */ var ofsample = _.extend(_.clone(dfsample), { orientation: 2*Math.PI*Math.random() }); /** * @param {number[]} arr * @returns {boolean} */ function isValidDescriptor(arr){ return arr.every(function(e){ return e >=0 && e <= 255 && (e % 1 === 0); }); } describe('websift', function(){
docs = docs.map(function(doc){ return _.extend(_.clone(doc), { type: DRIVING_DETAIL_DOC_TYPE, _id: docs._id || getDrivingDetailKey(doc) }); });
stylus.on('end', function(err, css){ var options = _.clone(config); options.name = path.basename(stylus.options.filename, path.extname(stylus.options.filename)); options.data = css; return ccss(options); });
_updateRange: function (categories) { var range = _.clone(this.model.get('range')); range[this._index] = categories[this._index].color; this.model.set('range', range); },
module.exports = function(config) { config = _.extend(_.clone(defaults), (config || {})); function move_file(old_file, new_file, files) { files[new_file] = files[old_file]; delete(files[old_file]); } return function(files, metalsmith, done) { var metadata = metalsmith.metadata(); metadata['build_date'] = metadata['date']; async.series([ function (callback) { async.each(metadata.courses, function(course, finished) { course.common = metadata.courses_common[course.common]; if (course.common.logo) { course.thumbnail = path.join("/assets/img/logos/courses", course.common.logo); } course.year = common.format_date(course.started, "YYYY"); course.name = course.common.title + ' (' + course.semester + ' ' + course.year + ')'; course.description = course.snippet.replace(/<(?:.|\n)*?>/gm, '').replace(/\s+/gm, ' '); finished(); }, function () { callback(); }); }, function (callback) { async.each(metadata.posts, function(post, finished) { var $ = cheerio.load(post.contents); if (!post.title) { post.title = $("h2").first().text(); $("h2").first().remove(); post.contents = new Buffer($.html()); } post.description = post.snippet.toString() .replace(/<(?:.|\n)*?>/gm, '').replace(/\s+/gm, ' '); finished(); }, function () { callback(); }); }, function (callback) { var post_slugs = {}; async.forEachOf(files, function (file, filename, finished) { if ('person' in file) { file.email = filename.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi)[0]; file.display_email = file.display_email || file.email; file.username = /([a-zA-Z0-9._-]+)@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+/gi.exec(filename)[1]; if (!file.slug) { file.slug = file.username; } } else if ('project' in file) { file.slug = filename.match(/\/(\S+)\/summary.html/)[1]; } else if ('paper' in file) { file.slug = filename.match(/\/([\w-]+)\/summary.html/)[1]; file.year = filename.match(/^papers\/(\d+)\//)[1]; } else if ('proposal' in file) { file.slug = filename.match(/\/([\w-]+)\/summary.html/)[1]; file.year = common.format_date(file.started, "YYYY"); } else if ('course' in file) { file.slug = file.common.slug + '_' + file.semester + '_' + file.year; } else if ('post' in file) { function slugify(text) { return text.toString().toLowerCase() .replace(/\s+/g, '-') .replace(/[^\w\-]+/g, '') .replace(/\-\-+/g, '-') .replace(/^-+/, '') .replace(/-+$/, ''); } post_slug = common.format_date(file.created, 'YYYY-MM-DD', false) + "-" + slugify(file.title.slice(0, 32)); if (post_slugs[post_slug] !== undefined) { return done(new Error("duplicate post slug")); } if (file.working && config.verbose) { console.log("Working post: " + post_slug); } post_slugs[post_slug] = true; file.slug = post_slug; file.people = [filename.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi)[0]]; } finished(); }, function () { callback(); }); }, function (callback) { async.each(metadata.people, function(person, finished) { person.person = true; if (person.link) { if ((person.link + '/photo.jpg').slice(1) in files) { person.photo = person.link + '/photo.jpg'; } if (!person.CV) { old_file = (person.link + '/CV.pdf').slice(1); if (old_file in files) { new_file = (person.link + '/' + person.name.replace(/\s+/g, '') + '-CV.pdf').slice(1); move_file(old_file, new_file, files); person.CV = "/" + new_file; } } person.finished = person.photo && person.snippet.length; } if (person.finished && !person.alumni) { person.group = true; } else if (person.finished && person.alumni) { if (!person.short_alumni) { person.long_alumni = true; } else { person.short_alumni = true; } } else if (person.old_group) { person.short_alumni = true; } else { person.collaborator = true; } if (person.snippet) { person.description = person.snippet.replace(/<(?:.|\n)*?>/gm, '').replace(/\s+/gm, ' '); } finished(); }, function () { callback(); }); }, function (callback) { async.each(metadata.projects, function(project, finished) { if (project.ended) { project.active = false; } else { project.active = true; } if (!project.title) { project.title = project.name; } else if (!project.name) { project.name = project.title; } project.description = project.snippet.toString() .replace(/<(?:.|\n)*?>/gm, '').replace(/\s+/gm, ' '); finished(); }, function () { callback(); }); }, function (callback) { async.each(metadata.papers, function(paper, finished) { if (paper.arxiv) { if (!paper.date) { console.log("arxiv paper without date: " + paper); } paper.toappear = (paper.date > Date.now()); } else if (!paper.thesis) { paper.conference = metadata.conferences[paper.published][paper.year]; paper.conference.year = paper.year; paper.published = metadata.conferences[paper.published]; paper.date = paper.conference.date; paper.toappear = (paper.date > Date.now()); } old_file = undefined; if ((paper.link + '/paper.pdf').slice(1) in files) { old_file = (paper.link + '/paper.pdf').slice(1); } else if ((paper.link + '/poster.pdf').slice(1) in files) { old_file = (paper.link + '/poster.pdf').slice(1); } else if ((paper.link + '/thesis.pdf').slice(1) in files) { old_file = (paper.link + '/thesis.pdf').slice(1); } if (old_file) { paper.thumbnail = "/" + old_file.substr(0, old_file.lastIndexOf(".")) + ".png"; if (!(fs.existsSync(path.join(metalsmith.source(), paper.thumbnail)))) { if (config.verbose) { console.log("Missing " + paper.thumbnail); } delete(paper.thumbnail); } new_file = (paper.link + '/' + paper.slug + '.pdf').slice(1); move_file(old_file, new_file, files); paper.PDF = "/" + new_file; } old_file = undefined; if ((paper.link + '/slides.pdf').slice(1) in files) { old_file = (paper.link + '/slides.pdf').slice(1); } if (old_file) { new_file = (paper.link + '/' + paper.slug + '-Slides.pdf').slice(1); move_file(old_file, new_file, files); paper.slides = "/" + new_file; } paper.conference_metadata = !(paper.poster || paper.thesis); paper.description = paper.snippet.toString() .replace(/<(?:.|\n)*?>/gm, '').replace(/\s+/gm, ' '); finished(); }, function () { callback(); }); }, function (callback) { async.each(metadata.proposals, function(proposal, finished) { proposal.source = metadata.sources[proposal.source]; proposal.program = proposal.source.programs[proposal.program]; proposal.pretty_amount = formatMoney(proposal.amount); proposal.year = proposal.started.getFullYear(); old_file = undefined; if ((proposal.link + '/external.pdf').slice(1) in files) { old_file = (proposal.link + '/external.pdf').slice(1); } if (old_file) { proposal.thumbnail = "/" + old_file.substr(0, old_file.lastIndexOf(".")) + ".png"; if (!(fs.existsSync(path.join(metalsmith.source(), proposal.thumbnail)))) { if (config.verbose) { console.log("Missing " + proposal.thumbnail); } delete(proposal.thumbnail); } new_file = (proposal.link + '/' + proposal.slug + '.pdf').slice(1); move_file(old_file, new_file, files); proposal.PDF = "/" + new_file; } if (proposal.ends < Date.now()) { proposal.active = false; } else { proposal.active = true; } proposal.inactive = !(proposal.active); if ('proposals/logos/' + proposal.source.shortname + '.jpg' in files) { proposal.logo = '/proposals/logos/' + proposal.source.shortname + '.jpg'; } proposal.description = proposal.snippet.toString() .replace(/<(?:.|\n)*?>/gm, '').replace(/\s+/gm, ' '); finished(); }, function () { callback(); }); }, function (callback) { async.each(metadata.courses, function(course, finished) { var $ = cheerio.load(course.contents); course.has_evaluations = $().is('#evaluations'); course.has_summary = $().is('#summary'); old_file = undefined; if ((course.link + '/syllabus.pdf').slice(1) in files) { old_file = (course.link + '/syllabus.pdf').slice(1); } if (old_file) { new_file = (course.link + '/' + course.slug + '-Syllabus.pdf').slice(1); move_file(old_file, new_file, files); course.syllabus = "/" + new_file; } old_file = false if ((course.link + '/evaluations.pdf').slice(1) in files) { old_file = (course.link + '/evaluations.pdf').slice(1); } if (old_file) { new_file = (course.link + '/' + course.slug + '-Evaluations.pdf').slice(1); move_file(old_file, new_file, files); course.evaluations = "/" + new_file; } course.info = course.website || course.syllabus || course.videos || course.evaluations; finished(); }, function() { callback(); }); } ], function (err) { done(err); }); } };
function makeRequest(config) { var request = _.clone(config || {}); request.params = request.params || {}; return request; }
import _ from "underscore"; import inflection from 'inflection'; import MetabaseUtils from "metabase/lib/utils"; const mb_settings = _.clone(window.MetabaseBootstrap); // provides access to Metabase application settings const MetabaseSettings = { get: function(propName, defaultValue = null) { return mb_settings[propName] !== undefined ? mb_settings[propName] : defaultValue; }, setAll: function(settings) { for (var attrname in settings) { mb_settings[attrname] = settings[attrname]; } }, // these are all special accessors which provide a lookup of a property plus some additional help adminEmail: function() { return mb_settings.admin_email; }, isEmailConfigured: function() { return mb_settings.email_configured; }, isTrackingEnabled: function() { return mb_settings.anon_tracking_enabled || false;
previousAttributes : function() { return _.clone(this._previousAttributes); },
var astIsEqual = exports.astIsEqual = function(node, pattern, config) { const tokens = Narcissus.definitions.tokenIds; // Narcissus messes up the AST when parsing [,] (no idea what [,] means) if (node == null && pattern == null) { return true; } else if (node == null || pattern == null) { return false; } if (pattern.type == tokens.IDENTIFIER && Matcher.identifierIsMetavar(pattern.value)) { if (pattern.value in config.variables) { // Variable already matched, compare this node to that value return astIsEqual(node, config.variables[pattern.value], { strictMatches: true }); } else { if (config.failOnMetavar) { throw { message: "Matching metavariables inside partially-matched lists is " + "unsupported. Sorry!" }; } // Bind variable to this value config.variables[pattern.value] = node; return true; } } if (node.type != pattern.type) { return false; } if (node.type == tokens.OBJECT_INIT && !config.strictMatches) { // Strict matching will be handled normally (below). if (pattern.children.length > node.children.length) { return false; } var keys = _.clone(pattern.children); for (var i = 0; i < node.children.length; i++) { for (var j = 0; j < keys.length;) { config.failOnMetavar = true; var match = astIsEqual(node.children[i], keys[j], config); config.failOnMetavar = false; if (match) { keys.splice(j, 1); break; } else { j++; } } if (keys.length == 0) { break; } } // No keys left over -> match. return keys.length == 0; } switch(node.type) { // Core values case tokens.FALSE: case tokens.IDENTIFIER: case tokens.NULL: case tokens.NUMBER: case tokens.REGEXP: case tokens.STRING: case tokens.THIS: case tokens.TRUE: return node.value == pattern.value; break; // 0-child statements case tokens.BREAK: case tokens.CONTINUE: case tokens.DEBUGGER: return true; break; // Unary expressions case tokens.BITWISE_NOT: case tokens.NEW: case tokens.NEW_WITH_ARGS: case tokens.NOT: case tokens.TYPEOF: case tokens.UNARY_MINUS: case tokens.UNARY_PLUS: case tokens.VOID: // Binary expressions case tokens.AND: case tokens.BITWISE_AND: case tokens.BITWISE_OR: case tokens.BITWISE_XOR: case tokens.DIV: case tokens.EQ: case tokens.GE: case tokens.GT: case tokens.IN: case tokens.INSTANCEOF: case tokens.LE: case tokens.LSH: case tokens.LT: case tokens.MINUS: case tokens.MOD: case tokens.MUL: case tokens.NE: case tokens.OR: case tokens.PLUS: case tokens.RSH: case tokens.STRICT_EQ: case tokens.STRICT_NE: case tokens.ULSH: case tokens.URSH: // Other case tokens.ASSIGN: case tokens.CALL: case tokens.COMMA: case tokens.DELETE: case tokens.DOT: case tokens.HOOK: case tokens.INDEX: // Special //case tokens.SCRIPT: if (node.children.length == pattern.children.length) { for (var i = 0; i < node.children.length; i++) { if (!astIsEqual(node.children[i], pattern.children[i], config)) { return false; } } return true; } break; case tokens.DECREMENT: case tokens.INCREMENT: return node.postfix === pattern.postfix && astIsEqual(node.children[0], pattern.children[0], config); break; case tokens.PROPERTY_INIT: if (node.children.length != 2 || pattern.children.length != 2) { throw { message: "astIsEqual: Unsupported PROPERTY_INIT" }; } // In strict mode, the ordering will prevent an ambiguous match. config.failOnMetavar = !config.strictMatches; var match = astIsEqual(node.children[0], pattern.children[0], config); config.failOnMetavar = false; if (!match) { return false; } return astIsEqual(node.children[1], pattern.children[1], config); break; case tokens.ARRAY_INIT: case tokens.BLOCK: case tokens.LIST: case tokens.OBJECT_INIT: return astMatchList(node.children, pattern.children, config); break; case tokens.LET: case tokens.VAR: // All of var's children are IDENTIFIERs with name/initializer values // TODO: this does not support destructuring assignments // XXX: Note that "A = B" as a pattern will *not* match "var A = B" if (config.strictMatches) { // TODO: this is using astMatchList even though the parser won't // accept an ellipsis in a var. return astMatchList(node.children, pattern.children, config, function(node, pattern, config) { if (!astIsEqual(node, pattern, config)) { return false; } // If the pattern has an initializer, it must be equal to the one in // the source. if (pattern.initializer && (!node.initializer || !astIsEqual(node.initializer, pattern.initializer, config))) { return false; } // If in strict mode and the pattern has no initializer, neither can // the source. if (!pattern.initializer && config.strictMatches && node.initializer) { return false; } return true; }); } else { if (pattern.children.length > node.children.length) { return false; } var keys = _.clone(pattern.children); for (var i = 0; i < node.children.length; i++) { for (var j = 0; j < keys.length;) { config.failOnMetavar = true; var match = astIsEqual(node.children[i], keys[j], config); config.failOnMetavar = false; if (match) { // If the pattern has an initializer, it must be equal to the one // in the source. if (keys[j].initializer && (!node.children[i].initializer || !astIsEqual(node.children[i].initializer, keys[j].initializer, config))) { return false; } keys.splice(j, 1); break; } else { j++; } } if (keys.length == 0) { break; } } // No keys left over -> match. return keys.length == 0; } break; case tokens.SEMICOLON: if (!node.expression && !pattern.expression) { return true; } else if (node.expression && pattern.expression) { return astIsEqual(node.expression, pattern.expression, config); } return false; break; //case tokens.DO: //forEachNode(node.body, callback); //forEachNode(node.condition, callback); break; //case tokens.WHILE: //forEachNode(node.condition, callback); //forEachNode(node.body, callback); break; //case tokens.FUNCTION: //forEachNode(node.body, callback); break; //case tokens.RETURN: if (node.value) { //forEachNode(node.value, callback); } break; //case tokens.SWITCH: //forEachNode(node.discriminant, callback); _.each(node.cases, function(child) { //forEachNode(child, callback); }); break; //case tokens.DEFAULT: //forEachNode(node.statements, callback); break; //case tokens.CASE: //forEachNode(node.caseLabel, callback); //forEachNode(node.statements, callback); break; //case tokens.LABEL: //forEachNode(node.statement, callback); break; //case tokens.FOR_IN: //forEachNode(node.iterator, callback); //forEachNode(node.object, callback); //forEachNode(node.body, callback); break; //case tokens.FOR: //forEachNode(node.setup, callback); //forEachNode(node.condition, callback); //forEachNode(node.update, callback); //forEachNode(node.body, callback); break; case tokens.IF: if (!astIsEqual(node.condition, pattern.condition, config)) { return false; } if (!astIsEqual(node.thenPart, pattern.thenPart, config)) { return false; } if (config.strictMatches) { if (node.elsePart && pattern.elsePart) { return astIsEqual(node.elsePart, pattern.elsePart, config); } if (node.elsePart || pattern.elsePart) { return false; } return true; } else if (pattern.elsePart) { if (!node.elsePart) { return false; } return astIsEqual(node.elsePart, pattern.elsePart, config); } return true; break; //case tokens.TRY: //forEachNode(node.tryBlock, callback); _.each(node.catchClauses, function(child) { //forEachNode(child, callback); }); if (node.finallyBlock) { //forEachNode(node.finallyBlock, callback); } break; //case tokens.CATCH: if (node.guard) { //forEachNode(node.guard, callback); } //forEachNode(node.block); break; case tokens.THROW: return astIsEqual(node.exception, pattern.exception, config); break; default: throw { message: "Pattern type is not yet supported: " + tokenString(node.type) }; break; } }
toJSON : function() { return _.clone(this.attributes); },
change : function(options) { this.trigger('change', this, options); this._previousAttributes = _.clone(this.attributes); this._unsetAttributes = null; this._changed = false; },
HistoryView.prototype.templates = (() => { var mainTemplate = () => `<div> <div class="controls"></div> <ul class="list-items"></ul> <div class="empty-message infomessagesmall"></div>', </div>`; var controlsTemplate = BASE_MVC.wrapTemplate( [ '<div class="controls">', '<div class="title">', '<div class="name"><%- history.name %></div>', "</div>", '<div class="subtitle"></div>', '<div class="history-size"><%- history.nice_size %></div>', '<div class="actions"></div>', '<div class="messages">', "<% if( history.deleted && history.purged ){ %>", '<div class="deleted-msg warningmessagesmall">', _l("This history has been purged and deleted"), "</div>", "<% } else if( history.deleted ){ %>", '<div class="deleted-msg warningmessagesmall">', _l("This history has been deleted"), "</div>", "<% } else if( history.purged ){ %>", '<div class="deleted-msg warningmessagesmall">', _l("This history has been purged"), "</div>", "<% } %>", "<% if( history.message ){ %>", // should already be localized '<div class="<%= history.message.level || "info" %>messagesmall">', "<%= history.message.text %>", "</div>", "<% } %>", "</div>", // add tags and annotations '<div class="tags-display"></div>', '<div class="annotation-display"></div>', '<div class="search">', '<div class="search-input"></div>', "</div>", '<div class="list-actions">', '<div class="btn-group">', '<button class="select-all btn btn-secondary"', 'data-mode="select">', _l("All"), "</button>", '<button class="deselect-all btn btn-secondary"', 'data-mode="select">', _l("None"), "</button>", "</div>", '<div class="list-action-menu btn-group">', "</div>", "</div>", '<div class="list-pagination form-inline"></div>', "</div>" ], "history" ); var paginationTemplate = BASE_MVC.wrapTemplate( [ '<button class="prev" <%- pages.current === 1 ? "disabled" : "" %>>previous</button>', '<select class="pages form-control" ', 'title="', _l("Click to open and select a page. Begin typing a page number to select it"), '">', "<% _.range( 1, pages.last + 1 ).forEach( function( i ){ %>", '<option value="<%- i - 1 %>" <%- i === pages.current ? "selected" : "" %>>', "<%- view.ordinalIndicator( i ) %> of <%- pages.last %> pages", "</option>", "<% }); %>", "</select>", '<button class="next" <%- pages.current === pages.last ? "disabled" : "" %>>next</button>' ], "pages" ); return _.extend(_.clone(_super.prototype.templates), { el: mainTemplate, controls: controlsTemplate, pagination: paginationTemplate }); })();
collapseAll: function() { this.model.contents.storage.clearExpanded(); _super.prototype.collapseAll.call(this); }, // ------------------------------------------------------------------------ selection /** Override to correctly set the historyId of the new collection */ getSelectedModels: function() { var collection = _super.prototype.getSelectedModels.call(this); collection.historyId = this.collection.historyId; return collection; }, // ------------------------------------------------------------------------ panel events /** event map */ events: _.extend(_.clone(_super.prototype.events), { "click .show-selectors-btn": "toggleSelectors", "click > .controls .prev": "_clickPrevPage", "click > .controls .next": "_clickNextPage", "change > .controls .pages": "_changePageSelect", // allow (error) messages to be clicked away "click .messages [class$=message]": "clearMessages" }), _clickPrevPage: function(ev) { this.model.stopPolling(); this.model.contents.fetchPrevPage(); }, _clickNextPage: function(ev) { this.model.stopPolling();
function (results, next) { plugins.fireHook('action:post.restore', _.clone(postData)); next(null, postData); }
module.exports = function csp(options) { options = _.clone(options) || { 'default-src': ["'self'"] }; var reportOnly = options.reportOnly || false; var setAllHeaders = options.setAllHeaders || false; var safari5 = options.safari5 || false; DIRECTIVES.forEach(function (directive) { var cameledKey = camelize(directive); var cameledValue = options[cameledKey]; if (cameledValue && (cameledKey !== directive)) { if (options[directive]) { throw new Error(directive + ' and ' + cameledKey + ' specified. Specify just one.'); } options[directive] = cameledValue; } }); _.each(options, function (value) { if (Array.isArray(value)) { MUST_BE_QUOTED.forEach(function (must) { if (value.indexOf(must) !== -1) { throw new Error(value + ' must be quoted'); } }); } else { MUST_BE_QUOTED.forEach(function (must) { if (value === must) { throw new Error(value + ' must be quoted'); } }); } }); if (reportOnly && !options['report-uri']) { throw new Error('Please remove reportOnly or add a report-uri.'); } return function csp(req, res, next) { var headers = []; var policy = {}; var browser = platform.parse(req.headers['user-agent']); var version = parseFloat(browser.version); var unknownBrowser = false; DIRECTIVES.forEach(function (directive) { var value = options[directive]; if ((value !== null) && (value !== undefined)) { policy[directive] = value; } var shouldWrapInArray = (_(value).isString()) && ( (directive !== 'sandbox') || ((directive === 'sandbox') && (value !== true)) ); if (shouldWrapInArray) { policy[directive] = value.split(/\s/g); } }); switch (browser.name) { case 'IE': if (version >= 10) { headers.push('X-Content-Security-Policy'); if (!setAllHeaders) { if (policy.sandbox) { policy = { sandbox: policy.sandbox }; } else { policy = {}; } } } break; case 'Firefox': if (version >= 23) { headers.push('Content-Security-Policy'); } else if ((version >= 4) && (version < 23)) { headers.push('X-Content-Security-Policy'); policy['default-src'] = policy['default-src'] || ['*']; Object.keys(options).forEach(function (key) { var value = options[key]; if (Array.isArray(value)) { // Clone the array so we don't later mutate `options` by mistake value = value.slice(); } if (key === 'connect-src') { policy['xhr-src'] = value; } else if (key === 'default-src') { if (version < 5) { policy.allow = value; } else { policy['default-src'] = value; } } else if (key !== 'sandbox') { policy[key] = value; } if (Array.isArray(policy[key])) { var index; if ((index = policy[key].indexOf("'unsafe-inline'")) !== -1) { if (key === 'script-src') { policy[key][index] = "'inline-script'"; } else { policy[key].splice(index, 1); } } if ((index = policy[key].indexOf("'unsafe-eval'")) !== -1) { if (key === 'script-src') { policy[key][index] = "'eval-script'"; } else { policy[key].splice(index, 1); } } } }); } break; case 'Chrome': if ((version >= 14) && (version < 25)) { headers.push('X-WebKit-CSP'); } else if (version >= 25) { headers.push('Content-Security-Policy'); } break; case 'Safari': if (version >= 7) { headers.push('Content-Security-Policy'); } else if ((version >= 6) || ((version >= 5.1) && safari5)) { headers.push('X-WebKit-CSP'); } break; case 'Opera': if (version >= 15) { headers.push('Content-Security-Policy'); } break; case 'Chrome Mobile': if (version >= 14) { headers.push('Content-Security-Policy'); } break; default: unknownBrowser = true; } var policyString = _.map(policy, function (value, key) { if ((key === 'sandbox') && (value === true)) { return 'sandbox'; } else if (Array.isArray(value)) { return key + ' ' + value.join(' '); } else { return key + ' ' + value; } }).join(';'); if (setAllHeaders || unknownBrowser) { headers = ALL_HEADERS; } if (policyString) { headers.forEach(function (header) { var headerName = header; if (reportOnly) { headerName += '-Report-Only'; } res.setHeader(headerName, policyString); }); } next(); }; };
app.get('/prices.json', function(req, res){ var prices = _.clone(pricesContainer.prices); _.extend(prices, {'date': pricesContainer.lastUpdate}); res.set('Content-Type', 'application/json') .send(prices); });
], function(err) { plugins.fireHook('action:post.restore', _.clone(postData)); next(err, postData); });
BaseModel.prototype.setRelation = function(attr, val, options) { var relation = this.attributes[attr], id = this.idAttribute || 'id', modelsToAdd = [], modelsToRemove = []; if (options.unset && relation) { delete relation.parent; } if (this.relations && _.has(this.relations, attr)) { // If the relation already exists, we don't want to replace it, rather // update the data within it whether it is a collection or model if (relation && relation instanceof Backbone.Collection) { // If the val that is being set is already a collection, use the models // within the collection. if (val instanceof Backbone.Collection || val instanceof Array) { val = val.models || val; modelsToAdd = _.clone(val); if (options.reset) { // Adding option to reset nested collections via Model.set relation.reset(modelsToAdd); } else { relation.each(function(model) { var idAttribute; if (ComponentWidget.isComponent(model)) { idAttribute = model.model.idAttribute || 'id'; } else { idAttribute = model.idAttribute || 'id'; } // If the model does not have an 'id' skip logic to detect if it already // exists and simply add it to the collection var id = model.get(idAttribute); if (typeof id === 'undefined') { return; } // If the incoming model also exists within the existing collection, // call set on that model. If it doesn't exist in the incoming array, // then add it to a list that will be removed. var rModel = null, mIndex = -1; for (var i = 0; i < modelsToAdd.length; i++) { if (modelsToAdd[i][idAttribute] === id) { rModel = modelsToAdd[i]; mIndex = i; break; } } if (rModel) { model.set(rModel.toJSON ? rModel.toJSON() : rModel); // Remove the model from the incoming list because all remaining models // will be added to the relation modelsToAdd.splice(mIndex, 1); } else { modelsToRemove.push(model); } }); _.each(modelsToRemove, function(model) { relation.remove(model); }); relation.add(modelsToAdd); } } else { // The incoming val that is being set is not an array or collection, then it represents // a single model. Go through each of the models in the existing relation and remove // all models that aren't the same as this one (by id). If it is the same, call set on that // model. relation.each(function(model) { if (val && val[id] === model[id]) { model.set(val); } else { relation.remove(model); } }); } return relation; } if (relation && relation instanceof Backbone.Model) { relation.set(val); return relation; } options._parent = this; // Since this is a relation for a model, unset any collection option that might be passed through if (options.collection) { options.collection = null; } val = new this.relations[attr](val, options); val.parent = this; val.parentProp = attr; } return val; };
var CWAgent = function(options) { this.options = _.clone(options); this.client = aws.createCWClient(options.awskey || null, options.awssecret || null, {host: 'monitoring.' + options.region + '.amazonaws.com'}); return this; }
BaseModel.prototype.set = function(key, val, options) { var attr, attrs, unset, changes, silent, changing, prev, current; if (key == null) { return this; } // Handle both `'key', value` and `{key: value}` -style arguments. if (typeof key === 'object') { attrs = key; options = val; } else { (attrs = {})[key] = val; } options = options || {}; var propTypes = _.result(this, 'propTypes') || {}; // iterate though properties and check if valid _.each(propTypes, (propType, propName) => { var propValue = attrs[propName]; var validationResult = this.validateProperty(propType, propValue); if (validationResult !== true) { throw new TypeError('PropTypes.' + propName + ' ' + validationResult.msg); } }); if (typeof TUNGSTENJS_DEBUG_MODE !== 'undefined') { // In order to compare server vs. client data, save off the initial data if (!this.initialData) { // Using JSON to get a deep clone to avoid any overlapping object references var initialStr = '{}'; try { initialStr = JSON.stringify(_.has(options, 'initialData') ? options.initialData : attrs); } catch (e) { initialStr = '{"Error": "Unable to serialize initial data (possible circular reference)."}'; } delete options.initialData; this.initialData = JSON.parse(initialStr || '{}'); if (!_.isObject(this.initialData) || _.isArray(this.initialData)) { errors.modelExpectedObjectOfAttributesButGot(initialStr); } } } // Run validation. if (!this._validate(attrs, options)) { return false; } // Extract attributes and options. unset = options.unset; silent = options.silent; changes = []; changing = this._changing; this._changing = true; if (!changing) { this._previousAttributes = _.clone(this.attributes); this.changed = {}; } current = this.attributes; prev = this._previousAttributes; // Check for changes of `id`. if (this.idAttribute in attrs) { this.id = attrs[this.idAttribute]; } var i, l; // For each `set` attribute, update or delete the current value. for (attr in attrs) { if (attrs.hasOwnProperty(attr)) { val = attrs[attr]; // Inject in the relational lookup var opts = options; if (typeof TUNGSTENJS_DEBUG_MODE !== 'undefined') { opts = _.extend({ initialData: val }, options); } val = this.setRelation(attr, val, opts); if (!_.isEqual(current[attr], val)) { changes.push(attr); } if (!_.isEqual(prev[attr], val)) { this.changed[attr] = val; } else { delete this.changed[attr]; } if (unset) { delete current[attr]; } else { current[attr] = val; } if (ComponentWidget.isComponent(val)) { if (val.exposedEvents) { var events = val.exposedEvents; if (events === true) { val.model.parent = this; val.model.parentProp = attr; } else if (events.length) { for (i = 0, l = events.length; i < l; i++) { this.bindExposedEvent(events[i], attr, val); } } } } } } // Trigger all relevant attribute changes. if (!silent) { if (changes.length) { this._pending = true; } for (i = 0, l = changes.length; i < l; i++) { this.trigger('change:' + changes[i], this, current[changes[i]], options); } } if (changing) { return this; } if (!silent) { while (this._pending) { this._pending = false; this.trigger('change', this, options); } } this._pending = false; this._changing = false; return this; };
var _ = require('underscore'); var CDB = require('cartodb.js'); var Backbone = require('backbone'); var CoreView = require('backbone/core-view'); var template = require('./input-color-categories.tpl'); var StackLayoutView = require('../../../../../../components/stack-layout/stack-layout-view'); var InputColorPickerView = require('../input-color-picker/input-color-picker-view'); var CategoriesListView = require('./input-color-categories-list-view'); var rampList = require('cartocolor'); var AssetPickerView = require('../assets-picker/input-asset-picker-view'); var MAX_VALUES = 10; // max values + "others" color var DEFAULT_COLORS = _.clone(rampList.Prism[MAX_VALUES + 1]); var queryTemplate = _.template('SELECT <%= column %>, count(<%= column %>) FROM (<%= sql %>) _table_sql GROUP BY <%= column %> ORDER BY count DESC, <%= column %> ASC LIMIT <%= max_values %>'); function _quote (c) { if (c && c !== true) { return '"' + c.toString().replace(/"/g, '\\"').replace(/\n/g, '\\n') + '"'; } return c; } module.exports = CoreView.extend({ events: { 'click .js-back': '_onClickBack', 'click .js-quantification': '_onClickQuantification' }, initialize: function (opts) { if (!opts.columns) throw new Error('columns param is required');
[true, false].forEach(function(server) { var config = _.clone(fileConfig); config.server = server; ret.push(config); });
_onImageChanged: function (data) { var images = _.clone(this.model.get('images')); images[this._index] = data.url; this.model.set('images', images); },
import _ from "underscore"; import pumpkins from "./pumpkins_base.js"; var myPumpkins = _.clone(pumpkins); myPumpkins.privSquadName = 'v6'; myPumpkins.pumpkinBirthplace = function () { var self = this; // CONTROLLO SPAZIO FINITO if (_.indexOf(this.fieldArray, 0) == -1) { return -1; } var level1 = []; // FREE SPOTS var level2 = []; // + NO PIG AROUND var level3 = []; // + NO PIG LOOKING var level4 = []; // + 1 PASSO var level5 = []; // + 2 PASSI var level_used = []; // GUARDO MEGLIO 1 PASSO AVANTI let min_threatened_pumpkins = 99999; let min_threat_pos = []; _.each(_.range(this.tileRows*this.tileRows), function(pos) { let f = _.clone(self.fieldArray); f[pos] = 3; let threatened_pumpkins = self.gu.how_many_threatened_pumpkins(self.gu.simulate_move(f, 0)) + self.gu.how_many_threatened_pumpkins(self.gu.simulate_move(f, 1)) +
docs = docs.map(function(doc){ return _.extend(_.clone(doc), { type: DRIVING_BEHAVIOR_DOC_TYPE, _id: doc._id || getDrivingBehaviorKey(doc) }); });
app.use(bunyanMiddleware( { headerName: 'X-Request-Id' , propertyName: 'reqId' , logName: 'req_id' , obscureHeaders: [] , logger: logger } ) ); // The Swagger document (require it, build it programmatically, fetch it from a URL, ...) var swaggerDoc = require('./api/definition'), swaggerDocMock = _.clone(swaggerDoc); swaggerDocMock.basePath = "/mockedapi"; // Initialize the Swagger middleware async.map([swaggerDoc, swaggerDocMock], function (doc, callback) { try { swaggerTools.initializeMiddleware(doc, function (middleware) { callback(null, middleware); }); } catch (err) { callback(err); } }, function (err, results) {
}).forEach(function (file) { var data = _.extend(_.clone(pluginType), { location: file }); plugindata.pluginIncludes.push(data); });
bodyExt.errors = _.map(body.results.errors, function (error) { var result = _.clone(error); result.path = error.path.join('/'); return result; });
return _.map(users, function(user) { return _.clone(user); });
GitEngine.prototype.getHead = function() { return _.clone(this.HEAD); };