text:
package server

import (
	"context"

	"github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl"
	cloudbuildpb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/cloudbuild/cloudbuild_go_proto"
	emptypb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/empty_go_proto"
	"github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/cloudbuild"
)

// Server implements the gRPC interface for BuildTrigger.
type BuildTriggerServer struct{}

// ProtoToBuildTriggerGithubPullRequestCommentControlEnum converts a BuildTriggerGithubPullRequestCommentControlEnum enum from its proto representation.
func ProtoToCloudbuildBuildTriggerGithubPullRequestCommentControlEnum(e cloudbuildpb.CloudbuildBuildTriggerGithubPullRequestCommentControlEnum) *cloudbuild.BuildTriggerGithubPullRequestCommentControlEnum {
	if e == 0 {
		return nil
	}
	if n, ok := cloudbuildpb.CloudbuildBuildTriggerGithubPullRequestCommentControlEnum_name[int32(e)]; ok {
		e := cloudbuild.BuildTriggerGithubPullRequestCommentControlEnum(n[len("CloudbuildBuildTriggerGithubPullRequestCommentControlEnum"):])
		return &e
	}
	return nil
}

// ProtoToBuildTriggerBuildStepsStatusEnum converts a BuildTriggerBuildStepsStatusEnum enum from its proto representation.
func ProtoToCloudbuildBuildTriggerBuildStepsStatusEnum(e cloudbuildpb.CloudbuildBuildTriggerBuildStepsStatusEnum) *cloudbuild.BuildTriggerBuildStepsStatusEnum {
	if e == 0 {
		return nil
	}
	if n, ok := cloudbuildpb.CloudbuildBuildTriggerBuildStepsStatusEnum_name[int32(e)]; ok {
		e := cloudbuild.BuildTriggerBuildStepsStatusEnum(n[len("CloudbuildBuildTriggerBuildStepsStatusEnum"):])
		return &e
	}
	return nil
}

// ProtoToBuildTriggerTriggerTemplate converts a BuildTriggerTriggerTemplate resource from its proto representation.
func ProtoToCloudbuildBuildTriggerTriggerTemplate(p *cloudbuildpb.CloudbuildBuildTriggerTriggerTemplate) *cloudbuild.BuildTriggerTriggerTemplate {
	if p == nil {
		return nil
	}
	obj := &cloudbuild.BuildTriggerTriggerTemplate{
		ProjectId:   dcl.StringOrNil(p.ProjectId),
		RepoName:    dcl.StringOrNil(p.RepoName),
		BranchName:  dcl.StringOrNil(p.BranchName),
		TagName:     dcl.StringOrNil(p.TagName),
		CommitSha:   dcl.StringOrNil(p.CommitSha),
		Dir:         dcl.StringOrNil(p.Dir),
		InvertRegex: dcl.Bool(p.InvertRegex),
	}
	return obj
}

// ProtoToBuildTriggerGithub converts a BuildTriggerGithub resource from its proto representation.
func ProtoToCloudbuildBuildTriggerGithub(p *cloudbuildpb.CloudbuildBuildTriggerGithub) *cloudbuild.BuildTriggerGithub {
	if p == nil {
		return nil
	}
	obj := &cloudbuild.BuildTriggerGithub{
		Owner:       dcl.StringOrNil(p.Owner),
		Name:        dcl.StringOrNil(p.Name),
		PullRequest: ProtoToCloudbuildBuildTriggerGithubPullRequest(p.GetPullRequest()),
		Push:        ProtoToCloudbuildBuildTriggerGithubPush(p.GetPush()),
	}
	return obj
}

// ProtoToBuildTriggerGithubPullRequest converts a BuildTriggerGithubPullRequest resource from its proto representation.
func ProtoToCloudbuildBuildTriggerGithubPullRequest(p *cloudbuildpb.CloudbuildBuildTriggerGithubPullRequest) *cloudbuild.BuildTriggerGithubPullRequest {
	if p == nil {
		return nil
	}
	obj := &cloudbuild.BuildTriggerGithubPullRequest{
		Branch:         dcl.StringOrNil(p.Branch),
		CommentControl: ProtoToCloudbuildBuildTriggerGithubPullRequestCommentControlEnum(p.GetCommentControl()),
		InvertRegex:    dcl.Bool(p.InvertRegex),
	}
	return obj
}

// ProtoToBuildTriggerGithubPush converts a BuildTriggerGithubPush resource from its proto representation.
func ProtoToCloudbuildBuildTriggerGithubPush(p *cloudbuildpb.CloudbuildBuildTriggerGithubPush) *cloudbuild.BuildTriggerGithubPush {
	if p == nil {
		return nil
	}
	obj := &cloudbuild.BuildTriggerGithubPush{
		Branch:      dcl.StringOrNil(p.Branch),
		Tag:         dcl.StringOrNil(p.Tag),
		InvertRegex: dcl.Bool(p.InvertRegex),
	}
	return obj
}

// ProtoToBuildTriggerBuild converts a BuildTriggerBuild resource from its proto representation.
func ProtoToCloudbuildBuildTriggerBuild(p *cloudbuildpb.CloudbuildBuildTriggerBuild) *cloudbuild.BuildTriggerBuild {
	if p == nil {
		return nil
	}
	obj := &cloudbuild.BuildTriggerBuild{
		QueueTtl:   dcl.StringOrNil(p.QueueTtl),
		LogsBucket: dcl.StringOrNil(p.LogsBucket),
		Timeout:    dcl.StringOrNil(p.Timeout),
		Source:     ProtoToCloudbuildBuildTriggerBuildSource(p.GetSource()),
	}
	for _, r := range p.GetTags() {
		obj.Tags = append(obj.Tags, r)
	}
	for _, r := range p.GetImages() {
		obj.Images = append(obj.Images, r)
	}
	for _, r := range p.GetSecrets() {
		obj.Secrets = append(obj.Secrets, *ProtoToCloudbuildBuildTriggerBuildSecrets(r))
	}
	for _, r := range p.GetSteps() {
		obj.Steps = append(obj.Steps, *ProtoToCloudbuildBuildTriggerBuildSteps(r))
	}
	return obj
}

// ProtoToBuildTriggerBuildSecrets converts a BuildTriggerBuildSecrets resource from its proto representation.
func ProtoToCloudbuildBuildTriggerBuildSecrets(p *cloudbuildpb.CloudbuildBuildTriggerBuildSecrets) *cloudbuild.BuildTriggerBuildSecrets {
	if p == nil {
		return nil
	}
	obj := &cloudbuild.BuildTriggerBuildSecrets{
		KmsKeyName: dcl.StringOrNil(p.KmsKeyName),
	}
	return obj
}

// ProtoToBuildTriggerBuildSteps converts a BuildTriggerBuildSteps resource from its proto representation.
func ProtoToCloudbuildBuildTriggerBuildSteps(p *cloudbuildpb.CloudbuildBuildTriggerBuildSteps) *cloudbuild.BuildTriggerBuildSteps {
	if p == nil {
		return nil
	}
	obj := &cloudbuild.BuildTriggerBuildSteps{
		Name:       dcl.StringOrNil(p.Name),
		Dir:        dcl.StringOrNil(p.Dir),
		Id:         dcl.StringOrNil(p.Id),
		Entrypoint: dcl.StringOrNil(p.Entrypoint),
		Timing:     ProtoToCloudbuildBuildTriggerBuildStepsTiming(p.GetTiming()),
		PullTiming: ProtoToCloudbuildBuildTriggerBuildStepsPullTiming(p.GetPullTiming()),
		Timeout:    dcl.StringOrNil(p.Timeout),
		Status:     ProtoToCloudbuildBuildTriggerBuildStepsStatusEnum(p.GetStatus()),
	}
	for _, r := range p.GetEnv() {
		obj.Env = append(obj.Env, r)
	}
	for _, r := range p.GetArgs() {
		obj.Args = append(obj.Args, r)
	}
	for _, r := range p.GetWaitFor() {
		obj.WaitFor = append(obj.WaitFor, r)
	}
	for _, r := range p.GetSecretEnv() {
		obj.SecretEnv = append(obj.SecretEnv, r)
	}
	for _, r := range p.GetVolumes() {
		obj.Volumes = append(obj.Volumes, *ProtoToCloudbuildBuildTriggerBuildStepsVolumes(r))
	}
	return obj
}

// ProtoToBuildTriggerBuildStepsVolumes converts a BuildTriggerBuildStepsVolumes resource from its proto representation.
func ProtoToCloudbuildBuildTriggerBuildStepsVolumes(p *cloudbuildpb.CloudbuildBuildTriggerBuildStepsVolumes) *cloudbuild.BuildTriggerBuildStepsVolumes {
	if p == nil {
		return nil
	}
	obj := &cloudbuild.BuildTriggerBuildStepsVolumes{
		Name: dcl.StringOrNil(p.Name),
		Path: dcl.StringOrNil(p.Path),
	}
	return obj
}

// ProtoToBuildTriggerBuildStepsTiming converts a BuildTriggerBuildStepsTiming resource from its proto representation.
func ProtoToCloudbuildBuildTriggerBuildStepsTiming(p *cloudbuildpb.CloudbuildBuildTriggerBuildStepsTiming) *cloudbuild.BuildTriggerBuildStepsTiming {
	if p == nil {
		return nil
	}
	obj := &cloudbuild.BuildTriggerBuildStepsTiming{
		StartTime: dcl.StringOrNil(p.StartTime),
		EndTime:   dcl.StringOrNil(p.EndTime),
	}
	return obj
}

// ProtoToBuildTriggerBuildStepsPullTiming converts a BuildTriggerBuildStepsPullTiming resource from its proto representation.
func ProtoToCloudbuildBuildTriggerBuildStepsPullTiming(p *cloudbuildpb.CloudbuildBuildTriggerBuildStepsPullTiming) *cloudbuild.BuildTriggerBuildStepsPullTiming {
	if p == nil {
		return nil
	}
	obj := &cloudbuild.BuildTriggerBuildStepsPullTiming{
		StartTime: dcl.StringOrNil(p.StartTime),
		EndTime:   dcl.StringOrNil(p.EndTime),
	}
	return obj
}

// ProtoToBuildTriggerBuildSource converts a BuildTriggerBuildSource resource from its proto representation.
func ProtoToCloudbuildBuildTriggerBuildSource(p *cloudbuildpb.CloudbuildBuildTriggerBuildSource) *cloudbuild.BuildTriggerBuildSource {
	if p == nil {
		return nil
	}
	obj := &cloudbuild.BuildTriggerBuildSource{
		StorageSource: ProtoToCloudbuildBuildTriggerBuildSourceStorageSource(p.GetStorageSource()),
		RepoSource:    ProtoToCloudbuildBuildTriggerBuildSourceRepoSource(p.GetRepoSource()),
	}
	return obj
}

// ProtoToBuildTriggerBuildSourceStorageSource converts a BuildTriggerBuildSourceStorageSource resource from its proto representation.
func ProtoToCloudbuildBuildTriggerBuildSourceStorageSource(p *cloudbuildpb.CloudbuildBuildTriggerBuildSourceStorageSource) *cloudbuild.BuildTriggerBuildSourceStorageSource {
	if p == nil {
		return nil
	}
	obj := &cloudbuild.BuildTriggerBuildSourceStorageSource{
		Bucket:     dcl.StringOrNil(p.Bucket),
		Object:     dcl.StringOrNil(p.Object),
		Generation: dcl.StringOrNil(p.Generation),
	}
	return obj
}

// ProtoToBuildTriggerBuildSourceRepoSource converts a BuildTriggerBuildSourceRepoSource resource from its proto representation.
func ProtoToCloudbuildBuildTriggerBuildSourceRepoSource(p *cloudbuildpb.CloudbuildBuildTriggerBuildSourceRepoSource) *cloudbuild.BuildTriggerBuildSourceRepoSource {
	if p == nil {
		return nil
	}
	obj := &cloudbuild.BuildTriggerBuildSourceRepoSource{
		ProjectId:   dcl.StringOrNil(p.ProjectId),
		RepoName:    dcl.StringOrNil(p.RepoName),
		BranchName:  dcl.StringOrNil(p.BranchName),
		TagName:     dcl.StringOrNil(p.TagName),
		CommitSha:   dcl.StringOrNil(p.CommitSha),
		Dir:         dcl.StringOrNil(p.Dir),
		InvertRegex: dcl.Bool(p.InvertRegex),
	}
	return obj
}

