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 |
|---|---|---|---|---|---|
Mixed | Go | add godoc for client package | 070038bbc720192338850ff714459fbd5e633853 | <ide><path>client/README.md
<del>## Client
<add>## Go client for the Docker Remote API
<ide>
<del>The client package implements a fully featured http client to interact with the Docker engine. It's modeled after the requirements of the Docker engine CLI, but it can also serve other purposes.
<add>The `docker` command uses this package to communicate with the daemon. It can also be used by your own Go applications to do anything the command-line interface does – running containers, pulling images, managing swarms, etc.
<ide>
<del>### Usage
<del>
<del>You can use this client package in your applications by creating a new client object. Then use that object to execute operations against the remote server. Follow the example below to see how to list all the containers running in a Docker engine host:
<add>For example, to list running containers (the equivalent of `docker ps`):
<ide>
<ide> ```go
<ide> package main
<ide>
<ide> import (
<del> "fmt"
<ide> "context"
<add> "fmt"
<ide>
<del> "github.com/docker/docker/client"
<ide> "github.com/docker/docker/api/types"
<add> "github.com/docker/docker/client"
<ide> )
<ide>
<ide> func main() {
<del> defaultHeaders := map[string]string{"User-Agent": "engine-api-cli-1.0"}
<del> cli, err := client.NewClient("unix:///var/run/docker.sock", "v1.22", nil, defaultHeaders)
<add> cli, err := client.NewEnvClient()
<ide> if err != nil {
<ide> panic(err)
<ide> }
<ide>
<del> options := types.ContainerListOptions{All: true}
<del> containers, err := cli.ContainerList(context.Background(), options)
<add> containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{})
<ide> if err != nil {
<ide> panic(err)
<ide> }
<ide>
<del> for _, c := range containers {
<del> fmt.Println(c.ID)
<add> for _, container := range containers {
<add> fmt.Printf("%s %s\n", container.ID[:10], container.Image)
<ide> }
<ide> }
<ide> ```
<add>
<add>[Full documentation is available on GoDoc.](https://godoc.org/github.com/docker/docker/client)
<ide><path>client/client.go
<add>/*
<add>Package client is a Go client for the Docker Remote API.
<add>
<add>The "docker" command uses this package to communicate with the daemon. It can also
<add>be used by your own Go applications to do anything the command-line interface does
<add>– running containers, pulling images, managing swarms, etc.
<add>
<add>For more information about the Remote API, see the documentation:
<add>https://docs.docker.com/engine/reference/api/docker_remote_api/
<add>
<add>Usage
<add>
<add>You use the library by creating a client object and calling methods on it. The
<add>client can be created either from environment variables with NewEnvClient, or
<add>configured manually with NewClient.
<add>
<add>For example, to list running containers (the equivalent of "docker ps"):
<add>
<add> package main
<add>
<add> import (
<add> "context"
<add> "fmt"
<add>
<add> "github.com/docker/docker/api/types"
<add> "github.com/docker/docker/client"
<add> )
<add>
<add> func main() {
<add> cli, err := client.NewEnvClient()
<add> if err != nil {
<add> panic(err)
<add> }
<add>
<add> containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{})
<add> if err != nil {
<add> panic(err)
<add> }
<add>
<add> for _, container := range containers {
<add> fmt.Printf("%s %s\n", container.ID[:10], container.Image)
<add> }
<add> }
<add>
<add>*/
<ide> package client
<ide>
<ide> import ( | 2 |
Text | Text | create a new section on raspberry pi | 0b7857e0ee378bd994074131eaf9534813ac8b4c | <ide><path>guide/english/raspberry-pi/what-is-raspberry-pi/index.md
<add>---
<add>title: What Is Raspberry Pi
<add>---
<add>
<add>## The Raspberry Pi
<add>Raspberry Pi is a mini computer in its third-generation. The $35 circuit board contains a processor, RAM, GPU as well as ports for
<add>USB, HDMI, audio, ethernet and a set of GPIO pins used to build and manipulate circuits. The board also contains onboard wireless and
<add>special connections for components such as the Raspberry Pi digital camera accessory.
<add> | 1 |
Java | Java | improve etag & last-modifed support in webrequest | 953608ec49dea6dfdf1e0a2626839e84df909b69 | <ide><path>spring-web/src/main/java/org/springframework/web/context/request/FacesWebRequest.java
<ide> public boolean checkNotModified(String eTag) {
<ide> return false;
<ide> }
<ide>
<add> /**
<add> * Last-modified handling not supported for portlet requests:
<add> * As a consequence, this method always returns {@code false}.
<add> *
<add> * @since 4.2
<add> */
<add> @Override
<add> public boolean checkNotModified(String etag, long lastModifiedTimestamp) {
<add> return false;
<add> }
<add>
<ide> @Override
<ide> public String getDescription(boolean includeClientInfo) {
<ide> ExternalContext externalContext = getExternalContext();
<ide><path>spring-web/src/main/java/org/springframework/web/context/request/ServletWebRequest.java
<ide> /*
<del> * Copyright 2002-2014 the original author or authors.
<add> * Copyright 2002-2015 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 java.util.Iterator;
<ide> import java.util.Locale;
<ide> import java.util.Map;
<add>
<ide> import javax.servlet.http.HttpServletRequest;
<ide> import javax.servlet.http.HttpServletResponse;
<ide> import javax.servlet.http.HttpSession;
<ide> * {@link WebRequest} adapter for an {@link javax.servlet.http.HttpServletRequest}.
<ide> *
<ide> * @author Juergen Hoeller
<add> * @author Brian Clozel
<add> * @author Markus Malkusch
<add> *
<ide> * @since 2.0
<ide> */
<ide> public class ServletWebRequest extends ServletRequestAttributes implements NativeWebRequest {
<ide> public ServletWebRequest(HttpServletRequest request, HttpServletResponse respons
<ide> super(request, response);
<ide> }
<ide>
<del>
<ide> @Override
<ide> public Object getNativeRequest() {
<ide> return getRequest();
<ide> public <T> T getNativeResponse(Class<T> requiredType) {
<ide> return WebUtils.getNativeResponse(getResponse(), requiredType);
<ide> }
<ide>
<del>
<ide> /**
<ide> * Return the HTTP method of the request.
<ide> * @since 4.0.2
<ide> public boolean isSecure() {
<ide> }
<ide>
<ide> @Override
<del> @SuppressWarnings("deprecation")
<ide> public boolean checkNotModified(long lastModifiedTimestamp) {
<ide> HttpServletResponse response = getResponse();
<del> if (lastModifiedTimestamp >= 0 && !this.notModified &&
<del> (response == null || !response.containsHeader(HEADER_LAST_MODIFIED))) {
<del> long ifModifiedSince = -1;
<del> try {
<del> ifModifiedSince = getRequest().getDateHeader(HEADER_IF_MODIFIED_SINCE);
<del> }
<del> catch (IllegalArgumentException ex) {
<del> String headerValue = getRequest().getHeader(HEADER_IF_MODIFIED_SINCE);
<del> // Possibly an IE 10 style value: "Wed, 09 Apr 2014 09:57:42 GMT; length=13774"
<del> int separatorIndex = headerValue.indexOf(';');
<del> if (separatorIndex != -1) {
<del> String datePart = headerValue.substring(0, separatorIndex);
<del> try {
<del> ifModifiedSince = Date.parse(datePart);
<del> }
<del> catch (IllegalArgumentException ex2) {
<del> // Giving up
<add> if (lastModifiedTimestamp >= 0 && !this.notModified) {
<add> if (response == null || !response.containsHeader(HEADER_LAST_MODIFIED)) {
<add> this.notModified = isTimeStampNotModified(lastModifiedTimestamp);
<add> if (response != null) {
<add> if (this.notModified && supportsNotModifiedStatus()) {
<add> response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
<ide> }
<add> response.setDateHeader(HEADER_LAST_MODIFIED, lastModifiedTimestamp);
<ide> }
<ide> }
<del> this.notModified = (ifModifiedSince >= (lastModifiedTimestamp / 1000 * 1000));
<del> if (response != null) {
<del> if (this.notModified && supportsNotModifiedStatus()) {
<del> response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
<add> }
<add> return this.notModified;
<add> }
<add>
<add> @SuppressWarnings("deprecation")
<add> private boolean isTimeStampNotModified(long lastModifiedTimestamp) {
<add> long ifModifiedSince = -1;
<add> try {
<add> ifModifiedSince = getRequest().getDateHeader(HEADER_IF_MODIFIED_SINCE);
<add> }
<add> catch (IllegalArgumentException ex) {
<add> String headerValue = getRequest().getHeader(HEADER_IF_MODIFIED_SINCE);
<add> // Possibly an IE 10 style value: "Wed, 09 Apr 2014 09:57:42 GMT; length=13774"
<add> int separatorIndex = headerValue.indexOf(';');
<add> if (separatorIndex != -1) {
<add> String datePart = headerValue.substring(0, separatorIndex);
<add> try {
<add> ifModifiedSince = Date.parse(datePart);
<ide> }
<del> else {
<del> response.setDateHeader(HEADER_LAST_MODIFIED, lastModifiedTimestamp);
<add> catch (IllegalArgumentException ex2) {
<add> // Giving up
<ide> }
<ide> }
<ide> }
<del> return this.notModified;
<add> return (ifModifiedSince >= (lastModifiedTimestamp / 1000 * 1000));
<ide> }
<ide>
<ide> @Override
<ide> public boolean checkNotModified(String etag) {
<ide> HttpServletResponse response = getResponse();
<del> if (StringUtils.hasLength(etag) && !this.notModified &&
<del> (response == null || !response.containsHeader(HEADER_ETAG))) {
<del> String ifNoneMatch = getRequest().getHeader(HEADER_IF_NONE_MATCH);
<del> this.notModified = etag.equals(ifNoneMatch);
<del> if (response != null) {
<del> if (this.notModified && supportsNotModifiedStatus()) {
<del> response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
<del> }
<del> else {
<add> if (StringUtils.hasLength(etag) && !this.notModified) {
<add> if (response == null || !response.containsHeader(HEADER_ETAG)) {
<add> etag = addEtagPadding(etag);
<add> this.notModified = isETagNotModified(etag);
<add> if (response != null) {
<add> if (this.notModified && supportsNotModifiedStatus()) {
<add> response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
<add> }
<ide> response.setHeader(HEADER_ETAG, etag);
<ide> }
<ide> }
<ide> }
<ide> return this.notModified;
<ide> }
<ide>
<add> private String addEtagPadding(String etag) {
<add> if (!(etag.startsWith("\"") || etag.startsWith("W/\"")) || !etag.endsWith("\"")) {
<add> etag = "\"" + etag + "\"";
<add> }
<add> return etag;
<add> }
<add>
<add> private boolean isETagNotModified(String etag) {
<add> if (StringUtils.hasLength(etag)) {
<add> String ifNoneMatch = getRequest().getHeader(HEADER_IF_NONE_MATCH);
<add> if (StringUtils.hasLength(ifNoneMatch)) {
<add> String[] clientETags = StringUtils.delimitedListToStringArray(ifNoneMatch, ",", " ");
<add> for (String clientETag : clientETags) {
<add> // compare weak/strong ETags as per https://tools.ietf.org/html/rfc7232#section-2.3
<add> if (StringUtils.hasLength(clientETag) &&
<add> (clientETag.replaceFirst("^W/", "").equals(etag.replaceFirst("^W/", ""))
<add> || clientETag.equals("*"))) {
<add> return true;
<add> }
<add> }
<add> }
<add> }
<add> return false;
<add> }
<add>
<ide> private boolean supportsNotModifiedStatus() {
<ide> String method = getRequest().getMethod();
<ide> return (METHOD_GET.equals(method) || METHOD_HEAD.equals(method));
<ide> }
<ide>
<add> @Override
<add> public boolean checkNotModified(String etag, long lastModifiedTimestamp) {
<add> HttpServletResponse response = getResponse();
<add> if (StringUtils.hasLength(etag) && !this.notModified) {
<add> if (response == null ||
<add> (!response.containsHeader(HEADER_ETAG) && !response.containsHeader(HEADER_LAST_MODIFIED))) {
<add> etag = addEtagPadding(etag);
<add> this.notModified = isETagNotModified(etag) && isTimeStampNotModified(lastModifiedTimestamp);
<add> if (response != null) {
<add> if (this.notModified && supportsNotModifiedStatus()) {
<add> response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
<add> }
<add> response.setHeader(HEADER_ETAG, etag);
<add> response.setDateHeader(HEADER_LAST_MODIFIED, lastModifiedTimestamp);
<add> }
<add> }
<add> }
<add> return this.notModified;
<add> }
<add>
<ide> public boolean isNotModified() {
<ide> return this.notModified;
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/web/context/request/WebRequest.java
<ide> /*
<del> * Copyright 2002-2014 the original author or authors.
<add> * Copyright 2002-2015 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 interface WebRequest extends RequestAttributes {
<ide> * model.addAttribute(...);
<ide> * return "myViewName";
<ide> * }</pre>
<del> * <p><strong>Note:</strong> that you typically want to use either
<add> * <p><strong>Note:</strong> you can use either
<ide> * this {@code #checkNotModified(long)} method; or
<del> * {@link #checkNotModified(String)}, but not both.
<add> * {@link #checkNotModified(String)}. If you want enforce both
<add> * a strong entity tag and a Last-Modified value,
<add> * as recommended by the HTTP specification,
<add> * then you should use {@link #checkNotModified(String, long)}.
<ide> * <p>If the "If-Modified-Since" header is set but cannot be parsed
<ide> * to a date value, this method will ignore the header and proceed
<ide> * with setting the last-modified timestamp on the response.
<ide> public interface WebRequest extends RequestAttributes {
<ide> * model.addAttribute(...);
<ide> * return "myViewName";
<ide> * }</pre>
<del> * <p><strong>Note:</strong> that you typically want to use either
<add> * <p><strong>Note:</strong> you can use either
<ide> * this {@code #checkNotModified(String)} method; or
<del> * {@link #checkNotModified(long)}, but not both.
<add> * {@link #checkNotModified(long)}. If you want enforce both
<add> * a strong entity tag and a Last-Modified value,
<add> * as recommended by the HTTP specification,
<add> * then you should use {@link #checkNotModified(String, long)}.
<ide> * @param etag the entity tag that the application determined
<ide> * for the underlying resource. This parameter will be padded
<ide> * with quotes (") if necessary.
<ide> public interface WebRequest extends RequestAttributes {
<ide> */
<ide> boolean checkNotModified(String etag);
<ide>
<add> /**
<add> * Check whether the request qualifies as not modified given the
<add> * supplied {@code ETag} (entity tag) and last-modified timestamp,
<add> * as determined by the application.
<add> * <p>This will also transparently set the appropriate response headers,
<add> * for both the modified case and the not-modified case.
<add> * <p>Typical usage:
<add> * <pre class="code">
<add> * public String myHandleMethod(WebRequest webRequest, Model model) {
<add> * String eTag = // application-specific calculation
<add> * long lastModified = // application-specific calculation
<add> * if (request.checkNotModified(eTag, lastModified)) {
<add> * // shortcut exit - no further processing necessary
<add> * return null;
<add> * }
<add> * // further request processing, actually building content
<add> * model.addAttribute(...);
<add> * return "myViewName";
<add> * }</pre>
<add> * <p><strong>Note:</strong> The HTTP specification recommends
<add> * setting both ETag and Last-Modified values, but you can also
<add> * use {@code #checkNotModified(String)} or
<add> * {@link #checkNotModified(long)}.
<add> * @param etag the entity tag that the application determined
<add> * for the underlying resource. This parameter will be padded
<add> * with quotes (") if necessary.
<add> * @param lastModifiedTimestamp the last-modified timestamp that
<add> * the application determined for the underlying resource
<add> * @return whether the request qualifies as not modified,
<add> * allowing to abort request processing and relying on the response
<add> * telling the client that the content has not been modified
<add> *
<add> * @since 4.2
<add> */
<add> boolean checkNotModified(String etag, long lastModifiedTimestamp);
<add>
<ide> /**
<ide> * Get a short description of this request,
<ide> * typically containing request URI and session id.
<ide><path>spring-web/src/test/java/org/springframework/web/context/request/ServletWebRequestHttpMethodsTests.java
<add>/*
<add> * Copyright 2002-2015 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.web.context.request;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>import java.text.SimpleDateFormat;
<add>import java.util.Arrays;
<add>import java.util.Date;
<add>import java.util.Locale;
<add>
<add>import org.junit.Before;
<add>import org.junit.Test;
<add>import org.junit.runner.RunWith;
<add>import org.junit.runners.Parameterized;
<add>import org.junit.runners.Parameterized.Parameters;
<add>
<add>import org.springframework.mock.web.test.MockHttpServletRequest;
<add>import org.springframework.mock.web.test.MockHttpServletResponse;
<add>
<add>/**
<add> * Parameterized tests for ServletWebRequest
<add> * @author Juergen Hoeller
<add> * @author Brian Clozel
<add> * @author Markus Malkusch
<add> */
<add>@RunWith(Parameterized.class)
<add>public class ServletWebRequestHttpMethodsTests {
<add>
<add> private SimpleDateFormat dateFormat;
<add>
<add> private MockHttpServletRequest servletRequest;
<add>
<add> private MockHttpServletResponse servletResponse;
<add>
<add> private ServletWebRequest request;
<add>
<add> private String method;
<add>
<add> @Parameters
<add> static public Iterable<Object[]> safeMethods() {
<add> return Arrays.asList(new Object[][] {
<add> {"GET"},
<add> {"HEAD"}
<add> });
<add> }
<add>
<add> public ServletWebRequestHttpMethodsTests(String method) {
<add> this.method = method;
<add> }
<add>
<add> @Before
<add> public void setUp() {
<add> dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
<add> servletRequest = new MockHttpServletRequest(method, "http://example.org");
<add> servletResponse = new MockHttpServletResponse();
<add> request = new ServletWebRequest(servletRequest, servletResponse);
<add> }
<add>
<add> @Test
<add> public void checkNotModifiedTimestamp() {
<add> long currentTime = new Date().getTime();
<add> servletRequest.addHeader("If-Modified-Since", currentTime);
<add>
<add> assertTrue(request.checkNotModified(currentTime));
<add>
<add> assertEquals(304, servletResponse.getStatus());
<add> assertEquals("" + currentTime, servletResponse.getHeader("Last-Modified"));
<add> }
<add>
<add> @Test
<add> public void checkModifiedTimestamp() {
<add> long currentTime = new Date().getTime();
<add> long oneMinuteAgo = currentTime - (1000 * 60);
<add> servletRequest.addHeader("If-Modified-Since", oneMinuteAgo);
<add>
<add> assertFalse(request.checkNotModified(currentTime));
<add>
<add> assertEquals(200, servletResponse.getStatus());
<add> assertEquals("" + currentTime, servletResponse.getHeader("Last-Modified"));
<add> }
<add>
<add> @Test
<add> public void checkNotModifiedETag() {
<add> String eTag = "\"Foo\"";
<add> servletRequest.addHeader("If-None-Match", eTag);
<add>
<add> assertTrue(request.checkNotModified(eTag));
<add>
<add> assertEquals(304, servletResponse.getStatus());
<add> assertEquals(eTag, servletResponse.getHeader("ETag"));
<add> }
<add>
<add> @Test
<add> public void checkModifiedETag() {
<add> String currentETag = "\"Foo\"";
<add> String oldEtag = "Bar";
<add> servletRequest.addHeader("If-None-Match", oldEtag);
<add>
<add> assertFalse(request.checkNotModified(currentETag));
<add>
<add> assertEquals(200, servletResponse.getStatus());
<add> assertEquals(currentETag, servletResponse.getHeader("ETag"));
<add> }
<add>
<add> @Test
<add> public void checkNotModifiedUnpaddedETag() {
<add> String eTag = "Foo";
<add> String paddedEtag = String.format("\"%s\"", eTag);
<add> servletRequest.addHeader("If-None-Match", paddedEtag);
<add>
<add> assertTrue(request.checkNotModified(eTag));
<add>
<add> assertEquals(304, servletResponse.getStatus());
<add> assertEquals(paddedEtag, servletResponse.getHeader("ETag"));
<add> }
<add>
<add> @Test
<add> public void checkModifiedUnpaddedETag() {
<add> String currentETag = "Foo";
<add> String oldEtag = "Bar";
<add> servletRequest.addHeader("If-None-Match", oldEtag);
<add>
<add> assertFalse(request.checkNotModified(currentETag));
<add>
<add> assertEquals(200, servletResponse.getStatus());
<add> assertEquals(String.format("\"%s\"", currentETag), servletResponse.getHeader("ETag"));
<add> }
<add>
<add> @Test
<add> public void checkNotModifiedWildcardETag() {
<add> String eTag = "\"Foo\"";
<add> servletRequest.addHeader("If-None-Match", "*");
<add>
<add> assertTrue(request.checkNotModified(eTag));
<add>
<add> assertEquals(304, servletResponse.getStatus());
<add> assertEquals(eTag, servletResponse.getHeader("ETag"));
<add> }
<add>
<add> @Test
<add> public void checkNotModifiedETagAndTimestamp() {
<add> String eTag = "\"Foo\"";
<add> servletRequest.addHeader("If-None-Match", eTag);
<add> long currentTime = new Date().getTime();
<add> servletRequest.addHeader("If-Modified-Since", currentTime);
<add>
<add> assertTrue(request.checkNotModified(eTag, currentTime));
<add>
<add> assertEquals(304, servletResponse.getStatus());
<add> assertEquals(eTag, servletResponse.getHeader("ETag"));
<add> assertEquals("" + currentTime, servletResponse.getHeader("Last-Modified"));
<add> }
<add>
<add> @Test
<add> public void checkNotModifiedETagAndModifiedTimestamp() {
<add> String eTag = "\"Foo\"";
<add> servletRequest.addHeader("If-None-Match", eTag);
<add> long currentTime = new Date().getTime();
<add> long oneMinuteAgo = currentTime - (1000 * 60);
<add> servletRequest.addHeader("If-Modified-Since", oneMinuteAgo);
<add>
<add> assertFalse(request.checkNotModified(eTag, currentTime));
<add>
<add> assertEquals(200, servletResponse.getStatus());
<add> assertEquals(eTag, servletResponse.getHeader("ETag"));
<add> assertEquals("" + currentTime, servletResponse.getHeader("Last-Modified"));
<add> }
<add>
<add> @Test
<add> public void checkModifiedETagAndNotModifiedTimestamp() {
<add> String currentETag = "\"Foo\"";
<add> String oldEtag = "\"Bar\"";
<add> servletRequest.addHeader("If-None-Match", oldEtag);
<add> long currentTime = new Date().getTime();
<add> servletRequest.addHeader("If-Modified-Since", currentTime);
<add>
<add> assertFalse(request.checkNotModified(currentETag, currentTime));
<add>
<add> assertEquals(200, servletResponse.getStatus());
<add> assertEquals(currentETag, servletResponse.getHeader("ETag"));
<add> assertEquals("" + currentTime, servletResponse.getHeader("Last-Modified"));
<add> }
<add>
<add> @Test
<add> public void checkNotModifiedETagWeakStrong() {
<add> String eTag = "\"Foo\"";
<add> String weakEtag = String.format("W/%s", eTag);
<add> servletRequest.addHeader("If-None-Match", eTag);
<add>
<add> assertTrue(request.checkNotModified(weakEtag));
<add>
<add> assertEquals(304, servletResponse.getStatus());
<add> assertEquals(weakEtag, servletResponse.getHeader("ETag"));
<add> }
<add>
<add> @Test
<add> public void checkNotModifiedETagStrongWeak() {
<add> String eTag = "\"Foo\"";
<add> servletRequest.addHeader("If-None-Match", String.format("W/%s", eTag));
<add>
<add> assertTrue(request.checkNotModified(eTag));
<add>
<add> assertEquals(304, servletResponse.getStatus());
<add> assertEquals(eTag, servletResponse.getHeader("ETag"));
<add> }
<add>
<add> @Test
<add> public void checkNotModifiedMultipleETags() {
<add> String eTag = "\"Bar\"";
<add> String multipleETags = String.format("\"Foo\", %s", eTag);
<add> servletRequest.addHeader("If-None-Match", multipleETags);
<add>
<add> assertTrue(request.checkNotModified(eTag));
<add>
<add> assertEquals(304, servletResponse.getStatus());
<add> assertEquals(eTag, servletResponse.getHeader("ETag"));
<add> }
<add>
<add> @Test
<add> public void checkNotModifiedTimestampWithLengthPart() throws Exception {
<add> long currentTime = dateFormat.parse("Wed, 09 Apr 2014 09:57:42 GMT").getTime();
<add> servletRequest.setMethod("GET");
<add> servletRequest.addHeader("If-Modified-Since", "Wed, 09 Apr 2014 09:57:42 GMT; length=13774");
<add>
<add> assertTrue(request.checkNotModified(currentTime));
<add>
<add> assertEquals(304, servletResponse.getStatus());
<add> assertEquals("" + currentTime, servletResponse.getHeader("Last-Modified"));
<add> }
<add>
<add> @Test
<add> public void checkModifiedTimestampWithLengthPart() throws Exception {
<add> long currentTime = dateFormat.parse("Wed, 09 Apr 2014 09:57:42 GMT").getTime();
<add> servletRequest.setMethod("GET");
<add> servletRequest.addHeader("If-Modified-Since", "Wed, 08 Apr 2014 09:57:42 GMT; length=13774");
<add>
<add> assertFalse(request.checkNotModified(currentTime));
<add>
<add> assertEquals(200, servletResponse.getStatus());
<add> assertEquals("" + currentTime, servletResponse.getHeader("Last-Modified"));
<add> }
<add>
<add>}
<ide><path>spring-web/src/test/java/org/springframework/web/context/request/ServletWebRequestTests.java
<ide> /*
<del> * Copyright 2002-2014 the original author or authors.
<add> * Copyright 2002-2015 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>
<ide> package org.springframework.web.context.request;
<ide>
<del>import java.util.Date;
<add>import static org.junit.Assert.*;
<add>
<ide> import java.util.Locale;
<ide> import java.util.Map;
<add>
<ide> import javax.servlet.ServletRequest;
<ide> import javax.servlet.ServletResponse;
<ide> import javax.servlet.http.HttpServletRequest;
<ide> import org.springframework.mock.web.test.MockHttpServletResponse;
<ide> import org.springframework.web.multipart.MultipartRequest;
<ide>
<del>import static org.junit.Assert.*;
<del>
<ide> /**
<ide> * @author Juergen Hoeller
<del> * @author Markus Malkusch
<del> * @since 26.07.2006
<ide> */
<ide> public class ServletWebRequestTests {
<ide>
<ide> public void decoratedNativeRequest() {
<ide> assertNull(request.getNativeResponse(MultipartRequest.class));
<ide> }
<ide>
<del> @Test
<del> public void checkNotModifiedTimestampForGET() {
<del> long currentTime = new Date().getTime();
<del> servletRequest.setMethod("GET");
<del> servletRequest.addHeader("If-Modified-Since", currentTime);
<del>
<del> assertTrue(request.checkNotModified(currentTime));
<del> assertEquals(304, servletResponse.getStatus());
<del> }
<del>
<del> @Test
<del> public void checkModifiedTimestampForGET() {
<del> long currentTime = new Date().getTime();
<del> long oneMinuteAgo = currentTime - (1000 * 60);
<del> servletRequest.setMethod("GET");
<del> servletRequest.addHeader("If-Modified-Since", oneMinuteAgo);
<del>
<del> assertFalse(request.checkNotModified(currentTime));
<del> assertEquals(200, servletResponse.getStatus());
<del> assertEquals("" + currentTime, servletResponse.getHeader("Last-Modified"));
<del> }
<del>
<del> @Test
<del> public void checkNotModifiedTimestampForHEAD() {
<del> long currentTime = new Date().getTime();
<del> servletRequest.setMethod("HEAD");
<del> servletRequest.addHeader("If-Modified-Since", currentTime);
<del>
<del> assertTrue(request.checkNotModified(currentTime));
<del> assertEquals(304, servletResponse.getStatus());
<del> }
<del>
<del> @Test
<del> public void checkModifiedTimestampForHEAD() {
<del> long currentTime = new Date().getTime();
<del> long oneMinuteAgo = currentTime - (1000 * 60);
<del> servletRequest.setMethod("HEAD");
<del> servletRequest.addHeader("If-Modified-Since", oneMinuteAgo);
<del>
<del> assertFalse(request.checkNotModified(currentTime));
<del> assertEquals(200, servletResponse.getStatus());
<del> assertEquals(""+currentTime, servletResponse.getHeader("Last-Modified"));
<del> }
<del>
<del> @Test
<del> public void checkNotModifiedTimestampWithLengthPart() {
<del> long currentTime = Date.parse("Wed, 09 Apr 2014 09:57:42 GMT");
<del> servletRequest.setMethod("GET");
<del> servletRequest.addHeader("If-Modified-Since", "Wed, 09 Apr 2014 09:57:42 GMT; length=13774");
<del>
<del> assertTrue(request.checkNotModified(currentTime));
<del> assertEquals(304, servletResponse.getStatus());
<del> }
<del>
<del> @Test
<del> public void checkModifiedTimestampWithLengthPart() {
<del> long currentTime = Date.parse("Wed, 09 Apr 2014 09:57:42 GMT");
<del> servletRequest.setMethod("GET");
<del> servletRequest.addHeader("If-Modified-Since", "Wed, 08 Apr 2014 09:57:42 GMT; length=13774");
<del>
<del> assertFalse(request.checkNotModified(currentTime));
<del> assertEquals(200, servletResponse.getStatus());
<del> assertEquals("" + currentTime, servletResponse.getHeader("Last-Modified"));
<del> }
<del>
<del> @Test
<del> public void checkNotModifiedETagForGET() {
<del> String eTag = "\"Foo\"";
<del> servletRequest.setMethod("GET");
<del> servletRequest.addHeader("If-None-Match", eTag );
<del>
<del> assertTrue(request.checkNotModified(eTag));
<del> assertEquals(304, servletResponse.getStatus());
<del> }
<del>
<del> @Test
<del> public void checkModifiedETagForGET() {
<del> String currentETag = "\"Foo\"";
<del> String oldEtag = "Bar";
<del> servletRequest.setMethod("GET");
<del> servletRequest.addHeader("If-None-Match", oldEtag);
<del>
<del> assertFalse(request.checkNotModified(currentETag));
<del> assertEquals(200, servletResponse.getStatus());
<del> assertEquals(currentETag, servletResponse.getHeader("ETag"));
<del> }
<del>
<del> @Test
<del> public void checkNotModifiedETagForHEAD() {
<del> String eTag = "\"Foo\"";
<del> servletRequest.setMethod("HEAD");
<del> servletRequest.addHeader("If-None-Match", eTag );
<del>
<del> assertTrue(request.checkNotModified(eTag));
<del> assertEquals(304, servletResponse.getStatus());
<del> }
<del>
<del> @Test
<del> public void checkModifiedETagForHEAD() {
<del> String currentETag = "\"Foo\"";
<del> String oldEtag = "Bar";
<del> servletRequest.setMethod("HEAD");
<del> servletRequest.addHeader("If-None-Match", oldEtag);
<del>
<del> assertFalse(request.checkNotModified(currentETag));
<del> assertEquals(200, servletResponse.getStatus());
<del> assertEquals(currentETag, servletResponse.getHeader("ETag"));
<del> }
<del>
<del>}
<add>}
<ide>\ No newline at end of file
<ide><path>spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletWebRequest.java
<ide> public boolean checkNotModified(String eTag) {
<ide> return false;
<ide> }
<ide>
<add> /**
<add> * Last-modified handling not supported for portlet requests:
<add> * As a consequence, this method always returns {@code false}.
<add> *
<add> * @since 4.2
<add> */
<add> @Override
<add> public boolean checkNotModified(String etag, long lastModifiedTimestamp) {
<add> return false;
<add> }
<add>
<ide> @Override
<ide> public String getDescription(boolean includeClientInfo) {
<ide> PortletRequest request = getRequest(); | 6 |
Javascript | Javascript | fix files order | 2c59bf8a65d77d2a1e6803f7024af1830fbd9bee | <ide><path>lib/webpack.js
<ide> module.exports = function(context, moduleName, options, callback) {
<ide>
<ide> options.context = options.context || context;
<ide>
<del> options.emitFile = options.emitFile || function(filename, content) {
<del> options.internal.fileWrites.push([path.join(options.outputDirectory, filename), content]);
<add> options.emitFile = options.emitFile || function(filename, content, toFront) {
<add> options.internal.fileWrites[toFront?"unshift":"push"]([path.join(options.outputDirectory, filename), content]);
<ide> }
<ide>
<ide> if(options.output) {
<ide> function webpack(context, moduleName, options, callback) {
<ide> }
<ide>
<ide> // push it as "file write"
<del> options.emitFile(filename, buffer);
<add> options.emitFile(filename, buffer, true);
<ide> });
<ide> options.events.emit("task-end", "prepare chunks");
<ide> options.events.emit("start-writing", hash); | 1 |
Java | Java | fix javadoc in mockrestserviceserver | bf8a33902f170ef7bcef73dbef0db7c66eb33153 | <ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/client/MockRestServiceServer.java
<ide> * // Use the hotel instance...
<ide> *
<ide> * mockServer.verify();
<add> * </pre>
<ide> *
<ide> * <p>To create an instance of this class, use {@link #createServer(RestTemplate)}
<ide> * and provide the {@code RestTemplate} to set up for the mock testing. | 1 |
Java | Java | detect cache hit with multiple @cachables | b0b40dade132577533bfbab34dbe8e03d9c613b6 | <ide><path>spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java
<ide> private void collectPutRequests(Collection<CacheOperationContext> contexts,
<ide> for (CacheOperationContext context : contexts) {
<ide> if (isConditionPassing(context, result)) {
<ide> Object key = generateKey(context, result);
<del> if (!whenNotInCache || findInCaches(context, key) == null) {
<add> if (!whenNotInCache || findInAnyCaches(contexts, key) == null) {
<ide> putRequests.add(new CachePutRequest(context, key));
<ide> }
<ide> }
<ide> private Cache.ValueWrapper findCachedResult(Collection<CacheOperationContext> co
<ide> return result;
<ide> }
<ide>
<add> private Cache.ValueWrapper findInAnyCaches(Collection<CacheOperationContext> contexts, Object key) {
<add> for (CacheOperationContext context : contexts) {
<add> ValueWrapper wrapper = findInCaches(context, key);
<add> if (wrapper != null) {
<add> return wrapper;
<add> }
<add> }
<add> return null;
<add> }
<add>
<ide> private Cache.ValueWrapper findInCaches(CacheOperationContext context, Object key) {
<ide> for (Cache cache : context.getCaches()) {
<ide> Cache.ValueWrapper wrapper = cache.get(key);
<ide><path>spring-context/src/test/java/org/springframework/cache/CacheReproTests.java
<add>/*
<add> * Copyright 2002-2013 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;
<add>
<add>import java.util.Collections;
<add>import java.util.List;
<add>
<add>import org.junit.Test;
<add>import org.springframework.cache.annotation.Cacheable;
<add>import org.springframework.cache.annotation.Caching;
<add>import org.springframework.cache.annotation.EnableCaching;
<add>import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
<add>import org.springframework.context.annotation.AnnotationConfigApplicationContext;
<add>import org.springframework.context.annotation.Bean;
<add>import org.springframework.context.annotation.Configuration;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>/**
<add> * Tests to reproduce raised caching issues.
<add> *
<add> * @author Phillip Webb
<add> */
<add>public class CacheReproTests {
<add>
<add> @Test
<add> public void spr11124() throws Exception {
<add> AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
<add> Spr11124Config.class);
<add> Spr11124Service bean = context.getBean(Spr11124Service.class);
<add> bean.single(2);
<add> bean.single(2);
<add> bean.multiple(2);
<add> bean.multiple(2);
<add> context.close();
<add> }
<add>
<add> @Configuration
<add> @EnableCaching
<add> public static class Spr11124Config {
<add>
<add> @Bean
<add> public CacheManager cacheManager() {
<add> return new ConcurrentMapCacheManager();
<add> }
<add>
<add> @Bean
<add> public Spr11124Service service() {
<add> return new Spr11124ServiceImpl();
<add> }
<add>
<add> }
<add>
<add> public interface Spr11124Service {
<add>
<add> public List<String> single(int id);
<add>
<add> public List<String> multiple(int id);
<add>
<add> }
<add>
<add> public static class Spr11124ServiceImpl implements Spr11124Service {
<add>
<add> private int multipleCount = 0;
<add>
<add> @Override
<add> @Cacheable(value = "smallCache")
<add> public List<String> single(int id) {
<add> if (this.multipleCount > 0) {
<add> fail("Called too many times");
<add> }
<add> this.multipleCount++;
<add> return Collections.emptyList();
<add> }
<add>
<add> @Override
<add> @Caching(cacheable = {
<add> @Cacheable(value = "bigCache", unless = "#result.size() < 4"),
<add> @Cacheable(value = "smallCache", unless = "#result.size() > 3") })
<add> public List<String> multiple(int id) {
<add> if (this.multipleCount > 0) {
<add> fail("Called too many times");
<add> }
<add> this.multipleCount++;
<add> return Collections.emptyList();
<add> }
<add>
<add> }
<add>
<add>} | 2 |
Javascript | Javascript | remove use of framestopop from jstimers | 9f71551167c211d5c2604896c2fb449b44747b18 | <ide><path>Libraries/Core/Timers/JSTimers.js
<ide> const Systrace = require('../../Performance/Systrace');
<ide>
<ide> const invariant = require('invariant');
<ide>
<del>import type {ExtendedError} from '../Devtools/parseErrorStack';
<ide> import NativeTiming from './NativeTiming';
<ide>
<ide> let _performanceNow = null;
<ide> function _allocateCallback(func: Function, type: JSTimerType): number {
<ide> types[freeIndex] = type;
<ide> if (__DEV__) {
<ide> const parseErrorStack = require('../Devtools/parseErrorStack');
<del> const error: ExtendedError = new Error();
<del> error.framesToPop = 1;
<del> const stack = parseErrorStack(error);
<add> // TODO: (moti) T55685778 Use Error.captureStackTrace on Hermes
<add> const stack = parseErrorStack(new Error());
<ide> if (stack) {
<del> identifiers[freeIndex] = stack.shift();
<add> identifiers[freeIndex] = stack[1]; // skip _allocateCallback's own stack frame
<ide> }
<ide> }
<ide> return id; | 1 |
Javascript | Javascript | add spec for nativedeviceeventmanager | 580088c1994e29f25e5e6bd524808b821f57f5bf | <ide><path>Libraries/NativeModules/specs/NativeDeviceEventManager.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow strict-local
<add> * @format
<add> */
<add>
<add>'use strict';
<add>
<add>import type {TurboModule} from 'RCTExport';
<add>import * as TurboModuleRegistry from 'TurboModuleRegistry';
<add>
<add>export interface Spec extends TurboModule {
<add> +invokeDefaultBackPressHandler: () => void;
<add>}
<add>
<add>export default TurboModuleRegistry.get<Spec>('DeviceEventManager');
<ide><path>Libraries/Utilities/BackHandler.android.js
<ide>
<ide> 'use strict';
<ide>
<del>const DeviceEventManager = require('../BatchedBridge/NativeModules')
<del> .DeviceEventManager;
<del>const RCTDeviceEventEmitter = require('../EventEmitter/RCTDeviceEventEmitter');
<add>import NativeDeviceEventManager from '../../Libraries/NativeModules/specs/NativeDeviceEventManager';
<add>import RCTDeviceEventEmitter from '../EventEmitter/RCTDeviceEventEmitter';
<ide>
<ide> const DEVICE_BACK_EVENT = 'hardwareBackPress';
<ide>
<ide> type TBackHandler = {|
<ide> |};
<ide> const BackHandler: TBackHandler = {
<ide> exitApp: function(): void {
<del> DeviceEventManager.invokeDefaultBackPressHandler();
<add> if (!NativeDeviceEventManager) {
<add> return;
<add> }
<add>
<add> NativeDeviceEventManager.invokeDefaultBackPressHandler();
<ide> },
<ide>
<ide> /** | 2 |
PHP | PHP | fix failing test cases and add missing classname | 8be7de76a2410c5af6d1703b690d4e3c4b8bcb01 | <ide><path>src/Core/functions.php
<ide> function namespaceSplit($class) {
<ide> */
<ide> function pr($var) {
<ide> if (Configure::read('debug')) {
<del> $template = php_sapi_name() !== 'cli' ? '<pre>%s</pre>' : "\n%s\n\n";
<add> $template = php_sapi_name() !== 'cli' ? '<pre class="pr">%s</pre>' : "\n%s\n\n";
<ide> printf($template, trim(print_r($var, true)));
<ide> }
<ide> }
<ide> function pr($var) {
<ide> * @link http://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#pj
<ide> */
<ide> function pj($var) {
<add> if (!Configure::read('debug')) {
<add> return;
<add> }
<ide> if (php_sapi_name() === 'cli') {
<ide> printf("\n%s\n\n", trim(json_encode($var, JSON_PRETTY_PRINT)));
<ide> } elseif (Configure::read('debug')) {
<ide><path>tests/TestCase/BasicsTest.php
<ide> public function testPj() {
<ide> ob_start();
<ide> pj(['this' => 'is', 'a' => 'test', 123 => 456]);
<ide> $result = ob_get_clean();
<del> $expected = "\n{\n \"this\" => \"is\",\n \"a\" => \"test\",\n \"123\" => 456\n}\n\n";
<add> $expected = "\n{\n \"this\": \"is\",\n \"a\": \"test\",\n \"123\": 456\n}\n\n";
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<ide><path>tests/TestCase/Error/DebuggerTest.php
<ide> public function testDump() {
<ide> Debugger::dump($var);
<ide> $result = ob_get_clean();
<ide>
<del> $open = php_sapi_name() === 'cli' ? "\n" : '<pre>';
<del> $close = php_sapi_name() === 'cli' ? "\n" : '</pre>';
<add> $open = "\n";
<add> $close = "\n\n";
<ide> $expected = <<<TEXT
<ide> {$open}[
<ide> 'People' => [
<ide> public function testDump() {
<ide> Debugger::dump($var, 1);
<ide> $result = ob_get_clean();
<ide>
<del> $open = php_sapi_name() === 'cli' ? "\n" : '<pre>';
<del> $close = php_sapi_name() === 'cli' ? "\n" : '</pre>';
<ide> $expected = <<<TEXT
<ide> {$open}[
<ide> 'People' => [ | 3 |
PHP | PHP | fix bug in closure after filters | 198e9f2519a29ba8ff67ab08444f75509b80498b | <ide><path>src/Illuminate/Routing/ControllerDispatcher.php
<ide> <?php namespace Illuminate\Routing;
<ide>
<add>use Closure;
<ide> use Illuminate\Http\Request;
<ide> use Illuminate\Container\Container;
<ide>
<ide> protected function assignAfter($instance, $route, $request, $method)
<ide> // router take care of calling these filters so we do not duplicate logics.
<ide> if ($this->filterApplies($filter, $request, $method))
<ide> {
<del> $route->after($filter['original']);
<add> $route->after($this->getAssignableAfter($filter));
<ide> }
<ide> }
<ide> }
<ide>
<add> /**
<add> * Get the assignable after filter for the route.
<add> *
<add> * @param Closure|string $filter
<add> * @return string
<add> */
<add> protected function getAssignableAfter($filter)
<add> {
<add> return $filter['original'] instanceof Closure ? $filter['filter'] : $filter['original'];
<add> }
<add>
<ide> /**
<ide> * Determine if the given filter applies to the request.
<ide> * | 1 |
Python | Python | use filename (vs file name) consistently | 15ff4fdaa592ee512285054eaca2bf3a9bd3a0d4 | <ide><path>numpy/lib/npyio.py
<ide> def save(file, arr, allow_pickle=True, fix_imports=True):
<ide> file : file, str, or pathlib.Path
<ide> File or filename to which the data is saved. If file is a file-object,
<ide> then the filename is unchanged. If file is a string or Path, a ``.npy``
<del> extension will be appended to the file name if it does not already
<add> extension will be appended to the filename if it does not already
<ide> have one.
<ide> arr : array_like
<ide> Array data to be saved.
<ide> def savez(file, *args, **kwds):
<ide> Parameters
<ide> ----------
<ide> file : str or file
<del> Either the file name (string) or an open file (file-like object)
<add> Either the filename (string) or an open file (file-like object)
<ide> where the data will be saved. If file is a string or a Path, the
<del> ``.npz`` extension will be appended to the file name if it is not
<add> ``.npz`` extension will be appended to the filename if it is not
<ide> already there.
<ide> args : Arguments, optional
<ide> Arrays to save to the file. Since it is not possible for Python to
<ide> def savez(file, *args, **kwds):
<ide> its list of arrays (with the ``.files`` attribute), and for the arrays
<ide> themselves.
<ide>
<del> When saving dictionaries, the dictionary keys become file names
<add> When saving dictionaries, the dictionary keys become filenames
<ide> inside the ZIP archive. Therefore, keys should be valid filenames.
<ide> E.g., avoid keys that begin with ``/`` or contain ``.``.
<ide>
<ide> def savez_compressed(file, *args, **kwds):
<ide> Save several arrays into a single file in compressed ``.npz`` format.
<ide>
<ide> If keyword arguments are given, then filenames are taken from the keywords.
<del> If arguments are passed in with no keywords, then stored file names are
<add> If arguments are passed in with no keywords, then stored filenames are
<ide> arr_0, arr_1, etc.
<ide>
<ide> Parameters
<ide> ----------
<ide> file : str or file
<del> Either the file name (string) or an open file (file-like object)
<add> Either the filename (string) or an open file (file-like object)
<ide> where the data will be saved. If file is a string or a Path, the
<del> ``.npz`` extension will be appended to the file name if it is not
<add> ``.npz`` extension will be appended to the filename if it is not
<ide> already there.
<ide> args : Arguments, optional
<ide> Arrays to save to the file. Since it is not possible for Python to
<ide> def fromregex(file, regexp, dtype, encoding=None):
<ide> Parameters
<ide> ----------
<ide> file : str or file
<del> File name or file object to read.
<add> Filename or file object to read.
<ide> regexp : str or regexp
<ide> Regular expression used to parse the file.
<ide> Groups in the regular expression correspond to fields in the dtype. | 1 |
PHP | PHP | fix inheritance to use a class that exists | a43d4185f657d4fd4dc2b7d2a3f97cb8b0732eb3 | <ide><path>lib/Cake/Model/I18nModel.php
<ide> *
<ide> * @package Cake.Model
<ide> */
<del>class I18nModel extends AppModel {
<add>class I18nModel extends Model {
<ide>
<ide> /**
<ide> * Model name | 1 |
Mixed | Python | fix bug where pk could be set in post data | ab173fd8f9070ccdb70f86f400d2ffa780977ce4 | <ide><path>docs/api-guide/serializers.md
<ide> The `nested` option may also be set by passing it to the `serialize()` method.
<ide> class Meta:
<ide> model = Account
<ide>
<add> def get_pk_field(self, model_field):
<add> return Field(readonly=True)
<add>
<ide> def get_nested_field(self, model_field):
<ide> return ModelSerializer()
<ide>
<ide><path>rest_framework/serializers.py
<ide> def default_fields(self, serialize, obj=None, data=None, nested=False):
<ide> fields += [field for field in opts.many_to_many if field.serialize]
<ide>
<ide> ret = SortedDict()
<add> is_pk = True # First field in the list is the pk
<add>
<ide> for model_field in fields:
<del> if model_field.rel and nested:
<add> if is_pk:
<add> field = self.get_pk_field(model_field)
<add> is_pk = False
<add> elif model_field.rel and nested:
<ide> field = self.get_nested_field(model_field)
<ide> elif model_field.rel:
<ide> field = self.get_related_field(model_field)
<ide> else:
<ide> field = self.get_field(model_field)
<del> field.initialize(parent=self, model_field=model_field)
<del> ret[model_field.name] = field
<add>
<add> if field is not None:
<add> field.initialize(parent=self, model_field=model_field)
<add> ret[model_field.name] = field
<add>
<ide> return ret
<ide>
<add> def get_pk_field(self, model_field):
<add> """
<add> Returns a default instance of the pk field.
<add> """
<add> return Field(readonly=True)
<add>
<ide> def get_nested_field(self, model_field):
<ide> """
<ide> Creates a default instance of a nested relational field.
<ide> def get_related_field(self, model_field):
<ide>
<ide> def get_field(self, model_field):
<ide> """
<del> Creates a default instance of a basic field.
<add> Creates a default instance of a basic non-relational field.
<ide> """
<ide> return Field()
<ide>
<ide><path>rest_framework/tests/generics.py
<ide> def test_options_root_view(self):
<ide> self.assertEquals(response.status_code, status.HTTP_200_OK)
<ide> self.assertEquals(response.data, expected)
<ide>
<add> def test_post_cannot_set_id(self):
<add> """
<add> POST requests to create a new object should not be able to set the id.
<add> """
<add> content = {'id': 999, 'text': 'foobar'}
<add> request = factory.post('/', json.dumps(content), content_type='application/json')
<add> response = self.view(request).render()
<add> self.assertEquals(response.status_code, status.HTTP_201_CREATED)
<add> self.assertEquals(response.data, {'id': 4, 'text': u'foobar'})
<add> created = self.objects.get(id=4)
<add> self.assertEquals(created.text, 'foobar')
<add>
<ide>
<ide> class TestInstanceView(TestCase):
<ide> def setUp(self): | 3 |
Go | Go | modify /proc/sys only if needed | 5a259d55f003da5085d0e333e9ef479805e9669b | <ide><path>libnetwork/drivers/bridge/setup_ip_forwarding.go
<ide> const (
<ide> )
<ide>
<ide> func setupIPForwarding() error {
<del> // Enable IPv4 forwarding
<del> if err := ioutil.WriteFile(ipv4ForwardConf, []byte{'1', '\n'}, ipv4ForwardConfPerm); err != nil {
<del> return fmt.Errorf("Setup IP forwarding failed: %v", err)
<add> // Get current IPv4 forward setup
<add> ipv4ForwardData, err := ioutil.ReadFile(ipv4ForwardConf)
<add> if err != nil {
<add> return fmt.Errorf("Cannot read IP forwarding setup: %v", err)
<add> }
<add>
<add> // Enable IPv4 forwarding only if it is not already enabled
<add> if ipv4ForwardData[0] != '1' {
<add> // Enable IPv4 forwarding
<add> if err := ioutil.WriteFile(ipv4ForwardConf, []byte{'1', '\n'}, ipv4ForwardConfPerm); err != nil {
<add> return fmt.Errorf("Setup IP forwarding failed: %v", err)
<add> }
<ide> }
<ide>
<ide> return nil
<ide><path>libnetwork/drivers/bridge/setup_ipv4.go
<ide> func setupGatewayIPv4(config *networkConfiguration, i *bridgeInterface) error {
<ide> }
<ide>
<ide> func setupLoopbackAdressesRouting(config *networkConfiguration, i *bridgeInterface) error {
<del> // Enable loopback adresses routing
<ide> sysPath := filepath.Join("/proc/sys/net/ipv4/conf", config.BridgeName, "route_localnet")
<del> if err := ioutil.WriteFile(sysPath, []byte{'1', '\n'}, 0644); err != nil {
<del> return fmt.Errorf("Unable to enable local routing for hairpin mode: %v", err)
<add> ipv4LoRoutingData, err := ioutil.ReadFile(sysPath)
<add> if err != nil {
<add> return fmt.Errorf("Cannot read IPv4 local routing setup: %v", err)
<add> }
<add> // Enable loopback adresses routing only if it isn't already enabled
<add> if ipv4LoRoutingData[0] != '1' {
<add> if err := ioutil.WriteFile(sysPath, []byte{'1', '\n'}, 0644); err != nil {
<add> return fmt.Errorf("Unable to enable local routing for hairpin mode: %v", err)
<add> }
<ide> }
<ide> return nil
<ide> }
<ide><path>libnetwork/drivers/bridge/setup_ipv6.go
<ide> import (
<ide> var bridgeIPv6 *net.IPNet
<ide>
<ide> const (
<del> bridgeIPv6Str = "fe80::1/64"
<del> ipv6ForwardConfPerm = 0644
<add> bridgeIPv6Str = "fe80::1/64"
<add> ipv6ForwardConfPerm = 0644
<add> ipv6ForwardConfDefault = "/proc/sys/net/ipv6/conf/default/forwarding"
<add> ipv6ForwardConfAll = "/proc/sys/net/ipv6/conf/all/forwarding"
<ide> )
<ide>
<ide> func init() {
<ide> func init() {
<ide> }
<ide>
<ide> func setupBridgeIPv6(config *networkConfiguration, i *bridgeInterface) error {
<del> // Enable IPv6 on the bridge
<ide> procFile := "/proc/sys/net/ipv6/conf/" + config.BridgeName + "/disable_ipv6"
<del> if err := ioutil.WriteFile(procFile, []byte{'0', '\n'}, ipv6ForwardConfPerm); err != nil {
<del> return fmt.Errorf("Unable to enable IPv6 addresses on bridge: %v", err)
<add> ipv6BridgeData, err := ioutil.ReadFile(procFile)
<add> if err != nil {
<add> return fmt.Errorf("Cannot read IPv6 setup for bridge %v: %v", config.BridgeName, err)
<add> }
<add> // Enable IPv6 on the bridge only if it isn't already enabled
<add> if ipv6BridgeData[0] != '0' {
<add> if err := ioutil.WriteFile(procFile, []byte{'0', '\n'}, ipv6ForwardConfPerm); err != nil {
<add> return fmt.Errorf("Unable to enable IPv6 addresses on bridge: %v", err)
<add> }
<ide> }
<ide>
<ide> _, addrsv6, err := i.addresses()
<ide> func setupGatewayIPv6(config *networkConfiguration, i *bridgeInterface) error {
<ide> }
<ide>
<ide> func setupIPv6Forwarding(config *networkConfiguration, i *bridgeInterface) error {
<del> // Enable IPv6 forwarding
<del> if err := ioutil.WriteFile("/proc/sys/net/ipv6/conf/default/forwarding", []byte{'1', '\n'}, ipv6ForwardConfPerm); err != nil {
<del> logrus.Warnf("Unable to enable IPv6 default forwarding: %v", err)
<add> // Get current IPv6 default forwarding setup
<add> ipv6ForwardDataDefault, err := ioutil.ReadFile(ipv6ForwardConfDefault)
<add> if err != nil {
<add> return fmt.Errorf("Cannot read IPv6 default forwarding setup: %v", err)
<ide> }
<del> if err := ioutil.WriteFile("/proc/sys/net/ipv6/conf/all/forwarding", []byte{'1', '\n'}, ipv6ForwardConfPerm); err != nil {
<del> logrus.Warnf("Unable to enable IPv6 all forwarding: %v", err)
<add> // Enable IPv6 default forwarding only if it is not already enabled
<add> if ipv6ForwardDataDefault[0] != '1' {
<add> if err := ioutil.WriteFile(ipv6ForwardConfDefault, []byte{'1', '\n'}, ipv6ForwardConfPerm); err != nil {
<add> logrus.Warnf("Unable to enable IPv6 default forwarding: %v", err)
<add> }
<ide> }
<add>
<add> // Get current IPv6 all forwarding setup
<add> ipv6ForwardDataAll, err := ioutil.ReadFile(ipv6ForwardConfAll)
<add> if err != nil {
<add> return fmt.Errorf("Cannot read IPv6 all forwarding setup: %v", err)
<add> }
<add> // Enable IPv6 all forwarding only if it is not already enabled
<add> if ipv6ForwardDataAll[0] != '1' {
<add> if err := ioutil.WriteFile(ipv6ForwardConfAll, []byte{'1', '\n'}, ipv6ForwardConfPerm); err != nil {
<add> logrus.Warnf("Unable to enable IPv6 all forwarding: %v", err)
<add> }
<add> }
<add>
<ide> return nil
<ide> } | 3 |
Javascript | Javascript | expose output path in stats object | 3e0baf8303d9af89124c0cb7915db25e1cb7dce6 | <ide><path>lib/Stats.js
<ide> class Stats {
<ide> const sortModules = optionsOrFallback(options.modulesSort, "id");
<ide> const sortChunks = optionsOrFallback(options.chunksSort, "id");
<ide> const sortAssets = optionsOrFallback(options.assetsSort, "");
<add> const showOutputPath = optionOrLocalFallback(options.outputPath, true);
<ide>
<ide> if(!showCachedModules) {
<ide> excludeModules.push((ident, module) => !module.built);
<ide> class Stats {
<ide> hash: this.compilation.hash
<ide> });
<ide> }
<add> if(showOutputPath) {
<add> obj.outputPath = this.compilation.mainTemplate.outputOptions.path;
<add> }
<ide> if(showAssets) {
<ide> const assetsByFile = {};
<ide> const compilationAssets = Object.keys(compilation.assets);
<ide><path>test/Stats.unittest.js
<ide> "use strict";
<ide>
<ide> require("should");
<del>
<ide> const Stats = require("../lib/Stats");
<add>const packageJson = require("../package.json")
<ide>
<ide> describe("Stats", () => {
<ide> describe("Error Handling", () => {
<ide> describe("Stats", () => {
<ide> children: [],
<ide> hash: "1234",
<ide> mainTemplate: {
<add> outputOptions: {
<add> path: ""
<add> },
<ide> getPublicPath: () => "path"
<ide> },
<ide> compiler: {
<ide> describe("Stats", () => {
<ide> obj.errors[0].should.be.equal("firstError");
<ide> });
<ide> });
<add> describe("toJson", () => {
<add> it("returns plain object representation", () => {
<add> const mockStats = new Stats({
<add> errors: [],
<add> warnings: [],
<add> assets: [],
<add> entrypoints: {},
<add> chunks: [],
<add> modules: [],
<add> children: [],
<add> hash: "1234",
<add> mainTemplate: {
<add> outputOptions: {
<add> path: "/"
<add> },
<add> getPublicPath: () => "path"
<add> }
<add> });
<add> const result = mockStats.toJson();
<add> result.should.deepEqual({
<add> assets: [],
<add> assetsByChunkName: {},
<add> children: [],
<add> chunks: [],
<add> entrypoints: {},
<add> errors: [],
<add> filteredAssets: 0,
<add> filteredModules: 0,
<add> hash: "1234",
<add> modules: [],
<add> outputPath: "/",
<add> publicPath: "path",
<add> version: packageJson.version,
<add> warnings: []
<add> });
<add> });
<add> });
<ide> describe("Presets", () => {
<ide> describe("presetToOptions", () => {
<ide> it("returns correct object with 'Normal'", () => { | 2 |
PHP | PHP | fix handling of base paths | 7696f5b0fc10e247d26ecb6aa2eabca43876d6de | <ide><path>src/Routing/Router.php
<ide> public static function url($url = null, $full = false)
<ide> }
<ide>
<ide> if (empty($url)) {
<del> $output = isset($here) ? $here : $base . '/';
<add> $output = $base . (isset($here) ? $here : '/');
<ide> if ($full) {
<ide> $output = static::fullBaseUrl() . $output;
<ide> }
<ide><path>tests/TestCase/Routing/RouterTest.php
<ide> public function tearDown()
<ide> *
<ide> * @return void
<ide> */
<del> public function testbaseUrl()
<add> public function testBaseUrl()
<ide> {
<ide> $this->assertRegExp('/^http(s)?:\/\//', Router::url('/', true));
<ide> $this->assertRegExp('/^http(s)?:\/\//', Router::url(null, true));
<ide> public function testbaseUrl()
<ide> *
<ide> * @return void
<ide> */
<del> public function testfullBaseURL()
<add> public function testFullBaseURL()
<ide> {
<ide> Router::fullBaseUrl('http://example.com');
<ide> $this->assertEquals('http://example.com/', Router::url('/', true));
<ide> public function testUrlGenerationWithBasePath()
<ide> 'plugin' => null,
<ide> 'controller' => 'subscribe',
<ide> ],
<del> 'url' => '/magazine/',
<add> 'url' => '/subscribe',
<ide> 'base' => '/magazine',
<ide> 'webroot' => '/magazine/'
<ide> ]);
<ide> Router::pushRequest($request);
<ide>
<ide> $result = Router::url();
<del> $this->assertEquals('/magazine/', $result);
<add> $this->assertEquals('/magazine/subscribe', $result);
<add>
<add> $result = Router::url([]);
<add> $this->assertEquals('/magazine/subscribe', $result);
<ide>
<ide> $result = Router::url('/');
<ide> $this->assertEquals('/magazine/', $result);
<ide> public function testUrlGenerationWithPrefix()
<ide> ],
<ide> 'webroot' => '/magazine/',
<ide> 'base' => '/magazine',
<del> 'url' => '/magazine/admin/subscriptions/edit/1',
<add> 'url' => '/admin/subscriptions/edit/1',
<ide> ]);
<ide> Router::setRequestInfo($request);
<ide>
<ide><path>tests/TestCase/View/Helper/UrlHelperTest.php
<ide> public function tearDown()
<ide> *
<ide> * @return void
<ide> */
<del> public function testUrlConversion()
<add> public function testBuildUrlConversion()
<ide> {
<ide> Router::connect('/:controller/:action/*');
<ide>
<ide> public function testUrlConversion()
<ide> $this->assertEquals('/posts/index?one=value&two=value&three=purple&page=1', $result);
<ide> }
<ide>
<add> /**
<add> * ensure that build factors in base paths.
<add> *
<add> * @return void
<add> */
<add> public function testBuildBasePath()
<add> {
<add> Router::connect('/:controller/:action/*');
<add> $request = new ServerRequest([
<add> 'params' => [
<add> 'action' => 'index',
<add> 'plugin' => null,
<add> 'controller' => 'subscribe',
<add> ],
<add> 'url' => '/subscribe',
<add> 'base' => '/magazine',
<add> 'webroot' => '/magazine/'
<add> ]);
<add> Router::pushRequest($request);
<add>
<add> $this->assertEquals('/magazine/subscribe', $this->Helper->build());
<add> $this->assertEquals(
<add> '/magazine/articles/add',
<add> $this->Helper->build(['controller' => 'articles', 'action' => 'add'])
<add> );
<add> }
<add>
<ide> /**
<ide> * @return void
<ide> */
<del> public function testUrlConversionUnescaped()
<add> public function testBuildUrlConversionUnescaped()
<ide> {
<ide> $result = $this->Helper->build('/controller/action/1?one=1&two=2', ['escape' => false]);
<ide> $this->assertEquals('/controller/action/1?one=1&two=2', $result); | 3 |
Text | Text | add todos-with-undo to examples.md | 1170c2c0824ae48652311654a6c6cc844169be59 | <ide><path>README.md
<ide> For PDF, ePub, and MOBI exports for offline reading, and instructions on how to
<ide>
<ide> * [Counter](http://rackt.github.io/redux/docs/introduction/Examples.html#counter) ([source](https://github.com/rackt/redux/tree/master/examples/counter))
<ide> * [TodoMVC](http://rackt.github.io/redux/docs/introduction/Examples.html#todomvc) ([source](https://github.com/rackt/redux/tree/master/examples/todomvc))
<del>* [Todos with Undo](https://github.com/rackt/redux/tree/master/examples/todos-with-undo) ([source](https://github.com/rackt/redux/tree/master/examples/todos-with-undo))
<add>* [Todos with Undo](http://rackt.github.io/redux/docs/introduction/Examples.html#todos-with-undo) ([source](https://github.com/rackt/redux/tree/master/examples/todos-with-undo))
<ide> * [Async](http://rackt.github.io/redux/docs/introduction/Examples.html#async) ([source](https://github.com/rackt/redux/tree/master/examples/async))
<ide> * [Real World](http://rackt.github.io/redux/docs/introduction/Examples.html#real-world) ([source](https://github.com/rackt/redux/tree/master/examples/real-world))
<ide>
<ide><path>docs/introduction/Examples.md
<ide> It covers:
<ide> * Updating nested data
<ide> * Testing
<ide>
<add>## Todos with Undo
<add>
<add>Run the [todos-with-undo](https://github.com/rackt/redux/tree/master/examples/todos-with-undo) example:
<add>
<add>```
<add>git clone https://github.com/rackt/redux.git
<add>
<add>cd redux/examples/todos-with-undo
<add>npm install
<add>npm start
<add>
<add>open http://localhost:3000/
<add>```
<add>
<add>It covers:
<add>
<add>* Redux flow with two reducers
<add>* Undo/Redo functionality in Redux with [redux-undo](https://github.com/omnidan/redux-undo)
<add>
<ide> ## Async
<ide>
<ide> Run the [Async](https://github.com/rackt/redux/tree/master/examples/async) example: | 2 |
Ruby | Ruby | remove unused argument | 683e209b10e897199595696f9c86a9568fd7bc6c | <ide><path>Library/Homebrew/formula_versions.rb
<ide> def version_at_revision(rev)
<ide> formula_at_revision(rev) { |f| f.version }
<ide> end
<ide>
<del> def formula_at_revision rev, &block
<add> def formula_at_revision(rev)
<ide> FileUtils.mktemp(f.name) do
<ide> path = Pathname.pwd.join("#{f.name}.rb")
<ide> path.write file_contents_at_revision(rev) | 1 |
Javascript | Javascript | add parenthesis typo | a9e615a98ddcd88f6a174645ca73d938e0d8452a | <ide><path>test/createStore.spec.js
<ide> describe('createStore', () => {
<ide> const listener2 = expect.createSpy(() => {})
<ide> const listener3 = expect.createSpy(() => {})
<ide>
<del> unsubscribeHandles.push(store.subscribe(() => listener1())))
<add> unsubscribeHandles.push(store.subscribe(() => listener1()))
<ide> unsubscribeHandles.push(store.subscribe(() => {
<ide> listener2()
<ide> doUnsubscribeAll()
<del> })))
<del> unsubscribeHandles.push(store.subscribe(() => listener3())))
<add> }))
<add> unsubscribeHandles.push(store.subscribe(() => listener3()))
<ide>
<ide> store.dispatch(unknownAction())
<ide> store.dispatch(unknownAction()) | 1 |
Text | Text | add translating guide | da47c264f9a881f5db5f6fbb59a30c95e428571f | <ide><path>docs/README.md
<ide> Make sure to put your new file under the proper section. It's unlikely to go in
<ide> depending on the intended targets (beginners, more advanced users or researchers) it should go in section two, three or
<ide> four.
<ide>
<add>### Translating
<add>
<add>When translating, refer to the guide at [./TRANSLATING.md](https://github.com/huggingface/transformers/blob/main/docs/TRANSLATING.md).
<add>
<add>
<ide> ### Adding a new model
<ide>
<ide> When adding a new model:
<ide><path>docs/TRANSLATING.md
<add>### Translating the Transformers documentation into your language
<add>
<add>As part of our mission to democratize machine learning, we'd love to make the Transformers library available in many more languages! Follow the steps below if you want to help translate the documentation into your language 🙏.
<add>
<add>**🗞️ Open an issue**
<add>
<add>To get started, navigate to the [Issues](https://github.com/huggingface/transformers/issues) page of this repo and check if anyone else has opened an issue for your language. If not, open a new issue by selecting the "Translation template" from the "New issue" button.
<add>
<add>Once an issue exists, post a comment to indicate which chapters you'd like to work on, and we'll add your name to the list.
<add>
<add>
<add>**🍴 Fork the repository**
<add>
<add>First, you'll need to [fork the Transformers repo](https://docs.github.com/en/get-started/quickstart/fork-a-repo). You can do this by clicking on the **Fork** button on the top-right corner of this repo's page.
<add>
<add>Once you've forked the repo, you'll want to get the files on your local machine for editing. You can do that by cloning the fork with Git as follows:
<add>
<add>```bash
<add>git clone https://github.com/YOUR-USERNAME/transformers.git
<add>```
<add>
<add>**📋 Copy-paste the English version with a new language code**
<add>
<add>The documentation files are in one leading directory:
<add>
<add>- [`docs/source`](https://github.com/huggingface/transformers/tree/main/docs/source): All the documentation materials are organized here by language.
<add>
<add>You'll only need to copy the files in the [`docs/source/en`](https://github.com/huggingface/transformers/tree/main/docs/source/en) directory, so first navigate to your fork of the repo and run the following:
<add>
<add>```bash
<add>cd ~/path/to/transformers/docs
<add>cp -r source/en source/LANG-ID
<add>```
<add>
<add>Here, `LANG-ID` should be one of the ISO 639-1 or ISO 639-2 language codes -- see [here](https://www.loc.gov/standards/iso639-2/php/code_list.php) for a handy table.
<add>
<add>**✍️ Start translating**
<add>
<add>The fun part comes - translating the text!
<add>
<add>The first thing we recommend is translating the part of the `_toctree.yml` file that corresponds to your doc chapter. This file is used to render the table of contents on the website.
<add>
<add>> 🙋 If the `_toctree.yml` file doesn't yet exist for your language, you can create one by copy-pasting from the English version and deleting the sections unrelated to your chapter. Just make sure it exists in the `docs/source/LANG-ID/` directory!
<add>
<add>The fields you should add are `local` (with the name of the file containing the translation; e.g. `autoclass_tutorial`), and `title` (with the title of the doc in your language; e.g. `Load pretrained instances with an AutoClass`) -- as a reference, here is the `_toctree.yml` for [English](https://github.com/huggingface/transformers/blob/main/docs/source/en/_toctree.yml):
<add>
<add>```yaml
<add>- sections:
<add> - local: pipeline_tutorial # Do not change this! Use the same name for your .md file
<add> title: Pipelines for inference # Translate this!
<add> ...
<add> title: Tutorials # Translate this!
<add>```
<add>
<add>Once you have translated the `_toctree.yml` file, you can start translating the [MDX](https://mdxjs.com/) files associated with your docs chapter.
<add>
<add>> 🙋 If you'd like others to help you with the translation, you can either [open an issue](https://github.com/huggingface/transformers/issues) or tag @[espejelomar](https://twitter.com/espejelomar)
<add> on Twitter to gain some visibility.
<ide>\ No newline at end of file | 2 |
Text | Text | add link to live demo already hosted | 6f420962338fb99a377bde8e1e663bc202c95b68 | <ide><path>examples/image-component/README.md
<ide> This example shows how to use the [Image Component in Next.js](https://nextjs.or
<ide>
<ide> The index page ([`pages/index.js`](pages/index.js)) has a couple images, one internal image and one external image. In [`next.config.js`](next.config.js), the `domains` property is used to enable external images. The other pages demonstrate the different layouts. Run or deploy the app to see how it works!
<ide>
<add>## Live demo
<add>
<add>[https://image-component.nextjs.gallery/](https://image-component.nextjs.gallery/)
<add>
<ide> ## Preview
<ide>
<ide> Preview the example live on [StackBlitz](http://stackblitz.com/): | 1 |
PHP | PHP | defer uri language support to l4 | f68559718044ab52d798860f9c845196834ee998 | <ide><path>laravel/url.php
<ide> public static function to_asset($url, $https = null)
<ide> $url = str_replace($index.'/', '', $url);
<ide> }
<ide>
<del> if (count(Config::get('application.languages')) > 0)
<del> {
<del> $url = str_replace(Config::get('application.language').'/', '', $url);
<del> }
<del>
<ide> return $url;
<ide> }
<ide> | 1 |
Javascript | Javascript | fix formatting of pull 325. fixes | 84712bd624a9a4eeaab9ea9c543bba494f2cc3e1 | <ide><path>src/css.js
<ide> var ralpha = /alpha\([^)]*\)/i,
<ide> rnum = /^-?\d/,
<ide> rrelNum = /^[+\-]=/,
<ide> rrelNumFilter = /[^+\-\.\de]+/g,
<add> rinputbutton = /input|button/i,
<ide>
<ide> cssShow = { position: "absolute", visibility: "hidden", display: "block" },
<ide> cssWidth = [ "Left", "Right" ],
<ide> curCSS = getComputedStyle || currentStyle;
<ide>
<ide> function getWH( elem, name, extra ) {
<ide> var which = name === "width" ? cssWidth : cssHeight,
<del> cur = curCSS(elem, name),
<del> // We're addressing the way Firefox handles certain inputs and buttons, offsetWidth/height actually returns a normal width/height
<del> ff = /input|button/i.test( elem.tagName.toLowerCase() ) && curCSS( elem, '-moz-box-sizing' ) === 'border-box';
<add> cur = curCSS( elem, name ),
<add>
<add> // We're addressing the way Firefox handles certain inputs and buttons,
<add> // offsetWidth/height actually returns a normal width/height
<add> boxSizing = rinputbutton.test( elem.nodeName ) &&
<add> curCSS( elem, "-moz-box-sizing" ) === "border-box";
<ide>
<ide> // IE will return auto if we try to grab a width/height that is not set
<del> if( ff || cur === 'auto') {
<add> if ( boxSizing || cur === "auto" ) {
<ide> cur = name === "width" ? elem.offsetWidth : elem.offsetHeight;
<ide> }
<del>
<del> // Fixes an IE7 effects test. "Chain show hide" was returning "scroll" instead of "visible"
<del> if( name == "height" ){
<add>
<add> // Make sure that IE7 returns the correct computed value for display
<add> if ( name === "height" ) {
<ide> elem.offsetHeight;
<ide> }
<ide>
<del> var val = parseFloat(cur) || 0;
<add> var val = parseFloat( cur ) || 0;
<ide>
<ide> if ( extra ) {
<del> for( var i = 0, len = which.length; i < len ; i++ ) {
<add> for ( var i = 0, len = which.length; i < len ; i++ ) {
<ide> var dir = which[i];
<add>
<ide> // outerWidth/height
<del> if ( extra === "border" || extra === 'margin' ) {
<add> if ( extra === "border" || extra === "margin" ) {
<ide> val += parseFloat(jQuery.css( elem, "border" + dir + "Width" )) || 0;
<ide> val += parseFloat(jQuery.css( elem, "padding" + dir )) || 0;
<del> if( extra == 'margin' ) {
<add>
<add> if ( extra == "margin" ) {
<ide> val += parseFloat(jQuery.css( elem, "margin" + dir )) || 0;
<ide> }
<del> }
<add>
<ide> // innerWidth/height
<del> else {
<add> } else {
<ide> val += parseFloat(jQuery.css( elem, "padding" + dir )) || 0;
<ide> }
<ide> }
<ide> }
<add>
<ide> return val;
<ide> }
<ide> | 1 |
Python | Python | set version to v2.1.0.dev1 | c6be9964ec540758d9dcaea3ad4866060f45c464 | <ide><path>spacy/about.py
<ide> # fmt: off
<ide>
<ide> __title__ = "spacy"
<del>__version__ = "2.1.0.dev0"
<add>__version__ = "2.1.0.dev1"
<ide> __summary__ = "Industrial-strength Natural Language Processing (NLP) with Python and Cython"
<ide> __uri__ = "https://spacy.io"
<ide> __author__ = "Explosion AI" | 1 |
Python | Python | update version in about.py | 4a1a2bce684e23d7171c731f44e8c7f4ecc0b561 | <ide><path>spacy/about.py
<ide> # https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py
<ide>
<ide> __title__ = 'spacy'
<del>__version__ = '0.101.0'
<add>__version__ = '1.0.0'
<ide> __summary__ = 'Industrial-strength NLP'
<ide> __uri__ = 'https://spacy.io'
<ide> __author__ = 'Matthew Honnibal' | 1 |
Ruby | Ruby | implement equality for dependencies collections | 0b2c6e87f191b2ef5ad404c8d16f507becbd53cf | <ide><path>Library/Homebrew/dependencies.rb
<ide> def required
<ide> def default
<ide> build + required + recommended
<ide> end
<add>
<add> attr_reader :deps
<add> protected :deps
<add>
<add> def ==(other)
<add> deps == other.deps
<add> end
<add> alias_method :eql?, :==
<ide> end
<ide><path>Library/Homebrew/test/test_dependencies.rb
<ide> def test_type_helpers
<ide> assert_equal [qux], @deps.recommended
<ide> assert_equal [foo, baz, quux, qux].sort_by(&:name), @deps.default.sort_by(&:name)
<ide> end
<add>
<add> def test_equality
<add> a = Dependencies.new
<add> b = Dependencies.new
<add>
<add> dep = Dependency.new("foo")
<add>
<add> a << dep
<add> b << dep
<add>
<add> assert_equal a, b
<add> assert a.eql?(b)
<add>
<add> b << Dependency.new("bar", [:optional])
<add>
<add> assert_not_equal a, b
<add> assert !a.eql?(b)
<add> end
<ide> end | 2 |
Javascript | Javascript | remove shebang from upload-artifacts.js | cdc8a23bc39c45e84a16ff122e45b5172f58e5fd | <ide><path>script/vsts/upload-artifacts.js
<del>#!/usr/bin/env node
<del>
<ide> 'use strict'
<ide>
<ide> const path = require('path') | 1 |
Mixed | Ruby | deprecate rescuable option | 10bac29b330ddda69102d43b77a1e7dba8741c45 | <ide><path>actionpack/lib/action_dispatch/middleware/callbacks.rb
<ide> module ActionDispatch
<ide> class Callbacks
<ide> include ActiveSupport::Callbacks
<ide>
<del> define_callbacks :call, :rescuable => true
<add> define_callbacks :call
<ide>
<ide> class << self
<ide> delegate :to_prepare, :to_cleanup, :to => "ActionDispatch::Reloader"
<ide> def initialize(app)
<ide> end
<ide>
<ide> def call(env)
<del> run_callbacks :call do
<del> @app.call(env)
<add> error = nil
<add> result = run_callbacks :call do
<add> begin
<add> @app.call(env)
<add> rescue => error
<add> end
<ide> end
<add> raise error if error
<add> result
<ide> end
<ide> end
<ide> end
<ide><path>activesupport/CHANGELOG.md
<ide> ## Rails 4.0.0 (unreleased) ##
<ide>
<add>* AS::Callbacks: deprecate `:rescuable` option. *Bogdan Gusiev*
<add>
<ide> * Adds Integer#ordinal to get the ordinal suffix string of an integer. *Tim Gildea*
<ide>
<ide> * AS::Callbacks: `:per_key` option is no longer supported
<ide><path>activesupport/lib/active_support/callbacks.rb
<ide> def initialize(name, config)
<ide> @name = name
<ide> @config = {
<ide> :terminator => "false",
<del> :rescuable => false,
<ide> :scope => [ :kind ]
<ide> }.merge(config)
<ide> end
<ide> def compile
<ide> method << "value = nil"
<ide> method << "halted = false"
<ide>
<del> callbacks = yielding
<add> callbacks = "value = yield if block_given? && !halted"
<ide> reverse_each do |callback|
<ide> callbacks = callback.apply(callbacks)
<ide> end
<ide> method << callbacks
<ide>
<del> method << "raise rescued_error if rescued_error" if config[:rescuable]
<ide> method << "halted ? false : (block_given? ? value : true)"
<ide> method.flatten.compact.join("\n")
<ide> end
<ide>
<del> # Returns part of method that evaluates the callback block
<del> def yielding
<del> method = []
<del> if config[:rescuable]
<del> method << "rescued_error = nil"
<del> method << "begin"
<del> end
<del>
<del> method << "value = yield if block_given? && !halted"
<del>
<del> if config[:rescuable]
<del> method << "rescue Exception => e"
<del> method << "rescued_error = e"
<del> method << "end"
<del> end
<del> method.join("\n")
<del> end
<del>
<ide> end
<ide>
<ide> module ClassMethods
<ide> def reset_callbacks(symbol)
<ide> # if callback chain was terminated or not.
<ide> # Option makes sence only when <tt>:terminator</tt> option is specified.
<ide> #
<del> # * <tt>:rescuable</tt> - By default, after filters are not executed if
<del> # the given block or a before filter raises an error. By setting this option
<del> # to <tt>true</tt> exception raised by given block is stored and after
<del> # executing all the after callbacks the stored exception is raised.
<del> #
<ide> # * <tt>:scope</tt> - Indicates which methods should be executed when an object
<ide> # is used as a callback.
<ide> #
<ide><path>activesupport/test/callbacks_test.rb
<ide> module CallbacksTest
<ide> class Phone
<ide> include ActiveSupport::Callbacks
<del> define_callbacks :save, :rescuable => true
<add> define_callbacks :save
<ide>
<ide> set_callback :save, :before, :before_save1
<ide> set_callback :save, :after, :after_save1
<ide> def test_skip_person
<ide> end
<ide>
<ide> class CallbacksTest < ActiveSupport::TestCase
<del> def test_save_phone
<del> phone = Phone.new
<del> assert_raise RuntimeError do
<del> phone.save
<del> end
<del> assert_equal [:before, :after], phone.history
<del> end
<ide>
<ide> def test_save_person
<ide> person = Person.new | 4 |
PHP | PHP | add support for fixed length strings | 55251e5ebbcc3e2f6a9159ab2644b56ecd2598f0 | <ide><path>lib/Cake/Database/Schema/MysqlSchema.php
<ide> public function describeTableSql($table) {
<ide> * The returned type will be a type that Cake\Database\Type can handle.
<ide> *
<ide> * @param string $column The column type + length
<del> * @return array List of (type, length)
<add> * @return array Array of column information.
<ide> */
<ide> public function convertColumn($column) {
<ide> preg_match('/([a-z]+)(?:\(([0-9,]+)\))?/i', $column, $matches);
<ide> public function convertColumn($column) {
<ide> if (strpos($col, 'int') !== false) {
<ide> return ['type' => 'integer', 'length' => $length];
<ide> }
<add> if ($col === 'char') {
<add> return ['type' => 'string', 'fixed' => true, 'length' => $length];
<add> }
<ide> if (strpos($col, 'char') !== false || $col === 'tinytext') {
<ide> return ['type' => 'string', 'length' => $length];
<ide> }
<ide><path>lib/Cake/Database/Schema/PostgresSchema.php
<ide> public function describeTableSql($table, $config) {
<ide> * Cake\Database\Type can handle.
<ide> *
<ide> * @param string $column The column type + length
<add> * @throws Cake\Error\Exception when column cannot be parsed.
<ide> * @return array Array of column information.
<ide> */
<ide> public function convertColumn($column) {
<del> $col = strtolower($column);
<add> preg_match('/([a-z\s]+)(?:\(([0-9,]+)\))?/i', $column, $matches);
<add> if (empty($matches)) {
<add> throw new Error\Exception(__d('cake_dev', 'Unable to parse column type from "%s"', $column));
<add> }
<add>
<add> $col = strtolower($matches[1]);
<add> $length = null;
<add> if (isset($matches[2])) {
<add> $length = (int)$matches[2];
<add> }
<add>
<ide> if (in_array($col, array('date', 'time', 'boolean'))) {
<ide> return ['type' =>$col, 'length' => null];
<ide> }
<ide> public function convertColumn($column) {
<ide> if ($col === 'uuid') {
<ide> return ['type' => 'string', 'length' => 36];
<ide> }
<add> if ($col === 'char' || $col === 'character') {
<add> return ['type' => 'string', 'fixed' => true, 'length' => $length];
<add> }
<ide> if (strpos($col, 'char') !== false) {
<del> return ['type' => 'string', 'length' => null];
<add> return ['type' => 'string', 'length' => $length];
<ide> }
<ide> if (strpos($col, 'text') !== false) {
<ide> return ['type' => 'text', 'length' => null];
<ide><path>lib/Cake/Database/Schema/SqliteSchema.php
<ide> public function convertColumn($column) {
<ide> if (strpos($col, 'int') !== false) {
<ide> return ['type' => 'integer', 'length' => $length];
<ide> }
<add> if ($col === 'char') {
<add> return ['type' => 'string', 'fixed' => true, 'length' => $length];
<add> }
<ide> if (strpos($col, 'char') !== false) {
<ide> return ['type' => 'string', 'length' => $length];
<ide> }
<ide><path>lib/Cake/Test/TestCase/Database/Schema/MysqlSchemaTest.php
<ide> public static function columnProvider() {
<ide> ],
<ide> [
<ide> 'CHAR(25)',
<del> ['type' => 'string', 'length' => 25]
<add> ['type' => 'string', 'length' => 25, 'fixed' => true]
<ide> ],
<ide> [
<ide> 'TINYTEXT',
<ide><path>lib/Cake/Test/TestCase/Database/Schema/PostgresSchemaTest.php
<ide> public static function columnProvider() {
<ide> 'VARCHAR',
<ide> ['type' => 'string', 'length' => null]
<ide> ],
<add> [
<add> 'VARCHAR(10)',
<add> ['type' => 'string', 'length' => 10]
<add> ],
<ide> [
<ide> 'CHARACTER VARYING',
<ide> ['type' => 'string', 'length' => null]
<ide> ],
<ide> [
<del> 'CHAR',
<del> ['type' => 'string', 'length' => null]
<add> 'CHARACTER VARYING(10)',
<add> ['type' => 'string', 'length' => 10]
<ide> ],
<ide> [
<del> 'UUID',
<del> ['type' => 'string', 'length' => 36]
<add> 'CHAR(10)',
<add> ['type' => 'string', 'fixed' => true, 'length' => 10]
<ide> ],
<ide> [
<del> 'CHARACTER',
<del> ['type' => 'string', 'length' => null]
<add> 'CHARACTER(10)',
<add> ['type' => 'string', 'fixed' => true, 'length' => 10]
<add> ],
<add> [
<add> 'UUID',
<add> ['type' => 'string', 'length' => 36]
<ide> ],
<ide> [
<ide> 'INET',
<ide><path>lib/Cake/Test/TestCase/Database/Schema/SqliteSchemaTest.php
<ide> public static function columnProvider() {
<ide> ],
<ide> [
<ide> 'CHAR(25)',
<del> ['type' => 'string', 'length' => 25]
<add> ['type' => 'string', 'fixed' => true, 'length' => 25]
<ide> ],
<ide> [
<ide> 'BLOB', | 6 |
Text | Text | add german distilbert model | e7cf2ccd1567615513013d5fc9f9002733f70e13 | <ide><path>examples/distillation/README.md
<ide>
<ide> This folder contains the original code used to train Distil* as well as examples showcasing how to use DistilBERT, DistilRoBERTa and DistilGPT2.
<ide>
<add>**November 19th, 2019 - Update** We release German **DistilBERT**: 98.8% of `bert-base-german-dbmdz-cased` on NER tasks.
<add>
<ide> **October 23rd, 2019 - Update** We release **DistilRoBERTa**: 95% of `RoBERTa-base`'s performance on GLUE, twice as fast as RoBERTa while being 35% smaller.
<ide>
<ide> **October 3rd, 2019 - Update** We release our [NeurIPS workshop paper](https://arxiv.org/abs/1910.01108) explaining our approach on **DistilBERT**. It includes updated results and further experiments. We applied the same method to GPT2 and release the weights of **DistilGPT2**. DistilGPT2 is two times faster and 33% smaller than GPT2. **The paper superseeds our [previous blogpost](https://medium.com/huggingface/distilbert-8cf3380435b5) with a different distillation loss and better performances. Please use the paper as a reference when comparing/reporting results on DistilBERT.**
<ide> This part of the library has only be tested with Python3.6+. There are few speci
<ide>
<ide> ## How to use DistilBERT
<ide>
<del>Transformers includes two pre-trained Distil* models, currently only provided for English (we are investigating the possibility to train and release a multilingual version of DistilBERT):
<add>Transformers includes five pre-trained Distil* models, currently only provided for English and German (we are investigating the possibility to train and release a multilingual version of DistilBERT):
<ide>
<ide> - `distilbert-base-uncased`: DistilBERT English language model pretrained on the same data used to pretrain Bert (concatenation of the Toronto Book Corpus and full English Wikipedia) using distillation with the supervision of the `bert-base-uncased` version of Bert. The model has 6 layers, 768 dimension and 12 heads, totalizing 66M parameters.
<ide> - `distilbert-base-uncased-distilled-squad`: A finetuned version of `distilbert-base-uncased` finetuned using (a second step of) knwoledge distillation on SQuAD 1.0. This model reaches a F1 score of 86.9 on the dev set (for comparison, Bert `bert-base-uncased` version reaches a 88.5 F1 score).
<add>- `distilbert-base-german-cased`: DistilBERT German language model pretrained on 1/2 of the data used to pretrain Bert using distillation with the supervision of the `bert-base-german-dbmdz-cased` version of German DBMDZ Bert. For NER tasks the model reaches a F1 score of 83.49 on the CoNLL-2003 test set (for comparison, `bert-base-german-dbmdz-cased` reaches a 84.52 F1 score), and a F1 score of 85.23 on the GermEval 2014 test set (`bert-base-german-dbmdz-cased` reaches a 86.89 F1 score).
<ide> - `distilgpt2`: DistilGPT2 English language model pretrained with the supervision of `gpt2` (the smallest version of GPT2) on [OpenWebTextCorpus](https://skylion007.github.io/OpenWebTextCorpus/), a reproduction of OpenAI's WebText dataset. The model has 6 layers, 768 dimension and 12 heads, totalizing 82M parameters (compared to 124M parameters for GPT2). On average, DistilGPT2 is two times faster than GPT2.
<ide> - `distilroberta-base`: DistilRoBERTa English language model pretrained with the supervision of `roberta-base` solely on [OpenWebTextCorpus](https://skylion007.github.io/OpenWebTextCorpus/), a reproduction of OpenAI's WebText dataset (it is ~4 times less training data than the teacher RoBERTa). The model has 6 layers, 768 dimension and 12 heads, totalizing 82M parameters (compared to 125M parameters for RoBERTa-base). On average DistilRoBERTa is twice as fast as Roberta-base.
<ide> - and more to come! 🤗🤗🤗 | 1 |
Ruby | Ruby | add the ability to have plugins load rake tasks | c02f2782631a1893e2e880e3ccc65fb9a734567a | <ide><path>railties/lib/rails/application.rb
<ide> def reload_routes!
<ide>
<ide> def load_tasks
<ide> require "rails/tasks"
<add> # Load all extension rake tasks
<add> plugins.each(&:load_tasks)
<add> # Load all plugin tasks
<ide> Dir["#{root}/vendor/plugins/*/**/tasks/**/*.rake"].sort.each { |ext| load ext }
<add> # Load all application tasks
<add> # TODO: extract out the path to the rake tasks
<ide> Dir["#{root}/lib/tasks/**/*.rake"].sort.each { |ext| load ext }
<ide> task :environment do
<ide> $rails_rake_task = true
<ide><path>railties/lib/rails/plugin.rb
<ide> def self.config
<ide> Configuration.default
<ide> end
<ide>
<add> def self.rake_tasks(&blk)
<add> @rake_tasks ||= []
<add> @rake_tasks << blk
<add> end
<add>
<add> def self.load_tasks
<add> return unless @rake_tasks
<add> @rake_tasks.each { |blk| blk.call }
<add> end
<add>
<ide> # Creates an initializer which includes all given modules to the given class.
<ide> #
<ide> # module Rails
<ide><path>railties/test/plugins/framework_extension_test.rb
<ide>
<ide> module PluginsTest
<ide> class FrameworkExtensionTest < Test::Unit::TestCase
<add> def setup
<add> build_app
<add> boot_rails
<add> require "rails"
<add> end
<add>
<add> test "rake_tasks block is executed when MyApp.load_tasks is called" do
<add> $ran_block = false
<add>
<add> class MyPlugin < Rails::Plugin
<add> rake_tasks do
<add> $ran_block = true
<add> end
<add> end
<add>
<add> require "#{app_path}/config/environment"
<add>
<add> assert !$ran_block
<add> require 'rake'
<add> require 'rake/testtask'
<add> require 'rake/rdoctask'
<add> AppTemplate::Application.load_tasks
<add> assert $ran_block
<add> end
<add> end
<add>
<add> class ActiveRecordExtensionTest < Test::Unit::TestCase
<ide> def setup
<ide> build_app
<ide> boot_rails | 3 |
Python | Python | update callback system | 49603c1594daf6267f8135937c11a23fe03112f6 | <ide><path>keras/callbacks.py
<ide> def on_epoch_begin(self, epoch):
<ide> self._delta_ts_batch_begin = deque([], maxlen=self.queue_length)
<ide> self._delta_ts_batch_end = deque([], maxlen=self.queue_length)
<ide>
<del> def on_epoch_end(self, epoch, val_loss, val_acc):
<add> def on_epoch_end(self, epoch):
<ide> for callback in self.callbacks:
<del> callback.on_epoch_end(epoch, val_loss, val_acc)
<add> callback.on_epoch_end(epoch)
<ide>
<ide> def on_batch_begin(self, batch):
<ide> t_before_callbacks = time.time()
<ide> def on_batch_begin(self, batch):
<ide> 'to the batch update (%f). Check your callbacks.' % delta_t_median)
<ide> self._t_enter_batch = time.time()
<ide>
<del> def on_batch_end(self, batch, indices, loss, accuracy):
<add> def on_batch_end(self, batch):
<ide> self._delta_t_batch = time.time() - self._t_enter_batch
<ide> t_before_callbacks = time.time()
<ide> for callback in self.callbacks:
<del> callback.on_batch_end(batch, indices, loss, accuracy)
<add> callback.on_batch_end(batch)
<ide> self._delta_ts_batch_end.append(time.time() - t_before_callbacks)
<ide> delta_t_median = np.median(self._delta_ts_batch_end)
<ide> if self._delta_t_batch > 0. and delta_t_median > 0.95 * self._delta_t_batch \
<ide> def _set_model(self, model):
<ide> def on_epoch_begin(self, epoch):
<ide> pass
<ide>
<del> def on_epoch_end(self, epoch, val_loss, val_acc):
<add> def on_epoch_end(self, epoch):
<ide> pass
<ide>
<ide> def on_batch_begin(self, batch):
<ide> pass
<ide>
<del> def on_batch_end(self, batch, indices, loss, accuracy):
<add> def on_batch_end(self, batch):
<ide> pass
<ide>
<ide> def on_train_begin(self):
<ide> def on_train_begin(self):
<ide>
<ide> def on_epoch_begin(self, epoch):
<ide> self.seen = 0
<del> self.cum_loss = 0.
<del> self.cum_accuracy = 0.
<add> self.tot_loss = 0.
<add> self.tot_accuracy = 0.
<ide>
<del> def on_batch_end(self, batch, indices, loss, accuracy):
<del> batch_length = len(indices)
<del> self.seen += batch_length
<del> self.cum_loss += loss * batch_length
<add> def on_batch_end(self, batch):
<add> batch_size = self.model.batch_history['batch_size'][-1]
<add> self.seen += batch_size
<add> self.tot_loss += self.model.batch_history['loss'][-1] * batch_size
<ide> if self.params['show_accuracy']:
<del> self.cum_accuracy += accuracy * batch_length
<add> self.tot_accuracy += self.model.batch_history['accuracy'][-1] * batch_size
<ide>
<del> def on_epoch_end(self, epoch, val_loss, val_acc):
<add> def on_epoch_end(self, epoch):
<add> val_loss = self.model.epoch_history['loss'][-1]
<add> val_acc = self.model.epoch_history['accuracy'][-1]
<ide> self.epochs.append(epoch)
<del> self.losses.append(self.cum_loss / self.seen)
<add> self.losses.append(self.tot_loss / self.seen)
<ide> if self.params['show_accuracy']:
<del> self.accuracies.append(self.cum_accuracy / self.seen)
<add> self.accuracies.append(self.tot_accuracy / self.seen)
<ide> if self.params['do_validation']:
<ide> self.validation_losses.append(val_loss)
<ide> if self.params['show_accuracy']:
<ide> self.validation_accuracies.append(val_acc)
<ide>
<del>class Logger(Callback):
<add>class BaseLogger(Callback):
<ide>
<ide> def on_train_begin(self):
<ide> self.verbose = self.params['verbose']
<ide> def on_epoch_begin(self, epoch):
<ide> def on_batch_begin(self, batch):
<ide> self.log_values = []
<ide>
<del> def on_batch_end(self, batch, indices, loss, accuracy):
<add> def on_batch_end(self, batch_index):
<add> self.current += self.model.batch_history['batch_size'][-1]
<add> # skip progbar update for the last batch; will be handled by on_epoch_end
<add> if self.current < self.params['nb_sample']:
<add> loss = self.model.batch_history['loss'][-1]
<add> self.log_values.append(('loss', loss))
<add> if self.params['show_accuracy']:
<add> accuracy = self.model.batch_history['accuracy'][-1]
<add> self.log_values.append(('acc.', accuracy))
<add> if self.verbose:
<add> self.progbar.update(self.current, self.log_values)
<add>
<add> def on_epoch_end(self, epoch):
<add> loss = self.model.batch_history['loss'][-1]
<ide> self.log_values.append(('loss', loss))
<del> self.current += len(indices)
<del> if self.params['show_accuracy']:
<del> self.log_values.append(('acc.', acc))
<del> if self.verbose:
<del> self.progbar.update(self.current, self.log_values)
<ide>
<del> def on_epoch_end(self, epoch, val_loss, val_acc):
<del> # TODO: Show validation scores in the logger
<add> if self.params['show_accuracy']:
<add> accuracy = self.model.batch_history['accuracy'][-1]
<add> self.log_values.append(('acc.', accuracy))
<ide> if self.params['do_validation']:
<add> val_loss = self.model.epoch_history['val_loss'][-1]
<ide> self.log_values.append(('val. loss', val_loss))
<ide> if self.params['show_accuracy']:
<add> val_acc = self.model.epoch_history['val_accuracy'][-1]
<ide> self.log_values.append(('val. acc.', val_acc))
<add> self.progbar.update(self.current, self.log_values)
<ide><path>keras/models.py
<ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1, callbacks=[],
<ide> index_array = np.arange(len(y))
<ide>
<ide> callbacks = cbks.CallbackList(callbacks)
<del> callbacks.append(cbks.Logger())
<add> if verbose:
<add> callbacks.append(cbks.BaseLogger())
<ide>
<ide> callbacks._set_model(self)
<ide> callbacks._set_params({
<ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1, callbacks=[],
<ide> 'do_validation': do_validation,
<ide> 'show_accuracy': show_accuracy
<ide> })
<del>
<add> self.batch_history = {
<add> 'batch':[],
<add> 'batch_size':[],
<add> 'loss':[],
<add> 'accuracy':[],
<add> 'val_loss':[],
<add> 'val_accuracy':[],
<add> }
<add> self.epoch_history = {
<add> 'epoch':[],
<add> 'epoch_size':[],
<add> 'loss':[],
<add> 'accuracy':[],
<add> 'val_loss':[],
<add> 'val_accuracy':[],
<add> }
<ide> callbacks.on_train_begin()
<ide>
<ide> for epoch in range(nb_epoch):
<add> self.epoch_history['epoch'] = epoch
<ide> callbacks.on_epoch_begin(epoch)
<ide> if shuffle:
<ide> np.random.shuffle(index_array)
<ide>
<ide> batches = make_batches(len(y), batch_size)
<ide> for batch_index, (batch_start, batch_end) in enumerate(batches):
<add> batch_ids = index_array[batch_start:batch_end]
<add> X_batch = slice_X(X, batch_ids)
<add> y_batch = y[batch_ids]
<add>
<add> self.batch_history['batch'].append(batch_index)
<add> self.batch_history['batch_size'].append(len(batch_ids))
<ide> callbacks.on_batch_begin(batch_index)
<ide>
<del> try:
<del> batch_ids = index_array[batch_start:batch_end]
<del> X_batch = slice_X(X, batch_ids)
<del> y_batch = y[batch_ids]
<del>
<del> ins = X_batch + [y_batch]
<del> if show_accuracy:
<del> loss, acc = self._train_with_acc(*ins)
<del> else:
<del> loss = self._train(*ins)
<del> acc = None
<del> except KeyboardInterrupt:
<del> # If training is aborted, call the callbacks anyway before terminating
<del> callbacks.on_batch_end(batch_index, [], 0., 0.)
<del> callbacks.on_epoch_end(epoch, 0., 0.)
<del> callbacks.on_train_end()
<del> raise KeyboardInterrupt # TODO: Raise a more explicit Exception (?)
<del>
<del> callbacks.on_batch_end(batch_index, batch_ids, loss, acc)
<del>
<del> # validation
<del> val_loss, val_acc = None, None
<del> if do_validation:
<add> ins = X_batch + [y_batch]
<ide> if show_accuracy:
<del> val_loss, val_acc = self.evaluate(X_val, y_val, batch_size=batch_size, \
<del> verbose=0, show_accuracy=True)
<add> loss, acc = self._train_with_acc(*ins)
<add> self.batch_history['accuracy'].append(acc)
<ide> else:
<del> val_loss = self.evaluate(X_val, y_val, batch_size=batch_size, verbose=0)
<del>
<del> callbacks.on_epoch_end(epoch, val_loss, val_acc)
<add> loss = self._train(*ins)
<add> self.batch_history['loss'].append(loss)
<add>
<add> callbacks.on_batch_end(batch_index)
<add>
<add> if batch_index == len(batches) - 1: # last batch
<add> # validation
<add> if do_validation:
<add> if show_accuracy:
<add> val_loss, val_acc = self.evaluate(X_val, y_val, batch_size=batch_size, \
<add> verbose=0, show_accuracy=True)
<add> self.epoch_history['val_accuracy'].append(val_acc)
<add> else:
<add> val_loss = self.evaluate(X_val, y_val, batch_size=batch_size, verbose=0)
<add> self.epoch_history['val_loss'].append(val_loss)
<add>
<add> epoch_loss = sum(map(lambda x: x[0]*x[1], zip(self.batch_history['batch_size'], self.batch_history['loss']))) / len(y)
<add> self.epoch_history['loss'].append(epoch_loss)
<add> if show_accuracy:
<add> epoch_acc = sum(map(lambda x: x[0]*x[1], zip(self.batch_history['batch_size'], self.batch_history['accuracy']))) / len(y)
<add> self.epoch_history['accuracy'].append(epoch_acc)
<add> callbacks.on_epoch_end(epoch)
<ide>
<ide> callbacks.on_train_end()
<del>
<del> # return history
<del> return True
<add> return self.epoch_history
<ide>
<ide> def predict(self, X, batch_size=128, verbose=1):
<ide> X = standardize_X(X)
<ide><path>keras/utils/generic_utils.py
<ide> def update(self, current, values=[]):
<ide> '''
<ide> for k, v in values:
<ide> if k not in self.sum_values:
<del> self.sum_values[k] = [v * (current-self.seen_so_far), current-self.seen_so_far]
<add> self.sum_values[k] = [v * max(1, current-self.seen_so_far), current-self.seen_so_far]
<ide> self.unique_values.append(k)
<ide> else:
<ide> self.sum_values[k][0] += v * (current-self.seen_so_far)
<ide> def update(self, current, values=[]):
<ide> else:
<ide> info += ' - %ds' % (now - self.start)
<ide> for k in self.unique_values:
<del> info += ' - %s: %.4f' % (k, self.sum_values[k][0]/self.sum_values[k][1])
<add> info += ' - %s: %.4f' % (k, self.sum_values[k][0]/ max(1, self.sum_values[k][1]))
<ide>
<ide> self.total_width += len(info)
<ide> if prev_total_width > self.total_width:
<ide> def update(self, current, values=[]):
<ide> if current >= self.target:
<ide> info = '%ds' % (now - self.start)
<ide> for k in self.unique_values:
<del> info += ' - %s: %.4f' % (k, self.sum_values[k][0]/self.sum_values[k][1])
<add> info += ' - %s: %.4f' % (k, self.sum_values[k][0]/ max(1, self.sum_values[k][1]))
<ide> sys.stdout.write(info + "\n")
<ide>
<ide> | 3 |
Javascript | Javascript | use start instead of stop + start | d7894f3969fd3932eef57d9759f01282c7d76aa5 | <ide><path>lib/internal/timers.js
<ide> Timeout.prototype[refreshFnSymbol] = function refresh() {
<ide> // Would be more ideal with uv_timer_again(), however that API does not
<ide> // cause libuv's sorted timers data structure (a binary heap at the time
<ide> // of writing) to re-sort itself. This causes ordering inconsistencies.
<del> this._handle.stop();
<ide> this._handle.start(this._idleTimeout);
<ide> } else if (this[unrefedSymbol]) {
<ide> getTimers()._unrefActive(this); | 1 |
Ruby | Ruby | fix insecure mirror check when stdout is empty | c667a43b9790be9887bf3f175d9e6ab3dad80e1a | <ide><path>Library/Homebrew/dev-cmd/audit.rb
<ide> def check_insecure_mirror(url)
<ide> secure_url = url.sub "http", "https"
<ide> secure_details = get_content_details(secure_url)
<ide>
<del> return if !details[:status].start_with?("2") || !secure_details[:status].start_with?("2")
<add> return if details[:status].nil? || secure_details[:status].nil? || !details[:status].start_with?("2") || !secure_details[:status].start_with?("2")
<ide>
<ide> etag_match = details[:etag] && details[:etag] == secure_details[:etag]
<ide> content_length_match = details[:content_length] && details[:content_length] == secure_details[:content_length] | 1 |
Javascript | Javascript | set animation context only if window is available | edd804017ab5c7f4bf86c3283fb981563dfe1be1 | <ide><path>src/renderers/WebGLRenderer.js
<ide> function WebGLRenderer( parameters ) {
<ide>
<ide> var animation = new WebGLAnimation();
<ide> animation.setAnimationLoop( onAnimationFrame );
<del> animation.setContext( typeof window !== 'undefined' ? window : null );
<add>
<add> if ( typeof window !== 'undefined' ) animation.setContext( window );
<ide>
<ide> this.setAnimationLoop = function ( callback ) {
<ide> | 1 |
Ruby | Ruby | add relinking instructions | e99ca2d59f59bc91506a62256429a5f7e9b3dbe0 | <ide><path>Library/Homebrew/cmd/link.rb
<ide> def link
<ide> ARGV.kegs.each do |keg|
<ide> if keg.linked?
<ide> opoo "Already linked: #{keg}"
<add> puts "To relink: brew unlink #{keg.fname} && brew link #{keg.fname}"
<ide> next
<ide> end
<ide> | 1 |
PHP | PHP | fix cs error | 0b9f56fc202915b393e6d8bd11d40f079ba82cbe | <ide><path>src/Core/App.php
<ide> public static function path(string $type, ?string $plugin = null): array
<ide> *
<ide> * Will return the plugin based path for those.
<ide> *
<del> * @param string $type
<del> * @param string|null $plugin
<add> * @param string $type Package type.
<add> * @param string|null $plugin Plugin name.
<ide> *
<ide> * @return string[]
<ide> */ | 1 |
Javascript | Javascript | update trackballcontrols tab consistency | cebc2aca2c57df591bb86f055c52d52c725e6079 | <ide><path>examples/js/controls/TrackballControls.js
<ide> THREE.TrackballControls = function ( object, domElement ) {
<ide>
<ide> switch ( event.deltaMode ) {
<ide>
<del> case 2:
<del> // Zoom in pages
<del> _zoomStart.y -= event.deltaY * 0.025;
<del> break;
<add> case 2:
<add> // Zoom in pages
<add> _zoomStart.y -= event.deltaY * 0.025;
<add> break;
<ide>
<ide> case 1:
<del> // Zoom in lines
<add> // Zoom in lines
<ide> _zoomStart.y -= event.deltaY * 0.01;
<ide> break;
<ide> | 1 |
PHP | PHP | fix more coding standards | dbb2dd44d723aaae015b0b7d56ed77544b0b59a2 | <ide><path>lib/Cake/Test/Case/Model/AclNodeTest.php
<ide> public function bindNode($ref = null) {
<ide> return array('DbAroTest' => array('DbAroTest.model' => 'AuthUser', 'DbAroTest.foreign_key' => 2));
<ide> }
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function __construct() {
<ide> $this->Aco = new DbAcoTest();
<ide> $this->Aro->Permission = new DbPermissionTest();
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function testNodeObjectFind() {
<ide> $result = Set::extract($Aro->node($Model), '{n}.DbAroTest.id');
<ide> $expected = array(4, 2, 1);
<ide> $this->assertEquals($expected, $result);
<del>
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Test/Case/Model/BehaviorCollectionTest.php
<ide> public function speakEnglish(Model $model, $method, $query) {
<ide> $query = preg_replace('/^in\s+/', 'Location.name = \'', $query);
<ide> return $method . '\' AND ' . $query . '\'';
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function speakEnglish(Model $model, $method, $query) {
<ide> * @package Cake.Test.Case.Model
<ide> */
<ide> class Test2Behavior extends TestBehavior {
<add>
<ide> public $mapMethods = array('/mappingRobot(\w+)/' => 'mapped');
<ide>
<ide> public function resolveMethod(Model $model, $stuff) {
<del>
<ide> }
<ide>
<ide> public function mapped(Model $model, $method, $query) {
<del>
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> class Test3Behavior extends TestBehavior{
<ide> * @package Cake.Test.Case.Model
<ide> */
<ide> class Test4Behavior extends ModelBehavior{
<add>
<ide> public function setup(Model $model, $config = null) {
<ide> $model->bindModel(
<ide> array('hasMany' => array('Comment'))
<ide> );
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function setup(Model $model, $config = null) {
<ide> * @package Cake.Test.Case.Model
<ide> */
<ide> class Test5Behavior extends ModelBehavior{
<add>
<ide> public function setup(Model $model, $config = null) {
<ide> $model->bindModel(
<ide> array('belongsTo' => array('User'))
<ide> );
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function setup(Model $model, $config = null) {
<ide> * @package Cake.Test.Case.Model
<ide> */
<ide> class Test6Behavior extends ModelBehavior{
<add>
<ide> public function setup(Model $model, $config = null) {
<ide> $model->bindModel(
<ide> array('hasAndBelongsToMany' => array('Tag'))
<ide> );
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function setup(Model $model, $config = null) {
<ide> * @package Cake.Test.Case.Model
<ide> */
<ide> class Test7Behavior extends ModelBehavior{
<add>
<ide> public function setup(Model $model, $config = null) {
<ide> $model->bindModel(
<ide> array('hasOne' => array('Attachment'))
<ide> );
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function testBehaviorHasManyFindCallbacks() {
<ide>
<ide> $Apple->Child->Behaviors->attach('Test', array('before' => 'modify'));
<ide> $result = $Apple->find('all', array('fields' => array('Apple.id'), 'conditions' => array('Apple.id <' => '4')));
<del> //$this->assertEquals($expected, $result2);
<ide>
<ide> $Apple->Child->Behaviors->disable('Test');
<ide> $result = $Apple->find('all');
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $Apple->Child->Behaviors->attach('Test', array('before' => 'off', 'after' => 'on'));
<del> //$this->assertSame($Apple->find('all'), array());
<ide>
<ide> $Apple->Child->Behaviors->attach('Test', array('after' => 'off'));
<ide> $this->assertEquals($Apple->find('all'), $expected);
<ide> public function testBehaviorHasManyFindCallbacks() {
<ide>
<ide> $Apple->Child->Behaviors->attach('Test', array('after' => 'test2'));
<ide> $this->assertEquals($Apple->find('all'), $expected);
<del>
<del> $Apple->Child->Behaviors->attach('Test', array('after' => 'modify'));
<del> $expected = array(
<del> array('id' => '1', 'apple_id' => '2', 'color' => 'Red 1', 'name' => 'Red Apple 1', 'created' => '2006-11-22 10:38:58', 'date' => '1951-01-04', 'modified' => '2006-12-01 13:31:26', 'mytime' => '22:57:17'),
<del> array('id' => '2', 'apple_id' => '1', 'color' => 'Bright Red 1', 'name' => 'Bright Red Apple', 'created' => '2006-11-22 10:43:13', 'date' => '2014-01-01', 'modified' => '2006-11-30 18:38:10', 'mytime' => '22:57:17'),
<del> array('id' => '3', 'apple_id' => '2', 'color' => 'blue green', 'name' => 'green blue', 'created' => '2006-12-25 05:13:36', 'date' => '2006-12-25', 'modified' => '2006-12-25 05:23:24', 'mytime' => '22:57:17'),
<del> array('id' => '4', 'apple_id' => '2', 'color' => 'Blue Green', 'name' => 'Test Name', 'created' => '2006-12-25 05:23:36', 'date' => '2006-12-25', 'modified' => '2006-12-25 05:23:36', 'mytime' => '22:57:17'),
<del> array('id' => '5', 'apple_id' => '5', 'color' => 'Green', 'name' => 'Blue Green', 'created' => '2006-12-25 05:24:06', 'date' => '2006-12-25', 'modified' => '2006-12-25 05:29:16', 'mytime' => '22:57:17'),
<del> array('id' => '6', 'apple_id' => '4', 'color' => 'My new appleOrange', 'name' => 'My new apple', 'created' => '2006-12-25 05:29:39', 'date' => '2006-12-25', 'modified' => '2006-12-25 05:29:39', 'mytime' => '22:57:17'),
<del> array('id' => '7', 'apple_id' => '6', 'color' => 'Some wierd color', 'name' => 'Some odd color', 'created' => '2006-12-25 05:34:21', 'date' => '2006-12-25', 'modified' => '2006-12-25 05:34:21', 'mytime' => '22:57:17')
<del> );
<del> //$this->assertEquals($Apple->find('all'), $expected);
<del>
<ide> }
<del> /**
<add>
<add>/**
<ide> * testBehaviorHasOneFindCallbacks method
<ide> *
<ide> * @return void
<ide> public function testBehaviorHasOneFindCallbacks() {
<ide> $Apple->Sample->Behaviors->attach('Test', array('before' => 'test'));
<ide> $this->assertSame($Apple->find('all'), $expected);
<ide>
<del> $Apple->Sample->Behaviors->attach('Test', array('before' => 'modify'));
<del> $expected2 = array(
<del> array(
<del> 'Apple' => array('id' => 1),
<del> 'Child' => array(
<del> array('id' => 2, 'name' => 'Bright Red Apple', 'mytime' => '22:57:17'))),
<del> array(
<del> 'Apple' => array('id' => 2),
<del> 'Child' => array(
<del> array('id' => 1, 'name' => 'Red Apple 1', 'mytime' => '22:57:17'),
<del> array('id' => 3, 'name' => 'green blue', 'mytime' => '22:57:17'),
<del> array('id' => 4, 'name' => 'Test Name', 'mytime' => '22:57:17'))),
<del> array(
<del> 'Apple' => array('id' => 3),
<del> 'Child' => array())
<del> );
<del> $result = $Apple->find('all', array('fields' => array('Apple.id'), 'conditions' => array('Apple.id <' => '4')));
<del> //$this->assertEquals($expected, $result2);
<del>
<ide> $Apple->Sample->Behaviors->disable('Test');
<ide> $result = $Apple->find('all');
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $Apple->Sample->Behaviors->attach('Test', array('before' => 'off', 'after' => 'on'));
<del> //$this->assertSame($Apple->find('all'), array());
<del>
<ide> $Apple->Sample->Behaviors->attach('Test', array('after' => 'off'));
<ide> $this->assertEquals($Apple->find('all'), $expected);
<ide>
<ide> public function testBehaviorHasOneFindCallbacks() {
<ide>
<ide> $Apple->Sample->Behaviors->attach('Test', array('after' => 'test2'));
<ide> $this->assertEquals($Apple->find('all'), $expected);
<del>
<del> $Apple->Sample->Behaviors->attach('Test', array('after' => 'modify'));
<del> $expected = array(
<del> array('id' => '1', 'apple_id' => '2', 'color' => 'Red 1', 'name' => 'Red Apple 1', 'created' => '2006-11-22 10:38:58', 'date' => '1951-01-04', 'modified' => '2006-12-01 13:31:26', 'mytime' => '22:57:17'),
<del> array('id' => '2', 'apple_id' => '1', 'color' => 'Bright Red 1', 'name' => 'Bright Red Apple', 'created' => '2006-11-22 10:43:13', 'date' => '2014-01-01', 'modified' => '2006-11-30 18:38:10', 'mytime' => '22:57:17'),
<del> array('id' => '3', 'apple_id' => '2', 'color' => 'blue green', 'name' => 'green blue', 'created' => '2006-12-25 05:13:36', 'date' => '2006-12-25', 'modified' => '2006-12-25 05:23:24', 'mytime' => '22:57:17'),
<del> array('id' => '4', 'apple_id' => '2', 'color' => 'Blue Green', 'name' => 'Test Name', 'created' => '2006-12-25 05:23:36', 'date' => '2006-12-25', 'modified' => '2006-12-25 05:23:36', 'mytime' => '22:57:17'),
<del> array('id' => '5', 'apple_id' => '5', 'color' => 'Green', 'name' => 'Blue Green', 'created' => '2006-12-25 05:24:06', 'date' => '2006-12-25', 'modified' => '2006-12-25 05:29:16', 'mytime' => '22:57:17'),
<del> array('id' => '6', 'apple_id' => '4', 'color' => 'My new appleOrange', 'name' => 'My new apple', 'created' => '2006-12-25 05:29:39', 'date' => '2006-12-25', 'modified' => '2006-12-25 05:29:39', 'mytime' => '22:57:17'),
<del> array('id' => '7', 'apple_id' => '6', 'color' => 'Some wierd color', 'name' => 'Some odd color', 'created' => '2006-12-25 05:34:21', 'date' => '2006-12-25', 'modified' => '2006-12-25 05:34:21', 'mytime' => '22:57:17')
<del> );
<del> //$this->assertEquals($Apple->find('all'), $expected);
<ide> }
<ide>
<ide> /**
<ide> public function testBehaviorBelongsToFindCallbacks() {
<ide>
<ide> $Apple->Parent->Behaviors->attach('Test', array('after' => 'test2'));
<ide> $this->assertEquals($Apple->find('all'), $expected);
<del>
<del> $Apple->Parent->Behaviors->attach('Test', array('after' => 'modify'));
<del> $expected = array(
<del> array('id' => '1', 'apple_id' => '2', 'color' => 'Red 1', 'name' => 'Red Apple 1', 'created' => '2006-11-22 10:38:58', 'date' => '1951-01-04', 'modified' => '2006-12-01 13:31:26', 'mytime' => '22:57:17'),
<del> array('id' => '2', 'apple_id' => '1', 'color' => 'Bright Red 1', 'name' => 'Bright Red Apple', 'created' => '2006-11-22 10:43:13', 'date' => '2014-01-01', 'modified' => '2006-11-30 18:38:10', 'mytime' => '22:57:17'),
<del> array('id' => '3', 'apple_id' => '2', 'color' => 'blue green', 'name' => 'green blue', 'created' => '2006-12-25 05:13:36', 'date' => '2006-12-25', 'modified' => '2006-12-25 05:23:24', 'mytime' => '22:57:17'),
<del> array('id' => '4', 'apple_id' => '2', 'color' => 'Blue Green', 'name' => 'Test Name', 'created' => '2006-12-25 05:23:36', 'date' => '2006-12-25', 'modified' => '2006-12-25 05:23:36', 'mytime' => '22:57:17'),
<del> array('id' => '5', 'apple_id' => '5', 'color' => 'Green', 'name' => 'Blue Green', 'created' => '2006-12-25 05:24:06', 'date' => '2006-12-25', 'modified' => '2006-12-25 05:29:16', 'mytime' => '22:57:17'),
<del> array('id' => '6', 'apple_id' => '4', 'color' => 'My new appleOrange', 'name' => 'My new apple', 'created' => '2006-12-25 05:29:39', 'date' => '2006-12-25', 'modified' => '2006-12-25 05:29:39', 'mytime' => '22:57:17'),
<del> array('id' => '7', 'apple_id' => '6', 'color' => 'Some wierd color', 'name' => 'Some odd color', 'created' => '2006-12-25 05:34:21', 'date' => '2006-12-25', 'modified' => '2006-12-25 05:34:21', 'mytime' => '22:57:17')
<del> );
<del> //$this->assertEquals($Apple->find('all'), $expected);
<ide> }
<ide>
<ide> /**
<ide> public function testBehaviorDeleteCallbacks() {
<ide> $this->assertSame(trim(ob_get_clean()), 'beforeDelete success');
<ide> $this->assertSame($results, true);
<ide>
<del>
<ide> $Apple->Behaviors->attach('Test', array('beforeDelete' => 'off', 'afterDelete' => 'on'));
<ide> ob_start();
<ide> $results = $Apple->delete(2, false);
<ide> public function testHasMethodAsCallback() {
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<del>
<ide> }
<ide><path>lib/Cake/Test/Case/Model/CakeSchemaTest.php
<ide> public function getVar($var) {
<ide> }
<ide> return $this->$var;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function setup($version) {
<ide> */
<ide> public function teardown($version) {
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> class SchemaCrossDatabaseFixture extends CakeTestFixture {
<ide> * @package Cake.Test.Case.Model
<ide> */
<ide> class SchemaPrefixAuthUser extends CakeTestModel {
<add>
<ide> /**
<ide> * name property
<ide> *
<ide> public function setUp() {
<ide> */
<ide> public function tearDown() {
<ide> parent::tearDown();
<del> if (file_exists(TMP . 'tests' . DS .'schema.php')) {
<del> unlink(TMP . 'tests' . DS .'schema.php');
<add> if (file_exists(TMP . 'tests' . DS . 'schema.php')) {
<add> unlink(TMP . 'tests' . DS . 'schema.php');
<ide> }
<ide> unset($this->Schema);
<ide> CakePlugin::unload();
<ide> public function testSchemaRead() {
<ide> }
<ide>
<ide> /**
<del>* testSchemaReadWithAppModel method
<del>*
<del>* @access public
<del>* @return void
<del>*/
<add> * testSchemaReadWithAppModel method
<add> *
<add> * @access public
<add> * @return void
<add> */
<ide> public function testSchemaReadWithAppModel() {
<ide> $connections = ConnectionManager::enumConnectionObjects();
<ide> ConnectionManager::drop('default');
<ide> ConnectionManager::create('default', $connections['test']);
<ide> try {
<ide> $read = $this->Schema->read(array(
<del> 'connection' => 'default',
<del> 'name' => 'TestApp',
<del> 'models' => array('AppModel')
<add> 'connection' => 'default',
<add> 'name' => 'TestApp',
<add> 'models' => array('AppModel')
<ide> ));
<ide> } catch(MissingTableException $mte) {
<ide> ConnectionManager::drop('default');
<ide> public function testSchemaReadWithTablePrefix() {
<ide> ));
<ide> unset($read['tables']['missing']);
<ide> $this->assertTrue(isset($read['tables']['auth_users']), 'auth_users key missing %s');
<del>
<ide> }
<ide>
<ide> /**
<ide> public function testSchemaReadWithCrossDatabase() {
<ide> $config = ConnectionManager::enumConnectionObjects();
<ide> $this->skipIf(
<ide> !isset($config['test']) || !isset($config['test2']),
<del> 'Primary and secondary test databases not configured, skipping cross-database join tests.'
<del> . ' To run these tests, you must define $test and $test2 in your database configuration.'
<add> 'Primary and secondary test databases not configured, ' .
<add> 'skipping cross-database join tests. ' .
<add> 'To run these tests, you must define $test and $test2 in your database configuration.'
<ide> );
<ide>
<del> $db2 = ConnectionManager::getDataSource('test2');
<add> $db = ConnectionManager::getDataSource('test2');
<ide> $fixture = new SchemaCrossDatabaseFixture();
<del> $fixture->create($db2);
<del> $fixture->insert($db2);
<add> $fixture->create($db);
<add> $fixture->insert($db);
<ide>
<ide> $read = $this->Schema->read(array(
<ide> 'connection' => 'test',
<ide> public function testSchemaReadWithCrossDatabase() {
<ide> $this->assertFalse(isset($read['tables']['posts']), 'Posts should not appear');
<ide> $this->assertTrue(isset($read['tables']['cross_database']));
<ide>
<del> $fixture->drop($db2);
<add> $fixture->drop($db);
<ide> }
<ide>
<ide> /**
<ide> public function testGenerateTable() {
<ide> * @return void
<ide> */
<ide> public function testSchemaWrite() {
<del> $write = $this->Schema->write(array('name' => 'MyOtherApp', 'tables' => $this->Schema->tables, 'path' => TMP . 'tests'));
<del> $file = file_get_contents(TMP . 'tests' . DS .'schema.php');
<add> $write = $this->Schema->write(array(
<add> 'name' => 'MyOtherApp',
<add> 'tables' => $this->Schema->tables,
<add> 'path' => TMP . 'tests'
<add> ));
<add> $file = file_get_contents(TMP . 'tests' . DS . 'schema.php');
<ide> $this->assertEquals($write, $file);
<ide>
<del> require_once( TMP . 'tests' . DS .'schema.php');
<add> require_once TMP . 'tests' . DS . 'schema.php';
<ide> $OtherSchema = new MyOtherAppSchema();
<ide> $this->assertEquals($this->Schema->tables, $OtherSchema->tables);
<ide> }
<ide> public function testSchemaComparison() {
<ide> $tables = array(
<ide> 'missing' => array(
<ide> 'categories' => array(
<del> 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
<del> 'created' => array('type' => 'datetime', 'null' => false, 'default' => NULL),
<del> 'modified' => array('type' => 'datetime', 'null' => false, 'default' => NULL),
<del> 'name' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 100),
<add> 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'primary'),
<add> 'created' => array('type' => 'datetime', 'null' => false, 'default' => null),
<add> 'modified' => array('type' => 'datetime', 'null' => false, 'default' => null),
<add> 'name' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 100),
<ide> 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)),
<ide> 'tableParameters' => array('charset' => 'latin1', 'collate' => 'latin1_swedish_ci', 'engine' => 'MyISAM')
<ide> )
<ide> ),
<ide> 'ratings' => array(
<del> 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
<del> 'foreign_key' => array('type' => 'integer', 'null' => false, 'default' => NULL),
<del> 'model' => array('type' => 'varchar', 'null' => false, 'default' => NULL),
<del> 'value' => array('type' => 'float', 'null' => false, 'length' => '5,2', 'default' => NULL),
<del> 'created' => array('type' => 'datetime', 'null' => false, 'default' => NULL),
<del> 'modified' => array('type' => 'datetime', 'null' => false, 'default' => NULL),
<add> 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'primary'),
<add> 'foreign_key' => array('type' => 'integer', 'null' => false, 'default' => null),
<add> 'model' => array('type' => 'varchar', 'null' => false, 'default' => null),
<add> 'value' => array('type' => 'float', 'null' => false, 'length' => '5,2', 'default' => null),
<add> 'created' => array('type' => 'datetime', 'null' => false, 'default' => null),
<add> 'modified' => array('type' => 'datetime', 'null' => false, 'default' => null),
<ide> 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)),
<ide> 'tableParameters' => array('charset' => 'latin1', 'collate' => 'latin1_swedish_ci', 'engine' => 'MyISAM')
<ide> )
<ide> public function testSchemaComparison() {
<ide> $expected = array(
<ide> 'ratings' => array(
<ide> 'add' => array(
<del> 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
<del> 'foreign_key' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'after' => 'id'),
<del> 'model' => array('type' => 'varchar', 'null' => false, 'default' => NULL, 'after' => 'foreign_key'),
<del> 'value' => array('type' => 'float', 'null' => false, 'length' => '5,2', 'default' => NULL, 'after' => 'model'),
<del> 'created' => array('type' => 'datetime', 'null' => false, 'default' => NULL, 'after' => 'value'),
<del> 'modified' => array('type' => 'datetime', 'null' => false, 'default' => NULL, 'after' => 'created'),
<add> 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'primary'),
<add> 'foreign_key' => array('type' => 'integer', 'null' => false, 'default' => null, 'after' => 'id'),
<add> 'model' => array('type' => 'varchar', 'null' => false, 'default' => null, 'after' => 'foreign_key'),
<add> 'value' => array('type' => 'float', 'null' => false, 'length' => '5,2', 'default' => null, 'after' => 'model'),
<add> 'created' => array('type' => 'datetime', 'null' => false, 'default' => null, 'after' => 'value'),
<add> 'modified' => array('type' => 'datetime', 'null' => false, 'default' => null, 'after' => 'created'),
<ide> 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)),
<ide> 'tableParameters' => array('charset' => 'latin1', 'collate' => 'latin1_swedish_ci', 'engine' => 'MyISAM')
<ide> )
<ide> public function testSchemaComparison() {
<ide> public function testCompareEmptyStringAndNull() {
<ide> $One = new CakeSchema(array(
<ide> 'posts' => array(
<del> 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
<add> 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'primary'),
<ide> 'name' => array('type' => 'string', 'null' => false, 'default' => '')
<ide> )
<ide> ));
<ide> $Two = new CakeSchema(array(
<ide> 'posts' => array(
<del> 'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
<add> 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'primary'),
<ide> 'name' => array('type' => 'string', 'null' => false, 'default' => null)
<ide> )
<ide> ));
<ide><path>lib/Cake/Test/Case/Model/ConnectionManagerTest.php
<ide> public function testGetSourceName() {
<ide> */
<ide> public function testLoadDataSource() {
<ide> $connections = array(
<del> array('classname' => 'Mysql', 'filename' => 'Mysql', 'package' => 'Database'),
<del> array('classname' => 'Postgres', 'filename' => 'Postgres', 'package' => 'Database'),
<add> array('classname' => 'Mysql', 'filename' => 'Mysql', 'package' => 'Database'),
<add> array('classname' => 'Postgres', 'filename' => 'Postgres', 'package' => 'Database'),
<ide> array('classname' => 'Sqlite', 'filename' => 'Sqlite', 'package' => 'Database'),
<ide> );
<ide>
<ide><path>lib/Cake/Test/Case/Model/Datasource/Session/DatabaseSessionTest.php
<ide> class_exists('CakeSession');
<ide>
<ide> class SessionTestModel extends Model {
<add>
<ide> public $name = 'SessionTestModel';
<add>
<ide> public $useTable = 'sessions';
<add>
<ide> }
<ide>
<ide> /**
<ide> public function testGc() {
<ide> $storage->gc();
<ide> $this->assertFalse($storage->read('foo'));
<ide> }
<del>}
<ide>\ No newline at end of file
<add>}
<ide><path>lib/Cake/Test/Case/Model/ModelCrossSchemaHabtmTest.php
<ide> protected function _checkConfigs() {
<ide> $this->skipIf($this->db instanceof Sqlite, 'This test is not compatible with Sqlite.');
<ide> $this->skipIf(
<ide> !isset($config['test']) || !isset($config['test2']),
<del> 'Primary and secondary test databases not configured, skipping cross-database join tests.'
<del> . ' To run these tests, you must define $test and $test2 in your database configuration.'
<add> 'Primary and secondary test databases not configured, ' .
<add> 'skipping cross-database join tests.' .
<add> ' To run these tests, you must define $test and $test2 in your database configuration.'
<ide> );
<ide> }
<ide>
<ide> public function testHabtmWithThreeDatabases() {
<ide> $config = ConnectionManager::enumConnectionObjects();
<ide> $this->skipIf(
<ide> !isset($config['test']) || !isset($config['test2']) || !isset($config['test_database_three']),
<del> 'Primary, secondary, and tertiary test databases not configured, skipping test.'
<del> . ' To run these tests, you must define $test, $test2, and $test_database_three in your database configuration.'
<add> 'Primary, secondary, and tertiary test databases not configured,' .
<add> ' skipping test. To run these tests, you must define ' .
<add> '$test, $test2, and $test_database_three in your database configuration.'
<ide> );
<ide>
<ide> $this->loadFixtures('Player', 'Guild', 'GuildsPlayer', 'Armor', 'ArmorsPlayer');
<ide><path>lib/Cake/Test/Case/Model/ModelDeleteTest.php
<ide> public function testDelete() {
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<del>
<ide> /**
<ide> * test that delete() updates the correct records counterCache() records.
<ide> *
<ide> public function testDeleteLinksWithMultipleHabtmAssociations() {
<ide> * @return void
<ide> */
<ide> public function testHabtmDeleteLinksWhenNoPrimaryKeyInJoinTable() {
<del>
<ide> $this->loadFixtures('Apple', 'Device', 'ThePaperMonkies');
<ide> $ThePaper = new ThePaper();
<ide> $ThePaper->id = 1;
<ide> public function testDeleteHabtmPostgresFailure() {
<ide> $this->assertEquals(count($before[0]['Tag']), 2, 'Tag count for Article.id = 1 is incorrect, should be 2 %s');
<ide>
<ide> // From now on, Tag #1 is only associated with Post #1
<del> $submitted_data = array(
<add> $submittedData = array(
<ide> "Tag" => array("id" => 1, 'tag' => 'tag1'),
<ide> "Article" => array(
<ide> "Article" => array(1)
<ide> )
<ide> );
<del> $Tag->save($submitted_data);
<add> $Tag->save($submittedData);
<ide>
<ide> // One more submission (The other way around) to make sure the reverse save looks good.
<del> $submitted_data = array(
<add> $submittedData = array(
<ide> "Article" => array("id" => 2, 'title' => 'second article'),
<ide> "Tag" => array(
<ide> "Tag" => array(2, 3)
<ide> )
<ide> );
<add>
<ide> // ERROR:
<ide> // Postgresql: DELETE FROM "articles_tags" WHERE tag_id IN ('1', '3')
<ide> // MySQL: DELETE `ArticlesTag` FROM `articles_tags` AS `ArticlesTag` WHERE `ArticlesTag`.`article_id` = 2 AND `ArticlesTag`.`tag_id` IN (1, 3)
<del> $Article->save($submitted_data);
<add> $Article->save($submittedData);
<ide>
<ide> // Want to make sure Article #1 has Tag #1 and Tag #2 still.
<ide> $after = $Article->find("all", array(
<ide><path>lib/Cake/Test/Case/Model/ModelIntegrationTest.php
<ide> class DboMock extends DboSource {
<ide>
<ide> /**
<del>* Returns the $field without modifications
<del>*/
<add> * Returns the $field without modifications
<add> */
<ide> public function name($field) {
<ide> return $field;
<ide> }
<ide>
<ide> /**
<del>* Returns true to fake a database connection
<del>*/
<add> * Returns true to fake a database connection
<add> */
<ide> public function connect() {
<ide> return true;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function testMissingTable() {
<ide> */
<ide> public function testPkInHabtmLinkModelArticleB() {
<ide> $this->loadFixtures('Article', 'Tag', 'ArticlesTag');
<del> $TestModel2 = new ArticleB();
<del> $this->assertEquals($TestModel2->ArticlesTag->primaryKey, 'article_id');
<add> $TestModel = new ArticleB();
<add> $this->assertEquals($TestModel->ArticlesTag->primaryKey, 'article_id');
<ide> }
<ide>
<ide> /**
<ide> public function testCacheSourcesDisabling() {
<ide> /**
<ide> * testPkInHabtmLinkModel method
<ide> *
<del> * @return void
<add> * @return void
<ide> */
<ide> public function testPkInHabtmLinkModel() {
<ide> //Test Nonconformant Models
<ide> public function testPkInHabtmLinkModel() {
<ide>
<ide> //test conformant models with no PK in the join table
<ide> $this->loadFixtures('Article', 'Tag');
<del> $TestModel2 = new Article();
<del> $this->assertEquals($TestModel2->ArticlesTag->primaryKey, 'article_id');
<add> $TestModel = new Article();
<add> $this->assertEquals($TestModel->ArticlesTag->primaryKey, 'article_id');
<ide>
<ide> //test conformant models with PK in join table
<del> $TestModel3 = new Portfolio();
<del> $this->assertEquals($TestModel3->ItemsPortfolio->primaryKey, 'id');
<add> $TestModel = new Portfolio();
<add> $this->assertEquals($TestModel->ItemsPortfolio->primaryKey, 'id');
<ide>
<ide> //test conformant models with PK in join table - join table contains extra field
<ide> $this->loadFixtures('JoinA', 'JoinB', 'JoinAB');
<del> $TestModel4 = new JoinA();
<del> $this->assertEquals($TestModel4->JoinAsJoinB->primaryKey, 'id');
<del>
<add> $TestModel = new JoinA();
<add> $this->assertEquals($TestModel->JoinAsJoinB->primaryKey, 'id');
<ide> }
<ide>
<ide> /**
<ide> public function testHABTMKeepExisting() {
<ide> $expected = 3; // 3 domains belonging to cakephp
<ide> $this->assertEquals($expected, count($results['Domain']));
<ide>
<del>
<ide> $Site->id = 2;
<ide> $results = $Site->read();
<ide> $expected = 2; // 2 domains belonging to markstory
<ide> public function testHasMethod() {
<ide> * @return void
<ide> */
<ide> public function testMultischemaFixture() {
<del>
<ide> $config = ConnectionManager::enumConnectionObjects();
<ide> $this->skipIf($this->db instanceof Sqlite, 'This test is not compatible with Sqlite.');
<ide> $this->skipIf(!isset($config['test']) || !isset($config['test2']),
<ide> public function testMultischemaFixture() {
<ide> * @return void
<ide> */
<ide> public function testMultischemaFixtureWithThreeDatabases() {
<del>
<ide> $config = ConnectionManager::enumConnectionObjects();
<ide> $this->skipIf($this->db instanceof Sqlite, 'This test is not compatible with Sqlite.');
<ide> $this->skipIf(
<ide><path>lib/Cake/Test/Case/Model/ModelReadTest.php
<ide> public function testFetchingNonUniqueFKJoinTableRecords() {
<ide> )
<ide> );
<ide>
<del>
<ide> $Something->JoinThing->create($joinThingData);
<ide> $Something->JoinThing->save();
<ide>
<ide> public function testPreparedQuery() {
<ide>
<ide> $result = $this->db->getQueryCache($query, $params);
<ide> $this->assertFalse($result === false);
<del>
<ide> }
<ide>
<ide> /**
<ide> public function testBuildQuery() {
<ide>
<ide> $expected = array(
<ide> 'conditions' => array(
<del> 'user' => 'larry'),
<del> 'fields' => NULL,
<add> 'user' => 'larry'
<add> ),
<add> 'fields' => null,
<ide> 'joins' => array(),
<del> 'limit' => NULL,
<del> 'offset' => NULL,
<add> 'limit' => null,
<add> 'offset' => null,
<ide> 'order' => array(
<del> 0 => NULL),
<add> 0 => null
<add> ),
<ide> 'page' => 1,
<del> 'group' => NULL,
<add> 'group' => null,
<ide> 'callbacks' => true,
<del> 'returnQuery' => true);
<add> 'returnQuery' => true
<add> );
<ide> $result = $TestModel->buildQuery('all', array('returnQuery' => true, 'conditions' => array('user' => 'larry')));
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide> public function testVirtualFieldsMysql() {
<ide>
<ide> $this->assertEquals($result, $expectation);
<ide>
<del>
<ide> $Author = ClassRegistry::init('Author');
<ide> $Author->virtualFields = array(
<ide> 'full_name' => 'CONCAT(Author.user, " ", Author.id)'
<ide> public function testGetVirtualField() {
<ide> $this->assertEquals($Post->getVirtualField('Post.other_field'), $Post->virtualFields['other_field']);
<ide> }
<ide>
<del>
<ide> /**
<ide> * test that checks for error when NOT condition passed in key and a 1 element array value
<ide> *
<ide> public function testNotInArrayWithOneValue() {
<ide> )
<ide> )
<ide> );
<del>
<ide> $this->assertTrue(is_array($result) && !empty($result));
<del> }
<add> }
<ide>
<ide> /**
<ide> * test custom find method
<ide> public function testfindCustom() {
<ide>
<ide> $result = $Article->find('unPublished');
<ide> $this->assertEquals(1, count($result));
<del> }
<add> }
<add>
<ide> }
<ide><path>lib/Cake/Test/Case/Model/ModelValidationTest.php
<ide> public function testValidationParams() {
<ide> 'required' => true
<ide> ),
<ide> 'or' => true,
<del> 'ignore_on_same' => 'id'
<add> 'ignoreOnSame' => 'id'
<ide> );
<ide> $this->assertEquals($TestModel->validatorParams, $expected);
<ide>
<ide><path>lib/Cake/Test/Case/Model/ModelWriteTest.php
<ide> public function testSaveDateAsFirstEntry() {
<ide>
<ide> $this->assertEquals($testResult['Article']['title'], $data['Article']['title']);
<ide> $this->assertEquals($testResult['Article']['created'], '2008-01-01 00:00:00');
<del>
<ide> }
<ide>
<ide> /**
<ide> public function testCounterCacheWithSelfJoin() {
<ide> $column = '';
<ide> }
<ide> $column .= $this->db->buildColumn(array('name' => 'child_count', 'type' => 'integer'));
<del> $this->db->query('ALTER TABLE '. $this->db->fullTableName('category_threads') . ' ADD ' . $column);
<add> $this->db->query('ALTER TABLE ' . $this->db->fullTableName('category_threads') . ' ADD ' . $column);
<ide> $this->db->flushMethodCache();
<ide> $Category = new CategoryThread();
<ide> $result = $Category->updateAll(array('CategoryThread.name' => "'updated'"), array('CategoryThread.parent_id' => 5));
<ide> public function testSaveField() {
<ide> $result = $TestModel->saveField('title', '', true);
<ide> $this->assertFalse($result);
<ide>
<del>
<ide> $TestModel->recursive = -1;
<ide> $TestModel->id = 1;
<ide> $result = $TestModel->saveField('user_id', 9999);
<ide> public function testSaveField() {
<ide> ));
<ide> $this->assertEquals($expected, $result);
<ide>
<del>
<ide> $this->loadFixtures('Node', 'Dependency');
<ide> $Node = new Node();
<ide> $Node->set('id', 1);
<ide> public function testSaveHabtm() {
<ide> ),
<ide> 'Tag' => array(
<ide> 'Tag' => array(1, 2, 3)
<del> ));
<del> $result = $TestModel->create()
<add> )
<add> );
<add> $result = $TestModel->create()
<ide> && $TestModel->save($data, true, array('user_id', 'title', 'published'));
<ide> $this->assertFalse(empty($result));
<ide>
<del> $TestModel->unbindModel(array('belongsTo' => array('User'), 'hasMany' => array('Comment')));
<add> $TestModel->unbindModel(array(
<add> 'belongsTo' => array('User'),
<add> 'hasMany' => array('Comment')
<add> ));
<ide> $result = $TestModel->read();
<ide> $expected = array(
<ide> 'Article' => array(
<ide> public function testSaveHabtm() {
<ide> )));
<ide> $this->assertEquals($expected, $result);
<ide>
<del>
<ide> $this->loadFixtures('JoinA', 'JoinC', 'JoinAC', 'JoinB', 'JoinAB');
<ide> $TestModel = new JoinA();
<ide> $TestModel->hasBelongsToMany = array('JoinC' => array('unique' => true));
<ide> public function testSaveAll() {
<ide> unset($result[6]['Comment']['created'], $result[6]['Comment']['updated']);
<ide> $this->assertEquals($result[6]['Comment'], $expected);
<ide>
<del>
<ide> $expected = array(
<ide> 'id' => '2',
<ide> 'comment_id' => '7',
<ide> public function testSaveAllHasOne() {
<ide> )));
<ide> $this->assertEquals($expected, $result);
<ide>
<del>
<ide> $model->Attachment->bindModel(array('belongsTo' => array('Comment')), false);
<ide> $data = array(
<ide> 'Comment' => array(
<ide> public function testSaveAllValidateFirst() {
<ide> $result = Set::extract('/Comment/article_id', $result);
<ide> $this->assertEquals($result[0], 4);
<ide>
<del>
<ide> $model->deleteAll(true);
<ide> $data = array(
<ide> 'Article' => array(
<ide> public function testSaveAssociated() {
<ide> unset($result[6]['Comment']['updated'], $result[6]['Comment']['created']);
<ide> $this->assertEquals($result[6]['Comment'], $expected);
<ide>
<del>
<ide> $expected = array(
<ide> 'id' => '2',
<ide> 'comment_id' => '7',
<ide> public function testSaveAssociatedHasOne() {
<ide> )));
<ide> $this->assertEquals($expected, $result);
<ide>
<del>
<ide> $model->Attachment->bindModel(array('belongsTo' => array('Comment')), false);
<ide> $data = array(
<ide> 'Comment' => array(
<ide> public function testSaveManyAtomic() {
<ide> ), array('validate' => true, 'atomic' => false));
<ide>
<ide> $this->assertSame($result, array(true, false));
<del>
<ide> }
<ide>
<ide> /**
<ide> public function testSaveAssociatedValidateFirst() {
<ide> $result = Set::extract('/Comment/article_id', $result);
<ide> $this->assertEquals($result[0], 4);
<ide>
<del>
<ide> $model->deleteAll(true);
<ide> $data = array(
<ide> 'Article' => array(
<ide> public function testSaveAllFieldListValidateBelongsTo() {
<ide> 'id' => '4',
<ide> 'author_id' => '5',
<ide> 'title' => 'Post without body',
<del> 'body' => NULL,
<add> 'body' => null,
<ide> 'published' => 'N',
<ide> 'created' => $ts,
<ide> 'updated' => $ts,
<ide> ),
<ide> 'Author' => array (
<ide> 'id' => '5',
<ide> 'user' => 'bob',
<del> 'password' => NULL,
<add> 'password' => null,
<ide> 'created' => $ts,
<ide> 'updated' => $ts,
<ide> 'test' => 'working',
<ide><path>lib/Cake/Test/Case/Model/models.php
<ide> class AppModel extends Model {
<ide> *
<ide> * @return array
<ide> */
<del> public function _findPublished($state, $query, $results = array()) {
<del> if ($state === 'before') {
<del> $query['conditions']['published'] = 'Y';
<del> return $query;
<del> }
<del> return $results;
<add> protected function _findPublished($state, $query, $results = array()) {
<add> if ($state === 'before') {
<add> $query['conditions']['published'] = 'Y';
<add> return $query;
<add> }
<add> return $results;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> class Test extends CakeTestModel {
<ide> 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''),
<ide> 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null)
<ide> );
<add>
<ide> }
<ide>
<ide> /**
<ide> public function validateNumber($value, $options) {
<ide> public function validateTitle($value) {
<ide> return (!empty($value) && strpos(strtolower($value['title']), 'title-') === 0);
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> class User extends CakeTestModel {
<ide> * beforeFind() callback used to run ContainableBehaviorTest::testLazyLoad()
<ide> *
<ide> * @return bool
<del>*/
<add> * @throws Exception
<add> */
<ide> public function beforeFind($queryData) {
<ide> if (!empty($queryData['lazyLoad'])) {
<ide> if (!isset($this->Article, $this->Comment, $this->ArticleFeatured)) {
<ide> public function beforeFind($queryData) {
<ide> }
<ide> return true;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function beforeSave($options = array()) {
<ide> * @param mixed $title
<ide> * @return void
<ide> */
<del> static function titleDuplicate($title) {
<add> public static function titleDuplicate($title) {
<ide> if ($title === 'My Article Title') {
<ide> return false;
<ide> }
<ide> return true;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> static function titleDuplicate($title) {
<ide> * @package Cake.Test.Case.Model
<ide> */
<ide> class BeforeDeleteComment extends CakeTestModel {
<add>
<ide> public $name = 'BeforeDeleteComment';
<ide>
<ide> public $useTable = 'comments';
<ide> public function beforeDelete($cascade = true) {
<ide> $db->delete($this, array($this->alias . '.' . $this->primaryKey => array(1, 3)));
<ide> return true;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> class NumericArticle extends CakeTestModel {
<ide> * @var string 'numeric_articles'
<ide> */
<ide> public $useTable = 'numeric_articles';
<add>
<ide> }
<ide>
<ide> /**
<ide> class Article10 extends CakeTestModel {
<ide> * @var array
<ide> */
<ide> public $hasMany = array('Comment' => array('dependent' => true, 'exclusive' => true));
<add>
<ide> }
<ide>
<ide> /**
<ide> class ArticleFeatured extends CakeTestModel {
<ide> * @var array
<ide> */
<ide> public $validate = array('user_id' => 'numeric', 'title' => 'notEmpty', 'body' => 'notEmpty');
<add>
<ide> }
<ide>
<ide> /**
<ide> public function afterFind($results, $primary = false) {
<ide> }
<ide> return $results;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function afterFind($results, $primary = false) {
<ide> }
<ide> return $results;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function afterFind($results, $primary = false) {
<ide> $this->useDbConfig = 'test';
<ide> return $results;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function afterFind($results, $primary = false) {
<ide> $results[0]['Author']['test'] = 'working';
<ide> return $results;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function afterFind($results, $primary = false) {
<ide> }
<ide> return $results;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> class BiddingMessage extends CakeTestModel {
<ide> */
<ide> public $primaryKey = 'bidding';
<ide>
<del>
<ide> /**
<ide> * belongsTo property
<ide> *
<ide> class NodeAfterFind extends CakeTestModel {
<ide> public function afterFind($results, $primary = false) {
<ide> return $results;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> class Callback extends CakeTestModel {
<ide> * @package Cake.Test.Case.Model
<ide> */
<ide> class CallbackPostTestModel extends CakeTestModel {
<add>
<ide> public $useTable = 'posts';
<add>
<ide> /**
<ide> * variable to control return of beforeValidate
<ide> *
<ide> * @var string
<ide> */
<ide> public $beforeValidateReturn = true;
<add>
<ide> /**
<ide> * variable to control return of beforeSave
<ide> *
<ide> * @var string
<ide> */
<ide> public $beforeSaveReturn = true;
<add>
<ide> /**
<ide> * variable to control return of beforeDelete
<ide> *
<ide> * @var string
<ide> */
<ide> public $beforeDeleteReturn = true;
<add>
<ide> /**
<ide> * beforeSave callback
<ide> *
<ide> class CallbackPostTestModel extends CakeTestModel {
<ide> public function beforeSave($options = array()) {
<ide> return $this->beforeSaveReturn;
<ide> }
<add>
<ide> /**
<ide> * beforeValidate callback
<ide> *
<ide> public function beforeSave($options = array()) {
<ide> public function beforeValidate($options = array()) {
<ide> return $this->beforeValidateReturn;
<ide> }
<add>
<ide> /**
<ide> * beforeDelete callback
<ide> *
<ide> public function beforeValidate($options = array()) {
<ide> public function beforeDelete($cascade = true) {
<ide> return $this->beforeDeleteReturn;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function customValidationMethod($data) {
<ide> *
<ide> * @return array
<ide> */
<del> public function customValidatorWithParams($data, $validator, $or = true, $ignore_on_same = 'id') {
<add> public function customValidatorWithParams($data, $validator, $or = true, $ignoreOnSame = 'id') {
<ide> $this->validatorParams = get_defined_vars();
<ide> unset($this->validatorParams['this']);
<ide> return true;
<ide> public function customValidatorWithParams($data, $validator, $or = true, $ignore
<ide> public function customValidatorWithMessage($data) {
<ide> return 'This field will *never* validate! Muhahaha!';
<ide> }
<add>
<ide> /**
<ide> * Test validation with many parameters
<ide> *
<ide> public function customValidatorWithSixParams($data, $one = 1, $two = 2, $three =
<ide> unset($this->validatorParams['this']);
<ide> return true;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function customValidationMethod($data) {
<ide> public function schema($field = false) {
<ide> return array();
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> class Person extends CakeTestModel {
<ide> * @var array
<ide> */
<ide> public $belongsTo = array(
<del> 'Mother' => array(
<del> 'className' => 'Person',
<del> 'foreignKey' => 'mother_id'),
<del> 'Father' => array(
<del> 'className' => 'Person',
<del> 'foreignKey' => 'father_id'));
<add> 'Mother' => array(
<add> 'className' => 'Person',
<add> 'foreignKey' => 'mother_id'
<add> ),
<add> 'Father' => array(
<add> 'className' => 'Person',
<add> 'foreignKey' => 'father_id'
<add> )
<add> );
<ide> }
<ide>
<ide> /**
<ide> class Cd extends CakeTestModel {
<ide> *
<ide> * @var array
<ide> */
<del> public $hasOne = array('OverallFavorite' => array('foreignKey' => 'model_id', 'dependent' => true, 'conditions' => array('model_type' => 'Cd')));
<add> public $hasOne = array(
<add> 'OverallFavorite' => array(
<add> 'foreignKey' => 'model_id',
<add> 'dependent' => true,
<add> 'conditions' => array('model_type' => 'Cd')
<add> )
<add> );
<add>
<ide> }
<ide>
<ide> /**
<ide> class Book extends CakeTestModel {
<ide> *
<ide> * @var array
<ide> */
<del> public $hasOne = array('OverallFavorite' => array('foreignKey' => 'model_id', 'dependent' => true, 'conditions' => 'OverallFavorite.model_type = \'Book\''));
<add> public $hasOne = array(
<add> 'OverallFavorite' => array(
<add> 'foreignKey' => 'model_id',
<add> 'dependent' => true,
<add> 'conditions' => 'OverallFavorite.model_type = \'Book\''
<add> )
<add> );
<add>
<ide> }
<ide>
<ide> /**
<ide> class NumberTree extends CakeTestModel {
<ide> * @param bool $hierachial
<ide> * @return void
<ide> */
<del> public function initialize($levelLimit = 3, $childLimit = 3, $currentLevel = null, $parent_id = null, $prefix = '1', $hierachial = true) {
<del> if (!$parent_id) {
<add> public function initialize($levelLimit = 3, $childLimit = 3, $currentLevel = null, $parentId = null, $prefix = '1', $hierachial = true) {
<add> if (!$parentId) {
<ide> $db = ConnectionManager::getDataSource($this->useDbConfig);
<ide> $db->truncate($this->table);
<ide> $this->save(array($this->name => array('name' => '1. Root')));
<ide> public function initialize($levelLimit = 3, $childLimit = 3, $currentLevel = nul
<ide>
<ide> if ($hierachial) {
<ide> if ($this->name == 'UnconventionalTree') {
<del> $data[$this->name]['join'] = $parent_id;
<add> $data[$this->name]['join'] = $parentId;
<ide> } else {
<del> $data[$this->name]['parent_id'] = $parent_id;
<add> $data[$this->name]['parent_id'] = $parentId;
<ide> }
<ide> }
<ide> $this->save($data);
<ide> $this->initialize($levelLimit, $childLimit, $currentLevel + 1, $this->id, $name, $hierachial);
<ide> }
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> class UnconventionalTree extends NumberTree {
<ide> * @var string 'FlagTree'
<ide> */
<ide> public $name = 'UnconventionalTree';
<add>
<ide> public $actsAs = array(
<ide> 'Tree' => array(
<ide> 'parent' => 'join',
<ide> 'left' => 'left',
<ide> 'right' => 'right'
<ide> )
<ide> );
<add>
<ide> }
<ide>
<ide> /**
<ide> public function afterSave($created) {
<ide> $this->data['AfterTree']['name'] = 'Six and One Half Changed in AfterTree::afterSave() but not in database';
<ide> }
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> class ContentAccount extends CakeTestModel {
<ide> * @package Cake.Test.Case.Model
<ide> */
<ide> class FilmFile extends CakeTestModel {
<add>
<ide> public $name = 'FilmFile';
<add>
<ide> }
<ide>
<ide> /**
<ide> class FilmFile extends CakeTestModel {
<ide> * @package Cake.Test.Case.Model
<ide> */
<ide> class Basket extends CakeTestModel {
<add>
<ide> public $name = 'Basket';
<ide>
<ide> public $belongsTo = array(
<ide> class Basket extends CakeTestModel {
<ide> 'order' => ''
<ide> )
<ide> );
<add>
<ide> }
<ide>
<ide> /**
<ide> class TranslateTestModel extends CakeTestModel {
<ide> * @package Cake.Test.Case.Model
<ide> */
<ide> class TranslateWithPrefix extends CakeTestModel {
<add>
<ide> /**
<ide> * name property
<ide> *
<ide> * @var string 'TranslateTestModel'
<ide> */
<ide> public $name = 'TranslateWithPrefix';
<add>
<ide> /**
<ide> * tablePrefix property
<ide> *
<ide> * @var string 'i18n'
<ide> */
<ide> public $tablePrefix = 'i18n_';
<add>
<ide> /**
<ide> * displayField property
<ide> *
<ide> * @var string 'field'
<ide> */
<ide> public $displayField = 'field';
<add>
<ide> }
<add>
<ide> /**
<ide> * TranslatedItem class.
<ide> *
<ide> class TranslatedItem extends CakeTestModel {
<ide> * @var string 'TranslateTestModel'
<ide> */
<ide> public $translateModel = 'TranslateTestModel';
<add>
<ide> }
<ide>
<ide> /**
<ide> class TranslatedItem extends CakeTestModel {
<ide> * @package Cake.Test.Case.Model
<ide> */
<ide> class TranslatedItem2 extends CakeTestModel {
<add>
<ide> /**
<ide> * name property
<ide> *
<ide> * @var string 'TranslatedItem'
<ide> */
<ide> public $name = 'TranslatedItem';
<add>
<ide> /**
<ide> * cacheQueries property
<ide> *
<ide> * @var bool false
<ide> */
<ide> public $cacheQueries = false;
<add>
<ide> /**
<ide> * actsAs property
<ide> *
<ide> * @var array
<ide> */
<ide> public $actsAs = array('Translate' => array('content', 'title'));
<add>
<ide> /**
<ide> * translateModel property
<ide> *
<ide> * @var string 'TranslateTestModel'
<ide> */
<ide> public $translateModel = 'TranslateWithPrefix';
<add>
<ide> }
<add>
<ide> /**
<ide> * TranslatedItemWithTable class.
<ide> *
<ide> class TranslatedItemWithTable extends CakeTestModel {
<ide> * @var string 'another_i18n'
<ide> */
<ide> public $translateTable = 'another_i18n';
<add>
<ide> }
<ide>
<ide> /**
<ide> class TranslateArticleModel extends CakeTestModel {
<ide> * @var string 'field'
<ide> */
<ide> public $displayField = 'field';
<add>
<ide> }
<ide>
<ide> /**
<ide> class TranslatedArticle extends CakeTestModel {
<ide> * @var array
<ide> */
<ide> public $belongsTo = array('User');
<add>
<ide> }
<ide>
<ide> class CounterCacheUser extends CakeTestModel {
<add>
<ide> public $name = 'CounterCacheUser';
<add>
<ide> public $alias = 'User';
<ide>
<del> public $hasMany = array('Post' => array(
<del> 'className' => 'CounterCachePost',
<del> 'foreignKey' => 'user_id'
<del> ));
<add> public $hasMany = array(
<add> 'Post' => array(
<add> 'className' => 'CounterCachePost',
<add> 'foreignKey' => 'user_id'
<add> )
<add> );
<ide> }
<ide>
<ide> class CounterCachePost extends CakeTestModel {
<add>
<ide> public $name = 'CounterCachePost';
<add>
<ide> public $alias = 'Post';
<ide>
<del> public $belongsTo = array('User' => array(
<del> 'className' => 'CounterCacheUser',
<del> 'foreignKey' => 'user_id',
<del> 'counterCache' => true
<del> ));
<add> public $belongsTo = array(
<add> 'User' => array(
<add> 'className' => 'CounterCacheUser',
<add> 'foreignKey' => 'user_id',
<add> 'counterCache' => true
<add> )
<add> );
<ide> }
<ide>
<ide> class CounterCacheUserNonstandardPrimaryKey extends CakeTestModel {
<add>
<ide> public $name = 'CounterCacheUserNonstandardPrimaryKey';
<add>
<ide> public $alias = 'User';
<add>
<ide> public $primaryKey = 'uid';
<ide>
<del> public $hasMany = array('Post' => array(
<del> 'className' => 'CounterCachePostNonstandardPrimaryKey',
<del> 'foreignKey' => 'uid'
<del> ));
<add> public $hasMany = array(
<add> 'Post' => array(
<add> 'className' => 'CounterCachePostNonstandardPrimaryKey',
<add> 'foreignKey' => 'uid'
<add> )
<add> );
<add>
<ide> }
<ide>
<ide> class CounterCachePostNonstandardPrimaryKey extends CakeTestModel {
<add>
<ide> public $name = 'CounterCachePostNonstandardPrimaryKey';
<add>
<ide> public $alias = 'Post';
<add>
<ide> public $primaryKey = 'pid';
<ide>
<del> public $belongsTo = array('User' => array(
<del> 'className' => 'CounterCacheUserNonstandardPrimaryKey',
<del> 'foreignKey' => 'uid',
<del> 'counterCache' => true
<del> ));
<add> public $belongsTo = array(
<add> 'User' => array(
<add> 'className' => 'CounterCacheUserNonstandardPrimaryKey',
<add> 'foreignKey' => 'uid',
<add> 'counterCache' => true
<add> )
<add> );
<add>
<ide> }
<ide>
<ide> class ArticleB extends CakeTestModel {
<add>
<ide> public $name = 'ArticleB';
<add>
<ide> public $useTable = 'articles';
<add>
<ide> public $hasAndBelongsToMany = array(
<ide> 'TagB' => array(
<ide> 'className' => 'TagB',
<ide> class ArticleB extends CakeTestModel {
<ide> 'associationForeignKey' => 'tag_id'
<ide> )
<ide> );
<add>
<ide> }
<ide>
<ide> class TagB extends CakeTestModel {
<add>
<ide> public $name = 'TagB';
<add>
<ide> public $useTable = 'tags';
<add>
<ide> public $hasAndBelongsToMany = array(
<ide> 'ArticleB' => array(
<ide> 'className' => 'ArticleB',
<ide> class TagB extends CakeTestModel {
<ide> 'associationForeignKey' => 'article_id'
<ide> )
<ide> );
<add>
<ide> }
<ide>
<ide> class Fruit extends CakeTestModel {
<add>
<ide> public $name = 'Fruit';
<add>
<ide> public $hasAndBelongsToMany = array(
<ide> 'UuidTag' => array(
<ide> 'className' => 'UuidTag',
<ide> class Fruit extends CakeTestModel {
<ide> 'with' => 'FruitsUuidTag'
<ide> )
<ide> );
<add>
<ide> }
<ide>
<ide> class FruitsUuidTag extends CakeTestModel {
<add>
<ide> public $name = 'FruitsUuidTag';
<add>
<ide> public $primaryKey = false;
<add>
<ide> public $belongsTo = array(
<ide> 'UuidTag' => array(
<ide> 'className' => 'UuidTag',
<ide> class FruitsUuidTag extends CakeTestModel {
<ide> 'foreignKey' => 'fruit_id',
<ide> )
<ide> );
<add>
<ide> }
<ide>
<ide> class UuidTag extends CakeTestModel {
<add>
<ide> public $name = 'UuidTag';
<add>
<ide> public $hasAndBelongsToMany = array(
<ide> 'Fruit' => array(
<ide> 'className' => 'Fruit',
<ide> class UuidTag extends CakeTestModel {
<ide> 'with' => 'FruitsUuidTag'
<ide> )
<ide> );
<add>
<ide> }
<ide>
<ide> class FruitNoWith extends CakeTestModel {
<add>
<ide> public $name = 'Fruit';
<add>
<ide> public $useTable = 'fruits';
<add>
<ide> public $hasAndBelongsToMany = array(
<ide> 'UuidTag' => array(
<ide> 'className' => 'UuidTagNoWith',
<ide> class FruitNoWith extends CakeTestModel {
<ide> 'associationForeignKey' => 'uuid_tag_id',
<ide> )
<ide> );
<add>
<ide> }
<ide>
<ide> class UuidTagNoWith extends CakeTestModel {
<add>
<ide> public $name = 'UuidTag';
<add>
<ide> public $useTable = 'uuid_tags';
<add>
<ide> public $hasAndBelongsToMany = array(
<ide> 'Fruit' => array(
<ide> 'className' => 'FruitNoWith',
<ide> class UuidTagNoWith extends CakeTestModel {
<ide> 'associationForeignKey' => 'fruit_id',
<ide> )
<ide> );
<add>
<ide> }
<ide>
<ide> class ProductUpdateAll extends CakeTestModel {
<add>
<ide> public $name = 'ProductUpdateAll';
<add>
<ide> public $useTable = 'product_update_all';
<ide>
<ide> }
<ide>
<ide> class GroupUpdateAll extends CakeTestModel {
<add>
<ide> public $name = 'GroupUpdateAll';
<add>
<ide> public $useTable = 'group_update_all';
<add>
<ide> }
<ide>
<ide> class TransactionTestModel extends CakeTestModel {
<add>
<ide> public $name = 'TransactionTestModel';
<add>
<ide> public $useTable = 'samples';
<ide>
<ide> public function afterSave($created) {
<ide> public function afterSave($created) {
<ide> );
<ide> $this->saveAll($data, array('atomic' => true, 'callbacks' => false));
<ide> }
<add>
<ide> }
<ide>
<ide> class TransactionManyTestModel extends CakeTestModel {
<add>
<ide> public $name = 'TransactionManyTestModel';
<add>
<ide> public $useTable = 'samples';
<ide>
<ide> public function afterSave($created) {
<ide> public function afterSave($created) {
<ide> );
<ide> $this->saveMany($data, array('atomic' => true, 'callbacks' => false));
<ide> }
<add>
<ide> }
<ide>
<ide> class Site extends CakeTestModel {
<add>
<ide> public $name = 'Site';
<add>
<ide> public $useTable = 'sites';
<ide>
<ide> public $hasAndBelongsToMany = array(
<ide> 'Domain' => array('unique' => 'keepExisting'),
<del> );
<add> );
<ide> }
<ide>
<ide> class Domain extends CakeTestModel {
<add>
<ide> public $name = 'Domain';
<add>
<ide> public $useTable = 'domains';
<ide>
<ide> public $hasAndBelongsToMany = array(
<ide> 'Site' => array('unique' => 'keepExisting'),
<del> );
<add> );
<ide> }
<ide>
<ide> /**
<ide> public function find($conditions = null, $fields = null, $order = null, $recursi
<ide> public function findAll($conditions = null, $fields = null, $order = null, $recursive = null) {
<ide> return $conditions;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function schema($field = false) {
<ide> }
<ide> return $this->_schema;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function schema($field = false) {
<ide> }
<ide> return $this->_schema;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function schema($field = false) {
<ide> }
<ide> return $this->_schema;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> class TestModel6 extends CakeTestModel {
<ide> *
<ide> * @var array
<ide> */
<del> public $belongsTo = array('TestModel5' => array(
<del> 'className' => 'TestModel5',
<del> 'foreignKey' => 'test_model5_id'
<del> ));
<add> public $belongsTo = array(
<add> 'TestModel5' => array(
<add> 'className' => 'TestModel5',
<add> 'foreignKey' => 'test_model5_id'
<add> )
<add> );
<ide>
<ide> /**
<ide> * schema method
<ide> public function schema($field = false) {
<ide> }
<ide> return $this->_schema;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function schema($field = false) {
<ide> }
<ide> return $this->_schema;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function schema($field = false) {
<ide> }
<ide> return $this->_schema;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> class TestModel9 extends CakeTestModel {
<ide> *
<ide> * @var array
<ide> */
<del> public $belongsTo = array('TestModel8' => array(
<del> 'className' => 'TestModel8',
<del> 'foreignKey' => 'test_model8_id',
<del> 'conditions' => 'TestModel8.name != \'larry\''
<del> ));
<add> public $belongsTo = array(
<add> 'TestModel8' => array(
<add> 'className' => 'TestModel8',
<add> 'foreignKey' => 'test_model8_id',
<add> 'conditions' => 'TestModel8.name != \'larry\''
<add> )
<add> );
<ide>
<ide> /**
<ide> * schema method
<ide> public function schema($field = false) {
<ide> }
<ide> return $this->_schema;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function schema($field = false) {
<ide> }
<ide> return $this->_schema;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function schema($field = false) {
<ide> }
<ide> return $this->_schema;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function schema($field = false) {
<ide> }
<ide> return $this->_schema;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function schema($field = false) {
<ide> }
<ide> return $this->_schema;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function schema($field = false) {
<ide> }
<ide> return $this->_schema;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function schema($field = false) {
<ide> }
<ide> return $this->_schema;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function schema($field = false) {
<ide> }
<ide> return $this->_schema;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function schema($field = false) {
<ide> }
<ide> return $this->_schema;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function findAll($conditions = null, $fields = null, $order = null, $recu
<ide> */
<ide> public function schema($field = false) {
<ide> return array(
<del> 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'),
<del> 'client_id' => array('type' => 'integer', 'null' => '', 'default' => '0', 'length' => '11'),
<del> 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'),
<del> 'login' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'),
<del> 'passwd' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'),
<del> 'addr_1' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'),
<del> 'addr_2' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '25'),
<del> 'zip_code' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
<del> 'city' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
<del> 'country' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
<del> 'phone' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
<del> 'fax' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
<del> 'url' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'),
<del> 'email' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
<del> 'comments' => array('type' => 'text', 'null' => '1', 'default' => '', 'length' => ''),
<del> 'last_login'=> array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => ''),
<del> 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''),
<del> 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null)
<add> 'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'),
<add> 'client_id' => array('type' => 'integer', 'null' => '', 'default' => '0', 'length' => '11'),
<add> 'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'),
<add> 'login' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'),
<add> 'passwd' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'),
<add> 'addr_1' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'),
<add> 'addr_2' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '25'),
<add> 'zip_code' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
<add> 'city' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
<add> 'country' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
<add> 'phone' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
<add> 'fax' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
<add> 'url' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'),
<add> 'email' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
<add> 'comments' => array('type' => 'text', 'null' => '1', 'default' => '', 'length' => ''),
<add> 'last_login' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => ''),
<add> 'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''),
<add> 'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null)
<ide> );
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function schema($field = false) {
<ide> */
<ide> class PrefixTestModel extends CakeTestModel {
<ide> }
<add>
<ide> class PrefixTestUseTableModel extends CakeTestModel {
<add>
<ide> public $name = 'PrefixTest';
<add>
<ide> public $useTable = 'prefix_tests';
<add>
<ide> }
<ide>
<ide> /**
<ide> class ScaffoldMock extends CakeTestModel {
<ide> 'foreignKey' => 'article_id',
<ide> )
<ide> );
<add>
<ide> /**
<ide> * hasAndBelongsToMany property
<ide> *
<ide> class ScaffoldMock extends CakeTestModel {
<ide> 'joinTable' => 'join_things'
<ide> )
<ide> );
<add>
<ide> }
<ide>
<ide> /**
<ide> class ScaffoldComment extends CakeTestModel {
<ide> * @package Cake.Test.Case.Controller
<ide> */
<ide> class ScaffoldTag extends CakeTestModel {
<add>
<ide> /**
<ide> * useTable property
<ide> *
<ide> * @var string 'posts'
<ide> */
<ide> public $useTable = 'tags';
<add>
<ide> }
<ide>
<ide> /**
<ide> class ScaffoldTag extends CakeTestModel {
<ide> * @package Cake.Test.Case.Model
<ide> */
<ide> class Player extends CakeTestModel {
<add>
<ide> public $hasAndBelongsToMany = array(
<ide> 'Guild' => array(
<ide> 'with' => 'GuildsPlayer',
<ide> 'unique' => true,
<del> ),
<del> );
<add> ),
<add> );
<add>
<ide> }
<ide>
<ide> /**
<ide> class Player extends CakeTestModel {
<ide> * @package Cake.Test.Case.Model
<ide> */
<ide> class Guild extends CakeTestModel {
<add>
<ide> public $hasAndBelongsToMany = array(
<ide> 'Player' => array(
<ide> 'with' => 'GuildsPlayer',
<ide> 'unique' => true,
<del> ),
<del> );
<add> ),
<add> );
<add>
<ide> }
<ide>
<ide> /**
<ide> class ArmorsPlayer extends CakeTestModel {
<ide> * @package Cake.Test.Case.Model
<ide> */
<ide> class CustomArticle extends AppModel {
<add>
<ide> /**
<ide> * useTable property
<ide> *
<ide> class CustomArticle extends AppModel {
<ide> *
<ide> * @return array
<ide> */
<del> public function _findUnPublished($state, $query, $results = array()) {
<del> if ($state === 'before') {
<del> $query['conditions']['published'] = 'N';
<del> return $query;
<del> }
<del> return $results;
<add> protected function _findUnPublished($state, $query, $results = array()) {
<add> if ($state === 'before') {
<add> $query['conditions']['published'] = 'N';
<add> return $query;
<add> }
<add> return $results;
<ide> }
<ide>
<del>}
<ide>\ No newline at end of file
<add>} | 12 |
PHP | PHP | add doc about the new serialize setting | d099c5ad7e511789355c36ab09691c8839ec0f5f | <ide><path>lib/Cake/Cache/Engine/MemcachedEngine.php
<ide> class MemcachedEngine extends CacheEngine {
<ide> * - compress = boolean, default => false
<ide> * - persistent = string The name of the persistent connection. All configurations using
<ide> * the same persistent value will share a single underlying connection.
<add> * - serialize = string, default => php. The serializer engine used to serialize data.
<add> * Available engines are php, igbinary and json. Beside php, the memcached extension
<add> * must be compiled with the appropriate serializer support.
<ide> *
<ide> * @var array
<ide> */ | 1 |
Text | Text | fix broken links in spanish challenges | 8bf15ba060337eebf484cf7f7e91ade1b5012a8f | <ide><path>curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/assignment-with-a-returned-value.spanish.md
<ide> localeTitle: Asignación con un valor devuelto
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> Si recuerda de nuestra discusión sobre el <a href="javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator" target="_blank">almacenamiento de valores con el operador de asignación</a> , todo a la derecha del signo igual se resuelve antes de que se asigne el valor. Esto significa que podemos tomar el valor de retorno de una función y asignarlo a una variable. Supongamos que hemos predefinido una <code>sum</code> función que suma dos números, entonces: <code>ourSum = sum(5, 12);</code> <code>ourSum</code> a la función <code>sum</code> , que devuelve un valor de <code>17</code> y lo asigna a <code>ourSum</code> variable <code>ourSum</code> </section>
<add><section id="description"> Si recuerda de nuestra discusión sobre el <a href="learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator" target="_blank">almacenamiento de valores con el operador de asignación</a> , todo a la derecha del signo igual se resuelve antes de que se asigne el valor. Esto significa que podemos tomar el valor de retorno de una función y asignarlo a una variable. Supongamos que hemos predefinido una <code>sum</code> función que suma dos números, entonces: <code>ourSum = sum(5, 12);</code> <code>ourSum</code> a la función <code>sum</code> , que devuelve un valor de <code>17</code> y lo asigna a <code>ourSum</code> variable <code>ourSum</code> </section>
<ide>
<ide> ## Instructions
<ide> <section id="instructions"> Llame a la función <code>processArg</code> con un argumento de <code>7</code> y asigne su valor de retorno a la variable <code>processed</code> . </section>
<ide><path>curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/generate-random-fractions-with-javascript.spanish.md
<ide> localeTitle: Generar fracciones aleatorias con JavaScript
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> Los números aleatorios son útiles para crear un comportamiento aleatorio. JavaScript tiene una función <code>Math.random()</code> que genera un número decimal aleatorio entre <code>0</code> (incluido) y no hasta <code>1</code> (exclusivo). Por <code>Math.random()</code> tanto, <code>Math.random()</code> puede devolver un <code>0</code> pero nunca devolver una <code>1</code> <strong>Nota</strong> <br> Al igual que el <a href="storing-values-with-the-assignment-operator" target="_blank">almacenamiento de valores con el operador igual</a> , todas las llamadas de función se resolverán antes de que se ejecute la <code>return</code> , por lo que podemos <code>return</code> el valor de la función <code>Math.random()</code> . </section>
<add><section id="description"> Los números aleatorios son útiles para crear un comportamiento aleatorio. JavaScript tiene una función <code>Math.random()</code> que genera un número decimal aleatorio entre <code>0</code> (incluido) y no hasta <code>1</code> (exclusivo). Por <code>Math.random()</code> tanto, <code>Math.random()</code> puede devolver un <code>0</code> pero nunca devolver una <code>1</code> <strong>Nota</strong> <br> Al igual que el <a href="learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator" target="_blank">almacenamiento de valores con el operador igual</a> , todas las llamadas de función se resolverán antes de que se ejecute la <code>return</code> , por lo que podemos <code>return</code> el valor de la función <code>Math.random()</code> . </section>
<ide>
<ide> ## Instructions
<ide> <section id="instructions"> Cambie <code>randomFraction</code> para devolver un número aleatorio en lugar de devolver <code>0</code> . </section>
<ide><path>curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/record-collection.spanish.md
<ide> localeTitle: Colección de discos
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> Te dan un objeto JSON que representa una parte de tu colección de álbumes musicales. Cada álbum tiene varias propiedades y un número de identificación único como clave. No todos los álbumes tienen información completa. Escriba una función que tome la <code>id</code> un álbum (como <code>2548</code> ), una propiedad <code>prop</code> (como <code>"artist"</code> o <code>"tracks"</code> ) y un <code>value</code> (como <code>"Addicted to Love"</code> ) para modificar los datos de esta colección. Si <code>prop</code> no es <code>"tracks"</code> y el <code>value</code> no está vacío ( <code>""</code> ), actualice o establezca el <code>value</code> para la propiedad del álbum de grabación. Su función debe devolver siempre el objeto de colección completo. Existen varias reglas para manejar datos incompletos: si <code>prop</code> es <code>"tracks"</code> pero el álbum no tiene una propiedad de <code>"tracks"</code> , cree una matriz vacía antes de agregar el nuevo valor a la propiedad correspondiente del álbum. Si <code>prop</code> es <code>"tracks"</code> y el <code>value</code> no está vacío ( <code>""</code> ), presione el <code>value</code> en el extremo de la matriz de <code>tracks</code> existente del <code>tracks</code> . Si el <code>value</code> está vacío ( <code>""</code> ), elimine la propiedad de <code>prop</code> determinada del álbum. <strong>Consejos</strong> <br> Utilice la <code>bracket notation</code> cuando <a href="javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-variables" target="_blank">acceda a las propiedades de objetos con variables</a> . Push es un método de matriz que puede leer sobre <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push" target="_blank">Mozilla Developer Network</a> . Puede volver a consultar <a href="javascript-algorithms-and-data-structures/basic-javascript/manipulating-complex-objects" target="_blank">Manipular objetos complejos</a> presentando la notación de objetos de JavaScript (JSON) para obtener una actualización. </section>
<add><section id="description"> Te dan un objeto JSON que representa una parte de tu colección de álbumes musicales. Cada álbum tiene varias propiedades y un número de identificación único como clave. No todos los álbumes tienen información completa. Escriba una función que tome la <code>id</code> un álbum (como <code>2548</code> ), una propiedad <code>prop</code> (como <code>"artist"</code> o <code>"tracks"</code> ) y un <code>value</code> (como <code>"Addicted to Love"</code> ) para modificar los datos de esta colección. Si <code>prop</code> no es <code>"tracks"</code> y el <code>value</code> no está vacío ( <code>""</code> ), actualice o establezca el <code>value</code> para la propiedad del álbum de grabación. Su función debe devolver siempre el objeto de colección completo. Existen varias reglas para manejar datos incompletos: si <code>prop</code> es <code>"tracks"</code> pero el álbum no tiene una propiedad de <code>"tracks"</code> , cree una matriz vacía antes de agregar el nuevo valor a la propiedad correspondiente del álbum. Si <code>prop</code> es <code>"tracks"</code> y el <code>value</code> no está vacío ( <code>""</code> ), presione el <code>value</code> en el extremo de la matriz de <code>tracks</code> existente del <code>tracks</code> . Si el <code>value</code> está vacío ( <code>""</code> ), elimine la propiedad de <code>prop</code> determinada del álbum. <strong>Consejos</strong> <br> Utilice la <code>bracket notation</code> cuando <a href="javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-variables" target="_blank">acceda a las propiedades de objetos con variables</a> . Push es un método de matriz que puede leer sobre <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push" target="_blank">Mozilla Developer Network</a> . Puede volver a consultar <a href="learn/javascript-algorithms-and-data-structures/basic-javascript/manipulating-complex-objects" target="_blank">Manipular objetos complejos</a> presentando la notación de objetos de JavaScript (JSON) para obtener una actualización. </section>
<ide>
<ide> ## Instructions
<ide> <section id="instructions">
<ide><path>curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/returning-boolean-values-from-functions.spanish.md
<ide> localeTitle: Devolviendo valores booleanos desde funciones
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> De la <a href="waypoint-comparison-with-the-equality-operator" target="_blank">comparación con el operador de igualdad</a> puede recordar que todos los operadores de comparación devuelven un valor booleano <code>true</code> o <code>false</code> . A veces las personas usan una declaración if / else para hacer una comparación, como esta: <blockquote> función isEqual (a, b) { <br> si (a === b) { <br> devuelve verdadero <br> } else { <br> falso retorno; <br> } <br> } </blockquote> Pero hay una mejor manera de hacer esto. Como <code>===</code> devuelve <code>true</code> o <code>false</code> , podemos devolver el resultado de la comparación: <blockquote> función isEqual (a, b) { <br> devuelve a === b; <br> } </blockquote></section>
<add><section id="description"> De la <a href="learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator" target="_blank">comparación con el operador de igualdad</a> puede recordar que todos los operadores de comparación devuelven un valor booleano <code>true</code> o <code>false</code> . A veces las personas usan una declaración if / else para hacer una comparación, como esta: <blockquote> función isEqual (a, b) { <br> si (a === b) { <br> devuelve verdadero <br> } else { <br> falso retorno; <br> } <br> } </blockquote> Pero hay una mejor manera de hacer esto. Como <code>===</code> devuelve <code>true</code> o <code>false</code> , podemos devolver el resultado de la comparación: <blockquote> función isEqual (a, b) { <br> devuelve a === b; <br> } </blockquote></section>
<ide>
<ide> ## Instructions
<ide> <section id="instructions"> Arreglar la función <code>isLess</code> permite eliminar las sentencias <code>if/else</code> . </section>
<ide><path>curriculum/challenges/spanish/03-front-end-libraries/react/introducing-inline-styles.spanish.md
<ide> localeTitle: Introducción a los estilos en línea
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> Hay otros conceptos complejos que agregan capacidades poderosas a su código React. Pero puede que se esté preguntando sobre el problema más simple de cómo diseñar los elementos JSX que crea en React. Probablemente sepa que no será exactamente lo mismo que trabajar con HTML debido a <a target="_blank" href="front-end-libraries/react/define-an-html-class-in-jsx">la forma en que aplica las clases a los elementos JSX</a> . Si importa estilos de una hoja de estilo, no es muy diferente en absoluto. Aplicas una clase a tu elemento JSX usando el atributo <code>className</code> y aplicas estilos a la clase en tu hoja de estilo. Otra opción es aplicar estilos en <strong><em>línea</em></strong> , que son muy comunes en el desarrollo de ReactJS. Usted aplica estilos en línea a elementos JSX similares a cómo lo hace en HTML, pero con algunas diferencias JSX. Aquí hay un ejemplo de un estilo en línea en HTML: <code><div style="color: yellow; font-size: 16px">Mellow Yellow</div></code> elementos JSX usan el atributo de <code>style</code> , pero debido a la forma en que se transpila JSX, puede 't establecer el valor a una <code>string</code> . En su lugar, lo establece igual a un <code>object</code> JavaScript. Aquí hay un ejemplo: <code><div style={{color: "yellow", fontSize: 16}}>Mellow Yellow</div></code> ¿Observa cómo la propiedad "fontSize" está en <a target="_blank" href="https://es.wikipedia.org/wiki/CamelCase">camelCase</a>? Esto se debe a que React no aceptará claves de kebab en el objeto de estilo. React aplicará el nombre de propiedad correcto para nosotros en el HTML. </section>
<add><section id="description"> Hay otros conceptos complejos que agregan capacidades poderosas a su código React. Pero puede que se esté preguntando sobre el problema más simple de cómo diseñar los elementos JSX que crea en React. Probablemente sepa que no será exactamente lo mismo que trabajar con HTML debido a <a target="_blank" href="learn/front-end-libraries/react/define-an-html-class-in-jsx">la forma en que aplica las clases a los elementos JSX</a> . Si importa estilos de una hoja de estilo, no es muy diferente en absoluto. Aplicas una clase a tu elemento JSX usando el atributo <code>className</code> y aplicas estilos a la clase en tu hoja de estilo. Otra opción es aplicar estilos en <strong><em>línea</em></strong> , que son muy comunes en el desarrollo de ReactJS. Usted aplica estilos en línea a elementos JSX similares a cómo lo hace en HTML, pero con algunas diferencias JSX. Aquí hay un ejemplo de un estilo en línea en HTML: <code><div style="color: yellow; font-size: 16px">Mellow Yellow</div></code> elementos JSX usan el atributo de <code>style</code> , pero debido a la forma en que se transpila JSX, puede 't establecer el valor a una <code>string</code> . En su lugar, lo establece igual a un <code>object</code> JavaScript. Aquí hay un ejemplo: <code><div style={{color: "yellow", fontSize: 16}}>Mellow Yellow</div></code> ¿Observa cómo la propiedad "fontSize" está en <a target="_blank" href="https://es.wikipedia.org/wiki/CamelCase">camelCase</a>? Esto se debe a que React no aceptará claves de kebab en el objeto de estilo. React aplicará el nombre de propiedad correcto para nosotros en el HTML. </section>
<ide>
<ide> ## Instructions
<ide> <section id="instructions"> Agregue un atributo de <code>style</code> al <code>div</code> en el editor de código para darle al texto un color rojo y un tamaño de fuente de 72px. Tenga en cuenta que, opcionalmente, puede configurar el tamaño de fuente como un número, omitiendo las unidades "px", o escribirlo como "72px". </section> | 5 |
Ruby | Ruby | exclude pypy from unbrewed | 6370ccf9a81bbd9c0b4ddb6068a91c649529d514 | <ide><path>Library/Homebrew/cmd/list.rb
<ide> def list
<ide> lib/gio/*
<ide> lib/node_modules/*
<ide> lib/python[23].[0-9]/*
<add> lib/pypy/*
<add> lib/pypy3/*
<add> share/pypy/*
<add> share/pypy3/*
<ide> share/doc/homebrew/*
<ide> share/info/dir
<ide> share/man/man1/brew.1 | 1 |
PHP | PHP | apply fixes from styleci | e3c86b6bcecc0cfbcb5b9d5b735ad6bb3213b37d | <ide><path>tests/Integration/Database/DatabaseEloquentModelCustomCastingTest.php
<ide> public function testGetOriginalWithCastValueObjects()
<ide> $this->assertEquals('110 Kingsbrook St.', $model->getOriginal('address')->lineOne);
<ide> $this->assertEquals('117 Spencer St.', $model->address->lineOne);
<ide>
<del>
<ide> $model = new TestEloquentModelWithCustomCast([
<del> 'address' => new Address('110 Kingsbrook St.', 'My Childhood House')
<add> 'address' => new Address('110 Kingsbrook St.', 'My Childhood House'),
<ide> ]);
<ide>
<ide> $model->syncOriginal();
<ide> public function testGetOriginalWithCastValueObjects()
<ide> $this->assertEquals('110 Kingsbrook St.', $model->getOriginal()['address_line_one']);
<ide> $this->assertEquals('117 Spencer St.', $model->address->lineOne);
<ide>
<del>
<ide> $model = new TestEloquentModelWithCustomCast([
<ide> 'address' => new Address('110 Kingsbrook St.', 'My Childhood House'),
<ide> ]); | 1 |
Ruby | Ruby | add test to 57daaef | add9500eb8d373407bf379d5ab8d833a055a07cd | <ide><path>activerecord/test/cases/relation/delegation_test.rb
<ide> def call_method(target, method)
<ide> module DelegationWhitelistBlacklistTests
<ide> ARRAY_DELEGATES = [
<ide> :+, :-, :|, :&, :[],
<del> :all?, :collect, :detect, :each, :each_cons, :each_with_index,
<add> :all?, :collect, :compact, :detect, :each, :each_cons, :each_with_index,
<ide> :exclude?, :find_all, :flat_map, :group_by, :include?, :length,
<ide> :map, :none?, :one?, :partition, :reject, :reverse,
<ide> :sample, :second, :sort, :sort_by, :third, | 1 |
Javascript | Javascript | simplify isidentityunicode detection | f82977caf9b09b970b520c8cb2822a102ac19b38 | <ide><path>src/core/fonts.js
<ide> var Font = (function FontClosure() {
<ide> this.descent = properties.descent / PDF_GLYPH_SPACE_UNITS;
<ide> this.fontMatrix = properties.fontMatrix;
<ide>
<del> var unicode = this.buildToUnicode(properties);
<del> this.toUnicode = properties.toUnicode = unicode.toUnicode;
<del> this.isIdentityUnicode = properties.isIdentityUnicode = unicode.isIdentity;
<add> this.toUnicode = properties.toUnicode = this.buildToUnicode(properties);
<ide>
<ide> this.toFontChar = [];
<ide>
<ide> var Font = (function FontClosure() {
<ide> function adjustMapping(charCodeToGlyphId, properties) {
<ide> var toUnicode = properties.toUnicode;
<ide> var isSymbolic = !!(properties.flags & FontFlags.Symbolic);
<del> var isIdentityUnicode = properties.isIdentityUnicode;
<add> var isIdentityUnicode =
<add> properties.toUnicode instanceof IdentityToUnicodeMap;
<ide> var isCidFontType2 = (properties.type === 'CIDFontType2');
<ide> var newMap = Object.create(null);
<ide> var toFontChar = [];
<ide> var Font = (function FontClosure() {
<ide> /**
<ide> * Builds a char code to unicode map based on section 9.10 of the spec.
<ide> * @param {Object} properties Font properties object.
<del> * @return {Object} Has two properties: 'toUnicode' which maps char codes to
<del> * unicode (string) values and 'isIdentity' which is true if an identity map
<del> * is used.
<add> * @return {Object} A ToUnicodeMap object.
<ide> */
<ide> buildToUnicode: function Font_buildToUnicode(properties) {
<del> var map = {
<del> isIdentity: false,
<del> toUnicode: null
<del> };
<ide> // Section 9.10.2 Mapping Character Codes to Unicode Values
<ide> if (properties.toUnicode && properties.toUnicode.length !== 0) {
<del> map.toUnicode = properties.toUnicode;
<del> return map;
<add> return properties.toUnicode;
<ide> }
<ide> // According to the spec if the font is a simple font we should only map
<ide> // to unicode if the base encoding is MacRoman, MacExpert, or WinAnsi or
<ide> var Font = (function FontClosure() {
<ide> }
<ide> toUnicode[charcode] = String.fromCharCode(GlyphsUnicode[glyphName]);
<ide> }
<del> map.toUnicode = new ToUnicodeMap(toUnicode);
<del> return map;
<add> return new ToUnicodeMap(toUnicode);
<ide> }
<ide> // If the font is a composite font that uses one of the predefined CMaps
<ide> // listed in Table 118 (except Identity–H and Identity–V) or whose
<ide> var Font = (function FontClosure() {
<ide> ucs2.charCodeAt(1));
<ide> }
<ide> });
<del> map.toUnicode = new ToUnicodeMap(toUnicode);
<del> return map;
<add> return new ToUnicodeMap(toUnicode);
<ide> }
<ide>
<ide> // The viewer's choice, just use an identity map.
<del> map.isIdentity = true;
<del> map.toUnicode =
<del> new IdentityToUnicodeMap(properties.firstChar, properties.lastChar);
<del> return map;
<add> return new IdentityToUnicodeMap(properties.firstChar,
<add> properties.lastChar);
<ide> },
<ide>
<ide> get spaceWidth() { | 1 |
Javascript | Javascript | clarify dropmembership() call | 226b8e0cf8374a0074142145858fa0aa94bca3ce | <ide><path>test/internet/test-dgram-multicast-multi-process.js
<ide> var common = require('../common'),
<ide> assert = require('assert'),
<ide> dgram = require('dgram'),
<ide> util = require('util'),
<del> assert = require('assert'),
<ide> Buffer = require('buffer').Buffer,
<ide> fork = require('child_process').fork,
<ide> LOCAL_BROADCAST_HOST = '224.0.0.114',
<ide> if (process.argv[2] === 'child') {
<ide> process.send({ message: buf.toString() });
<ide>
<ide> if (receivedMessages.length == messages.length) {
<add> // .dropMembership() not strictly needed but here as a sanity check
<ide> listenSocket.dropMembership(LOCAL_BROADCAST_HOST);
<del>
<del> process.nextTick(function() { // TODO should be changed to below.
<del> // listenSocket.dropMembership(LOCAL_BROADCAST_HOST, function() {
<add> process.nextTick(function() {
<ide> listenSocket.close();
<ide> });
<ide> } | 1 |
PHP | PHP | hastable | 1c1f2f2d87876be86fc1ce98efa0f2bc1a3670f6 | <ide><path>src/Illuminate/Database/PostgresConnection.php
<ide>
<ide> namespace Illuminate\Database;
<ide>
<add>use Illuminate\Database\Schema\PostgresBuilder;
<ide> use Doctrine\DBAL\Driver\PDOPgSql\Driver as DoctrineDriver;
<ide> use Illuminate\Database\Query\Processors\PostgresProcessor;
<ide> use Illuminate\Database\Query\Grammars\PostgresGrammar as QueryGrammar;
<ide> use Illuminate\Database\Schema\Grammars\PostgresGrammar as SchemaGrammar;
<ide>
<ide> class PostgresConnection extends Connection
<ide> {
<add> /**
<add> * Get a schema builder instance for the connection.
<add> *
<add> * @return \Illuminate\Database\Schema\PostgresBuilder
<add> */
<add> public function getSchemaBuilder()
<add> {
<add> if (is_null($this->schemaGrammar)) {
<add> $this->useDefaultSchemaGrammar();
<add> }
<add>
<add> return new PostgresBuilder($this);
<add> }
<add>
<ide> /**
<ide> * Get the default query grammar instance.
<ide> *
<ide><path>src/Illuminate/Database/Schema/Grammars/PostgresGrammar.php
<ide> class PostgresGrammar extends Grammar
<ide> */
<ide> public function compileTableExists()
<ide> {
<del> return 'select * from information_schema.tables where table_name = ?';
<add> return 'select * from information_schema.tables where table_schema = ? and table_name = ?';
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Database/Schema/PostgresBuilder.php
<add><?php
<add>
<add>namespace Illuminate\Database\Schema;
<add>
<add>class PostgresBuilder extends Builder
<add>{
<add> /**
<add> * Determine if the given table exists.
<add> *
<add> * @param string $table
<add> * @return bool
<add> */
<add> public function hasTable($table)
<add> {
<add> $sql = $this->grammar->compileTableExists();
<add>
<add> $schema = $this->connection->getConfig('schema');
<add>
<add> $table = $this->connection->getTablePrefix().$table;
<add>
<add> return count($this->connection->select($sql, [$schema, $table])) > 0;
<add> }
<add>} | 3 |
Javascript | Javascript | remove copying of jquery-latest files | c34ed46eee12c92cb050a53eb62daf9e1258caf9 | <ide><path>build/release.js
<ide> module.exports = function( Release ) {
<ide> releaseFiles = {
<ide> "jquery-VER.js": devFile,
<ide> "jquery-VER.min.js": minFile,
<del> "jquery-VER.min.map": mapFile //,
<del>// Disable these until 2.0 defeats 1.9 as the ONE TRUE JQUERY
<del> // "jquery.js": devFile,
<del> // "jquery.min.js": minFile,
<del> // "jquery.min.map": mapFile,
<del> // "jquery-latest.js": devFile,
<del> // "jquery-latest.min.js": minFile,
<del> // "jquery-latest.min.map": mapFile
<add> "jquery-VER.min.map": mapFile
<ide> },
<ide>
<ide> googleFilesCDN = [
<ide> module.exports = function( Release ) {
<ide> unpathedFile = key.replace( /VER/g, Release.newVersion ),
<ide> releaseFile = cdnFolder + "/" + unpathedFile;
<ide>
<del> // Beta releases don't update the jquery-latest etc. copies
<del> if ( !Release.preRelease || key.indexOf( "VER" ) >= 0 ) {
<del>
<del> if ( /\.map$/.test( releaseFile ) ) {
<del> // Map files need to reference the new uncompressed name;
<del> // assume that all files reside in the same directory.
<del> // "file":"jquery.min.js","sources":["jquery.js"]
<del> text = fs.readFileSync( builtFile, "utf8" )
<del> .replace( /"file":"([^"]+)","sources":\["([^"]+)"\]/,
<del> "\"file\":\"" + unpathedFile.replace( /\.min\.map/, ".min.js" ) +
<del> "\",\"sources\":[\"" + unpathedFile.replace( /\.min\.map/, ".js" ) + "\"]" );
<del> fs.writeFileSync( releaseFile, text );
<del> } else if ( /\.min\.js$/.test( releaseFile ) ) {
<del> // Remove the source map comment; it causes way too many problems.
<del> // Keep the map file in case DevTools allow manual association.
<del> text = fs.readFileSync( builtFile, "utf8" )
<del> .replace( /\/\/# sourceMappingURL=\S+/, "" );
<del> fs.writeFileSync( releaseFile, text );
<del> } else if ( builtFile !== releaseFile ) {
<del> shell.cp( "-f", builtFile, releaseFile );
<del> }
<add> if ( /\.map$/.test( releaseFile ) ) {
<add> // Map files need to reference the new uncompressed name;
<add> // assume that all files reside in the same directory.
<add> // "file":"jquery.min.js","sources":["jquery.js"]
<add> text = fs.readFileSync( builtFile, "utf8" )
<add> .replace( /"file":"([^"]+)","sources":\["([^"]+)"\]/,
<add> "\"file\":\"" + unpathedFile.replace( /\.min\.map/, ".min.js" ) +
<add> "\",\"sources\":[\"" + unpathedFile.replace( /\.min\.map/, ".js" ) + "\"]" );
<add> fs.writeFileSync( releaseFile, text );
<add> } else if ( /\.min\.js$/.test( releaseFile ) ) {
<add> // Remove the source map comment; it causes way too many problems.
<add> // Keep the map file in case DevTools allow manual association.
<add> text = fs.readFileSync( builtFile, "utf8" )
<add> .replace( /\/\/# sourceMappingURL=\S+/, "" );
<add> fs.writeFileSync( releaseFile, text );
<add> } else if ( builtFile !== releaseFile ) {
<add> shell.cp( "-f", builtFile, releaseFile );
<ide> }
<ide> });
<ide> } | 1 |
Python | Python | fix mypy for exasol and facebook hooks | cdd2ba032aa27b496c0e2cfa06ba45569d393401 | <ide><path>airflow/providers/exasol/hooks/exasol.py
<ide> def export_to_file(
<ide> )
<ide> self.log.info("Data saved to %s", filename)
<ide>
<del> def run(self, sql: Union[str, list], autocommit: bool = False, parameters: Optional[dict] = None) -> None:
<add> def run(
<add> self, sql: Union[str, list], autocommit: bool = False, parameters: Optional[dict] = None, handler=None
<add> ) -> None:
<ide> """
<ide> Runs a command or a list of commands. Pass a list of sql
<ide> statements to the sql parameter to get them to execute
<ide> def run(self, sql: Union[str, list], autocommit: bool = False, parameters: Optio
<ide> :type autocommit: bool
<ide> :param parameters: The parameters to render the SQL query with.
<ide> :type parameters: dict or iterable
<add> :param handler: The result handler which is called with the result of each statement.
<add> :type handler: callable
<ide> """
<ide> if isinstance(sql, str):
<ide> sql = [sql] | 1 |
Javascript | Javascript | add flatlist and sectionlist to animated exports | daa7c78055857cd2d9ea650de0c4b0f72d3f2acf | <ide><path>Libraries/Animated/src/Animated.js
<ide> 'use strict';
<ide>
<ide> const AnimatedImplementation = require('AnimatedImplementation');
<add>const FlatList = require('FlatList');
<ide> const Image = require('Image');
<ide> const ScrollView = require('ScrollView');
<add>const SectionList = require('SectionList');
<ide> const Text = require('Text');
<ide> const View = require('View');
<ide>
<ide> module.exports = {
<ide> Text: AnimatedImplementation.createAnimatedComponent(Text),
<ide> Image: AnimatedImplementation.createAnimatedComponent(Image),
<ide> ScrollView: AnimatedImplementation.createAnimatedComponent(ScrollView),
<add> FlatList: AnimatedImplementation.createAnimatedComponent(FlatList),
<add> SectionList: AnimatedImplementation.createAnimatedComponent(SectionList),
<ide> };
<ide><path>Libraries/Animated/src/__tests__/AnimatedNative-test.js
<ide> jest
<ide> .setMock('View', ClassComponentMock)
<ide> .setMock('Image', ClassComponentMock)
<ide> .setMock('ScrollView', ClassComponentMock)
<add> .setMock('FlatList', ClassComponentMock)
<add> .setMock('SectionList', ClassComponentMock)
<ide> .setMock('React', {Component: class {}})
<ide> .setMock('NativeModules', {
<ide> NativeAnimatedModule: {},
<ide><path>RNTester/js/FlatListExample.js
<ide> const Alert = require('Alert');
<ide> const React = require('react');
<ide> const ReactNative = require('react-native');
<del>const {Animated, FlatList, StyleSheet, View} = ReactNative;
<add>const {Animated, StyleSheet, View} = ReactNative;
<ide>
<ide> const RNTesterPage = require('./RNTesterPage');
<ide>
<ide> const {
<ide> renderSmallSwitchOption,
<ide> } = require('./ListExampleShared');
<ide>
<del>const AnimatedFlatList = Animated.createAnimatedComponent(FlatList);
<del>
<ide> const VIEWABILITY_CONFIG = {
<ide> minimumViewTime: 3000,
<ide> viewAreaCoveragePercentThreshold: 100,
<ide> class FlatListExample extends React.PureComponent<{}, $FlowFixMeState> {
<ide> </View>
<ide> </View>
<ide> <SeparatorComponent />
<del> <AnimatedFlatList
<add> <Animated.FlatList
<ide> ItemSeparatorComponent={ItemSeparatorComponent}
<ide> ListHeaderComponent={<HeaderComponent />}
<ide> ListFooterComponent={FooterComponent}
<ide> class FlatListExample extends React.PureComponent<{}, $FlowFixMeState> {
<ide> this._listRef.getNode().recordInteraction();
<ide> pressItem(this, key);
<ide> };
<del> _listRef: AnimatedFlatList;
<add> _listRef: Animated.FlatList;
<ide> }
<ide>
<ide> const styles = StyleSheet.create({
<ide><path>RNTester/js/SectionListExample.js
<ide>
<ide> const React = require('react');
<ide> const ReactNative = require('react-native');
<del>const {
<del> Alert,
<del> Animated,
<del> Button,
<del> SectionList,
<del> StyleSheet,
<del> Text,
<del> View,
<del>} = ReactNative;
<add>const {Alert, Animated, Button, StyleSheet, Text, View} = ReactNative;
<ide>
<ide> const RNTesterPage = require('./RNTesterPage');
<ide>
<ide> const {
<ide> renderStackedItem,
<ide> } = require('./ListExampleShared');
<ide>
<del>const AnimatedSectionList = Animated.createAnimatedComponent(SectionList);
<del>
<ide> const VIEWABILITY_CONFIG = {
<ide> minimumViewTime: 3000,
<ide> viewAreaCoveragePercentThreshold: 100,
<ide> class SectionListExample extends React.PureComponent<{}, $FlowFixMeState> {
<ide> {useNativeDriver: true},
<ide> );
<ide>
<del> _sectionListRef: any;
<add> _sectionListRef: Animated.SectionList;
<ide> _captureRef = ref => {
<ide> this._sectionListRef = ref;
<ide> };
<ide> class SectionListExample extends React.PureComponent<{}, $FlowFixMeState> {
<ide> </View>
<ide> </View>
<ide> <SeparatorComponent />
<del> <AnimatedSectionList
<add> <Animated.SectionList
<ide> ref={this._captureRef}
<ide> ListHeaderComponent={HeaderComponent}
<ide> ListFooterComponent={FooterComponent} | 4 |
Javascript | Javascript | fix typeerror of symbol in template literals | 027c2880a642c94b5927bbb7f90923f415ff9f39 | <ide><path>lib/internal/util/inspect.js
<ide> function getConstructorName(obj, ctx, recurseTimes, protoProps) {
<ide> addPrototypeProperties(
<ide> ctx, tmp, firstProto || tmp, recurseTimes, protoProps);
<ide> }
<del> return descriptor.value.name;
<add> return String(descriptor.value.name);
<ide> }
<ide>
<ide> obj = ObjectGetPrototypeOf(obj);
<ide><path>test/parallel/test-util-inspect.js
<ide> if (typeof Symbol !== 'undefined') {
<ide> class SetSubclass extends Set {}
<ide> class MapSubclass extends Map {}
<ide> class PromiseSubclass extends Promise {}
<add> class SymbolNameClass {
<add> static name = Symbol('name');
<add> }
<ide>
<ide> const x = new ObjectSubclass();
<ide> x.foo = 42;
<ide> if (typeof Symbol !== 'undefined') {
<ide> "MapSubclass(1) [Map] { 'foo' => 42 }");
<ide> assert.strictEqual(util.inspect(new PromiseSubclass(() => {})),
<ide> 'PromiseSubclass [Promise] { <pending> }');
<add> assert.strictEqual(util.inspect(new SymbolNameClass()),
<add> 'Symbol(name) {}');
<ide> assert.strictEqual(
<ide> util.inspect({ a: { b: new ArraySubclass([1, [2], 3]) } }, { depth: 1 }),
<ide> '{ a: { b: [ArraySubclass] } }' | 2 |
PHP | PHP | restore second=>true behavior | f02c898d0cb0cbb9e236b74df5d054b7b0debdef | <ide><path>src/View/Helper/FormHelper.php
<ide> public function dateTime($fieldName, array $options = [])
<ide> protected function _datetimeOptions($options)
<ide> {
<ide> foreach ($this->_datetimeParts as $type) {
<del> if (!isset($options[$type])) {
<add> if (!array_key_exists($type, $options)) {
<add> $options[$type] = [];
<add> }
<add> if ($options[$type] === true) {
<ide> $options[$type] = [];
<ide> }
<ide>
<ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testDateTimeLabelIdMatchesFirstInput()
<ide> $this->assertContains('<label>Date</label>', $result);
<ide> }
<ide>
<add> /**
<add> * test datetime second=true
<add> *
<add> * @return void
<add> */
<add> public function testDateTimeSecondOptions()
<add> {
<add> $result = $this->Form->dateTime('updated', ['second' => true]);
<add> $this->assertContains('updated[second]', $result, 'Should have seconds');
<add>
<add> $result = $this->Form->dateTime('updated', ['second' => []]);
<add> $this->assertContains('updated[second]', $result, 'Should have seconds');
<add>
<add> $result = $this->Form->dateTime('updated', ['second' => null]);
<add> $this->assertNotContains('updated[second]', $result, 'Should not have seconds');
<add>
<add> $result = $this->Form->dateTime('updated', ['second' => false]);
<add> $this->assertNotContains('updated[second]', $result, 'Should not have seconds');
<add> }
<add>
<ide> /**
<ide> * testMonth method
<ide> *
<ide><path>tests/TestCase/View/Widget/DateTimeWidgetTest.php
<ide> public function testRenderMonthWidgetWithNamesNoLeadingZeros()
<ide> 'no 13 in value'
<ide> );
<ide> }
<del>
<add>
<ide> /**
<ide> * Test rendering month widget with names.
<ide> *
<ide> public function testRenderMinuteWidgetEmptyZeroDefault()
<ide> 'hour' => false,
<ide> 'minute' => [
<ide> 'data-foo' => 'test',
<del>
<ide> ],
<ide> 'empty' => '-',
<ide> 'default' => '', | 3 |
Go | Go | add requirements for tests that require network | da9ef68f06e9c73b0913a53dbe31fce3244536a2 | <ide><path>integration-cli/docker_api_swarm_test.go
<ide> func (s *DockerSwarmSuite) TestAPISwarmLeaveRemovesContainer(c *check.C) {
<ide>
<ide> // #23629
<ide> func (s *DockerSwarmSuite) TestAPISwarmLeaveOnPendingJoin(c *check.C) {
<add> testRequires(c, Network)
<ide> s.AddDaemon(c, true, true)
<ide> d2 := s.AddDaemon(c, false, false)
<ide>
<ide> func (s *DockerSwarmSuite) TestAPISwarmLeaveOnPendingJoin(c *check.C) {
<ide>
<ide> // #23705
<ide> func (s *DockerSwarmSuite) TestAPISwarmRestoreOnPendingJoin(c *check.C) {
<add> testRequires(c, Network)
<ide> d := s.AddDaemon(c, false, false)
<ide> err := d.Join(swarm.JoinRequest{
<ide> RemoteAddrs: []string{"123.123.123.123:1234"},
<ide><path>integration-cli/docker_cli_daemon_experimental_test.go
<ide> var pluginName = "tiborvass/no-remove"
<ide>
<ide> // TestDaemonRestartWithPluginEnabled tests state restore for an enabled plugin
<ide> func (s *DockerDaemonSuite) TestDaemonRestartWithPluginEnabled(c *check.C) {
<add> testRequires(c, Network)
<ide> if err := s.d.Start(); err != nil {
<ide> c.Fatalf("Could not start daemon: %v", err)
<ide> }
<ide> func (s *DockerDaemonSuite) TestDaemonRestartWithPluginEnabled(c *check.C) {
<ide>
<ide> // TestDaemonRestartWithPluginDisabled tests state restore for a disabled plugin
<ide> func (s *DockerDaemonSuite) TestDaemonRestartWithPluginDisabled(c *check.C) {
<add> testRequires(c, Network)
<ide> if err := s.d.Start(); err != nil {
<ide> c.Fatalf("Could not start daemon: %v", err)
<ide> }
<ide> func (s *DockerDaemonSuite) TestDaemonRestartWithPluginDisabled(c *check.C) {
<ide> // TestDaemonKillLiveRestoreWithPlugins SIGKILLs daemon started with --live-restore.
<ide> // Plugins should continue to run.
<ide> func (s *DockerDaemonSuite) TestDaemonKillLiveRestoreWithPlugins(c *check.C) {
<add> testRequires(c, Network)
<ide> if err := s.d.Start("--live-restore"); err != nil {
<ide> c.Fatalf("Could not start daemon: %v", err)
<ide> }
<ide> func (s *DockerDaemonSuite) TestDaemonKillLiveRestoreWithPlugins(c *check.C) {
<ide> // TestDaemonShutdownLiveRestoreWithPlugins SIGTERMs daemon started with --live-restore.
<ide> // Plugins should continue to run.
<ide> func (s *DockerDaemonSuite) TestDaemonShutdownLiveRestoreWithPlugins(c *check.C) {
<add> testRequires(c, Network)
<ide> if err := s.d.Start("--live-restore"); err != nil {
<ide> c.Fatalf("Could not start daemon: %v", err)
<ide> }
<ide> func (s *DockerDaemonSuite) TestDaemonShutdownLiveRestoreWithPlugins(c *check.C)
<ide>
<ide> // TestDaemonShutdownWithPlugins shuts down running plugins.
<ide> func (s *DockerDaemonSuite) TestDaemonShutdownWithPlugins(c *check.C) {
<add> testRequires(c, Network)
<ide> if err := s.d.Start(); err != nil {
<ide> c.Fatalf("Could not start daemon: %v", err)
<ide> }
<ide> func (s *DockerDaemonSuite) TestDaemonShutdownWithPlugins(c *check.C) {
<ide>
<ide> // TestVolumePlugin tests volume creation using a plugin.
<ide> func (s *DockerDaemonSuite) TestVolumePlugin(c *check.C) {
<add> testRequires(c, Network)
<ide> volName := "plugin-volume"
<ide> volRoot := "/data"
<ide> destDir := "/tmp/data/"
<ide><path>integration-cli/docker_cli_plugins_test.go
<ide> var (
<ide> )
<ide>
<ide> func (s *DockerSuite) TestPluginBasicOps(c *check.C) {
<del> testRequires(c, DaemonIsLinux, ExperimentalDaemon)
<add> testRequires(c, DaemonIsLinux, ExperimentalDaemon, Network)
<ide> _, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", pNameWithTag)
<ide> c.Assert(err, checker.IsNil)
<ide>
<ide> func (s *DockerSuite) TestPluginBasicOps(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestPluginForceRemove(c *check.C) {
<del> testRequires(c, DaemonIsLinux, ExperimentalDaemon)
<add> testRequires(c, DaemonIsLinux, ExperimentalDaemon, Network)
<ide> out, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", pNameWithTag)
<ide> c.Assert(err, checker.IsNil)
<ide>
<ide> func (s *DockerSuite) TestPluginForceRemove(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestPluginActive(c *check.C) {
<del> testRequires(c, DaemonIsLinux, ExperimentalDaemon)
<add> testRequires(c, DaemonIsLinux, ExperimentalDaemon, Network)
<ide> out, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", pNameWithTag)
<ide> c.Assert(err, checker.IsNil)
<ide>
<ide> func (s *DockerSuite) TestPluginActive(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestPluginInstallDisable(c *check.C) {
<del> testRequires(c, DaemonIsLinux, ExperimentalDaemon)
<add> testRequires(c, DaemonIsLinux, ExperimentalDaemon, Network)
<ide> out, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", "--disable", pName)
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(strings.TrimSpace(out), checker.Contains, pName)
<ide> func (s *DockerSuite) TestPluginInstallImage(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestPluginEnableDisableNegative(c *check.C) {
<del> testRequires(c, DaemonIsLinux, ExperimentalDaemon)
<add> testRequires(c, DaemonIsLinux, ExperimentalDaemon, Network)
<ide> out, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", pName)
<ide> c.Assert(err, checker.IsNil)
<ide> c.Assert(strings.TrimSpace(out), checker.Contains, pName) | 3 |
Python | Python | fix broken link in open_memmap see also | 63e256cb9b2316ece0e8eb05ea992345a573b190 | <ide><path>numpy/lib/format.py
<ide> def open_memmap(filename, mode='r+', dtype=None, shape=None,
<ide>
<ide> See Also
<ide> --------
<del> memmap
<add> numpy.memmap
<ide>
<ide> """
<ide> if isfileobj(filename): | 1 |
Javascript | Javascript | remove extra get call | 9a4c350826898375aec71d638e537f3aae9ca3c0 | <ide><path>packages/ember-handlebars/lib/helpers/collection.js
<ide> Ember.Handlebars.registerHelper('collection', function(path, options) {
<ide> }
<ide> }
<ide>
<del> var tagName = hash.tagName || get(collectionClass, 'proto').tagName;
<add> var tagName = hash.tagName || collectionPrototype.tagName;
<ide>
<ide> if (fn) {
<ide> itemHash.template = fn; | 1 |
Ruby | Ruby | move tab creation into build process | 3ac74331a86d031179c3e25fe46bcb9f292dacc1 | <ide><path>Library/Homebrew/build.rb
<ide> def install
<ide>
<ide> begin
<ide> f.install
<add> Tab.create(f, Options.coerce(ARGV.options_only)).write
<ide> rescue Exception => e
<ide> if ARGV.debug?
<ide> debrew e, f
<ide><path>Library/Homebrew/formula_installer.rb
<ide> def build
<ide>
<ide> raise "Empty installation" if Dir["#{f.prefix}/*"].empty?
<ide>
<del> Tab.create(f, build_argv).write # INSTALL_RECEIPT.json
<del>
<ide> rescue Exception
<ide> ignore_interrupts do
<ide> # any exceptions must leave us with nothing installed | 2 |
Javascript | Javascript | simplify code by a ternary op instead of if-else | e0ce9ed36d9b8c1858e4f928b61d21d7d4c023b8 | <ide><path>src/ng/filter/filter.js
<ide> function filterFilter() {
<ide> case "object":
<ide> // jshint +W086
<ide> for (var key in expression) {
<del> if (key == '$') {
<del> (function() {
<del> if (!expression[key]) return;
<del> var path = key;
<del> predicates.push(function(value) {
<del> return search(value, expression[path]);
<del> });
<del> })();
<del> } else {
<del> (function() {
<del> if (typeof(expression[key]) == 'undefined') { return; }
<del> var path = key;
<del> predicates.push(function(value) {
<del> return search(getter(value,path), expression[path]);
<del> });
<del> })();
<del> }
<add> (function(path) {
<add> if (typeof expression[path] == 'undefined') return;
<add> predicates.push(function(value) {
<add> return search(path == '$' ? value : getter(value, path), expression[path]);
<add> });
<add> })(key);
<ide> }
<ide> break;
<ide> case 'function':
<ide><path>test/ng/filter/filterSpec.js
<ide> describe('Filter: filter', function() {
<ide> expect(filter(items, {first:'misko', last:'hevery'})[0]).toEqual(items[0]);
<ide> });
<ide>
<add> it('should match any properties for given "$" property', function() {
<add> var items = [{first: 'tom', last: 'hevery'},
<add> {first: 'adam', last: 'hevery', alias: 'tom', done: false},
<add> {first: 'john', last: 'clark', middle: 'tommy'}];
<add> expect(filter(items, {$: 'tom'}).length).toBe(3);
<add> expect(filter(items, {$: 'a'}).length).toBe(2);
<add> expect(filter(items, {$: false}).length).toBe(1);
<add> expect(filter(items, {$: 10}).length).toBe(0);
<add> expect(filter(items, {$: 'hevery'})[0]).toEqual(items[0]);
<add> });
<add>
<ide> it('should support boolean properties', function() {
<ide> var items = [{name: 'tom', current: true},
<ide> {name: 'demi', current: false}, | 2 |
Go | Go | use dockercmd when possible | 27ac154d05cf9f7aa1e9cbebe3c7769fa746de1e | <ide><path>integration-cli/docker_cli_run_test.go
<ide> import (
<ide>
<ide> // "test123" should be printed by docker run
<ide> func (s *DockerSuite) TestRunEchoStdout(c *check.C) {
<del> runCmd := exec.Command(dockerBinary, "run", "busybox", "echo", "test123")
<del> out, _, _, err := runCommandWithStdoutStderr(runCmd)
<del> if err != nil {
<del> c.Fatalf("failed to run container: %v, output: %q", err, out)
<del> }
<del>
<add> out, _ := dockerCmd(c, "run", "busybox", "echo", "test123")
<ide> if out != "test123\n" {
<ide> c.Fatalf("container should've printed 'test123'")
<ide> }
<ide> func (s *DockerSuite) TestRunEchoStdoutWithMemoryLimit(c *check.C) {
<ide> // should run without memory swap
<ide> func (s *DockerSuite) TestRunWithoutMemoryswapLimit(c *check.C) {
<ide> testRequires(c, NativeExecDriver)
<del> runCmd := exec.Command(dockerBinary, "run", "-m", "16m", "--memory-swap", "-1", "busybox", "true")
<del> out, _, err := runCommandWithOutput(runCmd)
<del> if err != nil {
<del> c.Fatalf("failed to run container, output: %q", out)
<del> }
<add> dockerCmd(c, "run", "-m", "16m", "--memory-swap", "-1", "busybox", "true")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunWithSwappiness(c *check.C) {
<del> runCmd := exec.Command(dockerBinary, "run", "--memory-swappiness", "0", "busybox", "true")
<del> out, _, err := runCommandWithOutput(runCmd)
<del> if err != nil {
<del> c.Fatalf("failed to run container, output: %q", out)
<del> }
<add> dockerCmd(c, "run", "--memory-swappiness", "0", "busybox", "true")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunWithSwappinessInvalid(c *check.C) {
<del> runCmd := exec.Command(dockerBinary, "run", "--memory-swappiness", "101", "busybox", "true")
<del> out, _, err := runCommandWithOutput(runCmd)
<add> out, _, err := dockerCmdWithError(c, "run", "--memory-swappiness", "101", "busybox", "true")
<ide> if err == nil {
<ide> c.Fatalf("failed. test was able to set invalid value, output: %q", out)
<ide> }
<ide> }
<ide>
<ide> // "test" should be printed
<ide> func (s *DockerSuite) TestRunEchoStdoutWitCPULimit(c *check.C) {
<del> runCmd := exec.Command(dockerBinary, "run", "-c", "1000", "busybox", "echo", "test")
<del> out, _, _, err := runCommandWithStdoutStderr(runCmd)
<del> if err != nil {
<del> c.Fatalf("failed to run container: %v, output: %q", err, out)
<del> }
<del>
<add> out, _ := dockerCmd(c, "run", "-c", "1000", "busybox", "echo", "test")
<ide> if out != "test\n" {
<ide> c.Errorf("container should've printed 'test'")
<ide> }
<ide> func (s *DockerSuite) TestRunEchoStdoutWithCPUAndMemoryLimit(c *check.C) {
<ide>
<ide> // "test" should be printed
<ide> func (s *DockerSuite) TestRunEchoNamedContainer(c *check.C) {
<del> runCmd := exec.Command(dockerBinary, "run", "--name", "testfoonamedcontainer", "busybox", "echo", "test")
<del> out, _, _, err := runCommandWithStdoutStderr(runCmd)
<del> if err != nil {
<del> c.Fatalf("failed to run container: %v, output: %q", err, out)
<del> }
<del>
<add> out, _ := dockerCmd(c, "run", "--name", "testfoonamedcontainer", "busybox", "echo", "test")
<ide> if out != "test\n" {
<ide> c.Errorf("container should've printed 'test'")
<ide> }
<ide> }
<ide>
<ide> // docker run should not leak file descriptors
<ide> func (s *DockerSuite) TestRunLeakyFileDescriptors(c *check.C) {
<del> runCmd := exec.Command(dockerBinary, "run", "busybox", "ls", "-C", "/proc/self/fd")
<del> out, _, _, err := runCommandWithStdoutStderr(runCmd)
<del> if err != nil {
<del> c.Fatalf("failed to run container: %v, output: %q", err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "busybox", "ls", "-C", "/proc/self/fd")
<ide>
<ide> // normally, we should only get 0, 1, and 2, but 3 gets created by "ls" when it does "opendir" on the "fd" directory
<ide> if out != "0 1 2 3\n" {
<ide> func (s *DockerSuite) TestRunLeakyFileDescriptors(c *check.C) {
<ide> // this will fail when Internet access is unavailable
<ide> func (s *DockerSuite) TestRunLookupGoogleDns(c *check.C) {
<ide> testRequires(c, Network)
<del>
<del> out, _, _, err := runCommandWithStdoutStderr(exec.Command(dockerBinary, "run", "busybox", "nslookup", "google.com"))
<del> if err != nil {
<del> c.Fatalf("failed to run container: %v, output: %q", err, out)
<del> }
<add> dockerCmd(c, "run", "busybox", "nslookup", "google.com")
<ide> }
<ide>
<ide> // the exit code should be 0
<ide> // some versions of lxc might make this test fail
<ide> func (s *DockerSuite) TestRunExitCodeZero(c *check.C) {
<del> runCmd := exec.Command(dockerBinary, "run", "busybox", "true")
<del> if out, _, err := runCommandWithOutput(runCmd); err != nil {
<del> c.Errorf("container should've exited with exit code 0: %s, %v", out, err)
<del> }
<add> dockerCmd(c, "run", "busybox", "true")
<ide> }
<ide>
<ide> // the exit code should be 1
<ide> // some versions of lxc might make this test fail
<ide> func (s *DockerSuite) TestRunExitCodeOne(c *check.C) {
<del> runCmd := exec.Command(dockerBinary, "run", "busybox", "false")
<del> exitCode, err := runCommand(runCmd)
<add> _, exitCode, err := dockerCmdWithError(c, "run", "busybox", "false")
<ide> if err != nil && !strings.Contains("exit status 1", fmt.Sprintf("%s", err)) {
<ide> c.Fatal(err)
<ide> }
<ide> func (s *DockerSuite) TestRunStdinPipe(c *check.C) {
<ide> }
<ide>
<ide> out = strings.TrimSpace(out)
<del> waitCmd := exec.Command(dockerBinary, "wait", out)
<del> if waitOut, _, err := runCommandWithOutput(waitCmd); err != nil {
<del> c.Fatalf("error thrown while waiting for container: %s, %v", waitOut, err)
<del> }
<add> dockerCmd(c, "wait", out)
<ide>
<del> logsCmd := exec.Command(dockerBinary, "logs", out)
<del> logsOut, _, err := runCommandWithOutput(logsCmd)
<del> if err != nil {
<del> c.Fatalf("error thrown while trying to get container logs: %s, %v", logsOut, err)
<del> }
<add> logsOut, _ := dockerCmd(c, "logs", out)
<ide>
<ide> containerLogs := strings.TrimSpace(logsOut)
<del>
<ide> if containerLogs != "blahblah" {
<ide> c.Errorf("logs didn't print the container's logs %s", containerLogs)
<ide> }
<ide>
<del> rmCmd := exec.Command(dockerBinary, "rm", out)
<del> if out, _, err = runCommandWithOutput(rmCmd); err != nil {
<del> c.Fatalf("rm failed to remove container: %s, %v", out, err)
<del> }
<add> dockerCmd(c, "rm", out)
<ide> }
<ide>
<ide> // the container's ID should be printed when starting a container in detached mode
<ide> func (s *DockerSuite) TestRunDetachedContainerIDPrinting(c *check.C) {
<del> runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "true")
<del> out, _, _, err := runCommandWithStdoutStderr(runCmd)
<del> if err != nil {
<del> c.Fatalf("failed to run container: %v, output: %q", err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "-d", "busybox", "true")
<ide>
<ide> out = strings.TrimSpace(out)
<del> waitCmd := exec.Command(dockerBinary, "wait", out)
<del> if waitOut, _, err := runCommandWithOutput(waitCmd); err != nil {
<del> c.Fatalf("error thrown while waiting for container: %s, %v", waitOut, err)
<del> }
<add> dockerCmd(c, "wait", out)
<ide>
<del> rmCmd := exec.Command(dockerBinary, "rm", out)
<del> rmOut, _, err := runCommandWithOutput(rmCmd)
<del> if err != nil {
<del> c.Fatalf("rm failed to remove container: %s, %v", rmOut, err)
<del> }
<add> rmOut, _ := dockerCmd(c, "rm", out)
<ide>
<ide> rmOut = strings.TrimSpace(rmOut)
<ide> if rmOut != out {
<ide> func (s *DockerSuite) TestRunDetachedContainerIDPrinting(c *check.C) {
<ide>
<ide> // the working directory should be set correctly
<ide> func (s *DockerSuite) TestRunWorkingDirectory(c *check.C) {
<del> runCmd := exec.Command(dockerBinary, "run", "-w", "/root", "busybox", "pwd")
<del> out, _, _, err := runCommandWithStdoutStderr(runCmd)
<del> if err != nil {
<del> c.Fatalf("failed to run container: %v, output: %q", err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "-w", "/root", "busybox", "pwd")
<ide>
<ide> out = strings.TrimSpace(out)
<del>
<ide> if out != "/root" {
<ide> c.Errorf("-w failed to set working directory")
<ide> }
<ide>
<del> runCmd = exec.Command(dockerBinary, "run", "--workdir", "/root", "busybox", "pwd")
<del> out, _, _, err = runCommandWithStdoutStderr(runCmd)
<del> if err != nil {
<del> c.Fatal(out, err)
<del> }
<del>
<add> out, _ = dockerCmd(c, "run", "--workdir", "/root", "busybox", "pwd")
<ide> out = strings.TrimSpace(out)
<del>
<ide> if out != "/root" {
<ide> c.Errorf("--workdir failed to set working directory")
<ide> }
<ide> }
<ide>
<ide> // pinging Google's DNS resolver should fail when we disable the networking
<ide> func (s *DockerSuite) TestRunWithoutNetworking(c *check.C) {
<del> runCmd := exec.Command(dockerBinary, "run", "--net=none", "busybox", "ping", "-c", "1", "8.8.8.8")
<del> out, _, exitCode, err := runCommandWithStdoutStderr(runCmd)
<add> out, exitCode, err := dockerCmdWithError(c, "run", "--net=none", "busybox", "ping", "-c", "1", "8.8.8.8")
<ide> if err != nil && exitCode != 1 {
<ide> c.Fatal(out, err)
<ide> }
<ide> if exitCode != 1 {
<ide> c.Errorf("--net=none should've disabled the network; the container shouldn't have been able to ping 8.8.8.8")
<ide> }
<ide>
<del> runCmd = exec.Command(dockerBinary, "run", "-n=false", "busybox", "ping", "-c", "1", "8.8.8.8")
<del> out, _, exitCode, err = runCommandWithStdoutStderr(runCmd)
<add> out, exitCode, err = dockerCmdWithError(c, "run", "-n=false", "busybox", "ping", "-c", "1", "8.8.8.8")
<ide> if err != nil && exitCode != 1 {
<ide> c.Fatal(out, err)
<ide> }
<ide> func (s *DockerSuite) TestRunWithoutNetworking(c *check.C) {
<ide>
<ide> //test --link use container name to link target
<ide> func (s *DockerSuite) TestRunLinksContainerWithContainerName(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "-i", "-t", "-d", "--name", "parent", "busybox")
<del> out, _, _, err := runCommandWithStdoutStderr(cmd)
<del> if err != nil {
<del> c.Fatalf("failed to run container: %v, output: %q", err, out)
<del> }
<add> dockerCmd(c, "run", "-i", "-t", "-d", "--name", "parent", "busybox")
<add>
<ide> ip, err := inspectField("parent", "NetworkSettings.IPAddress")
<ide> c.Assert(err, check.IsNil)
<del> cmd = exec.Command(dockerBinary, "run", "--link", "parent:test", "busybox", "/bin/cat", "/etc/hosts")
<del> out, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatalf("failed to run container: %v, output: %q", err, out)
<del> }
<add>
<add> out, _ := dockerCmd(c, "run", "--link", "parent:test", "busybox", "/bin/cat", "/etc/hosts")
<ide> if !strings.Contains(out, ip+" test") {
<ide> c.Fatalf("use a container name to link target failed")
<ide> }
<ide> }
<ide>
<ide> //test --link use container id to link target
<ide> func (s *DockerSuite) TestRunLinksContainerWithContainerId(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "-i", "-t", "-d", "busybox")
<del> cID, _, _, err := runCommandWithStdoutStderr(cmd)
<del> if err != nil {
<del> c.Fatalf("failed to run container: %v, output: %q", err, cID)
<del> }
<add> cID, _ := dockerCmd(c, "run", "-i", "-t", "-d", "busybox")
<add>
<ide> cID = strings.TrimSpace(cID)
<ide> ip, err := inspectField(cID, "NetworkSettings.IPAddress")
<ide> c.Assert(err, check.IsNil)
<del> cmd = exec.Command(dockerBinary, "run", "--link", cID+":test", "busybox", "/bin/cat", "/etc/hosts")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatalf("failed to run container: %v, output: %q", err, out)
<del> }
<add>
<add> out, _ := dockerCmd(c, "run", "--link", cID+":test", "busybox", "/bin/cat", "/etc/hosts")
<ide> if !strings.Contains(out, ip+" test") {
<ide> c.Fatalf("use a container id to link target failed")
<ide> }
<ide> }
<ide>
<ide> // Regression test for #4979
<ide> func (s *DockerSuite) TestRunWithVolumesFromExited(c *check.C) {
<del> runCmd := exec.Command(dockerBinary, "run", "--name", "test-data", "--volume", "/some/dir", "busybox", "touch", "/some/dir/file")
<del> out, stderr, exitCode, err := runCommandWithStdoutStderr(runCmd)
<del> if err != nil && exitCode != 0 {
<del> c.Fatal("1", out, stderr, err)
<add> out, exitCode := dockerCmd(c, "run", "--name", "test-data", "--volume", "/some/dir", "busybox", "touch", "/some/dir/file")
<add> if exitCode != 0 {
<add> c.Fatal("1", out, exitCode)
<ide> }
<ide>
<del> runCmd = exec.Command(dockerBinary, "run", "--volumes-from", "test-data", "busybox", "cat", "/some/dir/file")
<del> out, stderr, exitCode, err = runCommandWithStdoutStderr(runCmd)
<del> if err != nil && exitCode != 0 {
<del> c.Fatal("2", out, stderr, err)
<add> out, exitCode = dockerCmd(c, "run", "--volumes-from", "test-data", "busybox", "cat", "/some/dir/file")
<add> if exitCode != 0 {
<add> c.Fatal("2", out, exitCode)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunCreateVolumesInSymlinkDir(c *check.C) {
<ide> c.Fatal(err)
<ide> }
<ide>
<del> out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-v", "/test/test", name))
<del> if err != nil {
<del> c.Fatalf("Failed with errors: %s, %v", out, err)
<del> }
<add> dockerCmd(c, "run", "-v", "/test/test", name)
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunVolumesMountedAsReadonly(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "-v", "/test:/test:ro", "busybox", "touch", "/test/somefile")
<del> if code, err := runCommand(cmd); err == nil || code == 0 {
<add> if _, code, err := dockerCmdWithError(c, "run", "-v", "/test:/test:ro", "busybox", "touch", "/test/somefile"); err == nil || code == 0 {
<ide> c.Fatalf("run should fail because volume is ro: exit code %d", code)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunVolumesFromInReadonlyMode(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--name", "parent", "-v", "/test", "busybox", "true")
<del> if _, err := runCommand(cmd); err != nil {
<del> c.Fatal(err)
<del> }
<add> dockerCmd(c, "run", "--name", "parent", "-v", "/test", "busybox", "true")
<ide>
<del> cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent:ro", "busybox", "touch", "/test/file")
<del> if code, err := runCommand(cmd); err == nil || code == 0 {
<add> if _, code, err := dockerCmdWithError(c, "run", "--volumes-from", "parent:ro", "busybox", "touch", "/test/file"); err == nil || code == 0 {
<ide> c.Fatalf("run should fail because volume is ro: exit code %d", code)
<ide> }
<ide> }
<ide>
<ide> // Regression test for #1201
<ide> func (s *DockerSuite) TestRunVolumesFromInReadWriteMode(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--name", "parent", "-v", "/test", "busybox", "true")
<del> if _, err := runCommand(cmd); err != nil {
<del> c.Fatal(err)
<del> }
<del>
<del> cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent:rw", "busybox", "touch", "/test/file")
<del> if out, _, err := runCommandWithOutput(cmd); err != nil {
<del> c.Fatalf("running --volumes-from parent:rw failed with output: %q\nerror: %v", out, err)
<del> }
<add> dockerCmd(c, "run", "--name", "parent", "-v", "/test", "busybox", "true")
<add> dockerCmd(c, "run", "--volumes-from", "parent:rw", "busybox", "touch", "/test/file")
<ide>
<del> cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent:bar", "busybox", "touch", "/test/file")
<del> if out, _, err := runCommandWithOutput(cmd); err == nil || !strings.Contains(out, "invalid mode for volumes-from: bar") {
<add> if out, _, err := dockerCmdWithError(c, "run", "--volumes-from", "parent:bar", "busybox", "touch", "/test/file"); err == nil || !strings.Contains(out, "invalid mode for volumes-from: bar") {
<ide> c.Fatalf("running --volumes-from foo:bar should have failed with invalid mount mode: %q", out)
<ide> }
<ide>
<del> cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent", "busybox", "touch", "/test/file")
<del> if out, _, err := runCommandWithOutput(cmd); err != nil {
<del> c.Fatalf("running --volumes-from parent failed with output: %q\nerror: %v", out, err)
<del> }
<add> dockerCmd(c, "run", "--volumes-from", "parent", "busybox", "touch", "/test/file")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestVolumesFromGetsProperMode(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--name", "parent", "-v", "/test:/test:ro", "busybox", "true")
<del> if _, err := runCommand(cmd); err != nil {
<del> c.Fatal(err)
<del> }
<add> dockerCmd(c, "run", "--name", "parent", "-v", "/test:/test:ro", "busybox", "true")
<add>
<ide> // Expect this "rw" mode to be be ignored since the inherited volume is "ro"
<del> cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent:rw", "busybox", "touch", "/test/file")
<del> if _, err := runCommand(cmd); err == nil {
<add> if _, _, err := dockerCmdWithError(c, "run", "--volumes-from", "parent:rw", "busybox", "touch", "/test/file"); err == nil {
<ide> c.Fatal("Expected volumes-from to inherit read-only volume even when passing in `rw`")
<ide> }
<ide>
<del> cmd = exec.Command(dockerBinary, "run", "--name", "parent2", "-v", "/test:/test:ro", "busybox", "true")
<del> if _, err := runCommand(cmd); err != nil {
<del> c.Fatal(err)
<del> }
<add> dockerCmd(c, "run", "--name", "parent2", "-v", "/test:/test:ro", "busybox", "true")
<add>
<ide> // Expect this to be read-only since both are "ro"
<del> cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent2:ro", "busybox", "touch", "/test/file")
<del> if _, err := runCommand(cmd); err == nil {
<add> if _, _, err := dockerCmdWithError(c, "run", "--volumes-from", "parent2:ro", "busybox", "touch", "/test/file"); err == nil {
<ide> c.Fatal("Expected volumes-from to inherit read-only volume even when passing in `ro`")
<ide> }
<ide> }
<ide> func (s *DockerSuite) TestRunNoDupVolumes(c *check.C) {
<ide> mountstr1 := randomUnixTmpDirPath("test1") + ":/someplace"
<ide> mountstr2 := randomUnixTmpDirPath("test2") + ":/someplace"
<ide>
<del> cmd := exec.Command(dockerBinary, "run", "-v", mountstr1, "-v", mountstr2, "busybox", "true")
<del> if out, _, err := runCommandWithOutput(cmd); err == nil {
<add> if out, _, err := dockerCmdWithError(c, "run", "-v", mountstr1, "-v", mountstr2, "busybox", "true"); err == nil {
<ide> c.Fatal("Expected error about duplicate volume definitions")
<ide> } else {
<ide> if !strings.Contains(out, "Duplicate bind mount") {
<ide> func (s *DockerSuite) TestRunNoDupVolumes(c *check.C) {
<ide>
<ide> // Test for #1351
<ide> func (s *DockerSuite) TestRunApplyVolumesFromBeforeVolumes(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--name", "parent", "-v", "/test", "busybox", "touch", "/test/foo")
<del> if _, err := runCommand(cmd); err != nil {
<del> c.Fatal(err)
<del> }
<del>
<del> cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent", "-v", "/test", "busybox", "cat", "/test/foo")
<del> if out, _, err := runCommandWithOutput(cmd); err != nil {
<del> c.Fatal(out, err)
<del> }
<add> dockerCmd(c, "run", "--name", "parent", "-v", "/test", "busybox", "touch", "/test/foo")
<add> dockerCmd(c, "run", "--volumes-from", "parent", "-v", "/test", "busybox", "cat", "/test/foo")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunMultipleVolumesFrom(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--name", "parent1", "-v", "/test", "busybox", "touch", "/test/foo")
<del> if _, err := runCommand(cmd); err != nil {
<del> c.Fatal(err)
<del> }
<del>
<del> cmd = exec.Command(dockerBinary, "run", "--name", "parent2", "-v", "/other", "busybox", "touch", "/other/bar")
<del> if _, err := runCommand(cmd); err != nil {
<del> c.Fatal(err)
<del> }
<del>
<del> cmd = exec.Command(dockerBinary, "run", "--volumes-from", "parent1", "--volumes-from", "parent2",
<del> "busybox", "sh", "-c", "cat /test/foo && cat /other/bar")
<del> if _, err := runCommand(cmd); err != nil {
<del> c.Fatal(err)
<del> }
<add> dockerCmd(c, "run", "--name", "parent1", "-v", "/test", "busybox", "touch", "/test/foo")
<add> dockerCmd(c, "run", "--name", "parent2", "-v", "/other", "busybox", "touch", "/other/bar")
<add> dockerCmd(c, "run", "--volumes-from", "parent1", "--volumes-from", "parent2", "busybox", "sh", "-c", "cat /test/foo && cat /other/bar")
<ide> }
<ide>
<ide> // this tests verifies the ID format for the container
<ide> func (s *DockerSuite) TestRunVerifyContainerID(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "-d", "busybox", "true")
<del> out, exit, err := runCommandWithOutput(cmd)
<add> out, exit, err := dockerCmdWithError(c, "run", "-d", "busybox", "true")
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<ide> if exit != 0 {
<ide> c.Fatalf("expected exit code 0 received %d", exit)
<ide> }
<add>
<ide> match, err := regexp.MatchString("^[0-9a-f]{64}$", strings.TrimSuffix(out, "\n"))
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> func (s *DockerSuite) TestRunVerifyContainerID(c *check.C) {
<ide>
<ide> // Test that creating a container with a volume doesn't crash. Regression test for #995.
<ide> func (s *DockerSuite) TestRunCreateVolume(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "-v", "/var/lib/data", "busybox", "true")
<del> if _, err := runCommand(cmd); err != nil {
<del> c.Fatal(err)
<del> }
<add> dockerCmd(c, "run", "-v", "/var/lib/data", "busybox", "true")
<ide> }
<ide>
<ide> // Test that creating a volume with a symlink in its path works correctly. Test for #5152.
<ide> func (s *DockerSuite) TestRunCreateVolumeWithSymlink(c *check.C) {
<ide> c.Fatalf("could not build '%s': %v", image, err)
<ide> }
<ide>
<del> cmd := exec.Command(dockerBinary, "run", "-v", "/bar/foo", "--name", "test-createvolumewithsymlink", image, "sh", "-c", "mount | grep -q /home/foo")
<del> exitCode, err := runCommand(cmd)
<add> _, exitCode, err := dockerCmdWithError(c, "run", "-v", "/bar/foo", "--name", "test-createvolumewithsymlink", image, "sh", "-c", "mount | grep -q /home/foo")
<ide> if err != nil || exitCode != 0 {
<ide> c.Fatalf("[run] err: %v, exitcode: %d", err, exitCode)
<ide> }
<ide>
<ide> var volPath string
<del> cmd = exec.Command(dockerBinary, "inspect", "-f", "{{range .Volumes}}{{.}}{{end}}", "test-createvolumewithsymlink")
<del> volPath, exitCode, err = runCommandWithOutput(cmd)
<add> volPath, exitCode, err = dockerCmdWithError(c, "inspect", "-f", "{{range .Volumes}}{{.}}{{end}}", "test-createvolumewithsymlink")
<ide> if err != nil || exitCode != 0 {
<ide> c.Fatalf("[inspect] err: %v, exitcode: %d", err, exitCode)
<ide> }
<ide>
<del> cmd = exec.Command(dockerBinary, "rm", "-v", "test-createvolumewithsymlink")
<del> exitCode, err = runCommand(cmd)
<add> _, exitCode, err = dockerCmdWithError(c, "rm", "-v", "test-createvolumewithsymlink")
<ide> if err != nil || exitCode != 0 {
<ide> c.Fatalf("[rm] err: %v, exitcode: %d", err, exitCode)
<ide> }
<ide> func (s *DockerSuite) TestRunVolumesFromSymlinkPath(c *check.C) {
<ide> c.Fatalf("could not build 'docker-test-volumesfromsymlinkpath': %v", err)
<ide> }
<ide>
<del> cmd := exec.Command(dockerBinary, "run", "--name", "test-volumesfromsymlinkpath", name)
<del> exitCode, err := runCommand(cmd)
<add> _, exitCode, err := dockerCmdWithError(c, "run", "--name", "test-volumesfromsymlinkpath", name)
<ide> if err != nil || exitCode != 0 {
<ide> c.Fatalf("[run] (volume) err: %v, exitcode: %d", err, exitCode)
<ide> }
<ide>
<del> cmd = exec.Command(dockerBinary, "run", "--volumes-from", "test-volumesfromsymlinkpath", "busybox", "sh", "-c", "ls /foo | grep -q bar")
<del> exitCode, err = runCommand(cmd)
<add> _, exitCode, err = dockerCmdWithError(c, "run", "--volumes-from", "test-volumesfromsymlinkpath", "busybox", "sh", "-c", "ls /foo | grep -q bar")
<ide> if err != nil || exitCode != 0 {
<ide> c.Fatalf("[run] err: %v, exitcode: %d", err, exitCode)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunExitCode(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "busybox", "/bin/sh", "-c", "exit 72")
<del>
<del> exit, err := runCommand(cmd)
<add> _, exit, err := dockerCmdWithError(c, "run", "busybox", "/bin/sh", "-c", "exit 72")
<ide> if err == nil {
<ide> c.Fatal("should not have a non nil error")
<ide> }
<ide> func (s *DockerSuite) TestRunExitCode(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunUserDefaultsToRoot(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "busybox", "id")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "busybox", "id")
<ide> if !strings.Contains(out, "uid=0(root) gid=0(root)") {
<ide> c.Fatalf("expected root user got %s", out)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunUserByName(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "-u", "root", "busybox", "id")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "-u", "root", "busybox", "id")
<ide> if !strings.Contains(out, "uid=0(root) gid=0(root)") {
<ide> c.Fatalf("expected root user got %s", out)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunUserByID(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "-u", "1", "busybox", "id")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "-u", "1", "busybox", "id")
<ide> if !strings.Contains(out, "uid=1(daemon) gid=1(daemon)") {
<ide> c.Fatalf("expected daemon user got %s", out)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunUserByIDBig(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "-u", "2147483648", "busybox", "id")
<del> out, _, err := runCommandWithOutput(cmd)
<add> out, _, err := dockerCmdWithError(c, "run", "-u", "2147483648", "busybox", "id")
<ide> if err == nil {
<ide> c.Fatal("No error, but must be.", out)
<ide> }
<ide> func (s *DockerSuite) TestRunUserByIDBig(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunUserByIDNegative(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "-u", "-1", "busybox", "id")
<del> out, _, err := runCommandWithOutput(cmd)
<add> out, _, err := dockerCmdWithError(c, "run", "-u", "-1", "busybox", "id")
<ide> if err == nil {
<ide> c.Fatal("No error, but must be.", out)
<ide> }
<ide> func (s *DockerSuite) TestRunUserByIDNegative(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunUserByIDZero(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "-u", "0", "busybox", "id")
<del> out, _, err := runCommandWithOutput(cmd)
<add> out, _, err := dockerCmdWithError(c, "run", "-u", "0", "busybox", "id")
<ide> if err != nil {
<ide> c.Fatal(err, out)
<ide> }
<ide> func (s *DockerSuite) TestRunUserByIDZero(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunUserNotFound(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "-u", "notme", "busybox", "id")
<del> _, err := runCommand(cmd)
<add> _, _, err := dockerCmdWithError(c, "run", "-u", "notme", "busybox", "id")
<ide> if err == nil {
<ide> c.Fatal("unknown user should cause container to fail")
<ide> }
<ide> func (s *DockerSuite) TestRunTwoConcurrentContainers(c *check.C) {
<ide> for i := 0; i < 2; i++ {
<ide> go func() {
<ide> defer group.Done()
<del> cmd := exec.Command(dockerBinary, "run", "busybox", "sleep", "2")
<del> _, err := runCommand(cmd)
<add> _, _, err := dockerCmdWithError(c, "run", "busybox", "sleep", "2")
<ide> errChan <- err
<ide> }()
<ide> }
<ide> func (s *DockerSuite) TestRunEnvironmentOverride(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunContainerNetwork(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "busybox", "ping", "-c", "1", "127.0.0.1")
<del> if _, err := runCommand(cmd); err != nil {
<del> c.Fatal(err)
<del> }
<add> dockerCmd(c, "run", "busybox", "ping", "-c", "1", "127.0.0.1")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunNetHostNotAllowedWithLinks(c *check.C) {
<del> out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--name", "linked", "busybox", "true"))
<del> if err != nil {
<del> c.Fatalf("Failed with errors: %s, %v", out, err)
<del> }
<del> cmd := exec.Command(dockerBinary, "run", "--net=host", "--link", "linked:linked", "busybox", "true")
<del> _, _, err = runCommandWithOutput(cmd)
<add> dockerCmd(c, "run", "--name", "linked", "busybox", "true")
<add>
<add> _, _, err := dockerCmdWithError(c, "run", "--net=host", "--link", "linked:linked", "busybox", "true")
<ide> if err == nil {
<ide> c.Fatal("Expected error")
<ide> }
<ide> func (s *DockerSuite) TestRunNetHostNotAllowedWithLinks(c *check.C) {
<ide> // codepath is executed with "docker run -h <hostname>". Both were manually
<ide> // tested, but this testcase takes the simpler path of using "run -h .."
<ide> func (s *DockerSuite) TestRunFullHostnameSet(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "-h", "foo.bar.baz", "busybox", "hostname")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<del>
<add> out, _ := dockerCmd(c, "run", "-h", "foo.bar.baz", "busybox", "hostname")
<ide> if actual := strings.Trim(out, "\r\n"); actual != "foo.bar.baz" {
<ide> c.Fatalf("expected hostname 'foo.bar.baz', received %s", actual)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunPrivilegedCanMknod(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--privileged", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err)
<del> }
<del>
<add> out, _ := dockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
<ide> if actual := strings.Trim(out, "\r\n"); actual != "ok" {
<ide> c.Fatalf("expected output ok received %s", actual)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunUnprivilegedCanMknod(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err)
<del> }
<del>
<add> out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
<ide> if actual := strings.Trim(out, "\r\n"); actual != "ok" {
<ide> c.Fatalf("expected output ok received %s", actual)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunCapDropInvalid(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--cap-drop=CHPASS", "busybox", "ls")
<del> out, _, err := runCommandWithOutput(cmd)
<add> out, _, err := dockerCmdWithError(c, "run", "--cap-drop=CHPASS", "busybox", "ls")
<ide> if err == nil {
<ide> c.Fatal(err, out)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunCapDropCannotMknod(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--cap-drop=MKNOD", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
<del> out, _, err := runCommandWithOutput(cmd)
<add> out, _, err := dockerCmdWithError(c, "run", "--cap-drop=MKNOD", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
<add>
<ide> if err == nil {
<ide> c.Fatal(err, out)
<ide> }
<del>
<ide> if actual := strings.Trim(out, "\r\n"); actual == "ok" {
<ide> c.Fatalf("expected output not ok received %s", actual)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunCapDropCannotMknodLowerCase(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--cap-drop=mknod", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
<del> out, _, err := runCommandWithOutput(cmd)
<add> out, _, err := dockerCmdWithError(c, "run", "--cap-drop=mknod", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
<add>
<ide> if err == nil {
<ide> c.Fatal(err, out)
<ide> }
<del>
<ide> if actual := strings.Trim(out, "\r\n"); actual == "ok" {
<ide> c.Fatalf("expected output not ok received %s", actual)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunCapDropALLCannotMknod(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--cap-drop=ALL", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
<del> out, _, err := runCommandWithOutput(cmd)
<add> out, _, err := dockerCmdWithError(c, "run", "--cap-drop=ALL", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
<ide> if err == nil {
<ide> c.Fatal(err, out)
<ide> }
<del>
<ide> if actual := strings.Trim(out, "\r\n"); actual == "ok" {
<ide> c.Fatalf("expected output not ok received %s", actual)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunCapDropALLAddMknodCanMknod(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--cap-drop=ALL", "--cap-add=MKNOD", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=MKNOD", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
<ide>
<ide> if actual := strings.Trim(out, "\r\n"); actual != "ok" {
<ide> c.Fatalf("expected output ok received %s", actual)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunCapAddInvalid(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--cap-add=CHPASS", "busybox", "ls")
<del> out, _, err := runCommandWithOutput(cmd)
<add> out, _, err := dockerCmdWithError(c, "run", "--cap-add=CHPASS", "busybox", "ls")
<ide> if err == nil {
<ide> c.Fatal(err, out)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunCapAddCanDownInterface(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--cap-add=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "--cap-add=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
<ide>
<ide> if actual := strings.Trim(out, "\r\n"); actual != "ok" {
<ide> c.Fatalf("expected output ok received %s", actual)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunCapAddALLCanDownInterface(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--cap-add=ALL", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "--cap-add=ALL", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
<ide>
<ide> if actual := strings.Trim(out, "\r\n"); actual != "ok" {
<ide> c.Fatalf("expected output ok received %s", actual)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunCapAddALLDropNetAdminCanDownInterface(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--cap-add=ALL", "--cap-drop=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
<del> out, _, err := runCommandWithOutput(cmd)
<add> out, _, err := dockerCmdWithError(c, "run", "--cap-add=ALL", "--cap-drop=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
<ide> if err == nil {
<ide> c.Fatal(err, out)
<ide> }
<del>
<ide> if actual := strings.Trim(out, "\r\n"); actual == "ok" {
<ide> c.Fatalf("expected output not ok received %s", actual)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunGroupAdd(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--group-add=audio", "--group-add=dbus", "--group-add=777", "busybox", "sh", "-c", "id")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "--group-add=audio", "--group-add=dbus", "--group-add=777", "busybox", "sh", "-c", "id")
<ide>
<ide> groupsList := "uid=0(root) gid=0(root) groups=10(wheel),29(audio),81(dbus),777"
<ide> if actual := strings.Trim(out, "\r\n"); actual != groupsList {
<ide> func (s *DockerSuite) TestRunGroupAdd(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunPrivilegedCanMount(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--privileged", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err)
<del> }
<add> out, _ := dockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
<ide>
<ide> if actual := strings.Trim(out, "\r\n"); actual != "ok" {
<ide> c.Fatalf("expected output ok received %s", actual)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunUnprivilegedCannotMount(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
<del> out, _, err := runCommandWithOutput(cmd)
<add> out, _, err := dockerCmdWithError(c, "run", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
<add>
<ide> if err == nil {
<ide> c.Fatal(err, out)
<ide> }
<del>
<ide> if actual := strings.Trim(out, "\r\n"); actual == "ok" {
<ide> c.Fatalf("expected output not ok received %s", actual)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunSysNotWritableInNonPrivilegedContainers(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "busybox", "touch", "/sys/kernel/profiling")
<del> if code, err := runCommand(cmd); err == nil || code == 0 {
<add> if _, code, err := dockerCmdWithError(c, "run", "busybox", "touch", "/sys/kernel/profiling"); err == nil || code == 0 {
<ide> c.Fatal("sys should not be writable in a non privileged container")
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunSysWritableInPrivilegedContainers(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--privileged", "busybox", "touch", "/sys/kernel/profiling")
<del> if code, err := runCommand(cmd); err != nil || code != 0 {
<add> if _, code, err := dockerCmdWithError(c, "run", "--privileged", "busybox", "touch", "/sys/kernel/profiling"); err != nil || code != 0 {
<ide> c.Fatalf("sys should be writable in privileged container")
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunProcNotWritableInNonPrivilegedContainers(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "busybox", "touch", "/proc/sysrq-trigger")
<del> if code, err := runCommand(cmd); err == nil || code == 0 {
<add> if _, code, err := dockerCmdWithError(c, "run", "busybox", "touch", "/proc/sysrq-trigger"); err == nil || code == 0 {
<ide> c.Fatal("proc should not be writable in a non privileged container")
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunProcWritableInPrivilegedContainers(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--privileged", "busybox", "touch", "/proc/sysrq-trigger")
<del> if code, err := runCommand(cmd); err != nil || code != 0 {
<add> if _, code := dockerCmd(c, "run", "--privileged", "busybox", "touch", "/proc/sysrq-trigger"); code != 0 {
<ide> c.Fatalf("proc should be writable in privileged container")
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunWithCpuset(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--cpuset", "0", "busybox", "true")
<del> if code, err := runCommand(cmd); err != nil || code != 0 {
<del> c.Fatalf("container should run successfully with cpuset of 0: %s", err)
<add> if _, code := dockerCmd(c, "run", "--cpuset", "0", "busybox", "true"); code != 0 {
<add> c.Fatalf("container should run successfully with cpuset of 0")
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunWithCpusetCpus(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--cpuset-cpus", "0", "busybox", "true")
<del> if code, err := runCommand(cmd); err != nil || code != 0 {
<del> c.Fatalf("container should run successfully with cpuset-cpus of 0: %s", err)
<add> if _, code := dockerCmd(c, "run", "--cpuset-cpus", "0", "busybox", "true"); code != 0 {
<add> c.Fatalf("container should run successfully with cpuset-cpus of 0")
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunWithCpusetMems(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--cpuset-mems", "0", "busybox", "true")
<del> if code, err := runCommand(cmd); err != nil || code != 0 {
<del> c.Fatalf("container should run successfully with cpuset-mems of 0: %s", err)
<add> if _, code := dockerCmd(c, "run", "--cpuset-mems", "0", "busybox", "true"); code != 0 {
<add> c.Fatalf("container should run successfully with cpuset-mems of 0")
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunWithBlkioWeight(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--blkio-weight", "300", "busybox", "true")
<del> if code, err := runCommand(cmd); err != nil || code != 0 {
<del> c.Fatalf("container should run successfully with blkio-weight of 300: %s", err)
<add> if _, code := dockerCmd(c, "run", "--blkio-weight", "300", "busybox", "true"); code != 0 {
<add> c.Fatalf("container should run successfully with blkio-weight of 300")
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunWithBlkioInvalidWeight(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--blkio-weight", "5", "busybox", "true")
<del> if _, err := runCommand(cmd); err == nil {
<add> if _, _, err := dockerCmdWithError(c, "run", "--blkio-weight", "5", "busybox", "true"); err == nil {
<ide> c.Fatalf("run with invalid blkio-weight should failed")
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunDeviceNumbers(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "busybox", "sh", "-c", "ls -l /dev/null")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "ls -l /dev/null")
<ide> deviceLineFields := strings.Fields(out)
<ide> deviceLineFields[6] = ""
<ide> deviceLineFields[7] = ""
<ide> func (s *DockerSuite) TestRunDeviceNumbers(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunThatCharacterDevicesActLikeCharacterDevices(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "busybox", "sh", "-c", "dd if=/dev/zero of=/zero bs=1k count=5 2> /dev/null ; du -h /zero")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<del>
<add> out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "dd if=/dev/zero of=/zero bs=1k count=5 2> /dev/null ; du -h /zero")
<ide> if actual := strings.Trim(out, "\r\n"); actual[0] == '0' {
<ide> c.Fatalf("expected a new file called /zero to be create that is greater than 0 bytes long, but du says: %s", actual)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunUnprivilegedWithChroot(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "busybox", "chroot", "/", "true")
<del> if _, err := runCommand(cmd); err != nil {
<del> c.Fatal(err)
<del> }
<add> dockerCmd(c, "run", "busybox", "chroot", "/", "true")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunAddingOptionalDevices(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--device", "/dev/zero:/dev/nulo", "busybox", "sh", "-c", "ls /dev/nulo")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<del>
<add> out, _ := dockerCmd(c, "run", "--device", "/dev/zero:/dev/nulo", "busybox", "sh", "-c", "ls /dev/nulo")
<ide> if actual := strings.Trim(out, "\r\n"); actual != "/dev/nulo" {
<ide> c.Fatalf("expected output /dev/nulo, received %s", actual)
<ide> }
<ide> func (s *DockerSuite) TestRunAddingOptionalDevices(c *check.C) {
<ide> func (s *DockerSuite) TestRunModeHostname(c *check.C) {
<ide> testRequires(c, SameHostDaemon)
<ide>
<del> cmd := exec.Command(dockerBinary, "run", "-h=testhostname", "busybox", "cat", "/etc/hostname")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "-h=testhostname", "busybox", "cat", "/etc/hostname")
<ide>
<ide> if actual := strings.Trim(out, "\r\n"); actual != "testhostname" {
<ide> c.Fatalf("expected 'testhostname', but says: %q", actual)
<ide> }
<ide>
<del> cmd = exec.Command(dockerBinary, "run", "--net=host", "busybox", "cat", "/etc/hostname")
<add> out, _ = dockerCmd(c, "run", "--net=host", "busybox", "cat", "/etc/hostname")
<ide>
<del> out, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<ide> hostname, err := os.Hostname()
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> func (s *DockerSuite) TestRunModeHostname(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunRootWorkdir(c *check.C) {
<del> out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--workdir", "/", "busybox", "pwd"))
<del> if err != nil {
<del> c.Fatalf("Failed with errors: %s, %v", out, err)
<del> }
<add> out, _ := dockerCmd(c, "run", "--workdir", "/", "busybox", "pwd")
<ide> if out != "/\n" {
<ide> c.Fatalf("pwd returned %q (expected /\\n)", s)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunAllowBindMountingRoot(c *check.C) {
<del> out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-v", "/:/host", "busybox", "ls", "/host"))
<del> if err != nil {
<del> c.Fatalf("Failed with errors: %s, %v", out, err)
<del> }
<add> dockerCmd(c, "run", "-v", "/:/host", "busybox", "ls", "/host")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunDisallowBindMountingRootToRoot(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "-v", "/:/", "busybox", "ls", "/host")
<del> out, _, err := runCommandWithOutput(cmd)
<add> out, _, err := dockerCmdWithError(c, "run", "-v", "/:/", "busybox", "ls", "/host")
<ide> if err == nil {
<ide> c.Fatal(out, err)
<ide> }
<ide> func (s *DockerSuite) TestRunDnsDefaultOptions(c *check.C) {
<ide> c.Fatal(err)
<ide> }
<ide>
<del> cmd := exec.Command(dockerBinary, "run", "busybox", "cat", "/etc/resolv.conf")
<del>
<del> actual, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, actual)
<del> }
<del>
<add> actual, _ := dockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf")
<ide> // check that the actual defaults are appended to the commented out
<ide> // localhost resolver (which should be preserved)
<ide> // NOTE: if we ever change the defaults from google dns, this will break
<ide> func (s *DockerSuite) TestRunDnsOptionsBasedOnHostResolvConf(c *check.C) {
<ide> hostSearch := resolvconf.GetSearchDomains(origResolvConf)
<ide>
<ide> var out string
<del> cmd := exec.Command(dockerBinary, "run", "--dns=127.0.0.1", "busybox", "cat", "/etc/resolv.conf")
<del> if out, _, _, err = runCommandWithStdoutStderr(cmd); err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ = dockerCmd(c, "run", "--dns=127.0.0.1", "busybox", "cat", "/etc/resolv.conf")
<ide>
<ide> if actualNameservers := resolvconf.GetNameservers([]byte(out)); string(actualNameservers[0]) != "127.0.0.1" {
<ide> c.Fatalf("expected '127.0.0.1', but says: %q", string(actualNameservers[0]))
<ide> func (s *DockerSuite) TestRunDnsOptionsBasedOnHostResolvConf(c *check.C) {
<ide> }
<ide> }
<ide>
<del> cmd = exec.Command(dockerBinary, "run", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf")
<del>
<del> if out, _, err = runCommandWithOutput(cmd); err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ = dockerCmd(c, "run", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf")
<ide>
<ide> actualNameservers := resolvconf.GetNameservers([]byte(out))
<ide> if len(actualNameservers) != len(hostNamservers) {
<ide> func (s *DockerSuite) TestRunDnsOptionsBasedOnHostResolvConf(c *check.C) {
<ide> hostNamservers = resolvconf.GetNameservers(resolvConf)
<ide> hostSearch = resolvconf.GetSearchDomains(resolvConf)
<ide>
<del> cmd = exec.Command(dockerBinary, "run", "busybox", "cat", "/etc/resolv.conf")
<del>
<del> if out, _, err = runCommandWithOutput(cmd); err != nil {
<del> c.Fatal(err, out)
<del> }
<del>
<add> out, _ = dockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf")
<ide> if actualNameservers = resolvconf.GetNameservers([]byte(out)); string(actualNameservers[0]) != "12.34.56.78" || len(actualNameservers) != 1 {
<ide> c.Fatalf("expected '12.34.56.78', but has: %v", actualNameservers)
<ide> }
<ide> func (s *DockerSuite) TestRunNonRootUserResolvName(c *check.C) {
<ide> testRequires(c, SameHostDaemon)
<ide> testRequires(c, Network)
<ide>
<del> cmd := exec.Command(dockerBinary, "run", "--name=testperm", "--user=default", "busybox", "ping", "-c", "1", "www.docker.io")
<del> if out, err := runCommand(cmd); err != nil {
<del> c.Fatal(err, out)
<del> }
<add> dockerCmd(c, "run", "--name=testperm", "--user=default", "busybox", "ping", "-c", "1", "www.docker.io")
<ide>
<ide> cID, err := getIDByName("testperm")
<ide> if err != nil {
<ide> func (s *DockerSuite) TestRunResolvconfUpdate(c *check.C) {
<ide> }()
<ide>
<ide> //1. test that a restarting container gets an updated resolv.conf
<del> cmd = exec.Command(dockerBinary, "run", "--name='first'", "busybox", "true")
<del> if _, err := runCommand(cmd); err != nil {
<del> c.Fatal(err)
<del> }
<add> dockerCmd(c, "run", "--name='first'", "busybox", "true")
<ide> containerID1, err := getIDByName("first")
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> func (s *DockerSuite) TestRunResolvconfUpdate(c *check.C) {
<ide> }
<ide>
<ide> // start the container again to pickup changes
<del> cmd = exec.Command(dockerBinary, "start", "first")
<del> if out, err := runCommand(cmd); err != nil {
<del> c.Fatalf("Errored out %s, \nerror: %v", string(out), err)
<del> }
<add> dockerCmd(c, "start", "first")
<ide>
<ide> // check for update in container
<ide> containerResolv, err := readContainerFile(containerID1, "resolv.conf")
<ide> func (s *DockerSuite) TestRunResolvconfUpdate(c *check.C) {
<ide>
<ide> /* //make a change to resolv.conf (in this case replacing our tmp copy with orig copy)
<ide> if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
<del> c.Fatal(err)
<del> } */
<add> c.Fatal(err)
<add> } */
<ide> //2. test that a restarting container does not receive resolv.conf updates
<ide> // if it modified the container copy of the starting point resolv.conf
<del> cmd = exec.Command(dockerBinary, "run", "--name='second'", "busybox", "sh", "-c", "echo 'search mylittlepony.com' >>/etc/resolv.conf")
<del> if _, err = runCommand(cmd); err != nil {
<del> c.Fatal(err)
<del> }
<add> dockerCmd(c, "run", "--name='second'", "busybox", "sh", "-c", "echo 'search mylittlepony.com' >>/etc/resolv.conf")
<ide> containerID2, err := getIDByName("second")
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> func (s *DockerSuite) TestRunResolvconfUpdate(c *check.C) {
<ide> }
<ide>
<ide> // start the container again
<del> cmd = exec.Command(dockerBinary, "start", "second")
<del> if out, err := runCommand(cmd); err != nil {
<del> c.Fatalf("Errored out %s, \nerror: %v", string(out), err)
<del> }
<add> dockerCmd(c, "start", "second")
<ide>
<ide> // check for update in container
<ide> containerResolv, err = readContainerFile(containerID2, "resolv.conf")
<ide> func (s *DockerSuite) TestRunResolvconfUpdate(c *check.C) {
<ide> }
<ide>
<ide> //3. test that a running container's resolv.conf is not modified while running
<del> cmd = exec.Command(dockerBinary, "run", "-d", "busybox", "top")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err)
<del> }
<add> out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
<ide> runningContainerID := strings.TrimSpace(out)
<ide>
<ide> // replace resolv.conf
<ide> func (s *DockerSuite) TestRunResolvconfUpdate(c *check.C) {
<ide>
<ide> //4. test that a running container's resolv.conf is updated upon restart
<ide> // (the above container is still running..)
<del> cmd = exec.Command(dockerBinary, "restart", runningContainerID)
<del> if _, err = runCommand(cmd); err != nil {
<del> c.Fatal(err)
<del> }
<add> dockerCmd(c, "restart", runningContainerID)
<ide>
<ide> // check for update in container
<ide> containerResolv, err = readContainerFile(runningContainerID, "resolv.conf")
<ide> func (s *DockerSuite) TestRunResolvconfUpdate(c *check.C) {
<ide> }
<ide>
<ide> // start the container again to pickup changes
<del> cmd = exec.Command(dockerBinary, "start", "first")
<del> if out, err := runCommand(cmd); err != nil {
<del> c.Fatalf("Errored out %s, \nerror: %v", string(out), err)
<del> }
<add> dockerCmd(c, "start", "first")
<ide>
<ide> // our first exited container ID should have been updated, but with default DNS
<ide> // after the cleanup of resolv.conf found only a localhost nameserver:
<ide> func (s *DockerSuite) TestRunResolvconfUpdate(c *check.C) {
<ide> }
<ide>
<ide> // Run the container so it picks up the old settings
<del> cmd = exec.Command(dockerBinary, "run", "--name='third'", "busybox", "true")
<del> if _, err := runCommand(cmd); err != nil {
<del> c.Fatal(err)
<del> }
<add> dockerCmd(c, "run", "--name='third'", "busybox", "true")
<ide> containerID3, err := getIDByName("third")
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> func (s *DockerSuite) TestRunResolvconfUpdate(c *check.C) {
<ide> }
<ide>
<ide> // start the container again to pickup changes
<del> cmd = exec.Command(dockerBinary, "start", "third")
<del> if out, err := runCommand(cmd); err != nil {
<del> c.Fatalf("Errored out %s, \nerror: %v", string(out), err)
<del> }
<add> dockerCmd(c, "start", "third")
<ide>
<ide> // check for update in container
<ide> containerResolv, err = readContainerFile(containerID3, "resolv.conf")
<ide> func (s *DockerSuite) TestRunResolvconfUpdate(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunAddHost(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--add-host=extra:86.75.30.9", "busybox", "grep", "extra", "/etc/hosts")
<del>
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "--add-host=extra:86.75.30.9", "busybox", "grep", "extra", "/etc/hosts")
<ide>
<ide> actual := strings.Trim(out, "\r\n")
<ide> if actual != "86.75.30.9\textra" {
<ide> func (s *DockerSuite) TestRunAddHost(c *check.C) {
<ide>
<ide> // Regression test for #6983
<ide> func (s *DockerSuite) TestRunAttachStdErrOnlyTTYMode(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "-t", "-a", "stderr", "busybox", "true")
<del> exitCode, err := runCommand(cmd)
<del> if err != nil {
<del> c.Fatal(err)
<del> } else if exitCode != 0 {
<add> _, exitCode := dockerCmd(c, "run", "-t", "-a", "stderr", "busybox", "true")
<add> if exitCode != 0 {
<ide> c.Fatalf("Container should have exited with error code 0")
<ide> }
<ide> }
<ide>
<ide> // Regression test for #6983
<ide> func (s *DockerSuite) TestRunAttachStdOutOnlyTTYMode(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "-t", "-a", "stdout", "busybox", "true")
<del>
<del> exitCode, err := runCommand(cmd)
<del> if err != nil {
<del> c.Fatal(err)
<del> } else if exitCode != 0 {
<add> _, exitCode := dockerCmd(c, "run", "-t", "-a", "stdout", "busybox", "true")
<add> if exitCode != 0 {
<ide> c.Fatalf("Container should have exited with error code 0")
<ide> }
<ide> }
<ide>
<ide> // Regression test for #6983
<ide> func (s *DockerSuite) TestRunAttachStdOutAndErrTTYMode(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "-t", "-a", "stdout", "-a", "stderr", "busybox", "true")
<del> exitCode, err := runCommand(cmd)
<del> if err != nil {
<del> c.Fatal(err)
<del> } else if exitCode != 0 {
<add> _, exitCode := dockerCmd(c, "run", "-t", "-a", "stdout", "-a", "stderr", "busybox", "true")
<add> if exitCode != 0 {
<ide> c.Fatalf("Container should have exited with error code 0")
<ide> }
<ide> }
<ide> func (s *DockerSuite) TestRunAttachWithDetach(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunState(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
<add> out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
<ide>
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<ide> id := strings.TrimSpace(out)
<ide> state, err := inspectField(id, "State.Running")
<ide> c.Assert(err, check.IsNil)
<ide> func (s *DockerSuite) TestRunState(c *check.C) {
<ide> c.Fatal("Container state Pid 0")
<ide> }
<ide>
<del> cmd = exec.Command(dockerBinary, "stop", id)
<del> out, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> dockerCmd(c, "stop", id)
<ide> state, err = inspectField(id, "State.Running")
<ide> c.Assert(err, check.IsNil)
<ide> if state != "false" {
<ide> func (s *DockerSuite) TestRunState(c *check.C) {
<ide> c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1)
<ide> }
<ide>
<del> cmd = exec.Command(dockerBinary, "start", id)
<del> out, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> dockerCmd(c, "start", id)
<ide> state, err = inspectField(id, "State.Running")
<ide> c.Assert(err, check.IsNil)
<ide> if state != "true" {
<ide> func (s *DockerSuite) TestRunCopyVolumeUidGid(c *check.C) {
<ide> }
<ide>
<ide> // Test that the uid and gid is copied from the image to the volume
<del> cmd := exec.Command(dockerBinary, "run", "--rm", "-v", "/hello", name, "sh", "-c", "ls -l / | grep hello | awk '{print $3\":\"$4}'")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "--rm", "-v", "/hello", name, "sh", "-c", "ls -l / | grep hello | awk '{print $3\":\"$4}'")
<ide> out = strings.TrimSpace(out)
<ide> if out != "dockerio:dockerio" {
<ide> c.Fatalf("Wrong /hello ownership: %s, expected dockerio:dockerio", out)
<ide> func (s *DockerSuite) TestRunCopyVolumeContent(c *check.C) {
<ide> }
<ide>
<ide> // Test that the content is copied from the image to the volume
<del> cmd := exec.Command(dockerBinary, "run", "--rm", "-v", "/hello", name, "find", "/hello")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "--rm", "-v", "/hello", name, "find", "/hello")
<ide> if !(strings.Contains(out, "/hello/local/world") && strings.Contains(out, "/hello/local")) {
<ide> c.Fatal("Container failed to transfer content to volume")
<ide> }
<ide> func (s *DockerSuite) TestRunCleanupCmdOnEntrypoint(c *check.C) {
<ide> if _, err := buildImage(name,
<ide> `FROM busybox
<ide> ENTRYPOINT ["echo"]
<del> CMD ["testingpoint"]`,
<add> CMD ["testingpoint"]`,
<ide> true); err != nil {
<ide> c.Fatal(err)
<ide> }
<del> runCmd := exec.Command(dockerBinary, "run", "--entrypoint", "whoami", name)
<del> out, exit, err := runCommandWithOutput(runCmd)
<del> if err != nil {
<del> c.Fatalf("Error: %v, out: %q", err, out)
<del> }
<add>
<add> out, exit := dockerCmd(c, "run", "--entrypoint", "whoami", name)
<ide> if exit != 0 {
<ide> c.Fatalf("expected exit code 0 received %d, out: %q", exit, out)
<ide> }
<ide> func (s *DockerSuite) TestRunCleanupCmdOnEntrypoint(c *check.C) {
<ide>
<ide> // TestRunWorkdirExistsAndIsFile checks that if 'docker run -w' with existing file can be detected
<ide> func (s *DockerSuite) TestRunWorkdirExistsAndIsFile(c *check.C) {
<del> runCmd := exec.Command(dockerBinary, "run", "-w", "/bin/cat", "busybox")
<del> out, exit, err := runCommandWithOutput(runCmd)
<add> out, exit, err := dockerCmdWithError(c, "run", "-w", "/bin/cat", "busybox")
<ide> if !(err != nil && exit == 1 && strings.Contains(out, "Cannot mkdir: /bin/cat is not a directory")) {
<ide> c.Fatalf("Docker must complains about making dir, but we got out: %s, exit: %d, err: %s", out, exit, err)
<ide> }
<ide> func (s *DockerSuite) TestRunExitOnStdinClose(c *check.C) {
<ide> // Test for #2267
<ide> func (s *DockerSuite) TestRunWriteHostsFileAndNotCommit(c *check.C) {
<ide> name := "writehosts"
<del> cmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hosts && cat /etc/hosts")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hosts && cat /etc/hosts")
<ide> if !strings.Contains(out, "test2267") {
<ide> c.Fatal("/etc/hosts should contain 'test2267'")
<ide> }
<ide>
<del> cmd = exec.Command(dockerBinary, "diff", name)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<del> out, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<del>
<add> out, _ = dockerCmd(c, "diff", name)
<ide> if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) {
<ide> c.Fatal("diff should be empty")
<ide> }
<ide> }
<ide>
<ide> func eqToBaseDiff(out string, c *check.C) bool {
<del> cmd := exec.Command(dockerBinary, "run", "-d", "busybox", "echo", "hello")
<del> out1, _, err := runCommandWithOutput(cmd)
<add> out1, _ := dockerCmd(c, "run", "-d", "busybox", "echo", "hello")
<ide> cID := strings.TrimSpace(out1)
<del> cmd = exec.Command(dockerBinary, "diff", cID)
<del> baseDiff, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, baseDiff)
<del> }
<add>
<add> baseDiff, _ := dockerCmd(c, "diff", cID)
<ide> baseArr := strings.Split(baseDiff, "\n")
<ide> sort.Strings(baseArr)
<ide> outArr := strings.Split(out, "\n")
<ide> func sliceEq(a, b []string) bool {
<ide> // Test for #2267
<ide> func (s *DockerSuite) TestRunWriteHostnameFileAndNotCommit(c *check.C) {
<ide> name := "writehostname"
<del> cmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hostname && cat /etc/hostname")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hostname && cat /etc/hostname")
<ide> if !strings.Contains(out, "test2267") {
<ide> c.Fatal("/etc/hostname should contain 'test2267'")
<ide> }
<ide>
<del> cmd = exec.Command(dockerBinary, "diff", name)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<del> out, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ = dockerCmd(c, "diff", name)
<ide> if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) {
<ide> c.Fatal("diff should be empty")
<ide> }
<ide> func (s *DockerSuite) TestRunWriteHostnameFileAndNotCommit(c *check.C) {
<ide> // Test for #2267
<ide> func (s *DockerSuite) TestRunWriteResolvFileAndNotCommit(c *check.C) {
<ide> name := "writeresolv"
<del> cmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/resolv.conf && cat /etc/resolv.conf")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/resolv.conf && cat /etc/resolv.conf")
<ide> if !strings.Contains(out, "test2267") {
<ide> c.Fatal("/etc/resolv.conf should contain 'test2267'")
<ide> }
<ide>
<del> cmd = exec.Command(dockerBinary, "diff", name)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<del> out, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ = dockerCmd(c, "diff", name)
<ide> if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) {
<ide> c.Fatal("diff should be empty")
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunWithBadDevice(c *check.C) {
<ide> name := "baddevice"
<del> cmd := exec.Command(dockerBinary, "run", "--name", name, "--device", "/etc", "busybox", "true")
<del> out, _, err := runCommandWithOutput(cmd)
<add> out, _, err := dockerCmdWithError(c, "run", "--name", name, "--device", "/etc", "busybox", "true")
<add>
<ide> if err == nil {
<ide> c.Fatal("Run should fail with bad device")
<ide> }
<ide> func (s *DockerSuite) TestRunWithBadDevice(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestRunEntrypoint(c *check.C) {
<ide> name := "entrypoint"
<del> cmd := exec.Command(dockerBinary, "run", "--name", name, "--entrypoint", "/bin/echo", "busybox", "-n", "foobar")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "--name", name, "--entrypoint", "/bin/echo", "busybox", "-n", "foobar")
<add>
<ide> expected := "foobar"
<ide> if out != expected {
<ide> c.Fatalf("Output should be %q, actual out: %q", expected, out)
<ide> func (s *DockerSuite) TestRunBindMounts(c *check.C) {
<ide> writeFile(path.Join(tmpDir, "touch-me"), "", c)
<ide>
<ide> // Test reading from a read-only bind mount
<del> cmd := exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox", "ls", "/tmp")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox", "ls", "/tmp")
<ide> if !strings.Contains(out, "touch-me") {
<ide> c.Fatal("Container failed to read from bind mount")
<ide> }
<ide>
<ide> // test writing to bind mount
<del> cmd = exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s:/tmp:rw", tmpDir), "busybox", "touch", "/tmp/holla")
<del> out, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp:rw", tmpDir), "busybox", "touch", "/tmp/holla")
<add>
<ide> readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist
<ide>
<ide> // test mounting to an illegal destination directory
<del> cmd = exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s:.", tmpDir), "busybox", "ls", ".")
<del> _, err = runCommand(cmd)
<add> _, _, err = dockerCmdWithError(c, "run", "-v", fmt.Sprintf("%s:.", tmpDir), "busybox", "ls", ".")
<ide> if err == nil {
<ide> c.Fatal("Container bind mounted illegal directory")
<ide> }
<ide>
<ide> // test mount a file
<del> cmd = exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s/holla:/tmp/holla:rw", tmpDir), "busybox", "sh", "-c", "echo -n 'yotta' > /tmp/holla")
<del> _, err = runCommand(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> dockerCmd(c, "run", "-v", fmt.Sprintf("%s/holla:/tmp/holla:rw", tmpDir), "busybox", "sh", "-c", "echo -n 'yotta' > /tmp/holla")
<ide> content := readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist
<ide> expected := "yotta"
<ide> if content != expected {
<ide> func (s *DockerSuite) TestRunCidFileCleanupIfEmpty(c *check.C) {
<ide> }
<ide> defer os.RemoveAll(tmpDir)
<ide> tmpCidFile := path.Join(tmpDir, "cid")
<del> cmd := exec.Command(dockerBinary, "run", "--cidfile", tmpCidFile, "emptyfs")
<del> out, _, err := runCommandWithOutput(cmd)
<add>
<add> out, _, err := dockerCmdWithError(c, "run", "--cidfile", tmpCidFile, "emptyfs")
<ide> if err == nil {
<ide> c.Fatalf("Run without command must fail. out=%s", out)
<ide> } else if !strings.Contains(out, "No command specified") {
<ide> func (s *DockerSuite) TestRunCidFileCheckIDLength(c *check.C) {
<ide> }
<ide> tmpCidFile := path.Join(tmpDir, "cid")
<ide> defer os.RemoveAll(tmpDir)
<del> cmd := exec.Command(dockerBinary, "run", "-d", "--cidfile", tmpCidFile, "busybox", "true")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err)
<del> }
<add>
<add> out, _ := dockerCmd(c, "run", "-d", "--cidfile", tmpCidFile, "busybox", "true")
<add>
<ide> id := strings.TrimSpace(out)
<ide> buffer, err := ioutil.ReadFile(tmpCidFile)
<ide> if err != nil {
<ide> func (s *DockerSuite) TestRunCidFileCheckIDLength(c *check.C) {
<ide> func (s *DockerSuite) TestRunSetMacAddress(c *check.C) {
<ide> mac := "12:34:56:78:9a:bc"
<ide>
<del> cmd := exec.Command(dockerBinary, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "/bin/sh", "-c", "ip link show eth0 | tail -1 | awk '{print $2}'")
<del> out, ec, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatalf("exec failed:\nexit code=%v\noutput=%s", ec, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "/bin/sh", "-c", "ip link show eth0 | tail -1 | awk '{print $2}'")
<add>
<ide> actualMac := strings.TrimSpace(out)
<ide> if actualMac != mac {
<ide> c.Fatalf("Set MAC address with --mac-address failed. The container has an incorrect MAC address: %q, expected: %q", actualMac, mac)
<ide> func (s *DockerSuite) TestRunSetMacAddress(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestRunInspectMacAddress(c *check.C) {
<ide> mac := "12:34:56:78:9a:bc"
<del> cmd := exec.Command(dockerBinary, "run", "-d", "--mac-address="+mac, "busybox", "top")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err)
<del> }
<add> out, _ := dockerCmd(c, "run", "-d", "--mac-address="+mac, "busybox", "top")
<add>
<ide> id := strings.TrimSpace(out)
<ide> inspectedMac, err := inspectField(id, "NetworkSettings.MacAddress")
<ide> c.Assert(err, check.IsNil)
<ide> func (s *DockerSuite) TestRunInspectMacAddress(c *check.C) {
<ide>
<ide> // test docker run use a invalid mac address
<ide> func (s *DockerSuite) TestRunWithInvalidMacAddress(c *check.C) {
<del> runCmd := exec.Command(dockerBinary, "run", "--mac-address", "92:d0:c6:0a:29", "busybox")
<del> out, _, err := runCommandWithOutput(runCmd)
<add> out, _, err := dockerCmdWithError(c, "run", "--mac-address", "92:d0:c6:0a:29", "busybox")
<ide> //use a invalid mac address should with a error out
<ide> if err == nil || !strings.Contains(out, "is not a valid mac address") {
<ide> c.Fatalf("run with an invalid --mac-address should with error out")
<ide> func (s *DockerSuite) TestRunWithInvalidMacAddress(c *check.C) {
<ide> func (s *DockerSuite) TestRunDeallocatePortOnMissingIptablesRule(c *check.C) {
<ide> testRequires(c, SameHostDaemon)
<ide>
<del> cmd := exec.Command(dockerBinary, "run", "-d", "-p", "23:23", "busybox", "top")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err)
<del> }
<add> out, _ := dockerCmd(c, "run", "-d", "-p", "23:23", "busybox", "top")
<add>
<ide> id := strings.TrimSpace(out)
<ide> ip, err := inspectField(id, "NetworkSettings.IPAddress")
<ide> c.Assert(err, check.IsNil)
<ide> func (s *DockerSuite) TestRunDeallocatePortOnMissingIptablesRule(c *check.C) {
<ide> if err := deleteContainer(id); err != nil {
<ide> c.Fatal(err)
<ide> }
<del> cmd = exec.Command(dockerBinary, "run", "-d", "-p", "23:23", "busybox", "top")
<del> out, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add>
<add> dockerCmd(c, "run", "-d", "-p", "23:23", "busybox", "top")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunPortInUse(c *check.C) {
<ide> testRequires(c, SameHostDaemon)
<ide>
<ide> port := "1234"
<del> cmd := exec.Command(dockerBinary, "run", "-d", "-p", port+":80", "busybox", "top")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatalf("Fail to run listening container")
<del> }
<add> dockerCmd(c, "run", "-d", "-p", port+":80", "busybox", "top")
<ide>
<del> cmd = exec.Command(dockerBinary, "run", "-d", "-p", port+":80", "busybox", "top")
<del> out, _, err = runCommandWithOutput(cmd)
<add> out, _, err := dockerCmdWithError(c, "run", "-d", "-p", port+":80", "busybox", "top")
<ide> if err == nil {
<ide> c.Fatalf("Binding on used port must fail")
<ide> }
<ide> func (s *DockerSuite) TestRunPortInUse(c *check.C) {
<ide> // https://github.com/docker/docker/issues/12148
<ide> func (s *DockerSuite) TestRunAllocatePortInReservedRange(c *check.C) {
<ide> // allocate a dynamic port to get the most recent
<del> cmd := exec.Command(dockerBinary, "run", "-d", "-P", "-p", "80", "busybox", "top")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatalf("Failed to run, output: %s, error: %s", out, err)
<del> }
<add> out, _ := dockerCmd(c, "run", "-d", "-P", "-p", "80", "busybox", "top")
<add>
<ide> id := strings.TrimSpace(out)
<add> out, _ = dockerCmd(c, "port", id, "80")
<ide>
<del> cmd = exec.Command(dockerBinary, "port", id, "80")
<del> out, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatalf("Failed to get port, output: %s, error: %s", out, err)
<del> }
<ide> strPort := strings.Split(strings.TrimSpace(out), ":")[1]
<ide> port, err := strconv.ParseInt(strPort, 10, 64)
<ide> if err != nil {
<ide> func (s *DockerSuite) TestRunAllocatePortInReservedRange(c *check.C) {
<ide>
<ide> // allocate a static port and a dynamic port together, with static port
<ide> // takes the next recent port in dynamic port range.
<del> cmd = exec.Command(dockerBinary, "run", "-d", "-P",
<del> "-p", "80",
<del> "-p", fmt.Sprintf("%d:8080", port+1),
<del> "busybox", "top")
<del> out, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatalf("Failed to run, output: %s, error: %s", out, err)
<del> }
<add> dockerCmd(c, "run", "-d", "-P", "-p", "80", "-p", fmt.Sprintf("%d:8080", port+1), "busybox", "top")
<ide> }
<ide>
<ide> // Regression test for #7792
<ide> func (s *DockerSuite) TestRunMountOrdering(c *check.C) {
<ide> c.Fatal(err)
<ide> }
<ide>
<del> cmd := exec.Command(dockerBinary, "run",
<add> dockerCmd(c, "run",
<ide> "-v", fmt.Sprintf("%s:/tmp", tmpDir),
<ide> "-v", fmt.Sprintf("%s:/tmp/foo", fooDir),
<ide> "-v", fmt.Sprintf("%s:/tmp/tmp2", tmpDir2),
<ide> "-v", fmt.Sprintf("%s:/tmp/tmp2/foo", fooDir),
<ide> "busybox:latest", "sh", "-c",
<ide> "ls /tmp/touch-me && ls /tmp/foo/touch-me && ls /tmp/tmp2/touch-me && ls /tmp/tmp2/foo/touch-me")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(out, err)
<del> }
<ide> }
<ide>
<ide> // Regression test for https://github.com/docker/docker/issues/8259
<ide> func (s *DockerSuite) TestRunReuseBindVolumeThatIsSymlink(c *check.C) {
<ide> defer os.RemoveAll(linkPath)
<ide>
<ide> // Create first container
<del> cmd := exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s:/tmp/test", linkPath), "busybox", "ls", "-lh", "/tmp/test")
<del> if _, err := runCommand(cmd); err != nil {
<del> c.Fatal(err)
<del> }
<add> dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp/test", linkPath), "busybox", "ls", "-lh", "/tmp/test")
<ide>
<ide> // Create second container with same symlinked path
<ide> // This will fail if the referenced issue is hit with a "Volume exists" error
<del> cmd = exec.Command(dockerBinary, "run", "-v", fmt.Sprintf("%s:/tmp/test", linkPath), "busybox", "ls", "-lh", "/tmp/test")
<del> if out, _, err := runCommandWithOutput(cmd); err != nil {
<del> c.Fatal(err, out)
<del> }
<add> dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp/test", linkPath), "busybox", "ls", "-lh", "/tmp/test")
<ide> }
<ide>
<ide> //GH#10604: Test an "/etc" volume doesn't overlay special bind mounts in container
<ide> func (s *DockerSuite) TestRunCreateVolumeEtc(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--dns=127.0.0.1", "-v", "/etc", "busybox", "cat", "/etc/resolv.conf")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatalf("failed to run container: %v, output: %q", err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "--dns=127.0.0.1", "-v", "/etc", "busybox", "cat", "/etc/resolv.conf")
<ide> if !strings.Contains(out, "nameserver 127.0.0.1") {
<ide> c.Fatal("/etc volume mount hides /etc/resolv.conf")
<ide> }
<ide>
<del> cmd = exec.Command(dockerBinary, "run", "-h=test123", "-v", "/etc", "busybox", "cat", "/etc/hostname")
<del> out, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatalf("failed to run container: %v, output: %q", err, out)
<del> }
<add> out, _ = dockerCmd(c, "run", "-h=test123", "-v", "/etc", "busybox", "cat", "/etc/hostname")
<ide> if !strings.Contains(out, "test123") {
<ide> c.Fatal("/etc volume mount hides /etc/hostname")
<ide> }
<ide>
<del> cmd = exec.Command(dockerBinary, "run", "--add-host=test:192.168.0.1", "-v", "/etc", "busybox", "cat", "/etc/hosts")
<del> out, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatalf("failed to run container: %v, output: %q", err, out)
<del> }
<add> out, _ = dockerCmd(c, "run", "--add-host=test:192.168.0.1", "-v", "/etc", "busybox", "cat", "/etc/hosts")
<ide> out = strings.Replace(out, "\n", " ", -1)
<ide> if !strings.Contains(out, "192.168.0.1\ttest") || !strings.Contains(out, "127.0.0.1\tlocalhost") {
<ide> c.Fatal("/etc volume mount hides /etc/hosts")
<ide> func (s *DockerSuite) TestRunCreateVolumeEtc(c *check.C) {
<ide> func (s *DockerSuite) TestVolumesNoCopyData(c *check.C) {
<ide> if _, err := buildImage("dataimage",
<ide> `FROM busybox
<del> RUN mkdir -p /foo
<del> RUN touch /foo/bar`,
<add> RUN mkdir -p /foo
<add> RUN touch /foo/bar`,
<ide> true); err != nil {
<ide> c.Fatal(err)
<ide> }
<ide>
<del> cmd := exec.Command(dockerBinary, "run", "--name", "test", "-v", "/foo", "busybox")
<del> if _, err := runCommand(cmd); err != nil {
<del> c.Fatal(err)
<del> }
<add> dockerCmd(c, "run", "--name", "test", "-v", "/foo", "busybox")
<ide>
<del> cmd = exec.Command(dockerBinary, "run", "--volumes-from", "test", "dataimage", "ls", "-lh", "/foo/bar")
<del> if out, _, err := runCommandWithOutput(cmd); err == nil || !strings.Contains(out, "No such file or directory") {
<add> if out, _, err := dockerCmdWithError(c, "run", "--volumes-from", "test", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") {
<ide> c.Fatalf("Data was copied on volumes-from but shouldn't be:\n%q", out)
<ide> }
<ide>
<ide> tmpDir := randomUnixTmpDirPath("docker_test_bind_mount_copy_data")
<del> cmd = exec.Command(dockerBinary, "run", "-v", tmpDir+":/foo", "dataimage", "ls", "-lh", "/foo/bar")
<del> if out, _, err := runCommandWithOutput(cmd); err == nil || !strings.Contains(out, "No such file or directory") {
<add> if out, _, err := dockerCmdWithError(c, "run", "-v", tmpDir+":/foo", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") {
<ide> c.Fatalf("Data was copied on bind-mount but shouldn't be:\n%q", out)
<ide> }
<ide> }
<ide> func (s *DockerSuite) TestRunNoOutputFromPullInStdout(c *check.C) {
<ide> func (s *DockerSuite) TestRunVolumesCleanPaths(c *check.C) {
<ide> if _, err := buildImage("run_volumes_clean_paths",
<ide> `FROM busybox
<del> VOLUME /foo/`,
<add> VOLUME /foo/`,
<ide> true); err != nil {
<ide> c.Fatal(err)
<ide> }
<ide>
<del> cmd := exec.Command(dockerBinary, "run", "-v", "/foo", "-v", "/bar/", "--name", "dark_helmet", "run_volumes_clean_paths")
<del> if out, _, err := runCommandWithOutput(cmd); err != nil {
<del> c.Fatal(err, out)
<del> }
<add> dockerCmd(c, "run", "-v", "/foo", "-v", "/bar/", "--name", "dark_helmet", "run_volumes_clean_paths")
<ide>
<ide> out, err := inspectFieldMap("dark_helmet", "Volumes", "/foo/")
<ide> c.Assert(err, check.IsNil)
<ide> func (s *DockerSuite) TestRunSlowStdoutConsumer(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunAllowPortRangeThroughExpose(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "-d", "--expose", "3000-3003", "-P", "busybox", "top")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err)
<del> }
<add> out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-P", "busybox", "top")
<add>
<ide> id := strings.TrimSpace(out)
<ide> portstr, err := inspectFieldJSON(id, "NetworkSettings.Ports")
<ide> c.Assert(err, check.IsNil)
<ide> func (s *DockerSuite) TestRunAllowPortRangeThroughExpose(c *check.C) {
<ide>
<ide> // test docker run expose a invalid port
<ide> func (s *DockerSuite) TestRunExposePort(c *check.C) {
<del> runCmd := exec.Command(dockerBinary, "run", "--expose", "80000", "busybox")
<del> out, _, err := runCommandWithOutput(runCmd)
<add> out, _, err := dockerCmdWithError(c, "run", "--expose", "80000", "busybox")
<ide> //expose a invalid port should with a error out
<ide> if err == nil || !strings.Contains(out, "Invalid range format for --expose") {
<ide> c.Fatalf("run --expose a invalid port should with error out")
<ide> func (s *DockerSuite) TestRunModeIpcHost(c *check.C) {
<ide> c.Fatal(err)
<ide> }
<ide>
<del> cmd := exec.Command(dockerBinary, "run", "--ipc=host", "busybox", "readlink", "/proc/self/ns/ipc")
<del> out2, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out2)
<del> }
<del>
<del> out2 = strings.Trim(out2, "\n")
<del> if hostIpc != out2 {
<del> c.Fatalf("IPC different with --ipc=host %s != %s\n", hostIpc, out2)
<del> }
<del>
<del> cmd = exec.Command(dockerBinary, "run", "busybox", "readlink", "/proc/self/ns/ipc")
<del> out2, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out2)
<add> out, _ := dockerCmd(c, "run", "--ipc=host", "busybox", "readlink", "/proc/self/ns/ipc")
<add> out = strings.Trim(out, "\n")
<add> if hostIpc != out {
<add> c.Fatalf("IPC different with --ipc=host %s != %s\n", hostIpc, out)
<ide> }
<ide>
<del> out2 = strings.Trim(out2, "\n")
<del> if hostIpc == out2 {
<del> c.Fatalf("IPC should be different without --ipc=host %s == %s\n", hostIpc, out2)
<add> out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/ipc")
<add> out = strings.Trim(out, "\n")
<add> if hostIpc == out {
<add> c.Fatalf("IPC should be different without --ipc=host %s == %s\n", hostIpc, out)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunModeIpcContainer(c *check.C) {
<ide> testRequires(c, SameHostDaemon)
<ide>
<del> cmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
<add>
<ide> id := strings.TrimSpace(out)
<ide> state, err := inspectField(id, "State.Running")
<ide> c.Assert(err, check.IsNil)
<ide> func (s *DockerSuite) TestRunModeIpcContainer(c *check.C) {
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<del> cmd = exec.Command(dockerBinary, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox", "readlink", "/proc/self/ns/ipc")
<del> out2, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out2)
<del> }
<ide>
<del> out2 = strings.Trim(out2, "\n")
<del> if parentContainerIpc != out2 {
<del> c.Fatalf("IPC different with --ipc=container:%s %s != %s\n", id, parentContainerIpc, out2)
<add> out, _ = dockerCmd(c, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox", "readlink", "/proc/self/ns/ipc")
<add> out = strings.Trim(out, "\n")
<add> if parentContainerIpc != out {
<add> c.Fatalf("IPC different with --ipc=container:%s %s != %s\n", id, parentContainerIpc, out)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunModeIpcContainerNotExists(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "-d", "--ipc", "container:abcd1234", "busybox", "top")
<del> out, _, err := runCommandWithOutput(cmd)
<add> out, _, err := dockerCmdWithError(c, "run", "-d", "--ipc", "container:abcd1234", "busybox", "top")
<ide> if !strings.Contains(out, "abcd1234") || err == nil {
<ide> c.Fatalf("run IPC from a non exists container should with correct error out")
<ide> }
<ide> func (s *DockerSuite) TestRunModeIpcContainerNotExists(c *check.C) {
<ide> func (s *DockerSuite) TestRunModeIpcContainerNotRunning(c *check.C) {
<ide> testRequires(c, SameHostDaemon)
<ide>
<del> cmd := exec.Command(dockerBinary, "create", "busybox")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<del> id := strings.TrimSpace(out)
<add> out, _ := dockerCmd(c, "create", "busybox")
<ide>
<del> cmd = exec.Command(dockerBinary, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox")
<del> out, _, err = runCommandWithOutput(cmd)
<add> id := strings.TrimSpace(out)
<add> out, _, err := dockerCmdWithError(c, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox")
<ide> if err == nil {
<ide> c.Fatalf("Run container with ipc mode container should fail with non running container: %s\n%s", out, err)
<ide> }
<ide> func (s *DockerSuite) TestRunModeIpcContainerNotRunning(c *check.C) {
<ide> func (s *DockerSuite) TestContainerNetworkMode(c *check.C) {
<ide> testRequires(c, SameHostDaemon)
<ide>
<del> cmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
<ide> id := strings.TrimSpace(out)
<ide> if err := waitRun(id); err != nil {
<ide> c.Fatal(err)
<ide> func (s *DockerSuite) TestContainerNetworkMode(c *check.C) {
<ide> if err != nil {
<ide> c.Fatal(err)
<ide> }
<del> cmd = exec.Command(dockerBinary, "run", fmt.Sprintf("--net=container:%s", id), "busybox", "readlink", "/proc/self/ns/net")
<del> out2, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out2)
<del> }
<ide>
<del> out2 = strings.Trim(out2, "\n")
<del> if parentContainerNet != out2 {
<del> c.Fatalf("NET different with --net=container:%s %s != %s\n", id, parentContainerNet, out2)
<add> out, _ = dockerCmd(c, "run", fmt.Sprintf("--net=container:%s", id), "busybox", "readlink", "/proc/self/ns/net")
<add> out = strings.Trim(out, "\n")
<add> if parentContainerNet != out {
<add> c.Fatalf("NET different with --net=container:%s %s != %s\n", id, parentContainerNet, out)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunModePidHost(c *check.C) {
<ide> c.Fatal(err)
<ide> }
<ide>
<del> cmd := exec.Command(dockerBinary, "run", "--pid=host", "busybox", "readlink", "/proc/self/ns/pid")
<del> out2, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out2)
<del> }
<del>
<del> out2 = strings.Trim(out2, "\n")
<del> if hostPid != out2 {
<del> c.Fatalf("PID different with --pid=host %s != %s\n", hostPid, out2)
<del> }
<del>
<del> cmd = exec.Command(dockerBinary, "run", "busybox", "readlink", "/proc/self/ns/pid")
<del> out2, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out2)
<add> out, _ := dockerCmd(c, "run", "--pid=host", "busybox", "readlink", "/proc/self/ns/pid")
<add> out = strings.Trim(out, "\n")
<add> if hostPid != out {
<add> c.Fatalf("PID different with --pid=host %s != %s\n", hostPid, out)
<ide> }
<ide>
<del> out2 = strings.Trim(out2, "\n")
<del> if hostPid == out2 {
<del> c.Fatalf("PID should be different without --pid=host %s == %s\n", hostPid, out2)
<add> out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/pid")
<add> out = strings.Trim(out, "\n")
<add> if hostPid == out {
<add> c.Fatalf("PID should be different without --pid=host %s == %s\n", hostPid, out)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunModeUTSHost(c *check.C) {
<ide> c.Fatal(err)
<ide> }
<ide>
<del> cmd := exec.Command(dockerBinary, "run", "--uts=host", "busybox", "readlink", "/proc/self/ns/uts")
<del> out2, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out2)
<del> }
<del>
<del> out2 = strings.Trim(out2, "\n")
<del> if hostUTS != out2 {
<del> c.Fatalf("UTS different with --uts=host %s != %s\n", hostUTS, out2)
<del> }
<del>
<del> cmd = exec.Command(dockerBinary, "run", "busybox", "readlink", "/proc/self/ns/uts")
<del> out2, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out2)
<add> out, _ := dockerCmd(c, "run", "--uts=host", "busybox", "readlink", "/proc/self/ns/uts")
<add> out = strings.Trim(out, "\n")
<add> if hostUTS != out {
<add> c.Fatalf("UTS different with --uts=host %s != %s\n", hostUTS, out)
<ide> }
<ide>
<del> out2 = strings.Trim(out2, "\n")
<del> if hostUTS == out2 {
<del> c.Fatalf("UTS should be different without --uts=host %s == %s\n", hostUTS, out2)
<add> out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/uts")
<add> out = strings.Trim(out, "\n")
<add> if hostUTS == out {
<add> c.Fatalf("UTS should be different without --uts=host %s == %s\n", hostUTS, out)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunTLSverify(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "ps")
<del> out, ec, err := runCommandWithOutput(cmd)
<del> if err != nil || ec != 0 {
<add> if out, code, err := dockerCmdWithError(c, "ps"); err != nil || code != 0 {
<ide> c.Fatalf("Should have worked: %v:\n%v", err, out)
<ide> }
<ide>
<ide> // Regardless of whether we specify true or false we need to
<ide> // test to make sure tls is turned on if --tlsverify is specified at all
<del>
<del> cmd = exec.Command(dockerBinary, "--tlsverify=false", "ps")
<del> out, ec, err = runCommandWithOutput(cmd)
<del> if err == nil || ec == 0 || !strings.Contains(out, "trying to connect") {
<del> c.Fatalf("Should have failed: \net:%v\nout:%v\nerr:%v", ec, out, err)
<add> out, code, err := dockerCmdWithError(c, "--tlsverify=false", "ps")
<add> if err == nil || code == 0 || !strings.Contains(out, "trying to connect") {
<add> c.Fatalf("Should have failed: \net:%v\nout:%v\nerr:%v", code, out, err)
<ide> }
<ide>
<del> cmd = exec.Command(dockerBinary, "--tlsverify=true", "ps")
<del> out, ec, err = runCommandWithOutput(cmd)
<del> if err == nil || ec == 0 || !strings.Contains(out, "cert") {
<del> c.Fatalf("Should have failed: \net:%v\nout:%v\nerr:%v", ec, out, err)
<add> out, code, err = dockerCmdWithError(c, "--tlsverify=true", "ps")
<add> if err == nil || code == 0 || !strings.Contains(out, "cert") {
<add> c.Fatalf("Should have failed: \net:%v\nout:%v\nerr:%v", code, out, err)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunPortFromDockerRangeInUse(c *check.C) {
<ide> // first find allocator current position
<del> cmd := exec.Command(dockerBinary, "run", "-d", "-p", ":80", "busybox", "top")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(out, err)
<del> }
<add> out, _ := dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top")
<add>
<ide> id := strings.TrimSpace(out)
<del> cmd = exec.Command(dockerBinary, "port", id)
<del> out, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(out, err)
<del> }
<del> out = strings.TrimSpace(out)
<add> out, _ = dockerCmd(c, "port", id)
<ide>
<add> out = strings.TrimSpace(out)
<ide> if out == "" {
<ide> c.Fatal("docker port command output is empty")
<ide> }
<ide> func (s *DockerSuite) TestRunPortFromDockerRangeInUse(c *check.C) {
<ide> c.Fatal(err)
<ide> }
<ide> defer l.Close()
<del> cmd = exec.Command(dockerBinary, "run", "-d", "-p", ":80", "busybox", "top")
<del> out, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatalf(out, err)
<del> }
<add>
<add> out, _ = dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top")
<add>
<ide> id = strings.TrimSpace(out)
<del> cmd = exec.Command(dockerBinary, "port", id)
<del> out, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(out, err)
<del> }
<add> dockerCmd(c, "port", id)
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunTtyWithPipe(c *check.C) {
<ide> func (s *DockerSuite) TestRunTtyWithPipe(c *check.C) {
<ide> func (s *DockerSuite) TestRunNonLocalMacAddress(c *check.C) {
<ide> addr := "00:16:3E:08:00:50"
<ide>
<del> cmd := exec.Command(dockerBinary, "run", "--mac-address", addr, "busybox", "ifconfig")
<del> if out, _, err := runCommandWithOutput(cmd); err != nil || !strings.Contains(out, addr) {
<del> c.Fatalf("Output should have contained %q: %s, %v", addr, out, err)
<add> if out, _ := dockerCmd(c, "run", "--mac-address", addr, "busybox", "ifconfig"); !strings.Contains(out, addr) {
<add> c.Fatalf("Output should have contained %q: %s", addr, out)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunNetHost(c *check.C) {
<ide> c.Fatal(err)
<ide> }
<ide>
<del> cmd := exec.Command(dockerBinary, "run", "--net=host", "busybox", "readlink", "/proc/self/ns/net")
<del> out2, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out2)
<del> }
<del>
<del> out2 = strings.Trim(out2, "\n")
<del> if hostNet != out2 {
<del> c.Fatalf("Net namespace different with --net=host %s != %s\n", hostNet, out2)
<del> }
<del>
<del> cmd = exec.Command(dockerBinary, "run", "busybox", "readlink", "/proc/self/ns/net")
<del> out2, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out2)
<add> out, _ := dockerCmd(c, "run", "--net=host", "busybox", "readlink", "/proc/self/ns/net")
<add> out = strings.Trim(out, "\n")
<add> if hostNet != out {
<add> c.Fatalf("Net namespace different with --net=host %s != %s\n", hostNet, out)
<ide> }
<ide>
<del> out2 = strings.Trim(out2, "\n")
<del> if hostNet == out2 {
<del> c.Fatalf("Net namespace should be different without --net=host %s == %s\n", hostNet, out2)
<add> out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/net")
<add> out = strings.Trim(out, "\n")
<add> if hostNet == out {
<add> c.Fatalf("Net namespace should be different without --net=host %s == %s\n", hostNet, out)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunNetHostTwiceSameName(c *check.C) {
<ide> testRequires(c, SameHostDaemon)
<ide>
<del> cmd := exec.Command(dockerBinary, "run", "--rm", "--name=thost", "--net=host", "busybox", "true")
<del> out2, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out2)
<del> }
<del>
<del> cmd = exec.Command(dockerBinary, "run", "--rm", "--name=thost", "--net=host", "busybox", "true")
<del> out2, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out2)
<del> }
<add> dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true")
<add> dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunNetContainerWhichHost(c *check.C) {
<ide> func (s *DockerSuite) TestRunNetContainerWhichHost(c *check.C) {
<ide> c.Fatal(err)
<ide> }
<ide>
<del> cmd := exec.Command(dockerBinary, "run", "-d", "--net=host", "--name=test", "busybox", "top")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<del>
<del> cmd = exec.Command(dockerBinary, "run", "--net=container:test", "busybox", "readlink", "/proc/self/ns/net")
<del> out, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> dockerCmd(c, "run", "-d", "--net=host", "--name=test", "busybox", "top")
<ide>
<add> out, _ := dockerCmd(c, "run", "--net=container:test", "busybox", "readlink", "/proc/self/ns/net")
<ide> out = strings.Trim(out, "\n")
<ide> if hostNet != out {
<ide> c.Fatalf("Container should have host network namespace")
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunAllowPortRangeThroughPublish(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "-d", "--expose", "3000-3003", "-p", "3000-3003", "busybox", "top")
<del> out, _, err := runCommandWithOutput(cmd)
<add> out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-p", "3000-3003", "busybox", "top")
<ide>
<ide> id := strings.TrimSpace(out)
<ide> portstr, err := inspectFieldJSON(id, "NetworkSettings.Ports")
<ide> c.Assert(err, check.IsNil)
<add>
<ide> var ports nat.PortMap
<ide> err = unmarshalJSON([]byte(portstr), &ports)
<ide> for port, binding := range ports {
<ide> func (s *DockerSuite) TestRunAllowPortRangeThroughPublish(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunSetDefaultRestartPolicy(c *check.C) {
<del> runCmd := exec.Command(dockerBinary, "run", "-d", "--name", "test", "busybox", "top")
<del> if out, _, err := runCommandWithOutput(runCmd); err != nil {
<del> c.Fatalf("failed to run container: %v, output: %q", err, out)
<del> }
<add> dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top")
<add>
<ide> out, err := inspectField("test", "HostConfig.RestartPolicy.Name")
<ide> c.Assert(err, check.IsNil)
<ide> if out != "no" {
<ide> func (s *DockerSuite) TestRunSetDefaultRestartPolicy(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunRestartMaxRetries(c *check.C) {
<del> out, err := exec.Command(dockerBinary, "run", "-d", "--restart=on-failure:3", "busybox", "false").CombinedOutput()
<del> if err != nil {
<del> c.Fatal(string(out), err)
<del> }
<add> out, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "false")
<add>
<ide> id := strings.TrimSpace(string(out))
<ide> if err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false false", 10); err != nil {
<ide> c.Fatal(err)
<ide> }
<add>
<ide> count, err := inspectField(id, "RestartCount")
<ide> c.Assert(err, check.IsNil)
<ide> if count != "3" {
<ide> c.Fatalf("Container was restarted %s times, expected %d", count, 3)
<ide> }
<add>
<ide> MaximumRetryCount, err := inspectField(id, "HostConfig.RestartPolicy.MaximumRetryCount")
<ide> c.Assert(err, check.IsNil)
<ide> if MaximumRetryCount != "3" {
<ide> func (s *DockerSuite) TestRunRestartMaxRetries(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunContainerWithWritableRootfs(c *check.C) {
<del> out, err := exec.Command(dockerBinary, "run", "--rm", "busybox", "touch", "/file").CombinedOutput()
<del> if err != nil {
<del> c.Fatal(string(out), err)
<del> }
<add> dockerCmd(c, "run", "--rm", "busybox", "touch", "/file")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunContainerWithReadonlyRootfs(c *check.C) {
<ide> func (s *DockerSuite) TestPermissionsPtsReadonlyRootfs(c *check.C) {
<ide> func testReadOnlyFile(filename string, c *check.C) {
<ide> testRequires(c, NativeExecDriver)
<ide>
<del> out, err := exec.Command(dockerBinary, "run", "--read-only", "--rm", "busybox", "touch", filename).CombinedOutput()
<add> out, _, err := dockerCmdWithError(c, "run", "--read-only", "--rm", "busybox", "touch", filename)
<ide> if err == nil {
<ide> c.Fatal("expected container to error on run with read only error")
<ide> }
<ide> func testReadOnlyFile(filename string, c *check.C) {
<ide> c.Fatalf("expected output from failure to contain %s but contains %s", expected, out)
<ide> }
<ide>
<del> out, err = exec.Command(dockerBinary, "run", "--read-only", "--privileged", "--rm", "busybox", "touch", filename).CombinedOutput()
<add> out, _, err = dockerCmdWithError(c, "run", "--read-only", "--privileged", "--rm", "busybox", "touch", filename)
<ide> if err == nil {
<ide> c.Fatal("expected container to error on run with read only error")
<ide> }
<ide> func testReadOnlyFile(filename string, c *check.C) {
<ide> func (s *DockerSuite) TestRunContainerWithReadonlyEtcHostsAndLinkedContainer(c *check.C) {
<ide> testRequires(c, NativeExecDriver)
<ide>
<del> _, err := runCommand(exec.Command(dockerBinary, "run", "-d", "--name", "test-etc-hosts-ro-linked", "busybox", "top"))
<del> c.Assert(err, check.IsNil)
<del>
<del> out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--read-only", "--link", "test-etc-hosts-ro-linked:testlinked", "busybox", "cat", "/etc/hosts"))
<del> c.Assert(err, check.IsNil)
<add> dockerCmd(c, "run", "-d", "--name", "test-etc-hosts-ro-linked", "busybox", "top")
<ide>
<add> out, _ := dockerCmd(c, "run", "--read-only", "--link", "test-etc-hosts-ro-linked:testlinked", "busybox", "cat", "/etc/hosts")
<ide> if !strings.Contains(string(out), "testlinked") {
<ide> c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled")
<ide> }
<ide> func (s *DockerSuite) TestRunContainerWithReadonlyEtcHostsAndLinkedContainer(c *
<ide> func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithDnsFlag(c *check.C) {
<ide> testRequires(c, NativeExecDriver)
<ide>
<del> out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--read-only", "--dns", "1.1.1.1", "busybox", "/bin/cat", "/etc/resolv.conf"))
<del> c.Assert(err, check.IsNil)
<del>
<add> out, _ := dockerCmd(c, "run", "--read-only", "--dns", "1.1.1.1", "busybox", "/bin/cat", "/etc/resolv.conf")
<ide> if !strings.Contains(string(out), "1.1.1.1") {
<ide> c.Fatal("Expected /etc/resolv.conf to be updated even if --read-only enabled and --dns flag used")
<ide> }
<ide> func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithDnsFlag(c *check.C)
<ide> func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithAddHostFlag(c *check.C) {
<ide> testRequires(c, NativeExecDriver)
<ide>
<del> out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--read-only", "--add-host", "testreadonly:127.0.0.1", "busybox", "/bin/cat", "/etc/hosts"))
<del> c.Assert(err, check.IsNil)
<del>
<add> out, _ := dockerCmd(c, "run", "--read-only", "--add-host", "testreadonly:127.0.0.1", "busybox", "/bin/cat", "/etc/hosts")
<ide> if !strings.Contains(string(out), "testreadonly") {
<ide> c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled and --add-host flag used")
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunVolumesFromRestartAfterRemoved(c *check.C) {
<del> out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", "voltest", "-v", "/foo", "busybox"))
<del> if err != nil {
<del> c.Fatal(out, err)
<del> }
<del>
<del> out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", "restarter", "--volumes-from", "voltest", "busybox", "top"))
<del> if err != nil {
<del> c.Fatal(out, err)
<del> }
<add> dockerCmd(c, "run", "-d", "--name", "voltest", "-v", "/foo", "busybox")
<add> dockerCmd(c, "run", "-d", "--name", "restarter", "--volumes-from", "voltest", "busybox", "top")
<ide>
<ide> // Remove the main volume container and restart the consuming container
<del> out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "rm", "-f", "voltest"))
<del> if err != nil {
<del> c.Fatal(out, err)
<del> }
<add> dockerCmd(c, "rm", "-f", "voltest")
<ide>
<ide> // This should not fail since the volumes-from were already applied
<del> out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "restart", "restarter"))
<del> if err != nil {
<del> c.Fatalf("expected container to restart successfully: %v\n%s", err, out)
<del> }
<add> dockerCmd(c, "restart", "restarter")
<ide> }
<ide>
<ide> // run container with --rm should remove container if exit code != 0
<ide> func (s *DockerSuite) TestRunContainerWithRmFlagExitCodeNotEqualToZero(c *check.C) {
<ide> name := "flowers"
<del> runCmd := exec.Command(dockerBinary, "run", "--name", name, "--rm", "busybox", "ls", "/notexists")
<del> out, _, err := runCommandWithOutput(runCmd)
<add> out, _, err := dockerCmdWithError(c, "run", "--name", name, "--rm", "busybox", "ls", "/notexists")
<ide> if err == nil {
<ide> c.Fatal("Expected docker run to fail", out, err)
<ide> }
<ide> func (s *DockerSuite) TestRunContainerWithRmFlagExitCodeNotEqualToZero(c *check.
<ide>
<ide> func (s *DockerSuite) TestRunContainerWithRmFlagCannotStartContainer(c *check.C) {
<ide> name := "sparkles"
<del> runCmd := exec.Command(dockerBinary, "run", "--name", name, "--rm", "busybox", "commandNotFound")
<del> out, _, err := runCommandWithOutput(runCmd)
<add> out, _, err := dockerCmdWithError(c, "run", "--name", name, "--rm", "busybox", "commandNotFound")
<ide> if err == nil {
<ide> c.Fatal("Expected docker run to fail", out, err)
<ide> }
<ide> func (s *DockerSuite) TestRunContainerWithRmFlagCannotStartContainer(c *check.C)
<ide>
<ide> func (s *DockerSuite) TestRunPidHostWithChildIsKillable(c *check.C) {
<ide> name := "ibuildthecloud"
<del> if out, err := exec.Command(dockerBinary, "run", "-d", "--pid=host", "--name", name, "busybox", "sh", "-c", "sleep 30; echo hi").CombinedOutput(); err != nil {
<del> c.Fatal(err, out)
<del> }
<add> dockerCmd(c, "run", "-d", "--pid=host", "--name", name, "busybox", "sh", "-c", "sleep 30; echo hi")
<add>
<ide> time.Sleep(1 * time.Second)
<ide> errchan := make(chan error)
<ide> go func() {
<del> if out, err := exec.Command(dockerBinary, "kill", name).CombinedOutput(); err != nil {
<add> if out, _, err := dockerCmdWithError(c, "kill", name); err != nil {
<ide> errchan <- fmt.Errorf("%v:\n%s", err, out)
<ide> }
<ide> close(errchan)
<ide> func (s *DockerSuite) TestRunPidHostWithChildIsKillable(c *check.C) {
<ide> func (s *DockerSuite) TestRunWithTooSmallMemoryLimit(c *check.C) {
<ide> // this memory limit is 1 byte less than the min, which is 4MB
<ide> // https://github.com/docker/docker/blob/v1.5.0/daemon/create.go#L22
<del> out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-m", "4194303", "busybox"))
<add> out, _, err := dockerCmdWithError(c, "run", "-m", "4194303", "busybox")
<ide> if err == nil || !strings.Contains(out, "Minimum memory limit allowed is 4MB") {
<ide> c.Fatalf("expected run to fail when using too low a memory limit: %q", out)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunWriteToProcAsound(c *check.C) {
<del> code, err := runCommand(exec.Command(dockerBinary, "run", "busybox", "sh", "-c", "echo 111 >> /proc/asound/version"))
<add> _, code, err := dockerCmdWithError(c, "run", "busybox", "sh", "-c", "echo 111 >> /proc/asound/version")
<ide> if err == nil || code == 0 {
<ide> c.Fatal("standard container should not be able to write to /proc/asound")
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunReadProcTimer(c *check.C) {
<ide> testRequires(c, NativeExecDriver)
<del> out, code, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "busybox", "cat", "/proc/timer_stats"))
<add> out, code, err := dockerCmdWithError(c, "run", "busybox", "cat", "/proc/timer_stats")
<ide> if err != nil || code != 0 {
<ide> c.Fatal(err)
<ide> }
<ide> func (s *DockerSuite) TestRunReadProcLatency(c *check.C) {
<ide> c.Skip("kernel doesnt have latency_stats configured")
<ide> return
<ide> }
<del> out, code, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "busybox", "cat", "/proc/latency_stats"))
<add> out, code, err := dockerCmdWithError(c, "run", "busybox", "cat", "/proc/latency_stats")
<ide> if err != nil || code != 0 {
<ide> c.Fatal(err)
<ide> }
<ide> func (s *DockerSuite) TestRunReadProcLatency(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestMountIntoProc(c *check.C) {
<ide> testRequires(c, NativeExecDriver)
<del> code, err := runCommand(exec.Command(dockerBinary, "run", "-v", "/proc//sys", "busybox", "true"))
<add> _, code, err := dockerCmdWithError(c, "run", "-v", "/proc//sys", "busybox", "true")
<ide> if err == nil || code == 0 {
<ide> c.Fatal("container should not be able to mount into /proc")
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestMountIntoSys(c *check.C) {
<ide> testRequires(c, NativeExecDriver)
<del> _, err := runCommand(exec.Command(dockerBinary, "run", "-v", "/sys/fs/cgroup", "busybox", "true"))
<del> if err != nil {
<del> c.Fatal("container should be able to mount into /sys/fs/cgroup")
<del> }
<add> dockerCmd(c, "run", "-v", "/sys/fs/cgroup", "busybox", "true")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunUnshareProc(c *check.C) {
<ide> testRequires(c, Apparmor, NativeExecDriver)
<ide>
<ide> name := "acidburn"
<del> runCmd := exec.Command(dockerBinary, "run", "--name", name, "jess/unshare", "unshare", "-p", "-m", "-f", "-r", "--mount-proc=/proc", "mount")
<del> if out, _, err := runCommandWithOutput(runCmd); err == nil || !strings.Contains(out, "Permission denied") {
<add> if out, _, err := dockerCmdWithError(c, "run", "--name", name, "jess/unshare", "unshare", "-p", "-m", "-f", "-r", "--mount-proc=/proc", "mount"); err == nil || !strings.Contains(out, "Permission denied") {
<ide> c.Fatalf("unshare should have failed with permission denied, got: %s, %v", out, err)
<ide> }
<ide>
<ide> name = "cereal"
<del> runCmd = exec.Command(dockerBinary, "run", "--name", name, "jess/unshare", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc")
<del> if out, _, err := runCommandWithOutput(runCmd); err == nil || !strings.Contains(out, "Permission denied") {
<add> if out, _, err := dockerCmdWithError(c, "run", "--name", name, "jess/unshare", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc"); err == nil || !strings.Contains(out, "Permission denied") {
<ide> c.Fatalf("unshare should have failed with permission denied, got: %s, %v", out, err)
<ide> }
<ide>
<ide> /* Ensure still fails if running privileged with the default policy */
<ide> name = "crashoverride"
<del> runCmd = exec.Command(dockerBinary, "run", "--privileged", "--security-opt", "apparmor:docker-default", "--name", name, "jess/unshare", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc")
<del> if out, _, err := runCommandWithOutput(runCmd); err == nil || !strings.Contains(out, "Permission denied") {
<add> if out, _, err := dockerCmdWithError(c, "run", "--privileged", "--security-opt", "apparmor:docker-default", "--name", name, "jess/unshare", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc"); err == nil || !strings.Contains(out, "Permission denied") {
<ide> c.Fatalf("unshare should have failed with permission denied, got: %s, %v", out, err)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunPublishPort(c *check.C) {
<del> out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "--name", "test", "--expose", "8080", "busybox", "top"))
<del> c.Assert(err, check.IsNil)
<del> out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "port", "test"))
<del> c.Assert(err, check.IsNil)
<add> dockerCmd(c, "run", "-d", "--name", "test", "--expose", "8080", "busybox", "top")
<add> out, _ := dockerCmd(c, "port", "test")
<ide> out = strings.Trim(out, "\r\n")
<ide> if out != "" {
<ide> c.Fatalf("run without --publish-all should not publish port, out should be nil, but got: %s", out)
<ide> func (s *DockerSuite) TestDevicePermissions(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunCapAddCHOWN(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--cap-drop=ALL", "--cap-add=CHOWN", "busybox", "sh", "-c", "adduser -D -H newuser && chown newuser /home && echo ok")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=CHOWN", "busybox", "sh", "-c", "adduser -D -H newuser && chown newuser /home && echo ok")
<ide>
<ide> if actual := strings.Trim(out, "\r\n"); actual != "ok" {
<ide> c.Fatalf("expected output ok received %s", actual) | 1 |
Javascript | Javascript | add spec for filereadermodule | 0e7a2ca54e623bcaed6999e973ca148e4b30d51c | <ide><path>Libraries/Blob/FileReader.js
<ide>
<ide> const EventTarget = require('event-target-shim');
<ide> const Blob = require('./Blob');
<del>const {FileReaderModule} = require('../BatchedBridge/NativeModules');
<add>import NativeFileReaderModule from './NativeFileReaderModule';
<ide>
<ide> type ReadyState =
<ide> | 0 // EMPTY
<ide> class FileReader extends EventTarget(...READER_EVENTS) {
<ide> readAsDataURL(blob: Blob) {
<ide> this._aborted = false;
<ide>
<del> FileReaderModule.readAsDataURL(blob.data).then(
<add> NativeFileReaderModule.readAsDataURL(blob.data).then(
<ide> (text: string) => {
<ide> if (this._aborted) {
<ide> return;
<ide> class FileReader extends EventTarget(...READER_EVENTS) {
<ide> readAsText(blob: Blob, encoding: string = 'UTF-8') {
<ide> this._aborted = false;
<ide>
<del> FileReaderModule.readAsText(blob.data, encoding).then(
<add> NativeFileReaderModule.readAsText(blob.data, encoding).then(
<ide> (text: string) => {
<ide> if (this._aborted) {
<ide> return;
<ide><path>Libraries/Blob/NativeFileReaderModule.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow
<add> * @format
<add> */
<add>
<add>'use strict';
<add>
<add>import type {TurboModule} from 'RCTExport';
<add>import * as TurboModuleRegistry from 'TurboModuleRegistry';
<add>
<add>export interface Spec extends TurboModule {
<add> +readAsDataURL: (data: Object) => Promise<string>;
<add> +readAsText: (data: Object, encoding: string) => Promise<string>;
<add>}
<add>
<add>export default TurboModuleRegistry.getEnforcing<Spec>('FileReaderModule'); | 2 |
Mixed | Javascript | do deprecation warning outside `node_modules` | 9d4ab9011796902a086ca12b0a18088e2fb35cd4 | <ide><path>doc/api/buffer.md
<ide> It can be constructed in a variety of ways.
<ide> <!-- YAML
<ide> deprecated: v6.0.0
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/19524
<add> description: Calling this constructor emits a deprecation warning when
<add> run from code outside the `node_modules` directory.
<ide> - version: v7.2.1
<ide> pr-url: https://github.com/nodejs/node/pull/9529
<ide> description: Calling this constructor no longer emits a deprecation warning.
<ide> const buf = new Buffer([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
<ide> added: v3.0.0
<ide> deprecated: v6.0.0
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/19524
<add> description: Calling this constructor emits a deprecation warning when
<add> run from code outside the `node_modules` directory.
<ide> - version: v7.2.1
<ide> pr-url: https://github.com/nodejs/node/pull/9529
<ide> description: Calling this constructor no longer emits a deprecation warning.
<ide> console.log(buf);
<ide> <!-- YAML
<ide> deprecated: v6.0.0
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/19524
<add> description: Calling this constructor emits a deprecation warning when
<add> run from code outside the `node_modules` directory.
<ide> - version: v7.2.1
<ide> pr-url: https://github.com/nodejs/node/pull/9529
<ide> description: Calling this constructor no longer emits a deprecation warning.
<ide> console.log(buf2.toString());
<ide> <!-- YAML
<ide> deprecated: v6.0.0
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/19524
<add> description: Calling this constructor emits a deprecation warning when
<add> run from code outside the `node_modules` directory.
<ide> - version: v8.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/12141
<ide> description: new Buffer(size) will return zero-filled memory by default.
<ide> console.log(buf);
<ide> <!-- YAML
<ide> deprecated: v6.0.0
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/19524
<add> description: Calling this constructor emits a deprecation warning when
<add> run from code outside the `node_modules` directory.
<ide> - version: v7.2.1
<ide> pr-url: https://github.com/nodejs/node/pull/9529
<ide> description: Calling this constructor no longer emits a deprecation warning.
<ide><path>doc/api/deprecations.md
<ide> be used.
<ide> <a id="DEP0005"></a>
<ide> ### DEP0005: Buffer() constructor
<ide>
<del>Type: Documentation-only (supports [`--pending-deprecation`][])
<add>Type: Runtime (supports [`--pending-deprecation`][])
<ide>
<ide> The `Buffer()` function and `new Buffer()` constructor are deprecated due to
<ide> API usability issues that can potentially lead to accidental security issues.
<ide> is strongly recommended:
<ide> * [`Buffer.from(string[, encoding])`][from_string_encoding] - Create a `Buffer`
<ide> that copies `string`.
<ide>
<add>As of REPLACEME, a deprecation warning is printed at runtime when
<add>`--pending-deprecation` is used or when the calling code is
<add>outside `node_modules` in order to better target developers, rather than users.
<add>
<ide> <a id="DEP0006"></a>
<ide> ### DEP0006: child\_process options.customFds
<ide>
<ide><path>lib/buffer.js
<ide> try {
<ide> }
<ide> const {
<ide> customInspectSymbol,
<add> isInsideNodeModules,
<ide> normalizeEncoding,
<ide> kIsEncodingSymbol
<ide> } = require('internal/util');
<ide> function alignPool() {
<ide> }
<ide> }
<ide>
<del>var bufferWarn = true;
<add>let bufferWarningAlreadyEmitted = false;
<add>let nodeModulesCheckCounter = 0;
<ide> const bufferWarning = 'Buffer() is deprecated due to security and usability ' +
<ide> 'issues. Please use the Buffer.alloc(), ' +
<ide> 'Buffer.allocUnsafe(), or Buffer.from() methods instead.';
<ide>
<ide> function showFlaggedDeprecation() {
<del> if (bufferWarn) {
<del> // This is a *pending* deprecation warning. It is not emitted by
<del> // default unless the --pending-deprecation command-line flag is
<del> // used or the NODE_PENDING_DEPRECATION=1 env var is set.
<del> process.emitWarning(bufferWarning, 'DeprecationWarning', 'DEP0005');
<del> bufferWarn = false;
<add> if (bufferWarningAlreadyEmitted ||
<add> ++nodeModulesCheckCounter > 10000 ||
<add> (!pendingDeprecation &&
<add> isInsideNodeModules())) {
<add> // We don't emit a warning, because we either:
<add> // - Already did so, or
<add> // - Already checked too many times whether a call is coming
<add> // from node_modules and want to stop slowing down things, or
<add> // - We aren't running with `--pending-deprecation` enabled,
<add> // and the code is inside `node_modules`.
<add> return;
<ide> }
<del>}
<ide>
<del>const doFlaggedDeprecation =
<del> pendingDeprecation ?
<del> showFlaggedDeprecation :
<del> function() {};
<add> process.emitWarning(bufferWarning, 'DeprecationWarning', 'DEP0005');
<add> bufferWarningAlreadyEmitted = true;
<add>}
<ide>
<ide> /**
<ide> * The Buffer() constructor is deprecated in documentation and should not be
<ide> const doFlaggedDeprecation =
<ide> * Deprecation Code: DEP0005
<ide> */
<ide> function Buffer(arg, encodingOrOffset, length) {
<del> doFlaggedDeprecation();
<add> showFlaggedDeprecation();
<ide> // Common case.
<ide> if (typeof arg === 'number') {
<ide> if (typeof encodingOrOffset === 'string') {
<ide><path>lib/internal/util.js
<ide> function spliceOne(list, index) {
<ide> list.pop();
<ide> }
<ide>
<add>const kNodeModulesRE = /^(.*)[\\/]node_modules[\\/]/;
<add>
<add>let getStructuredStack;
<add>let mainPrefix;
<add>
<add>function isInsideNodeModules() {
<add> // Match the prefix of the main file, if it is inside a `node_modules` folder,
<add> // up to and including the innermost `/node_modules/` bit, so that
<add> // we can later ignore files which are at the same node_modules level.
<add> // For example, having the main script at `/c/node_modules/d/d.js`
<add> // would match all code coming from `/c/node_modules/`.
<add> if (mainPrefix === undefined) {
<add> const match = process.mainModule &&
<add> process.mainModule.filename &&
<add> process.mainModule.filename.match(kNodeModulesRE);
<add> mainPrefix = match ? match[0] : '';
<add> }
<add>
<add> if (getStructuredStack === undefined) {
<add> // Lazy-load to avoid a circular dependency.
<add> const { runInNewContext } = require('vm');
<add> // Use `runInNewContext()` to get something tamper-proof and
<add> // side-effect-free. Since this is currently only used for a deprecated API,
<add> // the perf implications should be okay.
<add> getStructuredStack = runInNewContext('(' + function() {
<add> Error.prepareStackTrace = function(err, trace) {
<add> err.stack = trace;
<add> };
<add> Error.stackTraceLimit = Infinity;
<add>
<add> return function structuredStack() {
<add> // eslint-disable-next-line no-restricted-syntax
<add> return new Error().stack;
<add> };
<add> } + ')()', {}, { filename: 'structured-stack' });
<add> }
<add>
<add> const stack = getStructuredStack();
<add>
<add> // Iterate over all stack frames and look for the first one not coming
<add> // from inside Node.js itself:
<add> for (const frame of stack) {
<add> const filename = frame.getFileName();
<add> // If a filename does not start with / or contain \,
<add> // it's likely from Node.js core.
<add> if (!/^\/|\\/.test(filename))
<add> continue;
<add> const match = filename.match(kNodeModulesRE);
<add> return !!match && match[0] !== mainPrefix;
<add> }
<add>
<add> return false; // This should be unreachable.
<add>}
<add>
<add>
<ide> module.exports = {
<ide> assertCrypto,
<ide> cachedResult,
<ide> module.exports = {
<ide> getSystemErrorName,
<ide> getIdentificationOf,
<ide> isError,
<add> isInsideNodeModules,
<ide> join,
<ide> normalizeEncoding,
<ide> objectToString,
<ide><path>test/parallel/test-buffer-constructor-node-modules-paths.js
<add>'use strict';
<add>
<add>const child_process = require('child_process');
<add>const assert = require('assert');
<add>const common = require('../common');
<add>
<add>if (process.env.NODE_PENDING_DEPRECATION)
<add> common.skip('test does not work when NODE_PENDING_DEPRECATION is set');
<add>
<add>function test(main, callSite, expected) {
<add> const { stderr } = child_process.spawnSync(process.execPath, ['-p', `
<add> process.mainModule = { filename: ${JSON.stringify(main)} };
<add>
<add> vm.runInNewContext('new Buffer(10)', { Buffer }, {
<add> filename: ${JSON.stringify(callSite)}
<add> });`], { encoding: 'utf8' });
<add> if (expected)
<add> assert(stderr.includes('[DEP0005] DeprecationWarning'), stderr);
<add> else
<add> assert.strictEqual(stderr.trim(), '');
<add>}
<add>
<add>test('/a/node_modules/b.js', '/a/node_modules/x.js', true);
<add>test('/a/node_modules/b.js', '/a/node_modules/foo/node_modules/x.js', false);
<add>test('/a/node_modules/foo/node_modules/b.js', '/a/node_modules/x.js', false);
<add>test('/node_modules/foo/b.js', '/node_modules/foo/node_modules/x.js', false);
<add>test('/a.js', '/b.js', true);
<add>test('/a.js', '/node_modules/b.js', false);
<add>test('c:\\a\\node_modules\\b.js', 'c:\\a\\node_modules\\x.js', true);
<add>test('c:\\a\\node_modules\\b.js',
<add> 'c:\\a\\node_modules\\foo\\node_modules\\x.js', false);
<add>test('c:\\node_modules\\foo\\b.js',
<add> 'c:\\node_modules\\foo\\node_modules\\x.js', false);
<add>test('c:\\a.js', 'c:\\b.js', true);
<add>test('c:\\a.js', 'c:\\node_modules\\b.js', false);
<ide><path>test/parallel/test-buffer-constructor-outside-node-modules.js
<add>// Flags: --no-warnings
<add>'use strict';
<add>
<add>const vm = require('vm');
<add>const assert = require('assert');
<add>const common = require('../common');
<add>
<add>if (new Error().stack.includes('node_modules'))
<add> common.skip('test does not work when inside `node_modules` directory');
<add>if (process.env.NODE_PENDING_DEPRECATION)
<add> common.skip('test does not work when NODE_PENDING_DEPRECATION is set');
<add>
<add>const bufferWarning = 'Buffer() is deprecated due to security and usability ' +
<add> 'issues. Please use the Buffer.alloc(), ' +
<add> 'Buffer.allocUnsafe(), or Buffer.from() methods instead.';
<add>
<add>process.addListener('warning', common.mustCall((warning) => {
<add> assert(warning.stack.includes('this_should_emit_a_warning'), warning.stack);
<add>}));
<add>
<add>vm.runInNewContext('new Buffer(10)', { Buffer }, {
<add> filename: '/a/node_modules/b'
<add>});
<add>
<add>common.expectWarning('DeprecationWarning', bufferWarning, 'DEP0005');
<add>
<add>vm.runInNewContext('new Buffer(10)', { Buffer }, {
<add> filename: '/this_should_emit_a_warning'
<add>}); | 6 |
Javascript | Javascript | pass texture in onupdate | bbf4c70823288f2253de1a66ac503eb2affac5c6 | <ide><path>src/renderers/WebGLRenderer.js
<ide> THREE.WebGLRenderer = function ( parameters ) {
<ide>
<ide> texture.needsUpdate = false;
<ide>
<del> if ( texture.onUpdate ) texture.onUpdate();
<add> if ( texture.onUpdate ) texture.onUpdate( texture );
<ide>
<ide> };
<ide>
<ide> THREE.WebGLRenderer = function ( parameters ) {
<ide>
<ide> texture.needsUpdate = false;
<ide>
<del> if ( texture.onUpdate ) texture.onUpdate();
<add> if ( texture.onUpdate ) texture.onUpdate( texture );
<ide>
<ide> } else {
<ide> | 1 |
Mixed | Python | add berttokenizer flag to skip basic tokenization | e14c6b52e37876ee642ffde49367c51b0d374f41 | <ide><path>README.md
<ide> where
<ide> Examples:
<ide> ```python
<ide> # BERT
<del>tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True)
<add>tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True, do_basic_tokenize=True)
<ide> model = BertForSequenceClassification.from_pretrained('bert-base-uncased')
<ide>
<ide> # OpenAI GPT
<ide> This model *outputs*:
<ide>
<ide> `BertTokenizer` perform end-to-end tokenization, i.e. basic tokenization followed by WordPiece tokenization.
<ide>
<del>This class has four arguments:
<add>This class has five arguments:
<ide>
<ide> - `vocab_file`: path to a vocabulary file.
<ide> - `do_lower_case`: convert text to lower-case while tokenizing. **Default = True**.
<ide> - `max_len`: max length to filter the input of the Transformer. Default to pre-trained value for the model if `None`. **Default = None**
<add>- `do_basic_tokenize`: Do basic tokenization before wordpice tokenization. Set to false if text is pre-tokenized. **Default = True**.
<ide> - `never_split`: a list of tokens that should not be splitted during tokenization. **Default = `["[UNK]", "[SEP]", "[PAD]", "[CLS]", "[MASK]"]`**
<ide>
<ide> and three methods:
<ide><path>pytorch_pretrained_bert/tokenization.py
<ide> def whitespace_tokenize(text):
<ide> class BertTokenizer(object):
<ide> """Runs end-to-end tokenization: punctuation splitting + wordpiece"""
<ide>
<del> def __init__(self, vocab_file, do_lower_case=True, max_len=None,
<add> def __init__(self, vocab_file, do_lower_case=True, max_len=None, do_basic_tokenize=True,
<ide> never_split=("[UNK]", "[SEP]", "[PAD]", "[CLS]", "[MASK]")):
<add> """Constructs a BertTokenizer.
<add>
<add> Args:
<add> do_lower_case: Whether to lower case the input.
<add> do_wordpiece_only: Whether to do basic tokenization before wordpiece.
<add> """
<ide> if not os.path.isfile(vocab_file):
<ide> raise ValueError(
<ide> "Can't find a vocabulary file at path '{}'. To load the vocabulary from a Google pretrained "
<ide> "model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`".format(vocab_file))
<ide> self.vocab = load_vocab(vocab_file)
<ide> self.ids_to_tokens = collections.OrderedDict(
<ide> [(ids, tok) for tok, ids in self.vocab.items()])
<del> self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case,
<del> never_split=never_split)
<add> self.do_basic_tokenize = do_basic_tokenize
<add> if do_basic_tokenize:
<add> self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case,
<add> never_split=never_split)
<ide> self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab)
<ide> self.max_len = max_len if max_len is not None else int(1e12)
<ide>
<ide> def tokenize(self, text):
<del> split_tokens = []
<del> for token in self.basic_tokenizer.tokenize(text):
<del> for sub_token in self.wordpiece_tokenizer.tokenize(token):
<del> split_tokens.append(sub_token)
<add> if self.do_basic_tokenize:
<add> split_tokens = []
<add> for token in self.basic_tokenizer.tokenize(text):
<add> for sub_token in self.wordpiece_tokenizer.tokenize(token):
<add> split_tokens.append(sub_token)
<add> else:
<add> split_tokens = self.wordpiece_tokenizer.tokenize(text)
<ide> return split_tokens
<ide>
<ide> def convert_tokens_to_ids(self, tokens): | 2 |
Go | Go | add some error checking in container monitor | 69c2250ec2fd23dc9d31372cb433b7c18a917d09 | <ide><path>container.go
<ide> func (container *Container) releaseNetwork() error {
<ide> func (container *Container) monitor() {
<ide> // Wait for the program to exit
<ide> Debugf("Waiting for process")
<del> container.cmd.Wait()
<add> if err := container.cmd.Wait(); err != nil {
<add> // Discard the error as any signals or non 0 returns will generate an error
<add> Debugf("%s: Process: %s", container.Id, err)
<add> }
<ide> Debugf("Process finished")
<ide>
<ide> exitCode := container.cmd.ProcessState.Sys().(syscall.WaitStatus).ExitStatus()
<ide> func (container *Container) monitor() {
<ide> if err := container.releaseNetwork(); err != nil {
<ide> log.Printf("%v: Failed to release network: %v", container.Id, err)
<ide> }
<del> container.stdout.Close()
<del> container.stderr.Close()
<add> if err := container.stdout.Close(); err != nil {
<add> Debugf("%s: Error close stdout: %s", container.Id, err)
<add> }
<add> if err := container.stderr.Close(); err != nil {
<add> Debugf("%s: Error close stderr: %s", container.Id, err)
<add> }
<ide> if err := container.Unmount(); err != nil {
<ide> log.Printf("%v: Failed to umount filesystem: %v", container.Id, err)
<ide> }
<ide> func (container *Container) monitor() {
<ide>
<ide> // Report status back
<ide> container.State.setStopped(exitCode)
<del> container.ToDisk()
<add> if err := container.ToDisk(); err != nil {
<add> log.Printf("%s: Failed to dump configuration to the disk: %s", container.Id, err)
<add> }
<ide> }
<ide>
<ide> func (container *Container) kill() error { | 1 |
PHP | PHP | move middleware to route | cf0875a655ad68bdf3204615264086ab462dd9c9 | <ide><path>routes/api.php
<ide>
<ide> Route::get('/user', function (Request $request) {
<ide> return $request->user();
<del>});
<add>})->middleware('auth:api'); | 1 |
Javascript | Javascript | remove unused variables | 6a7012aaca42fcca32550cd7c04817bda76f70b3 | <ide><path>make.js
<ide> try {
<ide> }
<ide>
<ide> var builder = require('./external/builder/builder.js');
<del>var path = require('path');
<ide> var fs = require('fs');
<ide>
<ide> var CONFIG_FILE = 'pdfjs.config';
<ide><path>src/core/chunked_stream.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> */
<del>/* globals NetworkManager */
<ide>
<ide> 'use strict';
<ide>
<ide><path>src/display/text_layer.js
<ide> var Util = sharedUtil.Util;
<ide> var createPromiseCapability = sharedUtil.createPromiseCapability;
<ide> var CustomStyle = displayDOMUtils.CustomStyle;
<ide> var getDefaultSetting = displayDOMUtils.getDefaultSetting;
<del>var PageViewport = sharedUtil.PageViewport;
<ide>
<ide> /**
<ide> * Text layer render parameters.
<ide><path>test/unit/api_spec.js
<ide> /* globals PDFJS, expect, it, describe, Promise, beforeAll,
<ide> InvalidPDFException, MissingPDFException, StreamType, FontType,
<ide> PDFDocumentProxy, PasswordException, PasswordResponses, afterAll,
<del> PDFPageProxy, createPromiseCapability, beforeEach, afterEach */
<add> PDFPageProxy, createPromiseCapability, afterEach */
<ide>
<ide> 'use strict';
<ide>
<ide><path>web/app.js
<ide> var PDFViewerApplication = {
<ide> pdfViewer.setDocument(pdfDocument);
<ide> var firstPagePromise = pdfViewer.firstPagePromise;
<ide> var pagesPromise = pdfViewer.pagesPromise;
<del> var onePageRendered = pdfViewer.onePageRendered;
<ide>
<ide> this.pageRotation = 0;
<ide>
<ide><path>web/pdf_find_controller.js
<ide> } else {
<ide> factory((root.pdfjsWebPDFFindController = {}), root.pdfjsWebUIUtils);
<ide> }
<del>}(this, function (exports, uiUtils, firefoxCom) {
<add>}(this, function (exports, uiUtils) {
<ide>
<ide> var scrollIntoView = uiUtils.scrollIntoView;
<ide>
<ide> var PDFFindController = (function PDFFindControllerClosure() {
<ide> * @param {number} index - match index.
<ide> * @param {Array} elements - text layer div elements array.
<ide> * @param {number} beginIdx - start index of the div array for the match.
<del> * @param {number} endIdx - end index of the div array for the match.
<ide> */
<ide> updateMatchPosition: function PDFFindController_updateMatchPosition(
<del> pageIndex, index, elements, beginIdx, endIdx) {
<add> pageIndex, index, elements, beginIdx) {
<ide> if (this.selected.matchIdx === index &&
<ide> this.selected.pageIdx === pageIndex) {
<ide> var spot = {
<ide><path>web/pdf_page_view.js
<ide> var PDFPageView = (function PDFPageViewClosure() {
<ide> var isScalingRestricted = false;
<ide> if (this.canvas && pdfjsLib.PDFJS.maxCanvasPixels > 0) {
<ide> var outputScale = this.outputScale;
<del> var pixelsInViewport = this.viewport.width * this.viewport.height;
<ide> if (((Math.floor(this.viewport.width) * outputScale.sx) | 0) *
<ide> ((Math.floor(this.viewport.height) * outputScale.sy) | 0) >
<ide> pdfjsLib.PDFJS.maxCanvasPixels) {
<ide><path>web/text_layer_builder.js
<ide> var TextLayerBuilder = (function TextLayerBuilderClosure() {
<ide>
<ide> if (this.findController) {
<ide> this.findController.updateMatchPosition(pageIdx, i, textDivs,
<del> begin.divIdx, end.divIdx);
<add> begin.divIdx);
<ide> }
<ide>
<ide> // Match inside new div. | 8 |
PHP | PHP | add some package helpers to service provider | 85ff8b3f8de7fd2795db44929217d08879ebd917 | <ide><path>src/Illuminate/Support/ServiceProvider.php
<ide> public function __construct($app)
<ide> */
<ide> abstract public function register();
<ide>
<add> /**
<add> * Register a view file namespace.
<add> *
<add> * @param string $namespace
<add> * @param string $path
<add> * @return void
<add> */
<add> protected function loadViewsFrom($namespace, $path)
<add> {
<add> if (is_dir($appPath = $this->app->basePath().'/resources/views/packages/'.$namespace))
<add> {
<add> $this->app['view']->addNamespace($namespace, $appPath);
<add> }
<add>
<add> $this->app['view']->addNamespace($namespace, $path);
<add> }
<add>
<add> /**
<add> * Register a translation file namespace.
<add> *
<add> * @param string $namespace
<add> * @param string $path
<add> * @return void
<add> */
<add> protected function loadTranslationsFrom($namespace, $path)
<add> {
<add> $this->app['translator']->addNamespace($namespace, $path);
<add> }
<add>
<ide> /**
<ide> * Register the package's custom Artisan commands.
<ide> * | 1 |
Javascript | Javascript | fix typo in common/wpt.js | 127da0f36bfbdb8adcc53da6b22b4c9eeed2f518 | <ide><path>test/common/wpt.js
<ide> class ResourceLoader {
<ide> /**
<ide> * Load a resource in test/fixtures/wpt specified with a URL
<ide> * @param {string} from the path of the file loading this resource,
<del> * relative to thw WPT folder.
<add> * relative to the WPT folder.
<ide> * @param {string} url the url of the resource being loaded.
<ide> * @param {boolean} asFetch if true, return the resource in a
<ide> * pseudo-Response object. | 1 |
Text | Text | add guide for backporting prs | ece9ab55067c7d6ca20b8295eb0c1f2451e8729c | <ide><path>COLLABORATOR_GUIDE.md
<ide> LTS release.
<ide>
<ide> When you send your pull request, consider including information about
<ide> whether your change is breaking. If you think your patch can be backported,
<del>please feel free to include that information in the PR thread.
<add>please feel free to include that information in the PR thread. For more
<add>information on backporting, please see the [backporting guide][].
<ide>
<ide> Several LTS related issue and PR labels have been provided:
<ide>
<ide> When the LTS working group determines that a new LTS release is required,
<ide> selected commits will be picked from the staging branch to be included in the
<ide> release. This process of making a release will be a collaboration between the
<ide> LTS working group and the Release team.
<add>
<add>[backporting guide]: doc/guides/backporting-to-release-lines.md
<ide><path>doc/guides/backporting-to-release-lines.md
<add># How to Backport a Pull Request to a Release Line
<add>
<add>## Staging branches
<add>
<add>Each release line has a staging branch that the releaser will use as a scratch
<add>pad while preparing a release. The branch name is formatted as follows:
<add>`vN.x-staging` where `N` is the major release number.
<add>
<add>### Active staging branches
<add>
<add>| Release Line | Staging Branch |
<add>| ------------ | -------------- |
<add>| `v7.x` | `v7.x-staging` |
<add>| `v6.x` | `v6.x-staging` |
<add>| `v4.x` | `v4.x-staging` |
<add>
<add>## What needs to be backported?
<add>
<add>If a cherry-pick from master does not land cleanly on a staging branch, the
<add>releaser will mark the pull request with a particular label for that release
<add>line, specifying to our tooling that this pull request should not be included.
<add>The releaser will then add a comment that a backport is needed.
<add>
<add>## What can be backported?
<add>
<add>The "Current" release line is much more lenient than the LTS release lines in
<add>what can be landed. Our LTS release lines (v4.x and v6.x as of March 2017)
<add>require that commits mature in a Current release for at least 2 weeks before
<add>they can be landed on staging. If the commit can not be cherry-picked from
<add>master a manual backport will need to be submitted. Please see the [LTS Plan][]
<add>for more information. After that time, if the commit can be cherry-picked
<add>cleanly from master, then nothing needs to be done. If not, a backport pull
<add>request will need to be submitted.
<add>
<add>## How to submit a backport pull request
<add>
<add>For these steps, let's assume that a backport is needed for the v7.x release
<add>line. All commands will use the v7.x-staging branch as the target branch.
<add>In order to submit a backport pull request to another branch, simply replace
<add>that with the staging branch for the targeted release line.
<add>
<add>* Checkout the staging branch for the targeted release line
<add>* Make sure that the local staging branch is up to date with the remote
<add>* Create a new branch off of the staging branch
<add>
<add>```shell
<add># Assuming your fork of Node.js is checked out in $NODE_DIR,
<add># the origin remote points to your fork, and the upstream remote points
<add># to git://github.com/nodejs/node
<add>cd $NODE_DIR
<add># Fails if you already have a v7.x-staging
<add>git branch v7.x-staging upstream/v7.x-staging
<add>git checkout v7.x-staging
<add>git reset --hard upstream/v7.x-staging
<add># We want to backport pr #10157
<add>git checkout -b backport-10157-to-v7.x
<add>```
<add>
<add>* After creating the branch, apply the changes to the branch. The cherry-pick
<add> will likely fail due to conflicts. In that case, you will see something this:
<add>
<add>```shell
<add># Say the $SHA is 773cdc31ef
<add>$ git cherry-pick $SHA # Use your commit hash
<add>error: could not apply 773cdc3... <commit title>
<add>hint: after resolving the conflicts, mark the corrected paths
<add>hint: with 'git add <paths>' or 'git rm <paths>'
<add>hint: and commit the result with 'git commit'
<add>```
<add>
<add>* Make the required changes to remove the conflicts, add the files to the index
<add> using `git add`, and then commit the changes. That can be done with
<add> `git cherry-pick --continue`.
<add>* Leave the commit message as is. If you think it should be modified, comment
<add> in the Pull Request.
<add>* Make sure `make -j4 test` passes
<add>* Push the changes to your fork and open a pull request.
<add>* Be sure to target the `v7.x-staging` branch in the pull request.
<add>
<add>### Helpful Hints
<add>
<add>* Please include the backport target in the pull request title in the following
<add> format: `(v7.x backport) <commit title>`
<add> * Ex. `(v4.x backport) process: improve performance of nextTick`
<add>* Please check the checkbox labelled "Allow edits from maintainers".
<add> This is the easiest way to to avoid constant rebases.
<add>
<add>In the event the backport pull request is different than the original,
<add>the backport pull request should be reviewed the same way a new pull request
<add>is reviewed.
<add>
<add>[LTS Plan]: https://github.com/nodejs/LTS#lts-plan | 2 |
Go | Go | add integration test for fqdn hostname | 950792dc6d26b6ec6d62579ada57570acedcd0ee | <ide><path>integration-cli/docker_cli_run_test.go
<ide> func (s *DockerSuite) TestRunMountReadOnlyDevShm(c *check.C) {
<ide> c.Assert(out, checker.Contains, "Read-only file system")
<ide> }
<ide>
<add>// Test that passing a FQDN as hostname properly sets hostname, and
<add>// /etc/hostname. Test case for 29100
<add>func (s *DockerSuite) TestRunHostnameFQDN(c *check.C) {
<add> testRequires(c, DaemonIsLinux)
<add>
<add> expectedOutput := "foobar.example.com\nfoobar.example.com\nfoobar\nexample.com\nfoobar.example.com"
<add> out, _ := dockerCmd(c, "run", "--hostname=foobar.example.com", "busybox", "sh", "-c", `cat /etc/hostname && hostname && hostname -s && hostname -d && hostname -f`)
<add> c.Assert(strings.TrimSpace(out), checker.Equals, expectedOutput)
<add>
<add> out, _ = dockerCmd(c, "run", "--hostname=foobar.example.com", "busybox", "sh", "-c", `cat /etc/hosts`)
<add> expectedOutput = "foobar.example.com foobar"
<add> c.Assert(strings.TrimSpace(out), checker.Contains, expectedOutput)
<add>}
<add>
<ide> // Test case for 29129
<ide> func (s *DockerSuite) TestRunHostnameInHostMode(c *check.C) {
<ide> testRequires(c, DaemonIsLinux, NotUserNamespace) | 1 |
PHP | PHP | simplify loops by indexing data in separate loops | 04ed50026b35bbb9e5c12bf53e67e62abf77a168 | <ide><path>src/ORM/Marshaller.php
<ide> protected function _belongsToMany(Association $assoc, array $data, $options = []
<ide> }
<ide>
<ide> if (isset($query)) {
<del> $queryData = $query->toArray();
<del> foreach ($queryData as $queryItem) {
<del> foreach ($data as $i => $row) {
<del> $matchCount = 0;
<del> foreach ($primaryKey as $key => $value) {
<del> if (isset($row[$key]) && $row[$key] == $queryItem->$key) {
<del> $matchCount++;
<del> }
<del> if ($matchCount === count($primaryKey)) {
<del> $records[$i] = $queryItem;
<del> break 2;
<del> }
<add> $keyFields = array_keys($primaryKey);
<add>
<add> $existing = [];
<add> foreach ($query as $row) {
<add> $k = implode(';', $row->extract($keyFields));
<add> $existing[$k] = $row;
<add> }
<add>
<add> foreach ($data as $i => $row) {
<add> $key = [];
<add> foreach ($keyFields as $k) {
<add> if (isset($row[$k])) {
<add> $key[] = $row[$k];
<ide> }
<ide> }
<add> $key = implode(';', $key);
<add> if (isset($existing[$key])) {
<add> $records[$i] = $existing[$key];
<add> }
<ide> }
<ide> }
<ide>
<del> $joint = $assoc->junction();
<del> $jointMarshaller = $joint->marshaller();
<add> $jointMarshaller = $assoc->junction()->marshaller();
<ide>
<ide> $nested = [];
<ide> if (isset($associated['_joinData'])) {
<ide><path>tests/TestCase/ORM/MarshallerTest.php
<ide> public function testBelongsToManyWithMixedJoinData()
<ide> ]
<ide> ]
<ide> ];
<del>
<del> $articlesTags = TableRegistry::get('ArticlesTags');
<del> $articlesTags->belongsTo('Users');
<del>
<ide> $marshall = new Marshaller($this->articles);
<ide>
<del> $result = $marshall->one($data, ['associated' => ['Tags._joinData.Users']]);
<add> $result = $marshall->one($data, ['associated' => ['Tags._joinData']]);
<ide>
<ide> $this->assertEquals($data['tags'][0]['id'], $result->tags[0]->id);
<ide> $this->assertEquals($data['tags'][1]['name'], $result->tags[1]->name);
<ide> $this->assertEquals(0, $result->tags[0]->_joinData->active);
<ide> $this->assertEquals(1, $result->tags[1]->_joinData->active);
<ide> }
<ide>
<add> /**
<add> * Test belongsToMany association with mixed data and _joinData
<add> *
<add> * @return void
<add> */
<add> public function testBelongsToManyWithMixedJoinDataOutOfOrder()
<add> {
<add> $data = [
<add> 'title' => 'My title',
<add> 'body' => 'My content',
<add> 'author_id' => 1,
<add> 'tags' => [
<add> [
<add> 'name' => 'tag5',
<add> '_joinData' => [
<add> 'active' => 1,
<add> ]
<add> ],
<add> [
<add> 'id' => 1,
<add> '_joinData' => [
<add> 'active' => 0,
<add> ]
<add> ],
<add> [
<add> 'name' => 'tag3',
<add> '_joinData' => [
<add> 'active' => 1,
<add> ]
<add> ],
<add> ]
<add> ];
<add> $marshall = new Marshaller($this->articles);
<add> $result = $marshall->one($data, ['associated' => ['Tags._joinData']]);
<add>
<add> $this->assertEquals($data['tags'][0]['name'], $result->tags[0]->name);
<add> $this->assertEquals($data['tags'][1]['id'], $result->tags[1]->id);
<add> $this->assertEquals($data['tags'][2]['name'], $result->tags[2]->name);
<add>
<add> $this->assertEquals(1, $result->tags[0]->_joinData->active);
<add> $this->assertEquals(0, $result->tags[1]->_joinData->active);
<add> $this->assertEquals(1, $result->tags[2]->_joinData->active);
<add> }
<add>
<ide> /**
<ide> * Test belongsToMany association with mixed data array
<ide> * | 2 |
Javascript | Javascript | fix lint errors | 17fafd34321ea60025ab06cf647d4f5fb6842e15 | <ide><path>test/configCases/source-map/default-filename-extensions-css/webpack.config.js
<ide> module.exports = {
<ide> },
<ide> devtool: "source-map"
<ide> };
<del>
<ide><path>test/configCases/source-map/default-filename-extensions-js/webpack.config.js
<ide> module.exports = {
<ide> },
<ide> devtool: "source-map"
<ide> };
<del>
<ide><path>test/configCases/source-map/default-filename-extensions-mjs/webpack.config.js
<ide> module.exports = {
<ide> },
<ide> devtool: "source-map"
<ide> };
<del> | 3 |
Ruby | Ruby | fix regression when formula.tap is nil | 8fb6218d052cd7e33435ba88f3ecc38c62278e4c | <ide><path>Library/Homebrew/dev-cmd/bump-formula-pr.rb
<ide> def use_correct_linux_tap(formula, args:)
<ide> end
<ide> end
<ide> end
<del> origin_branch = Utils.popen_read("git", "-C", formula.tap.path.to_s, "symbolic-ref", "-q", "--short",
<del> "refs/remotes/origin/HEAD").chomp.presence
<add> if formula.tap
<add> origin_branch = Utils.popen_read("git", "-C", formula.tap.path.to_s, "symbolic-ref", "-q", "--short",
<add> "refs/remotes/origin/HEAD").chomp.presence
<add> end
<ide> origin_branch ||= "origin/master"
<ide> [formula.tap&.full_name, origin_branch, "-"]
<ide> end | 1 |
Ruby | Ruby | use a set and reject to avoid array allocations | c8b566d54da278a8e675115bcf2e9590f75f5eb5 | <ide><path>actionpack/lib/abstract_controller/rendering.rb
<ide> def rendered_format
<ide> Mime::TEXT
<ide> end
<ide>
<del> DEFAULT_PROTECTED_INSTANCE_VARIABLES = %w(
<add> require 'set'
<add>
<add> DEFAULT_PROTECTED_INSTANCE_VARIABLES = Set.new %w(
<ide> @_action_name @_response_body @_formats @_prefixes @_config
<ide> @_view_context_class @_view_renderer @_lookup_context
<ide> @_routes @_db_runtime
<ide> def rendered_format
<ide> # You can overwrite this configuration per controller.
<ide> # :api: public
<ide> def view_assigns
<del> variables = instance_variables
<del> variables -= protected_instance_variables
<del> variables -= DEFAULT_PROTECTED_INSTANCE_VARIABLES
<add> protected_vars = _protected_ivars
<add> variables = instance_variables
<add>
<add> variables.reject! { |s| protected_vars.include? s }
<ide> variables.each_with_object({}) { |name, hash|
<ide> hash[name.slice(1, name.length)] = instance_variable_get(name)
<ide> }
<ide> def _normalize_render(*args, &block)
<ide> _normalize_options(options)
<ide> options
<ide> end
<add>
<add> def _protected_ivars # :nodoc:
<add> DEFAULT_PROTECTED_INSTANCE_VARIABLES + protected_instance_variables
<add> end
<ide> end
<ide> end | 1 |
Javascript | Javascript | use correct size in test-stream-buffer-list | 2313424abc6f88b72630f79a483721dd0cd10c27 | <ide><path>test/parallel/test-stream-buffer-list.js
<ide> assert.strictEqual(emptyList.join(','), '');
<ide>
<ide> assert.deepStrictEqual(emptyList.concat(0), Buffer.alloc(0));
<ide>
<add>const buf = Buffer.from('foo');
<add>
<ide> // Test buffer list with one element.
<ide> const list = new BufferList();
<del>list.push('foo');
<add>list.push(buf);
<add>
<add>const copy = list.concat(3);
<ide>
<del>assert.strictEqual(list.concat(1), 'foo');
<add>assert.notStrictEqual(copy, buf);
<add>assert.deepStrictEqual(copy, buf);
<ide>
<ide> assert.strictEqual(list.join(','), 'foo');
<ide>
<ide> const shifted = list.shift();
<del>assert.strictEqual(shifted, 'foo');
<add>assert.strictEqual(shifted, buf);
<ide> assert.deepStrictEqual(list, new BufferList());
<ide>
<ide> const tmp = util.inspect.defaultOptions.colors; | 1 |
Javascript | Javascript | remove noassert argument | 81aaab75ca2ae04c4d0e07efd12e3a74aa306850 | <ide><path>benchmark/buffers/buffer-read-float.js
<ide> const common = require('../common.js');
<ide>
<ide> const bench = common.createBenchmark(main, {
<del> noAssert: ['false', 'true'],
<ide> type: ['Double', 'Float'],
<ide> endian: ['BE', 'LE'],
<ide> value: ['zero', 'big', 'small', 'inf', 'nan'],
<ide> millions: [1]
<ide> });
<ide>
<del>function main({ noAssert, millions, type, endian, value }) {
<del> noAssert = noAssert === 'true';
<add>function main({ millions, type, endian, value }) {
<ide> type = type || 'Double';
<ide> const buff = Buffer.alloc(8);
<ide> const fn = `read${type}${endian}`;
<ide> function main({ noAssert, millions, type, endian, value }) {
<ide> },
<ide> };
<ide>
<del> buff[`write${type}${endian}`](values[type][value], 0, noAssert);
<add> buff[`write${type}${endian}`](values[type][value], 0);
<ide>
<ide> bench.start();
<ide> for (var i = 0; i !== millions * 1e6; i++) {
<del> buff[fn](0, noAssert);
<add> buff[fn](0);
<ide> }
<ide> bench.end(millions);
<ide> }
<ide><path>benchmark/buffers/buffer-read-with-byteLength.js
<ide> const types = [
<ide> ];
<ide>
<ide> const bench = common.createBenchmark(main, {
<del> noAssert: ['false', 'true'],
<ide> buffer: ['fast', 'slow'],
<ide> type: types,
<ide> millions: [1],
<del> byteLength: [1, 2, 4, 6]
<add> byteLength: [1, 2, 3, 4, 5, 6]
<ide> });
<ide>
<del>function main({ millions, noAssert, buf, type, byteLength }) {
<del> noAssert = noAssert === 'true';
<del> type = type || 'UInt8';
<add>function main({ millions, buf, type, byteLength }) {
<ide> const clazz = buf === 'fast' ? Buffer : require('buffer').SlowBuffer;
<ide> const buff = new clazz(8);
<del> const fn = `read${type}`;
<add> const fn = `read${type || 'IntBE'}`;
<ide>
<del> buff.writeDoubleLE(0, 0, noAssert);
<add> buff.writeDoubleLE(0, 0);
<ide> bench.start();
<ide> for (var i = 0; i !== millions * 1e6; i++) {
<del> buff[fn](0, byteLength, noAssert);
<add> buff[fn](0, byteLength);
<ide> }
<ide> bench.end(millions);
<ide> }
<ide><path>benchmark/buffers/buffer-read.js
<ide> const types = [
<ide> ];
<ide>
<ide> const bench = common.createBenchmark(main, {
<del> noAssert: ['false', 'true'],
<ide> buffer: ['fast', 'slow'],
<ide> type: types,
<ide> millions: [1]
<ide> });
<ide>
<del>function main({ noAssert, millions, buf, type }) {
<del> noAssert = noAssert === 'true';
<add>function main({ millions, buf, type }) {
<ide> const clazz = buf === 'fast' ? Buffer : require('buffer').SlowBuffer;
<ide> const buff = new clazz(8);
<ide> const fn = `read${type || 'UInt8'}`;
<ide>
<del> buff.writeDoubleLE(0, 0, noAssert);
<add> buff.writeDoubleLE(0, 0);
<ide> bench.start();
<ide> for (var i = 0; i !== millions * 1e6; i++) {
<del> buff[fn](0, noAssert);
<add> buff[fn](0);
<ide> }
<ide> bench.end(millions);
<ide> }
<ide><path>benchmark/buffers/buffer-write.js
<ide> const types = [
<ide> 'UInt16BE',
<ide> 'UInt32LE',
<ide> 'UInt32BE',
<add> 'UIntLE',
<add> 'UIntBE',
<ide> 'Int8',
<ide> 'Int16LE',
<ide> 'Int16BE',
<ide> 'Int32LE',
<ide> 'Int32BE',
<add> 'IntLE',
<add> 'IntBE',
<ide> 'FloatLE',
<ide> 'FloatBE',
<ide> 'DoubleLE',
<ide> 'DoubleBE'
<ide> ];
<ide>
<ide> const bench = common.createBenchmark(main, {
<del> noAssert: ['false', 'true'],
<ide> buffer: ['fast', 'slow'],
<ide> type: types,
<ide> millions: [1]
<ide> const bench = common.createBenchmark(main, {
<ide> const INT8 = 0x7f;
<ide> const INT16 = 0x7fff;
<ide> const INT32 = 0x7fffffff;
<del>const UINT8 = (INT8 * 2) + 1;
<del>const UINT16 = (INT16 * 2) + 1;
<del>const UINT32 = INT32;
<add>const INT48 = 0x7fffffffffff;
<add>const UINT8 = 0xff;
<add>const UINT16 = 0xffff;
<ide>
<ide> const mod = {
<ide> writeInt8: INT8,
<ide> const mod = {
<ide> writeUInt8: UINT8,
<ide> writeUInt16BE: UINT16,
<ide> writeUInt16LE: UINT16,
<del> writeUInt32BE: UINT32,
<del> writeUInt32LE: UINT32
<add> writeUInt32BE: INT32,
<add> writeUInt32LE: INT32,
<add> writeUIntLE: INT8,
<add> writeUIntBE: INT16,
<add> writeIntLE: INT32,
<add> writeIntBE: INT48
<ide> };
<ide>
<del>function main({ noAssert, millions, buf, type }) {
<add>const byteLength = {
<add> writeUIntLE: 1,
<add> writeUIntBE: 2,
<add> writeIntLE: 4,
<add> writeIntBE: 6
<add>};
<add>
<add>function main({ millions, buf, type }) {
<ide> const clazz = buf === 'fast' ? Buffer : require('buffer').SlowBuffer;
<ide> const buff = new clazz(8);
<ide> const fn = `write${type || 'UInt8'}`;
<ide>
<del> if (/Int/.test(fn))
<del> benchInt(buff, fn, millions, noAssert);
<add> if (!/\d/.test(fn))
<add> benchSpecialInt(buff, fn, millions);
<add> else if (/Int/.test(fn))
<add> benchInt(buff, fn, millions);
<ide> else
<del> benchFloat(buff, fn, millions, noAssert);
<add> benchFloat(buff, fn, millions);
<add>}
<add>
<add>function benchInt(buff, fn, millions) {
<add> const m = mod[fn];
<add> bench.start();
<add> for (var i = 0; i !== millions * 1e6; i++) {
<add> buff[fn](i & m, 0);
<add> }
<add> bench.end(millions);
<ide> }
<ide>
<del>function benchInt(buff, fn, millions, noAssert) {
<add>function benchSpecialInt(buff, fn, millions) {
<ide> const m = mod[fn];
<add> const byte = byteLength[fn];
<ide> bench.start();
<ide> for (var i = 0; i !== millions * 1e6; i++) {
<del> buff[fn](i & m, 0, noAssert);
<add> buff[fn](i & m, 0, byte);
<ide> }
<ide> bench.end(millions);
<ide> }
<ide>
<del>function benchFloat(buff, fn, millions, noAssert) {
<add>function benchFloat(buff, fn, millions) {
<ide> bench.start();
<ide> for (var i = 0; i !== millions * 1e6; i++) {
<del> buff[fn](i, 0, noAssert);
<add> buff[fn](i, 0);
<ide> }
<ide> bench.end(millions);
<ide> }
<ide><path>test/sequential/test-benchmark-buffer.js
<ide> runBenchmark('buffers',
<ide> 'millions=0.000001',
<ide> 'method=',
<ide> 'n=1',
<del> 'noAssert=true',
<ide> 'pieces=1',
<ide> 'pieceSize=1',
<ide> 'search=@', | 5 |
Javascript | Javascript | reduce scope of variable in common module | 03b8ac14e7cb535fc7a82188c666b5a2a38d00bc | <ide><path>test/common/index.js
<ide> exports.skipIf32Bits = function skipIf32Bits() {
<ide> }
<ide> };
<ide>
<del>const arrayBufferViews = [
<del> Int8Array,
<del> Uint8Array,
<del> Uint8ClampedArray,
<del> Int16Array,
<del> Uint16Array,
<del> Int32Array,
<del> Uint32Array,
<del> Float32Array,
<del> Float64Array,
<del> DataView
<del>];
<del>
<ide> exports.getArrayBufferViews = function getArrayBufferViews(buf) {
<ide> const { buffer, byteOffset, byteLength } = buf;
<ide>
<ide> const out = [];
<add>
<add> const arrayBufferViews = [
<add> Int8Array,
<add> Uint8Array,
<add> Uint8ClampedArray,
<add> Int16Array,
<add> Uint16Array,
<add> Int32Array,
<add> Uint32Array,
<add> Float32Array,
<add> Float64Array,
<add> DataView
<add> ];
<add>
<ide> for (const type of arrayBufferViews) {
<ide> const { BYTES_PER_ELEMENT = 1 } = type;
<ide> if (byteLength % BYTES_PER_ELEMENT === 0) { | 1 |
Text | Text | add v3.16.0-beta.1 to changelog | 1df3e992ed01bd9f97f302927bd596fdb82ee8a4 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.16.0-beta.1 (December 9, 2019)
<add>
<add>- [#18436](https://github.com/emberjs/ember.js/pull/18436) [DEPRECATION] Deprecate globals resolver per [RFC #331](https://github.com/emberjs/rfcs/blob/master/text/0331-deprecate-globals-resolver.md).
<add>
<ide> ### v3.15.0 (December 9, 2019)
<ide>
<ide> - [#17948](https://github.com/emberjs/ember.js/pull/17948) [DEPRECATION] Deprecate `Component#isVisible` per [RFC #324](https://github.com/emberjs/rfcs/blob/master/text/0324-deprecate-component-isvisible.md). | 1 |
Java | Java | fix default accessibility delegate | d3f2f96f9373ea84975ff44b5c447ad3bcaf6edd | <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/AccessibilityDelegateUtil.java
<ide> private AccessibilityDelegateUtil() {
<ide> }
<ide>
<ide> public static void setDelegate(final View view) {
<add> final String accessibilityHint = (String) view.getTag(R.id.accessibility_hint);
<add> final AccessibilityRole accessibilityRole = (AccessibilityRole) view.getTag(R.id.accessibility_role);
<ide> // if a view already has an accessibility delegate, replacing it could cause problems,
<ide> // so leave it alone.
<del> if (!ViewCompat.hasAccessibilityDelegate(view)) {
<add> if (!ViewCompat.hasAccessibilityDelegate(view) &&
<add> accessibilityHint != null &&
<add> accessibilityRole != null) {
<ide> ViewCompat.setAccessibilityDelegate(
<ide> view,
<ide> new AccessibilityDelegateCompat() {
<ide> @Override
<ide> public void onInitializeAccessibilityNodeInfo(
<ide> View host, AccessibilityNodeInfoCompat info) {
<ide> super.onInitializeAccessibilityNodeInfo(host, info);
<del> String accessibilityHint = (String) view.getTag(R.id.accessibility_hint);
<del> AccessibilityRole accessibilityRole = (AccessibilityRole) view.getTag(R.id.accessibility_role);
<del> if (accessibilityRole == null) {
<del> accessibilityRole = AccessibilityRole.NONE;
<del> }
<ide> setRole(info, accessibilityRole, view.getContext());
<ide> if (!(accessibilityHint == null)) {
<ide> String contentDescription=(String)info.getContentDescription();
<ide> public void onInitializeAccessibilityNodeInfo(
<ide>
<ide> //TODO: Eventually support for other languages on talkback
<ide>
<del> public static void setRole(AccessibilityNodeInfoCompat nodeInfo, final AccessibilityRole role, final Context context) {
<add> public static void setRole(AccessibilityNodeInfoCompat nodeInfo, AccessibilityRole role, final Context context) {
<add> if (role == null) {
<add> role = AccessibilityRole.NONE;
<add> }
<ide> nodeInfo.setClassName(role.getValue());
<ide> if (Locale.getDefault().getLanguage().equals(new Locale("en").getLanguage())) {
<ide> if (role.equals(AccessibilityRole.LINK)) { | 1 |
Javascript | Javascript | simplify html wrappers | 0ea342a6a6dce793c1b0f14f051c2573f40f4e44 | <ide><path>src/manipulation.js
<ide> var
<ide> option: [ 1, "<select multiple='multiple'>", "</select>" ],
<ide>
<ide> thead: [ 1, "<table>", "</table>" ],
<add>
<add> // Some of the following wrappers are not fully defined, because
<add> // their parent elements (except for "table" element) could be omitted
<add> // since browser parsers are smart enough to auto-insert them
<add>
<add> // Support: Android 2.3
<add> // Android browser doesn't auto-insert colgroup
<ide> col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
<del> tr: [ 2, "<table><tbody>", "</tbody></table>" ],
<del> td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
<add>
<add> // Auto-insert "tbody" element
<add> tr: [ 2, "<table>", "</table>" ],
<add>
<add> // Auto-insert "tbody" and "tr" elements
<add> td: [ 3, "<table>", "</table>" ],
<ide>
<ide> _default: [ 0, "", "" ]
<ide> };
<ide><path>test/unit/manipulation.js
<ide> test( "Validate creation of multiple quantities of certain elements (#13818)", 4
<ide> });
<ide> });
<ide>
<add>test( "Make sure col element is appended correctly", function() {
<add> expect( 1 );
<add>
<add> var table = jQuery( "<table cellpadding='0'><tr><td>test</td></tr></table>" );
<add>
<add> jQuery( table ).appendTo( "#qunit-fixture" );
<add>
<add> jQuery( "<col width='150'/>" ).prependTo( table );
<add>
<add> strictEqual( table.find( "td" ).width(), 150 );
<add>});
<add>
<ide> asyncTest( "Insert script with data-URI (gh-1887)", 1, function() {
<ide> Globals.register( "testFoo" );
<ide> Globals.register( "testSrcFoo" ); | 2 |
Java | Java | remove unnecessary loop in serializabletypewrapper | a43ba052e94eb3b07ec9e407500e713d24e02b16 | <ide><path>spring-core/src/main/java/org/springframework/core/SerializableTypeWrapper.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 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> *
<ide> * @author Phillip Webb
<ide> * @author Juergen Hoeller
<add> * @author Sam Brannen
<ide> * @since 4.0
<ide> */
<ide> final class SerializableTypeWrapper {
<ide> public static Type forMethodParameter(MethodParameter methodParameter) {
<ide> */
<ide> @SuppressWarnings("unchecked")
<ide> public static <T extends Type> T unwrap(T type) {
<del> Type unwrapped = type;
<del> while (unwrapped instanceof SerializableTypeProxy) {
<add> Type unwrapped = null;
<add> if (type instanceof SerializableTypeProxy) {
<ide> unwrapped = ((SerializableTypeProxy) type).getTypeProvider().getType();
<ide> }
<ide> return (unwrapped != null ? (T) unwrapped : type);
<ide><path>spring-core/src/test/java/org/springframework/core/SerializableTypeWrapperTests.java
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide>
<del>
<del>
<ide> /**
<ide> * Tests for {@link SerializableTypeWrapper}.
<ide> * | 2 |
Java | Java | add guards around log statements | 50d38b72bdb091aba97e030f6143ee56e49c9708 | <ide><path>rxjava-contrib/rxjava-android/src/main/java/rx/operators/OperationObserveFromAndroidComponent.java
<ide> private OnSubscribeBase(Observable<T> source, AndroidComponent component) {
<ide> }
<ide>
<ide> private void log(String message) {
<del> Log.d(LOG_TAG, "componentRef = " + componentRef);
<del> Log.d(LOG_TAG, "observerRef = " + observerRef);
<del> Log.d(LOG_TAG, message);
<add> if (Log.isLoggable(LOG_TAG, Log.DEBUG)) {
<add> Log.d(LOG_TAG, "componentRef = " + componentRef);
<add> Log.d(LOG_TAG, "observerRef = " + observerRef);
<add> Log.d(LOG_TAG, message);
<add> }
<ide> }
<ide>
<ide> protected abstract boolean isComponentValid(AndroidComponent component); | 1 |
Ruby | Ruby | fix wrong number of arguments | 265ab264fde4d07f391d7332514502870d2888b4 | <ide><path>Library/Homebrew/exceptions.rb
<ide> def initialize(cmd, status:, output: nil)
<ide> s = "Failure while executing; `#{cmd.shelljoin.gsub(/\\=/, "=")}` exited with #{exitstatus}."
<ide>
<ide> unless [*output].empty?
<del> format_output_line = lambda do |type, line|
<add> format_output_line = lambda do |type_line|
<add> type, line = *type_line
<ide> if type == :stderr
<ide> Formatter.error(line)
<ide> else | 1 |
Python | Python | fix nan functions to allow sub-class | 56aa233a535263f309be2086f451a648d462d518 | <ide><path>numpy/lib/function_base.py
<ide> def place(arr, mask, vals):
<ide> def nansum(a, axis=None):
<ide> """Sum the array over the given axis, treating NaNs as 0.
<ide> """
<del> y = array(a)
<add> y = array(a,subok=True)
<ide> if not issubclass(y.dtype.type, _nx.integer):
<ide> y[isnan(a)] = 0
<ide> return y.sum(axis)
<ide>
<ide> def nanmin(a, axis=None):
<ide> """Find the minimium over the given axis, ignoring NaNs.
<ide> """
<del> y = array(a)
<add> y = array(a,subok=True)
<ide> if not issubclass(y.dtype.type, _nx.integer):
<ide> y[isnan(a)] = _nx.inf
<ide> return y.min(axis)
<ide>
<ide> def nanargmin(a, axis=None):
<ide> """Find the indices of the minimium over the given axis ignoring NaNs.
<ide> """
<del> y = array(a)
<add> y = array(a, subok=True)
<ide> if not issubclass(y.dtype.type, _nx.integer):
<ide> y[isnan(a)] = _nx.inf
<ide> return y.argmin(axis)
<ide>
<ide> def nanmax(a, axis=None):
<ide> """Find the maximum over the given axis ignoring NaNs.
<ide> """
<del> y = array(a)
<add> y = array(a, subok=True)
<ide> if not issubclass(y.dtype.type, _nx.integer):
<ide> y[isnan(a)] = -_nx.inf
<ide> return y.max(axis)
<ide>
<ide> def nanargmax(a, axis=None):
<ide> """Find the maximum over the given axis ignoring NaNs.
<ide> """
<del> y = array(a)
<add> y = array(a,subok=True)
<ide> if not issubclass(y.dtype.type, _nx.integer):
<ide> y[isnan(a)] = -_nx.inf
<ide> return y.argmax(axis) | 1 |
Javascript | Javascript | fix bits of documentation | c7203f636e97d7fb7ba90c370ff2549effcf276c | <ide><path>packages/ember-routing/lib/router.js
<ide> var merge = function(original, hash) {
<ide> route: '/theBaseRouteForThisSet',
<ide>
<ide> indexSubRoute: Ember.Route.extend({
<del> route: '/',
<add> route: '/'
<ide> }),
<ide>
<ide> subRouteOne: Ember.Route.extend({
<del> route: '/subroute1
<add> route: '/subroute1'
<ide> }),
<ide>
<ide> subRouteTwo: Ember.Route.extend({ | 1 |
PHP | PHP | add test case for __debuginfo throwing exception | bc8cceeb29fbf62401db841d5831d8b0110913eb | <ide><path>tests/TestCase/Error/DebuggerTest.php
<ide> use TestApp\Error\TestDebugger;
<ide> use TestApp\Error\Thing\DebuggableThing;
<ide> use TestApp\Error\Thing\SecurityThing;
<add>use TestApp\Utility\ThrowsDebugInfo;
<ide>
<ide> /**
<ide> * DebuggerTest class
<ide> public function testExportVarDebugInfo()
<ide> $this->assertStringContainsString("'_validator' => [", $result);
<ide> }
<ide>
<add> /**
<add> * Test exportVar with an exception during __debugInfo()
<add> *
<add> * @return void
<add> */
<add> public function testExportVarInvalidDebugInfo()
<add> {
<add> $result = Debugger::exportVar(new ThrowsDebugInfo());
<add> $expected = '(unable to export object: from __debugInfo)';
<add> $this->assertTextEquals($expected, $result);
<add> }
<add>
<ide> /**
<ide> * Text exportVarAsNodes()
<ide> *
<ide><path>tests/test_app/TestApp/Utility/ThrowsDebugInfo.php
<add><?php
<add>declare(strict_types=1);
<add>
<add>namespace TestApp\Utility;
<add>
<add>use Exception;
<add>
<add>class ThrowsDebugInfo
<add>{
<add> public function __debugInfo()
<add> {
<add> throw new Exception('from __debugInfo');
<add> }
<add>} | 2 |
Python | Python | fix loading models with pretrained vectors | 81f4005f3d9e4b0b09c34f0c12b6ffc464b961a2 | <ide><path>spacy/language.py
<ide> def from_disk(self, path, disable=tuple()):
<ide> """
<ide> path = util.ensure_path(path)
<ide> deserializers = OrderedDict((
<del> ('vocab', lambda p: self.vocab.from_disk(p)),
<add> ('meta.json', lambda p: self.meta.update(util.read_json(p))),
<add> ('vocab', lambda p: (
<add> self.vocab.from_disk(p) and _fix_pretrained_vectors_name(self))),
<ide> ('tokenizer', lambda p: self.tokenizer.from_disk(p, vocab=False)),
<del> ('meta.json', lambda p: self.meta.update(util.read_json(p)))
<ide> ))
<del> _fix_pretrained_vectors_name(self)
<ide> for name, proc in self.pipeline:
<ide> if name in disable:
<ide> continue
<ide> def from_bytes(self, bytes_data, disable=[]):
<ide> RETURNS (Language): The `Language` object.
<ide> """
<ide> deserializers = OrderedDict((
<del> ('vocab', lambda b: self.vocab.from_bytes(b)),
<add> ('meta', lambda b: self.meta.update(ujson.loads(b))),
<add> ('vocab', lambda b: (
<add> self.vocab.from_bytes(b) and _fix_pretrained_vectors_name(self))),
<ide> ('tokenizer', lambda b: self.tokenizer.from_bytes(b, vocab=False)),
<del> ('meta', lambda b: self.meta.update(ujson.loads(b)))
<ide> ))
<del> _fix_pretrained_vectors_name(self)
<ide> for i, (name, proc) in enumerate(self.pipeline):
<ide> if name in disable:
<ide> continue
<ide> def _fix_pretrained_vectors_name(nlp):
<ide> nlp.vocab.vectors.name = vectors_name
<ide> else:
<ide> raise ValueError(Errors.E092)
<add> link_vectors_to_models(nlp.vocab)
<ide> for name, proc in nlp.pipeline:
<ide> if not hasattr(proc, 'cfg'):
<ide> continue
<del> if proc.cfg.get('pretrained_dims'):
<del> assert nlp.vocab.vectors.name
<del> proc.cfg['pretrained_vectors'] = nlp.vocab.vectors.name
<add> proc.cfg.setdefault('deprecation_fixes', {})
<add> proc.cfg['deprecation_fixes']['vectors_name'] = nlp.vocab.vectors.name
<ide>
<ide>
<ide> class DisabledPipes(list): | 1 |
Javascript | Javascript | improve box3 closure performance | 7ea7d9db8968e446fff6a92573a4685293b1be70 | <ide><path>src/math/Box3.js
<ide> Object.assign( Box3.prototype, {
<ide>
<ide> intersectsSphere: ( function () {
<ide>
<del> var closestPoint;
<add> var closestPoint = new Vector3();
<ide>
<ide> return function intersectsSphere( sphere ) {
<ide>
<del> if ( closestPoint === undefined ) closestPoint = new Vector3();
<del>
<ide> // Find the point on the AABB closest to the sphere center.
<ide> this.clampPoint( sphere.center, closestPoint );
<ide> | 1 |
PHP | PHP | remove unneeded service provider | 60d782a1bb25d8a9685261adb009cb5f6067b003 | <ide><path>config/app.php
<ide> Illuminate\Bus\BusServiceProvider::class,
<ide> Illuminate\Cache\CacheServiceProvider::class,
<ide> Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
<del> Illuminate\Routing\ControllerServiceProvider::class,
<ide> Illuminate\Cookie\CookieServiceProvider::class,
<ide> Illuminate\Database\DatabaseServiceProvider::class,
<ide> Illuminate\Encryption\EncryptionServiceProvider::class, | 1 |
Javascript | Javascript | add combineurls helper | e253b0ef3ef17d900ec9d1814a4bba8e00c1c70b | <ide><path>lib/helpers/combineURLs.js
<add>'use strict';
<add>
<add>/**
<add> * Creates a new URL by combining the specified URLs
<add> *
<add> * @param {string} baseURL The base URL
<add> * @param {string} relativeURL The relative URL
<add> * @returns {string} The combined URL
<add> */
<add>module.exports = function combineURLs(baseURL, relativeURL) {
<add> return baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '');
<add>};
<ide><path>test/specs/helpers/combineURLs.spec.js
<add>var combineURLs = require('../../../lib/helpers/combineURLs');
<add>
<add>describe('helpers::combineURLs', function () {
<add> it('should combine URLs', function () {
<add> expect(combineURLs('https://api.github.com', '/users')).toBe('https://api.github.com/users');
<add> });
<add>
<add> it('should remove duplicate slashes', function () {
<add> expect(combineURLs('https://api.github.com/', '/users')).toBe('https://api.github.com/users');
<add> });
<add>
<add> it('should insert missing slash', function () {
<add> expect(combineURLs('https://api.github.com', 'users')).toBe('https://api.github.com/users');
<add> });
<add>}); | 2 |
Go | Go | fix testapiimagesdelete for --net none build | 5c86f311c88fafe87e08e58e2cd083fba127f95a | <ide><path>integration-cli/docker_api_images_test.go
<ide> func (s *DockerSuite) TestApiImagesSaveAndLoad(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestApiImagesDelete(c *check.C) {
<add> testRequires(c, Network)
<ide> name := "test-api-images-delete"
<ide> out, err := buildImage(name, "FROM hello-world\nENV FOO bar", false)
<ide> if err != nil { | 1 |
Javascript | Javascript | copy all node_modules paths in one step | d3cfbf97f98d7b487f8458bbf83c2fbbfd5a3387 | <ide><path>script/lib/copy-assets.js
<ide> module.exports = function () {
<ide> path.join(CONFIG.repositoryRootPath, 'benchmarks', 'benchmark-runner.js'),
<ide> path.join(CONFIG.repositoryRootPath, 'dot-atom'),
<ide> path.join(CONFIG.repositoryRootPath, 'exports'),
<del> path.join(CONFIG.repositoryRootPath, 'node_modules'),
<ide> path.join(CONFIG.repositoryRootPath, 'package.json'),
<ide> path.join(CONFIG.repositoryRootPath, 'static'),
<ide> path.join(CONFIG.repositoryRootPath, 'src'),
<ide> module.exports = function () {
<ide> fs.copySync(srcPath, computeDestinationPath(srcPath), {filter: includePathInPackagedApp})
<ide> }
<ide>
<del> // Run a second copy pass for symlinked directories under node_modules.
<add> // Run a copy pass to dereference symlinked directories under node_modules.
<ide> // We do this to ensure that symlinked repo-local bundled packages get
<ide> // copied to the output folder correctly. We dereference only the top-level
<ide> // symlinks and not nested symlinks to avoid issues where symlinked binaries
<ide> // are duplicated in Atom's installation packages (see atom/atom#18490).
<ide> const nodeModulesPath = path.join(CONFIG.repositoryRootPath, 'node_modules')
<del> fs.readdirSync(nodeModulesPath)
<del> .map(p => path.join(nodeModulesPath, p))
<del> .filter(p => fs.lstatSync(p).isSymbolicLink())
<del> .forEach(modulePath => {
<del> // Replace the symlink that was copied already
<del> const destPath = path.join(CONFIG.intermediateAppPath, 'node_modules', path.basename(modulePath))
<del> fs.unlinkSync(destPath)
<del> fs.copySync(modulePath, destPath, { filter: includePathInPackagedApp, clobber: true })
<del> })
<add> glob.sync(path.join(nodeModulesPath, '*'))
<add> .map(p => fs.lstatSync(p).isSymbolicLink() ? fs.readlinkSync(p) : p)
<add> .forEach(modulePath => {
<add> const destPath = path.join(CONFIG.intermediateAppPath, 'node_modules', path.basename(modulePath))
<add> fs.copySync(modulePath, destPath, { filter: includePathInPackagedApp })
<add> })
<ide>
<ide> fs.copySync(
<ide> path.join(CONFIG.repositoryRootPath, 'resources', 'app-icons', CONFIG.channel, 'png', '1024.png'), | 1 |
Ruby | Ruby | handle recursive directory installs | 58cb4444da8f20e4e51800af253dedeadefc0edf | <ide><path>Library/Homebrew/extend/pathname.rb
<ide> def install_p src, new_basename = nil
<ide> dst = dst.to_s
<ide>
<ide> dst = yield(src, dst) if block_given?
<add> return unless dst
<ide>
<ide> mkpath
<ide>
<ide><path>Library/Homebrew/install_renamed.rb
<ide> module InstallRenamed
<ide> def install_p src, new_basename = nil
<ide> super do |src, dst|
<ide> dst += "/#{File.basename(src)}" if File.directory? dst
<add>
<add> if File.directory? src
<add> Pathname.new(dst).install Dir["#{src}/*"]
<add> next
<add> end
<add>
<ide> append_default_if_different(src, dst)
<ide> end
<ide> end
<ide> def cp_path_sub pattern, replacement
<ide> end
<ide> end
<ide>
<add> def + path
<add> super(path).extend(InstallRenamed)
<add> end
<add>
<add> def / path
<add> super(path).extend(InstallRenamed)
<add> end
<add>
<ide> private
<ide>
<ide> def append_default_if_different src, dst | 2 |
Java | Java | fix javadoc error in jdbcoperations | 4e522c0cc36f5d506d01e1906c70f1151bddf1b7 | <ide><path>org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/JdbcOperations.java
<ide> * As an alternative to a mock objects approach to testing data access code,
<ide> * consider the powerful integration testing support provided in the
<ide> * <code>org.springframework.test</code> package, shipped in
<del> * <code>spring-mock.jar</code>.
<add> * <code>spring-test.jar</code>.
<ide> *
<ide> * @author Rod Johnson
<ide> * @author Juergen Hoeller | 1 |
Python | Python | add exception to catch single line private keys | e63dbdc431c2fa973e9a4c0b48ec6230731c38d1 | <ide><path>airflow/providers/ssh/hooks/ssh.py
<ide> def _pkey_from_private_key(self, private_key: str, passphrase: Optional[str] = N
<ide> :return: ``paramiko.PKey`` appropriate for given key
<ide> :raises AirflowException: if key cannot be read
<ide> """
<add> if len(private_key.split("\n", 2)) < 2:
<add> raise AirflowException('Key must have BEGIN and END header/footer on separate lines.')
<add>
<ide> for pkey_class in self._pkey_loaders:
<ide> try:
<ide> key = pkey_class.from_private_key(StringIO(private_key), password=passphrase)
<ide><path>tests/providers/ssh/hooks/test_ssh.py
<ide> def test_openssh_private_key(self):
<ide> session.delete(conn)
<ide> session.commit()
<ide>
<add> def test_oneline_key(self):
<add> with pytest.raises(Exception):
<add> TEST_ONELINE_KEY = "-----BEGIN OPENSSH" + "PRIVATE KEY-----asdfg-----END OPENSSH PRIVATE KEY-----"
<add> session = settings.Session()
<add> try:
<add> conn = Connection(
<add> conn_id='openssh_pkey',
<add> host='localhost',
<add> conn_type='ssh',
<add> extra={"private_key": TEST_ONELINE_KEY},
<add> )
<add> session.add(conn)
<add> session.flush()
<add> SSHHook(ssh_conn_id=conn.conn_id)
<add> finally:
<add> session.delete(conn)
<add> session.commit()
<add>
<ide> @pytest.mark.flaky(max_runs=5, min_passes=1)
<ide> def test_exec_ssh_client_command(self):
<ide> hook = SSHHook( | 2 |
Javascript | Javascript | make handling of nowarncode stricter | 41843e23f260eccf1e4a3be8ed9e429fa4b87ea5 | <ide><path>test/common/index.js
<ide> exports.isAlive = function isAlive(pid) {
<ide> }
<ide> };
<ide>
<del>exports.noWarnCode = 'no_expected_warning_code';
<add>exports.noWarnCode = undefined;
<ide>
<ide> function expectWarning(name, expected) {
<ide> const map = new Map(expected);
<ide> function expectWarning(name, expected) {
<ide> assert.ok(map.has(warning.message),
<ide> `unexpected error message: "${warning.message}"`);
<ide> const code = map.get(warning.message);
<del> if (code === undefined) {
<del> throw new Error('An error code must be specified or use ' +
<del> 'common.noWarnCode if there is no error code. The error ' +
<del> `code for this warning was ${warning.code}`);
<del> }
<del> if (code !== exports.noWarnCode) {
<del> assert.strictEqual(warning.code, code);
<del> }
<add> assert.strictEqual(warning.code, code);
<ide> // Remove a warning message after it is seen so that we guarantee that we
<ide> // get each message only once.
<ide> map.delete(expected);
<ide><path>test/parallel/test-promises-unhandled-symbol-rejections.js
<ide> const expectedDeprecationWarning = ['Unhandled promise rejections are ' +
<ide> 'deprecated. In the future, promise ' +
<ide> 'rejections that are not handled will ' +
<ide> 'terminate the Node.js process with a ' +
<del> 'non-zero exit code.', common.noWarnCode];
<add> 'non-zero exit code.', 'DEP0018'];
<ide> const expectedPromiseWarning = ['Unhandled promise rejection. ' +
<ide> 'This error originated either by throwing ' +
<ide> 'inside of an async function without a catch ' +
<ide><path>test/parallel/test-util.js
<ide> assert.strictEqual(util.isFunction(), false);
<ide> assert.strictEqual(util.isFunction('string'), false);
<ide>
<ide> common.expectWarning('DeprecationWarning', [
<del> ['util.print is deprecated. Use console.log instead.', common.noWarnCode],
<del> ['util.puts is deprecated. Use console.log instead.', common.noWarnCode],
<del> ['util.debug is deprecated. Use console.error instead.', common.noWarnCode],
<del> ['util.error is deprecated. Use console.error instead.', common.noWarnCode]
<add> ['util.print is deprecated. Use console.log instead.', 'DEP0026'],
<add> ['util.puts is deprecated. Use console.log instead.', 'DEP0027'],
<add> ['util.debug is deprecated. Use console.error instead.', 'DEP0028'],
<add> ['util.error is deprecated. Use console.error instead.', 'DEP0029']
<ide> ]);
<ide>
<ide> util.print('test'); | 3 |
PHP | PHP | fix lint errors + comment content | 62dd39133b5c2fab30977f2e509e7bbfb7287984 | <ide><path>lib/Cake/Console/Command/Task/TestTask.php
<ide> public function mapType($type, $plugin) {
<ide> /**
<ide> * Get the base class and package name for a given type.
<ide> *
<del> * @param string $package The package the class having a test
<del> * generated for is in.
<add> * @param string $type The type of class having a test
<add> * generated is in.
<ide> * @return array Array of class, type)
<add> * @throws CakeException on invalid types.
<ide> */
<ide> public function getBaseType($type) {
<ide> if (empty($this->baseTypes[$type])) {
<del> throw new CakeException(__d('cake_dev', 'Invalid package name'));
<add> throw new CakeException(__d('cake_dev', 'Invalid type name'));
<ide> }
<ide> return $this->baseTypes[$type];
<ide> } | 1 |
PHP | PHP | update mysqlconnector.php to support sphinx | c3fc09e4e56b700e390827153acf9d13d51596b9 | <ide><path>src/Illuminate/Database/Connectors/MySqlConnector.php
<ide> public function connect(array $config)
<ide> // is set on the server but needs to be set here on this client objects.
<ide> $charset = $config['charset'];
<ide>
<del> $names = "set names '$charset' collate '$collation'";
<add> $names = "set names '$charset'".($collation!==null ? " collate '$collation'" : null);
<ide>
<ide> $connection->prepare($names)->execute();
<ide>
<ide> protected function getDsn(array $config)
<ide> return $dsn;
<ide> }
<ide>
<del>}
<ide>\ No newline at end of file
<add>} | 1 |
Python | Python | add test for custom data augmentation | c41a4332e4f21627db1a7c5e057c3cfd70f5fea7 | <ide><path>spacy/tests/training/test_training.py
<ide> from spacy.training.augment import create_orth_variants_augmenter
<ide> from spacy.lang.en import English
<ide> from spacy.tokens import Doc, DocBin
<del>from spacy.lookups import Lookups
<ide> from spacy.util import get_words_and_spaces, minibatch
<ide> from thinc.api import compounding
<ide> import pytest
<ide> import srsly
<add>import random
<ide>
<ide> from ..util import make_tempdir
<ide>
<ide> def test_make_orth_variants(doc):
<ide> list(reader(nlp))
<ide>
<ide>
<add>@pytest.mark.filterwarnings("ignore::UserWarning")
<add>def test_custom_data_augmentation(doc):
<add> def create_spongebob_augmenter(randomize: bool = False):
<add> def augment(nlp, example):
<add> text = example.text
<add> if randomize:
<add> ch = [c.lower() if random.random() < 0.5 else c.upper() for c in text]
<add> else:
<add> ch = [c.lower() if i % 2 else c.upper() for i, c in enumerate(text)]
<add> example_dict = example.to_dict()
<add> doc = nlp.make_doc("".join(ch))
<add> example_dict["token_annotation"]["ORTH"] = [t.text for t in doc]
<add> yield example
<add> yield example.from_dict(doc, example_dict)
<add>
<add> return augment
<add>
<add> nlp = English()
<add> with make_tempdir() as tmpdir:
<add> output_file = tmpdir / "roundtrip.spacy"
<add> DocBin(docs=[doc]).to_disk(output_file)
<add> reader = Corpus(output_file, augmenter=create_spongebob_augmenter())
<add> corpus = list(reader(nlp))
<add> orig_text = "Sarah 's sister flew to Silicon Valley via London . "
<add> augmented = "SaRaH 's sIsTeR FlEw tO SiLiCoN VaLlEy vIa lOnDoN . "
<add> assert corpus[0].text == orig_text
<add> assert corpus[0].reference.text == orig_text
<add> assert corpus[0].predicted.text == orig_text
<add> assert corpus[1].text == augmented
<add> assert corpus[1].reference.text == augmented
<add> assert corpus[1].predicted.text == augmented
<add>
<add>
<ide> @pytest.mark.skip("Outdated")
<ide> @pytest.mark.parametrize(
<ide> "tokens_a,tokens_b,expected", | 1 |
Text | Text | remove parenthetical in onboarding-extras | 45c7e03f400bbb0e7d037ae470d291bce2183155 | <ide><path>doc/onboarding-extras.md
<ide> need to be attached anymore, as only important bugfixes will be included.
<ide> to update from nodejs/node:
<ide>
<ide> * `git checkout master`
<del>* `git remote update -p` OR `git fetch --all` (I prefer the former)
<add>* `git remote update -p` OR `git fetch --all`
<ide> * `git merge --ff-only upstream/master` (or `REMOTENAME/BRANCH`)
<ide>
<ide> ## Best practices | 1 |
Python | Python | fix searchfilter issues | 092d5223eb7ea1bbf9b6bb967200cb3725e02112 | <ide><path>rest_framework/filters.py
<ide> def get_search_terms(self, request):
<ide> Search terms are set by a ?search=... query parameter,
<ide> and may be comma and/or whitespace delimited.
<ide> """
<del> params = request.QUERY_PARAMS.get(self.search_param)
<add> params = request.QUERY_PARAMS.get(self.search_param, '')
<ide> return params.replace(',', ' ').split()
<ide>
<ide> def construct_search(self, field_name):
<ide> def filter_queryset(self, request, queryset, view):
<ide> search_fields = getattr(view, 'search_fields', None)
<ide>
<ide> if not search_fields:
<del> return None
<add> return queryset
<ide>
<ide> orm_lookups = [self.construct_search(str(search_field))
<ide> for search_field in search_fields] | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.