Specify map of ant paths to max-age times (in seconds). The default map is:

/**&#47;*.aggr.min.js - 365 days
/**&#47;*.aggr.min.css - 365 days
/**&#47;*.min.js - 365 days
/**&#47;*.min.css - 365 days
/rs/**&#47;* - 365 days
769693
public void setCacheMaxAges(Map<String, ? extends Number> cacheMaxAges) {
        final Builder<String, Long> cacheMaxAgesBuilder = ImmutableMap.builder();
        final Builder<Long, String> cachedControlStringsBuilder = ImmutableMap.builder();
        final Set<Long> maxAgeLog = new HashSet<Long>();
        
        for (final Map.Entry<String, ? extends Number> cacheMaxAgeEntry : cacheMaxAges.entrySet()) {
            final Number maxAgeNum = cacheMaxAgeEntry.getValue();
            final int maxAge = maxAgeNum.intValue();
            final long maxAgeMillis = TimeUnit.SECONDS.toMillis(maxAge);
            cacheMaxAgesBuilder.put(cacheMaxAgeEntry.getKey(), maxAgeMillis);
            
            if (maxAgeLog.add(maxAgeMillis)) {
                cachedControlStringsBuilder.put(maxAgeMillis, "public, max-age=" + maxAge);
            }
        }
        
        this.cacheMaxAges = cacheMaxAgesBuilder.build();
        this.cachedControlStrings = cachedControlStringsBuilder.build();
    }
30222
def draw_geoscale(ax, minx=0, maxx=175):
    
    a, b = .1, .6  # Correspond to 200mya and 0mya
    def cv(x): return b - (x - b) / (maxx - minx) * (b - a)
    ax.plot((a, b), (.5, .5), "k-")
    tick = .015
    for mya in xrange(maxx - 25, 0, -25):
        p = cv(mya)
        ax.plot((p, p), (.5, .5 - tick), "k-")
        ax.text(p, .5 - 2.5 * tick, str(mya), ha="center", va="center")
    ax.text((a + b) / 2, .5 - 5 * tick, "Time before present (million years)",
            ha="center", va="center")

    # Source:
    # http://www.weston.org/schools/ms/biologyweb/evolution/handouts/GSAchron09.jpg
    Geo = (("Neogene", 2.6, 23.0, "#fee400"),
           ("Paleogene", 23.0, 65.5, "#ff9a65"),
           ("Cretaceous", 65.5, 145.5, "#80ff40"),
           ("Jurassic", 145.5, 201.6, "#33fff3"))
    h = .05
    for era, start, end, color in Geo:
        start, end = cv(start), cv(end)
        end = max(a, end)
        p = Rectangle((end, .5 + tick / 2), abs(start - end),
                      h, lw=1, ec="w", fc=color)
        ax.text((start + end) / 2, .5 + (tick + h) / 2, era,
                ha="center", va="center", size=9)
        ax.add_patch(p)
660075
def _build_basemap(self):
        '''
        
        '''
        if self.config['min_lon'] >= self.config['max_lon']:
            raise ValueError('Upper limit of long is smaller than lower limit')

        if self.config['min_lon'] >= self.config['max_lon']:
            raise ValueError('Upper limit of long is smaller than lower limit')
        # Corners of the map
        lowcrnrlat = self.config['min_lat']
        lowcrnrlon = self.config['min_lon']
        uppcrnrlat = self.config['max_lat']
        uppcrnrlon = self.config['max_lon']
        if 'resolution' not in self.config.keys():
            self.config['resolution'] = 'l'

        lat0 = lowcrnrlat + ((uppcrnrlat - lowcrnrlat) / 2)
        lon0 = lowcrnrlon + ((uppcrnrlon - lowcrnrlon) / 2)
        if (uppcrnrlat - lowcrnrlat) >= (uppcrnrlon - lowcrnrlon):
            fig_aspect = PORTRAIT_ASPECT
        else:
            fig_aspect = LANDSCAPE_ASPECT

        if self.ax is None:
            self.fig, self.ax = plt.subplots(figsize=fig_aspect,
                                             facecolor='w',
                                             edgecolor='k')
        else:
            self.fig = self.ax.get_figure()

        if self.title:
            self.ax.set_title(self.title, fontsize=16)
        parallels = np.arange(-90., 90., self.lat_lon_spacing)
        meridians = np.arange(0., 360., self.lat_lon_spacing)

        # Build Map
        # Do not import Basemap at top level since it's an optional feature
        # and it would break doctests
        from mpl_toolkits.basemap import Basemap
        self.m = Basemap(
            llcrnrlon=lowcrnrlon, llcrnrlat=lowcrnrlat,
            urcrnrlon=uppcrnrlon, urcrnrlat=uppcrnrlat,
            projection='stere', resolution=self.config['resolution'],
            area_thresh=1000.0, lat_0=lat0, lon_0=lon0, ax=self.ax)
        self.m.drawcountries()
        self.m.drawmapboundary()
        self.m.drawcoastlines()
        self.m.drawstates()
        self.m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=12)
        self.m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=12)
        self.m.fillcontinents(color='wheat')
328689
function top () { // NOTE: Replacing line above
  // if (!opts) opts = {}

  // const tick = opts.interval || 1000
  // const started = Date.now()
  // const interval = setInterval(perSecond, tick)
  // const win = [{ time: process.hrtime(), cpu: process.cpuUsage(), delay: 0 }, null, null, null]
  const win = [{ time: process.hrtime(), cpu: process.cpuUsage() }, null, null, null] // NOTE: Replacing line above
  // const loopSampler = eld()

  let sec = 1

  // interval.unref()

  return {
    // pid: process.pid,
    // command: process.argv.join(' '),
    // started,
    // time () {
    //   return Date.now() - started
    // },
    // delay () {
    //   const btm = oldest()
    //   const timeDelta = process.hrtime(win[btm].time)
    //   const ms = timeDelta[0] * 1e3 + Math.floor(timeDelta[1] / 1e6)
    //   return Math.floor((loopSampler.delay - win[btm].delay) / (ms / tick))
    // },
    cpu () {
      const btm = oldest()
      const cpuDelta = process.cpuUsage(win[btm].cpu)
      const timeDelta = process.hrtime(win[btm].time)
      const us = timeDelta[0] * 1e6 + timeDelta[1] / 1e3
      perSecond() // NOTE: Added to skip timer and update at each check
      return {
        time: us,
        percent: (cpuDelta.system + cpuDelta.user) / us,
        system: cpuDelta.system,
        user: cpuDelta.user
      }
    }
    // memory () {
    //   const mem = process.memoryUsage()
    //   const total = os.totalmem()
    //   return {
    //     percent: mem.rss / total,
    //     rss: mem.rss,
    //     total,
    //     heapPercent: mem.heapUsed / mem.heapTotal,
    //     heapUsed: mem.heapUsed,
    //     heapTotal: mem.heapTotal,
    //     external: mem.external
    //   }
    // },
    // loadavg () {
    //   return os.loadavg()
    // },
    // destroy () {
    //   clearInterval(interval)
    // },
    // toString () {
    //   const mem = this.memory()
    //   return `cpu: ${pct(this.cpu().percent)} | rss: ${p(mem.rss)} (${pct(mem.percent)}) | heap: ${p(mem.heapUsed)} / ${p(mem.heapTotal)} (${pct(mem.heapPercent)}) | ext: ${p(mem.external)} | delay: ${this.delay()} ms | ${time(this.time())} | loadavg: ${os.loadavg().map(fixed2).join(', ')}`
    // }
  }

  function oldest () {
    let btm = (sec - 4) & 3
    while (!win[btm]) btm = (btm + 1) & 3
    return btm
  }

  function perSecond () {
    const ptr = sec++ & 3
    // win[ptr] = { time: process.hrtime(), cpu: process.cpuUsage(), delay: loopSampler.delay }
    win[ptr] = { time: process.hrtime(), cpu: process.cpuUsage() } // NOTE: Replacing line above
  }
}
546162
private Map<String, Double> getMinMax(Map<Long, Double> metricData) {
        double min = 0.0;
        double max = 0.0;
        boolean isMinMaxSet = false;
        for (Double value : metricData.values()) {
            double valueDouble = value;
            if (!isMinMaxSet) {
                min = valueDouble;
                max = valueDouble;
                isMinMaxSet = true;
            } else {
                if (valueDouble < min) {
                    min = valueDouble;
                } else if (valueDouble > max) {
                    max = valueDouble;
                }
            }
        }

        Map<String, Double> minMax = new HashMap<>();
        minMax.put("min", min);
        minMax.put("max", max);
        return minMax;
    }
387949
def default_base_ant_pairs(self, context):
    
    k = 0 if context.cfg['auto_correlations'] == True else 1
    na = context.dim_global_size('na')
    gen = (i.astype(context.dtype) for i in np.triu_indices(na, k))

    # Cache np.triu_indices(na, k) as its likely that (na, k) will
    # stay constant much of the time. Assumption here is that this
    # method will be grafted onto a DefaultsSourceProvider with
    # the appropriate members.
    if self._is_cached:
        array_cache = self._chunk_cache['default_base_ant_pairs']
        key = (k, na)

        # Cache miss
        if key not in array_cache:
            array_cache[key] = tuple(gen)

        return array_cache[key]

    return tuple(gen)
257702
function({_t0, arg, keys, inv}) {
		const key = keys && makeKey(opts, keys);
		const lay = layers.map(l => l.instantiate({key, ttl, ttr, inv}));
		const fix = lay.slice();
		const ret = Q.defer();
		const bld = () => {
			const _t1 = new Date;
			return Q()
				.then(() => func.apply(this, arg))
				.then(val => {
					time('build', new Date - _t1);
					return val;
				});
		}

		const set = (layer, val) => {
			if (shouldCache(val)) {
				layer.set(val);
			}
		}

		const pump = () => {

			// Get the next layer.
			const cur = lay.shift();
			const _t1 = new Date;

			// If we couldn't make a key, then we force a miss.
			// If we're out of layers, then we'll just have to
			// build.  It's a full miss.
			// We can _force_ a miss with the `_bust` parameter.
			if (!key || !cur || force()) {
				bld().then(val => {

					// Hand it off.
					ret.resolve(val)

					// Sob about it.
					time('miss', new Date - _t0);

				// Patch rejection through to return promise.
				}).catch(err => ret.reject(err));
				return;
			}

			Q().then(() => cur.get()).then(() => {

				// If we found a value and it's not expired.
				if (cur.val && !cur.exp) {

					// Hand it off.
					ret.resolve(cur.val);

					// Brag about it.
					time('hit', new Date - _t0);
					time(`layer.${cur.name()}.hit.fromStart`,  new Date - _t0);
					time(`layer.${cur.name()}.hit.individual`, new Date - _t1);

					// If our time-to-rebuild has elapsed,
					// we'll rebuild in the background and
					// populate the new value into all
					// layers.
					if (cur.red) {
						bld().then((val) => {
							fix.forEach(layer => set(layer, val));
						}).catch(() => {
							time('error.background', new Date - _t0);
						});

					}
				} else {

					// Miss.  Populate this layer later
					// when we get a value.
					ret.promise.then(val => set(cur, val));

					time(`layer.${cur.name()}.miss.fromStart`,  new Date - _t0);
					time(`layer.${cur.name()}.miss.individual`, new Date - _t1);

					// Try the next layer.
					pump();
				}
			});
		}

		if (inv) {
			// Invalidate.
			Q.all(fix.map(l => l.set())).then(ret.resolve);
		} else {
			// Start looking!
			pump();
		}

		// Log if we reject.
		ret.promise.catch(() => time('error.returned', new Date - _t0));

		// We'll find it, we promise!
		return ret.promise

			// Post-processing on the way out of the cache.
			.then(after)

			// Down and to the right!
			.then(v => (time('overall', new Date - _t0), v))
	}
1360778
def _GetTimelineStatEntriesLegacy(client_id, file_path, with_history=True):
  """"""

  folder_urn = aff4.ROOT_URN.Add(str(client_id)).Add(file_path)

  child_urns = []
  for _, children in aff4.FACTORY.RecursiveMultiListChildren([folder_urn]):
    child_urns.extend(children)

  if with_history:
    timestamp = aff4.ALL_TIMES
  else:
    timestamp = aff4.NEWEST_TIME

  for fd in aff4.FACTORY.MultiOpen(child_urns, age=timestamp):
    file_path = "/".join(str(fd.urn).split("/")[2:])

    if not with_history:
      yield file_path, fd.Get(fd.Schema.STAT), fd.Get(fd.Schema.HASH)
      continue

    result = {}

    stats = fd.GetValuesForAttribute(fd.Schema.STAT)
    for s in stats:
      result[s.age] = [s, None]

    hashes = fd.GetValuesForAttribute(fd.Schema.HASH)
    for h in hashes:
      prev = result.setdefault(h.age, [None, None])
      prev[1] = h

    for ts in sorted(result):
      v = result[ts]
      yield file_path, v[0], v[1]
568272
def manifest_path_is_old(self, path):
        ''''''
        mtime = os.path.getmtime(path)
        return (time.time() - mtime) > 24*60*60
860678
private static void remainLongest(Collection<Emit> collectedEmits)
    {
        if (collectedEmits.size() < 2) return;
        Map<Integer, Emit> emitMapStart = new TreeMap<Integer, Emit>();
        for (Emit emit : collectedEmits)
        {
            Emit pre = emitMapStart.get(emit.getStart());
            if (pre == null || pre.size() < emit.size())
            {
                emitMapStart.put(emit.getStart(), emit);
            }
        }
        if (emitMapStart.size() < 2)
        {
            collectedEmits.clear();
            collectedEmits.addAll(emitMapStart.values());
            return;
        }
        Map<Integer, Emit> emitMapEnd = new TreeMap<Integer, Emit>();
        for (Emit emit : emitMapStart.values())
        {
            Emit pre = emitMapEnd.get(emit.getEnd());
            if (pre == null || pre.size() < emit.size())
            {
                emitMapEnd.put(emit.getEnd(), emit);
            }
        }

        collectedEmits.clear();
        collectedEmits.addAll(emitMapEnd.values());
    }
382374
function dotMap(path) {
  if (typeof path !== 'string' || path.length === 0) {
    return I
  }
  var segments = path.split('.')
  var len = segments.length

  switch (len) {
    case 0: return I
    case 1: return function (x) {
        return x[segments[0]]
      }
    case 2: return function (x) {
        return x[segments[0]][segments[1]]
      }
    case 3: return function (x) {
        return x[segments[0]][segments[1]][segments[2]]
      }
    case 4: return function (x) {
      return x[segments[0]][segments[1]][segments[2]][segments[3]]
    }
  }
  return function (x) {
    var i
    while(i = segments.shift(), x = x[i], segments.length);
    return x;
  }
}
851657
def write(self, path):
        """"""
        meta = {
            'generated_at': self.generated_at,
            'elapsed_time': self.elapsed_time,
        }
        sources = {}
        for result in self.results:
            unique_id = result.node.unique_id
            if result.error is not None:
                result_dict = {
                    'error': result.error,
                    'state': 'runtime error'
                }
            else:
                result_dict = {
                    'max_loaded_at': result.max_loaded_at,
                    'snapshotted_at': result.snapshotted_at,
                    'max_loaded_at_time_ago_in_s': result.age,
                    'state': result.status,
                    'criteria': result.node.freshness,
                }
            sources[unique_id] = result_dict
        output = FreshnessRunOutput(meta=meta, sources=sources)
        output.write(path)
1172872
function(el, properties) {
    var duration = 0;

    for (var i = 0; i < properties.length; i++) {
      // Get raw CSS value
      var value = el.css(properties[i]);
      if (!value) continue;

      // Multiple transitions--pick the longest
      if (value.indexOf(",") !== -1) {
        var values = value.split(",");
        var durations = (function(){
          var results = [];
          for (var i = 0; i < values.length; i++) {
            var duration = parseTime(values[i]);
            results.push(duration);
          }
          return results;
        })();

        duration = Math.max.apply(Math, durations);
      }

      // Single transition
      else {
        duration = parseTime(value);
      }

      // Accept first vaue
      break;
    }

    return duration;
  }
961998
function setBasemap(basemap) {
      app.debug('MapActions >>> setBasemap');
      app.map.setBasemap(basemap);
      _jsDispatcher.Dispatcher.dispatch({
        actionType: _jsConstantsAppConstants.MAP.basemap,
        data: basemap
      });
    }
204627
function TokenBucket(timespan, limit, { distFactor = 1, factor = 20, spread = 500 / timespan, now = Date.now } = {}) {
  this.now = now;

  this.timespan = timespan;
  // this.givenLimit is the limit given to the constructor, this.limit is the
  // functional limit, accounting for this.distFactor.
  this.givenLimit = limit;
  this.factor = factor;
  this.spread = spread;
  this.timespanIndex = Math.ceil(timespan / factor);
  this.total = 0;
  this.time = -1;
  this.buffer = new Array(this.factor + 1).fill(0);

  this.setDistFactor(distFactor);
}
502802
function (settings) {
            var setting, i, j, last, interval,
                sp = this.stepParams,
                isStart = (sp.timing === "start"),
                p = [];

            var defaultSettings = {
                bgColor:        "transparent",
                borderColor:    "#bbb",
                stepColor:      "#2893ef",
                dashColor:      "#b8b8b8",
                borderWidth:    0.00667,
                stepLineWidth:  0.02,
                dashLineWidth:  0.008,
                pointLineWidth: 0.008,
                pointRadius:    0.015
            };

            this.settings = settings || {};

            for (setting in defaultSettings) {
                if (defaultSettings.hasOwnProperty(setting)) {
                    if (!this.settings.hasOwnProperty(setting)) {
                        this.settings[setting] = defaultSettings[setting];
                    }
                }
            }

            this.ctx = this.canvas.getContext("2d");

            // Build points array. There's a starting point at 0,0
            // plus a point for each step
            p[0] = { x: 0, y: 0 };
            for (i = 1; i <= sp.count; i++) {
                interval = i / sp.count;
                p[i] = { x: interval, y: interval };
            }

            // Start with a clean slate
            this.ctx.clearRect(-0.5, -0.5, 2, 2);
            this.drawBackground();

            // Draw each interval
            last = p.length - 1;
            for (i = 0, j = 1; i < last; i++, j++) {
                if (isStart) {
                    this.drawStartInterval(p[i].x, p[i].y, p[j].x, p[j].y);
                } else {
                    this.drawEndInterval(p[i].x, p[i].y, p[j].x, p[j].y);
                }
            }

            // Each interval draws start and mid point for that interval,
            // so we need to draw last point. It's always filled.
            this.drawPoint(p[last].x, p[last].y, true);
        }
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))