// ToPrivilege returns a legacy sparta.IAMRolePrivilege type for this
// entry
422094
func (iamRes *IAMResourceBuilder) ToPrivilege() sparta.IAMRolePrivilege {
	return sparta.IAMRolePrivilege{
		Actions:  iamRes.builder.apiCalls,
		Resource: gocf.Join("", iamRes.resourceParts...),
	}
}
431368
func CheckPrivilege(activeRoles []*auth.RoleIdentity, pm privilege.Manager, vs []visitInfo) error {
	for _, v := range vs {
		if !pm.RequestVerification(activeRoles, v.db, v.table, v.column, v.privilege) {
			if v.err == nil {
				return ErrPrivilegeCheckFail
			}
			return v.err
		}
	}
	return nil
}
1130603
func (m *multi) ToProto() proto.Message {
	// aggregate calls per region
	actionsPerReg := map[hrpc.RegionInfo][]*pb.Action{}

	for i, c := range m.calls {
		select {
		case <-c.Context().Done():
			// context has expired, don't bother sending it
			m.calls[i] = nil
			continue
		default:
		}

		msg := c.ToProto()

		a := &pb.Action{
			Index: proto.Uint32(uint32(i) + 1), // +1 because 0 index means there's no index
		}

		switch r := msg.(type) {
		case *pb.GetRequest:
			a.Get = r.Get
		case *pb.MutateRequest:
			a.Mutation = r.Mutation
		default:
			panic(fmt.Sprintf("unsupported call type for Multi: %T", c))
		}

		actionsPerReg[c.Region()] = append(actionsPerReg[c.Region()], a)
	}

	// construct the multi proto
	ra := make([]*pb.RegionAction, len(actionsPerReg))
	m.regions = make([]hrpc.RegionInfo, len(actionsPerReg))

	i := 0
	for r, as := range actionsPerReg {
		ra[i] = &pb.RegionAction{
			Region: &pb.RegionSpecifier{
				Type:  pb.RegionSpecifier_REGION_NAME.Enum(),
				Value: r.Name(),
			},
			Action: as,
		}
		// Track the order of RegionActions,
		// so that we can handle whole region exceptions.
		m.regions[i] = r
		i++
	}
	return &pb.MultiRequest{RegionAction: ra}
}
1177178
func ToPriv(a chronograf.Allowances) string {
	if len(a) == 0 {
		return NoPrivileges
	}
	hasWrite := false
	hasRead := false
	for _, aa := range a {
		if aa == Read {
			hasRead = true
		} else if aa == Write {
			hasWrite = true
		} else if aa == All {
			hasRead, hasWrite = true, true
		}
	}

	if hasWrite && hasRead {
		return All
	} else if hasWrite {
		return Write
	} else if hasRead {
		return Read
	}
	return NoPrivileges
}
278592
func (cp *ComparablePrincipal) ToRole() *ComparablePrincipal {
	mspRole := &msp.MSPRole{}
	err := proto.Unmarshal(cp.principal.Principal, mspRole)
	if err != nil {
		logger.Warning("Failed unmarshaling principal:", err)
		return nil
	}
	cp.mspID = mspRole.MspIdentifier
	cp.role = mspRole
	return cp
}
236666
func (p *PUPolicyPublic) ToPrivatePolicy(convert bool) (*PUPolicy, error) {
	var err error

	exposedServices := ApplicationServicesList{}
	for _, e := range p.ExposedServices {
		if convert {
			e.UserAuthorizationHandler, err = usertokens.NewVerifier(e.UserAuthorizationHandler)
			if err != nil {
				return nil, fmt.Errorf("unable to initialize user authorization handler for service: %s - error %s", e.ID, err)
			}
		}
		exposedServices = append(exposedServices, e)
	}

	return &PUPolicy{
		managementID:          p.ManagementID,
		triremeAction:         p.TriremeAction,
		applicationACLs:       p.ApplicationACLs,
		networkACLs:           p.NetworkACLs.Copy(),
		DNSACLs:               p.DNSACLs.Copy(),
		transmitterRules:      p.TransmitterRules.Copy(),
		receiverRules:         p.ReceiverRules.Copy(),
		annotations:           p.Annotations.Copy(),
		identity:              p.Identity.Copy(),
		ips:                   p.IPs.Copy(),
		servicesListeningPort: p.ServicesListeningPort,
		exposedServices:       exposedServices,
		dependentServices:     p.DependentServices,
		scopes:                p.Scopes,
		servicesCA:            p.ServicesCA,
		servicesCertificate:   p.ServicesCertificate,
		servicesPrivateKey:    p.ServicesPrivateKey,
	}, nil
}
1195491
func (m *GormIdentityRoleRepository) FindIdentityRolesByIdentityAndResource(ctx context.Context, resourceID string, identityID uuid.UUID) ([]IdentityRole, error) {
	return m.query(identityRoleFilterByIdentityID(identityID), identityRoleFilterByResource(resourceID))
}
527782
func (g *Generic) PrincipalIDFromClaims(claims gojwt.MapClaims) (string, error) {
	if id, ok := claims[g.APIKey].(string); ok {
		return id, nil
	}
	return "", fmt.Errorf("no claim for %s", g.APIKey)
}
263598
func (f *HumanPrintFlags) ToPrinter(outputFormat string) (printers.ResourcePrinter, error) {
	if len(outputFormat) > 0 && outputFormat != "wide" {
		return nil, genericclioptions.NoCompatiblePrinterError{Options: f, AllowedFormats: f.AllowedFormats()}
	}

	showKind := false
	if f.ShowKind != nil {
		showKind = *f.ShowKind
	}

	showLabels := false
	if f.ShowLabels != nil {
		showLabels = *f.ShowLabels
	}

	columnLabels := []string{}
	if f.ColumnLabels != nil {
		columnLabels = *f.ColumnLabels
	}

	p := printers.NewTablePrinter(printers.PrintOptions{
		Kind:          f.Kind,
		WithKind:      showKind,
		NoHeaders:     f.NoHeaders,
		Wide:          outputFormat == "wide",
		WithNamespace: f.WithNamespace,
		ColumnLabels:  columnLabels,
		ShowLabels:    showLabels,
	})
	printersinternal.AddHandlers(p)

	// TODO(juanvallejo): handle sorting here

	return p, nil
}
71483
func activateTopoCustomRules(qsc tabletserver.Controller) {
	if *rulePath != "" {
		qsc.RegisterQueryRuleSource(topoCustomRuleSource)

		cr, err := newTopoCustomRule(qsc, *ruleCell, *rulePath)
		if err != nil {
			log.Fatalf("cannot start TopoCustomRule: %v", err)
		}
		cr.start()

		servenv.OnTerm(cr.stop)
	}
}
799472
func (s *privilegeCacheServiceImpl) CachedPrivileges(ctx context.Context, identityID uuid.UUID, resourceID string) (*permission.PrivilegeCache, error) {
	nowTime := time.Now()

	// Attempt to load the privilege cache record from the database
	privilegeCache, err := s.Repositories().PrivilegeCacheRepository().FindForIdentityResource(ctx, identityID, resourceID)
	notFound := false
	if err != nil {
		switch err.(type) {
		case errors.NotFoundError:
			notFound = true
		}
	}

	// If there was no privilege cache record found, or the record has expired, then recalculate the scopes and either
	// update the existing record, or create a new one
	if notFound || privilegeCache.Stale || privilegeCache.ExpiryTime.Before(nowTime) {
		scopes, err := s.Repositories().IdentityRoleRepository().FindScopesByIdentityAndResource(ctx, identityID, resourceID)
		if err != nil {
			return nil, errors.NewInternalError(ctx, err)
		}

		scopeList := strings.Join(scopes, ",")

		// If the privilege cache record doesn't exist, create a new one
		if notFound {
			privilegeCache = &permission.PrivilegeCache{
				IdentityID: identityID,
				ResourceID: resourceID,
				Scopes:     scopeList,
				Stale:      false,
				ExpiryTime: time.Now().Local().Add(time.Second * time.Duration(s.conf.GetPrivilegeCacheExpirySeconds())),
			}

			err = s.ExecuteInTransaction(func() error {
				return s.Repositories().PrivilegeCacheRepository().Create(ctx, privilegeCache)
			})

			if err != nil {
				return nil, errors.NewInternalError(ctx, err)
			}
		} else {
			// Otherwise update the existing record
			privilegeCache.Scopes = scopeList
			privilegeCache.Stale = false
			privilegeCache.ExpiryTime = time.Now().Local().Add(time.Second * time.Duration(s.conf.GetPrivilegeCacheExpirySeconds()))

			err = s.ExecuteInTransaction(func() error {
				return s.Repositories().PrivilegeCacheRepository().Save(ctx, privilegeCache)
			})

			if err != nil {
				return nil, errors.NewInternalError(ctx, err)
			}
		}
	}

	return privilegeCache, nil
}
772323
func (f *PrintFlags) ToPrinter() (printers.ResourcePrinter, error) {
	outputFormat := ""
	if f.OutputFormat != nil {
		outputFormat = *f.OutputFormat
	}

	noHeaders := false
	if f.NoHeaders != nil {
		noHeaders = *f.NoHeaders
	}
	f.HumanReadableFlags.NoHeaders = noHeaders
	f.CustomColumnsFlags.NoHeaders = noHeaders

	// for "get.go" we want to support a --template argument given, even when no --output format is provided
	if f.TemplateFlags.TemplateArgument != nil && len(*f.TemplateFlags.TemplateArgument) > 0 && len(outputFormat) == 0 {
		outputFormat = "go-template"
	}

	if p, err := f.TemplateFlags.ToPrinter(outputFormat); !genericclioptions.IsNoCompatiblePrinterError(err) {
		return p, err
	}

	if f.TemplateFlags.TemplateArgument != nil {
		f.CustomColumnsFlags.TemplateArgument = *f.TemplateFlags.TemplateArgument
	}

	if p, err := f.JSONYamlPrintFlags.ToPrinter(outputFormat); !genericclioptions.IsNoCompatiblePrinterError(err) {
		return p, err
	}

	if p, err := f.HumanReadableFlags.ToPrinter(outputFormat); !genericclioptions.IsNoCompatiblePrinterError(err) {
		return p, err
	}

	if p, err := f.CustomColumnsFlags.ToPrinter(outputFormat); !genericclioptions.IsNoCompatiblePrinterError(err) {
		return p, err
	}

	if p, err := f.NamePrintFlags.ToPrinter(outputFormat); !genericclioptions.IsNoCompatiblePrinterError(err) {
		return p, err
	}

	return nil, genericclioptions.NoCompatiblePrinterError{OutputFormat: &outputFormat, AllowedFormats: f.AllowedFormats()}
}
1325474
func isValidPath(candidatePath string, delgRole data.DelegationRole) bool {
	return candidatePath == "" || delgRole.CheckPaths(candidatePath)
}
185762
func (d *Context) ToPointer(index int) unsafe.Pointer {
	return C.duk_to_pointer(d.duk_context, C.duk_idx_t(index))
}
1048039
func toPointer(i *Message) pointer {
	// Super-tricky - read pointer out of data word of interface value.
	// Saves ~25ns over the equivalent:
	// return valToPointer(reflect.ValueOf(*i))
	return pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]}
}
193460
func ToPredicate(ce ConsumedElement) (*predicate.Predicate, error) {
	if ce.IsSymbol() {
		return nil, fmt.Errorf("semantic.ToPredicate cannot convert symbol %v to a predicate", ce)
	}
	tkn := ce.Token()
	if tkn.Type != lexer.ItemPredicate {
		return nil, fmt.Errorf("semantic.ToPredicate cannot convert token type %s to a predicate", tkn.Type)
	}
	return predicate.Parse(tkn.Text)
}
328188
func (t *EmpireTemplate) serviceRoleArn() interface{} {
	if _, err := arn.Parse(t.ServiceRole); err == nil {
		return t.ServiceRole
	}
	return Join("", "arn:aws:iam::", Ref("AWS::AccountId"), ":role/", t.ServiceRole)
}