Return an immutable view of filtered metrics
161969
public Iterable<MetricsInfo> filter(Iterable<MetricsInfo> metricsInfos) {
    List<MetricsInfo> metricsFiltered = new ArrayList<MetricsInfo>();
    for (MetricsInfo metricsInfo : metricsInfos) {
      if (contains(metricsInfo.getName())) {
        metricsFiltered.add(metricsInfo);
      }
    }

    return metricsFiltered;
  }
405251
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'aggregations' in _dict:
            args['aggregations'] = [
                MetricTokenAggregation._from_dict(x)
                for x in (_dict.get('aggregations'))
            ]
        return cls(**args)
1084604
def metrics(self):
        
        return dict(
            (name, getattr(Metrics, config['type']))
            for name, config in six.iteritems(self._metrics)
        )
1058271
def process_metrics(self, snmp_data):
        ""
        self.metrics = {}
        for i in range(0, len(snmp_data)):
            mib_name = self.models[self.modem_type]['metrics'][i]
            conv = metric_mib[mib_name]['conv']
            self.metrics[mib_name] = conv(snmp_data[i])
1090723
def get_default_metrics(config):
    
    archivers = list_archivers(config)
    default_metrics = []

    for archiver in archivers:
        index = get_archiver_index(config, archiver)

        if len(index) == 0:
            logger.warning("No records found in the index, no metrics available")
            return []

        operators = index[0]["operators"]
        for operator in operators:
            o = resolve_operator(operator)
            if o.cls.default_metric_index is not None:
                metric = o.cls.metrics[o.cls.default_metric_index]
                default_metrics.append("{0}.{1}".format(o.cls.name, metric.name))
    return default_metrics
189529
async def metrics(self, offs, size=None):
        '''
        
        '''
        for i, (indx, item) in enumerate(self._metrics.iter(offs)):

            if size is not None and i >= size:
                return

            yield indx, item
6521
def get_metric(self, slug):
        
        results = OrderedDict()
        granularities = self._granularities()
        keys = self._build_keys(slug)
        for granularity, key in zip(granularities, keys):
            results[granularity] = self.r.get(key)
        return results
112704
@Override
    public SortedMap<String, Counter> getCounters(MetricFilter filter) {
        return getMetrics(Counter.class, filter);
    }
415156
def text_fd_to_metric_families(fd):
    
    name = ''
    documentation = ''
    typ = 'untyped'
    samples = []
    allowed_names = []

    def build_metric(name, documentation, typ, samples):
        # Munge counters into OpenMetrics representation
        # used internally.
        if typ == 'counter':
            if name.endswith('_total'):
                name = name[:-6]
            else:
                new_samples = []
                for s in samples:
                    new_samples.append(Sample(s[0] + '_total', *s[1:]))
                    samples = new_samples
        metric = Metric(name, documentation, typ)
        metric.samples = samples
        return metric

    for line in fd:
        line = line.strip()

        if line.startswith('#'):
            parts = line.split(None, 3)
            if len(parts) < 2:
                continue
            if parts[1] == 'HELP':
                if parts[2] != name:
                    if name != '':
                        yield build_metric(name, documentation, typ, samples)
                    # New metric
                    name = parts[2]
                    typ = 'untyped'
                    samples = []
                    allowed_names = [parts[2]]
                if len(parts) == 4:
                    documentation = _replace_help_escaping(parts[3])
                else:
                    documentation = ''
            elif parts[1] == 'TYPE':
                if parts[2] != name:
                    if name != '':
                        yield build_metric(name, documentation, typ, samples)
                    # New metric
                    name = parts[2]
                    documentation = ''
                    samples = []
                typ = parts[3]
                allowed_names = {
                    'counter': [''],
                    'gauge': [''],
                    'summary': ['_count', '_sum', ''],
                    'histogram': ['_count', '_sum', '_bucket'],
                }.get(typ, [''])
                allowed_names = [name + n for n in allowed_names]
            else:
                # Ignore other comment tokens
                pass
        elif line == '':
            # Ignore blank lines
            pass
        else:
            sample = _parse_sample(line)
            if sample.name not in allowed_names:
                if name != '':
                    yield build_metric(name, documentation, typ, samples)
                # New metric, yield immediately as untyped singleton
                name = ''
                documentation = ''
                typ = 'untyped'
                samples = []
                allowed_names = []
                yield build_metric(sample[0], documentation, typ, [sample])
            else:
                samples.append(sample)

    if name != '':
        yield build_metric(name, documentation, typ, samples)
