List all known metrics
2427
def list():
    ''''''
    for cls, metrics in metric_catalog.items():
        echo(white(cls.__name__))

        for metric in metrics.keys():
            echo('> {0}'.format(metric))
306673
def list_billing(region, filter_by_kwargs):
    """"""
    conn = boto.ec2.cloudwatch.connect_to_region(region)
    metrics = conn.list_metrics(metric_name='EstimatedCharges')
    # Filtering is based on metric Dimensions.  Only really valuable one is
    # ServiceName.
    if filter_by_kwargs:
        filter_key = filter_by_kwargs.keys()[0]
        filter_value = filter_by_kwargs.values()[0]
        if filter_value:
            filtered_metrics = [x for x in metrics if x.dimensions.get(filter_key) and x.dimensions.get(filter_key)[0] == filter_value]
        else:
            # ServiceName=''
            filtered_metrics = [x for x in metrics if not x.dimensions.get(filter_key)]
    else:
        filtered_metrics = metrics
    return filtered_metrics
1178709
def get_metrics(self):
        
        now = datetime.utcnow()
        metrics = set()
        for gauge in self.gauges.values():
            metrics.add(gauge.get_metric(now))
        return metrics
199662
def _collect_monitor_metrics(self, conn, tags):
        
        for entry in conn.entries:
            # Get metrics from monitor backend
            dn = entry.entry_dn.lower()
            if dn.endswith(self.CONNECTIONS_METRICS_DN):
                self._handle_connections_entry(entry, tags)
            elif dn.endswith(self.OPERATIONS_METRICS_DN):
                self._handle_operations_entry(entry, tags)
            elif dn.endswith(self.STATISTICS_METRICS_DN):
                self._handle_statistics_entry(entry, tags)
            elif dn.endswith(self.THREADS_METRICS_DN):
                self._handle_threads_entry(entry, tags)
            elif dn.endswith(self.TIME_METRICS_DN):
                self._handle_time_entry(entry, tags)
            elif dn.endswith(self.WAITERS_METRICS_DN):
                self._handle_waiters_entry(entry, tags)
1265542
def _build_session_metric_values(self, session_name):
    """"""

    # result is a list of api_pb2.MetricValue instances.
    result = []
    metric_infos = self._experiment.metric_infos
    for metric_info in metric_infos:
      metric_name = metric_info.name
      try:
        metric_eval = metrics.last_metric_eval(
            self._context.multiplexer,
            session_name,
            metric_name)
      except KeyError:
        # It's ok if we don't find the metric in the session.
        # We skip it here. For filtering and sorting purposes its value is None.
        continue

      # metric_eval is a 3-tuple of the form [wall_time, step, value]
      result.append(api_pb2.MetricValue(name=metric_name,
                                        wall_time_secs=metric_eval[0],
                                        training_step=metric_eval[1],
                                        value=metric_eval[2]))
    return result
28403
def calculate_metrics(self, model, train_loader, valid_loader, metrics_dict):
        """"""
        # Check whether or not it's time for validation as well
        self.log_count += 1
        log_valid = (
            valid_loader is not None
            and self.valid_every_X
            and not (self.log_count % self.valid_every_X)
        )

        metrics_dict = {}

        # Calculate custom metrics
        if self.config["log_train_metrics_func"] is not None:
            func = self.config["log_train_metrics_func"]
            func_list = func if isinstance(func, list) else [func]
            for func in func_list:
                metrics_dict = self._calculate_custom_metrics(
                    model, train_loader, func, metrics_dict, split="train"
                )
        if self.config["log_valid_metrics_func"] is not None and log_valid:
            func = self.config["log_valid_metrics_func"]
            func_list = func if isinstance(func, list) else [func]
            for func in func_list:
                metrics_dict = self._calculate_custom_metrics(
                    model, valid_loader, func, metrics_dict, split="valid"
                )

        # Calculate standard metrics
        metrics_dict = self._calculate_standard_metrics(
            model, train_loader, self.log_train_metrics, metrics_dict, "train"
        )

        if log_valid:
            metrics_dict = self._calculate_standard_metrics(
                model, valid_loader, self.log_valid_metrics, metrics_dict, "valid"
            )

        return metrics_dict
