// Apply alters the weights of two services.
172842
func (input *BackendInput) Apply(ref, to *routev1.RouteTargetReference, backends []routev1.RouteTargetReference) {
	weight := int32(100)
	if ref.Weight != nil {
		weight = *ref.Weight
	}
	switch {
	case input.Percentage:
		if to == nil {
			weight += (weight * input.Value) / 100
			ref.Weight = &weight
			return
		}

		otherWeight := int32(0)
		if to.Weight != nil {
			otherWeight = *to.Weight
		}
		previousWeight := weight + otherWeight

		// rebalance all other backends to be relative in weight to the current
		for i, other := range backends {
			if previousWeight == 0 || other.Weight == nil || other.Name == ref.Name || other.Name == to.Name {
				continue
			}
			adjusted := *other.Weight * 100 / previousWeight
			backends[i].Weight = &adjusted
		}

		// adjust the weight between ref and to
		target := float32(input.Value) / 100
		if input.Relative {
			if previousWeight != 0 {
				percent := float32(weight) / float32(previousWeight)
				target = percent + target
			}
		}
		switch {
		case target < 0:
			target = 0
		case target > 1:
			target = 1
		}
		weight = int32(target * 100)
		otherWeight = int32((1 - target) * 100)
		ref.Weight = &weight
		to.Weight = &otherWeight

		// rescale the max to 200 in case we are dealing with very small percentages
		max := int32(0)
		for _, other := range backends {
			if other.Weight == nil {
				continue
			}
			if *other.Weight > max {
				max = *other.Weight
			}
		}
		if max > 256 {
			for i, other := range backends {
				if other.Weight == nil || *other.Weight == 0 {
					continue
				}
				adjusted := 200 * *other.Weight / max
				if adjusted < 1 {
					adjusted = 1
				}
				backends[i].Weight = &adjusted
			}
		}

	case input.Relative:
		weight += input.Value
		if weight < 0 {
			weight = 0
		}
		ref.Weight = &weight

	default:
		ref.Weight = &input.Value
	}
}
1093794
func (f RedirectPolicyFunc) Apply(req *http.Request, via []*http.Request) error {
	return f(req, via)
}
808655
func (t BackendTransform) Apply(b *Backends) error {
	switch {
	case t.Zero:
		zero := int32(0)
		for i := range b.Backends {
			b.Backends[i].Weight = &zero
		}

	case t.Equal:
		equal := int32(100)
		for i := range b.Backends {
			b.Backends[i].Weight = &equal
		}

	case t.Adjust:
		input := t.Inputs[0]
		switch {
		case len(b.Backends) == 0:
			return fmt.Errorf("no backends can be adjusted")
		case len(b.Backends) == 1:
			// treat adjusting primary specially
			backend := &b.Backends[0]
			if backend.Name != input.Name {
				return fmt.Errorf("backend %q is not in the list of backends (%s)", input.Name, strings.Join(b.Names(), ", "))
			}
			if input.Relative {
				return fmt.Errorf("cannot adjust a single backend by relative weight")
			}
			// ignore distinction between percentage and weight for single backend
			backend.Weight = &input.Value
		case b.Backends[0].Name == input.Name:
			// changing the primary backend, multiple available
			if len(b.Backends) == 1 {
				input.Apply(&b.Backends[0], nil, b.Backends)
				return nil
			}
			input.Apply(&b.Backends[0], &b.Backends[1], b.Backends)

		default:
			// changing an alternate backend, multiple available
			for i := range b.Backends {
				if b.Backends[i].Name != input.Name {
					continue
				}
				input.Apply(&b.Backends[i], &b.Backends[0], b.Backends)
				return nil
			}
			return fmt.Errorf("backend %q is not in the list of backends (%s)", input.Name, strings.Join(b.Names(), ", "))
		}

	default:
		b.Backends = nil
		for _, input := range t.Inputs {
			weight := input.Value
			b.Backends = append(b.Backends, routev1.RouteTargetReference{
				Kind:   "Service",
				Name:   input.Name,
				Weight: &weight,
			})
		}
	}
	return nil
}
12572
func (o *QueryOptions) Apply(opts []QueryOpt) {
	for _, opt := range opts {
		opt.f(o)
	}
}
1365175
func (u *VariableUpdate) Apply(m *Variable) error {
	if u.Name != "" {
		m.Name = u.Name
	}

	if u.Selected != nil {
		m.Selected = u.Selected
	}

	if u.Arguments != nil {
		m.Arguments = u.Arguments
	}

	if u.Description != "" {
		m.Description = u.Description
	}

	return nil
}
582819
func (sf *SigFilter) Apply(message *cb.Envelope) error {
	signedData, err := message.AsSignedData()

	if err != nil {
		return fmt.Errorf("could not convert message to signedData: %s", err)
	}

	policy, ok := sf.support.PolicyManager().GetPolicy(sf.policyName)
	if !ok {
		return fmt.Errorf("could not find policy %s", sf.policyName)
	}

	err = policy.Evaluate(signedData)
	if err != nil {
		return errors.Wrap(errors.WithStack(ErrPermissionDenied), err.Error())
	}
	return nil
}
943393
func (q *Query) Apply(fn func(*Query) (*Query, error)) *Query {
	qq, err := fn(q)
	if err != nil {
		q.err(err)
		return q
	}
	return qq
}
181099
func (f *Int64Flag) Apply(set *flag.FlagSet) {
	f.set = set
	f.Int64Flag.Apply(set)
}
468552
func (s windowsLcowDiff) Apply(ctx context.Context, desc ocispec.Descriptor, mounts []mount.Mount) (d ocispec.Descriptor, err error) {
	t1 := time.Now()
	defer func() {
		if err == nil {
			log.G(ctx).WithFields(logrus.Fields{
				"d":     time.Since(t1),
				"dgst":  desc.Digest,
				"size":  desc.Size,
				"media": desc.MediaType,
			}).Debugf("diff applied")
		}
	}()

	layer, _, err := mountsToLayerAndParents(mounts)
	if err != nil {
		return emptyDesc, err
	}

	isCompressed, err := images.IsCompressedDiff(ctx, desc.MediaType)
	if err != nil {
		return emptyDesc, errors.Wrapf(errdefs.ErrNotImplemented, "unsupported diff media type: %v", desc.MediaType)
	}

	ra, err := s.store.ReaderAt(ctx, desc)
	if err != nil {
		return emptyDesc, errors.Wrap(err, "failed to get reader from content store")
	}
	defer ra.Close()
	rdr := content.NewReader(ra)
	if isCompressed {
		ds, err := compression.DecompressStream(rdr)
		if err != nil {
			return emptyDesc, err
		}
		defer ds.Close()
		rdr = ds
	}
	// Calculate the Digest as we go
	digester := digest.Canonical.Digester()
	rc := &readCounter{
		r: io.TeeReader(rdr, digester.Hash()),
	}

	layerPath := path.Join(layer, "layer.vhd")
	outFile, err := os.Create(layerPath)
	if err != nil {
		return emptyDesc, err
	}
	defer func() {
		if err != nil {
			outFile.Close()
			os.Remove(layerPath)
		}
	}()

	err = tar2ext4.Convert(rc, outFile, tar2ext4.ConvertWhiteout, tar2ext4.AppendVhdFooter, tar2ext4.MaximumDiskSize(maxLcowVhdSizeGB))
	if err != nil {
		return emptyDesc, errors.Wrapf(err, "failed to convert tar to ext4 vhd")
	}
	outFile.Close()

	err = security.GrantVmGroupAccess(layerPath)
	if err != nil {
		return emptyDesc, errors.Wrapf(err, "failed GrantVmGroupAccess on layer vhd: %v", layerPath)
	}

	return ocispec.Descriptor{
		MediaType: ocispec.MediaTypeImageLayer,
		Size:      rc.c,
		Digest:    digester.Digest(),
	}, nil
}
263524
func (c *clusterOption) Apply(server *Server) {
	// TODO: support enabling/disabling clustering.
	server.mu.Lock()
	tlsRequired := c.newValue.TLSConfig != nil
	server.routeInfo.TLSRequired = tlsRequired
	server.routeInfo.TLSVerify = tlsRequired
	server.routeInfo.AuthRequired = c.newValue.Username != ""
	if c.newValue.NoAdvertise {
		server.routeInfo.ClientConnectURLs = nil
	} else {
		server.routeInfo.ClientConnectURLs = server.clientConnectURLs
	}
	server.setRouteInfoHostPortAndIP()
	server.mu.Unlock()
	server.Noticef("Reloaded: cluster")
	if tlsRequired && c.newValue.TLSConfig.InsecureSkipVerify {
		server.Warnf(clusterTLSInsecureWarning)
	}
}
1077596
func (s windowsDiff) Apply(ctx context.Context, desc ocispec.Descriptor, mounts []mount.Mount) (d ocispec.Descriptor, err error) {
	t1 := time.Now()
	defer func() {
		if err == nil {
			log.G(ctx).WithFields(logrus.Fields{
				"d":     time.Since(t1),
				"dgst":  desc.Digest,
				"size":  desc.Size,
				"media": desc.MediaType,
			}).Debugf("diff applied")
		}
	}()

	isCompressed, err := images.IsCompressedDiff(ctx, desc.MediaType)
	if err != nil {
		return emptyDesc, errors.Wrapf(errdefs.ErrNotImplemented, "unsupported diff media type: %v", desc.MediaType)
	}

	ra, err := s.store.ReaderAt(ctx, desc)
	if err != nil {
		return emptyDesc, errors.Wrap(err, "failed to get reader from content store")
	}
	defer ra.Close()

	r := content.NewReader(ra)
	if isCompressed {
		ds, err := compression.DecompressStream(r)
		if err != nil {
			return emptyDesc, err
		}
		defer ds.Close()
		r = ds
	}

	digester := digest.Canonical.Digester()
	rc := &readCounter{
		r: io.TeeReader(r, digester.Hash()),
	}

	layer, parentLayerPaths, err := mountsToLayerAndParents(mounts)
	if err != nil {
		return emptyDesc, err
	}

	// TODO darrenstahlmsft: When this is done isolated, we should disable these.
	// it currently cannot be disabled, unless we add ref counting. Since this is
	// temporary, leaving it enabled is OK for now.
	if err := winio.EnableProcessPrivileges([]string{winio.SeBackupPrivilege, winio.SeRestorePrivilege}); err != nil {
		return emptyDesc, err
	}

	if _, err := archive.Apply(ctx, layer, rc, archive.WithParentLayers(parentLayerPaths), archive.AsWindowsContainerLayer()); err != nil {
		return emptyDesc, err
	}

	// Read any trailing data
	if _, err := io.Copy(ioutil.Discard, rc); err != nil {
		return emptyDesc, err
	}

	return ocispec.Descriptor{
		MediaType: ocispec.MediaTypeImageLayer,
		Size:      rc.c,
		Digest:    digester.Digest(),
	}, nil
}
193957
func (b BoolTag) Apply(err error) error {
	if err == nil {
		return nil
	}
	a := &Annotator{err, stackContext{frameInfo: stackFrameInfoForError(1, err)}}
	return a.Tag(b).Err()
}
473591
func (cm *Validator) Apply(configEnv *cb.ConfigEnvelope) error {
	cm.AppliedConfigUpdateEnvelope = configEnv
	return cm.ApplyVal
}
208136
func (m *Map) Apply(
	info *terraform.InstanceInfo,
	s *terraform.InstanceState,
	d *terraform.InstanceDiff,
	meta interface{}) (*terraform.InstanceState, error) {
	r, ok := m.Mapping[info.Type]
	if !ok {
		return nil, fmt.Errorf("Unknown resource type: %s", info.Type)
	}

	if d.Destroy || d.RequiresNew() {
		if s.ID != "" {
			// Destroy the resource if it is created
			err := r.Destroy(s, meta)
			if err != nil {
				return s, err
			}

			s.ID = ""
		}

		// If we're only destroying, and not creating, then return now.
		// Otherwise, we continue so that we can create a new resource.
		if !d.RequiresNew() {
			return nil, nil
		}
	}

	var result *terraform.InstanceState
	var err error
	if s.ID == "" {
		result, err = r.Create(s, d, meta)
	} else {
		if r.Update == nil {
			return s, fmt.Errorf(
				"Resource type '%s' doesn't support update",
				info.Type)
		}

		result, err = r.Update(s, d, meta)
	}
	if result != nil {
		if result.Attributes == nil {
			result.Attributes = make(map[string]string)
		}

		result.Attributes["id"] = result.ID
	}

	return result, err
}
460864
func (t *tlsOption) Apply(server *Server) {
	server.mu.Lock()
	tlsRequired := t.newValue != nil
	server.info.TLSRequired = tlsRequired
	message := "disabled"
	if tlsRequired {
		server.info.TLSVerify = (t.newValue.ClientAuth == tls.RequireAndVerifyClientCert)
		message = "enabled"
	}
	server.mu.Unlock()
	server.Noticef("Reloaded: tls = %s", message)
}
596460
func (inj *injector) Apply(val interface{}) error {
	v := reflect.ValueOf(val)

	for v.Kind() == reflect.Ptr {
		v = v.Elem()
	}

	if v.Kind() != reflect.Struct {
		return nil // Should not panic here ?
	}

	t := v.Type()

	for i := 0; i < v.NumField(); i++ {
		f := v.Field(i)
		structField := t.Field(i)
		if f.CanSet() && (structField.Tag == "inject" || structField.Tag.Get("inject") != "") {
			ft := f.Type()
			v := inj.GetVal(ft)
			if !v.IsValid() {
				return fmt.Errorf("Value not found for type %v", ft)
			}

			f.Set(v)
		}

	}

	return nil
}
1057939
func (x Vector) Apply(f func(float64) float64) Vector {
	y := make(Vector, len(x))

	for i, v := range x {
		y[i] = f(v)
	}
	return y
}