text:
namespace :memcache do

  desc "Start Memcached"
  task :start, :roles => :cache do
    sudo "/etc/init.d/memcached start"
    #sudo "memcached -d -m #{memcache_memory} -l #{memcache_ip} -p #{memcache_port}"
  end

  desc "Stop Memcached using killall"
  task :stop, :roles => :cache do
    sudo "/etc/init.d/memcached stop"
    #sudo "killall memcached; echo 0"
  end

  desc "Restart Memcached"
  task :restart, :roles => :cache do
    stop
    start
  end

end

redpajama_set_name: RedPajamaGithub


text:
package api_test

import (
	"archive/tar"
	"bytes"
	"compress/gzip"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"regexp"
	"runtime"
	"time"

	"github.com/concourse/go-archive/tarfs"
	"github.com/klauspost/compress/zstd"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"code.cloudfoundry.org/lager/lagertest"
	"github.com/concourse/go-archive/tgzfs"

	"github.com/concourse/baggageclaim"
	"github.com/concourse/baggageclaim/api"
	"github.com/concourse/baggageclaim/uidgid"
	"github.com/concourse/baggageclaim/volume"
	"github.com/concourse/baggageclaim/volume/driver"
)

var _ = Describe("Volume Server", func() {
	var (
		handler http.Handler

		volumeDir string
		tempDir   string
	)

	BeforeEach(func() {
		var err error

		tempDir, err = ioutil.TempDir("", fmt.Sprintf("baggageclaim_volume_dir_%d", GinkgoParallelNode()))
		Expect(err).NotTo(HaveOccurred())

		// ioutil.TempDir creates it 0700; we need public readability for
		// unprivileged StreamIn
		err = os.Chmod(tempDir, 0755)
		Expect(err).NotTo(HaveOccurred())

		volumeDir = tempDir
	})

	JustBeforeEach(func() {
		logger := lagertest.NewTestLogger("volume-server")

		fs, err := volume.NewFilesystem(&driver.NaiveDriver{}, volumeDir)
		Expect(err).NotTo(HaveOccurred())

		var privilegedNamespacer, unprivilegedNamespacer uidgid.Namespacer
		if runtime.GOOS == "linux" {
			privilegedNamespacer = &uidgid.UidNamespacer{
				Translator: uidgid.NewTranslator(uidgid.NewPrivilegedMapper()),
				Logger:     logger.Session("uid-namespacer"),
			}

			unprivilegedNamespacer = &uidgid.UidNamespacer{
				Translator: uidgid.NewTranslator(uidgid.NewUnprivilegedMapper()),
				Logger:     logger.Session("uid-namespacer"),
			}
		} else {
			privilegedNamespacer = &uidgid.NoopNamespacer{}
			unprivilegedNamespacer = &uidgid.NoopNamespacer{}
		}

		repo := volume.NewRepository(
			fs,
			volume.NewLockManager(),
			privilegedNamespacer,
			unprivilegedNamespacer,
		)

		strategerizer := volume.NewStrategerizer()

		re := regexp.MustCompile("lo")
		handler, err = api.NewHandler(logger, strategerizer, repo, re, 4, 7766)
		Expect(err).NotTo(HaveOccurred())
	})

	AfterEach(func() {
		// keep trying; async volume creation tests can cause failures on windows
		// while multiple processes have a file open
		Eventually(func() error {
			return os.RemoveAll(tempDir)
		}, time.Minute).ShouldNot(HaveOccurred())
	})

	Describe("listing the volumes", func() {
		var recorder *httptest.ResponseRecorder

		JustBeforeEach(func() {
			recorder = httptest.NewRecorder()
			request, _ := http.NewRequest("GET", "/volumes", nil)

			handler.ServeHTTP(recorder, request)
		})

		Context("when there are no volumes", func() {
			It("returns an empty array", func() {
				Expect(recorder.Body).To(MatchJSON(`[]`))
			})
		})
	})

	Describe("querying for volumes with properties", func() {
		props := baggageclaim.VolumeProperties{
			"property-query": "value",
		}

		It("finds volumes that have a property", func() {
			body := &bytes.Buffer{}

			err := json.NewEncoder(body).Encode(baggageclaim.VolumeRequest{
				Handle: "some-handle",
				Strategy: encStrategy(map[string]string{
					"type": "empty",
				}),
				Properties: props,
			})
			Expect(err).NotTo(HaveOccurred())

			recorder := httptest.NewRecorder()
			request, _ := http.NewRequest("POST", "/volumes", body)
			handler.ServeHTTP(recorder, request)
			Expect(recorder.Code).To(Equal(201))

			body.Reset()
			err = json.NewEncoder(body).Encode(baggageclaim.VolumeRequest{
				Handle: "another-handle",
				Strategy: encStrategy(map[string]string{
					"type": "empty",
				}),
			})
			Expect(err).NotTo(HaveOccurred())

			recorder = httptest.NewRecorder()
			request, _ = http.NewRequest("POST", "/volumes", body)
			handler.ServeHTTP(recorder, request)
			Expect(recorder.Code).To(Equal(201))

			recorder = httptest.NewRecorder()
			request, _ = http.NewRequest("GET", "/volumes?property-query=value", nil)
			handler.ServeHTTP(recorder, request)
			Expect(recorder.Code).To(Equal(200))

			var volumes volume.Volumes
			err = json.NewDecoder(recorder.Body).Decode(&volumes)
			Expect(err).NotTo(HaveOccurred())

			Expect(volumes).To(HaveLen(1))
		})

		It("returns an error if an invalid set of properties are specified", func() {
			recorder := httptest.NewRecorder()
			request, _ := http.NewRequest("GET", "/volumes?property-query=value&property-query=another-value", nil)
			handler.ServeHTTP(recorder, request)

			Expect(recorder.Code).To(Equal(422))
		})
	})

	Describe("streaming tar files into volumes", func() {
		var (
			myVolume     volume.Volume
			tgzBuffer    *bytes.Buffer
			isPrivileged bool
		)

		JustBeforeEach(func() {
			body := &bytes.Buffer{}

			err := json.NewEncoder(body).Encode(baggageclaim.VolumeRequest{
				Handle: "some-handle",
				Strategy: encStrategy(map[string]string{
					"type": "empty",
				}),
				Privileged: isPrivileged,
			})
			Expect(err).NotTo(HaveOccurred())

			request, err := http.NewRequest("POST", "/volumes", body)
			Expect(err).NotTo(HaveOccurred())

			recorder := httptest.NewRecorder()
			handler.ServeHTTP(recorder, request)
			Expect(recorder.Code).To(Equal(201))

			err = json.NewDecoder(recorder.Body).Decode(&myVolume)
			Expect(err).NotTo(HaveOccurred())
		})

		Context("when tar file is valid", func() {

			Context("when using gzip encoding", func() {
				BeforeEach(func() {
					tgzBuffer = new(bytes.Buffer)
					gzWriter := gzip.NewWriter(tgzBuffer)
					defer gzWriter.Close()

					tarWriter := tar.NewWriter(gzWriter)
					defer tarWriter.Close()

					err := tarWriter.WriteHeader(&tar.Header{
						Name: "some-file",
						Mode: 0600,
						Size: int64(len("file-content")),
					})
					Expect(err).NotTo(HaveOccurred())
					_, err = tarWriter.Write([]byte("file-content"))
					Expect(err).NotTo(HaveOccurred())
				})

				It("extracts the tar stream into the volume's DataPath", func() {
					request, _ := http.NewRequest("PUT", fmt.Sprintf("/volumes/%s/stream-in?path=%s", myVolume.Handle, "dest-path"), tgzBuffer)
					request.Header.Set("Content-Encoding", string(baggageclaim.GzipEncoding))
					recorder := httptest.NewRecorder()
					handler.ServeHTTP(recorder, request)
					Expect(recorder.Code).To(Equal(204))

					tarContentsPath := filepath.Join(volumeDir, "live", myVolume.Handle, "volume", "dest-path", "some-file")
					Expect(tarContentsPath).To(BeAnExistingFile())

					Expect(ioutil.ReadFile(tarContentsPath)).To(Equal([]byte("file-content")))
				})

			})

			Context("when using zstd encoding", func() {
				BeforeEach(func() {
					tgzBuffer = new(bytes.Buffer)
					zstdWriter, err := zstd.NewWriter(tgzBuffer)
					Expect(err).ToNot(HaveOccurred())
					defer zstdWriter.Close()

					tarWriter := tar.NewWriter(zstdWriter)
					defer tarWriter.Close()

					err = tarWriter.WriteHeader(&tar.Header{
						Name: "some-file",
						Mode: 0600,
						Size: int64(len("file-content")),
					})
					Expect(err).NotTo(HaveOccurred())
					_, err = tarWriter.Write([]byte("file-content"))
					Expect(err).NotTo(HaveOccurred())
				})

				It("extracts the tar stream into the volume's DataPath", func() {
					request, _ := http.NewRequest("PUT", fmt.Sprintf("/volumes/%s/stream-in?path=%s", myVolume.Handle, "dest-path"), tgzBuffer)
					request.Header.Set("Content-Encoding", string(baggageclaim.ZstdEncoding))
					recorder := httptest.NewRecorder()
					handler.ServeHTTP(recorder, request)
					Expect(recorder.Code).To(Equal(204))

					tarContentsPath := filepath.Join(volumeDir, "live", myVolume.Handle, "volume", "dest-path", "some-file")
					Expect(tarContentsPath).To(BeAnExistingFile())

					Expect(ioutil.ReadFile(tarContentsPath)).To(Equal([]byte("file-content")))
				})
			})
		})

		Context("when the tar stream is invalid", func() {
			BeforeEach(func() {
				tgzBuffer = new(bytes.Buffer)
				tgzBuffer.Write([]byte("This is an invalid tar file!"))
			})

			Context("when using gzip encoding", func() {
				It("returns 400 when err is exitError", func() {
					request, _ := http.NewRequest("PUT", fmt.Sprintf("/volumes/%s/stream-in", myVolume.Handle), tgzBuffer)
					request.Header.Set("Content-Encoding", string(baggageclaim.GzipEncoding))
					recorder := httptest.NewRecorder()
					handler.ServeHTTP(recorder, request)
					Expect(recorder.Code).To(Equal(400))
				})

			})
			Context("when using zstd encoding", func() {
				It("returns 400 when err is exitError", func() {
					request, _ := http.NewRequest("PUT", fmt.Sprintf("/volumes/%s/stream-in", myVolume.Handle), tgzBuffer)
					request.Header.Set("Content-Encoding", string(baggageclaim.ZstdEncoding))
					recorder := httptest.NewRecorder()
					handler.ServeHTTP(recorder, request)
					Expect(recorder.Code).To(Equal(400))
				})
			})
		})

		Context("when using an unsupported encoding", func() {
			BeforeEach(func() {
				tgzBuffer = new(bytes.Buffer)
			})

			It("returns 400 when err is UnsupportedEncodingError", func() {
				request, _ := http.NewRequest("PUT", fmt.Sprintf("/volumes/%s/stream-in", myVolume.Handle), tgzBuffer)
				request.Header.Set("Content-Encoding", "unsupported")
				recorder := httptest.NewRecorder()
				handler.ServeHTTP(recorder, request)
				Expect(recorder.Code).To(Equal(400))
			})
		})

		It("returns 404 when volume is not found", func() {
			tgzBuffer = new(bytes.Buffer)
			request, _ := http.NewRequest("PUT", fmt.Sprintf("/volumes/%s/stream-in", "invalid-handle"), tgzBuffer)
			recorder := httptest.NewRecorder()
			handler.ServeHTTP(recorder, request)
			Expect(recorder.Code).To(Equal(404))
		})
	})

	Describe("streaming tar out of a volume", func() {
		var (
			myVolume  volume.Volume
			tarBuffer *bytes.Buffer
			encoding  string
		)

		BeforeEach(func() {
			tarBuffer = new(bytes.Buffer)
		})

		JustBeforeEach(func() {
			body := &bytes.Buffer{}

			err := json.NewEncoder(body).Encode(baggageclaim.VolumeRequest{
				Handle: "some-handle",
				Strategy: encStrategy(map[string]string{
					"type": "empty",
				}),
			})
			Expect(err).NotTo(HaveOccurred())

			request, err := http.NewRequest("POST", "/volumes", body)
			Expect(err).NotTo(HaveOccurred())

			recorder := httptest.NewRecorder()
			handler.ServeHTTP(recorder, request)
			Expect(recorder.Code).To(Equal(201))

			err = json.NewDecoder(recorder.Body).Decode(&myVolume)
			Expect(err).NotTo(HaveOccurred())
		})

		It("returns 404 when source path is invalid", func() {
			request, _ := http.NewRequest("PUT", fmt.Sprintf("/volumes/%s/stream-out?path=%s", myVolume.Handle, "bogus-path"), nil)
			request.Header.Set("Accept-Encoding", string(baggageclaim.GzipEncoding))
			recorder := httptest.NewRecorder()
			handler.ServeHTTP(recorder, request)
			Expect(recorder.Code).To(Equal(404))

			var responseError *api.ErrorResponse
			err := json.NewDecoder(recorder.Body).Decode(&responseError)
			Expect(err).NotTo(HaveOccurred())
			Expect(responseError.Message).To(Equal("no such file or directory"))
		})

		Context("when streaming a file", func() {

			JustBeforeEach(func() {
				streamInRequest, _ := http.NewRequest("PUT", fmt.Sprintf("/volumes/%s/stream-in?path=%s", myVolume.Handle, "dest-path"), tarBuffer)
				streamInRequest.Header.Set("Content-Encoding", encoding)
				streamInRecorder := httptest.NewRecorder()
				handler.ServeHTTP(streamInRecorder, streamInRequest)
				Expect(streamInRecorder.Code).To(Equal(204))

				tarContentsPath := filepath.Join(volumeDir, "live", myVolume.Handle, "volume", "dest-path", "some-file")
				Expect(tarContentsPath).To(BeAnExistingFile())

				Expect(ioutil.ReadFile(tarContentsPath)).To(Equal([]byte("file-content")))
			})

			Context("when using gzip encoding", func() {
				BeforeEach(func() {
					gzWriter := gzip.NewWriter(tarBuffer)
					defer gzWriter.Close()

					tarWriter := tar.NewWriter(gzWriter)
					defer tarWriter.Close()

					err := tarWriter.WriteHeader(&tar.Header{
						Name: "some-file",
						Mode: 0600,
						Size: int64(len("file-content")),
					})
					Expect(err).NotTo(HaveOccurred())
					_, err = tarWriter.Write([]byte("file-content"))
					Expect(err).NotTo(HaveOccurred())
					encoding = string(baggageclaim.GzipEncoding)
				})

				It("creates a tar", func() {
					request, _ := http.NewRequest("PUT", fmt.Sprintf("/volumes/%s/stream-out?path=%s", myVolume.Handle, "dest-path"), nil)
					request.Header.Set("Accept-Encoding", string(baggageclaim.GzipEncoding))
					recorder := httptest.NewRecorder()
					handler.ServeHTTP(recorder, request)
					Expect(recorder.Code).To(Equal(200))

					unpackedDir := filepath.Join(tempDir, "unpacked-dir")
					err := os.MkdirAll(unpackedDir, os.ModePerm)
					Expect(err).NotTo(HaveOccurred())
					defer os.RemoveAll(unpackedDir)

					err = tgzfs.Extract(recorder.Body, unpackedDir)
					Expect(err).NotTo(HaveOccurred())

					fileInfo, err := os.Stat(filepath.Join(unpackedDir, "some-file"))
					Expect(err).NotTo(HaveOccurred())
					Expect(fileInfo.IsDir()).To(BeFalse())
					Expect(fileInfo.Size()).To(Equal(int64(len("file-content"))))

					contents, err := ioutil.ReadFile(filepath.Join(unpackedDir, "./some-file"))
					Expect(err).NotTo(HaveOccurred())
					Expect(string(contents)).To(Equal("file-content"))
				})
			})

			Context("when using zstd encoding", func() {
				BeforeEach(func() {
					zstdWriter, err := zstd.NewWriter(tarBuffer)
					Expect(err).NotTo(HaveOccurred())
					defer zstdWriter.Close()

					tarWriter := tar.NewWriter(zstdWriter)
					defer tarWriter.Close()

					err = tarWriter.WriteHeader(&tar.Header{
						Name: "some-file",
						Mode: 0600,
						Size: int64(len("file-content")),
					})
					Expect(err).NotTo(HaveOccurred())
					_, err = tarWriter.Write([]byte("file-content"))
					Expect(err).NotTo(HaveOccurred())
					encoding = string(baggageclaim.ZstdEncoding)
				})

				It("creates a tar", func() {
					request, _ := http.NewRequest("PUT", fmt.Sprintf("/volumes/%s/stream-out?path=%s", myVolume.Handle, "dest-path"), nil)
					request.Header.Set("Accept-Encoding", string(baggageclaim.ZstdEncoding))
					recorder := httptest.NewRecorder()
					handler.ServeHTTP(recorder, request)
					Expect(recorder.Code).To(Equal(200))

					unpackedDir := filepath.Join(tempDir, "unpacked-dir")
					err := os.MkdirAll(unpackedDir, os.ModePerm)
					Expect(err).NotTo(HaveOccurred())
					defer os.RemoveAll(unpackedDir)

					zstdReader, err := zstd.NewReader(recorder.Body)
					Expect(err).NotTo(HaveOccurred())
					err = tarfs.Extract(zstdReader, unpackedDir)
					Expect(err).NotTo(HaveOccurred())

					fileInfo, err := os.Stat(filepath.Join(unpackedDir, "some-file"))
					Expect(err).NotTo(HaveOccurred())
					Expect(fileInfo.IsDir()).To(BeFalse())
					Expect(fileInfo.Size()).To(Equal(int64(len("file-content"))))

					contents, err := ioutil.ReadFile(filepath.Join(unpackedDir, "./some-file"))
					Expect(err).NotTo(HaveOccurred())
					Expect(string(contents)).To(Equal("file-content"))
				})
			})
		})

		Context("when streaming a directory", func() {
			var tarDir string

			BeforeEach(func() {
				tarDir = filepath.Join(tempDir, "tar-dir")

				err := os.MkdirAll(filepath.Join(tarDir, "sub"), os.ModePerm)
				Expect(err).NotTo(HaveOccurred())

				err = ioutil.WriteFile(filepath.Join(tarDir, "sub", "some-file"), []byte("some-file-content"), os.ModePerm)
				Expect(err).NotTo(HaveOccurred())

				err = ioutil.WriteFile(filepath.Join(tarDir, "other-file"), []byte("other-file-content"), os.ModePerm)
				Expect(err).NotTo(HaveOccurred())

				tarBuffer = new(bytes.Buffer)
			})

			JustBeforeEach(func() {
				streamInRequest, _ := http.NewRequest("PUT", fmt.Sprintf("/volumes/%s/stream-in?path=%s", myVolume.Handle, "dest-path"), tarBuffer)
				streamInRequest.Header.Set("Content-Encoding", encoding)
				streamInRecorder := httptest.NewRecorder()
				handler.ServeHTTP(streamInRecorder, streamInRequest)
				Expect(streamInRecorder.Code).To(Equal(204))

				tarContentsPath := filepath.Join(volumeDir, "live", myVolume.Handle, "volume", "dest-path")
				Expect(tarContentsPath).To(BeADirectory())
			})

			Context("when using gzip encoding", func() {
				BeforeEach(func() {
					err := tgzfs.Compress(tarBuffer, tarDir, ".")
					Expect(err).NotTo(HaveOccurred())
					encoding = string(baggageclaim.GzipEncoding)
				})

				It("creates a tar", func() {
					request, _ := http.NewRequest("PUT", fmt.Sprintf("/volumes/%s/stream-out?path=%s", myVolume.Handle, "dest-path"), nil)
					request.Header.Set("Accept-Encoding", string(baggageclaim.GzipEncoding))
					recorder := httptest.NewRecorder()
					handler.ServeHTTP(recorder, request)
					Expect(recorder.Code).To(Equal(200))

					unpackedDir := filepath.Join(tempDir, "unpacked-dir")
					err := os.MkdirAll(unpackedDir, os.ModePerm)
					Expect(err).NotTo(HaveOccurred())
					defer os.RemoveAll(unpackedDir)

					err = tgzfs.Extract(recorder.Body, unpackedDir)
					Expect(err).NotTo(HaveOccurred())

					fileInfo, err := os.Stat(filepath.Join(unpackedDir, "other-file"))
					Expect(err).NotTo(HaveOccurred())
					Expect(fileInfo.IsDir()).To(BeFalse())
					Expect(fileInfo.Size()).To(Equal(int64(len("other-file-content"))))

					contents, err := ioutil.ReadFile(filepath.Join(unpackedDir, "other-file"))
					Expect(err).NotTo(HaveOccurred())
					Expect(string(contents)).To(Equal("other-file-content"))

					dirInfo, err := os.Stat(filepath.Join(unpackedDir, "sub"))
					Expect(err).NotTo(HaveOccurred())
					Expect(dirInfo.IsDir()).To(BeTrue())

					fileInfo, err = os.Stat(filepath.Join(unpackedDir, "sub/some-file"))
					Expect(err).NotTo(HaveOccurred())
					Expect(fileInfo.IsDir()).To(BeFalse())
					Expect(fileInfo.Size()).To(Equal(int64(len("some-file-content"))))

					contents, err = ioutil.ReadFile(filepath.Join(unpackedDir, "sub/some-file"))
					Expect(err).NotTo(HaveOccurred())
					Expect(string(contents)).To(Equal("some-file-content"))
				})
			})

			Context("when using zstd encoding", func() {
				BeforeEach(func() {
					zstdWriter, err := zstd.NewWriter(tarBuffer)
					Expect(err).ToNot(HaveOccurred())
					err = tarfs.Compress(zstdWriter, tarDir, ".")
					Expect(err).NotTo(HaveOccurred())
					zstdWriter.Close()
					encoding = string(baggageclaim.ZstdEncoding)
				})

				It("creates a tar", func() {
					request, _ := http.NewRequest("PUT", fmt.Sprintf("/volumes/%s/stream-out?path=%s", myVolume.Handle, "dest-path"), nil)
					request.Header.Set("Accept-Encoding", string(baggageclaim.ZstdEncoding))
					recorder := httptest.NewRecorder()
					handler.ServeHTTP(recorder, request)
					Expect(recorder.Code).To(Equal(200))

					unpackedDir := filepath.Join(tempDir, "unpacked-dir")
					err := os.MkdirAll(unpackedDir, os.ModePerm)
					Expect(err).NotTo(HaveOccurred())
					defer os.RemoveAll(unpackedDir)

					tarByteReader, err := zstd.NewReader(recorder.Body)
					Expect(err).NotTo(HaveOccurred())
					err = tarfs.Extract(tarByteReader, unpackedDir)
					Expect(err).NotTo(HaveOccurred())
					tarByteReader.Close()
					fileInfo, err := os.Stat(filepath.Join(unpackedDir, "other-file"))
					Expect(err).NotTo(HaveOccurred())
					Expect(fileInfo.IsDir()).To(BeFalse())
					Expect(fileInfo.Size()).To(Equal(int64(len("other-file-content"))))

					contents, err := ioutil.ReadFile(filepath.Join(unpackedDir, "other-file"))
					Expect(err).NotTo(HaveOccurred())
					Expect(string(contents)).To(Equal("other-file-content"))

					dirInfo, err := os.Stat(filepath.Join(unpackedDir, "sub"))
					Expect(err).NotTo(HaveOccurred())
					Expect(dirInfo.IsDir()).To(BeTrue())

					fileInfo, err = os.Stat(filepath.Join(unpackedDir, "sub/some-file"))
					Expect(err).NotTo(HaveOccurred())
					Expect(fileInfo.IsDir()).To(BeFalse())
					Expect(fileInfo.Size()).To(Equal(int64(len("some-file-content"))))

					contents, err = ioutil.ReadFile(filepath.Join(unpackedDir, "sub/some-file"))
					Expect(err).NotTo(HaveOccurred())
					Expect(string(contents)).To(Equal("some-file-content"))
				})
			})
		})

		Context("when using an unsupported encoding", func() {
			It("returns 400 when err is UnsupportedEncodingError", func() {
				request, _ := http.NewRequest("PUT", fmt.Sprintf("/volumes/%s/stream-out?path=%s", myVolume.Handle, "dest-path"), nil)
				request.Header.Set("Accept-Encoding", "unsupported")
				recorder := httptest.NewRecorder()
				handler.ServeHTTP(recorder, request)
				Expect(recorder.Code).To(Equal(400))
			})
		})

		It("returns 404 when volume is not found", func() {
			request, _ := http.NewRequest("PUT", fmt.Sprintf("/volumes/%s/stream-out", "invalid-handle"), nil)
			recorder := httptest.NewRecorder()
			handler.ServeHTTP(recorder, request)
			Expect(recorder.Code).To(Equal(404))
		})
	})

	Describe("updating a volume", func() {
		It("can have it's properties updated", func() {
			body := &bytes.Buffer{}

			err := json.NewEncoder(body).Encode(baggageclaim.VolumeRequest{
				Handle: "some-handle",
				Strategy: encStrategy(map[string]string{
					"type": "empty",
				}),
				Properties: baggageclaim.VolumeProperties{
					"property-name": "property-val",
				},
			})
			Expect(err).NotTo(HaveOccurred())

			recorder := httptest.NewRecorder()
			request, _ := http.NewRequest("POST", "/volumes", body)
			handler.ServeHTTP(recorder, request)
			Expect(recorder.Code).To(Equal(201))

			recorder = httptest.NewRecorder()
			request, _ = http.NewRequest("GET", "/volumes?property-name=property-val", nil)
			handler.ServeHTTP(recorder, request)
			Expect(recorder.Code).To(Equal(200))

			var volumes volume.Volumes
			err = json.NewDecoder(recorder.Body).Decode(&volumes)
			Expect(err).NotTo(HaveOccurred())
			Expect(volumes).To(HaveLen(1))

			err = json.NewEncoder(body).Encode(baggageclaim.PropertyRequest{
				Value: "other-val",
			})
			Expect(err).NotTo(HaveOccurred())

			recorder = httptest.NewRecorder()
			request, _ = http.NewRequest("PUT", fmt.Sprintf("/volumes/%s/properties/property-name", volumes[0].Handle), body)
			handler.ServeHTTP(recorder, request)
			Expect(recorder.Code).To(Equal(http.StatusNoContent))
			Expect(recorder.Body.String()).To(BeEmpty())

			recorder = httptest.NewRecorder()
			request, _ = http.NewRequest("GET", "/volumes?property-name=other-val", nil)
			handler.ServeHTTP(recorder, request)
			Expect(recorder.Code).To(Equal(200))

			err = json.NewDecoder(recorder.Body).Decode(&volumes)
			Expect(err).NotTo(HaveOccurred())

			Expect(volumes).To(HaveLen(1))
		})

	})

	Describe("destroying a volume", func() {
		It("can be destroyed", func() {
			body := &bytes.Buffer{}

			err := json.NewEncoder(body).Encode(baggageclaim.VolumeRequest{
				Handle: "some-handle",
				Strategy: encStrategy(map[string]string{
					"type": "empty",
				}),
			})
			Expect(err).NotTo(HaveOccurred())

			recorder := httptest.NewRecorder()
			request, _ := http.NewRequest("POST", "/volumes", body)
			handler.ServeHTTP(recorder, request)
			Expect(recorder.Code).To(Equal(201))

			var createdVolume volume.Volume
			err = json.NewDecoder(recorder.Body).Decode(&createdVolume)
			Expect(err).NotTo(HaveOccurred())

			recorder = httptest.NewRecorder()
			request, err = http.NewRequest("DELETE", fmt.Sprintf("/volumes/%s", createdVolume.Handle), nil)
			Expect(err).NotTo(HaveOccurred())
			handler.ServeHTTP(recorder, request)
			Expect(recorder.Code).To(Equal(http.StatusNoContent))
			Expect(recorder.Body.String()).To(BeEmpty())

			recorder = httptest.NewRecorder()
			request, _ = http.NewRequest("GET", "/volumes", body)
			handler.ServeHTTP(recorder, request)
			Expect(recorder.Code).To(Equal(200))

			var volumes volume.Volumes
			err = json.NewDecoder(recorder.Body).Decode(&volumes)
			Expect(err).NotTo(HaveOccurred())
			Expect(volumes).To(HaveLen(0))
		})
	})

	Describe("destroying volumes", func() {
		It("can be destroyed", func() {
			for i := 1; i < 3; i++ {
				body := &bytes.Buffer{}
				err := json.NewEncoder(body).Encode(baggageclaim.VolumeRequest{
					Handle: fmt.Sprintf("some-handle-%d", i),
					Strategy: encStrategy(map[string]string{
						"type": "empty",
					}),
				})
				Expect(err).NotTo(HaveOccurred())

				recorder := httptest.NewRecorder()
				request, err := http.NewRequest("POST", "/volumes", body)
				Expect(err).NotTo(HaveOccurred())
				handler.ServeHTTP(recorder, request)
				Expect(recorder.Code).To(Equal(201))
			}

			recorder := httptest.NewRecorder()
			request, _ := http.NewRequest("GET", "/volumes", nil)
			handler.ServeHTTP(recorder, request)
			Expect(recorder.Code).To(Equal(200))

			var volumes volume.Volumes
			err := json.NewDecoder(recorder.Body).Decode(&volumes)
			Expect(err).NotTo(HaveOccurred())
			Expect(volumes).To(HaveLen(2))

			body := &bytes.Buffer{}
			err = json.NewEncoder(body).Encode([]string{"some-handle-1", "some-handle-2", "some-handle-3"})
			Expect(err).NotTo(HaveOccurred())

			recorder = httptest.NewRecorder()
			request, _ = http.NewRequest("DELETE", "/volumes/destroy", body)
			handler.ServeHTTP(recorder, request)
			Expect(recorder.Code).To(Equal(204))

			recorder = httptest.NewRecorder()
			request, _ = http.NewRequest("GET", "/volumes", nil)
			handler.ServeHTTP(recorder, request)
			Expect(recorder.Code).To(Equal(200))

			var volumes1 volume.Volumes
			err = json.NewDecoder(recorder.Body).Decode(&volumes1)
			Expect(err).NotTo(HaveOccurred())
			Expect(volumes1).To(HaveLen(0))
		})
	})

	Describe("creating a volume", func() {
		var (
			recorder *httptest.ResponseRecorder
			body     io.ReadWriter
		)

		JustBeforeEach(func() {
			recorder = httptest.NewRecorder()
			request, _ := http.NewRequest("POST", "/volumes", body)

			handler.ServeHTTP(recorder, request)
		})

		Context("when there are properties given", func() {
			var properties baggageclaim.VolumeProperties

			Context("with valid properties", func() {
				BeforeEach(func() {
					properties = baggageclaim.VolumeProperties{
						"property-name": "property-value",
					}

					body = &bytes.Buffer{}
					_ = json.NewEncoder(body).Encode(baggageclaim.VolumeRequest{
						Handle: "some-handle",
						Strategy: encStrategy(map[string]string{
							"type": "empty",
						}),
						Properties: properties,
					})
				})

				It("creates the properties file", func() {
					var response volume.Volume
					err := json.NewDecoder(recorder.Body).Decode(&response)
					Expect(err).NotTo(HaveOccurred())

					propertiesPath := filepath.Join(volumeDir, "live", response.Handle, "properties.json")
					Expect(propertiesPath).To(BeAnExistingFile())

					propertiesContents, err := ioutil.ReadFile(propertiesPath)
					Expect(err).NotTo(HaveOccurred())

					var storedProperties baggageclaim.VolumeProperties
					err = json.Unmarshal(propertiesContents, &storedProperties)
					Expect(err).NotTo(HaveOccurred())

					Expect(storedProperties).To(Equal(properties))
				})

				It("returns the properties in the response", func() {
					Expect(recorder.Body).To(ContainSubstring(`"property-name":"property-value"`))
				})
			})
		})

		Context("when there are no properties given", func() {
			BeforeEach(func() {
				body = &bytes.Buffer{}
				_ = json.NewEncoder(body).Encode(baggageclaim.VolumeRequest{
					Handle: "some-handle",
					Strategy: encStrategy(map[string]string{
						"type": "empty",
					}),
				})
			})

			It("writes a nice JSON", func() {
				Expect(recorder.Body).To(ContainSubstring(`"path":`))
				Expect(recorder.Body).To(ContainSubstring(`"handle":"some-handle"`))
			})

			Context("when handle is not provided in request", func() {
				BeforeEach(func() {
					body = &bytes.Buffer{}
					_ = json.NewEncoder(body).Encode(baggageclaim.VolumeRequest{
						Strategy: encStrategy(map[string]string{
							"type": "empty",
						}),
					})
				})

				It("generates a handle", func() {
					Expect(recorder.Body).To(ContainSubstring(`"path":`))
					uuidV4Regexp := `[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}`
					Expect(recorder.Body).To(MatchRegexp(`"handle":"` + uuidV4Regexp + `"`))
				})
			})

			Context("when invalid JSON is submitted", func() {
				BeforeEach(func() {
					body = bytes.NewBufferString("{{{{{{")
				})

				It("returns a 400 Bad Request response", func() {
					Expect(recorder.Code).To(Equal(http.StatusBadRequest))
				})

				It("writes a nice JSON response", func() {
					Expect(recorder.Body).To(ContainSubstring(`"error":`))
				})

				It("does not create a volume", func() {
					getRecorder := httptest.NewRecorder()
					getReq, _ := http.NewRequest("GET", "/volumes", nil)
					handler.ServeHTTP(getRecorder, getReq)
					Expect(getRecorder.Body).To(MatchJSON("[]"))
				})
			})

			Context("when no strategy is submitted", func() {
				BeforeEach(func() {
					body = bytes.NewBufferString("{}")
				})

				It("returns a 422 Unprocessable Entity response", func() {
					Expect(recorder.Code).To(Equal(422))
				})

				It("writes a nice JSON response", func() {
					Expect(recorder.Body).To(ContainSubstring(`"error":`))
				})

				It("does not create a volume", func() {
					getRecorder := httptest.NewRecorder()
					getReq, _ := http.NewRequest("GET", "/volumes", nil)
					handler.ServeHTTP(getRecorder, getReq)
					Expect(getRecorder.Body).To(MatchJSON("[]"))
				})
			})

			Context("when an unrecognized strategy is submitted", func() {
				BeforeEach(func() {
					body = &bytes.Buffer{}
					_ = json.NewEncoder(body).Encode(baggageclaim.VolumeRequest{
						Handle: "some-handle",
						Strategy: encStrategy(map[string]string{
							"type": "grime",
						}),
					})
				})

				It("returns a 422 Unprocessable Entity response", func() {
					Expect(recorder.Code).To(Equal(422))
				})

				It("writes a nice JSON response", func() {
					Expect(recorder.Body).To(ContainSubstring(`"error":`))
				})

				It("does not create a volume", func() {
					getRecorder := httptest.NewRecorder()
					getReq, _ := http.NewRequest("GET", "/volumes", nil)
					handler.ServeHTTP(getRecorder, getReq)
					Expect(getRecorder.Body).To(MatchJSON("[]"))
				})
			})

			Context("when the strategy is cow but not parent volume is provided", func() {
				BeforeEach(func() {
					body = &bytes.Buffer{}
					_ = json.NewEncoder(body).Encode(baggageclaim.VolumeRequest{
						Handle: "some-handle",
						Strategy: encStrategy(map[string]string{
							"type": "cow",
						}),
					})
				})

				It("returns a 422 Unprocessable Entity response", func() {
					Expect(recorder.Code).To(Equal(422))
				})

				It("writes a nice JSON response", func() {
					Expect(recorder.Body).To(ContainSubstring(`"error":`))
				})

				It("does not create a volume", func() {
					getRecorder := httptest.NewRecorder()
					getReq, _ := http.NewRequest("GET", "/volumes", nil)
					handler.ServeHTTP(getRecorder, getReq)
					Expect(getRecorder.Body).To(MatchJSON("[]"))
				})
			})

			Context("when the strategy is cow and the parent volume does not exist", func() {
				BeforeEach(func() {
					body = &bytes.Buffer{}
					_ = json.NewEncoder(body).Encode(baggageclaim.VolumeRequest{
						Strategy: encStrategy(map[string]string{
							"type":   "cow",
							"volume": "#pain",
						}),
					})
				})

				It("returns a 422 Unprocessable Entity response", func() {
					Expect(recorder.Code).To(Equal(422))
				})

				It("writes a nice JSON response", func() {
					Expect(recorder.Body).To(ContainSubstring(`"error":`))
				})

				It("does not create a volume", func() {
					getRecorder := httptest.NewRecorder()
					getReq, _ := http.NewRequest("GET", "/volumes", nil)
					handler.ServeHTTP(getRecorder, getReq)
					Expect(getRecorder.Body).To(MatchJSON("[]"))
				})
			})
		})
	})

	Describe("creating a volume asynchronously", func() {
		It("returns a volume future", func() {
			body := &bytes.Buffer{}
			err := json.NewEncoder(body).Encode(baggageclaim.VolumeRequest{
				Handle: "some-handle-1",
				Strategy: encStrategy(map[string]string{
					"type": "empty",
				}),
			})
			Expect(err).NotTo(HaveOccurred())

			recorder := httptest.NewRecorder()
			request, err := http.NewRequest("POST", "/volumes-async", body)
			Expect(err).NotTo(HaveOccurred())

			handler.ServeHTTP(recorder, request)

			Expect(recorder.Code).To(Equal(201))

			var volumeFuture baggageclaim.VolumeFutureResponse
			err = json.NewDecoder(recorder.Body).Decode(&volumeFuture)
			Expect(err).NotTo(HaveOccurred())
			Expect(volumeFuture.Handle).To(Equal("some-handle-1"))
		})

		Context("after creating a future", func() {
			It("returns a volume as soon as it has been created", func() {
				body := &bytes.Buffer{}
				err := json.NewEncoder(body).Encode(baggageclaim.VolumeRequest{
					Handle: "some-handle-2",
					Strategy: encStrategy(map[string]string{
						"type": "empty",
					}),
				})
				Expect(err).NotTo(HaveOccurred())

				recorder := httptest.NewRecorder()
				request, err := http.NewRequest("POST", "/volumes-async", body)
				Expect(err).NotTo(HaveOccurred())

				handler.ServeHTTP(recorder, request)

				Expect(recorder.Code).To(Equal(201))

				var volumeFuture baggageclaim.VolumeFutureResponse
				err = json.NewDecoder(recorder.Body).Decode(&volumeFuture)
				Expect(err).NotTo(HaveOccurred())

				recorder = httptest.NewRecorder()
				request, err = http.NewRequest("GET", "/volumes-async/"+volumeFuture.Handle, nil)
				Expect(err).NotTo(HaveOccurred())

				handler.ServeHTTP(recorder, request)

				Expect(recorder.Code).To(SatisfyAny(Equal(204), Equal(200)))

				Eventually(func() *httptest.ResponseRecorder {
					recorder = httptest.NewRecorder()
					request, err := http.NewRequest("GET", "/volumes-async/"+volumeFuture.Handle, nil)
					Expect(err).NotTo(HaveOccurred())

					handler.ServeHTTP(recorder, request)

					return recorder
				}).Should(SatisfyAll(
					WithTransform(func(recorder *httptest.ResponseRecorder) int { return recorder.Code }, Equal(200)),
					WithTransform(func(recorder *httptest.ResponseRecorder) baggageclaim.VolumeResponse {
						var volumeResponse baggageclaim.VolumeResponse
						err := json.NewDecoder(recorder.Body).Decode(&volumeResponse)
						Expect(err).NotTo(HaveOccurred())
						return volumeResponse
					}, Equal(baggageclaim.VolumeResponse{
						Handle:     "some-handle-2",
						Path:       filepath.Join(volumeDir, "live", "some-handle-2", "volume"),
						Properties: nil,
					})),
				))
			})

			It("can be canceled", func() {
				body := &bytes.Buffer{}
				err := json.NewEncoder(body).Encode(baggageclaim.VolumeRequest{
					Handle: "some-handle-3",
					Strategy: encStrategy(map[string]string{
						"type": "empty",
					}),
				})
				Expect(err).NotTo(HaveOccurred())

				recorder := httptest.NewRecorder()
				request, err := http.NewRequest("POST", "/volumes-async", body)
				Expect(err).NotTo(HaveOccurred())

				handler.ServeHTTP(recorder, request)

				Expect(recorder.Code).To(Equal(201))

				var volumeFuture baggageclaim.VolumeFutureResponse
				err = json.NewDecoder(recorder.Body).Decode(&volumeFuture)
				Expect(err).NotTo(HaveOccurred())

				recorder = httptest.NewRecorder()
				request, err = http.NewRequest("DELETE", "/volumes-async/"+volumeFuture.Handle, nil)
				Expect(err).NotTo(HaveOccurred())

				handler.ServeHTTP(recorder, request)

				Expect(recorder.Code).To(Equal(204))
			})
		})
	})

	Describe("p2p stream tar out of a volume", func() {
		var (
			myVolume    volume.Volume
			encoding    string
			otherWorker *httptest.Server
		)

		JustBeforeEach(func() {
			// Init a fake remote worker
			otherWorker = httptest.NewServer(handler)

			// Create a volume to stream out
			body := &bytes.Buffer{}
			err := json.NewEncoder(body).Encode(baggageclaim.VolumeRequest{
				Handle: "some-handle",
				Strategy: encStrategy(map[string]string{
					"type": "empty",
				}),
			})
			Expect(err).NotTo(HaveOccurred())
			request, err := http.NewRequest("POST", "/volumes", body)
			Expect(err).NotTo(HaveOccurred())

			recorder := httptest.NewRecorder()
			handler.ServeHTTP(recorder, request)
			Expect(recorder.Code).To(Equal(http.StatusCreated))

			err = json.NewDecoder(recorder.Body).Decode(&myVolume)
			Expect(err).NotTo(HaveOccurred())
		})

		AfterEach(func() {
			if otherWorker != nil {
				otherWorker.Close()
			}
		})

		It("returns 404 when source path is invalid", func() {
			request, _ := http.NewRequest("PUT", fmt.Sprintf("/volumes/%s/stream-p2p-out?path=%s&streamInURL=some-url&encoding=gzip", myVolume.Handle, "bogus-path"), nil)
			request.Header.Set("Accept-Encoding", string(baggageclaim.GzipEncoding))
			recorder := httptest.NewRecorder()
			handler.ServeHTTP(recorder, request)
			Expect(recorder.Code).To(Equal(404))

			var responseError *api.ErrorResponse
			err := json.NewDecoder(recorder.Body).Decode(&responseError)
			Expect(err).NotTo(HaveOccurred())
			Expect(responseError.Message).To(Equal("no such file or directory"))
		})

		Context("when streaming a file", func() {
			JustBeforeEach(func() {
				// Create a file in the volume.
				filePath := filepath.Join(volumeDir, "live", myVolume.Handle, "volume", "some-file")
				err := ioutil.WriteFile(filePath, []byte("some-file-content"), os.ModePerm)
				Expect(err).ToNot(HaveOccurred())

				streamInP2pURL := fmt.Sprintf("%s/volumes/%s/stream-in?path=dest-path", otherWorker.URL, myVolume.Handle)
				streamP2pOutRequest, _ := http.NewRequest(
					"PUT",
					fmt.Sprintf("/volumes/%s/stream-p2p-out?path=%s&streamInURL=%s&encoding=%s",
						myVolume.Handle, "some-file", streamInP2pURL, encoding),
					nil)
				streamP2pOutRecorder := httptest.NewRecorder()
				handler.ServeHTTP(streamP2pOutRecorder, streamP2pOutRequest)
				Expect(streamP2pOutRecorder.Code).To(Equal(200))

				destContentsPath := filepath.Join(volumeDir, "live", myVolume.Handle, "volume", "dest-path", "some-file")
				Expect(destContentsPath).To(BeAnExistingFile())
				Expect(ioutil.ReadFile(destContentsPath)).To(Equal([]byte("some-file-content")))
			})

			Context("when using gzip encoding", func() {
				BeforeEach(func() {
					encoding = string(baggageclaim.GzipEncoding)
				})

				It("should succeed", func() {
					// tests are in JustBeforeEach
				})
			})

			Context("when using zstd encoding", func() {
				BeforeEach(func() {
					encoding = string(baggageclaim.ZstdEncoding)
				})

				It("should succeed", func() {
					// tests are in JustBeforeEach
				})
			})
		})

		Context("when streaming a directory", func() {
			JustBeforeEach(func() {
				// Create a dir and a few files under the dir in the volume.
				path := filepath.Join(volumeDir, "live", myVolume.Handle, "volume", "some-dir")
				err := os.MkdirAll(filepath.Join(path, "sub"), os.ModePerm)
				Expect(err).NotTo(HaveOccurred())
				err = ioutil.WriteFile(filepath.Join(path, "sub", "some-file"), []byte("some-file-content"), os.ModePerm)
				Expect(err).NotTo(HaveOccurred())
				err = ioutil.WriteFile(filepath.Join(path, "other-file"), []byte("other-file-content"), os.ModePerm)
				Expect(err).NotTo(HaveOccurred())

				streamInP2pURL := fmt.Sprintf("%s/volumes/%s/stream-in?path=dest-path", otherWorker.URL, myVolume.Handle)
				streamP2pOutRequest, _ := http.NewRequest("PUT", fmt.Sprintf("/volumes/%s/stream-p2p-out?path=%s&streamInURL=%s&encoding=%s", myVolume.Handle, "some-dir", streamInP2pURL, encoding), nil)
				streamP2pOutRecorder := httptest.NewRecorder()
				handler.ServeHTTP(streamP2pOutRecorder, streamP2pOutRequest)
				Expect(streamP2pOutRecorder.Code).To(Equal(200))

				someContentsPath := filepath.Join(volumeDir, "live", myVolume.Handle, "volume", "dest-path", "sub", "some-file")
				Expect(someContentsPath).To(BeAnExistingFile())
				Expect(ioutil.ReadFile(someContentsPath)).To(Equal([]byte("some-file-content")))

				otherContentsPath := filepath.Join(volumeDir, "live", myVolume.Handle, "volume", "dest-path", "other-file")
				Expect(otherContentsPath).To(BeAnExistingFile())
				Expect(ioutil.ReadFile(otherContentsPath)).To(Equal([]byte("other-file-content")))
			})

			Context("when using gzip encoding", func() {
				BeforeEach(func() {
					encoding = string(baggageclaim.GzipEncoding)
				})
				It("should succeed", func() {
					// real tests are in JustBeforeEach
				})
			})

			Context("when using zstd encoding", func() {
				BeforeEach(func() {
					encoding = string(baggageclaim.ZstdEncoding)
				})
				It("should succeed", func() {
					// real tests are in JustBeforeEach
				})
			})
		})
	})
})

