Filters common attributes from list of metrics and writes them to result metric.

@param  metrics  - The set of metrics that needs to be filtered
@param  result   - The resultant metric that gets populated with the common tags
497540
public static void setCommonAttributes(List<Metric> metrics, Metric result) {
        MetricDistiller distiller = new MetricDistiller();

        distiller.distill(metrics);
        result.setDisplayName(distiller.getDisplayName());
        result.setUnits(distiller.getUnits());
        result.setTags(distiller.getTags());
    }
266863
private AbstractSigarMetricSet<?> init(AbstractSigarMetricSet<?> metrics) {
		try {
			metrics.getSnapshot();
			return metrics;
		} catch (RuntimeException e) {
			logger.warn(e.getMessage() + ". (This exception is ignored)", e);
			return new EmptySigarMetricSet();
		}
	}
603572
def output_results(results, metric, options):
    
    formatter = options['Formatter']
    context = metric.copy()  # XXX might need to sanitize this
    try:
        context['dimension'] = list(metric['Dimensions'].values())[0]
    except AttributeError:
        context['dimension'] = ''
    for result in results:
        stat_keys = metric['Statistics']
        if not isinstance(stat_keys, list):
            stat_keys = [stat_keys]
        for statistic in stat_keys:
            context['statistic'] = statistic
            # get and then sanitize metric name, first copy the unit name from the
            # result to the context to keep the default format happy
            context['Unit'] = result['Unit']
            metric_name = (formatter % context).replace('/', '.').lower()
            line = '{0} {1} {2}\n'.format(
                metric_name,
                result[statistic],
                timegm(result['Timestamp'].timetuple()),
            )
            sys.stdout.write(line)
1344111
public MetricFilter metricsFilter() {
        if (id() == null) {
            return (name, metric) -> false;
        }
        return (name, metric) -> metricNames.contains(name);

    }
1224327
@Override
    public List<MetricSchemaRecord> filterRecords(SchemaQuery query) {
        requireNotDisposed();
        
        _logger.debug(query.toString());
        
        if(query instanceof MetricSchemaRecordQuery) {
        	long start = System.nanoTime();
        	List<MetricSchemaRecord> result = _schemaService.get(MetricSchemaRecordQuery.class.cast(query));
            _logger.debug("Time to filter records in ms: " + (System.nanoTime() - start) / 1000000);
            return result;
        } else {
        	long start = System.nanoTime();
        	List<MetricSchemaRecord> result = _schemaService.keywordSearch(KeywordQuery.class.cast(query));
            _logger.debug("Time to filter records in ms: " + (System.nanoTime() - start) / 1000000);
            return result;
        }
        
    }
883567
public void submitMetrics(MetricsRecord metricsRecord) {
    List<PoolMetadata> poolMetadatas = getPoolMetadataList();
    PoolFairnessCalculator.calculateFairness(poolMetadatas, metricsRecord);
    for (SchedulerForType scheduler: schedulersForTypes.values()) {
      scheduler.submitMetrics();
    }
  }
266599
def _match_metric(self, metric):
        
        if len(self._compiled_filters) == 0:
            return True
        for (collector, filter_regex) in self._compiled_filters:
            if collector != metric.getCollectorPath():
                continue
            if filter_regex.match(metric.getMetricPath()):
                return True
        return False
682158
private Collection<MetricDatum> filterOSMetrics(Collection<MetricDatum> data) {
        Collection<MetricDatum> output = new ArrayList<MetricDatum>(data.size());
        for (MetricDatum datum: data) {
            if (!OS_METRIC_NAME.equals(datum.getMetricName()))
                output.add(datum);
        }
        return output;
    }
133406
@Inject
    public void setReporterMetrics(@Nullable ReporterMetrics metrics) {
        if (metrics != null) {
            builder.metrics(metrics);
        }
    }
454411
protected void addBasicMetrics(Collection<Metric<?>> result) {
        // NOTE: ManagementFactory must not be used here since it fails on GAE
        Runtime runtime = Runtime.getRuntime();
        result.add(newMemoryMetric("mem", runtime.totalMemory() + getTotalNonHeapMemoryIfPossible()));
        result.add(newMemoryMetric("mem.free", runtime.freeMemory()));
        result.add(new Metric<>("processors", runtime.availableProcessors()));
        result.add(new Metric<>("instance.uptime", System.currentTimeMillis() - this.timestamp));
    }
284174
@Override
    public List<Metric> transform(QueryContext context, List<Metric> metrics) {
        SystemAssert.requireArgument(metrics != null, "Cannot transform null metric/metrics");

        List<Metric> result = new ArrayList<>(metrics.size());

        for (Metric metric : metrics) {
            Map<Long, Double> sortedDatapoints = new TreeMap<>();
            Double prevSum = 0.0;

            sortedDatapoints.putAll(metric.getDatapoints());
            for (Entry<Long, Double> entry : sortedDatapoints.entrySet()) {
                prevSum += entry.getValue();
                sortedDatapoints.put(entry.getKey(), prevSum);
            }
            metric.setDatapoints(sortedDatapoints);
            result.add(metric);
        }
        return result;
    }
