generates CartoCSS for time-based maps (torque)
512872
def _setup_time(self, basemap):
        """"""
        # validate time column information
        if self.geom_type != 'point':
            raise ValueError('Cannot do time-based maps with data in '
                             '`{query}` since this table does not contain '
                             'point geometries'.format(
                                 query=self.orig_query))
        elif self.style_cols[self.time['column']] not in (
                'number', 'date', ):
            raise ValueError('Cannot create an animated map from column '
                             '`{col}` because it is of type {t1}. It must '
                             'be of type number or date.'.format(
                                 col=self.time['column'],
                                 t1=self.style_cols[self.time['column']]))

        # don't use turbo-carto for animated maps
        column = self.time['column']
        frames = self.time['frames']
        method = self.time['method']
        duration = self.time['duration']
        if (self.color in self.style_cols and
                self.style_cols[self.color] in ('string', 'boolean', )):
            self.query = minify_sql([
                'SELECT',
                '    orig.*, __wrap.cf_value_{col}',
                'FROM ({query}) AS orig, (',
                '    SELECT',
                '      row_number() OVER (',
                '        ORDER BY val_{col}_cnt DESC) AS cf_value_{col},',
                '      {col}',
                '    FROM (',
                '        SELECT {col}, count({col}) AS val_{col}_cnt',
                '        FROM ({query}) as orig',
                '        GROUP BY {col}',
                '        ORDER BY 2 DESC',
                '    ) AS _wrap',
                ') AS __wrap',
                'WHERE __wrap.{col} = orig.{col}',
            ]).format(col=self.color, query=self.orig_query)
            agg_func = '\'CDB_Math_Mode(cf_value_{})\''.format(self.color)
            self.scheme = {
                'bins': [str(i) for i in range(1, 11)],
                'name': (self.scheme.get('name') if self.scheme
                         else 'Bold'),
                'bin_method': '', }
        elif (self.color in self.style_cols and
              self.style_cols[self.color] in ('number', )):
            self.query = ' '.join([
                'SELECT *, {col} as value',
                'FROM ({query}) as _wrap'
            ]).format(col=self.color, query=self.orig_query)
            agg_func = '\'avg({})\''.format(self.color)
        else:
            agg_func = "'{method}(cartodb_id)'".format(
                method=method)
        self.torque_cartocss = cssify({
            'Map': {
                '-torque-frame-count': frames,
                '-torque-animation-duration': duration,
                '-torque-time-attribute': "'{}'".format(column),
                '-torque-aggregation-function': agg_func,
                '-torque-resolution': 1,
                '-torque-data-aggregation': ('cumulative'
                                             if self.time['cumulative']
                                             else 'linear'),
            },
        })
        self.cartocss = (self.torque_cartocss
                         + self._get_cartocss(basemap, has_time=True))
1196354
def get_time_attr_map(t):
    
    now = datetime.datetime.now()
    if t + datetime.timedelta(hours=3) > now:
        return get_map("main_list_white")
    if t + datetime.timedelta(days=3) > now:
        return get_map("main_list_lg")
    else:
        return get_map("main_list_dg")
765925
def export(cls, folder, particles, datetimes):
        
        normalized_locations = [particle.normalized_locations(datetimes) for particle in particles]

        track_coords = []
        for x in xrange(0, len(datetimes)):
            points = MultiPoint([loc[x].point.coords[0] for loc in normalized_locations])
            track_coords.append(points.centroid.coords[0])

        ls = LineString(track_coords)

        if not os.path.exists(folder):
            os.makedirs(folder)
        filepath = os.path.join(folder, "trackline.geojson")
        f = open(filepath, "wb")
        f.write(json.dumps(mapping(ls)))
        f.close()
        return filepath
378044
def _create_request_map(cls, input_map):
        """"""
        field_map = cls._get_attributes_map()
        return {field_map[k]: v for k, v in input_map.items() if k in field_map}
1216417
function wheelTimedOut(element) {

  // Snap to the closest item.
  element[symbols.dragging] = false;
  const travelFraction = element.travelFraction;
  if (travelFraction >= 0.5) {
    element[symbols.goRight]();
  } else if (travelFraction <= -0.5) {
    element[symbols.goLeft]();
  }

  // TODO: Listen for the transition to complete, and then restore
  // dragging to false (or the previous value).

  resetWheelTracking(element);
}
753666
def starmap_t(func):
    
    return Transformation('starmap({})'.format(name(func)),
                          partial(starmap, func),
                          {ExecutionStrategies.PARALLEL})