// ProtoToBuildTrigger converts a BuildTrigger resource from its proto representation.
func ProtoToBuildTrigger(p *cloudbuildpb.CloudbuildBuildTrigger) *cloudbuild.BuildTrigger {
	obj := &cloudbuild.BuildTrigger{
		Name:            dcl.StringOrNil(p.Name),
		Description:     dcl.StringOrNil(p.Description),
		Disabled:        dcl.Bool(p.Disabled),
		Filename:        dcl.StringOrNil(p.Filename),
		TriggerTemplate: ProtoToCloudbuildBuildTriggerTriggerTemplate(p.GetTriggerTemplate()),
		Github:          ProtoToCloudbuildBuildTriggerGithub(p.GetGithub()),
		Project:         dcl.StringOrNil(p.Project),
		Build:           ProtoToCloudbuildBuildTriggerBuild(p.GetBuild()),
		Id:              dcl.StringOrNil(p.Id),
		CreateTime:      dcl.StringOrNil(p.CreateTime),
	}
	for _, r := range p.GetTags() {
		obj.Tags = append(obj.Tags, r)
	}
	for _, r := range p.GetIgnoredFiles() {
		obj.IgnoredFiles = append(obj.IgnoredFiles, r)
	}
	for _, r := range p.GetIncludedFiles() {
		obj.IncludedFiles = append(obj.IncludedFiles, r)
	}
	return obj
}

// BuildTriggerGithubPullRequestCommentControlEnumToProto converts a BuildTriggerGithubPullRequestCommentControlEnum enum to its proto representation.
func CloudbuildBuildTriggerGithubPullRequestCommentControlEnumToProto(e *cloudbuild.BuildTriggerGithubPullRequestCommentControlEnum) cloudbuildpb.CloudbuildBuildTriggerGithubPullRequestCommentControlEnum {
	if e == nil {
		return cloudbuildpb.CloudbuildBuildTriggerGithubPullRequestCommentControlEnum(0)
	}
	if v, ok := cloudbuildpb.CloudbuildBuildTriggerGithubPullRequestCommentControlEnum_value["BuildTriggerGithubPullRequestCommentControlEnum"+string(*e)]; ok {
		return cloudbuildpb.CloudbuildBuildTriggerGithubPullRequestCommentControlEnum(v)
	}
	return cloudbuildpb.CloudbuildBuildTriggerGithubPullRequestCommentControlEnum(0)
}

// BuildTriggerBuildStepsStatusEnumToProto converts a BuildTriggerBuildStepsStatusEnum enum to its proto representation.
func CloudbuildBuildTriggerBuildStepsStatusEnumToProto(e *cloudbuild.BuildTriggerBuildStepsStatusEnum) cloudbuildpb.CloudbuildBuildTriggerBuildStepsStatusEnum {
	if e == nil {
		return cloudbuildpb.CloudbuildBuildTriggerBuildStepsStatusEnum(0)
	}
	if v, ok := cloudbuildpb.CloudbuildBuildTriggerBuildStepsStatusEnum_value["BuildTriggerBuildStepsStatusEnum"+string(*e)]; ok {
		return cloudbuildpb.CloudbuildBuildTriggerBuildStepsStatusEnum(v)
	}
	return cloudbuildpb.CloudbuildBuildTriggerBuildStepsStatusEnum(0)
}

// BuildTriggerTriggerTemplateToProto converts a BuildTriggerTriggerTemplate resource to its proto representation.
func CloudbuildBuildTriggerTriggerTemplateToProto(o *cloudbuild.BuildTriggerTriggerTemplate) *cloudbuildpb.CloudbuildBuildTriggerTriggerTemplate {
	if o == nil {
		return nil
	}
	p := &cloudbuildpb.CloudbuildBuildTriggerTriggerTemplate{
		ProjectId:   dcl.ValueOrEmptyString(o.ProjectId),
		RepoName:    dcl.ValueOrEmptyString(o.RepoName),
		BranchName:  dcl.ValueOrEmptyString(o.BranchName),
		TagName:     dcl.ValueOrEmptyString(o.TagName),
		CommitSha:   dcl.ValueOrEmptyString(o.CommitSha),
		Dir:         dcl.ValueOrEmptyString(o.Dir),
		InvertRegex: dcl.ValueOrEmptyBool(o.InvertRegex),
	}
	return p
}

// BuildTriggerGithubToProto converts a BuildTriggerGithub resource to its proto representation.
func CloudbuildBuildTriggerGithubToProto(o *cloudbuild.BuildTriggerGithub) *cloudbuildpb.CloudbuildBuildTriggerGithub {
	if o == nil {
		return nil
	}
	p := &cloudbuildpb.CloudbuildBuildTriggerGithub{
		Owner:       dcl.ValueOrEmptyString(o.Owner),
		Name:        dcl.ValueOrEmptyString(o.Name),
		PullRequest: CloudbuildBuildTriggerGithubPullRequestToProto(o.PullRequest),
		Push:        CloudbuildBuildTriggerGithubPushToProto(o.Push),
	}
	return p
}

// BuildTriggerGithubPullRequestToProto converts a BuildTriggerGithubPullRequest resource to its proto representation.
func CloudbuildBuildTriggerGithubPullRequestToProto(o *cloudbuild.BuildTriggerGithubPullRequest) *cloudbuildpb.CloudbuildBuildTriggerGithubPullRequest {
	if o == nil {
		return nil
	}
	p := &cloudbuildpb.CloudbuildBuildTriggerGithubPullRequest{
		Branch:         dcl.ValueOrEmptyString(o.Branch),
		CommentControl: CloudbuildBuildTriggerGithubPullRequestCommentControlEnumToProto(o.CommentControl),
		InvertRegex:    dcl.ValueOrEmptyBool(o.InvertRegex),
	}
	return p
}

// BuildTriggerGithubPushToProto converts a BuildTriggerGithubPush resource to its proto representation.
func CloudbuildBuildTriggerGithubPushToProto(o *cloudbuild.BuildTriggerGithubPush) *cloudbuildpb.CloudbuildBuildTriggerGithubPush {
	if o == nil {
		return nil
	}
	p := &cloudbuildpb.CloudbuildBuildTriggerGithubPush{
		Branch:      dcl.ValueOrEmptyString(o.Branch),
		Tag:         dcl.ValueOrEmptyString(o.Tag),
		InvertRegex: dcl.ValueOrEmptyBool(o.InvertRegex),
	}
	return p
}

// BuildTriggerBuildToProto converts a BuildTriggerBuild resource to its proto representation.
func CloudbuildBuildTriggerBuildToProto(o *cloudbuild.BuildTriggerBuild) *cloudbuildpb.CloudbuildBuildTriggerBuild {
	if o == nil {
		return nil
	}
	p := &cloudbuildpb.CloudbuildBuildTriggerBuild{
		QueueTtl:   dcl.ValueOrEmptyString(o.QueueTtl),
		LogsBucket: dcl.ValueOrEmptyString(o.LogsBucket),
		Timeout:    dcl.ValueOrEmptyString(o.Timeout),
		Source:     CloudbuildBuildTriggerBuildSourceToProto(o.Source),
	}
	for _, r := range o.Tags {
		p.Tags = append(p.Tags, r)
	}
	for _, r := range o.Images {
		p.Images = append(p.Images, r)
	}
	p.Substitutions = make(map[string]string)
	for k, r := range o.Substitutions {
		p.Substitutions[k] = r
	}
	for _, r := range o.Secrets {
		p.Secrets = append(p.Secrets, CloudbuildBuildTriggerBuildSecretsToProto(&r))
	}
	for _, r := range o.Steps {
		p.Steps = append(p.Steps, CloudbuildBuildTriggerBuildStepsToProto(&r))
	}
	return p
}

// BuildTriggerBuildSecretsToProto converts a BuildTriggerBuildSecrets resource to its proto representation.
func CloudbuildBuildTriggerBuildSecretsToProto(o *cloudbuild.BuildTriggerBuildSecrets) *cloudbuildpb.CloudbuildBuildTriggerBuildSecrets {
	if o == nil {
		return nil
	}
	p := &cloudbuildpb.CloudbuildBuildTriggerBuildSecrets{
		KmsKeyName: dcl.ValueOrEmptyString(o.KmsKeyName),
	}
	p.SecretEnv = make(map[string]string)
	for k, r := range o.SecretEnv {
		p.SecretEnv[k] = r
	}
	return p
}

// BuildTriggerBuildStepsToProto converts a BuildTriggerBuildSteps resource to its proto representation.
func CloudbuildBuildTriggerBuildStepsToProto(o *cloudbuild.BuildTriggerBuildSteps) *cloudbuildpb.CloudbuildBuildTriggerBuildSteps {
	if o == nil {
		return nil
	}
	p := &cloudbuildpb.CloudbuildBuildTriggerBuildSteps{
		Name:       dcl.ValueOrEmptyString(o.Name),
		Dir:        dcl.ValueOrEmptyString(o.Dir),
		Id:         dcl.ValueOrEmptyString(o.Id),
		Entrypoint: dcl.ValueOrEmptyString(o.Entrypoint),
		Timing:     CloudbuildBuildTriggerBuildStepsTimingToProto(o.Timing),
		PullTiming: CloudbuildBuildTriggerBuildStepsPullTimingToProto(o.PullTiming),
		Timeout:    dcl.ValueOrEmptyString(o.Timeout),
		Status:     CloudbuildBuildTriggerBuildStepsStatusEnumToProto(o.Status),
	}
	for _, r := range o.Env {
		p.Env = append(p.Env, r)
	}
	for _, r := range o.Args {
		p.Args = append(p.Args, r)
	}
	for _, r := range o.WaitFor {
		p.WaitFor = append(p.WaitFor, r)
	}
	for _, r := range o.SecretEnv {
		p.SecretEnv = append(p.SecretEnv, r)
	}
	for _, r := range o.Volumes {
		p.Volumes = append(p.Volumes, CloudbuildBuildTriggerBuildStepsVolumesToProto(&r))
	}
	return p
}

// BuildTriggerBuildStepsVolumesToProto converts a BuildTriggerBuildStepsVolumes resource to its proto representation.
func CloudbuildBuildTriggerBuildStepsVolumesToProto(o *cloudbuild.BuildTriggerBuildStepsVolumes) *cloudbuildpb.CloudbuildBuildTriggerBuildStepsVolumes {
	if o == nil {
		return nil
	}
	p := &cloudbuildpb.CloudbuildBuildTriggerBuildStepsVolumes{
		Name: dcl.ValueOrEmptyString(o.Name),
		Path: dcl.ValueOrEmptyString(o.Path),
	}
	return p
}

// BuildTriggerBuildStepsTimingToProto converts a BuildTriggerBuildStepsTiming resource to its proto representation.
func CloudbuildBuildTriggerBuildStepsTimingToProto(o *cloudbuild.BuildTriggerBuildStepsTiming) *cloudbuildpb.CloudbuildBuildTriggerBuildStepsTiming {
	if o == nil {
		return nil
	}
	p := &cloudbuildpb.CloudbuildBuildTriggerBuildStepsTiming{
		StartTime: dcl.ValueOrEmptyString(o.StartTime),
		EndTime:   dcl.ValueOrEmptyString(o.EndTime),
	}
	return p
}

// BuildTriggerBuildStepsPullTimingToProto converts a BuildTriggerBuildStepsPullTiming resource to its proto representation.
func CloudbuildBuildTriggerBuildStepsPullTimingToProto(o *cloudbuild.BuildTriggerBuildStepsPullTiming) *cloudbuildpb.CloudbuildBuildTriggerBuildStepsPullTiming {
	if o == nil {
		return nil
	}
	p := &cloudbuildpb.CloudbuildBuildTriggerBuildStepsPullTiming{
		StartTime: dcl.ValueOrEmptyString(o.StartTime),
		EndTime:   dcl.ValueOrEmptyString(o.EndTime),
	}
	return p
}

// BuildTriggerBuildSourceToProto converts a BuildTriggerBuildSource resource to its proto representation.
func CloudbuildBuildTriggerBuildSourceToProto(o *cloudbuild.BuildTriggerBuildSource) *cloudbuildpb.CloudbuildBuildTriggerBuildSource {
	if o == nil {
		return nil
	}
	p := &cloudbuildpb.CloudbuildBuildTriggerBuildSource{
		StorageSource: CloudbuildBuildTriggerBuildSourceStorageSourceToProto(o.StorageSource),
		RepoSource:    CloudbuildBuildTriggerBuildSourceRepoSourceToProto(o.RepoSource),
	}
	return p
}

// BuildTriggerBuildSourceStorageSourceToProto converts a BuildTriggerBuildSourceStorageSource resource to its proto representation.
func CloudbuildBuildTriggerBuildSourceStorageSourceToProto(o *cloudbuild.BuildTriggerBuildSourceStorageSource) *cloudbuildpb.CloudbuildBuildTriggerBuildSourceStorageSource {
	if o == nil {
		return nil
	}
	p := &cloudbuildpb.CloudbuildBuildTriggerBuildSourceStorageSource{
		Bucket:     dcl.ValueOrEmptyString(o.Bucket),
		Object:     dcl.ValueOrEmptyString(o.Object),
		Generation: dcl.ValueOrEmptyString(o.Generation),
	}
	return p
}