func encStrategy(strategy map[string]string) *json.RawMessage {
	bytes, err := json.Marshal(strategy)
	Expect(err).NotTo(HaveOccurred())

	msg := json.RawMessage(bytes)

	return &msg
}


text:
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
	xmlns:g="urn:import:com.google.gwt.user.client.ui">
	<ui:style>
		/* Add CSS here. See the GWT docs on UI Binder for more details */
	</ui:style>
	<g:FlowPanel>
		<g:TextBox ui:field="username">Username</g:TextBox>
		<g:PasswordTextBox ui:field="password">Password</g:PasswordTextBox>
		<g:Button ui:field="loginButton">Login</g:Button>
	</g:FlowPanel>
</ui:UiBinder>


text:
@extends("SimpleMenu::admin.shared")
@section('title', trans('SimpleMenu::messages.pages'))

@section('sub')
    <sm-index inline-template v-cloak :count="{{ count($pages) }}">

                    {{-- delete multi --}}

                        <template v-if="ids.length > 1">
                            {{ Form::open(['route' => $crud_prefix.'.pages.destroy_multi']) }}
                                <input type="hidden" name="ids" :value="ids">
                                <button type="submit" class="button is-danger">
                                    {{ trans('SimpleMenu::messages.delete_selected') }} "@{{ ids.length }}"
                                </button>
                            {{ Form::close() }}
                        </template>

                    {{-- add new --}}

                            {{ trans('SimpleMenu::messages.add_new') }}

                        {{ trans('SimpleMenu::messages.pages') }} "@{{ itemsCount }}"

                {{-- search --}}

                            <input class="input"
                            type="text"
                            v-model="searchFor"
                            placeholder="{{ trans('SimpleMenu::messages.find') }}">

                                <icon name="search"></icon>

                            <button class="button is-black" :disabled="!searchFor"
                                @click="resetSearch()">
                                <icon name="times"></icon>
                            </button>

                         0
                            ? '{{ trans('SimpleMenu::messages.select_non') }}'
                            : '{{ trans('SimpleMenu::messages.select_all') }}'">
                        {{ trans('SimpleMenu::messages.title') }}
                        {{ trans('SimpleMenu::messages.route') }}
                        {{ trans('SimpleMenu::messages.url') }}
                        {{ trans('SimpleMenu::messages.middlewares') }}
                        {{ trans('SimpleMenu::messages.roles') }}
                        {{ trans('SimpleMenu::messages.permissions') }}
                        {{ trans('SimpleMenu::messages.menus') }}
                        {{ trans('SimpleMenu::messages.locals') }}
                        {{ trans('SimpleMenu::messages.template') }}
                        {{ trans('SimpleMenu::messages.ops') }}

                    @foreach ($pages as $page)
                        @include('SimpleMenu::menu.partials.r_params')

