text:
import { ElementRef, Injectable, OnDestroy, Renderer2 } from '@angular/core';
import { Subscription, Subject } from 'rxjs';

@Injectable()
export class ClockPickerService implements OnDestroy {

  private subscribe = new Subscription();

  private elementNumber: ElementRef;

  private step;

  private opened = false;

  private angle;

  private relativeAngle;

  private radius;

  private numbers = 12;

  private minNumber = 12;

  private maxNumber = 60;

  private divisor = 30;

  private timeClock = { hour: '00', minute: '00' };

  public type = 'hour';

  public change = new Subject();

  private clockRadius = { height: 200, width: 200 };

  constructor( private wrapperDial: ElementRef, private wrapperDialMin: ElementRef, private renderer: Renderer2 ) {
  }

  createMinHourDial() {
    this.numbers = 12;
    this.minNumber = 0;
    this.divisor = 30;
    this.maxNumber = 12;
    this.type = 'minHour';
    this.setRelativeAngle();
    this.setClockStep();
    this.createNumbers();
    this.angle = this.getClockAngle( this.timeClock.hour );
  }

  createHourDial() {
    this.createMinHourDial();
    this.clearWrapper();
    this.numbers = 12;
    this.minNumber = 12;
    this.divisor = 30;
    this.maxNumber = 24;
    this.type = 'hour';
    this.setRelativeAngle();
    this.setClockStep();
    this.createNumbers();
    this.angle = this.getClockAngle( this.timeClock.hour );
  }

  createMinuteDial() {
    this.clearWrapper();
    this.clearWrapperMin();
    this.numbers = 60;
    this.minNumber = 0;
    this.maxNumber = 60;
    this.divisor = 6;
    this.type = 'minute';
    this.setRelativeAngle();
    this.setClockStep();
    this.createNumbers();
    this.angle = this.getClockAngle( this.timeClock.minute );
  }

  clearWrapper() {
    this.wrapperDial.nativeElement.innerHTML = '';
  }

  clearWrapperMin() {
    this.wrapperDialMin.nativeElement.innerHTML = '';
  }

  getDivisorAngle() {
    return this.divisor;
  }

  getAngleClock() {
    return this.angle;
  }

  setRelativeAngle() {
    this.relativeAngle = -90 * Math.PI / 180;
  }

  setClockStep() {
    this.step = (2 * Math.PI) / this.numbers;
  }

  createNumbers() {
    let hour = this.maxNumber;
    for ( let index = this.maxNumber; index > this.minNumber; index-- ) {
      this.createElementNumber();
      this.setElementNumberValue( hour );
      hour--;
      this.setRadiusNumber();
      this.setStylesNumber();
      this.listenClickNumber( index );
      this.appendElementNumber();
      this.relativeAngle -= this.step;
    }
  }

  createElementNumber() {
    this.elementNumber = new ElementRef( this.renderer.createElement( 'div' ) );
  }

  appendElementNumber() {
    if ( this.type === 'minHour' ) {
      this.renderer.appendChild( this.wrapperDialMin.nativeElement, this.elementNumber.nativeElement );
    } else {
      this.renderer.appendChild( this.wrapperDial.nativeElement, this.elementNumber.nativeElement );
    }
  }

  listenClickNumber( index: number ) {
    this.subscribe.add( this.renderer.listen( this.elementNumber.nativeElement, 'click', ( $event ) => {
      this.setAngleLineHour( index * this.divisor );
      this.change.next( this.timeClock );
    } ) );
  }

  setElementNumberValue( hour: number ) {
    const time = ((hour === 24) || (hour === 60)) ? 0 : hour;
    if ( this.type === 'minHour' ) {
      this.renderer.addClass( this.elementNumber.nativeElement, 'clock-number' );
      this.elementNumber.nativeElement.innerHTML = ('0' + time).slice( -2 );
    }
    if ( this.type === 'minute' && (hour % 5) === 0 ) {
      this.renderer.addClass( this.elementNumber.nativeElement, 'clock-number' );
      this.elementNumber.nativeElement.innerHTML = ('0' + time).slice( -2 );
    }
    if ( this.type === 'hour' ) {
      this.renderer.addClass( this.elementNumber.nativeElement, 'clock-number' );
      this.elementNumber.nativeElement.innerHTML = ('0' + time).slice( -2 );
    }
  }

  setRadiusNumber() {
    this.radius = Math.round( (this.clockRadius.width / 2) - (this.type !== 'minHour' ? 15 : 40) );
  }

  setStylesNumber() {
    this.renderer.setStyle( this.elementNumber.nativeElement, 'position', 'absolute' );
    this.renderer.setStyle( this.elementNumber.nativeElement, 'left', this.getAngleX() + 'px' );
    this.renderer.setStyle( this.elementNumber.nativeElement, 'top', this.getAngleY() + 'px' );
  }

  setAngleLineHour( angle: number ) {
    this.angle = angle;
    if ( this.type === 'minute' ) {
      this.divisor = 6;
      this.timeClock.minute = ('0' + angle / this.divisor).slice( -2 );
    } else {
      this.divisor = 30;
      this.timeClock.hour = ('0' + angle / this.divisor).slice( -2 );
    }
  }

  setTimeClock( value: string ) {
    value.length > 2 ? this.createMinuteDial() : this.createHourDial();
    if ( value.length === 2 ) {
      this.timeClock.hour = String( value.substring( 0, 2 ) );
      this.angle = this.getClockAngle( this.timeClock.hour );
    } else if ( value.length === 4 ) {
      this.timeClock.hour = String( value.substring( 0, 2 ) );
      this.timeClock.minute = String( value.substring( 2, 4 ) );
      this.angle = this.getClockAngle( this.timeClock.minute );
    }
  }

  closeClockPicker() {
    this.opened = false;
  }

  getTimeByAngle( angle ) {
    if ( this.type === 'hour' ) {
      const time = Math.floor( (12 * angle) / 360 ) + 12;
      this.timeClock.hour = time > 12 ? time + '' : '00';
      this.change.next( this.timeClock );
    } else {
      const time = Math.floor( (60 * angle) / 360 );
      this.timeClock.minute = ( '0' + time).slice( -2 );
      this.change.next( this.timeClock );
    }
  }

  getClockAngle( value ) {
    let radius = 12;
    if ( this.type === 'minute' ) {
      radius = 60;
    }
    return (parseInt( value, 10 ) / radius) * 360;
  }

  getClockPickerValue() {
    return this.timeClock;
  }

  openClockPicker() {
    this.opened = true;
  }

  getOpened() {
    return this.opened;
  }

  getAngleX() {
    return Math.round( this.radius * Math.cos( this.relativeAngle ) + (this.clockRadius.width / 2 ) );
  }

  getAngleY() {
    return Math.round( this.radius * Math.sin( this.relativeAngle ) + (this.clockRadius.height / 2 ) );
  }

  ngOnDestroy() {
    this.subscribe.unsubscribe();
  }

}


text:
package net.beaconcontroller.web.view.json;

import java.io.IOException;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;
import org.openflow.util.U16;

/**
 * @author David Erickson (derickso@cs.stanford.edu)
 *
 */
public class UnsignedShortJsonSerializer extends JsonSerializer<Short> {

