text:
package registry

import (
	"encoding/json"
	"reflect"
	"testing"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/labels"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
	"github.com/coreos/go-etcd/etcd"
)

func MakeTestEtcdRegistry(client util.EtcdClient, machines []string) *EtcdRegistry {
	registry := MakeEtcdRegistry(client, machines)
	registry.manifestFactory = &BasicManifestFactory{
		serviceRegistry: &MockServiceRegistry{},
	}
	return registry
}

func TestEtcdGetPod(t *testing.T) {
	fakeClient := util.MakeFakeEtcdClient(t)
	fakeClient.Set("/registry/hosts/machine/pods/foo", util.MakeJSONString(api.Pod{JSONBase: api.JSONBase{ID: "foo"}}), 0)
	registry := MakeTestEtcdRegistry(fakeClient, []string{"machine"})
	pod, err := registry.GetPod("foo")
	expectNoError(t, err)
	if pod.ID != "foo" {
		t.Errorf("Unexpected pod: %#v", pod)
	}
}

func TestEtcdGetPodNotFound(t *testing.T) {
	fakeClient := util.MakeFakeEtcdClient(t)
	fakeClient.Data["/registry/hosts/machine/pods/foo"] = util.EtcdResponseWithError{
		R: &etcd.Response{
			Node: nil,
		},
		E: &etcd.EtcdError{
			ErrorCode: 100,
		},
	}
	registry := MakeTestEtcdRegistry(fakeClient, []string{"machine"})
	_, err := registry.GetPod("foo")
	if err == nil {
		t.Errorf("Unexpected non-error.")
	}
}

func TestEtcdCreatePod(t *testing.T) {
	fakeClient := util.MakeFakeEtcdClient(t)
	fakeClient.Data["/registry/hosts/machine/pods/foo"] = util.EtcdResponseWithError{
		R: &etcd.Response{
			Node: nil,
		},
		E: &etcd.EtcdError{ErrorCode: 100},
	}
	fakeClient.Set("/registry/hosts/machine/kubelet", util.MakeJSONString([]api.ContainerManifest{}), 0)
	registry := MakeTestEtcdRegistry(fakeClient, []string{"machine"})
	err := registry.CreatePod("machine", api.Pod{
		JSONBase: api.JSONBase{
			ID: "foo",
		},
		DesiredState: api.PodState{
			Manifest: api.ContainerManifest{
				Containers: []api.Container{
					{
						Name: "foo",
					},
				},
			},
		},
	})
	expectNoError(t, err)
	resp, err := fakeClient.Get("/registry/hosts/machine/pods/foo", false, false)
	expectNoError(t, err)
	var pod api.Pod
	err = json.Unmarshal([]byte(resp.Node.Value), &pod)
	expectNoError(t, err)
	if pod.ID != "foo" {
		t.Errorf("Unexpected pod: %#v %s", pod, resp.Node.Value)
	}
	var manifests []api.ContainerManifest
	resp, err = fakeClient.Get("/registry/hosts/machine/kubelet", false, false)
	expectNoError(t, err)
	err = json.Unmarshal([]byte(resp.Node.Value), &manifests)
	if len(manifests) != 1 || manifests[0].Id != "foo" {
		t.Errorf("Unexpected manifest list: %#v", manifests)
	}
}

func TestEtcdCreatePodAlreadyExisting(t *testing.T) {
	fakeClient := util.MakeFakeEtcdClient(t)
	fakeClient.Data["/registry/hosts/machine/pods/foo"] = util.EtcdResponseWithError{
		R: &etcd.Response{
			Node: &etcd.Node{
				Value: util.MakeJSONString(api.Pod{JSONBase: api.JSONBase{ID: "foo"}}),
			},
		},
		E: nil,
	}
	registry := MakeTestEtcdRegistry(fakeClient, []string{"machine"})
	err := registry.CreatePod("machine", api.Pod{
		JSONBase: api.JSONBase{
			ID: "foo",
		},
	})
	if err == nil {
		t.Error("Unexpected non-error")
	}
}

func TestEtcdCreatePodWithContainersError(t *testing.T) {
	fakeClient := util.MakeFakeEtcdClient(t)
	fakeClient.Data["/registry/hosts/machine/pods/foo"] = util.EtcdResponseWithError{
		R: &etcd.Response{
			Node: nil,
		},
		E: &etcd.EtcdError{ErrorCode: 100},
	}
	fakeClient.Data["/registry/hosts/machine/kubelet"] = util.EtcdResponseWithError{
		R: &etcd.Response{
			Node: nil,
		},
		E: &etcd.EtcdError{ErrorCode: 200},
	}
	registry := MakeTestEtcdRegistry(fakeClient, []string{"machine"})
	err := registry.CreatePod("machine", api.Pod{
		JSONBase: api.JSONBase{
			ID: "foo",
		},
	})
	if err == nil {
		t.Error("Unexpected non-error")
	}
	_, err = fakeClient.Get("/registry/hosts/machine/pods/foo", false, false)
	if err == nil {
		t.Error("Unexpected non-error")
	}
	if err != nil && err.(*etcd.EtcdError).ErrorCode != 100 {
		t.Errorf("Unexpected error: %#v", err)
	}
}

func TestEtcdCreatePodWithContainersNotFound(t *testing.T) {
	fakeClient := util.MakeFakeEtcdClient(t)
	fakeClient.Data["/registry/hosts/machine/pods/foo"] = util.EtcdResponseWithError{
		R: &etcd.Response{
			Node: nil,
		},
		E: &etcd.EtcdError{ErrorCode: 100},
	}
	fakeClient.Data["/registry/hosts/machine/kubelet"] = util.EtcdResponseWithError{
		R: &etcd.Response{
			Node: nil,
		},
		E: &etcd.EtcdError{ErrorCode: 100},
	}
	registry := MakeTestEtcdRegistry(fakeClient, []string{"machine"})
	err := registry.CreatePod("machine", api.Pod{
		JSONBase: api.JSONBase{
			ID: "foo",
		},
		DesiredState: api.PodState{
			Manifest: api.ContainerManifest{
				Id: "foo",
				Containers: []api.Container{
					{
						Name: "foo",
					},
				},
			},
		},
	})
	expectNoError(t, err)
	resp, err := fakeClient.Get("/registry/hosts/machine/pods/foo", false, false)
	expectNoError(t, err)
	var pod api.Pod
	err = json.Unmarshal([]byte(resp.Node.Value), &pod)
	expectNoError(t, err)
	if pod.ID != "foo" {
		t.Errorf("Unexpected pod: %#v %s", pod, resp.Node.Value)
	}
	var manifests []api.ContainerManifest
	resp, err = fakeClient.Get("/registry/hosts/machine/kubelet", false, false)
	expectNoError(t, err)
	err = json.Unmarshal([]byte(resp.Node.Value), &manifests)
	if len(manifests) != 1 || manifests[0].Id != "foo" {
		t.Errorf("Unexpected manifest list: %#v", manifests)
	}
}

