create string to be used as metric type
188602
def namespaced_view_name(view_name, metric_prefix):
    
    metric_prefix = metric_prefix or "custom.googleapis.com/opencensus"
    return os.path.join(metric_prefix, view_name).replace('\\', '/')
589876
def generate_make_string(out_f, max_step):
    """"""
    steps = [2 ** n for n in xrange(int(math.log(max_step, 2)), -1, -1)]

    with Namespace(
        out_f,
        ['boost', 'metaparse', 'v{0}'.format(VERSION), 'impl']
    ) as nsp:
        generate_take(out_f, steps, nsp.prefix())

        out_f.write(
            '{0}template <int LenNow, int LenRemaining, char... Cs>\n'
            '{0}struct make_string;\n'
            '\n'
            '{0}template <char... Cs>'
            ' struct make_string<0, 0, Cs...> : string<> {{}};\n'
            .format(nsp.prefix())
        )

        disable_sun = False
        for i in reversed(steps):
            if i > 64 and not disable_sun:
                out_f.write('#ifndef __SUNPRO_CC\n')
                disable_sun = True
            out_f.write(
                '{0}template <int LenRemaining,{1}char... Cs>'
                ' struct make_string<{2},LenRemaining,{3}Cs...> :'
                ' concat<string<{4}>,'
                ' typename make_string<take(LenRemaining),'
                'LenRemaining-take(LenRemaining),Cs...>::type> {{}};\n'
                .format(
                    nsp.prefix(),
                    ''.join('char {0},'.format(n) for n in unique_names(i)),
                    i,
                    ''.join('{0},'.format(n) for n in unique_names(i)),
                    ','.join(unique_names(i))
                )
            )
        if disable_sun:
            out_f.write('#endif\n')
1051239
private String createString(String f)
    {
        return
            "dst="+dst+f+
            "pitch="+pitch+f+
            "value="+value+f+
            "elementSize="+elementSize+f+
            "width="+width+f+
            "height="+height;
    }
110591
def MetricValueTypeFromPythonType(python_type):
  """"""
  if python_type in (int, long):
    return rdf_stats.MetricMetadata.ValueType.INT
  elif python_type == float:
    return rdf_stats.MetricMetadata.ValueType.FLOAT
  else:
    raise ValueError("Invalid value type: %s" % python_type)
124450
def _metric_value(value_str, metric_type):
    
    if metric_type in (int, float):
        try:
            return metric_type(value_str)
        except ValueError:
            raise ValueError("Invalid {} metric value: {!r}".
                             format(metric_type.__class__.__name__, value_str))
    elif metric_type is six.text_type:
        # In Python 3, decode('unicode_escape) requires bytes, so we need
        # to encode to bytes. This also works in Python 2.
        return value_str.strip('"').encode('utf-8').decode('unicode_escape')
    else:
        assert metric_type is bool
        lower_str = value_str.lower()
        if lower_str == 'true':
            return True
        elif lower_str == 'false':
            return False
        else:
            raise ValueError("Invalid boolean metric value: {!r}".
                             format(value_str))
131839
static Map<String, Double> processMetrics(String prefix, Iterable<MetricsInfo> metrics) {
    Map<String, Double> map = new HashMap<>();
    for (MetricsInfo r : metrics) {
      try {
        map.put(prefix + r.getName(), Double.valueOf(r.getValue()));
      } catch (NumberFormatException ne) {
        LOG.log(Level.SEVERE, "Could not parse metric, Name: "
            + r.getName() + " Value: " + r.getValue(), ne);
      }
    }
    return map;
  }
380479
def create_string_buffer(init, size=None, encoding=sys.getdefaultencoding()):
    
    if isinstance(init, six.string_types + (six.binary_type,)):
        if size is None:
            size = len(init) + 1
        buftype = c_char * size
        buf = buftype()
        try:
            buf.value = init.encode(encoding)
        except AttributeError:
            buf.value = init

        return buf
    elif isinstance(init, six.integer_types):
        buftype = c_char * init
        buf = buftype()
        return buf
    raise TypeError(init)