808477
def group_for_view_by(view_by, measures)
      if view_by.nil? || measures.nil?
        return nil
      else
        return {
          metric: measures.first,
          dimension: view_by,
          rank: "DESCENDING",
          limit: 3
        }
      end
    end
911585
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'aggregations' in _dict:
            args['aggregations'] = [
                MetricAggregation._from_dict(x)
                for x in (_dict.get('aggregations'))
            ]
        return cls(**args)
372291
def search_metrics(self, query, fromTime=None, toTime=None, requestedDataPoints=600, maxDataPoints=800):
        ''''''
        def millisectimestamp(ts):
            '''Convert UNIX timestamp to milliseconds'''
            if ts > 10**12:
                ts = ts/(10**(len(str(ts))-13))
            else:
                ts = ts*10**(12-len(str(ts)))
            return int(ts)

        params = {'query': [{"query":query, "rowId":"A"}],
                  'startTime': millisectimestamp(fromTime),
                  'endTime': millisectimestamp(toTime),
                  'requestedDataPoints': requestedDataPoints,
                  'maxDataPoints': maxDataPoints}
        r = self.post('/metrics/results', params)
        return json.loads(r.text)
590131
private void getMetrics(
      MBeanServerConnection con,
      MetricFilter filter,
      List<Metric> metrics,
      ObjectName name)
      throws JMException, IOException {
    // Create tags from the object name
    TagList tags = createTagList(name);
    MBeanInfo info = con.getMBeanInfo(name);
    MBeanAttributeInfo[] attrInfos = info.getAttributes();

    // Restrict to attributes that match the filter
    List<String> matchingNames = new ArrayList<>();
    for (MBeanAttributeInfo attrInfo : attrInfos) {
      String attrName = attrInfo.getName();
      if (filter.matches(new MonitorConfig.Builder(attrName).withTags(tags).build())) {
        matchingNames.add(attrName);
      }
    }
    List<Attribute> attributeList = safelyLoadAttributes(con, name, matchingNames);

    for (Attribute attr : attributeList) {
      String attrName = attr.getName();
      Object obj = attr.getValue();
      if (obj instanceof TabularData) {
        ((TabularData) obj).values().stream()
            .filter(key -> key instanceof CompositeData)
            .forEach(key -> addTabularMetrics(filter, metrics, tags, attrName,
                (CompositeData) key));
      } else if (obj instanceof CompositeData) {
        addCompositeMetrics(filter, metrics, tags, attrName, (CompositeData) obj);
      } else {
        addMetric(metrics, attrName, tags, obj);
      }
    }
  }
582433
def update_metric(self, eval_metric, labels, pre_sliced=False):
        
        assert self.binded and self.params_initialized
        self._curr_module.update_metric(eval_metric, labels, pre_sliced)
504114
def metric_ids(self):
        
        return self._sorted_ingredients([
            d.id for d in self.values() if isinstance(d, Metric)
        ])
55818
private Map<String, String> getMetricFilterParameters( MetricFilterOptions options ) {
        if( options == null ) {
            return null;
        }

        Map<String, String> parameters = new HashMap<String, String>();

        AWSCloud.addValueIfNotNull(parameters, "MetricName", options.getMetricName());
        AWSCloud.addValueIfNotNull(parameters, "Namespace", options.getMetricNamespace());
        AWSCloud.addIndexedParameters(parameters, "Dimensions.member.", options.getMetricMetadata());

        if( parameters.size() == 0 ) {
            return null;
        }

        return parameters;
    }
1008483
def list_metrics():
    """"""
    for name, operator in ALL_OPERATORS.items():
        print(f"{name} operator:")
        if len(operator.cls.metrics) > 0:
            print(
                tabulate.tabulate(
                    headers=("Name", "Description", "Type"),
                    tabular_data=operator.cls.metrics,
                    tablefmt=DEFAULT_GRID_STYLE,
                )
            )