91136
private Metric reduce(List<Metric> metrics) {
		SystemAssert.requireArgument(metrics != null, "Cannot transform empty metric/metrics");

		/*
		 * if (metrics.isEmpty()) { return new Metric(defaultScope, defaultMetricName); }
		 */
		MetricDistiller distiller = new MetricDistiller();

		distiller.distill(metrics);

		Map<Long, List<Double>> collated = collate(metrics);
		Map<Long, Double> minDatapoints = reduce(collated);
		String newMetricName = distiller.getMetric() == null ? defaultMetricName : distiller.getMetric();
		String newScopeName = distiller.getScope() == null ? defaultScope : distiller.getScope();
		Metric newMetric = new Metric(newScopeName, newMetricName);

		newMetric.setDisplayName(distiller.getDisplayName());
		newMetric.setUnits(distiller.getUnits());
		newMetric.setTags(distiller.getTags());
		newMetric.setDatapoints(minDatapoints);
		return newMetric;
	}
1161602
public void removeAll() {
        for(Iterator<Map.Entry<MetricName, Metric>> it = metrics.entrySet().iterator(); it.hasNext();) {
            Map.Entry<MetricName, Metric> entry = it.next();
            Metric metric = entry.getValue();
            if(metric != null) {
                onMetricRemoved(entry.getKey(), metric);
            }
            it.remove();
        }
    }
88588
@SuppressWarnings("unchecked")
  private void gatherOneMetric(
      String metricName,
      Metrics.MetricPublisherPublishMessage.Builder builder) {
    Object metricValue = metrics.get(metricName).getValueAndReset();
    // Decide how to handle the metric based on type
    if (metricValue == null) {
      return;
    }
    if (metricValue instanceof Map) {
      for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) metricValue).entrySet()) {
        if (entry.getKey() != null && entry.getValue() != null) {
          addDataToMetricPublisher(
              builder, metricName + "/" + entry.getKey().toString(), entry.getValue());
        }
      }
    } else if (metricValue instanceof Collection) {
      int index = 0;
      for (Object value : (Collection) metricValue) {
        addDataToMetricPublisher(builder, metricName + "/" + (index++), value);
      }
    } else {
      addDataToMetricPublisher(builder, metricName, metricValue);
    }
  }
1210586
@Override
    public List<Metric> transform(QueryContext context, List<Metric> metrics) {
        SystemAssert.requireArgument(metrics != null, "Cannot transform empty metric/metrics");
        if (metrics.isEmpty()) {
            return metrics;
        }

        // do a union transform, the reducer perform a sum calculation
        Transform unionTransform = new MetricUnionTransform(new CountValueUnionReducer());
        List<Metric> sumUnitMetric = unionTransform.transform(null, metrics);

        // union of all timestamp
        Set<Long> unionKeyset = sumUnitMetric.get(0).getDatapoints().keySet();

        // create a list of metrics, for every metric it has union of all timestamps
        List<Metric> paddingMetrics = new ArrayList<Metric>();

        // Padding Zeros for every datapoints map in every metric
        for (Metric metric : metrics) {
            Map<Long, Double> paddingDatapoints = new TreeMap<>();
            Set<Long> metricDPKeyset = metric.getDatapoints().keySet();

            // Calculate those timestamps this datapoint map doesn't have
            for (Long unionKey : unionKeyset) {
                if (!metricDPKeyset.contains(unionKey)) {
                    paddingDatapoints.put(unionKey, 0.0);
                }
            }

            // create paddingDatapoints
            paddingDatapoints.putAll(metric.getDatapoints());
            metric.setDatapoints(paddingDatapoints);
            paddingMetrics.add(metric);
        }

        // adding base metric
        paddingMetrics.add(sumUnitMetric.get(0));

        // do a divide_v transform
        // Transform divide_vTransform = transformFactory.createMetricZipperTransform(Function.DIVIDE_V);
        Transform divide_vTransform = new MetricZipperTransform(new DivideValueZipper());

        return divide_vTransform.transform(null, paddingMetrics);
    }
905924
private void addMetrics(List<MetricDatum> list,
            MetricValues metricValues,
            StandardUnit unit) {
        List<MachineMetric> machineMetrics = metricValues.getMetrics();
        List<Long> values = metricValues.getValues();
        for (int i=0; i < machineMetrics.size(); i++) {
            MachineMetric metric = machineMetrics.get(i);
            long val = values.get(i).longValue();
            // skip zero values in some cases
            if (val != 0 || metric.includeZeroValue()) {
                MetricDatum datum = new MetricDatum()
                    .withMetricName(metric.getMetricName())
                    .withDimensions(
                        new Dimension()
                        .withName(metric.getDimensionName())
                        .withValue(metric.name()))
                    .withUnit(unit)
                    .withValue((double) val)
                    ;
                list.add(datum);
            }
        }
    }
277730
public void setMetricsToAnnotate(List<String> metricsToAnnotate) {
        this.metricsToAnnotate.clear();
        if (metricsToAnnotate != null && !metricsToAnnotate.isEmpty()) {
            for (String metric : metricsToAnnotate) {
                requireArgument(getMetricToAnnotate(metric) != null, "Metrics to annotate should be of the form 'scope:metric[{[tagk=tagv]+}]");
                this.metricsToAnnotate.add(metric);
            }
        }
    }