    @Override
    public void serialize(Short value, JsonGenerator jgen,
            SerializerProvider provider) throws IOException,
            JsonProcessingException {
        jgen.writeNumber(U16.f(value));
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.deltadna.android.sdk.ads.exceptions;

import com.deltadna.android.sdk.Engagement;

public class EngagementFailureException extends Exception {

    public EngagementFailureException(Engagement engagement) {
        super(engagement.getError());
    }
}


text:
package registry

import (
	"context"
	"fmt"
	"strings"
	"testing"

	"github.com/apigee/registry/rpc"
	"github.com/apigee/registry/server/registry/test/seeder"
	"github.com/google/go-cmp/cmp"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/testing/protocmp"
)

var (
	// Example deployment api_spec_revision.
	deploymentApiSpecRevision = "/projects/p/apis/a/versions/v/specs/s@12345678"
)

func TestTagApiDeploymentRevision(t *testing.T) {
	ctx := context.Background()
	server := defaultTestServer(t)
	if err := seeder.SeedDeployments(ctx, server, &rpc.ApiDeployment{Name: "projects/my-project/locations/global/apis/my-api/deployments/d"}); err != nil {
		t.Fatalf("Setup/Seeding: Failed to seed registry: %s", err)
	}

	updateReq := &rpc.UpdateApiDeploymentRequest{
		ApiDeployment: &rpc.ApiDeployment{
			Name:            "projects/my-project/locations/global/apis/my-api/deployments/d",
			ApiSpecRevision: deploymentApiSpecRevision,
		},
	}

	revision, err := server.UpdateApiDeployment(ctx, updateReq)
	if err != nil {
		t.Fatalf("Setup: UpdateApiDeployment(%+v) returned error: %s", updateReq, err)
	}

	req := &rpc.TagApiDeploymentRevisionRequest{
		Name: fmt.Sprintf("%s@%s", revision.GetName(), revision.GetRevisionId()),
		Tag:  "my-tag",
	}

	got, err := server.TagApiDeploymentRevision(ctx, req)
	if err != nil {
		t.Fatalf("TagApiDeploymentRevision(%+v) returned error: %s", req, err)
	}

	opts := cmp.Options{
		protocmp.Transform(),
		protocmp.IgnoreFields(revision, "name"),
	}

	t.Run("response", func(t *testing.T) {
		if !cmp.Equal(revision, got, opts) {
			t.Errorf("TagApiDeploymentRevision(%+v) returned unexpected diff (-want +got):\n%s", req, cmp.Diff(revision, got, opts))
		}

		if want := fmt.Sprintf("%s@my-tag", revision.GetName()); want != got.GetName() {
			t.Errorf("TagApiDeploymentRevision(%+v) returned unexpected name %q, want %q", req, got.GetName(), want)
		}
	})

	t.Run("GetApiDeployment", func(t *testing.T) {
		req := &rpc.GetApiDeploymentRequest{
			Name: got.GetName(),
		}

		got, err := server.GetApiDeployment(ctx, req)
		if err != nil {
			t.Fatalf("GetApiDeployment(%+v) returned error: %s", req, err)
		}

		if !cmp.Equal(revision, got, opts) {
			t.Errorf("GetApiDeployment(%+v) returned unexpected diff (-want +got):\n%s", req, cmp.Diff(revision, got, opts))
		}

		if got.GetName() != req.GetName() {
			t.Errorf("GetApiDeployment(%+v) returned unexpected name %q, want %q", req, got.GetName(), req.GetName())
		}
	})

	t.Run("add another tag to a tagged revision", func(t *testing.T) {
		req := &rpc.TagApiDeploymentRevisionRequest{
			Name: got.GetName(),
			Tag:  "my-second-tag",
		}

		got, err := server.TagApiDeploymentRevision(ctx, req)
		if err != nil {
			t.Fatalf("TagApiDeploymentRevision(%+v) returned error: %s", req, err)
		}

		opts := cmp.Options{
			protocmp.Transform(),
			protocmp.IgnoreFields(revision, "name"),
		}

		if !cmp.Equal(revision, got, opts) {
			t.Errorf("TagApiDeploymentRevision(%+v) returned unexpected diff (-want +got):\n%s", req, cmp.Diff(revision, got, opts))
		}

		if want := fmt.Sprintf("%s@my-second-tag", revision.GetName()); want != got.GetName() {
			t.Errorf("TagApiDeploymentRevision(%+v) returned unexpected name %q, want %q", req, got.GetName(), want)
		}

		t.Run("GetApiDeployment", func(t *testing.T) {
			req := &rpc.GetApiDeploymentRequest{
				Name: got.GetName(),
			}

			got, err := server.GetApiDeployment(ctx, req)
			if err != nil {
				t.Fatalf("GetApiDeployment(%+v) returned error: %s", req, err)
			}

			if !cmp.Equal(revision, got, opts) {
				t.Errorf("GetApiDeployment(%+v) returned unexpected diff (-want +got):\n%s", req, cmp.Diff(revision, got, opts))
			}

			if got.GetName() != req.GetName() {
				t.Errorf("GetApiDeployment(%+v) returned unexpected name %q, want %q", req, got.GetName(), req.GetName())
			}
		})
	})

	t.Run("DeleteApiDeploymentRevision", func(t *testing.T) {
		req := &rpc.DeleteApiDeploymentRevisionRequest{
			Name: got.GetName(),
		}

		if _, err := server.DeleteApiDeploymentRevision(ctx, req); err != nil {
			t.Fatalf("DeleteApiDeploymentRevision(%+v) returned error: %s", req, err)
		}

		t.Run("GetApiDeployment", func(t *testing.T) {
			req := &rpc.GetApiDeploymentRequest{
				Name: req.GetName(),
			}

			if _, err := server.GetApiDeployment(ctx, req); status.Code(err) != codes.NotFound {
				t.Fatalf("GetApiDeployment(%+v) returned status code %q, want %q: %v", req, status.Code(err), codes.NotFound, err)
			}
		})
	})
}

func TestTagApiDeploymentRevisionResponseCodes(t *testing.T) {
	tests := []struct {
		desc string
		tag  string
		want codes.Code
	}{
		{
			desc: "contains uppercase leters",
			tag:  "TestTag",
			want: codes.InvalidArgument,
		},
		{
			desc: "single dash",
			tag:  "-",
			want: codes.InvalidArgument,
		},
		{
			desc: "valid one-character tag",
			tag:  "x",
			want: codes.OK,
		},
		{
			desc: "valid tag",
			tag:  "latest",
			want: codes.OK,
		},
	}

	for _, test := range tests {
		t.Run(test.desc, func(t *testing.T) {
			ctx := context.Background()
			server := defaultTestServer(t)
			if err := seeder.SeedDeployments(ctx, server, &rpc.ApiDeployment{Name: "projects/my-project/locations/global/apis/a/deployments/d"}); err != nil {
				t.Fatalf("Setup/Seeding: Failed to seed registry: %s", err)
			}
			if _, err := server.TagApiDeploymentRevision(ctx, &rpc.TagApiDeploymentRevisionRequest{
				Name: "projects/my-project/locations/global/apis/a/deployments/d",
				Tag:  test.tag,
			}); status.Code(err) != test.want {
				t.Errorf("TagApiDeploymentRevision(%+v) returned status code %q, want %q: %v", test.tag, status.Code(err), test.want, err)
			}
		})
	}
}

func TestRollbackApiDeployment(t *testing.T) {
	ctx := context.Background()
	server := defaultTestServer(t)
	if err := seeder.SeedApis(ctx, server, &rpc.Api{Name: "projects/my-project/locations/global/apis/my-api"}); err != nil {
		t.Fatalf("Setup/Seeding: Failed to seed registry: %s", err)
	}

	createReq := &rpc.CreateApiDeploymentRequest{
		Parent:          "projects/my-project/locations/global/apis/my-api",
		ApiDeploymentId: "d",
		ApiDeployment:   &rpc.ApiDeployment{},
	}

	firstRevision, err := server.CreateApiDeployment(ctx, createReq)
	if err != nil {
		t.Fatalf("Setup: CreateApiDeployment(%+v) returned error: %s", createReq, err)
	}

	// Create a new revision so we can roll back from it.
	updateReq := &rpc.UpdateApiDeploymentRequest{
		ApiDeployment: &rpc.ApiDeployment{
			Name:            firstRevision.GetName(),
			ApiSpecRevision: deploymentApiSpecRevision,
		},
	}

	secondRevision, err := server.UpdateApiDeployment(ctx, updateReq)
	if err != nil {
		t.Fatalf("Setup: UpdateApiDeployment(%+v) returned error: %s", updateReq, err)
	}

	if secondRevision.GetRevisionId() == firstRevision.GetRevisionId() {
		t.Fatalf("Setup: UpdateApiDeployment(%+v) returned unexpected revision_id %q matching first revision, expected new revision ID", updateReq, secondRevision.GetRevisionId())
	}

	req := &rpc.RollbackApiDeploymentRequest{
		Name:       secondRevision.GetName(),
		RevisionId: firstRevision.GetRevisionId(),
	}

	rollback, err := server.RollbackApiDeployment(ctx, req)
	if err != nil {
		t.Fatalf("RollbackApiDeployment(%+v) returned error: %s", req, err)
	}

	want := &rpc.ApiDeployment{
		Name:               fmt.Sprintf("%s@%s", firstRevision.GetName(), rollback.GetRevisionId()),
		ApiSpecRevision:    firstRevision.GetApiSpecRevision(),
		CreateTime:         firstRevision.GetCreateTime(),
		RevisionCreateTime: firstRevision.GetRevisionCreateTime(),
		RevisionUpdateTime: firstRevision.GetRevisionUpdateTime(),
	}

	opts := cmp.Options{
		protocmp.Transform(),
		protocmp.IgnoreFields(new(rpc.ApiDeployment), "revision_id", "revision_create_time", "revision_update_time"),
	}

	if !cmp.Equal(want, rollback, opts) {
		t.Errorf("RollbackApiDeployment(%+v) returned unexpected diff (-want +got):\n%s", req, cmp.Diff(want, rollback, opts))
	}

	// Rollback should create a new revision, i.e. it should not reuse an existing revision ID.
	if rollback.GetRevisionId() == firstRevision.GetRevisionId() {
		t.Fatalf("RollbackApiDeployment(%+v) returned unexpected revision_id %q matching first revision, expected new revision ID", req, rollback.GetRevisionId())
	} else if rollback.GetRevisionId() == secondRevision.GetRevisionId() {
		t.Fatalf("RollbackApiDeployment(%+v) returned unexpected revision_id %q matching second revision, expected new revision ID", req, rollback.GetRevisionId())
	}
}

func TestDeleteApiDeploymentRevision(t *testing.T) {
	ctx := context.Background()
	server := defaultTestServer(t)
	if err := seeder.SeedDeployments(ctx, server, &rpc.ApiDeployment{Name: "projects/my-project/locations/global/apis/my-api/deployments/d"}); err != nil {
		t.Fatalf("Setup/Seeding: Failed to seed registry: %s", err)
	}

	getReq := &rpc.GetApiDeploymentRequest{
		Name: "projects/my-project/locations/global/apis/my-api/deployments/d",
	}
	firstRevision, err := server.GetApiDeployment(ctx, getReq)
	if err != nil {
		t.Fatalf("Setup: GetApiSpecRequest(%+v) returned error: %s", getReq, err)
	}

	t.Run("only remaining revision", func(t *testing.T) {
		req := &rpc.DeleteApiDeploymentRevisionRequest{
			Name: fmt.Sprintf("projects/my-project/locations/global/apis/my-api/deployments/d@%s", firstRevision.GetRevisionId()),
		}

		if _, err := server.DeleteApiDeploymentRevision(ctx, req); status.Code(err) != codes.FailedPrecondition {
			t.Fatalf("DeleteApiDeploymentRevision(%+v) returned unexpected status code %q, want %q: %v", req, status.Code(err), codes.FailedPrecondition, err)
		}
	})

	// Create a new revision so we can delete it.
	updateReq := &rpc.UpdateApiDeploymentRequest{
		ApiDeployment: &rpc.ApiDeployment{
			Name:            "projects/my-project/locations/global/apis/my-api/deployments/d",
			ApiSpecRevision: deploymentApiSpecRevision,
		},
	}

	secondRevision, err := server.UpdateApiDeployment(ctx, updateReq)
	if err != nil {
		t.Fatalf("Setup: UpdateApiDeployment(%+v) returned error: %s", updateReq, err)
	}

	t.Run("one of multiple existing revisions", func(t *testing.T) {
		req := &rpc.DeleteApiDeploymentRevisionRequest{
			Name: fmt.Sprintf("projects/my-project/locations/global/apis/my-api/deployments/d@%s", secondRevision.GetRevisionId()),
		}

		if _, err := server.DeleteApiDeploymentRevision(ctx, req); err != nil {
			t.Fatalf("DeleteApiDeploymentRevision(%+v) returned error: %s", req, err)
		}

		t.Run("GetApiDeployment", func(t *testing.T) {
			req := &rpc.GetApiDeploymentRequest{
				Name: req.GetName(),
			}

			if _, err := server.GetApiDeployment(ctx, req); status.Code(err) != codes.NotFound {
				t.Fatalf("GetApiDeployment(%+v) returned status code %q, want %q: %v", req, status.Code(err), codes.NotFound, err)
			}
		})
	})
}

func TestListApiDeploymentRevisions(t *testing.T) {
	tests := []struct {
		admin     bool
		desc      string
		seed      []*rpc.ApiDeployment
		req       *rpc.ListApiDeploymentRevisionsRequest
		want      *rpc.ListApiDeploymentRevisionsResponse
		wantToken bool
	}{
		{
			desc: "single deployment latest rev",
			seed: []*rpc.ApiDeployment{
				{
					Name: "projects/my-project/locations/global/apis/my-api/deployments/my-dep",
				},
				{
					Name:        "projects/my-project/locations/global/apis/my-api/deployments/my-dep",
					EndpointUri: "updated",
				},
				{
					Name: "projects/my-project/locations/global/apis/my-api/deployments/other-dep",
				},
			},
			req: &rpc.ListApiDeploymentRevisionsRequest{
				Name: "projects/my-project/locations/global/apis/my-api/deployments/my-dep",
			},
			want: &rpc.ListApiDeploymentRevisionsResponse{
				ApiDeployments: []*rpc.ApiDeployment{
					{
						Name:        "projects/my-project/locations/global/apis/my-api/deployments/my-dep",
						EndpointUri: "updated",
					},
				},
			},
		},
		{
			desc: "single deployment all revs",
			seed: []*rpc.ApiDeployment{
				{
					Name: "projects/my-project/locations/global/apis/my-api/deployments/my-dep",
				},
				{
					Name:        "projects/my-project/locations/global/apis/my-api/deployments/my-dep",
					EndpointUri: "updated",
				},
				{
					Name: "projects/my-project/locations/global/apis/my-api/deployments/other-dep",
				},
			},
			req: &rpc.ListApiDeploymentRevisionsRequest{
				Name: "projects/my-project/locations/global/apis/my-api/deployments/my-dep@-",
			},
			want: &rpc.ListApiDeploymentRevisionsResponse{
				ApiDeployments: []*rpc.ApiDeployment{
					{
						Name:        "projects/my-project/locations/global/apis/my-api/deployments/my-dep",
						EndpointUri: "updated",
					},
					{
						Name: "projects/my-project/locations/global/apis/my-api/deployments/my-dep",
					},
				},
			},
		},
		{
			desc: "across multiple deployments all revs",
			seed: []*rpc.ApiDeployment{
				{Name: "projects/my-project/locations/global/apis/my-api/deployments/my-dep"},
				{Name: "projects/my-project/locations/global/apis/my-api/deployments/other-dep"},
			},
			req: &rpc.ListApiDeploymentRevisionsRequest{
				Name: "projects/my-project/locations/global/apis/my-api/deployments/-@-",
			},
			want: &rpc.ListApiDeploymentRevisionsResponse{
				ApiDeployments: []*rpc.ApiDeployment{
					{Name: "projects/my-project/locations/global/apis/my-api/deployments/my-dep"},
					{Name: "projects/my-project/locations/global/apis/my-api/deployments/other-dep"},
				},
			},
		},
		{
			desc: "across multiple apis all revs",
			seed: []*rpc.ApiDeployment{
				{Name: "projects/my-project/locations/global/apis/my-api/deployments/my-dep"},
				{Name: "projects/my-project/locations/global/apis/other-api/deployments/my-dep"},
			},
			req: &rpc.ListApiDeploymentRevisionsRequest{
				Name: "projects/my-project/locations/global/apis/-/deployments/my-dep@-",
			},
			want: &rpc.ListApiDeploymentRevisionsResponse{
				ApiDeployments: []*rpc.ApiDeployment{
					{Name: "projects/my-project/locations/global/apis/my-api/deployments/my-dep"},
					{Name: "projects/my-project/locations/global/apis/other-api/deployments/my-dep"},
				},
			},
		},
		{
			admin: true,
			desc:  "across multiple projects all revs",
			seed: []*rpc.ApiDeployment{
				{Name: "projects/my-project/locations/global/apis/my-api/deployments/my-dep"},
				{Name: "projects/other-project/locations/global/apis/my-api/deployments/my-dep"},
			},
			req: &rpc.ListApiDeploymentRevisionsRequest{
				Name: "projects/-/locations/global/apis/my-api/deployments/my-dep@-",
			},
			want: &rpc.ListApiDeploymentRevisionsResponse{
				ApiDeployments: []*rpc.ApiDeployment{
					{Name: "projects/my-project/locations/global/apis/my-api/deployments/my-dep"},
					{Name: "projects/other-project/locations/global/apis/my-api/deployments/my-dep"},
				},
			},
		},
		{
			desc: "custom page size, single spec all revs",
			seed: []*rpc.ApiDeployment{
				{
					Name: "projects/my-project/locations/global/apis/my-api/deployments/my-dep",
				},
				{
					Name:        "projects/my-project/locations/global/apis/my-api/deployments/my-dep",
					EndpointUri: "updated",
				},
			},
			req: &rpc.ListApiDeploymentRevisionsRequest{
				Name:     "projects/my-project/locations/global/apis/my-api/deployments/my-dep@-",
				PageSize: 1,
			},
			want: &rpc.ListApiDeploymentRevisionsResponse{
				ApiDeployments: []*rpc.ApiDeployment{
					{
						Name:        "projects/my-project/locations/global/apis/my-api/deployments/my-dep",
						EndpointUri: "updated",
					},
				},
			},
			wantToken: true,
		},
		{
			desc: "name filtering",
			seed: []*rpc.ApiDeployment{
				{Name: "projects/my-project/locations/global/apis/my-api/deployments/dep1"},
				{
					Name:        "projects/my-project/locations/global/apis/my-api/deployments/dep2",
					Description: "match",
				},
				{Name: "projects/my-project/locations/global/apis/my-api/deployments/dep3"},
			},
			req: &rpc.ListApiDeploymentRevisionsRequest{
				Name:   "projects/my-project/locations/global/apis/my-api/deployments/-@-",
				Filter: "description == 'match'",
			},
			want: &rpc.ListApiDeploymentRevisionsResponse{
				ApiDeployments: []*rpc.ApiDeployment{
					{
						Name:        "projects/my-project/locations/global/apis/my-api/deployments/dep2",
						Description: "match",
					},
				},
			},
		},
		{
			desc: "reverse order",
			seed: []*rpc.ApiDeployment{
				{Name: "projects/my-project/locations/global/apis/my-api/deployments/my-dep"},
				{Name: "projects/my-project/locations/global/apis/my-api/deployments/other-dep"},
			},
			req: &rpc.ListApiDeploymentRevisionsRequest{
				Name:    "projects/my-project/locations/global/apis/my-api/deployments/-@-",
				OrderBy: "name desc",
			},
			want: &rpc.ListApiDeploymentRevisionsResponse{
				ApiDeployments: []*rpc.ApiDeployment{
					{Name: "projects/my-project/locations/global/apis/my-api/deployments/other-dep"},
					{Name: "projects/my-project/locations/global/apis/my-api/deployments/my-dep"},
				},
			},
		},
	}

	for _, test := range tests {
		t.Run(test.desc, func(t *testing.T) {
			if test.admin && adminServiceUnavailable() {
				t.Skip(testRequiresAdminService)
			}
			ctx := context.Background()
			server := defaultTestServer(t)
			if err := seeder.SeedDeployments(ctx, server, test.seed...); err != nil {
				t.Fatalf("Setup/Seeding: Failed to seed registry: %s", err)
			}

			got, err := server.ListApiDeploymentRevisions(ctx, test.req)
			if err != nil {
				t.Fatalf("ListApiDeploymentRevisions(%+v) returned error: %s", test.req, err)
			}

			opts := cmp.Options{
				protocmp.Transform(),
				protocmp.IgnoreFields(new(rpc.ListApiDeploymentRevisionsResponse), "next_page_token"),
				protocmp.IgnoreFields(new(rpc.ApiDeployment), "name", "revision_id", "create_time", "revision_create_time", "revision_update_time"),
			}

			if !cmp.Equal(test.want, got, opts) {
				t.Errorf("ListApiDeploymentRevisions(%+v) returned unexpected diff (-want +got):\n%s", test.req, cmp.Diff(test.want, got, opts))
			}

			if test.wantToken && got.NextPageToken == "" {
				t.Errorf("ListApiDeploymentRevisions(%+v) returned empty next_page_token, expected non-empty next_page_token", test.req)
			} else if !test.wantToken && got.NextPageToken != "" {
				t.Errorf("ListApiDeploymentRevisions(%+v) returned non-empty next_page_token, expected empty next_page_token: %s", test.req, got.GetNextPageToken())
			}

			if len(got.ApiDeployments) != len(test.want.ApiDeployments) {
				t.Fatalf("ListApiDeploymentRevisions(%+v) returned unexpected number of revisions: got %d, want %d", test.req, len(got.ApiDeployments), len(test.want.ApiDeployments))
			}

			for i, got := range got.ApiDeployments {
				if want := test.want.ApiDeployments[i]; !strings.HasPrefix(got.GetName(), want.GetName()) {
					t.Errorf("ListApiDeploymentRevisions(%+v) returned unexpected revision: got %q, want %q", test.req, got.GetName(), want.GetName())
				}
			}
		})
	}
}

func TestListApiDeploymentRevisionsSequence(t *testing.T) {
	ctx := context.Background()
	server := defaultTestServer(t)
	if err := seeder.SeedApis(ctx, server, &rpc.Api{Name: "projects/my-project/locations/global/apis/my-api"}); err != nil {
		t.Fatalf("Setup/Seeding: Failed to seed registry: %s", err)
	}

	createReq := &rpc.CreateApiDeploymentRequest{
		Parent:          "projects/my-project/locations/global/apis/my-api",
		ApiDeploymentId: "d",
		ApiDeployment:   &rpc.ApiDeployment{},
	}

	firstRevision, err := server.CreateApiDeployment(ctx, createReq)
	if err != nil {
		t.Fatalf("Setup: CreateApiDeployment(%+v) returned error: %s", createReq, err)
	}

	firstWant := &rpc.ApiDeployment{
		Name:               fmt.Sprintf("%s@%s", firstRevision.GetName(), firstRevision.GetRevisionId()),
		CreateTime:         firstRevision.GetCreateTime(),
		RevisionCreateTime: firstRevision.GetRevisionCreateTime(),
		RevisionUpdateTime: firstRevision.GetRevisionUpdateTime(),
		RevisionId:         firstRevision.GetRevisionId(),
	}

	updateReq := &rpc.UpdateApiDeploymentRequest{
		ApiDeployment: &rpc.ApiDeployment{
			Name:            firstRevision.GetName(),
			ApiSpecRevision: deploymentApiSpecRevision,
		},
	}

	secondRevision, err := server.UpdateApiDeployment(ctx, updateReq)
	if err != nil {
		t.Fatalf("Setup: UpdateApiDeployment(%+v) returned error: %s", updateReq, err)
	}

	secondWant := &rpc.ApiDeployment{
		Name:               fmt.Sprintf("%s@%s", secondRevision.GetName(), secondRevision.GetRevisionId()),
		ApiSpecRevision:    deploymentApiSpecRevision,
		CreateTime:         secondRevision.GetCreateTime(),
		RevisionCreateTime: secondRevision.GetRevisionCreateTime(),
		RevisionUpdateTime: secondRevision.GetRevisionUpdateTime(),
		RevisionId:         secondRevision.GetRevisionId(),
	}

	opts := cmp.Options{
		protocmp.Transform(),
	}

	var nextToken string
	t.Run("first page", func(t *testing.T) {
		req := &rpc.ListApiDeploymentRevisionsRequest{
			Name:     firstRevision.GetName() + "@-",
			PageSize: 1,
		}

		got, err := server.ListApiDeploymentRevisions(ctx, req)
		if err != nil {
			t.Fatalf("ListApiDeploymentRevisions(%+v) returned error: %s", req, err)
		}

		if count := len(got.GetApiDeployments()); count != 1 {
			t.Errorf("ListApiDeploymentRevisions(%+v) returned %d specs, expected exactly one", req, count)
		}

		// Check that the most recent revision is returned.
		want := []*rpc.ApiDeployment{secondWant}
		if !cmp.Equal(want, got.GetApiDeployments(), opts) {
			t.Errorf("List sequence returned unexpected diff (-want +got):\n%s", cmp.Diff(want, got.GetApiDeployments(), opts))
		}

		if got.GetNextPageToken() == "" {
			t.Errorf("ListApiDeploymentRevisions(%+v) returned empty next_page_token, expected another page", req)
		}

		nextToken = got.GetNextPageToken()
	})

	if t.Failed() {
		t.Fatal("Cannot test final page after failure on first page")
	}

	t.Run("final page", func(t *testing.T) {
		req := &rpc.ListApiDeploymentRevisionsRequest{
			Name:      firstRevision.GetName() + "@-",
			PageToken: nextToken,
		}

		got, err := server.ListApiDeploymentRevisions(ctx, req)
		if err != nil {
			t.Fatalf("ListApiDeploymentRevisions(%+v) returned error: %s", req, err)
		}

		if count := len(got.GetApiDeployments()); count != 1 {
			t.Errorf("ListApiDeploymentRevisions(%+v) returned %d specs, expected exactly one", req, count)
		}

		// Check that the original revision is returned.
		want := []*rpc.ApiDeployment{firstWant}
		if !cmp.Equal(want, got.GetApiDeployments(), opts) {
			t.Errorf("List sequence returned unexpected diff (-want +got):\n%s", cmp.Diff(want, got.GetApiDeployments(), opts))
		}

		if got.GetNextPageToken() != "" {
			t.Errorf("ListApiDeploymentRevisions(%+v) returned next_page_token, expected no next page", req)
		}
	})
}

func TestUpdateApiDeploymentRevisions(t *testing.T) {
	ctx := context.Background()
	server := defaultTestServer(t)
	if err := seeder.SeedApis(ctx, server, &rpc.Api{Name: "projects/my-project/locations/global/apis/my-api"}); err != nil {
		t.Fatalf("Setup/Seeding: Failed to seed registry: %s", err)
	}

	createReq := &rpc.CreateApiDeploymentRequest{
		Parent:          "projects/my-project/locations/global/apis/my-api",
		ApiDeploymentId: "my-spec",
		ApiDeployment: &rpc.ApiDeployment{
			Description: "Empty First Revision",
		},
	}

	created, err := server.CreateApiDeployment(ctx, createReq)
	if err != nil {
		t.Fatalf("Setup: CreateApiDeployment(%+v) returned error: %s", createReq, err)
	}

	opts := cmp.Options{
		protocmp.Transform(),
		protocmp.IgnoreFields(new(rpc.ApiDeployment), "revision_id", "create_time", "revision_create_time", "revision_update_time"),
	}

	t.Run("modify revision without content changes", func(t *testing.T) {
		req := &rpc.UpdateApiDeploymentRequest{
			ApiDeployment: &rpc.ApiDeployment{
				Name: created.GetName(),
			},
		}

		got, err := server.UpdateApiDeployment(ctx, req)
		if err != nil {
			t.Fatalf("UpdateApiDeployment(%+v) returned error: %s", req, err)
		}

		if got.GetRevisionId() != created.GetRevisionId() {
			t.Errorf("UpdateApiDeployment(%+v) returned unexpected revision_id %q, expected no change (%q)", req, got.GetRevisionId(), created.GetRevisionId())
		}

		if ct, ut := got.GetRevisionCreateTime().AsTime(), got.GetRevisionUpdateTime().AsTime(); !ct.Before(ut) {
			t.Errorf("UpdateApiDeployment(%+v) returned unexpected timestamps, expected revision_update_time %v > revision_create_time %v", req, ut, ct)
		}
	})

	t.Run("modify revision with api_spec_revision changes", func(t *testing.T) {
		req := &rpc.UpdateApiDeploymentRequest{
			ApiDeployment: &rpc.ApiDeployment{
				Name:            created.GetName(),
				ApiSpecRevision: deploymentApiSpecRevision,
			},
		}
		want := proto.Clone(created).(*rpc.ApiDeployment)
		want.ApiSpecRevision = req.GetApiDeployment().GetApiSpecRevision()

		got, err := server.UpdateApiDeployment(ctx, req)
		if err != nil {
			t.Fatalf("UpdateApiDeployment(%+v) returned error: %s", req, err)
		}

		if !cmp.Equal(want, got, opts) {
			t.Errorf("UpdateApiDeployment(%+v) returned unexpected diff (-want +got):\n%s", req, cmp.Diff(want, got, opts))
		}

		if got.GetRevisionId() == created.GetRevisionId() {
			t.Errorf("UpdateApiDeployment(%+v) returned unexpected revision_id %q, expected new revision", req, got.GetRevisionId())
		}

		if ct, ut := got.GetCreateTime().AsTime(), got.GetRevisionUpdateTime().AsTime(); !ct.Before(ut) {
			t.Errorf("UpdateApiDeployment(%+v) returned unexpected timestamps, expected revision_update_time %v > create_time %v", req, ut, ct)
		}
	})

	t.Run("modify specific revision", func(t *testing.T) {
		req := &rpc.UpdateApiDeploymentRequest{
			ApiDeployment: &rpc.ApiDeployment{
				Name: fmt.Sprintf("%s@%s", created.GetName(), created.GetRevisionId()),
			},
		}

		if _, err := server.UpdateApiDeployment(ctx, req); status.Code(err) != codes.InvalidArgument {
			t.Fatalf("UpdateApiDeployment(%+v) returned unexpected status code %q, want %q: %v", req, status.Code(err), codes.InvalidArgument, err)
		}
	})
}


text:
pub enum AffineCipherError {
    NotCoprime(i32),
}

/// Encodes the plaintext using the affine cipher with key (`a`, `b`). Note that, rather than
/// returning a return code, the more common convention in Rust is to return a `Result`.
pub fn encode(plaintext: &str, a: i32, b: i32) -> Result<String, AffineCipherError> {
    unimplemented!("Encode {} with the key ({}, {})", plaintext, a, b);
}

/// Decodes the ciphertext using the affine cipher with key (`a`, `b`). Note that, rather than
/// returning a return code, the more common convention in Rust is to return a `Result`.
pub fn decode(ciphertext: &str, a: i32, b: i32) -> Result<String, AffineCipherError> {
    unimplemented!("Decode {} with the key ({}, {})", ciphertext, a, b);
}


text:
"""
The EditraBaseStc is the base StyledTextCtrl that provides automatic styling and
syntax highlighting of all supported filetypes.

@summary: Editra's base styled text ctrl.

"""

__author__ = "Cody Precord <cprecord@editra.org>"
__svnid__ = "$Id: ed_basestc.py 73711 2013-03-23 14:19:01Z CJP $"
__revision__ = "$Revision: 73711 $"

#-----------------------------------------------------------------------------#
# Imports
import wx
import wx.stc

# Editra Imports
import ed_glob
import ed_style
import eclib
import ebmlib
import ed_msg
import ed_txt
from syntax import syntax
from syntax import synglob
import autocomp
from extern import vertedit
from profiler import Profile_Get
import plugin
import iface
import util
import ed_marker

#-----------------------------------------------------------------------------#

# Margins
MARK_MARGIN = 0
NUM_MARGIN  = 1
FOLD_MARGIN = 2

# Markers (3rd party)
MARKER_VERT_EDIT = ed_marker.NewMarkerId()

# Key code additions
ALT_SHIFT = wx.stc.STC_SCMOD_ALT|wx.stc.STC_SCMOD_SHIFT
CTRL_SHIFT = wx.stc.STC_SCMOD_CTRL|wx.stc.STC_SCMOD_SHIFT

#-----------------------------------------------------------------------------#

class EditraBaseStc(wx.stc.StyledTextCtrl, ed_style.StyleMgr):
    """Base StyledTextCtrl that provides all the base code editing
    functionality.

    """
    ED_STC_MASK_MARKERS = ~wx.stc.STC_MASK_FOLDERS
    def __init__(self, parent, id_=wx.ID_ANY,
                 pos=wx.DefaultPosition, size=wx.DefaultSize, style=0):
        wx.stc.StyledTextCtrl.__init__(self, parent, id_, pos, size, style)
        ed_style.StyleMgr.__init__(self, self.GetStyleSheet())

        # Attributes
        self.file = ed_txt.EdFile()
        self._code = dict(compsvc=autocomp.AutoCompService.GetCompleter(self),
                          synmgr=syntax.SyntaxMgr(ed_glob.CONFIG['CACHE_DIR']),
                          keywords=[ ' ' ],
                          comment=list(),
                          clexer=None,      # Container lexer method
                          indenter=None,    # Auto indenter
                          lang_id=0)        # Language ID from syntax module

        self.vert_edit = vertedit.VertEdit(self, markerNumber=MARKER_VERT_EDIT)
        self._line_num = True # Show line numbers
        self._last_cwidth = 1 # one pixel

        # Set Up Margins
        ## Outer Left Margin Bookmarks
        self.SetMarginType(MARK_MARGIN, wx.stc.STC_MARGIN_SYMBOL)
        self.SetMarginMask(MARK_MARGIN, EditraBaseStc.ED_STC_MASK_MARKERS)
        self.SetMarginSensitive(MARK_MARGIN, True)
        self.SetMarginWidth(MARK_MARGIN, 16)

        ## Middle Left Margin Line Number Indication
        self.SetMarginType(NUM_MARGIN, wx.stc.STC_MARGIN_NUMBER)
        self.SetMarginMask(NUM_MARGIN, 0)

        ## Inner Left Margin Setup Folders
        self.SetMarginType(FOLD_MARGIN, wx.stc.STC_MARGIN_SYMBOL)
        self.SetMarginMask(FOLD_MARGIN, wx.stc.STC_MASK_FOLDERS)
        self.SetMarginSensitive(FOLD_MARGIN, True)

        # Set Mac specific keybindings
        if wx.Platform == '__WXMAC__':
            for keys in _GetMacKeyBindings():
                self.CmdKeyAssign(*keys)

        # Set default EOL format
        if wx.Platform != '__WXMSW__':
            self.SetEOLMode(wx.stc.STC_EOL_LF)

        # Setup Auto-comp images
        # TODO: should be called on theme change messages
        self.RegisterImages()

        # Event Handlers
        self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy, self)
        self.Bind(wx.stc.EVT_STC_CHANGE, self.OnChanged)
        self.Bind(wx.stc.EVT_STC_MODIFIED, self.OnModified)
        self.Bind(wx.stc.EVT_STC_AUTOCOMP_SELECTION, self.OnAutoCompSel)