id }}">
                            id }}')">
                                <input type="checkbox"
                                    id="sm-{{ $page->id }}"
                                    v-model="ids"
                                    class="cbx-checkbox"
                                    value="{{ $page->id }}"
                                    v-multi-ref:sm-ids>
                                id }}" class="cbx is-marginless" @click.prevent>
                                    <svg width="14px" height="12px" viewBox="0 0 14 12"><polyline points="1 7.6 5 11 13 1"></polyline></svg>

                                @if (in_array(LaravelLocalization::getCurrentLocale(), $page->getTranslatedLocales('title')))
                                    {{ $page->title }}
                                @else
                                    {{ empty($page->title) ? collect($page->getTranslations('title'))->first() : $page->title }}
                                @endif

                            {{ $page->route_name }}
                            {{ $page->prefix ? "$page->prefix/$page->url" : $page->url }}

                                @if ($page->middlewares)
                                    {{ $page->middlewares }}
                                @endif

                            roles->count() }}">
                                @foreach ($page->roles as $role)

                                        id) }}" class="is-white">{{ $role->name }}

                                @endforeach

                            permissions->count() }}">
                                @foreach ($page->permissions as $perm)

                                        id) }}" class="is-white">{{ $perm->name }}

                                @endforeach

                            menus->count() }}">
                                @foreach ($page->menus as $menu)

                                        id) }}" class="is-white">{{ $menu->name }}

                                @endforeach

                            getTranslatedLocales('title')) }}">
                                @foreach ($page->getTranslatedLocales('title') as $locale)
                                    {{ $locale }}
                                @endforeach

                                @if ($page->template)
                                    {{ $page->template }}
                                @endif

                            trashed() ? 'false' : 'true' }}">
                                id) }}"
                                    class="button is-link is-inline-block">
                                    {{ trans('SimpleMenu::messages.edit') }}

                                {{-- soft delete --}}
                                @if ($page->trashed())

                                        {{ Form::open(['method' => 'PUT', 'route' => [$crud_prefix.'.pages.restore', $page->id]]) }}
                                            <button type="submit" class="button is-success" {{ $check }}>
                                                {{ trans('SimpleMenu::messages.restore') }}
                                            </button>
                                        {{ Form::close() }}

                                        {{ Form::open(['method' => 'DELETE', 'route' => [$crud_prefix.'.pages.destroy_force', $page->id]]) }}
                                            <button type="submit" class="button is-danger is-outlined" {{ $check }}>
                                                {{ trans('SimpleMenu::messages.perm_delete') }}
                                            </button>
                                        {{ Form::close() }}

                                {{-- delete --}}
                                @else
                                    @php
                                        $check = $page->route_name == $crud_prefix ? 'disabled' : '';
                                    @endphp

                                        {{ Form::open(['method' => 'DELETE', 'route' => [$crud_prefix.'.pages.destroy', $page->id]]) }}
                                            <button type="submit" class="button is-danger" {{ $check }}>
                                                {{ trans('SimpleMenu::messages.delete') }}
                                            </button>
                                        {{ Form::close() }}

                                @endif

                    @endforeach

                        {{ trans('SimpleMenu::messages.no_entries') }}

    </sm-index>
