TODO: should be grouped with the metric name strategy
767666
private <E extends Member & AnnotatedElement> String metricName(E element, Class<? extends Annotation> type, String name, boolean absolute) {
        String metric = name.isEmpty() ? defaultName(element, type) : metricName.of(name);
        return absolute ? metric : MetricRegistry.name(element.getDeclaringClass(), metric);
    }
709177
protected void addMetric(String name, Metric metric) {
		if (metric == null) {
			LOG.warn("Ignoring attempted registration of a metric due to being null for name {}.", name);
			return;
		}
		// add the metric only if the group is still open
		synchronized (this) {
			if (!closed) {
				// immediately put without a 'contains' check to optimize the common case (no collision)
				// collisions are resolved later
				Metric prior = metrics.put(name, metric);

				// check for collisions with other metric names
				if (prior == null) {
					// no other metric with this name yet

					if (groups.containsKey(name)) {
						// we warn here, rather than failing, because metrics are tools that should not fail the
						// program when used incorrectly
						LOG.warn("Name collision: Adding a metric with the same name as a metric subgroup: '" +
								name + "'. Metric might not get properly reported. " + Arrays.toString(scopeComponents));
					}

					registry.register(metric, name, this);
				}
				else {
					// we had a collision. put back the original value
					metrics.put(name, prior);

					// we warn here, rather than failing, because metrics are tools that should not fail the
					// program when used incorrectly
					LOG.warn("Name collision: Group already contains a Metric with the name '" +
							name + "'. Metric will not be reported." + Arrays.toString(scopeComponents));
				}
			}
		}
	}
416966
def accumulate_metric(cls, name, value):
        
        metrics_cache = cls._get_metrics_cache()
        metrics_cache.setdefault(name, 0)
        metrics_cache.set(name, value)