func TestEtcdCreatePodWithExistingContainers(t *testing.T) {
	fakeClient := util.MakeFakeEtcdClient(t)
	fakeClient.Data["/registry/hosts/machine/pods/foo"] = util.EtcdResponseWithError{
		R: &etcd.Response{
			Node: nil,
		},
		E: &etcd.EtcdError{ErrorCode: 100},
	}
	fakeClient.Set("/registry/hosts/machine/kubelet", util.MakeJSONString([]api.ContainerManifest{
		{
			Id: "bar",
		},
	}), 0)
	registry := MakeTestEtcdRegistry(fakeClient, []string{"machine"})
	err := registry.CreatePod("machine", api.Pod{
		JSONBase: api.JSONBase{
			ID: "foo",
		},
		DesiredState: api.PodState{
			Manifest: api.ContainerManifest{
				Id: "foo",
				Containers: []api.Container{
					{
						Name: "foo",
					},
				},
			},
		},
	})
	expectNoError(t, err)
	resp, err := fakeClient.Get("/registry/hosts/machine/pods/foo", false, false)
	expectNoError(t, err)
	var pod api.Pod
	err = json.Unmarshal([]byte(resp.Node.Value), &pod)
	expectNoError(t, err)
	if pod.ID != "foo" {
		t.Errorf("Unexpected pod: %#v %s", pod, resp.Node.Value)
	}
	var manifests []api.ContainerManifest
	resp, err = fakeClient.Get("/registry/hosts/machine/kubelet", false, false)
	expectNoError(t, err)
	err = json.Unmarshal([]byte(resp.Node.Value), &manifests)
	if len(manifests) != 2 || manifests[1].Id != "foo" {
		t.Errorf("Unexpected manifest list: %#v", manifests)
	}
}

func TestEtcdDeletePod(t *testing.T) {
	fakeClient := util.MakeFakeEtcdClient(t)
	key := "/registry/hosts/machine/pods/foo"
	fakeClient.Set(key, util.MakeJSONString(api.Pod{JSONBase: api.JSONBase{ID: "foo"}}), 0)
	fakeClient.Set("/registry/hosts/machine/kubelet", util.MakeJSONString([]api.ContainerManifest{
		{
			Id: "foo",
		},
	}), 0)
	registry := MakeTestEtcdRegistry(fakeClient, []string{"machine"})
	err := registry.DeletePod("foo")
	expectNoError(t, err)
	if len(fakeClient.DeletedKeys) != 1 {
		t.Errorf("Expected 1 delete, found %#v", fakeClient.DeletedKeys)
	}
	if fakeClient.DeletedKeys[0] != key {
		t.Errorf("Unexpected key: %s, expected %s", fakeClient.DeletedKeys[0], key)
	}
	response, _ := fakeClient.Get("/registry/hosts/machine/kubelet", false, false)
	if response.Node.Value != "[]" {
		t.Errorf("Unexpected container set: %s, expected empty", response.Node.Value)
	}
}

func TestEtcdDeletePodMultipleContainers(t *testing.T) {
	fakeClient := util.MakeFakeEtcdClient(t)
	key := "/registry/hosts/machine/pods/foo"
	fakeClient.Set(key, util.MakeJSONString(api.Pod{JSONBase: api.JSONBase{ID: "foo"}}), 0)
	fakeClient.Set("/registry/hosts/machine/kubelet", util.MakeJSONString([]api.ContainerManifest{
		{Id: "foo"},
		{Id: "bar"},
	}), 0)
	registry := MakeTestEtcdRegistry(fakeClient, []string{"machine"})
	err := registry.DeletePod("foo")
	expectNoError(t, err)
	if len(fakeClient.DeletedKeys) != 1 {
		t.Errorf("Expected 1 delete, found %#v", fakeClient.DeletedKeys)
	}
	if fakeClient.DeletedKeys[0] != key {
		t.Errorf("Unexpected key: %s, expected %s", fakeClient.DeletedKeys[0], key)
	}
	response, _ := fakeClient.Get("/registry/hosts/machine/kubelet", false, false)
	var manifests []api.ContainerManifest
	json.Unmarshal([]byte(response.Node.Value), &manifests)
	if len(manifests) != 1 {
		t.Errorf("Unexpected manifest set: %#v, expected empty", manifests)
	}
	if manifests[0].Id != "bar" {
		t.Errorf("Deleted wrong manifest: %#v", manifests)
	}
}

func TestEtcdEmptyListPods(t *testing.T) {
	fakeClient := util.MakeFakeEtcdClient(t)
	key := "/registry/hosts/machine/pods"
	fakeClient.Data[key] = util.EtcdResponseWithError{
		R: &etcd.Response{
			Node: &etcd.Node{
				Nodes: []*etcd.Node{},
			},
		},
		E: nil,
	}
	registry := MakeTestEtcdRegistry(fakeClient, []string{"machine"})
	pods, err := registry.ListPods(labels.Everything())
	expectNoError(t, err)
	if len(pods) != 0 {
		t.Errorf("Unexpected pod list: %#v", pods)
	}
}

func TestEtcdListPodsNotFound(t *testing.T) {
	fakeClient := util.MakeFakeEtcdClient(t)
	key := "/registry/hosts/machine/pods"
	fakeClient.Data[key] = util.EtcdResponseWithError{
		R: &etcd.Response{},
		E: &etcd.EtcdError{ErrorCode: 100},
	}
	registry := MakeTestEtcdRegistry(fakeClient, []string{"machine"})
	pods, err := registry.ListPods(labels.Everything())
	expectNoError(t, err)
	if len(pods) != 0 {
		t.Errorf("Unexpected pod list: %#v", pods)
	}
}

func TestEtcdListPods(t *testing.T) {
	fakeClient := util.MakeFakeEtcdClient(t)
	key := "/registry/hosts/machine/pods"
	fakeClient.Data[key] = util.EtcdResponseWithError{
		R: &etcd.Response{
			Node: &etcd.Node{
				Nodes: []*etcd.Node{
					{
						Value: util.MakeJSONString(api.Pod{JSONBase: api.JSONBase{ID: "foo"}}),
					},
					{
						Value: util.MakeJSONString(api.Pod{JSONBase: api.JSONBase{ID: "bar"}}),
					},
				},
			},
		},
		E: nil,
	}
	registry := MakeTestEtcdRegistry(fakeClient, []string{"machine"})
	pods, err := registry.ListPods(labels.Everything())
	expectNoError(t, err)
	if len(pods) != 2 || pods[0].ID != "foo" || pods[1].ID != "bar" {
		t.Errorf("Unexpected pod list: %#v", pods)
	}
	if pods[0].CurrentState.Host != "machine" ||
		pods[1].CurrentState.Host != "machine" {
		t.Errorf("Failed to populate host name.")
	}
}

