// populateAggregations extracts aggregation values from a given data point
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
}
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
}
1291899
func NewAggregator(samples bool, utcOffset time.Duration, outlierTime float64) *Aggregator {
	a := &Aggregator{
		samples:     samples,
		utcOffset:   utcOffset,
		outlierTime: outlierTime,
		// --
		global:  NewClass("", "", false),
		classes: make(map[string]*Class),
	}
	return a
}
717987
func MatchAggregate(t AggregateType) EventMatcher {
	return func(e Event) bool {
		return e != nil && e.AggregateType() == t
	}
}
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)
}
443582
func (f *Facade) GetAggregateServices(ctx datastore.Context, since time.Time, serviceIDs []string) ([]service.AggregateService, error) {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.GetAggregateServices"))
	logger := plog.WithField("serviceids", strings.Join(serviceIDs, ","))

	// Create an instance map to map instances to their memory usage.  This is
	// so that we only have to make one call to query service to get metrics
	// for all the instances.
	instanceMap := make(map[string]*service.Usage)

	// Set up an array containing all the metrics to collect
	var metricsreq []metrics.ServiceInstance

	// Results are for saving the metric data that will be returned to the
	// caller.
	results := make([]service.AggregateService, len(serviceIDs))

	for i, serviceID := range serviceIDs {
		svclog := logger.WithField("serviceid", serviceID)

		svc, err := f.serviceStore.GetServiceHealth(ctx, serviceID)
		if datastore.IsErrNoSuchEntity(err) {

			// If the service is not found, set the NotFound boolean to true
			// and continue
			results[i] = service.AggregateService{
				ServiceID: serviceID,
				NotFound:  true,
			}
			svclog.Debug("Service not found")
			continue
		} else if err != nil {
			svclog.WithError(err).Debug("Could not retrieve service")
			return nil, err
		}

		// Get all the state ids running on that service
		stateIDs, err := f.zzk.GetServiceStateIDs(svc.PoolID, svc.ID)
		if err != nil {
			svclog.WithError(err).Debug("Could not retrieve instances for service")
			return nil, err
		}

		// set up the aggregated service object
		results[i] = service.AggregateService{
			ServiceID:         serviceID,
			Name:              svc.Name,
			DesiredState:      service.DesiredState(svc.DesiredState),
			CurrentState:      service.ServiceCurrentState(svc.CurrentState),
			Status:            make([]service.StatusInstance, len(stateIDs)),
			NotFound:          false,
			EmergencyShutdown: svc.EmergencyShutdown,
			RAMCommitment:     int64(svc.RAMCommitment.Value),
		}

		// set up the status of each instance
		for j, stateID := range stateIDs {

			// report the instance id and the health
			results[i].Status[j] = service.StatusInstance{
				InstanceID:   stateID.InstanceID,
				HealthStatus: f.getInstanceHealth(svc, stateID.InstanceID),
			}

			// append a request to the metrics query for this instance
			metricsreq = append(metricsreq, metrics.ServiceInstance{
				ServiceID:  serviceID,
				InstanceID: stateID.InstanceID,
			})

			// add the memory usage response
			instanceMap[fmt.Sprintf("%s-%d", serviceID, stateID.InstanceID)] = &results[i].Status[j].MemoryUsage
		}
	}

	// look up the metrics of all the instances
	metricsres, err := f.metricsClient.GetInstanceMemoryStats(since, metricsreq...)
	if err != nil {
		logger.WithError(err).Debug("Could not look up memory metrics for instances on service")
	} else {
		for _, metric := range metricsres {
			*instanceMap[fmt.Sprintf("%s-%s", metric.ServiceID, metric.InstanceID)] = service.Usage{
				Cur: metric.Last,
				Max: metric.Max,
				Avg: metric.Average,
			}
		}
	}

	logger.Debug("Loaded aggregate service instance data")
	return results, nil
}
166251
func (a *FiltersAggregation) SubAggregation(name string, subAggregation Aggregation) *FiltersAggregation {
	a.subAggregations[name] = subAggregation
	return a
}
272082
func (s *DescribeAggregationAuthorizationsOutput) SetAggregationAuthorizations(v []*AggregationAuthorization) *DescribeAggregationAuthorizationsOutput {
	s.AggregationAuthorizations = v
	return s
}
129509
func PopulateCommonTypes(ctx context.Context, db *gorm.DB) error {
	populateLocker.Lock()
	defer populateLocker.Unlock()

	// Create or update space templates
	templateFunctions := []func() (*importer.ImportHelper, error){
		importer.BaseTemplate,
		importer.LegacyTemplate,
		importer.ScrumTemplate,
		importer.AgileTemplate,
	}
	importRepo := importer.NewRepository(db)
	for idx, loadFunction := range templateFunctions {
		log.Debug(ctx, nil, `importing space template #%d`, idx)
		t, err := loadFunction()
		if err != nil {
			return errs.Wrapf(err, `failed to load space template #%d`, idx)
		}
		_, err = importRepo.Import(ctx, *t)
		if err != nil {
			log.Error(ctx, map[string]interface{}{
				"err":  err,
				"id":   t.Template.ID,
				"name": t.Template.Name,
			}, `failed to import space template #%d with name "%s" and ID %s`, idx, t.Template.Name, t.Template.ID)
			return errs.Wrapf(err, `failed to import space template #%d with name "%s" and ID %s`, idx, t.Template.Name, t.Template.ID)
		}
		log.Debug(ctx, nil, `imported space template #%d "%s"`, idx, t.Template.Name)
	}
	workitem.ClearGlobalWorkItemTypeCache() // Clear the WIT cache after updating existing WITs
	return nil
}
310859
func registerAggregator(a *TabletStatusAggregator) {
	muAggr.Lock()
	defer muAggr.Unlock()
	aggregators = append(aggregators, a)
}
643427
func (list ErrorList) ToAggregate() utilerrors.Aggregate {
	errs := make([]error, len(list))
	for i := range list {
		errs[i] = list[i]
	}
	return utilerrors.NewAggregate(errs)
}
1174206
func (tc *TabletStatsCache) updateAggregateMap(keyspace, shard string, tabletType topodatapb.TabletType, e *tabletStatsCacheEntry, stats []*TabletStats) {
	// Save the new value
	e.aggregates = tc.makeAggregateMap(stats)
}
804071
func (a *AggMetric) addAggregators(ts uint32, val float64) {
	for _, agg := range a.aggregators {
		log.Debugf("AM: %s pushing %d,%f to aggregator %d", a.key, ts, val, agg.span)
		agg.Add(ts, val)
	}
}
554823
func NewHistogramAggregator() telegraf.Aggregator {
	h := &HistogramAggregator{}
	h.buckets = make(bucketsByMetrics)
	h.resetCache()

	return h
}
475158
func NewAdjacencyMatrixAggregation() *AdjacencyMatrixAggregation {
	return &AdjacencyMatrixAggregation{
		filters:         make(map[string]Query),
		subAggregations: make(map[string]Aggregation),
	}
}
1015637
func (t *NetworkDevice) PopulateProto(d *pb.MetricsCollection) {
	d.TargetSchema = &pb.MetricsCollection_NetworkDevice{
		&pb.NetworkDevice{
			Alertable: proto.Bool(true),
			Realm:     proto.String("ACQ_CHROME"),
			Metro:     &t.Metro,
			Role:      &t.Role,
			Hostname:  &t.Hostname,
			Hostgroup: &t.Hostgroup,
		},
	}
}
1177868
func (self *RecordSet) PopulateFromRecords(into interface{}, schema *Collection) error {
	vInto := reflect.ValueOf(into)

	// get value pointed to if we were given a pointer
	if vInto.Kind() == reflect.Ptr {
		vInto = vInto.Elem()
	} else {
		return fmt.Errorf("Output argument must be a pointer")
	}

	// we're going to fill arrays or slices
	switch vInto.Type().Kind() {
	case reflect.Array, reflect.Slice:
		indirectResult := true

		// get the type of the underlying slice element
		sliceType := vInto.Type().Elem()

		// get the type pointed to
		if sliceType.Kind() == reflect.Ptr {
			sliceType = sliceType.Elem()
			indirectResult = false
		}

		// for each resulting record...
		for _, record := range self.Records {
			// make a new zero-valued instance of the slice type
			elem := reflect.New(sliceType)

			// if we have a registered collection, use its
			if schema != nil && schema.HasRecordType() {
				elem = reflect.ValueOf(schema.NewInstance())
			}

			// populate that type with data from this record
			if err := record.Populate(elem.Interface(), schema); err == nil {
				// if the slice elements are pointers, we can append the pointer we just created as-is
				// otherwise, we need to indirect the value and append a copy

				if indirectResult {
					vInto.Set(reflect.Append(vInto, reflect.Indirect(elem)))
				} else {
					vInto.Set(reflect.Append(vInto, elem))
				}
			} else {
				return err
			}
		}

		return nil
	case reflect.Struct:
		if rs, ok := into.(*RecordSet); ok {
			*rs = *self
			return nil
		}
	}

	return fmt.Errorf("RecordSet can only populate records into slice or array, got %T", into)
}