TODO remove the following methods
This method is used in the /metrics/:/:/cache route
515074
def moving_averages!(days)
      subselects = Metric.subselects_with_day(days).join(",")
      metric_with_calculated_averages = Metric.find_by_sql("SELECT fulldate, fulldate AS d, year, monthofyear AS month, dayofyear AS day, '#{days}' AS movingaverage, #{subselects} FROM heart_metrics WHERE fulldate = '#{fulldate}' AND movingaverage = 0")
      metric_with_calculated_averages.first.attributes.each do |name, value|
        next if Metric.metadata.include?(name)
        next if Metric.groupbydata.include?(name)
          self.send(name+"=",value)
      end
    end
681211
private static <T> void aggregateRoutes(
		String method, Map<PathPattern, T> routes,
		List<String> accMethods, List<String> accPatterns, List<String> accTargets) {
		for (Map.Entry<PathPattern, T> entry : routes.entrySet()) {
			accMethods.add(method);
			accPatterns.add("/" + entry.getKey().pattern());
			accTargets.add(targetToString(entry.getValue()));
		}
	}
985795
public void processMetricAggregation() {
        if (!isEmpty(metricAggregation)) {
            String[] aggregations = metricAggregation.split(";");
            for (int i = 0; i < aggregations.length; i++) {
                String definition = aggregations[i].trim();
                int index0 = definition.indexOf("=");
                int index1 = definition.indexOf("(");
                int index2 = definition.indexOf(")");
                String aggregatedName = definition.substring(0, index0);
                String operation = definition.substring(index0 + 1, index1);
                String parameters = definition.substring(index1 + 1, index2);
                List<String> metricNames = new ArrayList<>();
                metricNames.add(operation);
                // Case a list of metricNames
                if (parameters.contains(",")) {
                    String[] listMetricNames = parameters.split(",");
                    for (int j = 0; j < listMetricNames.length; j++) {
                        metricNames.add(listMetricNames[j].trim());
                    }
                } else {
                    Pattern pattern = Pattern.compile(parameters);
                    for (String metricName : nameIdMetrics.keySet()) {
                        if (pattern.matcher(metricName).matches()) {
                            metricNames.add(metricName);
                        }
                    }
                }
                aggregatedMetrics.put(aggregatedName, metricNames);
            }
            log.debugf("Gnocchi Aggregated Metrics from %s -> %s", metricAggregation, aggregatedMetrics);
        }
    }
503603
public function invalidateCache()
    {
        $cache = Craft::$app->getCache();
        TagDependency::invalidate($cache, self::ROUTEMAP_CACHE_TAG);
        Craft::info(
            'Route Map cache cleared',
            __METHOD__
        );
    }
632585
def process(self, metric):
        
        # Send the data as ......
        if not pika:
            return

        routingKeyDic = {
            'metric': lambda: metric.path,
            'custom': lambda: self.custom_routing_key,

            # These option and the below are really not needed because
            #  with Rabbitmq you can use regular expressions to indicate
            #  what routing_keys to subscribe to. But I figure this is
            #  a good example of how to allow more routing keys

            'host': lambda: metric.host,
            'metric.path': metric.getMetricPath,
            'path.prefix': metric.getPathPrefix,
            'collector.path': metric.getCollectorPath,
        }

        try:
            self.channel.basic_publish(
                exchange=self.topic_exchange,
                routing_key=routingKeyDic[self.routing_key](),
                body="%s" % metric)

        except Exception:  # Rough connection re-try logic.
            self.log.info(
                "Failed publishing to rabbitMQ. Attempting reconnect")
            self._bind()
182347
public static void putOverloadMethodCache(String serviceName, Method method) {
        ConcurrentHashMap<String, Method> cache = OVERLOAD_METHOD_CACHE.get(serviceName);
        if (cache == null) {
            cache = new ConcurrentHashMap<String, Method>();
            ConcurrentHashMap<String, Method> old = OVERLOAD_METHOD_CACHE.putIfAbsent(serviceName, cache);
            if (old != null) {
                cache = old;
            }
        }
        StringBuilder mSigs = new StringBuilder(128);
        mSigs.append(method.getName());
        for (Class<?> paramType : method.getParameterTypes()) {
            mSigs.append(paramType.getName());
        }
        cache.putIfAbsent(mSigs.toString(), method);
    }