@endsection


text:
<?php

namespace Elcodi\Admin\BannerBundle\Controller;

use Doctrine\ORM\Tools\Pagination\Paginator;
use Mmoreram\ControllerExtraBundle\Annotation\Entity as EntityAnnotation;
use Mmoreram\ControllerExtraBundle\Annotation\Form as FormAnnotation;
use Mmoreram\ControllerExtraBundle\Annotation\Paginator as PaginatorAnnotation;
use Mmoreram\ControllerExtraBundle\ValueObject\PaginatorAttributes;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;

use Elcodi\Admin\CoreBundle\Controller\Abstracts\AbstractAdminController;
use Elcodi\Component\Banner\Entity\Interfaces\BannerZoneInterface;
use Elcodi\Component\Core\Entity\Interfaces\EnabledInterface;

/**
 * Class Controller for Banner
 *
 * @Route(
 *      path = "/bannerzone",
 * )
 */
class BannerZoneController extends AbstractAdminController
{
    /**
     * List elements of certain entity type.
     *
     * This action is just a wrapper, so should never get any data,
     * as this is component responsibility
     *
     * @param integer $page             Page
     * @param integer $limit            Limit of items per page
     * @param string  $orderByField     Field to order by
     * @param string  $orderByDirection Direction to order by
     *
     * @return array Result
     *
     * @Route(
     *      path = "s/{page}/{limit}/{orderByField}/{orderByDirection}",
     *      name = "admin_banner_zone_list",
     *      requirements = {
     *          "page" = "\d*",
     *          "limit" = "\d*",
     *      },
     *      defaults = {
     *          "page" = "1",
     *          "limit" = "50",
     *          "orderByField" = "id",
     *          "orderByDirection" = "DESC",
     *      },
     * )
     * @Template
     * @Method({"GET"})
     */
    public function listAction(
        $page,
        $limit,
        $orderByField,
        $orderByDirection
    ) {
        if (!$this->canRead()) {
            $this->addFlash('error', $this->get('translator')->trans('admin.permissions.error'));
            return $this->redirect($this->generateUrl('admin_homepage'));
        }

        return [
            'page'             => $page,
            'limit'            => $limit,
            'orderByField'     => $orderByField,
            'orderByDirection' => $orderByDirection,
        ];
    }

