text:
package integration

import (
	"bytes"
	"context"
	"os"
	"reflect"
	"strings"
	"testing"
	"time"

	"github.com/coreos/etcd/clientv3"
	"github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
	"github.com/coreos/etcd/integration"
	"github.com/coreos/etcd/mvcc/mvccpb"
	"github.com/coreos/etcd/pkg/testutil"

	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
)

func TestKVPutError(t *testing.T) {
	defer testutil.AfterTest(t)

	var (
		maxReqBytes = 1.5 * 1024 * 1024 // hard coded max in v3_server.go
		quota       = int64(int(maxReqBytes) + 8*os.Getpagesize())
	)
	clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1, QuotaBackendBytes: quota, ClientMaxCallSendMsgSize: 100 * 1024 * 1024})
	defer clus.Terminate(t)

	kv := clus.RandClient()
	ctx := context.TODO()

	_, err := kv.Put(ctx, "", "bar")
	if err != rpctypes.ErrEmptyKey {
		t.Fatalf("expected %v, got %v", rpctypes.ErrEmptyKey, err)
	}

	_, err = kv.Put(ctx, "key", strings.Repeat("a", int(maxReqBytes+100)))
	if err != rpctypes.ErrRequestTooLarge {
		t.Fatalf("expected %v, got %v", rpctypes.ErrRequestTooLarge, err)
	}

	_, err = kv.Put(ctx, "foo1", strings.Repeat("a", int(maxReqBytes-50)))
	if err != nil { // below quota
		t.Fatal(err)
	}

	time.Sleep(1 * time.Second) // give enough time for commit

	_, err = kv.Put(ctx, "foo2", strings.Repeat("a", int(maxReqBytes-50)))
	if err != rpctypes.ErrNoSpace { // over quota
		t.Fatalf("expected %v, got %v", rpctypes.ErrNoSpace, err)
	}
}

func TestKVPut(t *testing.T) {
	defer testutil.AfterTest(t)

	clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
	defer clus.Terminate(t)

	lapi := clus.RandClient()

	kv := clus.RandClient()
	ctx := context.TODO()

	resp, err := lapi.Grant(context.Background(), 10)
	if err != nil {
		t.Fatalf("failed to create lease %v", err)
	}

	tests := []struct {
		key, val string
		leaseID  clientv3.LeaseID
	}{
		{"foo", "bar", clientv3.NoLease},
		{"hello", "world", resp.ID},
	}

	for i, tt := range tests {
		if _, err := kv.Put(ctx, tt.key, tt.val, clientv3.WithLease(tt.leaseID)); err != nil {
			t.Fatalf("#%d: couldn't put %q (%v)", i, tt.key, err)
		}
		resp, err := kv.Get(ctx, tt.key)
		if err != nil {
			t.Fatalf("#%d: couldn't get key (%v)", i, err)
		}
		if len(resp.Kvs) != 1 {
			t.Fatalf("#%d: expected 1 key, got %d", i, len(resp.Kvs))
		}
		if !bytes.Equal([]byte(tt.val), resp.Kvs[0].Value) {
			t.Errorf("#%d: val = %s, want %s", i, tt.val, resp.Kvs[0].Value)
		}
		if tt.leaseID != clientv3.LeaseID(resp.Kvs[0].Lease) {
			t.Errorf("#%d: val = %d, want %d", i, tt.leaseID, resp.Kvs[0].Lease)
		}
	}
}

// TestKVPutWithIgnoreValue ensures that Put with WithIgnoreValue does not clobber the old value.
func TestKVPutWithIgnoreValue(t *testing.T) {
	defer testutil.AfterTest(t)

	clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
	defer clus.Terminate(t)

	kv := clus.RandClient()

	_, err := kv.Put(context.TODO(), "foo", "", clientv3.WithIgnoreValue())
	if err != rpctypes.ErrKeyNotFound {
		t.Fatalf("err expected %v, got %v", rpctypes.ErrKeyNotFound, err)
	}

	if _, err := kv.Put(context.TODO(), "foo", "bar"); err != nil {
		t.Fatal(err)
	}

	if _, err := kv.Put(context.TODO(), "foo", "", clientv3.WithIgnoreValue()); err != nil {
		t.Fatal(err)
	}
	rr, rerr := kv.Get(context.TODO(), "foo")
	if rerr != nil {
		t.Fatal(rerr)
	}
	if len(rr.Kvs) != 1 {
		t.Fatalf("len(rr.Kvs) expected 1, got %d", len(rr.Kvs))
	}
	if !bytes.Equal(rr.Kvs[0].Value, []byte("bar")) {
		t.Fatalf("value expected 'bar', got %q", rr.Kvs[0].Value)
	}
}

// TestKVPutWithIgnoreLease ensures that Put with WithIgnoreLease does not affect the existing lease for the key.
func TestKVPutWithIgnoreLease(t *testing.T) {
	defer testutil.AfterTest(t)

	clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
	defer clus.Terminate(t)

	kv := clus.RandClient()

	lapi := clus.RandClient()

	resp, err := lapi.Grant(context.Background(), 10)
	if err != nil {
		t.Errorf("failed to create lease %v", err)
	}

	if _, err := kv.Put(context.TODO(), "zoo", "bar", clientv3.WithIgnoreLease()); err != rpctypes.ErrKeyNotFound {
		t.Fatalf("err expected %v, got %v", rpctypes.ErrKeyNotFound, err)
	}

	if _, err := kv.Put(context.TODO(), "zoo", "bar", clientv3.WithLease(resp.ID)); err != nil {
		t.Fatal(err)
	}

	if _, err := kv.Put(context.TODO(), "zoo", "bar1", clientv3.WithIgnoreLease()); err != nil {
		t.Fatal(err)
	}

	rr, rerr := kv.Get(context.TODO(), "zoo")
	if rerr != nil {
		t.Fatal(rerr)
	}
	if len(rr.Kvs) != 1 {
		t.Fatalf("len(rr.Kvs) expected 1, got %d", len(rr.Kvs))
	}
	if rr.Kvs[0].Lease != int64(resp.ID) {
		t.Fatalf("lease expected %v, got %v", resp.ID, rr.Kvs[0].Lease)
	}
}

func TestKVPutWithRequireLeader(t *testing.T) {
	defer testutil.AfterTest(t)

	clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
	defer clus.Terminate(t)

	clus.Members[1].Stop(t)
	clus.Members[2].Stop(t)

	// wait for election timeout, then member[0] will not have a leader.
	var (
		electionTicks = 10
		tickDuration  = 10 * time.Millisecond
	)
	time.Sleep(time.Duration(3*electionTicks) * tickDuration)

	kv := clus.Client(0)
	_, err := kv.Put(clientv3.WithRequireLeader(context.Background()), "foo", "bar")
	if err != rpctypes.ErrNoLeader {
		t.Fatal(err)
	}

	// clients may give timeout errors since the members are stopped; take
	// the clients so that terminating the cluster won't complain
	clus.Client(1).Close()
	clus.Client(2).Close()
	clus.TakeClient(1)
	clus.TakeClient(2)
}