817746
function (request, response, next) {
                if (!next) {
                    next = makeDefaultNext(request, response);
                }
                try {
                    var url = request.url;
                    var questionIndex = url.indexOf("?");
                    var querystring = "";
                    if (questionIndex !== -1) {
                        // if there is a querystring, we'll just chop that part off
                        // it's still preserved in request.url, and should be handled
                        // by other middleware.
                        querystring = url.substring(questionIndex);
                        url = url.substring(0, questionIndex);
                    }
                    
                    var now = +new Date();
                    if (cacheExpirationTime < now) {
                        // time to reset the dynamic cache cache
                        
                        // Object.create(null) is used instead of {} so it doesn't have a prototype of Object.prototype
                        dynamicRouteCache = Object.create(null);
                        redirectCache = Object.create(null);
                        cacheExpirationTime = now + CACHE_CLEAR_TIME;
                    }
                    
                    var actualUrl = url;
                    var cachedResult = redirectCache[actualUrl];
                    if (cachedResult) {
                        movedPermanently(response, cachedResult + querystring);
                        return;
                    }
                    
                    var lowerMethod = request.method.toLowerCase();
                    if (url.length > 1 && url[url.length - 1] === "/") {
                        url = trimEndingSlashes(url);
                    }
                    var lowerUrl = url.toLowerCase();
                    var staticRoute = staticRoutes[lowerUrl];
                    var params;
                    var callback;
                    var descriptor;
                    var properUrl;
                    
                    if (staticRoute) {
                        properUrl = staticRoute.route;
                        if (properUrl !== actualUrl) {
                            redirectCache[actualUrl] = properUrl;
                            movedPermanently(response, properUrl + querystring);
                            return;
                        }
                        
                        descriptor = staticRoute.descriptor;
                        
                        // we found a static route
                        callback = descriptor[lowerMethod];
                        
                        if (!callback) {
                            // the URL exists, but does not have the provided method defined for it
                            methodNotAllowedHandler(request, response, next);
                            return;
                        }

                        params = emptyParams;
                    } else {
                        cachedResult = dynamicRouteCache[actualUrl];
                        if (cachedResult) {
                            descriptor = cachedResult.descriptor;
                            callback = descriptor[lowerMethod];
                            if (!callback) {
                                // the URL exists, but does not have the provided method defined for it
                                methodNotAllowedHandler(request, response, next);
                                return;
                            }
                            params = cachedResult.params;
                        } else {
                            searchDynamicRoutes:
                            for (var i = 0, len = dynamicRoutes.length; i < len; i += 1) {
                                var dynamicRoute = dynamicRoutes[i];
                                var prefix = dynamicRoute.prefix;
                            
                                if (prefix !== "/" && !startsWith(lowerUrl, prefix)) {
                                    continue;
                                }
                            
                                var routes = dynamicRoute.routes;
                                searchWithinPrefix:
                                for (var j = 0, lenJ = routes.length; j < lenJ; j += 1) {
                                    var route = routes[j];
                                    var match = route.regex.exec(url);
                                    if (!match) {
                                        continue;
                                    }
                                
                                    descriptor = route.descriptor;
                                    callback = descriptor[lowerMethod];
                                    if (!callback) {
                                        // the URL exists, but does not have the provided method defined for it
                                        methodNotAllowedHandler(request, response, next);
                                        return;
                                    }
                                
                                    var literals = route.literals;
                                    properUrl = literals[0];
                                    var argumentNames = route.argumentNames;
                                    var converters = route.converters;
                                    params = {};
                                    for (var k = 0, lenK = argumentNames.length; k < lenK; k += 1) {
                                        var unconvertedValue = match[k * 2 + 2];
                                        var convertedValue;
                                        try {
                                            convertedValue = converters[k](unconvertedValue);
                                        } catch (ex) {
                                            if (ex instanceof escort.ValidationError) {
                                                // if the converter explicitly throws a ValidationError, the route doesn't match.
                                                // thus, we need to keep searching for the correct route.
                                                callback = undefined;
                                                continue searchWithinPrefix;
                                            } else if (ex instanceof escort.CasingError) {
                                                unconvertedValue = ex.expectedCasing;
                                                convertedValue = converters[k](unconvertedValue); // guaranteed not to error
                                            } else {
                                                throw ex;
                                            }
                                        }
                                        properUrl += unconvertedValue;
                                        properUrl += literals[k + 1] || "";
                                        params[argumentNames[k]] = convertedValue;
                                    }
                                    if (route.hasEndingSlash) {
                                        properUrl += "/";
                                    }
                            
                                    if (actualUrl !== properUrl) {
                                        redirectCache[actualUrl] = properUrl;
                                        movedPermanently(response, properUrl + querystring);
                                        return;
                                    }
                                    
                                    // params needs to be frozen since it will be potentially used in later requests through the dynamic route caching system
                                    freeze(params);
                                    dynamicRouteCache[actualUrl] = {
                                        descriptor: descriptor,
                                        params: params
                                    };
                                    
                                    // we're done, so we need to break out of the outer for loop
                                    break searchDynamicRoutes;
                                }
                            }
                        }
                    }
                    
                    if (!callback) {
                        // route was unable to be located
                        if (notFoundHandler) {
                            notFoundHandler(request, response, next);
                        } else {
                            next();
                        }
                        return;
                    }
                    
                    // set params on request as well as pass it into the callback.
                    request.params = params;
                    // the descriptor is passed in as "this" so that the user can do this.post(request, response) from their get callback.
                    callback.call(descriptor, request, response, params, !notFoundHandler ? next : function (err) {
                        if (err) {
                            next(err);
                        } else {
                            notFoundHandler(request, response, next);
                        }
                    });
                } catch (err) {
                    next(err);
                }
            }