980927
public Page<Metric> listMetrics() {
    // [START listMetrics]
    Page<Metric> metrics = logging.listMetrics(ListOption.pageSize(100));
    for (Metric metric : metrics.iterateAll()) {
      // do something with the metric
    }
    // [END listMetrics]
    return metrics;
  }
829712
def results_overall_metrics(self):
        

        if self.overall['Nsys'] != 0:
            accuracy = self.overall['Ncorr'] / float(self.overall['Nsys'])
        else:
            accuracy = None

        return {
            'count': self.overall,
            'accuracy': accuracy
        }
442657
def _report_container_spec_metrics(self, pod_list, instance_tags):
        """"""
        for pod in pod_list['items']:
            pod_name = pod.get('metadata', {}).get('name')
            pod_phase = pod.get('status', {}).get('phase')
            if self._should_ignore_pod(pod_name, pod_phase):
                continue

            for ctr in pod['spec']['containers']:
                if not ctr.get('resources'):
                    continue

                c_name = ctr.get('name', '')
                cid = None
                for ctr_status in pod['status'].get('containerStatuses', []):
                    if ctr_status.get('name') == c_name:
                        # it is already prefixed with 'runtime://'
                        cid = ctr_status.get('containerID')
                        break
                if not cid:
                    continue

                pod_uid = pod.get('metadata', {}).get('uid')
                if self.pod_list_utils.is_excluded(cid, pod_uid):
                    continue

                tags = tagger.tag('%s' % cid, tagger.HIGH) + instance_tags

                try:
                    for resource, value_str in iteritems(ctr.get('resources', {}).get('requests', {})):
                        value = self.parse_quantity(value_str)
                        self.gauge('{}.{}.requests'.format(self.NAMESPACE, resource), value, tags)
                except (KeyError, AttributeError) as e:
                    self.log.debug("Unable to retrieve container requests for %s: %s", c_name, e)

                try:
                    for resource, value_str in iteritems(ctr.get('resources', {}).get('limits', {})):
                        value = self.parse_quantity(value_str)
                        self.gauge('{}.{}.limits'.format(self.NAMESPACE, resource), value, tags)
                except (KeyError, AttributeError) as e:
                    self.log.debug("Unable to retrieve container limits for %s: %s", c_name, e)
1110338
def _format_disk_metrics(self, metrics):
        """"""
        for name, raw_val in metrics.iteritems():
            if raw_val:
                match = DISK_STATS_RE.search(raw_val)
                if match is None or len(match.groups()) != 2:
                    self.log.warning('Can\'t parse value %s for disk metric %s. Dropping it.' % (raw_val, name))
                    metrics[name] = None
                val, unit = match.groups()
                # by default some are uppercased others lowercased. That's error prone.
                unit = unit.lower()
                try:
                    val = int(float(val) * UNIT_MAP[unit])
                    metrics[name] = val
                except KeyError:
                    self.log.error('Unrecognized unit %s for disk metric %s. Dropping it.' % (unit, name))
                    metrics[name] = None
        return metrics
630436
def metrics(self):
        
        masterThrp, backupThrp = self.getThroughputs(self.instances.masterId)
        r = self.instance_throughput_ratio(self.instances.masterId)
        m = [
            ("{} Monitor metrics:".format(self), None),
            ("Delta", self.Delta),
            ("Lambda", self.Lambda),
            ("Omega", self.Omega),
            ("instances started", self.instances.started),
            ("ordered request counts",
             {i: r[0] for i, r in self.numOrderedRequests.items()}),
            ("ordered request durations",
             {i: r[1] for i, r in self.numOrderedRequests.items()}),
            ("master request latencies", self.masterReqLatencies),
            ("client avg request latencies", {i: self.getLatency(i)
                                              for i in self.instances.ids}),
            ("throughput", {i: self.getThroughput(i)
                            for i in self.instances.ids}),
            ("master throughput", masterThrp),
            ("total requests", self.totalRequests),
            ("avg backup throughput", backupThrp),
            ("master throughput ratio", r)]
        return m
255517
def retrieve_metrics(self):
        

        time = np.array(self.list_dates)
        if len(time) >= 1:
            time -= time[0]
        return {'time': time, 'index': self.list_iters,
                'values': self.list_cv_values}