    def OnDestroy(self, evt):
        if evt.GetId() == self.GetId():
            # Cleanup the file object callbacks
            self.file.RemoveModifiedCallback(self.FireModified)
            self.file.CleanUp()
        evt.Skip()

    #---- Public Methods ----#

    # General marker api
    def AddMarker(self, marker, line=-1):
        """Add a bookmark and return its handle
        @param marker: ed_marker.Marker instance
        @keyword line: if < 0 bookmark will be added to current line

        """
        assert isinstance(marker, ed_marker.Marker)
        if line < 0:
            line = self.GetCurrentLine()
        marker.Set(self, line)
        return marker.Handle

    def RemoveMarker(self, marker, line):
        """Remove the book mark from the given line
        @param marker: ed_marker.Marker instance
        @param line: int

        """
        assert isinstance(marker, ed_marker.Marker)
        marker.Set(self, line, delete=True)

    def RemoveAllMarkers(self, marker):
        """Remove all the bookmarks in the buffer
        @param marker: ed_marker.Marker instance

        """
        assert isinstance(marker, ed_marker.Marker)
        marker.DeleteAll(self)

    #-- Breakpoint marker api --#
    def DeleteAllBreakpoints(self):
        """Delete all the breakpoints in the buffer"""
        ed_marker.Breakpoint().DeleteAll(self)
        ed_marker.BreakpointDisabled().DeleteAll(self)
        ed_marker.BreakpointStep().DeleteAll(self)

