// evaluateResourceCountExpressionKnown is like evaluateResourceCountExpression
// except that it handles an unknown result by returning count = 0 and
// a known = false, rather than by reporting the unknown value as an error
// diagnostic.
495512
func evaluateResourceCountExpressionKnown(expr hcl.Expression, ctx EvalContext) (count int, known bool, diags tfdiags.Diagnostics) {
	if expr == nil {
		return -1, true, nil
	}

	countVal, countDiags := ctx.EvaluateExpr(expr, cty.Number, nil)
	diags = diags.Append(countDiags)
	if diags.HasErrors() {
		return -1, true, diags
	}

	switch {
	case countVal.IsNull():
		diags = diags.Append(&hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Invalid count argument",
			Detail:   `The given "count" argument value is null. An integer is required.`,
			Subject:  expr.Range().Ptr(),
		})
		return -1, true, diags
	case !countVal.IsKnown():
		return 0, false, diags
	}

	err := gocty.FromCtyValue(countVal, &count)
	if err != nil {
		diags = diags.Append(&hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Invalid count argument",
			Detail:   fmt.Sprintf(`The given "count" argument value is unsuitable: %s.`, err),
			Subject:  expr.Range().Ptr(),
		})
		return -1, true, diags
	}
	if count < 0 {
		diags = diags.Append(&hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Invalid count argument",
			Detail:   `The given "count" argument value is unsuitable: negative numbers are not supported.`,
			Subject:  expr.Range().Ptr(),
		})
		return -1, true, diags
	}

	return count, true, diags
}
161300
func (scope *EvalScope) EvalExpression(expr string, cfg LoadConfig) (*Variable, error) {
	t, err := parser.ParseExpr(expr)
	if err != nil {
		return nil, err
	}

	ev, err := scope.evalToplevelTypeCast(t, cfg)
	if ev == nil && err == nil {
		ev, err = scope.evalAST(t)
	}
	if err != nil {
		return nil, err
	}
	ev.loadValue(cfg)
	if ev.Name == "" {
		ev.Name = expr
	}
	return ev, nil
}
542929
func (service *Service) EvaluateVolumesTemplate(gs GetService, fc FindChildService, instanceID int) (err error) {
	for i, vol := range service.Volumes {
		err, result := service.evaluateTemplate(gs, fc, instanceID, vol.ResourcePath)
		if err != nil {
			return err
		}

		if result != "" {
			vol.ResourcePath = result
		}
		service.Volumes[i] = vol
	}
	return
}
610620
func InterpretCreateError(err error, qualifiedResource schema.GroupResource, name string) error {
	switch {
	case storage.IsNodeExist(err):
		return errors.NewAlreadyExists(qualifiedResource, name)
	case storage.IsUnreachable(err):
		return errors.NewServerTimeout(qualifiedResource, "create", 2) // TODO: make configurable or handled at a higher level
	case storage.IsInternalError(err):
		return errors.NewInternalError(err)
	default:
		return err
	}
}
502844
func (s *AutoScaleService) GetCounterByName(name string, opts ...OptionFunc) (*Counter, int, error) {
	id, count, err := s.GetCounterID(name, opts...)
	if err != nil {
		return nil, count, err
	}

	r, count, err := s.GetCounterByID(id, opts...)
	if err != nil {
		return nil, count, err
	}
	return r, count, nil
}
296013
func containerResourceRuntimeValue(fs *v1.ResourceFieldSelector, pod *v1.Pod, container *v1.Container) (string, error) {
	containerName := fs.ContainerName
	if len(containerName) == 0 {
		return resource.ExtractContainerResourceValue(fs, container)
	}
	return resource.ExtractResourceValueByContainerName(fs, pod, containerName)
}
826826
func (tpc *TwoPC) CountUnresolvedRedo(ctx context.Context, unresolvedTime time.Time) (int64, error) {
	conn, err := tpc.readPool.Get(ctx)
	if err != nil {
		return 0, err
	}
	defer conn.Recycle()

	bindVars := map[string]*querypb.BindVariable{
		"time_created": sqltypes.Int64BindVariable(unresolvedTime.UnixNano()),
	}
	qr, err := tpc.read(ctx, conn, tpc.countUnresolvedRedo, bindVars)
	if err != nil {
		return 0, err
	}
	if len(qr.Rows) < 1 {
		return 0, nil
	}
	v, _ := sqltypes.ToInt64(qr.Rows[0][0])
	return v, nil
}
373481
func validateResourceQuotaScopes(resourceQuotaSpec *core.ResourceQuotaSpec, fld *field.Path) field.ErrorList {
	allErrs := field.ErrorList{}
	if len(resourceQuotaSpec.Scopes) == 0 {
		return allErrs
	}
	hardLimits := sets.NewString()
	for k := range resourceQuotaSpec.Hard {
		hardLimits.Insert(string(k))
	}
	fldPath := fld.Child("scopes")
	scopeSet := sets.NewString()
	for _, scope := range resourceQuotaSpec.Scopes {
		if !helper.IsStandardResourceQuotaScope(string(scope)) {
			allErrs = append(allErrs, field.Invalid(fldPath, resourceQuotaSpec.Scopes, "unsupported scope"))
		}
		for _, k := range hardLimits.List() {
			if helper.IsStandardQuotaResourceName(k) && !helper.IsResourceQuotaScopeValidForResource(scope, k) {
				allErrs = append(allErrs, field.Invalid(fldPath, resourceQuotaSpec.Scopes, "unsupported scope applied to resource"))
			}
		}
		scopeSet.Insert(string(scope))
	}
	invalidScopePairs := []sets.String{
		sets.NewString(string(core.ResourceQuotaScopeBestEffort), string(core.ResourceQuotaScopeNotBestEffort)),
		sets.NewString(string(core.ResourceQuotaScopeTerminating), string(core.ResourceQuotaScopeNotTerminating)),
	}
	for _, invalidScopePair := range invalidScopePairs {
		if scopeSet.HasAll(invalidScopePair.List()...) {
			allErrs = append(allErrs, field.Invalid(fldPath, resourceQuotaSpec.Scopes, "conflicting scopes"))
		}
	}
	return allErrs
}
1254873
func (s *ComplianceSummary) SetCompliantResourceCount(v *ComplianceContributorCount) *ComplianceSummary {
	s.CompliantResourceCount = v
	return s
}
1236467
func resolveResourceRef(expr interface{}) (*resourceRef, error) {

	// Is there any chance it's just a string?
	typedString, typedStringOk := expr.(string)
	if typedStringOk {
		return &resourceRef{
			RefType:      resourceLiteral,
			ResourceName: typedString,
		}, nil
	}
	// Some type of intrinsic function?
	marshalled, marshalledErr := json.Marshal(expr)
	if marshalledErr != nil {
		return nil, errors.Errorf("Failed to unmarshal dynamic resource ref %v", expr)
	}
	var refFunc gocf.RefFunc
	if json.Unmarshal(marshalled, &refFunc) == nil &&
		len(refFunc.Name) != 0 {
		return &resourceRef{
			RefType:      resourceRefFunc,
			ResourceName: refFunc.Name,
		}, nil
	}

	var getAttFunc gocf.GetAttFunc
	if json.Unmarshal(marshalled, &getAttFunc) == nil && len(getAttFunc.Resource) != 0 {
		return &resourceRef{
			RefType:      resourceGetAttrFunc,
			ResourceName: getAttFunc.Resource,
		}, nil
	}
	// Any chance it's a string?
	var stringExprFunc gocf.StringExpr
	if json.Unmarshal(marshalled, &stringExprFunc) == nil && len(stringExprFunc.Literal) != 0 {
		return &resourceRef{
			RefType:      resourceStringFunc,
			ResourceName: stringExprFunc.Literal,
		}, nil
	}

	// Nope
	return nil, nil
}
892937
func (s *GroupedResourceCount) SetResourceCount(v int64) *GroupedResourceCount {
	s.ResourceCount = &v
	return s
}
642348
func ExtractResourceValueByContainerNameAndNodeAllocatable(fs *v1.ResourceFieldSelector, pod *v1.Pod, containerName string, nodeAllocatable v1.ResourceList) (string, error) {
	realContainer, err := findContainerInPod(pod, containerName)
	if err != nil {
		return "", err
	}

	container := realContainer.DeepCopy()

	MergeContainerResourceLimits(container, nodeAllocatable)

	return ExtractContainerResourceValue(fs, container)
}
1069380
func (st *resourceSyncTask) evalSpec(res *smith_v1.Resource, actual runtime.Object) (*unstructured.Unstructured, resourceStatus) {
	// Process the spec
	var objectOrPluginSpec map[string]interface{}

	switch {
	case res.Spec.Object != nil:
		specUnstr, err := util.RuntimeToUnstructured(res.Spec.Object)
		if err != nil {
			return nil, resourceStatusError{
				err: err,
			}
		}
		objectOrPluginSpec = specUnstr.Object
	case res.Spec.Plugin != nil:
		res = res.DeepCopy() // Spec processor mutates in place
		objectOrPluginSpec = res.Spec.Plugin.Spec
	default:
		return nil, resourceStatusError{
			err:             errors.New(`neither "object" nor "plugin" field is specified`),
			isExternalError: true,
		}
	}

	// Process references
	sp, err := newSpec(st.processedResources, res.References)
	if err != nil {
		return nil, resourceStatusError{
			err:             err,
			isExternalError: true,
		}
	}
	if err := sp.ProcessObject(objectOrPluginSpec); err != nil {
		return nil, resourceStatusError{
			err:             err,
			isExternalError: true,
		}
	}

	var obj *unstructured.Unstructured
	switch {
	case res.Spec.Object != nil:
		obj = &unstructured.Unstructured{
			Object: objectOrPluginSpec,
		}
	case res.Spec.Plugin != nil:
		var status resourceStatus
		obj, status = st.evalPluginSpec(res, actual)
		if status != nil {
			return nil, status
		}
	default:
		return nil, resourceStatusError{
			err:             errors.New(`neither "object" nor "plugin" field is specified`),
			isExternalError: true,
		}
	}

	// Update OwnerReferences
	trueRef := true
	refs := obj.GetOwnerReferences()
	for i, ref := range refs {
		if ref.Controller != nil && *ref.Controller {
			// user (or plugin) tried to create a resource with controller owner reference
			return nil, resourceStatusError{
				err:             errors.Errorf("cannot create resource with controller owner reference %v", ref),
				isExternalError: res.Spec.Plugin == nil,
			}
		}
		refs[i].BlockOwnerDeletion = &trueRef
	}
	// Hardcode APIVersion/Kind because of https://github.com/kubernetes/client-go/issues/60
	refs = append(refs, meta_v1.OwnerReference{
		APIVersion:         smith_v1.BundleResourceGroupVersion,
		Kind:               smith_v1.BundleResourceKind,
		Name:               st.bundle.Name,
		UID:                st.bundle.UID,
		Controller:         &trueRef,
		BlockOwnerDeletion: &trueRef,
	})
	setRefs := make(map[smith_v1.ResourceName]struct{}, len(res.References))
	for _, dep := range res.References {
		if _, ok := setRefs[dep.Resource]; ok {
			// This resource is referenced more than once and an owner reference has been added already
			continue
		}
		setRefs[dep.Resource] = struct{}{}
		processedObj := st.processedResources[dep.Resource].actual // this is ok because we've checked earlier that resources contains all dependencies
		refs = append(refs, meta_v1.OwnerReference{
			APIVersion:         processedObj.GetAPIVersion(),
			Kind:               processedObj.GetKind(),
			Name:               processedObj.GetName(),
			UID:                processedObj.GetUID(),
			BlockOwnerDeletion: &trueRef,
		})
	}
	obj.SetOwnerReferences(refs)
	switch obj.GetNamespace() {
	case "":
		obj.SetNamespace(st.bundle.Namespace)
	case st.bundle.Namespace:
	default:
		// the plugin or user created an object template with the namespace set to something wrong
		return nil, resourceStatusError{
			err:             errors.Errorf("namespace was %q which is different from the bundle namespace %q", obj.GetNamespace(), st.bundle.Namespace),
			isExternalError: res.Spec.Plugin == nil,
		}
	}

	return obj, nil
}
1265851
func (cf *countFunction) CalculateDefaultValue(schema Schema, ctx context.Context) (d types.Datum, valid bool) {
	for _, arg := range cf.Args {
		result, err := EvaluateExprWithNull(ctx, schema, arg)
		if err != nil {
			log.Printf("Evaluate expr with null failed in function %s, err msg is %s", cf, err.Error())
			return d, false
		}
		if con, ok := result.(*Constant); ok {
			if con.Value.IsNull() {
				return types.NewDatum(0), true
			}
		} else {
			return d, false
		}
	}
	return types.NewDatum(1), true
}
918174
func (s *Set) GetCount(name interface{}) int {
	if opt := s.Lookup(name); opt != nil {
		return opt.Count()
	}
	return 0
}
671088
func countFunc(q query, t iterator) interface{} {
	var count = 0
	test := predicate(q)
	switch typ := q.Evaluate(t).(type) {
	case query:
		for node := typ.Select(t); node != nil; node = typ.Select(t) {
			if test(node) {
				count++
			}
		}
	}
	return float64(count)
}
253383
func ExtractResourceValueByContainerName(fs *v1.ResourceFieldSelector, pod *v1.Pod, containerName string) (string, error) {
	container, err := findContainerInPod(pod, containerName)
	if err != nil {
		return "", err
	}
	return ExtractContainerResourceValue(fs, container)
}