func TestEtcdListControllersNotFound(t *testing.T) {
	fakeClient := util.MakeFakeEtcdClient(t)
	key := "/registry/controllers"
	fakeClient.Data[key] = util.EtcdResponseWithError{
		R: &etcd.Response{},
		E: &etcd.EtcdError{ErrorCode: 100},
	}
	registry := MakeTestEtcdRegistry(fakeClient, []string{"machine"})
	controllers, err := registry.ListControllers()
	expectNoError(t, err)
	if len(controllers) != 0 {
		t.Errorf("Unexpected controller list: %#v", controllers)
	}
}

func TestEtcdListServicesNotFound(t *testing.T) {
	fakeClient := util.MakeFakeEtcdClient(t)
	key := "/registry/services/specs"
	fakeClient.Data[key] = util.EtcdResponseWithError{
		R: &etcd.Response{},
		E: &etcd.EtcdError{ErrorCode: 100},
	}
	registry := MakeTestEtcdRegistry(fakeClient, []string{"machine"})
	services, err := registry.ListServices()
	expectNoError(t, err)
	if len(services.Items) != 0 {
		t.Errorf("Unexpected controller list: %#v", services)
	}
}

func TestEtcdListControllers(t *testing.T) {
	fakeClient := util.MakeFakeEtcdClient(t)
	key := "/registry/controllers"
	fakeClient.Data[key] = util.EtcdResponseWithError{
		R: &etcd.Response{
			Node: &etcd.Node{
				Nodes: []*etcd.Node{
					{
						Value: util.MakeJSONString(api.ReplicationController{JSONBase: api.JSONBase{ID: "foo"}}),
					},
					{
						Value: util.MakeJSONString(api.ReplicationController{JSONBase: api.JSONBase{ID: "bar"}}),
					},
				},
			},
		},
		E: nil,
	}
	registry := MakeTestEtcdRegistry(fakeClient, []string{"machine"})
	controllers, err := registry.ListControllers()
	expectNoError(t, err)
	if len(controllers) != 2 || controllers[0].ID != "foo" || controllers[1].ID != "bar" {
		t.Errorf("Unexpected controller list: %#v", controllers)
	}
}

func TestEtcdGetController(t *testing.T) {
	fakeClient := util.MakeFakeEtcdClient(t)
	fakeClient.Set("/registry/controllers/foo", util.MakeJSONString(api.ReplicationController{JSONBase: api.JSONBase{ID: "foo"}}), 0)
	registry := MakeTestEtcdRegistry(fakeClient, []string{"machine"})
	ctrl, err := registry.GetController("foo")
	expectNoError(t, err)
	if ctrl.ID != "foo" {
		t.Errorf("Unexpected controller: %#v", ctrl)
	}
}

func TestEtcdGetControllerNotFound(t *testing.T) {
	fakeClient := util.MakeFakeEtcdClient(t)
	fakeClient.Data["/registry/controllers/foo"] = util.EtcdResponseWithError{
		R: &etcd.Response{
			Node: nil,
		},
		E: &etcd.EtcdError{
			ErrorCode: 100,
		},
	}
	registry := MakeTestEtcdRegistry(fakeClient, []string{"machine"})
	ctrl, err := registry.GetController("foo")
	if ctrl != nil {
		t.Errorf("Unexpected non-nil controller: %#v", ctrl)
	}
	if err == nil {
		t.Error("Unexpected non-error.")
	}
}

func TestEtcdDeleteController(t *testing.T) {
	fakeClient := util.MakeFakeEtcdClient(t)
	registry := MakeTestEtcdRegistry(fakeClient, []string{"machine"})
	err := registry.DeleteController("foo")
	expectNoError(t, err)
	if len(fakeClient.DeletedKeys) != 1 {
		t.Errorf("Expected 1 delete, found %#v", fakeClient.DeletedKeys)
	}
	key := "/registry/controllers/foo"
	if fakeClient.DeletedKeys[0] != key {
		t.Errorf("Unexpected key: %s, expected %s", fakeClient.DeletedKeys[0], key)
	}
}

func TestEtcdCreateController(t *testing.T) {
	fakeClient := util.MakeFakeEtcdClient(t)
	registry := MakeTestEtcdRegistry(fakeClient, []string{"machine"})
	err := registry.CreateController(api.ReplicationController{
		JSONBase: api.JSONBase{
			ID: "foo",
		},
	})
	expectNoError(t, err)
	resp, err := fakeClient.Get("/registry/controllers/foo", false, false)
	expectNoError(t, err)
	var ctrl api.ReplicationController
	err = json.Unmarshal([]byte(resp.Node.Value), &ctrl)
	expectNoError(t, err)
	if ctrl.ID != "foo" {
		t.Errorf("Unexpected pod: %#v %s", ctrl, resp.Node.Value)
	}
}

func TestEtcdUpdateController(t *testing.T) {
	fakeClient := util.MakeFakeEtcdClient(t)
	fakeClient.Set("/registry/controllers/foo", util.MakeJSONString(api.ReplicationController{JSONBase: api.JSONBase{ID: "foo"}}), 0)
	registry := MakeTestEtcdRegistry(fakeClient, []string{"machine"})
	err := registry.UpdateController(api.ReplicationController{
		JSONBase: api.JSONBase{ID: "foo"},
		DesiredState: api.ReplicationControllerState{
			Replicas: 2,
		},
	})
	expectNoError(t, err)
	ctrl, err := registry.GetController("foo")
	if ctrl.DesiredState.Replicas != 2 {
		t.Errorf("Unexpected controller: %#v", ctrl)
	}
}

func TestEtcdListServices(t *testing.T) {
	fakeClient := util.MakeFakeEtcdClient(t)
	key := "/registry/services/specs"
	fakeClient.Data[key] = util.EtcdResponseWithError{
		R: &etcd.Response{
			Node: &etcd.Node{
				Nodes: []*etcd.Node{
					{
						Value: util.MakeJSONString(api.Service{JSONBase: api.JSONBase{ID: "foo"}}),
					},
					{
						Value: util.MakeJSONString(api.Service{JSONBase: api.JSONBase{ID: "bar"}}),
					},
				},
			},
		},
		E: nil,
	}
	registry := MakeTestEtcdRegistry(fakeClient, []string{"machine"})
	services, err := registry.ListServices()
	expectNoError(t, err)
	if len(services.Items) != 2 || services.Items[0].ID != "foo" || services.Items[1].ID != "bar" {
		t.Errorf("Unexpected pod list: %#v", services)
	}
}

func TestEtcdCreateService(t *testing.T) {
	fakeClient := util.MakeFakeEtcdClient(t)
	fakeClient.Data["/registry/services/specs/foo"] = util.EtcdResponseWithError{
		R: &etcd.Response{
			Node: nil,
		},
		E: &etcd.EtcdError{ErrorCode: 100},
	}
	registry := MakeTestEtcdRegistry(fakeClient, []string{"machine"})
	err := registry.CreateService(api.Service{
		JSONBase: api.JSONBase{ID: "foo"},
	})
	expectNoError(t, err)
	resp, err := fakeClient.Get("/registry/services/specs/foo", false, false)
	expectNoError(t, err)
	var service api.Service
	err = json.Unmarshal([]byte(resp.Node.Value), &service)
	expectNoError(t, err)
	if service.ID != "foo" {
		t.Errorf("Unexpected service: %#v %s", service, resp.Node.Value)
	}
}