    def DeleteBreakpoint(self, line):
        """Delete the breakpoint from the given line"""
        ed_marker.Breakpoint().Set(self, line, delete=True)
        ed_marker.BreakpointDisabled().Set(self, line, delete=True)

    def _SetBreakpoint(self, mobj, line=-1):
        """Set the breakpoint state
        @param mtype: Marker object
        @return: int (-1 if already set)

        """
        handle = -1
        if line < 0:
            line = self.GetCurrentLine()
        if not mobj.IsSet(self, line):
            # Clear other set breakpoint marker states on same line
            ed_marker.Breakpoint().Set(self, line, delete=True)
            ed_marker.BreakpointDisabled().Set(self, line, delete=True)
            mobj.Set(self, line, delete=False)
            handle = mobj.Handle
        return handle

    def SetBreakpoint(self, line=-1, disabled=False):
        """Set a breakpoint marker on the given line
        @keyword line: line number
        @keyword disabled: bool
        @return: breakpoint handle

        """
        if not disabled:
            handle = self._SetBreakpoint(ed_marker.Breakpoint(), line)
        else:
            handle = self._SetBreakpoint(ed_marker.BreakpointDisabled(), line)
        return handle

    def ShowStepMarker(self, line=-1, show=True):
        """Show the step (arrow) marker to the given line."""
        if line < 0:
            line = self.GetCurrentLine()
        mark = ed_marker.BreakpointStep()
        if show:
            mark.Set(self, line, delete=False)
        else:
            mark.DeleteAll(self)

    def AddLine(self, before=False, indent=False):
        """Add a new line to the document
        @keyword before: whether to add the line before current pos or not
        @keyword indent: autoindent the new line
        @postcondition: a new line is added to the document

        """
        if before:
            self.LineUp()

        self.LineEnd()

        if indent:
            self.AutoIndent()
        else:
            self.InsertText(self.GetCurrentPos(), self.GetEOLChar())
            self.LineDown()

    def AutoIndent(self):
        """Indent from the current position to match the indentation
        of the previous line. Unless the current file type has registered
        a custom AutoIndenter in which case it will implement its own
        behavior.

        """
        cpos = self.GetCurrentPos()

