// Partition the MetricDatums into smaller slices of a max size so that are under the limit
// for the AWS API calls.
346607
func PartitionDatums(size int, datums []*cloudwatch.MetricDatum) [][]*cloudwatch.MetricDatum {

	numberOfPartitions := len(datums) / size
	if len(datums)%size != 0 {
		numberOfPartitions += 1
	}

	partitions := make([][]*cloudwatch.MetricDatum, numberOfPartitions)

	for i := 0; i < numberOfPartitions; i++ {
		start := size * i
		end := size * (i + 1)
		if end > len(datums) {
			end = len(datums)
		}

		partitions[i] = datums[start:end]
	}

	return partitions
}
134969
func (b *Blob) PartsSize() int64 {
	n := int64(0)
	for _, part := range b.ss.Parts {
		n += int64(part.Size)
	}
	return n
}
270146
func (p *PartitionedMemoryIdx) LoadPartition(partition int32, defs []schema.MetricDefinition) int {
	return p.Partition[partition].Load(defs)
}
806126
func partition(slice []int) int {
	pi := rand.Intn(len(slice))
	n := len(slice) - 1                       // convenience
	slice[n], slice[pi] = slice[pi], slice[n] // swap pivot to end
	b := 0                                    // boundry between larger and smaller elements. demarcates first element index larger than p[i]
	for i := 0; i < n; i++ {
		if slice[i] < slice[n] {
			slice[i], slice[b] = slice[b], slice[i] // smaller element, swap boundry element (large) with this smaller element
			b++                                     // and increment the boundry to point past the smaller element
		}
	}
	pi = b
	slice[n], slice[pi] = slice[pi], slice[n] // swap pivot to boundry between larger and smaller
	return pi                                 // and return the index
}
61169
func sliceCompress(data []byte) []byte {
	var buf bytes.Buffer
	cmp, _ := zlib.NewWriterLevel(&buf, zlib.BestSpeed)
	cmp.Write(data)
	cmp.Close()
	return buf.Bytes()
}
1144677
func (a *HistoricalApi) clusterAggregations(request *restful.Request, response *restful.Response) {
	key := core.HistoricalKey{ObjectType: core.MetricSetTypeCluster}
	a.processAggregationRequest(key, request, response)
}
711447
func MetricsScrapingOption(path string) ServeOption {
	return func(n *core.IpfsNode, _ net.Listener, mux *http.ServeMux) (*http.ServeMux, error) {
		mux.Handle(path, promhttp.HandlerFor(prometheus.DefaultGatherer, promhttp.HandlerOpts{}))
		return mux, nil
	}
}
469780
func Metrics(m metrics.Metrics) func(r *Rego) {
	return func(r *Rego) {
		r.metrics = m
	}
}
1147925
func Format(metrics []prometheus.Metric) []string {
	r := prometheus.NewRegistry()
	r.MustRegister(&collector{metrics: metrics})
	families, err := r.Gather()
	if err != nil {
		panic(err)
	}

	var buf strings.Builder
	e := expfmt.NewEncoder(&buf, expfmt.FmtText)
	for _, f := range families {
		if err = e.Encode(f); err != nil {
			panic(err)
		}
	}
	return strings.Split(strings.TrimSpace(buf.String()), "\n")
}
401994
func newPartitionMetrics(labels prometheus.Labels) *partitionMetrics {
	names := []string{"index_partition"} // All metrics have a partition
	for k := range labels {
		names = append(names, k)
	}
	sort.Strings(names)

	// type = {"index", "log"}
	fileNames := append(append([]string(nil), names...), "type")
	sort.Strings(fileNames)

	// level = [0, 7]
	compactionNames := append(append([]string(nil), names...), "level")
	sort.Strings(compactionNames)

	// status = {"ok", "error"}
	attemptedCompactionNames := append(append([]string(nil), compactionNames...), "status")
	sort.Strings(attemptedCompactionNames)

	return &partitionMetrics{
		SeriesCreated: prometheus.NewCounterVec(prometheus.CounterOpts{
			Namespace: namespace,
			Subsystem: partitionSubsystem,
			Name:      "series_created",
			Help:      "Number of series created in the partition.",
		}, names),
		SeriesCreatedDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
			Namespace: namespace,
			Subsystem: partitionSubsystem,
			Name:      "series_created_duration_ns",
			Help:      "Time taken in nanosecond to create single series.",
			// 30 buckets spaced exponentially between 100ns and ~19 us.
			Buckets: prometheus.ExponentialBuckets(100.0, 1.2, 30),
		}, names),
		SeriesDropped: prometheus.NewCounterVec(prometheus.CounterOpts{
			Namespace: namespace,
			Subsystem: partitionSubsystem,
			Name:      "series_dropped",
			Help:      "Number of series dropped from the partition.",
		}, names),
		Series: prometheus.NewGaugeVec(prometheus.GaugeOpts{
			Namespace: namespace,
			Subsystem: partitionSubsystem,
			Name:      "series_total",
			Help:      "Number of series in the partition.",
		}, names),
		Measurements: prometheus.NewGaugeVec(prometheus.GaugeOpts{
			Namespace: namespace,
			Subsystem: partitionSubsystem,
			Name:      "measurements_total",
			Help:      "Number of series in the partition.",
		}, names),
		FilesTotal: prometheus.NewGaugeVec(prometheus.GaugeOpts{
			Namespace: namespace,
			Subsystem: partitionSubsystem,
			Name:      "files_total",
			Help:      "Number of files in the partition.",
		}, fileNames),
		DiskSize: prometheus.NewGaugeVec(prometheus.GaugeOpts{
			Namespace: namespace,
			Subsystem: partitionSubsystem,
			Name:      "disk_bytes",
			Help:      "Number of bytes TSI partition is using on disk.",
		}, names),
		CompactionsActive: prometheus.NewGaugeVec(prometheus.GaugeOpts{
			Namespace: namespace,
			Subsystem: partitionSubsystem,
			Name:      "compactions_active",
			Help:      "Number of active partition compactions.",
		}, compactionNames),
		CompactionDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
			Namespace: namespace,
			Subsystem: partitionSubsystem,
			Name:      "compactions_duration_seconds",
			Help:      "Time taken for a successful compaction of partition.",
			// 30 buckets spaced exponentially between 1s and ~10 minutes.
			Buckets: prometheus.ExponentialBuckets(1.0, 1.25, 30),
		}, compactionNames),
		Compactions: prometheus.NewCounterVec(prometheus.CounterOpts{
			Namespace: namespace,
			Subsystem: partitionSubsystem,
			Name:      "compactions_total",
			Help:      "Number of compactions.",
		}, attemptedCompactionNames),
	}
}
924560
func split(data []byte) [][]byte {
	chunks := [][]byte{}

	start := 0
	dirDepth := 0
	for i, b := range data {
		switch b {
		case dirStartMark:
			dirDepth++
		case dirEndMark:
			dirDepth--
		case dirElementSep:
			if dirDepth == 0 {
				chunks = append(chunks, data[start:i+1])
				start = i + 1
			}
		}
	}
	chunks = append(chunks, data[start:])

	return chunks
}
906122
func (mvl *MetricsList) Aggregate() (*MetricsAggregate, error) {
	if len(mvl.data) == 0 {
		return nil, fmt.Errorf("MetricsList contains no data!")
	}

	if mvl.aggregate != nil {
		return mvl.aggregate, nil
	}

	mvl.Sort()
	sum, min, max := 0.0, mvl.First().Value, mvl.First().Value

	for _, v := range mvl.data {
		sum += v.Value
		switch {
		case v.Value < min:
			min = v.Value
		case v.Value > max:
			max = v.Value
		}
	}

	mvl.aggregate = &MetricsAggregate{
		Sum:         sum,
		firstMetric: mvl.First().Time,
		lastMetric:  mvl.Last().Time,
		Min:         min,
		Max:         max,
		Avg:         sum / float64(len(mvl.data)),
	}

	return mvl.aggregate, nil
}
842864
func (p *Partition) MeasurementIterator() (tsdb.MeasurementIterator, error) {
	fs, err := p.FileSet()
	if err != nil {
		return nil, err
	}
	return newFileSetMeasurementIterator(fs,
		NewTSDBMeasurementIteratorAdapter(fs.MeasurementIterator())), nil
}
501570
func extractCollectdDimensions(doit bool, metricName string) (string, map[string]string) {
	dimensions := make(map[string]string)
	if !doit {
		return metricName, dimensions
	}
	index := strings.Index(metricName, "..")
	var toAddDims map[string]string
	for {
		metricName, toAddDims = collectd.GetDimensionsFromName(&metricName)
		if len(toAddDims) == 0 {
			// we may have put two dots next to each other extracting this stuff, see
			// if there were two beforehand and if not, replace them if they occur with
			// a single dot
			// TODO could do better here if wavefront users prefixed all metrics with
			// collectd, we could know how they're constructed and could make them be
			// almost as good as coming from collectd.
			// could even be crazy and put the types.db file in here and provide
			// accurate metric types... overkill?
			if index == -1 {
				metricName = strings.Replace(metricName, "..", ".", -1)
			}

			return metricName, dimensions
		}
		for k, v := range toAddDims {
			dimensions[k] = v
		}
	}
}
506063
func Convert_v1_MetricStatus_To_autoscaling_MetricStatus(in *v1.MetricStatus, out *autoscaling.MetricStatus, s conversion.Scope) error {
	return autoConvert_v1_MetricStatus_To_autoscaling_MetricStatus(in, out, s)
}
1258361
func (d *Dataset) Partition(name string, shard int, sortOption *SortOption) *Dataset {
	indexes := sortOption.Indexes()
	if intArrayEquals(d.IsPartitionedBy, indexes) && shard == len(d.Shards) {
		return d
	}
	if 1 == len(d.Shards) && shard == 1 {
		return d
	}
	ret := d.partition_scatter(name, shard, indexes)
	if shard > 1 {
		ret = ret.partition_collect(name, shard, indexes)
	}
	ret.IsPartitionedBy = indexes
	return ret
}
173780
func (w *Writer) GetTermDimensions() (int, int) {
	cmd := exec.Command("stty", "size")
	cmd.Stdin = os.Stdin
	out, err := cmd.Output()
	if err != nil {
		return 80, 25
	}
	splits := strings.Split(strings.Trim(string(out), "\n"), " ")
	height, err := strconv.ParseInt(splits[0], 0, 0)
	width, err1 := strconv.ParseInt(splits[1], 0, 0)
	if err != nil || err1 != nil {
		return 80, 25
	}
	return int(width), int(height)
}