func TestEtcdGetService(t *testing.T) {
	fakeClient := util.MakeFakeEtcdClient(t)
	fakeClient.Set("/registry/services/specs/foo", util.MakeJSONString(api.Service{JSONBase: api.JSONBase{ID: "foo"}}), 0)
	registry := MakeTestEtcdRegistry(fakeClient, []string{"machine"})
	service, err := registry.GetService("foo")
	expectNoError(t, err)
	if service.ID != "foo" {
		t.Errorf("Unexpected pod: %#v", service)
	}
}

func TestEtcdGetServiceNotFound(t *testing.T) {
	fakeClient := util.MakeFakeEtcdClient(t)
	fakeClient.Data["/registry/services/specs/foo"] = util.EtcdResponseWithError{
		R: &etcd.Response{
			Node: nil,
		},
		E: &etcd.EtcdError{
			ErrorCode: 100,
		},
	}
	registry := MakeTestEtcdRegistry(fakeClient, []string{"machine"})
	_, err := registry.GetService("foo")
	if err == nil {
		t.Errorf("Unexpected non-error.")
	}
}

func TestEtcdDeleteService(t *testing.T) {
	fakeClient := util.MakeFakeEtcdClient(t)
	registry := MakeTestEtcdRegistry(fakeClient, []string{"machine"})
	err := registry.DeleteService("foo")
	expectNoError(t, err)
	if len(fakeClient.DeletedKeys) != 2 {
		t.Errorf("Expected 2 delete, found %#v", fakeClient.DeletedKeys)
	}
	key := "/registry/services/specs/foo"
	if fakeClient.DeletedKeys[0] != key {
		t.Errorf("Unexpected key: %s, expected %s", fakeClient.DeletedKeys[0], key)
	}
	key = "/registry/services/endpoints/foo"
	if fakeClient.DeletedKeys[1] != key {
		t.Errorf("Unexpected key: %s, expected %s", fakeClient.DeletedKeys[1], key)
	}
}

func TestEtcdUpdateService(t *testing.T) {
	fakeClient := util.MakeFakeEtcdClient(t)
	fakeClient.Set("/registry/services/specs/foo", util.MakeJSONString(api.Service{JSONBase: api.JSONBase{ID: "foo"}}), 0)
	registry := MakeTestEtcdRegistry(fakeClient, []string{"machine"})
	testService := api.Service{
		JSONBase: api.JSONBase{ID: "foo"},
		Labels: map[string]string{
			"baz": "bar",
		},
		Selector: map[string]string{
			"baz": "bar",
		},
	}
	err := registry.UpdateService(testService)
	expectNoError(t, err)
	svc, err := registry.GetService("foo")
	expectNoError(t, err)
	if !reflect.DeepEqual(*svc, testService) {
		t.Errorf("Unexpected service: got %#v, wanted %#v", svc, testService)
	}
}

func TestEtcdUpdateEndpoints(t *testing.T) {
	fakeClient := util.MakeFakeEtcdClient(t)
	registry := MakeTestEtcdRegistry(fakeClient, []string{"machine"})
	endpoints := api.Endpoints{
		Name:      "foo",
		Endpoints: []string{"baz", "bar"},
	}
	err := registry.UpdateEndpoints(endpoints)
	expectNoError(t, err)
	response, err := fakeClient.Get("/registry/services/endpoints/foo", false, false)
	expectNoError(t, err)
	var endpointsOut api.Endpoints
	err = json.Unmarshal([]byte(response.Node.Value), &endpointsOut)
	if !reflect.DeepEqual(endpoints, endpointsOut) {
		t.Errorf("Unexpected endpoints: %#v, expected %#v", endpointsOut, endpoints)
	}
}


text:
import { PrismaClient } from '@prisma/client'

async function main() {
  const prisma = new PrismaClient()

  const data = await prisma.record.findFirst()

  console.log(data)
  await prisma.$disconnect()
}

main()

redpajama_set_name: RedPajamaGithub


text:
package org.apache.drill.exec;

import com.codahale.metrics.MetricRegistry;
import mockit.Mock;
import mockit.MockUp;
import mockit.NonStrictExpectations;
import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;
import org.apache.drill.common.config.DrillConfig;
import org.apache.drill.common.expression.LogicalExpression;
import org.apache.drill.common.expression.parser.ExprLexer;
import org.apache.drill.common.expression.parser.ExprParser;
import org.apache.drill.common.scanner.ClassPathScanner;
import org.apache.drill.exec.compile.CodeCompilerTestFactory;
import org.apache.drill.exec.memory.RootAllocatorFactory;
import org.apache.drill.exec.metrics.DrillMetrics;
import org.apache.drill.exec.physical.impl.OperatorCreatorRegistry;
import org.apache.drill.exec.planner.PhysicalPlanReaderTestFactory;
import org.apache.drill.exec.server.DrillbitContext;
import org.apache.drill.exec.server.options.SystemOptionManager;
import org.apache.drill.exec.store.sys.store.provider.LocalPersistentStoreProvider;
import org.apache.drill.exec.util.GuavaPatcher;
import org.apache.drill.test.DrillTest;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.joda.time.DateTimeUtils;
import org.joda.time.DateTimeZone;
import org.junit.After;
import org.junit.BeforeClass;
import java.io.IOException;
import java.text.DateFormatSymbols;
import java.util.Locale;

public class ExecTest extends DrillTest {

  protected static SystemOptionManager optionManager;
  static {
    GuavaPatcher.patch();
  }

  protected static final DrillConfig c = DrillConfig.create();

  @After
  public void clear(){
    // TODO:  (Re DRILL-1735) Check whether still needed now that
    // BootstrapContext.close() resets the metrics.
    DrillMetrics.resetMetrics();
  }

  @BeforeClass
  public static void setupOptionManager() throws Exception{
    final LocalPersistentStoreProvider provider = new LocalPersistentStoreProvider(c);
    provider.start();
    optionManager = new SystemOptionManager(PhysicalPlanReaderTestFactory.defaultLogicalPlanPersistence(c), provider,c);
    optionManager.init();
  }

  /**
   * Creates instance of local file system.
   *
   * @return local file system
   */
  public static FileSystem getLocalFileSystem() throws IOException {
    Configuration configuration = new Configuration();
    configuration.set(FileSystem.FS_DEFAULT_NAME_KEY, FileSystem.DEFAULT_FS);
    return FileSystem.get(configuration);
  }