        # Check if a special purpose indenter has been registered
        if self._code['indenter'] is not None:
            self.BeginUndoAction()
            self._code['indenter'](self, cpos, self.GetIndentChar())
            self.EndUndoAction()
        else:
            # Default Indenter
            line = self.GetCurrentLine()
            text = self.GetTextRange(self.PositionFromLine(line), cpos)
            if text.strip() == u'':
                self.AddText(self.GetEOLChar() + text)
                self.EnsureCaretVisible()
                return
            indent = self.GetLineIndentation(line)
            i_space = indent / self.GetTabWidth()
            ndent = self.GetEOLChar() + self.GetIndentChar() * i_space
            txt = ndent + ((indent - (self.GetTabWidth() * i_space)) * u' ')
            self.AddText(txt)

        self.EnsureCaretVisible()

    def BackTab(self):
        """Unindent or remove excess whitespace to left of cursor"""
        sel = self.GetSelection()
        if sel[0] == sel[1]:
            # There is no selection
            cpos = self.GetCurrentPos()
            cline = self.GetCurrentLine()
            cipos = self.GetLineIndentPosition(cline)
            if cpos <= cipos:
                # In indentation so simply backtab
                super(EditraBaseStc, self).BackTab()
            else:
                # In middle of line somewhere
                text = self.GetLine(cline)
                column = max(0, self.GetColumn(cpos) - 1)
                if len(text) > column and text[column].isspace():

                    # Find the end of the whitespace
                    end = column
                    while end < len(text) and \
                          text[end].isspace() and \
                          text[end] not in '\r\n':
                        end += 1

                    # Find the start of the whitespace
                    end -= 1
                    start = end
                    while end > 0 and text[start].isspace():
                        start -= 1

                    diff = end - start
                    if diff > 1:
                        # There is space to compress
                        isize = self.GetIndent()
                        if isize < diff:
                            # More space than indent to remove
                            repeat = isize
                        else:
                            # Less than one indent width to remove
                            repeat = end - (start + 1)

                        # Update the control
                        self.BeginUndoAction()
                        self.SetCurrentPos(cpos + (end - column))
                        for x in range(repeat):
                            self.DeleteBack()
                        self.EndUndoAction()

        else:
            # There is a selection
            super(EditraBaseStc, self).BackTab()

    def SetBlockCaret(self):
        """Change caret style to block"""
        if hasattr(self, 'SetCaretStyle'): # wxPython 2.9 or greater
            self.SetCaretStyle(wx.stc.STC_CARETSTYLE_BLOCK)
        else:
            # Alternatively, just make the caret a bit thicker!
            # best we can do on 2.8
            self.SetCaretWidth(3)

    def SetLineCaret(self):
        """Change caret style to line"""
        if hasattr(self, 'SetCaretStyle'):
            self.SetCaretStyle(wx.stc.STC_CARETSTYLE_LINE)
        else:
            pwidth = Profile_Get('CARETWIDTH', default=1)
            self.SetCaretWidth(pwidth)

    def BraceBadLight(self, pos):
        """Highlight the character at the given position
        @param pos: position of character to highlight with STC_STYLE_BRACEBAD

        """
        # Check if we are still alive or not, as this may be called
        # after we have been deleted.
        if self:
            super(EditraBaseStc, self).BraceBadLight(pos)

    def BraceHighlight(self, pos1, pos2):
        """Highlight characters at pos1 and pos2
        @param pos1: position of char 1
        @param pos2: position of char 2

        """
        # Check if we are still alive or not, as this may be called
        # after we have been deleted.
        if self:
            super(EditraBaseStc, self).BraceHighlight(pos1, pos2)

    def CanCopy(self):
        """Check if copy/cut is possible"""
        return self.HasSelection()

    CanCut = CanCopy

    def Comment(self, start, end, uncomment=False):
        """(Un)Comments a line or a selected block of text
        in a document.
        @param start: beginning line (int)
        @param end: end line (int)
        @keyword uncomment: uncomment selection

        """
        if len(self._code['comment']):
            sel = self.GetSelection()
            c_start = self._code['comment'][0]
            c_end = u''
            if len(self._code['comment']) > 1:
                c_end = self._code['comment'][1]

            # Modify the selected line(s)
            self.BeginUndoAction()
            try:
                nchars = 0
                lines = range(start, end+1)
                lines.reverse()
                for line_num in lines:
                    lstart = self.PositionFromLine(line_num)
                    lend = self.GetLineEndPosition(line_num)
                    text = self.GetTextRange(lstart, lend)
                    tmp = text.strip()
                    if len(tmp):
                        if uncomment:
                            if tmp.startswith(c_start):
                                text = text.replace(c_start, u'', 1)
                            if c_end and tmp.endswith(c_end):
                                text = text.replace(c_end, u'', 1)
                            nchars = nchars - len(c_start + c_end)
                        else:
                            text = c_start + text + c_end
                            nchars = nchars + len(c_start + c_end)

                        self.SetTargetStart(lstart)
                        self.SetTargetEnd(lend)
                        self.ReplaceTarget(text)
            finally:
                self.EndUndoAction()
                if sel[0] != sel[1]:
                    self.SetSelection(sel[0], sel[1] + nchars)
                else:
                    if len(self._code['comment']) > 1:
                        nchars = nchars - len(self._code['comment'][1])
                    self.GotoPos(sel[0] + nchars)

    def ConfigureAutoComp(self):
        """Sets up the Autocompleter, the autocompleter
        configuration depends on the currently set lexer
        @postcondition: autocomp is configured

        """
        self.AutoCompSetAutoHide(False)
        self.InitCompleter()
        self.AutoCompSetChooseSingle(self._code['compsvc'].GetChooseSingle())
        self.AutoCompSetIgnoreCase(not self._code['compsvc'].GetCaseSensitive())
        self.AutoCompStops(self._code['compsvc'].GetAutoCompStops())
        # TODO: come back to this it can cause some annoying behavior where
        #       it automatically completes strings that you don't want to be
        #       inserted in the buffer. (i.e typing self._value will bring up
        #       the autocomp list but if self._value is not in the list and you
        #       hit space it will automatically insert something from the list.)
#        self.AutoCompSetFillUps(self._code['compsvc'].GetAutoCompFillups())

    def ConfigureLexer(self, file_ext):
        """Sets Lexer and Lexer Keywords for the specified file extension
        @param file_ext: a file extension to configure the lexer from

        """
        syn_data = self._code['synmgr'].GetSyntaxData(file_ext)

        # Set the ID of the selected lexer
        self._code['lang_id'] = syn_data.LangId

        lexer = syn_data.Lexer
        # Check for special cases
        # TODO: add fetch method to check if container lexer requires extra
        #       style bytes beyond the default 5.
        if lexer in [ wx.stc.STC_LEX_HTML, wx.stc.STC_LEX_XML]:
            self.SetStyleBits(7)
        elif lexer == wx.stc.STC_LEX_NULL:
            self.SetStyleBits(5)
            self.SetLexer(lexer)
            self.ClearDocumentStyle()
            self.UpdateBaseStyles()
            return True
        else:
            self.SetStyleBits(5)

        # Set Lexer
        self.SetLexer(lexer)
        # Set Keywords
        self.SetKeyWords(syn_data.Keywords)
        # Set Lexer/Syntax Specifications
        self.SetSyntax(syn_data.SyntaxSpec)
        # Set Extra Properties
        self.SetProperties(syn_data.Properties)
        # Set Comment Pattern
        self._code['comment'] = syn_data.CommentPattern

        # Get Extension Features
        clexer = syn_data.GetFeature(synglob.FEATURE_STYLETEXT)
        indenter = syn_data.GetFeature(synglob.FEATURE_AUTOINDENT)

        # Set the Container Lexer Method
        self._code['clexer'] = clexer
        # Auto-indenter function
        self._code['indenter'] = indenter

    def DefineMarkers(self):
        """Defines the folder and bookmark icons for this control
        @postcondition: all margin markers are defined

        """
        # Get the colours for the various markers
        style = self.GetItemByName('foldmargin_style')
        back = style.GetFore()
        rgb = eclib.HexToRGB(back[1:])
        back = wx.Colour(red=rgb[0], green=rgb[1], blue=rgb[2])

        fore = style.GetBack()
        rgb = eclib.HexToRGB(fore[1:])
        fore = wx.Colour(red=rgb[0], green=rgb[1], blue=rgb[2])

        # Buffer background highlight
        caret_line = self.GetItemByName('caret_line').GetBack()
        rgb = eclib.HexToRGB(caret_line[1:])
        clback = wx.Colour(*rgb)

        # Code Folding markers
        folder = ed_marker.FoldMarker()
        folder.Foreground = fore
        folder.Background = back
        folder.RegisterWithStc(self)

        # Bookmarks
        ed_marker.Bookmark().RegisterWithStc(self)

        # Breakpoints
        ed_marker.Breakpoint().RegisterWithStc(self)
        ed_marker.BreakpointDisabled().RegisterWithStc(self)
        step = ed_marker.BreakpointStep()
        step.Background = clback
        step.RegisterWithStc(self)
        ed_marker.StackMarker().RegisterWithStc(self)

        # Other markers
        errmk = ed_marker.ErrorMarker()
        errsty = self.GetItemByName('error_style')
        rgb = eclib.HexToRGB(errsty.GetBack()[1:])
        errmk.Background = wx.Colour(*rgb)
        rgb = eclib.HexToRGB(errsty.GetFore()[1:])
        errmk.Foreground = wx.Colour(*rgb)
        errmk.RegisterWithStc(self)
        # Lint Marker
        ed_marker.LintMarker().RegisterWithStc(self)
        ed_marker.LintMarkerWarning().RegisterWithStc(self)
        ed_marker.LintMarkerError().RegisterWithStc(self)

    def DoZoom(self, mode):
        """Zoom control in or out
        @param mode: either zoom in or out

        """
        id_type = mode
        zoomlevel = self.GetZoom()
        if id_type == ed_glob.ID_ZOOM_OUT:
            if zoomlevel > -9:
                self.ZoomOut()
        elif id_type == ed_glob.ID_ZOOM_IN:
            if zoomlevel < 19:
                self.ZoomIn()
        else:
            self.SetZoom(0)
        return self.GetZoom()

    def EnableLineNumbers(self, enable=True):
        """Enable/Disable line number margin
        @keyword enable: bool

        """
        if enable:
            self.SetMarginWidth(NUM_MARGIN, 30)
        else:
            self.SetMarginWidth(NUM_MARGIN, 0)
        self._line_num = enable

    def FindChar(self, char, repeat=1, reverse=False, extra_offset=0):
        """Find the position of the next (ith) 'char' character
        on the current line and move caret to it

        @note: used by vim motions for finding a character on a line (f,F,t,T)
        @param char: the character to be found
        @keyword repeat: how many times to repeat the search
        @keyword reverse: whether to search backwards
        @keyword extra_offset: extra offset to be applied to the movement

        """
        text, pos = self.GetCurLine()
        oldpos = pos
        if not reverse:
            # search forward
            for i in range(repeat):
                pos = text.find(char, pos+1)
                if pos == -1:
                    return
        else:
            # search backward
            for i in range(repeat):
                pos = text.rfind(char, 0, pos)
                if pos == -1:
                    return

        newpos = pos + extra_offset
        if newpos in range(len(text)):
            self.MoveCaretPos(newpos - oldpos)

    @property
    def File(self):
        """Reference to this buffers file object"""
        return self.file

    def FindLexer(self, set_ext=u''):
        """Sets Text Controls Lexer Based on File Extension
        @param set_ext: explicit extension to use in search
        @postcondition: lexer is configured for file

        """
        if set_ext != u'':
            ext = set_ext.lower()
        else:
            ext = self.file.GetExtension().lower()

        if ext == u'':
            fname = self.GetFileName()
            ext = ebmlib.GetFileName(fname).lower()

        self.ClearDocumentStyle()

        # Configure Lexer from File Extension
        self.ConfigureLexer(ext)