134271
def get_map(self, create_html=True):
        """"""
        strike_data = self.df
        num_rows = len(self.df)
        if num_rows > 1000:
            print("Warning, you have requested lots of data be mapped." /
                  " Limiting your request to the first 1,000 rows" /
                  " as this is currently only a preview feature.")
            strike_data = self.df[0:1000]
        m = folium.Map(location=[0.0, 0.01], zoom_start=2)
        marker_cluster = folium.MarkerCluster().add_to(m)
        for event in strike_data.index:
            self.add_to_map(map_obj=m,
                            date_time=strike_data.dt[event],
                            cluster_obj=marker_cluster,
                            lat=strike_data.geometry[event].y,
                            lon=strike_data.geometry[event].x,
                            key=event)
        if create_html:
            data_date = strike_data.dt[0].split()[0]
            m.save('map_{0}.html'.format(data_date))
        return m
473075
def _init_map(self):
        """"""
        ItemTextsFormRecord._init_map(self)
        ItemFilesFormRecord._init_map(self)
        edXBaseFormRecord._init_map(self)
        IRTItemFormRecord._init_map(self)
        TimeValueFormRecord._init_map(self)
        ProvenanceFormRecord._init_map(self)
        super(edXItemFormRecord, self)._init_map()
151565
function generateSnippet (config) {
    const apiKey = config.b || 'default_public';
    const username = config.c;
    const serverURL = config.d || 'https://{user}.carto.com';
    const vizSpec = config.e || '';
    const center = config.f || { lat: 0, lng: 0 };
    const zoom = config.g || 10;
    const basemap = BASEMAPS[config.h] || 'https://basemaps.cartocdn.com/gl/voyager-gl-style/style.json';

    const source = config.i === sourceTypes.DATASET
        ? `new carto.source.Dataset("${config.a}")`
        : `new carto.source.SQL(\`${config.a}\`)`;

    return `<!DOCTYPE html>
<html>
<head>
<title>Exported map | CARTO VL</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<script src="http://libs.cartocdn.com/carto-vl/v${carto.version}/carto-vl.js"></script>
<script src="https://api.tiles.mapbox.com/mapbox-gl-js/v0.52.0/mapbox-gl.js"></script>
<link href="https://api.tiles.mapbox.com/mapbox-gl-js/v0.52.0/mapbox-gl.css" rel="stylesheet" />
<style>
    html, body {
        margin: 0;
    }
    #map {
        position: absolute;
        width: 100%;
        height: 100%;
    }
</style>
</head>
<body>
<div id="map"></div>
<script>
    const map = new mapboxgl.Map({
        container: 'map',
        style: '${basemap}',
        center: [${center.lng}, ${center.lat}],
        zoom: ${zoom}
    });

    carto.setDefaultConfig({
        serverURL: '${serverURL}'
    });

    carto.setDefaultAuth({
        username: '${username}',
        apiKey: '${apiKey}'
    });


    const source = ${source};
    const viz = new carto.Viz(\`
        ${vizSpec}
    \`);
    const layer = new carto.Layer('layer', source, viz);

    layer.addTo(map, 'watername_ocean');
</script>
</body>
</html>
`;
}
1335215
def io_surface(timestep, time, fid, fld):
    """"""
    fid.write("{} {}".format(timestep, time))
    fid.writelines(["%10.2e" % item for item in fld[:]])
    fid.writelines(["\n"])
969988
def to_cartopy(self):
        """"""
        globe = self.cartopy_globe
        proj_name = self._attrs['grid_mapping_name']
        try:
            proj_handler = self.projection_registry[proj_name]
        except KeyError:
            raise ValueError('Unhandled projection: {}'.format(proj_name))

        return proj_handler(self._attrs, globe)
978246
static void mapAutomatically() {
    Order order = createOrder();
    ModelMapper modelMapper = new ModelMapper();
    OrderDTO orderDTO = modelMapper.map(order, OrderDTO.class);
    assertOrdersEqual(order, orderDTO);
  }
606675
def map_t(func):
    
    return Transformation('map({0})'.format(name(func)),
                          partial(map, func),
                          {ExecutionStrategies.PARALLEL})
1296409
def mapped(cls, key='id', **kwargs):
    """"""
    kwargs.setdefault('metadata', {})
    kwargs['metadata']['jsonldPredicate'] = {'mapSubject': key}
    kwargs.setdefault('default', attr.Factory(list))

    def converter(value):
        """Convert mapping to a list of instances."""
        if isinstance(value, dict):
            result = []
            for k, v in iteritems(value):
                if not hasattr(cls, 'from_cwl'):
                    vv = dict(v)
                    vv[key] = k
                else:
                    vv = attr.evolve(cls.from_cwl(v), **{key: k})
                result.append(vv)
        else:
            result = value

        def fix_keys(data):
            """Fix names of keys."""
            for a in fields(cls):
                a_name = a.name.rstrip('_')
                if a_name in data:
                    yield a.name, data[a_name]

        return [
            cls(**{kk: vv
                   for kk, vv in fix_keys(v)}) if not isinstance(v, cls) else v
            for v in result
        ]

    kwargs['converter'] = converter
    return attr.ib(**kwargs)
