// ParseMonitorAggregationLevel turns a string into a monitor aggregation
// level. The string may contain an integer value or a string representation of
// a particular monitor aggregation level.
965954
func ParseMonitorAggregationLevel(value string) (OptionSetting, error) {
	// First, attempt the string representation.
	if level, ok := monitorAggregationOption[strings.ToLower(value)]; ok {
		return level, nil
	}

	// If it's not a valid string option, attempt to parse an integer.
	valueParsed, err := strconv.Atoi(value)
	if err != nil {
		err = fmt.Errorf("Invalid monitor aggregation level %q", value)
		return MonitorAggregationLevelNone, err
	}
	parsed := OptionSetting(valueParsed)
	if parsed < MonitorAggregationLevelNone || parsed > MonitorAggregationLevelMax {
		err = fmt.Errorf("Monitor aggregation level must be between %d and %d",
			MonitorAggregationLevelNone, MonitorAggregationLevelMax)
		return MonitorAggregationLevelNone, err
	}
	return parsed, nil
}
1249246
func (sink *influxdbSink) aggregationFunc(aggregationName core.AggregationType, fieldName string) string {
	switch aggregationName {
	case core.AggregationTypeAverage:
		return fmt.Sprintf("MEAN(%q)", fieldName)
	case core.AggregationTypeMaximum:
		return fmt.Sprintf("MAX(%q)", fieldName)
	case core.AggregationTypeMinimum:
		return fmt.Sprintf("MIN(%q)", fieldName)
	case core.AggregationTypeMedian:
		return fmt.Sprintf("MEDIAN(%q)", fieldName)
	case core.AggregationTypeCount:
		return fmt.Sprintf("COUNT(%q)", fieldName)
	case core.AggregationTypePercentile50:
		return fmt.Sprintf("PERCENTILE(%q, 50)", fieldName)
	case core.AggregationTypePercentile95:
		return fmt.Sprintf("PERCENTILE(%q, 95)", fieldName)
	case core.AggregationTypePercentile99:
		return fmt.Sprintf("PERCENTILE(%q, 99)", fieldName)
	}

	// This should have been checked by the API level, so something's seriously wrong here
	panic(fmt.Sprintf("Unknown aggregation type %q", aggregationName))
}
1025514
func AggMin(cols ...string) Aggregator {
	min := func(xs []float64) float64 {
		x, _ := stats.Bounds(xs)
		return x
	}
	return aggFn(min, "min ", cols...)
}
1144677
func (a *HistoricalApi) clusterAggregations(request *restful.Request, response *restful.Response) {
	key := core.HistoricalKey{ObjectType: core.MetricSetTypeCluster}
	a.processAggregationRequest(key, request, response)
}
196222
func populateAggregations(rawRowName string, rawVal []interface{}, val *core.TimestampedAggregationValue, aggregationLookup map[core.AggregationType]int, wasInt map[string]bool) error {
	for _, aggregation := range core.MultiTypedAggregations {
		if err := setAggregationValueIfPresent(aggregation, rawVal, &val.AggregationValue, aggregationLookup, wasInt); err != nil {
			glog.Errorf("Unable to parse field %q in series %q: %v", aggregation, rawRowName, err)
			return fmt.Errorf("Unable to parse values in series %q", rawRowName)
		}
	}

	return nil
}
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
}
26821
func (s *Store) FindAggregate(dataType interface{}, query *Query, groupBy ...string) ([]*AggregateResult, error) {
	var result []*AggregateResult
	var err error
	err = s.Bolt().View(func(tx *bolt.Tx) error {
		result, err = s.TxFindAggregate(tx, dataType, query, groupBy...)
		return err
	})

	if err != nil {
		return nil, err
	}

	return result, nil
}
31644
func (s *Server) StreamAggregatedResources(stream ADSStream) error {
	// a channel for receiving incoming requests
	reqCh := make(chan *envoy.DiscoveryRequest)
	reqStop := int32(0)
	go func() {
		for {
			req, err := stream.Recv()
			if atomic.LoadInt32(&reqStop) != 0 {
				return
			}
			if err != nil {
				close(reqCh)
				return
			}
			reqCh <- req
		}
	}()

	err := s.process(stream, reqCh)
	if err != nil {
		s.Logger.Printf("[DEBUG] Error handling ADS stream: %s", err)
	}

	// prevents writing to a closed channel if send failed on blocked recv
	atomic.StoreInt32(&reqStop, 1)

	return err
}
474583
func (e *FuncExpr) getAggregate() (*Value, error) {
	switch e.getFunctionName() {
	case aggFnCount:
		return FromInt(e.aggregate.runningCount), nil

	case aggFnAvg:
		if e.aggregate.runningCount == 0 {
			// No rows were seen by AVG.
			return FromNull(), nil
		}
		err := e.aggregate.runningSum.arithOp(opDivide, FromInt(e.aggregate.runningCount))
		return e.aggregate.runningSum, err

	case aggFnMin:
		if !e.aggregate.seen {
			// No rows were seen by MIN
			return FromNull(), nil
		}
		return e.aggregate.runningMin, nil

	case aggFnMax:
		if !e.aggregate.seen {
			// No rows were seen by MAX
			return FromNull(), nil
		}
		return e.aggregate.runningMax, nil

	case aggFnSum:
		// TODO: check if returning 0 when no rows were seen
		// by SUM is expected behavior.
		return e.aggregate.runningSum, nil

	default:
		// TODO:
	}

	return nil, errInvalidAggregation
}
1079236
func DelegatorAggregator(m MetaContext, ds []Delegator, extra AggSigProducer,
	pukBoxes []keybase1.PerUserKeyBox, pukPrev *PerUserKeyPrev, userEKReboxArg *keybase1.UserEkReboxArg) (err error) {
	if len(ds) == 0 {
		return errors.New("Empty delegators to aggregator")
	}

	// Store all the args to build a single big json later
	var args []JSONPayload
	var uid keybase1.UID
	var lastSeqno keybase1.Seqno
	var lastLinkID LinkID

	for i := range ds {
		// Mutate the original and not a copy from range
		var d = &ds[i]

		d.Aggregated = true
		if err := d.Run(m); err != nil {
			return err
		}

		flatArgs := d.postArg.flattenHTTPArgs(d.postArg.getHTTPArgs())
		args = append(args, convertStringMapToJSONPayload(flatArgs))
		if uid.IsNil() && d.Me != nil {
			uid = d.Me.GetUID()
		}
		lastSeqno = d.proof.Seqno
		lastLinkID = d.linkID
	}

	if extra != nil {
		x, seqno, linkID, err := extra()
		if err != nil {
			return err
		}
		args = append(args, x)
		lastSeqno = seqno
		lastLinkID = linkID
	}

	payload := make(JSONPayload)
	payload["sigs"] = args

	if len(pukBoxes) > 0 {
		AddPerUserKeyServerArg(payload, pukBoxes[0].Generation, pukBoxes, pukPrev)
	} else if pukPrev != nil {
		return errors.New("cannot delegate per-user-key with prev but no boxes")
	}
	AddUserEKReBoxServerArg(payload, userEKReboxArg)

	// Adopt most parameters from the first item
	var apiArgBase = ds[0]
	var apiArg = apiArgBase.postArg
	apiArg.Args = nil
	apiArg.uArgs = nil
	apiArg.Endpoint = "key/multi"
	apiArg.JSONPayload = payload

	_, err = m.G().API.PostJSON(m, apiArg)
	if err != nil {
		return err
	}
	return MerkleCheckPostedUserSig(m, uid, lastSeqno, lastLinkID)
}
538153
func AggCount(label string) Aggregator {
	if label == "" {
		label = "count"
	}

	return func(input table.Grouping, b *table.Builder) {
		counts := make([]int, 0, len(input.Tables()))
		for _, gid := range input.Tables() {
			counts = append(counts, input.Table(gid).Len())
		}
		b.Add(label, counts)
	}
}
1138015
func (list ErrorList) ToAggregate() utilerrors.Aggregate {
	errs := make([]error, 0, len(list))
	errorMsgs := sets.NewString()
	for _, err := range list {
		msg := fmt.Sprintf("%v", err)
		if errorMsgs.Has(msg) {
			continue
		}
		errorMsgs.Insert(msg)
		errs = append(errs, err)
	}
	return utilerrors.NewAggregate(errs)
}
1227554
func (sink *influxdbSink) parseAggregateQueryRow(rawRow influx_models.Row, aggregationLookup map[core.AggregationType]int, bucketSize time.Duration) ([]core.TimestampedAggregationValue, error) {
	vals := make([]core.TimestampedAggregationValue, len(rawRow.Values))
	wasInt := make(map[string]bool, len(aggregationLookup))

	for i, rawVal := range rawRow.Values {
		val := core.TimestampedAggregationValue{
			BucketSize: bucketSize,
			AggregationValue: core.AggregationValue{
				Aggregations: map[core.AggregationType]core.MetricValue{},
			},
		}

		if ts, err := time.Parse(time.RFC3339, rawVal[0].(string)); err != nil {
			return nil, fmt.Errorf("Unable to parse timestamp %q in series %q", rawVal[0].(string), rawRow.Name)
		} else {
			val.Timestamp = ts
		}

		// The Influx client decods numeric fields to json.Number (a string), so we have to try decoding to both types of numbers

		// Count is always a uint64
		if countIndex, ok := aggregationLookup[core.AggregationTypeCount]; ok {
			if err := json.Unmarshal([]byte(rawVal[countIndex].(json.Number).String()), &val.Count); err != nil {
				glog.Errorf("Unable to parse count value in series %q: %v", rawRow.Name, err)
				return nil, fmt.Errorf("Unable to parse values in series %q", rawRow.Name)
			}
		}

		// The rest of the aggregation values can be either float or int, so attempt to parse both
		if err := populateAggregations(rawRow.Name, rawVal, &val, aggregationLookup, wasInt); err != nil {
			return nil, err
		}

		vals[i] = val
	}

	// figure out whether each aggregation was full of float values, or int values
	setAggregationValueTypes(vals, wasInt)

	return vals, nil
}
426851
func (hg *Histogram) AvgCountPerNotNullValue(totalCount int64) float64 {
	factor := hg.GetIncreaseFactor(totalCount)
	totalNotNull := hg.notNullCount() * factor
	curNDV := float64(hg.NDV) * factor
	if curNDV == 0 {
		curNDV = 1
	}
	return totalNotNull / curNDV
}
1324790
func (s *AggregationAuthorization) SetAggregationAuthorizationArn(v string) *AggregationAuthorization {
	s.AggregationAuthorizationArn = &v
	return s
}
1104339
func NewMonitorFormatter(verbosity Verbosity) *MonitorFormatter {
	return &MonitorFormatter{
		Hex:        false,
		EventTypes: monitorAPI.MessageTypeFilter{},
		FromSource: Uint16Flags{},
		ToDst:      Uint16Flags{},
		Related:    Uint16Flags{},
		Verbose:    false,
		JSONOutput: false,
		Verbosity:  verbosity,
	}
}
38006
func ReadAggregations(file string) (Aggregations, error) {
	config, err := configparser.Read(file)
	if err != nil {
		return Aggregations{}, err
	}
	sections, err := config.AllSections()
	if err != nil {
		return Aggregations{}, err
	}

	result := NewAggregations()

	for _, s := range sections {
		item := Aggregation{}
		item.Name = strings.Trim(strings.SplitN(s.String(), "\n", 2)[0], " []")
		if item.Name == "" || strings.HasPrefix(item.Name, "#") {
			continue
		}

		item.Pattern, err = regexp.Compile(s.ValueOf("pattern"))
		if err != nil {
			return Aggregations{}, fmt.Errorf("[%s]: failed to parse pattern %q: %s", item.Name, s.ValueOf("pattern"), err.Error())
		}

		item.XFilesFactor, err = strconv.ParseFloat(s.ValueOf("xFilesFactor"), 64)
		if err != nil {
			return Aggregations{}, fmt.Errorf("[%s]: failed to parse xFilesFactor %q: %s", item.Name, s.ValueOf("xFilesFactor"), err.Error())
		}

		aggregationMethodStr := s.ValueOf("aggregationMethod")
		methodStrs := strings.Split(aggregationMethodStr, ",")
		for _, methodStr := range methodStrs {
			switch methodStr {
			case "average", "avg":
				item.AggregationMethod = append(item.AggregationMethod, Avg)
			case "sum":
				item.AggregationMethod = append(item.AggregationMethod, Sum)
			case "last":
				item.AggregationMethod = append(item.AggregationMethod, Lst)
			case "max":
				item.AggregationMethod = append(item.AggregationMethod, Max)
			case "min":
				item.AggregationMethod = append(item.AggregationMethod, Min)
			default:
				return result, fmt.Errorf("[%s]: unknown aggregation method %q", item.Name, methodStr)
			}
		}

		result.Data = append(result.Data, item)
	}

	return result, nil
}