        # If syntax auto detection fails from file extension try to
        # see if there is an interpreter line that can be parsed.
        if self.GetLexer() == wx.stc.STC_LEX_NULL:
            interp = self.GetLine(0)
            if interp != wx.EmptyString:
                interp = interp.split(u"/")[-1]
                interp = interp.strip().split()
                if len(interp) and interp[-1][0] != u"-":
                    interp = interp[-1]
                elif len(interp):
                    interp = interp[0]
                else:
                    interp = u''
                # TODO: should check user config to ensure the explict
                #       extension is still associated with the expected
                #       file type.
                ex_map = { "python" : "py", "wish" : "tcl", "ruby" : "rb",
                           "bash" : "sh", "csh" : "csh", "perl" : "pl",
                           "ksh" : "ksh", "php" : "php", "booi" : "boo",
                           "pike" : "pike"}
                self.ConfigureLexer(ex_map.get(interp, interp))
        self.Colourise(0, -1)

    def FireModified(self):
        """Fire a modified event"""
        self.OnChanged(wx.stc.StyledTextEvent(wx.stc.wxEVT_STC_CHANGE,
                                              self.GetId()))

    def GetCommandStr(self, line=None, col=None):
        """Gets the command string to the left of the autocomp
        activation character.
        @keyword line: optional if None current cursor position used
        @keyword col: optional if None current cursor position used
        @return: the command string to the left of the autocomp char

        """
        if None in (line, col):
            # NOTE: the column position returned by GetCurLine is not correct
            #       for multibyte characters.
            line, col = self.GetCurLine()
            col = self.GetColumn(self.GetCurrentPos())
        cmd = self._code['compsvc'].GetCommandString(self, line, col)
        return cmd

    def GetCommentChars(self):
        """Return the list of characters used to comment a string in the
        current language.
        @return: list of strings

        """
        return self._code['comment']

    def GetCompleter(self):
        """Get this buffers completer object
        @return: Completer

        """
        return self._code['compsvc']

    def GetDocument(self):
        """Return a reference to the document object represented in this buffer.
        @return: EdFile
        @see: L{ed_txt.EdFile}

        """
        return self.file

    def GetEOLChar(self):
        """Gets the eol character used in document
        @return: the character used for eol in this document

        """
        m_id = self.GetEOLMode()
        if m_id == wx.stc.STC_EOL_CR:
            return u'\r'
        elif m_id == wx.stc.STC_EOL_CRLF:
            return u'\r\n'
        else:
            return u'\n'

    def GetFileName(self):
        """Returns the full path name of the current file
        @return: full path name of document

        """
        return self.file.GetPath()

    def GetIndentChar(self):
        """Gets the indentation char used in document
        @return: indentation char used either space or tab

        """
        if self.GetUseTabs():
            return u'\t'
        else:
            return u' ' * self.GetIndent()

    def GetKeywords(self):
        """Get the keyword set for the current document.
        @return: list of strings

        """
        return self._code['keywords']

    def GetLangId(self):
        """Returns the language identifier of this control
        @return: language identifier of document

        """
        return self._code['lang_id']

    def GetModTime(self):
        """Get the value of the buffers file last modtime"""
        return self.file.ModTime

    def GetPos(self):
        """Update Line/Column information
        @return: tuple (line, column)

        """
        return (self.GetCurrentLine() + 1, self.GetColumn(self.GetCurrentPos()))

    GetRange = wx.stc.StyledTextCtrl.GetTextRange

    def GetWordFromPosition(self, pos):
        """Get the word at the given position
        @param pos: int
        @return: (string, int_start, int_end)

        """
        end = self.WordEndPosition(pos, True)
        start = self.WordStartPosition(pos, True)
        word = self.GetTextRange(start, end)
        return (word, start, end)

    def IsColumnMode(self):
        """Is the buffer in column edit mode
        @return: bool

        """
        return self.VertEdit.Enabled

    def IsComment(self, pos):
        """Is the given position in a comment region of the current buffer
        @param pos: int position in buffer
        @return: bool

        """
        pos = max(0, pos-1)
        return 'comment' in self.FindTagById(self.GetStyleAt(pos))

    def IsString(self, pos):
        """Is the given position in a string region of the current buffer
        @param pos: int position in buffer
        @return: bool

        """
        style = self.GetStyleAt(pos)
        return self.FindTagById(style) in ('string_style', 'char_style')

    def IsNonCode(self, pos):
        """Is the passed in position in a non code region
        @param pos: buffer position
        @return: bool

        """
        return self.IsComment(pos) or self.IsString(pos)

    def HasMarker(self, line, marker):
        """Check if the given line has the given marker set
        @param line: line number
        @param marker: marker id

        """
        mask = self.MarkerGet(line)
        return bool(1<<marker & mask)

    def HasSelection(self):
        """Check if there is a selection in the buffer
        @return: bool

        """
        sel = super(EditraBaseStc, self).GetSelection()
        return sel[0] != sel[1]

    def HasMultilineSelection(self):
        """Is the selection over multiple lines?
        @return: bool

        """
        bMulti = False
        sel = super(EditraBaseStc, self).GetSelection()
        if sel[0] != sel[1]:
            sline = self.LineFromPosition(sel[0])
            eline = self.LineFromPosition(sel[1])
            bMulti = sline != eline
        return bMulti

    def CallTipCancel(self):
        """Cancel any active calltip(s)"""
        if self.CallTipActive():
            super(EditraBaseStc, self).CallTipCancel()

    def CallTipShow(self, position, tip):
        """Show a calltip at the given position in the control
        @param position: int
        @param tip: unicode

        """
        self.CallTipCancel()
        super(EditraBaseStc, self).CallTipShow(position, tip)

    def HidePopups(self):
        """Hide autocomp/calltip popup windows if any are active"""
        if self.AutoCompActive():
            self.AutoCompCancel()

        self.CallTipCancel()

    def InitCompleter(self):
        """(Re)Initialize a completer object for this buffer
        @todo: handle extended autocomp for plugins?

        """
        # Check for plugins that may extend or override functionality for this
        # file type.
        autocomp_ext = AutoCompExtension(wx.GetApp().GetPluginManager())
        completer = autocomp_ext.GetCompleter(self)
        if completer is not None:
            self._code['compsvc'] = completer
        else:
            extend = Profile_Get('AUTO_COMP_EX') # Using extended autocomp?
            self._code['compsvc'] = autocomp.AutoCompService.GetCompleter(self, extend)

    def LoadFile(self, path):
        """Load the file at the given path into the buffer. Returns
        True if no errors and False otherwise. To retrieve the errors
        check the last error that was set in the file object returned by
        L{GetDocument}.
        @param path: path to file

        """
        # Post notification that a file load is starting
        ed_msg.PostMessage(ed_msg.EDMSG_FILE_OPENING, path)
        self.file.SetPath(path)
        txt = self.file.Read()
        if txt is not None:
            if self.file.IsRawBytes() and not ebmlib.IsUnicode(txt):
                self.AddStyledText(txt)
                self.SetReadOnly(True) # Don't allow editing of raw bytes
            else:
                self.SetText(txt)
        else:
            self.file.SetPath('')
            return False

        if self.file.GetLastError() != 'None':
            # Return false if there was an encoding error and a fallback
            # was used. So the caller knows to check the error status
            return False
        else:
            return True

    def MoveCaretPos(self, offset):
        """Move caret by the given offset
        @param offset: int (+ move right, - move left)

        """
        pos = max(self.GetCurrentPos() + offset, 0)
        pos = min(pos, self.GetLength())
        self.GotoPos(pos)
        self.ChooseCaretX()

    def OnAutoCompSel(self, evt):
        """Handle when an item is inserted from the autocomp list"""
        text = evt.GetText()
        cpos = evt.GetPosition()
        self._code['compsvc'].OnCompletionInserted(cpos, text)

    def OnChanged(self, evt):
        """Handles updates that need to take place after
        the control has been modified.
        @param evt: wx.stc.StyledTextEvent

        """
        if self._line_num:
            # Adjust line number margin width to expand as needed when line
            # number width over fills the area.
            lines = self.GetLineCount()
            mwidth = self.GetTextExtent(str(lines))[0]

            adj = 8
            if wx.Platform == '__WXMAC__':
                adj = 2

            nwidth = max(15, mwidth + adj)
            if self.GetMarginWidth(NUM_MARGIN) != nwidth:
                self.SetMarginWidth(NUM_MARGIN, nwidth)

        wx.PostEvent(self.GetParent(), evt)
        ed_msg.PostMessage(ed_msg.EDMSG_UI_STC_CHANGED, context=self)

    def OnModified(self, evt):
        """Handle modify events, includes style changes!"""
        if self.VertEdit.Enabled:
            self.VertEdit.OnModified(evt)
        else:
            evt.Skip()

    def OnStyleNeeded(self, evt):
        """Perform custom styling when registered for a container lexer"""
        if self._code['clexer'] is not None:
            self._code['clexer'](self, self.GetEndStyled(), evt.GetPosition())
        else:
            evt.Skip()

    def PutText(self, text):
        """Put text in the buffer. Like AddText but does the right thing
        depending upon the input mode and buffer state.
        @param text: string

        """
        if not self.HasSelection():
            cpos = self.GetCurrentPos()
            lepos = self.GetLineEndPosition(self.GetCurrentLine())
            if self.GetOvertype() and cpos != lepos:
                self.CharRight()
                self.DeleteBack()
            self.AddText(text)
        else:
            self.ReplaceSelection(text)

    def RegisterImages(self):
        """Register the images for the autocomp popup list"""
        images = [(autocomp.TYPE_FUNCTION, ed_glob.ID_FUNCT_TYPE),
                  (autocomp.TYPE_METHOD, ed_glob.ID_METHOD_TYPE),
                  (autocomp.TYPE_PROPERTY, ed_glob.ID_PROPERTY_TYPE),
                  (autocomp.TYPE_ATTRIBUTE, ed_glob.ID_ATTR_TYPE),
                  (autocomp.TYPE_CLASS, ed_glob.ID_CLASS_TYPE),
                  (autocomp.TYPE_VARIABLE, ed_glob.ID_VARIABLE_TYPE),
                  (autocomp.TYPE_ELEMENT, ed_glob.ID_ELEM_TYPE)]
        for idx, img in images:
            bmp = wx.ArtProvider.GetBitmap(str(img), wx.ART_MENU)
            if bmp.IsOk():
                self.RegisterImage(idx, bmp)

    def SearchText(self, text, regex=False, back=False):
        """Search for text forward or backward
        @param text: string
        @keyword regex: bool
        @keyword back: bool

        """
        flags = wx.stc.STC_FIND_MATCHCASE
        if regex:
            flags = flags | wx.stc.STC_FIND_REGEXP

        self.SearchAnchor()
        if not back:
            # Search forward
            res = self.SearchNext(flags, text)
            if res == -1:
                # Nothing found, search from top
                self.DocumentStart()
                self.SearchAnchor()
                res = self.SearchNext(flags, text)
        else:
            # Search backward
            res = self.SearchPrev(flags, text)
            if res == -1:
                # Nothing found, search from bottom
                self.DocumentEnd()
                self.SearchAnchor()
                res = self.SearchPrev(flags, text)
        return res # returns -1 if nothing found even after wrapping around

    def SetDocument(self, doc):
        """Change the document object used.
        @param doc: an L{ed_txt.EdFile} instance

        """
        del self.file
        self.file = doc

    def SetEncoding(self, enc):
        """Sets the encoding of the document
        @param enc: encoding to set for document

        """
        self.file.SetEncoding(enc)

    def GetEncoding(self):
        """Get the document objects encoding
        @return: string

        """
        return self.file.GetEncoding()

    def SetFileName(self, path):
        """Set the buffers filename attributes from the given path"""
        self.file.SetPath(path)