1355249
def new_metric(name, class_, *args, **kwargs):
    

    with LOCK:
        try:
            item = REGISTRY[name]
        except KeyError:
            item = REGISTRY[name] = class_(*args, **kwargs)
            return item

    raise DuplicateMetricError("Metric {} already exists of type {}".format(name, type(item).__name__))
1227186
static String metricName(final TSDB tsdb, final byte[] row) {
    try {
      return metricNameAsync(tsdb, row).joinUninterruptibly();
    } catch (RuntimeException e) {
      throw e;
    } catch (Exception e) {
      throw new RuntimeException("Should never be here", e);
    }
  }
695380
def metric(slug, num=1, category=None, expire=None, date=None):
    """"""
    get_r().metric(slug, num=num, category=category, expire=expire, date=date)
997358
static String generateFullMetricName(String name, String type) {
    return SOURCE + DELIMITER + name + DELIMITER + type;
  }
777016
@VisibleForTesting
  static Metric createMetric(
      io.opencensus.metrics.export.MetricDescriptor metricDescriptor,
      List<LabelValue> labelValues,
      String domain,
      Map<LabelKey, LabelValue> constantLabels) {
    Metric.Builder builder = Metric.newBuilder();
    builder.setType(generateType(metricDescriptor.getName(), domain));
    Map<String, String> stringTagMap = Maps.newHashMap();
    List<LabelKey> labelKeys = metricDescriptor.getLabelKeys();
    for (int i = 0; i < labelValues.size(); i++) {
      String value = labelValues.get(i).getValue();
      if (value == null) {
        continue;
      }
      stringTagMap.put(labelKeys.get(i).getKey(), value);
    }
    for (Map.Entry<LabelKey, LabelValue> constantLabel : constantLabels.entrySet()) {
      String constantLabelKey = constantLabel.getKey().getKey();
      String constantLabelValue = constantLabel.getValue().getValue();
      constantLabelValue = constantLabelValue == null ? "" : constantLabelValue;
      stringTagMap.put(constantLabelKey, constantLabelValue);
    }
    builder.putAllLabels(stringTagMap);
    return builder.build();
  }
397868
def metric_parts(metric):
    """"""
    operator, met = resolve_metric_as_tuple(metric)
    return operator.name, met.name
