// calculateRandomExpiry returns a random duration between 50% and 80% of the
// original validity period
777937
func calculateRandomExpiry(validFrom, validUntil time.Time) time.Duration {
	duration := validUntil.Sub(validFrom)

	var randomExpiry int
	// Our lower bound of renewal will be half of the total expiration time
	minValidity := int(duration.Minutes() * CertLowerRotationRange)
	// Our upper bound of renewal will be 80% of the total expiration time
	maxValidity := int(duration.Minutes() * CertUpperRotationRange)
	// Let's select a random number of minutes between min and max, and set our retry for that
	// Using randomly selected rotation allows us to avoid certificate thundering herds.
	if maxValidity-minValidity < 1 {
		randomExpiry = minValidity
	} else {
		randomExpiry = rand.Intn(maxValidity-minValidity) + minValidity
	}

	expiry := time.Until(validFrom.Add(time.Duration(randomExpiry) * time.Minute))
	if expiry < 0 {
		return 0
	}
	return expiry
}
1127651
func Between(min, lessThan int) int {
	return rand.Intn(lessThan-min) + min
}
786210
func (c *CHA2DS2VAScPlugin) Calculate(es *plugin.EventStream, fhirEndpointURL string) ([]plugin.RiskServiceCalculationResult, error) {
	var results []plugin.RiskServiceCalculationResult

	// First make sure there is AFIB in the history, since this score is only valid for patients with AFIB
	var hasAFib bool
	for i := 0; !hasAFib && i < len(es.Events); i++ {
		if es.Events[i].Type == "Condition" && !es.Events[i].End {
			if cond, ok := es.Events[i].Value.(*models.Condition); ok {
				hasAFib = fuzzyFindCondition("427.31", "http://hl7.org/fhir/sid/icd-9", cond)
			}
		}
	}
	if !hasAFib {
		return nil, plugin.NewNotApplicableError("CHA2DS2-VASc is only applicable to patients with Atrial Fibrillation")
	}

	// Create the initial pie based on gender
	pie := plugin.NewPie(fhirEndpointURL + "/Patient/" + es.Patient.Id)
	pie.Slices = c.Config().DefaultPieSlices
	if es.Patient.Gender == "female" {
		pie.UpdateSliceValue("Gender", 1)
	} else if es.Patient.Gender == "male" {
		pie.UpdateSliceValue("Gender", 0)
	}

	// Now go through the event stream, updating the pie
	var hasAfib bool
	for _, event := range es.Events {
		// NOTE: We are not paying attention to end times -- if it's in the patient history, we count it.
		// Also guard against future dates (for example, our patient generator can create future events)
		if event.End || event.Date.Local().After(time.Now()) {
			continue
		}

		var isFactor bool
		pie = pie.Clone(true)
		switch event.Type {
		case "Condition":
			r := event.Value.(*models.Condition)
			if fuzzyFindCondition("427.31", "http://hl7.org/fhir/sid/icd-9", r) {
				// Found atrial fibrillation, so all events from here on should produce scores
				hasAfib = true
				isFactor = true
			} else if fuzzyFindCondition("428", "http://hl7.org/fhir/sid/icd-9", r) {
				pie.UpdateSliceValue("Congestive Heart Failure", 1)
				isFactor = true
			} else if fuzzyFindCondition("401", "http://hl7.org/fhir/sid/icd-9", r) {
				pie.UpdateSliceValue("Hypertension", 1)
				isFactor = true
			} else if fuzzyFindCondition("250", "http://hl7.org/fhir/sid/icd-9", r) {
				pie.UpdateSliceValue("Diabetes", 1)
				isFactor = true
			} else if fuzzyFindCondition("434", "http://hl7.org/fhir/sid/icd-9", r) {
				pie.UpdateSliceValue("Stroke", 2)
				isFactor = true
			} else if fuzzyFindCondition("443", "http://hl7.org/fhir/sid/icd-9", r) {
				pie.UpdateSliceValue("Vascular Disease", 1)
				isFactor = true
			}
		case "Age":
			age := event.Value.(int)
			if age >= 65 && age < 75 {
				pie.UpdateSliceValue("Age", 1)
				isFactor = true
			} else if age >= 75 {
				pie.UpdateSliceValue("Age", 2)
				isFactor = true
			}
		}
		if hasAfib && isFactor {
			score := pie.TotalValues()
			percent := ScoreToStrokeRisk[score]
			results = append(results, plugin.RiskServiceCalculationResult{
				AsOf:               event.Date,
				Score:              &score,
				ProbabilityDecimal: &percent,
				Pie:                pie,
			})
		}
	}

	return results, nil
}
239902
func (c *CmdChatSetRetention) parseExpireAgeLimited(s string) (gregor1.DurationSec, error) {
	var d time.Duration
	switch s {
	case "1d", "24h":
		d = 24 * time.Hour
	case "7d", "1w":
		d = 7 * 24 * time.Hour
	case "30d", "1m":
		d = 30 * 24 * time.Hour
	case "3m":
		d = 90 * 24 * time.Hour
	case "12m", "1y":
		d = 365 * 24 * time.Hour
	default:
		return 0, fmt.Errorf("invalid expiration age: %v", s)
	}
	return gregor1.DurationSec(d.Seconds()), nil
}
351378
func CalculateTTL(sysView logical.SystemView, increment, backendTTL, period, backendMaxTTL, explicitMaxTTL time.Duration, startTime time.Time) (ttl time.Duration, warnings []string, errors error) {
	// Truncate all times to the second since that is the lowest precision for
	// TTLs
	now := time.Now().Truncate(time.Second)
	if startTime.IsZero() {
		startTime = now
	} else {
		startTime = startTime.Truncate(time.Second)
	}

	// Use the mount's configured max unless the backend specifies
	// something more restrictive (perhaps from a role configuration
	// parameter)
	maxTTL := sysView.MaxLeaseTTL()
	if backendMaxTTL > 0 && backendMaxTTL < maxTTL {
		maxTTL = backendMaxTTL
	}
	if explicitMaxTTL > 0 && explicitMaxTTL < maxTTL {
		maxTTL = explicitMaxTTL
	}

	// Should never happen, but guard anyways
	if maxTTL <= 0 {
		return 0, nil, fmt.Errorf("max TTL must be greater than zero")
	}

	var maxValidTime time.Time
	switch {
	case period > 0:
		// Cap the period value to the sys max_ttl value
		if period > maxTTL {
			warnings = append(warnings,
				fmt.Sprintf("period of %q exceeded the effective max_ttl of %q; period value is capped accordingly", period, maxTTL))
			period = maxTTL
		}
		ttl = period

		if explicitMaxTTL > 0 {
			maxValidTime = startTime.Add(explicitMaxTTL)
		}
	default:
		switch {
		case increment > 0:
			ttl = increment
		case backendTTL > 0:
			ttl = backendTTL
		default:
			ttl = sysView.DefaultLeaseTTL()
		}

		// We cannot go past this time
		maxValidTime = startTime.Add(maxTTL)
	}

	if !maxValidTime.IsZero() {
		// Determine the max valid TTL
		maxValidTTL := maxValidTime.Sub(now)

		// If we are past the max TTL, we shouldn't be in this function...but
		// fast path out if we are
		if maxValidTTL < 0 {
			return 0, nil, fmt.Errorf("past the max TTL, cannot renew")
		}

		// If the proposed expiration is after the maximum TTL of the lease,
		// cap the increment to whatever is left
		if maxValidTTL-ttl < 0 {
			warnings = append(warnings,
				fmt.Sprintf("TTL of %q exceeded the effective max_ttl of %q; TTL value is capped accordingly", ttl, maxValidTTL))
			ttl = maxValidTTL
		}
	}

	return ttl, warnings, nil
}
210637
func (ttles *TTLExpirationScheduler) OnBlobExpire(f expiryFunc) {
	ttles.Lock()
	defer ttles.Unlock()

	ttles.onBlobExpire = f
}
1057991
func Expiry(clock clockwork.Clock, ttl time.Duration) time.Time {
	if ttl == 0 {
		return time.Time{}
	}
	return clock.Now().UTC().Add(ttl)
}
237835
func OptionExperimental(exp bool) Option {
	return func(c *Config) {
		logrus.Debugf("Option Experimental: %v", exp)
		c.Daemon.Experimental = exp
	}
}
435017
func convertExpirationTime(t time.Time) (secs uint64, nsecs uint32) {
	// Fuse represents durations as unsigned 64-bit counts of seconds and 32-bit
	// counts of nanoseconds (cf. http://goo.gl/EJupJV). So negative durations
	// are right out. There is no need to cap the positive magnitude, because
	// 2^64 seconds is well longer than the 2^63 ns range of time.Duration.
	d := t.Sub(time.Now())
	if d > 0 {
		secs = uint64(d / time.Second)
		nsecs = uint32((d % time.Second) / time.Nanosecond)
	}

	return
}
32430
func (rw *RetryWaiter) calculateWait() time.Duration {
	waitTime := rw.minWait
	if rw.failures > rw.minFailures {
		shift := rw.failures - rw.minFailures - 1
		waitTime = rw.maxWait
		if shift < 31 {
			waitTime = (1 << shift) * time.Second
		}
		if waitTime > rw.maxWait {
			waitTime = rw.maxWait
		}

		if rw.jitter != nil {
			waitTime = rw.jitter.AddJitter(waitTime)
		}
	}

	if waitTime < rw.minWait {
		waitTime = rw.minWait
	}

	return waitTime
}
254245
func roundDuration(in int64) int64 {
	abs := in
	if abs < 0 {
		abs = -abs
	}
	if abs <= 10 { // 10s -> don't round
		return in
	} else if abs <= 60 { // 1min -> round to 10s
		return round(in, 10)
	} else if abs <= 600 { // 10min -> round to 1min
		return round(in, 60)
	} else if abs <= 3600 { // 1h -> round to 10min
		return round(in, 600)
	} else if abs <= 3600*24 { // 24h -> round to 1h
		return round(in, 3600)
	} else if abs <= 3600*24*7 { // 7d -> round to 1d
		return round(in, 3600*24)
	} else if abs <= 3600*24*30 { // 30d -> round to 7d
		return round(in, 3600*24*7)
	}
	// default to rounding to months
	return round(in, 3600*24*30)
}
221200
func (c *Context) Timing(sampleRate float32, bucket string, d ...time.Duration) {
	if rand.Float32() > sampleRate {
		return
	}

	for _, dur := range d {
		c.Log(Data{"metric": bucket, "timing": int64(dur / time.Millisecond)})
	}
}
419235
func randEatTime(minSec, maxSec int) time.Duration {
	sec := rand.Intn(maxSec-minSec) + minSec
	return time.Duration(sec) * time.Second
}
107521
func RandomDuration(max time.Duration) time.Duration {
	if max == 0 {
		return 0
	}

	var sleepns int64
	maxSleep := big.NewInt(max.Nanoseconds())
	if j, err := rand.Int(rand.Reader, maxSleep); err == nil {
		sleepns = j.Int64()
	}

	return time.Duration(sleepns)
}
616128
func (t ntpTime) Duration() time.Duration {
	sec := (t >> 32) * nanoPerSec
	frac := (t & 0xffffffff) * nanoPerSec >> 32
	return time.Duration(sec + frac)
}
638990
func calculateEvenSplits(size int64, src SourceInfo) (startIndex, endIndex []int64) {
	if size == 0 {
		return
	}

	reqParts := partsRequired(size)
	startIndex = make([]int64, reqParts)
	endIndex = make([]int64, reqParts)
	// Compute number of required parts `k`, as:
	//
	// k = ceiling(size / copyPartSize)
	//
	// Now, distribute the `size` bytes in the source into
	// k parts as evenly as possible:
	//
	// r parts sized (q+1) bytes, and
	// (k - r) parts sized q bytes, where
	//
	// size = q * k + r (by simple division of size by k,
	// so that 0 <= r < k)
	//
	start := src.start
	if start == -1 {
		start = 0
	}
	quot, rem := size/reqParts, size%reqParts
	nextStart := start
	for j := int64(0); j < reqParts; j++ {
		curPartSize := quot
		if j < rem {
			curPartSize++
		}

		cStart := nextStart
		cEnd := cStart + curPartSize - 1
		nextStart = cEnd + 1

		startIndex[j], endIndex[j] = cStart, cEnd
	}
	return
}
1325729
func Exponential(factor time.Duration, base float64) Algorithm {
	return func(attempt uint) time.Duration {
		return (factor * time.Duration(math.Pow(base, float64(attempt))))
	}
}