169166
def _compute_needed_metrics(self, instance, available_metrics):
        
        i_key = self._instance_key(instance)
        if self.in_compatibility_mode(instance):
            if instance.get('all_metrics', False):
                return available_metrics

            wanted_metrics = []
            # Get only the basic metrics
            for counter_id in available_metrics:
                # No cache yet, skip it for now
                if not self.metadata_cache.contains(i_key, counter_id):
                    self.log.debug(
                        "No metadata found for counter {}, will not collect it".format(ensure_unicode(counter_id))
                    )
                    continue
                metadata = self.metadata_cache.get_metadata(i_key, counter_id)
                if metadata.get('name') in BASIC_METRICS:
                    wanted_metrics.append(vim.PerformanceManager.MetricId(counterId=counter_id, instance="*"))

            return wanted_metrics
        else:
            # The metadata cache contains only metrics of the desired level, so use it to filter the metrics to keep
            return [
                vim.PerformanceManager.MetricId(counterId=counter_id, instance="*")
                for counter_id in available_metrics
                if self.metadata_cache.contains(i_key, counter_id)
            ]
853684
def log(self, metrics_dict):
        """"""
        if self.writer:
            self.write_to_file(metrics_dict)

        if self.verbose:
            self.print_to_screen(metrics_dict)
        self.reset()
929420
public static MetricInfo computeAllMetrics() {
        long start = System.currentTimeMillis();
        MetricInfo metricInfo = MetricUtils.mkMetricInfo();

        List<Map.Entry<String, AsmMetric>> entries = Lists.newLinkedList();
        if (enableStreamMetrics) {
            entries.addAll(streamMetrics.metrics.entrySet());
        }
        entries.addAll(taskMetrics.metrics.entrySet());
        entries.addAll(componentMetrics.metrics.entrySet());
        entries.addAll(compStreamMetrics.metrics.entrySet());
        entries.addAll(workerMetrics.metrics.entrySet());
        entries.addAll(nettyMetrics.metrics.entrySet());
        entries.addAll(topologyMetrics.metrics.entrySet());

        for (Map.Entry<String, AsmMetric> entry : entries) {
            String name = entry.getKey();
            AsmMetric metric = entry.getValue();

            // skip disabled metrics, double check
            if (disabledMetricNames.contains(metric.getShortName())) {
                continue;
            }
            Map<Integer, AsmSnapshot> snapshots = metric.getSnapshots();
            if (snapshots.size() == 0) {
                continue;
            }

            int op = metric.getOp();
            if ((op & AsmMetric.MetricOp.LOG) == AsmMetric.MetricOp.LOG) {
                MetricUtils.printMetricSnapshot(metric, snapshots);
            }

            if ((op & AsmMetric.MetricOp.REPORT) == AsmMetric.MetricOp.REPORT) {
                MetaType metaType = MetricUtils.metaType(metric.getMetricName());
                try {
                    if (metric instanceof AsmCounter) {
                        Map data = MetricUtils.toThriftCounterSnapshots(snapshots);
                        putIfNotEmpty(metricInfo.get_metrics(), name, data);
                    } else if (metric instanceof AsmGauge) {
                        Map data = MetricUtils.toThriftGaugeSnapshots(snapshots);
                        putIfNotEmpty(metricInfo.get_metrics(), name, data);
                    } else if (metric instanceof AsmMeter) {
                        Map data = MetricUtils.toThriftMeterSnapshots(snapshots);
                        putIfNotEmpty(metricInfo.get_metrics(), name, data);
                    } else if (metric instanceof AsmHistogram) {
                        Map data = MetricUtils.toThriftHistoSnapshots(metaType, snapshots);
                        putIfNotEmpty(metricInfo.get_metrics(), name, data);
                    }
                } catch (Exception ex) {
                    LOG.error("Error", ex);
                }
            }
        }

        if (debug) {
            MetricUtils.printMetricInfo(metricInfo, debugMetricNames);
        }
        LOG.debug("compute all metrics, cost:{}", System.currentTimeMillis() - start);
        return metricInfo;
    }
443262
def get_custom_metrics():
    
    _rse = mx.metric.create(rse)
    _rae = mx.metric.create(rae)
    _corr = mx.metric.create(corr)
    return mx.metric.create([_rae, _rse, _corr])
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']})