content_type stringclasses 8
values | main_lang stringclasses 7
values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
PHP | PHP | allow throwable in stub renderer | f618b05c4ec86b4d424beeec525512d1cb34fac4 | <ide><path>src/TestSuite/Stub/TestExceptionRenderer.php
<ide> */
<ide> namespace Cake\TestSuite\Stub;
<ide>
<del>use Exception;
<add>use Throwable;
<ide>
<ide> /**
<ide> * Test Exception Renderer.
<ide> class TestExceptionRenderer
<ide> /**
<ide> * Simply rethrow the given exception
<ide> *
<del> * @param \Exception $exception Exception.
<add> * @param \Throwable $exception Exception.
<ide> * @return void
<del> * @throws \Exception $exception Rethrows the passed exception.
<add> * @throws \Throwable $exception Rethrows the passed exception.
<ide> */
<del> public function __construct(Exception $exception)
<add> public function __construct(Throwable $exception)
<ide> {
<ide> throw $exception;
<ide> } | 1 |
Text | Text | update translation for chinese | 930e1fefb3846aa295a6ff9450ed9e69657693ee | <ide><path>guide/chinese/python/if-elif-else-statements/index.md
<ide> ---
<ide> title: If Elif Else Statements
<del>localeTitle: 如果Elif Else声明
<add>localeTitle: If / Elif / Else语句
<ide> ---
<del>## 如果Elif Else声明
<add>## If / Elif / Else语句
<ide>
<del>`if` / `elif` / `else`结构是控制程序流的常用方法,允许您根据某些数据的值执行特定的代码块。如果关键字`if`后面的条件计算为`true` ,则代码块将执行: 请注意,在条件检查之前和之后不使用括号,如同其他语言一样。
<add>`if` / `elif` / `else`结构是控制程序流的常用方法,允许您根据某些数据的值执行特定的代码块。如果关键字`if`后面的条件表达式返回为`True` ,则代码块将执行: 请注意,在条件检查之前和之后不使用括号,如同其他语言一样。
<ide>
<ide> ```python
<ide> if True:
<ide> if True:
<ide> ```python
<ide> x = 5
<ide>
<del> if x > 4:
<add>if x > 4:
<ide> print("The condition was true!") #this statement executes
<ide> ```
<ide>
<del>如果条件为`false` ,您可以选择添加将执行的`else`响应:
<add>您可以选择添加`else`执行条件为`False`的代码块:
<ide>
<ide> ```python
<ide> if not True:
<ide> print('If statement will execute!')
<del> else:
<add>else:
<ide> print('Else statement will execute!')
<ide> ```
<ide>
<del>或者你也可以看到这个例子
<add>或者你也可以看看这个例子
<ide>
<ide> ```python
<ide> y = 3
<ide>
<del> if y > 4:
<add>if y > 4:
<ide> print("I won't print!") #this statement does not execute
<del> else:
<add>else:
<ide> print("The condition wasn't true!") #this statement executes
<ide> ```
<ide>
<del>_请注意, `else`关键字后面没有条件 - 它捕获条件为`false`所有情况_
<add>_请注意, `else`关键字后面没有条件 - 它捕获条件为`False`所有情况_
<ide>
<del>可以通过在初始`if`语句之后包含一个或多个`elif`检查来检查多个条件,但只执行一个条件:
<add>可以通过在初始`if`语句之后包含一个或多个`elif`来检查多个条件,但只执行一个条件:
<ide>
<ide> ```python
<ide> z = 7
<ide>
<del> if z > 8:
<add>if z > 8:
<ide> print("I won't print!") #this statement does not execute
<del> elif z > 5:
<add>elif z > 5:
<ide> print("I will!") #this statement will execute
<del> elif z > 6:
<add>elif z > 6:
<ide> print("I also won't print!") #this statement does not execute
<del> else:
<add>else:
<ide> print("Neither will I!") #this statement does not execute
<ide> ```
<ide>
<del>_请注意,只有第一个计算为`true`条件才会执行。即使`z > 6`为`true` , `if/elif/else`块`if/elif/else`在第一个真实条件之后终止。这意味着只有在没有条件`true`的情况下才会执行`else` 。_
<add>_请注意,只有第一个计算为`True`条件才会执行。即使`z > 6`为`True` , `if/elif/else`块在第一个真实条件之后终止。这意味着只有在没有条件为`True`的情况下才会执行`else` 。_
<ide>
<ide> 我们还可以创建嵌套if用于决策。在此之前请参阅前面的href ='https://guide.freecodecamp.org/python/code-blocks-and-indentation'target ='\_ blank'rel ='nofollow'>缩进指南。
<ide>
<del>让我们举个例子来找一个偶数也大于'10'的数字
<add>让我们举个例子来找一个偶数大于'10'的数字
<ide> ```
<ide> python
<del> x = 34
<del> if x % 2 == 0: # this is how you create a comment and now, checking for even.
<add>x = 34
<add>if x % 2 == 0: # this is how you create a comment and now, checking for even.
<ide> if x > 10:
<ide> print("This number is even and is greater than 10")
<ide> else:
<ide> print("This number is even, but not greater 10")
<del> else:
<add>else:
<ide> print ("The number is not even. So point checking further.")
<ide> ```
<ide>
<ide> python
<ide>
<ide> **_内联python if-else语句_**
<ide>
<del>我们也可以使用if-else语句内联python函数 以下示例应检查数字是否大于或等于50,如果是,则返回True:
<add>我们也可以使用if-else语句内联python函数。以下示例应检查数字是否大于或等于50,如果是,则返回`True`:
<ide> ```
<ide> python
<del> x = 89
<del> is_greater = True if x >= 50 else False
<add>x = 89
<add>is_greater = True if x >= 50 else False
<ide>
<del> print(is_greater)
<add>print(is_greater)
<ide> ```
<ide>
<del>产量
<add>输出
<ide> ```
<ide> >
<del> True
<del> >
<add>True
<add>>
<ide>
<del>```
<ide>\ No newline at end of file
<add>``` | 1 |
Ruby | Ruby | remove duplicate test and fix a typo in the test | 3e43edd5ae301892a702c19ffb90853c03a3fac1 | <ide><path>actionpack/test/controller/parameters/dup_test.rb
<ide> class ParametersDupTest < ActiveSupport::TestCase
<ide> assert_not_equal @params, dupped_params
<ide> end
<ide>
<del> test "changes tp a duplicate's permitted status do not affect the original" do
<add> test "changes to a duplicate's permitted status do not affect the original" do
<ide> dupped_params = @params.dup
<ide> dupped_params.permit!
<ide> assert_not_equal @params, dupped_params
<ide><path>actionpack/test/controller/parameters/parameters_permit_test.rb
<ide> def walk_permitted params
<ide> assert_equal "Jonas", @params[:person][:family][:brother]
<ide> end
<ide>
<del> test "permit state is kept on a dup" do
<del> @params.permit!
<del> assert_equal @params.permitted?, @params.dup.permitted?
<del> end
<del>
<ide> test "permit is recursive" do
<ide> @params.permit!
<ide> assert @params.permitted? | 2 |
Go | Go | implement teardown removeallimages | a9688cdca5577d6db65d76f38bcbe4c1e6f5994f | <ide><path>integration-cli/check_test.go
<ide> type DockerSuite struct {
<ide>
<ide> func (s *DockerSuite) TearDownTest(c *check.C) {
<ide> deleteAllContainers()
<add> deleteAllImages()
<ide> s.TimerSuite.TearDownTest(c)
<ide> }
<ide>
<ide><path>integration-cli/docker_api_containers_test.go
<ide> func (s *DockerSuite) TestContainerApiCommit(c *check.C) {
<ide> if err := json.Unmarshal(b, &img); err != nil {
<ide> c.Fatal(err)
<ide> }
<del> defer deleteImages(img.Id)
<ide>
<ide> cmd, err := inspectField(img.Id, "Config.Cmd")
<ide> if err != nil {
<ide><path>integration-cli/docker_api_images_test.go
<ide> func (s *DockerSuite) TestApiImagesFilter(c *check.C) {
<ide> name := "utest:tag1"
<ide> name2 := "utest/docker:tag2"
<ide> name3 := "utest:5000/docker:tag3"
<del> defer deleteImages(name, name2, name3)
<ide> for _, n := range []string{name, name2, name3} {
<ide> if out, err := exec.Command(dockerBinary, "tag", "busybox", n).CombinedOutput(); err != nil {
<ide> c.Fatal(err, out)
<ide> func (s *DockerSuite) TestApiImagesSaveAndLoad(c *check.C) {
<ide> c.Fatal(err)
<ide> }
<ide> id := strings.TrimSpace(out)
<del> defer deleteImages("saveandload")
<ide>
<ide> status, body, err := sockRequestRaw("GET", "/images/"+id+"/get", nil, "")
<ide> c.Assert(status, check.Equals, http.StatusOK)
<ide><path>integration-cli/docker_cli_build_test.go
<ide> import (
<ide>
<ide> func (s *DockerSuite) TestBuildJSONEmptyRun(c *check.C) {
<ide> name := "testbuildjsonemptyrun"
<del> defer deleteImages(name)
<ide>
<ide> _, err := buildImage(
<ide> name,
<ide> func (s *DockerSuite) TestBuildJSONEmptyRun(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildEmptyWhitespace(c *check.C) {
<ide> name := "testbuildemptywhitespace"
<del> defer deleteImages(name)
<ide>
<ide> _, err := buildImage(
<ide> name,
<ide> func (s *DockerSuite) TestBuildEmptyWhitespace(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildShCmdJSONEntrypoint(c *check.C) {
<ide> name := "testbuildshcmdjsonentrypoint"
<del> defer deleteImages(name)
<ide>
<ide> _, err := buildImage(
<ide> name,
<ide> func (s *DockerSuite) TestBuildShCmdJSONEntrypoint(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildEnvironmentReplacementUser(c *check.C) {
<ide> name := "testbuildenvironmentreplacement"
<del> defer deleteImages(name)
<ide>
<ide> _, err := buildImage(name, `
<ide> FROM scratch
<ide> func (s *DockerSuite) TestBuildEnvironmentReplacementUser(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildEnvironmentReplacementVolume(c *check.C) {
<ide> name := "testbuildenvironmentreplacement"
<del> defer deleteImages(name)
<ide>
<ide> _, err := buildImage(name, `
<ide> FROM scratch
<ide> func (s *DockerSuite) TestBuildEnvironmentReplacementVolume(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildEnvironmentReplacementExpose(c *check.C) {
<ide> name := "testbuildenvironmentreplacement"
<del> defer deleteImages(name)
<ide>
<ide> _, err := buildImage(name, `
<ide> FROM scratch
<ide> func (s *DockerSuite) TestBuildEnvironmentReplacementExpose(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildEnvironmentReplacementWorkdir(c *check.C) {
<ide> name := "testbuildenvironmentreplacement"
<del> defer deleteImages(name)
<ide>
<ide> _, err := buildImage(name, `
<ide> FROM busybox
<ide> func (s *DockerSuite) TestBuildEnvironmentReplacementWorkdir(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildEnvironmentReplacementAddCopy(c *check.C) {
<ide> name := "testbuildenvironmentreplacement"
<del> defer deleteImages(name)
<ide>
<ide> ctx, err := fakeContext(`
<ide> FROM scratch
<ide> func (s *DockerSuite) TestBuildEnvironmentReplacementAddCopy(c *check.C) {
<ide> func (s *DockerSuite) TestBuildEnvironmentReplacementEnv(c *check.C) {
<ide> name := "testbuildenvironmentreplacement"
<ide>
<del> defer deleteImages(name)
<del>
<ide> _, err := buildImage(name,
<ide> `
<ide> FROM busybox
<ide> func (s *DockerSuite) TestBuildEnvironmentReplacementEnv(c *check.C) {
<ide> func (s *DockerSuite) TestBuildHandleEscapes(c *check.C) {
<ide> name := "testbuildhandleescapes"
<ide>
<del> defer deleteImages(name)
<del>
<ide> _, err := buildImage(name,
<ide> `
<ide> FROM scratch
<ide> func (s *DockerSuite) TestBuildOnBuildLowercase(c *check.C) {
<ide> name := "testbuildonbuildlowercase"
<ide> name2 := "testbuildonbuildlowercase2"
<ide>
<del> defer deleteImages(name, name2)
<del>
<ide> _, err := buildImage(name,
<ide> `
<ide> FROM busybox
<ide> func (s *DockerSuite) TestBuildOnBuildLowercase(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildEnvEscapes(c *check.C) {
<ide> name := "testbuildenvescapes"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name,
<ide> `
<ide> FROM busybox
<ide> func (s *DockerSuite) TestBuildEnvEscapes(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildEnvOverwrite(c *check.C) {
<ide> name := "testbuildenvoverwrite"
<del> defer deleteImages(name)
<ide>
<ide> _, err := buildImage(name,
<ide> `
<ide> func (s *DockerSuite) TestBuildEnvOverwrite(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildOnBuildForbiddenMaintainerInSourceImage(c *check.C) {
<ide> name := "testbuildonbuildforbiddenmaintainerinsourceimage"
<del> defer deleteImages("onbuild")
<del> defer deleteImages(name)
<ide>
<ide> createCmd := exec.Command(dockerBinary, "create", "busybox", "true")
<ide> out, _, _, err := runCommandWithStdoutStderr(createCmd)
<ide> func (s *DockerSuite) TestBuildOnBuildForbiddenMaintainerInSourceImage(c *check.
<ide>
<ide> func (s *DockerSuite) TestBuildOnBuildForbiddenFromInSourceImage(c *check.C) {
<ide> name := "testbuildonbuildforbiddenfrominsourceimage"
<del> defer deleteImages("onbuild")
<del> defer deleteImages(name)
<ide>
<ide> createCmd := exec.Command(dockerBinary, "create", "busybox", "true")
<ide> out, _, _, err := runCommandWithStdoutStderr(createCmd)
<ide> func (s *DockerSuite) TestBuildOnBuildForbiddenFromInSourceImage(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildOnBuildForbiddenChainedInSourceImage(c *check.C) {
<ide> name := "testbuildonbuildforbiddenchainedinsourceimage"
<del> defer deleteImages("onbuild")
<del> defer deleteImages(name)
<ide>
<ide> createCmd := exec.Command(dockerBinary, "create", "busybox", "true")
<ide> out, _, _, err := runCommandWithStdoutStderr(createCmd)
<ide> func (s *DockerSuite) TestBuildOnBuildCmdEntrypointJSON(c *check.C) {
<ide> name1 := "onbuildcmd"
<ide> name2 := "onbuildgenerated"
<ide>
<del> defer deleteImages(name2)
<del> defer deleteImages(name1)
<del>
<ide> _, err := buildImage(name1, `
<ide> FROM busybox
<ide> ONBUILD CMD ["hello world"]
<ide> func (s *DockerSuite) TestBuildOnBuildEntrypointJSON(c *check.C) {
<ide> name1 := "onbuildcmd"
<ide> name2 := "onbuildgenerated"
<ide>
<del> defer deleteImages(name2)
<del> defer deleteImages(name1)
<del>
<ide> _, err := buildImage(name1, `
<ide> FROM busybox
<ide> ONBUILD ENTRYPOINT ["echo"]`,
<ide> ONBUILD ENTRYPOINT ["echo"]`,
<ide>
<ide> func (s *DockerSuite) TestBuildCacheADD(c *check.C) {
<ide> name := "testbuildtwoimageswithadd"
<del> defer deleteImages(name)
<ide> server, err := fakeStorage(map[string]string{
<ide> "robots.txt": "hello",
<ide> "index.html": "world",
<ide> func (s *DockerSuite) TestBuildCacheADD(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildLastModified(c *check.C) {
<ide> name := "testbuildlastmodified"
<del> defer deleteImages(name)
<ide>
<ide> server, err := fakeStorage(map[string]string{
<ide> "file": "hello",
<ide> RUN ls -le /file`
<ide>
<ide> func (s *DockerSuite) TestBuildSixtySteps(c *check.C) {
<ide> name := "foobuildsixtysteps"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext("FROM scratch\n"+strings.Repeat("ADD foo /\n", 60),
<ide> map[string]string{
<ide> "foo": "test1",
<ide> func (s *DockerSuite) TestBuildSixtySteps(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildAddSingleFileToRoot(c *check.C) {
<ide> name := "testaddimg"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(fmt.Sprintf(`FROM busybox
<ide> RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
<ide> RUN echo 'dockerio:x:1001:' >> /etc/group
<ide> RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expecte
<ide> // Issue #3960: "ADD src ." hangs
<ide> func (s *DockerSuite) TestBuildAddSingleFileToWorkdir(c *check.C) {
<ide> name := "testaddsinglefiletoworkdir"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM busybox
<ide> ADD test_file .`,
<ide> map[string]string{
<ide> ADD test_file .`,
<ide>
<ide> func (s *DockerSuite) TestBuildAddSingleFileToExistDir(c *check.C) {
<ide> name := "testaddsinglefiletoexistdir"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM busybox
<ide> RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
<ide> RUN echo 'dockerio:x:1001:' >> /etc/group
<ide> func (s *DockerSuite) TestBuildCopyAddMultipleFiles(c *check.C) {
<ide> defer server.Close()
<ide>
<ide> name := "testcopymultiplefilestofile"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(fmt.Sprintf(`FROM busybox
<ide> RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
<ide> RUN echo 'dockerio:x:1001:' >> /etc/group
<ide> RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio'
<ide>
<ide> func (s *DockerSuite) TestBuildAddMultipleFilesToFile(c *check.C) {
<ide> name := "testaddmultiplefilestofile"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM scratch
<ide> ADD file1.txt file2.txt test
<ide> `,
<ide> func (s *DockerSuite) TestBuildAddMultipleFilesToFile(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildJSONAddMultipleFilesToFile(c *check.C) {
<ide> name := "testjsonaddmultiplefilestofile"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM scratch
<ide> ADD ["file1.txt", "file2.txt", "test"]
<ide> `,
<ide> func (s *DockerSuite) TestBuildJSONAddMultipleFilesToFile(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildAddMultipleFilesToFileWild(c *check.C) {
<ide> name := "testaddmultiplefilestofilewild"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM scratch
<ide> ADD file*.txt test
<ide> `,
<ide> func (s *DockerSuite) TestBuildAddMultipleFilesToFileWild(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildJSONAddMultipleFilesToFileWild(c *check.C) {
<ide> name := "testjsonaddmultiplefilestofilewild"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM scratch
<ide> ADD ["file*.txt", "test"]
<ide> `,
<ide> func (s *DockerSuite) TestBuildJSONAddMultipleFilesToFileWild(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildCopyMultipleFilesToFile(c *check.C) {
<ide> name := "testcopymultiplefilestofile"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM scratch
<ide> COPY file1.txt file2.txt test
<ide> `,
<ide> func (s *DockerSuite) TestBuildCopyMultipleFilesToFile(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildJSONCopyMultipleFilesToFile(c *check.C) {
<ide> name := "testjsoncopymultiplefilestofile"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM scratch
<ide> COPY ["file1.txt", "file2.txt", "test"]
<ide> `,
<ide> func (s *DockerSuite) TestBuildJSONCopyMultipleFilesToFile(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildAddFileWithWhitespace(c *check.C) {
<ide> name := "testaddfilewithwhitespace"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM busybox
<ide> RUN mkdir "/test dir"
<ide> RUN mkdir "/test_dir"
<ide> RUN [ $(cat "/test dir/test_file6") = 'test6' ]`,
<ide>
<ide> func (s *DockerSuite) TestBuildCopyFileWithWhitespace(c *check.C) {
<ide> name := "testcopyfilewithwhitespace"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM busybox
<ide> RUN mkdir "/test dir"
<ide> RUN mkdir "/test_dir"
<ide> RUN [ $(cat "/test dir/test_file6") = 'test6' ]`,
<ide>
<ide> func (s *DockerSuite) TestBuildAddMultipleFilesToFileWithWhitespace(c *check.C) {
<ide> name := "testaddmultiplefilestofilewithwhitespace"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM busybox
<ide> ADD [ "test file1", "test file2", "test" ]
<ide> `,
<ide> func (s *DockerSuite) TestBuildAddMultipleFilesToFileWithWhitespace(c *check.C)
<ide>
<ide> func (s *DockerSuite) TestBuildCopyMultipleFilesToFileWithWhitespace(c *check.C) {
<ide> name := "testcopymultiplefilestofilewithwhitespace"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM busybox
<ide> COPY [ "test file1", "test file2", "test" ]
<ide> `,
<ide> func (s *DockerSuite) TestBuildCopyMultipleFilesToFileWithWhitespace(c *check.C)
<ide>
<ide> func (s *DockerSuite) TestBuildCopyWildcard(c *check.C) {
<ide> name := "testcopywildcard"
<del> defer deleteImages(name)
<ide> server, err := fakeStorage(map[string]string{
<ide> "robots.txt": "hello",
<ide> "index.html": "world",
<ide> func (s *DockerSuite) TestBuildCopyWildcard(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildCopyWildcardNoFind(c *check.C) {
<ide> name := "testcopywildcardnofind"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM busybox
<ide> COPY file*.txt /tmp/
<ide> `, nil)
<ide> func (s *DockerSuite) TestBuildCopyWildcardNoFind(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildCopyWildcardCache(c *check.C) {
<ide> name := "testcopywildcardcache"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM busybox
<ide> COPY file1.txt /tmp/`,
<ide> map[string]string{
<ide> func (s *DockerSuite) TestBuildCopyWildcardCache(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildAddSingleFileToNonExistingDir(c *check.C) {
<ide> name := "testaddsinglefiletononexistingdir"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM busybox
<ide> RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
<ide> RUN echo 'dockerio:x:1001:' >> /etc/group
<ide> RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
<ide>
<ide> func (s *DockerSuite) TestBuildAddDirContentToRoot(c *check.C) {
<ide> name := "testadddircontenttoroot"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM busybox
<ide> RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
<ide> RUN echo 'dockerio:x:1001:' >> /etc/group
<ide> RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
<ide>
<ide> func (s *DockerSuite) TestBuildAddDirContentToExistingDir(c *check.C) {
<ide> name := "testadddircontenttoexistingdir"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM busybox
<ide> RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
<ide> RUN echo 'dockerio:x:1001:' >> /etc/group
<ide> RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]`,
<ide>
<ide> func (s *DockerSuite) TestBuildAddWholeDirToRoot(c *check.C) {
<ide> name := "testaddwholedirtoroot"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(fmt.Sprintf(`FROM busybox
<ide> RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
<ide> RUN echo 'dockerio:x:1001:' >> /etc/group
<ide> RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expecte
<ide> // Testing #5941
<ide> func (s *DockerSuite) TestBuildAddEtcToRoot(c *check.C) {
<ide> name := "testaddetctoroot"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM scratch
<ide> ADD . /`,
<ide> map[string]string{
<ide> ADD . /`,
<ide> // Testing #9401
<ide> func (s *DockerSuite) TestBuildAddPreservesFilesSpecialBits(c *check.C) {
<ide> name := "testaddpreservesfilesspecialbits"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM busybox
<ide> ADD suidbin /usr/bin/suidbin
<ide> RUN chmod 4755 /usr/bin/suidbin
<ide> RUN [ $(ls -l /usr/bin/suidbin | awk '{print $1}') = '-rwsr-xr-x' ]`,
<ide>
<ide> func (s *DockerSuite) TestBuildCopySingleFileToRoot(c *check.C) {
<ide> name := "testcopysinglefiletoroot"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(fmt.Sprintf(`FROM busybox
<ide> RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
<ide> RUN echo 'dockerio:x:1001:' >> /etc/group
<ide> RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expecte
<ide> // Issue #3960: "ADD src ." hangs - adapted for COPY
<ide> func (s *DockerSuite) TestBuildCopySingleFileToWorkdir(c *check.C) {
<ide> name := "testcopysinglefiletoworkdir"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM busybox
<ide> COPY test_file .`,
<ide> map[string]string{
<ide> COPY test_file .`,
<ide>
<ide> func (s *DockerSuite) TestBuildCopySingleFileToExistDir(c *check.C) {
<ide> name := "testcopysinglefiletoexistdir"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM busybox
<ide> RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
<ide> RUN echo 'dockerio:x:1001:' >> /etc/group
<ide> RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio'
<ide>
<ide> func (s *DockerSuite) TestBuildCopySingleFileToNonExistDir(c *check.C) {
<ide> name := "testcopysinglefiletononexistdir"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM busybox
<ide> RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
<ide> RUN echo 'dockerio:x:1001:' >> /etc/group
<ide> RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
<ide>
<ide> func (s *DockerSuite) TestBuildCopyDirContentToRoot(c *check.C) {
<ide> name := "testcopydircontenttoroot"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM busybox
<ide> RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
<ide> RUN echo 'dockerio:x:1001:' >> /etc/group
<ide> RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
<ide>
<ide> func (s *DockerSuite) TestBuildCopyDirContentToExistDir(c *check.C) {
<ide> name := "testcopydircontenttoexistdir"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM busybox
<ide> RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
<ide> RUN echo 'dockerio:x:1001:' >> /etc/group
<ide> RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]`,
<ide>
<ide> func (s *DockerSuite) TestBuildCopyWholeDirToRoot(c *check.C) {
<ide> name := "testcopywholedirtoroot"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(fmt.Sprintf(`FROM busybox
<ide> RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
<ide> RUN echo 'dockerio:x:1001:' >> /etc/group
<ide> RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expecte
<ide>
<ide> func (s *DockerSuite) TestBuildCopyEtcToRoot(c *check.C) {
<ide> name := "testcopyetctoroot"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM scratch
<ide> COPY . /`,
<ide> map[string]string{
<ide> COPY . /`,
<ide>
<ide> func (s *DockerSuite) TestBuildCopyDisallowRemote(c *check.C) {
<ide> name := "testcopydisallowremote"
<del> defer deleteImages(name)
<ide> _, out, err := buildImageWithOut(name, `FROM scratch
<ide> COPY https://index.docker.io/robots.txt /`,
<ide> true)
<ide> func (s *DockerSuite) TestBuildAddBadLinks(c *check.C) {
<ide> var (
<ide> name = "test-link-absolute"
<ide> )
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(dockerfile, nil)
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> func (s *DockerSuite) TestBuildAddBadLinksVolume(c *check.C) {
<ide> name = "test-link-absolute-volume"
<ide> dockerfile = ""
<ide> )
<del> defer deleteImages(name)
<ide>
<ide> tempDir, err := ioutil.TempDir("", "test-link-absolute-volume-temp-")
<ide> if err != nil {
<ide> func (s *DockerSuite) TestBuildWithInaccessibleFilesInContext(c *check.C) {
<ide>
<ide> {
<ide> name := "testbuildinaccessiblefiles"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext("FROM scratch\nADD . /foo/", map[string]string{"fileWithoutReadAccess": "foo"})
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> func (s *DockerSuite) TestBuildWithInaccessibleFilesInContext(c *check.C) {
<ide> }
<ide> {
<ide> name := "testbuildinaccessibledirectory"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext("FROM scratch\nADD . /foo/", map[string]string{"directoryWeCantStat/bar": "foo"})
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> func (s *DockerSuite) TestBuildWithInaccessibleFilesInContext(c *check.C) {
<ide> }
<ide> {
<ide> name := "testlinksok"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext("FROM scratch\nADD . /foo/", nil)
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> func (s *DockerSuite) TestBuildWithInaccessibleFilesInContext(c *check.C) {
<ide> }
<ide> {
<ide> name := "testbuildignoredinaccessible"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext("FROM scratch\nADD . /foo/",
<ide> map[string]string{
<ide> "directoryWeCantStat/bar": "foo",
<ide> func (s *DockerSuite) TestBuildForceRm(c *check.C) {
<ide> c.Fatalf("failed to get the container count: %s", err)
<ide> }
<ide> name := "testbuildforcerm"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext("FROM scratch\nRUN true\nRUN thiswillfail", nil)
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> func (s *DockerSuite) TestBuildCancelationKillsSleep(c *check.C) {
<ide> defer wg.Wait()
<ide>
<ide> name := "testbuildcancelation"
<del> defer deleteImages(name)
<ide>
<ide> // (Note: one year, will never finish)
<ide> ctx, err := fakeContext("FROM busybox\nRUN sleep 31536000", nil)
<ide> func (s *DockerSuite) TestBuildCancelationKillsSleep(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildRm(c *check.C) {
<ide> name := "testbuildrm"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext("FROM scratch\nADD foo /\nADD foo /", map[string]string{"foo": "bar"})
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> func (s *DockerSuite) TestBuildWithVolumes(c *check.C) {
<ide> "/test8]": emptyMap,
<ide> }
<ide> )
<del> defer deleteImages(name)
<ide> _, err := buildImage(name,
<ide> `FROM scratch
<ide> VOLUME /test1
<ide> func (s *DockerSuite) TestBuildWithVolumes(c *check.C) {
<ide> func (s *DockerSuite) TestBuildMaintainer(c *check.C) {
<ide> name := "testbuildmaintainer"
<ide> expected := "dockerio"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name,
<ide> `FROM scratch
<ide> MAINTAINER dockerio`,
<ide> func (s *DockerSuite) TestBuildMaintainer(c *check.C) {
<ide> func (s *DockerSuite) TestBuildUser(c *check.C) {
<ide> name := "testbuilduser"
<ide> expected := "dockerio"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name,
<ide> `FROM busybox
<ide> RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
<ide> func (s *DockerSuite) TestBuildUser(c *check.C) {
<ide> func (s *DockerSuite) TestBuildRelativeWorkdir(c *check.C) {
<ide> name := "testbuildrelativeworkdir"
<ide> expected := "/test2/test3"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name,
<ide> `FROM busybox
<ide> RUN [ "$PWD" = '/' ]
<ide> func (s *DockerSuite) TestBuildRelativeWorkdir(c *check.C) {
<ide> func (s *DockerSuite) TestBuildWorkdirWithEnvVariables(c *check.C) {
<ide> name := "testbuildworkdirwithenvvariables"
<ide> expected := "/test1/test2"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name,
<ide> `FROM busybox
<ide> ENV DIRPATH /test1
<ide> func (s *DockerSuite) TestBuildWorkdirWithEnvVariables(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildRelativeCopy(c *check.C) {
<ide> name := "testbuildrelativecopy"
<del> defer deleteImages(name)
<ide> dockerfile := `
<ide> FROM busybox
<ide> WORKDIR /test1
<ide> func (s *DockerSuite) TestBuildRelativeCopy(c *check.C) {
<ide> func (s *DockerSuite) TestBuildEnv(c *check.C) {
<ide> name := "testbuildenv"
<ide> expected := "[PATH=/test:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin PORT=2375]"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name,
<ide> `FROM busybox
<ide> ENV PATH /test:$PATH
<ide> func (s *DockerSuite) TestBuildContextCleanup(c *check.C) {
<ide> testRequires(c, SameHostDaemon)
<ide>
<ide> name := "testbuildcontextcleanup"
<del> defer deleteImages(name)
<ide> entries, err := ioutil.ReadDir("/var/lib/docker/tmp")
<ide> if err != nil {
<ide> c.Fatalf("failed to list contents of tmp dir: %s", err)
<ide> func (s *DockerSuite) TestBuildContextCleanupFailedBuild(c *check.C) {
<ide> testRequires(c, SameHostDaemon)
<ide>
<ide> name := "testbuildcontextcleanup"
<del> defer deleteImages(name)
<ide> entries, err := ioutil.ReadDir("/var/lib/docker/tmp")
<ide> if err != nil {
<ide> c.Fatalf("failed to list contents of tmp dir: %s", err)
<ide> func (s *DockerSuite) TestBuildContextCleanupFailedBuild(c *check.C) {
<ide> func (s *DockerSuite) TestBuildCmd(c *check.C) {
<ide> name := "testbuildcmd"
<ide> expected := "{[/bin/echo Hello World]}"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name,
<ide> `FROM scratch
<ide> CMD ["/bin/echo", "Hello World"]`,
<ide> func (s *DockerSuite) TestBuildCmd(c *check.C) {
<ide> func (s *DockerSuite) TestBuildExpose(c *check.C) {
<ide> name := "testbuildexpose"
<ide> expected := "map[2375/tcp:{}]"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name,
<ide> `FROM scratch
<ide> EXPOSE 2375`,
<ide> func (s *DockerSuite) TestBuildExposeMorePorts(c *check.C) {
<ide> tmpl.Execute(buf, portList)
<ide>
<ide> name := "testbuildexpose"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name, buf.String(), true)
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> func (s *DockerSuite) TestBuildExposeOrder(c *check.C) {
<ide>
<ide> id1 := buildID("testbuildexpose1", "80 2375")
<ide> id2 := buildID("testbuildexpose2", "2375 80")
<del> defer deleteImages("testbuildexpose1", "testbuildexpose2")
<ide> if id1 != id2 {
<ide> c.Errorf("EXPOSE should invalidate the cache only when ports actually changed")
<ide> }
<ide> func (s *DockerSuite) TestBuildExposeOrder(c *check.C) {
<ide> func (s *DockerSuite) TestBuildExposeUpperCaseProto(c *check.C) {
<ide> name := "testbuildexposeuppercaseproto"
<ide> expected := "map[5678/udp:{}]"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name,
<ide> `FROM scratch
<ide> EXPOSE 5678/UDP`,
<ide> func (s *DockerSuite) TestBuildExposeHostPort(c *check.C) {
<ide> // start building docker file with ip:hostPort:containerPort
<ide> name := "testbuildexpose"
<ide> expected := "map[5678/tcp:{}]"
<del> defer deleteImages(name)
<ide> _, out, err := buildImageWithOut(name,
<ide> `FROM scratch
<ide> EXPOSE 192.168.1.2:2375:5678`,
<ide> func (s *DockerSuite) TestBuildExposeHostPort(c *check.C) {
<ide> func (s *DockerSuite) TestBuildEmptyEntrypointInheritance(c *check.C) {
<ide> name := "testbuildentrypointinheritance"
<ide> name2 := "testbuildentrypointinheritance2"
<del> defer deleteImages(name, name2)
<ide>
<ide> _, err := buildImage(name,
<ide> `FROM busybox
<ide> func (s *DockerSuite) TestBuildEmptyEntrypointInheritance(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildEmptyEntrypoint(c *check.C) {
<ide> name := "testbuildentrypoint"
<del> defer deleteImages(name)
<ide> expected := "{[]}"
<ide>
<ide> _, err := buildImage(name,
<ide> func (s *DockerSuite) TestBuildEmptyEntrypoint(c *check.C) {
<ide> func (s *DockerSuite) TestBuildEntrypoint(c *check.C) {
<ide> name := "testbuildentrypoint"
<ide> expected := "{[/bin/echo]}"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name,
<ide> `FROM scratch
<ide> ENTRYPOINT ["/bin/echo"]`,
<ide> func (s *DockerSuite) TestBuildOnBuildLimitedInheritence(c *check.C) {
<ide> if err != nil {
<ide> c.Fatalf("build failed to complete: %s, %v", out1, err)
<ide> }
<del> defer deleteImages(name1)
<ide> }
<ide> {
<ide> name2 := "testonbuildtrigger2"
<ide> func (s *DockerSuite) TestBuildOnBuildLimitedInheritence(c *check.C) {
<ide> if err != nil {
<ide> c.Fatalf("build failed to complete: %s, %v", out2, err)
<ide> }
<del> defer deleteImages(name2)
<ide> }
<ide> {
<ide> name3 := "testonbuildtrigger3"
<ide> func (s *DockerSuite) TestBuildOnBuildLimitedInheritence(c *check.C) {
<ide> c.Fatalf("build failed to complete: %s, %v", out3, err)
<ide> }
<ide>
<del> defer deleteImages(name3)
<ide> }
<ide>
<ide> // ONBUILD should be run in second build.
<ide> func (s *DockerSuite) TestBuildOnBuildLimitedInheritence(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildWithCache(c *check.C) {
<ide> name := "testbuildwithcache"
<del> defer deleteImages(name)
<ide> id1, err := buildImage(name,
<ide> `FROM scratch
<ide> MAINTAINER dockerio
<ide> func (s *DockerSuite) TestBuildWithCache(c *check.C) {
<ide> func (s *DockerSuite) TestBuildWithoutCache(c *check.C) {
<ide> name := "testbuildwithoutcache"
<ide> name2 := "testbuildwithoutcache2"
<del> defer deleteImages(name, name2)
<ide> id1, err := buildImage(name,
<ide> `FROM scratch
<ide> MAINTAINER dockerio
<ide> func (s *DockerSuite) TestBuildWithoutCache(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildConditionalCache(c *check.C) {
<ide> name := "testbuildconditionalcache"
<del> name2 := "testbuildconditionalcache2"
<del> defer deleteImages(name, name2)
<ide>
<ide> dockerfile := `
<ide> FROM busybox
<ide> func (s *DockerSuite) TestBuildConditionalCache(c *check.C) {
<ide> if id3 != id2 {
<ide> c.Fatal("Should have used the cache")
<ide> }
<del>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildADDLocalFileWithCache(c *check.C) {
<ide> name := "testbuildaddlocalfilewithcache"
<ide> name2 := "testbuildaddlocalfilewithcache2"
<del> defer deleteImages(name, name2)
<ide> dockerfile := `
<ide> FROM busybox
<ide> MAINTAINER dockerio
<ide> func (s *DockerSuite) TestBuildADDLocalFileWithCache(c *check.C) {
<ide> func (s *DockerSuite) TestBuildADDMultipleLocalFileWithCache(c *check.C) {
<ide> name := "testbuildaddmultiplelocalfilewithcache"
<ide> name2 := "testbuildaddmultiplelocalfilewithcache2"
<del> defer deleteImages(name, name2)
<ide> dockerfile := `
<ide> FROM busybox
<ide> MAINTAINER dockerio
<ide> func (s *DockerSuite) TestBuildADDMultipleLocalFileWithCache(c *check.C) {
<ide> func (s *DockerSuite) TestBuildADDLocalFileWithoutCache(c *check.C) {
<ide> name := "testbuildaddlocalfilewithoutcache"
<ide> name2 := "testbuildaddlocalfilewithoutcache2"
<del> defer deleteImages(name, name2)
<ide> dockerfile := `
<ide> FROM busybox
<ide> MAINTAINER dockerio
<ide> func (s *DockerSuite) TestBuildADDLocalFileWithoutCache(c *check.C) {
<ide> func (s *DockerSuite) TestBuildCopyDirButNotFile(c *check.C) {
<ide> name := "testbuildcopydirbutnotfile"
<ide> name2 := "testbuildcopydirbutnotfile2"
<del> defer deleteImages(name, name2)
<ide> dockerfile := `
<ide> FROM scratch
<ide> COPY dir /tmp/`
<ide> func (s *DockerSuite) TestBuildADDCurrentDirWithCache(c *check.C) {
<ide> name3 := name + "3"
<ide> name4 := name + "4"
<ide> name5 := name + "5"
<del> defer deleteImages(name, name2, name3, name4, name5)
<ide> dockerfile := `
<ide> FROM scratch
<ide> MAINTAINER dockerio
<ide> func (s *DockerSuite) TestBuildADDCurrentDirWithCache(c *check.C) {
<ide> func (s *DockerSuite) TestBuildADDCurrentDirWithoutCache(c *check.C) {
<ide> name := "testbuildaddcurrentdirwithoutcache"
<ide> name2 := "testbuildaddcurrentdirwithoutcache2"
<del> defer deleteImages(name, name2)
<ide> dockerfile := `
<ide> FROM scratch
<ide> MAINTAINER dockerio
<ide> func (s *DockerSuite) TestBuildADDCurrentDirWithoutCache(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildADDRemoteFileWithCache(c *check.C) {
<ide> name := "testbuildaddremotefilewithcache"
<del> defer deleteImages(name)
<ide> server, err := fakeStorage(map[string]string{
<ide> "baz": "hello",
<ide> })
<ide> func (s *DockerSuite) TestBuildADDRemoteFileWithCache(c *check.C) {
<ide> func (s *DockerSuite) TestBuildADDRemoteFileWithoutCache(c *check.C) {
<ide> name := "testbuildaddremotefilewithoutcache"
<ide> name2 := "testbuildaddremotefilewithoutcache2"
<del> defer deleteImages(name, name2)
<ide> server, err := fakeStorage(map[string]string{
<ide> "baz": "hello",
<ide> })
<ide> func (s *DockerSuite) TestBuildADDRemoteFileMTime(c *check.C) {
<ide> name3 := name + "3"
<ide> name4 := name + "4"
<ide>
<del> defer deleteImages(name, name2, name3, name4)
<del>
<ide> files := map[string]string{"baz": "hello"}
<ide> server, err := fakeStorage(files)
<ide> if err != nil {
<ide> func (s *DockerSuite) TestBuildADDRemoteFileMTime(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildADDLocalAndRemoteFilesWithCache(c *check.C) {
<ide> name := "testbuildaddlocalandremotefilewithcache"
<del> defer deleteImages(name)
<ide> server, err := fakeStorage(map[string]string{
<ide> "baz": "hello",
<ide> })
<ide> CMD ["cat", "/foo"]`,
<ide> }
<ide> name := "contexttar"
<ide> buildCmd := exec.Command(dockerBinary, "build", "-t", name, "-")
<del> defer deleteImages(name)
<ide> buildCmd.Stdin = context
<ide>
<ide> if out, _, err := runCommandWithOutput(buildCmd); err != nil {
<ide> func (s *DockerSuite) TestBuildNoContext(c *check.C) {
<ide> if out, _ := dockerCmd(c, "run", "--rm", "nocontext"); out != "ok\n" {
<ide> c.Fatalf("run produced invalid output: %q, expected %q", out, "ok")
<ide> }
<del>
<del> deleteImages("nocontext")
<ide> }
<ide>
<ide> // TODO: TestCaching
<ide> func (s *DockerSuite) TestBuildADDLocalAndRemoteFilesWithoutCache(c *check.C) {
<ide> name := "testbuildaddlocalandremotefilewithoutcache"
<ide> name2 := "testbuildaddlocalandremotefilewithoutcache2"
<del> defer deleteImages(name, name2)
<ide> server, err := fakeStorage(map[string]string{
<ide> "baz": "hello",
<ide> })
<ide> func (s *DockerSuite) TestBuildADDLocalAndRemoteFilesWithoutCache(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildWithVolumeOwnership(c *check.C) {
<ide> name := "testbuildimg"
<del> defer deleteImages(name)
<ide>
<ide> _, err := buildImage(name,
<ide> `FROM busybox:latest
<ide> func (s *DockerSuite) TestBuildWithVolumeOwnership(c *check.C) {
<ide> // utilizing cache
<ide> func (s *DockerSuite) TestBuildEntrypointRunCleanup(c *check.C) {
<ide> name := "testbuildcmdcleanup"
<del> defer deleteImages(name)
<ide> if _, err := buildImage(name,
<ide> `FROM busybox
<ide> RUN echo "hello"`,
<ide> func (s *DockerSuite) TestBuildEntrypointRunCleanup(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildForbiddenContextPath(c *check.C) {
<ide> name := "testbuildforbidpath"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM scratch
<ide> ADD ../../ test/
<ide> `,
<ide> func (s *DockerSuite) TestBuildForbiddenContextPath(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildADDFileNotFound(c *check.C) {
<ide> name := "testbuildaddnotfound"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM scratch
<ide> ADD foo /usr/local/bar`,
<ide> map[string]string{"bar": "hello"})
<ide> func (s *DockerSuite) TestBuildADDFileNotFound(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildInheritance(c *check.C) {
<ide> name := "testbuildinheritance"
<del> defer deleteImages(name)
<ide>
<ide> _, err := buildImage(name,
<ide> `FROM scratch
<ide> func (s *DockerSuite) TestBuildInheritance(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildFails(c *check.C) {
<ide> name := "testbuildfails"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name,
<ide> `FROM busybox
<ide> RUN sh -c "exit 23"`,
<ide> func (s *DockerSuite) TestBuildFails(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildFailsDockerfileEmpty(c *check.C) {
<ide> name := "testbuildfails"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name, ``, true)
<ide> if err != nil {
<ide> if !strings.Contains(err.Error(), "The Dockerfile (Dockerfile) cannot be empty") {
<ide> func (s *DockerSuite) TestBuildFailsDockerfileEmpty(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildOnBuild(c *check.C) {
<ide> name := "testbuildonbuild"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name,
<ide> `FROM busybox
<ide> ONBUILD RUN touch foobar`,
<ide> func (s *DockerSuite) TestBuildOnBuild(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildOnBuildForbiddenChained(c *check.C) {
<ide> name := "testbuildonbuildforbiddenchained"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name,
<ide> `FROM busybox
<ide> ONBUILD ONBUILD RUN touch foobar`,
<ide> func (s *DockerSuite) TestBuildOnBuildForbiddenChained(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildOnBuildForbiddenFrom(c *check.C) {
<ide> name := "testbuildonbuildforbiddenfrom"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name,
<ide> `FROM busybox
<ide> ONBUILD FROM scratch`,
<ide> func (s *DockerSuite) TestBuildOnBuildForbiddenFrom(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildOnBuildForbiddenMaintainer(c *check.C) {
<ide> name := "testbuildonbuildforbiddenmaintainer"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name,
<ide> `FROM busybox
<ide> ONBUILD MAINTAINER docker.io`,
<ide> func (s *DockerSuite) TestBuildOnBuildForbiddenMaintainer(c *check.C) {
<ide> // gh #2446
<ide> func (s *DockerSuite) TestBuildAddToSymlinkDest(c *check.C) {
<ide> name := "testbuildaddtosymlinkdest"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`FROM busybox
<ide> RUN mkdir /foo
<ide> RUN ln -s /foo /bar
<ide> func (s *DockerSuite) TestBuildAddToSymlinkDest(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildEscapeWhitespace(c *check.C) {
<ide> name := "testbuildescaping"
<del> defer deleteImages(name)
<ide>
<ide> _, err := buildImage(name, `
<ide> FROM busybox
<ide> docker.com>"
<ide> func (s *DockerSuite) TestBuildVerifyIntString(c *check.C) {
<ide> // Verify that strings that look like ints are still passed as strings
<ide> name := "testbuildstringing"
<del> defer deleteImages(name)
<ide>
<ide> _, err := buildImage(name, `
<ide> FROM busybox
<ide> func (s *DockerSuite) TestBuildVerifyIntString(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildDockerignore(c *check.C) {
<ide> name := "testbuilddockerignore"
<del> defer deleteImages(name)
<ide> dockerfile := `
<ide> FROM busybox
<ide> ADD . /bla
<ide> func (s *DockerSuite) TestBuildDockerignore(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildDockerignoreCleanPaths(c *check.C) {
<ide> name := "testbuilddockerignorecleanpaths"
<del> defer deleteImages(name)
<ide> dockerfile := `
<ide> FROM busybox
<ide> ADD . /tmp/
<ide> func (s *DockerSuite) TestBuildDockerignoreCleanPaths(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildDockerignoringDockerfile(c *check.C) {
<ide> name := "testbuilddockerignoredockerfile"
<del> defer deleteImages(name)
<ide> dockerfile := `
<ide> FROM busybox
<ide> ADD . /tmp/
<ide> func (s *DockerSuite) TestBuildDockerignoringDockerfile(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildDockerignoringRenamedDockerfile(c *check.C) {
<ide> name := "testbuilddockerignoredockerfile"
<del> defer deleteImages(name)
<ide> dockerfile := `
<ide> FROM busybox
<ide> ADD . /tmp/
<ide> func (s *DockerSuite) TestBuildDockerignoringRenamedDockerfile(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildDockerignoringDockerignore(c *check.C) {
<ide> name := "testbuilddockerignoredockerignore"
<del> defer deleteImages(name)
<ide> dockerfile := `
<ide> FROM busybox
<ide> ADD . /tmp/
<ide> func (s *DockerSuite) TestBuildDockerignoreTouchDockerfile(c *check.C) {
<ide> var id2 string
<ide>
<ide> name := "testbuilddockerignoretouchdockerfile"
<del> defer deleteImages(name)
<ide> dockerfile := `
<ide> FROM busybox
<ide> ADD . /tmp/`
<ide> func (s *DockerSuite) TestBuildDockerignoreTouchDockerfile(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildDockerignoringWholeDir(c *check.C) {
<ide> name := "testbuilddockerignorewholedir"
<del> defer deleteImages(name)
<ide> dockerfile := `
<ide> FROM busybox
<ide> COPY . /
<ide> func (s *DockerSuite) TestBuildDockerignoringWholeDir(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildLineBreak(c *check.C) {
<ide> name := "testbuildlinebreak"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name,
<ide> `FROM busybox
<ide> RUN sh -c 'echo root:testpass \
<ide> RUN [ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]`,
<ide>
<ide> func (s *DockerSuite) TestBuildEOLInLine(c *check.C) {
<ide> name := "testbuildeolinline"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name,
<ide> `FROM busybox
<ide> RUN sh -c 'echo root:testpass > /tmp/passwd'
<ide> RUN [ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]`,
<ide>
<ide> func (s *DockerSuite) TestBuildCommentsShebangs(c *check.C) {
<ide> name := "testbuildcomments"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name,
<ide> `FROM busybox
<ide> # This is an ordinary comment.
<ide> RUN [ "$(/hello.sh)" = "hello world" ]`,
<ide>
<ide> func (s *DockerSuite) TestBuildUsersAndGroups(c *check.C) {
<ide> name := "testbuildusers"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name,
<ide> `FROM busybox
<ide>
<ide> RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1042:1043/10
<ide>
<ide> func (s *DockerSuite) TestBuildEnvUsage(c *check.C) {
<ide> name := "testbuildenvusage"
<del> defer deleteImages(name)
<ide> dockerfile := `FROM busybox
<ide> ENV HOME /root
<ide> ENV PATH $HOME/bin:$PATH
<ide> RUN [ "$ghi" = "def" ]
<ide>
<ide> func (s *DockerSuite) TestBuildEnvUsage2(c *check.C) {
<ide> name := "testbuildenvusage2"
<del> defer deleteImages(name)
<ide> dockerfile := `FROM busybox
<ide> ENV abc=def
<ide> RUN [ "$abc" = "def" ]
<ide> RUN [ "$eee1,$eee2,$eee3,$eee4" = 'foo,foo,foo,foo' ]
<ide>
<ide> func (s *DockerSuite) TestBuildAddScript(c *check.C) {
<ide> name := "testbuildaddscript"
<del> defer deleteImages(name)
<ide> dockerfile := `
<ide> FROM busybox
<ide> ADD test /test
<ide> RUN [ "$(cat /testfile)" = 'test!' ]`
<ide>
<ide> func (s *DockerSuite) TestBuildAddTar(c *check.C) {
<ide> name := "testbuildaddtar"
<del> defer deleteImages(name)
<ide>
<ide> ctx := func() *FakeContext {
<ide> dockerfile := `
<ide> RUN cat /existing-directory-trailing-slash/test/foo | grep Hi`
<ide>
<ide> func (s *DockerSuite) TestBuildAddTarXz(c *check.C) {
<ide> name := "testbuildaddtarxz"
<del> defer deleteImages(name)
<ide>
<ide> ctx := func() *FakeContext {
<ide> dockerfile := `
<ide> func (s *DockerSuite) TestBuildAddTarXz(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildAddTarXzGz(c *check.C) {
<ide> name := "testbuildaddtarxzgz"
<del> defer deleteImages(name)
<ide>
<ide> ctx := func() *FakeContext {
<ide> dockerfile := `
<ide> func (s *DockerSuite) TestBuildAddTarXzGz(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildFromGIT(c *check.C) {
<ide> name := "testbuildfromgit"
<del> defer deleteImages(name)
<ide> git, err := fakeGIT("repo", map[string]string{
<ide> "Dockerfile": `FROM busybox
<ide> ADD first /first
<ide> func (s *DockerSuite) TestBuildFromGIT(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildCleanupCmdOnEntrypoint(c *check.C) {
<ide> name := "testbuildcmdcleanuponentrypoint"
<del> defer deleteImages(name)
<ide> if _, err := buildImage(name,
<ide> `FROM scratch
<ide> CMD ["test"]
<ide> func (s *DockerSuite) TestBuildCleanupCmdOnEntrypoint(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildClearCmd(c *check.C) {
<ide> name := "testbuildclearcmd"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name,
<ide> `From scratch
<ide> ENTRYPOINT ["/bin/bash"]
<ide> func (s *DockerSuite) TestBuildClearCmd(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildEmptyCmd(c *check.C) {
<ide> name := "testbuildemptycmd"
<del> defer deleteImages(name)
<ide> if _, err := buildImage(name, "FROM scratch\nMAINTAINER quux\n", true); err != nil {
<ide> c.Fatal(err)
<ide> }
<ide> func (s *DockerSuite) TestBuildEmptyCmd(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildOnBuildOutput(c *check.C) {
<ide> name := "testbuildonbuildparent"
<del> defer deleteImages(name)
<ide> if _, err := buildImage(name, "FROM busybox\nONBUILD RUN echo foo\n", true); err != nil {
<ide> c.Fatal(err)
<ide> }
<ide>
<del> childname := "testbuildonbuildchild"
<del> defer deleteImages(childname)
<del>
<ide> _, out, err := buildImageWithOut(name, "FROM "+name+"\nMAINTAINER quux\n", true)
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> func (s *DockerSuite) TestBuildOnBuildOutput(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildInvalidTag(c *check.C) {
<ide> name := "abcd:" + stringutils.GenerateRandomAlphaOnlyString(200)
<del> defer deleteImages(name)
<ide> _, out, err := buildImageWithOut(name, "FROM scratch\nMAINTAINER quux\n", true)
<ide> // if the error doesnt check for illegal tag name, or the image is built
<ide> // then this should fail
<ide> func (s *DockerSuite) TestBuildInvalidTag(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildCmdShDashC(c *check.C) {
<ide> name := "testbuildcmdshc"
<del> defer deleteImages(name)
<ide> if _, err := buildImage(name, "FROM busybox\nCMD echo cmd\n", true); err != nil {
<ide> c.Fatal(err)
<ide> }
<ide> func (s *DockerSuite) TestBuildCmdSpaces(c *check.C) {
<ide> // the arg separator to make sure ["echo","hi"] and ["echo hi"] don't
<ide> // look the same
<ide> name := "testbuildcmdspaces"
<del> defer deleteImages(name)
<ide> var id1 string
<ide> var id2 string
<ide> var err error
<ide> func (s *DockerSuite) TestBuildCmdSpaces(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildCmdJSONNoShDashC(c *check.C) {
<ide> name := "testbuildcmdjson"
<del> defer deleteImages(name)
<ide> if _, err := buildImage(name, "FROM busybox\nCMD [\"echo\", \"cmd\"]", true); err != nil {
<ide> c.Fatal(err)
<ide> }
<ide> func (s *DockerSuite) TestBuildCmdJSONNoShDashC(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildErrorInvalidInstruction(c *check.C) {
<ide> name := "testbuildignoreinvalidinstruction"
<del> defer deleteImages(name)
<ide>
<ide> out, _, err := buildImageWithOut(name, "FROM busybox\nfoo bar", true)
<ide> if err == nil {
<ide> func (s *DockerSuite) TestBuildErrorInvalidInstruction(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildEntrypointInheritance(c *check.C) {
<del> defer deleteImages("parent", "child")
<ide>
<ide> if _, err := buildImage("parent", `
<ide> FROM busybox
<ide> func (s *DockerSuite) TestBuildEntrypointInheritanceInspect(c *check.C) {
<ide> expected = `["/bin/sh","-c","echo quux"]`
<ide> )
<ide>
<del> defer deleteImages(name, name2)
<del>
<ide> if _, err := buildImage(name, "FROM busybox\nENTRYPOINT /foo/bar", true); err != nil {
<ide> c.Fatal(err)
<ide> }
<ide> func (s *DockerSuite) TestBuildEntrypointInheritanceInspect(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildRunShEntrypoint(c *check.C) {
<ide> name := "testbuildentrypoint"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name,
<ide> `FROM busybox
<ide> ENTRYPOINT /bin/echo`,
<ide> func (s *DockerSuite) TestBuildRunShEntrypoint(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildExoticShellInterpolation(c *check.C) {
<ide> name := "testbuildexoticshellinterpolation"
<del> defer deleteImages(name)
<ide>
<ide> _, err := buildImage(name, `
<ide> FROM busybox
<ide> func (s *DockerSuite) TestBuildVerifySingleQuoteFails(c *check.C) {
<ide> // as a "string" insead of "JSON array" and pass it on to "sh -c" and
<ide> // it should barf on it.
<ide> name := "testbuildsinglequotefails"
<del> defer deleteImages(name)
<ide>
<ide> _, err := buildImage(name,
<ide> `FROM busybox
<ide> func (s *DockerSuite) TestBuildVerifySingleQuoteFails(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildVerboseOut(c *check.C) {
<ide> name := "testbuildverboseout"
<del> defer deleteImages(name)
<ide>
<ide> _, out, err := buildImageWithOut(name,
<ide> `FROM busybox
<ide> RUN echo 123`,
<ide>
<ide> func (s *DockerSuite) TestBuildWithTabs(c *check.C) {
<ide> name := "testbuildwithtabs"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name,
<ide> "FROM busybox\nRUN echo\tone\t\ttwo", true)
<ide> if err != nil {
<ide> func (s *DockerSuite) TestBuildWithTabs(c *check.C) {
<ide> func (s *DockerSuite) TestBuildLabels(c *check.C) {
<ide> name := "testbuildlabel"
<ide> expected := `{"License":"GPL","Vendor":"Acme"}`
<del> defer deleteImages(name)
<ide> _, err := buildImage(name,
<ide> `FROM busybox
<ide> LABEL Vendor=Acme
<ide> func (s *DockerSuite) TestBuildLabels(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildLabelsCache(c *check.C) {
<ide> name := "testbuildlabelcache"
<del> defer deleteImages(name)
<ide>
<ide> id1, err := buildImage(name,
<ide> `FROM busybox
<ide> func (s *DockerSuite) TestBuildStderr(c *check.C) {
<ide> // This test just makes sure that no non-error output goes
<ide> // to stderr
<ide> name := "testbuildstderr"
<del> defer deleteImages(name)
<ide> _, _, stderr, err := buildImageWithStdoutStderr(name,
<ide> "FROM busybox\nRUN echo one", true)
<ide> if err != nil {
<ide> func (s *DockerSuite) TestBuildChownSingleFile(c *check.C) {
<ide> testRequires(c, UnixCli) // test uses chown: not available on windows
<ide>
<ide> name := "testbuildchownsinglefile"
<del> defer deleteImages(name)
<ide>
<ide> ctx, err := fakeContext(`
<ide> FROM busybox
<ide> func (s *DockerSuite) TestBuildSymlinkBreakout(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildXZHost(c *check.C) {
<ide> name := "testbuildxzhost"
<del> defer deleteImages(name)
<ide>
<ide> ctx, err := fakeContext(`
<ide> FROM busybox
<ide> func (s *DockerSuite) TestBuildVolumesRetainContents(c *check.C) {
<ide> name = "testbuildvolumescontent"
<ide> expected = "some text"
<ide> )
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext(`
<ide> FROM busybox
<ide> COPY content /foo/file
<ide> func (s *DockerSuite) TestBuildRenamedDockerfile(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildFromMixedcaseDockerfile(c *check.C) {
<ide> testRequires(c, UnixCli) // Dockerfile overwrites dockerfile on windows
<del> defer deleteImages("test1")
<ide>
<ide> ctx, err := fakeContext(`FROM busybox
<ide> RUN echo from dockerfile`,
<ide> func (s *DockerSuite) TestBuildFromMixedcaseDockerfile(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildWithTwoDockerfiles(c *check.C) {
<ide> testRequires(c, UnixCli) // Dockerfile overwrites dockerfile on windows
<del> defer deleteImages("test1")
<ide>
<ide> ctx, err := fakeContext(`FROM busybox
<ide> RUN echo from Dockerfile`,
<ide> RUN echo from Dockerfile`,
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildFromURLWithF(c *check.C) {
<del> defer deleteImages("test1")
<ide>
<ide> server, err := fakeStorage(map[string]string{"baz": `FROM busybox
<ide> RUN echo from baz
<ide> RUN echo from Dockerfile`,
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildFromStdinWithF(c *check.C) {
<del> defer deleteImages("test1")
<ide>
<ide> ctx, err := fakeContext(`FROM busybox
<ide> RUN echo from Dockerfile`,
<ide> func (s *DockerSuite) TestBuildDockerfileOutsideContext(c *check.C) {
<ide> if err == nil {
<ide> c.Fatalf("Expected error. Out: %s", out)
<ide> }
<del> deleteImages(name)
<del>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildSpaces(c *check.C) {
<ide> func (s *DockerSuite) TestBuildSpaces(c *check.C) {
<ide> )
<ide>
<ide> name := "testspaces"
<del> defer deleteImages(name)
<ide> ctx, err := fakeContext("FROM busybox\nCOPY\n",
<ide> map[string]string{
<ide> "Dockerfile": "FROM busybox\nCOPY\n",
<ide> func (s *DockerSuite) TestBuildSpaces(c *check.C) {
<ide> func (s *DockerSuite) TestBuildSpacesWithQuotes(c *check.C) {
<ide> // Test to make sure that spaces in quotes aren't lost
<ide> name := "testspacesquotes"
<del> defer deleteImages(name)
<ide>
<ide> dockerfile := `FROM busybox
<ide> RUN echo " \
<ide> func (s *DockerSuite) TestBuildMissingArgs(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildEmptyScratch(c *check.C) {
<del> defer deleteImages("sc")
<ide> _, out, err := buildImageWithOut("sc", "FROM scratch", true)
<ide> if err == nil {
<ide> c.Fatalf("Build was supposed to fail")
<ide> func (s *DockerSuite) TestBuildEmptyScratch(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildDotDotFile(c *check.C) {
<del> defer deleteImages("sc")
<ide> ctx, err := fakeContext("FROM busybox\n",
<ide> map[string]string{
<ide> "..gitme": "",
<ide> func (s *DockerSuite) TestBuildDotDotFile(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildNotVerbose(c *check.C) {
<del> defer deleteImages("verbose")
<ide>
<ide> ctx, err := fakeContext("FROM busybox\nENV abc=hi\nRUN echo $abc there", map[string]string{})
<ide> if err != nil {
<ide> func (s *DockerSuite) TestBuildNotVerbose(c *check.C) {
<ide> func (s *DockerSuite) TestBuildRUNoneJSON(c *check.C) {
<ide> name := "testbuildrunonejson"
<ide>
<del> defer deleteImages(name, "hello-world")
<del>
<ide> ctx, err := fakeContext(`FROM hello-world:frozen
<ide> RUN [ "/hello" ]`, map[string]string{})
<ide> if err != nil {
<ide> RUN [ "/hello" ]`, map[string]string{})
<ide>
<ide> func (s *DockerSuite) TestBuildResourceConstraintsAreUsed(c *check.C) {
<ide> name := "testbuildresourceconstraints"
<del> defer deleteImages(name, "hello-world")
<ide>
<ide> ctx, err := fakeContext(`
<ide> FROM hello-world:frozen
<ide> func (s *DockerSuite) TestBuildResourceConstraintsAreUsed(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestBuildEmptyStringVolume(c *check.C) {
<ide> name := "testbuildemptystringvolume"
<del> defer deleteImages(name)
<ide>
<ide> _, err := buildImage(name, `
<ide> FROM busybox
<ide><path>integration-cli/docker_cli_by_digest_test.go
<ide> func setupImageWithTag(tag string) (string, error) {
<ide> if out, _, err := runCommandWithOutput(cmd); err != nil {
<ide> return "", fmt.Errorf("image tagging failed: %s, %v", out, err)
<ide> }
<del> defer deleteImages(repoAndTag)
<ide>
<ide> // delete the container as we don't need it any more
<ide> if err := deleteContainer(containerName); err != nil {
<ide> func (s *DockerSuite) TestPullByTagDisplaysDigest(c *check.C) {
<ide> if err != nil {
<ide> c.Fatalf("error pulling by tag: %s, %v", out, err)
<ide> }
<del> defer deleteImages(repoName)
<ide>
<ide> // the pull output includes "Digest: <digest>", so find that
<ide> matches := digestRegex.FindStringSubmatch(out)
<ide> func (s *DockerSuite) TestPullByDigest(c *check.C) {
<ide> if err != nil {
<ide> c.Fatalf("error pulling by digest: %s, %v", out, err)
<ide> }
<del> defer deleteImages(imageReference)
<ide>
<ide> // the pull output includes "Digest: <digest>", so find that
<ide> matches := digestRegex.FindStringSubmatch(out)
<ide> func (s *DockerSuite) TestBuildByDigest(c *check.C) {
<ide>
<ide> // do the build
<ide> name := "buildbydigest"
<del> defer deleteImages(name)
<ide> _, err = buildImage(name, fmt.Sprintf(
<ide> `FROM %s
<ide> CMD ["/bin/echo", "Hello World"]`, imageReference),
<ide> func (s *DockerSuite) TestListImagesWithoutDigests(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestListImagesWithDigests(c *check.C) {
<ide> defer setupRegistry(c)()
<del> defer deleteImages(repoName+":tag1", repoName+":tag2")
<ide>
<ide> // setup image1
<ide> digest1, err := setupImageWithTag("tag1")
<ide> if err != nil {
<ide> c.Fatalf("error setting up image: %v", err)
<ide> }
<ide> imageReference1 := fmt.Sprintf("%s@%s", repoName, digest1)
<del> defer deleteImages(imageReference1)
<ide> c.Logf("imageReference1 = %s", imageReference1)
<ide>
<ide> // pull image1 by digest
<ide> func (s *DockerSuite) TestListImagesWithDigests(c *check.C) {
<ide> c.Fatalf("error setting up image: %v", err)
<ide> }
<ide> imageReference2 := fmt.Sprintf("%s@%s", repoName, digest2)
<del> defer deleteImages(imageReference2)
<ide> c.Logf("imageReference2 = %s", imageReference2)
<ide>
<ide> // pull image1 by digest
<ide> func (s *DockerSuite) TestDeleteImageByIDOnlyPulledByDigest(c *check.C) {
<ide> c.Fatalf("error pulling by digest: %s, %v", out, err)
<ide> }
<ide> // just in case...
<del> defer deleteImages(imageReference)
<ide>
<ide> imageID, err := inspectField(imageReference, ".Id")
<ide> if err != nil {
<ide><path>integration-cli/docker_cli_commit_test.go
<ide> func (s *DockerSuite) TestCommitAfterContainerIsDone(c *check.C) {
<ide> if out, _, err = runCommandWithOutput(inspectCmd); err != nil {
<ide> c.Fatalf("failed to inspect image: %s, %v", out, err)
<ide> }
<del>
<del> deleteContainer(cleanedContainerID)
<del> deleteImages(cleanedImageID)
<del>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestCommitWithoutPause(c *check.C) {
<ide> func (s *DockerSuite) TestCommitWithoutPause(c *check.C) {
<ide> if out, _, err = runCommandWithOutput(inspectCmd); err != nil {
<ide> c.Fatalf("failed to inspect image: %s, %v", out, err)
<ide> }
<del>
<del> deleteContainer(cleanedContainerID)
<del> deleteImages(cleanedImageID)
<del>
<ide> }
<ide>
<ide> //test commit a paused container should not unpause it after commit
<ide> func (s *DockerSuite) TestCommitPausedContainer(c *check.C) {
<ide> if err != nil {
<ide> c.Fatalf("failed to commit container to image: %s, %v", out, err)
<ide> }
<del> cleanedImageID := strings.TrimSpace(out)
<del> defer deleteImages(cleanedImageID)
<ide>
<ide> cmd = exec.Command(dockerBinary, "inspect", "-f", "{{.State.Paused}}", cleanedContainerID)
<ide> out, _, _, err = runCommandWithStdoutStderr(cmd)
<ide> func (s *DockerSuite) TestCommitNewFile(c *check.C) {
<ide> c.Fatal(err)
<ide> }
<ide> imageID = strings.Trim(imageID, "\r\n")
<del> defer deleteImages(imageID)
<ide>
<ide> cmd = exec.Command(dockerBinary, "run", imageID, "cat", "/foo")
<ide>
<ide> func (s *DockerSuite) TestCommitHardlink(c *check.C) {
<ide> c.Fatal(imageID, err)
<ide> }
<ide> imageID = strings.Trim(imageID, "\r\n")
<del> defer deleteImages(imageID)
<ide>
<ide> cmd = exec.Command(dockerBinary, "run", "-t", "hardlinks", "ls", "-di", "file1", "file2")
<ide> secondOuput, _, err := runCommandWithOutput(cmd)
<ide> func (s *DockerSuite) TestCommitHardlink(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestCommitTTY(c *check.C) {
<del> defer deleteImages("ttytest")
<ide>
<ide> cmd := exec.Command(dockerBinary, "run", "-t", "--name", "tty", "busybox", "/bin/ls")
<ide> if _, err := runCommand(cmd); err != nil {
<ide> func (s *DockerSuite) TestCommitWithHostBindMount(c *check.C) {
<ide> }
<ide>
<ide> imageID = strings.Trim(imageID, "\r\n")
<del> defer deleteImages(imageID)
<ide>
<ide> cmd = exec.Command(dockerBinary, "run", "bindtest", "true")
<ide>
<ide> func (s *DockerSuite) TestCommitChange(c *check.C) {
<ide> c.Fatal(imageId, err)
<ide> }
<ide> imageId = strings.Trim(imageId, "\r\n")
<del> defer deleteImages(imageId)
<ide>
<ide> expected := map[string]string{
<ide> "Config.ExposedPorts": "map[8080/tcp:{}]",
<ide> func (s *DockerSuite) TestCommitMergeConfigRun(c *check.C) {
<ide> id := strings.TrimSpace(out)
<ide>
<ide> dockerCmd(c, "commit", `--run={"Cmd": ["cat", "/tmp/foo"]}`, id, "commit-test")
<del> defer deleteImages("commit-test")
<ide>
<ide> out, _ = dockerCmd(c, "run", "--name", name, "commit-test")
<ide> if strings.TrimSpace(out) != "testing" {
<ide><path>integration-cli/docker_cli_create_test.go
<ide> func (s *DockerSuite) TestCreateLabels(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestCreateLabelFromImage(c *check.C) {
<ide> imageName := "testcreatebuildlabel"
<del> defer deleteImages(imageName)
<ide> _, err := buildImage(imageName,
<ide> `FROM busybox
<ide> LABEL k1=v1 k2=v2`,
<ide><path>integration-cli/docker_cli_events_test.go
<ide> func (s *DockerSuite) TestEventsContainerEventsSinceUnixEpoch(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestEventsImageUntagDelete(c *check.C) {
<ide> name := "testimageevents"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name,
<ide> `FROM scratch
<ide> MAINTAINER "docker"`,
<ide> func (s *DockerSuite) TestEventsImagePull(c *check.C) {
<ide> since := daemonTime(c).Unix()
<ide> testRequires(c, Network)
<ide>
<del> defer deleteImages("hello-world")
<del>
<ide> pullCmd := exec.Command(dockerBinary, "pull", "hello-world")
<ide> if out, _, err := runCommandWithOutput(pullCmd); err != nil {
<ide> c.Fatalf("pulling the hello-world image from has failed: %s, %v", out, err)
<ide><path>integration-cli/docker_cli_export_import_test.go
<ide> import (
<ide> func (s *DockerSuite) TestExportContainerAndImportImage(c *check.C) {
<ide> containerID := "testexportcontainerandimportimage"
<ide>
<del> defer deleteImages("repo/testexp:v1")
<del>
<ide> runCmd := exec.Command(dockerBinary, "run", "-d", "--name", containerID, "busybox", "true")
<ide> out, _, err := runCommandWithOutput(runCmd)
<ide> if err != nil {
<ide> func (s *DockerSuite) TestExportContainerAndImportImage(c *check.C) {
<ide> func (s *DockerSuite) TestExportContainerWithOutputAndImportImage(c *check.C) {
<ide> containerID := "testexportcontainerwithoutputandimportimage"
<ide>
<del> defer deleteImages("repo/testexp:v1")
<del>
<ide> runCmd := exec.Command(dockerBinary, "run", "-d", "--name", containerID, "busybox", "true")
<ide> out, _, err := runCommandWithOutput(runCmd)
<ide> if err != nil {
<ide><path>integration-cli/docker_cli_history_test.go
<ide> import (
<ide> // sort is not predictable it doesn't always fail.
<ide> func (s *DockerSuite) TestBuildHistory(c *check.C) {
<ide> name := "testbuildhistory"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name, `FROM busybox
<ide> RUN echo "A"
<ide> RUN echo "B"
<ide> func (s *DockerSuite) TestHistoryNonExistentImage(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestHistoryImageWithComment(c *check.C) {
<ide> name := "testhistoryimagewithcomment"
<del> defer deleteImages(name)
<ide>
<ide> // make a image through docker commit <container id> [ -m messages ]
<ide> //runCmd := exec.Command(dockerBinary, "run", "-i", "-a", "stdin", "busybox", "echo", "foo")
<ide><path>integration-cli/docker_cli_images_test.go
<ide> func (s *DockerSuite) TestImagesEnsureImageIsListed(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestImagesOrderedByCreationDate(c *check.C) {
<del> defer deleteImages("order:test_a")
<del> defer deleteImages("order:test_c")
<del> defer deleteImages("order:test_b")
<ide> id1, err := buildImage("order:test_a",
<ide> `FROM scratch
<ide> MAINTAINER dockerio1`, true)
<ide> func (s *DockerSuite) TestImagesFilterLabel(c *check.C) {
<ide> imageName1 := "images_filter_test1"
<ide> imageName2 := "images_filter_test2"
<ide> imageName3 := "images_filter_test3"
<del> defer deleteImages(imageName1)
<del> defer deleteImages(imageName2)
<del> defer deleteImages(imageName3)
<ide> image1ID, err := buildImage(imageName1,
<ide> `FROM scratch
<ide> LABEL match me`, true)
<ide> func (s *DockerSuite) TestImagesFilterLabel(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestImagesFilterSpaceTrimCase(c *check.C) {
<ide> imageName := "images_filter_test"
<del> defer deleteImages(imageName)
<ide> buildImage(imageName,
<ide> `FROM scratch
<ide> RUN touch /test/foo
<ide> func (s *DockerSuite) TestImagesEnsureDanglingImageOnlyListedOnce(c *check.C) {
<ide> c.Fatalf("error tagging foobox: %s", err)
<ide> }
<ide> imageId := stringid.TruncateID(strings.TrimSpace(out))
<del> defer deleteImages(imageId)
<ide>
<ide> // overwrite the tag, making the previous image dangling
<ide> cmd = exec.Command(dockerBinary, "tag", "-f", "busybox", "foobox")
<ide> out, _, err = runCommandWithOutput(cmd)
<ide> if err != nil {
<ide> c.Fatalf("error tagging foobox: %s", err)
<ide> }
<del> defer deleteImages("foobox")
<ide>
<ide> cmd = exec.Command(dockerBinary, "images", "-q", "-f", "dangling=true")
<ide> out, _, err = runCommandWithOutput(cmd)
<ide><path>integration-cli/docker_cli_import_test.go
<ide> func (s *DockerSuite) TestImportDisplay(c *check.C) {
<ide> c.Fatalf("display is messed up: %d '\\n' instead of 1:\n%s", n, out)
<ide> }
<ide> image := strings.TrimSpace(out)
<del> defer deleteImages(image)
<ide>
<ide> runCmd = exec.Command(dockerBinary, "run", "--rm", image, "true")
<ide> out, _, err = runCommandWithOutput(runCmd)
<ide><path>integration-cli/docker_cli_ps_test.go
<ide> func (s *DockerSuite) TestPsListContainersFilterExited(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestPsRightTagName(c *check.C) {
<ide> tag := "asybox:shmatest"
<del> defer deleteImages(tag)
<ide> if out, err := exec.Command(dockerBinary, "tag", "busybox", tag).CombinedOutput(); err != nil {
<ide> c.Fatalf("Failed to tag image: %s, out: %q", err, out)
<ide> }
<ide><path>integration-cli/docker_cli_pull_test.go
<ide> func (s *DockerSuite) TestPullImageWithAliases(c *check.C) {
<ide> defer setupRegistry(c)()
<ide>
<ide> repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL)
<del> defer deleteImages(repoName)
<ide>
<ide> repos := []string{}
<ide> for _, tag := range []string{"recent", "fresh"} {
<ide> func (s *DockerSuite) TestPullImageWithAliases(c *check.C) {
<ide> if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "tag", "busybox", repo)); err != nil {
<ide> c.Fatalf("Failed to tag image %v: error %v, output %q", repos, err, out)
<ide> }
<del> defer deleteImages(repo)
<ide> if out, err := exec.Command(dockerBinary, "push", repo).CombinedOutput(); err != nil {
<ide> c.Fatalf("Failed to push image %v: error %v, output %q", repo, err, string(out))
<ide> }
<ide> func (s *DockerSuite) TestPullVerified(c *check.C) {
<ide> // unless keychain is manually updated to contain the daemon's sign key.
<ide>
<ide> verifiedName := "hello-world"
<del> defer deleteImages(verifiedName)
<ide>
<ide> // pull it
<ide> expected := "The image you are pulling has been verified"
<ide> func (s *DockerSuite) TestPullVerified(c *check.C) {
<ide> func (s *DockerSuite) TestPullImageFromCentralRegistry(c *check.C) {
<ide> testRequires(c, Network)
<ide>
<del> defer deleteImages("hello-world")
<del>
<ide> pullCmd := exec.Command(dockerBinary, "pull", "hello-world")
<ide> if out, _, err := runCommandWithOutput(pullCmd); err != nil {
<ide> c.Fatalf("pulling the hello-world image from the registry has failed: %s, %v", out, err)
<ide><path>integration-cli/docker_cli_push_test.go
<ide> func (s *DockerSuite) TestPushBusyboxImage(c *check.C) {
<ide> if out, _, err := runCommandWithOutput(tagCmd); err != nil {
<ide> c.Fatalf("image tagging failed: %s, %v", out, err)
<ide> }
<del> defer deleteImages(repoName)
<ide>
<ide> pushCmd := exec.Command(dockerBinary, "push", repoName)
<ide> if out, _, err := runCommandWithOutput(pushCmd); err != nil {
<ide> func (s *DockerSuite) TestPushMultipleTags(c *check.C) {
<ide> if out, _, err := runCommandWithOutput(tagCmd1); err != nil {
<ide> c.Fatalf("image tagging failed: %s, %v", out, err)
<ide> }
<del> defer deleteImages(repoTag1)
<ide> tagCmd2 := exec.Command(dockerBinary, "tag", "busybox", repoTag2)
<ide> if out, _, err := runCommandWithOutput(tagCmd2); err != nil {
<ide> c.Fatalf("image tagging failed: %s, %v", out, err)
<ide> }
<del> defer deleteImages(repoTag2)
<ide>
<ide> pushCmd := exec.Command(dockerBinary, "push", repoName)
<ide> if out, _, err := runCommandWithOutput(pushCmd); err != nil {
<ide> func (s *DockerSuite) TestPushInterrupt(c *check.C) {
<ide> if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "tag", "busybox", repoName)); err != nil {
<ide> c.Fatalf("image tagging failed: %s, %v", out, err)
<ide> }
<del> defer deleteImages(repoName)
<ide>
<ide> pushCmd := exec.Command(dockerBinary, "push", repoName)
<ide> if err := pushCmd.Start(); err != nil {
<ide><path>integration-cli/docker_cli_rm_test.go
<ide> func (s *DockerSuite) TestRmContainerOrphaning(c *check.C) {
<ide>
<ide> // build first dockerfile
<ide> img1, err := buildImage(img, dockerfile1, true)
<del> defer deleteImages(img1)
<ide> if err != nil {
<ide> c.Fatalf("Could not build image %s: %v", img, err)
<ide> }
<ide><path>integration-cli/docker_cli_run_test.go
<ide> func (s *DockerSuite) TestRunCreateVolumesInSymlinkDir(c *check.C) {
<ide> if _, err := buildImage(name, dockerFile, false); err != nil {
<ide> c.Fatal(err)
<ide> }
<del> defer deleteImages(name)
<ide>
<ide> out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-v", "/test/test", name))
<ide> if err != nil {
<ide> func (s *DockerSuite) TestRunCreateVolume(c *check.C) {
<ide> // Note that this bug happens only with symlinks with a target that starts with '/'.
<ide> func (s *DockerSuite) TestRunCreateVolumeWithSymlink(c *check.C) {
<ide> image := "docker-test-createvolumewithsymlink"
<del> defer deleteImages(image)
<ide>
<ide> buildCmd := exec.Command(dockerBinary, "build", "-t", image, "-")
<ide> buildCmd.Stdin = strings.NewReader(`FROM busybox
<ide> func (s *DockerSuite) TestRunCreateVolumeWithSymlink(c *check.C) {
<ide> // Tests that a volume path that has a symlink exists in a container mounting it with `--volumes-from`.
<ide> func (s *DockerSuite) TestRunVolumesFromSymlinkPath(c *check.C) {
<ide> name := "docker-test-volumesfromsymlinkpath"
<del> defer deleteImages(name)
<ide>
<ide> buildCmd := exec.Command(dockerBinary, "build", "-t", name, "-")
<ide> buildCmd.Stdin = strings.NewReader(`FROM busybox
<ide> func (s *DockerSuite) TestRunState(c *check.C) {
<ide> // Test for #1737
<ide> func (s *DockerSuite) TestRunCopyVolumeUidGid(c *check.C) {
<ide> name := "testrunvolumesuidgid"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name,
<ide> `FROM busybox
<ide> RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
<ide> func (s *DockerSuite) TestRunCopyVolumeUidGid(c *check.C) {
<ide> // Test for #1582
<ide> func (s *DockerSuite) TestRunCopyVolumeContent(c *check.C) {
<ide> name := "testruncopyvolumecontent"
<del> defer deleteImages(name)
<ide> _, err := buildImage(name,
<ide> `FROM busybox
<ide> RUN mkdir -p /hello/local && echo hello > /hello/local/world`,
<ide> func (s *DockerSuite) TestRunCopyVolumeContent(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestRunCleanupCmdOnEntrypoint(c *check.C) {
<ide> name := "testrunmdcleanuponentrypoint"
<del> defer deleteImages(name)
<ide> if _, err := buildImage(name,
<ide> `FROM busybox
<ide> ENTRYPOINT ["echo"]
<ide> func (s *DockerSuite) TestRunCreateVolumeEtc(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestVolumesNoCopyData(c *check.C) {
<del> defer deleteImages("dataimage")
<ide> if _, err := buildImage("dataimage",
<ide> `FROM busybox
<ide> RUN mkdir -p /foo
<ide> func (s *DockerSuite) TestRunVolumesCleanPaths(c *check.C) {
<ide> true); err != nil {
<ide> c.Fatal(err)
<ide> }
<del> defer deleteImages("run_volumes_clean_paths")
<ide>
<ide> cmd := exec.Command(dockerBinary, "run", "-v", "/foo", "-v", "/bar/", "--name", "dark_helmet", "run_volumes_clean_paths")
<ide> if out, _, err := runCommandWithOutput(cmd); err != nil {
<ide><path>integration-cli/docker_cli_save_load_test.go
<ide> func (s *DockerSuite) TestSaveSingleTag(c *check.C) {
<ide> repoName := "foobar-save-single-tag-test"
<ide>
<ide> tagCmd := exec.Command(dockerBinary, "tag", "busybox:latest", fmt.Sprintf("%v:latest", repoName))
<del> defer deleteImages(repoName)
<ide> if out, _, err := runCommandWithOutput(tagCmd); err != nil {
<ide> c.Fatalf("failed to tag repo: %s, %v", out, err)
<ide> }
<ide> func (s *DockerSuite) TestSaveImageId(c *check.C) {
<ide> repoName := "foobar-save-image-id-test"
<ide>
<ide> tagCmd := exec.Command(dockerBinary, "tag", "emptyfs:latest", fmt.Sprintf("%v:latest", repoName))
<del> defer deleteImages(repoName)
<ide> if out, _, err := runCommandWithOutput(tagCmd); err != nil {
<ide> c.Fatalf("failed to tag repo: %s, %v", out, err)
<ide> }
<ide> func (s *DockerSuite) TestSaveMultipleNames(c *check.C) {
<ide> if out, _, err := runCommandWithOutput(tagCmd); err != nil {
<ide> c.Fatalf("failed to tag repo: %s, %v", out, err)
<ide> }
<del> defer deleteImages(repoName + "-one")
<ide>
<ide> // Make two images
<ide> tagCmd = exec.Command(dockerBinary, "tag", "emptyfs:latest", fmt.Sprintf("%v-two:latest", repoName))
<ide> out, _, err := runCommandWithOutput(tagCmd)
<ide> if err != nil {
<ide> c.Fatalf("failed to tag repo: %s, %v", out, err)
<ide> }
<del> defer deleteImages(repoName + "-two")
<ide>
<ide> out, _, err = runCommandPipelineWithOutput(
<ide> exec.Command(dockerBinary, "save", fmt.Sprintf("%v-one", repoName), fmt.Sprintf("%v-two:latest", repoName)),
<ide> func (s *DockerSuite) TestSaveRepoWithMultipleImages(c *check.C) {
<ide> tagBar := repoName + ":bar"
<ide>
<ide> idFoo := makeImage("busybox:latest", tagFoo)
<del> defer deleteImages(idFoo)
<ide> idBar := makeImage("busybox:latest", tagBar)
<del> defer deleteImages(idBar)
<ide>
<ide> deleteImages(repoName)
<ide>
<ide> func (s *DockerSuite) TestSaveDirectoryPermissions(c *check.C) {
<ide> os.Mkdir(extractionDirectory, 0777)
<ide>
<ide> defer os.RemoveAll(tmpDir)
<del> defer deleteImages(name)
<ide> _, err = buildImage(name,
<ide> `FROM busybox
<ide> RUN adduser -D user && mkdir -p /opt/a/b && chown -R user:user /opt/a
<ide><path>integration-cli/docker_cli_tag_test.go
<ide> func (s *DockerSuite) TestTagUnprefixedRepoByName(c *check.C) {
<ide> if out, _, err := runCommandWithOutput(tagCmd); err != nil {
<ide> c.Fatal(out, err)
<ide> }
<del>
<del> deleteImages("testfoobarbaz")
<del>
<ide> }
<ide>
<ide> // tagging an image by ID in a new unprefixed repo should work
<ide> func (s *DockerSuite) TestTagUnprefixedRepoByID(c *check.C) {
<ide> if out, _, err = runCommandWithOutput(tagCmd); err != nil {
<ide> c.Fatal(out, err)
<ide> }
<del>
<del> deleteImages("testfoobarbaz")
<del>
<ide> }
<ide>
<ide> // ensure we don't allow the use of invalid repository names; these tag operations should fail
<ide> func (s *DockerSuite) TestTagExistedNameWithoutForce(c *check.C) {
<ide> if err == nil || !strings.Contains(out, "Conflict: Tag test is already set to image") {
<ide> c.Fatal("tag busybox busybox:test should have failed,because busybox:test is existed")
<ide> }
<del> deleteImages("busybox:test")
<del>
<ide> }
<ide>
<ide> // tag an image with an existed tag name with -f option should work
<ide> func (s *DockerSuite) TestTagExistedNameWithForce(c *check.C) {
<ide> if out, _, err := runCommandWithOutput(tagCmd); err != nil {
<ide> c.Fatal(out, err)
<ide> }
<del> deleteImages("busybox:test")
<del>
<ide> }
<ide>
<ide> // ensure tagging using official names works
<ide><path>integration-cli/docker_utils.go
<ide> func deleteAllContainers() error {
<ide> return nil
<ide> }
<ide>
<add>var protectedImages = map[string]struct{}{}
<add>
<add>func init() {
<add> out, err := exec.Command(dockerBinary, "images").CombinedOutput()
<add> if err != nil {
<add> panic(err)
<add> }
<add> lines := strings.Split(string(out), "\n")[1:]
<add> for _, l := range lines {
<add> if l == "" {
<add> continue
<add> }
<add> fields := strings.Fields(l)
<add> imgTag := fields[0] + ":" + fields[1]
<add> protectedImages[imgTag] = struct{}{}
<add> }
<add>}
<add>
<add>func deleteAllImages() error {
<add> out, err := exec.Command(dockerBinary, "images").CombinedOutput()
<add> if err != nil {
<add> return err
<add> }
<add> lines := strings.Split(string(out), "\n")[1:]
<add> var imgs []string
<add> for _, l := range lines {
<add> if l == "" {
<add> continue
<add> }
<add> fields := strings.Fields(l)
<add> imgTag := fields[0] + ":" + fields[1]
<add> if _, ok := protectedImages[imgTag]; !ok {
<add> if fields[0] == "<none>" {
<add> imgs = append(imgs, fields[2])
<add> continue
<add> }
<add> imgs = append(imgs, imgTag)
<add> }
<add> }
<add> if len(imgs) == 0 {
<add> return nil
<add> }
<add> args := append([]string{"rmi", "-f"}, imgs...)
<add> if err := exec.Command(dockerBinary, args...).Run(); err != nil {
<add> return err
<add> }
<add> return nil
<add>}
<add>
<ide> func getPausedContainers() (string, error) {
<ide> getPausedContainersCmd := exec.Command(dockerBinary, "ps", "-f", "status=paused", "-q", "-a")
<ide> out, exitCode, err := runCommandWithOutput(getPausedContainersCmd) | 20 |
Text | Text | extend bash-ls and add fixes | 87bbeb906902ddfe6c5ceccc50aa61bda985d104 | <ide><path>guide/russian/bash/bash-ls/index.md
<ide> ---
<ide> title: Bash ls
<ide> localeTitle: Bash ls
<del>---
<ide>## Bash ls
<del>
<del>`ls` - это команда в Unix-подобных операционных системах для отображения содержимого каталога, например имен папок и файлов.
<del>
<del>### использование
<del>
<del>```bash
<del>cat [options] [file_names]
<del>```
<del>
<del>Наиболее часто используемые опции:
<del>
<del>* `-a` , все файлы и папки, в том числе скрытые и начинающиеся с `.`
<del>* `-l` , Список в длинном формате
<del>* `-G` , включить цветной вывод.
<del>
<del>### Пример:
<del>
<del>Список файлов в `freeCodeCamp/guide/`
<del>
<del>```bash
<del>ls ⚬ master
<del> CODE_OF_CONDUCT.md bin package.json utils
<del> CONTRIBUTING.md gatsby-browser.js plugins yarn.lock
<del> LICENSE.md gatsby-config.js src
<del> README.md gatsby-node.js static
<del> assets gatsby-ssr.js translations
<del>```
<del>
<del>#### Дополнительная информация:
<del>
<del>* [Википедия](https://en.wikipedia.org/wiki/Ls)
<ide>\ No newline at end of file
<add>---
<add>## Bash ls
<add>
<add>`ls` - это команда в Unix-подобных операционных системах для отображения содержимого каталога, например имен папок и файлов.
<add>
<add>### использование
<add>
<add>```bash
<add>ls [опция/фильтр] [имя_файла]
<add>```
<add>
<add>Команда ls предоставляет также возможность определить фильтр в командной строке.
<add>В этой команде фильтр используется для определения того, какие файлы или каталоги должны быть отображены в выводе.
<add>Фильтр работает как простая строка сопоставления с текстом. Для этого достаточно включить фильтр после любых параметров командной строки, к которым он должен быть применен.
<add>
<add>
<add>Наиболее часто используемые фильтры(опции):
<add>
<add>* `-a` , все файлы и папки, в том числе скрытые и начинающиеся с `.`
<add>* `-l` , Список в длинном формате
<add>* `--color` , включить цветной вывод.
<add>
<add>### Примеры:
<add>
<add>* Вывод списка файлов в `freeCodeCamp` папке без фильтра:
<add>
<add>```bash
<add>$ ls freeCodeCamp
<add>api-server config docker-compose-shared.yml guide netlify.toml package-lock.json tools
<add>client CONTRIBUTING.md docker-compose.yml lerna.json news README.md
<add>CODE_OF_CONDUCT.md curriculum docs LICENSE.md package.json sample.env
<add>```
<add>Если в качестве фильтра указано имя конкретного файла, то команда ls отображает информацию только об этом файле (папке).
<add>
<add>* Вывод списка файлов в `freeCodeCamp` папке с применением фильтра `l`:
<add>
<add>```bash
<add>$ ls -l freeCodeCamp
<add>total 432
<add>drwxrwxr-x 5 fuser fuser 4096 Oct 18 23:01 api-server
<add>drwxrwxr-x 7 fuser fuser 4096 Oct 18 23:01 client
<add>-rw-rw-r-- 1 fuser fuser 86 Oct 18 23:01 CODE_OF_CONDUCT.md
<add>drwxrwxr-x 2 fuser fuser 4096 Oct 18 23:01 config
<add>-rw-rw-r-- 1 fuser fuser 8965 Oct 18 23:01 CONTRIBUTING.md
<add>drwxrwxr-x 7 fuser fuser 4096 Oct 18 23:01 curriculum
<add>-rwxrwxr-x 1 fuser fuser 405 Oct 18 23:01 docker-compose-shared.yml
<add>-rw-rw-r-- 1 fuser fuser 826 Oct 18 23:01 docker-compose.yml
<add>drwxrwxr-x 9 fuser fuser 4096 Oct 18 23:01 docs
<add>drwxrwxr-x 8 fuser fuser 4096 Oct 18 23:01 guide
<add>-rw-rw-r-- 1 fuser fuser 160 Oct 18 23:01 lerna.json
<add>-rw-rw-r-- 1 fuser fuser 1513 Oct 18 23:01 LICENSE.md
<add>-rw-rw-r-- 1 fuser fuser 583 Oct 18 23:01 netlify.toml
<add>drwxrwxr-x 5 fuser fuser 4096 Oct 18 23:01 news
<add>-rw-rw-r-- 1 fuser fuser 1122 Oct 18 23:01 package.json
<add>-rw-rw-r-- 1 fuser fuser 354303 Oct 18 23:01 package-lock.json
<add>-rw-rw-r-- 1 fuser fuser 7010 Oct 18 23:01 README.md
<add>-rw-rw-r-- 1 fuser fuser 643 Oct 18 23:01 sample.env
<add>drwxrwxr-x 4 fuser fuser 4096 Oct 18 23:01 tools
<add>```
<add>
<add>В каждой строке листинга в длинном формате содержатся сведения о различных файлах и каталогах, имеющихся в данном каталоге. Такой листинг, кроме имени файла, показывает другую полезную информацию. В <strong>первой</strong> строке вывода содержатся сведения об общем количестве блоков данных, относящихся к текущему каталогу. Вслед за этим происходит вывод отдельных строк, каждая из которых включает следующую информацию о каждом файле (или каталоге):
<add>
<add>— Тип файла, такой как каталог `(d)`, файл `(-)`, символьное устройство `(c)` или блочное устройство `(b)`; <br>
<add>— Разрешения для файла;<br>
<add>— Количество жестких ссылок на файл;<br>
<add>— Имя пользователя владельца файла;<br>
<add>— Имя группы файлов, к которой принадлежит этот файл;<br>
<add>— Размер файла в байтах;<br>
<add>— Время последнего изменения файла;<br>
<add>— Имя файла или каталога.<br>
<add>
<add>#### Дополнительная информация:
<add>
<add>* [Википедия](https://ru.wikipedia.org/wiki/Ls) | 1 |
Javascript | Javascript | add examples to the ember.computed docs | b0c6394ac68035298dd437a8d97387e034776d5d | <ide><path>packages/ember-metal/lib/computed.js
<ide> function registerComputedWithProperties(name, macro) {
<ide> }
<ide>
<ide> /**
<add> A computed property that returns true of the value of the dependent
<add> property is null, an empty string, empty array, or empty function.
<add>
<add> Note: When using `Ember.computed.empty` to watch an array make sure to
<add> use the `array.length` or `array.@each` syntax so the computed can
<add> subscribe to transitions from empty to non-empty states.
<add>
<add> Example
<add>
<add>```javascript
<add> var ToDoList = Ember.Object.extend({
<add> done: Ember.computed.empty('todos.length')
<add> });
<add> var todoList = ToDoList.create({todoList: ['Unit Test', 'Documentation', 'Release']});
<add> todoList.get('done'); // false
<add> todoList.get('todoList').clear(); // []
<add> todoList.get('done'); // true
<add> ```
<add>
<ide> @method computed.empty
<ide> @for Ember
<ide> @param {String} dependentKey
<ide> registerComputed('empty', function(dependentKey) {
<ide> });
<ide>
<ide> /**
<add> A computed property that returns true of the value of the dependent
<add> property is NOT null, an empty string, empty array, or empty function.
<add>
<add> Example
<add>
<add> ```javascript
<add> var Hampster = Ember.Object.extend({
<add> hasStuff: Ember.computed.notEmpty('backpack')
<add> });
<add> var hampster = Hampster.create({backpack: ['Food', 'Sleeping Bag', 'Tent']});
<add> hampster.get('hasStuff'); // true
<add> hampster.get('backpack').clear(); // []
<add> hampster.get('hasStuff'); // false
<add> ```
<add>
<ide> @method computed.notEmpty
<ide> @for Ember
<ide> @param {String} dependentKey
<ide> registerComputed('notEmpty', function(dependentKey) {
<ide> });
<ide>
<ide> /**
<add> A computed property that returns true of the value of the dependent
<add> property is null or undefined. This avoids errors from JSLint complaining
<add> about use of ==, which can be technically confusing.
<add>
<add> Example
<add>
<add> ```javascript
<add> var Hampster = Ember.Object.extend({
<add> isHungry: Ember.computed.none('food')
<add> });
<add> var hampster = Hampster.create();
<add> hampster.get('isHungry'); // true
<add> hampster.set('food', 'Banana');
<add> hampster.get('isHungry'); // false
<add> hampster.set('food', null);
<add> hampster.get('isHungry'); // true
<add> ```
<add>
<ide> @method computed.none
<ide> @for Ember
<ide> @param {String} dependentKey
<ide> registerComputed('none', function(dependentKey) {
<ide> });
<ide>
<ide> /**
<add> A computed property that returns the inverse of the original value
<add> for the dependent property.
<add>
<add> Example
<add>
<add> ```javascript
<add> var User = Ember.Object.extend({
<add> isAnonymous: Ember.computed.not('loggedIn')
<add> });
<add> var user = User.create({loggedIn: false});
<add> user.get('isAnonymous'); // false
<add> user.set('loggedIn', true);
<add> user.get('isAnonymous'); // true
<add> ```
<add>
<ide> @method computed.not
<ide> @for Ember
<ide> @param {String} dependentKey
<ide> registerComputed('not', function(dependentKey) {
<ide> });
<ide>
<ide> /**
<add> A computed property that which convert the dependent propery to a boolean.
<add>
<add> ```javascript
<add> var Hampster = Ember.Object.extend({
<add> hasBananas: Ember.computed.bool('numBananas')
<add> });
<add> var hampster = Hampster.create();
<add> hampster.get('hasBananas'); // false
<add> hampster.set('numBananas', 0);
<add> hampster.get('hasBananas'); // false
<add> hampster.set('numBananas', 1);
<add> hampster.get('hasBananas'); // true
<add> hampster.set('numBananas', null);
<add> hampster.get('hasBananas'); // false
<add> ```
<add>
<ide> @method computed.bool
<ide> @for Ember
<ide> @param {String} dependentKey
<ide> registerComputed('bool', function(dependentKey) {
<ide> });
<ide>
<ide> /**
<add> A computed property which matchs the original value for dependent property
<add> against a given RegExp.
<add>
<add> Example
<add>
<add> ```javascript
<add> var User = Ember.Object.extend({
<add> hasValidEmail: Ember.computed.match('email', /^.+@.+\..+$/)
<add> });
<add> var user = User.create({loggedIn: false});
<add> user.get('hasValidEmail'); // false
<add> user.set('email', '');
<add> user.get('hasValidEmail'); // false
<add> user.set('email', 'ember_hampster@example.com');
<add> user.get('hasValidEmail'); // true
<add> ```
<add>
<ide> @method computed.match
<ide> @for Ember
<ide> @param {String} dependentKey
<ide> registerComputed('match', function(dependentKey, regexp) {
<ide> });
<ide>
<ide> /**
<add> A computed property that which returns true if dependent property is
<add> equal to the given value.
<add>
<add> Example
<add>
<add> ```javascript
<add> var Hampster = Ember.Object.extend({
<add> napTime: Ember.computed.equal('state', 'sleepy')
<add> });
<add> var hampster = Hampster.create();
<add> hampster.get('napTime'); // false
<add> hampster.set('state', 'sleepy');
<add> hampster.get('napTime'); // false
<add> hampster.set('state', 'hungry');
<add> hampster.get('napTime'); // false
<add> ```
<add>
<ide> @method computed.equal
<ide> @for Ember
<ide> @param {String} dependentKey
<ide> registerComputed('equal', function(dependentKey, value) {
<ide> });
<ide>
<ide> /**
<add> A computed property that which returns true if dependent property is
<add> greater than the given value.
<add>
<add> Example
<add>
<add> ```javascript
<add> var Hampster = Ember.Object.extend({
<add> hasTooManyBananas: Ember.computed.gt('numBananas', 10)
<add> });
<add> var hampster = Hampster.create();
<add> hampster.get('hasTooManyBananas'); // false
<add> hampster.set('numBananas', 3);
<add> hampster.get('hasTooManyBananas'); // false
<add> hampster.set('numBananas', 11);
<add> hampster.get('hasTooManyBananas'); // true
<add> ```
<add>
<ide> @method computed.gt
<ide> @for Ember
<ide> @param {String} dependentKey
<ide> registerComputed('gt', function(dependentKey, value) {
<ide> });
<ide>
<ide> /**
<add> A computed property that which returns true if dependent property is
<add> greater than or equal to the given value.
<add>
<add> Example
<add>
<add> ```javascript
<add> var Hampster = Ember.Object.extend({
<add> hasTooManyBananas: Ember.computed.gte('numBananas', 10)
<add> });
<add> var hampster = Hampster.create();
<add> hampster.get('hasTooManyBananas'); // false
<add> hampster.set('numBananas', 3);
<add> hampster.get('hasTooManyBananas'); // false
<add> hampster.set('numBananas', 10);
<add> hampster.get('hasTooManyBananas'); // true
<add> ```
<add>
<ide> @method computed.gte
<ide> @for Ember
<ide> @param {String} dependentKey
<ide> registerComputed('gte', function(dependentKey, value) {
<ide> });
<ide>
<ide> /**
<add> A computed property that which returns true if dependent property is
<add> less than the given value.
<add>
<add> Example
<add>
<add> ```javascript
<add> var Hampster = Ember.Object.extend({
<add> needsMoreBananas: Ember.computed.lt('numBananas', 3)
<add> });
<add> var hampster = Hampster.create();
<add> hampster.get('needsMoreBananas'); // true
<add> hampster.set('numBananas', 3);
<add> hampster.get('needsMoreBananas'); // false
<add> hampster.set('numBananas', 2);
<add> hampster.get('needsMoreBananas'); // true
<add> ```
<add>
<ide> @method computed.lt
<ide> @for Ember
<ide> @param {String} dependentKey
<ide> registerComputed('lt', function(dependentKey, value) {
<ide> });
<ide>
<ide> /**
<add> A computed property that which returns true if dependent property is
<add> less than or equal to the given value.
<add>
<add> Example
<add>
<add> ```javascript
<add> var Hampster = Ember.Object.extend({
<add> needsMoreBananas: Ember.computed.lte('numBananas', 3)
<add> });
<add> var hampster = Hampster.create();
<add> hampster.get('needsMoreBananas'); // true
<add> hampster.set('numBananas', 5);
<add> hampster.get('needsMoreBananas'); // false
<add> hampster.set('numBananas', 3);
<add> hampster.get('needsMoreBananas'); // true
<add> ```
<add>
<ide> @method computed.lte
<ide> @for Ember
<ide> @param {String} dependentKey
<ide> registerComputed('lte', function(dependentKey, value) {
<ide> });
<ide>
<ide> /**
<add> A computed property that which performs a logical `and` on the
<add> values of all the original values for dependent properties.
<add>
<add> Example
<add>
<add> ```javascript
<add> var Hampster = Ember.Object.extend({
<add> readyForCamp: Ember.computed.and('hasTent', 'hasBackpack')
<add> });
<add> var hampster = Hampster.create();
<add> hampster.get('readyForCamp'); // false
<add> hampster.set('hasTent', true);
<add> hampster.get('readyForCamp'); // false
<add> hampster.set('hasBackpack', true);
<add> hampster.get('readyForCamp'); // true
<add> ```
<add>
<ide> @method computed.and
<ide> @for Ember
<ide> @param {String} dependentKey, [dependentKey...]
<del> @return {Ember.ComputedProperty} computed property which peforms
<add> @return {Ember.ComputedProperty} computed property which performs
<ide> a logical `and` on the values of all the original values for properties.
<ide> */
<ide> registerComputedWithProperties('and', function(properties) {
<ide> registerComputedWithProperties('and', function(properties) {
<ide> });
<ide>
<ide> /**
<add> A computed property that which performs a logical `or` on the
<add> values of all the original values for dependent properties.
<add>
<add> Example
<add>
<add> ```javascript
<add> var Hampster = Ember.Object.extend({
<add> readyForRain: Ember.computed.or('hasJacket', 'hasUmbrella')
<add> });
<add> var hampster = Hampster.create();
<add> hampster.get('readyForRain'); // false
<add> hampster.set('hasJacket', true);
<add> hampster.get('readyForRain'); // true
<add> ```
<add>
<ide> @method computed.or
<ide> @for Ember
<ide> @param {String} dependentKey, [dependentKey...]
<del> @return {Ember.ComputedProperty} computed property which peforms
<add> @return {Ember.ComputedProperty} computed property which performs
<ide> a logical `or` on the values of all the original values for properties.
<ide> */
<ide> registerComputedWithProperties('or', function(properties) {
<ide> registerComputedWithProperties('or', function(properties) {
<ide> });
<ide>
<ide> /**
<add> A computed property that which returns the first truthy value
<add> of a given list of dependent properties.
<add>
<add> Example
<add>
<add> ```javascript
<add> var Hampster = Ember.Object.extend({
<add> hasClothes: Ember.computed.any('hat', 'shirt')
<add> });
<add> var hampster = Hampster.create();
<add> hampster.get('hasClothes'); // null
<add> hampster.set('shirt', 'Hawaiian Shirt');
<add> hampster.get('hasClothes'); // 'Hawaiian Shirt'
<add> ```
<add>
<ide> @method computed.any
<ide> @for Ember
<ide> @param {String} dependentKey, [dependentKey...]
<ide> registerComputedWithProperties('any', function(properties) {
<ide> });
<ide>
<ide> /**
<add> A computed property that which returns the first truthy value
<add> of a given list of dependent properties.
<add>
<add> Example
<add>
<add> ```javascript
<add> var Hampster = Ember.Object.extend({
<add> clothes: Ember.computed.map('hat', 'shirt')
<add> });
<add> var hampster = Hampster.create();
<add> hampster.get('clothes'); // [null, null]
<add> hampster.set('hat', 'Camp Hat');
<add> hampster.set('shirt', 'Camp Shirt');
<add> hampster.get('clothes'); // ['Camp Hat', 'Camp Shirt']
<add> ```
<add>
<ide> @method computed.map
<ide> @for Ember
<ide> @param {String} dependentKey, [dependentKey...]
<ide> Ember.computed.alias = function(dependentKey) {
<ide> };
<ide>
<ide> /**
<del> @method computed.oneWay
<del> @for Ember
<del> @param {String} dependentKey
<del> @return {Ember.ComputedProperty} computed property which creates an
<del> one way computed property to the original value for property.
<del>
<del> Where `computed.alias` aliases `get` and `set`, and allows for bidirectional
<add> Where `computed.alias` aliases `get` and `set`, and allows for bidirectional
<ide> data flow, `computed.oneWay` only provides an aliased `get`. The `set` will
<ide> not mutate the upstream property, rather causes the current property to
<ide> become the value set. This causes the downstream property to permentantly
<ide> diverge from the upstream property.
<ide>
<add> Example
<add>
<ide> ```javascript
<ide> User = Ember.Object.extend({
<ide> firstName: null,
<ide> Ember.computed.alias = function(dependentKey) {
<ide> user.get('firstName');
<ide> # 'Teddy'
<ide> ```
<add>
<add> @method computed.oneWay
<add> @for Ember
<add> @param {String} dependentKey
<add> @return {Ember.ComputedProperty} computed property which creates an
<add> one way computed property to the original value for property.
<ide> */
<ide> Ember.computed.oneWay = function(dependentKey) {
<ide> return Ember.computed(dependentKey, function() {
<ide> Ember.computed.oneWay = function(dependentKey) {
<ide>
<ide>
<ide> /**
<add> A computed property that which acts like a standard getter
<add> and setter, but defaults to the value from `defaultPath`.
<add>
<add> Example
<add>
<add> ```javascript
<add> var Hampster = Ember.Object.extend({
<add> wishList: Ember.computed.defaultTo('favoriteFood')
<add> });
<add> var hampster = Hampster.create({favoriteFood: 'Banana'});
<add> hampster.get('wishList'); // 'Banana'
<add> hampster.set('wishList', 'More Unit Tests');
<add> hampster.get('wishList'); // 'More Unit Tests'
<add> hampster.get('favoriteFood'); // 'Banana'
<add> ```
<add>
<ide> @method computed.defaultTo
<ide> @for Ember
<ide> @param {String} defaultPath | 1 |
Ruby | Ruby | avoid extra empty array allocation | 98c085357e87ee49aec27d270f18502f2a062bef | <ide><path>activerecord/lib/active_record/associations/preloader/association.rb
<ide> def associated_records_by_owner
<ide> owners_map = owners_by_key
<ide> owner_keys = owners_map.keys.compact
<ide>
<del> if klass.nil? || owner_keys.empty?
<del> records = []
<del> else
<add> # Each record may have multiple owners, and vice-versa
<add> records_by_owner = Hash[owners.map { |owner| [owner, []] }]
<add>
<add> if klass && owner_keys.any?
<ide> # Some databases impose a limit on the number of ids in a list (in Oracle it's 1000)
<ide> # Make several smaller queries if necessary or make one query if the adapter supports it
<ide> sliced = owner_keys.each_slice(klass.connection.in_clause_length || owner_keys.size)
<ide> records = sliced.flat_map { |slice| records_for(slice) }
<del> end
<ide>
<del> # Each record may have multiple owners, and vice-versa
<del> records_by_owner = Hash[owners.map { |owner| [owner, []] }]
<del> records.each do |record|
<del> owner_key = owner_id_for records, record
<add> records.each do |record|
<add> owner_key = owner_id_for records, record
<ide>
<del> owners_map[owner_key].each do |owner|
<del> records_by_owner[owner] << record
<add> owners_map[owner_key].each do |owner|
<add> records_by_owner[owner] << record
<add> end
<ide> end
<ide> end
<add>
<ide> records_by_owner
<ide> end
<ide> | 1 |
PHP | PHP | normalize all the line endings | ec0df100c5b97aeeb5e478e65ba5e5689365dd93 | <ide><path>src/Illuminate/Hashing/HashServiceProvider.php
<del><?php namespace Illuminate\Hashing;
<del>
<del>use Illuminate\Support\ServiceProvider;
<del>
<del>class HashServiceProvider extends ServiceProvider {
<del>
<del> /**
<del> * Indicates if loading of the provider is deferred.
<del> *
<del> * @var bool
<del> */
<del> protected $defer = true;
<del>
<del> /**
<del> * Register the service provider.
<del> *
<del> * @return void
<del> */
<del> public function register()
<del> {
<del> $this->app->singleton('hash', function() { return new BcryptHasher; });
<del> }
<del>
<del> /**
<del> * Get the services provided by the provider.
<del> *
<del> * @return array
<del> */
<del> public function provides()
<del> {
<del> return array('hash');
<del> }
<del>
<del>}
<add><?php namespace Illuminate\Hashing;
<add>
<add>use Illuminate\Support\ServiceProvider;
<add>
<add>class HashServiceProvider extends ServiceProvider {
<add>
<add> /**
<add> * Indicates if loading of the provider is deferred.
<add> *
<add> * @var bool
<add> */
<add> protected $defer = true;
<add>
<add> /**
<add> * Register the service provider.
<add> *
<add> * @return void
<add> */
<add> public function register()
<add> {
<add> $this->app->singleton('hash', function() { return new BcryptHasher; });
<add> }
<add>
<add> /**
<add> * Get the services provided by the provider.
<add> *
<add> * @return array
<add> */
<add> public function provides()
<add> {
<add> return array('hash');
<add> }
<add>
<add>}
<ide><path>src/Illuminate/Pagination/PaginationServiceProvider.php
<del><?php namespace Illuminate\Pagination;
<del>
<del>use Illuminate\Support\ServiceProvider;
<del>
<del>class PaginationServiceProvider extends ServiceProvider {
<del>
<del> /**
<del> * Register the service provider.
<del> *
<del> * @return void
<del> */
<del> public function register()
<del> {
<del> Paginator::currentPathResolver(function()
<del> {
<del> return $this->app['request']->url();
<del> });
<del>
<del> Paginator::currentPageResolver(function()
<del> {
<del> return $this->app['request']->input('page');
<del> });
<del> }
<del>
<del>}
<add><?php namespace Illuminate\Pagination;
<add>
<add>use Illuminate\Support\ServiceProvider;
<add>
<add>class PaginationServiceProvider extends ServiceProvider {
<add>
<add> /**
<add> * Register the service provider.
<add> *
<add> * @return void
<add> */
<add> public function register()
<add> {
<add> Paginator::currentPathResolver(function()
<add> {
<add> return $this->app['request']->url();
<add> });
<add>
<add> Paginator::currentPageResolver(function()
<add> {
<add> return $this->app['request']->input('page');
<add> });
<add> }
<add>
<add>}
<ide><path>src/Illuminate/Queue/Console/ListenCommand.php
<del><?php namespace Illuminate\Queue\Console;
<del>
<del>use Illuminate\Queue\Listener;
<del>use Illuminate\Console\Command;
<del>use Symfony\Component\Console\Input\InputOption;
<del>use Symfony\Component\Console\Input\InputArgument;
<del>
<del>class ListenCommand extends Command {
<del>
<del> /**
<del> * The console command name.
<del> *
<del> * @var string
<del> */
<del> protected $name = 'queue:listen';
<del>
<del> /**
<del> * The console command description.
<del> *
<del> * @var string
<del> */
<del> protected $description = 'Listen to a given queue';
<del>
<del> /**
<del> * The queue listener instance.
<del> *
<del> * @var \Illuminate\Queue\Listener
<del> */
<del> protected $listener;
<del>
<del> /**
<del> * Create a new queue listen command.
<del> *
<del> * @param \Illuminate\Queue\Listener $listener
<del> * @return void
<del> */
<del> public function __construct(Listener $listener)
<del> {
<del> parent::__construct();
<del>
<del> $this->listener = $listener;
<del> }
<del>
<del> /**
<del> * Execute the console command.
<del> *
<del> * @return void
<del> */
<del> public function fire()
<del> {
<del> $this->setListenerOptions();
<del>
<del> $delay = $this->input->getOption('delay');
<del>
<del> // The memory limit is the amount of memory we will allow the script to occupy
<del> // before killing it and letting a process manager restart it for us, which
<del> // is to protect us against any memory leaks that will be in the scripts.
<del> $memory = $this->input->getOption('memory');
<del>
<del> $connection = $this->input->getArgument('connection');
<del>
<del> $timeout = $this->input->getOption('timeout');
<del>
<del> // We need to get the right queue for the connection which is set in the queue
<del> // configuration file for the application. We will pull it based on the set
<del> // connection being run for the queue operation currently being executed.
<del> $queue = $this->getQueue($connection);
<del>
<del> $this->listener->listen(
<del> $connection, $queue, $delay, $memory, $timeout
<del> );
<del> }
<del>
<del> /**
<del> * Get the name of the queue connection to listen on.
<del> *
<del> * @param string $connection
<del> * @return string
<del> */
<del> protected function getQueue($connection)
<del> {
<del> if (is_null($connection))
<del> {
<del> $connection = $this->laravel['config']['queue.default'];
<del> }
<del>
<del> $queue = $this->laravel['config']->get("queue.connections.{$connection}.queue", 'default');
<del>
<del> return $this->input->getOption('queue') ?: $queue;
<del> }
<del>
<del> /**
<del> * Set the options on the queue listener.
<del> *
<del> * @return void
<del> */
<del> protected function setListenerOptions()
<del> {
<del> $this->listener->setEnvironment($this->laravel->environment());
<del>
<del> $this->listener->setSleep($this->option('sleep'));
<del>
<del> $this->listener->setMaxTries($this->option('tries'));
<del>
<del> $this->listener->setOutputHandler(function($type, $line)
<del> {
<del> $this->output->write($line);
<del> });
<del> }
<del>
<del> /**
<del> * Get the console command arguments.
<del> *
<del> * @return array
<del> */
<del> protected function getArguments()
<del> {
<del> return array(
<del> array('connection', InputArgument::OPTIONAL, 'The name of connection'),
<del> );
<del> }
<del>
<del> /**
<del> * Get the console command options.
<del> *
<del> * @return array
<del> */
<del> protected function getOptions()
<del> {
<del> return array(
<del> array('queue', null, InputOption::VALUE_OPTIONAL, 'The queue to listen on', null),
<del>
<del> array('delay', null, InputOption::VALUE_OPTIONAL, 'Amount of time to delay failed jobs', 0),
<del>
<del> array('memory', null, InputOption::VALUE_OPTIONAL, 'The memory limit in megabytes', 128),
<del>
<del> array('timeout', null, InputOption::VALUE_OPTIONAL, 'Seconds a job may run before timing out', 60),
<del>
<del> array('sleep', null, InputOption::VALUE_OPTIONAL, 'Seconds to wait before checking queue for jobs', 3),
<del>
<del> array('tries', null, InputOption::VALUE_OPTIONAL, 'Number of times to attempt a job before logging it failed', 0),
<del> );
<del> }
<del>
<del>}
<add><?php namespace Illuminate\Queue\Console;
<add>
<add>use Illuminate\Queue\Listener;
<add>use Illuminate\Console\Command;
<add>use Symfony\Component\Console\Input\InputOption;
<add>use Symfony\Component\Console\Input\InputArgument;
<add>
<add>class ListenCommand extends Command {
<add>
<add> /**
<add> * The console command name.
<add> *
<add> * @var string
<add> */
<add> protected $name = 'queue:listen';
<add>
<add> /**
<add> * The console command description.
<add> *
<add> * @var string
<add> */
<add> protected $description = 'Listen to a given queue';
<add>
<add> /**
<add> * The queue listener instance.
<add> *
<add> * @var \Illuminate\Queue\Listener
<add> */
<add> protected $listener;
<add>
<add> /**
<add> * Create a new queue listen command.
<add> *
<add> * @param \Illuminate\Queue\Listener $listener
<add> * @return void
<add> */
<add> public function __construct(Listener $listener)
<add> {
<add> parent::__construct();
<add>
<add> $this->listener = $listener;
<add> }
<add>
<add> /**
<add> * Execute the console command.
<add> *
<add> * @return void
<add> */
<add> public function fire()
<add> {
<add> $this->setListenerOptions();
<add>
<add> $delay = $this->input->getOption('delay');
<add>
<add> // The memory limit is the amount of memory we will allow the script to occupy
<add> // before killing it and letting a process manager restart it for us, which
<add> // is to protect us against any memory leaks that will be in the scripts.
<add> $memory = $this->input->getOption('memory');
<add>
<add> $connection = $this->input->getArgument('connection');
<add>
<add> $timeout = $this->input->getOption('timeout');
<add>
<add> // We need to get the right queue for the connection which is set in the queue
<add> // configuration file for the application. We will pull it based on the set
<add> // connection being run for the queue operation currently being executed.
<add> $queue = $this->getQueue($connection);
<add>
<add> $this->listener->listen(
<add> $connection, $queue, $delay, $memory, $timeout
<add> );
<add> }
<add>
<add> /**
<add> * Get the name of the queue connection to listen on.
<add> *
<add> * @param string $connection
<add> * @return string
<add> */
<add> protected function getQueue($connection)
<add> {
<add> if (is_null($connection))
<add> {
<add> $connection = $this->laravel['config']['queue.default'];
<add> }
<add>
<add> $queue = $this->laravel['config']->get("queue.connections.{$connection}.queue", 'default');
<add>
<add> return $this->input->getOption('queue') ?: $queue;
<add> }
<add>
<add> /**
<add> * Set the options on the queue listener.
<add> *
<add> * @return void
<add> */
<add> protected function setListenerOptions()
<add> {
<add> $this->listener->setEnvironment($this->laravel->environment());
<add>
<add> $this->listener->setSleep($this->option('sleep'));
<add>
<add> $this->listener->setMaxTries($this->option('tries'));
<add>
<add> $this->listener->setOutputHandler(function($type, $line)
<add> {
<add> $this->output->write($line);
<add> });
<add> }
<add>
<add> /**
<add> * Get the console command arguments.
<add> *
<add> * @return array
<add> */
<add> protected function getArguments()
<add> {
<add> return array(
<add> array('connection', InputArgument::OPTIONAL, 'The name of connection'),
<add> );
<add> }
<add>
<add> /**
<add> * Get the console command options.
<add> *
<add> * @return array
<add> */
<add> protected function getOptions()
<add> {
<add> return array(
<add> array('queue', null, InputOption::VALUE_OPTIONAL, 'The queue to listen on', null),
<add>
<add> array('delay', null, InputOption::VALUE_OPTIONAL, 'Amount of time to delay failed jobs', 0),
<add>
<add> array('memory', null, InputOption::VALUE_OPTIONAL, 'The memory limit in megabytes', 128),
<add>
<add> array('timeout', null, InputOption::VALUE_OPTIONAL, 'Seconds a job may run before timing out', 60),
<add>
<add> array('sleep', null, InputOption::VALUE_OPTIONAL, 'Seconds to wait before checking queue for jobs', 3),
<add>
<add> array('tries', null, InputOption::VALUE_OPTIONAL, 'Number of times to attempt a job before logging it failed', 0),
<add> );
<add> }
<add>
<add>}
<ide><path>src/Illuminate/Redis/RedisServiceProvider.php
<del><?php namespace Illuminate\Redis;
<del>
<del>use Illuminate\Support\ServiceProvider;
<del>
<del>class RedisServiceProvider extends ServiceProvider {
<del>
<del> /**
<del> * Indicates if loading of the provider is deferred.
<del> *
<del> * @var bool
<del> */
<del> protected $defer = true;
<del>
<del> /**
<del> * Register the service provider.
<del> *
<del> * @return void
<del> */
<del> public function register()
<del> {
<del> $this->app->singleton('redis', function($app)
<del> {
<del> return new Database($app['config']['database.redis']);
<del> });
<del> }
<del>
<del> /**
<del> * Get the services provided by the provider.
<del> *
<del> * @return array
<del> */
<del> public function provides()
<del> {
<del> return array('redis');
<del> }
<del>
<del>}
<add><?php namespace Illuminate\Redis;
<add>
<add>use Illuminate\Support\ServiceProvider;
<add>
<add>class RedisServiceProvider extends ServiceProvider {
<add>
<add> /**
<add> * Indicates if loading of the provider is deferred.
<add> *
<add> * @var bool
<add> */
<add> protected $defer = true;
<add>
<add> /**
<add> * Register the service provider.
<add> *
<add> * @return void
<add> */
<add> public function register()
<add> {
<add> $this->app->singleton('redis', function($app)
<add> {
<add> return new Database($app['config']['database.redis']);
<add> });
<add> }
<add>
<add> /**
<add> * Get the services provided by the provider.
<add> *
<add> * @return array
<add> */
<add> public function provides()
<add> {
<add> return array('redis');
<add> }
<add>
<add>}
<ide><path>src/Illuminate/Routing/Matching/HostValidator.php
<del><?php namespace Illuminate\Routing\Matching;
<del>
<del>use Illuminate\Http\Request;
<del>use Illuminate\Routing\Route;
<del>
<del>class HostValidator implements ValidatorInterface {
<del>
<del> /**
<del> * Validate a given rule against a route and request.
<del> *
<del> * @param \Illuminate\Routing\Route $route
<del> * @param \Illuminate\Http\Request $request
<del> * @return bool
<del> */
<del> public function matches(Route $route, Request $request)
<del> {
<del> if (is_null($route->getCompiled()->getHostRegex())) return true;
<del>
<del> return preg_match($route->getCompiled()->getHostRegex(), $request->getHost());
<del> }
<del>
<del>}
<add><?php namespace Illuminate\Routing\Matching;
<add>
<add>use Illuminate\Http\Request;
<add>use Illuminate\Routing\Route;
<add>
<add>class HostValidator implements ValidatorInterface {
<add>
<add> /**
<add> * Validate a given rule against a route and request.
<add> *
<add> * @param \Illuminate\Routing\Route $route
<add> * @param \Illuminate\Http\Request $request
<add> * @return bool
<add> */
<add> public function matches(Route $route, Request $request)
<add> {
<add> if (is_null($route->getCompiled()->getHostRegex())) return true;
<add>
<add> return preg_match($route->getCompiled()->getHostRegex(), $request->getHost());
<add> }
<add>
<add>}
<ide><path>src/Illuminate/Routing/Matching/MethodValidator.php
<del><?php namespace Illuminate\Routing\Matching;
<del>
<del>use Illuminate\Http\Request;
<del>use Illuminate\Routing\Route;
<del>
<del>class MethodValidator implements ValidatorInterface {
<del>
<del> /**
<del> * Validate a given rule against a route and request.
<del> *
<del> * @param \Illuminate\Routing\Route $route
<del> * @param \Illuminate\Http\Request $request
<del> * @return bool
<del> */
<del> public function matches(Route $route, Request $request)
<del> {
<del> return in_array($request->getMethod(), $route->methods());
<del> }
<del>
<del>}
<add><?php namespace Illuminate\Routing\Matching;
<add>
<add>use Illuminate\Http\Request;
<add>use Illuminate\Routing\Route;
<add>
<add>class MethodValidator implements ValidatorInterface {
<add>
<add> /**
<add> * Validate a given rule against a route and request.
<add> *
<add> * @param \Illuminate\Routing\Route $route
<add> * @param \Illuminate\Http\Request $request
<add> * @return bool
<add> */
<add> public function matches(Route $route, Request $request)
<add> {
<add> return in_array($request->getMethod(), $route->methods());
<add> }
<add>
<add>}
<ide><path>src/Illuminate/Routing/Matching/SchemeValidator.php
<del><?php namespace Illuminate\Routing\Matching;
<del>
<del>use Illuminate\Http\Request;
<del>use Illuminate\Routing\Route;
<del>
<del>class SchemeValidator implements ValidatorInterface {
<del>
<del> /**
<del> * Validate a given rule against a route and request.
<del> *
<del> * @param \Illuminate\Routing\Route $route
<del> * @param \Illuminate\Http\Request $request
<del> * @return bool
<del> */
<del> public function matches(Route $route, Request $request)
<del> {
<del> if ($route->httpOnly())
<del> {
<del> return ! $request->secure();
<del> }
<del> elseif ($route->secure())
<del> {
<del> return $request->secure();
<del> }
<del>
<del> return true;
<del> }
<del>
<del>}
<add><?php namespace Illuminate\Routing\Matching;
<add>
<add>use Illuminate\Http\Request;
<add>use Illuminate\Routing\Route;
<add>
<add>class SchemeValidator implements ValidatorInterface {
<add>
<add> /**
<add> * Validate a given rule against a route and request.
<add> *
<add> * @param \Illuminate\Routing\Route $route
<add> * @param \Illuminate\Http\Request $request
<add> * @return bool
<add> */
<add> public function matches(Route $route, Request $request)
<add> {
<add> if ($route->httpOnly())
<add> {
<add> return ! $request->secure();
<add> }
<add> elseif ($route->secure())
<add> {
<add> return $request->secure();
<add> }
<add>
<add> return true;
<add> }
<add>
<add>}
<ide><path>src/Illuminate/Routing/Matching/UriValidator.php
<del><?php namespace Illuminate\Routing\Matching;
<del>
<del>use Illuminate\Http\Request;
<del>use Illuminate\Routing\Route;
<del>
<del>class UriValidator implements ValidatorInterface {
<del>
<del> /**
<del> * Validate a given rule against a route and request.
<del> *
<del> * @param \Illuminate\Routing\Route $route
<del> * @param \Illuminate\Http\Request $request
<del> * @return bool
<del> */
<del> public function matches(Route $route, Request $request)
<del> {
<del> $path = $request->path() == '/' ? '/' : '/'.$request->path();
<del>
<del> return preg_match($route->getCompiled()->getRegex(), rawurldecode($path));
<del> }
<del>
<del>}
<add><?php namespace Illuminate\Routing\Matching;
<add>
<add>use Illuminate\Http\Request;
<add>use Illuminate\Routing\Route;
<add>
<add>class UriValidator implements ValidatorInterface {
<add>
<add> /**
<add> * Validate a given rule against a route and request.
<add> *
<add> * @param \Illuminate\Routing\Route $route
<add> * @param \Illuminate\Http\Request $request
<add> * @return bool
<add> */
<add> public function matches(Route $route, Request $request)
<add> {
<add> $path = $request->path() == '/' ? '/' : '/'.$request->path();
<add>
<add> return preg_match($route->getCompiled()->getRegex(), rawurldecode($path));
<add> }
<add>
<add>}
<ide><path>src/Illuminate/Routing/Matching/ValidatorInterface.php
<del><?php namespace Illuminate\Routing\Matching;
<del>
<del>use Illuminate\Http\Request;
<del>use Illuminate\Routing\Route;
<del>
<del>interface ValidatorInterface {
<del>
<del> /**
<del> * Validate a given rule against a route and request.
<del> *
<del> * @param \Illuminate\Routing\Route $route
<del> * @param \Illuminate\Http\Request $request
<del> * @return bool
<del> */
<del> public function matches(Route $route, Request $request);
<del>
<del>}
<add><?php namespace Illuminate\Routing\Matching;
<add>
<add>use Illuminate\Http\Request;
<add>use Illuminate\Routing\Route;
<add>
<add>interface ValidatorInterface {
<add>
<add> /**
<add> * Validate a given rule against a route and request.
<add> *
<add> * @param \Illuminate\Routing\Route $route
<add> * @param \Illuminate\Http\Request $request
<add> * @return bool
<add> */
<add> public function matches(Route $route, Request $request);
<add>
<add>}
<ide><path>src/Illuminate/Session/SessionManager.php
<del><?php namespace Illuminate\Session;
<del>
<del>use Illuminate\Support\Manager;
<del>use Symfony\Component\HttpFoundation\Session\Storage\Handler\NullSessionHandler;
<del>
<del>class SessionManager extends Manager {
<del>
<del> /**
<del> * Call a custom driver creator.
<del> *
<del> * @param string $driver
<del> * @return mixed
<del> */
<del> protected function callCustomCreator($driver)
<del> {
<del> return $this->buildSession(parent::callCustomCreator($driver));
<del> }
<del>
<del> /**
<del> * Create an instance of the "array" session driver.
<del> *
<del> * @return \Illuminate\Session\Store
<del> */
<del> protected function createArrayDriver()
<del> {
<del> return $this->buildSession(new NullSessionHandler);
<del> }
<del>
<del> /**
<del> * Create an instance of the "cookie" session driver.
<del> *
<del> * @return \Illuminate\Session\Store
<del> */
<del> protected function createCookieDriver()
<del> {
<del> $lifetime = $this->app['config']['session.lifetime'];
<del>
<del> return $this->buildSession(new CookieSessionHandler($this->app['cookie'], $lifetime));
<del> }
<del>
<del> /**
<del> * Create an instance of the file session driver.
<del> *
<del> * @return \Illuminate\Session\Store
<del> */
<del> protected function createFileDriver()
<del> {
<del> return $this->createNativeDriver();
<del> }
<del>
<del> /**
<del> * Create an instance of the file session driver.
<del> *
<del> * @return \Illuminate\Session\Store
<del> */
<del> protected function createNativeDriver()
<del> {
<del> $path = $this->app['config']['session.files'];
<del>
<del> return $this->buildSession(new FileSessionHandler($this->app['files'], $path));
<del> }
<del>
<del> /**
<del> * Create an instance of the database session driver.
<del> *
<del> * @return \Illuminate\Session\Store
<del> */
<del> protected function createDatabaseDriver()
<del> {
<del> $connection = $this->getDatabaseConnection();
<del>
<del> $table = $this->app['config']['session.table'];
<del>
<del> return $this->buildSession(new DatabaseSessionHandler($connection, $table));
<del> }
<del>
<del> /**
<del> * Get the database connection for the database driver.
<del> *
<del> * @return \Illuminate\Database\Connection
<del> */
<del> protected function getDatabaseConnection()
<del> {
<del> $connection = $this->app['config']['session.connection'];
<del>
<del> return $this->app['db']->connection($connection);
<del> }
<del>
<del> /**
<del> * Create an instance of the APC session driver.
<del> *
<del> * @return \Illuminate\Session\Store
<del> */
<del> protected function createApcDriver()
<del> {
<del> return $this->createCacheBased('apc');
<del> }
<del>
<del> /**
<del> * Create an instance of the Memcached session driver.
<del> *
<del> * @return \Illuminate\Session\Store
<del> */
<del> protected function createMemcachedDriver()
<del> {
<del> return $this->createCacheBased('memcached');
<del> }
<del>
<del> /**
<del> * Create an instance of the Wincache session driver.
<del> *
<del> * @return \Illuminate\Session\Store
<del> */
<del> protected function createWincacheDriver()
<del> {
<del> return $this->createCacheBased('wincache');
<del> }
<del>
<del> /**
<del> * Create an instance of the Redis session driver.
<del> *
<del> * @return \Illuminate\Session\Store
<del> */
<del> protected function createRedisDriver()
<del> {
<del> $handler = $this->createCacheHandler('redis');
<del>
<del> $handler->getCache()->getStore()->setConnection($this->app['config']['session.connection']);
<del>
<del> return $this->buildSession($handler);
<del> }
<del>
<del> /**
<del> * Create an instance of a cache driven driver.
<del> *
<del> * @param string $driver
<del> * @return \Illuminate\Session\Store
<del> */
<del> protected function createCacheBased($driver)
<del> {
<del> return $this->buildSession($this->createCacheHandler($driver));
<del> }
<del>
<del> /**
<del> * Create the cache based session handler instance.
<del> *
<del> * @param string $driver
<del> * @return \Illuminate\Session\CacheBasedSessionHandler
<del> */
<del> protected function createCacheHandler($driver)
<del> {
<del> $minutes = $this->app['config']['session.lifetime'];
<del>
<del> return new CacheBasedSessionHandler($this->app['cache']->driver($driver), $minutes);
<del> }
<del>
<del> /**
<del> * Build the session instance.
<del> *
<del> * @param \SessionHandlerInterface $handler
<del> * @return \Illuminate\Session\Store
<del> */
<del> protected function buildSession($handler)
<del> {
<del> if ($this->app['config']['session.encrypt'])
<del> {
<del> return new EncryptedStore(
<del> $this->app['config']['session.cookie'], $handler, $this->app['encrypter']
<del> );
<del> }
<del> else
<del> {
<del> return new Store($this->app['config']['session.cookie'], $handler);
<del> }
<del> }
<del>
<del> /**
<del> * Get the session configuration.
<del> *
<del> * @return array
<del> */
<del> public function getSessionConfig()
<del> {
<del> return $this->app['config']['session'];
<del> }
<del>
<del> /**
<del> * Get the default session driver name.
<del> *
<del> * @return string
<del> */
<del> public function getDefaultDriver()
<del> {
<del> return $this->app['config']['session.driver'];
<del> }
<del>
<del> /**
<del> * Set the default session driver name.
<del> *
<del> * @param string $name
<del> * @return void
<del> */
<del> public function setDefaultDriver($name)
<del> {
<del> $this->app['config']['session.driver'] = $name;
<del> }
<del>
<del>}
<add><?php namespace Illuminate\Session;
<add>
<add>use Illuminate\Support\Manager;
<add>use Symfony\Component\HttpFoundation\Session\Storage\Handler\NullSessionHandler;
<add>
<add>class SessionManager extends Manager {
<add>
<add> /**
<add> * Call a custom driver creator.
<add> *
<add> * @param string $driver
<add> * @return mixed
<add> */
<add> protected function callCustomCreator($driver)
<add> {
<add> return $this->buildSession(parent::callCustomCreator($driver));
<add> }
<add>
<add> /**
<add> * Create an instance of the "array" session driver.
<add> *
<add> * @return \Illuminate\Session\Store
<add> */
<add> protected function createArrayDriver()
<add> {
<add> return $this->buildSession(new NullSessionHandler);
<add> }
<add>
<add> /**
<add> * Create an instance of the "cookie" session driver.
<add> *
<add> * @return \Illuminate\Session\Store
<add> */
<add> protected function createCookieDriver()
<add> {
<add> $lifetime = $this->app['config']['session.lifetime'];
<add>
<add> return $this->buildSession(new CookieSessionHandler($this->app['cookie'], $lifetime));
<add> }
<add>
<add> /**
<add> * Create an instance of the file session driver.
<add> *
<add> * @return \Illuminate\Session\Store
<add> */
<add> protected function createFileDriver()
<add> {
<add> return $this->createNativeDriver();
<add> }
<add>
<add> /**
<add> * Create an instance of the file session driver.
<add> *
<add> * @return \Illuminate\Session\Store
<add> */
<add> protected function createNativeDriver()
<add> {
<add> $path = $this->app['config']['session.files'];
<add>
<add> return $this->buildSession(new FileSessionHandler($this->app['files'], $path));
<add> }
<add>
<add> /**
<add> * Create an instance of the database session driver.
<add> *
<add> * @return \Illuminate\Session\Store
<add> */
<add> protected function createDatabaseDriver()
<add> {
<add> $connection = $this->getDatabaseConnection();
<add>
<add> $table = $this->app['config']['session.table'];
<add>
<add> return $this->buildSession(new DatabaseSessionHandler($connection, $table));
<add> }
<add>
<add> /**
<add> * Get the database connection for the database driver.
<add> *
<add> * @return \Illuminate\Database\Connection
<add> */
<add> protected function getDatabaseConnection()
<add> {
<add> $connection = $this->app['config']['session.connection'];
<add>
<add> return $this->app['db']->connection($connection);
<add> }
<add>
<add> /**
<add> * Create an instance of the APC session driver.
<add> *
<add> * @return \Illuminate\Session\Store
<add> */
<add> protected function createApcDriver()
<add> {
<add> return $this->createCacheBased('apc');
<add> }
<add>
<add> /**
<add> * Create an instance of the Memcached session driver.
<add> *
<add> * @return \Illuminate\Session\Store
<add> */
<add> protected function createMemcachedDriver()
<add> {
<add> return $this->createCacheBased('memcached');
<add> }
<add>
<add> /**
<add> * Create an instance of the Wincache session driver.
<add> *
<add> * @return \Illuminate\Session\Store
<add> */
<add> protected function createWincacheDriver()
<add> {
<add> return $this->createCacheBased('wincache');
<add> }
<add>
<add> /**
<add> * Create an instance of the Redis session driver.
<add> *
<add> * @return \Illuminate\Session\Store
<add> */
<add> protected function createRedisDriver()
<add> {
<add> $handler = $this->createCacheHandler('redis');
<add>
<add> $handler->getCache()->getStore()->setConnection($this->app['config']['session.connection']);
<add>
<add> return $this->buildSession($handler);
<add> }
<add>
<add> /**
<add> * Create an instance of a cache driven driver.
<add> *
<add> * @param string $driver
<add> * @return \Illuminate\Session\Store
<add> */
<add> protected function createCacheBased($driver)
<add> {
<add> return $this->buildSession($this->createCacheHandler($driver));
<add> }
<add>
<add> /**
<add> * Create the cache based session handler instance.
<add> *
<add> * @param string $driver
<add> * @return \Illuminate\Session\CacheBasedSessionHandler
<add> */
<add> protected function createCacheHandler($driver)
<add> {
<add> $minutes = $this->app['config']['session.lifetime'];
<add>
<add> return new CacheBasedSessionHandler($this->app['cache']->driver($driver), $minutes);
<add> }
<add>
<add> /**
<add> * Build the session instance.
<add> *
<add> * @param \SessionHandlerInterface $handler
<add> * @return \Illuminate\Session\Store
<add> */
<add> protected function buildSession($handler)
<add> {
<add> if ($this->app['config']['session.encrypt'])
<add> {
<add> return new EncryptedStore(
<add> $this->app['config']['session.cookie'], $handler, $this->app['encrypter']
<add> );
<add> }
<add> else
<add> {
<add> return new Store($this->app['config']['session.cookie'], $handler);
<add> }
<add> }
<add>
<add> /**
<add> * Get the session configuration.
<add> *
<add> * @return array
<add> */
<add> public function getSessionConfig()
<add> {
<add> return $this->app['config']['session'];
<add> }
<add>
<add> /**
<add> * Get the default session driver name.
<add> *
<add> * @return string
<add> */
<add> public function getDefaultDriver()
<add> {
<add> return $this->app['config']['session.driver'];
<add> }
<add>
<add> /**
<add> * Set the default session driver name.
<add> *
<add> * @param string $name
<add> * @return void
<add> */
<add> public function setDefaultDriver($name)
<add> {
<add> $this->app['config']['session.driver'] = $name;
<add> }
<add>
<add>}
<ide><path>src/Illuminate/Session/SessionServiceProvider.php
<del><?php namespace Illuminate\Session;
<del>
<del>use Illuminate\Support\ServiceProvider;
<del>
<del>class SessionServiceProvider extends ServiceProvider {
<del>
<del> /**
<del> * Register the service provider.
<del> *
<del> * @return void
<del> */
<del> public function register()
<del> {
<del> $this->registerSessionManager();
<del>
<del> $this->registerSessionDriver();
<del>
<del> $this->app->singleton('Illuminate\Session\Middleware\StartSession');
<del> }
<del>
<del> /**
<del> * Register the session manager instance.
<del> *
<del> * @return void
<del> */
<del> protected function registerSessionManager()
<del> {
<del> $this->app->singleton('session', function($app)
<del> {
<del> return new SessionManager($app);
<del> });
<del> }
<del>
<del> /**
<del> * Register the session driver instance.
<del> *
<del> * @return void
<del> */
<del> protected function registerSessionDriver()
<del> {
<del> $this->app->singleton('session.store', function($app)
<del> {
<del> // First, we will create the session manager which is responsible for the
<del> // creation of the various session drivers when they are needed by the
<del> // application instance, and will resolve them on a lazy load basis.
<del> $manager = $app['session'];
<del>
<del> return $manager->driver();
<del> });
<del> }
<del>
<del>}
<add><?php namespace Illuminate\Session;
<add>
<add>use Illuminate\Support\ServiceProvider;
<add>
<add>class SessionServiceProvider extends ServiceProvider {
<add>
<add> /**
<add> * Register the service provider.
<add> *
<add> * @return void
<add> */
<add> public function register()
<add> {
<add> $this->registerSessionManager();
<add>
<add> $this->registerSessionDriver();
<add>
<add> $this->app->singleton('Illuminate\Session\Middleware\StartSession');
<add> }
<add>
<add> /**
<add> * Register the session manager instance.
<add> *
<add> * @return void
<add> */
<add> protected function registerSessionManager()
<add> {
<add> $this->app->singleton('session', function($app)
<add> {
<add> return new SessionManager($app);
<add> });
<add> }
<add>
<add> /**
<add> * Register the session driver instance.
<add> *
<add> * @return void
<add> */
<add> protected function registerSessionDriver()
<add> {
<add> $this->app->singleton('session.store', function($app)
<add> {
<add> // First, we will create the session manager which is responsible for the
<add> // creation of the various session drivers when they are needed by the
<add> // application instance, and will resolve them on a lazy load basis.
<add> $manager = $app['session'];
<add>
<add> return $manager->driver();
<add> });
<add> }
<add>
<add>}
<ide><path>src/Illuminate/Support/Facades/App.php
<del><?php namespace Illuminate\Support\Facades;
<del>
<del>/**
<del> * @see \Illuminate\Foundation\Application
<del> */
<del>class App extends Facade {
<del>
<del> /**
<del> * Get the registered name of the component.
<del> *
<del> * @return string
<del> */
<del> protected static function getFacadeAccessor() { return 'app'; }
<del>
<del>}
<add><?php namespace Illuminate\Support\Facades;
<add>
<add>/**
<add> * @see \Illuminate\Foundation\Application
<add> */
<add>class App extends Facade {
<add>
<add> /**
<add> * Get the registered name of the component.
<add> *
<add> * @return string
<add> */
<add> protected static function getFacadeAccessor() { return 'app'; }
<add>
<add>}
<ide><path>src/Illuminate/Support/Facades/Artisan.php
<del><?php namespace Illuminate\Support\Facades;
<del>
<del>/**
<del> * @see \Illuminate\Foundation\Artisan
<del> */
<del>class Artisan extends Facade {
<del>
<del> /**
<del> * Get the registered name of the component.
<del> *
<del> * @return string
<del> */
<del> protected static function getFacadeAccessor() { return 'Illuminate\Contracts\Console\Kernel'; }
<del>
<del>}
<add><?php namespace Illuminate\Support\Facades;
<add>
<add>/**
<add> * @see \Illuminate\Foundation\Artisan
<add> */
<add>class Artisan extends Facade {
<add>
<add> /**
<add> * Get the registered name of the component.
<add> *
<add> * @return string
<add> */
<add> protected static function getFacadeAccessor() { return 'Illuminate\Contracts\Console\Kernel'; }
<add>
<add>}
<ide><path>src/Illuminate/Support/Facades/Auth.php
<del><?php namespace Illuminate\Support\Facades;
<del>
<del>/**
<del> * @see \Illuminate\Auth\AuthManager
<del> * @see \Illuminate\Auth\Guard
<del> */
<del>class Auth extends Facade {
<del>
<del> /**
<del> * Get the registered name of the component.
<del> *
<del> * @return string
<del> */
<del> protected static function getFacadeAccessor() { return 'auth'; }
<del>
<del>}
<add><?php namespace Illuminate\Support\Facades;
<add>
<add>/**
<add> * @see \Illuminate\Auth\AuthManager
<add> * @see \Illuminate\Auth\Guard
<add> */
<add>class Auth extends Facade {
<add>
<add> /**
<add> * Get the registered name of the component.
<add> *
<add> * @return string
<add> */
<add> protected static function getFacadeAccessor() { return 'auth'; }
<add>
<add>}
<ide><path>src/Illuminate/Support/Facades/Cache.php
<del><?php namespace Illuminate\Support\Facades;
<del>
<del>/**
<del> * @see \Illuminate\Cache\CacheManager
<del> * @see \Illuminate\Cache\Repository
<del> */
<del>class Cache extends Facade {
<del>
<del> /**
<del> * Get the registered name of the component.
<del> *
<del> * @return string
<del> */
<del> protected static function getFacadeAccessor() { return 'cache'; }
<del>
<del>}
<add><?php namespace Illuminate\Support\Facades;
<add>
<add>/**
<add> * @see \Illuminate\Cache\CacheManager
<add> * @see \Illuminate\Cache\Repository
<add> */
<add>class Cache extends Facade {
<add>
<add> /**
<add> * Get the registered name of the component.
<add> *
<add> * @return string
<add> */
<add> protected static function getFacadeAccessor() { return 'cache'; }
<add>
<add>}
<ide><path>src/Illuminate/Support/Facades/Config.php
<del><?php namespace Illuminate\Support\Facades;
<del>
<del>/**
<del> * @see \Illuminate\Config\Repository
<del> */
<del>class Config extends Facade {
<del>
<del> /**
<del> * Get the registered name of the component.
<del> *
<del> * @return string
<del> */
<del> protected static function getFacadeAccessor() { return 'config'; }
<del>
<del>}
<add><?php namespace Illuminate\Support\Facades;
<add>
<add>/**
<add> * @see \Illuminate\Config\Repository
<add> */
<add>class Config extends Facade {
<add>
<add> /**
<add> * Get the registered name of the component.
<add> *
<add> * @return string
<add> */
<add> protected static function getFacadeAccessor() { return 'config'; }
<add>
<add>}
<ide><path>src/Illuminate/Support/Facades/Cookie.php
<del><?php namespace Illuminate\Support\Facades;
<del>
<del>/**
<del> * @see \Illuminate\Cookie\CookieJar
<del> */
<del>class Cookie extends Facade {
<del>
<del> /**
<del> * Determine if a cookie exists on the request.
<del> *
<del> * @param string $key
<del> * @return bool
<del> */
<del> public static function has($key)
<del> {
<del> return ! is_null(static::$app['request']->cookie($key, null));
<del> }
<del>
<del> /**
<del> * Retrieve a cookie from the request.
<del> *
<del> * @param string $key
<del> * @param mixed $default
<del> * @return string
<del> */
<del> public static function get($key = null, $default = null)
<del> {
<del> return static::$app['request']->cookie($key, $default);
<del> }
<del>
<del> /**
<del> * Get the registered name of the component.
<del> *
<del> * @return string
<del> */
<del> protected static function getFacadeAccessor() { return 'cookie'; }
<del>
<del>}
<add><?php namespace Illuminate\Support\Facades;
<add>
<add>/**
<add> * @see \Illuminate\Cookie\CookieJar
<add> */
<add>class Cookie extends Facade {
<add>
<add> /**
<add> * Determine if a cookie exists on the request.
<add> *
<add> * @param string $key
<add> * @return bool
<add> */
<add> public static function has($key)
<add> {
<add> return ! is_null(static::$app['request']->cookie($key, null));
<add> }
<add>
<add> /**
<add> * Retrieve a cookie from the request.
<add> *
<add> * @param string $key
<add> * @param mixed $default
<add> * @return string
<add> */
<add> public static function get($key = null, $default = null)
<add> {
<add> return static::$app['request']->cookie($key, $default);
<add> }
<add>
<add> /**
<add> * Get the registered name of the component.
<add> *
<add> * @return string
<add> */
<add> protected static function getFacadeAccessor() { return 'cookie'; }
<add>
<add>}
<ide><path>src/Illuminate/Support/Facades/Crypt.php
<del><?php namespace Illuminate\Support\Facades;
<del>
<del>/**
<del> * @see \Illuminate\Encryption\Encrypter
<del> */
<del>class Crypt extends Facade {
<del>
<del> /**
<del> * Get the registered name of the component.
<del> *
<del> * @return string
<del> */
<del> protected static function getFacadeAccessor() { return 'encrypter'; }
<del>
<del>}
<add><?php namespace Illuminate\Support\Facades;
<add>
<add>/**
<add> * @see \Illuminate\Encryption\Encrypter
<add> */
<add>class Crypt extends Facade {
<add>
<add> /**
<add> * Get the registered name of the component.
<add> *
<add> * @return string
<add> */
<add> protected static function getFacadeAccessor() { return 'encrypter'; }
<add>
<add>}
<ide><path>src/Illuminate/Support/Facades/DB.php
<del><?php namespace Illuminate\Support\Facades;
<del>
<del>/**
<del> * @see \Illuminate\Database\DatabaseManager
<del> * @see \Illuminate\Database\Connection
<del> */
<del>class DB extends Facade {
<del>
<del> /**
<del> * Get the registered name of the component.
<del> *
<del> * @return string
<del> */
<del> protected static function getFacadeAccessor() { return 'db'; }
<del>
<del>}
<add><?php namespace Illuminate\Support\Facades;
<add>
<add>/**
<add> * @see \Illuminate\Database\DatabaseManager
<add> * @see \Illuminate\Database\Connection
<add> */
<add>class DB extends Facade {
<add>
<add> /**
<add> * Get the registered name of the component.
<add> *
<add> * @return string
<add> */
<add> protected static function getFacadeAccessor() { return 'db'; }
<add>
<add>}
<ide><path>src/Illuminate/Support/Facades/Event.php
<del><?php namespace Illuminate\Support\Facades;
<del>
<del>/**
<del> * @see \Illuminate\Events\Dispatcher
<del> */
<del>class Event extends Facade {
<del>
<del> /**
<del> * Get the registered name of the component.
<del> *
<del> * @return string
<del> */
<del> protected static function getFacadeAccessor() { return 'events'; }
<del>
<del>}
<add><?php namespace Illuminate\Support\Facades;
<add>
<add>/**
<add> * @see \Illuminate\Events\Dispatcher
<add> */
<add>class Event extends Facade {
<add>
<add> /**
<add> * Get the registered name of the component.
<add> *
<add> * @return string
<add> */
<add> protected static function getFacadeAccessor() { return 'events'; }
<add>
<add>}
<ide><path>src/Illuminate/Support/Facades/File.php
<del><?php namespace Illuminate\Support\Facades;
<del>
<del>/**
<del> * @see \Illuminate\Filesystem\Filesystem
<del> */
<del>class File extends Facade {
<del>
<del> /**
<del> * Get the registered name of the component.
<del> *
<del> * @return string
<del> */
<del> protected static function getFacadeAccessor() { return 'files'; }
<del>
<del>}
<add><?php namespace Illuminate\Support\Facades;
<add>
<add>/**
<add> * @see \Illuminate\Filesystem\Filesystem
<add> */
<add>class File extends Facade {
<add>
<add> /**
<add> * Get the registered name of the component.
<add> *
<add> * @return string
<add> */
<add> protected static function getFacadeAccessor() { return 'files'; }
<add>
<add>}
<ide><path>src/Illuminate/Support/Facades/Hash.php
<del><?php namespace Illuminate\Support\Facades;
<del>
<del>/**
<del> * @see \Illuminate\Hashing\BcryptHasher
<del> */
<del>class Hash extends Facade {
<del>
<del> /**
<del> * Get the registered name of the component.
<del> *
<del> * @return string
<del> */
<del> protected static function getFacadeAccessor() { return 'hash'; }
<del>
<del>}
<add><?php namespace Illuminate\Support\Facades;
<add>
<add>/**
<add> * @see \Illuminate\Hashing\BcryptHasher
<add> */
<add>class Hash extends Facade {
<add>
<add> /**
<add> * Get the registered name of the component.
<add> *
<add> * @return string
<add> */
<add> protected static function getFacadeAccessor() { return 'hash'; }
<add>
<add>}
<ide><path>src/Illuminate/Support/Facades/Input.php
<del><?php namespace Illuminate\Support\Facades;
<del>
<del>/**
<del> * @see \Illuminate\Http\Request
<del> */
<del>class Input extends Facade {
<del>
<del> /**
<del> * Get an item from the input data.
<del> *
<del> * This method is used for all request verbs (GET, POST, PUT, and DELETE)
<del> *
<del> * @param string $key
<del> * @param mixed $default
<del> * @return mixed
<del> */
<del> public static function get($key = null, $default = null)
<del> {
<del> return static::$app['request']->input($key, $default);
<del> }
<del>
<del> /**
<del> * Get the registered name of the component.
<del> *
<del> * @return string
<del> */
<del> protected static function getFacadeAccessor() { return 'request'; }
<del>
<del>}
<add><?php namespace Illuminate\Support\Facades;
<add>
<add>/**
<add> * @see \Illuminate\Http\Request
<add> */
<add>class Input extends Facade {
<add>
<add> /**
<add> * Get an item from the input data.
<add> *
<add> * This method is used for all request verbs (GET, POST, PUT, and DELETE)
<add> *
<add> * @param string $key
<add> * @param mixed $default
<add> * @return mixed
<add> */
<add> public static function get($key = null, $default = null)
<add> {
<add> return static::$app['request']->input($key, $default);
<add> }
<add>
<add> /**
<add> * Get the registered name of the component.
<add> *
<add> * @return string
<add> */
<add> protected static function getFacadeAccessor() { return 'request'; }
<add>
<add>}
<ide><path>src/Illuminate/Support/Facades/Lang.php
<del><?php namespace Illuminate\Support\Facades;
<del>
<del>/**
<del> * @see \Illuminate\Translation\Translator
<del> */
<del>class Lang extends Facade {
<del>
<del> /**
<del> * Get the registered name of the component.
<del> *
<del> * @return string
<del> */
<del> protected static function getFacadeAccessor() { return 'translator'; }
<del>
<del>}
<add><?php namespace Illuminate\Support\Facades;
<add>
<add>/**
<add> * @see \Illuminate\Translation\Translator
<add> */
<add>class Lang extends Facade {
<add>
<add> /**
<add> * Get the registered name of the component.
<add> *
<add> * @return string
<add> */
<add> protected static function getFacadeAccessor() { return 'translator'; }
<add>
<add>}
<ide><path>src/Illuminate/Support/Facades/Log.php
<del><?php namespace Illuminate\Support\Facades;
<del>
<del>/**
<del> * @see \Illuminate\Log\Writer
<del> */
<del>class Log extends Facade {
<del>
<del> /**
<del> * Get the registered name of the component.
<del> *
<del> * @return string
<del> */
<del> protected static function getFacadeAccessor() { return 'log'; }
<del>
<del>}
<add><?php namespace Illuminate\Support\Facades;
<add>
<add>/**
<add> * @see \Illuminate\Log\Writer
<add> */
<add>class Log extends Facade {
<add>
<add> /**
<add> * Get the registered name of the component.
<add> *
<add> * @return string
<add> */
<add> protected static function getFacadeAccessor() { return 'log'; }
<add>
<add>}
<ide><path>src/Illuminate/Support/Facades/Mail.php
<del><?php namespace Illuminate\Support\Facades;
<del>
<del>/**
<del> * @see \Illuminate\Mail\Mailer
<del> */
<del>class Mail extends Facade {
<del>
<del> /**
<del> * Get the registered name of the component.
<del> *
<del> * @return string
<del> */
<del> protected static function getFacadeAccessor() { return 'mailer'; }
<del>
<del>}
<add><?php namespace Illuminate\Support\Facades;
<add>
<add>/**
<add> * @see \Illuminate\Mail\Mailer
<add> */
<add>class Mail extends Facade {
<add>
<add> /**
<add> * Get the registered name of the component.
<add> *
<add> * @return string
<add> */
<add> protected static function getFacadeAccessor() { return 'mailer'; }
<add>
<add>}
<ide><path>src/Illuminate/Support/Facades/Redirect.php
<del><?php namespace Illuminate\Support\Facades;
<del>
<del>/**
<del> * @see \Illuminate\Routing\Redirector
<del> */
<del>class Redirect extends Facade {
<del>
<del> /**
<del> * Get the registered name of the component.
<del> *
<del> * @return string
<del> */
<del> protected static function getFacadeAccessor() { return 'redirect'; }
<del>
<del>}
<add><?php namespace Illuminate\Support\Facades;
<add>
<add>/**
<add> * @see \Illuminate\Routing\Redirector
<add> */
<add>class Redirect extends Facade {
<add>
<add> /**
<add> * Get the registered name of the component.
<add> *
<add> * @return string
<add> */
<add> protected static function getFacadeAccessor() { return 'redirect'; }
<add>
<add>}
<ide><path>src/Illuminate/Support/Facades/Redis.php
<del><?php namespace Illuminate\Support\Facades;
<del>
<del>/**
<del> * @see \Illuminate\Redis\Database
<del> */
<del>class Redis extends Facade {
<del>
<del> /**
<del> * Get the registered name of the component.
<del> *
<del> * @return string
<del> */
<del> protected static function getFacadeAccessor() { return 'redis'; }
<del>
<del>}
<add><?php namespace Illuminate\Support\Facades;
<add>
<add>/**
<add> * @see \Illuminate\Redis\Database
<add> */
<add>class Redis extends Facade {
<add>
<add> /**
<add> * Get the registered name of the component.
<add> *
<add> * @return string
<add> */
<add> protected static function getFacadeAccessor() { return 'redis'; }
<add>
<add>}
<ide><path>src/Illuminate/Support/Facades/Request.php
<del><?php namespace Illuminate\Support\Facades;
<del>
<del>/**
<del> * @see \Illuminate\Http\Request
<del> */
<del>class Request extends Facade {
<del>
<del> /**
<del> * Get the registered name of the component.
<del> *
<del> * @return string
<del> */
<del> protected static function getFacadeAccessor() { return 'request'; }
<del>
<del>}
<add><?php namespace Illuminate\Support\Facades;
<add>
<add>/**
<add> * @see \Illuminate\Http\Request
<add> */
<add>class Request extends Facade {
<add>
<add> /**
<add> * Get the registered name of the component.
<add> *
<add> * @return string
<add> */
<add> protected static function getFacadeAccessor() { return 'request'; }
<add>
<add>}
<ide><path>src/Illuminate/Support/Facades/Route.php
<del><?php namespace Illuminate\Support\Facades;
<del>
<del>/**
<del> * @see \Illuminate\Routing\Router
<del> */
<del>class Route extends Facade {
<del>
<del> /**
<del> * Get the registered name of the component.
<del> *
<del> * @return string
<del> */
<del> protected static function getFacadeAccessor() { return 'router'; }
<del>
<del>}
<add><?php namespace Illuminate\Support\Facades;
<add>
<add>/**
<add> * @see \Illuminate\Routing\Router
<add> */
<add>class Route extends Facade {
<add>
<add> /**
<add> * Get the registered name of the component.
<add> *
<add> * @return string
<add> */
<add> protected static function getFacadeAccessor() { return 'router'; }
<add>
<add>}
<ide><path>src/Illuminate/Support/Facades/Schema.php
<del><?php namespace Illuminate\Support\Facades;
<del>
<del>/**
<del> * @see \Illuminate\Database\Schema\Builder
<del> */
<del>class Schema extends Facade {
<del>
<del> /**
<del> * Get a schema builder instance for a connection.
<del> *
<del> * @param string $name
<del> * @return \Illuminate\Database\Schema\Builder
<del> */
<del> public static function connection($name)
<del> {
<del> return static::$app['db']->connection($name)->getSchemaBuilder();
<del> }
<del>
<del> /**
<del> * Get the registered name of the component.
<del> *
<del> * @return string
<del> */
<del> protected static function getFacadeAccessor()
<del> {
<del> return static::$app['db']->connection()->getSchemaBuilder();
<del> }
<del>
<del>}
<add><?php namespace Illuminate\Support\Facades;
<add>
<add>/**
<add> * @see \Illuminate\Database\Schema\Builder
<add> */
<add>class Schema extends Facade {
<add>
<add> /**
<add> * Get a schema builder instance for a connection.
<add> *
<add> * @param string $name
<add> * @return \Illuminate\Database\Schema\Builder
<add> */
<add> public static function connection($name)
<add> {
<add> return static::$app['db']->connection($name)->getSchemaBuilder();
<add> }
<add>
<add> /**
<add> * Get the registered name of the component.
<add> *
<add> * @return string
<add> */
<add> protected static function getFacadeAccessor()
<add> {
<add> return static::$app['db']->connection()->getSchemaBuilder();
<add> }
<add>
<add>}
<ide><path>src/Illuminate/Support/Facades/Session.php
<del><?php namespace Illuminate\Support\Facades;
<del>
<del>/**
<del> * @see \Illuminate\Session\SessionManager
<del> * @see \Illuminate\Session\Store
<del> */
<del>class Session extends Facade {
<del>
<del> /**
<del> * Get the registered name of the component.
<del> *
<del> * @return string
<del> */
<del> protected static function getFacadeAccessor() { return 'session'; }
<del>
<del>}
<add><?php namespace Illuminate\Support\Facades;
<add>
<add>/**
<add> * @see \Illuminate\Session\SessionManager
<add> * @see \Illuminate\Session\Store
<add> */
<add>class Session extends Facade {
<add>
<add> /**
<add> * Get the registered name of the component.
<add> *
<add> * @return string
<add> */
<add> protected static function getFacadeAccessor() { return 'session'; }
<add>
<add>}
<ide><path>src/Illuminate/Support/Facades/URL.php
<del><?php namespace Illuminate\Support\Facades;
<del>
<del>/**
<del> * @see \Illuminate\Routing\UrlGenerator
<del> */
<del>class URL extends Facade {
<del>
<del> /**
<del> * Get the registered name of the component.
<del> *
<del> * @return string
<del> */
<del> protected static function getFacadeAccessor() { return 'url'; }
<del>
<del>}
<add><?php namespace Illuminate\Support\Facades;
<add>
<add>/**
<add> * @see \Illuminate\Routing\UrlGenerator
<add> */
<add>class URL extends Facade {
<add>
<add> /**
<add> * Get the registered name of the component.
<add> *
<add> * @return string
<add> */
<add> protected static function getFacadeAccessor() { return 'url'; }
<add>
<add>}
<ide><path>src/Illuminate/Support/Facades/Validator.php
<del><?php namespace Illuminate\Support\Facades;
<del>
<del>/**
<del> * @see \Illuminate\Validation\Factory
<del> */
<del>class Validator extends Facade {
<del>
<del> /**
<del> * Get the registered name of the component.
<del> *
<del> * @return string
<del> */
<del> protected static function getFacadeAccessor() { return 'validator'; }
<del>
<del>}
<add><?php namespace Illuminate\Support\Facades;
<add>
<add>/**
<add> * @see \Illuminate\Validation\Factory
<add> */
<add>class Validator extends Facade {
<add>
<add> /**
<add> * Get the registered name of the component.
<add> *
<add> * @return string
<add> */
<add> protected static function getFacadeAccessor() { return 'validator'; }
<add>
<add>}
<ide><path>src/Illuminate/Support/Facades/View.php
<del><?php namespace Illuminate\Support\Facades;
<del>
<del>/**
<del> * @see \Illuminate\View\Factory
<del> */
<del>class View extends Facade {
<del>
<del> /**
<del> * Get the registered name of the component.
<del> *
<del> * @return string
<del> */
<del> protected static function getFacadeAccessor() { return 'view'; }
<del>
<del>}
<add><?php namespace Illuminate\Support\Facades;
<add>
<add>/**
<add> * @see \Illuminate\View\Factory
<add> */
<add>class View extends Facade {
<add>
<add> /**
<add> * Get the registered name of the component.
<add> *
<add> * @return string
<add> */
<add> protected static function getFacadeAccessor() { return 'view'; }
<add>
<add>}
<ide><path>src/Illuminate/View/ViewServiceProvider.php
<del><?php namespace Illuminate\View;
<del>
<del>use Illuminate\View\Engines\PhpEngine;
<del>use Illuminate\Support\ServiceProvider;
<del>use Illuminate\View\Engines\CompilerEngine;
<del>use Illuminate\View\Engines\EngineResolver;
<del>use Illuminate\View\Compilers\BladeCompiler;
<del>
<del>class ViewServiceProvider extends ServiceProvider {
<del>
<del> /**
<del> * Register the service provider.
<del> *
<del> * @return void
<del> */
<del> public function register()
<del> {
<del> $this->registerEngineResolver();
<del>
<del> $this->registerViewFinder();
<del>
<del> $this->registerFactory();
<del> }
<del>
<del> /**
<del> * Register the engine resolver instance.
<del> *
<del> * @return void
<del> */
<del> public function registerEngineResolver()
<del> {
<del> $this->app->singleton('view.engine.resolver', function()
<del> {
<del> $resolver = new EngineResolver;
<del>
<del> // Next we will register the various engines with the resolver so that the
<del> // environment can resolve the engines it needs for various views based
<del> // on the extension of view files. We call a method for each engines.
<del> foreach (array('php', 'blade') as $engine)
<del> {
<del> $this->{'register'.ucfirst($engine).'Engine'}($resolver);
<del> }
<del>
<del> return $resolver;
<del> });
<del> }
<del>
<del> /**
<del> * Register the PHP engine implementation.
<del> *
<del> * @param \Illuminate\View\Engines\EngineResolver $resolver
<del> * @return void
<del> */
<del> public function registerPhpEngine($resolver)
<del> {
<del> $resolver->register('php', function() { return new PhpEngine; });
<del> }
<del>
<del> /**
<del> * Register the Blade engine implementation.
<del> *
<del> * @param \Illuminate\View\Engines\EngineResolver $resolver
<del> * @return void
<del> */
<del> public function registerBladeEngine($resolver)
<del> {
<del> $app = $this->app;
<del>
<del> // The Compiler engine requires an instance of the CompilerInterface, which in
<del> // this case will be the Blade compiler, so we'll first create the compiler
<del> // instance to pass into the engine so it can compile the views properly.
<del> $app->singleton('blade.compiler', function($app)
<del> {
<del> $cache = $app['config']['view.compiled'];
<del>
<del> return new BladeCompiler($app['files'], $cache);
<del> });
<del>
<del> $resolver->register('blade', function() use ($app)
<del> {
<del> return new CompilerEngine($app['blade.compiler'], $app['files']);
<del> });
<del> }
<del>
<del> /**
<del> * Register the view finder implementation.
<del> *
<del> * @return void
<del> */
<del> public function registerViewFinder()
<del> {
<del> $this->app->bind('view.finder', function($app)
<del> {
<del> $paths = $app['config']['view.paths'];
<del>
<del> return new FileViewFinder($app['files'], $paths);
<del> });
<del> }
<del>
<del> /**
<del> * Register the view environment.
<del> *
<del> * @return void
<del> */
<del> public function registerFactory()
<del> {
<del> $this->app->singleton('view', function($app)
<del> {
<del> // Next we need to grab the engine resolver instance that will be used by the
<del> // environment. The resolver will be used by an environment to get each of
<del> // the various engine implementations such as plain PHP or Blade engine.
<del> $resolver = $app['view.engine.resolver'];
<del>
<del> $finder = $app['view.finder'];
<del>
<del> $env = new Factory($resolver, $finder, $app['events']);
<del>
<del> // We will also set the container instance on this view environment since the
<del> // view composers may be classes registered in the container, which allows
<del> // for great testable, flexible composers for the application developer.
<del> $env->setContainer($app);
<del>
<del> $env->share('app', $app);
<del>
<del> return $env;
<del> });
<del> }
<del>
<del>}
<add><?php namespace Illuminate\View;
<add>
<add>use Illuminate\View\Engines\PhpEngine;
<add>use Illuminate\Support\ServiceProvider;
<add>use Illuminate\View\Engines\CompilerEngine;
<add>use Illuminate\View\Engines\EngineResolver;
<add>use Illuminate\View\Compilers\BladeCompiler;
<add>
<add>class ViewServiceProvider extends ServiceProvider {
<add>
<add> /**
<add> * Register the service provider.
<add> *
<add> * @return void
<add> */
<add> public function register()
<add> {
<add> $this->registerEngineResolver();
<add>
<add> $this->registerViewFinder();
<add>
<add> $this->registerFactory();
<add> }
<add>
<add> /**
<add> * Register the engine resolver instance.
<add> *
<add> * @return void
<add> */
<add> public function registerEngineResolver()
<add> {
<add> $this->app->singleton('view.engine.resolver', function()
<add> {
<add> $resolver = new EngineResolver;
<add>
<add> // Next we will register the various engines with the resolver so that the
<add> // environment can resolve the engines it needs for various views based
<add> // on the extension of view files. We call a method for each engines.
<add> foreach (array('php', 'blade') as $engine)
<add> {
<add> $this->{'register'.ucfirst($engine).'Engine'}($resolver);
<add> }
<add>
<add> return $resolver;
<add> });
<add> }
<add>
<add> /**
<add> * Register the PHP engine implementation.
<add> *
<add> * @param \Illuminate\View\Engines\EngineResolver $resolver
<add> * @return void
<add> */
<add> public function registerPhpEngine($resolver)
<add> {
<add> $resolver->register('php', function() { return new PhpEngine; });
<add> }
<add>
<add> /**
<add> * Register the Blade engine implementation.
<add> *
<add> * @param \Illuminate\View\Engines\EngineResolver $resolver
<add> * @return void
<add> */
<add> public function registerBladeEngine($resolver)
<add> {
<add> $app = $this->app;
<add>
<add> // The Compiler engine requires an instance of the CompilerInterface, which in
<add> // this case will be the Blade compiler, so we'll first create the compiler
<add> // instance to pass into the engine so it can compile the views properly.
<add> $app->singleton('blade.compiler', function($app)
<add> {
<add> $cache = $app['config']['view.compiled'];
<add>
<add> return new BladeCompiler($app['files'], $cache);
<add> });
<add>
<add> $resolver->register('blade', function() use ($app)
<add> {
<add> return new CompilerEngine($app['blade.compiler'], $app['files']);
<add> });
<add> }
<add>
<add> /**
<add> * Register the view finder implementation.
<add> *
<add> * @return void
<add> */
<add> public function registerViewFinder()
<add> {
<add> $this->app->bind('view.finder', function($app)
<add> {
<add> $paths = $app['config']['view.paths'];
<add>
<add> return new FileViewFinder($app['files'], $paths);
<add> });
<add> }
<add>
<add> /**
<add> * Register the view environment.
<add> *
<add> * @return void
<add> */
<add> public function registerFactory()
<add> {
<add> $this->app->singleton('view', function($app)
<add> {
<add> // Next we need to grab the engine resolver instance that will be used by the
<add> // environment. The resolver will be used by an environment to get each of
<add> // the various engine implementations such as plain PHP or Blade engine.
<add> $resolver = $app['view.engine.resolver'];
<add>
<add> $finder = $app['view.finder'];
<add>
<add> $env = new Factory($resolver, $finder, $app['events']);
<add>
<add> // We will also set the container instance on this view environment since the
<add> // view composers may be classes registered in the container, which allows
<add> // for great testable, flexible composers for the application developer.
<add> $env->setContainer($app);
<add>
<add> $env->share('app', $app);
<add>
<add> return $env;
<add> });
<add> }
<add>
<add>}
<ide><path>tests/Queue/QueueListenerTest.php
<del><?php
<del>
<del>use Mockery as m;
<del>
<del>class QueueListenerTest extends PHPUnit_Framework_TestCase {
<del>
<del> public function tearDown()
<del> {
<del> m::close();
<del> }
<del>
<del>
<del> public function testRunProcessCallsProcess()
<del> {
<del> $process = m::mock('Symfony\Component\Process\Process')->makePartial();
<del> $process->shouldReceive('run')->once();
<del> $listener = m::mock('Illuminate\Queue\Listener')->makePartial();
<del> $listener->shouldReceive('memoryExceeded')->once()->with(1)->andReturn(false);
<del>
<del> $listener->runProcess($process, 1);
<del> }
<del>
<del>
<del> public function testListenerStopsWhenMemoryIsExceeded()
<del> {
<del> $process = m::mock('Symfony\Component\Process\Process')->makePartial();
<del> $process->shouldReceive('run')->once();
<del> $listener = m::mock('Illuminate\Queue\Listener')->makePartial();
<del> $listener->shouldReceive('memoryExceeded')->once()->with(1)->andReturn(true);
<del> $listener->shouldReceive('stop')->once();
<del>
<del> $listener->runProcess($process, 1);
<del> }
<del>
<del>
<del> public function testMakeProcessCorrectlyFormatsCommandLine()
<del> {
<del> $listener = new Illuminate\Queue\Listener(__DIR__);
<del> $process = $listener->makeProcess('connection', 'queue', 1, 2, 3);
<del>
<del> $this->assertInstanceOf('Symfony\Component\Process\Process', $process);
<del> $this->assertEquals(__DIR__, $process->getWorkingDirectory());
<del> $this->assertEquals(3, $process->getTimeout());
<del> $this->assertEquals('"'.PHP_BINARY.'" artisan queue:work connection --queue="queue" --delay=1 --memory=2 --sleep=3 --tries=0', $process->getCommandLine());
<del> }
<del>
<del>}
<add><?php
<add>
<add>use Mockery as m;
<add>
<add>class QueueListenerTest extends PHPUnit_Framework_TestCase {
<add>
<add> public function tearDown()
<add> {
<add> m::close();
<add> }
<add>
<add>
<add> public function testRunProcessCallsProcess()
<add> {
<add> $process = m::mock('Symfony\Component\Process\Process')->makePartial();
<add> $process->shouldReceive('run')->once();
<add> $listener = m::mock('Illuminate\Queue\Listener')->makePartial();
<add> $listener->shouldReceive('memoryExceeded')->once()->with(1)->andReturn(false);
<add>
<add> $listener->runProcess($process, 1);
<add> }
<add>
<add>
<add> public function testListenerStopsWhenMemoryIsExceeded()
<add> {
<add> $process = m::mock('Symfony\Component\Process\Process')->makePartial();
<add> $process->shouldReceive('run')->once();
<add> $listener = m::mock('Illuminate\Queue\Listener')->makePartial();
<add> $listener->shouldReceive('memoryExceeded')->once()->with(1)->andReturn(true);
<add> $listener->shouldReceive('stop')->once();
<add>
<add> $listener->runProcess($process, 1);
<add> }
<add>
<add>
<add> public function testMakeProcessCorrectlyFormatsCommandLine()
<add> {
<add> $listener = new Illuminate\Queue\Listener(__DIR__);
<add> $process = $listener->makeProcess('connection', 'queue', 1, 2, 3);
<add>
<add> $this->assertInstanceOf('Symfony\Component\Process\Process', $process);
<add> $this->assertEquals(__DIR__, $process->getWorkingDirectory());
<add> $this->assertEquals(3, $process->getTimeout());
<add> $this->assertEquals('"'.PHP_BINARY.'" artisan queue:work connection --queue="queue" --delay=1 --memory=2 --sleep=3 --tries=0', $process->getCommandLine());
<add> }
<add>
<add>}
<ide><path>tests/Support/SupportMessageBagTest.php
<del><?php
<del>
<del>use Illuminate\Support\MessageBag;
<del>use Mockery as m;
<del>
<del>class SupportMessageBagTest extends PHPUnit_Framework_TestCase {
<del>
<del> public function tearDown()
<del> {
<del> m::close();
<del> }
<del>
<del>
<del> public function testUniqueness()
<del> {
<del> $container = new MessageBag;
<del> $container->add('foo', 'bar');
<del> $container->add('foo', 'bar');
<del> $messages = $container->getMessages();
<del> $this->assertEquals(array('bar'), $messages['foo']);
<del> }
<del>
<del>
<del> public function testMessagesAreAdded()
<del> {
<del> $container = new MessageBag;
<del> $container->setFormat(':message');
<del> $container->add('foo', 'bar');
<del> $container->add('foo', 'baz');
<del> $container->add('boom', 'bust');
<del> $messages = $container->getMessages();
<del> $this->assertEquals(array('bar', 'baz'), $messages['foo']);
<del> $this->assertEquals(array('bust'), $messages['boom']);
<del> }
<del>
<del>
<del> public function testMessagesMayBeMerged()
<del> {
<del> $container = new MessageBag(array('username' => array('foo')));
<del> $container->merge(array('username' => array('bar')));
<del> $this->assertEquals(array('username' => array('foo', 'bar')), $container->getMessages());
<del> }
<del>
<del>
<del> public function testMessageBagsCanBeMerged()
<del> {
<del> $container = new MessageBag(array('foo' => array('bar')));
<del> $otherContainer = new MessageBag(array('foo' => array('baz'), 'bar' => array('foo')));
<del> $container->merge($otherContainer);
<del> $this->assertEquals(array('foo' => array('bar', 'baz'), 'bar' => array('foo')), $container->getMessages());
<del> }
<del>
<del>
<del> public function testGetReturnsArrayOfMessagesByKey()
<del> {
<del> $container = new MessageBag;
<del> $container->setFormat(':message');
<del> $container->add('foo', 'bar');
<del> $container->add('foo', 'baz');
<del> $this->assertEquals(array('bar', 'baz'), $container->get('foo'));
<del> }
<del>
<del>
<del> public function testFirstReturnsSingleMessage()
<del> {
<del> $container = new MessageBag;
<del> $container->setFormat(':message');
<del> $container->add('foo', 'bar');
<del> $container->add('foo', 'baz');
<del> $messages = $container->getMessages();
<del> $this->assertEquals('bar', $container->first('foo'));
<del> }
<del>
<del>
<del> public function testHasIndicatesExistence()
<del> {
<del> $container = new MessageBag;
<del> $container->setFormat(':message');
<del> $container->add('foo', 'bar');
<del> $this->assertTrue($container->has('foo'));
<del> $this->assertFalse($container->has('bar'));
<del> }
<del>
<del>
<del> public function testAllReturnsAllMessages()
<del> {
<del> $container = new MessageBag;
<del> $container->setFormat(':message');
<del> $container->add('foo', 'bar');
<del> $container->add('boom', 'baz');
<del> $this->assertEquals(array('bar', 'baz'), $container->all());
<del> }
<del>
<del>
<del> public function testFormatIsRespected()
<del> {
<del> $container = new MessageBag;
<del> $container->setFormat('<p>:message</p>');
<del> $container->add('foo', 'bar');
<del> $container->add('boom', 'baz');
<del> $this->assertEquals('<p>bar</p>', $container->first('foo'));
<del> $this->assertEquals(array('<p>bar</p>'), $container->get('foo'));
<del> $this->assertEquals(array('<p>bar</p>', '<p>baz</p>'), $container->all());
<del> $this->assertEquals('bar', $container->first('foo', ':message'));
<del> $this->assertEquals(array('bar'), $container->get('foo', ':message'));
<del> $this->assertEquals(array('bar', 'baz'), $container->all(':message'));
<del>
<del> $container->setFormat(':key :message');
<del> $this->assertEquals('foo bar', $container->first('foo'));
<del> }
<del>
<del>
<del> public function testMessageBagReturnsCorrectArray()
<del> {
<del> $container = new MessageBag;
<del> $container->setFormat(':message');
<del> $container->add('foo', 'bar');
<del> $container->add('boom', 'baz');
<del>
<del> $this->assertEquals(array('foo' => array('bar'), 'boom' => array('baz')), $container->toArray());
<del> }
<del>
<del>
<del> public function testMessageBagReturnsExpectedJson()
<del> {
<del> $container = new MessageBag;
<del> $container->setFormat(':message');
<del> $container->add('foo', 'bar');
<del> $container->add('boom', 'baz');
<del>
<del> $this->assertEquals('{"foo":["bar"],"boom":["baz"]}', $container->toJson());
<del> }
<del>
<del>
<del> public function testCountReturnsCorrectValue()
<del> {
<del> $container = new MessageBag;
<del> $this->assertEquals(0, $container->count());
<del>
<del> $container->add('foo', 'bar');
<del> $container->add('foo', 'baz');
<del> $container->add('boom', 'baz');
<del>
<del> $this->assertEquals(3, $container->count());
<del> }
<del>
<del>
<del> public function testCountable()
<del> {
<del> $container = new MessageBag;
<del>
<del> $container->add('foo', 'bar');
<del> $container->add('boom', 'baz');
<del>
<del> $this->assertCount(2, $container);
<del> }
<del>
<del>
<del> public function testConstructor()
<del> {
<del> $messageBag = new MessageBag(array('country' => 'Azerbaijan', 'capital' => 'Baku'));
<del> $this->assertEquals(array('country' => array('Azerbaijan'), 'capital' => array('Baku')), $messageBag->getMessages());
<del> }
<del>
<del>}
<add><?php
<add>
<add>use Illuminate\Support\MessageBag;
<add>use Mockery as m;
<add>
<add>class SupportMessageBagTest extends PHPUnit_Framework_TestCase {
<add>
<add> public function tearDown()
<add> {
<add> m::close();
<add> }
<add>
<add>
<add> public function testUniqueness()
<add> {
<add> $container = new MessageBag;
<add> $container->add('foo', 'bar');
<add> $container->add('foo', 'bar');
<add> $messages = $container->getMessages();
<add> $this->assertEquals(array('bar'), $messages['foo']);
<add> }
<add>
<add>
<add> public function testMessagesAreAdded()
<add> {
<add> $container = new MessageBag;
<add> $container->setFormat(':message');
<add> $container->add('foo', 'bar');
<add> $container->add('foo', 'baz');
<add> $container->add('boom', 'bust');
<add> $messages = $container->getMessages();
<add> $this->assertEquals(array('bar', 'baz'), $messages['foo']);
<add> $this->assertEquals(array('bust'), $messages['boom']);
<add> }
<add>
<add>
<add> public function testMessagesMayBeMerged()
<add> {
<add> $container = new MessageBag(array('username' => array('foo')));
<add> $container->merge(array('username' => array('bar')));
<add> $this->assertEquals(array('username' => array('foo', 'bar')), $container->getMessages());
<add> }
<add>
<add>
<add> public function testMessageBagsCanBeMerged()
<add> {
<add> $container = new MessageBag(array('foo' => array('bar')));
<add> $otherContainer = new MessageBag(array('foo' => array('baz'), 'bar' => array('foo')));
<add> $container->merge($otherContainer);
<add> $this->assertEquals(array('foo' => array('bar', 'baz'), 'bar' => array('foo')), $container->getMessages());
<add> }
<add>
<add>
<add> public function testGetReturnsArrayOfMessagesByKey()
<add> {
<add> $container = new MessageBag;
<add> $container->setFormat(':message');
<add> $container->add('foo', 'bar');
<add> $container->add('foo', 'baz');
<add> $this->assertEquals(array('bar', 'baz'), $container->get('foo'));
<add> }
<add>
<add>
<add> public function testFirstReturnsSingleMessage()
<add> {
<add> $container = new MessageBag;
<add> $container->setFormat(':message');
<add> $container->add('foo', 'bar');
<add> $container->add('foo', 'baz');
<add> $messages = $container->getMessages();
<add> $this->assertEquals('bar', $container->first('foo'));
<add> }
<add>
<add>
<add> public function testHasIndicatesExistence()
<add> {
<add> $container = new MessageBag;
<add> $container->setFormat(':message');
<add> $container->add('foo', 'bar');
<add> $this->assertTrue($container->has('foo'));
<add> $this->assertFalse($container->has('bar'));
<add> }
<add>
<add>
<add> public function testAllReturnsAllMessages()
<add> {
<add> $container = new MessageBag;
<add> $container->setFormat(':message');
<add> $container->add('foo', 'bar');
<add> $container->add('boom', 'baz');
<add> $this->assertEquals(array('bar', 'baz'), $container->all());
<add> }
<add>
<add>
<add> public function testFormatIsRespected()
<add> {
<add> $container = new MessageBag;
<add> $container->setFormat('<p>:message</p>');
<add> $container->add('foo', 'bar');
<add> $container->add('boom', 'baz');
<add> $this->assertEquals('<p>bar</p>', $container->first('foo'));
<add> $this->assertEquals(array('<p>bar</p>'), $container->get('foo'));
<add> $this->assertEquals(array('<p>bar</p>', '<p>baz</p>'), $container->all());
<add> $this->assertEquals('bar', $container->first('foo', ':message'));
<add> $this->assertEquals(array('bar'), $container->get('foo', ':message'));
<add> $this->assertEquals(array('bar', 'baz'), $container->all(':message'));
<add>
<add> $container->setFormat(':key :message');
<add> $this->assertEquals('foo bar', $container->first('foo'));
<add> }
<add>
<add>
<add> public function testMessageBagReturnsCorrectArray()
<add> {
<add> $container = new MessageBag;
<add> $container->setFormat(':message');
<add> $container->add('foo', 'bar');
<add> $container->add('boom', 'baz');
<add>
<add> $this->assertEquals(array('foo' => array('bar'), 'boom' => array('baz')), $container->toArray());
<add> }
<add>
<add>
<add> public function testMessageBagReturnsExpectedJson()
<add> {
<add> $container = new MessageBag;
<add> $container->setFormat(':message');
<add> $container->add('foo', 'bar');
<add> $container->add('boom', 'baz');
<add>
<add> $this->assertEquals('{"foo":["bar"],"boom":["baz"]}', $container->toJson());
<add> }
<add>
<add>
<add> public function testCountReturnsCorrectValue()
<add> {
<add> $container = new MessageBag;
<add> $this->assertEquals(0, $container->count());
<add>
<add> $container->add('foo', 'bar');
<add> $container->add('foo', 'baz');
<add> $container->add('boom', 'baz');
<add>
<add> $this->assertEquals(3, $container->count());
<add> }
<add>
<add>
<add> public function testCountable()
<add> {
<add> $container = new MessageBag;
<add>
<add> $container->add('foo', 'bar');
<add> $container->add('boom', 'baz');
<add>
<add> $this->assertCount(2, $container);
<add> }
<add>
<add>
<add> public function testConstructor()
<add> {
<add> $messageBag = new MessageBag(array('country' => 'Azerbaijan', 'capital' => 'Baku'));
<add> $this->assertEquals(array('country' => array('Azerbaijan'), 'capital' => array('Baku')), $messageBag->getMessages());
<add> }
<add>
<add>} | 38 |
Java | Java | fix deviceinfomodule lifecycleeventlistener | 22735f6903d4101ec48946b1a63230c720b93880 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/deviceinfo/DeviceInfoModule.java
<ide> public class DeviceInfoModule extends BaseJavaModule implements
<ide> public DeviceInfoModule(ReactApplicationContext reactContext) {
<ide> this((Context) reactContext);
<ide> mReactApplicationContext = reactContext;
<add> mReactApplicationContext.addLifecycleEventListener(this);
<ide> }
<ide>
<ide> public DeviceInfoModule(Context context) { | 1 |
Text | Text | add evanlucas to collaborators | 8f9502a20a8851cfbf5f6181a52813baec23fe0f | <ide><path>README.md
<ide> information about the governance of the io.js project, see
<ide> * **Thorsten Lorenz** ([@thlorenz](https://github.com/thlorenz)) <thlorenz@gmx.de>
<ide> * **Stephen Belanger** ([@qard](https://github.com/qard)) <admin@stephenbelanger.com>
<ide> * **Jeremiah Senkpiel** ([@fishrock123](https://github.com/fishrock123)) <fishrock123@rocketmail.com>
<add>* **Evan Lucas** ([@evanlucas](https://github.com/evanlucas)) <evanlucas@me.com>
<ide>
<ide> Collaborators follow the [COLLABORATOR_GUIDE.md](./COLLABORATOR_GUIDE.md) in
<ide> maintaining the io.js project. | 1 |
Text | Text | add rgba, hsl, hsla for defining color | 35162199c62496cac442abcf7db291d3d74386e1 | <ide><path>guide/english/css/background/index.md
<ide> h1 {
<ide> ```
<ide> 
<ide>
<del>In CSS color can be defined in a few different ways:
<del>* A valid color name such as `blue`
<del>* A HEX value such as `#FFFFF` (This is the hex value for white.)
<del>* An abbreviated HEX value such as '#FFF'.
<del>* An RGB value such as `rgb(76,175,80)` (This is the RGB value for light green.)
<del>* RGBA color values are an extension of RGB color values with an alpha channel - which specifies the opacity of the object.
<del> * An RGBA color is specified with the rgba() function, which has the following syntax: `rgba(red, green, blue, alpha)`
<del> * The alpha parameter is a number between `0.0` (fully transparent) and `1.0` (fully opaque).
<add>In CSS color can be defined in the following ways:
<add>* A valid "color" keyword name such as `blue`
<add>* Numerical color values
<add> + A HEX value such as `#FFFFF` (This is the hex value for white.)
<add> + An abbreviated HEX value such as `#FFF`.
<add> + An RGB value such as `rgb(76,175,80)` (This is the RGB value for light green.)
<add> + RGBA value (RGB + alpha channel for contolling opacity)
<add> - Note: The alpha parameter is a number between `0.0` (fully transparent) and `1.0` (fully opaque)
<add> + HSL (Hue, Saturation, Lightness) (e.g., `hsl(115, 75%, 73%)` is HSL for light green)
<add> + HSLA (HSL + alpha channel for controlling opacity)
<ide>
<ide> ### Background Images
<ide> You can use the `background-image` property to set an image as a background for an element. | 1 |
Text | Text | add error check to fs example | 540cbf84afddfbdd2e88ecbb92c28b7dcc582498 | <ide><path>doc/api/fs.md
<ide> fs.open('myfile', 'wx', (err, fd) => {
<ide> fs.exists('myfile', (exists) => {
<ide> if (exists) {
<ide> fs.open('myfile', 'r', (err, fd) => {
<add> if (err) throw err;
<ide> readMyData(fd);
<ide> });
<ide> } else { | 1 |
PHP | PHP | fix code markup for the docs | 2b0710742e7644fd45b502ed59ec9eb6b0349302 | <ide><path>src/Datasource/EntityTrait.php
<ide> public function __unset($property)
<ide> *
<ide> * ### Example:
<ide> *
<del> * ``$entity->set('name', 'Andrew');``
<add> * ```
<add> * $entity->set('name', 'Andrew');
<add> * ```
<ide> *
<ide> * It is also possible to mass-assign multiple properties to this entity
<ide> * with one call by passing a hashed array as properties in the form of | 1 |
PHP | PHP | fix code formatting | 208d1b04fab8b07f911c78de020398c9f18b9bdd | <ide><path>src/Illuminate/Console/Command.php
<ide> public function __construct()
<ide> $this->specifyParameters();
<ide> }
<ide>
<add> /**
<add> * Execute the console command.
<add> *
<add> * @return void
<add> */
<add> abstract public function fire();
<add>
<ide> /**
<ide> * Specify the arguments and options on the command.
<ide> *
<ide> public function setLaravel($laravel)
<ide> $this->laravel = $laravel;
<ide> }
<ide>
<del> abstract public function fire();
<ide> } | 1 |
Python | Python | fix edge case that took the scheduler down | e9f09b339880a38a06ec27b0ee16e767c4818488 | <ide><path>airflow/models.py
<ide> def process_file(self, filepath, only_if_updated=True, safe_mode=True):
<ide> # This failed before in what may have been a git sync
<ide> # race condition
<ide> dttm = datetime.fromtimestamp(os.path.getmtime(filepath))
<add> mod_name, file_ext = os.path.splitext(os.path.split(filepath)[-1])
<add> mod_name = 'unusual_prefix_' + mod_name
<ide> except:
<del> dttm = datetime(2001, 1, 1)
<del> mod_name, file_ext = os.path.splitext(os.path.split(filepath)[-1])
<del> mod_name = 'unusual_prefix_' + mod_name
<add> return
<ide>
<ide> if safe_mode and os.path.isfile(filepath):
<ide> # Skip file if no obvious references to airflow or DAG are found. | 1 |
PHP | PHP | add basic index support | 62115e1cda1acc7f9fcf16f46df0cf5ef08ab2c6 | <ide><path>lib/Cake/Database/Schema/Table.php
<ide> */
<ide> namespace Cake\Database\Schema;
<ide>
<add>use Cake\Error;
<add>
<ide> /**
<ide> * Represents a single table in a database schema.
<ide> *
<ide> class Table {
<ide> 'charset' => null,
<ide> ];
<ide>
<add>/**
<add> * The valid keys that can be used in an index
<add> * definition.
<add> *
<add> * @var array
<add> */
<add> protected $_indexKeys = [
<add> 'type' => null,
<add> 'columns' => [],
<add> ];
<add>
<add>/**
<add> * Names of the valid index types.
<add> *
<add> * @var array
<add> */
<add> protected $_validIndexTypes = [
<add> self::INDEX_PRIMARY,
<add> self::INDEX_INDEX,
<add> self::INDEX_UNIQUE,
<add> self::INDEX_FOREIGN,
<add> ];
<add>
<add> const INDEX_PRIMARY = 'primary';
<add> const INDEX_INDEX = 'index';
<add> const INDEX_UNIQUE = 'unique';
<add> const INDEX_FOREIGN = 'foreign';
<add>
<add>/**
<add> * Constructor.
<add> *
<add> * @param string $table The table name.
<add> */
<ide> public function __construct($table) {
<ide> $this->_table = $table;
<ide> }
<ide> public function column($name) {
<ide> /**
<ide> * Add an index or key.
<ide> *
<add> * Used to add primary keys, indexes, and foreign keys
<add> * to a table.
<add> *
<add> * ### Attributes
<add> *
<add> * - `type` The type of index being added.
<add> * - `columns` The columns in the index.
<add> *
<ide> * @param string $name The name of the index.
<ide> * @param array $attrs The attributes for the index.
<ide> * @return Table $this
<add> * @throws Cake\Error\Exception
<ide> */
<ide> public function addIndex($name, $attrs) {
<add> if (is_string($attrs)) {
<add> $attrs = ['type' => $attrs];
<add> }
<add> $attrs = array_intersect_key($attrs, $this->_indexKeys);
<add> $attrs = $attrs + $this->_indexKeys;
<add>
<add> if (!in_array($attrs['type'], $this->_validIndexTypes, true)) {
<add> throw new Error\Exception(__d('cake_dev', 'Invalid index type'));
<add> }
<add> foreach ($attrs['columns'] as $field) {
<add> if (empty($this->_columns[$field])) {
<add> throw new Error\Exception(__d('cake_dev', 'Columns used in indexes must already exist.'));
<add> }
<add> }
<ide> $this->_indexes[$name] = $attrs;
<ide> return $this;
<ide> }
<ide><path>lib/Cake/Test/TestCase/Database/Schema/TableTest.php
<ide> public function testAddIndex() {
<ide> $this->assertEquals(['primary'], $table->indexes());
<ide> }
<ide>
<add>/**
<add> * Test that an exception is raised when indexes
<add> * are added for fields that do not exist.
<add> *
<add> * @expectedException Cake\Error\Exception
<add> * @return void
<add> */
<ide> public function testAddIndexErrorWhenFieldIsMissing() {
<add> $table = new Table('articles');
<add> $table->addIndex('author_idx', [
<add> 'columns' => ['author_id']
<add> ]);
<ide> }
<del>
<del> public function testAddIndexForeign() {
<add>/**
<add> * Test that exceptions are raised when indexes
<add> * are added with invalid types
<add> *
<add> * @expectedException Cake\Error\Exception
<add> * @return void
<add> */
<add> public function testAddIndexErrorWrongType() {
<add> $table = new Table('articles');
<add> $table->addColumn('author_id', 'integer')
<add> ->addIndex('author_idx', [
<add> 'type' => 'derp',
<add> 'columns' => ['author_id']
<add> ]);
<ide> }
<ide>
<add>/**
<add> * Test adding different kinds of indexes.
<add> *
<add> * @return void
<add> */
<ide> public function testAddIndexTypes() {
<add> $table = new Table('articles');
<add> $table->addColumn('title', 'string')
<add> ->addColumn('author_id', 'integer');
<add>
<add> $table->addIndex('author_idx', [
<add> 'fields' => ['author_id'],
<add> 'type' => 'unique'
<add> ]);
<add> }
<add>
<add>/**
<add> * Test adding foreign keys.
<add> *
<add> * @return void
<add> */
<add> public function testAddIndexForeign() {
<ide> }
<ide>
<ide> } | 2 |
Ruby | Ruby | capture stdout during test_prefix | 02e53d44cb23e5f798897ac97df357353c0e6242 | <ide><path>Library/Homebrew/unittest.rb
<ide> $:.unshift File.dirname(__FILE__)
<ide> require 'test/unit'
<ide> require 'brewkit'
<add>require 'stringio'
<ide>
<ide> class TestFormula <Formula
<ide> def initialize url, md5='nomd5'
<ide> def initialize url, md5='nomd5'
<ide> end
<ide> end
<ide>
<add>def nostdout
<add> tmp=$stdout
<add> $stdout=StringIO.new
<add> yield
<add> $stdout=tmp
<add>end
<add>
<ide>
<ide> class BeerTasting <Test::Unit::TestCase
<ide> def test_version_all_dots
<ide> def test_supported_compressed_types
<ide> def test_prefix
<ide> url='http://www.methylblue.com/test-0.1.tar.gz'
<ide> md5='d496ea538a21dc4bb8524a8888baf88c'
<del>
<del> TestFormula.new(url, md5).brew do |f|
<del> prefix=f.prefix
<del> # we test for +/unittest/0.1 because we derive @name from $0
<del> assert_equal File.expand_path(prefix), ($cellar+'test'+'0.1').to_s
<del> assert_kind_of Pathname, prefix
<add>
<add> nostdout do
<add> TestFormula.new(url, md5).brew do |f|
<add> assert_equal File.expand_path(f.prefix), ($cellar+f.name+'0.1').to_s
<add> assert_kind_of Pathname, f.prefix
<add> end
<ide> end
<ide> end
<ide> end
<ide>\ No newline at end of file | 1 |
Mixed | Ruby | raise missingattributeerror on query methods | 4f107da4ffafa2b77d87fc5a6fb09fa34343184c | <ide><path>activerecord/CHANGELOG.md
<ide> ## Rails 4.0.0 (unreleased) ##
<ide>
<add>* Attribute predicate methods, such as `article.title?`, will now raise
<add> `ActiveModel::MissingAttributeError` if the attribute being queried for
<add> truthiness was not read from the database, instead of just returning false.
<add>
<add> *Ernie Miller*
<add>
<ide> * `ActiveRecord::SchemaDumper` uses Ruby 1.9 style hash, which means that the
<ide> schema.rb file will be generated using this new syntax from now on.
<ide>
<ide><path>activerecord/lib/active_record/attribute_methods/query.rb
<ide> module Query
<ide> end
<ide>
<ide> def query_attribute(attr_name)
<del> value = read_attribute(attr_name)
<add> value = read_attribute(attr_name) { |n| missing_attribute(n, caller) }
<ide>
<ide> case value
<ide> when true then true
<ide><path>activerecord/test/cases/finder_test.rb
<ide> def test_unexisting_record_exception_handling
<ide> def test_find_only_some_columns
<ide> topic = Topic.all.merge!(:select => "author_name").find(1)
<ide> assert_raise(ActiveModel::MissingAttributeError) {topic.title}
<add> assert_raise(ActiveModel::MissingAttributeError) {topic.title?}
<ide> assert_nil topic.read_attribute("title")
<ide> assert_equal "David", topic.author_name
<ide> assert !topic.attribute_present?("title") | 3 |
Go | Go | change reading order of tailfile | 63904eb6745d553573ffe8b7cef43dfc0b8a07cf | <ide><path>integration-cli/docker_cli_logs_test.go
<ide> func (s *DockerSuite) TestLogsTail(c *check.C) {
<ide> id := strings.TrimSpace(out)
<ide> dockerCmd(c, "wait", id)
<ide>
<del> out, _ = dockerCmd(c, "logs", "--tail", "5", id)
<del>
<add> out, _ = dockerCmd(c, "logs", "--tail", "0", id)
<ide> lines := strings.Split(out, "\n")
<add> c.Assert(lines, checker.HasLen, 1)
<ide>
<add> out, _ = dockerCmd(c, "logs", "--tail", "5", id)
<add> lines = strings.Split(out, "\n")
<ide> c.Assert(lines, checker.HasLen, 6)
<ide>
<del> out, _ = dockerCmd(c, "logs", "--tail", "all", id)
<add> out, _ = dockerCmd(c, "logs", "--tail", "99", id)
<add> lines = strings.Split(out, "\n")
<add> c.Assert(lines, checker.HasLen, 100)
<ide>
<add> out, _ = dockerCmd(c, "logs", "--tail", "all", id)
<ide> lines = strings.Split(out, "\n")
<add> c.Assert(lines, checker.HasLen, testLen+1)
<ide>
<add> out, _ = dockerCmd(c, "logs", "--tail", "-1", id)
<add> lines = strings.Split(out, "\n")
<ide> c.Assert(lines, checker.HasLen, testLen+1)
<ide>
<ide> out, _, _ = dockerCmdWithStdoutStderr(c, "logs", "--tail", "random", id)
<del>
<ide> lines = strings.Split(out, "\n")
<del>
<ide> c.Assert(lines, checker.HasLen, testLen+1)
<ide> }
<ide>
<ide><path>pkg/tailfile/tailfile.go
<ide> func TailFile(f io.ReadSeeker, n int) ([][]byte, error) {
<ide> break
<ide> } else {
<ide> b = make([]byte, blockSize)
<del> if _, err := f.Seek(step, os.SEEK_END); err != nil {
<add> if _, err := f.Seek(left, os.SEEK_SET); err != nil {
<ide> return nil, err
<ide> }
<ide> if _, err := f.Read(b); err != nil { | 2 |
PHP | PHP | add tests and refactor | 83ef6a7eae193ef11e03c400364f2a39fd92acb3 | <ide><path>src/Illuminate/Routing/CompiledRouteCollection.php
<ide> public function match(Request $request)
<ide>
<ide> $route = null;
<ide>
<del> $checkedDynamicRoutes = false;
<del> $matchedCachedRouteIsFallback = false;
<del>
<ide> try {
<ide> if ($result = $matcher->matchRequest($request)) {
<ide> $route = $this->getByName($result['_route']);
<ide> }
<del>
<del> $matchedCachedRouteIsFallback = $route->isFallback;
<ide> } catch (ResourceNotFoundException | MethodNotAllowedException $e) {
<del> $checkedDynamicRoutes = true;
<del>
<ide> try {
<ide> return $this->routes->match($request);
<ide> } catch (NotFoundHttpException $e) {
<ide> //
<ide> }
<ide> }
<ide>
<del> if ($matchedCachedRouteIsFallback && ! $checkedDynamicRoutes) {
<add> if ($route && $route->isFallback) {
<ide> try {
<del> $dynamicRoute = $this->routes->match($request);
<del>
<del> if (! $dynamicRoute->isFallback) {
<del> $route = $dynamicRoute;
<del> }
<del> } catch (Exception $e) {
<add> return $this->routes->match($request);
<add> } catch (NotFoundHttpException $e) {
<ide> //
<ide> }
<ide> }
<ide><path>tests/Integration/Routing/CompiledRouteCollectionTest.php
<ide> public function testMatchingThrowsMethodNotAllowedHttpExceptionWhenMethodIsNotAl
<ide> $this->collection()->match(Request::create('/foo', 'POST'));
<ide> }
<ide>
<del> public function testMatchingThrowsMethodNotAllowedHttpExceptionWhenMethodIsNotAllowedWhileSameRouteIsAddedDynamically()
<add> public function testMatchingThrowsExceptionWhenMethodIsNotAllowedWhileSameRouteIsAddedDynamically()
<ide> {
<ide> $this->routeCollection->add($this->newRoute('GET', '/', ['uses' => 'FooController@index']));
<ide>
<ide> public function testMatchingWildcardFromCompiledRoutesAlwaysTakesPrecedent()
<ide> $this->assertSame('foo', $routes->match(Request::create('/foo', 'GET'))->getName());
<ide> }
<ide>
<del> public function testSlashPrefixIsProperly()
<add> public function testMatchingDynamicallyAddedRoutesTakePrecedenceOverFallbackRoutes()
<add> {
<add> $this->routeCollection->add($this->fallbackRoute(['uses' => 'FooController@index']));
<add> $this->routeCollection->add(
<add> $this->newRoute('GET', '/foo/{id}', ['uses' => 'FooController@index', 'as' => 'foo'])
<add> );
<add>
<add> $routes = $this->collection();
<add>
<add> $routes->add($this->newRoute('GET', '/bar/{id}', ['uses' => 'FooController@index', 'as' => 'bar']));
<add>
<add> $this->assertEquals('bar', $routes->match(Request::create('/bar/1', 'GET'))->getName());
<add> }
<add>
<add> public function testMatchingFallbackRouteCatchesAll()
<add> {
<add> $this->routeCollection->add($this->fallbackRoute(['uses' => 'FooController@index', 'as' => 'fallback']));
<add> $this->routeCollection->add(
<add> $this->newRoute('GET', '/foo/{id}', ['uses' => 'FooController@index', 'as' => 'foo'])
<add> );
<add>
<add> $routes = $this->collection();
<add>
<add> $routes->add($this->newRoute('GET', '/bar/{id}', ['uses' => 'FooController@index', 'as' => 'bar']));
<add>
<add> $this->assertEquals('fallback', $routes->match(Request::create('/baz/1', 'GET'))->getName());
<add> }
<add>
<add> public function testSlashPrefixIsProperlyHandled()
<ide> {
<ide> $this->routeCollection->add($this->newRoute('GET', 'foo/bar', ['uses' => 'FooController@index', 'prefix' => '/']));
<ide>
<ide> protected function newRoute($methods, $uri, $action)
<ide> ->setRouter($this->router)
<ide> ->setContainer($this->app);
<ide> }
<add>
<add> /**
<add> * Create a new fallback Route object.
<add> *
<add> * @param mixed $action
<add> * @return \Illuminate\Routing\Route
<add> */
<add> protected function fallbackRoute($action)
<add> {
<add> $placeholder = 'fallbackPlaceholder';
<add>
<add> return $this->newRoute(
<add> 'GET', "{{$placeholder}}", $action
<add> )->where($placeholder, '.*')->fallback();
<add> }
<ide> } | 2 |
Java | Java | remove synchronized block | e7d40f930f8e85d67b3d235ca26c7f2f076d6a58 | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapter.java
<ide> protected long getLastModifiedInternal(HttpServletRequest request, HandlerMethod
<ide> * (never {@code null}).
<ide> */
<ide> private SessionAttributesHandler getSessionAttributesHandler(HandlerMethod handlerMethod) {
<del> Class<?> handlerType = handlerMethod.getBeanType();
<del> SessionAttributesHandler sessionAttrHandler = this.sessionAttributesHandlerCache.get(handlerType);
<del> if (sessionAttrHandler == null) {
<del> synchronized (this.sessionAttributesHandlerCache) {
<del> sessionAttrHandler = this.sessionAttributesHandlerCache.computeIfAbsent(handlerType, type -> new SessionAttributesHandler(type, this.sessionAttributeStore));
<del> }
<del> }
<del> return sessionAttrHandler;
<add> return this.sessionAttributesHandlerCache.computeIfAbsent(
<add> handlerMethod.getBeanType(),
<add> type -> new SessionAttributesHandler(type, this.sessionAttributeStore));
<ide> }
<ide>
<ide> /** | 1 |
Java | Java | refactor the usages of choreographercompat | a5f3571770e9f5da454f4eb8eff8e57de7acd551 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/FpsView.java
<ide> public FpsView(ReactContext reactContext) {
<ide> super(reactContext);
<ide> inflate(reactContext, R.layout.fps_view, this);
<ide> mTextView = (TextView) findViewById(R.id.fps_text);
<del> mFrameCallback = new FpsDebugFrameCallback(ChoreographerCompat.getInstance(), reactContext);
<add> mFrameCallback = new FpsDebugFrameCallback(reactContext);
<ide> mFPSMonitorRunnable = new FPSMonitorRunnable();
<ide> setCurrentFPS(0, 0, 0, 0);
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/debug/AnimationsDebugModule.java
<ide> public void startRecordingFps() {
<ide> }
<ide>
<ide> mFrameCallback = new FpsDebugFrameCallback(
<del> ChoreographerCompat.getInstance(),
<ide> getReactApplicationContext());
<ide> mFrameCallback.startAndRecordFpsAtEachFrame();
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/debug/FpsDebugFrameCallback.java
<ide>
<ide> package com.facebook.react.modules.debug;
<ide>
<add>import com.facebook.react.bridge.UiThreadUtil;
<ide> import javax.annotation.Nullable;
<ide>
<ide> import java.util.Map;
<ide> public FpsInfo(
<ide>
<ide> private static final double EXPECTED_FRAME_TIME = 16.9;
<ide>
<del> private final ChoreographerCompat mChoreographer;
<add> private @Nullable ChoreographerCompat mChoreographer;
<ide> private final ReactContext mReactContext;
<ide> private final UIManagerModule mUIManagerModule;
<ide> private final DidJSUpdateUiDuringFrameDetector mDidJSUpdateUiDuringFrameDetector;
<ide> public FpsInfo(
<ide> private boolean mIsRecordingFpsInfoAtEachFrame = false;
<ide> private @Nullable TreeMap<Long, FpsInfo> mTimeToFps;
<ide>
<del> public FpsDebugFrameCallback(ChoreographerCompat choreographer, ReactContext reactContext) {
<del> mChoreographer = choreographer;
<add> public FpsDebugFrameCallback(ReactContext reactContext) {
<ide> mReactContext = reactContext;
<ide> mUIManagerModule = reactContext.getNativeModule(UIManagerModule.class);
<ide> mDidJSUpdateUiDuringFrameDetector = new DidJSUpdateUiDuringFrameDetector();
<ide> public void doFrame(long l) {
<ide> mTimeToFps.put(System.currentTimeMillis(), info);
<ide> }
<ide> mExpectedNumFramesPrev = expectedNumFrames;
<del>
<del> mChoreographer.postFrameCallback(this);
<add> if (mChoreographer != null) {
<add> mChoreographer.postFrameCallback(this);
<add> }
<ide> }
<ide>
<ide> public void start() {
<ide> mShouldStop = false;
<ide> mReactContext.getCatalystInstance().addBridgeIdleDebugListener(
<ide> mDidJSUpdateUiDuringFrameDetector);
<ide> mUIManagerModule.setViewHierarchyUpdateDebugListener(mDidJSUpdateUiDuringFrameDetector);
<del> mChoreographer.postFrameCallback(this);
<add> final FpsDebugFrameCallback fpsDebugFrameCallback = this;
<add> UiThreadUtil.runOnUiThread(new Runnable() {
<add> @Override
<add> public void run() {
<add> mChoreographer = ChoreographerCompat.getInstance();
<add> mChoreographer.postFrameCallback(fpsDebugFrameCallback);
<add> }
<add> });
<ide> }
<ide>
<ide> public void startAndRecordFpsAtEachFrame() { | 3 |
Go | Go | add missing json check | 801a7fed19643b7b89929daf53b37e0630e05586 | <ide><path>api/server/server.go
<ide> func (s *Server) postContainerExecCreate(version version.Version, w http.Respons
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<add> if err := checkForJson(r); err != nil {
<add> return err
<add> }
<ide> name := vars["name"]
<ide>
<ide> execConfig := &runconfig.ExecConfig{}
<ide><path>integration-cli/docker_api_exec_test.go
<ide> package main
<ide>
<ide> import (
<ide> "bytes"
<add> "encoding/json"
<ide> "fmt"
<ide> "net/http"
<ide> "os/exec"
<ide> func (s *DockerSuite) TestExecApiCreateNoCmd(c *check.C) {
<ide> c.Fatalf("Expected message when creating exec command with no Cmd specified")
<ide> }
<ide> }
<add>
<add>func (s *DockerSuite) TestExecApiCreateNoValidContentType(c *check.C) {
<add> name := "exec_test"
<add> dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh")
<add>
<add> jsonData := bytes.NewBuffer(nil)
<add> if err := json.NewEncoder(jsonData).Encode(map[string]interface{}{"Cmd": nil}); err != nil {
<add> c.Fatalf("Can not encode data to json %s", err)
<add> }
<add>
<add> res, body, err := sockRequestRaw("POST", fmt.Sprintf("/containers/%s/exec", name), jsonData, "text/plain")
<add> c.Assert(err, check.IsNil)
<add> c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError)
<add>
<add> b, err := readBody(body)
<add> c.Assert(err, check.IsNil)
<add>
<add> if !bytes.Contains(b, []byte("Content-Type specified")) {
<add> c.Fatalf("Expected message when creating exec command with invalid Content-Type specified")
<add> }
<add>} | 2 |
PHP | PHP | remove unnecessary whitespace | 4341e3c9339f29b00289650a39b6244bbbcd04c1 | <ide><path>config/broadcasting.php
<ide> 'driver' => 'redis',
<ide> 'connection' => 'default',
<ide> ],
<del>
<add>
<ide> 'log' => [
<ide> 'driver' => 'log',
<ide> ], | 1 |
Ruby | Ruby | fix a failing mailer test | 6bf9b69bdeaba794d6ec55a6501723d24e7f98e0 | <ide><path>actionmailer/test/mail_service_test.rb
<ide> def test_starttls_is_not_enabled
<ide>
<ide> class InheritableTemplateRootTest < Test::Unit::TestCase
<ide> def test_attr
<del> expected = ("#{File.dirname(__FILE__)}/fixtures/path.with.dots").sub(/\.\//, '')
<add> expected = "#{File.dirname(__FILE__)}/fixtures/path.with.dots"
<ide> assert_equal expected, FunkyPathMailer.template_root.to_s
<ide>
<ide> sub = Class.new(FunkyPathMailer) | 1 |
PHP | PHP | remove code duplication | 68f61a0efa2b191cf59101868373231093c99594 | <ide><path>src/Http/Client/Response.php
<ide> namespace Cake\Http\Client;
<ide>
<ide> use Cake\Http\Cookie\CookieCollection;
<del>use Cake\Http\Cookie\CookieInterface;
<ide> use Psr\Http\Message\ResponseInterface;
<ide> use RuntimeException;
<ide> use SimpleXMLElement;
<ide> public function getCookieData(string $name): ?array
<ide> return null;
<ide> }
<ide>
<del> $cookie = $this->cookies->get($name);
<del>
<del> return $this->convertCookieToArray($cookie);
<del> }
<del>
<del> /**
<del> * Convert the cookie into an array of its properties.
<del> *
<del> * This method is compatible with older client code that
<del> * expects date strings instead of timestamps.
<del> *
<del> * @param \Cake\Http\Cookie\CookieInterface $cookie Cookie object.
<del> * @return array
<del> */
<del> protected function convertCookieToArray(CookieInterface $cookie): array
<del> {
<del> return [
<del> 'name' => $cookie->getName(),
<del> 'value' => $cookie->getValue(),
<del> 'path' => $cookie->getPath(),
<del> 'domain' => $cookie->getDomain(),
<del> 'secure' => $cookie->isSecure(),
<del> 'httponly' => $cookie->isHttpOnly(),
<del> 'expires' => $cookie->getFormattedExpires(),
<del> ];
<add> return $this->cookies->get($name)->toArray();
<ide> }
<ide>
<ide> /**
<ide> protected function _getCookies(): array
<ide> /** @var \Cake\Http\Cookie\Cookie[] $cookies */
<ide> $cookies = $this->cookies;
<ide> foreach ($cookies as $cookie) {
<del> $out[$cookie->getName()] = $this->convertCookieToArray($cookie);
<add> $out[$cookie->getName()] = $cookie->toArray();
<ide> }
<ide>
<ide> return $out;
<ide><path>tests/TestCase/Http/Client/ResponseTest.php
<ide> public function testGetCookies()
<ide>
<ide> $result = $response->getCookieData('expiring');
<ide> $this->assertSame('soon', $result['value']);
<del> $this->assertTrue($result['httponly']);
<del> $this->assertTrue($result['secure']);
<add> $this->assertTrue($result['options']['httponly']);
<add> $this->assertTrue($result['options']['secure']);
<ide> $this->assertEquals(
<del> 'Wed, 09-Jun-2021 10:18:14 GMT',
<del> $result['expires']
<add> strtotime('Wed, 09-Jun-2021 10:18:14 GMT'),
<add> $result['options']['expires']
<ide> );
<del> $this->assertSame('/', $result['path']);
<add> $this->assertSame('/', $result['options']['path']);
<ide>
<ide> $result = $response->getCookies();
<ide> $this->assertCount(3, $result); | 2 |
PHP | PHP | fix error message | d65fd83656bca17ade879eed3861499c98f18bb1 | <ide><path>src/Http/ActionDispatcher.php
<ide> protected function _invoke(Controller $controller)
<ide>
<ide> $response = $controller->invokeAction();
<ide> if ($response !== null && !($response instanceof Response)) {
<del> throw new LogicException('Controller actions can only Cake\Network\Response instances');
<add> throw new LogicException('Controller actions can only return Cake\Network\Response or null.');
<ide> }
<ide>
<ide> if (!$response && $controller->autoRender) { | 1 |
Javascript | Javascript | add pug to prism languages | deb7fcc362d17e44eb63e7eb2afb4c33f21a7956 | <ide><path>client/.babelrc.js
<ide> const config = {
<ide> 'javascript',
<ide> 'markup',
<ide> 'mathml',
<add> 'pug',
<ide> 'python',
<del> 'svg',
<del> 'xml',
<ide> 'sql',
<del> 'typescript'
<add> 'svg',
<add> 'typescript',
<add> 'xml'
<ide> ],
<ide> theme: 'default',
<ide> css: true, | 1 |
Ruby | Ruby | improve serialization doc | e34a4014ad2bf1d52c934f06093d179f469c62ac | <ide><path>activemodel/lib/active_model/serialization.rb
<ide> module ActiveModel
<ide> # person.serializable_hash # => {"name"=>"Bob"}
<ide> #
<ide> # You need to declare an attributes hash which contains the attributes
<del> # you want to serialize. When called, serializable hash will use
<add> # you want to serialize. Attributes must be strings, not symbols.
<add> # When called, serializable hash will use
<ide> # instance methods that match the name of the attributes hash's keys.
<ide> # In order to override this behavior, take a look at the private
<del> # method read_attribute_for_serialization.
<add> # method ++read_attribute_for_serialization++.
<ide> #
<ide> # Most of the time though, you will want to include the JSON or XML
<ide> # serializations. Both of these modules automatically include the
<del> # ActiveModel::Serialization module, so there is no need to explicitly
<add> # ++ActiveModel::Serialization++ module, so there is no need to explicitly
<ide> # include it.
<ide> #
<del> # So a minimal implementation including XML and JSON would be:
<add> # A minimal implementation including XML and JSON would be:
<ide> #
<ide> # class Person
<ide> # include ActiveModel::Serializers::JSON | 1 |
Java | Java | fix expression cache | 397aa8298492d74ab64bff900229c11d2f5c5112 | <ide><path>spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java
<ide> protected class CacheOperationContext implements CacheOperationInvocationContext
<ide>
<ide> private final Collection<? extends Cache> caches;
<ide>
<add> private final MethodCacheKey methodCacheKey;
<add>
<ide> public CacheOperationContext(CacheOperationMetadata metadata,
<ide> Object[] args, Object target) {
<ide> this.metadata = metadata;
<ide> this.args = extractArgs(metadata.method, args);
<ide> this.target = target;
<ide> this.caches = CacheAspectSupport.this.getCaches(this, metadata.cacheResolver);
<add> this.methodCacheKey = new MethodCacheKey(metadata.method, metadata.targetClass);
<ide> }
<ide>
<ide> @Override
<ide> private Object[] extractArgs(Method method, Object[] args) {
<ide> protected boolean isConditionPassing(Object result) {
<ide> if (StringUtils.hasText(this.metadata.operation.getCondition())) {
<ide> EvaluationContext evaluationContext = createEvaluationContext(result);
<del> return evaluator.condition(this.metadata.operation.getCondition(), this.metadata.method, evaluationContext);
<add> return evaluator.condition(this.metadata.operation.getCondition(), this.methodCacheKey, evaluationContext);
<ide> }
<ide> return true;
<ide> }
<ide> else if (this.metadata.operation instanceof CachePutOperation) {
<ide> }
<ide> if (StringUtils.hasText(unless)) {
<ide> EvaluationContext evaluationContext = createEvaluationContext(value);
<del> return !evaluator.unless(unless, this.metadata.method, evaluationContext);
<add> return !evaluator.unless(unless, this.methodCacheKey, evaluationContext);
<ide> }
<ide> return true;
<ide> }
<ide> else if (this.metadata.operation instanceof CachePutOperation) {
<ide> protected Object generateKey(Object result) {
<ide> if (StringUtils.hasText(this.metadata.operation.getKey())) {
<ide> EvaluationContext evaluationContext = createEvaluationContext(result);
<del> return evaluator.key(this.metadata.operation.getKey(), this.metadata.method, evaluationContext);
<add> return evaluator.key(this.metadata.operation.getKey(), this.methodCacheKey, evaluationContext);
<ide> }
<ide> return metadata.keyGenerator.generate(this.target, this.metadata.method, this.args);
<ide> }
<ide><path>spring-context/src/main/java/org/springframework/cache/interceptor/ExpressionEvaluator.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import org.springframework.expression.EvaluationContext;
<ide> import org.springframework.expression.Expression;
<ide> import org.springframework.expression.spel.standard.SpelExpressionParser;
<add>import org.springframework.util.ObjectUtils;
<ide>
<ide> /**
<ide> * Utility class handling the SpEL expression parsing.
<ide> * Meant to be used as a reusable, thread-safe component.
<ide> *
<del> * <p>Performs internal caching for performance reasons.
<add> * <p>Performs internal caching for performance reasons
<add> * using {@link MethodCacheKey}.
<ide> *
<ide> * @author Costin Leau
<ide> * @author Phillip Webb
<ide> * @author Sam Brannen
<add> * @author Stephane Nicoll
<ide> * @since 3.1
<ide> */
<ide> class ExpressionEvaluator {
<ide> class ExpressionEvaluator {
<ide> // shared param discoverer since it caches data internally
<ide> private final ParameterNameDiscoverer paramNameDiscoverer = new DefaultParameterNameDiscoverer();
<ide>
<del> private final Map<String, Expression> keyCache = new ConcurrentHashMap<String, Expression>(64);
<add> private final Map<ExpressionKey, Expression> keyCache
<add> = new ConcurrentHashMap<ExpressionKey, Expression>(64);
<ide>
<del> private final Map<String, Expression> conditionCache = new ConcurrentHashMap<String, Expression>(64);
<add> private final Map<ExpressionKey, Expression> conditionCache
<add> = new ConcurrentHashMap<ExpressionKey, Expression>(64);
<ide>
<del> private final Map<String, Expression> unlessCache = new ConcurrentHashMap<String, Expression>(64);
<add> private final Map<ExpressionKey, Expression> unlessCache
<add> = new ConcurrentHashMap<ExpressionKey, Expression>(64);
<ide>
<del> private final Map<String, Method> targetMethodCache = new ConcurrentHashMap<String, Method>(64);
<add> private final Map<MethodCacheKey, Method> targetMethodCache = new ConcurrentHashMap<MethodCacheKey, Method>(64);
<ide>
<ide>
<ide> /**
<ide> public EvaluationContext createEvaluationContext(Collection<? extends Cache> cac
<ide> return evaluationContext;
<ide> }
<ide>
<del> public Object key(String keyExpression, Method method, EvaluationContext evalContext) {
<del> return getExpression(this.keyCache, keyExpression, method).getValue(evalContext);
<add> public Object key(String keyExpression, MethodCacheKey methodKey, EvaluationContext evalContext) {
<add> return getExpression(this.keyCache, keyExpression, methodKey).getValue(evalContext);
<ide> }
<ide>
<del> public boolean condition(String conditionExpression, Method method, EvaluationContext evalContext) {
<del> return getExpression(this.conditionCache, conditionExpression, method).getValue(
<add> public boolean condition(String conditionExpression, MethodCacheKey methodKey, EvaluationContext evalContext) {
<add> return getExpression(this.conditionCache, conditionExpression, methodKey).getValue(
<ide> evalContext, boolean.class);
<ide> }
<ide>
<del> public boolean unless(String unlessExpression, Method method, EvaluationContext evalContext) {
<del> return getExpression(this.unlessCache, unlessExpression, method).getValue(
<add> public boolean unless(String unlessExpression, MethodCacheKey methodKey, EvaluationContext evalContext) {
<add> return getExpression(this.unlessCache, unlessExpression, methodKey).getValue(
<ide> evalContext, boolean.class);
<ide> }
<ide>
<del> private Expression getExpression(Map<String, Expression> cache, String expression, Method method) {
<del> String key = toString(method, expression);
<add> private Expression getExpression(Map<ExpressionKey, Expression> cache, String expression, MethodCacheKey methodKey) {
<add> ExpressionKey key = createKey(methodKey, expression);
<ide> Expression rtn = cache.get(key);
<ide> if (rtn == null) {
<ide> rtn = this.parser.parseExpression(expression);
<ide> private Expression getExpression(Map<String, Expression> cache, String expressio
<ide> return rtn;
<ide> }
<ide>
<del> private String toString(Method method, String expression) {
<del> StringBuilder sb = new StringBuilder();
<del> sb.append(method.getDeclaringClass().getName());
<del> sb.append("#");
<del> sb.append(method.toString());
<del> sb.append("#");
<del> sb.append(expression);
<del> return sb.toString();
<add> private ExpressionKey createKey(MethodCacheKey methodCacheKey, String expression) {
<add> return new ExpressionKey(methodCacheKey, expression);
<ide> }
<add>
<add>
<add> private static class ExpressionKey {
<add> private final MethodCacheKey methodCacheKey;
<add> private final String expression;
<add>
<add> private ExpressionKey(MethodCacheKey methodCacheKey, String expression) {
<add> this.methodCacheKey = methodCacheKey;
<add> this.expression = expression;
<add> }
<add>
<add> @Override
<add> public boolean equals(Object other) {
<add> if (this == other) {
<add> return true;
<add> }
<add> if (!(other instanceof ExpressionKey)) {
<add> return false;
<add> }
<add> ExpressionKey otherKey = (ExpressionKey) other;
<add> return (this.methodCacheKey.equals(otherKey.methodCacheKey)
<add> && ObjectUtils.nullSafeEquals(this.expression, otherKey.expression));
<add> }
<add>
<add> @Override
<add> public int hashCode() {
<add> return this.methodCacheKey.hashCode() * 29 + (this.expression != null ? this.expression.hashCode() : 0);
<add> }
<add> }
<add>
<ide> }
<ide><path>spring-context/src/main/java/org/springframework/cache/interceptor/LazyParamAwareEvaluationContext.java
<ide> /*
<del> * Copyright 2002-2011 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * (rather then a dedicated 'closure'-like class for deferred execution).
<ide> *
<ide> * @author Costin Leau
<add> * @author Stephane Nicoll
<ide> * @since 3.1
<ide> */
<ide> class LazyParamAwareEvaluationContext extends StandardEvaluationContext {
<ide> class LazyParamAwareEvaluationContext extends StandardEvaluationContext {
<ide>
<ide> private final Class<?> targetClass;
<ide>
<del> private final Map<String, Method> methodCache;
<add> private final Map<MethodCacheKey, Method> methodCache;
<ide>
<ide> private boolean paramLoaded = false;
<ide>
<ide>
<ide> LazyParamAwareEvaluationContext(Object rootObject, ParameterNameDiscoverer paramDiscoverer, Method method,
<del> Object[] args, Class<?> targetClass, Map<String, Method> methodCache) {
<add> Object[] args, Class<?> targetClass, Map<MethodCacheKey, Method> methodCache) {
<ide> super(rootObject);
<ide>
<ide> this.paramDiscoverer = paramDiscoverer;
<ide> private void loadArgsAsVariables() {
<ide> return;
<ide> }
<ide>
<del> String methodKey = toString(this.method);
<add> MethodCacheKey methodKey = new MethodCacheKey(this.method, this.targetClass);
<ide> Method targetMethod = this.methodCache.get(methodKey);
<ide> if (targetMethod == null) {
<ide> targetMethod = AopUtils.getMostSpecificMethod(this.method, this.targetClass);
<ide> private void loadArgsAsVariables() {
<ide> }
<ide> }
<ide>
<del> private String toString(Method m) {
<del> StringBuilder sb = new StringBuilder();
<del> sb.append(m.getDeclaringClass().getName());
<del> sb.append("#");
<del> sb.append(m.toString());
<del> return sb.toString();
<del> }
<ide> }
<ide><path>spring-context/src/main/java/org/springframework/cache/interceptor/MethodCacheKey.java
<ide> *
<ide> * @author Costin Leau
<ide> * @author Stephane Nicoll
<del> * @since 4.1
<add> * @since 4.0.4
<ide> */
<ide> public final class MethodCacheKey {
<ide>
<ide><path>spring-context/src/test/java/org/springframework/cache/config/ExpressionCachingIntegrationTests.java
<add>/*
<add> * Copyright 2002-2014 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.cache.config;
<add>
<add>import org.junit.Test;
<add>
<add>import org.springframework.cache.CacheManager;
<add>import org.springframework.cache.annotation.CachePut;
<add>import org.springframework.cache.annotation.CachingConfigurerSupport;
<add>import org.springframework.cache.annotation.EnableCaching;
<add>import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
<add>import org.springframework.context.ConfigurableApplicationContext;
<add>import org.springframework.context.annotation.AnnotationConfigApplicationContext;
<add>import org.springframework.context.annotation.Bean;
<add>import org.springframework.context.annotation.Configuration;
<add>
<add>/**
<add> *
<add> * @author Stephane Nicoll
<add> */
<add>public class ExpressionCachingIntegrationTests {
<add>
<add> @SuppressWarnings("unchecked")
<add> @Test // SPR-11692
<add> public void expressionIsCacheBasedOnActualMethod() {
<add> ConfigurableApplicationContext context =
<add> new AnnotationConfigApplicationContext(SharedConfig.class, Spr11692Config.class);
<add>
<add> BaseDao<User> userDao = (BaseDao<User>) context.getBean("userDao");
<add> BaseDao<Order> orderDao = (BaseDao<Order>) context.getBean("orderDao");
<add>
<add> userDao.persist(new User("1"));
<add> orderDao.persist(new Order("2"));
<add>
<add> context.close();
<add> }
<add>
<add>
<add>
<add> @Configuration
<add> static class Spr11692Config {
<add> @Bean
<add> public BaseDao<User> userDao() {
<add> return new UserDaoImpl();
<add> }
<add>
<add> @Bean
<add> public BaseDao<Order> orderDao() {
<add> return new OrderDaoImpl();
<add> }
<add> }
<add>
<add>
<add> private static interface BaseDao<T> {
<add> T persist(T t);
<add> }
<add>
<add> private static class UserDaoImpl implements BaseDao<User> {
<add> @Override
<add> @CachePut(value = "users", key = "#user.id")
<add> public User persist(User user) {
<add> return user;
<add> }
<add> }
<add>
<add> private static class OrderDaoImpl implements BaseDao<Order> {
<add> @Override
<add> @CachePut(value = "orders", key = "#order.id")
<add> public Order persist(Order order) {
<add> return order;
<add> }
<add> }
<add>
<add> private static class User {
<add> private final String id;
<add>
<add> private User(String id) {
<add> this.id = id;
<add> }
<add>
<add> public String getId() {
<add> return id;
<add> }
<add> }
<add>
<add> private static class Order {
<add> private final String id;
<add>
<add> private Order(String id) {
<add> this.id = id;
<add> }
<add>
<add> public String getId() {
<add> return id;
<add> }
<add> }
<add>
<add> @Configuration
<add> @EnableCaching
<add> static class SharedConfig extends CachingConfigurerSupport {
<add> @Override
<add> @Bean
<add> public CacheManager cacheManager() {
<add> return new ConcurrentMapCacheManager();
<add> }
<add> }
<add>
<add>}
<ide><path>spring-context/src/test/java/org/springframework/cache/interceptor/ExpressionEvaluatorTests.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @author Costin Leau
<ide> * @author Phillip Webb
<ide> * @author Sam Brannen
<add> * @author Stephane Nicoll
<ide> */
<ide> public class ExpressionEvaluatorTests {
<ide>
<ide> public void testMultipleCachingEval() throws Exception {
<ide>
<ide> Iterator<CacheOperation> it = ops.iterator();
<ide>
<del> Object keyA = eval.key(it.next().getKey(), method, evalCtx);
<del> Object keyB = eval.key(it.next().getKey(), method, evalCtx);
<add> MethodCacheKey key = new MethodCacheKey(method, AnnotatedClass.class);
<add>
<add> Object keyA = eval.key(it.next().getKey(), key, evalCtx);
<add> Object keyB = eval.key(it.next().getKey(), key, evalCtx);
<ide>
<ide> assertEquals(args[0], keyA);
<ide> assertEquals(args[1], keyB); | 6 |
Text | Text | fix 3.x examples. fixes | c5ce7d1ef93b077cdf7cb704b712242955717993 | <ide><path>CHANGES.md
<ide> x.domain(); // [0, 1]
<ide> The *ordinal*.rangeBands and *ordinal*.rangeRoundBands methods have been replaced with a new subclass of ordinal scale: [band scales](https://github.com/d3/d3-scale#band-scales). The following code in 3.x:
<ide>
<ide> ```js
<del>var x = d3.scaleOrdinal()
<add>var x = d3.scale.ordinal()
<ide> .domain(["a", "b", "c"])
<ide> .rangeBands([0, width]);
<ide> ```
<ide> The new [*band*.padding](https://github.com/d3/d3-scale#band_padding), [*band*.p
<ide> Similarly, the *ordinal*.rangePoints and *ordinal*.rangeRoundPoints methods have been replaced with a new subclass of ordinal scale: [point scales](https://github.com/d3/d3-scale#point-scales). The following code in 3.x:
<ide>
<ide> ```js
<del>var x = d3.scaleOrdinal()
<add>var x = d3.scale.ordinal()
<ide> .domain(["a", "b", "c"])
<ide> .rangePoints([0, width]);
<ide> ```
<ide> The [ordinal scale constructor](https://github.com/d3/d3-scale#ordinal-scales) n
<ide> The following code in 3.x:
<ide>
<ide> ```js
<del>var color = d3.scaleCategory10();
<add>var color = d3.scale.category10();
<ide> ```
<ide>
<ide> Is equivalent to this in 4.0: | 1 |
Python | Python | remove 3.10 deprecations | db37512a6e4fa5ba793b7e401d7014dfd0984995 | <ide><path>rest_framework/__init__.py
<ide> default_app_config = 'rest_framework.apps.RestFrameworkConfig'
<ide>
<ide>
<del>class RemovedInDRF310Warning(DeprecationWarning):
<add>class RemovedInDRF311Warning(DeprecationWarning):
<ide> pass
<ide>
<ide>
<del>class RemovedInDRF311Warning(PendingDeprecationWarning):
<add>class RemovedInDRF312Warning(PendingDeprecationWarning):
<ide> pass
<ide><path>rest_framework/compat.py
<ide> def distinct(queryset, base):
<ide> requests = None
<ide>
<ide>
<del>def is_guardian_installed():
<del> """
<del> django-guardian is optional and only imported if in INSTALLED_APPS.
<del> """
<del> return 'guardian' in settings.INSTALLED_APPS
<del>
<del>
<ide> # PATCH method is not implemented by Django
<ide> if 'patch' not in View.http_method_names:
<ide> View.http_method_names = View.http_method_names + ['patch']
<ide><path>rest_framework/decorators.py
<ide> used to annotate methods on viewsets that should be included by routers.
<ide> """
<ide> import types
<del>import warnings
<ide>
<ide> from django.forms.utils import pretty_name
<ide>
<del>from rest_framework import RemovedInDRF310Warning
<ide> from rest_framework.views import APIView
<ide>
<ide>
<ide> def options(self, func):
<ide>
<ide> def trace(self, func):
<ide> return self._map('trace', func)
<del>
<del>
<del>def detail_route(methods=None, **kwargs):
<del> """
<del> Used to mark a method on a ViewSet that should be routed for detail requests.
<del> """
<del> warnings.warn(
<del> "`detail_route` is deprecated and will be removed in 3.10 in favor of "
<del> "`action`, which accepts a `detail` bool. Use `@action(detail=True)` instead.",
<del> RemovedInDRF310Warning, stacklevel=2
<del> )
<del>
<del> def decorator(func):
<del> func = action(methods, detail=True, **kwargs)(func)
<del> if 'url_name' not in kwargs:
<del> func.url_name = func.url_path.replace('_', '-')
<del> return func
<del> return decorator
<del>
<del>
<del>def list_route(methods=None, **kwargs):
<del> """
<del> Used to mark a method on a ViewSet that should be routed for list requests.
<del> """
<del> warnings.warn(
<del> "`list_route` is deprecated and will be removed in 3.10 in favor of "
<del> "`action`, which accepts a `detail` bool. Use `@action(detail=False)` instead.",
<del> RemovedInDRF310Warning, stacklevel=2
<del> )
<del>
<del> def decorator(func):
<del> func = action(methods, detail=False, **kwargs)(func)
<del> if 'url_name' not in kwargs:
<del> func.url_name = func.url_path.replace('_', '-')
<del> return func
<del> return decorator
<ide><path>rest_framework/filters.py
<ide> returned by list views.
<ide> """
<ide> import operator
<del>import warnings
<ide> from functools import reduce
<ide>
<ide> from django.core.exceptions import ImproperlyConfigured
<ide> from django.utils.encoding import force_text
<ide> from django.utils.translation import gettext_lazy as _
<ide>
<del>from rest_framework import RemovedInDRF310Warning
<del>from rest_framework.compat import (
<del> coreapi, coreschema, distinct, is_guardian_installed
<del>)
<add>from rest_framework.compat import coreapi, coreschema, distinct
<ide> from rest_framework.settings import api_settings
<ide>
<ide>
<ide> def get_schema_operation_parameters(self, view):
<ide> },
<ide> },
<ide> ]
<del>
<del>
<del>class DjangoObjectPermissionsFilter(BaseFilterBackend):
<del> """
<del> A filter backend that limits results to those where the requesting user
<del> has read object level permissions.
<del> """
<del> def __init__(self):
<del> warnings.warn(
<del> "`DjangoObjectPermissionsFilter` has been deprecated and moved to "
<del> "the 3rd-party django-rest-framework-guardian package.",
<del> RemovedInDRF310Warning, stacklevel=2
<del> )
<del> assert is_guardian_installed(), 'Using DjangoObjectPermissionsFilter, but django-guardian is not installed'
<del>
<del> perm_format = '%(app_label)s.view_%(model_name)s'
<del>
<del> def filter_queryset(self, request, queryset, view):
<del> # We want to defer this import until run-time, rather than import-time.
<del> # See https://github.com/encode/django-rest-framework/issues/4608
<del> # (Also see #1624 for why we need to make this import explicitly)
<del> from guardian import VERSION as guardian_version
<del> from guardian.shortcuts import get_objects_for_user
<del>
<del> extra = {}
<del> user = request.user
<del> model_cls = queryset.model
<del> kwargs = {
<del> 'app_label': model_cls._meta.app_label,
<del> 'model_name': model_cls._meta.model_name
<del> }
<del> permission = self.perm_format % kwargs
<del> if tuple(guardian_version) >= (1, 3):
<del> # Maintain behavior compatibility with versions prior to 1.3
<del> extra = {'accept_global_perms': False}
<del> else:
<del> extra = {}
<del> return get_objects_for_user(user, permission, queryset, **extra)
<ide><path>rest_framework/routers.py
<ide> from django.urls import NoReverseMatch
<ide> from django.utils.deprecation import RenameMethodsBase
<ide>
<del>from rest_framework import (
<del> RemovedInDRF310Warning, RemovedInDRF311Warning, views
<del>)
<add>from rest_framework import RemovedInDRF311Warning, views
<ide> from rest_framework.response import Response
<ide> from rest_framework.reverse import reverse
<ide> from rest_framework.schemas import SchemaGenerator
<ide> DynamicRoute = namedtuple('DynamicRoute', ['url', 'name', 'detail', 'initkwargs'])
<ide>
<ide>
<del>class DynamicDetailRoute:
<del> def __new__(cls, url, name, initkwargs):
<del> warnings.warn(
<del> "`DynamicDetailRoute` is deprecated and will be removed in 3.10 "
<del> "in favor of `DynamicRoute`, which accepts a `detail` boolean. Use "
<del> "`DynamicRoute(url, name, True, initkwargs)` instead.",
<del> RemovedInDRF310Warning, stacklevel=2
<del> )
<del> return DynamicRoute(url, name, True, initkwargs)
<del>
<del>
<del>class DynamicListRoute:
<del> def __new__(cls, url, name, initkwargs):
<del> warnings.warn(
<del> "`DynamicListRoute` is deprecated and will be removed in 3.10 in "
<del> "favor of `DynamicRoute`, which accepts a `detail` boolean. Use "
<del> "`DynamicRoute(url, name, False, initkwargs)` instead.",
<del> RemovedInDRF310Warning, stacklevel=2
<del> )
<del> return DynamicRoute(url, name, False, initkwargs)
<del>
<del>
<ide> def escape_curly_brackets(url_path):
<ide> """
<ide> Double brackets in regex of url_path for escape string formatting
<ide><path>tests/test_decorators.py
<ide> import pytest
<ide> from django.test import TestCase
<ide>
<del>from rest_framework import RemovedInDRF310Warning, status
<add>from rest_framework import status
<ide> from rest_framework.authentication import BasicAuthentication
<ide> from rest_framework.decorators import (
<del> action, api_view, authentication_classes, detail_route, list_route,
<del> parser_classes, permission_classes, renderer_classes, schema,
<del> throttle_classes
<add> action, api_view, authentication_classes, parser_classes,
<add> permission_classes, renderer_classes, schema, throttle_classes
<ide> )
<ide> from rest_framework.parsers import JSONParser
<ide> from rest_framework.permissions import IsAuthenticated
<ide> def test_action():
<ide> @test_action.mapping.post
<ide> def test_action():
<ide> raise NotImplementedError
<del>
<del> def test_detail_route_deprecation(self):
<del> with pytest.warns(RemovedInDRF310Warning) as record:
<del> @detail_route()
<del> def view(request):
<del> raise NotImplementedError
<del>
<del> assert len(record) == 1
<del> assert str(record[0].message) == (
<del> "`detail_route` is deprecated and will be removed in "
<del> "3.10 in favor of `action`, which accepts a `detail` bool. Use "
<del> "`@action(detail=True)` instead."
<del> )
<del>
<del> def test_list_route_deprecation(self):
<del> with pytest.warns(RemovedInDRF310Warning) as record:
<del> @list_route()
<del> def view(request):
<del> raise NotImplementedError
<del>
<del> assert len(record) == 1
<del> assert str(record[0].message) == (
<del> "`list_route` is deprecated and will be removed in "
<del> "3.10 in favor of `action`, which accepts a `detail` bool. Use "
<del> "`@action(detail=False)` instead."
<del> )
<del>
<del> def test_route_url_name_from_path(self):
<del> # pre-3.8 behavior was to base the `url_name` off of the `url_path`
<del> with pytest.warns(RemovedInDRF310Warning):
<del> @list_route(url_path='foo_bar')
<del> def view(request):
<del> raise NotImplementedError
<del>
<del> assert view.url_path == 'foo_bar'
<del> assert view.url_name == 'foo-bar'
<ide><path>tests/test_permissions.py
<ide> import base64
<ide> import unittest
<del>import warnings
<ide> from unittest import mock
<ide>
<ide> import django
<ide> import pytest
<add>from django.conf import settings
<ide> from django.contrib.auth.models import AnonymousUser, Group, Permission, User
<ide> from django.db import models
<ide> from django.test import TestCase
<ide> from django.urls import ResolverMatch
<ide>
<ide> from rest_framework import (
<del> HTTP_HEADER_ENCODING, RemovedInDRF310Warning, authentication, generics,
<del> permissions, serializers, status, views
<add> HTTP_HEADER_ENCODING, authentication, generics, permissions, serializers,
<add> status, views
<ide> )
<del>from rest_framework.compat import PY36, is_guardian_installed
<del>from rest_framework.filters import DjangoObjectPermissionsFilter
<add>from rest_framework.compat import PY36
<ide> from rest_framework.routers import DefaultRouter
<ide> from rest_framework.test import APIRequestFactory
<ide> from tests.models import BasicModel
<ide> def get_queryset(self):
<ide> get_queryset_object_permissions_view = GetQuerysetObjectPermissionInstanceView.as_view()
<ide>
<ide>
<del>@unittest.skipUnless(is_guardian_installed(), 'django-guardian not installed')
<add>@unittest.skipUnless('guardian' in settings.INSTALLED_APPS, 'django-guardian not installed')
<ide> class ObjectPermissionsIntegrationTests(TestCase):
<ide> """
<ide> Integration tests for the object level permissions API.
<ide> def test_can_read_get_queryset_permissions(self):
<ide> self.assertEqual(response.status_code, status.HTTP_200_OK)
<ide>
<ide> # Read list
<del> def test_django_object_permissions_filter_deprecated(self):
<del> with warnings.catch_warnings(record=True) as w:
<del> warnings.simplefilter("always")
<del> DjangoObjectPermissionsFilter()
<del>
<del> message = ("`DjangoObjectPermissionsFilter` has been deprecated and moved "
<del> "to the 3rd-party django-rest-framework-guardian package.")
<del> self.assertEqual(len(w), 1)
<del> self.assertIs(w[-1].category, RemovedInDRF310Warning)
<del> self.assertEqual(str(w[-1].message), message)
<del>
<add> # Note: this previously tested `DjangoObjectPermissionsFilter`, which has
<add> # since been moved to a separate package. These now act as sanity checks.
<ide> def test_can_read_list_permissions(self):
<ide> request = factory.get('/', HTTP_AUTHORIZATION=self.credentials['readonly'])
<del> object_permissions_list_view.cls.filter_backends = (DjangoObjectPermissionsFilter,)
<del> # TODO: remove in version 3.10
<del> with warnings.catch_warnings(record=True):
<del> warnings.simplefilter("always")
<del> response = object_permissions_list_view(request)
<add> response = object_permissions_list_view(request)
<ide> self.assertEqual(response.status_code, status.HTTP_200_OK)
<ide> self.assertEqual(response.data[0].get('id'), 1)
<ide>
<del> def test_cannot_read_list_permissions(self):
<del> request = factory.get('/', HTTP_AUTHORIZATION=self.credentials['writeonly'])
<del> object_permissions_list_view.cls.filter_backends = (DjangoObjectPermissionsFilter,)
<del> # TODO: remove in version 3.10
<del> with warnings.catch_warnings(record=True):
<del> warnings.simplefilter("always")
<del> response = object_permissions_list_view(request)
<del> self.assertEqual(response.status_code, status.HTTP_200_OK)
<del> self.assertListEqual(response.data, [])
<del>
<ide> def test_cannot_method_not_allowed(self):
<ide> request = factory.generic('METHOD_NOT_ALLOWED', '/', HTTP_AUTHORIZATION=self.credentials['readonly'])
<ide> response = object_permissions_list_view(request) | 7 |
Javascript | Javascript | prepare semver (`@latest`) releases in ci | 8f379427657ff1be5b25904864da54c7acfc8d64 | <ide><path>scripts/rollup/build-all-release-channels.js
<ide> function processStable(buildDir) {
<ide> updatePackageVersions(
<ide> buildDir + '/node_modules',
<ide> versionsMap,
<del> defaultVersionIfNotFound
<add> defaultVersionIfNotFound,
<add> true
<ide> );
<ide> fs.renameSync(buildDir + '/node_modules', buildDir + '/oss-stable');
<add>
<add> // Identical to `oss-stable` but with real, semver versions. This is what
<add> // will get published to @latest.
<add> spawnSync('cp', [
<add> '-r',
<add> buildDir + '/oss-stable',
<add> buildDir + '/oss-stable-semver',
<add> ]);
<add> const semverVersionsMap = new Map();
<add> for (const moduleName in stablePackages) {
<add> const version = stablePackages[moduleName];
<add> semverVersionsMap.set(moduleName, version);
<add> }
<add> updatePackageVersions(
<add> buildDir + '/oss-stable-semver',
<add> semverVersionsMap,
<add> defaultVersionIfNotFound,
<add> false
<add> );
<ide> }
<ide>
<ide> if (fs.existsSync(buildDir + '/facebook-www')) {
<ide> function processExperimental(buildDir, version) {
<ide> updatePackageVersions(
<ide> buildDir + '/node_modules',
<ide> versionsMap,
<del> defaultVersionIfNotFound
<add> defaultVersionIfNotFound,
<add> true
<ide> );
<ide> fs.renameSync(buildDir + '/node_modules', buildDir + '/oss-experimental');
<ide> }
<ide> function crossDeviceRenameSync(source, destination) {
<ide> function updatePackageVersions(
<ide> modulesDir,
<ide> versionsMap,
<del> defaultVersionIfNotFound
<add> defaultVersionIfNotFound,
<add> pinToExactVersion
<ide> ) {
<ide> for (const moduleName of fs.readdirSync(modulesDir)) {
<ide> let version = versionsMap.get(moduleName);
<ide> function updatePackageVersions(
<ide> if (packageInfo.dependencies) {
<ide> for (const dep of Object.keys(packageInfo.dependencies)) {
<ide> if (versionsMap.has(dep)) {
<del> packageInfo.dependencies[dep] = version;
<add> packageInfo.dependencies[dep] = pinToExactVersion
<add> ? version
<add> : '^' + version;
<ide> }
<ide> }
<ide> }
<ide> if (packageInfo.peerDependencies) {
<ide> for (const dep of Object.keys(packageInfo.peerDependencies)) {
<ide> if (versionsMap.has(dep)) {
<del> packageInfo.peerDependencies[dep] = version;
<add> packageInfo.peerDependencies[dep] = pinToExactVersion
<add> ? version
<add> : '^' + version;
<ide> }
<ide> }
<ide> } | 1 |
Go | Go | add debug output to manifest list parsing | 9a8cb9313c9c5eb535cf0bce25ca27f84bbfc570 | <ide><path>distribution/pull_v2.go
<ide> func (p *v2Puller) pullManifestList(ctx context.Context, ref reference.Named, mf
<ide> return "", "", err
<ide> }
<ide>
<add> logrus.Debugf("%s resolved to a manifestList object with %d entries; looking for a os/arch match", ref, len(mfstList.Manifests))
<ide> var manifestDigest digest.Digest
<ide> for _, manifestDescriptor := range mfstList.Manifests {
<ide> // TODO(aaronl): The manifest list spec supports optional
<ide> // "features" and "variant" fields. These are not yet used.
<ide> // Once they are, their values should be interpreted here.
<ide> if manifestDescriptor.Platform.Architecture == runtime.GOARCH && manifestDescriptor.Platform.OS == runtime.GOOS {
<ide> manifestDigest = manifestDescriptor.Digest
<add> logrus.Debugf("found match for %s/%s with media type %s, digest %s", runtime.GOOS, runtime.GOARCH, manifestDescriptor.MediaType, manifestDigest.String())
<ide> break
<ide> }
<ide> }
<ide>
<ide> if manifestDigest == "" {
<del> return "", "", errors.New("no supported platform found in manifest list")
<add> errMsg := fmt.Sprintf("no matching manifest for %s/%s in the manifest list entries", runtime.GOOS, runtime.GOARCH)
<add> logrus.Debugf(errMsg)
<add> return "", "", errors.New(errMsg)
<ide> }
<ide>
<ide> manSvc, err := p.repo.Manifests(ctx) | 1 |
Python | Python | add cluster instances to ec2 driver | bd88c2efeca57d50e53e38121d4946b35cac434d | <ide><path>libcloud/drivers/ec2.py
<ide> 'disk': 1690,
<ide> 'bandwidth': None
<ide> },
<add> 'cg1.4xlarge': {
<add> 'id': 'cg1.4xlarge',
<add> 'name': 'Cluster GPU Quadruple Extra Large Instance',
<add> 'ram': 22528,
<add> 'disk': 1690,
<add> 'bandwidth': None
<add> },
<add> 'cc1.4xlarge': {
<add> 'id': 'cc1.4xlarge',
<add> 'name': 'Cluster Compute Quadruple Extra Large Instance',
<add> 'ram': 23552,
<add> 'disk': 1690,
<add> 'bandwidth': None
<add> },
<ide> }
<ide>
<add>CLUSTER_INSTANCES_IDS = [ 'cg1.4xlarge', 'cc1.4xlarge' ]
<add>
<ide> EC2_US_EAST_INSTANCE_TYPES = dict(EC2_INSTANCE_TYPES)
<ide> EC2_US_WEST_INSTANCE_TYPES = dict(EC2_INSTANCE_TYPES)
<ide> EC2_EU_WEST_INSTANCE_TYPES = dict(EC2_INSTANCE_TYPES)
<ide> EC2_US_EAST_INSTANCE_TYPES['m2.xlarge']['price'] = '.50'
<ide> EC2_US_EAST_INSTANCE_TYPES['m2.2xlarge']['price'] = '1.2'
<ide> EC2_US_EAST_INSTANCE_TYPES['m2.4xlarge']['price'] = '2.4'
<add>EC2_US_EAST_INSTANCE_TYPES['cg1.4xlarge']['price'] = '2.1'
<add>EC2_US_EAST_INSTANCE_TYPES['cc1.4xlarge']['price'] = '1.6'
<ide>
<ide> EC2_US_WEST_INSTANCE_TYPES['t1.micro']['price'] = '.025'
<ide> EC2_US_WEST_INSTANCE_TYPES['m1.small']['price'] = '.095'
<ide> def list_nodes(self):
<ide> return nodes
<ide>
<ide> def list_sizes(self, location=None):
<del> return [ NodeSize(driver=self.connection.driver, **i)
<del> for i in self._instance_types.values() ]
<add> # Cluster instances are currently only available in the US - N. Virginia Region
<add> include_cluser_instances = self.region_name == 'us-east-1'
<add> sizes = self._get_sizes(include_cluser_instances =
<add> include_cluser_instances)
<add>
<add> return sizes
<add>
<add> def _get_sizes(self, include_cluser_instances=False):
<add> sizes = [ NodeSize(driver=self.connection.driver, **i)
<add> for i in self._instance_types.values() ]
<add>
<add> if not include_cluser_instances:
<add> sizes = [ size for size in sizes if \
<add> size.id not in CLUSTER_INSTANCES_IDS]
<add> return sizes
<ide>
<ide> def list_images(self, location=None):
<ide> params = {'Action': 'DescribeImages'}
<ide><path>test/test_ec2.py
<ide> def test_destroy_node(self):
<ide> self.assertTrue(ret)
<ide>
<ide> def test_list_sizes(self):
<del> sizes = self.driver.list_sizes()
<del> self.assertEqual(len(sizes), 9)
<del>
<del> ids = [s.id for s in sizes]
<del> self.assertTrue('t1.micro' in ids)
<del> self.assertTrue('m1.small' in ids)
<del> self.assertTrue('m1.large' in ids)
<del> self.assertTrue('m1.xlarge' in ids)
<del> self.assertTrue('c1.medium' in ids)
<del> self.assertTrue('c1.xlarge' in ids)
<del> self.assertTrue('m2.xlarge' in ids)
<del> self.assertTrue('m2.2xlarge' in ids)
<del> self.assertTrue('m2.4xlarge' in ids)
<add> region_old = self.driver.region_name
<add>
<add> for region_name in [ 'us-east-1', 'us-west-1', 'eu-west-1',
<add> 'ap-southeast-1' ]:
<add> self.driver.region_name = region_name
<add> sizes = self.driver.list_sizes()
<add>
<add> ids = [s.id for s in sizes]
<add> self.assertTrue('t1.micro' in ids)
<add> self.assertTrue('m1.small' in ids)
<add> self.assertTrue('m1.large' in ids)
<add> self.assertTrue('m1.xlarge' in ids)
<add> self.assertTrue('c1.medium' in ids)
<add> self.assertTrue('c1.xlarge' in ids)
<add> self.assertTrue('m2.xlarge' in ids)
<add> self.assertTrue('m2.2xlarge' in ids)
<add> self.assertTrue('m2.4xlarge' in ids)
<add>
<add> if region_name == 'us-east-1':
<add> self.assertEqual(len(sizes), 11)
<add> self.assertTrue('cg1.4xlarge' in ids)
<add> self.assertTrue('cc1.4xlarge' in ids)
<add> else:
<add> self.assertEqual(len(sizes), 9)
<add>
<add> self.driver.region_name = region_old
<ide>
<ide> def test_list_images(self):
<ide> images = self.driver.list_images() | 2 |
Ruby | Ruby | allow select to have multiple arguments | e7f7439d068f587db91e959ef803606cae9e7cc5 | <ide><path>activerecord/lib/active_record/relation/query_methods.rb
<ide> def preload(*args)
<ide> relation
<ide> end
<ide>
<del> def select(value = Proc.new)
<add> def select(*args, &blk)
<add> if !block_given? && args.blank?
<add> raise ArgumentError
<add> end
<ide> if block_given?
<del> to_a.select {|*block_args| value.call(*block_args) }
<add> to_a.select {|*block_args| blk.call(*block_args) }
<ide> else
<ide> relation = clone
<del> relation.select_values += Array.wrap(value)
<add> relation.select_values += args
<ide> relation
<ide> end
<ide> end
<ide><path>activerecord/test/cases/base_test.rb
<ide> def test_select_symbol
<ide> assert_equal Topic.all.map(&:id).sort, topic_ids
<ide> end
<ide>
<add> def test_select_symbol_for_many_arguments
<add> topics = Topic.select(:id, :author_name).map{|topic| [topic.id, topic.author_name]}.sort
<add> assert_equal Topic.all.map{|topic| [topic.id,topic.author_name]}.sort, topics
<add> end
<add>
<ide> def test_table_exists
<ide> assert !NonExistentTable.table_exists?
<ide> assert Topic.table_exists? | 2 |
Javascript | Javascript | fix comma causing terser issue | e5dee9f88e021cfe11ebced3ddb013ed5c6d679a | <ide><path>src/scales/scale.linearbase.js
<ide> function generateTicks(generationOptions, dataRange) {
<ide> // until this point
<ide> const decimalPlaces = Math.max(
<ide> _decimalPlaces(spacing),
<del> _decimalPlaces(niceMin),
<add> _decimalPlaces(niceMin)
<ide> );
<ide> factor = Math.pow(10, isNullOrUndef(precision) ? decimalPlaces : precision);
<ide> niceMin = Math.round(niceMin * factor) / factor; | 1 |
Python | Python | move files to core/ and common/ | 9cbe3c2f2bce60bb45b382dff0d0cc04247713f0 | <ide><path>official/common/__init__.py
<add>
<ide><path>official/common/flags.py
<add># Lint as: python3
<add># Copyright 2020 The TensorFlow Authors. All Rights Reserved.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add># ==============================================================================
<add>"""The central place to define flags."""
<add>
<add>from absl import flags
<add>
<add>
<add>def define_flags():
<add> """Defines flags."""
<add> flags.DEFINE_string(
<add> 'experiment', default=None, help='The experiment type registered.')
<add>
<add> flags.DEFINE_enum(
<add> 'mode',
<add> default=None,
<add> enum_values=['train', 'eval', 'train_and_eval',
<add> 'continuous_eval', 'continuous_train_and_eval'],
<add> help='Mode to run: `train`, `eval`, `train_and_eval`, '
<add> '`continuous_eval`, and `continuous_train_and_eval`.')
<add>
<add> flags.DEFINE_string(
<add> 'model_dir',
<add> default=None,
<add> help='The directory where the model and training/evaluation summaries'
<add> 'are stored.')
<add>
<add> flags.DEFINE_multi_string(
<add> 'config_file',
<add> default=None,
<add> help='YAML/JSON files which specifies overrides. The override order '
<add> 'follows the order of args. Note that each file '
<add> 'can be used as an override template to override the default parameters '
<add> 'specified in Python. If the same parameter is specified in both '
<add> '`--config_file` and `--params_override`, `config_file` will be used '
<add> 'first, followed by params_override.')
<add>
<add> flags.DEFINE_string(
<add> 'params_override',
<add> default=None,
<add> help='a YAML/JSON string or a YAML file which specifies additional '
<add> 'overrides over the default parameters and those specified in '
<add> '`--config_file`. Note that this is supposed to be used only to override '
<add> 'the model parameters, but not the parameters like TPU specific flags. '
<add> 'One canonical use case of `--config_file` and `--params_override` is '
<add> 'users first define a template config file using `--config_file`, then '
<add> 'use `--params_override` to adjust the minimal set of tuning parameters, '
<add> 'for example setting up different `train_batch_size`. The final override '
<add> 'order of parameters: default_model_params --> params from config_file '
<add> '--> params in params_override. See also the help message of '
<add> '`--config_file`.')
<add>
<add> flags.DEFINE_multi_string(
<add> 'gin_file', default=None, help='List of paths to the config files.')
<add>
<add> flags.DEFINE_multi_string(
<add> 'gin_params',
<add> default=None,
<add> help='Newline separated list of Gin parameter bindings.')
<add>
<add> flags.DEFINE_string(
<add> 'tpu', default=None,
<add> help='The Cloud TPU to use for training. This should be either the name '
<add> 'used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 '
<add> 'url.')
<ide><path>official/common/registry_imports.py
<add># Copyright 2020 The TensorFlow Authors. All Rights Reserved.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add># ==============================================================================
<add>"""All necessary imports for registration."""
<add>
<add># pylint: disable=unused-import
<add>from official.nlp import tasks
<add>from official.utils.testing import mock_task
<ide><path>official/core/train_lib.py
<add># Lint as: python3
<add># Copyright 2020 The TensorFlow Authors. All Rights Reserved.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add># ==============================================================================
<add>"""TFM common training driver library."""
<add>
<add>import os
<add>from typing import Any, Mapping
<add>
<add># Import libraries
<add>from absl import logging
<add>import orbit
<add>import tensorflow as tf
<add>
<add>from official.common import train_utils
<add>from official.core import base_task
<add>from official.modeling.hyperparams import config_definitions
<add>
<add>
<add>def run_experiment(distribution_strategy: tf.distribute.Strategy,
<add> task: base_task.Task,
<add> mode: str,
<add> params: config_definitions.ExperimentConfig,
<add> model_dir: str,
<add> run_post_eval: bool = False,
<add> save_summary: bool = True) -> Mapping[str, Any]:
<add> """Runs train/eval configured by the experiment params.
<add>
<add> Args:
<add> distribution_strategy: A distribution distribution_strategy.
<add> task: A Task instance.
<add> mode: A 'str', specifying the mode. Can be 'train', 'eval', 'train_and_eval'
<add> or 'continuous_eval'.
<add> params: ExperimentConfig instance.
<add> model_dir: A 'str', a path to store model checkpoints and summaries.
<add> run_post_eval: Whether to run post eval once after training, metrics logs
<add> are returned.
<add> save_summary: Whether to save train and validation summary.
<add>
<add> Returns:
<add> eval logs: returns eval metrics logs when run_post_eval is set to True,
<add> othewise, returns {}.
<add> """
<add>
<add> with distribution_strategy.scope():
<add> trainer = train_utils.create_trainer(
<add> params,
<add> task,
<add> model_dir,
<add> train='train' in mode,
<add> evaluate=('eval' in mode) or run_post_eval)
<add>
<add> if trainer.checkpoint:
<add> checkpoint_manager = tf.train.CheckpointManager(
<add> trainer.checkpoint,
<add> directory=model_dir,
<add> max_to_keep=params.trainer.max_to_keep,
<add> step_counter=trainer.global_step,
<add> checkpoint_interval=params.trainer.checkpoint_interval,
<add> init_fn=trainer.initialize)
<add> else:
<add> checkpoint_manager = None
<add>
<add> controller = orbit.Controller(
<add> distribution_strategy,
<add> trainer=trainer if 'train' in mode else None,
<add> evaluator=trainer,
<add> global_step=trainer.global_step,
<add> steps_per_loop=params.trainer.steps_per_loop,
<add> checkpoint_manager=checkpoint_manager,
<add> summary_dir=os.path.join(model_dir, 'train') if (
<add> save_summary) else None,
<add> eval_summary_dir=os.path.join(model_dir, 'validation') if (
<add> save_summary) else None,
<add> summary_interval=params.trainer.summary_interval if (
<add> save_summary) else None)
<add>
<add> logging.info('Starts to execute mode: %s', mode)
<add> with distribution_strategy.scope():
<add> if mode == 'train':
<add> controller.train(steps=params.trainer.train_steps)
<add> elif mode == 'train_and_eval':
<add> controller.train_and_evaluate(
<add> train_steps=params.trainer.train_steps,
<add> eval_steps=params.trainer.validation_steps,
<add> eval_interval=params.trainer.validation_interval)
<add> elif mode == 'eval':
<add> controller.evaluate(steps=params.trainer.validation_steps)
<add> elif mode == 'continuous_eval':
<add> controller.evaluate_continuously(
<add> steps=params.trainer.validation_steps,
<add> timeout=params.trainer.continuous_eval_timeout)
<add> else:
<add> raise NotImplementedError('The mode is not implemented: %s' % mode)
<add>
<add> if run_post_eval:
<add> with distribution_strategy.scope():
<add> return trainer.evaluate(
<add> tf.convert_to_tensor(params.trainer.validation_steps))
<add> else:
<add> return {}
<ide><path>official/core/train_lib_test.py
<add># Lint as: python3
<add># Copyright 2020 The TensorFlow Authors. All Rights Reserved.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add># ==============================================================================
<add>"""Tests for train_ctl_lib."""
<add>import json
<add>import os
<add>
<add>from absl import flags
<add>from absl.testing import flagsaver
<add>from absl.testing import parameterized
<add>import tensorflow as tf
<add>
<add>from tensorflow.python.distribute import combinations
<add>from tensorflow.python.distribute import strategy_combinations
<add>from official.common import flags as tfm_flags
<add># pylint: disable=unused-import
<add>from official.common import registry_imports
<add># pylint: enable=unused-import
<add>from official.core import task_factory
<add>from official.core import train_lib
<add>from official.core import train_utils
<add>
<add>FLAGS = flags.FLAGS
<add>
<add>tfm_flags.define_flags()
<add>
<add>
<add>class TrainTest(tf.test.TestCase, parameterized.TestCase):
<add>
<add> def setUp(self):
<add> super(TrainTest, self).setUp()
<add> self._test_config = {
<add> 'trainer': {
<add> 'checkpoint_interval': 10,
<add> 'steps_per_loop': 10,
<add> 'summary_interval': 10,
<add> 'train_steps': 10,
<add> 'validation_steps': 5,
<add> 'validation_interval': 10,
<add> 'optimizer_config': {
<add> 'optimizer': {
<add> 'type': 'sgd',
<add> },
<add> 'learning_rate': {
<add> 'type': 'constant'
<add> }
<add> }
<add> },
<add> }
<add>
<add> @combinations.generate(
<add> combinations.combine(
<add> distribution_strategy=[
<add> strategy_combinations.default_strategy,
<add> strategy_combinations.tpu_strategy,
<add> strategy_combinations.one_device_strategy_gpu,
<add> ],
<add> mode='eager',
<add> flag_mode=['train', 'eval', 'train_and_eval'],
<add> run_post_eval=[True, False]))
<add> def test_end_to_end(self, distribution_strategy, flag_mode, run_post_eval):
<add> model_dir = self.get_temp_dir()
<add> flags_dict = dict(
<add> experiment='mock',
<add> mode=flag_mode,
<add> model_dir=model_dir,
<add> params_override=json.dumps(self._test_config))
<add> with flagsaver.flagsaver(**flags_dict):
<add> params = train_utils.parse_configuration(flags.FLAGS)
<add> train_utils.serialize_config(params, model_dir)
<add> with distribution_strategy.scope():
<add> task = task_factory.get_task(params.task, logging_dir=model_dir)
<add>
<add> logs = train_lib.run_experiment(
<add> distribution_strategy=distribution_strategy,
<add> task=task,
<add> mode=flag_mode,
<add> params=params,
<add> model_dir=model_dir,
<add> run_post_eval=run_post_eval)
<add>
<add> if run_post_eval:
<add> self.assertNotEmpty(logs)
<add> else:
<add> self.assertEmpty(logs)
<add> self.assertNotEmpty(
<add> tf.io.gfile.glob(os.path.join(model_dir, 'params.yaml')))
<add> if flag_mode != 'eval':
<add> self.assertNotEmpty(
<add> tf.io.gfile.glob(os.path.join(model_dir, 'checkpoint')))
<add>
<add>
<add>if __name__ == '__main__':
<add> tf.test.main()
<ide><path>official/core/train_utils.py
<add># Lint as: python3
<add># Copyright 2020 The TensorFlow Authors. All Rights Reserved.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add># ==============================================================================
<add>"""Training utils."""
<add>
<add>import json
<add>import os
<add>import pprint
<add>
<add>from absl import logging
<add>import tensorflow as tf
<add>
<add>from official.core import base_trainer
<add>from official.core import exp_factory
<add>from official.modeling import hyperparams
<add>from official.modeling.hyperparams import config_definitions
<add>
<add>
<add>def create_trainer(params, task, model_dir, train, evaluate):
<add> del model_dir
<add> logging.info('Running default trainer.')
<add> trainer = base_trainer.Trainer(params, task, train=train, evaluate=evaluate)
<add> return trainer
<add>
<add>
<add>def parse_configuration(flags_obj):
<add> """Parses ExperimentConfig from flags."""
<add>
<add> # 1. Get the default config from the registered experiment.
<add> params = exp_factory.get_exp_config(flags_obj.experiment)
<add> params.override({
<add> 'runtime': {
<add> 'tpu': flags_obj.tpu,
<add> }
<add> })
<add>
<add> # 2. Get the first level of override from `--config_file`.
<add> # `--config_file` is typically used as a template that specifies the common
<add> # override for a particular experiment.
<add> for config_file in flags_obj.config_file or []:
<add> params = hyperparams.override_params_dict(
<add> params, config_file, is_strict=True)
<add>
<add> # 3. Get the second level of override from `--params_override`.
<add> # `--params_override` is typically used as a further override over the
<add> # template. For example, one may define a particular template for training
<add> # ResNet50 on ImageNet in a config file and pass it via `--config_file`,
<add> # then define different learning rates and pass it via `--params_override`.
<add> if flags_obj.params_override:
<add> params = hyperparams.override_params_dict(
<add> params, flags_obj.params_override, is_strict=True)
<add>
<add> params.validate()
<add> params.lock()
<add>
<add> pp = pprint.PrettyPrinter()
<add> logging.info('Final experiment parameters: %s', pp.pformat(params.as_dict()))
<add>
<add> return params
<add>
<add>
<add>def serialize_config(params: config_definitions.ExperimentConfig,
<add> model_dir: str):
<add> """Serializes and saves the experiment config."""
<add> params_save_path = os.path.join(model_dir, 'params.yaml')
<add> logging.info('Saving experiment configuration to %s', params_save_path)
<add> tf.io.gfile.makedirs(model_dir)
<add> hyperparams.save_params_dict_to_yaml(params, params_save_path)
<add>
<add>
<add>def read_global_step_from_checkpoint(ckpt_file_path):
<add> """Read global step from checkpoint, or get global step from its filename."""
<add> global_step = tf.Variable(-1, dtype=tf.int64)
<add> ckpt = tf.train.Checkpoint(global_step=global_step)
<add> try:
<add> ckpt.restore(ckpt_file_path).expect_partial()
<add> global_step_maybe_restored = global_step.numpy()
<add> except tf.errors.InvalidArgumentError:
<add> global_step_maybe_restored = -1
<add>
<add> if global_step_maybe_restored == -1:
<add> raise ValueError('global_step not found in checkpoint {}. '
<add> 'If you want to run finetune eval jobs, you need to '
<add> 'make sure that your pretrain model writes '
<add> 'global_step in its checkpoints.'.format(ckpt_file_path))
<add> global_step_restored = global_step.numpy()
<add> logging.info('get global_step %d from checkpoint %s',
<add> global_step_restored, ckpt_file_path)
<add> return global_step_restored
<add>
<add>
<add>def write_json_summary(log_dir, global_step, eval_metrics):
<add> """Dump evaluation metrics to json file."""
<add> serializable_dict = {}
<add> for name, value in eval_metrics.items():
<add> if hasattr(value, 'numpy'):
<add> serializable_dict[name] = str(value.numpy())
<add> else:
<add> serializable_dict[name] = str(value)
<add> output_json = os.path.join(log_dir, 'metrics-{}.json'.format(global_step))
<add> logging.info('Evaluation results at pretrain step %d: %s',
<add> global_step, serializable_dict)
<add> with tf.io.gfile.GFile(output_json, 'w') as writer:
<add> writer.write(json.dumps(serializable_dict, indent=4) + '\n')
<add>
<add>
<add>def write_summary(summary_writer, global_step, eval_metrics):
<add> """Write evaluation metrics to TF summary."""
<add> numeric_dict = {}
<add> for name, value in eval_metrics.items():
<add> if hasattr(value, 'numpy'):
<add> numeric_dict[name] = value.numpy().astype(float)
<add> else:
<add> numeric_dict[name] = value
<add> with summary_writer.as_default():
<add> for name, value in numeric_dict.items():
<add> tf.summary.scalar(name, value, step=global_step)
<add> summary_writer.flush()
<add>
<add>
<add>def remove_ckpts(model_dir):
<add> """Remove model checkpoints, so we can restart."""
<add> ckpts = os.path.join(model_dir, 'ckpt-*')
<add> logging.info('removing checkpoint files %s', ckpts)
<add> for file_to_remove in tf.io.gfile.glob(ckpts):
<add> tf.io.gfile.rmtree(file_to_remove)
<add>
<add> file_to_remove = os.path.join(model_dir, 'checkpoint')
<add> if tf.io.gfile.exists(file_to_remove):
<add> tf.io.gfile.remove(file_to_remove) | 6 |
Ruby | Ruby | recognize setuptools shim and refurbish args | fe16f36f3c19a29c5edfec4483d14b09cefdc175 | <ide><path>Library/Homebrew/formula.rb
<ide> def exec_cmd(cmd, args, out, logfn)
<ide> # Turn on argument filtering in the superenv compiler wrapper.
<ide> # We should probably have a better mechanism for this than adding
<ide> # special cases to this method.
<del> if cmd == "python" && %w[setup.py build.py].include?(args.first)
<del> ENV.refurbish_args
<add> if cmd == "python"
<add> setup_py_in_args = %w[setup.py build.py].include?(args.first)
<add> setuptools_shim_in_args = args.any? { |a| a.start_with? "import setuptools" }
<add> if setup_py_in_args || setuptools_shim_in_args
<add> ENV.refurbish_args
<add> end
<ide> end
<ide>
<ide> $stdout.reopen(out) | 1 |
PHP | PHP | add twicedailyat schedule frequency | 70490255a2249045699d0c9878f9fe847ad659b3 | <ide><path>src/Illuminate/Console/Scheduling/ManagesFrequencies.php
<ide> public function dailyAt($time)
<ide> * @return $this
<ide> */
<ide> public function twiceDaily($first = 1, $second = 13)
<add> {
<add> return $this->twiceDailyAt($first, $second, 0);
<add> }
<add>
<add> /**
<add> * Schedule the event to run twice daily at a given offset.
<add> *
<add> * @param int $first
<add> * @param int $second
<add> * @param int $offset
<add> * @return $this
<add> */
<add> public function twiceDailyAt($first = 1, $second = 13, $offset = 0)
<ide> {
<ide> $hours = $first.','.$second;
<ide>
<del> return $this->spliceIntoPosition(1, 0)
<add> return $this->spliceIntoPosition(1, $offset)
<ide> ->spliceIntoPosition(2, $hours);
<ide> }
<ide>
<ide><path>tests/Console/Scheduling/FrequencyTest.php
<ide> public function testTwiceDaily()
<ide> $this->assertSame('0 3,15 * * *', $this->event->twiceDaily(3, 15)->getExpression());
<ide> }
<ide>
<add> public function testTwiceDailyAt()
<add> {
<add> $this->assertSame('5 3,15 * * *', $this->event->twiceDailyAt(3, 15, 5)->getExpression());
<add> }
<add>
<ide> public function testWeekly()
<ide> {
<ide> $this->assertSame('0 0 * * 0', $this->event->weekly()->getExpression()); | 2 |
Javascript | Javascript | pass err to callback if buffer is too big | b6207906c452be4c5f049a098fc645fdfb897306 | <ide><path>lib/fs.js
<ide> function readFileAfterClose(err) {
<ide> else
<ide> buffer = context.buffer;
<ide>
<del> if (context.encoding)
<del> buffer = buffer.toString(context.encoding);
<add> if (err) return callback(err, buffer);
<ide>
<del> callback(err, buffer);
<add> if (context.encoding) {
<add> return tryToString(buffer, context.encoding, callback);
<add> }
<add>
<add> callback(null, buffer);
<ide> }
<ide>
<add>function tryToString(buf, encoding, callback) {
<add> var e;
<add> try {
<add> buf = buf.toString(encoding);
<add> } catch (err) {
<add> e = err;
<add> }
<add> callback(e, buf);
<add>}
<ide>
<ide> fs.readFileSync = function(path, options) {
<ide> if (!options) {
<ide><path>test/parallel/test-fs-readfile-tostring-fail.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const fs = require('fs');
<add>const path = require('path');
<add>const kStringMaxLength = process.binding('buffer').kStringMaxLength;
<add>
<add>common.refreshTmpDir();
<add>
<add>const file = path.join(common.tmpDir, 'toobig.txt');
<add>const stream = fs.createWriteStream(file, {
<add> flags: 'a'
<add>});
<add>
<add>const size = kStringMaxLength / 200;
<add>const a = new Buffer(size).fill('a');
<add>
<add>for (var i = 0; i < 201; i++) {
<add> stream.write(a);
<add>}
<add>
<add>stream.end();
<add>stream.on('finish', common.mustCall(function() {
<add> // make sure that the toString does not throw an error
<add> fs.readFile(file, 'utf8', common.mustCall(function(err, buf) {
<add> assert.ok(err instanceof Error);
<add> assert.strictEqual('toString failed', err.message);
<add> }));
<add>}));
<add>
<add>function destroy() {
<add> try {
<add> fs.unlinkSync(file);
<add> } catch (err) {
<add> // it may not exist
<add> }
<add>}
<add>
<add>process.on('exit', destroy);
<add>
<add>process.on('SIGINT', function() {
<add> destroy();
<add> process.exit();
<add>});
<add>
<add>// To make sure we don't leave a very large file
<add>// on test machines in the event this test fails.
<add>process.on('uncaughtException', function(err) {
<add> destroy();
<add> throw err;
<add>}); | 2 |
Javascript | Javascript | fix recursive hydration of next/dynamic | dd9811b206bb554251b34f4daebb052eb67f9b69 | <ide><path>packages/next-server/lib/loadable.js
<ide> import React from 'react'
<ide> import PropTypes from 'prop-types'
<ide>
<ide> const ALL_INITIALIZERS = []
<del>const READY_INITIALIZERS = new Map()
<add>const READY_INITIALIZERS = []
<ide> let initialized = false
<ide>
<ide> function load (loader) {
<ide> function createLoadableComponent (loadFn, options) {
<ide> // Client only
<ide> if (!initialized && typeof window !== 'undefined' && typeof opts.webpack === 'function') {
<ide> const moduleIds = opts.webpack()
<del> for (const moduleId of moduleIds) {
<del> READY_INITIALIZERS.set(moduleId, () => {
<del> return init()
<del> })
<del> }
<add> READY_INITIALIZERS.push((ids) => {
<add> for (const moduleId of moduleIds) {
<add> if (ids.indexOf(moduleId) !== -1) {
<add> return init()
<add> }
<add> }
<add> })
<ide> }
<ide>
<ide> return class LoadableComponent extends React.Component {
<ide> function LoadableMap (opts) {
<ide>
<ide> Loadable.Map = LoadableMap
<ide>
<del>function flushInitializers (initializers) {
<add>function flushInitializers (initializers, ids) {
<ide> let promises = []
<ide>
<ide> while (initializers.length) {
<ide> let init = initializers.pop()
<del> promises.push(init())
<add> promises.push(init(ids))
<ide> }
<ide>
<ide> return Promise.all(promises).then(() => {
<ide> if (initializers.length) {
<del> return flushInitializers(initializers)
<add> return flushInitializers(initializers, ids)
<ide> }
<ide> })
<ide> }
<ide> Loadable.preloadAll = () => {
<ide> })
<ide> }
<ide>
<del>Loadable.preloadReady = (webpackIds) => {
<del> return new Promise((resolve, reject) => {
<del> const initializers = webpackIds.reduce((allInitalizers, moduleId) => {
<del> const initializer = READY_INITIALIZERS.get(moduleId)
<del> if (!initializer) {
<del> return allInitalizers
<del> }
<del>
<del> allInitalizers.push(initializer)
<del> return allInitalizers
<del> }, [])
<del>
<del> initialized = true
<del> // Make sure the object is cleared
<del> READY_INITIALIZERS.clear()
<del>
<add>Loadable.preloadReady = (ids) => {
<add> return new Promise((resolve) => {
<add> const res = () => {
<add> initialized = true
<add> return resolve()
<add> }
<ide> // We always will resolve, errors should be handled within loading UIs.
<del> flushInitializers(initializers).then(resolve, resolve)
<add> flushInitializers(READY_INITIALIZERS, ids).then(res, res)
<ide> })
<ide> }
<ide>
<ide><path>test/integration/basic/components/nested1.js
<add>import dynamic from 'next/dynamic'
<add>
<add>const Nested2 = dynamic(() => import('./nested2'))
<add>
<add>export default () => <div>
<add> Nested 1
<add> <Nested2 />
<add></div>
<ide><path>test/integration/basic/components/nested2.js
<add>import dynamic from 'next/dynamic'
<add>
<add>const BrowserLoaded = dynamic(async () => () => <div>Browser hydrated</div>, {
<add> ssr: false
<add>})
<add>
<add>export default () => <div>
<add> <div>
<add> Nested 2
<add> </div>
<add> <BrowserLoaded />
<add></div>
<ide><path>test/integration/basic/pages/dynamic/nested.js
<add>import dynamic from 'next/dynamic'
<add>
<add>const DynamicComponent = dynamic(() => import('../../components/nested1'))
<add>
<add>export default DynamicComponent
<ide><path>test/integration/basic/test/dynamic.js
<ide> export default (context, render) => {
<ide> }
<ide> })
<ide>
<add> it('should hydrate nested chunks', async () => {
<add> let browser
<add> try {
<add> browser = await webdriver(context.appPort, '/dynamic/nested')
<add> await check(() => browser.elementByCss('body').text(), /Nested 1/)
<add> await check(() => browser.elementByCss('body').text(), /Nested 2/)
<add> await check(() => browser.elementByCss('body').text(), /Browser hydrated/)
<add>
<add> const logs = await browser.log('browser')
<add>
<add> logs.forEach(logItem => {
<add> expect(logItem.message).not.toMatch(/Expected server HTML to contain/)
<add> })
<add> } finally {
<add> if (browser) {
<add> browser.close()
<add> }
<add> }
<add> })
<add>
<ide> it('should render the component Head content', async () => {
<ide> let browser
<ide> try { | 5 |
Javascript | Javascript | allow next export to build html pages | dcc32284293047803ba6fd1808b56ee6cc2861ec | <ide><path>server/document.js
<ide> export class Head extends Component {
<ide>
<ide> return <head>
<ide> <link rel='preload' href={`${assetPrefix}/_next/${buildId}/page${realPathname}`} as='script' />
<del> <link rel='preload' href={`${assetPrefix}/_next/${buildId}/page/_error`} as='script' />
<add> <link rel='preload' href={`${assetPrefix}/_next/${buildId}/page/_error.js`} as='script' />
<ide> {this.getPreloadMainLinks()}
<ide> {(head || []).map((h, i) => React.cloneElement(h, { key: i }))}
<ide> {styles || null}
<ide> export class NextScript extends Component {
<ide> `
<ide> }} />}
<ide> <script async type='text/javascript' src={`${assetPrefix}/_next/${buildId}/page${realPathname}`} />
<del> <script async type='text/javascript' src={`${assetPrefix}/_next/${buildId}/page/_error`} />
<add> <script async type='text/javascript' src={`${assetPrefix}/_next/${buildId}/page/_error.js`} />
<ide> {staticMarkup ? null : this.getScripts()}
<ide> </div>
<ide> }
<ide><path>server/export.js
<ide> import del from 'del'
<ide> import cp from 'recursive-copy'
<ide> import mkdirp from 'mkdirp-then'
<del>import { resolve, join } from 'path'
<del>import { existsSync, readFileSync } from 'fs'
<add>import { resolve, join, dirname, sep } from 'path'
<add>import { existsSync, readFileSync, writeFileSync } from 'fs'
<add>import getConfig from './config'
<add>import { renderToHTML } from './render'
<add>import { printAndExit } from '../lib/utils'
<ide>
<ide> export default async function (dir) {
<del> const outDir = resolve(dir, '.out')
<del> const nextDir = resolve(dir, '.next')
<add> dir = resolve(dir)
<add> const outDir = join(dir, '.out')
<add> const nextDir = join(dir, '.next')
<ide>
<ide> if (!existsSync(nextDir)) {
<ide> console.error('Build your with "next build" before running "next start".')
<ide> process.exit(1)
<ide> }
<ide>
<add> const config = getConfig(dir)
<ide> const buildId = readFileSync(join(nextDir, 'BUILD_ID'), 'utf8')
<ide> const buildStats = require(join(nextDir, 'build-stats.json'))
<ide>
<ide> export default async function (dir) {
<ide> join(nextDir, 'bundles', 'pages'),
<ide> join(outDir, '_next', buildId, 'page')
<ide> )
<add>
<add> // Start the rendering process
<add> const renderOpts = {
<add> dir,
<add> buildStats,
<add> buildId,
<add> assetPrefix: config.assetPrefix.replace(/\/$/, ''),
<add> dev: false,
<add> staticMarkup: false,
<add> hotReloader: null
<add> }
<add>
<add> // Get the exportPathMap from the `next.config.js`
<add> if (typeof config.exportPathMap !== 'function') {
<add> printAndExit(
<add> '> Could not found "exportPathMap" function inside "next.config.js"\n' +
<add> '> "next export" uses that function build html pages.'
<add> )
<add> }
<add>
<add> const exportPathMap = await config.exportPathMap()
<add> const exportPaths = Object.keys(exportPathMap)
<add>
<add> for (const path of exportPaths) {
<add> const { page, query } = exportPathMap[path]
<add> const req = { url: path }
<add> const res = {}
<add>
<add> const htmlFilename = page === '/' ? 'index.html' : `${page}${sep}index.html`
<add> const baseDir = join(outDir, dirname(htmlFilename))
<add> const htmlFilepath = join(outDir, htmlFilename)
<add>
<add> await mkdirp(baseDir)
<add>
<add> const html = await renderToHTML(req, res, page, query, renderOpts)
<add> writeFileSync(htmlFilepath, html, 'utf8')
<add> }
<ide> } | 2 |
Ruby | Ruby | add verbose flag | 75aae9c8a87bbdd81cf1378e619265014e7b9cfb | <ide><path>Library/Homebrew/cmd/reinstall.rb
<ide> def reinstall_args
<ide> EOS
<ide> switch "--display-times",
<ide> description: "Print install times for each formula at the end of the run."
<add> switch :verbose
<ide> switch :debug
<ide> end
<ide> end | 1 |
Javascript | Javascript | replace anonymous closure with arrow func | 0fad875b3785123cc382f13c60df471985e403e5 | <ide><path>test/parallel/test-stream2-unpipe-drain.js
<ide> const src2 = new TestReader();
<ide>
<ide> src1.pipe(dest);
<ide>
<del>src1.once('readable', function() {
<del> process.nextTick(function() {
<add>src1.once('readable', () => {
<add> process.nextTick(() => {
<ide>
<ide> src2.pipe(dest);
<ide>
<del> src2.once('readable', function() {
<del> process.nextTick(function() {
<add> src2.once('readable', () => {
<add> process.nextTick(() => {
<ide>
<ide> src1.unpipe(dest);
<ide> });
<ide> src1.once('readable', function() {
<ide> });
<ide>
<ide>
<del>process.on('exit', function() {
<add>process.on('exit', () => {
<ide> assert.strictEqual(src1.reads, 2);
<ide> assert.strictEqual(src2.reads, 2);
<ide> }); | 1 |
Go | Go | remove use of pkg/integration in pkg/idtools | acf7ce1aa0bcaaf0b541b695ce5fbd22676e9239 | <ide><path>pkg/idtools/idtools_unix.go
<ide> import (
<ide> "strings"
<ide> "sync"
<ide>
<del> "github.com/docker/docker/pkg/integration/cmd"
<ide> "github.com/docker/docker/pkg/system"
<ide> "github.com/opencontainers/runc/libcontainer/user"
<ide> )
<ide> func callGetent(args string) (io.Reader, error) {
<ide> }
<ide> out, err := execCmd(getentCmd, args)
<ide> if err != nil {
<del> exitCode, errC := cmd.GetExitCode(err)
<add> exitCode, errC := system.GetExitCode(err)
<ide> if errC != nil {
<ide> return nil, err
<ide> }
<ide><path>pkg/integration/cmd/command.go
<ide> import (
<ide> "runtime"
<ide> "strings"
<ide> "sync"
<del> "syscall"
<ide> "time"
<ide>
<add> "github.com/docker/docker/pkg/system"
<ide> "github.com/go-check/check"
<ide> )
<ide>
<ide> const (
<ide> None string = "<NOTHING>"
<ide> )
<ide>
<del>// GetExitCode returns the ExitStatus of the specified error if its type is
<del>// exec.ExitError, returns 0 and an error otherwise.
<del>func GetExitCode(err error) (int, error) {
<del> exitCode := 0
<del> if exiterr, ok := err.(*exec.ExitError); ok {
<del> if procExit, ok := exiterr.Sys().(syscall.WaitStatus); ok {
<del> return procExit.ExitStatus(), nil
<del> }
<del> }
<del> return exitCode, fmt.Errorf("failed to get exit code")
<del>}
<del>
<del>// ProcessExitCode process the specified error and returns the exit status code
<del>// if the error was of type exec.ExitError, returns nothing otherwise.
<del>func ProcessExitCode(err error) (exitCode int) {
<del> if err != nil {
<del> var exiterr error
<del> if exitCode, exiterr = GetExitCode(err); exiterr != nil {
<del> // TODO: Fix this so we check the error's text.
<del> // we've failed to retrieve exit code, so we set it to 127
<del> exitCode = 127
<del> }
<del> }
<del> return
<del>}
<del>
<ide> type lockedBuffer struct {
<ide> m sync.RWMutex
<ide> buf bytes.Buffer
<ide> func (r *Result) SetExitError(err error) {
<ide> return
<ide> }
<ide> r.Error = err
<del> r.ExitCode = ProcessExitCode(err)
<add> r.ExitCode = system.ProcessExitCode(err)
<ide> }
<ide>
<ide> type matches struct{}
<ide><path>pkg/integration/utils.go
<ide> import (
<ide>
<ide> icmd "github.com/docker/docker/pkg/integration/cmd"
<ide> "github.com/docker/docker/pkg/stringutils"
<add> "github.com/docker/docker/pkg/system"
<ide> )
<ide>
<ide> // IsKilled process the specified error and returns whether the process was killed or not.
<ide> func IsKilled(err error) bool {
<ide> func runCommandWithOutput(cmd *exec.Cmd) (output string, exitCode int, err error) {
<ide> exitCode = 0
<ide> out, err := cmd.CombinedOutput()
<del> exitCode = icmd.ProcessExitCode(err)
<add> exitCode = system.ProcessExitCode(err)
<ide> output = string(out)
<ide> return
<ide> }
<ide><path>pkg/system/exitcode.go
<add>package system
<add>
<add>import (
<add> "fmt"
<add> "os/exec"
<add> "syscall"
<add>)
<add>
<add>// GetExitCode returns the ExitStatus of the specified error if its type is
<add>// exec.ExitError, returns 0 and an error otherwise.
<add>func GetExitCode(err error) (int, error) {
<add> exitCode := 0
<add> if exiterr, ok := err.(*exec.ExitError); ok {
<add> if procExit, ok := exiterr.Sys().(syscall.WaitStatus); ok {
<add> return procExit.ExitStatus(), nil
<add> }
<add> }
<add> return exitCode, fmt.Errorf("failed to get exit code")
<add>}
<add>
<add>// ProcessExitCode process the specified error and returns the exit status code
<add>// if the error was of type exec.ExitError, returns nothing otherwise.
<add>func ProcessExitCode(err error) (exitCode int) {
<add> if err != nil {
<add> var exiterr error
<add> if exitCode, exiterr = GetExitCode(err); exiterr != nil {
<add> // TODO: Fix this so we check the error's text.
<add> // we've failed to retrieve exit code, so we set it to 127
<add> exitCode = 127
<add> }
<add> }
<add> return
<add>} | 4 |
Javascript | Javascript | add tests for d3.ascending and d3.descending | 247a6c6e9db2c2ecfd11db5ebb748133e7950552 | <ide><path>test/core/ascending-test.js
<add>require("../env");
<add>require("../../d3");
<add>
<add>var vows = require("vows"),
<add> assert = require("assert");
<add>
<add>var suite = vows.describe("d3.ascending");
<add>
<add>suite.addBatch({
<add> "numbers": {
<add> "returns a negative number if a < b": function() {
<add> assert.isTrue(d3.ascending(0, 1) < 0);
<add> },
<add> "returns a positive number if a > b": function() {
<add> assert.isTrue(d3.ascending(1, 0) > 0);
<add> },
<add> "returns zero if a == b": function() {
<add> assert.equal(d3.ascending(0, 0), 0);
<add> }
<add> }
<add>});
<add>
<add>suite.addBatch({
<add> "strings": {
<add> "returns a negative number if a < b": function() {
<add> assert.isTrue(d3.ascending("a", "b") < 0);
<add> },
<add> "returns a positive number if a > b": function() {
<add> assert.isTrue(d3.ascending("b", "a") > 0);
<add> },
<add> "returns zero if a == b": function() {
<add> assert.equal(d3.ascending("a", "a"), 0);
<add> }
<add> }
<add>});
<add>
<add>suite.export(module);
<ide><path>test/core/descending-test.js
<add>require("../env");
<add>require("../../d3");
<add>
<add>var vows = require("vows"),
<add> assert = require("assert");
<add>
<add>var suite = vows.describe("d3.descending");
<add>
<add>suite.addBatch({
<add> "numbers": {
<add> "returns a negative number if a > b": function() {
<add> assert.isTrue(d3.descending(1, 0) < 0);
<add> },
<add> "returns a positive number if a < b": function() {
<add> assert.isTrue(d3.descending(0, 1) > 0);
<add> },
<add> "returns zero if a == b": function() {
<add> assert.equal(d3.descending(0, 0), 0);
<add> }
<add> }
<add>});
<add>
<add>suite.addBatch({
<add> "strings": {
<add> "returns a negative number if a > b": function() {
<add> assert.isTrue(d3.descending("b", "a") < 0);
<add> },
<add> "returns a positive number if a < b": function() {
<add> assert.isTrue(d3.descending("a", "b") > 0);
<add> },
<add> "returns zero if a == b": function() {
<add> assert.equal(d3.descending("a", "a"), 0);
<add> }
<add> }
<add>});
<add>
<add>suite.export(module); | 2 |
Python | Python | remove extra parentheses | 4dd71d68d2227cced7f1215a664343b20da8c804 | <ide><path>rest_framework/fields.py
<ide> def to_choices_dict(choices):
<ide> # choices = [('Category', ((1, 'First'), (2, 'Second'))), (3, 'Third')]
<ide> ret = OrderedDict()
<ide> for choice in choices:
<del> if (not isinstance(choice, (list, tuple))):
<add> if not isinstance(choice, (list, tuple)):
<ide> # single choice
<ide> ret[choice] = choice
<ide> else:
<ide><path>rest_framework/pagination.py
<ide> def _reverse_ordering(ordering_tuple):
<ide> ordering and return a new tuple, eg. `('created', '-uuid')`.
<ide> """
<ide> def invert(x):
<del> return x[1:] if (x.startswith('-')) else '-' + x
<add> return x[1:] if x.startswith('-') else '-' + x
<ide>
<ide> return tuple([invert(item) for item in ordering_tuple])
<ide>
<ide><path>rest_framework/relations.py
<ide> def get_attribute(self, instance):
<ide> return []
<ide>
<ide> relationship = get_attribute(instance, self.source_attrs)
<del> return relationship.all() if (hasattr(relationship, 'all')) else relationship
<add> return relationship.all() if hasattr(relationship, 'all') else relationship
<ide>
<ide> def to_representation(self, iterable):
<ide> return [
<ide><path>rest_framework/renderers.py
<ide> def get_raw_data_form(self, data, view, method, request):
<ide> # If possible, serialize the initial content for the generic form
<ide> default_parser = view.parser_classes[0]
<ide> renderer_class = getattr(default_parser, 'renderer_class', None)
<del> if (hasattr(view, 'get_serializer') and renderer_class):
<add> if hasattr(view, 'get_serializer') and renderer_class:
<ide> # View has a serializer defined and parser class has a
<ide> # corresponding renderer that can be used to render the data.
<ide>
<ide> def get_filter_form(self, data, view, request):
<ide> paginator = getattr(view, 'paginator', None)
<ide> if isinstance(data, list):
<ide> pass
<del> elif (paginator is not None and data is not None):
<add> elif paginator is not None and data is not None:
<ide> try:
<ide> paginator.get_results(data)
<ide> except (TypeError, KeyError):
<ide> def render(self, data, accepted_media_type=None, renderer_context=None):
<ide> ret = template_render(template, context, request=renderer_context['request'])
<ide>
<ide> # Creation and deletion should use redirects in the admin style.
<del> if (response.status_code == status.HTTP_201_CREATED) and ('Location' in response):
<add> if response.status_code == status.HTTP_201_CREATED and 'Location' in response:
<ide> response.status_code = status.HTTP_303_SEE_OTHER
<ide> response['Location'] = request.build_absolute_uri()
<ide> ret = ''
<ide> def get_context(self, data, accepted_media_type, renderer_context):
<ide> )
<ide>
<ide> paginator = getattr(context['view'], 'paginator', None)
<del> if (paginator is not None and data is not None):
<add> if paginator is not None and data is not None:
<ide> try:
<ide> results = paginator.get_results(data)
<ide> except (TypeError, KeyError):
<ide><path>rest_framework/request.py
<ide> def __init__(self, request, parsers=None, authenticators=None,
<ide>
<ide> force_user = getattr(request, '_force_auth_user', None)
<ide> force_token = getattr(request, '_force_auth_token', None)
<del> if (force_user is not None or force_token is not None):
<add> if force_user is not None or force_token is not None:
<ide> forced_auth = ForcedAuthentication(force_user, force_token)
<ide> self.authenticators = (forced_auth,)
<ide>
<ide><path>rest_framework/versioning.py
<ide> class NamespaceVersioning(BaseVersioning):
<ide>
<ide> def determine_version(self, request, *args, **kwargs):
<ide> resolver_match = getattr(request, 'resolver_match', None)
<del> if (resolver_match is None or not resolver_match.namespace):
<add> if resolver_match is None or not resolver_match.namespace:
<ide> return self.default_version
<ide>
<ide> # Allow for possibly nested namespaces. | 6 |
Javascript | Javascript | remove manual qunit fixture resetting | 84b6a0beb1de193520bb5541c841cbecc7195a5b | <ide><path>build/tasks/qunit_fixture.js
<ide> module.exports = function( grunt ) {
<ide> "utf8"
<ide> ).toString().replace( /\r\n/g, "\n" )
<ide> ) +
<del> ";\n" +
<del> "// Compat with QUnit 1.x:\n" +
<del> "document.getElementById( \"qunit-fixture\" ).innerHTML = QUnit.config.fixture;\n"
<add> ";\n"
<ide> );
<ide> grunt.log.ok( "Updated " + dest + "." );
<ide> } );
<ide><path>test/data/qunit-fixture.js
<ide> // Generated by build/tasks/qunit_fixture.js
<ide> QUnit.config.fixture = "<p id=\"firstp\">See <a id=\"simon1\" href=\"http://simon.incutio.com/archive/2003/03/25/#getElementsBySelector\" rel=\"bookmark\">this blog entry</a> for more information.</p>\n<p id=\"ap\">\n\tHere are some links in a normal paragraph: <a id=\"google\" href=\"http://www.google.com/\" title=\"Google!\">Google</a>,\n\t<a id=\"groups\" href=\"http://groups.google.com/\" class=\"GROUPS\">Google Groups (Link)</a>.\n\tThis link has <code><a href=\"http://smin\" id=\"anchor1\">class=\"blog\"</a></code>:\n\t<a href=\"http://diveintomark.org/\" class=\"blog\" hreflang=\"en\" id=\"mark\">diveintomark</a>\n\n</p>\n<div id=\"foo\">\n\t<p id=\"sndp\">Everything inside the red border is inside a div with <code>id=\"foo\"</code>.</p>\n\t<p lang=\"en\" id=\"en\">This is a normal link: <a id=\"yahoo\" href=\"http://www.yahoo.com/\" class=\"blogTest\">Yahoo</a></p>\n\t<p id=\"sap\">This link has <code><a href=\"#2\" id=\"anchor2\">class=\"blog\"</a></code>: <a href=\"http://simon.incutio.com/\" class=\"blog link\" id=\"simon\">Simon Willison's Weblog</a></p>\n\n</div>\n<div id=\"nothiddendiv\" style=\"height:1px;background:white;\" class=\"nothiddendiv\">\n\t<div id=\"nothiddendivchild\"></div>\n</div>\n<span id=\"name+value\"></span>\n<p id=\"first\">Try them out:</p>\n<ul id=\"firstUL\"></ul>\n<ol id=\"empty\"></ol>\n<form id=\"form\" action=\"formaction\">\n\t<label for=\"action\" id=\"label-for\">Action:</label>\n\t<input type=\"text\" name=\"action\" value=\"Test\" id=\"text1\" maxlength=\"30\"/>\n\t<input type=\"text\" name=\"text2\" value=\"Test\" id=\"text2\" disabled=\"disabled\"/>\n\t<input type=\"radio\" name=\"radio1\" id=\"radio1\" value=\"on\"/>\n\n\t<input type=\"radio\" name=\"radio2\" id=\"radio2\" checked=\"checked\"/>\n\t<input type=\"checkbox\" name=\"check\" id=\"check1\" checked=\"checked\"/>\n\t<input type=\"checkbox\" id=\"check2\" value=\"on\"/>\n\n\t<input type=\"hidden\" name=\"hidden\" id=\"hidden1\"/>\n\t<input type=\"text\" style=\"display:none;\" name=\"foo[bar]\" id=\"hidden2\"/>\n\n\t<input type=\"text\" id=\"name\" name=\"name\" value=\"name\" />\n\t<input type=\"search\" id=\"search\" name=\"search\" value=\"search\" />\n\n\t<button id=\"button\" name=\"button\" type=\"button\">Button</button>\n\n\t<textarea id=\"area1\" maxlength=\"30\">foobar</textarea>\n\n\t<select name=\"select1\" id=\"select1\">\n\t\t<option id=\"option1a\" class=\"emptyopt\" value=\"\">Nothing</option>\n\t\t<option id=\"option1b\" value=\"1\">1</option>\n\t\t<option id=\"option1c\" value=\"2\">2</option>\n\t\t<option id=\"option1d\" value=\"3\">3</option>\n\t</select>\n\t<select name=\"select2\" id=\"select2\">\n\t\t<option id=\"option2a\" class=\"emptyopt\" value=\"\">Nothing</option>\n\t\t<option id=\"option2b\" value=\"1\">1</option>\n\t\t<option id=\"option2c\" value=\"2\">2</option>\n\t\t<option id=\"option2d\" selected=\"selected\" value=\"3\">3</option>\n\t</select>\n\t<select name=\"select3\" id=\"select3\" multiple=\"multiple\">\n\t\t<option id=\"option3a\" class=\"emptyopt\" value=\"\">Nothing</option>\n\t\t<option id=\"option3b\" selected=\"selected\" value=\"1\">1</option>\n\t\t<option id=\"option3c\" selected=\"selected\" value=\"2\">2</option>\n\t\t<option id=\"option3d\" value=\"3\">3</option>\n\t\t<option id=\"option3e\">no value</option>\n\t</select>\n\t<select name=\"select4\" id=\"select4\" multiple=\"multiple\">\n\t\t<optgroup disabled=\"disabled\">\n\t\t\t<option id=\"option4a\" class=\"emptyopt\" value=\"\">Nothing</option>\n\t\t\t<option id=\"option4b\" disabled=\"disabled\" selected=\"selected\" value=\"1\">1</option>\n\t\t\t<option id=\"option4c\" selected=\"selected\" value=\"2\">2</option>\n\t\t</optgroup>\n\t\t<option selected=\"selected\" disabled=\"disabled\" id=\"option4d\" value=\"3\">3</option>\n\t\t<option id=\"option4e\">no value</option>\n\t</select>\n\t<select name=\"select5\" id=\"select5\">\n\t\t<option id=\"option5a\" value=\"3\">1</option>\n\t\t<option id=\"option5b\" value=\"2\">2</option>\n\t\t<option id=\"option5c\" value=\"1\" data-attr=\"\">3</option>\n\t</select>\n\n\t<object id=\"object1\" codebase=\"stupid\">\n\t\t<param name=\"p1\" value=\"x1\" />\n\t\t<param name=\"p2\" value=\"x2\" />\n\t</object>\n\n\t<span id=\"台北Táiběi\"></span>\n\t<span id=\"台北\" lang=\"中文\"></span>\n\t<span id=\"utf8class1\" class=\"台北Táiběi 台北\"></span>\n\t<span id=\"utf8class2\" class=\"台北\"></span>\n\t<span id=\"foo:bar\" class=\"foo:bar\"></span>\n\t<span id=\"test.foo[5]bar\" class=\"test.foo[5]bar\"></span>\n\n\t<foo_bar id=\"foobar\">test element</foo_bar>\n</form>\n<b id=\"floatTest\">Float test.</b>\n<iframe id=\"iframe\" name=\"iframe\"></iframe>\n<form id=\"lengthtest\">\n\t<input type=\"text\" id=\"length\" name=\"test\"/>\n\t<input type=\"text\" id=\"idTest\" name=\"id\"/>\n</form>\n<table id=\"table\"></table>\n\n<form id=\"name-tests\">\n\t<!-- Inputs with a grouped name attribute. -->\n\t<input name=\"types[]\" id=\"types_all\" type=\"checkbox\" value=\"all\" />\n\t<input name=\"types[]\" id=\"types_anime\" type=\"checkbox\" value=\"anime\" />\n\t<input name=\"types[]\" id=\"types_movie\" type=\"checkbox\" value=\"movie\" />\n</form>\n\n<form id=\"testForm\" action=\"#\" method=\"get\">\n\t<textarea name=\"T3\" rows=\"2\" cols=\"15\">?\nZ</textarea>\n\t<input type=\"hidden\" name=\"H1\" value=\"x\" />\n\t<input type=\"hidden\" name=\"H2\" />\n\t<input name=\"PWD\" type=\"password\" value=\"\" />\n\t<input name=\"T1\" type=\"text\" />\n\t<input name=\"T2\" type=\"text\" value=\"YES\" readonly=\"readonly\" />\n\t<input type=\"checkbox\" name=\"C1\" value=\"1\" />\n\t<input type=\"checkbox\" name=\"C2\" />\n\t<input type=\"radio\" name=\"R1\" value=\"1\" />\n\t<input type=\"radio\" name=\"R1\" value=\"2\" />\n\t<input type=\"text\" name=\"My Name\" value=\"me\" />\n\t<input type=\"reset\" name=\"reset\" value=\"NO\" />\n\t<select name=\"S1\">\n\t\t<option value=\"abc\">ABC</option>\n\t\t<option value=\"abc\">ABC</option>\n\t\t<option value=\"abc\">ABC</option>\n\t</select>\n\t<select name=\"S2\" multiple=\"multiple\" size=\"3\">\n\t\t<option value=\"abc\">ABC</option>\n\t\t<option value=\"abc\">ABC</option>\n\t\t<option value=\"abc\">ABC</option>\n\t</select>\n\t<select name=\"S3\">\n\t\t<option selected=\"selected\">YES</option>\n\t</select>\n\t<select name=\"S4\">\n\t\t<option value=\"\" selected=\"selected\">NO</option>\n\t</select>\n\t<input type=\"submit\" name=\"sub1\" value=\"NO\" />\n\t<input type=\"submit\" name=\"sub2\" value=\"NO\" />\n\t<input type=\"image\" name=\"sub3\" value=\"NO\" />\n\t<button name=\"sub4\" type=\"submit\" value=\"NO\">NO</button>\n\t<input name=\"D1\" type=\"text\" value=\"NO\" disabled=\"disabled\" />\n\t<input type=\"checkbox\" checked=\"checked\" disabled=\"disabled\" name=\"D2\" value=\"NO\" />\n\t<input type=\"radio\" name=\"D3\" value=\"NO\" checked=\"checked\" disabled=\"disabled\" />\n\t<select name=\"D4\" disabled=\"disabled\">\n\t\t<option selected=\"selected\" value=\"NO\">NO</option>\n\t</select>\n\t<input id=\"list-test\" type=\"text\" />\n\t<datalist id=\"datalist\">\n\t\t<option value=\"option\"></option>\n\t</datalist>\n</form>\n<div id=\"moretests\">\n\t<form>\n\t\t<div id=\"checkedtest\" style=\"display:none;\">\n\t\t\t<input type=\"radio\" name=\"checkedtestradios\" checked=\"checked\"/>\n\t\t\t<input type=\"radio\" name=\"checkedtestradios\" value=\"on\"/>\n\t\t\t<input type=\"checkbox\" name=\"checkedtestcheckboxes\" checked=\"checked\"/>\n\t\t\t<input type=\"checkbox\" name=\"checkedtestcheckboxes\" />\n\t\t</div>\n\t</form>\n\t<div id=\"nonnodes\"><span id=\"nonnodesElement\">hi</span> there <!-- mon ami --></div>\n\t<div id=\"t2037\">\n\t\t<div><div class=\"hidden\">hidden</div></div>\n\t</div>\n\t<div id=\"t6652\">\n\t\t<div></div>\n\t</div>\n\t<div id=\"no-clone-exception\"><object><embed></embed></object></div>\n</div>\n\n<div id=\"tabindex-tests\">\n\t<ol id=\"listWithTabIndex\" tabindex=\"5\">\n\t\t<li id=\"foodWithNegativeTabIndex\" tabindex=\"-1\">Rice</li>\n\t\t<li id=\"foodNoTabIndex\">Beans</li>\n\t\t<li>Blinis</li>\n\t\t<li>Tofu</li>\n\t</ol>\n\n\t<div id=\"divWithNoTabIndex\">I'm hungry. I should...</div>\n\t<span>...</span><a href=\"#\" id=\"linkWithNoTabIndex\">Eat lots of food</a><span>...</span> |\n\t<span>...</span><a href=\"#\" id=\"linkWithTabIndex\" tabindex=\"2\">Eat a little food</a><span>...</span> |\n\t<span>...</span><a href=\"#\" id=\"linkWithNegativeTabIndex\" tabindex=\"-1\">Eat no food</a><span>...</span>\n\t<span>...</span><a id=\"linkWithNoHrefWithNoTabIndex\">Eat a burger</a><span>...</span>\n\t<span>...</span><a id=\"linkWithNoHrefWithTabIndex\" tabindex=\"1\">Eat some funyuns</a><span>...</span>\n\t<span>...</span><a id=\"linkWithNoHrefWithNegativeTabIndex\" tabindex=\"-1\">Eat some funyuns</a><span>...</span>\n\t<input id=\"inputWithoutTabIndex\"/>\n\t<button id=\"buttonWithoutTabIndex\"></button>\n\t<textarea id=\"textareaWithoutTabIndex\"></textarea>\n\t<menu type=\"popup\">\n\t\t<menuitem id=\"menuitemWithoutTabIndex\" command=\"submitbutton\" default/>\n\t</menu>\n</div>\n\n<div id=\"liveHandlerOrder\">\n\t<span id=\"liveSpan1\"><a href=\"#\" id=\"liveLink1\"></a></span>\n\t<span id=\"liveSpan2\"><a href=\"#\" id=\"liveLink2\"></a></span>\n</div>\n\n<div id=\"siblingTest\">\n\t<em id=\"siblingfirst\">1</em>\n\t<em id=\"siblingnext\">2</em>\n\t<em id=\"siblingthird\">\n\t\t<em id=\"siblingchild\">\n\t\t\t<em id=\"siblinggrandchild\">\n\t\t\t\t<em id=\"siblinggreatgrandchild\"></em>\n\t\t\t</em>\n\t\t</em>\n\t</em>\n\t<span id=\"siblingspan\"></span>\n</div>\n<div id=\"fx-test-group\" style=\"position: absolute; width: 1px; height: 1px; overflow: hidden;\">\n\t<div id=\"fx-queue\" name=\"test\">\n\t\t<div id=\"fadein\" class='chain-test' name='div'>fadeIn<div>fadeIn</div></div>\n\t\t<div id=\"fadeout\" class='chain-test chain-test-out'>fadeOut<div>fadeOut</div></div>\n\n\t\t<div id=\"show\" class='chain-test'>show<div>show</div></div>\n\t\t<div id=\"hide\" class='chain-test chain-test-out'>hide<div>hide</div></div>\n\t\t<div id=\"easehide\" class='chain-test chain-test-out'>hide<div>hide</div></div>\n\n\t\t<div id=\"togglein\" class='chain-test'>togglein<div>togglein</div></div>\n\t\t<div id=\"toggleout\" class='chain-test chain-test-out'>toggleout<div>toggleout</div></div>\n\t\t<div id=\"easetoggleout\" class='chain-test chain-test-out'>toggleout<div>toggleout</div></div>\n\n\t\t<div id=\"slideup\" class='chain-test'>slideUp<div>slideUp</div></div>\n\t\t<div id=\"slidedown\" class='chain-test chain-test-out'>slideDown<div>slideDown</div></div>\n\t\t<div id=\"easeslideup\" class='chain-test'>slideUp<div>slideUp</div></div>\n\n\t\t<div id=\"slidetogglein\" class='chain-test'>slideToggleIn<div>slideToggleIn</div></div>\n\t\t<div id=\"slidetoggleout\" class='chain-test chain-test-out'>slideToggleOut<div>slideToggleOut</div></div>\n\n\t\t<div id=\"fadetogglein\" class='chain-test'>fadeToggleIn<div>fadeToggleIn</div></div>\n\t\t<div id=\"fadetoggleout\" class='chain-test chain-test-out'>fadeToggleOut<div>fadeToggleOut</div></div>\n\n\t\t<div id=\"fadeto\" class='chain-test'>fadeTo<div>fadeTo</div></div>\n\t</div>\n\n\t<div id=\"fx-tests\"></div>\n\t<span id=\"display\"></span>\n</div>\n";
<del>// Compat with QUnit 1.x:
<del>document.getElementById( "qunit-fixture" ).innerHTML = QUnit.config.fixture; | 2 |
Javascript | Javascript | remove stale code | 61978f57e6c3cfd8aeb3cc22490d10b1ea09f473 | <ide><path>lib/dgram.js
<ide> Socket.prototype.send = function(buffer,
<ide> function afterSend(status, handle, req, buffer) {
<ide> var self = handle.owner;
<ide>
<del> // CHECKME socket's been closed by user, don't call callback?
<del> if (handle !== self._handle)
<del> void(0);
<del>
<ide> if (req.cb)
<ide> req.cb(null, buffer.length); // compatibility with dgram_legacy.js
<ide> }
<ide> Socket.prototype._stopReceiving = function() {
<ide> if (!this._receiving)
<ide> return;
<ide>
<del> // Black hole messages coming in when reading is stopped. Libuv might do
<del> // this, but node applications (e.g. test/simple/test-dgram-pingpong) may
<del> // not expect it.
<del> this._handle.onmessage = noop;
<del>
<ide> this._handle.recvStop();
<ide> this._receiving = false;
<ide> this.fd = null; // compatibility hack | 1 |
PHP | PHP | add command alias to application configuration | 818be60551237e1c7fd2cc30891468b2180baab2 | <ide><path>application/config/application.php
<ide> 'Blade' => 'Laravel\\Blade',
<ide> 'Bundle' => 'Laravel\\Bundle',
<ide> 'Cache' => 'Laravel\\Cache',
<add> 'Command' => 'Laravel\CLI\Command',
<ide> 'Config' => 'Laravel\\Config',
<ide> 'Controller' => 'Laravel\\Routing\\Controller',
<ide> 'Cookie' => 'Laravel\\Cookie', | 1 |
PHP | PHP | fix phpdoc blocks for responses | 9dabd7ffab9c45d7558d2fe88dbf740fcc85d43b | <ide><path>src/Illuminate/Foundation/Http/FormRequest.php
<ide> public function response(array $errors)
<ide> /**
<ide> * Get the response for a forbidden operation.
<ide> *
<del> * @return \Illuminate\Http\Response
<add> * @return \Symfony\Component\HttpFoundation\Response
<ide> */
<ide> public function forbiddenResponse()
<ide> {
<ide><path>src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php
<ide> protected function tokensMatch($request)
<ide> * Add the CSRF token to the response cookies.
<ide> *
<ide> * @param \Illuminate\Http\Request $request
<del> * @param \Illuminate\Http\Response $response
<del> * @return \Illuminate\Http\Response
<add> * @param \Symfony\Component\HttpFoundation\Response $response
<add> * @return \Symfony\Component\HttpFoundation\Response
<ide> */
<ide> protected function addCookieToResponse($request, $response)
<ide> {
<ide><path>src/Illuminate/Foundation/Validation/ValidatesRequests.php
<ide> protected function throwValidationException(Request $request, $validator)
<ide> *
<ide> * @param \Illuminate\Http\Request $request
<ide> * @param array $errors
<del> * @return \Illuminate\Http\Response
<add> * @return \Symfony\Component\HttpFoundation\Response
<ide> */
<ide> protected function buildFailedValidationResponse(Request $request, array $errors)
<ide> {
<ide><path>src/Illuminate/Http/Middleware/FrameGuard.php
<ide> class FrameGuard
<ide> *
<ide> * @param \Illuminate\Http\Request $request
<ide> * @param \Closure $next
<del> * @return \Illuminate\Http\Response
<add> * @return \Symfony\Component\HttpFoundation\Response
<ide> */
<ide> public function handle($request, Closure $next)
<ide> {
<ide><path>src/Illuminate/Http/ResponseTrait.php
<ide> public function content()
<ide> * Set a header on the Response.
<ide> *
<ide> * @param string $key
<del> * @param string $value
<add> * @param array|string $values
<ide> * @param bool $replace
<ide> * @return $this
<ide> */
<del> public function header($key, $value, $replace = true)
<add> public function header($key, $values, $replace = true)
<ide> {
<del> $this->headers->set($key, $value, $replace);
<add> $this->headers->set($key, $values, $replace);
<ide>
<ide> return $this;
<ide> }
<ide> public function withCookie($cookie)
<ide> /**
<ide> * Throws the response in a HttpResponseException instance.
<ide> *
<del> * @throws Illuminate\Http\Exception\HttpResponseException;
<add> * @throws \Illuminate\Http\Exception\HttpResponseException;
<ide> */
<ide> public function throwResponse()
<ide> {
<ide><path>src/Illuminate/Routing/Middleware/ThrottleRequests.php
<ide> protected function resolveRequestSignature($request)
<ide> *
<ide> * @param string $key
<ide> * @param int $maxAttempts
<del> * @return \Illuminate\Http\Response
<add> * @return \Symfony\Component\HttpFoundation\Response
<ide> */
<ide> protected function buildResponse($key, $maxAttempts)
<ide> {
<ide> protected function buildResponse($key, $maxAttempts)
<ide> * @param int $maxAttempts
<ide> * @param int $remainingAttempts
<ide> * @param int|null $retryAfter
<del> * @return \Illuminate\Http\Response
<add> * @return \Symfony\Component\HttpFoundation\Response
<ide> */
<ide> protected function addHeaders(Response $response, $maxAttempts, $remainingAttempts, $retryAfter = null)
<ide> {
<ide><path>src/Illuminate/Validation/ValidationException.php
<ide> class ValidationException extends Exception
<ide> /**
<ide> * The recommended response to send to the client.
<ide> *
<del> * @var \Illuminate\Http\Response|null
<add> * @var \Symfony\Component\HttpFoundation\Response|null
<ide> */
<ide> public $response;
<ide>
<ide> /**
<ide> * Create a new exception instance.
<ide> *
<ide> * @param \Illuminate\Contracts\Validation\Validator $validator
<del> * @param \Illuminate\Http\Response $response
<add> * @param \Symfony\Component\HttpFoundation\Response $response
<ide> * @return void
<ide> */
<ide> public function __construct($validator, $response = null) | 7 |
Java | Java | add samesite support in webflux session cookies | 09d9450154be796349dabdc606ade57beae08724 | <ide><path>spring-web/src/main/java/org/springframework/http/ResponseCookie.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * static method.
<ide> *
<ide> * @author Rossen Stoyanchev
<add> * @author Brian Clozel
<ide> * @since 5.0
<ide> * @see <a href="https://tools.ietf.org/html/rfc6265">RFC 6265</a>
<ide> */
<ide> public final class ResponseCookie extends HttpCookie {
<ide>
<ide> private final boolean httpOnly;
<ide>
<add> @Nullable
<add> private final String sameSite;
<add>
<ide>
<ide> /**
<ide> * Private constructor. See {@link #from(String, String)}.
<ide> */
<ide> private ResponseCookie(String name, String value, Duration maxAge, @Nullable String domain,
<del> @Nullable String path, boolean secure, boolean httpOnly) {
<add> @Nullable String path, boolean secure, boolean httpOnly, @Nullable String sameSite) {
<ide>
<ide> super(name, value);
<ide> Assert.notNull(maxAge, "Max age must not be null");
<ide> private ResponseCookie(String name, String value, Duration maxAge, @Nullable Str
<ide> this.path = path;
<ide> this.secure = secure;
<ide> this.httpOnly = httpOnly;
<add> this.sameSite = sameSite;
<ide> }
<ide>
<ide>
<ide> public boolean isHttpOnly() {
<ide> return this.httpOnly;
<ide> }
<ide>
<add> /**
<add> * Return the cookie "SameSite" attribute, or {@code null} if not set.
<add> * <p>This limits the scope of the cookie such that it will only be attached to
<add> * same site requests if {@code "Strict"} or cross-site requests if {@code "Lax"}.
<add> * @see <a href="https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis#section-4.1.2.7">RFC6265 bis</a>
<add> */
<add> @Nullable
<add> public String getSameSite() {
<add> return this.sameSite;
<add> }
<ide>
<ide> @Override
<ide> public boolean equals(Object other) {
<ide> public String toString() {
<ide> headers.setExpires(seconds > 0 ? System.currentTimeMillis() + seconds : 0);
<ide> sb.append(headers.getFirst(HttpHeaders.EXPIRES));
<ide> }
<del>
<ide> if (this.secure) {
<ide> sb.append("; Secure");
<ide> }
<ide> if (this.httpOnly) {
<ide> sb.append("; HttpOnly");
<ide> }
<add> if (StringUtils.hasText(this.sameSite)) {
<add> sb.append("; SameSite=").append(this.sameSite);
<add> }
<ide> return sb.toString();
<ide> }
<ide>
<ide> public static ResponseCookieBuilder from(final String name, final String value)
<ide>
<ide> private boolean httpOnly;
<ide>
<add> @Nullable
<add> private String sameSite;
<add>
<ide> @Override
<ide> public ResponseCookieBuilder maxAge(Duration maxAge) {
<ide> this.maxAge = maxAge;
<ide> public ResponseCookieBuilder httpOnly(boolean httpOnly) {
<ide> return this;
<ide> }
<ide>
<add> @Override
<add> public ResponseCookieBuilder sameSite(String sameSite) {
<add> this.sameSite = sameSite;
<add> return this;
<add> }
<add>
<ide> @Override
<ide> public ResponseCookie build() {
<ide> return new ResponseCookie(name, value, this.maxAge, this.domain, this.path,
<del> this.secure, this.httpOnly);
<add> this.secure, this.httpOnly, this.sameSite);
<ide> }
<ide> };
<ide> }
<ide> public interface ResponseCookieBuilder {
<ide> */
<ide> ResponseCookieBuilder httpOnly(boolean httpOnly);
<ide>
<add> /**
<add> * Add the "SameSite" attribute to the cookie.
<add> * @see <a href="https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis#section-4.1.2.7">RFC6265 bis</a>
<add> */
<add> ResponseCookieBuilder sameSite(String sameSite);
<add>
<ide> /**
<ide> * Create the HttpCookie.
<ide> */
<ide><path>spring-web/src/main/java/org/springframework/web/server/session/CookieWebSessionIdResolver.java
<ide> * Cookie-based {@link WebSessionIdResolver}.
<ide> *
<ide> * @author Rossen Stoyanchev
<add> * @author Brian Clozel
<ide> * @since 5.0
<ide> */
<ide> public class CookieWebSessionIdResolver implements WebSessionIdResolver {
<ide> public class CookieWebSessionIdResolver implements WebSessionIdResolver {
<ide>
<ide> private Duration cookieMaxAge = Duration.ofSeconds(-1);
<ide>
<add> private String sameSite = "Strict";
<add>
<ide>
<ide> /**
<ide> * Set the name of the cookie to use for the session id.
<ide> public Duration getCookieMaxAge() {
<ide> return this.cookieMaxAge;
<ide> }
<ide>
<add> /**
<add> * Set the value for the "SameSite" attribute of the cookie that holds the
<add> * session id. For its meaning and possible values, see
<add> * {@link ResponseCookie#getSameSite()}.
<add> * <p>By default set to {@code "Strict"}
<add> * @param sameSite the SameSite value
<add> */
<add> public void setSameSite(String sameSite) {
<add> this.sameSite = sameSite;
<add> }
<add>
<add> /**
<add> * Return the configured "SameSite" attribute value for the session cookie.
<add> */
<add> public String getSameSite() {
<add> return sameSite;
<add> }
<ide>
<ide> @Override
<ide> public List<String> resolveSessionIds(ServerWebExchange exchange) {
<ide> public List<String> resolveSessionIds(ServerWebExchange exchange) {
<ide> @Override
<ide> public void setSessionId(ServerWebExchange exchange, String id) {
<ide> Assert.notNull(id, "'id' is required");
<del> setSessionCookie(exchange, id, getCookieMaxAge());
<add> setSessionCookie(exchange, id, getCookieMaxAge(), getSameSite());
<ide> }
<ide>
<ide> @Override
<ide> public void expireSession(ServerWebExchange exchange) {
<del> setSessionCookie(exchange, "", Duration.ofSeconds(0));
<add> setSessionCookie(exchange, "", Duration.ofSeconds(0), "");
<ide> }
<ide>
<del> private void setSessionCookie(ServerWebExchange exchange, String id, Duration maxAge) {
<add> private void setSessionCookie(ServerWebExchange exchange, String id, Duration maxAge, String sameSite) {
<ide> String name = getCookieName();
<ide> boolean secure = "https".equalsIgnoreCase(exchange.getRequest().getURI().getScheme());
<ide> String path = exchange.getRequest().getPath().contextPath().value() + "/";
<ide> exchange.getResponse().getCookies().set(name,
<ide> ResponseCookie.from(name, id).path(path)
<del> .maxAge(maxAge).httpOnly(true).secure(secure).build());
<add> .maxAge(maxAge).httpOnly(true).secure(secure).sameSite(sameSite).build());
<ide> }
<ide>
<ide> }
<ide><path>spring-web/src/test/java/org/springframework/web/server/session/CookieWebSessionIdResolverTests.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void setSessionId() throws Exception {
<ide> assertEquals(1, cookies.size());
<ide> ResponseCookie cookie = cookies.getFirst(this.resolver.getCookieName());
<ide> assertNotNull(cookie);
<del> assertEquals("SESSION=123; Path=/; Secure; HttpOnly", cookie.toString());
<add> assertEquals("SESSION=123; Path=/; Secure; HttpOnly; SameSite=Strict", cookie.toString());
<ide> }
<ide> } | 3 |
Ruby | Ruby | remove bottle api | 89483abda9199d6c6ded1dd1f1163a41d4d8c2cd | <ide><path>Library/Homebrew/api.rb
<ide> # frozen_string_literal: true
<ide>
<ide> require "api/analytics"
<del>require "api/bottle"
<ide> require "api/cask"
<ide> require "api/cask-source"
<ide> require "api/formula"
<ide><path>Library/Homebrew/api/bottle.rb
<del># typed: false
<del># frozen_string_literal: true
<del>
<del>require "github_packages"
<del>
<del>module Homebrew
<del> module API
<del> # Helper functions for using the bottle JSON API.
<del> #
<del> # @api private
<del> module Bottle
<del> class << self
<del> extend T::Sig
<del>
<del> sig { returns(String) }
<del> def bottle_api_path
<del> "bottle"
<del> end
<del> alias generic_bottle_api_path bottle_api_path
<del>
<del> GITHUB_PACKAGES_SHA256_REGEX = %r{#{GitHubPackages::URL_REGEX}.*/blobs/sha256:(?<sha256>\h{64})$}.freeze
<del>
<del> sig { params(name: String).returns(Hash) }
<del> def fetch(name)
<del> name = name.sub(%r{^homebrew/core/}, "")
<del> Homebrew::API.fetch "#{bottle_api_path}/#{name}.json"
<del> end
<del>
<del> sig { params(name: String).returns(T::Boolean) }
<del> def available?(name)
<del> fetch name
<del> true
<del> rescue ArgumentError
<del> false
<del> end
<del>
<del> sig { params(name: String).void }
<del> def fetch_bottles(name)
<del> hash = fetch(name)
<del> bottle_tag = Utils::Bottles.tag.to_s
<del>
<del> if !hash["bottles"].key?(bottle_tag) && !hash["bottles"].key?("all")
<del> odie "No bottle available for #{name} on the current OS"
<del> end
<del>
<del> download_bottle(hash, bottle_tag)
<del>
<del> hash["dependencies"].each do |dep_hash|
<del> existing_formula = begin
<del> Formulary.factory dep_hash["name"]
<del> rescue FormulaUnavailableError
<del> # The formula might not exist if it's not installed and homebrew/core isn't tapped
<del> nil
<del> end
<del>
<del> next if existing_formula.present? && existing_formula.latest_version_installed?
<del>
<del> download_bottle(dep_hash, bottle_tag)
<del> end
<del> end
<del>
<del> sig { params(url: String).returns(T.nilable(String)) }
<del> def checksum_from_url(url)
<del> match = url.match GITHUB_PACKAGES_SHA256_REGEX
<del> return if match.blank?
<del>
<del> match[:sha256]
<del> end
<del>
<del> sig { params(hash: Hash, tag: String).void }
<del> def download_bottle(hash, tag)
<del> bottle = hash["bottles"][tag]
<del> bottle ||= hash["bottles"]["all"]
<del> return if bottle.blank?
<del>
<del> sha256 = bottle["sha256"] || checksum_from_url(bottle["url"])
<del> bottle_filename = ::Bottle::Filename.new(hash["name"], hash["pkg_version"], tag, hash["rebuild"])
<del>
<del> resource = Resource.new hash["name"]
<del> resource.url bottle["url"]
<del> resource.sha256 sha256
<del> resource.version hash["pkg_version"]
<del> resource.downloader.resolved_basename = bottle_filename
<del>
<del> resource.fetch
<del>
<del> # Map the name of this formula to the local bottle path to allow the
<del> # formula to be loaded by passing just the name to `Formulary::factory`.
<del> [hash["name"], "homebrew/core/#{hash["name"]}"].each do |name|
<del> Formulary.map_formula_name_to_local_bottle_path name, resource.downloader.cached_location
<del> end
<del> end
<del> end
<del> end
<del> end
<del>end
<ide><path>Library/Homebrew/diagnostic.rb
<ide> def check_deleted_formula
<ide> # Formulae installed with HOMEBREW_INSTALL_FROM_API should not count as deleted formulae
<ide> # but may not have a tap listed in their tab
<ide> tap = Tab.for_keg(keg).tap
<del> next if (tap.blank? || tap.core_tap?) && Homebrew::API::Bottle.available?(keg.name)
<add> next if (tap.blank? || tap.core_tap?) && Homebrew::API::Formula.all_formulae.key?(keg.name)
<ide> end
<ide>
<ide> keg.name
<ide><path>Library/Homebrew/test/api/bottle_spec.rb
<del># typed: false
<del># frozen_string_literal: true
<del>
<del>require "api"
<del>
<del>describe Homebrew::API::Bottle do
<del> let(:bottle_json) {
<del> <<~EOS
<del> {
<del> "name": "hello",
<del> "pkg_version": "2.10",
<del> "rebuild": 0,
<del> "bottles": {
<del> "arm64_big_sur": {
<del> "url": "https://ghcr.io/v2/homebrew/core/hello/blobs/sha256:b3b083db0807ff92c6e289a298f378198354b7727fb9ba9f4d550b8e08f90a60"
<del> },
<del> "big_sur": {
<del> "url": "https://ghcr.io/v2/homebrew/core/hello/blobs/sha256:69489ae397e4645127aa7773211310f81ebb6c99e1f8e3e22c5cdb55333f5408"
<del> },
<del> "x86_64_linux": {
<del> "url": "https://ghcr.io/v2/homebrew/core/hello/blobs/sha256:e6980196298e0a9cfe4fa4e328a71a1869a4d5e1d31c38442150ed784cfc0e29"
<del> }
<del> },
<del> "dependencies": []
<del> }
<del> EOS
<del> }
<del> let(:bottle_hash) { JSON.parse(bottle_json) }
<del>
<del> def mock_curl_output(stdout: "", success: true)
<del> curl_output = OpenStruct.new(stdout: stdout, success?: success)
<del> allow(Utils::Curl).to receive(:curl_output).and_return curl_output
<del> end
<del>
<del> describe "::fetch" do
<del> it "fetches the bottle JSON for a formula that exists" do
<del> mock_curl_output stdout: bottle_json
<del> fetched_hash = described_class.fetch("foo")
<del> expect(fetched_hash).to eq bottle_hash
<del> end
<del>
<del> it "raises an error if the formula does not exist" do
<del> mock_curl_output success: false
<del> expect { described_class.fetch("bar") }.to raise_error(ArgumentError, /No file found/)
<del> end
<del>
<del> it "raises an error if the bottle JSON is invalid" do
<del> mock_curl_output stdout: "foo"
<del> expect { described_class.fetch("baz") }.to raise_error(ArgumentError, /Invalid JSON file/)
<del> end
<del> end
<del>
<del> describe "::available?" do
<del> it "returns `true` if `fetch` succeeds" do
<del> allow(described_class).to receive(:fetch)
<del> expect(described_class.available?("foo")).to be true
<del> end
<del>
<del> it "returns `false` if `fetch` fails" do
<del> allow(described_class).to receive(:fetch).and_raise ArgumentError
<del> expect(described_class.available?("foo")).to be false
<del> end
<del> end
<del>
<del> describe "::fetch_bottles" do
<del> before do
<del> ENV["HOMEBREW_INSTALL_FROM_API"] = "1"
<del> allow(described_class).to receive(:fetch).and_return bottle_hash
<del> end
<del>
<del> it "fetches bottles if a bottle is available" do
<del> allow(Utils::Bottles).to receive(:tag).and_return :arm64_big_sur
<del> expect { described_class.fetch_bottles("hello") }.not_to raise_error
<del> end
<del>
<del> it "raises an error if no bottle is available" do
<del> allow(Utils::Bottles).to receive(:tag).and_return :catalina
<del> expect { described_class.fetch_bottles("hello") }.to raise_error(SystemExit)
<del> end
<del> end
<del>
<del> describe "::checksum_from_url" do
<del> let(:sha256) { "b3b083db0807ff92c6e289a298f378198354b7727fb9ba9f4d550b8e08f90a60" }
<del> let(:url) { "https://ghcr.io/v2/homebrew/core/hello/blobs/sha256:#{sha256}" }
<del> let(:non_ghp_url) { "https://formulae.brew.sh/api/formula/hello.json" }
<del>
<del> it "returns the `sha256` for a GitHub packages URL" do
<del> expect(described_class.checksum_from_url(url)).to eq sha256
<del> end
<del>
<del> it "returns `nil` for a non-GitHub packages URL" do
<del> expect(described_class.checksum_from_url(non_ghp_url)).to be_nil
<del> end
<del> end
<del>end | 4 |
PHP | PHP | remove undersocre form protected property name | cf0e65fab9aa26d0a6f0912701fa2516e8e99922 | <ide><path>src/ORM/Locator/TableLocator.php
<ide> class TableLocator implements LocatorInterface
<ide> *
<ide> * @var array
<ide> */
<del> protected $_locations = [];
<add> protected $locations = [];
<ide>
<ide> /**
<ide> * Configuration for aliases.
<ide> protected function _getClassName($alias, array $options = [])
<ide> return $options['className'];
<ide> }
<ide>
<del> foreach ($this->_locations as $location) {
<add> foreach ($this->locations as $location) {
<ide> $class = App::className($options['className'], $location, 'Table');
<ide> if ($class !== false) {
<ide> return $class;
<ide> public function remove($alias)
<ide> public function addLocation($location)
<ide> {
<ide> $location = str_replace('\\', '/', $location);
<del> $this->_locations[] = trim($location, '/');
<add> $this->locations[] = trim($location, '/');
<ide>
<ide> return $this;
<ide> } | 1 |
Python | Python | fix assert_equal on time-like objects | f107d38b0513290307fa83dccebfe7db897d87b4 | <ide><path>numpy/testing/nose_tools/utils.py
<ide> def assert_equal(actual, desired, err_msg='', verbose=True):
<ide>
<ide> # Inf/nan/negative zero handling
<ide> try:
<del> # If one of desired/actual is not finite, handle it specially here:
<del> # check that both are nan if any is a nan, and test for equality
<del> # otherwise
<del> if not (gisfinite(desired) and gisfinite(actual)):
<del> isdesnan = gisnan(desired)
<del> isactnan = gisnan(actual)
<del> if isdesnan or isactnan:
<del> if not (isdesnan and isactnan):
<del> raise AssertionError(msg)
<del> else:
<del> if not desired == actual:
<del> raise AssertionError(msg)
<del> return
<del> elif desired == 0 and actual == 0:
<add> isdesnan = gisnan(desired)
<add> isactnan = gisnan(actual)
<add> if isdesnan and isactnan:
<add> return # both nan, so equal
<add>
<add> # handle signed zero specially for floats
<add> if desired == 0 and actual == 0:
<ide> if not signbit(desired) == signbit(actual):
<ide> raise AssertionError(msg)
<del> # If TypeError or ValueError raised while using isnan and co, just handle
<del> # as before
<add>
<ide> except (TypeError, ValueError, NotImplementedError):
<ide> pass
<ide>
<ide> try:
<del> # If both are NaT (and have the same dtype -- datetime or timedelta)
<del> # they are considered equal.
<del> if (isnat(desired) == isnat(actual) and
<del> array(desired).dtype.type == array(actual).dtype.type):
<add> isdesnat = isnat(desired)
<add> isactnat = isnat(actual)
<add> dtypes_match = array(desired).dtype.type == array(actual).dtype.type
<add> if isdesnat and isactnat and dtypes_match:
<add> # If both are NaT (and have the same dtype -- datetime or
<add> # timedelta) they are considered equal.
<ide> return
<del> else:
<del> raise AssertionError(msg)
<del>
<del> # If TypeError or ValueError raised while using isnan and co, just handle
<del> # as before
<ide> except (TypeError, ValueError, NotImplementedError):
<ide> pass
<ide>
<del> # Explicitly use __eq__ for comparison, ticket #2552
<del> if not (desired == actual):
<del> raise AssertionError(msg)
<add>
<add> try:
<add> # Explicitly use __eq__ for comparison, gh-2552
<add> if not (desired == actual):
<add> raise AssertionError(msg)
<add>
<add> except (DeprecationWarning, FutureWarning) as e:
<add> # this handles the case when the two types are not even comparable
<add> if 'elementwise == comparison' in e.args[0]:
<add> raise AssertionError(msg)
<add> else:
<add> raise
<ide>
<ide>
<ide> def print_assert_equal(test_string, actual, desired):
<ide><path>numpy/testing/tests/test_utils.py
<ide> def test_inf_items(self):
<ide> self._assert_func([np.inf], [np.inf])
<ide> self._test_not_equal(np.inf, [np.inf])
<ide>
<add> def test_datetime(self):
<add> self._test_equal(
<add> np.datetime64("2017-01-01", "s"),
<add> np.datetime64("2017-01-01", "s")
<add> )
<add> self._test_equal(
<add> np.datetime64("2017-01-01", "s"),
<add> np.datetime64("2017-01-01", "m")
<add> )
<add>
<add> # gh-10081
<add> self._test_not_equal(
<add> np.datetime64("2017-01-01", "s"),
<add> np.datetime64("2017-01-02", "s")
<add> )
<add> self._test_not_equal(
<add> np.datetime64("2017-01-01", "s"),
<add> np.datetime64("2017-01-02", "m")
<add> )
<add>
<ide> def test_nat_items(self):
<ide> # not a datetime
<ide> nadt_no_unit = np.datetime64("NaT") | 2 |
Python | Python | fix inconsistent lemmas | fd759a881b02a7bc3488b1d9c005d5849cfc05f9 | <ide><path>spacy/lang/ca/lemmatizer.py
<ide> def rule_lemmatize(self, token: Token) -> List[str]:
<ide> forms.append(self.lookup_lemmatize(token)[0])
<ide> if not forms:
<ide> forms.append(string)
<del> forms = list(set(forms))
<add> forms = list(dict.fromkeys(forms))
<ide> self.cache[cache_key] = forms
<ide> return forms
<ide><path>spacy/lang/fr/lemmatizer.py
<ide> def rule_lemmatize(self, token: Token) -> List[str]:
<ide> forms.append(self.lookup_lemmatize(token)[0])
<ide> if not forms:
<ide> forms.append(string)
<del> forms = list(set(forms))
<add> forms = list(dict.fromkeys(forms))
<ide> self.cache[cache_key] = forms
<ide> return forms
<ide><path>spacy/lang/nl/lemmatizer.py
<ide> def rule_lemmatize(self, token: Token) -> List[str]:
<ide> return forms
<ide> else:
<ide> oov_forms.append(form)
<del> forms = list(set(oov_forms))
<add> forms = list(dict.fromkeys(oov_forms))
<ide> # Back-off through remaining return value candidates.
<ide> if forms:
<ide> for form in forms:
<ide><path>spacy/lang/ru/lemmatizer.py
<ide> def pymorphy2_lemmatize(self, token: Token) -> List[str]:
<ide> if not len(filtered_analyses):
<ide> return [string.lower()]
<ide> if morphology is None or (len(morphology) == 1 and POS in morphology):
<del> return list(set([analysis.normal_form for analysis in filtered_analyses]))
<add> return list(dict.fromkeys([analysis.normal_form for analysis in filtered_analyses]))
<ide> if univ_pos in ("ADJ", "DET", "NOUN", "PROPN"):
<ide> features_to_compare = ["Case", "Number", "Gender"]
<ide> elif univ_pos == "NUM":
<ide> def pymorphy2_lemmatize(self, token: Token) -> List[str]:
<ide> filtered_analyses.append(analysis)
<ide> if not len(filtered_analyses):
<ide> return [string.lower()]
<del> return list(set([analysis.normal_form for analysis in filtered_analyses]))
<add> return list(dict.fromkeys([analysis.normal_form for analysis in filtered_analyses]))
<ide>
<ide> def pymorphy2_lookup_lemmatize(self, token: Token) -> List[str]:
<ide> string = token.text
<ide><path>spacy/util.py
<ide> def get_arg_names(func: Callable) -> List[str]:
<ide> RETURNS (List[str]): The argument names.
<ide> """
<ide> argspec = inspect.getfullargspec(func)
<del> return list(set([*argspec.args, *argspec.kwonlyargs]))
<add> return list(dict.fromkeys([*argspec.args, *argspec.kwonlyargs]))
<ide>
<ide>
<ide> def combine_score_weights( | 5 |
Text | Text | add docs for next dev and next start | 8f3931a0bec102b858afc99e6fa4f1257a0da6c0 | <ide><path>docs/api-reference/cli.md
<ide> NODE_OPTIONS='--inspect' next
<ide>
<ide> The first load is colored green, yellow, or red. Aim for green for performant applications.
<ide>
<add>## Development
<add>
<add>`next dev` starts the application in development mode with hot-code reloading, error reporting, and more:
<add>
<add>The application will start at `http://localhost:3000` by default. The default port can be changed with `-p`, like so:
<add>
<add>```bash
<add>npx next dev -p 4000
<add>```
<add>
<add>## Production
<add>
<add>`next start` starts the application in production mode. The application should be compiled with [`next build`](#build) first.
<add>
<add>The application will start at `http://localhost:3000` by default. The default port can be changed with `-p`, like so:
<add>
<add>```bash
<add>npx next start -p 4000
<add>```
<add>
<ide> ## Telemetry
<ide>
<ide> Next.js collects **completely anonymous** telemetry data about general usage. | 1 |
Ruby | Ruby | reduce block execution | c46172171b7beadcd28d71c1d5473b1bde0f7ede | <ide><path>actionpack/lib/action_controller/metal/instrumentation.rb
<ide> def process_action(*)
<ide> ActiveSupport::Notifications.instrument("start_processing.action_controller", raw_payload)
<ide>
<ide> ActiveSupport::Notifications.instrument("process_action.action_controller", raw_payload) do |payload|
<del> super.tap do
<del> payload[:status] = response.status
<del> end
<add> result = super
<add> payload[:status] = response.status
<add> result
<ide> ensure
<ide> append_info_to_payload(payload)
<ide> end | 1 |
PHP | PHP | remove dead code | 9446ff7e0afaf978858a1923e3e4722e5c36c01c | <ide><path>src/Database/Type.php
<ide> public static function set($name, TypeInterface $instance)
<ide> */
<ide> public static function map($type, $className = null)
<ide> {
<del> if ($type === null) {
<del> return static::$_types;
<del> }
<ide> if (is_array($type)) {
<ide> static::$_types = $type;
<ide> | 1 |
Text | Text | remove legacy wpt integration guide | 22f3ff9617019dc926e848498117fe04956f11f3 | <ide><path>doc/guides/writing-tests.md
<ide> functions worked correctly with the `beforeExit` event, then it might be named
<ide>
<ide> ### Web Platform Tests
<ide>
<del>Some of the tests for the WHATWG URL implementation (named
<del>`test-whatwg-url-*.js`) are imported from the [Web Platform Tests Project][].
<del>These imported tests will be wrapped like this:
<del>
<del>```js
<del>/* The following tests are copied from WPT. Modifications to them should be
<del> upstreamed first. Refs:
<del> https://github.com/w3c/web-platform-tests/blob/8791bed/url/urlsearchparams-stringifier.html
<del> License: http://www.w3.org/Consortium/Legal/2008/04-testsuite-copyright.html
<del>*/
<del>/* eslint-disable */
<del>
<del>// Test code
<del>
<del>/* eslint-enable */
<del>```
<del>
<del>To improve tests that have been imported this way, please send
<del>a PR to the upstream project first. When the proposed change is merged in
<del>the upstream project, send another PR here to update Node.js accordingly.
<del>Be sure to update the hash in the URL following `WPT Refs:`.
<add>See [`test/wpt`](../../test/wpt/README.md) for more information.
<ide>
<ide> ## C++ Unit test
<ide>
<ide> To generate a test coverage report, see the
<ide>
<ide> [ASCII]: http://man7.org/linux/man-pages/man7/ascii.7.html
<ide> [Google Test]: https://github.com/google/googletest
<del>[Web Platform Tests Project]: https://github.com/w3c/web-platform-tests/tree/master/url
<ide> [`common` module]: https://github.com/nodejs/node/blob/master/test/common/README.md
<ide> [all maintained branches]: https://github.com/nodejs/lts
<ide> [node.green]: http://node.green/ | 1 |
Text | Text | change http links to https in macos.md | cda38cd8cc1bb72e4f34a9ff5b0e912e7a693d56 | <ide><path>docs/build-instructions/macOS.md
<del>See the [Hacking on Atom Core](http://flight-manual.atom.io/hacking-atom/sections/hacking-on-atom-core/#platform-mac) section in the [Atom Flight Manual](http://flight-manual.atom.io).
<add>See the [Hacking on Atom Core](https://flight-manual.atom.io/hacking-atom/sections/hacking-on-atom-core/#platform-mac) section in the [Atom Flight Manual](https://flight-manual.atom.io). | 1 |
PHP | PHP | fix incorrect docs | 93ed7f87f3fec486869b59eb78e8631287325b6e | <ide><path>src/Routing/RouteBuilder.php
<ide> class RouteBuilder
<ide> *
<ide> * - `routeClass` - The default route class to use when adding routes.
<ide> * - `extensions` - The extensions to connect when adding routes.
<del> * - `namePrefix` - The prefix to append to all route names.
<add> * - `namePrefix` - The prefix to prepend to all route names.
<ide> *
<ide> * @param \Cake\Routing\RouteCollection $collection The route collection to append routes into.
<ide> * @param string $path The path prefix the scope is for. | 1 |
Java | Java | fix missing sslinfo with reactor netty and http/2 | 9b615ed8c669c272530733b17d11b852fed8e3b9 | <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ReactorServerHttpRequest.java
<ide>
<ide> import javax.net.ssl.SSLSession;
<ide>
<add>import io.netty.channel.Channel;
<ide> import io.netty.handler.codec.http.HttpHeaderNames;
<ide> import io.netty.handler.codec.http.cookie.Cookie;
<ide> import io.netty.handler.ssl.SslHandler;
<ide> public InetSocketAddress getRemoteAddress() {
<ide> @Override
<ide> @Nullable
<ide> protected SslInfo initSslInfo() {
<del> SslHandler sslHandler = ((Connection) this.request).channel().pipeline().get(SslHandler.class);
<add> Channel channel = ((Connection) this.request).channel();
<add> SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
<add> if (sslHandler == null && channel.parent() != null) { // HTTP/2
<add> sslHandler = channel.parent().pipeline().get(SslHandler.class);
<add> }
<ide> if (sslHandler != null) {
<ide> SSLSession session = sslHandler.engine().getSession();
<ide> return new DefaultSslInfo(session); | 1 |
Javascript | Javascript | fix performance issue when large line | f3473d7db696f78b284c7a874ba33ec5e2b91309 | <ide><path>lib/readline.js
<ide> Interface.prototype._normalWrite = function(b) {
<ide> this._sawReturn = false;
<ide> }
<ide>
<add> // Run test() on the new string chunk, not on the entire line buffer.
<add> var newPartContainsEnding = lineEnding.test(string);
<add>
<ide> if (this._line_buffer) {
<ide> string = this._line_buffer + string;
<ide> this._line_buffer = null;
<ide> }
<del> if (lineEnding.test(string)) {
<add> if (newPartContainsEnding) {
<ide> this._sawReturn = /\r$/.test(string);
<ide>
<ide> // got one or more newlines; process into "line" events | 1 |
Ruby | Ruby | fix sse3 detection on linux | 5ab745574cd951e5e3be018f7872004f78ef624f | <ide><path>Library/Homebrew/extend/os/linux/hardware/cpu.rb
<ide> def features
<ide> @features ||= flags[1..-1].map(&:intern)
<ide> end
<ide>
<del> %w[aes altivec avx avx2 lm sse3 ssse3 sse4 sse4_2].each do |flag|
<add> %w[aes altivec avx avx2 lm ssse3 sse4 sse4_2].each do |flag|
<ide> define_method(flag + "?") { flags.include? flag }
<ide> end
<add>
<add> def sse3?
<add> flags.include?("pni") || flags.include?("sse3")
<add> end
<add>
<ide> alias is_64_bit? lm?
<ide>
<ide> def bits | 1 |
Python | Python | fix multiple spaces after operator | 44b25b80b2fe0928378efd115c9a290ae1623445 | <ide><path>keras/layers/recurrent.py
<ide> def call(self, inputs, mask=None, initial_state=None, training=None):
<ide> if not isinstance(states, (list, tuple)):
<ide> states = [states]
<ide> else:
<del> states = list(states)
<add> states = list(states)
<ide> return [output] + states
<ide> else:
<ide> return output | 1 |
PHP | PHP | allow numerics for unix timestamps | da62677cea29ce3f5e6348c416218f11459ca3d6 | <ide><path>src/Illuminate/Validation/Validator.php
<ide> protected function validateDate($attribute, $value)
<ide> return true;
<ide> }
<ide>
<del> if (! is_string($value) || strtotime($value) === false) {
<add> if ((! is_string($value) && ! is_numeric($value)) || strtotime($value) === false) {
<ide> return false;
<ide> }
<ide>
<ide> protected function validateDateFormat($attribute, $value, $parameters)
<ide> {
<ide> $this->requireParameterCount(1, $parameters, 'date_format');
<ide>
<del> if (! is_string($value)) {
<add> if (! is_string($value) && ! is_numeric($value)) {
<ide> return false;
<ide> }
<ide>
<ide> protected function validateBefore($attribute, $value, $parameters)
<ide> {
<ide> $this->requireParameterCount(1, $parameters, 'before');
<ide>
<del> if (! is_string($value)) {
<add> if (! is_string($value) && ! is_numeric($value)) {
<ide> return false;
<ide> }
<ide>
<ide> protected function validateAfter($attribute, $value, $parameters)
<ide> {
<ide> $this->requireParameterCount(1, $parameters, 'after');
<ide>
<del> if (! is_string($value)) {
<add> if (! is_string($value) && ! is_numeric($value)) {
<ide> return false;
<ide> }
<ide> | 1 |
Javascript | Javascript | ignore dom writes outside the batch in reactperf | 3b2860222051cd3978529a89e4eb3193e23c6c26 | <ide><path>src/test/ReactDefaultPerfAnalysis.js
<ide> function getUnchangedComponents(measurement) {
<ide> // the amount of time it took to render the entire subtree.
<ide> var cleanComponents = {};
<ide> var writes = measurement.writes;
<add> var hierarchy = measurement.hierarchy;
<ide> var dirtyComposites = {};
<ide> Object.keys(writes).forEach(function(id) {
<ide> writes[id].forEach(function(write) {
<ide> // Root mounting (innerHTML set) is recorded with an ID of ''
<del> if (id !== '') {
<del> measurement.hierarchy[id].forEach((c) => dirtyComposites[c] = true);
<add> if (id !== '' && hierarchy.hasOwnProperty(id)) {
<add> hierarchy[id].forEach((c) => dirtyComposites[c] = true);
<ide> }
<ide> });
<ide> });
<ide><path>src/test/__tests__/ReactDefaultPerf-test.js
<ide> describe('ReactDefaultPerf', function() {
<ide> expect(summary).toEqual([]);
<ide> });
<ide>
<add> it('should not fail on input change events', function() {
<add> var container = document.createElement('div');
<add> var onChange = () => {};
<add> var input = ReactDOM.render(
<add> <input checked={true} onChange={onChange} />,
<add> container
<add> );
<add> expectNoWaste(() => {
<add> ReactTestUtils.Simulate.change(input);
<add> });
<add> });
<add>
<ide> it('should print a table after calling printOperations', function() {
<ide> var container = document.createElement('div');
<ide> var measurements = measure(() => { | 2 |
Javascript | Javascript | update shallowcompare to accept nextcontext | 8ea1cf4ee0f5315c4190a9e67e15f0f7404cb0cf | <ide><path>src/addons/ReactComponentWithPureRenderMixin.js
<ide> var shallowCompare = require('shallowCompare');
<ide> * See https://facebook.github.io/react/docs/pure-render-mixin.html
<ide> */
<ide> var ReactComponentWithPureRenderMixin = {
<del> shouldComponentUpdate: function(nextProps, nextState) {
<del> return shallowCompare(this, nextProps, nextState);
<add> shouldComponentUpdate: function(nextProps, nextState, nextContext) {
<add> return shallowCompare(this, nextProps, nextState, nextContext);
<ide> },
<ide> };
<ide>
<ide><path>src/addons/shallowCompare.js
<ide> var shallowEqual = require('shallowEqual');
<ide> * See ReactComponentWithPureRenderMixin
<ide> * See also https://facebook.github.io/react/docs/shallow-compare.html
<ide> */
<del>function shallowCompare(instance, nextProps, nextState) {
<add>function shallowCompare(instance, nextProps, nextState, nextContext) {
<ide> return (
<ide> !shallowEqual(instance.props, nextProps) ||
<del> !shallowEqual(instance.state, nextState)
<add> !shallowEqual(instance.state, nextState) ||
<add> !shallowEqual(instance.context, nextContext)
<ide> );
<ide> }
<ide> | 2 |
Go | Go | fix testparserunvolumes with go 1.3 randomization | f6e6cf9071b098f3e38b42597d94cd0768b17219 | <ide><path>runconfig/config_test.go
<ide> package runconfig
<ide>
<ide> import (
<add> "fmt"
<ide> "strings"
<ide> "testing"
<ide>
<ide> func mustParse(t *testing.T, args string) (*Config, *HostConfig) {
<ide> return config, hostConfig
<ide> }
<ide>
<add>// check if (a == c && b == d) || (a == d && b == c)
<add>// because maps are randomized
<add>func compareRandomizedStrings(a, b, c, d string) error {
<add> if a == c && b == d {
<add> return nil
<add> }
<add> if a == d && b == c {
<add> return nil
<add> }
<add> return fmt.Errorf("strings don't match")
<add>}
<add>
<ide> func TestParseRunLinks(t *testing.T) {
<ide> if _, hostConfig := mustParse(t, "--link a:b"); len(hostConfig.Links) == 0 || hostConfig.Links[0] != "a:b" {
<ide> t.Fatalf("Error parsing links. Expected []string{\"a:b\"}, received: %v", hostConfig.Links)
<ide> func TestParseRunVolumes(t *testing.T) {
<ide> t.Fatalf("Error parsing volume flags, `-v /hostTmp:/containerTmp` should mount-bind /hostTmp into /containeTmp. Received %v", hostConfig.Binds)
<ide> }
<ide>
<del> if _, hostConfig := mustParse(t, "-v /hostTmp:/containerTmp -v /hostVar:/containerVar"); hostConfig.Binds == nil || hostConfig.Binds[0] != "/hostTmp:/containerTmp" || hostConfig.Binds[1] != "/hostVar:/containerVar" {
<add> if _, hostConfig := mustParse(t, "-v /hostTmp:/containerTmp -v /hostVar:/containerVar"); hostConfig.Binds == nil || compareRandomizedStrings(hostConfig.Binds[0], hostConfig.Binds[1], "/hostTmp:/containerTmp", "/hostVar:/containerVar") != nil {
<ide> t.Fatalf("Error parsing volume flags, `-v /hostTmp:/containerTmp -v /hostVar:/containerVar` should mount-bind /hostTmp into /containeTmp and /hostVar into /hostContainer. Received %v", hostConfig.Binds)
<ide> }
<ide>
<del> if _, hostConfig := mustParse(t, "-v /hostTmp:/containerTmp:ro -v /hostVar:/containerVar:rw"); hostConfig.Binds == nil || hostConfig.Binds[0] != "/hostTmp:/containerTmp:ro" || hostConfig.Binds[1] != "/hostVar:/containerVar:rw" {
<add> if _, hostConfig := mustParse(t, "-v /hostTmp:/containerTmp:ro -v /hostVar:/containerVar:rw"); hostConfig.Binds == nil || compareRandomizedStrings(hostConfig.Binds[0], hostConfig.Binds[1], "/hostTmp:/containerTmp:ro", "/hostVar:/containerVar:rw") != nil {
<ide> t.Fatalf("Error parsing volume flags, `-v /hostTmp:/containerTmp:ro -v /hostVar:/containerVar:rw` should mount-bind /hostTmp into /containeTmp and /hostVar into /hostContainer. Received %v", hostConfig.Binds)
<ide> }
<ide> | 1 |
Python | Python | add fp16 to 8 gpu fp16 tests. | ba0a6f60a5305839c82b5d62d63222d2da5ea414 | <ide><path>official/resnet/keras/keras_imagenet_benchmark.py
<ide> def benchmark_8_gpu_fp16(self):
<ide> self._setup()
<ide>
<ide> FLAGS.num_gpus = 8
<add> FLAGS.dtype = 'fp16'
<ide> FLAGS.enable_eager = True
<ide> FLAGS.distribution_strategy = 'default'
<ide> FLAGS.model_dir = self._get_model_dir('benchmark_8_gpu_fp16')
<ide> def benchmark_xla_8_gpu_fp16(self):
<ide> self._setup()
<ide>
<ide> FLAGS.num_gpus = 8
<add> FLAGS.dtype = 'fp16'
<ide> FLAGS.enable_eager = True
<ide> FLAGS.enable_xla = True
<ide> FLAGS.distribution_strategy = 'default'
<ide> def benchmark_graph_xla_8_gpu(self):
<ide> FLAGS.enable_xla = True
<ide> FLAGS.distribution_strategy = 'default'
<ide> FLAGS.model_dir = self._get_model_dir('benchmark_graph_xla_8_gpu')
<del> # TODO(haoyuzhang): Set size to 128 per GPU when multi-GPU XLA OOM is fixed
<del> FLAGS.batch_size = 64 * 8 # 8 GPUs
<add> FLAGS.batch_size = 128 * 8 # 8 GPUs
<ide> self._run_and_report_benchmark()
<ide>
<ide> def fill_report_object(self, stats): | 1 |
Python | Python | include host info in image.extra for kvm | 1104beb447410562a75262605aea41ab9e077fda | <ide><path>libcloud/compute/drivers/libvirt_driver.py
<ide> def list_images(self, location=IMAGES_LOCATION):
<ide> if output:
<ide> for image in output.strip().split('\n'):
<ide> name = image.replace(IMAGES_LOCATION + '/', '')
<del> nodeimage = NodeImage(id=image, name=name, driver=self, extra={})
<add> nodeimage = NodeImage(id=image, name=name, driver=self, extra={'host': self.connection.getHostname()})
<ide> images.append(nodeimage)
<ide>
<ide> return images | 1 |
Java | Java | fix image orientation on android for local uris | 1f501a9431a56a357987dcf42520c0626b713b50 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/image/ReactImageView.java
<ide> public void maybeUpdateView() {
<ide> ImageRequest imageRequest = ImageRequestBuilder.newBuilderWithSource(mUri)
<ide> .setPostprocessor(postprocessor)
<ide> .setResizeOptions(resizeOptions)
<add> .setAutoRotateEnabled(true)
<ide> .setProgressiveRenderingEnabled(mProgressiveRenderingEnabled)
<ide> .build();
<ide> | 1 |
Javascript | Javascript | fix typo in test description | 9a06439a460196347d50092ae42dbbc1bc198429 | <ide><path>packages/ember-routing/tests/utils_test.js
<ide> QUnit.test('converts array style into verbose object style', function(assert) {
<ide> equal(normalized[paramName].scope, 'model', 'defaults scope to model');
<ide> });
<ide>
<del>QUnit.test('converts object stlye [{foo: \'an_alias\'}]', function(assert) {
<add>QUnit.test('converts object style [{foo: \'an_alias\'}]', function(assert) {
<ide> let paramName = 'foo';
<ide> let params = [{ 'foo': 'an_alias' }];
<ide> let normalized = normalizeControllerQueryParams(params);
<ide> QUnit.test('converts object stlye [{foo: \'an_alias\'}]', function(assert) {
<ide> equal(normalized[paramName].scope, 'model', 'defaults scope to model');
<ide> });
<ide>
<del>QUnit.test('retains maximally verbose object stlye [{foo: {as: \'foo\'}}]', function(assert) {
<add>QUnit.test('retains maximally verbose object style [{foo: {as: \'foo\'}}]', function(assert) {
<ide> let paramName = 'foo';
<ide> let params = [{ 'foo': { as: 'an_alias' } }];
<ide> let normalized = normalizeControllerQueryParams(params); | 1 |
Ruby | Ruby | fix hash#from_xml with frozen strings | dd829df07e632209404b025423f57d63148d0867 | <ide><path>activesupport/lib/active_support/xml_mini/rexml.rb
<ide> def parse(data)
<ide> data = StringIO.new(data || '')
<ide> end
<ide>
<del> char = data.getc
<del> if char.nil?
<add> if data.eof?
<ide> {}
<ide> else
<del> data.ungetc(char)
<ide> silence_warnings { require 'rexml/document' } unless defined?(REXML::Document)
<ide> doc = REXML::Document.new(data)
<ide>
<ide><path>activesupport/test/xml_mini/rexml_engine_test.rb
<ide> def test_parse_from_io
<ide> morning
<ide> </root>
<ide> eoxml
<del> assert_equal_rexml(io)
<add> hash = ActiveSupport::XmlMini.parse(io)
<add> assert hash.has_key?('root')
<add> assert hash['root'].has_key?('products')
<add> assert_match "good", hash['root']['__content__']
<add> products = hash['root']['products']
<add> assert products.has_key?("__content__")
<add> assert_match 'hello everyone', products['__content__']
<add> end
<add>
<add> def test_parse_from_empty_string
<add> ActiveSupport::XmlMini.backend = 'REXML'
<add> assert_equal({}, ActiveSupport::XmlMini.parse(""))
<add> end
<add>
<add> def test_parse_from_frozen_string
<add> ActiveSupport::XmlMini.backend = 'REXML'
<add> xml_string = "<root></root>".freeze
<add> assert_equal({"root" => {}}, ActiveSupport::XmlMini.parse(xml_string))
<ide> end
<ide>
<del> private
<del> def assert_equal_rexml(xml)
<del> parsed_xml = ActiveSupport::XmlMini.parse(xml)
<del> xml.rewind if xml.respond_to?(:rewind)
<del> hash = ActiveSupport::XmlMini.with_backend('REXML') { ActiveSupport::XmlMini.parse(xml) }
<del> assert_equal(hash, parsed_xml)
<del> end
<ide> end | 2 |
Go | Go | add test for dns options | e4f3bcb696d3ea3580ab7c93d2e41f02108aa011 | <ide><path>libnetwork/service_common_test.go
<ide> import (
<ide> "net"
<ide> "testing"
<ide>
<add> "github.com/docker/libnetwork/resolvconf"
<add> "github.com/stretchr/testify/assert"
<ide> "github.com/stretchr/testify/require"
<ide> )
<ide>
<ide> func TestCleanupServiceDiscovery(t *testing.T) {
<ide> t.Fatalf("Service record not cleaned correctly:%v", c.(*controller).svcRecords)
<ide> }
<ide> }
<add>
<add>func TestDNSOptions(t *testing.T) {
<add> c, err := New()
<add> require.NoError(t, err)
<add>
<add> sb, err := c.(*controller).NewSandbox("cnt1", nil)
<add> require.NoError(t, err)
<add> defer sb.Delete()
<add> sb.(*sandbox).startResolver(false)
<add>
<add> sb.(*sandbox).config.dnsOptionsList = []string{"ndots:5"}
<add> err = sb.(*sandbox).setupDNS()
<add> require.NoError(t, err)
<add> err = sb.(*sandbox).rebuildDNS()
<add> require.NoError(t, err)
<add>
<add> currRC, err := resolvconf.GetSpecific(sb.(*sandbox).config.resolvConfPath)
<add> require.NoError(t, err)
<add> dnsOptionsList := resolvconf.GetOptions(currRC.Content)
<add> assert.Equal(t, 1, len(dnsOptionsList), "There should be only 1 option instead:", dnsOptionsList)
<add> assert.Equal(t, "ndots:0", dnsOptionsList[0], "The option must be ndots:0 instead:", dnsOptionsList[0])
<add>} | 1 |
Ruby | Ruby | use each instead of for...in | de6660b5ec4aa8c0e2415f3483aa9346ef8c9223 | <ide><path>actionpack/lib/action_view/base.rb
<ide> module ActionView #:nodoc:
<ide> # xml.language "en-us"
<ide> # xml.ttl "40"
<ide> #
<del> # for item in @recent_items
<add> # @recent_items.each do |item|
<ide> # xml.item do
<ide> # xml.title(item_title(item))
<ide> # xml.description(item_description(item)) if item_description(item)
<ide><path>activerecord/lib/active_record/fixtures.rb
<ide> class FixturesFileNotFound < StandardError; end
<ide> # Some times you don't care about the content of the fixtures as much as you care about the volume. In these cases, you can
<ide> # mix ERB in with your YAML fixtures to create a bunch of fixtures for load testing, like:
<ide> #
<del># <% for i in 1..1000 %>
<add># <% (1..1000).each do |i| %>
<ide> # fix_<%= i %>:
<ide> # id: <%= i %>
<ide> # name: guy_<%= 1 %> | 2 |
Text | Text | clarify repack, fix a couple broken links | 7133fd85167c4f33d305d54408825fd6b06ecf31 | <ide><path>CONTRIBUTING.md
<ide> These HTML files are self-contained and run their own tests -- open a browser JS
<ide>
<ide> > **Note**: These in-browser tests should work for simple JavaScript challenges. But other types of challenges may not fare so well. For HTML challenges, challenge tests assume that the solution HTML is the only HTML on the whole page, so jQuery selectors may select seed *and* solution elements. For React / Modern JS challenges, we would need to transpile JSX or ES6 before running the tests.
<ide>
<del>`npm run repack` gathers up the unpacked/edited HTML files into challenge-block JSON files. After running repack, use `git diff` to see the changes.
<add>`npm run repack` gathers up the unpacked/edited HTML files into challenge-block JSON files. After running repack, use `git diff` to see the changes in your console, and `npm run seed` to see the changes in your local freeCodeCamp app instance.
<ide>
<ide> When editing the unpacked files, you must only insert or edit lines between comment fences like `<!--description-->` and `<!--end-->`. In descriptions, you can insert a paragraph break with `<!--break-->`.
<ide> | 1 |
Text | Text | add docker-exec to main manpage | fc75ade4f81229d5f6c36150b1c99c0edb7a8e8f | <ide><path>docs/man/docker-exec.md
<ide> % Docker Community
<ide> % SEPT 2014
<ide> # NAME
<del>docker-exec - Run a command in an existing container
<add>docker-exec - Run a command in an active container
<ide>
<ide> # SYNOPSIS
<ide> **docker exec**
<ide><path>docs/man/docker.1.md
<ide> unix://[/path/to/socket] to use.
<ide> **docker-events(1)**
<ide> Get real time events from the server
<ide>
<add>**docker-exec(1)**
<add> Run a command in an active container
<add>
<ide> **docker-export(1)**
<ide> Stream the contents of a container as a tar archive
<ide> | 2 |
Python | Python | remove commented lines | 0431e38ef2cf50da0c3e5c1d3f63f3a0ec30759d | <ide><path>libcloud/compute/drivers/gce.py
<ide> def ex_get_subnetwork(self, name, region=None):
<ide> """
<ide> region_name = None
<ide> if name.startswith('https://'):
<del> #parts = self._get_components_from_path(name)
<del> #name = parts['name']
<del> #region_name = parts['region']
<ide> request = name
<ide> else:
<ide> if isinstance(region, GCERegion):
<ide> def ex_get_subnetwork(self, name, region=None):
<ide>
<ide> request = '/regions/%s/subnetworks/%s' % (region_name, name)
<ide>
<del> # request = '/regions/%s/subnetworks/%s' % (region_name, name)
<ide> response = self.connection.request(request, method='GET').object
<ide> return self._to_subnetwork(response)
<ide> | 1 |
Ruby | Ruby | remove double underscore on test method | e0d4fa58df7ddbaddbe90a7fddab15945b8b324f | <ide><path>activerecord/test/cases/relation/where_chain_test.rb
<ide> def test_associated_with_multiple_associations
<ide> end
<ide> end
<ide>
<del> def test_associated__with_invalid_association_name
<add> def test_associated_with_invalid_association_name
<ide> e = assert_raises(ArgumentError) do
<ide> Post.where.associated(:cars).to_a
<ide> end | 1 |
Text | Text | update the contributing guide for docusaurus | 00f726b0eaeeaad177ded228a00cb4c4e0c9e529 | <ide><path>docs/docs/developers/contributing.md
<ide> The following commands are now available from the repository root:
<ide> > gulp lint // perform code linting (ESLint)
<ide> > gulp test // perform code linting and run unit tests
<ide> > gulp test --browsers ... // test with specified browsers (comma-separated)
<del>> gulp docs // build the documentation in ./dist/docs
<del>> gulp docs --watch // starts the gitbook live reloaded server
<ide> ```
<ide>
<ide> More information can be found in [gulpfile.js](https://github.com/chartjs/Chart.js/blob/master/gulpfile.js).
<ide>
<add>### Documentation
<add>
<add>We use [Docusaurus v2](https://v2.docusaurus.io/docs/introduction) to manage the docs which are contained as Markdown files in the docs directory. You can run the doc server locally using the commands provided by Docusaurus:
<add>
<add>```
<add>$ cd docs
<add>$ npm install
<add>$ npm run start
<add>```
<add>
<ide> ### Image-Based Tests
<ide>
<ide> Some display-related functionality is difficult to test via typical Jasmine units. For this reason, we introduced image-based tests ([#3988](https://github.com/chartjs/Chart.js/pull/3988) and [#5777](https://github.com/chartjs/Chart.js/pull/5777)) to assert that a chart is drawn pixel-for-pixel matching an expected image. | 1 |
Go | Go | name the ingress sandbox explicitly | e31db5d6af5a4c111435b65dbed486a968e1170f | <ide><path>libnetwork/controller.go
<ide> func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (s
<ide>
<ide> if sb.ingress {
<ide> c.ingressSandbox = sb
<add> sb.id = "ingress_sbox"
<ide> }
<ide> c.Unlock()
<ide> defer func() { | 1 |
Javascript | Javascript | terminate statement in matrix4 test | 7cdc5db5b137ae4f7c6ae416a98c74aa2085ddae | <ide><path>test/unit/math/Matrix4.js
<ide> test( "makeBasis/extractBasis", function() {
<ide> var identity = new THREE.Matrix4();
<ide> ok( matrixEquals4( a, identity ), "Passed!" );
<ide>
<del> var testBases = [ [ new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( -1, 0, 0 ), new THREE.Vector3( 0, 0, 1 ) ] ]
<add> var testBases = [ [ new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( -1, 0, 0 ), new THREE.Vector3( 0, 0, 1 ) ] ];
<ide> for( var i = 0; i < testBases.length; i ++ ) {
<ide> var testBasis = testBases[i];
<ide> var b = new THREE.Matrix4().makeBasis( testBasis[0], testBasis[1], testBasis[2] ); | 1 |
Text | Text | add links to get to know more info | b634228c1613f9271618c089cf6cff6ae1a34454 | <ide><path>guide/english/agile/continuous-delivery/index.md
<ide> Continuous delivery (CD) is a software engineering approach in which teams produ
<ide>
<ide> It aims at building, testing, and releasing software faster and more frequently. The approach helps reduce the cost, time, and risk of delivering changes by allowing for more incremental updates to applications in production. A straightforward and repeatable deployment process is important for continuous delivery. Continuous delivery means that the team ensures every change can be deployed to production but may choose not to do it, usually due to business reasons.
<ide>
<del>
<add>#### More information
<add>- [General information](https://continuousdelivery.com/)
<add>- [The Ultimate Guide To a Successful Continuous Delivery Pipeline](https://mobilelabsinc.com/blog/successful-continuous-delivery-pipeline)
<add>- [Build it, Test it, Deliver it!
<add>Complete iOS Guide on Continuous Delivery with fastlane and Jenkins](https://medium.com/flawless-app-stories/build-it-test-it-deliver-it-complete-ios-guide-on-continuous-delivery-with-fastlane-and-jenkins-cbe44e996ac5)
<ide> | 1 |
Java | Java | release fix for race condition on startsurface | d71a0be6fa0ed4d38d58f1bce30e532581a7bfca | <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java
<ide> public void showDevOptionsDialog() {
<ide> @ThreadConfined(UI)
<ide> private void clearReactRoot(ReactRoot reactRoot) {
<ide> UiThreadUtil.assertOnUiThread();
<del> if (ReactFeatureFlags.enableStartSurfaceRaceConditionFix) {
<del> reactRoot.getState().compareAndSet(ReactRoot.STATE_STARTED, ReactRoot.STATE_STOPPED);
<del> }
<add> reactRoot.getState().compareAndSet(ReactRoot.STATE_STARTED, ReactRoot.STATE_STOPPED);
<ide> ViewGroup rootViewGroup = reactRoot.getRootViewGroup();
<ide> rootViewGroup.removeAllViews();
<ide> rootViewGroup.setId(View.NO_ID);
<ide> public void attachRootView(ReactRoot reactRoot) {
<ide> // Calling clearReactRoot is necessary to initialize the Id on reactRoot
<ide> // This is necessary independently if the RN Bridge has been initialized or not.
<ide> // Ideally reactRoot should be initialized with id == NO_ID
<del> if (ReactFeatureFlags.enableStartSurfaceRaceConditionFix) {
<del> if (mAttachedReactRoots.add(reactRoot)) {
<del> clearReactRoot(reactRoot);
<del> }
<del> } else {
<del> mAttachedReactRoots.add(reactRoot);
<add> if (mAttachedReactRoots.add(reactRoot)) {
<ide> clearReactRoot(reactRoot);
<ide> }
<ide>
<ide> public void attachRootView(ReactRoot reactRoot) {
<ide> // reactRoot reactRoot list.
<ide> ReactContext currentContext = getCurrentReactContext();
<ide> if (mCreateReactContextThread == null && currentContext != null) {
<del> if (!ReactFeatureFlags.enableStartSurfaceRaceConditionFix
<del> || reactRoot.getState().compareAndSet(ReactRoot.STATE_STOPPED, ReactRoot.STATE_STARTED)) {
<add> if (reactRoot.getState().compareAndSet(ReactRoot.STATE_STOPPED, ReactRoot.STATE_STARTED)) {
<ide> attachRootViewToInstance(reactRoot);
<ide> }
<ide> }
<ide> private void setupReactContext(final ReactApplicationContext reactContext) {
<ide>
<ide> ReactMarker.logMarker(ATTACH_MEASURED_ROOT_VIEWS_START);
<ide> for (ReactRoot reactRoot : mAttachedReactRoots) {
<del> if (!ReactFeatureFlags.enableStartSurfaceRaceConditionFix
<del> || reactRoot
<del> .getState()
<del> .compareAndSet(ReactRoot.STATE_STOPPED, ReactRoot.STATE_STARTED)) {
<add> if (reactRoot.getState().compareAndSet(ReactRoot.STATE_STOPPED, ReactRoot.STATE_STARTED)) {
<ide> attachRootViewToInstance(reactRoot);
<ide> }
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/config/ReactFeatureFlags.java
<ide> public class ReactFeatureFlags {
<ide> /** Feature flag to configure eager initialization of Fabric */
<ide> public static boolean eagerInitializeFabric = false;
<ide>
<del> /**
<del> * Fixes race-condition in the initialization of RN surface. TODO T78832286: remove this flag once
<del> * we verify the fix is correct in production
<del> */
<del> public static boolean enableStartSurfaceRaceConditionFix = false;
<del>
<ide> /** Enables Static ViewConfig in RN Android native code. */
<ide> public static boolean enableExperimentalStaticViewConfigs = false;
<ide> | 2 |
Python | Python | add time sleep in the incomming loop | d153dd29cf7d5fdcd0424a5b78b9e3ced35c9b4d | <ide><path>glances/core/glances_autodiscover.py
<ide>
<ide> # Import system libs
<ide> import socket
<add>import time
<ide> try:
<ide> import netifaces
<ide> netifaces_tag = True
<ide> def addService(self, zeroconf, srv_type, srv_name):
<ide> self.servers.add_server(srv_name, new_server_ip, new_server_port)
<ide> logger.info("New Glances server detected (%s from %s:%s)" %
<ide> (srv_name, new_server_ip, new_server_port))
<add> time.sleep(3)
<ide> else:
<ide> logger.warning(
<ide> "New Glances server detected, but Zeroconf info failed to be grabbed")
<ide> class GlancesAutoDiscoverClient(object):
<ide> def __init__(self, hostname, args=None):
<ide> if netifaces_tag:
<ide> # !!! TO BE REFACTOR
<del> # OK with server: LANGUAGE=en_US.utf8 python -m glances -s -d -B 192.168.176.128
<del> # KO with server: LANGUAGE=en_US.utf8 python -m glances -s -d
<ide> try:
<ide> zeroconf_bind_address = netifaces.ifaddresses(netifaces.interfaces()[1])[netifaces.AF_INET][0]['addr']
<ide> except:
<ide><path>glances/core/glances_server.py
<ide> import json
<ide> import socket
<ide> import sys
<del>import time
<ide> from base64 import b64decode
<ide> try:
<ide> from xmlrpc.server import SimpleXMLRPCRequestHandler
<ide> def __init__(self, requestHandler=GlancesXMLRPCHandler,
<ide> self.server.register_introspection_functions()
<ide> self.server.register_instance(GlancesInstance(cached_time, config))
<ide>
<del> # Announce the server to the network (wait 1 seond before do this)
<del> time.sleep(1)
<ide> if not self.args.disable_autodiscover:
<ide> # Note: The Zeroconf service name will be based on the hostname
<ide> self.autodiscover_client = GlancesAutoDiscoverClient(socket.gethostname(), args) | 2 |
Javascript | Javascript | allow modifiers on inline ng-pattern | 12b6deb1ce99df64e2fc91a06bf05cd7f4a3a475 | <ide><path>src/ng/directive/input.js
<ide> function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
<ide>
<ide> // pattern validator
<ide> var pattern = attr.ngPattern,
<del> patternValidator;
<add> patternValidator,
<add> match;
<ide>
<ide> var validate = function(regexp, value) {
<ide> if (isEmpty(value) || regexp.test(value)) {
<ide> function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
<ide> };
<ide>
<ide> if (pattern) {
<del> if (pattern.match(/^\/(.*)\/$/)) {
<del> pattern = new RegExp(pattern.substr(1, pattern.length - 2));
<add> match = pattern.match(/^\/(.*)\/([gim]*)$/);
<add> if (match) {
<add> pattern = new RegExp(match[1], match[2]);
<ide> patternValidator = function(value) {
<ide> return validate(pattern, value)
<ide> };
<ide><path>test/ng/directive/inputSpec.js
<ide> describe('input', function() {
<ide> });
<ide>
<ide>
<add> it('should validate in-lined pattern with modifiers', function() {
<add> compileInput('<input type="text" ng-model="value" ng-pattern="/^abc?$/i" />');
<add> scope.$digest();
<add>
<add> changeInputValueTo('aB');
<add> expect(inputElm).toBeValid();
<add>
<add> changeInputValueTo('xx');
<add> expect(inputElm).toBeInvalid();
<add> });
<add>
<add>
<ide> it('should validate pattern from scope', function() {
<ide> compileInput('<input type="text" ng-model="value" ng-pattern="regexp" />');
<ide> scope.regexp = /^\d\d\d-\d\d-\d\d\d\d$/; | 2 |
Javascript | Javascript | update variable name and doc type to be accurate | c4b9b938cf5f40637deb9a27c21154785abd81e4 | <ide><path>src/browser/ui/ReactMount.js
<ide> var ReactMount = {
<ide> /**
<ide> * Take a component that's already mounted into the DOM and replace its props
<ide> * @param {ReactComponent} prevComponent component instance already in the DOM
<del> * @param {ReactComponent} nextComponent component instance to render
<add> * @param {ReactElement} nextElement component instance to render
<ide> * @param {DOMElement} container container to render into
<ide> * @param {?function} callback function triggered on completion
<ide> */
<ide> _updateRootComponent: function(
<ide> prevComponent,
<del> nextComponent,
<add> nextElement,
<ide> container,
<ide> callback) {
<del> var nextProps = nextComponent.props;
<add> var nextProps = nextElement.props;
<ide> ReactMount.scrollMonitor(container, function() {
<ide> prevComponent.replaceProps(nextProps, callback);
<ide> }); | 1 |
Ruby | Ruby | add brew doctor check for spaces in xcode path | 80335bba7498e484997a6ccf4bbfccef2bb251f9 | <ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def check_homebrew_prefix
<ide> end
<ide> end
<ide>
<add>def check_xcode_prefix
<add> prefix = MacOS.xcode_prefix
<add> return if prefix.nil?
<add> if prefix.to_s.match(' ')
<add> puts <<-EOS.undent
<add> Xcode is installed to a folder with a space in the name.
<add> This may cause some formulae, such as libiconv, to fail to build.
<add>
<add> EOS
<add> end
<add>end
<add>
<ide> def check_user_path
<ide> seen_prefix_bin = false
<ide> seen_prefix_sbin = false
<ide> def doctor
<ide> begin
<ide> check_usr_bin_ruby
<ide> check_homebrew_prefix
<add> check_xcode_prefix
<ide> check_for_macgpg2
<ide> check_for_stray_dylibs
<ide> check_for_stray_static_libs | 1 |
Javascript | Javascript | fix failing tests | cf66cccb19922c40df0fcf38acec3dd3e6768df8 | <ide><path>test/geom/voronoi-test.js
<ide> suite.addBatch({
<ide> },
<ide> "returns two cells with the expected geometry": function(cells) {
<ide> assert.inDelta(cells, [
<del> [[-178046.7857142857, 1e6], [179096.07142857145, -1e6], [-1e6, 1e6], [1e6, 1e6]],
<del> [[-178046.7857142857, 1e6], [179096.07142857145, -1e6], [-1e6, -1e6], [1e6, -1e6]]
<add> [[-1e6, 1e6], [-1e6, -1e6], [179096.07142857145, -1e6], [-178046.7857142857, 1e6]],
<add> [[1e6, -1e6], [1e6, 1e6], [-178046.7857142857, 1e6], [179096.07142857145, -1e6]]
<ide> ], 1e-6);
<ide> },
<ide> "the returned cells are open polygons": function(cells) {
<ide> suite.addBatch({
<ide> },
<ide> "for three points": function(v) {
<ide> assert.deepEqual(v.links([[200, 200], [500, 250], [760, 300]]), [
<del> {source: [200, 200], target: [760, 300]},
<add> {source: [200, 200], target: [500, 250]},
<ide> {source: [500, 250], target: [760, 300]},
<del> {source: [200, 200], target: [500, 250]}
<add> {source: [760, 300], target: [200, 200]}
<ide> ]);
<ide> }
<ide> },
<ide> suite.addBatch({
<ide> },
<ide> "returns two cells with the expected geometry": function(cells) {
<ide> assert.inDelta(cells, [
<del> [[480, 1e6], [480, -1e6], [-1e6, -1e6], [-1e6, 1e6]],
<del> [[480, -1e6], [480, 1e6], [1e6, -1e6], [1e6, 1e6]]
<add> [[-1e6, 1e6], [-1e6, -1e6], [480, -1e6], [480, 1e6]],
<add> [[1e6, -1e6], [1e6, 1e6], [480, 1e6], [480, -1e6]]
<ide> ], 1e-6);
<ide> }
<ide> },
<ide> suite.addBatch({
<ide> },
<ide> "for three points": function(v) {
<ide> assert.deepEqual(v.links([{x: 200, y: 200}, {x: 500, y: 250}, {x: 760, y: 300}]), [
<del> {source: {x: 200, y: 200}, target: {x: 760, y: 300}},
<add> {source: {x: 200, y: 200}, target: {x: 500, y: 250}},
<ide> {source: {x: 500, y: 250}, target: {x: 760, y: 300}},
<del> {source: {x: 200, y: 200}, target: {x: 500, y: 250}}
<add> {source: {x: 760, y: 300}, target: {x: 200, y: 200}}
<ide> ]);
<ide> }
<ide> }
<ide> suite.addBatch({
<ide> },
<ide> "returns two cells with the expected geometry": function(cells) {
<ide> assert.inDelta(cells, [
<del> [[435.35714285715324, 500], [524.6428571428696, 0], [0, 0], [0, 500]],
<add> [[0, 500], [0, 0], [524.6428571428696, 0], [435.35714285715324, 500]],
<ide> [[960, 0], [960, 500], [435.35714285715324, 500], [524.6428571428696, 0]]
<ide> ], 1e-6);
<ide> }, | 1 |
PHP | PHP | fix bug in eloqueny hydrator | 8af11e6d61446ab195fc987d71c5ba2969346595 | <ide><path>laravel/database/eloquent/query.php
<ide> public function hydrate($model, $results, $include = true)
<ide> $new->$key = $value;
<ide> }
<ide>
<add> $new->original = $new->attributes;
<add>
<ide> $models[$result[$this->model->key()]] = $new;
<ide> }
<ide> | 1 |
Go | Go | update logic of history | 5a3236d9e8ee8c0051c0cc758ec359fa089b3291 | <ide><path>api/client/history.go
<ide> func (cli *DockerCli) CmdHistory(args ...string) error {
<ide> return nil
<ide> }
<ide>
<add> var imageID string
<add> var createdBy string
<add> var created string
<add> var size string
<add>
<ide> fmt.Fprintln(w, "IMAGE\tCREATED\tCREATED BY\tSIZE\tCOMMENT")
<ide> for _, entry := range history {
<del> imageID := entry.ID
<del> createdBy := strings.Replace(entry.CreatedBy, "\t", " ", -1)
<add> imageID = entry.ID
<add> createdBy = strings.Replace(entry.CreatedBy, "\t", " ", -1)
<ide> if *noTrunc == false {
<ide> createdBy = stringutils.Truncate(createdBy, 45)
<ide> imageID = stringid.TruncateID(entry.ID)
<ide> }
<ide>
<del> created := units.HumanDuration(time.Now().UTC().Sub(time.Unix(entry.Created, 0))) + " ago"
<del> size := units.HumanSize(float64(entry.Size))
<del> if *human == false {
<add> if *human {
<add> created = units.HumanDuration(time.Now().UTC().Sub(time.Unix(entry.Created, 0))) + " ago"
<add> size = units.HumanSize(float64(entry.Size))
<add> } else {
<ide> created = time.Unix(entry.Created, 0).Format(time.RFC3339)
<ide> size = strconv.FormatInt(entry.Size, 10)
<ide> } | 1 |
Java | Java | add support for `overflow` on android | 6110a4cc75bf8f285ff091cc175b9ebf737f88fc | <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewProps.java
<ide> public static boolean isLayoutOnly(ReadableMap map, String prop) {
<ide> return map.isNull(BORDER_RIGHT_WIDTH) || map.getDouble(BORDER_RIGHT_WIDTH) == 0d;
<ide> case BORDER_BOTTOM_WIDTH:
<ide> return map.isNull(BORDER_BOTTOM_WIDTH) || map.getDouble(BORDER_BOTTOM_WIDTH) == 0d;
<del> case OVERFLOW: // We do nothing with this right now.
<del> return true;
<add> case OVERFLOW:
<add> return map.isNull(OVERFLOW) || map.getString(OVERFLOW) == "visible";
<ide> default:
<ide> return false;
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.java
<ide> public void onLayoutChange(
<ide>
<ide> public ReactViewGroup(Context context) {
<ide> super(context);
<add> setClipChildren(false);
<ide> mDrawingOrderHelper = new ViewGroupDrawingOrderHelper(this);
<ide> }
<ide>
<ide> public void setHitSlopRect(@Nullable Rect rect) {
<ide> }
<ide>
<ide> public void setOverflow(String overflow) {
<add> setClipChildren(mOverflow == "hidden");
<ide> mOverflow = overflow;
<ide> invalidate();
<ide> } | 2 |
Go | Go | remove unused code | 153248b60f551d4cb92bce4f35b08084f554c62c | <ide><path>deviceset.go
<del>package docker
<del>
<del>type DeviceSet interface {
<del> AddDevice(hash, baseHash string) error
<del> SetInitialized(hash string) error
<del> DeactivateDevice(hash string) error
<del> RemoveDevice(hash string) error
<del> MountDevice(hash, path string) error
<del> UnmountDevice(hash, path string, deactivate bool) error
<del> HasDevice(hash string) bool
<del> HasInitializedDevice(hash string) bool
<del> HasActivatedDevice(hash string) bool
<del> Shutdown() error
<del>}
<ide><path>devmapper/deviceset_devmapper.go
<ide> func (devices *DeviceSetDM) waitClose(hash string) error {
<ide> return nil
<ide> }
<ide>
<del>func (devices *DeviceSetDM) DeactivateDevice(hash string) error {
<del> devices.Lock()
<del> defer devices.Unlock()
<del>
<del> if err := devices.ensureInit(); err != nil {
<del> utils.Debugf("\n--->Err: %s\n", err)
<del> return err
<del> }
<del>
<del> utils.Debugf("DeactivateDevice %s", hash)
<del> return devices.deactivateDevice(hash)
<del>}
<del>
<ide> func (devices *DeviceSetDM) Shutdown() error {
<ide> devices.Lock()
<ide> utils.Debugf("[devmapper] Shutting down DeviceSet: %s", devices.root)
<ide><path>image.go
<ide> import (
<ide> "encoding/json"
<ide> "fmt"
<ide> "github.com/dotcloud/docker/utils"
<add> "github.com/dotcloud/docker/devmapper"
<ide> "io"
<ide> "io/ioutil"
<ide> "os"
<ide> func (image *Image) applyLayer(layer, target string) error {
<ide> return nil
<ide> }
<ide>
<del>func (image *Image) ensureImageDevice(devices DeviceSet) error {
<add>func (image *Image) ensureImageDevice(devices *devmapper.DeviceSetDM) error {
<ide> if devices.HasInitializedDevice(image.ID) {
<ide> return nil
<ide> }
<ide><path>runtime.go
<ide> type Runtime struct {
<ide> volumes *Graph
<ide> srv *Server
<ide> Dns []string
<del> deviceSet DeviceSet
<add> deviceSet *devmapper.DeviceSetDM
<ide> }
<ide>
<ide> var sysInitPath string
<ide> func (runtime *Runtime) getContainerElement(id string) *list.Element {
<ide> return nil
<ide> }
<ide>
<del>func (runtime *Runtime) GetDeviceSet() (DeviceSet, error) {
<add>func (runtime *Runtime) GetDeviceSet() (*devmapper.DeviceSetDM, error) {
<ide> if runtime.deviceSet == nil {
<ide> return nil, fmt.Errorf("No device set available")
<ide> }
<ide><path>utils_test.go
<ide> func TestParseLxcConfOpt(t *testing.T) {
<ide> }
<ide> }
<ide> }
<del>
<del>type DeviceSetWrapper struct {
<del> wrapped DeviceSet
<del> prefix string
<del>}
<del>
<del>func (wrapper *DeviceSetWrapper) wrap(hash string) string {
<del> if hash != "" {
<del> hash = wrapper.prefix + "-" + hash
<del> }
<del> return hash
<del>}
<del>
<del>func (wrapper *DeviceSetWrapper) AddDevice(hash, baseHash string) error {
<del> return wrapper.wrapped.AddDevice(wrapper.wrap(hash), wrapper.wrap(baseHash))
<del>}
<del>
<del>func (wrapper *DeviceSetWrapper) SetInitialized(hash string) error {
<del> return wrapper.wrapped.SetInitialized(wrapper.wrap(hash))
<del>}
<del>
<del>func (wrapper *DeviceSetWrapper) DeactivateDevice(hash string) error {
<del> return wrapper.wrapped.DeactivateDevice(wrapper.wrap(hash))
<del>}
<del>
<del>func (wrapper *DeviceSetWrapper) Shutdown() error {
<del> return nil
<del>}
<del>
<del>func (wrapper *DeviceSetWrapper) RemoveDevice(hash string) error {
<del> return wrapper.wrapped.RemoveDevice(wrapper.wrap(hash))
<del>}
<del>
<del>func (wrapper *DeviceSetWrapper) MountDevice(hash, path string) error {
<del> return wrapper.wrapped.MountDevice(wrapper.wrap(hash), path)
<del>}
<del>
<del>func (wrapper *DeviceSetWrapper) UnmountDevice(hash, path string, deactivate bool) error {
<del> return wrapper.wrapped.UnmountDevice(wrapper.wrap(hash), path, deactivate)
<del>}
<del>
<del>func (wrapper *DeviceSetWrapper) HasDevice(hash string) bool {
<del> return wrapper.wrapped.HasDevice(wrapper.wrap(hash))
<del>}
<del>
<del>func (wrapper *DeviceSetWrapper) HasInitializedDevice(hash string) bool {
<del> return wrapper.wrapped.HasInitializedDevice(wrapper.wrap(hash))
<del>}
<del>
<del>func (wrapper *DeviceSetWrapper) HasActivatedDevice(hash string) bool {
<del> return wrapper.wrapped.HasActivatedDevice(wrapper.wrap(hash))
<del>}
<del>
<del>func NewDeviceSetWrapper(wrapped DeviceSet, prefix string) DeviceSet {
<del> return &DeviceSetWrapper{
<del> wrapped: wrapped,
<del> prefix: prefix,
<del> }
<del>} | 5 |
Java | Java | add annotationconfigapplicationcontext constructor | f05d0885ef4076b6430f144ddb8e47627e5eee80 | <ide><path>spring-context/src/main/java/org/springframework/context/annotation/AnnotationConfigApplicationContext.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2013 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> package org.springframework.context.annotation;
<ide>
<ide> import org.springframework.beans.factory.support.BeanNameGenerator;
<add>import org.springframework.beans.factory.support.DefaultListableBeanFactory;
<ide> import org.springframework.context.support.GenericApplicationContext;
<ide> import org.springframework.core.env.ConfigurableEnvironment;
<ide> import org.springframework.util.Assert;
<ide> public AnnotationConfigApplicationContext() {
<ide> this.scanner = new ClassPathBeanDefinitionScanner(this);
<ide> }
<ide>
<add> /**
<add> * Create a new AnnotationConfigApplicationContext with the given DefaultListableBeanFactory.
<add> * @param beanFactory the DefaultListableBeanFactory instance to use for this context
<add> */
<add> public AnnotationConfigApplicationContext(DefaultListableBeanFactory beanFactory) {
<add> super(beanFactory);
<add> this.reader = new AnnotatedBeanDefinitionReader(this);
<add> this.scanner = new ClassPathBeanDefinitionScanner(this);
<add> }
<add>
<ide> /**
<ide> * Create a new AnnotationConfigApplicationContext, deriving bean definitions
<ide> * from the given annotated classes and automatically refreshing the context. | 1 |
Java | Java | fix checkstyle violations | 2146bc816a93caa0b12c2ec5d8896fe166253490 | <ide><path>spring-core/src/main/java/org/springframework/core/annotation/TypeMappedAnnotation.java
<ide> private Object getValueFromMetaAnnotation(int attributeIndex,
<ide> value = this.mapping.getMappedAnnotationValue(attributeIndex, forMirrorResolution);
<ide> }
<ide> if (value == null) {
<del> Method attribute = mapping.getAttributes().get(attributeIndex);
<del> value = ReflectionUtils.invokeMethod(attribute, mapping.getAnnotation());
<add> Method attribute = this.mapping.getAttributes().get(attributeIndex);
<add> value = ReflectionUtils.invokeMethod(attribute, this.mapping.getAnnotation());
<ide> }
<ide> return value;
<ide> } | 1 |
Javascript | Javascript | add @since tag to doc for the hash helper | 602b92dc92a2e36763d6c3c54c1e11e170eec8ce | <ide><path>packages/ember-glimmer/lib/helpers/hash.js
<ide> @for Ember.Templates.helpers
<ide> @param {Object} options
<ide> @return {Object} Hash
<add> @since 2.3.0
<ide> @public
<ide> */
<ide> | 1 |
Javascript | Javascript | delay the require of the vscode-ripgrep module | 0cbd329e34613c64cebc761ceead2dd84ef62b1b | <ide><path>src/ripgrep-directory-searcher.js
<ide> function updateTrailingContexts (message, pendingTrailingContexts, options) {
<ide> }
<ide>
<ide> module.exports = class RipgrepDirectorySearcher {
<del> constructor () {
<del> this.rgPath = require('vscode-ripgrep').rgPath
<del> }
<del>
<ide> canSearchDirectory () {
<ide> return true
<ide> }
<ide> module.exports = class RipgrepDirectorySearcher {
<ide> // Returns a *thenable* `DirectorySearch` that includes a `cancel()` method. If `cancel()` is
<ide> // invoked before the `DirectorySearch` is determined, it will resolve the `DirectorySearch`.
<ide> search (directories, regexp, options) {
<add> // Delay the require of vscode-ripgrep to not mess with the snapshot creation.
<add> if (!this.rgPath) {
<add> this.rgPath = require('vscode-ripgrep').rgPath
<add> }
<add>
<ide> const paths = directories.map(d => d.getPath())
<ide>
<ide> const args = ['--json', '--regexp', regexp.source] | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.