// NewEventForAggregate creates a new event with a type and data, setting its
// timestamp. It also sets the aggregate data on it.
181656
func NewEventForAggregate(eventType EventType, data EventData, timestamp time.Time,
	aggregateType AggregateType, aggregateID uuid.UUID, version int) Event {
	return event{
		eventType:     eventType,
		data:          data,
		timestamp:     timestamp,
		aggregateType: aggregateType,
		aggregateID:   aggregateID,
		version:       version,
	}
}
202839
func (query Query) MustAggregate(mode string, field string, out interface{}) {
	must(query.Aggregate(mode, field, out))
}
759343
func NewEvent(category string, action string) *Event {
	h := &Event{
		category: category,
		action:   action,
	}
	return h
}
941718
func (s *Sensu) DeleteAggregate(aggregate string) error {
	return s.delete(fmt.Sprintf("aggregate/%s", aggregate))
}
1079599
func NewAggregations() Aggregations {
	return Aggregations{
		Data: make([]Aggregation, 0),
		DefaultAggregation: Aggregation{
			Name:              "default",
			Pattern:           regexp.MustCompile(".*"),
			XFilesFactor:      0.5,
			AggregationMethod: []Method{Avg},
		},
	}
}
1072074
func setAggregationValueTypes(vals []core.TimestampedAggregationValue, wasInt map[string]bool) {
	for _, aggregation := range core.MultiTypedAggregations {
		if isInt, ok := wasInt[string(aggregation)]; ok && isInt {
			for i := range vals {
				val := vals[i].Aggregations[aggregation]
				val.ValueType = core.ValueInt64
				vals[i].Aggregations[aggregation] = val
			}
		} else if ok {
			for i := range vals {
				val := vals[i].Aggregations[aggregation]
				val.ValueType = core.ValueFloat
				vals[i].Aggregations[aggregation] = val
			}
		}
	}
}
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)
}
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
	}
}
764035
func CreateAggregateFromMessageCountMap(m MessageCountMap) Aggregate {
	if m == nil {
		return nil
	}
	result := make([]error, 0, len(m))
	for errStr, count := range m {
		var countStr string
		if count > 1 {
			countStr = fmt.Sprintf(" (repeated %v times)", count)
		}
		result = append(result, fmt.Errorf("%v%v", errStr, countStr))
	}
	return NewAggregate(result)
}
589402
func NewEventStore() *EventStore {
	s := &EventStore{
		db: map[string]map[uuid.UUID]aggregateRecord{},
	}
	return s
}
1215463
func (a *CompositeAggregation) SubAggregation(name string, subAggregation Aggregation) *CompositeAggregation {
	a.subAggregations[name] = subAggregation
	return a
}
1147921
func Aggregate(stats []*stat.Stat) (aggregate StatsAggregate) {
	if stats == nil || len(stats) == 0 {
		return StatsAggregate{}
	}

	aggregate = StatsAggregate{Min : stats[0].Value, Max : stats[0].Value, Count : len(stats)}
	sum := 0.0
	for i := range stats {
		v := stats[i].Value

		sum += v

		if v < aggregate.Min {
			aggregate.Min = v
		}

		if v > aggregate.Max {
			aggregate.Max = v
		}
	}
	aggregate.Average = sum / float64(len(stats))

	return
}
1087259
func newEvent(typ string, value interface{}, prevValue interface{}) *event {
	return &event{
		typ:       typ,
		value:     value,
		prevValue: prevValue,
	}
}
1019468
func NewProtobufEvent(e *com_signalfx_metrics_protobuf.Event) (*event.Event, error) {
	dims := make(map[string]string, len(e.GetDimensions())+1)
	edims := e.GetDimensions()
	for _, dpdim := range edims {
		dims[dpdim.GetKey()] = dpdim.GetValue()
	}

	// sure wish protobuf has something eqiv of interface{} instead of only union structs...
	// <sigh>
	props := make(map[string]interface{}, len(e.GetDimensions())+1)
	for _, dpdim := range e.GetProperties() {
		pval := dpdim.GetValue()
		pkey := dpdim.GetKey()
		if pval.StrValue != nil {
			props[pkey] = pval.GetStrValue()
		} else if pval.BoolValue != nil {
			props[pkey] = pval.GetBoolValue()
		} else if pval.DoubleValue != nil {
			props[pkey] = pval.GetDoubleValue()
		} else if pval.IntValue != nil {
			props[pkey] = pval.GetIntValue()
		} else {
			return nil, errPropertyValueNotSet
		}
	}

	cat := event.ToProtoEC(e.GetCategory())
	return event.NewWithProperties(e.GetEventType(), cat, dims, props, fromTs(e.GetTimestamp())), nil
}
504508
func NewAggregate(errs ...error) error {
	// filter out possible nil values
	var nonNils []error
	for _, err := range errs {
		if err != nil {
			nonNils = append(nonNils, err)
		}
	}
	if len(nonNils) == 0 {
		return nil
	}
	return wrapWithDepth(aggregate(nonNils), 2)
}
462646
func (a *TermsAggregation) OrderByAggregation(aggName string, asc bool) *TermsAggregation {
	// {
	//     "aggs" : {
	//         "genders" : {
	//             "terms" : {
	//                 "field" : "gender",
	//                 "order" : { "avg_height" : "desc" }
	//             },
	//             "aggs" : {
	//                 "avg_height" : { "avg" : { "field" : "height" } }
	//             }
	//         }
	//     }
	// }
	a.order = append(a.order, TermsOrder{Field: aggName, Ascending: asc})
	return a
}
1150605
func (a *HistoricalApi) namespaceAggregations(request *restful.Request, response *restful.Response) {
	key := core.HistoricalKey{
		ObjectType:    core.MetricSetTypeNamespace,
		NamespaceName: request.PathParameter("namespace-name"),
	}
	a.processAggregationRequest(key, request, response)
}