// BuildTriggerBuildSourceRepoSourceToProto converts a BuildTriggerBuildSourceRepoSource resource to its proto representation.
func CloudbuildBuildTriggerBuildSourceRepoSourceToProto(o *cloudbuild.BuildTriggerBuildSourceRepoSource) *cloudbuildpb.CloudbuildBuildTriggerBuildSourceRepoSource {
	if o == nil {
		return nil
	}
	p := &cloudbuildpb.CloudbuildBuildTriggerBuildSourceRepoSource{
		ProjectId:   dcl.ValueOrEmptyString(o.ProjectId),
		RepoName:    dcl.ValueOrEmptyString(o.RepoName),
		BranchName:  dcl.ValueOrEmptyString(o.BranchName),
		TagName:     dcl.ValueOrEmptyString(o.TagName),
		CommitSha:   dcl.ValueOrEmptyString(o.CommitSha),
		Dir:         dcl.ValueOrEmptyString(o.Dir),
		InvertRegex: dcl.ValueOrEmptyBool(o.InvertRegex),
	}
	p.Substitutions = make(map[string]string)
	for k, r := range o.Substitutions {
		p.Substitutions[k] = r
	}
	return p
}

// BuildTriggerToProto converts a BuildTrigger resource to its proto representation.
func BuildTriggerToProto(resource *cloudbuild.BuildTrigger) *cloudbuildpb.CloudbuildBuildTrigger {
	p := &cloudbuildpb.CloudbuildBuildTrigger{
		Name:            dcl.ValueOrEmptyString(resource.Name),
		Description:     dcl.ValueOrEmptyString(resource.Description),
		Disabled:        dcl.ValueOrEmptyBool(resource.Disabled),
		Filename:        dcl.ValueOrEmptyString(resource.Filename),
		TriggerTemplate: CloudbuildBuildTriggerTriggerTemplateToProto(resource.TriggerTemplate),
		Github:          CloudbuildBuildTriggerGithubToProto(resource.Github),
		Project:         dcl.ValueOrEmptyString(resource.Project),
		Build:           CloudbuildBuildTriggerBuildToProto(resource.Build),
		Id:              dcl.ValueOrEmptyString(resource.Id),
		CreateTime:      dcl.ValueOrEmptyString(resource.CreateTime),
	}
	for _, r := range resource.Tags {
		p.Tags = append(p.Tags, r)
	}
	for _, r := range resource.IgnoredFiles {
		p.IgnoredFiles = append(p.IgnoredFiles, r)
	}
	for _, r := range resource.IncludedFiles {
		p.IncludedFiles = append(p.IncludedFiles, r)
	}

	return p
}

// ApplyBuildTrigger handles the gRPC request by passing it to the underlying BuildTrigger Apply() method.
func (s *BuildTriggerServer) applyBuildTrigger(ctx context.Context, c *cloudbuild.Client, request *cloudbuildpb.ApplyCloudbuildBuildTriggerRequest) (*cloudbuildpb.CloudbuildBuildTrigger, error) {
	p := ProtoToBuildTrigger(request.GetResource())
	res, err := c.ApplyBuildTrigger(ctx, p)
	if err != nil {
		return nil, err
	}
	r := BuildTriggerToProto(res)
	return r, nil
}

// ApplyBuildTrigger handles the gRPC request by passing it to the underlying BuildTrigger Apply() method.
func (s *BuildTriggerServer) ApplyCloudbuildBuildTrigger(ctx context.Context, request *cloudbuildpb.ApplyCloudbuildBuildTriggerRequest) (*cloudbuildpb.CloudbuildBuildTrigger, error) {
	cl, err := createConfigBuildTrigger(ctx, request.ServiceAccountFile)
	if err != nil {
		return nil, err
	}
	return s.applyBuildTrigger(ctx, cl, request)
}

// DeleteBuildTrigger handles the gRPC request by passing it to the underlying BuildTrigger Delete() method.
func (s *BuildTriggerServer) DeleteCloudbuildBuildTrigger(ctx context.Context, request *cloudbuildpb.DeleteCloudbuildBuildTriggerRequest) (*emptypb.Empty, error) {

	cl, err := createConfigBuildTrigger(ctx, request.ServiceAccountFile)
	if err != nil {
		return nil, err
	}
	return &emptypb.Empty{}, cl.DeleteBuildTrigger(ctx, ProtoToBuildTrigger(request.GetResource()))

}

// ListCloudbuildBuildTrigger handles the gRPC request by passing it to the underlying BuildTriggerList() method.
func (s *BuildTriggerServer) ListCloudbuildBuildTrigger(ctx context.Context, request *cloudbuildpb.ListCloudbuildBuildTriggerRequest) (*cloudbuildpb.ListCloudbuildBuildTriggerResponse, error) {
	cl, err := createConfigBuildTrigger(ctx, request.ServiceAccountFile)
	if err != nil {
		return nil, err
	}

	resources, err := cl.ListBuildTrigger(ctx, request.Project)
	if err != nil {
		return nil, err
	}
	var protos []*cloudbuildpb.CloudbuildBuildTrigger
	for _, r := range resources.Items {
		rp := BuildTriggerToProto(r)
		protos = append(protos, rp)
	}
	return &cloudbuildpb.ListCloudbuildBuildTriggerResponse{Items: protos}, nil
}

func createConfigBuildTrigger(ctx context.Context, service_account_file string) (*cloudbuild.Client, error) {

	conf := dcl.NewConfig(dcl.WithUserAgent("dcl-test"), dcl.WithCredentialsFile(service_account_file))
	return cloudbuild.NewClient(conf), nil
}


text:
/***************************************************************************/
// Copyright 2013-2019 Riley White
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/***************************************************************************/