78788
function () {
    if (beatmap.timingPoints.length === 0) { return; }

    var maxCombo         = 0;
    var sliderMultiplier = parseFloat(beatmap.SliderMultiplier);
    var sliderTickRate   = parseInt(beatmap.SliderTickRate, 10);

    var timingPoints  = beatmap.timingPoints;
    var currentTiming = timingPoints[0];
    var nextOffset    = timingPoints[1] ? timingPoints[1].offset : Infinity;
    var i = 1;

    beatmap.hitObjects.forEach(function (hitObject) {
      if (hitObject.startTime >= nextOffset) {
        currentTiming = timingPoints[i++];
        nextOffset = timingPoints[i] ? timingPoints[i].offset : Infinity;
      }

      var osupxPerBeat = sliderMultiplier * 100 * currentTiming.velocity;
      var tickLength   = osupxPerBeat / sliderTickRate;

      switch (hitObject.objectName) {
        case 'spinner':
        case 'circle':
          maxCombo++;
          break;
        case 'slider':
          var tickPerSide = Math.ceil((Math.floor(hitObject.pixelLength / tickLength * 100) / 100) - 1);
          maxCombo += (hitObject.edges.length - 1) * (tickPerSide + 1) + 1;  // 1 combo for each tick and endpoint
      }
    });

    beatmap.maxCombo = maxCombo;
  }
205290
private static Map<Long, Double> _fillMetricTransform(QueryContext queryContext, Metric metric, long windowSizeInSeconds, long offsetInSeconds, double value) {
    	if(metric == null || metric.getDatapoints() == null || metric.getDatapoints().isEmpty()) {
    		return Collections.emptyMap();
    	}
    	
        Map<Long, Double> filledDatapoints = new TreeMap<>();
        Map<Long, Double> sortedDatapoints = new TreeMap<>(metric.getDatapoints());
        Long[] sortedTimestamps = new Long[sortedDatapoints.size()];

        sortedDatapoints.keySet().toArray(sortedTimestamps);

        Long[] startAndEndTimestamps = QueryUtils.getStartAndEndTimesWithMaxInterval(queryContext);
        
        Long startTimestamp = startAndEndTimestamps[0]>0 ? startAndEndTimestamps[0] : sortedTimestamps[0];
        Long endTimestamp = startAndEndTimestamps[1]>0 ? startAndEndTimestamps[1] : sortedTimestamps[sortedTimestamps.length - 1];

        // create a new datapoints map propagateDatpoints, which have all the
        // expected timestamps, then fill the missing value
        int index = 1;
        int numDatapoints = 0;
        while (startTimestamp <= endTimestamp && numDatapoints++ < MAX_DATAPOINTS_FOR_FILL) {
            filledDatapoints.put(startTimestamp, sortedDatapoints.containsKey(startTimestamp) ? sortedDatapoints.get(startTimestamp) : null);
            if (index >= sortedDatapoints.size()) {
              	startTimestamp = startTimestamp + windowSizeInSeconds * 1000;
                continue;
            }
            if ((startTimestamp + windowSizeInSeconds * 1000) < sortedTimestamps[index]) {
                startTimestamp = startTimestamp + windowSizeInSeconds * 1000;
            } else {
                startTimestamp = sortedTimestamps[index];
                index++;
            }
        }

        int newLength = filledDatapoints.size();
        List<Long> newTimestamps = new ArrayList<Long>();
        List<Double> newValues = new ArrayList<>();
        
        for (Map.Entry<Long, Double> entry : filledDatapoints.entrySet()) {
            newTimestamps.add(entry.getKey());
            newValues.add(entry.getValue());
        }
        for (int i = 0; i < newLength; i++) {
            if (newValues.get(i) != null) {
                continue;
            } else {
                filledDatapoints.put(newTimestamps.get(i) + offsetInSeconds * 1000, value);
            }
        }

        Map<Long, Double> cleanFilledDatapoints = new TreeMap<>();

        for (Map.Entry<Long, Double> entry : filledDatapoints.entrySet()) {
            if (entry.getValue() != null) {
                cleanFilledDatapoints.put(entry.getKey(), entry.getValue());
            }
        }
        return cleanFilledDatapoints;
    }
704096
def map(self, coords):
        
        for tr in reversed(self.transforms):
            coords = tr.map(coords)
        return coords