Send multiple different metric_ids to the server in a single batch. Metrics can be a mixture
        of types.

        :param data: A dict or a list of dicts created with create_metric(metric_type, metric_id, datapoints)
503180
def put(self, data):
        
        if not isinstance(data, list):
            data = [data]

        r = collections.defaultdict(list)

        for d in data:
            metric_type = d.pop('type', None)
            if metric_type is None:
                raise HawkularError('Undefined MetricType')
            r[metric_type].append(d)

        # This isn't transactional, but .. ouh well. One can always repost everything.
        for l in r:
            self._post(self._get_metrics_raw_url(self._get_url(l)), r[l],parse_json=False)
215327
async def AddMetricBatches(self, batches):
        '''
        
        '''
        # map input types to rpc msg
        _params = dict()
        msg = dict(type='MetricsAdder',
                   request='AddMetricBatches',
                   version=2,
                   params=_params)
        _params['batches'] = batches
        reply = await self.rpc(msg)
        return reply
540053
def send(self, path, value, metric_type):
        
        msg = self._msg_format.format(
            path=self._build_path(path, metric_type),
            value=value,
            metric_type=metric_type)

        LOGGER.debug('Sending %s to %s:%s', msg.encode('ascii'),
                     self._host, self._port)

        try:
            if self._tcp:
                if self._sock.closed():
                    return
                return self._sock.write(msg.encode('ascii'))

            self._sock.sendto(msg.encode('ascii'), (self._host, self._port))
        except iostream.StreamClosedError as error:  # pragma: nocover
            LOGGER.warning('Error sending TCP statsd metric: %s', error)
        except (OSError, socket.error) as error:  # pragma: nocover
            LOGGER.exception('Error sending statsd metric: %s', error)
294572
def _process_metric(self, data, metric, xtype, path, xform=None, tags=None, hostname=None):
        
        value = data

        # Traverse the nested dictionaries
        for key in path.split('.'):
            if value is not None:
                value = value.get(key)
            else:
                break

        if value is not None:
            if xform:
                value = xform(value)
            if xtype == "gauge":
                self.gauge(metric, value, tags=tags, hostname=hostname)
            else:
                self.rate(metric, value, tags=tags, hostname=hostname)
        else:
            self.log.debug("Metric not found: %s -> %s", path, metric)
21512
function Metrics(requests) {
  this.requests = requests;             // The total amount of requests send

  this.connections = 0;                 // Connections established
  this.disconnects = 0;                 // Closed connections
  this.failures = 0;                    // Connections that received an error

  this.errors = Object.create(null);    // Collection of different errors
  this.timing = Object.create(null);    // Different timings

  this.latency = new Stats();           // Latencies of the echo'd messages
  this.handshaking = new Stats();       // Handshake duration

  this.read = 0;                        // Bytes read
  this.send = 0;                        // Bytes send

  // Start tracking
  this.start();
}
812848
def _set_metrics_from_json(self, metrics_json, metrics, tags):
        
        for status, (metric_name, metric_type) in iteritems(metrics):
            metric_status = metrics_json.get(status)

            if metric_status is not None:
                self._set_metric(metric_name, metric_type, metric_status, tags=tags)
1076881
def write_metrics(baseName, values):
    
    m = open(baseName  + '_metrics.txt', 'w')
    for key in values:
        m.write(key + '=' + str(values[key]) + "\n")
    m.flush()
    m.close()
447829
def write(self, name, **data):
        

        data["name"] = name
        if not ("timestamp" in data):
            data["timestamp"] = datetime.utcnow()

        try:
            self.producer.send(topic=self.topic, value=data)
            self.producer.flush()
        except (KafkaTimeoutError, NoBrokersAvailable) as exc:
            logger.warning('writing metric %r failure %r', data, exc)
19627
public void sendAllMessage() {
    if (!isConnected()) {
      return;
    }

    LOG.info("Flushing all pending data in MetricsManagerClient");
    // Collect all tuples in queue
    for (Communicator<Metrics.MetricPublisherPublishMessage> c : outMetricsQueues) {
      int size = c.size();
      for (int i = 0; i < size; i++) {
        Metrics.MetricPublisherPublishMessage m = c.poll();
        sendMessage(m);
      }
    }
  }