    /**
     * Component for entity list.
     *
     * As a component, this action should not return all the html macro, but
     * only the specific component
     *
     * @param Paginator           $paginator           Paginator instance
     * @param PaginatorAttributes $paginatorAttributes Paginator attributes
     * @param integer             $page                Page
     * @param integer             $limit               Limit of items per page
     * @param string              $orderByField        Field to order by
     * @param string              $orderByDirection    Direction to order by
     *
     * @return array Result
     *
     * @Route(
     *      path = "s/component/{page}/{limit}/{orderByField}/{orderByDirection}",
     *      name = "admin_banner_zone_list_component",
     *      requirements = {
     *          "page" = "\d*",
     *          "limit" = "\d*",
     *      },
     *      defaults = {
     *          "page" = "1",
     *          "limit" = "50",
     *          "orderByField" = "id",
     *          "orderByDirection" = "DESC",
     *      },
     * )
     * @Template
     * @Method({"GET"})
     *
     * @PaginatorAnnotation(
     *      attributes = "paginatorAttributes",
     *      class = "elcodi.entity.banner_zone.class",
     *      page = "~page~",
     *      limit = "~limit~",
     *      orderBy = {
     *          {"x", "~orderByField~", "~orderByDirection~"}
     *      }
     * )
     */
    public function listComponentAction(
        Paginator $paginator,
        PaginatorAttributes $paginatorAttributes,
        $page,
        $limit,
        $orderByField,
        $orderByDirection
    ) {
        return [
            'paginator'        => $paginator,
            'page'             => $page,
            'limit'            => $limit,
            'orderByField'     => $orderByField,
            'orderByDirection' => $orderByDirection,
            'totalPages'       => $paginatorAttributes->getTotalPages(),
            'totalElements'    => $paginatorAttributes->getTotalElements(),
        ];
    }