  protected void mockDrillbitContext(final DrillbitContext bitContext) throws Exception {
    new NonStrictExpectations() {{
      bitContext.getMetrics(); result = new MetricRegistry();
      bitContext.getAllocator(); result = RootAllocatorFactory.newRoot(c);
      bitContext.getOperatorCreatorRegistry(); result = new OperatorCreatorRegistry(ClassPathScanner.fromPrescan(c));
      bitContext.getConfig(); result = c;
      bitContext.getOptionManager(); result = optionManager;
      bitContext.getCompiler(); result = CodeCompilerTestFactory.getTestCompiler(c);
    }};
  }

  protected LogicalExpression parseExpr(String expr) throws RecognitionException {
    final ExprLexer lexer = new ExprLexer(new ANTLRStringStream(expr));
    final CommonTokenStream tokens = new CommonTokenStream(lexer);
    final ExprParser parser = new ExprParser(tokens);
    final ExprParser.parse_return ret = parser.parse();
    return ret.e;
  }

  /**
   * This utility is to mock the method DateTimeUtils.getDateFormatSymbols()
   * to mock the current local as US.
   */
  public static void mockUsDateFormatSymbols() {
    new MockUp<DateTimeUtils>() {
      @Mock
      public DateFormatSymbols getDateFormatSymbols(Locale locale) {
        return new DateFormatSymbols(Locale.US);
      }
    };
  }

  /**
   * This utility is to mock the method DateTimeZone.getDefault() to
   * mock current timezone as UTC.
   */
  public static void mockUtcDateTimeZone() {
    new MockUp<DateTimeZone>() {
      @Mock
      public DateTimeZone getDefault() {
        return DateTimeZone.UTC;
      }
    };
  }
}


text:
Create new media clip

    <fieldset class="add-media-panel">

          Paste a link from YouTube, SoundCloud, Vimeo or an HTML5 video

        <textarea class="add-media-input" placeholder="Paste an HTML5, YouTube, Vimeo, or SoundCloud link here"></textarea>

          Create clip

    </fieldset>

        Media Gallery

    <fieldset class="media-gallery-base-media butter-form-inline form-single bottom">
      Duration
      <input type="text" class="media-base-duration" value="">
    </fieldset>


text:
#!/usr/bin/env node
/*eslint no-console: 0 */
// @flow

import fs from 'fs'
import PackageJSONLoader from '../lib/package-json-loader'
import program from 'commander'

const version = PackageJSONLoader.load(__dirname + '/../..').version
program.version(version)

const subcommands = {
    'init'           : 'add .autorelease.yml to your project',
    'generate'       : 'generate circle.yml',
    'bmp'            : 'generate circle.yml and bumping version',
    'update-modules' : 'update node modules',
    'release'        : 'release current version',
    'gh-pages'       : 'create "gh-pages" branch for documentation',
    'notice'         : 'show notice',
    'run'            : 'execute commands at releasable timings',
}

Object.keys(subcommands)
    .filter(sub => fs.existsSync(__dirname + '/nca-' + sub + '.js'))
    .forEach(sub => program.command(sub, subcommands[sub]))

export function run(args: Array<string>) {
    const argv = args.slice()
    argv.unshift(process.execPath, __filename)
    program.parse(argv)
}

if (require.main === module) run(process.argv.slice(2))


text:
"""
Module which tests the compat.py functionality.
"""

from __future__ import unicode_literals
from __future__ import absolute_import

import os
import unittest

import six
from scalyr_agent.compat import os_environ_unicode

class EnvironUnicode(unittest.TestCase):
    TEST_VAR = "TEST_VAR_ENVIRON_UNICODE"

    def test_environ_get(self):
        os.environ[EnvironUnicode.TEST_VAR] = six.ensure_str("Test string")
        self.assertEqual(
            os_environ_unicode.get(EnvironUnicode.TEST_VAR),
            six.text_type("Test string"),
        )
        self.assertEqual(
            os_environ_unicode[EnvironUnicode.TEST_VAR], six.text_type("Test string")
        )

    def test_environ_set(self):
        os_environ_unicode[EnvironUnicode.TEST_VAR] = six.ensure_str("Test two string")
        self.assertEqual(
            os_environ_unicode.get(EnvironUnicode.TEST_VAR),
            six.text_type("Test two string"),
        )

    def test_environ_pop(self):
        os_environ_unicode[EnvironUnicode.TEST_VAR] = six.ensure_str("Test four string")
        value = os_environ_unicode.pop(EnvironUnicode.TEST_VAR)
        self.assertEqual(value, six.text_type("Test four string"))

    def test_environ_in(self):
        os.environ[EnvironUnicode.TEST_VAR] = "Foo"
        self.assertTrue(EnvironUnicode.TEST_VAR in os_environ_unicode)
        self.assertFalse("FakeKey1234" in os_environ_unicode)


text:
package com.ja.rsc.api;

public interface Connection extends AutoCloseable {

}


text:
package com.twu.biblioteca;

import com.twu.biblioteca.controller.BookManager;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;

public class ExampleTest {

    @Test
    public void test() {
        assertEquals(1, 1);
    }

}


text:
class Solution:
    # @param head, a ListNode
    # @return a ListNode
    def sortList(self, head):
        return self.merge_sort(head)

    def merge_sort(self, head):
        if head == None or head.next == None:
            return head

        # first find the middle node of the whole linked list
        ptr1, ptr2 = head, head
        while ptr2.next != None:
            ptr2 = ptr2.next
            if ptr2.next != None:
                ptr2 = ptr2.next
                ptr1 = ptr1.next

        head2 = ptr1.next
        ptr1.next = None  # tighten the end of the first linked list
        l1 = self.merge_sort(head)
        l2 = self.merge_sort(head2)
        return self.merge2lists(l1, l2)

    def merge2lists(self, l1, l2):
        # Merge sorted linked l2 into l1
        # Result is l1 linked list
        if l1 == None:
            l1 = l2
            return l1

        h0 = ListNode(0)   # a helper head node
        h0.next = l1   # this is the merged list head
        prev_node = h0    # tracking the previous node in the l1 linked list
        while l1!=None and l2!=None:
            if l1.val > l2.val:  # insert a node before l1
                prev_node.next = l2
                l2_next = l2.next  # save l2.next temporarily
                l2.next = l1
                l2 = l2_next
            else:
                l1 = l1.next
            prev_node = prev_node.next
        if l1 == None:  # If l2 hasn't come to an end
            prev_node.next = l2
        return h0.next


text:
package io.quarkus.arc.deployment;

import io.quarkus.arc.processor.BuiltinScope;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.logging.LoggingResourceProcessor;

public class LoggingBeanSupportProcessor {

    @BuildStep
    public void discoveredComponents(BuildProducer<BeanDefiningAnnotationBuildItem> beanDefiningAnnotationProducer) {
        beanDefiningAnnotationProducer.produce(new BeanDefiningAnnotationBuildItem(
                LoggingResourceProcessor.LOGGING_FILTER, BuiltinScope.SINGLETON.getName(), false));
    }

}