609905
def insert_metric_changes(db, metrics, metric_mapping, commit):
    
    values = [
        [commit.sha, metric_mapping[metric.name], metric.value]
        for metric in metrics
        if metric.value != 0
    ]
    db.executemany(
        'INSERT INTO metric_changes (sha, metric_id, value) VALUES (?, ?, ?)',
        values,
    )
663370
def process(self, metric):
        
        for rmq_server in self.connections.keys():
            try:
                if ((self.connections[rmq_server] is None or
                     self.connections[rmq_server].is_open is False)):
                    self._bind(rmq_server)

                channel = self.channels[rmq_server]
                channel.basic_publish(exchange=self.rmq_exchange,
                                      routing_key='', body="%s" % metric)
            except Exception as exception:
                self.log.error(
                    "Failed publishing to %s, attempting reconnect",
                    rmq_server)
                self.log.debug("Caught exception: %s", exception)
                self._unbind(rmq_server)
                self._bind(rmq_server)
1349233
private void writeMetrics() throws IOException {
        if (metrics.size() > 0) {
            try {
                byte[] payload = pickleMetrics(metrics);
                byte[] header = ByteBuffer.allocate(4).putInt(payload.length).array();

                OutputStream outputStream = socket.getOutputStream();
                outputStream.write(header);
                outputStream.write(payload);
                outputStream.flush();

                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Wrote {} metrics", metrics.size());
                }
            } catch (IOException e) {
                this.failures++;
                throw e;
            } finally {
                // if there was an error, we might miss some data. for now, drop those on the floor and
                // try to keep going.
                metrics.clear();
            }

        }
    }
444086
def _process_metrics(
        self, data, url, services_incl_filter=None, services_excl_filter=None, custom_tags=None, active_tag=None
    ):
        
        hostname = data['svname']
        service_name = data['pxname']
        back_or_front = data['back_or_front']
        custom_tags = [] if custom_tags is None else custom_tags
        active_tag = [] if active_tag is None else active_tag
        tags = ["type:%s" % back_or_front, "instance_url:%s" % url, "service:%s" % service_name]
        tags.extend(custom_tags)
        tags.extend(active_tag)

        if self._is_service_excl_filtered(service_name, services_incl_filter, services_excl_filter):
            return

        if back_or_front == Services.BACKEND:
            tags.append('backend:%s' % hostname)
            if data.get('addr'):
                tags.append('server_address:{}'.format(data.get('addr')))

        for key, value in data.items():
            if HAProxy.METRICS.get(key):
                suffix = HAProxy.METRICS[key][1]
                name = "haproxy.%s.%s" % (back_or_front.lower(), suffix)
                try:
                    if HAProxy.METRICS[key][0] == 'rate':
                        self.rate(name, float(value), tags=tags)
                    else:
                        self.gauge(name, float(value), tags=tags)
                except ValueError:
                    pass
1344797
def do_metric_create_raw(mc, args):
    ''''''
    try:
        mc.metrics.create(**args.jsonbody)
    except (osc_exc.ClientException, k_exc.HttpError) as he:
        raise osc_exc.CommandError('%s\n%s' % (he.message, he.details))
    else:
        print('Successfully created metric')
339637
def add_metric(self, metric_id):
        
        payload = {
            'metric_id': metric_id
        }
        data = json.dumps(payload)
        req = self.request(self.mist_client.uri+"/clouds/"+self.cloud.id+"/machines/"+self.id+"/metrics", data=data)
        req.put()
943280
def _publish_metrics(self, prev_keys, key, data, publishfn=None):
        """"""
        if key not in data:
            return
        value = data[key]
        keys = prev_keys + [key]
        if not publishfn:
            publishfn = self.publish
        if isinstance(value, dict):
            for new_key in value:
                self._publish_metrics(keys, new_key, value)
        elif isinstance(value, int) or isinstance(value, float):
            publishfn('.'.join(keys), value)
        elif isinstance(value, long):
            publishfn('.'.join(keys), float(value))
455748
def write_diversity_metrics(data, sample_ids, fp=None):
    
    if fp is None:
        fp = "./diversity_data.txt"

    with open(fp, "w") as outf:
        out = csv.writer(outf, delimiter="\t")
        out.writerow(["SampleID", "Group", "Calculation"])
        for group, d in data.iteritems():
            for sid, value in d.iteritems():
                out.writerow([sid, group, value])