    def SetKeyWords(self, kw_lst):
        """Sets the keywords from a list of keyword sets
        @param kw_lst: [ (KWLVL, "KEWORDS"), (KWLVL2, "KEYWORDS2"), ect...]

        """
        # Parse Keyword Settings List simply ignoring bad values and badly
        # formed lists
        self._code['keywords'] = list()
        kwlist = ""
        for keyw in kw_lst:
            if len(keyw) != 2:
                continue
            else:
                if not isinstance(keyw[0], int) or \
                   not isinstance(keyw[1], basestring):
                    continue
                else:
                    kwlist += keyw[1]
                    super(EditraBaseStc, self).SetKeyWords(keyw[0], keyw[1])

        # Can't have ? in scintilla autocomp list unless specifying an image
        # TODO: this should be handled by the autocomp service
        if '?' in kwlist:
            kwlist.replace('?', '')

        kwlist = kwlist.split()         # Split into a list of words
        kwlist = list(set(kwlist))      # Remove duplicates from the list
        kwlist.sort()                   # Sort into alphabetical order

        self._code['keywords'] = kwlist

    def SetLexer(self, lexer):
        """Set the buffers lexer
        @param lexer: lexer to use
        @note: Overrides StyledTextCtrl.SetLexer

        """
        if lexer == wx.stc.STC_LEX_CONTAINER:
            # If setting a container lexer only bind the event if it hasn't
            # been done yet.
            if self._code['clexer'] is None:
                self.Bind(wx.stc.EVT_STC_STYLENEEDED, self.OnStyleNeeded)
        else:
            # If changing from a container lexer to a non container
            # lexer we need to unbind the event.
            if self._code['clexer'] is not None:
                self.Unbind(wx.stc.EVT_STC_STYLENEEDED)
                self._code['clexer'] = None

        super(EditraBaseStc, self).SetLexer(lexer)

    def SetModTime(self, modtime):
        """Set the value of the files last modtime"""
        self.file.SetModTime(modtime)

    def SetProperties(self, prop_lst):
        """Sets the Lexer Properties from a list of specifications
        @param prop_lst: [ ("PROPERTY", "VAL"), ("PROPERTY2", "VAL2) ]

        """
        # Parses Property list, ignoring all bad values
        for prop in prop_lst:
            if len(prop) != 2:
                continue
            else:
                if not isinstance(prop[0], basestring) or not \
                   isinstance(prop[1], basestring):
                    continue
                else:
                    self.SetProperty(prop[0], prop[1])
        return True

    def BaseSetSelection(self, start, end):
        """Call base STC SetSelection method, for use with internal utf-8
        indexes in use by derived classes, STC hell...

        """
        super(EditraBaseStc, self).SetSelection(start, end)

    def SetSelection(self, start, end):
        """Override base method to make it work correctly using
        Unicode character positions instead of UTF-8.

        """
        # STC HELL - some methods require UTF-8 offsets while others work
        #            with Unicode...
        # Calculate UTF-8 offsets in buffer
        unicode_txt = self.GetText()
        if start != 0:
            start = len(ed_txt.EncodeString(unicode_txt[0:start], 'utf-8'))
        if end != 0:
            end = len(ed_txt.EncodeString(unicode_txt[0:end], 'utf-8'))
        del unicode_txt
        super(EditraBaseStc, self).SetSelection(start, end)

    def GetSelection(self):
        """Get the selection positions in Unicode instead of UTF-8"""
        # STC HELL
        # Translate the UTF8 byte offsets to unicode
        start, end = super(EditraBaseStc, self).GetSelection()
        utf8_txt = self.GetTextUTF8()
        if start != 0:
            start = len(ed_txt.DecodeString(utf8_txt[0:start], 'utf-8'))
        if end != 0:
            end = len(ed_txt.DecodeString(utf8_txt[0:end], 'utf-8'))
        del utf8_txt
        return start, end

    def ShowAutoCompOpt(self, command):
        """Shows the autocompletion options list for the command
        @param command: command to look for autocomp options for

        """
        pos = self.GetCurrentPos()
        # symList is a list(completer.Symbol)
        symList = self._code['compsvc'].GetAutoCompList(command)

        # Build a list that can be feed to Scintilla
        lst = map(unicode, symList)
        if lst is not None and len(lst):
            self.BeginUndoAction()
            lst = u' '.join(lst)
            if lst.isspace():
                return
            self.AutoCompShow(pos - self.WordStartPosition(pos, True), lst)

            # Check if something was inserted due to there only being a
            # single choice returned from the completer and allow the completer
            # to adjust caret position as necessary.
            curpos = self.GetCurrentPos()
            if curpos != pos:
                text = self.GetTextRange(pos, curpos)
                self._code['compsvc'].OnCompletionInserted(pos, text)
            self.EndUndoAction()
            self.SetFocus()

    def GetViewWhiteSpace(self):
        """Get if view whitespace is turned on
        @return: bool

        """
        val = super(EditraBaseStc, self).GetViewWhiteSpace()
        return val != wx.stc.STC_WS_INVISIBLE

    def SetViewWhiteSpace(self, viewws):
        """Overrides base method to make it a simple bool toggle"""
        if viewws:
            val = wx.stc.STC_WS_VISIBLEALWAYS
        else:
            val = wx.stc.STC_WS_INVISIBLE
        super(EditraBaseStc, self).SetViewWhiteSpace(val)

    def GetWrapMode(self):
        """Get if word wrap is turned on
        @return: bool

        """
        val = super(EditraBaseStc, self).GetWrapMode()
        return val != wx.stc.STC_WRAP_NONE

    def SetWrapMode(self, wrap):
        """Overrides base method to make it a simple toggle operation
        @param wrap: bool

        """
        if wrap:
            val = wx.stc.STC_WRAP_WORD
        else:
            val = wx.stc.STC_WRAP_NONE
        super(EditraBaseStc, self).SetWrapMode(val)

    def ShowCallTip(self, command):
        """Shows call tip for given command
        @param command: command to  look for calltips for

        """
        self.CallTipCancel()

        tip = self._code['compsvc'].GetCallTip(command)
        if len(tip):
            curr_pos = self.GetCurrentPos()
            tip_pos = curr_pos - (len(command.split('.')[-1]) + 1)
            fail_safe = curr_pos - self.GetColumn(curr_pos)
            self.CallTipShow(max(tip_pos, fail_safe), tip)

    def ToggleColumnMode(self):
        """Toggle the column edit mode"""
        self.VertEdit.enable(not self.VertEdit.Enabled)

    def ToggleComment(self):
        """Toggle the comment of the selected region"""
        if len(self._code['comment']):
            sel = self.GetSelection()
            start = self.LineFromPosition(sel[0])
            end = self.LineFromPosition(sel[1])
            c_start = self._code['comment'][0]

            if end > start and self.GetColumn(sel[1]) == 0:
                end = end - 1

            # Analyze the selected line(s)
            comment = 0
            for line in range(start, end+1):
                txt = self.GetLine(line)
                if txt.lstrip().startswith(c_start):
                    comment += 1

            lcount = end - start
            mod = 1
            if lcount == 0:
                mod = 0

            if comment > (lcount / 2) + mod:
                # Uncomment
                self.Comment(start, end, True)
            else:
                self.Comment(start, end, False)

    def ToggleLineNumbers(self, switch=None):
        """Toggles the visibility of the line number margin
        @keyword switch: force a particular setting

        """
        if (switch is None and \
            not self.GetMarginWidth(NUM_MARGIN)) or switch:
            self.EnableLineNumbers(True)
        else:
            self.EnableLineNumbers(False)

    @property
    def VertEdit(self):
        """Vertical edit mode accessor."""
        return self.vert_edit

    #---- Style Function Definitions ----#

    def RefreshStyles(self):
        """Refreshes the colorization of the window by reloading any
        style tags that may have been modified.
        @postcondition: all style settings are refreshed in the control

        """
        with eclib.Freezer(self) as _tmp:
            self.StyleClearAll()
            self.SetSyntax(self.GetSyntaxParams())
            self.DefineMarkers()
        self.Refresh()

    def UpdateBaseStyles(self):
        """Update the controls basic styles"""
        super(EditraBaseStc, self).UpdateBaseStyles()

        # Set control specific styles
        sback = self.GetItemByName('select_style')
        if not sback.IsNull():
            sback = sback.GetBack()
        else:
            sback = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT)
        self.VertEdit.SetBlockColor(sback)
        self.DefineMarkers()

#-----------------------------------------------------------------------------#

class AutoCompExtension(plugin.Plugin):
    """Plugin that Extends the autocomp feature"""
    observers = plugin.ExtensionPoint(iface.AutoCompI)
    def GetCompleter(self, buff):
        """Get the completer for the specified file type id
        @param buff: EditraStc instance

        """
        ftypeid = buff.GetLangId()
        for observer in self.observers:
            try:
                if observer.GetFileTypeId() == ftypeid:
                    return observer.GetCompleter(buff)
            except Exception, msg:
                util.Log("[ed_basestc][err] GetCompleter Extension: %s" % str(msg))
        else:
            return None

#-----------------------------------------------------------------------------#

def _GetMacKeyBindings():
    """Returns a list of 3-element tuples defining the standard key
    bindings for Mac text editors -- i.e., the behavior of option-arrow,
    shift-delete, and so on.

    @return: list of (key code, modifier keys, STC action)

    """
    # A good reference for these: http://www.yellowbrain.com/stc/keymap.html
    return [
            # Move/select/delete by word
            (wx.stc.STC_KEY_LEFT, wx.stc.STC_SCMOD_ALT,
             wx.stc.STC_CMD_WORDLEFT),
            (wx.stc.STC_KEY_RIGHT, wx.stc.STC_SCMOD_ALT,
             wx.stc.STC_CMD_WORDRIGHT),
            (wx.stc.STC_KEY_LEFT, ALT_SHIFT, wx.stc.STC_CMD_WORDLEFTEXTEND),
            (wx.stc.STC_KEY_RIGHT, ALT_SHIFT, wx.stc.STC_CMD_WORDRIGHTEXTEND),
            (wx.stc.STC_KEY_BACK, wx.stc.STC_SCMOD_ALT,
             wx.stc.STC_CMD_DELWORDLEFT),
            (wx.stc.STC_KEY_DELETE, wx.stc.STC_SCMOD_ALT,
             wx.stc.STC_CMD_DELWORDRIGHT),
            (wx.stc.STC_KEY_BACK, ALT_SHIFT, wx.stc.STC_CMD_DELWORDRIGHT),
            (wx.stc.STC_KEY_DELETE, ALT_SHIFT, wx.stc.STC_CMD_DELWORDLEFT),

            # Move/select/delete by line
            (wx.stc.STC_KEY_LEFT, wx.stc.STC_SCMOD_CTRL,
             wx.stc.STC_CMD_VCHOME),
            (wx.stc.STC_KEY_LEFT, CTRL_SHIFT, wx.stc.STC_CMD_VCHOMEEXTEND),
            (wx.stc.STC_KEY_RIGHT, wx.stc.STC_SCMOD_CTRL,
             wx.stc.STC_CMD_LINEEND),
            (wx.stc.STC_KEY_RIGHT, CTRL_SHIFT, wx.stc.STC_CMD_LINEENDEXTEND),
            (wx.stc.STC_KEY_BACK, wx.stc.STC_SCMOD_CTRL,
             wx.stc.STC_CMD_DELLINELEFT),
            (wx.stc.STC_KEY_DELETE, wx.stc.STC_SCMOD_CTRL,
             wx.stc.STC_CMD_DELLINERIGHT),
            (wx.stc.STC_KEY_BACK, CTRL_SHIFT, wx.stc.STC_CMD_DELLINERIGHT),
            (wx.stc.STC_KEY_DELETE, CTRL_SHIFT, wx.stc.STC_CMD_DELLINELEFT),

            # By-character deletion behavior
            (wx.stc.STC_KEY_BACK, wx.stc.STC_SCMOD_NORM,
             wx.stc.STC_CMD_DELETEBACK),
            (wx.stc.STC_KEY_DELETE, wx.stc.STC_SCMOD_SHIFT,
             wx.stc.STC_CMD_DELETEBACK),

            # NOTE: The following two are a special case, since Scintilla
            # doesn't have a forward-delete action.  So here we just cancel any
            # tip our auto-completion display, and then implement forward
            # delete in OnKeyDown.
            #(wx.stc.STC_KEY_DELETE, 0, wx.stc.STC_CMD_CANCEL),
            # Disabled as it breaks some keyboard functionality
            # NOTE: forward delete on mac is Fn+Delete and works fine
          #  (wx.stc.STC_KEY_BACK, wx.stc.STC_SCMOD_SHIFT,
          #   wx.stc.STC_CMD_CANCEL),
            ]


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\modules\registro\models\Registro */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'almacen')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'categoria')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'elemento')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'marca')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'descripcion')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'fecha')->textInput() ?>

    <?= $form->field($model, 'cantidad')->textInput() ?>

    <?= $form->field($model, 'unidad')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'precio')->textInput() ?>

    <?= $form->field($model, 'precio_unitario')->textInput() ?>

    <?= $form->field($model, 'created_at')->textInput() ?>

    <?= $form->field($model, 'updated_at')->textInput() ?>

    <?= $form->field($model, 'created_by')->textInput() ?>

    <?= $form->field($model, 'updated_by')->textInput() ?>

    <?= $form->field($model, 'status')->textInput(['maxlength' => true]) ?>

        <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