func TestKVRange(t *testing.T) {
	defer testutil.AfterTest(t)

	clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
	defer clus.Terminate(t)

	kv := clus.RandClient()
	ctx := context.TODO()

	keySet := []string{"a", "b", "c", "c", "c", "foo", "foo/abc", "fop"}
	for i, key := range keySet {
		if _, err := kv.Put(ctx, key, ""); err != nil {
			t.Fatalf("#%d: couldn't put %q (%v)", i, key, err)
		}
	}
	resp, err := kv.Get(ctx, keySet[0])
	if err != nil {
		t.Fatalf("couldn't get key (%v)", err)
	}
	wheader := resp.Header

	tests := []struct {
		begin, end string
		rev        int64
		opts       []clientv3.OpOption

		wantSet []*mvccpb.KeyValue
	}{
		// range first two
		{
			"a", "c",
			0,
			nil,

			[]*mvccpb.KeyValue{
				{Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
				{Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
			},
		},
		// range first two with serializable
		{
			"a", "c",
			0,
			[]clientv3.OpOption{clientv3.WithSerializable()},

			[]*mvccpb.KeyValue{
				{Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
				{Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
			},
		},
		// range all with rev
		{
			"a", "x",
			2,
			nil,

			[]*mvccpb.KeyValue{
				{Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
			},
		},
		// range all with countOnly
		{
			"a", "x",
			2,
			[]clientv3.OpOption{clientv3.WithCountOnly()},

			nil,
		},
		// range all with SortByKey, SortAscend
		{
			"a", "x",
			0,
			[]clientv3.OpOption{clientv3.WithSort(clientv3.SortByKey, clientv3.SortAscend)},

			[]*mvccpb.KeyValue{
				{Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
				{Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
				{Key: []byte("c"), Value: nil, CreateRevision: 4, ModRevision: 6, Version: 3},
				{Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
				{Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
				{Key: []byte("fop"), Value: nil, CreateRevision: 9, ModRevision: 9, Version: 1},
			},
		},
		// range all with SortByKey, missing sorting order (ASCEND by default)
		{
			"a", "x",
			0,
			[]clientv3.OpOption{clientv3.WithSort(clientv3.SortByKey, clientv3.SortNone)},

			[]*mvccpb.KeyValue{
				{Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
				{Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
				{Key: []byte("c"), Value: nil, CreateRevision: 4, ModRevision: 6, Version: 3},
				{Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
				{Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
				{Key: []byte("fop"), Value: nil, CreateRevision: 9, ModRevision: 9, Version: 1},
			},
		},
		// range all with SortByCreateRevision, SortDescend
		{
			"a", "x",
			0,
			[]clientv3.OpOption{clientv3.WithSort(clientv3.SortByCreateRevision, clientv3.SortDescend)},

			[]*mvccpb.KeyValue{
				{Key: []byte("fop"), Value: nil, CreateRevision: 9, ModRevision: 9, Version: 1},
				{Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
				{Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
				{Key: []byte("c"), Value: nil, CreateRevision: 4, ModRevision: 6, Version: 3},
				{Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
				{Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
			},
		},
		// range all with SortByCreateRevision, missing sorting order (ASCEND by default)
		{
			"a", "x",
			0,
			[]clientv3.OpOption{clientv3.WithSort(clientv3.SortByCreateRevision, clientv3.SortNone)},

			[]*mvccpb.KeyValue{
				{Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
				{Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
				{Key: []byte("c"), Value: nil, CreateRevision: 4, ModRevision: 6, Version: 3},
				{Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
				{Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
				{Key: []byte("fop"), Value: nil, CreateRevision: 9, ModRevision: 9, Version: 1},
			},
		},
		// range all with SortByModRevision, SortDescend
		{
			"a", "x",
			0,
			[]clientv3.OpOption{clientv3.WithSort(clientv3.SortByModRevision, clientv3.SortDescend)},

			[]*mvccpb.KeyValue{
				{Key: []byte("fop"), Value: nil, CreateRevision: 9, ModRevision: 9, Version: 1},
				{Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
				{Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
				{Key: []byte("c"), Value: nil, CreateRevision: 4, ModRevision: 6, Version: 3},
				{Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
				{Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
			},
		},
		// WithPrefix
		{
			"foo", "",
			0,
			[]clientv3.OpOption{clientv3.WithPrefix()},

			[]*mvccpb.KeyValue{
				{Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
				{Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
			},
		},
		// WithFromKey
		{
			"fo", "",
			0,
			[]clientv3.OpOption{clientv3.WithFromKey()},

			[]*mvccpb.KeyValue{
				{Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
				{Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
				{Key: []byte("fop"), Value: nil, CreateRevision: 9, ModRevision: 9, Version: 1},
			},
		},
		// fetch entire keyspace using WithFromKey
		{
			"\x00", "",
			0,
			[]clientv3.OpOption{clientv3.WithFromKey(), clientv3.WithSort(clientv3.SortByKey, clientv3.SortAscend)},

			[]*mvccpb.KeyValue{
				{Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
				{Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
				{Key: []byte("c"), Value: nil, CreateRevision: 4, ModRevision: 6, Version: 3},
				{Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
				{Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
				{Key: []byte("fop"), Value: nil, CreateRevision: 9, ModRevision: 9, Version: 1},
			},
		},
		// fetch entire keyspace using WithPrefix
		{
			"", "",
			0,
			[]clientv3.OpOption{clientv3.WithPrefix(), clientv3.WithSort(clientv3.SortByKey, clientv3.SortAscend)},

			[]*mvccpb.KeyValue{
				{Key: []byte("a"), Value: nil, CreateRevision: 2, ModRevision: 2, Version: 1},
				{Key: []byte("b"), Value: nil, CreateRevision: 3, ModRevision: 3, Version: 1},
				{Key: []byte("c"), Value: nil, CreateRevision: 4, ModRevision: 6, Version: 3},
				{Key: []byte("foo"), Value: nil, CreateRevision: 7, ModRevision: 7, Version: 1},
				{Key: []byte("foo/abc"), Value: nil, CreateRevision: 8, ModRevision: 8, Version: 1},
				{Key: []byte("fop"), Value: nil, CreateRevision: 9, ModRevision: 9, Version: 1},
			},
		},
	}

	for i, tt := range tests {
		opts := []clientv3.OpOption{clientv3.WithRange(tt.end), clientv3.WithRev(tt.rev)}
		opts = append(opts, tt.opts...)
		resp, err := kv.Get(ctx, tt.begin, opts...)
		if err != nil {
			t.Fatalf("#%d: couldn't range (%v)", i, err)
		}
		if !reflect.DeepEqual(wheader, resp.Header) {
			t.Fatalf("#%d: wheader expected %+v, got %+v", i, wheader, resp.Header)
		}
		if !reflect.DeepEqual(tt.wantSet, resp.Kvs) {
			t.Fatalf("#%d: resp.Kvs expected %+v, got %+v", i, tt.wantSet, resp.Kvs)
		}
	}
}

func TestKVGetErrConnClosed(t *testing.T) {
	defer testutil.AfterTest(t)

	clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
	defer clus.Terminate(t)

	cli := clus.Client(0)

	donec := make(chan struct{})
	go func() {
		defer close(donec)
		_, err := cli.Get(context.TODO(), "foo")
		if !clientv3.IsConnCanceled(err) {
			t.Fatalf("expected %v or %v, got %v", context.Canceled, grpc.ErrClientConnClosing, err)
		}
	}()

	if err := cli.Close(); err != nil {
		t.Fatal(err)
	}
	clus.TakeClient(0)

	select {
	case <-time.After(integration.RequestWaitTimeout):
		t.Fatal("kv.Get took too long")
	case <-donec:
	}
}

func TestKVNewAfterClose(t *testing.T) {
	defer testutil.AfterTest(t)

	clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
	defer clus.Terminate(t)

	cli := clus.Client(0)
	clus.TakeClient(0)
	if err := cli.Close(); err != nil {
		t.Fatal(err)
	}

	donec := make(chan struct{})
	go func() {
		_, err := cli.Get(context.TODO(), "foo")
		if !clientv3.IsConnCanceled(err) {
			t.Fatalf("expected %v or %v, got %v", context.Canceled, grpc.ErrClientConnClosing, err)
		}
		close(donec)
	}()
	select {
	case <-time.After(integration.RequestWaitTimeout):
		t.Fatal("kv.Get took too long")
	case <-donec:
	}
}

func TestKVDeleteRange(t *testing.T) {
	defer testutil.AfterTest(t)

	clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
	defer clus.Terminate(t)

	kv := clus.RandClient()
	ctx := context.TODO()

	tests := []struct {
		key  string
		opts []clientv3.OpOption

		wkeys []string
	}{
		// [a, c)
		{
			key:  "a",
			opts: []clientv3.OpOption{clientv3.WithRange("c")},

			wkeys: []string{"c", "c/abc", "d"},
		},
		// >= c
		{
			key:  "c",
			opts: []clientv3.OpOption{clientv3.WithFromKey()},

			wkeys: []string{"a", "b"},
		},
		// c*
		{
			key:  "c",
			opts: []clientv3.OpOption{clientv3.WithPrefix()},

			wkeys: []string{"a", "b", "d"},
		},
		// *
		{
			key:  "\x00",
			opts: []clientv3.OpOption{clientv3.WithFromKey()},

			wkeys: []string{},
		},
	}

	for i, tt := range tests {
		keySet := []string{"a", "b", "c", "c/abc", "d"}
		for j, key := range keySet {
			if _, err := kv.Put(ctx, key, ""); err != nil {
				t.Fatalf("#%d: couldn't put %q (%v)", j, key, err)
			}
		}

		_, err := kv.Delete(ctx, tt.key, tt.opts...)
		if err != nil {
			t.Fatalf("#%d: couldn't delete range (%v)", i, err)
		}

		resp, err := kv.Get(ctx, "a", clientv3.WithFromKey())
		if err != nil {
			t.Fatalf("#%d: couldn't get keys (%v)", i, err)
		}
		keys := []string{}
		for _, kv := range resp.Kvs {
			keys = append(keys, string(kv.Key))
		}
		if !reflect.DeepEqual(tt.wkeys, keys) {
			t.Errorf("#%d: resp.Kvs got %v, expected %v", i, keys, tt.wkeys)
		}
	}
}

func TestKVDelete(t *testing.T) {
	defer testutil.AfterTest(t)

	clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
	defer clus.Terminate(t)

	kv := clus.RandClient()
	ctx := context.TODO()

	presp, err := kv.Put(ctx, "foo", "")
	if err != nil {
		t.Fatalf("couldn't put 'foo' (%v)", err)
	}
	if presp.Header.Revision != 2 {
		t.Fatalf("presp.Header.Revision got %d, want %d", presp.Header.Revision, 2)
	}
	resp, err := kv.Delete(ctx, "foo")
	if err != nil {
		t.Fatalf("couldn't delete key (%v)", err)
	}
	if resp.Header.Revision != 3 {
		t.Fatalf("resp.Header.Revision got %d, want %d", resp.Header.Revision, 3)
	}
	gresp, err := kv.Get(ctx, "foo")
	if err != nil {
		t.Fatalf("couldn't get key (%v)", err)
	}
	if len(gresp.Kvs) > 0 {
		t.Fatalf("gresp.Kvs got %+v, want none", gresp.Kvs)
	}
}

func TestKVCompactError(t *testing.T) {
	defer testutil.AfterTest(t)

	clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
	defer clus.Terminate(t)

	kv := clus.RandClient()
	ctx := context.TODO()

	for i := 0; i < 5; i++ {
		if _, err := kv.Put(ctx, "foo", "bar"); err != nil {
			t.Fatalf("couldn't put 'foo' (%v)", err)
		}
	}
	_, err := kv.Compact(ctx, 6)
	if err != nil {
		t.Fatalf("couldn't compact 6 (%v)", err)
	}

	_, err = kv.Compact(ctx, 6)
	if err != rpctypes.ErrCompacted {
		t.Fatalf("expected %v, got %v", rpctypes.ErrCompacted, err)
	}

	_, err = kv.Compact(ctx, 100)
	if err != rpctypes.ErrFutureRev {
		t.Fatalf("expected %v, got %v", rpctypes.ErrFutureRev, err)
	}
}

func TestKVCompact(t *testing.T) {
	defer testutil.AfterTest(t)

	clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
	defer clus.Terminate(t)

	kv := clus.RandClient()
	ctx := context.TODO()

	for i := 0; i < 10; i++ {
		if _, err := kv.Put(ctx, "foo", "bar"); err != nil {
			t.Fatalf("couldn't put 'foo' (%v)", err)
		}
	}

	_, err := kv.Compact(ctx, 7)
	if err != nil {
		t.Fatalf("couldn't compact kv space (%v)", err)
	}
	_, err = kv.Compact(ctx, 7)
	if err == nil || err != rpctypes.ErrCompacted {
		t.Fatalf("error got %v, want %v", err, rpctypes.ErrCompacted)
	}

	wcli := clus.RandClient()
	// new watcher could precede receiving the compaction without quorum first
	wcli.Get(ctx, "quorum-get")

	wchan := wcli.Watch(ctx, "foo", clientv3.WithRev(3))

	if wr := <-wchan; wr.CompactRevision != 7 {
		t.Fatalf("wchan CompactRevision got %v, want 7", wr.CompactRevision)
	}
	if wr, ok := <-wchan; ok {
		t.Fatalf("wchan got %v, expected closed", wr)
	}

	_, err = kv.Compact(ctx, 1000)
	if err == nil || err != rpctypes.ErrFutureRev {
		t.Fatalf("error got %v, want %v", err, rpctypes.ErrFutureRev)
	}
}

// TestKVGetRetry ensures get will retry on disconnect.
func TestKVGetRetry(t *testing.T) {
	defer testutil.AfterTest(t)

	clusterSize := 3
	clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: clusterSize})
	defer clus.Terminate(t)

	// because killing leader and following election
	// could give no other endpoints for client reconnection
	fIdx := (clus.WaitLeader(t) + 1) % clusterSize

	kv := clus.Client(fIdx)
	ctx := context.TODO()

	if _, err := kv.Put(ctx, "foo", "bar"); err != nil {
		t.Fatal(err)
	}

	clus.Members[fIdx].Stop(t)

	donec := make(chan struct{})
	go func() {
		// Get will fail, but reconnect will trigger
		gresp, gerr := kv.Get(ctx, "foo")
		if gerr != nil {
			t.Fatal(gerr)
		}
		wkvs := []*mvccpb.KeyValue{
			{
				Key:            []byte("foo"),
				Value:          []byte("bar"),
				CreateRevision: 2,
				ModRevision:    2,
				Version:        1,
			},
		}
		if !reflect.DeepEqual(gresp.Kvs, wkvs) {
			t.Fatalf("bad get: got %v, want %v", gresp.Kvs, wkvs)
		}
		donec <- struct{}{}
	}()

	time.Sleep(100 * time.Millisecond)
	clus.Members[fIdx].Restart(t)
	clus.Members[fIdx].WaitOK(t)

	select {
	case <-time.After(20 * time.Second):
		t.Fatalf("timed out waiting for get")
	case <-donec:
	}
}

// TestKVPutFailGetRetry ensures a get will retry following a failed put.
func TestKVPutFailGetRetry(t *testing.T) {
	defer testutil.AfterTest(t)

	clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
	defer clus.Terminate(t)

	kv := clus.Client(0)
	clus.Members[0].Stop(t)

	ctx, cancel := context.WithTimeout(context.TODO(), time.Second)
	defer cancel()
	_, err := kv.Put(ctx, "foo", "bar")
	if err == nil {
		t.Fatalf("got success on disconnected put, wanted error")
	}

	donec := make(chan struct{})
	go func() {
		// Get will fail, but reconnect will trigger
		gresp, gerr := kv.Get(context.TODO(), "foo")
		if gerr != nil {
			t.Fatal(gerr)
		}
		if len(gresp.Kvs) != 0 {
			t.Fatalf("bad get kvs: got %+v, want empty", gresp.Kvs)
		}
		donec <- struct{}{}
	}()

	time.Sleep(100 * time.Millisecond)
	clus.Members[0].Restart(t)

	select {
	case <-time.After(20 * time.Second):
		t.Fatalf("timed out waiting for get")
	case <-donec:
	}
}

// TestKVGetCancel tests that a context cancel on a Get terminates as expected.
func TestKVGetCancel(t *testing.T) {
	defer testutil.AfterTest(t)

	clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
	defer clus.Terminate(t)

	oldconn := clus.Client(0).ActiveConnection()
	kv := clus.Client(0)

	ctx, cancel := context.WithCancel(context.TODO())
	cancel()

	resp, err := kv.Get(ctx, "abc")
	if err == nil {
		t.Fatalf("cancel on get response %v, expected context error", resp)
	}
	newconn := clus.Client(0).ActiveConnection()
	if oldconn != newconn {
		t.Fatalf("cancel on get broke client connection")
	}
}

// TestKVGetStoppedServerAndClose ensures closing after a failed Get works.
func TestKVGetStoppedServerAndClose(t *testing.T) {
	defer testutil.AfterTest(t)

	clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
	defer clus.Terminate(t)

	cli := clus.Client(0)
	clus.Members[0].Stop(t)
	ctx, cancel := context.WithTimeout(context.TODO(), time.Second)
	// this Get fails and triggers an asynchronous connection retry
	_, err := cli.Get(ctx, "abc")
	cancel()
	if err != nil && !(isCanceled(err) || isClientTimeout(err)) {
		t.Fatal(err)
	}
}

// TestKVPutStoppedServerAndClose ensures closing after a failed Put works.
func TestKVPutStoppedServerAndClose(t *testing.T) {
	defer testutil.AfterTest(t)

	clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
	defer clus.Terminate(t)

	cli := clus.Client(0)
	clus.Members[0].Stop(t)

	ctx, cancel := context.WithTimeout(context.TODO(), time.Second)
	// get retries on all errors.
	// so here we use it to eat the potential broken pipe error for the next put.
	// grpc client might see a broken pipe error when we issue the get request before
	// grpc finds out the original connection is down due to the member shutdown.
	_, err := cli.Get(ctx, "abc")
	cancel()
	if err != nil && !(isCanceled(err) || isClientTimeout(err)) {
		t.Fatal(err)
	}

	ctx, cancel = context.WithTimeout(context.TODO(), time.Second)
	// this Put fails and triggers an asynchronous connection retry
	_, err = cli.Put(ctx, "abc", "123")
	cancel()
	if err != nil && !(isCanceled(err) || isClientTimeout(err) || isUnavailable(err)) {
		t.Fatal(err)
	}
}

// TestKVPutAtMostOnce ensures that a Put will only occur at most once
// in the presence of network errors.
func TestKVPutAtMostOnce(t *testing.T) {
	defer testutil.AfterTest(t)
	clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
	defer clus.Terminate(t)

	if _, err := clus.Client(0).Put(context.TODO(), "k", "1"); err != nil {
		t.Fatal(err)
	}

	for i := 0; i < 10; i++ {
		clus.Members[0].DropConnections()
		donec := make(chan struct{})
		go func() {
			defer close(donec)
			for i := 0; i < 10; i++ {
				clus.Members[0].DropConnections()
				time.Sleep(5 * time.Millisecond)
			}
		}()
		_, err := clus.Client(0).Put(context.TODO(), "k", "v")
		<-donec
		if err != nil {
			break
		}
	}

	resp, err := clus.Client(0).Get(context.TODO(), "k")
	if err != nil {
		t.Fatal(err)
	}
	if resp.Kvs[0].Version > 11 {
		t.Fatalf("expected version <= 10, got %+v", resp.Kvs[0])
	}
}

// TestKVLargeRequests tests various client/server side request limits.
func TestKVLargeRequests(t *testing.T) {
	defer testutil.AfterTest(t)
	tests := []struct {
		// make sure that "MaxCallSendMsgSize" < server-side default send/recv limit
		maxRequestBytesServer  uint
		maxCallSendBytesClient int
		maxCallRecvBytesClient int

		valueSize   int
		expectError error
	}{
		{
			maxRequestBytesServer:  1,
			maxCallSendBytesClient: 0,
			maxCallRecvBytesClient: 0,
			valueSize:              1024,
			expectError:            rpctypes.ErrRequestTooLarge,
		},

		// without proper client-side receive size limit
		// "code = ResourceExhausted desc = grpc: received message larger than max (5242929 vs. 4194304)"
		{

			maxRequestBytesServer:  7*1024*1024 + 512*1024,
			maxCallSendBytesClient: 7 * 1024 * 1024,
			maxCallRecvBytesClient: 0,
			valueSize:              5 * 1024 * 1024,
			expectError:            nil,
		},

		{
			maxRequestBytesServer:  10 * 1024 * 1024,
			maxCallSendBytesClient: 100 * 1024 * 1024,
			maxCallRecvBytesClient: 0,
			valueSize:              10 * 1024 * 1024,
			expectError:            rpctypes.ErrRequestTooLarge,
		},
		{
			maxRequestBytesServer:  10 * 1024 * 1024,
			maxCallSendBytesClient: 10 * 1024 * 1024,
			maxCallRecvBytesClient: 0,
			valueSize:              10 * 1024 * 1024,
			expectError:            grpc.Errorf(codes.ResourceExhausted, "trying to send message larger than max "),
		},
		{
			maxRequestBytesServer:  10 * 1024 * 1024,
			maxCallSendBytesClient: 100 * 1024 * 1024,
			maxCallRecvBytesClient: 0,
			valueSize:              10*1024*1024 + 5,
			expectError:            rpctypes.ErrRequestTooLarge,
		},
		{
			maxRequestBytesServer:  10 * 1024 * 1024,
			maxCallSendBytesClient: 10 * 1024 * 1024,
			maxCallRecvBytesClient: 0,
			valueSize:              10*1024*1024 + 5,
			expectError:            grpc.Errorf(codes.ResourceExhausted, "trying to send message larger than max "),
		},
	}
	for i, test := range tests {
		clus := integration.NewClusterV3(t,
			&integration.ClusterConfig{
				Size:                     1,
				MaxRequestBytes:          test.maxRequestBytesServer,
				ClientMaxCallSendMsgSize: test.maxCallSendBytesClient,
				ClientMaxCallRecvMsgSize: test.maxCallRecvBytesClient,
			},
		)
		cli := clus.Client(0)
		_, err := cli.Put(context.TODO(), "foo", strings.Repeat("a", test.valueSize))

		if _, ok := err.(rpctypes.EtcdError); ok {
			if err != test.expectError {
				t.Errorf("#%d: expected %v, got %v", i, test.expectError, err)
			}
		} else if err != nil && !strings.HasPrefix(err.Error(), test.expectError.Error()) {
			t.Errorf("#%d: expected error starting with '%s', got '%s'", i, test.expectError.Error(), err.Error())
		}

		// put request went through, now expects large response back
		if err == nil {
			_, err = cli.Get(context.TODO(), "foo")
			if err != nil {
				t.Errorf("#%d: get expected no error, got %v", i, err)
			}
		}

		clus.Terminate(t)
	}
}


text:
/**
 * Onshape REST API
 * The Onshape REST API consumed by all clients.
 *
 * OpenAPI spec version: 1.93
 * Contact: api-support@onshape.zendesk.com
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

export class BTStandardContentCustomParameterParams {
    'isDrivingConfiguration'?: boolean;
    'parameterValue'?: string;
    'ownerType'?: number;
    'parameterType'?: number;
    'parameterName'?: string;
    'ownerId'?: string;
    'propertyId'?: string;
    'type'?: string;
    'category'?: string;
    'standard'?: string;
    'types'?: string;
    'componentDocumentId'?: string;
    'disableProduction'?: boolean;
    'productionVersionId'?: string;
    'testVersionId'?: string;

    static discriminator: string | undefined = undefined;

    static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [
        {
            "name": "isDrivingConfiguration",
            "baseName": "isDrivingConfiguration",
            "type": "boolean"
        },
        {
            "name": "parameterValue",
            "baseName": "parameterValue",
            "type": "string"
        },
        {
            "name": "ownerType",
            "baseName": "ownerType",
            "type": "number"
        },
        {
            "name": "parameterType",
            "baseName": "parameterType",
            "type": "number"
        },
        {
            "name": "parameterName",
            "baseName": "parameterName",
            "type": "string"
        },
        {
            "name": "ownerId",
            "baseName": "ownerId",
            "type": "string"
        },
        {
            "name": "propertyId",
            "baseName": "propertyId",
            "type": "string"
        },
        {
            "name": "type",
            "baseName": "type",
            "type": "string"
        },
        {
            "name": "category",
            "baseName": "category",
            "type": "string"
        },
        {
            "name": "standard",
            "baseName": "standard",
            "type": "string"
        },
        {
            "name": "types",
            "baseName": "types",
            "type": "string"
        },
        {
            "name": "componentDocumentId",
            "baseName": "componentDocumentId",
            "type": "string"
        },
        {
            "name": "disableProduction",
            "baseName": "disableProduction",
            "type": "boolean"
        },
        {
            "name": "productionVersionId",
            "baseName": "productionVersionId",
            "type": "string"
        },
        {
            "name": "testVersionId",
            "baseName": "testVersionId",
            "type": "string"
        }    ];

    static getAttributeTypeMap() {
        return BTStandardContentCustomParameterParams.attributeTypeMap;
    }
}

redpajama_set_name: RedPajamaGithub


text: import "./connection"


text:
class Chef
  class Knife
    class EnvironmentFromFile < Knife

      deps do
        require 'chef/environment'
        require 'chef/knife/core/object_loader'
      end

      banner "knife environment from file FILE (options)"

      def loader
        @loader ||= Knife::Core::ObjectLoader.new(Chef::Environment, ui)
      end

      def run
        if @name_args[0].nil?
          show_usage
          ui.fatal("You must specify a file to load")
          exit 1
        end

        updated = loader.load_from("environments", @name_args[0])
        updated.save
        output(format_for_display(updated)) if config[:print_after]
        ui.info("Updated Environment #{updated.name}")
      end
    end
  end
end


text:
require 'test_helper'

class RoomsControllerTest < ActionController::TestCase
  # test "the truth" do
  #   assert true
  # end
end


text:
package views.html.search

import play.api.data.Form

import lila.api.Context
import lila.app.templating.Environment._
import lila.app.ui.ScalatagsTemplate._
import lila.common.paginator.Paginator

import controllers.routes

object index {

  import trans.search._

  def apply(form: Form[_], paginator: Option[Paginator[lila.game.Game]] = None, nbGames: Long)(implicit
      ctx: Context
  ) = {
    val commons = bits of form
    import commons._
    views.html.base.layout(
      title = searchInXGames.txt(nbGames.localize, nbGames),
      moreJs = frag(
        jsModule("gameSearch"),
        infiniteScrollTag
      ),
      moreCss = cssTag("search")
    ) {
      main(cls := "box page-small search")(
        h1(advancedSearch()),
        st.form(
          noFollow,
          cls := "box__pad search__form",
          action := s"${routes.Search.index()}#results",
          method := "GET"
        )(dataReqs)(
          globalError(form),
          table(
            tr(
              th(label(trans.players())),
              td(cls := "usernames two-columns")(List("a", "b").map { p =>
                div(form3.input(form("players")(p))(tpe := "text"))
              })
            ),
            colors(hide = true),
            winner(hide = true),
            loser(hide = true),
            rating,
            hasAi,
            aiLevel,
            source,
            perf,
            mode,
            turns,
            duration,
            clockTime,
            clockIncrement,
            status,
            winnerColor,
            date,
            sort,
            analysed,
            tr(
              th,
              td(cls := "action")(
                submitButton(cls := "button")(trans.search.search()),
                div(cls := "wait")(
                  spinner,
                  searchInXGames(nbGames.localize)
                )
              )
            )
          )
        ),
        div(cls := "search__result", id := "results")(
          paginator.map { pager =>
            val permalink =
              a(cls := "permalink", href := routes.Search.index(), noFollow)("Permalink")
            if (pager.nbResults > 0)
              frag(
                div(cls := "search__status box__pad")(
                  strong(xGamesFound(pager.nbResults.localize, pager.nbResults)),
                  " • ",
                  permalink
                ),
                div(cls := "search__rows infinite-scroll")(
                  views.html.game.widgets(pager.currentPageResults),
                  pagerNext(pager, np => routes.Search.index(np).url)
                )
              )
            else
              div(cls := "search__status box__pad")(
                strong(xGamesFound(0)),
                " • ",
                permalink
              )
          }
        )
      )
    }
  }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.eigpay.sp.log.infrastructure.dao.DictDao">
	<resultMap id="BaseResultMap"
		type="com.eigpay.sp.log.infrastructure.model.DictBean">
		<id column="ID" property="id" jdbcType="BIGINT" />
		<result column="DICT_CODE" property="dictCode" jdbcType="VARCHAR" />
		<result column="ELE_KEY" property="eleKey" jdbcType="VARCHAR" />
		<result column="ELE_VALUE" property="eleValue" jdbcType="VARCHAR" />
	</resultMap>
	<sql id="Base_Column_List">
		ID,DICT_CODE,ELE_KEY,ELE_VALUE
	</sql>

	<select id="searchDict" resultMap="BaseResultMap" parameterType="java.lang.String">
		select
		<include refid="Base_Column_List" />
		from sp_log.tb_dict
		where 1=1
		<if test="dictCode != null and dictCode != ''">
			and DICT_CODE = #{dictCode,jdbcType=VARCHAR}
		</if>
	</select>

</mapper>


text:
	<md-card ng-controller="TodoListController as listCtrl" layout-margin>

	        Todo Items

	        <ng-md-icon id="new-todo-btn" icon="add_circle_outline" size="32" style="fill: white;" hm-tap="listCtrl.newTodo($event)"></ng-md-icon>

	    <md-list layout="column" layout-align="start center" layout-fill>

		        <todo-item flex layout-fill todo="item"></todo-item>
		    	<md-divider flex ng-if="!$last"></md-divider>

	    </md-list>

Nothing todo?!

	</md-card>


text:
module Spree
  class Promotion
    module Actions
      class ConditionalPromotionAction < Spree::PromotionAction

        def eligible?(options = {})
          raise 'eligible?(options={}) should be implemented in a sub-class of ConditionalPromotionAction'
        end

        def perform(options = {})
          if self.eligible?(options)
            perform_eligible_action(options)
          else
            perform_ineligible_action(options)
          end
        end

        def perform_eligible_action(options={})
          raise 'perform_eligible_action(options={}) should be implemented in a sub-class of ConditionalPromotionAction'
        end

        def perform_ineligible_action(options={})
          raise 'perform_ineligible_action(options={}) should be implemented in a sub-class of ConditionalPromotionAction'
        end

      end
    end
  end
end


text:
/**
 * Allow this test suite to be used on custom implementations of db, model and collection.
 */
var _ = require('lodash');
var Backbone = require('backdash');
var modelTests = require('backbone-db/test/test.model');
var collectionTests = require('backbone-db/test/test.collection');
var Db = require('..');
var should = require('chai').should();
describe('backbone-db', function () {

  before(function () {
    this.db = new Db('mymodels');
    this.Model = Backbone.Model.extend({
      url: function () {
        if (this.isNew()) {
          return 'mymodels';
        }
        return 'mymodels:' + this.get(this.idAttribute);
      },
      db: this.db,
      sync: this.db.sync
    });
    this.IndexedModel = this.Model.extend({
      type: 'indexed',
      indexes: [
        {property: 'some_id'}
      ]
    });
    this.Collection = Backbone.Collection.extend({
      url: function () {
        return 'mymodels';
      },
      model: this.Model,
      db: this.db,
      sync: this.db.sync
    });
  });

  describe('Model', function () {
    after(function () {
      this.db = new Db('mymodels');
      this.Collection.prototype.db = this.db;
      this.Model.prototype.db = this.db;
    });
    modelTests();
  });

  describe('Collection', function () {
    after(function () {
      this.db = new Db('mymodels');
      this.Collection.prototype.db = this.db;
      this.Model.prototype.db = this.db;
    });
    collectionTests();
  });

  describe('Delayed mock db', function() {
    it('Should be possible to delay responses', function(next) {
      var db = new Db('mymodels-delayed', {delay: 10});
      var m = new Backbone.Model();
      m.url = function() {
        return '/testiiit' + (this.id ? '/' + this.id : '');
      };
      m.db = db;
      m.sync = db.sync;
      var now = Date.now();
      m.save(null, {
        success: function() {
          m.fetch({
            success: function() {
              ((Date.now() - now) > 20).should.equal(true);
              next();
            }});
        }});
    });
  });
});


text:
package org.springframework.boot.gradle.junit;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.gradle.api.Rule;
import org.junit.runner.Runner;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.Suite;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;

import org.springframework.boot.gradle.testkit.GradleBuild;

/**
 * Custom {@link Suite} that runs tests against multiple version of Gradle. Test classes
 * using the suite must have a public {@link GradleBuild} field named {@code gradleBuild}
 * and annotated with {@link Rule}.
 *
 * @author Andy Wilkinson
 */
public final class GradleCompatibilitySuite extends Suite {

	private static final List<String> GRADLE_VERSIONS = Arrays.asList("default", "3.4.1",
			"3.5", "4.0-rc-1");

	public GradleCompatibilitySuite(Class<?> clazz) throws InitializationError {
		super(clazz, createRunners(clazz));
	}

	private static List<Runner> createRunners(Class<?> clazz) throws InitializationError {
		List<Runner> runners = new ArrayList<>();
		for (String version : GRADLE_VERSIONS) {
			runners.add(new GradleCompatibilityClassRunner(clazz, version));
		}
		return runners;
	}

	private static final class GradleCompatibilityClassRunner
			extends BlockJUnit4ClassRunner {

		private final String gradleVersion;

		private GradleCompatibilityClassRunner(Class<?> klass, String gradleVersion)
				throws InitializationError {
			super(klass);
			this.gradleVersion = gradleVersion;
		}

		@Override
		protected Object createTest() throws Exception {
			Object test = super.createTest();
			configureTest(test);
			return test;
		}

		private void configureTest(Object test) throws Exception {
			GradleBuild gradleBuild = new GradleBuild();
			if (!"default".equals(this.gradleVersion)) {
				gradleBuild = gradleBuild.gradleVersion(this.gradleVersion);
			}
			test.getClass().getField("gradleBuild").set(test, gradleBuild);
		}

		@Override
		protected String getName() {
			return "Gradle " + this.gradleVersion;
		}

		@Override
		protected String testName(FrameworkMethod method) {
			return method.getName() + " [" + getName() + "]";
		}

	}

}


text:
package co.cask.cdap.gateway.handlers;

import co.cask.cdap.common.AlreadyExistsException;
import co.cask.cdap.common.BadRequestException;
import co.cask.cdap.common.conf.CConfiguration;
import co.cask.cdap.common.conf.Constants;
import co.cask.cdap.common.namespace.NamespaceAdmin;
import co.cask.cdap.gateway.handlers.util.AbstractAppFabricHttpHandler;
import co.cask.cdap.proto.Id;
import co.cask.cdap.proto.NamespaceConfig;
import co.cask.cdap.proto.NamespaceMeta;
import co.cask.http.HttpHandler;
import co.cask.http.HttpResponder;
import com.google.common.base.Strings;
import com.google.gson.JsonSyntaxException;
import com.google.inject.Inject;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;

/**
 * The {@link HttpHandler} for handling REST calls to namespace endpoints.
 */
@Path(Constants.Gateway.API_VERSION_3)
public class NamespaceHttpHandler extends AbstractAppFabricHttpHandler {
  private static final Logger LOG = LoggerFactory.getLogger(NamespaceHttpHandler.class);

  private final CConfiguration cConf;
  private final NamespaceAdmin namespaceAdmin;

  @Inject
  public NamespaceHttpHandler(CConfiguration cConf, NamespaceAdmin namespaceAdmin) {
    this.cConf = cConf;
    this.namespaceAdmin = namespaceAdmin;
  }

  @GET
  @Path("/namespaces")
  public void getAllNamespaces(HttpRequest request, HttpResponder responder) throws Exception {
    responder.sendJson(HttpResponseStatus.OK, namespaceAdmin.list());
  }

  @GET
  @Path("/namespaces/{namespace-id}")
  public void getNamespace(HttpRequest request, HttpResponder responder,
                           @PathParam("namespace-id") String namespaceId) throws Exception {
    NamespaceMeta ns = namespaceAdmin.get(Id.Namespace.from(namespaceId));
    responder.sendJson(HttpResponseStatus.OK, ns);
  }

  @PUT
  @Path("/namespaces/{namespace-id}/properties")
  public void updateNamespaceProperties(HttpRequest request, HttpResponder responder,
                                        @PathParam("namespace-id") String namespaceId) throws Exception {
    NamespaceMeta meta = parseBody(request, NamespaceMeta.class);
    namespaceAdmin.updateProperties(Id.Namespace.from(namespaceId), meta);
    responder.sendString(HttpResponseStatus.OK, String.format("Updated properties for namespace '%s'.", namespaceId));
  }

  @PUT
  @Path("/namespaces/{namespace-id}")
  public void create(HttpRequest request, HttpResponder responder, @PathParam("namespace-id") String namespaceId)
    throws Exception {
    Id.Namespace namespace;
    try {
      namespace = Id.Namespace.from(namespaceId);
    } catch (IllegalArgumentException e) {
      throw new BadRequestException("Namespace id can contain only alphanumeric characters or '_'.");
    }

    NamespaceMeta metadata;
    try {
      metadata = parseBody(request, NamespaceMeta.class);
    } catch (JsonSyntaxException e) {
      throw new BadRequestException("Invalid json object provided in request body.");
    }

    if (isReserved(namespaceId)) {
      throw new BadRequestException(String.format("Cannot create the namespace '%s'. '%s' is a reserved namespace.",
                                                  namespaceId, namespaceId));
    }

    NamespaceMeta.Builder builder = new NamespaceMeta.Builder().setName(namespace);

    // Handle optional params
    if (metadata != null) {
      if (metadata.getDescription() != null) {
        builder.setDescription(metadata.getDescription());
      }

      NamespaceConfig config = metadata.getConfig();
      if (config != null && !Strings.isNullOrEmpty(config.getSchedulerQueueName())) {
        builder.setSchedulerQueueName(config.getSchedulerQueueName());
      }
    }

    try {
      namespaceAdmin.create(builder.build());
      responder.sendString(HttpResponseStatus.OK,
                           String.format("Namespace '%s' created successfully.", namespaceId));
    } catch (AlreadyExistsException e) {
      responder.sendString(HttpResponseStatus.OK, String.format("Namespace '%s' already exists.", namespaceId));
    }
  }

  @DELETE
  @Path("/unrecoverable/namespaces/{namespace-id}")
  public void delete(HttpRequest request, HttpResponder responder, @PathParam("namespace-id") String namespace)
    throws Exception {
    if (!cConf.getBoolean(Constants.Dangerous.UNRECOVERABLE_RESET, Constants.Dangerous.DEFAULT_UNRECOVERABLE_RESET)) {
      responder.sendString(HttpResponseStatus.FORBIDDEN,
                           String.format("Namespace '%s' cannot be deleted because '%s' is not enabled. " +
                                           "Please enable it and restart CDAP Master.",
                                         namespace, Constants.Dangerous.UNRECOVERABLE_RESET));
      return;
    }
    Id.Namespace namespaceId = Id.Namespace.from(namespace);
    namespaceAdmin.delete(namespaceId);
    responder.sendStatus(HttpResponseStatus.OK);
  }

  @DELETE
  @Path("/unrecoverable/namespaces/{namespace-id}/datasets")
  public void deleteDatasets(HttpRequest request, HttpResponder responder,
                             @PathParam("namespace-id") String namespace) throws Exception {
    if (!cConf.getBoolean(Constants.Dangerous.UNRECOVERABLE_RESET, Constants.Dangerous.DEFAULT_UNRECOVERABLE_RESET)) {
      responder.sendString(HttpResponseStatus.FORBIDDEN,
                           String.format("All datasets in namespace %s cannot be deleted because '%s' is not enabled." +
                                           " Please enable it and restart CDAP Master.",
                                         namespace, Constants.Dangerous.UNRECOVERABLE_RESET));
      return;
    }
    Id.Namespace namespaceId = Id.Namespace.from(namespace);
    namespaceAdmin.deleteDatasets(namespaceId);
    responder.sendStatus(HttpResponseStatus.OK);
  }

  private boolean isReserved(String namespaceId) {
    return Id.Namespace.DEFAULT.getId().equals(namespaceId) || Id.Namespace.SYSTEM.getId().equals(namespaceId) ||
      Id.Namespace.CDAP.getId().equals(namespaceId);
  }
}


text:
#include "FileFormatOptionsMoXie.h"

namespace Open3DMotion
{
	FileFormatOptionsMoXie::FileFormatOptionsMoXie()
	{
		FormatID = "MoXie";
	}

}


text:
{-# LANGUAGE OverloadedStrings #-}

module Precomputed where

import Data.Text as Text (Text, unpack, take, dropAround)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit ((@?=), testCase)
import NLP.Punkt (split_sentences)

infix 4 :=?=>
data SanityCheck = Singleton Text | (:=?=>) Text [Text] deriving Show

test_cases :: [SanityCheck]
test_cases =
    [ Singleton "Look Ma, sentences!"
    , Singleton
        "Computer security experts question that figure, because Apple does \
        \not fully realize how quickly the N.S.A. supercomputers can crack \
        \codes."
    , "The quick brown T. rex swallowed the lazy, then fled from the F.B.I. \
      \Then he disappeared." :=?=> ["The quick brown T. rex swallowed the lazy, then fled from the F.B.I.", "Then he disappeared."]
    ]

precomputed_tests :: TestTree
precomputed_tests = testGroup "Precomputed splits" $ map mkcase test_cases
    where
    mkcase (Singleton s) = testCase (prefix s) $ split_sentences s @?= [s]
    mkcase (s :=?=> xs) = testCase (prefix s) $ split_sentences s @?= xs
    prefix = Text.unpack . Text.dropAround (== ' ') . Text.take 24


text:
use error::Result;

/// A retrieved offset for a particular partition in the context of an
/// already known topic.
#[derive(Debug)]
pub struct PartitionOffset {
    pub offset: Result<i64>,
    pub partition: i32,
}

/// A retrieved offset of a particular topic partition.
#[derive(Debug)]
pub struct TopicPartitionOffset {
    pub offset: Result<i64>,
    pub topic: String,
    pub partition: i32,
}


text:
#ifndef SDK_ANDROID_SRC_JNI_VIDEO_ENCODER_FACTORY_WRAPPER_H_
#define SDK_ANDROID_SRC_JNI_VIDEO_ENCODER_FACTORY_WRAPPER_H_

#include <jni.h>
#include <vector>

#include "api/video_codecs/sdp_video_format.h"
#include "api/video_codecs/video_encoder_factory.h"
#include "sdk/android/src/jni/jni_helpers.h"

namespace webrtc {
namespace jni {

// Wrapper for Java VideoEncoderFactory class. Delegates method calls through
// JNI and wraps the encoder inside VideoEncoderWrapper.
class VideoEncoderFactoryWrapper : public VideoEncoderFactory {
 public:
  VideoEncoderFactoryWrapper(JNIEnv* jni,
                             const JavaRef<jobject>& encoder_factory);
  ~VideoEncoderFactoryWrapper() override;

  std::unique_ptr<VideoEncoder> CreateVideoEncoder(
      const SdpVideoFormat& format) override;

  // Returns a list of supported codecs in order of preference.
  std::vector<SdpVideoFormat> GetSupportedFormats() const override;

  std::vector<SdpVideoFormat> GetImplementations() const override;

  CodecInfo QueryVideoEncoder(const SdpVideoFormat& format) const override;

  std::unique_ptr<EncoderSelectorInterface> GetEncoderSelector() const override;

 private:
  const ScopedJavaGlobalRef<jobject> encoder_factory_;
  std::vector<SdpVideoFormat> supported_formats_;
  std::vector<SdpVideoFormat> implementations_;
};

}  // namespace jni
}  // namespace webrtc

#endif  // SDK_ANDROID_SRC_JNI_VIDEO_ENCODER_FACTORY_WRAPPER_H_


text:
<?php
/**
* Use this script to help test the network environment prior to a PCF installation
*
**/
require_once('./lib/common.php');

$oFormatter = new TextFormatter();

if(!$oSettingsChecks->failed()) {

    $oRoutingSuite = new RoutingTestSuite("Routing tests");
    foreach($aDomains as $oDomain) {
        $oRoutingSuite->test(new RoutingTest("HTTP ".$oDomain->getName()." test", "http://toto.".$oDomain->getBase().'/json'));
    }
    foreach($aDomains as $oDomain) {
        $oRoutingSuite->test(new RoutingTest("HTTPS ".$oDomain->getName()." test", "https://tata.".$oDomain->getBase().'/json'));
    }
}

include('./lib/index-txt.tpl');

if($oSettingsChecks->failed() || $oRoutingSuite->failed()) {

    echo "*** Some tests failed. Check the log **\n";
    exit(1);

}

echo "*** All test passed ***\n";


text:
<form class="form-inline" ng-submit="jumpToReport(jumpReportId)">

            <input id="jumpToReportId" class="form-control" type="number"
                   ng-model="jumpReportId" placeholder="{{ 'PAGES.SUPERVISOR.TRAVEL_EXPENSE_REPORTS.JUMP_TO_REPORT' | translate }}"/>

    <button type="submit" class="btn btn-primary" translate="ACTIONS.GO"></button>
</form>

<tabset>
    <tab ng-repeat="state in states">
        <tab-heading>
             {{reports[state].page.totalElements}}
        </tab-heading>

                #{{report.id}}
                {{ report.employee.firstName + ' ' + report.employee.lastName }}
                {{ report.total | currency:'€' }}
                {{ report.debitor.name }}
                {{ report.project.name }}
                {{ report.submissionDate | date:'dd.MM.yyyy HH:mm:ss' }}
                {{ report.approver.firstName + ' ' + report.approver.lastName }}
                {{ report.approvalDate | date:'dd.MM.yyyy HH:mm:ss' }}

        <pagination class="pagination-sm" total-items="reports[state].page.totalElements" ng-model="reports[state].page.number" items-per-page="reports[state].page.size"
                    ng-change="setPage(state)" max-size="5"></pagination>
    </tab>
</tabset>


text:
import SimilaritySearch: optimize!
export NaiveBayesClassifier, NaiveBayesKernel, kernel_prob, predict, predict_proba, optimize!

abstract type NaiveBayesKernel end

mutable struct NaiveBayesClassifier{ItemType,LabelType}
    kernel::NaiveBayesKernel
    probs::Vector{Float64}
    le::LabelEncoder{LabelType}
end

include("nbgaussian.jl")
include("nbmultinomial.jl")

function NaiveBayesClassifier(X::AbstractVector{ItemType}, y::AbstractVector{LabelType}; kernel=GaussianKernel) where {ItemType,LabelType}
    le = fit(LabelEncoder, y)
    # y_ = [transform(le, l) for l in y]
    y_ = transform.(le, y)
    probs = Float64[freq/length(y) for freq in le.freqs]
    kernel_ = kernel(X, y_, length(le.labels))
    NaiveBayesClassifier{ItemType,LabelType}(kernel_, probs, le)
end

function predict(nbc::NaiveBayesClassifier{ItemType,LabelType}, vector)::Vector{LabelType} where {ItemType,LabelType}
    y = Vector{LabelType}(undef, length(vector))
    for i in 1:length(vector)
        y[i] = predict_one(nbc, vector[i])
    end

    y
end

function predict_one_proba(nbc::NaiveBayesClassifier{ItemType,LabelType}, x) where {ItemType,LabelType}
    w = kernel_prob(nbc, nbc.kernel, x)
    ws = sum(w)
    @inbounds for i in 1:length(w)
        w[i] /= ws
    end
    w
end

function predict_one(nbc::NaiveBayesClassifier{ItemType,LabelType}, x) where {ItemType,LabelType}
    p, i = findmax(kernel_prob(nbc, nbc.kernel, x))
    inverse_transform(nbc.le, i)
end

function optimize!(nbc::NaiveBayesClassifier{ItemType,LabelType}, X::AbstractVector{ItemType}, y::AbstractVector{LabelType}, scorefun::Function; runs=3, trainratio=0.5, testratio=0.5, folds=0, shufflefolds=true) where {ItemType,LabelType}
    @info "optimizing nbc $(typeof(nbc))"
    # y::Vector{Int} = transform.(nbc.le, y)
    mem = Dict{Any,Float64}()
    function f(train_X, train_y, test_X, test_y)
        tmp = NaiveBayesClassifier(train_X, train_y, kernel=MultinomialKernel)
        for smoothing in [0.0, 0.1, 0.3, 1.0]
            tmp.kernel.smoothing = smoothing
            pred_y = predict(tmp, test_X)
            score = scorefun(test_y, pred_y)
            mem[(MultinomialKernel, smoothing)] = get(mem, (MultinomialKernel, smoothing), 0.0) + score
        end

        tmp.kernel = GaussianKernel(train_X, transform.(tmp.le, train_y), length(tmp.le.labels))
        pred_y = predict(tmp, test_X)
        score = scorefun(test_y, pred_y)
        mem[(GaussianKernel, -1)] = get(mem, (GaussianKernel, -1), 0.0) + score
        0
    end

    if folds > 1
        kfolds(f, X, y, folds=folds, shuffle=shufflefolds)
        bestlist = [(score/folds, conf) for (conf, score) in mem]
    else
        montecarlo(f, X, y, runs=runs, trainratio=trainratio, testratio=testratio)
        bestlist = [(score/runs, conf) for (conf, score) in mem]
    end

    sort!(bestlist, by=x -> (-x[1], x[2][2]))
    best = bestlist[1][2]
    if best[1] == GaussianKernel
        nbc.kernel = GaussianKernel(X, transform.(nbc.le, y), length(nbc.le.labels))
    else
        nbc.kernel = MultinomialKernel(X, transform.(nbc.le, y), length(nbc.le.labels), smoothing=best[2])
    end

    bestlist
end


text:
#ifndef VOIDIR_ARRAY_TYPE_HPP_INCLUDED
#define VOIDIR_ARRAY_TYPE_HPP_INCLUDED

#include <algorithm>
#include <boost/iterator/indirect_iterator.hpp>
#include <cassert>
#include <memory>
#include <type_traits>
#include <iterator>
#include <utility>
#include <vector>
#include <VoidIR/ConstantValue.hpp>
#include <VoidIR/Type.hpp>

namespace VoidIR {

class Context;

/// An array type.
/** It is characterized by the data type of the data contained in the array and
 * the number of elements in the array. */
class ArrayType: public Type, public std::enable_shared_from_this<ArrayType> {
public:
  /// A constant value of array type.
  class Value: public ConstantValue {
  private:
    /// Element values.
    std::vector<std::unique_ptr<VoidIR::ConstantValue>> values;

  public:
    /** @name Vector-like access
     * All references and iterators are invalidated on calls to setValues(). */
    ///@{
    typedef decltype(values)::size_type size_type;

    typedef VoidIR::ConstantValue& reference;
    typedef VoidIR::ConstantValue const& const_reference;
    typedef VoidIR::ConstantValue* pointer;
    typedef VoidIR::ConstantValue const* const_pointer;

    typedef boost::indirect_iterator<decltype(values)::iterator> iterator;
    typedef boost::indirect_iterator<decltype(values)::const_iterator>
      const_iterator;
    typedef boost::indirect_iterator<decltype(values)::reverse_iterator>
      reverse_iterator;
    typedef boost::indirect_iterator<decltype(values)::const_reverse_iterator>
      const_reverse_iterator;

    VoidIR::ConstantValue& at(size_type pos) {
      return *values.at(pos);
    }
    VoidIR::ConstantValue const& at(size_type pos) const {
      return *values.at(pos);
    }
    VoidIR::ConstantValue& operator[](size_type pos) {
      return *values[pos];
    }
    VoidIR::ConstantValue const& operator[](size_type pos) const {
      return *values[pos];
    }
    VoidIR::ConstantValue& front() {
      return *values.front();
    }
    VoidIR::ConstantValue const& front() const {
      return *values.front();
    }
    VoidIR::ConstantValue& back() {
      return *values.back();
    }
    VoidIR::ConstantValue const& back() const {
      return *values.back();
    }

    iterator begin() noexcept { return values.begin(); }
    const_iterator begin() const noexcept { return values.begin(); }
    const_iterator cbegin() const noexcept { return values.cbegin(); }
    iterator end() noexcept { return values.end(); }
    const_iterator end() const noexcept { return values.end(); }
    const_iterator cend() const noexcept { return values.cend(); }
    reverse_iterator rbegin() noexcept { return values.rbegin(); }
    const_reverse_iterator rbegin() const noexcept { return values.rbegin(); }
    const_reverse_iterator crbegin() const noexcept { return values.crbegin(); }
    reverse_iterator rend() noexcept { return values.rend(); }
    const_reverse_iterator rend() const noexcept { return values.rend(); }
    const_reverse_iterator crend() const noexcept { return values.crend(); }

    bool empty() const noexcept { return values.empty(); }
    size_type size() const noexcept { return values.size(); }
    size_type max_size() const noexcept { return values.max_size(); }
    ///@}

    /// Replace the given element value with a new one.
    /** If the iterator is the past-the-end iterator, the behavior is undefined.
     * This is consisted with the way standard containers work given
     * past-the-end iterators.
     *
     * @return an owning pointer to the replaced value.
     *
     * @throws std::invalid_argument if the value's type is different from that
     * required by the array type.
     * @throws std::invalid_argument if the new value is null.
     * @throws VoidIR::ContextException if the value has a different context. */
    std::unique_ptr<VoidIR::ConstantValue> replaceValue(iterator,
      std::unique_ptr<VoidIR::ConstantValue>);

    /// Update the element values.
    /** Accepts a moved container of std::unique_ptr<ConstantValue> by rvalue
     * reference.
     *
     * @tparam Container must model the Container concept.
     *
     * @throws std::invalid_argument if the number or type of values is
     * different from that required by the array type.
     * @throws std::invalid_argument if a value is null.
     * @throws VoidIR::ContextException if a value has a different context. */
    template<typename Container> void setValues(Container&& newValues) {
      return setValuesImpl<std::decay_t<Container>>(std::forward<Container>(
        newValues));
    }

  private:
    /// Create a value of array type.
    /** Type must not be null. This is not actually checked by the constructor;
     * it has to be ensured by the caller.
     * @throws std::invalid_argument if the number or type of values is
     * different from that required by the array type.
     * @throws std::invalid_argument if a value is null.
     * @throws VoidIR::ContextException if something has a different context. */
    Value(std::shared_ptr<ArrayType const>,
      std::vector<std::unique_ptr<VoidIR::ConstantValue>>);

    /// This value's type.
    std::shared_ptr<ArrayType const> type;

    /// Get this value's type.
    virtual std::shared_ptr<Type const> doGetType() const noexcept override {
      return type;
    }

    /// Clone this value.
    virtual std::unique_ptr<ConstantValue> doClone() const override;

    friend class ArrayType;

    /** @brief This function is deleted because a container has to be moved, not
     * copied. */
    template<typename Container> void setValuesImpl(Container const&) = delete;

    /// Update the element values.
    /** Accepts a moved container of std::unique_ptr<ConstantValue> by rvalue
     * reference.
     *
     * @tparam Container must model the Container concept.
     *
     * @throws std::invalid_argument if the number or type of values is
     * different from that required by the array type.
     * @throws std::invalid_argument if a value is null.
     * @throws VoidIR::ContextException if a value has a different context. */
    template<typename Container> void setValuesImpl(Container&& newValues) {
      std::vector<std::unique_ptr<ConstantValue>> vec;
      vec.reserve(newValues.size());
      std::move(newValues.begin(), newValues.end(), std::back_inserter(vec));

      // The caller expects the reference to be moved from, so let's do that.
      Container{std::move(newValues)};

      setValuesImpl<std::vector<std::unique_ptr<ConstantValue>>>(
        std::move(vec));
    }
  };

  /// The type representing array sizes.
  /** This is std::vector::size_type, so that constant array values can be
   * represented. */
  typedef Value::size_type SizeType;

  /// Get the type's array element type.
  std::shared_ptr<Type const> getElement() const noexcept {
    return element;
  }

  /// Get the type's array size.
  SizeType getSize() const noexcept {
    return size;
  }

  /// Create a new array value.
  /** Accepts a moved container of std::unique_ptr<ConstantValue> by rvalue
   * reference.
   *
   * @tparam Container must model the Container concept.
   *
   * @throws std::invalid_argument if the number or type of values is
   * different from that required by the array type.
   * @throws std::invalid_argument if a value is null. */
  template<typename Container> std::unique_ptr<Value> makeValue(
      Container&& values) const {
    return makeValueImpl<std::decay_t<Container>>(std::forward<Container>(
      values));
  }

private:
  /// The type's array element type.
  std::shared_ptr<Type const> element;

  /// The type's array size.
  SizeType size;

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

  friend class Context;

  /// Create a data type given its element type and size.
  /** The element cannot be null and array size cannot be zero. This isn't
   * actually checked by the constructor; this is checked by
   * Context::getArray(). */
  ArrayType(Context& ctx, std::shared_ptr<Type const> element,
      SizeType size) noexcept: Type(ctx), element(element), size(size) {
    assert(0 != element.use_count());
    assert(0 != size);
  }

  /** @brief This function is deleted because a container has to be moved, not
   * copied. */
  template<typename Container> std::unique_ptr<Value>
    makeValueImpl(Container const&) const = delete;

  /// Create a new array value.
  /** Accepts a moved container of std::unique_ptr<ConstantValue> by rvalue
   * reference.
   *
   * @tparam Container must model the Container concept.
   *
   * @throws std::invalid_argument if the number or type of values is
   * different from that required by the array type.
   * @throws std::invalid_argument if a value is null. */
  template<typename Container> std::unique_ptr<Value>
      makeValueImpl(Container&& values) const {
    std::vector<std::unique_ptr<ConstantValue>> vec;
    vec.reserve(values.size());
    std::move(values.begin(), values.end(), std::back_inserter(vec));

    // The caller expects the reference to be moved from, so let's do that.
    Container{std::move(values)};

    return makeValueImpl<std::vector<std::unique_ptr<ConstantValue>>>(
      std::move(vec));
  }
};

template<> void
  ArrayType::Value::setValuesImpl<std::vector<std::unique_ptr<ConstantValue>>>(
  std::vector<std::unique_ptr<ConstantValue>>&&);

template<> std::unique_ptr<ArrayType::Value>
  ArrayType::makeValueImpl<std::vector<std::unique_ptr<ConstantValue>>>(
  std::vector<std::unique_ptr<ConstantValue>>&&) const;

}

#endif


text:
`GOPATH` is set to `/go`, and a `SRCPATH` env var is available, set to `/go/src`.

Make sure to ADD your source into a dir under `SRCPATH` named after your app, or
you'll run into problems finding dependencies. Specifically, don't use
`/usr/local/src`.

## example

```
FROM instructure/golang:1.18

RUN mkdir -p $SRCPATH/myapp
WORKDIR $SRCPATH/myapp

USER root
COPY . .
RUN chown -R docker:docker .
USER docker
RUN go install .

CMD myapp
```


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

<resources>
    <style name="CardTitleStyle">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_margin">16dp</item>
        <item name="android:textSize">24sp</item>
        <item name="android:textColor">@color/white</item>
        <item name="android:layout_alignParentBottom">true</item>
        <item name="android:layout_alignParentLeft">true</item>
    </style>
    <style name="CardBodyStyle">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textSize">16sp</item>
        <item name="android:textColor">@color/gray80</item>
    </style>
    <style name="CardSmallBodyStyle" parent="CardBodyStyle">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textSize">12sp</item>
        <item name="android:textColor">@color/gray60</item>
    </style>
</resources>


text:
using System;
using System.IO;
using Microsoft.Scripting.Hosting;
using WPFPython1.ViewModels.Interfaces;

namespace WPFPython1.ViewModels
{

    public sealed class PythonWrapper : IPythonWrapper
    {

        #region フィールド

        private readonly ScriptRuntime _ScriptRuntime;

        private dynamic _PythonObject;

        private dynamic _PythonTest;

        private readonly string _Path;

        #endregion

        #region コンストラクタ

        public PythonWrapper(ScriptRuntime scriptRuntime, string path)
        {
            if (scriptRuntime == null)
                throw new ArgumentNullException(nameof(scriptRuntime));
            if (path == null)
                throw new ArgumentNullException(nameof(path));

            if (!File.Exists(path))
                throw new FileNotFoundException(path);

            this._ScriptRuntime = scriptRuntime;
            this._Path = path;
            this._PythonObject = this._ScriptRuntime.UseFile(this._Path);
            this._PythonTest = this._PythonObject.PythonTest();
        }

        #endregion

        #region メソッド

        public string ShowMessage()
        {
            return this._PythonTest.showMessage();
        }

        #endregion

    }

}


text:
package mesosphere.marathon.state

import com.codahale.metrics.MetricRegistry
import mesosphere.marathon.MarathonSpec
import mesosphere.marathon.metrics.Metrics
import scala.concurrent.{ Await, Future }
import scala.concurrent.duration._
import org.mockito.Mockito._
import org.scalatest.Matchers
import scala.language.postfixOps
import PathId._

class GroupRepositoryTest extends MarathonSpec with Matchers {

  test("Store canary strategy") {
    val store = mock[MarathonStore[Group]]
    val group = Group("g1".toPath, Set.empty)
    val future = Future.successful(group)
    val versionedKey = s"root:${group.version}"
    val appRepo = mock[AppRepository]

    when(store.store(versionedKey, group)).thenReturn(future)
    when(store.store("root", group)).thenReturn(future)

    val metrics = new Metrics(new MetricRegistry)
    val repo = new GroupRepository(store, appRepo, None, metrics)
    val res = repo.store("root", group)

    assert(group == Await.result(res, 5 seconds), "Should return the correct Group")
    verify(store).store(versionedKey, group)
    verify(store).store(s"root", group)
  }

  test("group back and forth again with rolling strategy") {
    val group = Group("g1".toPath, Set.empty)
    val proto = group.toProto
    val merged = Group.fromProto(proto)
    group should be(merged)
  }
}


text:
/**
 * webswipe Swiping UI library for mobile web apps. Create beautiful swiping transitions for your web app.
 * Dependency free.
 * @author Erlend Ellingsen <erlend.ame@gmail.com>
 * @version 1.0
 * @license MIT
 */

 /**
  * @param {object} userOptsObj
  */
var webswipe = function(userOptsObj){

    //--- START VARS ---

    const self = this;

    this.tools = {}, this.triggers = {};

    let opts = {
        container: 'swipeContainer',
        focussStealer: 'swipeFocusStealer',
        pageContainer: 'pageContainer',
        size: {
            default: true,
            width: null,
            height: null
        },
        pageSecurityMargin: 20, //Used for ensuring that elements such as wrap-text does not show
        baseZIndex: 100,
        tabIndex: 1, //Used for preventing scroll in certian cases
        pageSwitchThreshold: 0.4, //in percentage.
        rapidForceThreshold: 0.05
    };

    //dom vars
    let motherDOM, swipeFocusStealer, pageContainerDOM;

    let pageActive = null;
    let pagePrevious = null;

    let currentPageID = null;

    //trigger vars
    let triggerIsMoving = false;
    let triggerMoveStartX = null;
    let triggerMoveLastX = null;
    let triggerReachedThreshold = false;
    let triggerReachedRapidForceThreshold = false;

    let onSwipeCallback = function(){};

    //misc vars
    let isTouchDevice = false;

    //--- END VARS ---
    //--- START METHODS ---

    this.init = function(userOptsObj) {

        //Detect environment
        isTouchDevice = self.tools.isTouchDevice();

        //Check for user present options
        if (userOptsObj != undefined || userOptsObj != null) {
            for (let prop in userOptsObj) {
                opts[prop] = userOptsObj[prop];
            }
        }

        //Check for custom webswipe dimensions
        if (opts.size.default) {
            let s = self.tools.getDefaultSize();
            opts.size.width = s.width,
            opts.size.height = s.height;
        }

        //Fetch DOM's
        motherDOM = document.getElementById(opts.container);
        swipeFocusStealer = document.getElementById(opts.focussStealer);
        pageContainerDOM = document.getElementById(opts.pageContainer);

        //Apply body styles
        document.body.style.height = '100%';
        document.body.style.width = '100%';

        //Apply mother styles
        motherDOM.style.outline = 'none';
        motherDOM.style.position = 'relative';

        //Apply focus stealer styles & attributes
        swipeFocusStealer.setAttribute('tabindex', opts.tabIndex);

        //Prepare elements
        motherDOM.innerHTML = `

        `;

        pageContainerDOM.style.display = 'none';

        //Append event listeners
        let activePage = document.getElementById('pageActive');
        if (isTouchDevice) {
            //add touch "mouse" listeners
            activePage.addEventListener('touchstart', this.triggers.triggerDown);
            activePage.addEventListener('touchmove', this.triggers.triggerMove);

            activePage.addEventListener('touchend', this.triggers.triggerUp);
            activePage.addEventListener('touchcancel', this.triggers.triggerUp);

            //motherDOM.addeve, this.triggers.triggerLeave);

        } else {
            //add computer "mouse" listeners
            activePage.addEventListener('mousedown', this.triggers.triggerDown);
            activePage.addEventListener('mousemove', this.triggers.triggerMove);
            activePage.addEventListener('mouseup', this.triggers.triggerUp);
            activePage.addEventListener('mouseleave', this.triggers.triggerLeave);
        }

        //end init
    }

    this.initPage = function(DOMReference) {
        let elem = document.getElementById(DOMReference);

        //Apply page styles.
        elem.style.width = opts.size.width;
        elem.style.minWidth = opts.size.width;
        elem.style.height = opts.size.height;
        elem.style.minHeight = opts.size.height;

        elem.style.position = 'absolute';
        elem.style.wordWrap = 'break-word';
        elem.style.overflow = 'hidden';
        elem.style.whiteSpace = 'nowrap';

        return elem;
        //end initPage
    }

    this.initPreviousPage = function(DOMReference, newInnerHTML) {
        let elem = self.initPage(DOMReference);

        //Set html of previous page
        elem.innerHTML = newInnerHTML;

        //Set z- layer
        elem.style.zIndex = opts.baseZIndex;

        //Previous page should be positioned left for active page
        let newLeft = '-' + (elem.offsetWidth + opts.pageSecurityMargin) + 'px';
        elem.style.marginLeft = newLeft;

        return elem;
        //end initPreviousPage
    }

    this.initActivePage = function(DOMReference) {
        let elem = self.initPage(DOMReference);

        //Set z- layer
        elem.style.zIndex = (opts.baseZIndex - 1);

        return elem;
        //end initActivePage
    }

    this.clearPreviousPage = function() {
        if (pagePrevious != null && pagePrevious.nodeName != undefined) pagePrevious.innerHTML = '';
        pagePrevious = null;
    }

    this.setPage = function(DOMReference, callback, useHistory) {

        //Set previous page
        if (pageActive != null && useHistory !== false) {
            pagePrevious = self.initPreviousPage('pagePrevious', pageActive.innerHTML);
        } else if (useHistory == false) {
            //We're not using history. Clear if previous set
            self.clearPreviousPage();
        }

        //Set current page
        let sourceHtml = document.getElementById(DOMReference);
        pageActive = self.initActivePage('pageActive');
        pageActive.innerHTML = sourceHtml.innerHTML;
        pageActive.setAttribute('ws-source-id', DOMReference);

        //Set onSwipeCallback
        if (callback != undefined) onSwipeCallback = callback;

        //Call arrange to organize changes.
        self.arrange();
        //end setPage
    }

    this.setPreviousPage = function(DOMReference) {
        if (pageActive == null) throw "cannot call setPreviousPage before setPage (requires pageActive)";
        let sourceElem = document.getElementById(DOMReference);
        pagePrevious = self.initPreviousPage('pagePrevious', sourceElem.innerHTML);
    }

    this.arrange = function() {
        if (pageActive == null) return;

        //Change styles
        //Set pageActive-style
        pageActive.style.marginLeft = '0px';

        if (pagePrevious == null) return;

        //Set pagePrevious-style
        let newLeft = '-' + (pagePrevious.offsetWidth + opts.pageSecurityMargin) + 'px';
        pagePrevious.style.marginLeft = newLeft;

        //end arrange
    }

    this.swipeBack = function() {
        //Change content
        let activePageDOMId = pageActive.getAttribute('ws-source-id');

        //Check if page previous is set. If then -> switch content.
        if (pagePrevious != null && pagePrevious.nodeName != undefined) {
            pageActive.innerHTML = pagePrevious.innerHTML;
            self.clearPreviousPage();
        }

        //Call callback
        if (typeof onSwipeCallback === 'function') onSwipeCallback();

        self.arrange();

        //end swipeBack
    }

    //-- TRIGGERS --
    this.triggers.triggerDown = function(e) {

        if (pageActive == null || pagePrevious == null) return;

        //Prevent default actions
        e.preventDefault();
        e.stopPropagation();

        let x = self.tools.getCurrentX(e);
        if (x === false) return;

        triggerIsMoving = true;
        triggerReachedThreshold = false;
        triggerReachedRapidForceThreshold = false;
        triggerMoveStartX = x;

        triggerMoveLastX = null;
        //end triggers.triggerDown
    }

    this.triggers.triggerMove = function(e) {
        //Check that pages are set
        if (pageActive == null || pagePrevious == null) return;

        //Prevent default actions
        e.preventDefault();
        e.stopPropagation();

        //Check that is moving
        if (!triggerIsMoving) return false;

        let x = self.tools.getCurrentX(e);
        if (x === false) return;

        //Check that we're dragging correct way...
        if (x < triggerMoveStartX) return false; //TODO: Add support for reverse?
        let movement = x - triggerMoveStartX;

        //If movement is more than treshold, begin blocking normal behaviour
        if (movement >= 100) {
            e.preventDefault();
            e.stopPropagation();

            //Set focus to mother dom
            swipeFocusStealer.focus();
        }

        //Start moving the previous page...
        let previousPageNewLeft = '-' + ((pagePrevious.offsetWidth + opts.pageSecurityMargin) - (movement)) + 'px';
        pagePrevious.style.marginLeft = previousPageNewLeft;

        let activePageNewLeft = movement + 'px';
        pageActive.style.marginLeft = activePageNewLeft;

        //Check threshold
        let threshold = (opts.size.width * opts.pageSwitchThreshold);
        if (movement >= threshold) {
            triggerReachedThreshold = true;
        } else if (triggerMoveLastX != null) {
            //is RapidForceThreshold reached?
            let rapidForceThreshold = (opts.size.width * opts.rapidForceThreshold);
            let lastMovement = x - triggerMoveLastX;

            if (lastMovement >= rapidForceThreshold) triggerReachedRapidForceThreshold = true;
        }

        triggerMoveLastX = x;

        //end triggers.triggerMove
    }

    this.triggers.triggerUp = function(e) {
        if (pageActive == null || pagePrevious == null) return;
        triggerIsMoving = false;

        //Either of thresholds reached?
        if (triggerReachedRapidForceThreshold || triggerReachedThreshold) {
            console.log(`
            triggerReachedRapidForceThreshold: ${triggerReachedRapidForceThreshold}
            triggerReachedThreshold: ${triggerReachedThreshold}
            `);
            self.swipeBack();
        }

        //Re-adjust containers
        self.arrange();

        triggerReachedThreshold = false;
        triggerReachedRapidForceThreshold = false;
        //end triggers.triggerUp
    }

    this.triggers.triggerLeave = function(e) {
        if (pageActive == null || pagePrevious == null) return;
        if (!triggerIsMoving) return;

        //Shut down the current movement (reset vars and call "end" trigger)
        triggerReachedThreshold = false;
        triggerReachedRapidForceThreshold = false;
        self.triggers.triggerUp();
    }

    //-- TOOLS --

    this.tools.getDefaultSize = function() {
        //Credit: https://www.w3schools.com/jsref/prop_win_innerheight.asp
        let w = window.innerWidth
        || document.documentElement.clientWidth
        || document.body.clientWidth;

        let h = window.innerHeight
        || document.documentElement.clientHeight
        || document.body.clientHeight;
        return {
            width: w,
            height: h
        }
    }

    this.tools.isTouchDevice = function() {
        //Credit: https://stackoverflow.com/a/4819886 (blmstr, Simon East)
        return (('ontouchstart' in window        // works on most browsers
            || navigator.maxTouchPoints) == 0 ? false : true);       // works on IE10/11 and Surface
    }

    this.tools.getCurrentX = function(e) {
        let x;
        if (isTouchDevice) {
            if (e.touches.length <= 0) return false; //No touch points
            let t = e.touches[0]; //Fetch first available touch point
            x = t.clientX;
        } else {
            x = e.clientX;
        }
        return x;
    }

    //--- END METHODS ---

    //Initialize the script
    self.init(userOptsObj);

    //end webswipe
}


text:
  echo "do not run this script in one go. hit ctrl-c NOW"
  read -n 1

##############################################################################################################
###  backup old machine's key items

mkdir -p ~/migration/home/
mkdir -p ~/migration/Library/"Application Support"/
mkdir -p ~/migration/Library/Preferences/
mkdir -p ~/migration/rootLibrary/Preferences/SystemConfiguration/

cd ~/migration

# what is worth reinstalling?
brew leaves              > brew-list.txt    # all top-level brew installs
brew cask list           > cask-list.txt
brew bundle dump         # => Brewfile
npm list -g --depth=0    > npm-g-list.txt

# then compare brew-list to what's in `brew.sh`
#   comm <(sort brew-list.txt) <(sort brew.sh-cleaned-up)

# backup some dotfiles likely not under source control
cp -Rp \
    ~/.bash_history \
    ~/.extra \
    ~/.gnupg \
        ~/migration/home

cp -Rp ~/Documents ~/migration

cp -Rp /Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist ~/migration/rootLibrary/Preferences/SystemConfiguration/ # wifi

cp -Rp ~/Library/Preferences/com.tinyspeck.slackmacgap.plist ~/migration/Library/Preferences/

cp -Rp ~/Library/Services ~/migration/Library/ # automator stuff
cp -Rp ~/Library/Fonts ~/migration/Library/ # all those fonts you've installed

# editor settings & plugins
cp -Rp ~/Library/Application\ Support/Sublime\ Text\ * ~/migration/Library/"Application Support"

# also consider...
# random git branches you never pushed anywhere?
# git untracked files (or local gitignored stuff). stuff you never added, but probably want..

# OneTab history pages, because chrome tabs are valuable.

# usage logs you've been keeping.

# iTerm settings.
  # Prefs, General, Use settings from Folder

# Finder settings and TotalFinder settings
#   Not sure how to do this yet. Really want to.

# Timestats chrome extension stats
#   chrome-extension://ejifodhjoeeenihgfpjijjmpomaphmah/options.html#_options
# 	gotta export into JSON through devtools:
#     copy(JSON.stringify(localStorage))
#     pbpaste > timestats-canary.json.txt

# software licenses.
#   sublimetext's is in its Application Support folder

# maybe ~/Pictures and such
cp -Rp ~/Pictures ~/migration

### end of old machine backup
##############################################################################################################

##############################################################################################################
### XCode Command Line Tools
#      thx https://github.com/alrra/dotfiles/blob/ff123ca9b9b/os/os_x/installs/install_xcode.sh

if ! xcode-select --print-path &> /dev/null; then

    # Prompt user to install the XCode Command Line Tools
    xcode-select --install &> /dev/null

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

    # Wait until the XCode Command Line Tools are installed
    until xcode-select --print-path &> /dev/null; do
        sleep 5
    done

    print_result $? 'Install XCode Command Line Tools'

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

    # Point the `xcode-select` developer directory to
    # the appropriate directory from within `Xcode.app`
    # https://github.com/alrra/dotfiles/issues/13

    sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer
    print_result $? 'Make "xcode-select" developer directory point to Xcode'

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

    # Prompt user to agree to the terms of the Xcode license
    # https://github.com/alrra/dotfiles/issues/10

    sudo xcodebuild -license
    print_result $? 'Agree with the XCode Command Line Tools licence'

fi
###
##############################################################################################################

##############################################################################################################
### homebrew!

# (if your machine has /usr/local locked down (like google's), you can do this to place everything in ~/.homebrew
mkdir $HOME/.homebrew && curl -L https://github.com/mxcl/homebrew/tarball/master | tar xz --strip 1 -C $HOME/.homebrew
export PATH=$HOME/.homebrew/bin:$HOME/.homebrew/sbin:$PATH

# install all the things
./brew.sh
./brew-cask.sh

### end of homebrew
##############################################################################################################

##############################################################################################################
### install of common things
###

# github.com/jamiew/git-friendly
# the `push` command which copies the github compare URL to my clipboard is heaven
bash < <( curl https://raw.github.com/jamiew/git-friendly/master/install.sh)

# Type `git open` to open the GitHub page or website for a repository.
npm install -g git-open

# fancy listing of recent branches
npm install -g git-recent

# sexy git diffs
npm install -g diff-so-fancy

# trash as the safe `rm` alternative
npm install --global trash-cli

# github.com/rupa/z   - oh how i love you
git clone https://github.com/rupa/z.git ~/code/z
# consider reusing your current .z file if possible. it's painful to rebuild :)
# z is hooked up in .bash_profile

# iterm with more margin! http://hackr.it/articles/prettier-gutter-in-iterm-2/
#   (admittedly not as easy to maintain)

# setting up the sublime symlink
ln -sf "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl" ~/bin/subl

##############################################################################################################
### remaining configuration
###

# go read mathias, paulmillr, gf3, alraa's dotfiles to see what's worth stealing.

# prezto and antigen communties also have great stuff
#   github.com/sorin-ionescu/prezto/blob/master/modules/utility/init.zsh

# set up osx defaults
#   maybe something else in here https://github.com/hjuutilainen/dotfiles/blob/master/bin/osx-user-defaults.sh
sh .osx

# setup and run Rescuetime!

###
##############################################################################################################


text:
import * as dom5 from 'dom5/lib/index-next';
import * as parse5 from 'parse5';
import stripIndent = require('strip-indent');

import {registry} from '../../registry';
import {HtmlRule} from '../../html/rule';
import {ParsedHtmlDocument, Severity, Warning} from 'polymer-analyzer';

import {nodeIsTemplateExtension} from './utils';

class PaperToolbarV1ToV2 extends HtmlRule {
  code = 'paper-toolbar-v1-to-v2';
  description = stripIndent(`
    Warns when children of <paper-toolbar> do not have slots. <paper-toolbar>
    v2 does not have a default slot and \`class="middle"\` / \`class="bottom"\`
    no longer cause children to be distributed.

    Child elements now need a slot; the 'top' slot is equivalent to the default
    distribution position from v1, the 'middle' and 'bottom' slots correspond to
    the distribution position for elements with 'middle' or 'bottom' as a class.

    Non-whitespace-only child text nodes, which can't be distributed to a named
    slot, should be have their non-whitespace portion wrapped in a span
    distributed to the 'top' slot: \`<span slot="top">\` ... \`</span>\`.

    Example usage of <paper-toolbar> v1:

      <paper-toolbar>

          This element is in the top bar (default).

          This element is in the middle bar.

          This element is in the bottom bar.

        This text node has non-whitespace characters.
      </paper-toolbar>

    After updating to <paper-toolbar> v2:

      <paper-toolbar>

          This element is in the top bar (default).

          This element is in the middle bar.

          This element is in the bottom bar.

        This text node has non-whitespace characters.
      </paper-toolbar>
  `).trim();

  async checkDocument(parsedDocument: ParsedHtmlDocument) {
    const warnings: Warning[] = [];

    const paperToolbars = dom5.queryAll(
        parsedDocument.ast,
        dom5.predicates.hasTagName('paper-toolbar'),
        dom5.childNodesIncludeTemplate);

    const checkNode = (node: dom5.Node) => {
      // Add the appropriate slot for the element: `slot="middle"` or
      // `slot="bottom"` for elements with a 'middle' or 'bottom' class,
      // `slot="top"` for all others.
      if (node.tagName !== undefined && !dom5.hasAttribute(node, 'slot')) {
        let desiredSlot = 'top';
        if (dom5.hasSpaceSeparatedAttrValue('class', 'middle')(node)) {
          desiredSlot = 'middle';
        }
        if (dom5.hasSpaceSeparatedAttrValue('class', 'bottom')(node)) {
          desiredSlot = 'bottom';
        }

        const startTagSourceRange =
            parsedDocument.sourceRangeForStartTag(node)!;
        const [startOffset, endOffset] =
            parsedDocument.sourceRangeToOffsets(startTagSourceRange);
        const startTagText =
            parsedDocument.contents.slice(startOffset, endOffset);
        const isSelfClosing = startTagText.endsWith('/>');

        warnings.push(new Warning({
          parsedDocument,
          code: this.code,
          message: '<paper-toolbar> no longer has a default slot: this ' +
              'element will not appear in the composed tree. Add `slot="top"` ' +
              'to distribute to the same position as the previous default ' +
              'content or `slot="middle"` / `slot="bottom"` to distribute to ' +
              'the middle or bottom bar.',
          severity: Severity.WARNING,
          sourceRange: startTagSourceRange,
          fix: [{
            range: startTagSourceRange,
            replacementText: startTagText.slice(0, isSelfClosing ? -2 : -1) +
                ` slot="${desiredSlot}"` + (isSelfClosing ? '/' : '') + '>',
          }],
        }));
      }

      // Non-whitespace-only text nodes, which were previously distributed into
      // a default slot, now need to be wrapped in `...`.
      if (node.nodeName === '#text' && node.value!.trim() !== '') {
        const textNodeSourceRange = parsedDocument.sourceRangeForNode(node)!;

        const fullText = node.value!;
        const trimmedText = fullText.trim();
        const trimmedOffset = fullText.indexOf(trimmedText);

        const treeAdapter = parse5.treeAdapters.default;
        const fragment = treeAdapter.createDocumentFragment();

        // Leading whitespace:
        dom5.append(fragment, {
          nodeName: '#text',
          value: fullText.substring(0, trimmedOffset),
        } as parse5.ASTNode);

        // Wrapped text:
        const span = treeAdapter.createElement('span', '', []);
        dom5.setAttribute(span, 'slot', 'top');
        dom5.append(span, {
          nodeName: '#text',
          value: trimmedText,
        } as parse5.ASTNode);
        dom5.append(fragment, span);

        // Trailing whitespace:
        dom5.append(fragment, {
          nodeName: '#text',
          value: fullText.substring(trimmedOffset + trimmedText.length),
        } as parse5.ASTNode);

        warnings.push(new Warning({
          parsedDocument,
          code: this.code,
          message: '<paper-toolbar> no longer has a default slot: this ' +
              'text node will not appear in the composed tree. Wrap with ' +
              '`<span slot="top">...</span>` to distribute to the same ' +
              'position as the previous default content.',
          severity: Severity.WARNING,
          sourceRange: textNodeSourceRange,
          fix: [{
            range: textNodeSourceRange,
            replacementText: parse5.serialize(fragment),
          }],
        }));
      }
    };

    for (const paperToolbar of paperToolbars) {
      let suspectNodes = Array.from(paperToolbar.childNodes!);

      while (suspectNodes.some(nodeIsTemplateExtension)) {
        suspectNodes =
            suspectNodes
                .map((node) => {
                  if (nodeIsTemplateExtension(node)) {
                    return Array.from(dom5.childNodesIncludeTemplate(node)!);
                  }

                  return [node];
                })
                .reduce((a, b) => a.concat(b), []);
      }

      for (const node of suspectNodes) {
        checkNode(node);
      }
    }

    return warnings;
  }
}

registry.register(new PaperToolbarV1ToV2());


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Webbia 10: 444 (1954)

#### Original name
Thelidium politum Servít

### Remarks
null


text:
package org.spotter.core.test.dummies.detection;

import org.spotter.core.detection.AbstractDetectionExtension;
import org.spotter.core.detection.IDetectionController;

public class DetectionEExtension extends AbstractDetectionExtension{

	@Override
	public IDetectionController createExtensionArtifact() {
		return new DetectionE(this);
	}

	@Override
	public String getName() {
		return "DetectionE";
	}

	@Override
	protected void initializeConfigurationParameters() {

	}

}


text:
package pl.java.scalatech.domain;

import java.io.Serializable;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Version;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@MappedSuperclass
@EqualsAndHashCode(of="id")
@ToString(exclude="version")
public abstract class AbstractEntity implements Serializable {
    private static final long serialVersionUID = 1764429777262538648L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Getter
    @Setter
    protected Long id;

    @Version
    @Getter
    private Long version;

}


text:
require 'fileutils'

module Rake
  module Microsecond
    class Base < Task
      attr_accessor :timestamp

      def prerequisites_needed?
        prerequisites.any? do |n|
          task = application[n]
          if task.is_a?(Rake::FileTask) or
            task.is_a?(self.class)
            task.timestamp > @timestamp
          else
            task.needed?
          end
        end
      end
    end

    # Compensate for file systems with 1s resolution
    class FileTask < Base
      def self.define_task( *args, &block )
        task = super( *args, &block )
        task.timestamp = nil
        task
      end

      def needed?
        return true if not File.exist?(self.name)
        @timestamp ||= File.stat(self.name).mtime
        prerequisites_needed?
      end

      def execute(*args)
        @timestamp = Time.now
        super(*args)
      end
    end

    class DirectoryTask < Base
      include FileUtils

      attr_accessor :path

      def self.define_task(*args, &block)
        task           = super(*args, &block)
        task.path      = args[0]
        task.timestamp = nil
        task
      end

      def needed?
        return true if not File.directory?(self.path)
        @timestamp ||= File.stat(self.path).mtime
        prerequisites_needed?
      end

      def execute(*args)
        mkdir_p self.path, :verbose => false
        @timestamp = Time.now
        super(*args)
      end
    end
  end
end

def microsecond_file(*args, &block)
  Rake::Microsecond::FileTask.define_task(*args, &block)
end

def microsecond_directory(*args, &block)
  Rake::Microsecond::DirectoryTask.define_task(*args, &block)
end