text:
require "rails_config/version"

module RailsConfig
end
RailsConfig = RailsConfig unless defined?(RailsConfig)

require 'rails_config/ext'
require 'rails_config/environment'
require 'rails_config/settings'


text:
namespace System.Security.Cryptography.Xml
{
    using System;
    using System.IO;
    using System.Net;
    using System.Runtime.InteropServices;
    using System.Security.Cryptography;
    using System.Xml;
    using System.Globalization;
    using System.Runtime.Versioning;

    [Serializable]
    internal enum ReferenceTargetType {
        Stream,
        XmlElement,
        UriReference
    }

    [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
    public class Reference {
        private string m_id;
        private string m_uri;
        private string m_type;
        private TransformChain m_transformChain;
        private string m_digestMethod;
        private byte[] m_digestValue;
        private HashAlgorithm m_hashAlgorithm;
        private Object m_refTarget;
        private ReferenceTargetType m_refTargetType;
        private XmlElement m_cachedXml;
        private SignedXml m_signedXml = null;
        internal CanonicalXmlNodeList m_namespaces = null;

        //
        // public constructors
        //

        public Reference () {
            m_transformChain = new TransformChain();
            m_refTarget = null;
            m_refTargetType = ReferenceTargetType.UriReference;
            m_cachedXml = null;
            m_digestMethod = SignedXml.XmlDsigSHA1Url;
        }

        public Reference (Stream stream) {
            m_transformChain = new TransformChain();
            m_refTarget = stream;
            m_refTargetType = ReferenceTargetType.Stream;
            m_cachedXml = null;
            m_digestMethod = SignedXml.XmlDsigSHA1Url;
        }

        public Reference (string uri) {
            m_transformChain = new TransformChain();
            m_refTarget = uri;
            m_uri = uri;
            m_refTargetType = ReferenceTargetType.UriReference;
            m_cachedXml = null;
            m_digestMethod = SignedXml.XmlDsigSHA1Url;
        }

        internal Reference (XmlElement element) {
            m_transformChain = new TransformChain();
            m_refTarget = element;
            m_refTargetType = ReferenceTargetType.XmlElement;
            m_cachedXml = null;
            m_digestMethod = SignedXml.XmlDsigSHA1Url;
        }

        //
        // public properties
        //

        public string Id {
            get { return m_id; }
            set { m_id = value; }
        }

        public string Uri {
            get { return m_uri; }
            set {
                m_uri = value;
                m_cachedXml = null;
            }
        }

        public string Type {
            get { return m_type; }
            set {
                m_type = value;
                m_cachedXml = null;
            }
        }

        public string DigestMethod {
            get { return m_digestMethod; }
            set {
                m_digestMethod = value;
                m_cachedXml = null;
            }
        }

        public byte[] DigestValue {
            get { return m_digestValue; }
            set {
                m_digestValue = value;
                m_cachedXml = null;
            }
        }

        public TransformChain TransformChain {
            get {
                if (m_transformChain == null)
                    m_transformChain = new TransformChain();
                return m_transformChain;
            }
            [ComVisible(false)]
            set {
                m_transformChain = value;
                m_cachedXml = null;
            }
        }

        internal bool CacheValid {
            get {
                return (m_cachedXml != null);
            }
        }

        internal SignedXml SignedXml {
            get { return m_signedXml; }
            set { m_signedXml = value; }
        }

        internal ReferenceTargetType ReferenceTargetType {
            get {
                return m_refTargetType;
            }
        }

        //
        // public methods
        //

        public XmlElement GetXml() {
            if (CacheValid) return(m_cachedXml);

            XmlDocument document = new XmlDocument();
            document.PreserveWhitespace = true;
            return GetXml(document);
        }

        internal XmlElement GetXml (XmlDocument document) {
            // Create the Reference
            XmlElement referenceElement = document.CreateElement("Reference", SignedXml.XmlDsigNamespaceUrl);

            if (!String.IsNullOrEmpty(m_id))
                referenceElement.SetAttribute("Id", m_id);

            if (m_uri != null)
                referenceElement.SetAttribute("URI", m_uri);

            if (!String.IsNullOrEmpty(m_type))
                referenceElement.SetAttribute("Type", m_type);

            // Add the transforms to the Reference
            if (this.TransformChain.Count != 0)
                referenceElement.AppendChild(this.TransformChain.GetXml(document, SignedXml.XmlDsigNamespaceUrl));

            // Add the DigestMethod
            if (String.IsNullOrEmpty(m_digestMethod))
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_DigestMethodRequired"));

            XmlElement digestMethodElement = document.CreateElement("DigestMethod", SignedXml.XmlDsigNamespaceUrl);
            digestMethodElement.SetAttribute("Algorithm",m_digestMethod);
            referenceElement.AppendChild(digestMethodElement);

            if (DigestValue == null) {
                if (m_hashAlgorithm.Hash == null)
                    throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_DigestValueRequired"));
                DigestValue = m_hashAlgorithm.Hash;
            }

            XmlElement digestValueElement = document.CreateElement("DigestValue", SignedXml.XmlDsigNamespaceUrl);
            digestValueElement.AppendChild(document.CreateTextNode(Convert.ToBase64String(m_digestValue)));
            referenceElement.AppendChild(digestValueElement);

            return referenceElement;
        }

        public void LoadXml(XmlElement value) {
            if (value == null)
                throw new ArgumentNullException("value");

            m_id = Utils.GetAttribute(value, "Id", SignedXml.XmlDsigNamespaceUrl);
            m_uri = Utils.GetAttribute(value, "URI", SignedXml.XmlDsigNamespaceUrl);
            m_type = Utils.GetAttribute(value, "Type", SignedXml.XmlDsigNamespaceUrl);

            XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable);
            nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);

            // Transforms
            this.TransformChain = new TransformChain();
            XmlElement transformsElement = value.SelectSingleNode("ds:Transforms", nsm) as XmlElement;
            if (transformsElement != null) {
                XmlNodeList transformNodes = transformsElement.SelectNodes("ds:Transform", nsm);
                if (transformNodes != null) {
                    foreach (XmlNode transformNode in transformNodes) {
                        XmlElement transformElement = transformNode as XmlElement;
                        string algorithm = Utils.GetAttribute(transformElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl);
                        Transform transform = CryptoConfig.CreateFromName(algorithm) as Transform;
                        if (transform == null)
                            throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UnknownTransform"));
                        AddTransform(transform);
                        // let the transform read the children of the transformElement for data
                        transform.LoadInnerXml(transformElement.ChildNodes);
                        // Hack! this is done to get around the lack of here() function support in XPath
                        if (transform is XmlDsigEnvelopedSignatureTransform) {
                            // Walk back to the Signature tag. Find the nearest signature ancestor
                            // Signature-->SignedInfo-->Reference-->Transforms-->Transform
                            XmlNode signatureTag = transformElement.SelectSingleNode("ancestor::ds:Signature[1]", nsm);
                            XmlNodeList signatureList = transformElement.SelectNodes("//ds:Signature", nsm);
                            if (signatureList != null) {
                                int position = 0;
                                foreach(XmlNode node in signatureList) {
                                    position++;
                                    if (node == signatureTag) {
                                        ((XmlDsigEnvelopedSignatureTransform)transform).SignaturePosition = position;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // DigestMethod
            XmlElement digestMethodElement = value.SelectSingleNode("ds:DigestMethod", nsm) as XmlElement;
            if (digestMethodElement == null)
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Reference/DigestMethod");
            m_digestMethod = Utils.GetAttribute(digestMethodElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl);

            // DigestValue
            XmlElement digestValueElement = value.SelectSingleNode("ds:DigestValue", nsm) as XmlElement;
            if (digestValueElement == null)
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Reference/DigestValue");
            m_digestValue = Convert.FromBase64String(Utils.DiscardWhiteSpaces(digestValueElement.InnerText));

            // cache the Xml
            m_cachedXml = value;
        }

        public void AddTransform(Transform transform) {
            if (transform == null)
                throw new ArgumentNullException("transform");

            transform.Reference = this;
            this.TransformChain.Add(transform);
        }

        internal void UpdateHashValue(XmlDocument document, CanonicalXmlNodeList refList) {
            DigestValue = CalculateHashValue(document, refList);
        }

        // What we want to do is pump the input throug the TransformChain and then
        // hash the output of the chain document is the document context for resolving relative references
        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
        internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList refList) {
            // refList is a list of elements that might be targets of references
            // Now's the time to create our hashing algorithm
            m_hashAlgorithm = CryptoConfig.CreateFromName(m_digestMethod) as HashAlgorithm;
            if (m_hashAlgorithm == null)
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreateHashAlgorithmFailed"));

            // Let's go get the target.
            string baseUri = (document == null ? System.Environment.CurrentDirectory + "\\" : document.BaseURI);
            Stream hashInputStream = null;
            WebRequest request = null;
            WebResponse response = null;
            Stream inputStream = null;
            XmlResolver resolver = null;
            byte[] hashval = null;

            try {
                switch (m_refTargetType) {
                case ReferenceTargetType.Stream:
                    // This is the easiest case. We already have a stream, so just pump it through the TransformChain
                    resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
                    hashInputStream = this.TransformChain.TransformToOctetStream((Stream) m_refTarget, resolver, baseUri);
                    break;
                case ReferenceTargetType.UriReference:
                    // Second-easiest case -- dereference the URI & pump through the TransformChain
                    // handle the special cases where the URI is null (meaning whole doc)
                    // or the URI is just a fragment (meaning a reference to an embedded Object)
                    if (m_uri == null) {
                        // We need to create a DocumentNavigator out of the XmlElement
                        resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
                        // In the case of a Uri-less reference, we will simply pass null to the transform chain.
                        // The first transform in the chain is expected to know how to retrieve the data to hash.
                        hashInputStream = this.TransformChain.TransformToOctetStream((Stream) null, resolver, baseUri);
                    } else if (m_uri.Length == 0) {
                        // This is the self-referential case. First, check that we have a document context.
                        // The Enveloped Signature does not discard comments as per spec; those will be omitted during the transform chain process
                       if (document == null)
                            throw new CryptographicException(String.Format(CultureInfo.CurrentCulture, SecurityResources.GetResourceString("Cryptography_Xml_SelfReferenceRequiresContext"), m_uri));

                        // Normalize the containing document
                        resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
                        XmlDocument docWithNoComments = Utils.DiscardComments(Utils.PreProcessDocumentInput(document, resolver, baseUri));
                        hashInputStream = this.TransformChain.TransformToOctetStream(docWithNoComments, resolver, baseUri);
                    } else if (m_uri[0] == '#') {
                        // If we get here, then we are constructing a Reference to an embedded DataObject
                        // referenced by an Id = attribute. Go find the relevant object
                        bool discardComments = true;
                        string idref = Utils.GetIdFromLocalUri(m_uri, out discardComments);
                        if (idref == "xpointer(/)") {
                            // This is a self referencial case
                            if (document == null)
                                throw new CryptographicException(String.Format(CultureInfo.CurrentCulture, SecurityResources.GetResourceString("Cryptography_Xml_SelfReferenceRequiresContext"),m_uri));

                            // We should not discard comments here!!!
                            resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
                            hashInputStream = this.TransformChain.TransformToOctetStream(Utils.PreProcessDocumentInput(document, resolver, baseUri), resolver, baseUri);
                            break;
                        }

                        XmlElement elem = this.SignedXml.GetIdElement(document, idref);
                        if (elem != null)
                            m_namespaces = Utils.GetPropagatedAttributes(elem.ParentNode as XmlElement);

                        if (elem == null) {
                            // Go throw the referenced items passed in
                            if (refList != null) {
                                foreach (XmlNode node in refList) {
                                    XmlElement tempElem = node as XmlElement;
                                    if ((tempElem != null) && (Utils.HasAttribute(tempElem, "Id", SignedXml.XmlDsigNamespaceUrl))
                                        && (Utils.GetAttribute(tempElem, "Id", SignedXml.XmlDsigNamespaceUrl).Equals(idref))) {
                                        elem = tempElem;
                                        if (this.m_signedXml.m_context != null)
                                            m_namespaces = Utils.GetPropagatedAttributes(this.m_signedXml.m_context);
                                        break;
                                    }
                                }
                            }
                        }

                        if (elem == null)
                            throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidReference"));

                        XmlDocument normDocument = Utils.PreProcessElementInput(elem, resolver, baseUri);
                        // Add the propagated attributes
                        Utils.AddNamespaces(normDocument.DocumentElement, m_namespaces);

                        resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
                        if (discardComments) {
                            // We should discard comments before going into the transform chain
                            XmlDocument docWithNoComments = Utils.DiscardComments(normDocument);
                            hashInputStream = this.TransformChain.TransformToOctetStream(docWithNoComments, resolver, baseUri);
                        } else {
                            // This is an XPointer reference, do not discard comments!!!
                            hashInputStream = this.TransformChain.TransformToOctetStream(normDocument, resolver, baseUri);
                        }
                    } else {
                        // WebRequest always expects an Absolute Uri, so try to resolve if we were passed a relative Uri.
                        System.Uri uri = new System.Uri(m_uri, UriKind.RelativeOrAbsolute);
                        if (!uri.IsAbsoluteUri) {
                            uri = new Uri(new Uri(baseUri), uri);
                        }
                        request = WebRequest.Create(uri);
                        if (request == null) goto default;
                        response = request.GetResponse();
                        if (response == null) goto default;
                        inputStream = response.GetResponseStream();
                        if (inputStream == null) goto default;
                        resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
                        hashInputStream = this.TransformChain.TransformToOctetStream(inputStream, resolver, m_uri);
                    }
                    break;
                case ReferenceTargetType.XmlElement:
                    // We need to create a DocumentNavigator out of the XmlElement
                    resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
                    hashInputStream = this.TransformChain.TransformToOctetStream(Utils.PreProcessElementInput((XmlElement) m_refTarget, resolver, baseUri), resolver, baseUri);
                    break;
                default:
                    throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UriNotResolved"), m_uri);
                }

                // Compute the new hash value
                hashInputStream = SignedXmlDebugLog.LogReferenceData(this, hashInputStream);
                hashval = m_hashAlgorithm.ComputeHash(hashInputStream);
            }
            finally {
                if (hashInputStream != null)
                    hashInputStream.Close();
                if (response != null)
                    response.Close();
                if (inputStream != null)
                    inputStream.Close();
            }

            return hashval;
        }
    }
}


text:
package org.capcaval.ccoutils.converter.basicconverters;

import org.capcaval.ccoutils.converter.ConverterAbstract;

public class EnumToString extends ConverterAbstract<Enum<?>, String> {
	@Override
	public String convert(Enum inobj) {
		Class<?> c = inobj.getDeclaringClass();

		return c.getSimpleName()+"."+inobj.toString();
	}

}


text:
<?php

namespace Tooter\Model;

class User
{
	private $id;

	private $userName;

	private $password;  //used during password set/reset only.  Do NOT store users' passwords - let Stormpath do that safely for you.

	private $confirmPassword;  //used during password set/reset only.

	private $sptoken;

	private $firstName;

	private $lastName;

	private $email;

	private $groupUrl;

	private $tootList;

	private $account;

	const NO_GROUP = "Basic";

	protected $inputFilter;

	public function __construct()
	{

	}

	public static function constructWithUser($user)
	{
		$obj = new User();
		if(!empty($user))
		{
			$obj->setAccount($user->getAccount());
            $obj->setConfirmPassword($user->getConfirmPassword());
			$obj->setEmail($user->getEmail());
            $obj->setFirstName($user->getFirstName());
            $obj->setId($user->getId());
            $obj->setLastName($user->getLastName());
            $obj->setPassword($user->getPassword());
            $obj->setTootList($user->getTootList());
            $obj->setUserName($user->getUserName());
		}
		return $obj;
	}

	public static function constructWithAccount($account)
	{
		$obj = new User();
		if(!empty($account))
		{
			$obj->setEmail($account->getEmail());
            $obj->setFirstName($account->getGivenName());
            $obj->setLastName($account->getSurname());
            $obj->setUserName($account->getUsername());
            $obj->setAccount($account);
		}
		return $obj;
	}

	public function getId()
	{
		return $this->id;
	}

	public function setId($id)
	{
		$this->id = $id;
	}

	public function getTootList()
	{
		return $this->tootList;
	}

	public function setTootList($tootList)
	{
		$this->tootList = $tootList;
	}

	 /**
     * Return the email associated with this user. If available, use the Stormpath SDK Account value, otherwise return the
     * local property. We do this because the user class is a form backing bean for authentication, profile updates, etc.
     *
     * @return the email from the Stormpath SDK Account object if the account is not null, otherwise return the underlying property
     */
	 public function getEmail()
	 {
		return !empty($this->account) ? $this->account->getEmail() : $this->email;
	 }

	 public function setEmail($email)
	 {
		$this->email = $email;
	 }

	 public function getPassword()
	 {
		return $this->password;
	 }

	 public function setPassword($password)
	 {
		$this->password = $password;
	 }

	/**
     * Return the username associated with this user. If available, use the Stormpath SDK Account value, otherwise return the
     * local property. We do this because the user class is a form backing bean for authentication, profile updates, etc.
     */
	 public function getUserName()
	 {
		return !empty($this->account) ? $this->account->getUsername() : $this->userName;
	 }

	 public function setUserName($userName)
	 {
		if(!empty($this->account))
			$this->account->setUsername($userName);
		else
			$this->userName = $userName;
	 }

	 public function getConfirmPassword()
	 {
		return $this->confirmPassword;
	 }

	 public function setConfirmPassword($confirmPassword)
	 {
		$this->confirmPassword = $confirmPassword;
	 }

	 public function getSptoken()
	 {
		return $this->sptoken;
	 }

	 public function setSptoken($sptoken)
	 {
		$this->sptoken = $sptoken;
	 }

	 /**
     * Return the first name associated with this user. If available, use the Stormpath SDK Account value, otherwise return the
     * local property. We do this because the user class is a form backing bean for authentication, profile updates, etc.
     *
     * @return the first name from the Stormpath SDK Account object if the account is not null, otherwise return the underlying property
     */

	 public function getFirstName()
	 {
		return !empty($this->account) ? $this->account->getGivenName() : $this->firstName;
	 }

	 public function setFirstName($firstName)
	 {
		if(!empty($this->account))
			$this->account->setGivenName($firstName);
		else
			$this->firstName = $firstName;
	 }

	  /**
     * Return the last name associated with this user. If available, use the Stormpath SDK Account value, otherwise return the
     * local property. We do this because the user class is a form backing bean for authentication, profile updates, etc.
     *
     * @return the last name from the Stormpath SDK Account object if the account is not null, otherwise return the underlying property
     */
	 public function getLastName()
	 {
		return !empty($this->account) ? $this->account->getSurname() : $this->lastName;
	 }

	 public function setLastName($lastName)
	 {
		if(!empty($this->account))
			$this->account->setSurname($lastName);
		else
			$this->lastName = $lastName;
	 }

	 public function getAccount()
	 {
		return $this->account;
	 }

	 public function setAccount($account)
	 {
		$this->account = $account;
	 }

	 /**
     * Return the name of the group for this user.
     *
     * @return the name of the group associated with this user, or "Basic" if the user is not assigned to any groups in Stormpath
     */
	 public function getGroupName()
	 {
		$memberships = $this->account->getGroupMemberships();
		$groupName = self::NO_GROUP;
		foreach($memberships as $membership)
			$groupName = $membership->getGroup()->getName();
		return $groupName;
	 }

	 public function getGroupUrl()
	 {
		return $this->groupUrl;
	 }

	 public function setGroupUrl($groupUrl)
	 {
		$this->groupUrl = $groupUrl;
	 }

	public function exchangeArray($data)
    {
        $this->userName     = (isset($data['userName']))     ? $data['userName']     : null;
        $this->password = (isset($data['password'])) ? $data['password'] : null;
		$this->email	= (isset($data['email'])) ? $data['email'] : null;
		$this->firstName	= (isset($data['firstName'])) ? $data['firstName'] : null;
		$this->lastName	= (isset($data['lastName'])) ? $data['lastName'] : null;
		$this->confirmPassword	= (isset($data['confirmPassword'])) ? $data['confirmPassword'] : null;
		$this->groupUrl = (isset($data['groupUrl'])) ? $data['groupUrl'] : null;
    }
}