    /**
     * View element action.
     *
     * This action is just a wrapper, so should never get any data,
     * as this is component responsibility
     *
     * @param integer $id Entity id
     *
     * @return array Result
     *
     * @Route(
     *      path = "/{id}",
     *      name = "admin_banner_zone_view",
     *      requirements = {
     *          "id" = "\d*",
     *      }
     * )
     * @Template
     * @Method({"GET"})
     */
    public function viewAction($id)
    {
        if (!$this->canRead()) {
            $this->addFlash('error', $this->get('translator')->trans('admin.permissions.error'));
            return $this->redirect($this->generateUrl('admin_homepage'));
        }

        return [
            'id' => $id,
        ];
    }

    /**
     * Component for entity view
     *
     * As a component, this action should not return all the html macro, but
     * only the specific component
     *
     * @param BannerZoneInterface $entity Entity to view
     *
     * @return array Result
     *
     * @Route(
     *      path = "/component/{id}",
     *      name = "admin_banner_zone_view_component",
     *      requirements = {
     *          "id" = "\d*",
     *      }
     * )
     * @Template
     * @Method({"GET"})
     *
     * @EntityAnnotation(
     *      class = {
     *          "factory" = "elcodi.factory.banner_zone",
     *      },
     *      mapping = {
     *          "id" = "~id~"
     *      }
     * )
     */
    public function viewComponentAction(BannerZoneInterface $entity)
    {
        return [
            'entity' => $entity,
        ];
    }