824113
private void readBufferAndLogMetrics(final Operation currentOp,
    final ByteBuffer rbuf, final MemcachedNode node) throws IOException {
    currentOp.readFromBuffer(rbuf);
    if (currentOp.getState() == OperationState.COMPLETE) {
      getLogger().debug("Completed read op: %s and giving the next %d "
        + "bytes", currentOp, rbuf.remaining());
      Operation op = node.removeCurrentReadOp();
      assert op == currentOp : "Expected to pop " + currentOp + " got "
        + op;

      if (op.hasErrored()) {
        metrics.markMeter(OVERALL_RESPONSE_FAIL_METRIC);
      } else {
        metrics.markMeter(OVERALL_RESPONSE_SUCC_METRIC);
      }
    } else if (currentOp.getState() == OperationState.RETRY) {
      handleRetryInformation(currentOp.getErrorMsg());
      getLogger().debug("Reschedule read op due to NOT_MY_VBUCKET error: "
        + "%s ", currentOp);
      ((VBucketAware) currentOp).addNotMyVbucketNode(
        currentOp.getHandlingNode());
      Operation op = node.removeCurrentReadOp();
      assert op == currentOp : "Expected to pop " + currentOp + " got "
        + op;

      retryOperation(currentOp);
      metrics.markMeter(OVERALL_RESPONSE_RETRY_METRIC);
    }
  }
23216
private <T> QueryRunner<T> withPerSinkMetrics(
      final QueryRunner<T> sinkRunner,
      final QueryToolChest<T, ? extends Query<T>> queryToolChest,
      final SegmentId sinkSegmentId,
      final AtomicLong cpuTimeAccumulator
  )
  {
    // Note: reportSegmentAndCacheTime and reportSegmentTime are effectively the same here. They don't split apart
    // cache vs. non-cache due to the fact that Sinks may be partially cached and partially uncached. Making this
    // better would need to involve another accumulator like the cpuTimeAccumulator that we could share with the
    // sinkRunner.
    String sinkSegmentIdString = sinkSegmentId.toString();
    return CPUTimeMetricQueryRunner.safeBuild(
        new MetricsEmittingQueryRunner<>(
            emitter,
            queryToolChest,
            new MetricsEmittingQueryRunner<>(
                emitter,
                queryToolChest,
                sinkRunner,
                QueryMetrics::reportSegmentTime,
                queryMetrics -> queryMetrics.segment(sinkSegmentIdString)
            ),
            QueryMetrics::reportSegmentAndCacheTime,
            queryMetrics -> queryMetrics.segment(sinkSegmentIdString)
        ).withWaitMeasuredFromNow(),
        queryToolChest,
        emitter,
        cpuTimeAccumulator,
        false
    );
  }
