// GetAggregation fetches the given aggregations for one or more objects (specified by metricKeys) of
// the same type, within the given time interval, calculated over a series of buckets
428637
func (sink *influxdbSink) GetAggregation(metricName string, aggregations []core.AggregationType, metricKeys []core.HistoricalKey, start, end time.Time, bucketSize time.Duration) (map[core.HistoricalKey][]core.TimestampedAggregationValue, error) {
	for _, key := range metricKeys {
		if err := sink.checkSanitizedKey(&key); err != nil {
			return nil, err
		}
	}

	if err := sink.checkSanitizedMetricName(metricName); err != nil {
		return nil, err
	}

	// make it easy to look up where the different aggregations are in the list
	aggregationLookup := make(map[core.AggregationType]int, len(aggregations))
	for i, agg := range aggregations {
		aggregationLookup[agg] = i + 1
	}

	query := sink.composeAggregateQuery(metricName, nil, aggregations, metricKeys, start, end, bucketSize)

	sink.RLock()
	defer sink.RUnlock()

	resp, err := sink.runQuery(query)
	if err != nil {
		return nil, err
	}

	// TODO: when there are too many points (e.g. certain times when a start time is not specified), Influx will sometimes return only a single bucket
	//       instead of returning an error.  We should detect this case and return an error ourselves (or maybe just require a start time at the API level)
	res := make(map[core.HistoricalKey][]core.TimestampedAggregationValue, len(metricKeys))
	for i, key := range metricKeys {
		if len(resp[i].Series) < 1 {
			return nil, fmt.Errorf("No results for metric %q describing %q", metricName, key.String())
		}

		vals, err := sink.parseAggregateQueryRow(resp[i].Series[0], aggregationLookup, bucketSize)
		if err != nil {
			return nil, err
		}
		res[key] = vals
	}

	return res, nil
}
1000398
func (s *Sensu) GetAggregate(check string, age int) ([]interface{}, error) {
	// FIXME GetAgregate Not handling age
	return s.getList(fmt.Sprintf("aggregate/%s", check), 0, 0)
}
631169
func (h *HistogramAggregator) getBuckets(metric string, field string) []float64 {
	if buckets, ok := h.buckets[metric][field]; ok {
		return buckets
	}

	for _, config := range h.Configs {
		if config.Metric == metric {
			if !isBucketExists(field, config) {
				continue
			}

			if _, ok := h.buckets[metric]; !ok {
				h.buckets[metric] = make(bucketsByFields)
			}

			h.buckets[metric][field] = sortBuckets(config.Buckets)
		}
	}

	return h.buckets[metric][field]
}
562090
func (_class GPUGroupClass) GetAll(sessionID SessionRef) (_retval []GPUGroupRef, _err error) {
	_method := "GPU_group.get_all"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg)
	if _err != nil {
		return
	}
	_retval, _err = convertGPUGroupRefSetToGo(_method + " -> ", _result.Value)
	return
}
399064
func (a *HistoricalApi) freeContainerAggregations(request *restful.Request, response *restful.Response) {
	key := core.HistoricalKey{
		ObjectType:    core.MetricSetTypeSystemContainer,
		NodeName:      request.PathParameter("node-name"),
		ContainerName: request.PathParameter("container-name"),
	}
	a.processAggregationRequest(key, request, response)
}
1109092
func NewAggregateConstructor(aggDescription string, aggFunc crossSeriesAggFunc) func() GraphiteFunc {
	return func() GraphiteFunc {
		return &FuncAggregate{agg: seriesAggregator{function: aggFunc, name: aggDescription}}
	}
}
725010
func (a *HistoricalApi) processAggregationRequest(key core.HistoricalKey, request *restful.Request, response *restful.Response) {
	start, end, err := getStartEndTimeHistorical(request)
	if err != nil {
		response.WriteError(http.StatusBadRequest, err)
		return
	}
	bucketSize, err := getBucketSize(request)
	if err != nil {
		response.WriteError(http.StatusBadRequest, err)
		return
	}
	aggregations, err := getAggregations(request)
	if err != nil {
		response.WriteError(http.StatusBadRequest, err)
		return
	}
	labels, err := getLabels(request)
	if err != nil {
		response.WriteError(http.StatusBadRequest, err)
		return
	}

	metricName := request.PathParameter("metric-name")
	convertedMetricName := convertMetricName(metricName)
	var metrics map[core.HistoricalKey][]core.TimestampedAggregationValue
	if labels != nil {
		metrics, err = a.historicalSource.GetLabeledAggregation(convertedMetricName, labels, aggregations, []core.HistoricalKey{key}, start, end, bucketSize)
	} else {
		metrics, err = a.historicalSource.GetAggregation(convertedMetricName, aggregations, []core.HistoricalKey{key}, start, end, bucketSize)
	}
	if err != nil {
		response.WriteError(http.StatusInternalServerError, err)
		return
	}

	converted := exportTimestampedAggregationValue(metrics[key])
	response.WriteEntity(converted)
}
160432
func (self *Collection) GetAggregatorName() string {
	if self.IndexName != `` {
		return self.IndexName
	}

	return self.Name
}
268441
func (o *VPort) AggregateMetadatas(info *bambou.FetchingInfo) (AggregateMetadatasList, *bambou.Error) {

	var list AggregateMetadatasList
	err := bambou.CurrentSession().FetchChildren(o, AggregateMetadataIdentity, &list, info)
	return list, err
}
4843
func (h *HistogramAggregator) groupFieldsByBuckets(
	metricsWithGroupedFields *[]groupedByCountFields,
	name string,
	field string,
	tags map[string]string,
	counts []int64,
) {
	count := int64(0)
	for index, bucket := range h.getBuckets(name, field) {
		count += counts[index]

		tags[bucketTag] = strconv.FormatFloat(bucket, 'f', -1, 64)
		h.groupField(metricsWithGroupedFields, name, field, count, copyTags(tags))
	}

	count += counts[len(counts)-1]
	tags[bucketTag] = bucketInf

	h.groupField(metricsWithGroupedFields, name, field, count, tags)
}
486620
func (a *AdjacencyMatrixAggregation) SubAggregation(name string, subAggregation Aggregation) *AdjacencyMatrixAggregation {
	a.subAggregations[name] = subAggregation
	return a
}
1155922
func (a *baseFuncDesc) WrapCastForAggArgs(ctx sessionctx.Context) {
	if len(a.Args) == 0 {
		return
	}
	if _, ok := noNeedCastAggFuncs[a.Name]; ok {
		return
	}
	var castFunc func(ctx sessionctx.Context, expr expression.Expression) expression.Expression
	switch retTp := a.RetTp; retTp.EvalType() {
	case types.ETInt:
		castFunc = expression.WrapWithCastAsInt
	case types.ETReal:
		castFunc = expression.WrapWithCastAsReal
	case types.ETString:
		castFunc = expression.WrapWithCastAsString
	case types.ETDecimal:
		castFunc = expression.WrapWithCastAsDecimal
	case types.ETDatetime, types.ETTimestamp:
		castFunc = func(ctx sessionctx.Context, expr expression.Expression) expression.Expression {
			return expression.WrapWithCastAsTime(ctx, expr, retTp)
		}
	case types.ETDuration:
		castFunc = expression.WrapWithCastAsDuration
	case types.ETJson:
		castFunc = expression.WrapWithCastAsJSON
	default:
		panic("should never happen in baseFuncDesc.WrapCastForAggArgs")
	}
	for i := range a.Args {
		// Do not cast the second args of these functions, as they are simply non-negative numbers.
		if i == 1 && (a.Name == ast.WindowFuncLead || a.Name == ast.WindowFuncLag || a.Name == ast.WindowFuncNthValue) {
			continue
		}
		a.Args[i] = castFunc(ctx, a.Args[i])
		if a.Name != ast.AggFuncAvg && a.Name != ast.AggFuncSum {
			continue
		}
		// After wrapping cast on the argument, flen etc. may not the same
		// as the type of the aggregation function. The following part set
		// the type of the argument exactly as the type of the aggregation
		// function.
		// Note: If the `Tp` of argument is the same as the `Tp` of the
		// aggregation function, it will not wrap cast function on it
		// internally. The reason of the special handling for `Column` is
		// that the `RetType` of `Column` refers to the `infoschema`, so we
		// need to set a new variable for it to avoid modifying the
		// definition in `infoschema`.
		if col, ok := a.Args[i].(*expression.Column); ok {
			col.RetType = types.NewFieldType(col.RetType.Tp)
		}
		// originTp is used when the the `Tp` of column is TypeFloat32 while
		// the type of the aggregation function is TypeFloat64.
		originTp := a.Args[i].GetType().Tp
		*(a.Args[i].GetType()) = *(a.RetTp)
		a.Args[i].GetType().Tp = originTp
	}
}
1296222
func (m *MetadataMapping) Aggregate() MetadataSet {
	m.RLock()
	defer m.RUnlock()
	var set MetadataSet
	for _, md := range m.mdByName {
		set = append(set, md)
	}
	return set
}
1277678
func (a *AggFuncDesc) GetAggFunc(ctx sessionctx.Context) Aggregation {
	aggFunc := aggFunction{AggFuncDesc: a}
	switch a.Name {
	case ast.AggFuncSum:
		return &sumFunction{aggFunction: aggFunc}
	case ast.AggFuncCount:
		return &countFunction{aggFunction: aggFunc}
	case ast.AggFuncAvg:
		return &avgFunction{aggFunction: aggFunc}
	case ast.AggFuncGroupConcat:
		var s string
		var err error
		var maxLen uint64
		s, err = variable.GetSessionSystemVar(ctx.GetSessionVars(), variable.GroupConcatMaxLen)
		if err != nil {
			panic(fmt.Sprintf("Error happened when GetAggFunc: no system variable named '%s'", variable.GroupConcatMaxLen))
		}
		maxLen, err = strconv.ParseUint(s, 10, 64)
		if err != nil {
			panic(fmt.Sprintf("Error happened when GetAggFunc: illegal value for system variable named '%s'", variable.GroupConcatMaxLen))
		}
		return &concatFunction{aggFunction: aggFunc, maxLen: maxLen}
	case ast.AggFuncMax:
		return &maxMinFunction{aggFunction: aggFunc, isMax: true}
	case ast.AggFuncMin:
		return &maxMinFunction{aggFunction: aggFunc, isMax: false}
	case ast.AggFuncFirstRow:
		return &firstRowFunction{aggFunction: aggFunc}
	case ast.AggFuncBitOr:
		return &bitOrFunction{aggFunction: aggFunc}
	case ast.AggFuncBitXor:
		return &bitXorFunction{aggFunction: aggFunc}
	case ast.AggFuncBitAnd:
		return &bitAndFunction{aggFunction: aggFunc}
	default:
		panic("unsupported agg function")
	}
}
809001
func AggMax(cols ...string) Aggregator {
	max := func(xs []float64) float64 {
		_, x := stats.Bounds(xs)
		return x
	}
	return aggFn(max, "max ", cols...)
}
1217764
func GetAggFunc(consolidator Consolidator) batch.AggFunc {
	var consFunc batch.AggFunc
	switch consolidator {
	case Avg:
		consFunc = batch.Avg
	case Cnt:
		consFunc = batch.Cnt
	case Lst:
		consFunc = batch.Lst
	case Min:
		consFunc = batch.Min
	case Max:
		consFunc = batch.Max
	case Mult:
		consFunc = batch.Mult
	case Med:
		consFunc = batch.Med
	case Diff:
		consFunc = batch.Diff
	case StdDev:
		consFunc = batch.StdDev
	case Range:
		consFunc = batch.Range
	case Sum:
		consFunc = batch.Sum
	}
	return consFunc
}
398790
func (c *RollingCounter) getBucket(t time.Time) int {
	return int(t.Truncate(c.resolution).Unix() % int64(len(c.values)))
}