    /**
     * New element action
     *
     * This action is just a wrapper, so should never get any data,
     * as this is component responsibility
     *
     * @return array Result
     *
     * @Route(
     *      path = "/new",
     *      name = "admin_banner_zone_new"
     * )
     * @Template
     * @Method({"GET"})
     */
    public function newAction()
    {
        if (!$this->canCreate()) {
            $this->addFlash('error', $this->get('translator')->trans('admin.permissions.error'));
            return $this->redirect($this->generateUrl('admin_homepage'));
        }

        return [];
    }

    /**
     * New element action
     *
     * As a component, this action should not return all the html macro, but
     * only the specific component
     *
     * @param FormView $formView Form view
     *
     * @return array Result
     *
     * @Route(
     *      path = "/new/component",
     *      name = "admin_banner_zone_new_component"
     * )
     * @Template
     * @Method({"GET"})
     *
     * @EntityAnnotation(
     *      class = {
     *          "factory" = "elcodi.factory.banner_zone",
     *      }
     * )
     * @FormAnnotation(
     *      class = "elcodi_admin_banner_zone_form_type_banner_zone",
     *      name  = "formView",
     *      entity = "entity"
     * )
     */
    public function newComponentAction(FormView $formView)
    {
        return [
            'form' => $formView,
        ];
    }

    /**
     * Save new element action
     *
     * Should be POST
     *
     * @param BannerZoneInterface $entity  Entity to save
     * @param FormInterface       $form    Form view
     * @param boolean             $isValid Request handle is valid
     *
     * @return RedirectResponse Redirect response
     *
     * @Route(
     *      path = "/save",
     *      name = "admin_banner_zone_save"
     * )
     * @Method({"POST"})
     *
     * @EntityAnnotation(
     *      class = {
     *          "factory" = "elcodi.factory.banner_zone",
     *      },
     *      persist = true
     * )
     * @FormAnnotation(
     *      class = "elcodi_admin_banner_zone_form_type_banner_zone",
     *      name  = "form",
     *      entity = "entity",
     *      handleRequest = true,
     *      validate = "isValid"
     * )
     */
    public function saveAction(
        BannerZoneInterface $entity,
        FormInterface $form,
        $isValid
    ) {
        if (!$this->canCreate()) {
            $this->addFlash('error', $this->get('translator')->trans('admin.permissions.error'));
            return $this->redirect($this->generateUrl('admin_homepage'));
        }

        if ($isValid) {
            $this
                ->get('elcodi.object_manager.banner_zone')
                ->flush($entity);
        }

        return $this->redirectRoute("admin_banner_zone_view", [
            'id' => $entity->getId(),
        ]);
    }

    /**
     * New element action
     *
     * This action is just a wrapper, so should never get any data,
     * as this is component responsibility
     *
     * @param integer $id Entity id
     *
     * @return array Result
     *
     * @Route(
     *      path = "/{id}/edit",
     *      name = "admin_banner_zone_edit"
     * )
     * @Template
     * @Method({"GET"})
     */
    public function editAction($id)
    {
        if (!$this->canUpdate()) {
            $this->addFlash('error', $this->get('translator')->trans('admin.permissions.error'));
            return $this->redirect($this->generateUrl('admin_homepage'));
        }

        return [
            'id' => $id,
        ];
    }

    /**
     * New element component action
     *
     * As a component, this action should not return all the html macro, but
     * only the specific component
     *
     * @param BannerZoneInterface $entity   Entity
     * @param FormView            $formView Form view
     *
     * @return array Result
     *
     * @Route(
     *      path = "/{id}/edit/component",
     *      name = "admin_banner_zone_edit_component"
     * )
     * @Template
     * @Method({"GET"})
     *
     * @EntityAnnotation(
     *      class = "elcodi.entity.banner_zone.class",
     *      mapping = {
     *          "id": "~id~",
     *      }
     * )
     * @FormAnnotation(
     *      class = "elcodi_admin_banner_zone_form_type_banner_zone",
     *      name  = "formView",
     *      entity = "entity"
     * )
     */
    public function editComponentAction(
        BannerZoneInterface $entity,
        FormView $formView
    ) {
        return [
            'entity' => $entity,
            'form'   => $formView,
        ];
    }

    /**
     * Updated edited element action
     *
     * Should be POST
     *
     * @param BannerZoneInterface $entity  Entity to update
     * @param FormInterface       $form    Form view
     * @param boolean             $isValid Request handle is valid
     *
     * @return RedirectResponse Redirect response
     *
     * @Route(
     *      path = "/{id}/update",
     *      name = "admin_banner_zone_update"
     * )
     * @Method({"POST"})
     *
     * @EntityAnnotation(
     *      class = "elcodi.entity.banner_zone.class",
     *      mapping = {
     *          "id": "~id~",
     *      }
     * )
     * @FormAnnotation(
     *      class = "elcodi_admin_banner_zone_form_type_banner_zone",
     *      name  = "form",
     *      entity = "entity",
     *      handleRequest = true,
     *      validate = "isValid"
     * )
     */
    public function updateAction(
        BannerZoneInterface $entity,
        FormInterface $form,
        $isValid
    ) {
        if (!$this->canUpdate()) {
            $this->addFlash('error', $this->get('translator')->trans('admin.permissions.error'));
            return $this->redirect($this->generateUrl('admin_homepage'));
        }

        if ($isValid) {
            $this
                ->get('elcodi.object_manager.banner_zone')
                ->flush($entity);
        }

        return $this->redirectRoute("admin_banner_zone_view", [
            'id' => $entity->getId(),
        ]);
    }

    /**
     * Enable entity
     *
     * @param Request          $request Request
     * @param EnabledInterface $entity  Entity to enable
     *
     * @return array Result
     *
     * @Route(
     *      path = "/{id}/enable",
     *      name = "admin_banner_zone_enable"
     * )
     * @Method({"GET", "POST"})
     *
     * @EntityAnnotation(
     *      class = "elcodi.entity.banner_zone.class",
     *      mapping = {
     *          "id" = "~id~"
     *      }
     * )
     */
    public function enableAction(
        Request $request,
        EnabledInterface $entity
    ) {
        if (!$this->canUpdate()) {
            $this->addFlash('error', $this->get('translator')->trans('admin.permissions.error'));
            return $this->redirect($this->generateUrl('admin_homepage'));
        }

        return parent::enableAction(
            $request,
            $entity
        );
    }

    /**
     * Disable entity
     *
     * @param Request          $request Request
     * @param EnabledInterface $entity  Entity to disable
     *
     * @return array Result
     *
     * @Route(
     *      path = "/{id}/disable",
     *      name = "admin_banner_zone_disable"
     * )
     * @Method({"GET", "POST"})
     *
     * @EntityAnnotation(
     *      class = "elcodi.entity.banner_zone.class",
     *      mapping = {
     *          "id" = "~id~"
     *      }
     * )
     */
    public function disableAction(
        Request $request,
        EnabledInterface $entity
    ) {
        if (!$this->canUpdate()) {
            $this->addFlash('error', $this->get('translator')->trans('admin.permissions.error'));
            return $this->redirect($this->generateUrl('admin_homepage'));
        }

        return parent::disableAction(
            $request,
            $entity
        );
    }

    /**
     * Delete entity
     *
     * @param Request $request      Request
     * @param mixed   $entity       Entity to delete
     * @param string  $redirectPath Redirect path
     *
     * @return RedirectResponse Redirect response
     *
     * @Route(
     *      path = "/{id}/delete",
     *      name = "admin_banner_zone_delete"
     * )
     * @Method({"GET", "POST"})
     *
     * @EntityAnnotation(
     *      class = "elcodi.entity.banner_zone.class",
     *      mapping = {
     *          "id" = "~id~"
     *      }
     * )
     */
    public function deleteAction(
        Request $request,
        $entity,
        $redirectPath = null
    ) {
        if (!$this->canDelete()) {
            $this->addFlash('error', $this->get('translator')->trans('admin.permissions.error'));
            return $this->redirect($this->generateUrl('admin_homepage'));
        }

        return parent::deleteAction(
            $request,
            $entity,
            $this->generateUrl('admin_banner_zone_list')
        );
    }
}


text:
#import <SportsWorkout/ObservationTarget.h>

@class NSString;

@interface UserEventObservationTarget : ObservationTarget
{
    NSString *_event;
}

+ (id)targetWithEvent:(id)arg1 selector:(SEL)arg2;
@property(retain, nonatomic) NSString *event; // @synthesize event=_event;
- (id)description;
- (void)dealloc;

@end


text:
package org.apache.syncope.client.console.panels;

import org.apache.commons.lang3.StringUtils;
import org.apache.syncope.client.console.SyncopeConsoleSession;
import org.apache.syncope.client.console.commons.Constants;
import org.apache.syncope.client.console.pages.BasePage;
import org.apache.syncope.client.console.wicket.markup.html.bootstrap.dialog.BaseModal;
import org.apache.syncope.common.lib.to.SecurityQuestionTO;
import org.apache.syncope.common.rest.api.service.SecurityQuestionService;
import org.apache.wicket.PageReference;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.form.Form;

public class SecurityQuestionsModalPanel extends AbstractModalPanel<SecurityQuestionTO> {

    private static final long serialVersionUID = 4024126489500665435L;

    private final SecurityQuestionTO securityQuestionTO;