using NUnit.Framework;
using System;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace Cilador.Fody.Tests.Common
{
    internal static class CommonExtensions
    {
        public static XElement ToXElement(this object @object)
        {
            Contract.Requires(@object != null);
            Contract.Requires(@object.GetType().IsSerializable);

            var objectType = @object.GetType();
            using (var memoryStream = new MemoryStream())
            {
                var xmlSerializer = new XmlSerializer(objectType);
                xmlSerializer.Serialize(memoryStream, @object);
                memoryStream.Position = 0;
                var xElement = XElement.Load(memoryStream);
                return xElement;
            }
        }

        public static void ValidateMemberCountsAre(
            this Type type,
            int expectedConstructorCount,
            int expectedMethodCount,
            int expectedFieldCount,
            int expectedPropertyCount,
            int expectedEventCount,
            int expectedNestedTypeCount)
        {
            Contract.Requires(type != null);
            type.ValidateConstructorCountIs(expectedConstructorCount);
            type.ValidateMethodCountIs(expectedMethodCount);
            type.ValidateFieldCountIs(expectedFieldCount);
            type.ValidatePropertyCountIs(expectedPropertyCount);
            type.ValidateEventCountIs(expectedEventCount);
            type.ValidateNestedTypeCountIs(expectedNestedTypeCount);
        }

        public static void ValidateFieldCountIs(this Type type, int expectedCount)
        {
            Contract.Requires(type != null);
            var actualCount = type.GetFields(TestContent.BindingFlagsForWeavedMembers).Length;
            Assert.That(
                expectedCount == actualCount,
                $"Expected {expectedCount} fields but found {actualCount} in type [{type.FullName}]");
        }

        public static void ValidatePropertyCountIs(this Type type, int expectedCount)
        {
            Contract.Requires(type != null);
            var actualCount = type.GetProperties(TestContent.BindingFlagsForWeavedMembers).Length;
            Assert.That(
                expectedCount == actualCount,
                $"Expected {expectedCount} properties but found {actualCount} in type [{type.FullName}]");
        }

        public static void ValidateConstructorCountIs(this Type type, int expectedCount)
        {
            Contract.Requires(type != null);
            var actualCount = type.GetConstructors(TestContent.BindingFlagsForWeavedMembers).Length;
            Assert.That(
                expectedCount == actualCount,
                $"Expected {expectedCount} constructors but found {actualCount} in type [{type.FullName}]");
        }

        public static void ValidateMethodCountIs(this Type type, int expectedCount)
        {
            Contract.Requires(type != null);
            var actualCount = type.GetMethods(TestContent.BindingFlagsForWeavedMembers).Length;
            Assert.That(
                expectedCount == actualCount,
                $"Expected {expectedCount} non-constructor methods but found {actualCount} in type [{type.FullName}]");
        }

        public static void ValidateEventCountIs(this Type type, int expectedCount)
        {
            Contract.Requires(type != null);
            var actualCount = type.GetEvents(TestContent.BindingFlagsForWeavedMembers).Length;
            Assert.That(
                expectedCount == actualCount,
                $"Expected {expectedCount} events but found {actualCount} in type [{type.FullName}]");
        }

        public static void ValidateNestedTypeCountIs(this Type type, int expectedCount)
        {
            Contract.Requires(type != null);
            var actualCount = type.GetNestedTypes(TestContent.BindingFlagsForWeavedMembers).Length;
            Assert.That(
                expectedCount == actualCount,
                $"Expected {expectedCount} nested types but found {actualCount} in type [{type.FullName}]");
        }

        public static string GetShortAssemblyQualifiedName(this Type type)
        {
            Contract.Requires(type != null);
            return $"{type.FullName}, {type.Assembly.GetName().Name}";
        }

        public static void ValidateMemberSources(this Type targetType, Type sourceType)
        {
            Contract.Requires(targetType != null);
            Contract.Requires(sourceType != null);
            Contract.Requires(targetType != sourceType);

            var rootTargetAndSourceFullNames = Tuple.Create(targetType.FullName, sourceType.FullName);

            foreach (var targetField in targetType.GetFields(TestContent.BindingFlagsForWeavedMembers))
            {
                targetField.ValidateSourceEqual(sourceType.GetField(targetField.Name, TestContent.BindingFlagsForWeavedMembers), rootTargetAndSourceFullNames);
            }

            foreach (var targetMethod in targetType.GetMethods(TestContent.BindingFlagsForWeavedMembers))
            {
                // can't match by parameter types because some of the generic type arguments may have been redirected during mixing
                targetMethod.ValidateSourceEqual(
                    sourceType.GetMethods(TestContent.BindingFlagsForWeavedMembers)
                        .SingleOrDefault(method => targetMethod.IsSourceNameEqual(method, rootTargetAndSourceFullNames)),
                    rootTargetAndSourceFullNames);
            }

            foreach (var targetProperty in targetType.GetProperties(TestContent.BindingFlagsForWeavedMembers))
            {
                targetProperty.ValidateSourceEqual(sourceType.GetProperty(
                    targetProperty.Name,
                    TestContent.BindingFlagsForWeavedMembers,
                    null,
                    targetProperty.PropertyType,
                    targetProperty.GetIndexParameters().Select(each => each.ParameterType).ToArray(),
                    null), rootTargetAndSourceFullNames);
            }

            foreach (var targetEvent in targetType.GetEvents(TestContent.BindingFlagsForWeavedMembers))
            {
                targetEvent.ValidateSourceEqual(sourceType.GetEvent(
                    targetEvent.Name,
                    TestContent.BindingFlagsForWeavedMembers), rootTargetAndSourceFullNames);
            }

            foreach (var targetNestedType in targetType.GetNestedTypes(TestContent.BindingFlagsForWeavedMembers))
            {
                targetNestedType.ValidateSourceEqual(sourceType.GetNestedType(targetNestedType.Name, TestContent.BindingFlagsForWeavedMembers), rootTargetAndSourceFullNames);
            }
        }

        private static void ValidateSourceEqual(this FieldInfo targetField, FieldInfo sourceField, Tuple<string, string> rootTargetAndSourceFullNames)
        {
            Contract.Requires(targetField != null);
            Contract.Requires(rootTargetAndSourceFullNames != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item1 != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item2 != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item1 != rootTargetAndSourceFullNames.Item2);

            Assert.That(sourceField != null, "Could not find source type");
            Assert.That(sourceField != targetField);
            Assert.That(sourceField.Attributes == targetField.Attributes);
            Assert.That(sourceField.DeclaringType != targetField.DeclaringType);
            Assert.That(sourceField.IsAssembly == targetField.IsAssembly);
            Assert.That(sourceField.IsFamily == targetField.IsFamily);
            Assert.That(sourceField.IsFamilyAndAssembly == targetField.IsFamilyAndAssembly);
            Assert.That(sourceField.IsFamilyOrAssembly == targetField.IsFamilyOrAssembly);
            Assert.That(sourceField.IsInitOnly == targetField.IsInitOnly);
            Assert.That(sourceField.IsLiteral == targetField.IsLiteral);
            Assert.That(sourceField.IsNotSerialized == targetField.IsNotSerialized);
            Assert.That(sourceField.IsPinvokeImpl == targetField.IsPinvokeImpl);
            Assert.That(sourceField.IsPrivate == targetField.IsPrivate);
            Assert.That(sourceField.IsPublic == targetField.IsPublic);
            Assert.That(sourceField.IsSecurityCritical == targetField.IsSecurityCritical);
            Assert.That(sourceField.IsSecuritySafeCritical == targetField.IsSecuritySafeCritical);
            Assert.That(sourceField.IsSecurityTransparent == targetField.IsSecurityTransparent);
            Assert.That(sourceField.IsSpecialName == targetField.IsSpecialName);
            Assert.That(sourceField.IsStatic == targetField.IsStatic);
            Assert.That(sourceField.MemberType == targetField.MemberType);
            Assert.That(sourceField.Name == targetField.Name);

            targetField.FieldType.ValidateSourceNameEqual(sourceField.FieldType, rootTargetAndSourceFullNames);

            if (sourceField.IsLiteral)
            {
                var sourceValue = sourceField.GetRawConstantValue();
                var targetValue = targetField.GetRawConstantValue();

                if (sourceValue == null) { Assert.That(targetValue == null); }
                else { Assert.That(sourceValue.Equals(targetValue)); }
            }

            Attribute.GetCustomAttributes(targetField, false).ValidateSourceEqual(Attribute.GetCustomAttributes(sourceField, false), rootTargetAndSourceFullNames);
        }

        private static void ValidateSourceEqual(this MethodInfo targetMethod, MethodInfo sourceMethod, Tuple<string, string> rootTargetAndSourceFullNames)
        {
            Contract.Requires(targetMethod != null);
            Contract.Requires(rootTargetAndSourceFullNames != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item1 != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item2 != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item1 != rootTargetAndSourceFullNames.Item2);

            Assert.That(sourceMethod != null, "Could not find source method");
            Assert.That(sourceMethod != targetMethod);
            Assert.That(sourceMethod.Attributes == targetMethod.Attributes);
            Assert.That(sourceMethod.CallingConvention == targetMethod.CallingConvention);
            Assert.That(sourceMethod.ContainsGenericParameters == targetMethod.ContainsGenericParameters);
            Assert.That(sourceMethod.DeclaringType != targetMethod.DeclaringType);
            Assert.That(sourceMethod.IsAbstract == targetMethod.IsAbstract);
            Assert.That(sourceMethod.IsAssembly == targetMethod.IsAssembly);
            Assert.That(sourceMethod.IsConstructor == targetMethod.IsConstructor);
            Assert.That(sourceMethod.IsFamily == targetMethod.IsFamily);
            Assert.That(sourceMethod.IsFamilyAndAssembly == targetMethod.IsFamilyAndAssembly);
            Assert.That(sourceMethod.IsFamilyOrAssembly == targetMethod.IsFamilyOrAssembly);
            Assert.That(sourceMethod.IsFinal == targetMethod.IsFinal);
            Assert.That(sourceMethod.IsGenericMethod == targetMethod.IsGenericMethod);
            Assert.That(sourceMethod.IsGenericMethodDefinition == targetMethod.IsGenericMethodDefinition);
            Assert.That(sourceMethod.IsHideBySig == targetMethod.IsHideBySig);
            Assert.That(sourceMethod.IsPrivate == targetMethod.IsPrivate);
            Assert.That(sourceMethod.IsPublic == targetMethod.IsPublic);
            Assert.That(sourceMethod.IsSecurityCritical == targetMethod.IsSecurityCritical);
            Assert.That(sourceMethod.IsSecuritySafeCritical == targetMethod.IsSecuritySafeCritical);
            Assert.That(sourceMethod.IsSecurityTransparent == targetMethod.IsSecurityTransparent);
            Assert.That(sourceMethod.IsSpecialName == targetMethod.IsSpecialName);
            Assert.That(sourceMethod.IsStatic == targetMethod.IsStatic);
            Assert.That(sourceMethod.IsVirtual == targetMethod.IsVirtual);
            Assert.That(sourceMethod.MemberType == targetMethod.MemberType);
            Assert.That(sourceMethod.MethodImplementationFlags == targetMethod.MethodImplementationFlags);
            Assert.That(sourceMethod.Name == targetMethod.Name);

            targetMethod.ReturnType.ValidateSourceNameEqual(sourceMethod.ReturnType, rootTargetAndSourceFullNames);

            targetMethod.ReturnParameter.ValidateSourceEqual(sourceMethod.ReturnParameter, rootTargetAndSourceFullNames);
            targetMethod.GetParameters().ValidateSourceEqual(sourceMethod.GetParameters(), rootTargetAndSourceFullNames);
            Attribute.GetCustomAttributes(targetMethod).ValidateSourceEqual(Attribute.GetCustomAttributes(sourceMethod), rootTargetAndSourceFullNames);
        }

        private static void ValidateSourceEqual(this PropertyInfo targetProperty, PropertyInfo sourceProperty, Tuple<string, string> rootTargetAndSourceFullNames)
        {
            Contract.Requires(targetProperty != null);
            Contract.Requires(rootTargetAndSourceFullNames != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item1 != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item2 != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item1 != rootTargetAndSourceFullNames.Item2);

            Assert.That(sourceProperty != null, "Could not find source property");
            Assert.That(sourceProperty != targetProperty);
            Assert.That(sourceProperty.Attributes == targetProperty.Attributes);
            Assert.That(sourceProperty.CanRead == targetProperty.CanRead);
            Assert.That(sourceProperty.CanWrite == targetProperty.CanWrite);
            Assert.That(sourceProperty.DeclaringType != targetProperty.DeclaringType);
            Assert.That(sourceProperty.IsSpecialName == targetProperty.IsSpecialName);
            Assert.That(sourceProperty.MemberType == targetProperty.MemberType);
            Assert.That(sourceProperty.Name == targetProperty.Name);

            targetProperty.PropertyType.ValidateSourceNameEqual(sourceProperty.PropertyType, rootTargetAndSourceFullNames); // won't work for mixed types

            if (sourceProperty.GetMethod == null) { Assert.That(targetProperty.GetMethod == null); }
            else { targetProperty.GetMethod.ValidateSourceNameEqual(sourceProperty.GetMethod, rootTargetAndSourceFullNames); }

            if (sourceProperty.SetMethod == null) { Assert.That(targetProperty.SetMethod == null); }
            else { targetProperty.SetMethod.ValidateSourceNameEqual(sourceProperty.SetMethod, rootTargetAndSourceFullNames); }

            Attribute.GetCustomAttributes(targetProperty).ValidateSourceEqual(Attribute.GetCustomAttributes(sourceProperty), rootTargetAndSourceFullNames);

            targetProperty.GetIndexParameters().ValidateSourceEqual(sourceProperty.GetIndexParameters(), rootTargetAndSourceFullNames);
        }

        private static void ValidateSourceEqual(this EventInfo targetEvent, EventInfo sourceEvent, Tuple<string, string> rootTargetAndSourceFullNames)
        {
            Contract.Requires(targetEvent != null);
            Contract.Requires(rootTargetAndSourceFullNames != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item1 != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item2 != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item1 != rootTargetAndSourceFullNames.Item2);

            Assert.That(sourceEvent != null, "Could not find source event");
            Assert.That(sourceEvent != targetEvent);
            Assert.That(sourceEvent.Attributes == targetEvent.Attributes);
            Assert.That(sourceEvent.DeclaringType != targetEvent.DeclaringType);
            Assert.That(sourceEvent.IsMulticast == targetEvent.IsMulticast);
            Assert.That(sourceEvent.IsSpecialName == targetEvent.IsSpecialName);
            Assert.That(sourceEvent.MemberType == targetEvent.MemberType);
            Assert.That(sourceEvent.Name == targetEvent.Name);

            targetEvent.EventHandlerType.ValidateSourceNameEqual(sourceEvent.EventHandlerType, rootTargetAndSourceFullNames);

            // only check names here; full check should be done separately for the methods
            if (sourceEvent.AddMethod == null) { Assert.That(targetEvent.AddMethod == null); }
            else { targetEvent.AddMethod.ValidateSourceNameEqual(sourceEvent.AddMethod, rootTargetAndSourceFullNames); }

            if (sourceEvent.RemoveMethod == null) { Assert.That(targetEvent.RemoveMethod == null); }
            else { targetEvent.RemoveMethod.ValidateSourceNameEqual(sourceEvent.RemoveMethod, rootTargetAndSourceFullNames); }

            if (sourceEvent.RaiseMethod == null) { Assert.That(targetEvent.RaiseMethod == null); }
            else { targetEvent.RaiseMethod.ValidateSourceNameEqual(sourceEvent.RaiseMethod, rootTargetAndSourceFullNames); }

            Attribute.GetCustomAttributes(targetEvent).ValidateSourceEqual(Attribute.GetCustomAttributes(sourceEvent), rootTargetAndSourceFullNames);
        }

        private static void ValidateSourceEqual(this Type targetType, Type sourceType, Tuple<string, string> rootTargetAndSourceFullNames)
        {
            Contract.Requires(targetType != null);
            Contract.Requires(rootTargetAndSourceFullNames != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item1 != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item2 != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item1 != rootTargetAndSourceFullNames.Item2);

            Assert.That(sourceType != null, "Could not find source type");
            Assert.That(sourceType != targetType);
            Assert.That(sourceType.Attributes == targetType.Attributes);
            Assert.That(sourceType.ContainsGenericParameters == targetType.ContainsGenericParameters);
            Assert.That(sourceType.DeclaringType != targetType.DeclaringType);
            Assert.That(sourceType.GUID != targetType.GUID);
            Assert.That(sourceType.HasElementType == targetType.HasElementType);
            Assert.That(sourceType.IsAbstract == targetType.IsAbstract);
            Assert.That(sourceType.IsAnsiClass == targetType.IsAnsiClass);
            Assert.That(sourceType.IsArray == targetType.IsArray);
            Assert.That(sourceType.IsAutoClass == targetType.IsAutoClass);
            Assert.That(sourceType.IsAutoLayout == targetType.IsAutoLayout);
            Assert.That(sourceType.IsByRef == targetType.IsByRef);
            Assert.That(sourceType.IsClass == targetType.IsClass);
            Assert.That(sourceType.IsCOMObject == targetType.IsCOMObject);
            Assert.That(sourceType.IsConstructedGenericType == targetType.IsConstructedGenericType);
            Assert.That(sourceType.IsContextful == targetType.IsContextful);
            Assert.That(sourceType.IsEnum == targetType.IsEnum);
            Assert.That(sourceType.IsExplicitLayout == targetType.IsExplicitLayout);
            Assert.That(sourceType.IsGenericType == targetType.IsGenericType);
            Assert.That(sourceType.IsGenericTypeDefinition == targetType.IsGenericTypeDefinition);
            Assert.That(sourceType.IsImport == targetType.IsImport);
            Assert.That(sourceType.IsInterface == targetType.IsInterface);
            Assert.That(sourceType.IsLayoutSequential == targetType.IsLayoutSequential);
            Assert.That(sourceType.IsMarshalByRef == targetType.IsMarshalByRef);
            Assert.That(sourceType.IsNested == targetType.IsNested);
            Assert.That(sourceType.IsNestedAssembly == targetType.IsNestedAssembly);
            Assert.That(sourceType.IsNestedFamANDAssem == targetType.IsNestedFamANDAssem);
            Assert.That(sourceType.IsNestedFamily == targetType.IsNestedFamily);
            Assert.That(sourceType.IsNestedFamORAssem == targetType.IsNestedFamORAssem);
            Assert.That(sourceType.IsNestedPrivate == targetType.IsNestedPrivate);
            Assert.That(sourceType.IsNestedPublic == targetType.IsNestedPublic);
            Assert.That(sourceType.IsNotPublic == targetType.IsNotPublic);
            Assert.That(sourceType.IsPointer == targetType.IsPointer);
            Assert.That(sourceType.IsPrimitive == targetType.IsPrimitive);
            Assert.That(sourceType.IsPublic == targetType.IsPublic);
            Assert.That(sourceType.IsSealed == targetType.IsSealed);
            Assert.That(sourceType.IsSecurityCritical == targetType.IsSecurityCritical);
            Assert.That(sourceType.IsSecuritySafeCritical == targetType.IsSecuritySafeCritical);
            Assert.That(sourceType.IsSecurityTransparent == targetType.IsSecurityTransparent);
            Assert.That(sourceType.IsSerializable == targetType.IsSerializable);
            Assert.That(sourceType.IsSpecialName == targetType.IsSpecialName);
            Assert.That(sourceType.IsUnicodeClass == targetType.IsUnicodeClass);
            Assert.That(sourceType.IsValueType == targetType.IsValueType);
            Assert.That(sourceType.IsVisible == targetType.IsVisible);
            Assert.That(sourceType.MemberType == targetType.MemberType);
            Assert.That(sourceType.Name == targetType.Name);
            Assert.That(sourceType.UnderlyingSystemType != targetType.UnderlyingSystemType);

            if (sourceType.BaseType == null) { Assert.That(targetType.BaseType == null); }
            else { targetType.BaseType.ValidateSourceNameEqual(sourceType.BaseType, rootTargetAndSourceFullNames); }

            Assert.That(targetType.IsGenericParameter == sourceType.IsGenericParameter);

            if (sourceType.StructLayoutAttribute == null) { Assert.That(targetType.StructLayoutAttribute == null); }
            else { Assert.That(sourceType.StructLayoutAttribute.Match(targetType.StructLayoutAttribute)); }

            Assert.That(targetType.GenericTypeArguments.Length == sourceType.GenericTypeArguments.Length);
            for (int i = 0; i < targetType.GenericTypeArguments.Length && i < sourceType.GenericTypeArguments.Length; i++)
            {
                targetType.GenericTypeArguments[i].ValidateSourceNameEqual(sourceType.GenericTypeArguments[i], rootTargetAndSourceFullNames);
            }

            targetType.ValidateMemberCountsAre(
                sourceType.GetConstructors(TestContent.BindingFlagsForWeavedMembers).Length,
                sourceType.GetMethods(TestContent.BindingFlagsForWeavedMembers).Length,
                sourceType.GetFields(TestContent.BindingFlagsForWeavedMembers).Length,
                sourceType.GetProperties(TestContent.BindingFlagsForWeavedMembers).Length,
                sourceType.GetEvents(TestContent.BindingFlagsForWeavedMembers).Length,
                sourceType.GetNestedTypes(TestContent.BindingFlagsForWeavedMembers).Length);

            Attribute.GetCustomAttributes(targetType).ValidateSourceEqual(Attribute.GetCustomAttributes(sourceType), rootTargetAndSourceFullNames);
        }

        private static void ValidateSourceEqual(this ParameterInfo[] targetParameters, ParameterInfo[] sourceParameters, Tuple<string, string> rootTargetAndSourceFullNames)
        {
            Contract.Requires(targetParameters != null);
            Contract.Requires(rootTargetAndSourceFullNames != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item1 != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item2 != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item1 != rootTargetAndSourceFullNames.Item2);

            Assert.That(sourceParameters != null, "Could not find source parameters");
            Assert.That(sourceParameters != targetParameters);
            Assert.That(sourceParameters.Length == targetParameters.Length);

            for (int i = 0; i < sourceParameters.Length && i < targetParameters.Length; i++)
            {
                targetParameters[i].ValidateSourceEqual(sourceParameters[i], rootTargetAndSourceFullNames);
            }
        }

        private static void ValidateSourceEqual(this ParameterInfo targetParameter, ParameterInfo sourceParameter, Tuple<string, string> rootTargetAndSourceFullNames)
        {
            Contract.Requires(targetParameter != null);
            Contract.Requires(rootTargetAndSourceFullNames != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item1 != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item2 != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item1 != rootTargetAndSourceFullNames.Item2);

            Assert.That(sourceParameter != null, "Could not find source parameter");
            Assert.That(sourceParameter != targetParameter);
            Assert.That(sourceParameter.Attributes == targetParameter.Attributes);

            if (sourceParameter.DefaultValue == null) { Assert.That(targetParameter.DefaultValue == null); }
            else { Assert.That(sourceParameter.DefaultValue.Equals(targetParameter.DefaultValue)); }

            Assert.That(sourceParameter.HasDefaultValue == targetParameter.HasDefaultValue);
            Assert.That(sourceParameter.IsIn == targetParameter.IsIn);
            Assert.That(sourceParameter.IsLcid == targetParameter.IsLcid);
            Assert.That(sourceParameter.IsOptional == targetParameter.IsOptional);
            Assert.That(sourceParameter.IsOut == targetParameter.IsOut);
            Assert.That(sourceParameter.IsRetval == targetParameter.IsRetval);
            Assert.That(sourceParameter.Member != targetParameter.Member);
            Assert.That(sourceParameter.Name == targetParameter.Name);
            Assert.That(sourceParameter.Position == targetParameter.Position);

            targetParameter.ParameterType.ValidateSourceNameEqual(sourceParameter.ParameterType, rootTargetAndSourceFullNames);

            if (sourceParameter.RawDefaultValue == null) { Assert.That(targetParameter.RawDefaultValue == null); }
            else { Assert.That(sourceParameter.RawDefaultValue.Equals(targetParameter.RawDefaultValue)); }

            Attribute.GetCustomAttributes(targetParameter).ValidateSourceEqual(Attribute.GetCustomAttributes(sourceParameter), rootTargetAndSourceFullNames);
        }

        private static void ValidateSourceEqual(this Attribute[] targetAttributes, Attribute[] sourceAttributes, Tuple<string, string> rootTargetAndSourceFullNames)
        {
            Contract.Requires(targetAttributes != null);
            Contract.Requires(rootTargetAndSourceFullNames != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item1 != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item2 != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item1 != rootTargetAndSourceFullNames.Item2);

            Assert.That(sourceAttributes != null, "Could not find source attributes");
            Assert.That(sourceAttributes != targetAttributes);
            Assert.That(sourceAttributes.Length == targetAttributes.Length);

            var sourceAttributeList = sourceAttributes.ToList();
            var targetAttributeList = targetAttributes.ToList();

            Assert.That(sourceAttributeList.Count == targetAttributeList.Count);

            if (sourceAttributeList.Count == 0) { return; }

            var attributeSorter = new Comparison<Attribute>(
                (left, right) =>
                {
                    var comparison = left.GetType().MetadataToken.CompareTo(right.GetType().MetadataToken);
                    if (comparison != 0 || left.Match(right)) { return comparison; }

                    // same type, and non-matching instances
                    // don't really care what "less than" means, just picking something consistent
                    return string.Compare(left.ToXElement().ToString(), right.ToXElement().ToString(), StringComparison.Ordinal);
                });

            sourceAttributeList.Sort(attributeSorter);
            targetAttributeList.Sort(attributeSorter);

            for (var i = 0; i < sourceAttributeList.Count && i < targetAttributeList.Count; i++)
            {
                Assert.That(sourceAttributeList[i].Match(targetAttributeList[i]));  // this will fail for mixed type arguments
            }
        }

        private static void ValidateSourceNameEqual(this Type target, Type source, Tuple<string, string> rootTargetAndSourceFullNames)
        {
            Contract.Requires(target != null);
            Contract.Requires(source != null);
            Contract.Requires(rootTargetAndSourceFullNames != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item1 != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item2 != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item1 != rootTargetAndSourceFullNames.Item2);

            Assert.That(target.IsSourceNameEqual(source, rootTargetAndSourceFullNames));
        }

        private static bool IsSourceNameEqual(this Type target, Type source, Tuple<string, string> rootTargetAndSourceFullNames)
        {
            Contract.Requires(target != null);
            Contract.Requires(source != null);
            Contract.Requires(rootTargetAndSourceFullNames != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item1 != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item2 != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item1 != rootTargetAndSourceFullNames.Item2);

            if (source.GenericTypeArguments.Length != target.GenericTypeArguments.Length) { return false; }
            if (source.IsArray != target.IsArray) { return false; }

            if (source.IsArray)
            {
                return
                    source.GetArrayRank() == target.GetArrayRank() &&
                    target.GetElementType().IsSourceNameEqual(source.GetElementType(), rootTargetAndSourceFullNames);
            }
            else if (source.GenericTypeArguments.Length == 0)
            {
                return source.FullName.Replace(rootTargetAndSourceFullNames.Item2, rootTargetAndSourceFullNames.Item1) == target.FullName;
            }
            else
            {
                if (!target.GetGenericTypeDefinition().IsSourceNameEqual(source.GetGenericTypeDefinition(), rootTargetAndSourceFullNames)) { return false; }

                return !source.GenericTypeArguments.Where(
                    (t, i) => !target.GenericTypeArguments[i].IsSourceNameEqual(t, rootTargetAndSourceFullNames)).Any();
            }
        }

        private static void ValidateSourceNameEqual(this MethodInfo target, MethodInfo source, Tuple<string, string> rootTargetAndSourceFullNames)
        {
            Contract.Requires(target != null);
            Contract.Requires(source != null);
            Contract.Requires(rootTargetAndSourceFullNames != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item1 != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item2 != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item1 != rootTargetAndSourceFullNames.Item2);

            Assert.That(target.IsSourceNameEqual(source, rootTargetAndSourceFullNames));
        }

        private static bool IsSourceNameEqual(this MethodInfo target, MethodInfo source, Tuple<string, string> rootTargetAndSourceFullNames)
        {
            Contract.Requires(target != null);
            Contract.Requires(source != null);
            Contract.Requires(rootTargetAndSourceFullNames != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item1 != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item2 != null);
            Contract.Requires(rootTargetAndSourceFullNames.Item1 != rootTargetAndSourceFullNames.Item2);

            if (!target.DeclaringType.IsSourceNameEqual(source.DeclaringType, rootTargetAndSourceFullNames)) { return false; }

            if (source.IsGenericMethodDefinition || !source.IsGenericMethod)
            {
                return source.ToString().Replace(rootTargetAndSourceFullNames.Item2, rootTargetAndSourceFullNames.Item1) == target.ToString();
            }
            else
            {
                if (target.IsGenericMethodDefinition || !target.IsGenericMethod) { return false; }

                var sourceGenericArguments = source.GetGenericArguments();
                var targetGenericArguments = target.GetGenericArguments();

                if (sourceGenericArguments.Length != targetGenericArguments.Length) { return false; }

                if (!target.GetGenericMethodDefinition().IsSourceNameEqual(source.GetGenericMethodDefinition(), rootTargetAndSourceFullNames)) { return false; }

                return !sourceGenericArguments.Where(
                    (t, i) => !targetGenericArguments[i].IsSourceNameEqual(t, rootTargetAndSourceFullNames)).Any();
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
/* Our Module is an Angular Module */
var gnaAsDirective = angular.module('gnaAsDirective', ['gnaAsDirectiveDirecives']);


text:
cask 'cinch' do
  version '1.2.4'
  sha256 '68afff19aaff4885e803733df74cfc87fe6529ec57107d21bddcb00d61dd14a0'

  url "https://www.irradiatedsoftware.com/downloads/Cinch_#{version}.zip"
  appcast 'https://www.irradiatedsoftware.com/updates/profiles/cinch.php'
  name 'Cinch'
  homepage 'https://www.irradiatedsoftware.com/cinch/'

  app 'Cinch.app'
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>acl</title>
    <link rel="root" href=""/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/hint.css"/>

          home

          edit page
          issue tracker

          <gcse:search></gcse:search>

        This page pertains to UD version 2.

            It appears that you have Javascript disabled.
            Please consider enabling Javascript for this page to see the visualizations.

acl: clausal modifier of noun

Clausal modifiers of nouns, with the bare acl relation, do not have relative pronouns dependent to them (those take the deprel acl:relcl). The head is the noun being modified, and the dependent is the head of the clausal modifier, which is usually the main verb.

ਤੁਰਦੀ ਰੇਲ ਗੱਡੀ \n moving rail car
compound(ਗੱਡੀ, ਰੇਲ)
compound(rail, car)
acl(ਗੱਡੀ, ਤੁਰਦੀ)
acl(car, moving)

ਬੈਠਿਆ ਹੋਇਆ ਮੁੰਡਾ \n sitting being boy
acl(ਮੁੰਡਾ, ਬੈਠਿਆ)
acl(boy, sitting)
aux(ਬੈਠਿਆ, ਹੋਇਆ)
aux(sitting, being)

Clausal modifiers can take some arguments, but the subject can never take the ergative case, instead a passive agentive case marker like ਵੱਲੋਂ vallõ.

ਸੱਸ ਵੱਲੋਂ ਨੂੰਹ ਨੂੰ ਦਿੱਤੇ ਅਸ਼ੀਰਵਾਦ \n mother.in.law by daughter.in.law DAT given blessings
nsubj:pass(ਦਿੱਤੇ, ਸੱਸ)
nsubj:pass(given, mother.in.law)
iobj(ਦਿੱਤੇ, ਨੂੰਹ)
iobj(given, daughter.in.law)
acl(ਅਸ਼ੀਰਵਾਦ, ਦਿੱਤੇ)
acl(blessings, given)

With case markers and postpositions

The postposition ਵਾਲਾ vālā marks such clausal modifiers, with a habitual connotation, as well.

ਆਖਣ ਵਾਲਾ ਮੁੰਡਾ \n saying (vālā) boy
acl(ਮੁੰਡਾ, ਆਖਣ)
acl(boy, saying)
mark(ਆਖਣ, ਵਾਲਾ)
mark(saying, (vālā))

Other cases can also be used. For example, the genitive with topic/information content of the head nominal.

ਭਾਰਤ ਜਾਣ ਦੀ ਗੱਲ \n India going GEN talk
acl(ਗੱਲ, ਜਾਣ)
acl(talk, going)
obl(ਜਾਣ, ਭਾਰਤ)
obl(going, India)
mark(ਜਾਣ, ਦੀ)
mark(going, GEN)

acl in other languages:

[bej]

[bg]

[bm]

[cop]

[cs]

[de]

[el]

[en]

[es]

[et]

[eu]

[fi]

[fr]

[fro]

[ga]

[gsw]

[hy]

[it]

[ja]

[kk]

[no]

[pa]

[pcm]

[pt]

[ro]

[ru]

[sl]

[sv]

[swl]

[tr]

[u]

[urj]

[yue]

[zh]

© 2014–2021
            Universal Dependencies contributors.
            Site powered by Annodoc and brat
.


text:
class Reason < SelectOption
  has_many :appointments
   validates_presence_of :name, :description
end


text:
"""
Unit tests for config section schema description.
"""

from __future__ import absolute_import, print_function
from click_configfile import Param, SectionSchema
from click_configfile import assign_param_names, matches_section
import pytest

# -----------------------------------------------------------------------------
# TEST SUITE
# -----------------------------------------------------------------------------
class TestDecorators(object):

    # -- TESTS RELATED TO: @assign_param_names decorator
    def test_assign_param_names__with_schema_class(self):
        @assign_param_names
        class ExampleSchema(SectionSchema):
            some_non_param = 123
            person = Param(type=str)
            number = Param(type=int)
            verbose = Param(type=bool)
            persons = Param(type=str, multiple=True)

        # -- ENSURE:
        assert ExampleSchema.person.name == "person"
        assert ExampleSchema.number.name == "number"
        assert ExampleSchema.verbose.name == "verbose"
        assert ExampleSchema.persons.name == "persons"

    def test_assign_param_names__with_other_class(self):
        @assign_param_names
        class ExampleSchema(object):
            person = Param(type=str)
            number = Param(type=int)

        # -- ENSURE:
        assert ExampleSchema.person.name == "person"
        assert ExampleSchema.number.name == "number"

    def test_assign_param_names__with_nested_schema_class(self):
        @assign_param_names
        class ConfigSectionSchema(object):
            class Example(SectionSchema):
                person = Param(type=str)
                number = Param(type=int)

        # -- ENSURE:
        assert ConfigSectionSchema.Example.person.name == "person"
        assert ConfigSectionSchema.Example.number.name == "number"

    def test_assign_param_names__with_deeper_nested_schema_class(self):
        @assign_param_names
        class ConfigSectionSchema(object):
            class Level(object):
                class Example(SectionSchema):
                    person = Param(type=str)
                    number = Param(type=int)

        # -- ENSURE:
        assert ConfigSectionSchema.Level.Example.person.name == "person"
        assert ConfigSectionSchema.Level.Example.number.name == "number"

    def test_assign_param_names__with_derived_param_class_in_schema(self):
        class DerivedParam(Param):
            pass

        @assign_param_names
        class ExampleSchema(object):
            person = DerivedParam(type=str)
            number = DerivedParam(type=int)

        # -- ENSURE:
        assert ExampleSchema.person.name == "person"
        assert ExampleSchema.number.name == "number"

    def test_assign_param_names__with_own_param_class_as_marker(self):
        class MyParam(Param):
            pass

        @assign_param_names(param_class=MyParam)
        class ExampleSchema(object):
            person = Param(type=str)
            number = MyParam(type=int)

        # -- ENSURE:
        assert ExampleSchema.person.name is None
        assert ExampleSchema.number.name == "number"

    def test_assign_param_names__skips_non_param_objects(self):
        @assign_param_names
        class ExampleSchema(SectionSchema):
            some_non_param = 123
            param_class_alias = Param

        # -- ENSURE:
        assert not hasattr(ExampleSchema.some_non_param, "name")
        assert not hasattr(ExampleSchema.param_class_alias, "name")

    def test_assign_param_names__skips_params_with_assigned_names(self):
        @assign_param_names
        class ExampleSchema(SectionSchema):
            person = Param("xxx", type=str)
            number = Param(name="PHI", type=float)

        # -- ENSURE:
        assert ExampleSchema.person.name == "xxx"
        assert ExampleSchema.number.name == "PHI"

    # -- TESTS RELATED TO: @matches_section decorator
    @pytest.mark.parametrize("section_name", [
        "hello", "hello.*", "*.hello"
    ])
    def test_matches_section__with_arg(self, section_name):
        @matches_section(section_name)
        class Hello(SectionSchema):
            pass

        assert Hello.section_names == [section_name]

    @pytest.mark.parametrize("section_names", [
        ["hello", "hello.*"]
    ])
    def test_matches_section__with_multiple_args(self, section_names):
        @matches_section(section_names)
        class Hello(SectionSchema):
            pass

        assert isinstance(section_names, (list, tuple))
        assert Hello.section_names == section_names

    def test_matches_section__with_several_decorators(self):
        @matches_section("foo")
        @matches_section("bar.*")
        class Hello(SectionSchema):
            pass

        assert Hello.section_names == ["foo", "bar.*"]

    def test_matches_section__with_other_class(self):
        @matches_section("hello")
        class Hello(object):
            pass

        assert Hello.section_names == ["hello"]

    def test_matches_section__with_class_that_has_section_names(self):
        @matches_section("hello")
        class Hello(SectionSchema):
            section_names = ["foo"]

        assert Hello.section_names == ["hello", "foo"]

    @pytest.mark.parametrize("bad_section_name", [None, 123, False, 1.23])
    def test_matches_section__with_bad_arg(self, bad_section_name):
        with pytest.raises(ValueError) as e:
            @matches_section(bad_section_name)
            class Hello(SectionSchema):
                pass

        expected = "ValueError: %r (expected: string, strings)" % bad_section_name
        assert expected in str(e)


text:
package Nov2020_FBPrep;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class _049DivideTwoIntegers {

	public static void main(String[] args) {
		System.out.println(subsets(new int[] { 1, 2, 3 }));
		System.out.println(subsets(new int[] { 0 }));
	}

    public int divide(int dividend, int divisor) {

    }
}


text:
require('jasmine_dom_matchers');
require('jasmine-ajax');

global.ReactTestUtils = require('react/lib/ReactTestUtils');
global.React = require('react');
global.ReactDOM = require('react/lib/ReactDOM');
global.jQuery = global.$ = require('jquery');

$.fn.simulate = function(eventName, ...args) {
  if (!this.length) {
    throw new Error(`jQuery Simulate has an empty selection for '${this.selector}'`);
  }
  $.each(this, function() {
    if (['mouseOver', 'mouseOut', 'click'].indexOf(eventName) !== -1) {
      ReactTestUtils.SimulateNative[eventName](this, ...args);
    } else {
      ReactTestUtils.Simulate[eventName](this, ...args);
    }
  });
  return this;
};

beforeEach(function () {
  jasmine.Ajax.install();
  $('body').find('#root').remove().end().append('<main id="root"/>');
});

afterEach(function () {
  jasmine.Ajax.uninstall();
  $('body').find('#root').remove().end().append('<main id="root"/>');
});


text:
namespace gzip {

namespace internal {

// We use a 16KB buffer with zlib compression / decompression.
#define GZIP_BUFFER_SIZE 16384

class GzipError : public Error
{
public:
  GzipError(const std::string& message, const z_stream_s& stream, int _code)
    : Error(message + ": " + GzipError::strerror(stream, _code)), code(_code) {}

  GzipError(const std::string& message, int _code)
    : Error(message + ": " + GzipError::strerror(_code)), code(_code) {}

  GzipError(const z_stream_s& stream, int _code)
    : Error(GzipError::strerror(stream, _code)), code(_code) {}

  GzipError(int _code)
    : Error(GzipError::strerror(_code)), code(_code) {}

  const int code;

private:
  static std::string strerror(int code)
  {
    // We do not attempt to interpret the error codes since
    // their meaning depends on which zlib call was made.
    switch (code) {
      case Z_OK:             return "Z_OK";           // Not an error.
      case Z_STREAM_END:     return "Z_STREAM_END";   // Not an error.
      case Z_NEED_DICT:      return "Z_NEED_DICT";    // Not an error.
      case Z_ERRNO:          return "Z_ERRNO: " + os::strerror(errno);
      case Z_STREAM_ERROR:   return "Z_STREAM_ERROR";
      case Z_DATA_ERROR:     return "Z_DATA_ERROR";
      case Z_MEM_ERROR:      return "Z_MEM_ERROR";
      case Z_BUF_ERROR:      return "Z_BUF_ERROR";
      case Z_VERSION_ERROR:  return "Z_VERSION_ERROR";
      default:               return "Unknown error " + stringify(code);
    }
  }

  static std::string strerror(const z_stream_s& stream, int code)
  {
    if (stream.msg == Z_NULL) {
      return GzipError::strerror(code);
    } else {
      return GzipError::strerror(code) + ": " + stream.msg;
    }
  }
};

} // namespace internal {

// Provides the ability to incrementally decompress
// a stream of compressed input data.
class Decompressor
{
public:
  Decompressor()
    : _finished(false)
  {
    stream.zalloc = Z_NULL;
    stream.zfree = Z_NULL;
    stream.opaque = Z_NULL;
    stream.next_in = Z_NULL;
    stream.avail_in = 0;

    int code = inflateInit2(
        &stream,
        MAX_WBITS + 16); // Zlib magic for gzip compression / decompression.

    if (code != Z_OK) {
      Error error = internal::GzipError("Failed to inflateInit2", stream, code);
      ABORT(error.message);
    }
  }

  Decompressor(const Decompressor&) = delete;
  Decompressor& operator=(const Decompressor&) = delete;

  ~Decompressor()
  {
    if (inflateEnd(&stream) != Z_OK) {
      ABORT("Failed to inflateEnd");
    }
  }

  // Returns the next decompressed chunk of data,
  // or an Error if decompression fails.
  Try<std::string> decompress(const std::string& compressed)
  {
    stream.next_in =
      const_cast<Bytef*>(reinterpret_cast<const Bytef*>(compressed.data()));
    stream.avail_in = static_cast<uInt>(compressed.length());

    // Build up the decompressed result.
    Bytef buffer[GZIP_BUFFER_SIZE];
    std::string result;

    while (stream.avail_in > 0) {
      stream.next_out = buffer;
      stream.avail_out = GZIP_BUFFER_SIZE;

      int code = inflate(&stream, Z_SYNC_FLUSH);

      _finished = code == Z_STREAM_END;

      if (code != Z_OK && !_finished) {
        return internal::GzipError("Failed to inflate", stream, code);
      }

      if (_finished && stream.avail_in > 0) {
        return Error("Stream finished with data unconsumed");
      }

      // Consume output and reset the buffer.
      result.append(
          reinterpret_cast<char*>(buffer),
          GZIP_BUFFER_SIZE - stream.avail_out);
      stream.next_out = buffer;
      stream.avail_out = GZIP_BUFFER_SIZE;
    }

    return result;
  }

  // Returns whether the decompression stream is finished.
  // If set to false, more input is expected.
  bool finished() const
  {
    return _finished;
  }

private:
  z_stream_s stream;
  bool _finished;
};

// Returns a gzip compressed version of the provided string.
// The compression level should be within the range [-1, 9].
// See zlib.h:
//   #define Z_NO_COMPRESSION         0
//   #define Z_BEST_SPEED             1
//   #define Z_BEST_COMPRESSION       9
//   #define Z_DEFAULT_COMPRESSION  (-1)
inline Try<std::string> compress(
    const std::string& decompressed,
    int level = Z_DEFAULT_COMPRESSION)
{
  // Verify the level is within range.
  if (!(level == Z_DEFAULT_COMPRESSION ||
      (level >= Z_NO_COMPRESSION && level <= Z_BEST_COMPRESSION))) {
    return Error("Invalid compression level: " + stringify(level));
  }

  z_stream_s stream;
  stream.next_in =
    const_cast<Bytef*>(reinterpret_cast<const Bytef*>(decompressed.data()));
  stream.avail_in = static_cast<uInt>(decompressed.length());
  stream.zalloc = Z_NULL;
  stream.zfree = Z_NULL;
  stream.opaque = Z_NULL;

  int code = deflateInit2(
      &stream,
      level,          // Compression level.
      Z_DEFLATED,     // Compression method.
      MAX_WBITS + 16, // Zlib magic for gzip compression / decompression.
      8,              // Default memLevel value.
      Z_DEFAULT_STRATEGY);

  if (code != Z_OK) {
    Error error = internal::GzipError("Failed to deflateInit2", stream, code);
    ABORT(error.message);
  }

  // Build up the compressed result.
  Bytef buffer[GZIP_BUFFER_SIZE];
  std::string result;
  do {
    stream.next_out = buffer;
    stream.avail_out = GZIP_BUFFER_SIZE;
    code = deflate(&stream, stream.avail_in > 0 ? Z_NO_FLUSH : Z_FINISH);

    if (code != Z_OK && code != Z_STREAM_END) {
      Error error = internal::GzipError("Failed to deflate", stream, code);
      if (deflateEnd(&stream) != Z_OK) {
        ABORT("Failed to deflateEnd");
      }
      return error;
    }

    // Consume output and reset the buffer.
    result.append(
        reinterpret_cast<char*>(buffer),
        GZIP_BUFFER_SIZE - stream.avail_out);
    stream.next_out = buffer;
    stream.avail_out = GZIP_BUFFER_SIZE;
  } while (code != Z_STREAM_END);

  if (deflateEnd(&stream) != Z_OK) {
    ABORT("Failed to deflateEnd");
  }

  return result;
}

// Returns a gzip decompressed version of the provided string.
inline Try<std::string> decompress(const std::string& compressed)
{
  Decompressor decompressor;
  Try<std::string> decompressed = decompressor.decompress(compressed);

  // Ensure that the decompression stream does not expect more input.
  if (decompressed.isSome() && !decompressor.finished()) {
    return Error("More input is expected");
  }

  return decompressed;
}

} // namespace gzip {

#endif // __STOUT_GZIP_HPP__


text:
package es.bsc.mobile.runtime.types.data.parameter;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import es.bsc.mobile.annotations.Parameter.Direction;
import es.bsc.mobile.annotations.Parameter.Type;
import java.io.Serializable;

public class FileParameter extends Parameter implements Serializable {

    // URI beginning
    protected static final String FILE_URI = "file:";
    protected static final String SHARED_URI = "shared:";

    private final String host;
    private final String path;
    private final String fileName;

    public FileParameter(Direction direction, String fullName)
            throws URISyntaxException, IOException {
        super(Type.FILE, direction);
        String[] file = extractHostPathName(fullName);
        host = file[0];
        path = file[1];
        fileName = file[2];
    }

    @Override
    public String toString() {
        return host + ":" + path + fileName + " " + getType() + " " + getDirection();
    }

    public String getFullFileName() {
        return path + fileName;
    }

    protected final String[] extractHostPathName(String fullName)
            throws URISyntaxException, IOException {
        String name;
        String extractedPath;
        String extractedHost;

        if (fullName.startsWith(FILE_URI)) {
            /*
             * URI syntax with host name and absolute path, e.g.
             * "file://bscgrid01.bsc.es/home/etejedor/file.txt" Only used in
             * grid-aware applications, using IT API and partial loader, since
             * total loader targets sequential applications that use local
             * files.
             */
            URI u = new URI(fullName);
            extractedHost = u.getHost();
            String fullPath = u.getPath();
            int pathEnd = fullPath.lastIndexOf("/");
            extractedPath = fullPath.substring(0, pathEnd + 1);
            name = fullPath.substring(pathEnd + 1);
        } else if (fullName.startsWith(SHARED_URI)) {
            URI u = new URI(fullName);
            extractedHost = "shared:" + u.getHost();
            String fullPath = u.getPath();
            int pathEnd = fullPath.lastIndexOf("/");
            extractedPath = fullPath.substring(0, pathEnd + 1);
            name = fullPath.substring(pathEnd + 1);
        } else {
            // Local file, format will depend on OS
            File f = new File(fullName);
            String canonicalPath = f.getCanonicalPath();
            name = f.getName();
            extractedPath = canonicalPath.substring(0,
                    canonicalPath.length() - name.length());
            extractedHost = "master";
        }
        return new String[]{extractedHost, extractedPath, name};
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
	xmlns:g="urn:import:com.google.gwt.user.client.ui" xmlns:d="urn:import:org.ovirt.engine.ui.webadmin.widget.dialog"
	xmlns:e="urn:import:org.ovirt.engine.ui.webadmin.widget.editor">

	<ui:style>
		.titleLabel {
			padding-top: 5px;
			padding-left: 5px;
		}

		.descriptionEditor {
			width: 100%;
		}

		.errorMessageLabel {
			color: #CD2127;
			margin-top: 10px;
			margin-left: 5px;
		}

		.treePanel {
			margin-top: 5px;
		}

		.buttonPanel {
			padding-left: 5px;
		}
	</ui:style>

	<d:SimpleDialogPanel width="400px" height="560px">
		<d:content>
			<g:VerticalPanel>
				<g:Label ui:field="titleLabel" addStyleNames="{style.titleLabel}" />
				<g:HTML>
					<hr style="width:100%;" />
				</g:HTML>
				<g:HorizontalPanel addStyleNames="{style.buttonPanel}">
					<g:Button ui:field="expandAllButton" />
					<g:Button ui:field="collapseAllButton" />
				</g:HorizontalPanel>
				<g:ScrollPanel height="385px" addStyleNames="{style.treePanel}">
					<e:EntityModelCellTree ui:field="tree" />
				</g:ScrollPanel>
				<e:EntityModelTextBoxEditor ui:field="emailEditor" />
			</g:VerticalPanel>
		</d:content>
	</d:SimpleDialogPanel>

</ui:UiBinder>


text:
package org.apache.skywalking.oap.log.analyzer.dsl;

import org.apache.skywalking.apm.network.logging.v3.LogData;
import org.apache.skywalking.apm.network.logging.v3.LogDataBody;
import org.apache.skywalking.apm.network.logging.v3.LogTags;
import org.apache.skywalking.apm.network.logging.v3.TraceContext;
import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.PropertyExpression;
import org.codehaus.groovy.ast.expr.VariableExpression;
import org.codehaus.groovy.transform.stc.AbstractTypeCheckingExtension;
import org.codehaus.groovy.transform.stc.StaticTypeCheckingVisitor;

import static org.codehaus.groovy.ast.ClassHelper.makeCached;

public class LALPrecompiledExtension extends AbstractTypeCheckingExtension {

    public LALPrecompiledExtension(final StaticTypeCheckingVisitor typeCheckingVisitor) {
        super(typeCheckingVisitor);
    }

    @Override
    public boolean handleUnresolvedProperty(final PropertyExpression pexp) {
        final Expression exp = pexp.getObjectExpression();

        if (exp.getText().startsWith("parsed")) {
            makeDynamic(pexp);
            setHandled(true);
            return true;
        }

        if (exp.getText().startsWith("log")) {
            if (handleLogVariable(pexp)) {
                return true;
            }
        }

        return super.handleUnresolvedProperty(pexp);
    }

    private boolean handleLogVariable(final PropertyExpression pexp) {
        final Expression exp = pexp.getObjectExpression();
        final Expression p = pexp.getProperty();

        if (exp instanceof VariableExpression) {
            final VariableExpression v = (VariableExpression) exp;
            if (v.getName().equals("log")) {
                storeType(v, makeCached(LogData.Builder.class));
            }
            if (p instanceof ConstantExpression) {
                final ConstantExpression c = (ConstantExpression) p;
                switch (c.getText()) {
                    case "body":
                        storeType(pexp, makeCached(LogDataBody.class));
                        break;
                    case "traceContext":
                        storeType(pexp, makeCached(TraceContext.class));
                        break;
                    case "tags":
                        storeType(pexp, makeCached(LogTags.class));
                        break;
                }
            }
            setHandled(true);
            return true;
        }

        return false;
    }
}


text:
/*
 * Created by Koen Deschacht (koendeschacht@gmail.com) 2017-5-3. For license
 * information see the LICENSE file in the root folder of this repository.
 */

package be.bagofwords.exec;

import java.io.ByteArrayInputStream;

public class RemoteObjectUtil {

    public static Object loadObject(PackedRemoteObject packedRemoteObject, RemoteObjectClassLoader remoteObjectClassLoader) {
        try {
            remoteObjectClassLoader.addRemoteClasses(packedRemoteObject.classSources);
            ByteArrayInputStream bis = new ByteArrayInputStream(packedRemoteObject.serializedObject);
            RemoteObjectInputStream ois = new RemoteObjectInputStream(bis, remoteObjectClassLoader);
            Object object = ois.readObject();
            ois.close();
            return object;
        } catch (Exception exp) {
            throw new RemoteObjectException("Failed to load " + packedRemoteObject, exp);
        }
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycologia 25: 146 (1933)

#### Original name
Pezicula spiculata Seaver

### Remarks
null


text:
package grago

import (
	"fmt"
	"testing"
)

func createGraphpr() *Graph {
	graph := NewGraph(false, true, false)
	graph.AddNode(stringer("alpha"))
	graph.AddLink(stringer("2"), stringer("3"), 2)
	graph.AddLink(stringer("2"), stringer("4"), 5)
	graph.AddLink(stringer("3"), stringer("5"), 8)
	graph.AddLink(stringer("5"), stringer("4"), 10)
	return graph
}

func createGraphpr2() *Graph {
	graph := NewGraph(false, true, false)
	graph.AddLink(stringer("2"), stringer("4"), 5)
	graph.AddLink(stringer("3"), stringer("5"), 8)
	return graph
}

func createGraphpr3() *Graph {
	graph := NewGraph(true, true, false)
	graph.AddLink(stringer("2"), stringer("4"), 5)
	graph.AddLink(stringer("3"), stringer("5"), 8)
	return graph
}

func ExampleGraph_HasCycle() {
	fmt.Println(createGraphpr().HasCycle())
	fmt.Println(createGraphpr2().HasCycle())
	fmt.Println(createGraphpr3().HasCycle())

	// Output:
	// true
	// true
	// false
}

func ExampleGraph_IsPlanar() {
	graph := createGraphpr()
	graph.RemoveNode(stringer("alpha"))

	fmt.Println(graph.IsPlanar())

	graph.AddLink(stringer("2"), stringer("5"), 20)
	graph.AddLink(stringer("3"), stringer("4"), 15)
	graph.AddLink(stringer("2"), stringer("alpha"), 1)
	graph.AddLink(stringer("3"), stringer("alpha"), 1)
	graph.AddLink(stringer("4"), stringer("alpha"), 1)
	graph.AddLink(stringer("5"), stringer("alpha"), 1)

	fmt.Println(graph.IsPlanar())

	// Output:
	// true
	// false
}

func ExampleGraph_IsBipartite() {
	graph := createGraphpr()

	fmt.Println(createGraphpr2().IsBipartite())
	fmt.Println(graph.IsBipartite())

	graph.AddLink(stringer("2"), stringer("5"), 20)

	fmt.Println(graph.IsBipartite())

	// Output:
	// true
	// true
	// false
}

func TestCycle(t *testing.T) {
	if createGraphpr().HasCycle() == false {
		t.Fail()
	}
}

func TestCycle2(t *testing.T) {
	if createGraphpr2().HasCycle() == false {
		t.Fail()
	}
}

func TestNoCycle(t *testing.T) {
	if createGraphpr3().HasCycle() == true {
		t.Fail()
	}
}

func TestPlanar(t *testing.T) {
	graph := createGraphpr()
	graph.RemoveNode(stringer("alpha"))

	if graph.IsPlanar() == false {
		t.Fail()
	}
}

func TestNonPlanar(t *testing.T) {
	graph := createGraphpr()
	graph.AddLink(stringer("2"), stringer("5"), 20)
	graph.AddLink(stringer("3"), stringer("4"), 15)
	graph.AddLink(stringer("2"), stringer("alpha"), 1)
	graph.AddLink(stringer("3"), stringer("alpha"), 1)
	graph.AddLink(stringer("4"), stringer("alpha"), 1)
	graph.AddLink(stringer("5"), stringer("alpha"), 1)

	if graph.IsPlanar() == true {
		t.Fail()
	}
}

func TestBipartite(t *testing.T) {
	if createGraphpr2().IsBipartite() == false {
		t.Fail()
	}
}

func TestBipartite2(t *testing.T) {
	if createGraphpr().IsBipartite() == false {
		t.Fail()
	}
}

func TestNonBipartite(t *testing.T) {
	graph := createGraphpr()

	graph.AddLink(stringer("3"), stringer("4"), 7)

	if graph.IsBipartite() == true {
		t.Fail()
	}
}


text:
package com.intellij.debugger.impl;

import com.intellij.configurationStore.XmlSerializer;
import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.actions.DebuggerAction;
import com.intellij.debugger.engine.DebugProcess;
import com.intellij.debugger.engine.DebugProcessImpl;
import com.intellij.debugger.engine.StackFrameContext;
import com.intellij.debugger.engine.evaluation.CodeFragmentKind;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.engine.evaluation.TextWithImports;
import com.intellij.debugger.engine.evaluation.TextWithImportsImpl;
import com.intellij.debugger.impl.attach.PidRemoteConnection;
import com.intellij.debugger.ui.impl.watch.DebuggerTreeNodeExpression;
import com.intellij.debugger.ui.tree.render.BatchEvaluator;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.RemoteConnection;
import com.intellij.ide.util.TreeClassChooser;
import com.intellij.ide.util.TreeClassChooserFactory;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.JDOMExternalizerUtil;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.ThrowableComputable;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiJavaParserFacadeImpl;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.util.net.NetUtils;
import com.intellij.xdebugger.XExpression;
import com.intellij.xdebugger.impl.breakpoints.XExpressionState;
import com.sun.jdi.*;
import com.sun.jdi.connect.Connector;
import com.sun.jdi.connect.IllegalConnectorArgumentsException;
import com.sun.jdi.connect.ListeningConnector;
import one.util.streamex.StreamEx;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

public class DebuggerUtilsImpl extends DebuggerUtilsEx{
  public static final Key<PsiType> PSI_TYPE_KEY = Key.create("PSI_TYPE_KEY");
  private static final Logger LOG = Logger.getInstance(DebuggerUtilsImpl.class);

  @Override
  public PsiExpression substituteThis(PsiExpression expressionWithThis, PsiExpression howToEvaluateThis, Value howToEvaluateThisValue, StackFrameContext context)
    throws EvaluateException {
    return DebuggerTreeNodeExpression.substituteThis(expressionWithThis, howToEvaluateThis, howToEvaluateThisValue);
  }

  @Override
  public DebuggerContextImpl getDebuggerContext(DataContext context) {
    return DebuggerAction.getDebuggerContext(context);
  }

  @Override
  @SuppressWarnings({"HardCodedStringLiteral"})
  public Element writeTextWithImports(TextWithImports text) {
    Element element = new Element("TextWithImports");

    element.setAttribute("text", text.toExternalForm());
    element.setAttribute("type", text.getKind() == CodeFragmentKind.EXPRESSION ? "expression" : "code fragment");
    return element;
  }

  @Override
  @SuppressWarnings({"HardCodedStringLiteral"})
  public TextWithImports readTextWithImports(Element element) {
    LOG.assertTrue("TextWithImports".equals(element.getName()));

    String text = element.getAttributeValue("text");
    if ("expression".equals(element.getAttributeValue("type"))) {
      return new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, text);
    } else {
      return new TextWithImportsImpl(CodeFragmentKind.CODE_BLOCK, text);
    }
  }

  @Override
  public void writeTextWithImports(Element root, String name, TextWithImports value) {
    if (value.getKind() == CodeFragmentKind.EXPRESSION) {
      JDOMExternalizerUtil.writeField(root, name, value.toExternalForm());
    }
    else {
      Element element = JDOMExternalizerUtil.writeOption(root, name);
      XExpression expression = TextWithImportsImpl.toXExpression(value);
      if (expression != null) {
        XmlSerializer.serializeObjectInto(new XExpressionState(expression), element);
      }
    }
  }

  @Override
  public TextWithImports readTextWithImports(Element root, String name) {
    String s = JDOMExternalizerUtil.readField(root, name);
    if (s != null) {
      return new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, s);
    }
    else {
      Element option = JDOMExternalizerUtil.readOption(root, name);
      if (option != null) {
        XExpressionState state = new XExpressionState();
        XmlSerializer.deserializeInto(option, state);
        return TextWithImportsImpl.fromXExpression(state.toXExpression());
      }
    }
    return null;
  }

  @Override
  public TextWithImports createExpressionWithImports(String expression) {
    return new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, expression);
  }

  @Override
  public PsiElement getContextElement(StackFrameContext context) {
    return PositionUtil.getContextElement(context);
  }

  @NotNull
  public static Pair<PsiElement, PsiType> getPsiClassAndType(@Nullable String className, Project project) {
    PsiElement contextClass = null;
    PsiType contextType = null;
    if (!StringUtil.isEmpty(className)) {
      PsiPrimitiveType primitiveType = PsiJavaParserFacadeImpl.getPrimitiveType(className);
      if (primitiveType != null) {
        contextClass = JavaPsiFacade.getInstance(project).findClass(primitiveType.getBoxedTypeName(), GlobalSearchScope.allScope(project));
        contextType = primitiveType;
      }
      else {
        contextClass = findClass(className, project, GlobalSearchScope.allScope(project));
        if (contextClass != null) {
          contextClass = contextClass.getNavigationElement();
        }
        if (contextClass instanceof PsiCompiledElement) {
          contextClass = ((PsiCompiledElement)contextClass).getMirror();
        }
        contextType = getType(className, project);
      }
      if (contextClass != null) {
        contextClass.putUserData(PSI_TYPE_KEY, contextType);
      }
    }
    return Pair.create(contextClass, contextType);
  }

  @Override
  public PsiClass chooseClassDialog(String title, Project project) {
    TreeClassChooser dialog = TreeClassChooserFactory.getInstance(project).createAllProjectScopeChooser(title);
    dialog.showDialog();
    return dialog.getSelected();
  }

  @Override
  public String findAvailableDebugAddress(boolean useSockets) throws ExecutionException {
    if (useSockets) {
      final int freePort;
      try {
        freePort = NetUtils.findAvailableSocketPort();
      }
      catch (IOException e) {
        throw new ExecutionException(DebugProcessImpl.processError(e));
      }
      return Integer.toString(freePort);
    }
    else {
      ListeningConnector connector = (ListeningConnector)DebugProcessImpl.findConnector(false, true);
      try {
        return tryShmemConnect(connector, "");
      }
      catch (Exception e) {
        int tryNum = 0;
        while (true) {
          try {
            return tryShmemConnect(connector, "javadebug_" + (int)(Math.random() * 1000));
          }
          catch (Exception ex) {
            if (tryNum++ > 10) {
              throw new ExecutionException(DebugProcessImpl.processError(ex));
            }
          }
        }
      }
    }
  }

  private static String tryShmemConnect(ListeningConnector connector, String address)
    throws IOException, IllegalConnectorArgumentsException {
    Map<String, Connector.Argument> map = connector.defaultArguments();
    map.get("name").setValue(address);
    address = connector.startListening(map);
    connector.stopListening(map);
    return address;
  }

  public static boolean isRemote(DebugProcess debugProcess) {
    return Boolean.TRUE.equals(debugProcess.getUserData(BatchEvaluator.REMOTE_SESSION_KEY));
  }

  public static <T, E extends Exception> T suppressExceptions(ThrowableComputable<? extends T, ? extends E> supplier, T defaultValue) throws E {
    return suppressExceptions(supplier, defaultValue, true, null);
  }

  public static <T, E extends Exception> T suppressExceptions(ThrowableComputable<? extends T, ? extends E> supplier,
                                                              T defaultValue,
                                                              boolean ignorePCE,
                                                              Class<E> rethrow) throws E {
    try {
      return supplier.compute();
    }
    catch (ProcessCanceledException e) {
      if (!ignorePCE) {
        throw e;
      }
    }
    catch (VMDisconnectedException | ObjectCollectedException e) {throw e;}
    catch (InternalException e) {LOG.info(e);}
    catch (Exception | AssertionError e) {
      if (rethrow != null && rethrow.isInstance(e)) {
        throw e;
      }
      else {
        LOG.error(e);
      }
    }
    return defaultValue;
  }

  public static String getConnectionDisplayName(RemoteConnection connection) {
    if (connection instanceof PidRemoteConnection) {
      return "pid " + ((PidRemoteConnection)connection).getPid();
    }
    String addressDisplayName = DebuggerBundle.getAddressDisplayName(connection);
    String transportName = DebuggerBundle.getTransportName(connection);
    return DebuggerBundle.message("string.connection", addressDisplayName, transportName);
  }

  public static boolean instanceOf(@Nullable ReferenceType type, @NotNull ReferenceType superType) {
    if (type == null) {
      return false;
    }
    if (superType.equals(type) || CommonClassNames.JAVA_LANG_OBJECT.equals(superType.name())) {
      return true;
    }
    return supertypes(type).anyMatch(t -> instanceOf(t, superType));
  }

  public static Stream<? extends ReferenceType> supertypes(ReferenceType type) {
    if (type instanceof InterfaceType) {
      return ((InterfaceType)type).superinterfaces().stream();
    } else if (type instanceof ClassType) {
      return StreamEx.<ReferenceType>ofNullable(((ClassType)type).superclass()).prepend(((ClassType)type).interfaces());
    }
    return StreamEx.empty();
  }

  public static byte @Nullable [] readBytesArray(Value bytesArray) {
    if (bytesArray instanceof ArrayReference) {
      List<Value> values = ((ArrayReference)bytesArray).getValues();
      byte[] res = new byte[values.size()];
      int idx = 0;
      for (Value value : values) {
        if (value instanceof ByteValue) {
          res[idx++] = ((ByteValue)value).value();
        }
        else {
          return null;
        }
      }
      return res;
    }
    return null;
  }
}


text:
class Map {
  static class Builder {}
  static Builder builder() {}
}
class BiMap extends Map {
  static class Builder extends Map.Builder {}
  static Builder builder() {}
}

class Usage {
  Map.Builder b = bui<caret>
}


text:
<?php

namespace Illuminate\Database\Console\Seeds;

use Illuminate\Console\GeneratorCommand;
use Illuminate\Support\Str;
use Symfony\Component\Console\Attribute\AsCommand;

#[AsCommand(name: 'make:seeder')]
class SeederMakeCommand extends GeneratorCommand
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'make:seeder';

    /**
     * The name of the console command.
     *
     * This name is used to identify the command during lazy loading.
     *
     * @var string|null
     *
     * @deprecated
     */
    protected static $defaultName = 'make:seeder';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new seeder class';

    /**
     * The type of class being generated.
     *
     * @var string
     */
    protected $type = 'Seeder';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        parent::handle();
    }

    /**
     * Get the stub file for the generator.
     *
     * @return string
     */
    protected function getStub()
    {
        return $this->resolveStubPath('/stubs/seeder.stub');
    }

    /**
     * Resolve the fully-qualified path to the stub.
     *
     * @param  string  $stub
     * @return string
     */
    protected function resolveStubPath($stub)
    {
        return is_file($customPath = $this->laravel->basePath(trim($stub, '/')))
            ? $customPath
            : __DIR__.$stub;
    }

    /**
     * Get the destination class path.
     *
     * @param  string  $name
     * @return string
     */
    protected function getPath($name)
    {
        $name = str_replace('\\', '/', Str::replaceFirst($this->rootNamespace(), '', $name));

        if (is_dir($this->laravel->databasePath().'/seeds')) {
            return $this->laravel->databasePath().'/seeds/'.$name.'.php';
        }

        return $this->laravel->databasePath().'/seeders/'.$name.'.php';
    }

    /**
     * Get the root namespace for the class.
     *
     * @return string
     */
    protected function rootNamespace()
    {
        return 'Database\Seeders\\';
    }
}


text:
  {{#author}}

  {{/author}}

          {{#mine}}
          <button class="js-edit btn btn-link btn-xs">Edit</button>
          {{/mine}}

        {{#author}}
      	{{name}}
        {{/author}}
        {{^author}}
        Deleted User
        {{/author}}

          {{modified}}

          {{^isCurrent}}
          about a previous version

          {{/isCurrent}}

{{message}}


text:
import sys
import pymongo
import json

print "import crawled json file into mongodb 'newspapers' database."

if len(sys.argv) < 3:
    print "input as [collection] [json_file]"
    exit(1)

connection = pymongo.Connection("localhost", 27017)
news_database = connection.newspapers
news_collection = news_database[sys.argv[1]]

json_file_name = sys.argv[2]
try:
    with open(json_file_name, mode='r') as json_file:
        items = json.loads(json_file.read())
        json_file.close()
except Exception, e:
    raise e

for item in items:
    news_collection.save(item)

print len(items), " items saved to mongodb."