708373
private String parseWithMetric(final String metric) {
    // TODO: Try to reduce code duplication with Tags.parseWithMetric().
    final int curly = metric.indexOf('{');
    if (curly < 0) {
      clearTags();
      return metric;
    }
    final int len = metric.length();
    if (metric.charAt(len - 1) != '}') {  // "foo{"
      clearTags();
      return null;  // Missing '}' at the end.
    } else if (curly == len - 2) {  // "foo{}"
      clearTags();
      return metric.substring(0, len - 2);
    }
    final int num_tags_before = getNumTags();
    
    final List<Filter> filters = new ArrayList<Filter>();
    final int close = metric.indexOf('}');
    int i = 0;
    if (close != metric.length() - 1) { // "foo{...}{tagk=filter}" 
      final int filter_bracket = metric.lastIndexOf('{');
      for (final String filter : metric.substring(filter_bracket + 1, 
          metric.length() - 1).split(",")) {
        if (filter.isEmpty()) {
          break;
        }
        final String[] kv = filter.split("=");
        if (kv.length != 2 || kv[0].isEmpty() || kv[1].isEmpty()) {
          continue;  // Invalid tag.
        }
        final Filter f = new Filter();
        f.tagk = kv[0];
        f.tagv = kv[1];
        f.is_groupby = false;
        filters.add(f);
        i++;  
      }
    }
    
    i = 0;
    for (final String tag : metric.substring(curly + 1, close).split(",")) {
      if (tag.isEmpty() && close != metric.length() - 1){
        break;
      }
      final String[] kv = tag.split("=");
      if (kv.length != 2 || kv[0].isEmpty() || kv[1].isEmpty()) {
        continue;  // Invalid tag.
      }
      final Filter f = new Filter();
      f.tagk = kv[0];
      f.tagv = kv[1];
      f.is_groupby = true;
      filters.add(f);
      i++;
    }
    if (!filters.isEmpty()) {
      Collections.sort(filters);
    }
    
    i = 0;
    for (int x = filters.size() - 1; x >= 0; x--) {
      final Filter filter = filters.get(x);
      if (i < num_tags_before) {
        setTag(i++, filter.tagk, filter.tagv, filter.is_groupby);
      } else {
        addTag(filter.tagk, filter.tagv, filter.is_groupby);
      }
    }
    
    if (i < num_tags_before) {
      setTag(i, "", "", true);
    } else {
      addTag();
    }
    // Remove extra tags.
    for (i++; i < num_tags_before; i++) {
      tagtable.removeRow(i + 1);
    }
    // Return the "foo" part of "foo{a=b,...,x=y}"
    return metric.substring(0, curly);
    
    /*
    // substring the tags out of "foo{a=b,...,x=y}" and parse them.
    int i = 0;  // Tag index.
    final int num_tags_before = getNumTags();
    for (final String tag : metric.substring(curly + 1, len - 1).split(",")) {
      final String[] kv = tag.split("=");
      if (kv.length != 2 || kv[0].isEmpty() || kv[1].isEmpty()) {
        setTag(i, "", "", true);
        continue;  // Invalid tag.
      }
      if (i < num_tags_before) {
        setTag(i, kv[0], kv[1], true);
      } else {
        addTag(kv[0], kv[1]);
      }
      i++;
    }
    // Leave an empty line at the end.
    if (i < num_tags_before) {
      setTag(i, "", "", true);
    } else {
      addTag();
    }
    // Remove extra tags.
    for (i++; i < num_tags_before; i++) {
      tagtable.removeRow(i + 1);
    }
    // Return the "foo" part of "foo{a=b,...,x=y}"
    return metric.substring(0, curly); */
  }
317469
def _normalize(self, metric_name, submit_method, prefix):
        
        metric_prefix = "mongodb." if not prefix else "mongodb.{0}.".format(prefix)
        metric_suffix = "ps" if submit_method == RATE else ""

        # Replace case-sensitive metric name characters
        for pattern, repl in iteritems(self.CASE_SENSITIVE_METRIC_NAME_SUFFIXES):
            metric_name = re.compile(pattern).sub(repl, metric_name)

        # Normalize, and wrap
        return u"{metric_prefix}{normalized_metric_name}{metric_suffix}".format(
            normalized_metric_name=self.normalize(metric_name.lower()),
            metric_prefix=metric_prefix,
            metric_suffix=metric_suffix,
        )
74344
private String constructMetricQueryKey(Long startTimeStampBoundary, MetricQuery query) {
        StringBuilder sb = new StringBuilder();

        sb.append(startTimeStampBoundary).append(":");
        sb.append(query.getNamespace()).append(":");
        sb.append(query.getScope()).append(":");
        sb.append(query.getMetric()).append(":");

        // sort the tag key and values within each tag key alphabetically
        Map<String, String> treeMap = new TreeMap<String, String>();

        for (Map.Entry<String, String> tag : query.getTags().entrySet()) {
            String[] tagValues = tag.getValue().split("\\|");

            Arrays.sort(tagValues);

            StringBuilder sbTag = new StringBuilder();
            String separator = "";

            for (String tagValue : tagValues) {
                sbTag.append(separator);
                separator = "|";
                sbTag.append(tagValue);
            }
            treeMap.put(tag.getKey(), sbTag.toString());
        }
        sb.append(treeMap).append(":");
        sb.append(query.getAggregator()).append(":");
        sb.append(query.getDownsampler()).append(":");
        sb.append(query.getDownsamplingPeriod());
        return sb.toString();
    }
861020
def String(length=None, **kwargs):
    """"""
    return Property(
        length=length,
        types=stringy_types,
        convert=to_string,
        **kwargs
    )