1110230
def text_fd_to_metric_families(fd):
    
    name = None
    allowed_names = []
    eof = False

    seen_metrics = set()

    def build_metric(name, documentation, typ, unit, samples):
        if name in seen_metrics:
            raise ValueError("Duplicate metric: " + name)
        seen_metrics.add(name)
        if typ is None:
            typ = 'unknown'
        if documentation is None:
            documentation = ''
        if unit is None:
            unit = ''
        if unit and not name.endswith("_" + unit):
            raise ValueError("Unit does not match metric name: " + name)
        if unit and typ in ['info', 'stateset']:
            raise ValueError("Units not allowed for this metric type: " + name)
        if typ in ['histogram', 'gaugehistogram']:
            _check_histogram(samples, name)
        metric = Metric(name, documentation, typ, unit)
        # TODO: check labelvalues are valid utf8
        metric.samples = samples
        return metric

    for line in fd:
        if line[-1] == '\n':
            line = line[:-1]

        if eof:
            raise ValueError("Received line after # EOF: " + line)

        if line == '# EOF':
            eof = True
        elif line.startswith('#'):
            parts = line.split(' ', 3)
            if len(parts) < 4:
                raise ValueError("Invalid line: " + line)
            if parts[2] == name and samples:
                raise ValueError("Received metadata after samples: " + line)
            if parts[2] != name:
                if name is not None:
                    yield build_metric(name, documentation, typ, unit, samples)
                # New metric
                name = parts[2]
                unit = None
                typ = None
                documentation = None
                group = None
                seen_groups = set()
                group_timestamp = None
                group_timestamp_samples = set()
                samples = []
                allowed_names = [parts[2]]

            if parts[1] == 'HELP':
                if documentation is not None:
                    raise ValueError("More than one HELP for metric: " + line)
                if len(parts) == 4:
                    documentation = _unescape_help(parts[3])
                elif len(parts) == 3:
                    raise ValueError("Invalid line: " + line)
            elif parts[1] == 'TYPE':
                if typ is not None:
                    raise ValueError("More than one TYPE for metric: " + line)
                typ = parts[3]
                if typ == 'untyped':
                    raise ValueError("Invalid TYPE for metric: " + line)
                allowed_names = {
                    'counter': ['_total', '_created'],
                    'summary': ['_count', '_sum', '', '_created'],
                    'histogram': ['_count', '_sum', '_bucket', '_created'],
                    'gaugehistogram': ['_gcount', '_gsum', '_bucket'],
                    'info': ['_info'],
                }.get(typ, [''])
                allowed_names = [name + n for n in allowed_names]
            elif parts[1] == 'UNIT':
                if unit is not None:
                    raise ValueError("More than one UNIT for metric: " + line)
                unit = parts[3]
            else:
                raise ValueError("Invalid line: " + line)
        else:
            sample = _parse_sample(line)
            if sample.name not in allowed_names:
                if name is not None:
                    yield build_metric(name, documentation, typ, unit, samples)
                # Start an unknown metric.
                name = sample.name
                documentation = None
                unit = None
                typ = 'unknown'
                samples = []
                group = None
                group_timestamp = None
                group_timestamp_samples = set()
                seen_groups = set()
                allowed_names = [sample.name]

            if typ == 'stateset' and name not in sample.labels:
                raise ValueError("Stateset missing label: " + line)
            if (typ in ['histogram', 'gaugehistogram'] and name + '_bucket' == sample.name
                    and (float(sample.labels.get('le', -1)) < 0
                         or sample.labels['le'] != floatToGoString(sample.labels['le']))):
                raise ValueError("Invalid le label: " + line)
            if (typ == 'summary' and name == sample.name
                    and (not (0 <= float(sample.labels.get('quantile', -1)) <= 1)
                         or sample.labels['quantile'] != floatToGoString(sample.labels['quantile']))):
                raise ValueError("Invalid quantile label: " + line)

            g = tuple(sorted(_group_for_sample(sample, name, typ).items()))
            if group is not None and g != group and g in seen_groups:
                raise ValueError("Invalid metric grouping: " + line)
            if group is not None and g == group:
                if (sample.timestamp is None) != (group_timestamp is None):
                    raise ValueError("Mix of timestamp presence within a group: " + line)
                if group_timestamp is not None and group_timestamp > sample.timestamp and typ != 'info':
                    raise ValueError("Timestamps went backwards within a group: " + line)
            else:
                group_timestamp_samples = set()

            series_id = (sample.name, tuple(sorted(sample.labels.items())))
            if sample.timestamp != group_timestamp or series_id not in group_timestamp_samples:
                # Not a duplicate due to timestamp truncation.
                samples.append(sample)
            group_timestamp_samples.add(series_id)

            group = g
            group_timestamp = sample.timestamp
            seen_groups.add(g)

            if typ == 'stateset' and sample.value not in [0, 1]:
                raise ValueError("Stateset samples can only have values zero and one: " + line)
            if typ == 'info' and sample.value != 1:
                raise ValueError("Info samples can only have value one: " + line)
            if typ == 'summary' and name == sample.name and sample.value < 0:
                raise ValueError("Quantile values cannot be negative: " + line)
            if sample.name[len(name):] in ['_total', '_sum', '_count', '_bucket', '_gcount', '_gsum'] and math.isnan(
                    sample.value):
                raise ValueError("Counter-like samples cannot be NaN: " + line)
            if sample.name[len(name):] in ['_total', '_sum', '_count', '_bucket', '_gcount',
                                           '_gsum'] and sample.value < 0:
                raise ValueError("Counter-like samples cannot be negative: " + line)
            if sample.exemplar and not (
                    typ in ['histogram', 'gaugehistogram']
                    and sample.name.endswith('_bucket')):
                raise ValueError("Invalid line only histogram/gaugehistogram buckets can have exemplars: " + line)

    if name is not None:
        yield build_metric(name, documentation, typ, unit, samples)

    if not eof:
        raise ValueError("Missing # EOF at end")
985929
private String metricName(Executable executable, Class<? extends Annotation> type, String name, boolean absolute) {
        String metric = name.isEmpty() ? defaultName(executable, type) : metricName.of(name);
        return absolute ? metric : MetricRegistry.name(executable.getDeclaringClass(), metric);
    }
958819
@Override
  public String metricNamePrefix(boolean includeTagKeys) {
    return Joiner.on('.').join(includeTagKeys ? getTags() : this.tags.values());
  }
644267
def do_metric_name_list(mc, args):
    ''''''
    fields = {}
    if args.dimensions:
        fields['dimensions'] = utils.format_dimensions_query(args.dimensions)
    if args.limit:
        fields['limit'] = args.limit
    if args.offset:
        fields['offset'] = args.offset
    if args.tenant_id:
        fields['tenant_id'] = args.tenant_id

    try:
        metric_names = mc.metrics.list_names(**fields)
    except (osc_exc.ClientException, k_exc.HttpError) as he:
        raise osc_exc.CommandError('%s\n%s' % (he.message, he.details))
    else:
        if args.json:
            print(utils.json_formatter(metric_names))
            return
        if isinstance(metric_names, list):
            utils.print_list(metric_names, ['Name'], formatters={'Name': lambda x: x['name']})
