// Determine the score of an event. An event with higher score should be
// emitted before lower ones.  The score based ordering ensures continuous
// routability, so events with running instances should be emitted first
// followed by remove events.
188272
func EventScore(e models.Event) int {
	lrp, crashed := getEventLRP(e)

	// sort crashed events first to be backward compatible with the old
	// event stream which emitted the crashed event before the
	// remove/changed events.
	if crashed {
		return 2
	}

	// this is an event with a running instance, this should be emitted before
	// any other event, such as removed ro changed event to non-running state.
	if lrp != nil && lrp.State == models.ActualLRPStateRunning {
		return 1
	}

	// The event is either a RemovedEvent or a ChangedEvent (to a non-RUNNING
	// state).  These are prioritized last, because those events cause loss of
	// routability.
	return 0
}
608174
func (m *Metrics) AddEvent(e *log.Event, outlier bool) {

	for metric, val := range e.TimeMetrics {
		stats, seenMetric := m.TimeMetrics[metric]
		if !seenMetric {
			m.TimeMetrics[metric] = &TimeStats{
				vals: []float64{},
			}
			stats = m.TimeMetrics[metric]
		}
		if outlier {
			stats.outlierSum += val
		} else {
			stats.Sum += val
		}
		stats.vals = append(stats.vals, float64(val))
	}

	for metric, val := range e.NumberMetrics {
		stats, seenMetric := m.NumberMetrics[metric]
		if !seenMetric {
			m.NumberMetrics[metric] = &NumberStats{
				vals: []uint64{},
			}
			stats = m.NumberMetrics[metric]
		}
		if outlier {
			stats.outlierSum += val
		} else {
			stats.Sum += val
		}
		stats.vals = append(stats.vals, val)
	}

	for metric, val := range e.BoolMetrics {
		stats, seenMetric := m.BoolMetrics[metric]
		if !seenMetric {
			stats = &BoolStats{}
			m.BoolMetrics[metric] = stats
		}
		if val {
			if outlier {
				stats.outlierSum += 1
			} else {
				stats.Sum += 1
			}
		}
	}
}
1062705
func findMaxScores(priorityList schedulerapi.HostPriorityList) []int {
	maxScoreIndexes := make([]int, 0, len(priorityList)/2)
	maxScore := priorityList[0].Score
	for i, hp := range priorityList {
		if hp.Score > maxScore {
			maxScore = hp.Score
			maxScoreIndexes = maxScoreIndexes[:0]
			maxScoreIndexes = append(maxScoreIndexes, i)
		} else if hp.Score == maxScore {
			maxScoreIndexes = append(maxScoreIndexes, i)
		}
	}
	return maxScoreIndexes
}
413154
func (b *eventBatch) events() []wrappedEvent {
	sort.Sort(byTimestamp(b.batch))
	return b.batch
}
719527
func (f *FSMContext) Decide(h HistoryEvent, data interface{}, decider Decider) Outcome {
	outcome := decider(f, h, data)
	f.pendingActivities.Track(h)
	return outcome
}
231570
func RaiseEvent(key Event, value interface{}) (response EventResponse) {
	utilLog.Info("Raising event", "len", len(initEventList))
	for _, handler := range initEventList {
		response |= handler(key, value)
	}
	return
}
13496
func (a *Aggregator) AddEvent(event *log.Event, id, fingerprint string) {
	if a.rateLimit != event.RateLimit {
		a.rateLimit = event.RateLimit
	}

	outlier := false
	if a.outlierTime > 0 && event.TimeMetrics["Query_time"] > a.outlierTime {
		outlier = true
	}

	a.global.AddEvent(event, outlier)

	class, ok := a.classes[id]
	if !ok {
		class = NewClass(id, fingerprint, a.samples)
		a.classes[id] = class
	}
	class.AddEvent(event, outlier)
}
905427
func (az *Cloud) Event(obj runtime.Object, eventtype, reason, message string) {
	if obj != nil && reason != "" {
		az.eventRecorder.Event(obj, eventtype, reason, message)
	}
}
810295
func (c *EventCorrelator) EventCorrelate(newEvent *v1.Event) (*EventCorrelateResult, error) {
	if newEvent == nil {
		return nil, fmt.Errorf("event is nil")
	}
	aggregateEvent, ckey := c.aggregator.EventAggregate(newEvent)
	observedEvent, patch, err := c.logger.eventObserve(aggregateEvent, ckey)
	if c.filterFunc(observedEvent) {
		return &EventCorrelateResult{Skip: true}, nil
	}
	return &EventCorrelateResult{Event: observedEvent, Patch: patch}, err
}
759025
func (m *OutlierDetectionEvent) Validate() error {
	if m == nil {
		return nil
	}

	if _, ok := OutlierEjectionType_name[int32(m.GetType())]; !ok {
		return OutlierDetectionEventValidationError{
			field:  "Type",
			reason: "value must be one of the defined enum values",
		}
	}

	{
		tmp := m.GetTimestamp()

		if v, ok := interface{}(tmp).(interface{ Validate() error }); ok {

			if err := v.Validate(); err != nil {
				return OutlierDetectionEventValidationError{
					field:  "Timestamp",
					reason: "embedded message failed validation",
					cause:  err,
				}
			}
		}
	}

	{
		tmp := m.GetSecsSinceLastAction()

		if v, ok := interface{}(tmp).(interface{ Validate() error }); ok {

			if err := v.Validate(); err != nil {
				return OutlierDetectionEventValidationError{
					field:  "SecsSinceLastAction",
					reason: "embedded message failed validation",
					cause:  err,
				}
			}
		}
	}

	if len(m.GetClusterName()) < 1 {
		return OutlierDetectionEventValidationError{
			field:  "ClusterName",
			reason: "value length must be at least 1 bytes",
		}
	}

	if len(m.GetUpstreamUrl()) < 1 {
		return OutlierDetectionEventValidationError{
			field:  "UpstreamUrl",
			reason: "value length must be at least 1 bytes",
		}
	}

	if _, ok := Action_name[int32(m.GetAction())]; !ok {
		return OutlierDetectionEventValidationError{
			field:  "Action",
			reason: "value must be one of the defined enum values",
		}
	}

	// no validation rules for NumEjections

	// no validation rules for Enforced

	switch m.Event.(type) {

	case *OutlierDetectionEvent_EjectSuccessRateEvent:

		{
			tmp := m.GetEjectSuccessRateEvent()

			if v, ok := interface{}(tmp).(interface{ Validate() error }); ok {

				if err := v.Validate(); err != nil {
					return OutlierDetectionEventValidationError{
						field:  "EjectSuccessRateEvent",
						reason: "embedded message failed validation",
						cause:  err,
					}
				}
			}
		}

	case *OutlierDetectionEvent_EjectConsecutiveEvent:

		{
			tmp := m.GetEjectConsecutiveEvent()

			if v, ok := interface{}(tmp).(interface{ Validate() error }); ok {

				if err := v.Validate(); err != nil {
					return OutlierDetectionEventValidationError{
						field:  "EjectConsecutiveEvent",
						reason: "embedded message failed validation",
						cause:  err,
					}
				}
			}
		}

	default:
		return OutlierDetectionEventValidationError{
			field:  "Event",
			reason: "value is required",
		}

	}

	return nil
}
70579
func (r *LabelSearchResponse) ResultsWithScore(score int) []*Label {
	var res []*Label
	for _, v := range r.Labels {
		if r.Scores[v] >= score {
			res = append(res, v)
		}
	}
	return res
}
167903
func (circuit *CircuitBreaker) ReportEvent(eventTypes []string, start time.Time, runDuration time.Duration) error {
	if len(eventTypes) == 0 {
		return fmt.Errorf("no event types sent for metrics")
	}

	circuit.mutex.RLock()
	o := circuit.open
	circuit.mutex.RUnlock()
	if eventTypes[0] == "success" && o {
		circuit.setClose()
	}

	var concurrencyInUse float64
	if circuit.executorPool.Max > 0 {
		concurrencyInUse = float64(circuit.executorPool.ActiveCount()) / float64(circuit.executorPool.Max)
	}

	select {
	case circuit.metrics.Updates <- &commandExecution{
		Types:            eventTypes,
		Start:            start,
		RunDuration:      runDuration,
		ConcurrencyInUse: concurrencyInUse,
	}:
	default:
		return CircuitError{Message: fmt.Sprintf("metrics channel (%v) is at capacity", circuit.Name)}
	}

	return nil
}
607852
func (tm *TrustMetric) BadEvents(num int) {
	tm.mtx.Lock()
	defer tm.mtx.Unlock()

	tm.unpause()
	tm.bad += float64(num)
}
935413
func SetOOMScore(pid, score int) error {
	path := fmt.Sprintf("/proc/%d/oom_score_adj", pid)
	f, err := os.OpenFile(path, os.O_WRONLY, 0)
	if err != nil {
		return err
	}
	defer f.Close()
	if _, err = f.WriteString(strconv.Itoa(score)); err != nil {
		if os.IsPermission(err) && (system.RunningInUserNS() || RunningUnprivileged()) {
			return nil
		}
		return err
	}
	return nil
}
596811
func ValidateEventType(eventtype string) bool {
	switch eventtype {
	case v1.EventTypeNormal, v1.EventTypeWarning:
		return true
	}
	return false
}
962516
func (s Scores) Calculate() int64 {
	return s.Score1 + int64(0.1*float64(s.Score2)) + int64(0.01*float64(s.Score3)) + int64(0.001*float64(s.Score4)) + int64(0.0001*float64(s.Score5))
}
1233187
func (s *FullJitterStrategy) Calculate(attempt int) time.Duration {
	// lazily initialize the RNG
	s.rngOnce.Do(func() {
		if s.rng != nil {
			return
		}
		s.rng = rand.New(rand.NewSource(time.Now().UnixNano()))
	})

	backoffDuration := s.cfg.BackoffMultiplier *
		time.Duration(math.Pow(2, float64(attempt)))
	return time.Duration(s.rng.Intn(int(backoffDuration)))
}