<?xml version="1.0" encoding="UTF-8"?>

		<item value="8" key="DIALOG_Y_ORIGIN"/>
		<item value="531" key="DIALOG_X_ORIGIN"/>

		<item value="450" key="org.eclipse.ui.internal.quickaccess.QuickAccessDialogDIALOG_WIDTH"/>
		<item value="false" key="org.eclipse.ui.internal.quickaccess.QuickAccessDialogDIALOG_USE_PERSISTED_LOCATION"/>
		<item value="445" key="org.eclipse.ui.internal.quickaccess.QuickAccessDialogDIALOG_HEIGHT"/>
		<item value="533" key="dialogHeight"/>
		<item value="960" key="dialogWidth"/>
		<item value="true" key="org.eclipse.ui.internal.quickaccess.QuickAccessDialogDIALOG_USE_PERSISTED_SIZE"/>
		<list key="textEntries">
			<item value="1"/>
			<item value="1"/>
		</list>
		<list key="orderedElements">
			<item value="org.eclipse.ui.texteditor.TemplatesView"/>
			<item value="org.eclipse.ui.views.ResourceNavigator"/>
		</list>
		<list key="orderedProviders">
			<item value="org.eclipse.e4.ui.parts"/>
			<item value="org.eclipse.e4.ui.parts"/>
		</list>
		<list key="textArray">
			<item value="temp"/>
			<item value="navi"/>
		</list>

		<item value="706" key="DIALOG_WIDTH"/>
		<item value="1|Segoe UI|9.0|0|WINDOWS|1|-12|0|0|0|400|0|0|0|1|0|0|0|0|Segoe UI" key="DIALOG_FONT_NAME"/>
		<item value="743" key="DIALOG_HEIGHT"/>
		<item value="-249" key="DIALOG_Y_ORIGIN"/>
		<item value="-77" key="DIALOG_X_ORIGIN"/>


text:
<!doctype html>

		<meta charset="utf-8">

		<title>Web Crypto API</title>

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">

		<link rel="stylesheet" href="css/reveal.css">
		<link rel="stylesheet" href="css/theme/white.css" id="theme">

		<link rel="stylesheet" href="lib/css/zenburn.css">

Web Crypto API

            Sung

            Monomax Software

            https://monomax.sh

Web Crypto API

              Why does it matter for node.js?

              Web Crypto API Examples

1. Why does it matter for node.js?

Web Crypto API

A standardized JavaScript interface for accessing cryptographic primitives

W3C published a recommendation in January 2017

All major browsers implement it

Browser crypto implementations

Firefox - NSS (Network Security Services)

Chrome - BoringSSL

An interface for the underlying implementations

window.crypto.subtle.generateKey(
    {
        name: "HMAC",
        hash: {name: "SHA-256"},
    },
    false,
    ["sign", "verify"]
)
.then(function(key){
    console.log(key);
})
.catch(function(err){
    console.error(err);
});

window.crypto.subtle.sign(
    {
        name: "HMAC",
    },
    key,
    data // ArrayBuffer of data you want to sign
)
.then(function(signature){
    //an ArrayBuffer containing the signature
    console.log(new Uint8Array(signature));
})
.catch(function(err){
    console.error(err);
});

Node.js has its own crypto API

crypto module

              first documented in v0.1.94 release (August 2011)

              relied on the host machine's OpenSSL library.

var secret = '/* some secret string */';

hmac = crypto.createHmac('sha-256', secret);
hmac.update(data);
hash = hmac.digest('hex');

console.log("result:", hash);

Problem

            Harder to write code that targets both browsers and non-browsers

Possible solution #1

Write shims or wrappers

Abstraction is where bugs live

              It is hard to audit and maintain shim and polyfills

              Should never be users' responsibility.

Possible solution #2

Use polyfill or npm modules

#1 rule of cryptography

            NEVER EVER implement your own cryptography.

Why not polyfill or package?

Users should NEVER EVER implement crypto

packages can be compromised

Native modules face compilation issues

Pure-JavaScript implementation would be slow

Should node.js implement Web Crypto API?

Trade-off

Favor

Write once to target browsers and non-browsers

              Rely on the standard library

No package to be compromised

No native module cross platform issues

Easier security audit

Favor - counter-arguments

How often do we have to write universal crypto code?

Core does not mean bug-free

Against

Can't just add stuff to core for convenience

Duplicate functionalities

Deprecation of crypto

Against - counter-arguments

It's more than convenience

Software evolve all the time

2. Web Crypto API Examples

Dnote

An open source, encrypted notebook that respects your privacy

          https://dnote.io

Design goal

Clients can write encrypted notes on the server

Server cannot decrypt the notes

My solution (registration)

User enters email and password

Derive k <- pbkdf2(password: password, salt: email, alg: 'sha256', iteration: 10000)

Derive k0 <- hkdf(alg: 'sha256', secret: k, salt: email, info: 'enc') (used as encryption key)

Derive k1 <- hkdf(alg: 'sha256', secret: k, salt: email, info: 'auth') (sent to server for authentication)

              POST to '/register': (email, k1, kdf_iteration)

              Generate salt <- 256bit random string

              Derive k2 <- pbkdf2(password: k1, salt: salt, alg: 'sha256', iteration: 20000)

              Create a user with (hashed_password, salt) = (k2, salt)

Crash course in cryptography

Key-derivation function

A function to derive multiple keys from a single source key

Pseudo-random function

Defined over space (K, X, Y)

K x X -> Y such that there exists "efficient" algorithm to evaluate F(k,x)

Problem with PRF

              Source key is not uniform (e.g. passwords are often dictionaries)

              PRF is not psuedo-random if key is not uniform

Extract-then-expand

Extract: extract a psuedo-random key, k, from the source key

Expand: Expand k using the pseudo-random function

HKDF (KDF from HMAC)

              Extract: k <- HMAC(salt, SK)

              Expand using HMAC as PRF using k

PBKDF (Password-based KDF)

              Defends against dictionary attack

              Salt, slow hash function

              bcrypt, scrypt, argon, ...

Registering on dnote.io

User enters email and password

Derive k <- pbkdf2(password: password, salt: email, alg: 'sha256', iteration: 10000)

Derive k0 <- hkdf(alg: 'sha256', secret: k, salt: email, info: 'enc') (used as encryption key)

Derive k1 <- hkdf(alg: 'sha256', secret: k, salt: email, info: 'auth') (sent to server for authentication)

              POST to '/register': (email, k1, kdf_iteration)

              Generate salt <- 256bit random string

              Derive k2 <- pbkdf2(password: k1, salt: salt, alg: 'sha256', iteration: 20000)

              Create a user with (hashed_password, salt) = (k2, salt)

function pbkdf2(secret, salt, iterations) {
  const secretBuf = strToBuffer(secret);
  const saltBuf = strToBuffer(salt);

  const key = await window.crypto.subtle.importKey(
    'raw',
    secretBuf,
    { name: 'PBKDF2' },
    false,
    ['deriveBits']
  );

  return window.crypto.subtle.deriveBits(
    {
      name: 'PBKDF2',
      salt: saltBuf,
      iterations,
      hash: { name: SHA256 }
    },
    key,
    256
  );
}

function strToBuffer(str) {
  // convert to utf8 encoding
  const strUtf8 = unescape(encodeURIComponent(str));

  const buf = new ArrayBuffer(strUtf8.length);
  const bufView = new Uint8Array(buf);
  for (let i = 0; i < strUtf8.length; i++) {
    bufView[i] = strUtf8.charCodeAt(i);
  }

  return buf;
}

What is ArrayBuffer?

Fixed-size raw binary data buffer

// create an ArrayBuffer with a size in bytes
var buffer = new ArrayBuffer(8);

console.log(buffer.byteLength);
// expected output: 8

Viewed and manipulated using a mask

function bufToB64(buf) {
  let binary = '';
  const bytes = new Uint8Array(buf);
  const len = bytes.byteLength;

  for (let i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
  }

  return window.btoa(binary);
}

function pbkdf2(secret, salt, iterations) {
  const secretBuf = strToBuffer(secret);
  const saltBuf = strToBuffer(salt);

  const key = await window.crypto.subtle.importKey(
    'raw',
    secretBuf,
    { name: 'PBKDF2' },
    false,
    ['deriveBits']
  );

  return window.crypto.subtle.deriveBits(
    {
      name: 'PBKDF2',
      salt: saltBuf,
      iterations,
      hash: { name: SHA256 }
    },
    key,
    256
  );
}

async function hkdf(secret, salt, info, algorithm, dkLen) {
  let secretBuf;
  if (typeof secret === 'string') {
    secretBuf = strToBuffer(secret);
  } else {
    secretBuf = secret;
  }

  const saltBuf = strToBuffer(salt);
  const infoBuf = strToBuffer(info);

  const key = await window.crypto.subtle.importKey(
    'raw',
    secretBuf,
    {
      name: 'HKDF'
    },
    false,
    ['deriveBits']
  );

  return window.crypto.subtle.deriveBits(
    {
      name: HKDF,
      hash: algorithm,
      salt: saltBuf,
      info: infoBuf
    },
    key,
    dkLen
  );
}

async function makeKeys(email, password, iteration) {
  const masterKey = await pbkdf2(password, email, iteration);
  const encKeyBits = await hkdf(
    masterKey, email, 'enc', SHA256, 256
  );
  const authKeyBits = await hkdf(
    masterKey, email, 'auth', SHA256, 256
  );

  return {
    encKey: bufToB64(encKeyBits),
    authKey: bufToB64(authKeyBits)
  };
}

...And more

symmetric block cipher using AES256 in GCM mode

Open source

          https://dnote.io

Wrap up - Web Crypto API

              Why does it matter for node.js?

              Web Crypto API Examples

Conclusion

              Node.js has crypto module

              Browsers have Web Crypto API

              Should node.js implement Web Crypto API? Depends.

Thanks

            Sung

            Monomax Software

            sung@monomax.sh

            https://monomax.sh


text:
@interface DropboxThumbnailFormatToStringSerializer : NSObject <EnumToStringSerializer>

+ (NSString * _Nullable)stringFromEnum:(DropboxThumbnailFormat)format;

@end