1182514
def cache_path
      Pathname.new(Berkshelf.berkshelf_path)
        .join('.cache', 'hg', Digest::SHA1.hexdigest(uri))
    end
677024
public function getRoutesWithCache()
    {
        if ($this->cacheService == null) {
            // Retrieve the split parts
            return $this->getRoutesWithoutCache();
        } else {
            $routes = $this->cacheService->get('splashWordpressRoutes');
            if ($routes == null) {
                // No value in cache, let's get the URL nodes
                $routes = $this->getRoutesWithoutCache();
                $this->cacheService->set('splashWordpressRoutes', $routes);
            }

            return $routes;
        }
    }
773393
def cache_resource(dest_dir=@local_cache_dir, options={})
      unless dest_dir
        raise ArgumentError, "Must specify destination directory when creating resource", caller
      end
      self.local_cache_dir=dest_dir
      @size = update_cache(@url, @local_path, options)
      if options[:include_pack_gz]
        @relative_local_path_pack_gz = "#{@relative_local_path}.pack.gz"
        @local_path_pack_gz = "#{dest_dir}/#{@relative_local_path_pack_gz}"
        @size_pack_gz = update_cache(@url_pack_gz, @local_path_pack_gz, options)
      end
      @signature_verified ? @size : @signature_verified
    end
868201
def method_missing(m, *args, &block)
      if m.to_s.end_with?("_url") || m.to_s.end_with?("_path")
        "/"
      else
        super
      end
    end
181886
def expose_endpoint(self):
        
        @self._app.route('/metrics', methods=['GET'])
        async def expose_metrics(request):
            return raw(self._get_metrics_data(),
                       content_type=CONTENT_TYPE_LATEST)
272321
def _process_cache(self, d, path=()):
        """"""
        for k, v in d.iteritems():
            if not isinstance(v, dict):
                self.metrics.append((path + (k,), v))
            else:
                self._process_cache(v, path + (k,))
606658
private Deferred<Object> resolveMetric() {
    if (metric == null || metric.isEmpty()) {
      throw new IllegalArgumentException("The metric cannot be empty");
    }
    if (tags == null) {
      throw new IllegalArgumentException("Tags cannot be null or empty "
          + "when getting a TSUID");
    }
    
    class TagsCB implements Callback<Object, ArrayList<byte[]>> {
      @Override
      public Object call(final ArrayList<byte[]> tag_list) throws Exception {
        setTagUIDs(tag_list);
        return null;
      }
      @Override
      public String toString() {
        return "Tag resolution callback";
      }
    }
    
    class MetricCB implements Callback<Deferred<Object>, byte[]> {
      @Override
      public Deferred<Object> call(final byte[] uid) 
          throws Exception {
        setMetricUID(uid);
        if (tags.isEmpty()) {
          setTagUIDs(new ArrayList<byte[]>(0));
          return null;
        }
        return Tags.resolveAllAsync(tsdb, tags).addCallback(new TagsCB());
      }
      @Override
      public String toString() {
        return "Metric resolution callback";
      }
    }
    
    return tsdb.getUIDAsync(UniqueIdType.METRIC, metric)
        .addCallbackDeferring(new MetricCB());
  }
