code
stringlengths 24
2.07M
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
92
| language
stringclasses 1
value | repo
stringlengths 5
64
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
emailNotifications () {
const notificationsURLParts = ['api/v3/email_notifications'];
return {
get: (callback) => {
return this.get(notificationsURLParts, callback);
},
set: (notifications, callback) => {
const opts = {
data: JSON.stringify({ notifications }),
dataType: 'json'
};
return this.put(notificationsURLParts, opts, callback);
}
};
}
|
API to enable/disable email notifications, such as DO notifications
|
emailNotifications
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/carto-node/lib/clients/authenticated.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/carto-node/lib/clients/authenticated.js
|
BSD-3-Clause
|
LocalStorageWrapper = function(name) {
this.name = name || 'cartodb';
if(!localStorage.getItem(this.name) && this.isEnabled()) {
localStorage.setItem(this.name, "{}");
}
}
|
Local storage wrapper
- It should be used within 'cartodb' key, for example:
var loc_sto = new cdb.common.LocalStorage();
loc_sto.set({ 'dashboard.order': 'create_at' });
loc_sto.get('dashboard.order');
|
LocalStorageWrapper
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/common/local_storage.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/common/local_storage.js
|
BSD-3-Clause
|
onClose = function() {
privacyModal.unbind('hide', onClose);
self.options.clean_on_hide = originalCleanOnHideValue;
self.show();
privacyModal.close();
}
|
@implements cdb.ui.common.Dialog.prototype.render_content
|
onClose
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/common/dialogs/publish/publish_view.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/common/dialogs/publish/publish_view.js
|
BSD-3-Clause
|
fn = function(bytes) {
if (!(this instanceof fn)) return new fn(bytes);
this.bytes = bytes;
if (bytes == 0) {
this.unit = 0;
} else {
this.unit = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
}
return this;
}
|
Object representing human-readable version of a given number of bytes.
(Extracted logic from an old dashboard view)
@param bytes {Number}
@returns {Object}
|
fn
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/common/view_helpers/bytes_to_size.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/common/view_helpers/bytes_to_size.js
|
BSD-3-Clause
|
function isLinuxMiddleOrRightClick(ev) {
return ev.which === 2 || ev.which === 3;
}
|
Check if Linux user used right/middle click at the time of the event
@param ev {Event}
@returns {boolean}
|
isLinuxMiddleOrRightClick
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/common/view_helpers/navigate_through_router.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/common/view_helpers/navigate_through_router.js
|
BSD-3-Clause
|
function isMacCmdKeyPressed(ev) {
return ev.metaKey;
}
|
Check if Mac user used CMD key at the time of the event Mac user used CMD key at the time of the event.
@param ev {Event}
@returns {boolean}
|
isMacCmdKeyPressed
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/common/view_helpers/navigate_through_router.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/common/view_helpers/navigate_through_router.js
|
BSD-3-Clause
|
function isCtrlKeyPressed(ev) {
return ev.ctrlKey;
}
|
Check if Mac user used CMD key at the time of the event Mac user used CMD key at the time of the event.
@param ev {Event}
@returns {boolean}
|
isCtrlKeyPressed
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/common/view_helpers/navigate_through_router.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/common/view_helpers/navigate_through_router.js
|
BSD-3-Clause
|
function manage_choropleth_props(type, props) {
var carto_props = {
'marker-width': props['marker-width'],
'marker-fill-opacity': props['marker-opacity'],
'marker-line-width': props['marker-line-width'],
'marker-line-color': props['marker-line-color'],
'marker-line-opacity': props['marker-line-opacity'],
'marker-allow-overlap': props['marker-allow-overlap'],
'line-color': props['line-color'],
'line-opacity': props['line-opacity'],
'line-width': props['line-width'],
'polygon-opacity': type == "line" ? 0 : props['polygon-opacity'],
'text-name': props['text-name'],
'text-halo-fill': props['text-halo-fill'],
'text-halo-radius': props['text-halo-radius'],
'text-face-name': props['text-face-name'],
'text-size': props['text-size'],
'text-dy': props['text-dy'],
'text-allow-overlap': props['text-allow-overlap'],
'text-placement': props['text-placement'],
'text-placement-type': props['text-placement-type'],
'text-label-position-tolerance': props['text-label-position-tolerance'],
'text-fill': props['text-fill']
}
// Remove all undefined properties
_.each(carto_props, function(v, k){
if(v === undefined) delete carto_props[k];
});
return carto_props;
}
|
Manage some carto properties depending on
type (line, polygon or point), for choropleth.
|
manage_choropleth_props
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/models/carto.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/models/carto.js
|
BSD-3-Clause
|
function getProp(obj, prop) {
var p = [];
for(var k in obj) {
var v = obj[k];
if (k === prop) {
p.push(v);
} else if (typeof(v) === 'object') {
p = p.concat(getProp(v, prop));
}
}
return p;
}
|
Manage some carto properties depending on
type (line, polygon or point), for choropleth.
|
getProp
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/models/carto.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/models/carto.js
|
BSD-3-Clause
|
function manage_carto_properies(props) {
if(/none/i.test(props['text-name']) || !props['text-name']) {
// remove all text-* properties
for(var p in props) {
if(isTextProperty(p)) {
delete props[p];
}
}
}
if(/none/i.test(props['polygon-comp-op'])) {
delete props['polygon-comp-op'];
}
if(/none/i.test(props['line-comp-op'])) {
delete props['line-comp-op'];
}
if(/none/i.test(props['marker-comp-op'])) {
delete props['marker-comp-op'];
}
// if polygon-pattern-file is present polygon-fill should be removed
if('polygon-pattern-file' in props) {
delete props['polygon-fill'];
}
delete props.zoom;
// translate props
props = translate_carto_properties(props);
return _.pick(props, _cartocss_spec_props);
}
|
some carto properties depends on others, this function
remove or add properties needed to carto works
|
manage_carto_properies
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/models/carto.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/models/carto.js
|
BSD-3-Clause
|
function isTextProperty(p) {
return /^text-/.test(p);
}
|
some carto properties depends on others, this function
remove or add properties needed to carto works
|
isTextProperty
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/models/carto.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/models/carto.js
|
BSD-3-Clause
|
function generate_carto_properties(props) {
return _(props).map(function(v, k) {
if(_.include(carto_quotables, k)) {
v = "'" + v + "'";
}
if(_.include(carto_variables, k)) {
v = "[" + v + "]";
}
return " " + k + ": " + v + ";";
});
}
|
some carto properties depends on others, this function
remove or add properties needed to carto works
|
generate_carto_properties
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/models/carto.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/models/carto.js
|
BSD-3-Clause
|
function filter_props(props, fn) {
var p = {};
for(var k in props) {
var v = props[k];
if(fn(k, v)) {
p[k] = v;
}
}
return p;
}
|
some carto properties depends on others, this function
remove or add properties needed to carto works
|
filter_props
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/models/carto.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/models/carto.js
|
BSD-3-Clause
|
function translate_carto_properties(props) {
if ('marker-opacity' in props) {
props['marker-fill-opacity'] = props['marker-opacity'];
delete props['marker-opacity'];
}
return props;
}
|
some carto properties depends on others, this function
remove or add properties needed to carto works
|
translate_carto_properties
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/models/carto.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/models/carto.js
|
BSD-3-Clause
|
function simple_polygon_generator(table, props, changed, callback) {
// remove unnecesary properties, for example
// if the text-name is not present remove all the
// properties related to text
props = manage_carto_properies(props);
var text_properties = filter_props(props, function(k, v) { return isTextProperty(k); });
var general_properties = filter_props(props, function(k, v) { return !isTextProperty(k); });
// generate cartocss with the properties
generalLayerProps = generate_carto_properties(general_properties);
textLayerProps = generate_carto_properties(text_properties);
// layer with non-text properties
var generalLayer = "#" + table.getUnqualifiedName() + "{\n" + generalLayerProps.join('\n') + "\n}";
var textLayer = '';
if (_.size(textLayerProps)) {
textLayer = "\n\n#" + table.getUnqualifiedName() + "::labels {\n" + textLayerProps.join('\n') + "\n}\n";
}
// text properties layer
callback(generalLayer + textLayer);
}
|
some carto properties depends on others, this function
remove or add properties needed to carto works
|
simple_polygon_generator
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/models/carto.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/models/carto.js
|
BSD-3-Clause
|
function intensity_generator(table, props, changed, callback) {
// remove unnecesary properties, for example
// if the text-name is not present remove all the
// properties related to text
props = manage_carto_properies(props);
var carto_props = {
'marker-fill': props['marker-fill'],
'marker-width': props['marker-width'],
'marker-line-color': props['marker-line-color'],
'marker-line-width': props['marker-line-width'],
'marker-line-opacity': props['marker-line-opacity'],
'marker-fill-opacity': props['marker-fill-opacity'],
'marker-comp-op': 'multiply',
'marker-type': 'ellipse',
'marker-placement': 'point',
'marker-allow-overlap': true,
'marker-clip': false,
'marker-multi-policy': 'largest'
};
var table_name = table.getUnqualifiedName();
var css = "\n#" + table_name +"{\n";
_(carto_props).each(function(prop, name) {
css += " " + name + ": " + prop + "; \n";
});
css += "}";
callback(css);
}
|
some carto properties depends on others, this function
remove or add properties needed to carto works
|
intensity_generator
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/models/carto.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/models/carto.js
|
BSD-3-Clause
|
function cluster_sql(table, zoom, props, nquartiles) {
var grids = ["A", "B", "C", "D", "E"];
var bucket = "bucket" + grids[0];
var mainBucket = bucket;
var sizes = [];
var step = 1 / (nquartiles + 1);
for (var i = 0; i < nquartiles; i++) {
sizes.push( 1 - step * i)
}
var sql = "WITH meta AS ( " +
" SELECT greatest(!pixel_width!,!pixel_height!) as psz, ext, ST_XMin(ext) xmin, ST_YMin(ext) ymin FROM (SELECT !bbox! as ext) a " +
" ), " +
" filtered_table AS ( " +
" SELECT t.* FROM <%= table %> t, meta m WHERE t.the_geom_webmercator && m.ext " +
" ), ";
for (var i = 0; i<nquartiles; i++) {
bucket = "bucket" + grids[i];
if (i == 0){
sql += mainBucket + "_snap AS (SELECT ST_SnapToGrid(f.the_geom_webmercator, 0, 0, m.psz * <%= size %>, m.psz * <%= size %>) the_geom_webmercator, count(*) as points_count, 1 as cartodb_id, array_agg(f.cartodb_id) AS id_list "
}
if (i > 0){
sql += "\n" + bucket + "_snap AS (SELECT ST_SnapToGrid(f.the_geom_webmercator, 0, 0, m.psz * " + sizes[i] + " * <%= size %>, m.psz * " + sizes[i] + " * <%= size %>) the_geom_webmercator, count(*) as points_count, 1 as cartodb_id, array_agg(f.cartodb_id) AS id_list "
}
sql += " FROM filtered_table f, meta m "
if (i == 0){
sql += " GROUP BY ST_SnapToGrid(f.the_geom_webmercator, 0, 0, m.psz * <%= size %>, m.psz * <%= size %>), m.xmin, m.ymin), ";
}
if (i > 0){
sql += " WHERE cartodb_id NOT IN (select unnest(id_list) FROM " + mainBucket + ") ";
for (var j = 1; j<i; j++) {
bucket2 = "bucket" + grids[j];
sql += " AND cartodb_id NOT IN (select unnest(id_list) FROM " + bucket2 + ") ";
}
sql += " GROUP BY ST_SnapToGrid(f.the_geom_webmercator, 0, 0, m.psz * " + sizes[i] + " * <%= size %>, m.psz * " + sizes[i] + " * <%= size %>), m.xmin, m.ymin), ";
}
sql += bucket + " AS (SELECT * FROM " + bucket + "_snap WHERE points_count > ";
if (i == nquartiles - 1) {
sql += " GREATEST(<%= size %> * 0.1, 2) ";
} else {
sql += " <%= size %> * " + sizes[i];
}
sql += " ) ";
if (i < nquartiles - 1) sql += ", ";
}
sql += " SELECT the_geom_webmercator, 1 points_count, cartodb_id, ARRAY[cartodb_id] as id_list, 'origin' as src, cartodb_id::text cdb_list FROM filtered_table WHERE ";
for (var i = 0; i < nquartiles; i++) {
bucket = "bucket" + grids[i];
sql += "\n" + (i > 0 ? "AND " : "") + "cartodb_id NOT IN (select unnest(id_list) FROM " + bucket + ") ";
}
for (var i = 0; i < nquartiles; i++) {
bucket = "bucket" + grids[i];
sql += " UNION ALL SELECT *, '" + bucket + "' as src, array_to_string(id_list, ',') cdb_list FROM " + bucket
}
return _.template(sql, {
name: table.get("name"),
//size: props["radius_min"],
size: 48,
table: "__wrapped"
});
}
|
some carto properties depends on others, this function
remove or add properties needed to carto works
|
cluster_sql
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/models/carto.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/models/carto.js
|
BSD-3-Clause
|
function cluster_generator(table, props, changed, callback) {
var methodMap = {
'2 Buckets': 2,
'3 Buckets': 3,
'4 Buckets': 4,
'5 Buckets': 5,
};
var grids = ["A", "B", "C", "D", "E"];
var nquartiles = methodMap[props['method']];
var table_name = table.getUnqualifiedName();
var sql = cluster_sql(table, props.zoom, props, nquartiles);
var c = "#" + table_name + "{\n";
c += " marker-width: " + (Math.round(props["radius_min"]/2)) + ";\n";
c += " marker-fill: " + props['marker-fill'] + ";\n";
c += " marker-line-width: 1.5;\n";
c += " marker-fill-opacity: " + props['marker-opacity'] + ";\n";
c += " marker-line-opacity: " + props['marker-line-opacity'] + ";\n";
c += " marker-line-color: " + props['marker-line-color'] + ";\n";
c += " marker-allow-overlap: true;\n";
var base = 20;
var min = props["radius_min"];
var max = props["radius_max"];
var sizes = [min];
var step = Math.round((max-min)/ (nquartiles - 1));
for (var i = 1; i < nquartiles - 1; i++) {
sizes.push(min + step * i);
}
sizes.push(max);
for (var i = 0; i < nquartiles; i++) {
c += "\n [src = 'bucket"+grids[nquartiles - i - 1]+"'] {\n";
c += " marker-line-width: " + props['marker-line-width'] + ";\n";
c += " marker-width: " + sizes[i] + ";\n";
c += " } \n";
}
c += "}\n\n";
// Generate label properties
c += "#" + table.getUnqualifiedName() + "::labels { \n";
c += " text-size: 0; \n";
c += " text-fill: " + props['text-fill'] + "; \n";
c += " text-opacity: 0.8;\n";
c += " text-name: [points_count]; \n";
c += " text-face-name: '" + props['text-face-name'] + "'; \n";
c += " text-halo-fill: " + props['text-halo-fill'] + "; \n";
c += " text-halo-radius: 0; \n";
for (var i = 0; i < nquartiles; i++) {
c += "\n [src = 'bucket"+grids[nquartiles - i - 1]+"'] {\n";
c += " text-size: " + (i * 5 + 12) + ";\n";
c += " text-halo-radius: " + props['text-halo-radius'] + ";";
c += "\n }\n";
}
c += "\n text-allow-overlap: true;\n\n";
c += " [zoom>11]{ text-size: " + Math.round(props["radius_min"] * 0.66) + "; }\n";
c += " [points_count = 1]{ text-size: 0; }\n";
c += "}\n";
callback(c, {}, sql);
}
|
some carto properties depends on others, this function
remove or add properties needed to carto works
|
cluster_generator
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/models/carto.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/models/carto.js
|
BSD-3-Clause
|
function bubble_generator(table, props, changed, callback) {
var carto_props = {
'marker-fill': props['marker-fill'],
'marker-line-color': props['marker-line-color'],
'marker-line-width': props['marker-line-width'],
'marker-line-opacity': props['marker-line-opacity'],
'marker-fill-opacity': props['marker-opacity'],
'marker-comp-op': props['marker-comp-op'],
'marker-placement': 'point',
'marker-type': 'ellipse',
'marker-allow-overlap': true,
'marker-clip':false,
'marker-multi-policy':'largest'
};
var prop = props['property'];
var min = props['radius_min'];
var max = props['radius_max'];
var fn = carto_functionMap[props['qfunction'] || DEFAULT_QFUNCTION];
if(/none/i.test(props['marker-comp-op'])) {
delete carto_props['marker-comp-op'];
}
var values = [];
var NPOINS = 10;
// TODO: make this related to the quartiles size
// instead of linear. The circle area should be related
// to the data and a little correction due to the problems
// humans have to measure the area of a circle
//calculate the bubles sizes
for(var i = 0; i < NPOINS; ++i) {
var t = i/(NPOINS-1);
values.push(min + t*(max - min));
}
// generate carto
simple_polygon_generator(table, carto_props, changed, function(css) {
var table_name = table.getUnqualifiedName();
table.data()[fn](NPOINS, prop, function(quartiles) {
for(var i = NPOINS - 1; i >= 0; --i) {
if(quartiles[i] !== undefined && quartiles[i] != null) {
css += "\n#" + table_name +" [ " + prop + " <= " + quartiles[i] + "] {\n"
css += " marker-width: " + values[i].toFixed(1) + ";\n}"
}
}
callback(css, quartiles);
});
});
}
|
some carto properties depends on others, this function
remove or add properties needed to carto works
|
bubble_generator
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/models/carto.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/models/carto.js
|
BSD-3-Clause
|
function normalizeQuartiles(quartiles) {
var maxNumber = 2147483648; // unsigned (1<<31);
var normalized = [];
for(var i = 0; i < quartiles.length; ++i) {
var q = quartiles[i];
if(q > Math.abs(maxNumber) && String(q).indexOf('.') === -1) {
q = q + ".01";
}
normalized.push(q);
}
return normalized;
}
|
when quartiles are greater than 1<<31 cast to float added .01
at the end. If you append only .0 it is casted to int and it
does not work
|
normalizeQuartiles
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/models/carto.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/models/carto.js
|
BSD-3-Clause
|
function choropleth_generator(table, props, changed, callback) {
var type = table.geomColumnTypes() && table.geomColumnTypes()[0] || "polygon";
var carto_props = manage_choropleth_props(type,props);
if(props['polygon-comp-op'] && !/none/i.test(props['polygon-comp-op'])) {
carto_props['polygon-comp-op'] = props['polygon-comp-op'];
}
if(props['line-comp-op'] && !/none/i.test(props['line-comp-op'])) {
carto_props['line-comp-op'] = props['line-comp-op'];
}
if(props['marker-comp-op'] && !/none/i.test(props['marker-comp-op'])) {
carto_props['marker-comp-op'] = props['marker-comp-op'];
}
var methodMap = {
'3 Buckets': 3,
'5 Buckets': 5,
'7 Buckets': 7
};
if(!props['color_ramp']) {
return;
}
var fn = carto_functionMap[props['qfunction'] || DEFAULT_QFUNCTION];
var prop = props['property'];
var nquartiles = methodMap[props['method']];
var ramp = cdb.admin.color_ramps[props['color_ramp']][nquartiles];
if(!ramp) {
cdb.log.error("no color ramp defined for " + nquartiles + " quartiles");
} else {
if (type == "line") {
carto_props["line-color"] = ramp[0];
} else if (type == "polygon") {
carto_props["polygon-fill"] = ramp[0];
} else {
carto_props["marker-fill"] = ramp[0];
}
}
simple_polygon_generator(table, carto_props, changed, function(css) {
var table_name = table.getUnqualifiedName();
table.data()[fn](nquartiles, prop, function(quartiles) {
quartiles = normalizeQuartiles(quartiles);
for(var i = nquartiles - 1; i >= 0; --i) {
if(quartiles[i] !== undefined && quartiles[i] != null) {
css += "\n#" + table_name +" [ " + prop + " <= " + quartiles[i] + "] {\n";
if (type == "line") {
css += " line-color: " + ramp[i] + ";\n}"
} else if (type == "polygon") {
css += " polygon-fill: " + ramp[i] + ";\n}"
} else {
css += " marker-fill: " + ramp[i] + ";\n}"
}
}
}
callback(css, quartiles);
});
});
}
|
when quartiles are greater than 1<<31 cast to float added .01
at the end. If you append only .0 it is casted to int and it
does not work
|
choropleth_generator
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/models/carto.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/models/carto.js
|
BSD-3-Clause
|
function density_sql(table, zoom, props) {
var prop = 'cartodb_id';
var sql;
// we generate a grid and get the number of points
// for each cell. With that the density is generated
// and calculated for zoom level 10, which is taken as reference when we calculate the quartiles for the style buclets
// see models/carto.js
if(props['geometry_type'] === 'Rectangles') {
sql = "WITH hgrid AS (SELECT CDB_RectangleGrid(ST_Expand(!bbox!, greatest(!pixel_width!,!pixel_height!) * <%= size %>), greatest(!pixel_width!,!pixel_height!) * <%= size %>, greatest(!pixel_width!,!pixel_height!) * <%= size %>) as cell) SELECT hgrid.cell as the_geom_webmercator, count(i.<%=prop%>) as points_count,count(i.<%=prop%>)/power( <%= size %> * CDB_XYZ_Resolution(<%= z %>), 2 ) as points_density, 1 as cartodb_id FROM hgrid, <%= table %> i where ST_Intersects(i.the_geom_webmercator, hgrid.cell) GROUP BY hgrid.cell";
} else {
sql = "WITH hgrid AS (SELECT CDB_HexagonGrid(ST_Expand(!bbox!, greatest(!pixel_width!,!pixel_height!) * <%= size %>), greatest(!pixel_width!,!pixel_height!) * <%= size %>) as cell) SELECT hgrid.cell as the_geom_webmercator, count(i.<%=prop%>) as points_count, count(i.<%=prop%>)/power( <%= size %> * CDB_XYZ_Resolution(<%= z %>), 2 ) as points_density, 1 as cartodb_id FROM hgrid, <%= table %> i where ST_Intersects(i.the_geom_webmercator, hgrid.cell) GROUP BY hgrid.cell";
}
return _.template(sql, {
prop: prop,
table: '__wrapped',
size: props['polygon-size'],
z: zoom
});
}
|
when quartiles are greater than 1<<31 cast to float added .01
at the end. If you append only .0 it is casted to int and it
does not work
|
density_sql
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/models/carto.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/models/carto.js
|
BSD-3-Clause
|
function density_generator(table, props, changed, callback) {
var carto_props = {
'line-color': props['line-color'],
'line-opacity': props['line-opacity'],
'line-width': props['line-width'],
'polygon-opacity': props['polygon-opacity'],
'polygon-comp-op': props['polygon-comp-op']
}
if(/none/i.test(props['polygon-comp-op'])) {
delete carto_props['polygon-comp-op'];
}
var methodMap = {
'3 Buckets': 3,
'5 Buckets': 5,
'7 Buckets': 7
};
var polygon_size = props['polygon-size'];
var nquartiles = methodMap[props['method']];
var ramp = cdb.admin.color_ramps[props['color_ramp']][nquartiles];
if(!ramp) {
cdb.log.error("no color ramp defined for " + nquartiles + " quartiles");
}
carto_props['polygon-fill'] = ramp[ramp.length - 1];
var density_sql_gen = density_sql(table, props.zoom, props);
simple_polygon_generator(table, carto_props, changed, function(css) {
// density
var tmpl = _.template("" +
"WITH clusters as ( " +
"SELECT " +
"cartodb_id, " +
"st_snaptogrid(the_geom_webmercator, <%= polygon_size %>*CDB_XYZ_Resolution(<%= z %>)) as center " +
"FROM <%= table_name %>" +
"), " +
"points as ( " +
"SELECT " +
"count(cartodb_id) as npoints, " +
"count(cartodb_id)/power( <%= polygon_size %> * CDB_XYZ_Resolution(<%= z %>), 2 ) as density " +
"FROM " +
"clusters " +
"group by " +
"center " +
"), " +
"stats as ( " +
"SELECT " +
"npoints, " +
"density, " +
"ntile(<%= slots %>) over (order by density) as quartile " +
"FROM points " +
") " +
"SELECT " +
"quartile, " +
"max(npoints) as maxAmount, " +
"max(density) as maxDensity " +
"FROM stats " +
"GROUP BY quartile ORDER BY quartile ");
var sql = tmpl({
slots: nquartiles,
table_name: table.get('name'),
polygon_size: polygon_size,
z: props.zoom
});
table.data()._sqlQuery(sql, function(data) {
// extract quartiles by zoom level
var rows = data.rows;
var quartiles = [];
for(var i = 0; i < rows.length; ++i) {
quartiles.push(rows[i].maxdensity);
}
quartiles = normalizeQuartiles(quartiles);
var table_name = table.getUnqualifiedName();
css += "\n#" + table_name + "{\n"
for(var i = nquartiles - 1; i >= 0; --i) {
if(quartiles[i] !== undefined) {
css += " [points_density <= " + quartiles[i] + "] { polygon-fill: " + ramp[i] + "; }\n";
}
}
css += "\n}"
callback(css, quartiles, density_sql_gen);
});
});
}
|
when quartiles are greater than 1<<31 cast to float added .01
at the end. If you append only .0 it is casted to int and it
does not work
|
density_generator
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/models/carto.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/models/carto.js
|
BSD-3-Clause
|
function searchRecursiveByType(v, t) {
var res = []
for(var i in v) {
if(v[i] instanceof t) {
res.push(v[i]);
} else if(typeof(v[i]) === 'object') {
var r = searchRecursiveByType(v[i], t);
if(r.length) {
res = res.concat(r);
}
}
}
return res;
}
|
return the error list, empty if there were no errors
|
searchRecursiveByType
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/models/carto.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/models/carto.js
|
BSD-3-Clause
|
function searchRecursiveByType(v, t) {
var res = []
for(var i in v) {
if(v[i] instanceof t) {
res.push(v[i]);
} else if(typeof(v[i]) === 'object') {
var r = searchRecursiveByType(v[i], t);
if(r.length) {
res = res.concat(r);
}
}
}
return res;
}
|
return the error list, empty if there were no errors
|
searchRecursiveByType
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/models/carto.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/models/carto.js
|
BSD-3-Clause
|
method = function(self, rule) {
return _.map(self._colorsFromRule(rule), function(f) {
return f.rgb;
})
}
|
return a list of colors used in cartocss
|
method
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/models/carto.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/models/carto.js
|
BSD-3-Clause
|
method = function(self, rule) {
return _.map(self._varsFromRule(rule), function(f) {
return f.value;
});
}
|
return a list of variables used in cartocss
|
method
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/models/carto.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/models/carto.js
|
BSD-3-Clause
|
function _hash(str){
var hash = 0, c;
for (i = 0; i < str.length; i++) {
c = str.charCodeAt(i);
hash = c + (hash << 6) + (hash << 16) - hash;
}
return hash;
}
|
when a table is linked to a infowindow each time a column
is renamed or removed the table pings to infowindow to remove
or rename the fields
|
_hash
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/models/table.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/models/table.js
|
BSD-3-Clause
|
function normalize(e) {
e = e.toLowerCase();
if (e === 'st_multipolygon') {
return 'st_polygon'
}
if (e === 'st_multilinestring') {
return 'st_linestring'
}
if (e === 'st_multipoint') {
return 'st_point'
}
return e;
}
|
this function can only be called during change event
returns true if the geometry type has changed
for this method multipolygon and polygon are the same geometry type
|
normalize
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/models/table.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/models/table.js
|
BSD-3-Clause
|
function priority(v) {
return priorities[v] || priorities['__default__'];
}
|
creates a new table from query
the called is responsable of calling save to create
the table in the server
|
priority
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/models/table.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/models/table.js
|
BSD-3-Clause
|
clampNum = function(x, min, max) {
return x < min ? min : x > max ? max : x;
}
|
call callback with the geometry bounds
|
clampNum
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/models/tabledata.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/models/tabledata.js
|
BSD-3-Clause
|
success = function() {
this.map.layers.unbind('reset', success);
this.map.layers.unbind('error', error);
callbacks && callbacks.success && callbacks.success(this);
}
|
Change current visualization by new one without
creating a new instance.
When turn table visualization to derived visualization,
it needs to wait until reset layers. If not, adding a new
layer after create the new visualization won't work...
|
success
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/models/vis.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/models/vis.js
|
BSD-3-Clause
|
error = function() {
this.map.layers.unbind('reset', success);
this.map.layers.unbind('error', error);
callbacks && callbacks.error && callbacks.error();
}
|
Change current visualization by new one without
creating a new instance.
When turn table visualization to derived visualization,
it needs to wait until reset layers. If not, adding a new
layer after create the new visualization won't work...
|
error
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/models/vis.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/models/vis.js
|
BSD-3-Clause
|
function _normalizeValue(v) {
return v.replace(/\n/g,'\\n')
// .replace(/\'/g, "\\'") // Not necessary right now becuase tiler does it itself.
.replace(/\"/g, "\\\"");
}
|
New category generator. It replaces Color wizard
|
_normalizeValue
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/models/carto/category.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/models/carto/category.js
|
BSD-3-Clause
|
function enableClickOut(el) {
el.click(function() {
cdb.god.trigger("closeDialogs");
});
}
|
enables a catch all for clicks to send singal in godbus to close all dialogs
|
enableClickOut
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/old_common/global_click.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/old_common/global_click.js
|
BSD-3-Clause
|
tabBind = function(dataLayerCid) {
var view = self.getPane(dataLayerCid);
self.trigger('switch', view);
self.vis.save('active_layer_id', view.dataLayer.id);
self.show(view.panels.activeTab);
self.unbind('tabEnabled', tabBind);
}
|
Actions menu view, aka LayersPanel
- It needs at least visualization and user models.
Globalerror to show connection or fetching errors.
var menu = new cdb.admin.LayersPanel({
vis: vis_model,
user: user_model,
globalError: globalError_obj
});
|
tabBind
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/table/actions_menu.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/table/actions_menu.js
|
BSD-3-Clause
|
function GrouperLayerMapView(mapViewClass) {
return {
initialize: function() {
this.groupLayer = null;
this.activeLayerModel = null;
mapViewClass.prototype.initialize.call(this);
},
_removeLayers: function() {
var self = this;
_.each(this.map.layers.getLayersByType('CartoDB'), function(layer) {
layer.unbind(null, null, self);
});
cdb.geo.MapView.prototype._removeLayers.call(this);
if(this.groupLayer) {
this.groupLayer.model.unbind();
}
this.groupLayer = null;
},
_removeLayer: function(layer) {
// if the layer is in layergroup
if(layer.cid in this.layers) {
if(this.layers[layer.cid] === this.groupLayer) {
this._updateLayerDefinition(layer);
layer.unbind(null, null, this);
delete this.layers[layer.cid];
this.trigger('removeLayerView', this);
} else {
this.trigger('removeLayerView', this);
cdb.geo.MapView.prototype._removeLayer.call(this, layer);
}
} else {
cdb.log.info("removing non existing layer");
}
},
setActiveLayer: function(layer) {
this.activeLayerModel = layer;
this._setInteraction();
},
disableInteraction: function() {
if (this.groupLayer) {
this.groupLayer._clearInteraction();
}
},
enableInteraction: function() {
this._setInteraction();
},
// set interaction only for the active layer
_setInteraction: function() {
if(!this.groupLayer) return;
if(this.activeLayerModel) {
this.groupLayer._clearInteraction();
var idx = this.map.layers.getLayerDefIndex(this.activeLayerModel);
// when layer is not found idx == -1 so the interaction is
// disabled for all the layers
for(var i = 0; i < this.groupLayer.getLayerCount(); ++i) {
this.groupLayer.setInteraction(i, i == idx);
}
}
},
_updateLayerDefinition: function(layer) {
if(!layer) throw "layer must be a valid layer (not null)";
if(this.groupLayer) {
if(this.map.layers.getLayersByType('CartoDB').length === 0) {
this.groupLayer.remove();
this.groupLayer = null;
} else {
var def = this.map.layers.getLayerDef();
this.groupLayer.setLayerDefinition(def);
this._setInteraction();
}
}
},
/**
* when merged layers raises an error this function send the error to the
* layer that actually caused it
*/
_routeErrors: function(errors) {
var styleRegExp = /style(\d+)/;
var postgresExp = /layer(\d+):/i;
var generalPostgresExp = /PSQL error/i;
var syntaxErrorExp = /syntax error/i;
var webMercatorErrorExp = /"the_geom_webmercator" does not exist/i;
var tilerError = /Error:/i;
var layers = this.map.layers.where({ visible: true, type: 'CartoDB' });
for(var i in errors) {
var err = errors[i];
// filter empty errors
if(err && err.length) {
var match = styleRegExp.exec(err);
if(match) {
var layerIndex = parseInt(match[1], 10);
layers[layerIndex].trigger('parseError', [err]);
} else {
var match = postgresExp.exec(err);
if(match) {
var layerIndex = parseInt(match[1], 10);
if (webMercatorErrorExp.exec(err)) {
err = _t("you should select the_geom_webmercator column");
layers[layerIndex].trigger('sqlNoMercator', [err]);
} else {
layers[layerIndex].trigger('sqlParseError', [err]);
}
} else if(generalPostgresExp.exec(err) || syntaxErrorExp.exec(err) || tilerError.exec(err)) {
var error = 'sqlError';
if (webMercatorErrorExp.exec(err)) {
error = 'sqlNoMercator';
err = _t("you should select the_geom_webmercator column");
}
_.each(layers, function(lyr) { lyr.trigger(error, err); });
} else {
_.each(layers, function(lyr) { lyr.trigger('error', err); });
}
}
}
}
},
_routeSignal: function(signal) {
var self = this;
return function() {
var layers = self.map.layers.where({ visible: true, type: 'CartoDB' });
var args = [signal].concat(arguments);
_.each(layers, function(lyr) { lyr.trigger.apply(lyr, args); });
}
},
_addLayer: function(layer, layers, opts) {
opts = opts || {};
// create group layer to acumulate cartodb layers
if (layer.get('type') === 'CartoDB') {
var self = this;
if(!this.groupLayer) {
// create model
var m = new cdb.geo.CartoDBGroupLayer(
_.extend(layer.toLayerGroup(), {
user_name: this.options.user.get("username"),
maps_api_template: cdb.config.get('maps_api_template'),
no_cdn: false,
force_cors: true // use CORS to control error management in a better way
})
);
var layer_view = mapViewClass.prototype._addLayer.call(this, m, layers, _.extend({}, opts, { silent: true }));
delete this.layers[m.cid];
this.layers[layer.cid] = layer_view;
this.groupLayer = layer_view;
m.bind('error', this._routeErrors, this);
m.bind('tileOk', this._routeSignal('tileOk'), this);
this.trigger('newLayerView', layer_view, layer, this);
} else {
this.layers[layer.cid] = this.groupLayer;
this._updateLayerDefinition(layer);
this.trigger('newLayerView', this.groupLayer, layer, this);
}
layer.bind('change:tile_style change:query change:query_wrapper change:interactivity change:visible', this._updateLayerDefinition, this);
this._addLayerToMap(this.groupLayer, opts);
delete this.layers[this.groupLayer.model.cid];
} else {
mapViewClass.prototype._addLayer.call(this, layer, layers, opts);
}
}
}
}
|
inside the UI all the cartodb layers should be shown merged.
the problem is that the editor needs the layers separated to work
with them so this class transform from multiple cartodb layers
and create only a view to represent all merged in a single layer group
|
GrouperLayerMapView
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/table/mapview.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/table/mapview.js
|
BSD-3-Clause
|
onBackgroundShown = function() {
$map.animate(
{ width: width, marginLeft: -Math.round(width/2) - 1, left: "50%" },
{ easing: "easeOutQuad", duration: 200, complete: onCanvasLandscapeStretched }
);
}
|
when the layer view is created this method is called
to attach all the click events
|
onBackgroundShown
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/table/mapview.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/table/mapview.js
|
BSD-3-Clause
|
onCanvasPortraitStretched = function() {
self.$el.find(".mobile_bkg").animate(
{ opacity: 1 },
{ duration: 250 }
);
self.overlays._showOverlays(mode);
// Let's set center view for mobile mode
var center = self.map.get('center');
self.mapView.invalidateSize();
$map.fadeOut(250);
setTimeout(function() {
self.mapView.map.setCenter(center);
$map.fadeIn(250);
},300);
}
|
when the layer view is created this method is called
to attach all the click events
|
onCanvasPortraitStretched
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/table/mapview.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/table/mapview.js
|
BSD-3-Clause
|
onCanvasLandscapeStretched = function() {
$map.animate(
{ height: height, marginTop: -Math.round(height/2) + 23, top: "50%" },
{ easing: "easeOutQuad", duration: 200, complete: onCanvasPortraitStretched }
);
}
|
when the layer view is created this method is called
to attach all the click events
|
onCanvasLandscapeStretched
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/table/mapview.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/table/mapview.js
|
BSD-3-Clause
|
onSecondAnimationFinished = function() {
$map.css('width', 'auto');
self.overlays._showOverlays(mode);
// Let's set center view for desktop mode
var center = self.map.get('center');
self.mapView.invalidateSize();
setTimeout(function() {
self.mapView.map.setCenter(center);
},300);
}
|
when the layer view is created this method is called
to attach all the click events
|
onSecondAnimationFinished
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/table/mapview.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/table/mapview.js
|
BSD-3-Clause
|
onFirstAnimationFinished = function() {
$map.css('height', 'auto');
$map.animate(
{ width: autoWidth, left: "15px", marginLeft: "0"},
{ easing: "easeOutQuad", duration: 200, complete: onSecondAnimationFinished }
);
}
|
when the layer view is created this method is called
to attach all the click events
|
onFirstAnimationFinished
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/table/mapview.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/table/mapview.js
|
BSD-3-Clause
|
stretchMapLandscape = function() {
$map.animate(
{ height: autoHeight, top: "82", marginTop: "0"},
{ easing: "easeOutQuad", duration: 200, complete: onFirstAnimationFinished }
);
}
|
when the layer view is created this method is called
to attach all the click events
|
stretchMapLandscape
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/table/mapview.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/table/mapview.js
|
BSD-3-Clause
|
function setPermissions() {
// check permissions to set read only
table.setReadOnly(!table.permission.hasWriteAccess(self.user));
}
|
Bind the keystrokes associated with menu actions
alt + <- : show right menu
alt + -> : hide right menu
alt + c : toggle carto
alt + s : toggle sql
@method keyBind
|
setPermissions
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/table/table_editor_view.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/table/table_editor_view.js
|
BSD-3-Clause
|
function toVis(new_id) {
self.table.master_vis
.set('id', new_id)
.fetch({
wait: true,
success: function(vis) {
// Get related tables if it is necessary
vis.getRelatedTables();
self.table.hideLoader();
},
error: function() {
self.table.hideLoader();
self.table.globalError.showError(self._TEXTS.error, "error", 5000);
}
});
}
|
New table router \o/
- No more /#/xxx routes
- Control if current visualization is a table or a viz
|
toVis
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/table/table_router.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/table/table_router.js
|
BSD-3-Clause
|
function proxyModel(m, fn) {
var proxyModel = new Backbone.Model();
proxyModel.set(m.attributes);
var signalDisabled = false;
fn = fn || function() {
m.set(proxyModel.attributes);
}
m.bind('change', function() {
signalDisabled = true;
proxyModel.set(m.attributes);
signalDisabled = false;
}, proxyModel);
proxyModel.bind('change', function() {
if (signalDisabled) return;
fn(m, proxyModel);
}, m);
proxyModel.unlink = function() {
m.unbind(null, null, proxyModel);
proxyModel.unbind(null, null, m);
}
return proxyModel;
}
|
this method creates a new Model in sync with the specicied one. Also takes a method to be executed every time the proxy model changes
returns the proxy model, an instance of Backbone.Model, it's not an instance of original model
|
proxyModel
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/table/slides/transition_dropdown.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/table/slides/transition_dropdown.js
|
BSD-3-Clause
|
function _save() {
m.set(proxy.attributes);
self.vis.save();
}
|
this method creates a new Model in sync with the specicied one. Also takes a method to be executed every time the proxy model changes
returns the proxy model, an instance of Backbone.Model, it's not an instance of original model
|
_save
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/cartodb/table/slides/transition_dropdown.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/cartodb/table/slides/transition_dropdown.js
|
BSD-3-Clause
|
toggleUserQuotas = function () {
const viewer = $('.js-userViewerOption:checked').val();
if (viewer === 'true') {
$('.user-quotas').hide();
$('.js-org-admin-row').hide();
$('#org_admin').prop('checked', false);
} else {
$('.user-quotas').show();
$('.js-org-admin-row').show();
}
}
|
Entry point for the new organization, bootstraps all
dependency models and application.
|
toggleUserQuotas
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/dashboard/organization.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/dashboard/organization.js
|
BSD-3-Clause
|
toggleUserQuotas = function () {
const viewer = $('.js-userViewerOption:checked').val();
if (viewer === 'true') {
$('.user-quotas').hide();
$('.js-org-admin-row').hide();
$('#org_admin').prop('checked', false);
} else {
$('.user-quotas').show();
$('.js-org-admin-row').show();
}
}
|
Entry point for the new organization, bootstraps all
dependency models and application.
|
toggleUserQuotas
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/dashboard/organization.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/dashboard/organization.js
|
BSD-3-Clause
|
regenerateApiKeyHandler = function (event, scope, form_action) {
if (event) event.preventDefault();
const authenticity_token = $('[name=authenticity_token][value]').get(0).value;
modalsService.create(modalModel => (
new RegenerateKeysDialog({
type: 'api',
scope,
form_action,
authenticity_token,
modalModel,
passwordNeeded: userModel.needsPasswordConfirmation()
})
));
}
|
Entry point for the new organization, bootstraps all
dependency models and application.
|
regenerateApiKeyHandler
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/dashboard/organization.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/dashboard/organization.js
|
BSD-3-Clause
|
regenerateApiKeyHandler = function (event, scope, form_action) {
if (event) event.preventDefault();
const authenticity_token = $('[name=authenticity_token][value]').get(0).value;
modalsService.create(modalModel => (
new RegenerateKeysDialog({
type: 'api',
scope,
form_action,
authenticity_token,
modalModel,
passwordNeeded: userModel.needsPasswordConfirmation()
})
));
}
|
Entry point for the new organization, bootstraps all
dependency models and application.
|
regenerateApiKeyHandler
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/dashboard/organization.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/dashboard/organization.js
|
BSD-3-Clause
|
listenToExpirationSettingsChanges = function () {
const expirationInput = $('#organization_password_expiration_in_d');
const unlimitedExpirationInput = $('#unlimited_password_expiration');
unlimitedExpirationInput.change(function () {
const isChecked = this.checked;
isChecked ? expirationInput.attr('disabled', 'disabled') : expirationInput.removeAttr('disabled');
expirationInput.val(null);
});
}
|
Entry point for the new organization, bootstraps all
dependency models and application.
|
listenToExpirationSettingsChanges
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/dashboard/organization.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/dashboard/organization.js
|
BSD-3-Clause
|
listenToExpirationSettingsChanges = function () {
const expirationInput = $('#organization_password_expiration_in_d');
const unlimitedExpirationInput = $('#unlimited_password_expiration');
unlimitedExpirationInput.change(function () {
const isChecked = this.checked;
isChecked ? expirationInput.attr('disabled', 'disabled') : expirationInput.removeAttr('disabled');
expirationInput.val(null);
});
}
|
Entry point for the new organization, bootstraps all
dependency models and application.
|
listenToExpirationSettingsChanges
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/dashboard/organization.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/dashboard/organization.js
|
BSD-3-Clause
|
function dataLoaded (data) {
const {user_data, organization_notifications} = data;
const configModel = new ConfigModel(
_.extend(
{ url_prefix: user_data.base_url,
base_url: user_data.base_url },
data.config
)
);
const userModelOptions = { };
if (user_data.organization) {
userModelOptions.organization = new OrganizationModel(user_data.organization, { configModel });
}
const currentUser = new UserModel(
_.extend(user_data, {
can_change_email: data.can_change_email,
logged_with_google: false,
google_enabled: false,
plan_url: data.plan_url
}),
userModelOptions
);
document.title = 'Your profile | CARTO';
new ProfileMainView({ // eslint-disable-line
el: document.body,
userModel: currentUser,
configModel,
modals,
organizationNotifications: organization_notifications,
assetsVersion: ASSETS_VERSION
});
}
|
Entry point for the new keys, bootstraps all dependency models and application.
|
dataLoaded
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/dashboard/profile.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/dashboard/profile.js
|
BSD-3-Clause
|
GAPusher = function (opts) {
var ga = window.ga;
opts = opts || {};
if (ga) {
ga(opts.eventName || 'send', {
hitType: opts.hitType,
eventCategory: opts.eventCategory,
eventAction: opts.eventAction,
eventLabel: opts.eventLabel
});
}
}
|
Send events to Google Analytics if it is available
- https://developers.google.com/analytics/devguides/collection/analyticsjs/sending-hits
*Remove this "helper" when dashboard is deprecated
|
GAPusher
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/dashboard/common/analytics-pusher.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/dashboard/common/analytics-pusher.js
|
BSD-3-Clause
|
clampNum = function (x, min, max) {
return x < min ? min : x > max ? max : x;
}
|
call callback with the geometry bounds
|
clampNum
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/dashboard/data/table/carto-table-data.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/dashboard/data/table/carto-table-data.js
|
BSD-3-Clause
|
BytesToSize = function (bytes) {
if (!(this instanceof BytesToSize)) return new BytesToSize(bytes);
this.bytes = bytes;
if (bytes === 0) {
this.unit = 0;
} else {
this.unit = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
}
return this;
}
|
Object representing human-readable version of a given number of bytes.
(Extracted logic from an old dashboard view)
@param bytes {Number}
@returns {Object}
|
BytesToSize
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/dashboard/helpers/bytes-to-size.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/dashboard/helpers/bytes-to-size.js
|
BSD-3-Clause
|
BytesToSize = function (bytes) {
if (!(this instanceof BytesToSize)) return new BytesToSize(bytes);
this.bytes = bytes;
if (bytes === 0) {
this.unit = 0;
} else {
this.unit = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
}
return this;
}
|
Object representing human-readable version of a given number of bytes.
(Extracted logic from an old dashboard view)
@param bytes {Number}
@returns {Object}
|
BytesToSize
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/dashboard/helpers/bytes-to-size.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/dashboard/helpers/bytes-to-size.js
|
BSD-3-Clause
|
LocalStorageWrapper = function (name) {
this.name = name || 'cartodb';
if (!localStorage.getItem(this.name) && this.isEnabled()) {
localStorage.setItem(this.name, '{}');
}
}
|
Local storage wrapper
- It should be used within 'cartodb' key, for example:
var loc_sto = new cdb.common.LocalStorage();
loc_sto.set({ 'dashboard.order': 'create_at' });
loc_sto.get('dashboard.order');
|
LocalStorageWrapper
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/dashboard/helpers/local-storage.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/dashboard/helpers/local-storage.js
|
BSD-3-Clause
|
function canChangeToPrivate (userModel, currentPrivacy, option) {
return currentPrivacy !== 'PRIVATE' && option.privacy === 'PRIVATE' && userModel.hasRemainingPrivateMaps();
}
|
type property should match the value given from the API.
|
canChangeToPrivate
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/dashboard/views/dashboard/dialogs/change-privacy/options-collection.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/dashboard/views/dashboard/dialogs/change-privacy/options-collection.js
|
BSD-3-Clause
|
function canChangeToPublic (userModel, currentPrivacy, option) {
return currentPrivacy !== 'PRIVATE' || currentPrivacy === 'PRIVATE' && option.privacy !== 'PRIVATE' && userModel.hasRemainingPublicMaps();
}
|
type property should match the value given from the API.
|
canChangeToPublic
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/dashboard/views/dashboard/dialogs/change-privacy/options-collection.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/dashboard/views/dashboard/dialogs/change-privacy/options-collection.js
|
BSD-3-Clause
|
function _hash (str) {
var hash = 0;
var c;
var i;
for (i = 0; i < str.length; i++) {
c = str.charCodeAt(i);
hash = c + (hash << 6) + (hash << 16) - hash;
}
return hash;
}
|
when a table is linked to a infowindow each time a column
is renamed or removed the table pings to infowindow to remove
or rename the fields
|
_hash
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/dashboard/views/public-dataset/carto-table-metadata.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/dashboard/views/public-dataset/carto-table-metadata.js
|
BSD-3-Clause
|
function normalize (e) {
e = e.toLowerCase();
if (e === 'st_multipolygon') {
return 'st_polygon';
}
if (e === 'st_multilinestring') {
return 'st_linestring';
}
if (e === 'st_multipoint') {
return 'st_point';
}
return e;
}
|
this function can only be called during change event
returns true if the geometry type has changed
for this method multipolygon and polygon are the same geometry type
|
normalize
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/dashboard/views/public-dataset/carto-table-metadata.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/dashboard/views/public-dataset/carto-table-metadata.js
|
BSD-3-Clause
|
WidgetsService = function (widgetsCollection, dataviews) {
this._widgetsCollection = widgetsCollection;
this._dataviews = dataviews;
}
|
Public API to interact with dashboard widgets.
|
WidgetsService
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/deep-insights/widgets-service.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/deep-insights/widgets-service.js
|
BSD-3-Clause
|
createDashboard = function (selector, vizJSON, opts, callback) {
var dashboardEl = document.querySelector(selector);
if (!dashboardEl) throw new Error('no element found with selector ' + selector);
// Default options
opts = opts || {};
opts.renderMenu = _.isBoolean(opts.renderMenu)
? opts.renderMenu
: true;
opts.autoStyle = _.isBoolean(opts.autoStyle)
? opts.autoStyle
: false;
var widgets = new WidgetsCollection();
var model = new cdb.core.Model({
title: vizJSON.title,
description: vizJSON.description,
updatedAt: vizJSON.updated_at,
userName: vizJSON.user.fullname,
userProfileURL: vizJSON.user.profile_url,
userAvatarURL: vizJSON.user.avatar_url,
renderMenu: opts.renderMenu,
autoStyle: opts.autoStyle,
showLogo: opts.cartodb_logo,
initialPosition: {
bounds: vizJSON.bounds
}
});
var dashboardView = new DashboardView({
el: dashboardEl,
widgets: widgets,
model: model
});
var dashboardState = opts.state || URLHelper.getStateFromCurrentURL();
if (dashboardState && !_.isEmpty(dashboardState.map)) {
if (_.isArray(dashboardState.map.center)) {
vizJSON.center = dashboardState.map.center;
}
if (_.isNumber(dashboardState.map.zoom)) {
vizJSON.zoom = dashboardState.map.zoom;
}
if (dashboardState.map.ne && dashboardState.map.sw) {
vizJSON.bounds = [dashboardState.map.ne, dashboardState.map.sw];
}
}
var vis = cdb.createVis(dashboardView.$('#map'), vizJSON, _.extend(opts, {
skipMapInstantiation: true
}));
vis.once('load', function (vis) {
var widgetsState = (dashboardState && dashboardState.widgets) || {};
// Create widgets
var widgetsService = new WidgetsService(widgets, vis.dataviews);
var widgetModelsMap = {
formula: widgetsService.createFormulaModel.bind(widgetsService),
histogram: widgetsService.createHistogramModel.bind(widgetsService),
'time-series': widgetsService.createTimeSeriesModel.bind(widgetsService),
category: widgetsService.createCategoryModel.bind(widgetsService)
};
vizJSON.widgets.forEach(function (widget) {
// Flatten the data structure given in vizJSON, the widgetsService will use whatever it needs and ignore the rest
var attrs = _.extend({}, widget, widget.options);
var newWidgetModel = widgetModelsMap[widget.type];
var state = widgetsState[widget.id];
if (_.isFunction(newWidgetModel)) {
// Find the Layer that the Widget should be created for.
var layer;
var source;
if (widget.layer_id) {
layer = vis.map.layers.get(widget.layer_id);
} else if (Number.isInteger(widget.layerIndex)) {
// TODO Since namedmap doesn't have ids we need to map in another way, here using index
// should we solve this in another way?
layer = vis.map.layers.at(widget.layerIndex);
}
if (widget.source && widget.source.id) {
source = vis.analysis.findNodeById(widget.source.id);
attrs.source = source;
}
newWidgetModel(attrs, layer, state);
} else {
cdb.log.error('No widget found for type ' + widget.type);
}
});
dashboardView.render();
var callbackObj = {
dashboardView: dashboardView,
widgets: widgetsService,
areWidgetsInitialised: function () {
var widgetsCollection = widgetsService.getCollection();
if (widgetsCollection.size() > 0) {
return widgetsCollection.hasInitialState();
}
return true;
},
vis: vis
};
vis.instantiateMap({
success: function () {
callback && callback(null, callbackObj);
},
error: function (errorMessage) {
callback && callback(new Error(errorMessage), callbackObj);
}
});
});
}
|
Translates a vizJSON v3 datastructure into a working dashboard which will be rendered in given selector.
@param {String} selector e.g. "#foobar-id", ".some-class"
@param {Object} vizJSON JSON datastructure
@param {Object} opts (Optional) flags, see 3rd param for cdb.createVis for available ones. Keys used here:
renderMenu: {Boolean} If true (default), render a top-level menu on the left side.
@return {Object} with keys:
dashboardView: root (backbone) view of the dashboard
vis: the instantiated vis map, same result as given from cdb.createVis()
|
createDashboard
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/deep-insights/api/create-dashboard.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/deep-insights/api/create-dashboard.js
|
BSD-3-Clause
|
function _load (vizJSON) {
createDashboard(selector, vizJSON, opts, function (error, dashboard) {
var _dashboard = new Dashboard(dashboard);
if (opts.share_urls) {
_dashboard.onStateChanged(
_.debounce(
function (state, url) {
window.history.replaceState('Object', 'Title', url);
},
500
)
);
}
callback && callback(error, _dashboard);
});
}
|
Translates a vizJSON v3 datastructure into a working dashboard which will be rendered in given selector.
@param {String} selector e.g. "#foobar-id", ".some-class"
@param {Object} vizJSON JSON datastructure
@param {Object} opts (Optional) flags, see 3rd param for cdb.createVis for available ones. Keys used here:
renderMenu: {Boolean} If true (default), render a top-level menu on the left side.
@return {Object} with keys:
dashboardView: root (backbone) view of the dashboard
vis: the instantiated vis map, same result as given from cdb.createVis()
|
_load
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/deep-insights/api/create-dashboard.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/deep-insights/api/create-dashboard.js
|
BSD-3-Clause
|
function changeStyle (cartocss, attr, newStyle) {
if (_.isUndefined(newStyle)) return cartocss;
var cssTree = generateCSSTreeFromCartoCSS(cartocss);
var root = cssTree.result.root;
var attributeAlreadyChanged = false;
if (root) {
root.walkDecls(attr, function (node) {
var parentNode = node.parent;
if (!(isOutlineRule(parentNode) && _.contains(OUTLINE_ATTRS, attr))) {
if (isSelectorRule(parentNode) || attributeAlreadyChanged) {
// If the attribute is inside a conditional selection, it has to be removed
node.remove();
} else {
// If the attribute is inside a regular root (or symbolizer), it just
// changes the value
node.value = newStyle;
attributeAlreadyChanged = true;
}
}
});
return cssTree.css;
}
return cartocss;
}
|
Change attr style and remove all the duplicates
@param {String} cartocss cartocss original String
@param {String} attr CSS Attribute ex, polygon-fill
@param {String} newStyle New style value ex, red;
@return {String} Cartocss modified String
|
changeStyle
|
javascript
|
CartoDB/cartodb
|
lib/assets/javascripts/deep-insights/widgets/auto-style/style-utils.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/javascripts/deep-insights/widgets/auto-style/style-utils.js
|
BSD-3-Clause
|
function getGlobal() {
return this;
}
|
By default exceptions thrown in the context of a test are caught by jasmine so that it can run the remaining tests in the suite.
Set to false to let the exception bubble up in the browser.
|
getGlobal
|
javascript
|
CartoDB/cartodb
|
lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
BSD-3-Clause
|
spyObj = function() {
spyObj.wasCalled = true;
spyObj.callCount++;
var args = jasmine.util.argsToArray(arguments);
spyObj.mostRecentCall.object = this;
spyObj.mostRecentCall.args = args;
spyObj.argsForCall.push(args);
spyObj.calls.push({object: this, args: args});
return spyObj.plan.apply(this, arguments);
}
|
Resets all of a spy's the tracking variables so that it can be used again.
@example
spyOn(foo, 'bar');
foo.bar();
expect(foo.bar.callCount).toEqual(1);
foo.bar.reset();
expect(foo.bar.callCount).toEqual(0);
|
spyObj
|
javascript
|
CartoDB/cartodb
|
lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
BSD-3-Clause
|
spyOn = function(obj, methodName) {
return jasmine.getEnv().currentSpec.spyOn(obj, methodName);
}
|
Function that installs a spy on an existing object's method name. Used within a Spec to create a spy.
@example
// spy example
var foo = {
not: function(bool) { return !bool; }
}
spyOn(foo, 'not'); // actual foo.not will not be called, execution stops
@see jasmine.createSpy
@param obj
@param methodName
@return {jasmine.Spy} a Jasmine spy that can be chained with all spy methods
|
spyOn
|
javascript
|
CartoDB/cartodb
|
lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
BSD-3-Clause
|
it = function(desc, func) {
return jasmine.getEnv().it(desc, func);
}
|
Creates a Jasmine spec that will be added to the current suite.
// TODO: pending tests
@example
it('should be true', function() {
expect(true).toEqual(true);
});
@param {String} desc description of this specification
@param {Function} func defines the preconditions and expectations of the spec
|
it
|
javascript
|
CartoDB/cartodb
|
lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
BSD-3-Clause
|
xit = function(desc, func) {
return jasmine.getEnv().xit(desc, func);
}
|
Creates a <em>disabled</em> Jasmine spec.
A convenience method that allows existing specs to be disabled temporarily during development.
@param {String} desc description of this specification
@param {Function} func defines the preconditions and expectations of the spec
|
xit
|
javascript
|
CartoDB/cartodb
|
lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
BSD-3-Clause
|
expect = function(actual) {
return jasmine.getEnv().currentSpec.expect(actual);
}
|
Starts a chain for a Jasmine expectation.
It is passed an Object that is the actual value and should chain to one of the many
jasmine.Matchers functions.
@param {Object} actual Actual value to test against and expected value
@return {jasmine.Matchers}
|
expect
|
javascript
|
CartoDB/cartodb
|
lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
BSD-3-Clause
|
waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) {
jasmine.getEnv().currentSpec.waitsFor.apply(jasmine.getEnv().currentSpec, arguments);
}
|
Waits for the latchFunction to return true before proceeding to the next block.
@param {Function} latchFunction
@param {String} optional_timeoutMessage
@param {Number} optional_timeout
|
waitsFor
|
javascript
|
CartoDB/cartodb
|
lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
BSD-3-Clause
|
describe = function(description, specDefinitions) {
return jasmine.getEnv().describe(description, specDefinitions);
}
|
Defines a suite of specifications.
Stores the description and all defined specs in the Jasmine environment as one suite of specs. Variables declared
are accessible by calls to beforeEach, it, and afterEach. Describe blocks can be nested, allowing for specialization
of setup in some tests.
@example
// TODO: a simple suite
// TODO: a simple suite with a nested describe block
@param {String} description A string, usually the class under test.
@param {Function} specDefinitions function that defines several specs.
|
describe
|
javascript
|
CartoDB/cartodb
|
lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
BSD-3-Clause
|
xdescribe = function(description, specDefinitions) {
return jasmine.getEnv().xdescribe(description, specDefinitions);
}
|
Disables a suite of specifications. Used to disable some suites in a file, or files, temporarily during development.
@param {String} description A string, usually the class under test.
@param {Function} specDefinitions function that defines several specs.
|
xdescribe
|
javascript
|
CartoDB/cartodb
|
lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
BSD-3-Clause
|
function tryIt(f) {
try {
return f();
} catch(e) {
}
return null;
}
|
Disables a suite of specifications. Used to disable some suites in a file, or files, temporarily during development.
@param {String} description A string, usually the class under test.
@param {Function} specDefinitions function that defines several specs.
|
tryIt
|
javascript
|
CartoDB/cartodb
|
lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
BSD-3-Clause
|
hasKey = function(obj, keyName) {
return obj !== null && obj[keyName] !== jasmine.undefined;
}
|
Register a reporter to receive status updates from Jasmine.
@param {jasmine.Reporter} reporter An object which will receive status updates.
|
hasKey
|
javascript
|
CartoDB/cartodb
|
lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
BSD-3-Clause
|
hasKey = function(obj, keyName) {
return obj != null && obj[keyName] !== jasmine.undefined;
}
|
Matcher that checks that the expected exception was thrown by the actual.
@param {String} [expected]
|
hasKey
|
javascript
|
CartoDB/cartodb
|
lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
BSD-3-Clause
|
onComplete = function () {
if (jasmine.Queue.LOOP_DONT_RECURSE && calledSynchronously) {
completedSynchronously = true;
return;
}
if (self.blocks[self.index].abort) {
self.abort = true;
}
self.offset = 0;
self.index++;
var now = new Date().getTime();
if (self.env.updateInterval && now - self.env.lastUpdate > self.env.updateInterval) {
self.env.lastUpdate = now;
self.env.setTimeout(function() {
self.next_();
}, 0);
} else {
if (jasmine.Queue.LOOP_DONT_RECURSE && completedSynchronously) {
goAgain = true;
} else {
self.next_();
}
}
}
|
Formats a value in a nice, human-readable string.
@param value
|
onComplete
|
javascript
|
CartoDB/cartodb
|
lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
BSD-3-Clause
|
newMatchersClass = function() {
parent.apply(this, arguments);
}
|
Waits for the latchFunction to return true before proceeding to the next block.
@param {Function} latchFunction
@param {String} optional_timeoutMessage
@param {Number} optional_timeout
|
newMatchersClass
|
javascript
|
CartoDB/cartodb
|
lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/test/lib/jasmine-1.3.1/jasmine.js
|
BSD-3-Clause
|
function flatten_views(view) {
var flatten = [];
var sub = view._subviews;
flatten.push(view);
for(var k in sub) {
var v = sub[k];
flatten.push(v);
flatten= flatten.concat(flatten_views(v));
}
return flatten;
}
|
Reset a table with nElements empty rows
@param {cdb.admin.CartoDBTableMetadata} table
@param {integer} nElements
|
flatten_views
|
javascript
|
CartoDB/cartodb
|
lib/assets/test/spec/SpecHelper.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/test/spec/SpecHelper.js
|
BSD-3-Clause
|
function evented_objects(obj) {
var ev = [];
for(var k in obj) {
var o = obj[k];
if( k !== '_parent' && o && obj.hasOwnProperty(k) && o._callbacks ) {
ev.push(o);
}
}
return ev;
}
|
Reset a table with nElements empty rows
@param {cdb.admin.CartoDBTableMetadata} table
@param {integer} nElements
|
evented_objects
|
javascript
|
CartoDB/cartodb
|
lib/assets/test/spec/SpecHelper.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/test/spec/SpecHelper.js
|
BSD-3-Clause
|
function callback_context(o) {
var c = [];
var callbacks = o._callbacks;
for(var i in callbacks) {
var node = callbacks[i];
var end = node.tail;
while ((node = node.next) !== end) {
if (node.context) {
c.push(node.context.cid);
}
}
}
return c;
}
|
Reset a table with nElements empty rows
@param {cdb.admin.CartoDBTableMetadata} table
@param {integer} nElements
|
callback_context
|
javascript
|
CartoDB/cartodb
|
lib/assets/test/spec/SpecHelper.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/test/spec/SpecHelper.js
|
BSD-3-Clause
|
function already_linked() {
var linked = [];
// check no pending callbacks
for (var k in views) {
var v = views[k];
var objs = evented_objects(v);
for(var o in objs) {
if (_.include(callback_context(objs[o]), v.cid)) {
linked.push(v);
}
}
}
return linked;
}
|
Reset a table with nElements empty rows
@param {cdb.admin.CartoDBTableMetadata} table
@param {integer} nElements
|
already_linked
|
javascript
|
CartoDB/cartodb
|
lib/assets/test/spec/SpecHelper.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/test/spec/SpecHelper.js
|
BSD-3-Clause
|
function flatten_views (view) {
var flatten = [];
var sub = view._subviews;
flatten.push(view);
for (var k in sub) {
var v = sub[k];
flatten.push(v);
flatten = flatten.concat(flatten_views(v));
}
return flatten;
}
|
Utilities to help the tests
@type {Object}
|
flatten_views
|
javascript
|
CartoDB/cartodb
|
lib/assets/test/spec/SpecHelper3.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/test/spec/SpecHelper3.js
|
BSD-3-Clause
|
function evented_objects (obj) {
var ev = [];
for (var k in obj) {
var o = obj[k];
if (k !== '_parent' && o && obj.hasOwnProperty(k) && o._callbacks) {
ev.push(o);
}
}
return ev;
}
|
Utilities to help the tests
@type {Object}
|
evented_objects
|
javascript
|
CartoDB/cartodb
|
lib/assets/test/spec/SpecHelper3.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/test/spec/SpecHelper3.js
|
BSD-3-Clause
|
function callback_context (o) {
var c = [];
var callbacks = o._callbacks;
for (var i in callbacks) {
var node = callbacks[i];
var end = node.tail;
while ((node = node.next) !== end) {
if (node.context) {
c.push(node.context.cid);
}
}
}
return c;
}
|
Utilities to help the tests
@type {Object}
|
callback_context
|
javascript
|
CartoDB/cartodb
|
lib/assets/test/spec/SpecHelper3.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/test/spec/SpecHelper3.js
|
BSD-3-Clause
|
function already_linked () {
var linked = [];
// check no pending callbacks
for (var k in views) {
var v = views[k];
var objs = evented_objects(v);
for (var o in objs) {
if (_.include(callback_context(objs[o]), v.cid)) {
linked.push(v);
}
}
}
return linked;
}
|
Utilities to help the tests
@type {Object}
|
already_linked
|
javascript
|
CartoDB/cartodb
|
lib/assets/test/spec/SpecHelper3.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/assets/test/spec/SpecHelper3.js
|
BSD-3-Clause
|
function Context(view, parent) {
this.view = view;
this.parent = parent;
this.clearCache();
}
|
Skips all text until the given regular expression can be matched. Returns
the skipped string, which is the entire tail if no match can be made.
|
Context
|
javascript
|
CartoDB/cartodb
|
lib/build/mustache.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/build/mustache.js
|
BSD-3-Clause
|
scopedRender = function (template) {
return self.render(template, context);
}
|
Skips all text until the given regular expression can be matched. Returns
the skipped string, which is the entire tail if no match can be made.
|
scopedRender
|
javascript
|
CartoDB/cartodb
|
lib/build/mustache.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/build/mustache.js
|
BSD-3-Clause
|
function compileTokens(tokens, returnBody) {
var body = ['""'];
var token, method, escape;
for (var i = 0, len = tokens.length; i < len; ++i) {
token = tokens[i];
switch (token.type) {
case "#":
case "^":
method = (token.type === "#") ? "_section" : "_inverted";
body.push("r." + method + "(" + quote(token.value) + ", c, function (c, r) {\n" +
" " + compileTokens(token.tokens, true) + "\n" +
"})");
break;
case "{":
case "&":
case "name":
escape = token.type === "name" ? "true" : "false";
body.push("r._name(" + quote(token.value) + ", c, " + escape + ")");
break;
case ">":
body.push("r._partial(" + quote(token.value) + ", c)");
break;
case "text":
body.push(quote(token.value));
break;
}
}
// Convert to a string body.
body = "return " + body.join(" + ") + ";";
// Good for debugging.
// console.log(body);
if (returnBody) {
return body;
}
// For great evil!
return new Function("c, r", body);
}
|
Low-level function that compiles the given `tokens` into a
function that accepts two arguments: a Context and a
Renderer. Returns the body of the function as a string if
`returnBody` is true.
|
compileTokens
|
javascript
|
CartoDB/cartodb
|
lib/build/mustache.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/build/mustache.js
|
BSD-3-Clause
|
function escapeTags(tags) {
if (tags.length === 2) {
return [
new RegExp(escapeRe(tags[0]) + "\\s*"),
new RegExp("\\s*" + escapeRe(tags[1]))
];
}
throw new Error("Invalid tags: " + tags.join(" "));
}
|
Low-level function that compiles the given `tokens` into a
function that accepts two arguments: a Context and a
Renderer. Returns the body of the function as a string if
`returnBody` is true.
|
escapeTags
|
javascript
|
CartoDB/cartodb
|
lib/build/mustache.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/build/mustache.js
|
BSD-3-Clause
|
function nestTokens(tokens) {
var tree = [];
var collector = tree;
var sections = [];
var token, section;
for (var i = 0; i < tokens.length; ++i) {
token = tokens[i];
switch (token.type) {
case "#":
case "^":
token.tokens = [];
sections.push(token);
collector.push(token);
collector = token.tokens;
break;
case "/":
if (sections.length === 0) {
throw new Error("Unopened section: " + token.value);
}
section = sections.pop();
if (section.value !== token.value) {
throw new Error("Unclosed section: " + section.value);
}
if (sections.length > 0) {
collector = sections[sections.length - 1].tokens;
} else {
collector = tree;
}
break;
default:
collector.push(token);
}
}
// Make sure there were no open sections when we're done.
section = sections.pop();
if (section) {
throw new Error("Unclosed section: " + section.value);
}
return tree;
}
|
Forms the given linear array of `tokens` into a nested tree structure
where tokens that represent a section have a "tokens" array property
that contains all tokens that are in that section.
|
nestTokens
|
javascript
|
CartoDB/cartodb
|
lib/build/mustache.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/build/mustache.js
|
BSD-3-Clause
|
function squashTokens(tokens) {
var lastToken;
for (var i = 0; i < tokens.length; ++i) {
var token = tokens[i];
if (lastToken && lastToken.type === "text" && token.type === "text") {
lastToken.value += token.value;
tokens.splice(i--, 1); // Remove this token from the array.
} else {
lastToken = token;
}
}
}
|
Combines the values of consecutive text tokens in the given `tokens` array
to a single token.
|
squashTokens
|
javascript
|
CartoDB/cartodb
|
lib/build/mustache.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/build/mustache.js
|
BSD-3-Clause
|
function parse(template, tags) {
tags = tags || exports.tags;
var tagRes = escapeTags(tags);
var scanner = new Scanner(template);
var tokens = [], // Buffer to hold the tokens
spaces = [], // Indices of whitespace tokens on the current line
hasTag = false, // Is there a {{tag}} on the current line?
nonSpace = false; // Is there a non-space char on the current line?
// Strips all whitespace tokens array for the current line
// if there was a {{#tag}} on it and otherwise only space.
var stripSpace = function () {
if (hasTag && !nonSpace) {
while (spaces.length) {
tokens.splice(spaces.pop(), 1);
}
} else {
spaces = [];
}
hasTag = false;
nonSpace = false;
};
var type, value, chr;
while (!scanner.eos()) {
value = scanner.scanUntil(tagRes[0]);
if (value) {
for (var i = 0, len = value.length; i < len; ++i) {
chr = value.charAt(i);
if (isWhitespace(chr)) {
spaces.push(tokens.length);
} else {
nonSpace = true;
}
tokens.push({type: "text", value: chr});
if (chr === "\n") {
stripSpace(); // Check for whitespace on the current line.
}
}
}
// Match the opening tag.
if (!scanner.scan(tagRes[0])) {
break;
}
hasTag = true;
type = scanner.scan(tagRe) || "name";
// Skip any whitespace between tag and value.
scanner.scan(whiteRe);
// Extract the tag value.
if (type === "=") {
value = scanner.scanUntil(eqRe);
scanner.scan(eqRe);
scanner.scanUntil(tagRes[1]);
} else if (type === "{") {
var closeRe = new RegExp("\\s*" + escapeRe("}" + tags[1]));
value = scanner.scanUntil(closeRe);
scanner.scan(curlyRe);
scanner.scanUntil(tagRes[1]);
} else {
value = scanner.scanUntil(tagRes[1]);
}
// Match the closing tag.
if (!scanner.scan(tagRes[1])) {
throw new Error("Unclosed tag at " + scanner.pos);
}
tokens.push({type: type, value: value});
if (type === "name" || type === "{" || type === "&") {
nonSpace = true;
}
// Set the tags for the next time around.
if (type === "=") {
tags = value.split(spaceRe);
tagRes = escapeTags(tags);
}
}
squashTokens(tokens);
return nestTokens(tokens);
}
|
Breaks up the given `template` string into a tree of token objects. If
`tags` is given here it must be an array with two string values: the
opening and closing tags used in the template (e.g. ["<%", "%>"]). Of
course, the default is to use mustaches (i.e. Mustache.tags).
|
parse
|
javascript
|
CartoDB/cartodb
|
lib/build/mustache.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/build/mustache.js
|
BSD-3-Clause
|
stripSpace = function () {
if (hasTag && !nonSpace) {
while (spaces.length) {
tokens.splice(spaces.pop(), 1);
}
} else {
spaces = [];
}
hasTag = false;
nonSpace = false;
}
|
Breaks up the given `template` string into a tree of token objects. If
`tags` is given here it must be an array with two string values: the
opening and closing tags used in the template (e.g. ["<%", "%>"]). Of
course, the default is to use mustaches (i.e. Mustache.tags).
|
stripSpace
|
javascript
|
CartoDB/cartodb
|
lib/build/mustache.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/build/mustache.js
|
BSD-3-Clause
|
function compile(tokens, tags) {
return _renderer.compile(tokens, tags);
}
|
High-level API for compiling the given `tokens` down to a reusable
function. If `tokens` is a string it will be parsed using the given `tags`
before it is compiled.
|
compile
|
javascript
|
CartoDB/cartodb
|
lib/build/mustache.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/build/mustache.js
|
BSD-3-Clause
|
function compilePartial(name, tokens, tags) {
return _renderer.compilePartial(name, tokens, tags);
}
|
High-level API for compiling the `tokens` for the partial with the given
`name` down to a reusable function. If `tokens` is a string it will be
parsed using the given `tags` before it is compiled.
|
compilePartial
|
javascript
|
CartoDB/cartodb
|
lib/build/mustache.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/build/mustache.js
|
BSD-3-Clause
|
function render(template, view, partials) {
if (partials) {
for (var name in partials) {
compilePartial(name, partials[name]);
}
}
return _renderer.render(template, view);
}
|
High-level API for rendering the `template` using the given `view`. The
optional `partials` object may be given here for convenience, but note that
it will cause all partials to be re-compiled, thus hurting performance. Of
course, this only matters if you're going to render the same template more
than once. If so, it is best to call `compilePartial` before calling this
function and to leave the `partials` argument blank.
|
render
|
javascript
|
CartoDB/cartodb
|
lib/build/mustache.js
|
https://github.com/CartoDB/cartodb/blob/master/lib/build/mustache.js
|
BSD-3-Clause
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.