646890
def _resolve_metric(self, original_metric_name, metrics_to_collect, prefix=""):
        

        submit_method = (
            metrics_to_collect[original_metric_name][0]
            if isinstance(metrics_to_collect[original_metric_name], tuple)
            else metrics_to_collect[original_metric_name]
        )
        metric_name = (
            metrics_to_collect[original_metric_name][1]
            if isinstance(metrics_to_collect[original_metric_name], tuple)
            else original_metric_name
        )

        return submit_method, self._normalize(metric_name, submit_method, prefix)
1075182
private static String getMasterMetricName(String name) {
    String result = CACHED_METRICS.get(name);
    if (result != null) {
      return result;
    }
    return CACHED_METRICS.computeIfAbsent(name, n -> InstanceType.MASTER.toString() + "." + name);
  }
836608
private boolean register(String name, Metric metric)
    { 
        boolean ret = allColumnFamilyMetrics.putIfAbsent(name,  new HashSet<Metric>()) == null;
        allColumnFamilyMetrics.get(name).add(metric);
        all.add(name);
        return ret;
    }
623427
public static MetricName join(MetricName... parts) {
        final StringBuilder nameBuilder = new StringBuilder();
        final Map<String, String> tags = new HashMap<>();

        boolean first = true;

        for (MetricName part : parts) {
            final String name = part.getKey();

            if (name != null && !name.isEmpty()) {
                if (first) {
                    first = false;
                } else {
                    nameBuilder.append(SEPARATOR);
                }

                nameBuilder.append(name);
            }

            if (!part.getTags().isEmpty())
                tags.putAll(part.getTags());
        }

        return new MetricName(nameBuilder.toString(), tags);
    }
95721
def clean_metric_name(self, metric_name):
        
        if not self._clean_metric_name:
            return metric_name
        metric_name = str(metric_name)
        for _from, _to in self.cleaning_replacement_list:
            metric_name = metric_name.replace(_from, _to)
        return metric_name
326186
function (metricType, statsdKey) {
                statsdKey = statsdKey.replace(/([^a-zA-Z0-9:_])/g, '_');
                return [prefixes[metricType], '_', statsdKey].join('');
            }
1099556
@Override
  public void getMetrics(MetricsCollector collector, boolean all) {
    MetricsRecordBuilder metricsRecordBuilder = collector.addRecord("sparkShuffleService");

    for (Map.Entry<String, Metric> entry : metricSet.getMetrics().entrySet()) {
      collectMetric(metricsRecordBuilder, entry.getKey(), entry.getValue());
    }
  }
1030022
def run_tag_from_session_and_metric(session_name, metric_name):
  
  assert isinstance(session_name, six.string_types)
  assert isinstance(metric_name, api_pb2.MetricName)
  # os.path.join() will append a final slash if the group is empty; it seems
  # like multiplexer.Tensors won't recognize paths that end with a '/' so
  # we normalize the result of os.path.join() to remove the final '/' in that
  # case.
  run = os.path.normpath(os.path.join(session_name, metric_name.group))
  tag = metric_name.tag
  return run, tag
1034748
function AggregatorFactory(aggregatorFn) {
	return metrics => {
		if (metrics.length === 0) return;
		const result = {
			help: metrics[0].help,
			name: metrics[0].name,
			type: metrics[0].type,
			values: [],
			aggregator: metrics[0].aggregator
		};
		// Gather metrics by metricName and labels.
		const byLabels = new Grouper();
		metrics.forEach(metric => {
			metric.values.forEach(value => {
				const key = hashObject(value.labels);
				byLabels.add(`${value.metricName}_${key}`, value);
			});
		});
		// Apply aggregator function to gathered metrics.
		byLabels.forEach(values => {
			if (values.length === 0) return;
			const valObj = {
				value: aggregatorFn(values),
				labels: values[0].labels
			};
			if (values[0].metricName) {
				valObj.metricName = values[0].metricName;
			}
			// NB: Timestamps are omitted.
			result.values.push(valObj);
		});
		return result;
	};
}
22762
function(name, value) {
			if (typeof metricsAvgStorage[name] === 'undefined') {
				metricsAvgStorage[name] = [];
			}

			metricsAvgStorage[name].push(value);

			this.setMetric(name, getAverage(metricsAvgStorage[name]));
		}