572130
public void doUpdates(MetricsContext unused) {
    // In case of running in LocalMode tracker == null
    if (tracker != null) {
      synchronized (tracker) {
        synchronized (this) {
          numRunningMaps = 0;
          numRunningReduces = 0;

          numWaitingMaps = 0;
          numWaitingReduces = 0;
          numTasksInMemory = 0;

          List<JobInProgress> jobs = tracker.getRunningJobs();
          for (JobInProgress jip : jobs) {
            for (TaskInProgress tip : jip.maps) {
              if (tip.isRunning()) {
                numRunningMaps++;
              } else if (tip.isRunnable()) {
                numWaitingMaps++;
              }
            }
            for (TaskInProgress tip : jip.reduces) {
              if (tip.isRunning()) {
                numRunningReduces++;
              } else if (tip.isRunnable()) {
                numWaitingReduces++;
              }

            }
            numTasksInMemory += jip.getTasks(TaskType.MAP).length;
            numTasksInMemory += jip.getTasks(TaskType.REDUCE).length;
          }

          // Get tracker metrics
          numTrackersDead = tracker.getDeadNodes().size();
          ClusterStatus cs = tracker.getClusterStatus(false);
          numTrackersExcluded = cs.getNumExcludedNodes();
        }
      }
    }
    synchronized (this) {
      metricsRecord.setMetric("map_slots", numMapSlots);
      metricsRecord.setMetric("reduce_slots", numReduceSlots);
      metricsRecord.incrMetric("blacklisted_maps", numBlackListedMapSlots);
      metricsRecord.incrMetric("blacklisted_reduces",
          numBlackListedReduceSlots);
      metricsRecord.incrMetric("jobs_submitted", numJobsSubmitted);
      metricsRecord.incrMetric("jobs_completed", numJobsCompleted);
      metricsRecord.setMetric("waiting_maps", numWaitingMaps);
      metricsRecord.setMetric("waiting_reduces", numWaitingReduces);

      metricsRecord.incrMetric("reserved_map_slots", numReservedMapSlots);
      metricsRecord.incrMetric("reserved_reduce_slots", numReservedReduceSlots);
      metricsRecord.incrMetric("occupied_map_slots", numOccupiedMapSlots);
      metricsRecord.incrMetric("occupied_reduce_slots", numOccupiedReduceSlots);

      metricsRecord.incrMetric("jobs_failed", numJobsFailed);
      metricsRecord.incrMetric("jobs_killed", numJobsKilled);

      metricsRecord.incrMetric("jobs_preparing", numJobsPreparing);
      metricsRecord.incrMetric("jobs_running", numJobsRunning);

      metricsRecord.setMetric("running_maps", numRunningMaps);
      metricsRecord.setMetric("running_reduces", numRunningReduces);

      metricsRecord.setMetric("num_tasks_in_memory", numTasksInMemory);

      metricsRecord.setMetric("trackers", numTrackers);
      metricsRecord.setMetric("trackers_blacklisted", numTrackersBlackListed);
      metricsRecord.setMetric("trackers_decommissioned",
          numTrackersDecommissioned);
      metricsRecord.setMetric("trackers_excluded", numTrackersExcluded);
      metricsRecord.setMetric("trackers_dead", numTrackersDead);

      metricsRecord.incrMetric("num_launched_jobs", numJobsLaunched);
      metricsRecord.incrMetric("total_submit_time", totalSubmitTime);

      aggregateJobStats.incrementMetricsAndReset(metricsRecord);

      // Update additional speculation stats for measuring the performance
      // of different kinds of speculation
      for (SpecStats.TaskType taskType : SpecStats.TaskType.values()) {
        for (SpecStats.SpecType specType : SpecStats.SpecType.values()) {
          for(SpecStats.StatType statType : SpecStats.StatType.values()) {
            String key = "speculation_by_" + specType.toString().toLowerCase()  
                + "_" + "rate_" + taskType.toString().toLowerCase() + "_" + 
                statType.toString().toLowerCase();
            long value = specStats.getStat(taskType, specType, statType);
            metricsRecord.setMetric(key, value);
          }
        }
      }

      
      for (Group group: countersToMetrics) {
        String groupName = group.getName();
        for (Counter counter : group) {
          String name = groupName + "_" + counter.getName();
          name = name.replaceAll("[^a-zA-Z_]", "_").toLowerCase();
          metricsRecord.incrMetric(name, counter.getValue());
        }
      }
      clearCounters();

      numJobsSubmitted = 0;
      numJobsCompleted = 0;
      numWaitingMaps = 0;
      numWaitingReduces = 0;
      numBlackListedMapSlots = 0;
      numBlackListedReduceSlots = 0;

      numReservedMapSlots = 0;
      numReservedReduceSlots = 0;
      numOccupiedMapSlots = 0;
      numOccupiedReduceSlots = 0;

      numJobsFailed = 0;
      numJobsKilled = 0;

      numJobsPreparing = 0;
      numJobsRunning = 0;

      numRunningMaps = 0;
      numRunningReduces = 0;

      numTrackers = 0;
      numTrackersBlackListed = 0;

      totalSubmitTime = 0;
      numJobsLaunched = 0;
    }
    metricsRecord.update();
  }