    public SecurityQuestionsModalPanel(
            final BaseModal<SecurityQuestionTO> modal,
            final SecurityQuestionTO securityQuestionTO,
            final PageReference pageRef) {
        super(modal, pageRef);
        this.securityQuestionTO = securityQuestionTO;
        add(new SecurityQuestionDetailsPanel("securityQuestionDetailsPanel", getItem()));
    }

    @Override
    public final SecurityQuestionTO getItem() {
        return this.securityQuestionTO;
    }

    @Override
    public void onSubmit(final AjaxRequestTarget target, final Form<?> form) {
        try {
            if (securityQuestionTO.getKey() == null) {
                SyncopeConsoleSession.get().getService(SecurityQuestionService.class).create(securityQuestionTO);
            } else {
                SyncopeConsoleSession.get().getService(SecurityQuestionService.class).update(securityQuestionTO);
            }

            SyncopeConsoleSession.get().info(getString(Constants.OPERATION_SUCCEEDED));
            modal.close(target);
        } catch (Exception e) {
            LOG.error("While creating or updating {}", securityQuestionTO, e);
            SyncopeConsoleSession.get().error(StringUtils.isBlank(e.getMessage()) ? e.getClass().getName() : e.
                    getMessage());
        }
        ((BasePage) pageRef.getPage()).getNotificationPanel().refresh(target);
    }
}


text:
import nerfDart from 'nerf-dart'
import { getAuthHeadersFromConfig } from './getAuthHeadersFromConfig'

export function createGetAuthHeaderByURI (
  opts: {
    allSettings: Record<string, string>
    userSettings?: Record<string, string>
  }
) {
  const authHeaders = getAuthHeadersFromConfig({
    allSettings: opts.allSettings,
    userSettings: opts.userSettings ?? {},
  })
  if (Object.keys(authHeaders).length === 0) return () => undefined
  return getAuthHeaderByURI.bind(null, authHeaders, getMaxParts(Object.keys(authHeaders)))
}

function getMaxParts (uris: string[]) {
  return uris.reduce((max, uri) => {
    const parts = uri.split('/').length
    return parts > max ? parts : max
  }, 0)
}

function getAuthHeaderByURI (authHeaders: Record<string, string>, maxParts: number, uri: string) {
  const nerfed = nerfDart(uri)
  const parts = nerfed.split('/')
  for (let i = Math.min(parts.length, maxParts) - 1; i >= 3; i--) {
    const key = `${parts.slice(0, i).join('/')}/` // eslint-disable-line
    if (authHeaders[key]) return authHeaders[key]
  }
  return undefined
}


text:
#ifndef JS_DATA_GATHERER_H_
#define JS_DATA_GATHERER_H_

#include "gears/base/npapi/browser_utils.h"
#include "gears/geolocation/device_data_provider.h"
#include "data_gatherer.h"

class JsDataGatherer
    : public ModuleImplBaseClass {
 public:
  JsDataGatherer();
  virtual ~JsDataGatherer();

  void GatherData(JsCallContext *context);

  bool CreateJavaScriptDataObject(
      LocutorSystemInfo &sysInfo,
      JsRunnerInterface *js_runner,
      JsObject *data_object);

};

#endif /* JS_DATA_GATHERER_H_ */


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W28936_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans13.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Existing Wells Within Spacing Unit

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Continental Resources, Inc. has identified the following wells which currently exist in the spacing unit consisting of: 19,30, 31-T153N—R99W 8: 3—N/2 10-T152N-R100W Williams County, ND

    <p class="styleSans44.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

APINo We" Name WeHbore 19424 3310501935 NENWSec19,153N,99W Bud 1-19H 375 FNL 1855 FWL 22986 3310502632 NENWSec31,153N,99W Alfsvaag1-31H 325FNL 2100FWL
CRI has determined that the identified existing wells in the spacing unit specified above are not within 500' ofthe proposed Alfsvaag 2-31H wellbore and do not pose any collision threats during drilling or completion operations.

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">


text:
package org.fest.swing.core;

import static org.fest.assertions.Assertions.assertThat;

import javax.swing.JButton;
import javax.swing.JTextField;

import org.junit.Test;

/**
 * Tests for {@link NameMatcher#matches(java.awt.Component)}.
 * <p>
 * The {@link NameMatcher} is created through {@link NameMatcher#NameMatcher(String, Class, boolean)}, passing
 * {@code true} to indicate that the {@link java.awt.Component} to match must be showing on the screen.
 * </p>
 *
 * @author Alex Ruiz
 */
public class NameMatcher_matches_byNameTypeAndShowing_Test extends NameMatcher_TestCase {
  @Test
  public void should_return_false_if_type_does_not_match() {
    window.display();
    NameMatcher matcher = new NameMatcher("b", JTextField.class, true);
    assertThat(matcher.matches(window.button)).isFalse();
  }

  @Test
  public void should_return_false_if_name_and_type_match_but_Component_is_not_showing() {
    NameMatcher matcher = new NameMatcher(LABEL_TEXT, JButton.class, true);
    assertThat(matcher.matches(window.button)).isFalse();
  }

  @Test
  public void should_return_false_if_nothing_matches() {
    NameMatcher matcher = new NameMatcher("b", JTextField.class, true);
    assertThat(matcher.matches(window.button)).isFalse();
  }

}


text:
package org.javalite.common;

import org.apache.commons.lang3.SystemUtils;
import org.junit.Test;

import java.io.File;

import static org.javalite.common.RuntimeUtil.execute;
import static org.javalite.test.jspec.JSpec.the;
import static org.junit.Assume.assumeFalse;

/**
 * @author igor on 9/23/18.
 */
public class RuntimeUtilSpec {

    @Test
    public void shouldUseDefaultBufferSize(){
        assumeFalse(SystemUtils.IS_OS_WINDOWS); // will skip these tests on Windows,

        the(execute("ls -ls").out).shouldContain("pom.xml");
    }

    @Test
    public void shouldUseDefaultBufferSizeSplitArguments(){
        assumeFalse(SystemUtils.IS_OS_WINDOWS);

        the(execute("ls", "-ls").out).shouldContain("pom.xml");
    }

    @Test
    public void shouldOverrideBufferSize(){
        assumeFalse(SystemUtils.IS_OS_WINDOWS);

        the(execute(4096, "ls", "-ls").out).shouldContain("pom.xml");
    }

    @Test
    public void shouldOverrideBufferSizeSplitArguments(){
        assumeFalse(SystemUtils.IS_OS_WINDOWS);

        the(execute(4096, "ls -ls").out).shouldContain("pom.xml");
    }

    @Test
    public void shouldUseLocation(){
        assumeFalse(SystemUtils.IS_OS_WINDOWS);

        the(execute(4096, new File("."), "ls -ls").out).shouldContain("pom.xml");
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GTA;
using GTA.Math;
using GTA.Native;
using Newtonsoft.Json;

namespace WebScriptHook
{
    delegate object WebFunction(string arg, params object[] args);

    class WebInput
    {
        public string Cmd { get; set; }
        public string Arg { get; set; }
        public object[] Args { get; set; }
        public string UID { get; private set; }

        [JsonConstructor]
        public WebInput(string Cmd, string Arg, object[] Args, string UID)
        {
            this.Cmd = Cmd;
            this.Arg = Arg;
            this.Args = Args;
            this.UID = UID;
        }

        public object Execute()
        {
            if (string.IsNullOrEmpty(Cmd)) return null;

            WebFunction func = FunctionConvert.GetFunction(Cmd);
            if (func != null)
            {
                return func(Arg, Args);
            }
            else
            {
                return null;
            }
        }
    }
}


text:
<?php

/**
 * OAuthAdminToken
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @package    ##PACKAGE##
 * @subpackage ##SUBPACKAGE##
 * @author     ##NAME## <##EMAIL##>
 * @version    SVN: $Id: Builder.php 5441 2009-01-30 22:58:43Z jwage $
 */
class OAuthAdminToken extends BaseOAuthAdminToken
{

}


text:
@interface HSBaseTableViewCell()

@end

@implementation HSBaseTableViewCell

+ (HSBaseTableViewCell *)cellWithIdentifier:(NSString *)cellIdentifier tableView:(UITableView *)tableView;

{
    HSBaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if(cell == nil){
         cell = [[HSBaseTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    return cell;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if(self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]){
        [self setupUI];
    }
    return self;
}

- (void)setupUI
{
    //添加顶部分割线
    CALayer *topLine = [CALayer layer];
    [topLine setFrame:CGRectMake(0, 0, self.frame.size.width, HS_KSeparateHeight)];
    [topLine setBackgroundColor:HS_KSeparateColor.CGColor];
    [self.contentView.layer addSublayer:topLine];
    self.topLine = topLine;

    //添加底部分割线
    CALayer *bottomLine = [CALayer layer];
    [bottomLine setFrame:CGRectMake(0, 0, self.frame.size.width, HS_KSeparateHeight)];
    [bottomLine setBackgroundColor:HS_KSeparateColor.CGColor];
    [self.contentView.layer addSublayer:bottomLine];
    self.bottomLine = bottomLine;

}

- (void)setupDataModel:(HSBaseCellModel *)model
{
    self.cellModel = model;
    self.selectionStyle = model.selectionStyle;
    [self.bottomLine setHs_y:model.cellHeight - model.separateHeight];
    [self.bottomLine setHs_height:model.separateHeight];
    [self.topLine setHs_height:model.separateHeight];
    [self.bottomLine setBackgroundColor:model.separateColor.CGColor];
    [self.topLine setBackgroundColor:model.separateColor.CGColor];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    [self.bottomLine setHs_width:self.frame.size.width];
    [self.topLine setHs_width:self.frame.size.width];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
}

+ (CGFloat)getCellHeight:(HSBaseCellModel *)model
{
    return model.cellHeight;
}

@end