content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
PHP
PHP
fix docblock for return values
9933484ca2ba7638007be888654538b65fd21a20
<ide><path>src/Illuminate/Routing/Router.php <ide> class Router implements HttpKernelInterface, RouteFiltererInterface { <ide> * <ide> * @param \Illuminate\Events\Dispatcher $events <ide> * @param \Illuminate\Container\Container $container <del> * @return void <ide> */ <ide> public function __construct(Dispatcher $events, Container $container = null) <ide> { <ide> protected function prefixedResource($name, $controller, array $options) <ide> // We need to extract the base resource from the resource name. Nested resources <ide> // are supported in the framework, but we need to know what name to use for a <ide> // place-holder on the route wildcards, which should be the base resources. <del> $callback = function($me) use ($name, $controller, $options) <add> $callback = function(Router $me) use ($name, $controller, $options) <ide> { <ide> $me->resource($name, $controller, $options); <ide> }; <ide> <del> return $this->group(compact('prefix'), $callback); <add> $this->group(compact('prefix'), $callback); <ide> } <ide> <ide> /** <ide> public function getResourceWildcard($value) <ide> * @param string $base <ide> * @param string $controller <ide> * @param array $options <del> * @return void <add> * @return Route <ide> */ <ide> protected function addResourceIndex($name, $base, $controller, $options) <ide> { <ide> protected function addResourceIndex($name, $base, $controller, $options) <ide> * @param string $base <ide> * @param string $controller <ide> * @param array $options <del> * @return void <add> * @return Route <ide> */ <ide> protected function addResourceCreate($name, $base, $controller, $options) <ide> { <ide> protected function addResourceCreate($name, $base, $controller, $options) <ide> * @param string $base <ide> * @param string $controller <ide> * @param array $options <del> * @return void <add> * @return Route <ide> */ <ide> protected function addResourceStore($name, $base, $controller, $options) <ide> { <ide> protected function addResourceStore($name, $base, $controller, $options) <ide> * @param string $base <ide> * @param string $controller <ide> * @param array $options <del> * @return void <add> * @return Route <ide> */ <ide> protected function addResourceShow($name, $base, $controller, $options) <ide> { <ide> protected function addResourceShow($name, $base, $controller, $options) <ide> * @param string $base <ide> * @param string $controller <ide> * @param array $options <del> * @return void <add> * @return Route <ide> */ <ide> protected function addResourceEdit($name, $base, $controller, $options) <ide> { <ide> protected function addResourceUpdate($name, $base, $controller, $options) <ide> { <ide> $this->addPutResourceUpdate($name, $base, $controller, $options); <ide> <del> return $this->addPatchResourceUpdate($name, $base, $controller); <add> $this->addPatchResourceUpdate($name, $base, $controller); <ide> } <ide> <ide> /** <ide> protected function addResourceUpdate($name, $base, $controller, $options) <ide> * @param string $base <ide> * @param string $controller <ide> * @param array $options <del> * @return void <add> * @return Route <ide> */ <ide> protected function addPutResourceUpdate($name, $base, $controller, $options) <ide> { <ide> protected function addPatchResourceUpdate($name, $base, $controller) <ide> * @param string $base <ide> * @param string $controller <ide> * @param array $options <del> * @return void <add> * @return Route <ide> */ <ide> protected function addResourceDestroy($name, $base, $controller, $options) <ide> { <ide> protected function routingToController($action) <ide> * Add a controller based route action to the action array. <ide> * <ide> * @param array|string $action <del> * @return void <add> * @return array <ide> */ <ide> protected function getControllerAction($action) <ide> { <ide> public function after($callback) <ide> * Register a new global filter with the router. <ide> * <ide> * @param string $filter <del> * @param mxied $callback <add> * @param mixed $callback <ide> * @return void <ide> */ <ide> protected function addGlobalFilter($filter, $callback) <ide> public function when($pattern, $name, $methods = null) <ide> */ <ide> public function model($key, $class, Closure $callback = null) <ide> { <del> return $this->bind($key, function($value) use ($class, $callback) <add> $this->bind($key, function($value) use ($class, $callback) <ide> { <ide> if (is_null($value)) return null; <ide>
1
Ruby
Ruby
remove redundant calls to stringify_keys
1f270e80e61570faafc7cc01c1ed19c1c5359ef3
<ide><path>actionpack/lib/action_view/helpers/form_tag_helper.rb <ide> def submit_tag(value = "Save changes", options = {}) <ide> options["data-confirm"] = confirm <ide> end <ide> <del> tag :input, { "type" => "submit", "name" => "commit", "value" => value }.update(options.stringify_keys) <add> tag :input, { "type" => "submit", "name" => "commit", "value" => value }.update(options) <ide> end <ide> <ide> # Creates a button element that defines a <tt>submit</tt> button, <ide> def image_submit_tag(source, options = {}) <ide> options["data-confirm"] = confirm <ide> end <ide> <del> tag :input, { "type" => "image", "src" => path_to_image(source) }.update(options.stringify_keys) <add> tag :input, { "type" => "image", "src" => path_to_image(source) }.update(options) <ide> end <ide> <ide> # Creates a field set for grouping HTML form elements.
1
Java
Java
simplify determination of sockjs path
2a6c1f75e7f9601d736dfebe5823e7070edf1db5
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/config/AbstractStompEndpointRegistration.java <ide> public StompSockJsServiceRegistration(TaskScheduler defaultTaskScheduler) { <ide> } <ide> <ide> protected SockJsService getSockJsService() { <del> return super.getSockJsService(paths); <add> return super.getSockJsService(); <ide> } <ide> } <ide> <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/server/config/AbstractWebSocketHandlerRegistration.java <ide> <ide> package org.springframework.web.socket.server.config; <ide> <del>import java.util.ArrayList; <ide> import java.util.Arrays; <del>import java.util.List; <ide> <ide> import org.springframework.scheduling.TaskScheduler; <ide> import org.springframework.util.Assert; <ide> final M getMappings() { <ide> M mappings = createMappings(); <ide> <ide> if (this.sockJsServiceRegistration != null) { <del> SockJsService sockJsService = this.sockJsServiceRegistration.getSockJsService(getAllPrefixes()); <add> SockJsService sockJsService = this.sockJsServiceRegistration.getSockJsService(); <ide> for (WebSocketHandler wsHandler : this.handlerMap.keySet()) { <ide> for (String path : this.handlerMap.get(wsHandler)) { <ide> String pathPattern = path.endsWith("/") ? path + "**" : path + "/**"; <ide> final M getMappings() { <ide> return mappings; <ide> } <ide> <del> private final String[] getAllPrefixes() { <del> List<String> all = new ArrayList<String>(); <del> for (List<String> prefixes: this.handlerMap.values()) { <del> all.addAll(prefixes); <del> } <del> return all.toArray(new String[all.size()]); <del> } <del> <ide> private HandshakeHandler getOrCreateHandshakeHandler() { <ide> return (this.handshakeHandler != null) ? this.handshakeHandler : new DefaultHandshakeHandler(); <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/server/config/SockJsServiceRegistration.java <ide> public SockJsServiceRegistration setInterceptors(HandshakeInterceptor... interce <ide> return this; <ide> } <ide> <del> protected SockJsService getSockJsService(String[] sockJsPrefixes) { <add> protected SockJsService getSockJsService() { <ide> DefaultSockJsService service = createSockJsService(); <del> if (sockJsPrefixes != null) { <del> service.setValidSockJsPrefixes(sockJsPrefixes); <del> } <ide> if (this.clientLibraryUrl != null) { <ide> service.setSockJsClientLibraryUrl(this.clientLibraryUrl); <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/SockJsHttpRequestHandler.java <ide> import org.springframework.http.server.ServletServerHttpResponse; <ide> import org.springframework.util.Assert; <ide> import org.springframework.web.HttpRequestHandler; <add>import org.springframework.web.servlet.HandlerMapping; <ide> import org.springframework.web.socket.WebSocketHandler; <ide> import org.springframework.web.socket.support.ExceptionWebSocketHandlerDecorator; <ide> import org.springframework.web.socket.support.LoggingWebSocketHandlerDecorator; <ide> public void handleRequest(HttpServletRequest servletRequest, HttpServletResponse <ide> ServerHttpResponse response = new ServletServerHttpResponse(servletResponse); <ide> <ide> try { <del> this.sockJsService.handleRequest(request, response, this.wsHandler); <add> this.sockJsService.handleRequest(request, response, getSockJsPath(servletRequest), this.wsHandler); <ide> } <ide> catch (Throwable t) { <ide> throw new SockJsException("Uncaught failure in SockJS request, uri=" + request.getURI(), t); <ide> } <ide> } <ide> <add> private String getSockJsPath(HttpServletRequest servletRequest) { <add> String attribute = HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE; <add> String path = (String) servletRequest.getAttribute(attribute); <add> return ((path.length() > 0) && (path.charAt(0) != '/')) ? "/" + path : path; <add> } <add> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/SockJsService.java <ide> * asynchronous support enabled through the ServletContext API or by adding an <ide> * {@code <async-support>true</async-support>} element to servlet and filter declarations <ide> * in web.xml. <del> * <p> <del> * The service can be integrated into any HTTP request handling mechanism (e.g. plain <del> * Servlet, Spring MVC, or other). It is expected that it will be mapped, as expected <del> * by the SockJS protocol, to a specific prefix (e.g. "/echo") including all sub-URLs <del> * (i.e. Ant path pattern "/echo/**"). <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> public interface SockJsService { <ide> * <ide> * @param request the current request <ide> * @param response the current response <add> * @param sockJsPath the remainder of the path within the SockJS service prefix <ide> * @param handler the handler that will exchange messages with the SockJS client <ide> * <ide> * @throws SockJsException raised when request processing fails; generally, failed <ide> public interface SockJsService { <ide> * The former is automatically added when using <ide> * {@link SockJsHttpRequestHandler}. <ide> */ <del> void handleRequest(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler handler) <del> throws SockJsException; <add> void handleRequest(ServerHttpRequest request, ServerHttpResponse response, String sockJsPath, <add> WebSocketHandler handler) throws SockJsException; <ide> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/support/AbstractSockJsService.java <ide> <ide> import java.io.IOException; <ide> import java.nio.charset.Charset; <del>import java.util.ArrayList; <ide> import java.util.Arrays; <del>import java.util.Collections; <del>import java.util.Comparator; <ide> import java.util.Date; <ide> import java.util.HashSet; <ide> import java.util.List; <ide> import java.util.Random; <del>import java.util.concurrent.CopyOnWriteArrayList; <ide> import java.util.concurrent.TimeUnit; <ide> <ide> import org.apache.commons.logging.Log; <ide> * An abstract base class for {@link SockJsService} implementations that provides SockJS <ide> * path resolution and handling of static SockJS requests (e.g. "/info", "/iframe.html", <ide> * etc). Sub-classes must handle session URLs (i.e. transport-specific requests). <del> * <p> <del> * This service is unaware of the underlying HTTP request processing mechanism and URL <del> * mappings but nevertheless needs to know the "SockJS path" for a given request, i.e. the <del> * portion of the URL path that follows the SockJS prefix. In most cases, this can be <del> * auto-detected since the <a href="https://github.com/sockjs/sockjs-client">SockJS <del> * client</a> sends a "greeting URL" first. However it is recommended to configure <del> * explicitly the expected SockJS prefixes via {@link #setValidSockJsPrefixes(String...)} <del> * to eliminate any potential issues. <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> public abstract class AbstractSockJsService implements SockJsService { <ide> <ide> private final TaskScheduler taskScheduler; <ide> <del> private final List<String> validSockJsPrefixes = new ArrayList<String>(); <del> <del> private final List<String> knownSockJsPrefixes = new CopyOnWriteArrayList<String>(); <del> <ide> <ide> public AbstractSockJsService(TaskScheduler scheduler) { <ide> Assert.notNull(scheduler, "scheduler must not be null"); <ide> public String getName() { <ide> return this.name; <ide> } <ide> <del> /** <del> * Use this property to configure one or more prefixes that this SockJS service is <del> * allowed to serve. The prefix (e.g. "/echo") is needed to extract the SockJS <del> * specific portion of the URL (e.g. "${prefix}/info", "${prefix}/iframe.html", etc). <del> * <del> * <p>This property is not strictly required. In most cases, the SockJS path can be <del> * auto-detected since the initial request from the SockJS client is of the form <del> * "{prefix}/info". Assuming the SockJS service is mapped correctly (e.g. using <del> * Ant-style pattern "/echo/**") this should work fine. This property can be used <del> * to configure explicitly the prefixes this service is allowed to service. <del> * <del> * @param prefixes the prefixes to use; prefixes do not need to include the portions <del> * of the path that represent Servlet container context or Servlet path. <del> */ <del> public void setValidSockJsPrefixes(String... prefixes) { <del> <del> this.validSockJsPrefixes.clear(); <del> for (String prefix : prefixes) { <del> if (prefix.endsWith("/") && (prefix.length() > 1)) { <del> prefix = prefix.substring(0, prefix.length() - 1); <del> } <del> this.validSockJsPrefixes.add(prefix); <del> } <del> <del> // sort with longest prefix at the top <del> Collections.sort(this.validSockJsPrefixes, Collections.reverseOrder(new Comparator<String>() { <del> @Override <del> public int compare(String o1, String o2) { <del> return new Integer(o1.length()).compareTo(new Integer(o2.length())); <del> } <del> })); <del> } <del> <ide> /** <ide> * Transports which don't support cross-domain communication natively (e.g. <ide> * "eventsource", "htmlfile") rely on serving a simple page (using the <ide> public boolean isWebSocketEnabled() { <ide> */ <ide> @Override <ide> public final void handleRequest(ServerHttpRequest request, ServerHttpResponse response, <del> WebSocketHandler wsHandler) throws SockJsException { <add> String sockJsPath, WebSocketHandler wsHandler) throws SockJsException { <ide> <del> String sockJsPath = getSockJsPath(request); <ide> if (sockJsPath == null) { <del> logger.warn("Could not determine SockJS path for URL \"" + request.getURI().getPath() + <del> ". Consider setting validSockJsPrefixes."); <add> logger.warn("No SockJS path provided, URI=\"" + request.getURI()); <ide> response.setStatusCode(HttpStatus.NOT_FOUND); <ide> return; <ide> } <ide> else if (sockJsPath.equals("/websocket")) { <ide> } <ide> } <ide> <del> /** <del> * Return the SockJS path or null if the path could not be determined. <del> */ <del> private String getSockJsPath(ServerHttpRequest request) { <del> <del> String path = request.getURI().getPath(); <del> <del> // Try SockJS prefix hints <del> if (!this.validSockJsPrefixes.isEmpty()) { <del> for (String prefix : this.validSockJsPrefixes) { <del> int index = path.lastIndexOf(prefix); <del> if (index != -1) { <del> return path.substring(index + prefix.length()); <del> } <del> } <del> return null; <del> } <del> <del> // Try SockJS info request <del> if (path.endsWith("/info")) { <del> addKnownSockJsPrefix(path.substring(0, path.length() - "/info".length())); <del> return "/info"; <del> } <del> <del> // Have we seen this prefix before (following the initial /info request)? <del> String match = null; <del> for (String sockJsPath : this.knownSockJsPrefixes) { <del> if (path.startsWith(sockJsPath)) { <del> if ((match == null) || (match.length() < sockJsPath.length())) { <del> match = sockJsPath; <del> } <del> } <del> } <del> if (match != null) { <del> String result = path.substring(match.length()); <del> Assert.isTrue(result.charAt(0) == '/', "Invalid SockJS path extracted from incoming path \"" + <del> path + "\". The extracted SockJS path is \"" + result + <del> "\". It was extracted from these known SockJS prefixes " + this.knownSockJsPrefixes + <del> ". Consider setting 'validSockJsPrefixes' on DefaultSockJsService."); <del> return result; <del> } <del> <del> // Try SockJS greeting <del> String pathNoSlash = path.endsWith("/") ? path.substring(0, path.length() - 1) : path; <del> String lastSegment = pathNoSlash.substring(pathNoSlash.lastIndexOf('/') + 1); <del> <del> if (!isValidTransportType(lastSegment) && !lastSegment.startsWith("iframe")) { <del> addKnownSockJsPrefix(path); <del> return ""; <del> } <del> <del> return null; <del> } <del> <del> private void addKnownSockJsPrefix(String path) { <del> if (this.knownSockJsPrefixes.size() > MAX_KNOWN_SOCKJS_PREFIX_COUNT) { <del> String removed = this.knownSockJsPrefixes.remove(0); <del> if (logger.isWarnEnabled()) { <del> logger.warn("MAX_KNOWN_SOCKJS_PREFIX_COUNT reached, removed prefix " + removed); <del> } <del> } <del> this.knownSockJsPrefixes.add(path); <del> } <del> <ide> /** <ide> * Validate whether the given transport String extracted from the URL is a valid <ide> * SockJS transport type (regardless of whether a transport handler is configured). <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/sockjs/support/AbstractSockJsServiceTests.java <ide> public void setUp() { <ide> this.service = new TestSockJsService(new ThreadPoolTaskScheduler()); <ide> } <ide> <del> @Test <del> public void getSockJsPathForGreetingRequest() throws Exception { <del> <del> handleRequest("GET", "/a", HttpStatus.OK); <del> assertEquals("Welcome to SockJS!\n", this.servletResponse.getContentAsString()); <del> <del> handleRequest("GET", "/a/", HttpStatus.OK); <del> assertEquals("Welcome to SockJS!\n", this.servletResponse.getContentAsString()); <del> <del> this.service.setValidSockJsPrefixes("/b"); <del> <del> handleRequest("GET", "/a", HttpStatus.NOT_FOUND); <del> handleRequest("GET", "/a/", HttpStatus.NOT_FOUND); <del> <del> handleRequest("GET", "/b", HttpStatus.OK); <del> assertEquals("Welcome to SockJS!\n", this.servletResponse.getContentAsString()); <del> } <del> <del> @Test <del> public void getSockJsPathForInfoRequest() throws Exception { <del> <del> handleRequest("GET", "/a/info", HttpStatus.OK); <del> <del> assertTrue(this.servletResponse.getContentAsString().startsWith("{\"entropy\":")); <del> <del> handleRequest("GET", "/a/server/session/xhr", HttpStatus.OK); <del> <del> assertEquals("session", this.service.sessionId); <del> assertEquals(TransportType.XHR.value(), this.service.transport); <del> assertSame(this.handler, this.service.handler); <del> <del> this.service.setValidSockJsPrefixes("/b"); <del> <del> handleRequest("GET", "/a/info", HttpStatus.NOT_FOUND); <del> handleRequest("GET", "/b/info", HttpStatus.OK); <del> <del> assertTrue(this.servletResponse.getContentAsString().startsWith("{\"entropy\":")); <del> } <del> <del> @Test <del> public void getSockJsPathForTransportRequest() throws Exception { <del> <del> // Info or greeting requests must be first so "/a" is cached as a known prefix <del> handleRequest("GET", "/a/info", HttpStatus.OK); <del> handleRequest("GET", "/a/server/session/xhr", HttpStatus.OK); <del> <del> assertEquals("session", this.service.sessionId); <del> assertEquals(TransportType.XHR.value(), this.service.transport); <del> assertSame(this.handler, this.service.handler); <del> } <del> <del> @Test <del> public void getSockJsPathForTransportRequestWithConfiguredPrefix() throws Exception { <del> <del> this.service.setValidSockJsPrefixes("/a"); <del> handleRequest("GET", "/a/server/session/xhr", HttpStatus.OK); <del> <del> assertEquals("session", this.service.sessionId); <del> assertEquals(TransportType.XHR.value(), this.service.transport); <del> assertSame(this.handler, this.service.handler); <del> } <del> <del> // SPR-10923 <del> <del> @Test <del> public void getSockJsPathWithPartlyMatchingServletPath() throws Exception { <del> <del> this.service.setValidSockJsPrefixes("/snake"); <del> handleRequest("GET", "/snakedemo/snake/info", HttpStatus.OK); <del> <del> assertTrue(this.servletResponse.getContentAsString().startsWith("{\"entropy\":")); <del> } <del> <ide> @Test <ide> public void validateRequest() throws Exception { <ide> <del> this.service.setValidSockJsPrefixes("/echo"); <del> <ide> this.service.setWebSocketsEnabled(false); <ide> handleRequest("GET", "/echo/server/session/websocket", HttpStatus.NOT_FOUND); <ide> <ide> public void validateRequest() throws Exception { <ide> @Test <ide> public void handleInfoGet() throws Exception { <ide> <del> handleRequest("GET", "/a/info", HttpStatus.OK); <add> handleRequest("GET", "/echo/info", HttpStatus.OK); <ide> <ide> assertEquals("application/json;charset=UTF-8", this.servletResponse.getContentType()); <ide> assertEquals("*", this.servletResponse.getHeader("Access-Control-Allow-Origin")); <ide> public void handleInfoGet() throws Exception { <ide> <ide> this.service.setSessionCookieNeeded(false); <ide> this.service.setWebSocketsEnabled(false); <del> handleRequest("GET", "/a/info", HttpStatus.OK); <add> handleRequest("GET", "/echo/info", HttpStatus.OK); <ide> <ide> body = this.servletResponse.getContentAsString(); <ide> assertEquals(",\"origins\":[\"*:*\"],\"cookie_needed\":false,\"websocket\":false}", <ide> public void handleInfoOptions() throws Exception { <ide> <ide> this.servletRequest.addHeader("Access-Control-Request-Headers", "Last-Modified"); <ide> <del> handleRequest("OPTIONS", "/a/info", HttpStatus.NO_CONTENT); <add> handleRequest("OPTIONS", "/echo/info", HttpStatus.NO_CONTENT); <ide> this.response.flush(); <ide> <ide> assertEquals("*", this.servletResponse.getHeader("Access-Control-Allow-Origin")); <ide> public void handleInfoOptions() throws Exception { <ide> @Test <ide> public void handleIframeRequest() throws Exception { <ide> <del> this.service.setValidSockJsPrefixes("/a"); <del> handleRequest("GET", "/a/iframe.html", HttpStatus.OK); <add> handleRequest("GET", "/echo/iframe.html", HttpStatus.OK); <ide> <ide> assertEquals("text/html;charset=UTF-8", this.servletResponse.getContentType()); <ide> assertTrue(this.servletResponse.getContentAsString().startsWith("<!DOCTYPE html>\n")); <ide> public void handleIframeRequestNotModified() throws Exception { <ide> <ide> this.servletRequest.addHeader("If-None-Match", "\"0da1ed070012f304e47b83c81c48ad620\""); <ide> <del> this.service.setValidSockJsPrefixes("/a"); <del> handleRequest("GET", "/a/iframe.html", HttpStatus.NOT_MODIFIED); <add> handleRequest("GET", "/echo/iframe.html", HttpStatus.NOT_MODIFIED); <ide> } <ide> <ide> @Test <ide> public void handleRawWebSocketRequest() throws Exception { <ide> <del> handleRequest("GET", "/a", HttpStatus.OK); <add> handleRequest("GET", "/echo", HttpStatus.OK); <ide> assertEquals("Welcome to SockJS!\n", this.servletResponse.getContentAsString()); <ide> <del> handleRequest("GET", "/a/websocket", HttpStatus.OK); <add> handleRequest("GET", "/echo/websocket", HttpStatus.OK); <ide> assertNull("Raw WebSocket should not open a SockJS session", this.service.sessionId); <ide> assertSame(this.handler, this.service.handler); <ide> } <ide> public void handleRawWebSocketRequest() throws Exception { <ide> private void handleRequest(String httpMethod, String uri, HttpStatus httpStatus) throws IOException { <ide> resetResponse(); <ide> setRequest(httpMethod, uri); <del> this.service.handleRequest(this.request, this.response, this.handler); <add> String sockJsPath = uri.substring("/echo".length()); <add> this.service.handleRequest(this.request, this.response, sockJsPath, this.handler); <ide> <ide> assertEquals(httpStatus.value(), this.servletResponse.getStatus()); <ide> } <ide> private void handleRequest(String httpMethod, String uri, HttpStatus httpStatus) <ide> public void handleEmptyContentType() throws Exception { <ide> <ide> servletRequest.setContentType(""); <del> handleRequest("GET", "/a/info", HttpStatus.OK); <add> handleRequest("GET", "/echo/info", HttpStatus.OK); <ide> <ide> assertEquals("Invalid/empty content should have been ignored", 200, this.servletResponse.getStatus()); <ide> } <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/sockjs/transport/handler/DefaultSockJsServiceTests.java <ide> */ <ide> public class DefaultSockJsServiceTests extends AbstractHttpRequestTests { <ide> <del> private static final String sockJsPrefix = "mysockjs"; <add> private static final String sockJsPrefix = "/mysockjs"; <ide> <ide> private static final String sessionId = "session1"; <ide> <del> private static final String sessionUrlPrefix = "/mysockjs/server1/" + sessionId + "/"; <add> private static final String sessionUrlPrefix = "/server1/" + sessionId + "/"; <ide> <ide> <ide> @Mock private SessionCreatingTransportHandler xhrHandler; <ide> public void setup() { <ide> <ide> this.service = new DefaultSockJsService(this.taskScheduler, <ide> Arrays.<TransportHandler>asList(this.xhrHandler, this.xhrSendHandler)); <del> this.service.setValidSockJsPrefixes(sockJsPrefix); <ide> } <ide> <ide> @Test <ide> public void customizedTransportHandlerList() { <ide> @Test <ide> public void handleTransportRequestXhr() throws Exception { <ide> <del> setRequest("POST", sessionUrlPrefix + "xhr"); <del> this.service.handleRequest(this.request, this.response, this.wsHandler); <add> String sockJsPath = sessionUrlPrefix + "xhr"; <add> setRequest("POST", sockJsPrefix + sockJsPath); <add> this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler); <ide> <ide> assertEquals(200, this.servletResponse.getStatus()); <ide> verify(this.xhrHandler).handleRequest(this.request, this.response, this.wsHandler, this.session); <ide> public void handleTransportRequestXhr() throws Exception { <ide> @Test <ide> public void handleTransportRequestXhrOptions() throws Exception { <ide> <del> setRequest("OPTIONS", sessionUrlPrefix + "xhr"); <del> this.service.handleRequest(this.request, this.response, this.wsHandler); <add> String sockJsPath = sessionUrlPrefix + "xhr"; <add> setRequest("OPTIONS", sockJsPrefix + sockJsPath); <add> this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler); <ide> <ide> assertEquals(204, this.servletResponse.getStatus()); <ide> assertEquals("*", this.response.getHeaders().getFirst("Access-Control-Allow-Origin")); <ide> public void handleTransportRequestXhrOptions() throws Exception { <ide> @Test <ide> public void handleTransportRequestNoSuitableHandler() throws Exception { <ide> <del> setRequest("POST", sessionUrlPrefix + "eventsource"); <del> this.service.handleRequest(this.request, this.response, this.wsHandler); <add> String sockJsPath = sessionUrlPrefix + "eventsource"; <add> setRequest("POST", sockJsPrefix + sockJsPath); <add> this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler); <ide> <ide> assertEquals(404, this.servletResponse.getStatus()); <ide> } <ide> <ide> @Test <ide> public void handleTransportRequestXhrSend() throws Exception { <ide> <del> setRequest("POST", sessionUrlPrefix + "xhr_send"); <del> this.service.handleRequest(this.request, this.response, this.wsHandler); <add> String sockJsPath = sessionUrlPrefix + "xhr_send"; <add> setRequest("POST", sockJsPrefix + sockJsPath); <add> this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler); <ide> <ide> assertEquals(404, this.servletResponse.getStatus()); // no session yet <ide> <ide> resetResponse(); <del> setRequest("POST", sessionUrlPrefix + "xhr"); <del> this.service.handleRequest(this.request, this.response, this.wsHandler); <add> sockJsPath = sessionUrlPrefix + "xhr"; <add> setRequest("POST", sockJsPrefix + sockJsPath); <add> this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler); <ide> <ide> assertEquals(200, this.servletResponse.getStatus()); // session created <ide> verify(this.xhrHandler).handleRequest(this.request, this.response, this.wsHandler, this.session); <ide> <ide> resetResponse(); <del> setRequest("POST", sessionUrlPrefix + "xhr_send"); <del> this.service.handleRequest(this.request, this.response, this.wsHandler); <add> sockJsPath = sessionUrlPrefix + "xhr_send"; <add> setRequest("POST", sockJsPrefix + sockJsPath); <add> this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler); <ide> <ide> assertEquals(200, this.servletResponse.getStatus()); // session exists <ide> verify(this.xhrSendHandler).handleRequest(this.request, this.response, this.wsHandler, this.session);
8
Python
Python
fix a bug reported in
ab891db0a0f8bddd1967288984fd60d1a489c7b2
<ide><path>libcloud/storage/drivers/google_storage.py <ide> # See the License for the specific language governing permissions and <ide> # limitations under the License. <ide> <add>from typing import Dict <add>from typing import Optional <add> <ide> import copy <ide> import json <ide> <ide> def ex_set_permissions(self, container_name, object_name=None, <ide> self.json_connection.request( <ide> url, method='POST', <ide> data=json.dumps({'role': role, 'entity': entity})) <add> <add> def _get_content_length_from_headers(self, <add> headers: Dict[str, str] <add> ) -> Optional[int]: <add> # We need to override this since Google storage doesn't always return <add> # Content-Length header. <add> # See https://github.com/apache/libcloud/issues/1544 for details. <add> x_goog_content_length = headers.get('x-goog-stored-content-length', <add> None) <add> content_length = headers.get('content-length', x_goog_content_length) <add> return content_length <ide><path>libcloud/storage/drivers/s3.py <ide> # See the License for the specific language governing permissions and <ide> # limitations under the License. <ide> <add>from typing import Dict <add>from typing import Optional <add> <ide> import base64 <ide> import hmac <ide> import time <ide> def _to_container(self, element): <ide> <ide> return container <ide> <add> def _get_content_length_from_headers(self, <add> headers: Dict[str, str] <add> ) -> Optional[int]: <add> """ <add> Prase object size from the provided response headers. <add> """ <add> content_length = headers.get("content-length", None) <add> return content_length <add> <ide> def _headers_to_object(self, object_name, container, headers): <ide> hash = headers['etag'].replace('"', '') <ide> extra = {'content_type': headers['content-type'], <ide> def _headers_to_object(self, object_name, container, headers): <ide> key = key.replace(self.http_vendor_prefix + '-meta-', '') <ide> meta_data[key] = value <ide> <del> obj = Object(name=object_name, size=headers['content-length'], <add> content_length = self._get_content_length_from_headers(headers=headers) <add> <add> if content_length is None: <add> raise KeyError("Can not deduce object size from headers for " <add> "object %s" % (object_name)) <add> <add> obj = Object(name=object_name, size=int(content_length), <ide> hash=hash, extra=extra, <ide> meta_data=meta_data, <ide> container=container, <ide><path>libcloud/test/storage/test_google_storage.py <ide> def _test2_test_get_object(self, method, url, body, headers): <ide> <ide> return httplib.OK, body, headers, httplib.responses[httplib.OK] <ide> <add> def _test2_test_cont_length_get_object(self, method, url, body, headers): <add> # test_get_object_object_size_not_in_content_length_header <add> # Google uses a different HTTP header prefix for meta data <add> body = self.fixtures.load('list_containers.xml') <add> headers = { <add> 'content-type': 'application/zip', <add> 'etag': '"e31208wqsdoj329jd"', <add> 'x-goog-meta-rabbits': 'monkeys', <add> 'x-goog-stored-content-length': '9587', <add> 'last-modified': 'Thu, 13 Sep 2012 07:13:22 GMT' <add> } <add> <add> return httplib.OK, body, headers, httplib.responses[httplib.OK] <add> <add> <ide> def _container_path_UNAUTHORIZED(self, method, url, body, headers): <ide> return (httplib.UNAUTHORIZED, <ide> '', <ide> def test_token(self): <ide> # Not supported on Google Storage <ide> pass <ide> <add> def test_get_object_object_size_in_content_length(self): <add> self.mock_response_klass.type = 'get_object' <add> obj = self.driver.get_object(container_name='test2', <add> object_name='test') <add> self.assertEqual(obj.size, 12345) <add> <add> def test_get_object_object_size_not_in_content_length_header(self): <add> self.mock_response_klass.type = 'get_object' <add> obj = self.driver.get_object(container_name='test2', <add> object_name='test_cont_length') <add> self.assertEqual(obj.size, 9587) <add> <ide> def test_delete_permissions(self): <ide> mock_request = mock.Mock() <ide> self.driver.json_connection.request = mock_request <ide><path>libcloud/test/storage/test_s3.py <ide> def _test2_get_object(self, method, url, body, headers): <ide> httplib.responses[httplib.OK]) <ide> <ide> def _test2_test_get_object(self, method, url, body, headers): <del> # test_get_object <add> # test_get_object_success <ide> body = self.fixtures.load('list_containers.xml') <ide> headers = {'content-type': 'application/zip', <ide> 'etag': '"e31208wqsdoj329jd"', <ide> def _test2_test_get_object(self, method, url, body, headers): <ide> headers, <ide> httplib.responses[httplib.OK]) <ide> <add> def _test2_get_object_no_content_length(self, method, url, body, headers): <add> # test_get_object_unable_to_determine_object_size <add> body = self.fixtures.load('list_containers.xml') <add> headers = {'content-type': 'application/zip', <add> 'etag': '"e31208wqsdoj329jd"', <add> 'x-amz-meta-rabbits': 'monkeys', <add> 'last-modified': 'Thu, 13 Sep 2012 07:13:22 GMT' <add> } <add> <add> return (httplib.OK, <add> body, <add> headers, <add> httplib.responses[httplib.OK]) <add> <add> def _test2_test_get_object_no_content_length(self, method, url, body, headers): <add> # test_get_object_unable_to_determine_object_size <add> body = self.fixtures.load('list_containers.xml') <add> headers = {'content-type': 'application/zip', <add> 'etag': '"e31208wqsdoj329jd"', <add> 'x-amz-meta-rabbits': 'monkeys', <add> 'last-modified': 'Thu, 13 Sep 2012 07:13:22 GMT' <add> } <add> <add> return (httplib.OK, <add> body, <add> headers, <add> httplib.responses[httplib.OK]) <add> <ide> def _new_container_INVALID_NAME(self, method, url, body, headers): <ide> # test_create_container <ide> return (httplib.BAD_REQUEST, <ide> def test_get_object_success(self): <ide> <ide> self.assertEqual(obj.name, 'test') <ide> self.assertEqual(obj.container.name, 'test2') <del> self.assertEqual(obj.size, '12345') <add> self.assertEqual(obj.size, 12345) <ide> self.assertEqual(obj.hash, 'e31208wqsdoj329jd') <ide> self.assertEqual(obj.extra['last_modified'], <ide> 'Thu, 13 Sep 2012 07:13:22 GMT') <ide> self.assertEqual(obj.extra['content_type'], 'application/zip') <ide> self.assertEqual(obj.meta_data['rabbits'], 'monkeys') <ide> <add> def test_get_object_unable_to_determine_object_size(self): <add> self.mock_response_klass.type = 'get_object_no_content_length' <add> <add> expected_msg = "Can not deduce object size from headers" <add> self.assertRaisesRegex(KeyError, expected_msg, <add> self.driver.get_object, <add> container_name='test2', <add> object_name='test') <add> <ide> def test_create_container_bad_request(self): <ide> # invalid container name, returns a 400 bad request <ide> self.mock_response_klass.type = 'INVALID_NAME'
4
PHP
PHP
fix usage of addparams() across the tests
5f923fffc9fda9565404f31c3dd79c7a8b0b07fc
<ide><path>src/Controller/Component/AuthComponent.php <ide> protected function _unauthenticated(Controller $controller) <ide> if ($auth === false) { <ide> throw new Exception('At least one authenticate object must be available.'); <ide> } <del> $result = $auth->unauthenticated($this->request, $response); <add> $result = $auth->unauthenticated($controller->request, $response); <ide> if ($result !== null) { <ide> return $result; <ide> } <ide> public function isAuthorized($user = null, ServerRequest $request = null) <ide> $user = $this->user(); <ide> } <ide> if (empty($request)) { <del> $request = $this->request; <add> $request = $this->getController()->getRequest(); <ide> } <ide> if (empty($this->_authorizeObjects)) { <ide> $this->constructAuthorize(); <ide> protected function _getUser() <ide> $this->constructAuthenticate(); <ide> } <ide> foreach ($this->_authenticateObjects as $auth) { <del> $result = $auth->getUser($this->request); <add> $result = $auth->getUser($this->getController()->getRequest()); <ide> if (!empty($result) && is_array($result)) { <ide> $this->_authenticationProvider = $auth; <ide> $event = $this->dispatchEvent('Auth.afterIdentify', [$result, $auth]); <ide> protected function _getUser() <ide> */ <ide> public function redirectUrl($url = null) <ide> { <del> $redirectUrl = $this->request->getQuery(static::QUERY_STRING_REDIRECT); <add> $redirectUrl = $this->getController()->getRequest()->getQuery(static::QUERY_STRING_REDIRECT); <ide> if ($redirectUrl && (substr($redirectUrl, 0, 1) !== '/' || substr($redirectUrl, 0, 2) === '//')) { <ide> $redirectUrl = null; <ide> } <ide> public function identify() <ide> $this->constructAuthenticate(); <ide> } <ide> foreach ($this->_authenticateObjects as $auth) { <del> $result = $auth->authenticate($this->request, $this->response); <add> $result = $auth->authenticate($this->getController()->getRequest(), $this->response); <ide> if (!empty($result)) { <ide> $this->_authenticationProvider = $auth; <ide> $event = $this->dispatchEvent('Auth.afterIdentify', [$result, $auth]); <ide> public function storage(StorageInterface $storage = null) <ide> if (!class_exists($className)) { <ide> throw new Exception(sprintf('Auth storage adapter "%s" was not found.', $class)); <ide> } <del> $this->_storage = new $className($this->request, $this->response, $config); <add> $request = $this->getController()->getRequest(); <add> $response = $this->getController()->getResponse(); <add> $this->_storage = new $className($request, $response, $config); <ide> <ide> return $this->_storage; <ide> } <ide><path>src/Controller/Component/PaginatorComponent.php <ide> public function getPaginator() <ide> */ <ide> protected function _setPagingParams() <ide> { <del> $request = $this->_registry->getController()->request; <add> $controller = $this->getController(); <add> $request = $controller->getRequest(); <add> $paging = $this->_paginator->getPagingParams() + (array)$request->getParam('paging'); <ide> <del> $request->addParams([ <del> 'paging' => $this->_paginator->getPagingParams() <del> + (array)$request->getParam('paging') <del> ]); <add> $controller->setRequest($request->withParam('paging', $paging)); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Auth/BasicAuthenticateTest.php <ide> public function testAuthenticateInjection() <ide> 'environment' => [ <ide> 'PHP_AUTH_USER' => '> 1', <ide> 'PHP_AUTH_PW' => "' OR 1 = 1" <del> ] <add> ], <ide> ]); <del> $request->addParams(['pass' => []]); <ide> <ide> $this->assertFalse($this->auth->getUser($request)); <ide> $this->assertFalse($this->auth->authenticate($request, $this->response)); <ide> public function testAuthenticateUsernameZero() <ide> public function testAuthenticateChallenge() <ide> { <ide> $request = new ServerRequest('posts/index'); <del> $request->addParams(['pass' => []]); <ide> <ide> try { <ide> $this->auth->unauthenticated($request, $this->response); <ide> public function testAuthenticateSuccess() <ide> 'PHP_AUTH_PW' => 'password' <ide> ] <ide> ]); <del> $request->addParams(['pass' => []]); <ide> <ide> $result = $this->auth->authenticate($request, $this->response); <ide> $expected = [ <ide> public function testAuthenticateFailReChallenge() <ide> 'PHP_AUTH_PW' => 'password' <ide> ] <ide> ]); <del> $request->addParams(['pass' => []]); <ide> <ide> $this->auth->unauthenticated($request, $this->response); <ide> } <ide><path>tests/TestCase/Auth/DigestAuthenticateTest.php <ide> public function testAuthenticateWrongUsername() <ide> { <ide> $this->expectException(\Cake\Http\Exception\UnauthorizedException::class); <ide> $this->expectExceptionCode(401); <del> $request = new ServerRequest('posts/index'); <del> $request->addParams(['pass' => []]); <add> $request = new ServerRequest(['url' => 'posts/index']); <ide> <ide> $data = [ <ide> 'username' => 'incorrect_user', <ide> public function testAuthenticateChallenge() <ide> 'url' => 'posts/index', <ide> 'environment' => ['REQUEST_METHOD' => 'GET'] <ide> ]); <del> $request->addParams(['pass' => []]); <ide> <ide> try { <ide> $this->auth->unauthenticated($request, $this->response); <ide> public function testAuthenticateChallengeIncludesStaleAttributeOnStaleNonce() <ide> 'url' => 'posts/index', <ide> 'environment' => ['REQUEST_METHOD' => 'GET'] <ide> ]); <del> $request->addParams(['pass' => []]); <ide> $data = [ <ide> 'uri' => '/dir/index.html', <ide> 'nonce' => $this->generateNonce(null, 5, strtotime('-10 minutes')), <ide> public function testAuthenticateFailsOnStaleNonce() <ide> 'url' => 'posts/index', <ide> 'environment' => ['REQUEST_METHOD' => 'GET'] <ide> ]); <del> $request->addParams(['pass' => []]); <ide> <ide> $data = [ <ide> 'uri' => '/dir/index.html', <ide> public function testAuthenticateValidUsernamePasswordNoNonce() <ide> 'url' => 'posts/index', <ide> 'environment' => ['REQUEST_METHOD' => 'GET'] <ide> ]); <del> $request->addParams(['pass' => []]); <ide> <ide> $data = [ <ide> 'username' => 'mariano', <ide> public function testAuthenticateSuccess() <ide> 'url' => 'posts/index', <ide> 'environment' => ['REQUEST_METHOD' => 'GET'] <ide> ]); <del> $request->addParams(['pass' => []]); <ide> <ide> $data = [ <ide> 'uri' => '/dir/index.html', <ide> public function testAuthenticateSuccessHiddenPasswordField() <ide> 'url' => 'posts/index', <ide> 'environment' => ['REQUEST_METHOD' => 'GET'] <ide> ]); <del> $request->addParams(['pass' => []]); <ide> <ide> $data = [ <ide> 'uri' => '/dir/index.html', <ide> public function testAuthenticateSuccessSimulatedRequestMethod() <ide> 'post' => ['_method' => 'PUT'], <ide> 'environment' => ['REQUEST_METHOD' => 'GET'] <ide> ]); <del> $request->addParams(['pass' => []]); <ide> <ide> $data = [ <ide> 'username' => 'mariano', <ide> public function testAuthenticateFailReChallenge() <ide> 'url' => 'posts/index', <ide> 'environment' => ['REQUEST_METHOD' => 'GET'] <ide> ]); <del> $request->addParams(['pass' => []]); <ide> <ide> $data = [ <ide> 'username' => 'invalid', <ide><path>tests/TestCase/Controller/Component/AuthComponentTest.php <ide> public function setUp() <ide> <ide> $Users = TableRegistry::get('AuthUsers'); <ide> $Users->updateAll(['password' => password_hash('cake', PASSWORD_BCRYPT)], []); <add> $this->request = $request; <ide> } <ide> <ide> /** <ide> public function testIdentify() <ide> <ide> $this->Auth->setAuthenticateObject(0, $AuthLoginFormAuthenticate); <ide> <del> $this->Auth->request->data = [ <add> $this->Controller->request->data = [ <ide> 'AuthUsers' => [ <ide> 'username' => 'mark', <ide> 'password' => Security::hash('cake', null, true) <ide> public function testIdentify() <ide> <ide> $AuthLoginFormAuthenticate->expects($this->once()) <ide> ->method('authenticate') <del> ->with($this->Auth->request) <add> ->with($this->Controller->request) <ide> ->will($this->returnValue($user)); <ide> <ide> $result = $this->Auth->identify(); <ide> public function testIdentifyArrayAccess() <ide> <ide> $this->Auth->setAuthenticateObject(0, $AuthLoginFormAuthenticate); <ide> <del> $this->Auth->request->data = [ <add> $this->Controller->request->data = [ <ide> 'AuthUsers' => [ <ide> 'username' => 'mark', <ide> 'password' => Security::hash('cake', null, true) <ide> public function testIdentifyArrayAccess() <ide> <ide> $AuthLoginFormAuthenticate->expects($this->once()) <ide> ->method('authenticate') <del> ->with($this->Auth->request) <add> ->with($this->Controller->request) <ide> ->will($this->returnValue($user)); <ide> <ide> $result = $this->Auth->identify(); <ide> public function testAuthorizeFalse() <ide> $this->Controller->Auth->storage()->write($user); <ide> $this->Controller->Auth->setConfig('userModel', 'Users'); <ide> $this->Controller->Auth->setConfig('authorize', false); <del> $this->Controller->request->addParams(['controller' => 'AuthTest', 'action' => 'add']); <add> $this->Controller->request = $this->request->withAttribute('params', ['controller' => 'AuthTest', 'action' => 'add']); <ide> $result = $this->Controller->Auth->startup($event); <ide> $this->assertNull($result); <ide> <ide> public function testAuthorizeFalse() <ide> $this->assertInstanceOf('Cake\Http\Response', $result); <ide> $this->assertTrue($this->Auth->session->check('Flash.flash')); <ide> <del> $this->Controller->request->addParams(['controller' => 'AuthTest', 'action' => 'camelCase']); <add> $this->Controller->request = $this->request->withAttribute('params', ['controller' => 'AuthTest', 'action' => 'camelCase']); <ide> $result = $this->Controller->Auth->startup($event); <ide> $this->assertInstanceOf('Cake\Http\Response', $result); <ide> } <ide> public function testIsAuthorizedDelegation() <ide> $this->Auth->setAuthorizeObject(0, $AuthMockOneAuthorize); <ide> $this->Auth->setAuthorizeObject(1, $AuthMockTwoAuthorize); <ide> $this->Auth->setAuthorizeObject(2, $AuthMockThreeAuthorize); <del> $request = $this->Auth->request; <add> $request = $this->Controller->request; <ide> <ide> $AuthMockOneAuthorize->expects($this->once()) <ide> ->method('authorize') <ide> public function testIsAuthorizedWithArrayObject() <ide> ->getMock(); <ide> <ide> $this->Auth->setAuthorizeObject(0, $AuthMockOneAuthorize); <del> $request = $this->Auth->request; <add> $request = $this->Controller->request; <ide> <ide> $user = new \ArrayObject(['User']); <ide> <ide> public function testDenyWithCamelCaseMethods() <ide> $this->Controller->Auth->deny(['add', 'camelCase']); <ide> <ide> $url = '/auth_test/camelCase'; <del> $this->Controller->request->addParams(['controller' => 'AuthTest', 'action' => 'camelCase']); <del> $this->Controller->request->query['url'] = Router::normalize($url); <add> $this->Controller->request = $this->request->withAttribute( <add> 'params', <add> ['controller' => 'AuthTest', 'action' => 'camelCase'] <add> )->withQueryParams(['url' => Router::normalize($url)]); <ide> <ide> $this->assertInstanceOf('Cake\Http\Response', $this->Controller->Auth->startup($event)); <ide> <ide> $url = '/auth_test/CamelCase'; <del> $this->Controller->request->addParams(['controller' => 'AuthTest', 'action' => 'camelCase']); <del> $this->Controller->request->query['url'] = Router::normalize($url); <add> $this->Controller->request = $this->request->withAttribute( <add> 'params', <add> ['controller' => 'AuthTest', 'action' => 'camelCase'] <add> )->withQueryParams(['url' => Router::normalize($url)]); <ide> $this->assertInstanceOf('Cake\Http\Response', $this->Controller->Auth->startup($event)); <ide> } <ide> <ide> public function testAllowedActionsWithCamelCaseMethods() <ide> { <ide> $event = new Event('Controller.startup', $this->Controller); <ide> $url = '/auth_test/camelCase'; <del> $this->Controller->request->addParams(['controller' => 'AuthTest', 'action' => 'camelCase']); <del> $this->Controller->request->query['url'] = Router::normalize($url); <add> $this->Controller->request = $this->request <add> ->withAttribute('params', ['controller' => 'AuthTest', 'action' => 'camelCase']) <add> ->withRequestTarget($url); <ide> $this->Controller->Auth->loginAction = ['controller' => 'AuthTest', 'action' => 'login']; <ide> $this->Controller->Auth->userModel = 'AuthUsers'; <ide> $this->Controller->Auth->allow(); <ide> $result = $this->Controller->Auth->startup($event); <ide> $this->assertNull($result, 'startup() should return null, as action is allowed. %s'); <ide> <ide> $url = '/auth_test/camelCase'; <del> $this->Controller->request->addParams(['controller' => 'AuthTest', 'action' => 'camelCase']); <del> $this->Controller->request->query['url'] = Router::normalize($url); <add> $this->Controller->request = $this->request <add> ->withAttribute('params', ['controller' => 'AuthTest', 'action' => 'camelCase']) <add> ->withRequestTarget($url); <ide> $this->Controller->Auth->loginAction = ['controller' => 'AuthTest', 'action' => 'login']; <ide> $this->Controller->Auth->userModel = 'AuthUsers'; <ide> $this->Controller->Auth->allowedActions = ['delete', 'camelCase', 'add']; <ide> public function testAllowedActionsWithCamelCaseMethods() <ide> $this->assertInstanceOf('Cake\Http\Response', $this->Controller->Auth->startup($event)); <ide> <ide> $url = '/auth_test/delete'; <del> $this->Controller->request->addParams(['controller' => 'AuthTest', 'action' => 'delete']); <del> $this->Controller->request->query['url'] = Router::normalize($url); <add> $this->Controller->request = $this->request <add> ->withAttribute('params', ['controller' => 'AuthTest', 'action' => 'delete']) <add> ->withRequestTarget($url); <ide> $this->Controller->Auth->loginAction = ['controller' => 'AuthTest', 'action' => 'login']; <ide> $this->Controller->Auth->userModel = 'AuthUsers'; <ide> <ide> public function testAllowedActionsWithCamelCaseMethods() <ide> public function testAllowedActionsSetWithAllowMethod() <ide> { <ide> $url = '/auth_test/action_name'; <del> $this->Controller->request->addParams(['controller' => 'AuthTest', 'action' => 'action_name']); <del> $this->Controller->request->query['url'] = Router::normalize($url); <add> $this->Controller->request = $this->request <add> ->withAttribute('params', ['controller' => 'AuthTest', 'action' => 'action_name']); <ide> $this->Controller->Auth->allow(['action_name', 'anotherAction']); <ide> $this->assertEquals(['action_name', 'anotherAction'], $this->Controller->Auth->allowedActions); <ide> } <ide> public function testLoginRedirect() <ide> 'AuthUsers' => ['id' => '1', 'username' => 'nate'] <ide> ]); <ide> <del> $this->Auth->request = $this->Controller->request = new ServerRequest([ <add> $this->Controller->request = $this->Controller->request = new ServerRequest([ <ide> 'params' => ['controller' => 'Users', 'action' => 'login'], <ide> 'url' => '/users/login', <ide> 'environment' => ['HTTP_REFERER' => false], <ide> public function testLoginRedirect() <ide> 'Auth', <ide> ['AuthUsers' => ['id' => '1', 'username' => 'nate']] <ide> ); <del> $this->Auth->request = $this->Controller->request = new ServerRequest([ <add> $this->Controller->request = $this->Controller->request = new ServerRequest([ <ide> 'params' => ['controller' => 'Posts', 'action' => 'view', 'pass' => [1]], <ide> 'url' => '/posts/view/1', <ide> 'environment' => ['HTTP_REFERER' => false, 'REQUEST_METHOD' => 'GET'], <ide> public function testLoginRedirect() <ide> // Auth.redirect gets set when accessing a protected action without being authenticated <ide> $this->Auth->session->delete('Auth'); <ide> <del> $this->Auth->request = $this->Controller->request = new ServerRequest([ <add> $this->Controller->request = $this->Controller->request = new ServerRequest([ <ide> 'params' => ['controller' => 'Posts', 'action' => 'view', 'pass' => [1]], <ide> 'url' => '/posts/view/1', <ide> 'environment' => ['HTTP_REFERER' => false, 'REQUEST_METHOD' => 'GET'], <ide> public function testLoginRedirect() <ide> public function testLoginRedirectPost() <ide> { <ide> $this->Auth->session->delete('Auth'); <del> $this->Auth->request = new ServerRequest([ <add> $this->Controller->request = new ServerRequest([ <ide> 'environment' => [ <ide> 'HTTP_REFERER' => Router::url('/foo/bar', true), <ide> 'REQUEST_METHOD' => 'POST' <ide> public function testLoginRedirectPost() <ide> public function testLoginRedirectPostNoReferer() <ide> { <ide> $this->Auth->session->delete('Auth'); <del> $this->Auth->request = new ServerRequest([ <add> $this->Controller->request = new ServerRequest([ <ide> 'environment' => ['REQUEST_METHOD' => 'POST'], <ide> 'params' => ['controller' => 'Posts', 'action' => 'view', 'pass' => [1]], <ide> 'url' => '/posts/view/1?print=true&refer=menu', <ide> public function testLoginRedirectQueryString() <ide> { <ide> // QueryString parameters are preserved when redirecting with redirect key <ide> $this->Auth->session->delete('Auth'); <del> $this->Auth->request = new ServerRequest([ <add> $this->Controller->request = new ServerRequest([ <ide> 'environment' => ['REQUEST_METHOD' => 'GET'], <ide> 'params' => ['controller' => 'Posts', 'action' => 'view', 'pass' => [29]], <ide> 'url' => '/posts/view/29?print=true&refer=menu', <ide> public function testLoginRedirectQueryString() <ide> public function testLoginRedirectQueryStringWithComplexLoginActionUrl() <ide> { <ide> $this->Auth->session->delete('Auth'); <del> $this->Auth->request = new ServerRequest([ <add> $this->Controller->request = new ServerRequest([ <ide> 'environment' => ['REQUEST_METHOD' => 'GET'], <ide> 'params' => ['controller' => 'Posts', 'action' => 'view', 'pass' => [29]], <ide> 'url' => '/posts/view/29?print=true&refer=menu', <ide> public function testNoLoginRedirectForAuthenticatedUser() <ide> public function testDefaultToLoginRedirect() <ide> { <ide> $url = '/party/on'; <del> $this->Auth->request = $request = new ServerRequest([ <add> $this->Controller->request = $request = new ServerRequest([ <ide> 'url' => $url, <ide> 'environment' => [ <ide> 'HTTP_REFERER' => false, <ide> public function testRedirectToUnauthorizedRedirect() <ide> ->setMethods(['set']) <ide> ->setConstructorArgs([$this->Controller->components()]) <ide> ->getMock(); <del> $this->Auth->request = $request = new ServerRequest([ <add> $request = new ServerRequest([ <ide> 'url' => $url, <del> 'session' => $this->Auth->session <add> 'session' => $this->Auth->session, <add> 'params' => ['controller' => 'Party', 'action' => 'on'] <ide> ]); <del> $this->Auth->request->addParams(['controller' => 'Party', 'action' => 'on']); <ide> $this->Auth->setConfig('authorize', ['Controller']); <ide> $this->Auth->setUser(['username' => 'admad', 'password' => 'cake']); <ide> <ide> $expected = ['controller' => 'no_can_do', 'action' => 'jack']; <ide> $this->Auth->setConfig('unauthorizedRedirect', $expected); <ide> <ide> $response = new Response(); <del> $Controller = $this->getMockBuilder('Cake\Controller\Controller') <add> $controller = $this->getMockBuilder('Cake\Controller\Controller') <ide> ->setMethods(['on', 'redirect']) <ide> ->setConstructorArgs([$request, $response]) <ide> ->getMock(); <ide> <del> $Controller->expects($this->once()) <add> $controller->expects($this->once()) <ide> ->method('redirect') <ide> ->with($this->equalTo($expected)); <ide> <ide> $this->Auth->Flash->expects($this->once()) <ide> ->method('set'); <ide> <del> $event = new Event('Controller.startup', $Controller); <add> $event = new Event('Controller.startup', $controller); <ide> $this->Auth->startup($event); <ide> } <ide> <ide> public function testRedirectToUnauthorizedRedirectLoginAction() <ide> ->setMethods(['set']) <ide> ->setConstructorArgs([$this->Controller->components()]) <ide> ->getMock(); <del> $this->Auth->request = $request = new ServerRequest([ <add> $request = new ServerRequest([ <ide> 'url' => $url, <del> 'session' => $this->Auth->session <add> 'session' => $this->Auth->session, <add> 'params' => ['controller' => 'Party', 'action' => 'on'] <ide> ]); <del> $this->Auth->request->addParams(['controller' => 'Party', 'action' => 'on']); <ide> $this->Auth->setConfig('authorize', ['Controller']); <ide> $this->Auth->setUser(['username' => 'admad', 'password' => 'cake']); <ide> <ide> $this->Auth->setConfig('unauthorizedRedirect', true); <ide> $this->Auth->setConfig('loginAction', '/users/login'); <ide> <ide> $response = new Response(); <del> $Controller = $this->getMockBuilder('Cake\Controller\Controller') <add> $controller = $this->getMockBuilder('Cake\Controller\Controller') <ide> ->setMethods(['on', 'redirect']) <ide> ->setConstructorArgs([$request, $response]) <ide> ->getMock(); <ide> <ide> // Uses referrer instead of loginAction. <del> $Controller->expects($this->once()) <add> $controller->expects($this->once()) <ide> ->method('redirect') <ide> ->with($this->equalTo('/')); <ide> <del> $event = new Event('Controller.startup', $Controller); <add> $event = new Event('Controller.startup', $controller); <ide> $this->Auth->startup($event); <ide> } <ide> <ide> public function testRedirectToUnauthorizedRedirectSuppressedAuthError() <ide> $this->Auth->session = $this->getMockBuilder(Session::class) <ide> ->setMethods(['flash']) <ide> ->getMock(); <del> $this->Auth->request = $Request = new ServerRequest($url); <del> $this->Auth->request->addParams(['controller' => 'Party', 'action' => 'on']); <add> $request = new ServerRequest([ <add> 'url' => $url, <add> 'params' => ['controller' => 'Party', 'action' => 'on'] <add> ]); <ide> $this->Auth->setConfig('authorize', ['Controller']); <ide> $this->Auth->setUser(['username' => 'admad', 'password' => 'cake']); <ide> $expected = ['controller' => 'no_can_do', 'action' => 'jack']; <ide> $this->Auth->setConfig('unauthorizedRedirect', $expected); <ide> $this->Auth->setConfig('authError', false); <ide> <del> $Response = new Response(); <del> $Controller = $this->getMockBuilder('Cake\Controller\Controller') <add> $response = new Response(); <add> $controller = $this->getMockBuilder('Cake\Controller\Controller') <ide> ->setMethods(['on', 'redirect']) <del> ->setConstructorArgs([$Request, $Response]) <add> ->setConstructorArgs([$request, $response]) <ide> ->getMock(); <ide> <del> $Controller->expects($this->once()) <add> $controller->expects($this->once()) <ide> ->method('redirect') <ide> ->with($this->equalTo($expected)); <ide> <ide> $this->Auth->session->expects($this->never()) <ide> ->method('flash'); <ide> <del> $event = new Event('Controller.startup', $Controller); <add> $event = new Event('Controller.startup', $controller); <ide> $this->Auth->startup($event); <ide> } <ide> <ide> public function testRedirectToUnauthorizedRedirectSuppressedAuthError() <ide> public function testForbiddenException() <ide> { <ide> $this->expectException(\Cake\Http\Exception\ForbiddenException::class); <del> $url = '/party/on'; <del> $this->Auth->request = $request = new ServerRequest($url); <del> $this->Auth->request->addParams(['controller' => 'Party', 'action' => 'on']); <ide> $this->Auth->setConfig([ <ide> 'authorize' => ['Controller'], <ide> 'unauthorizedRedirect' => false <ide> ]); <ide> $this->Auth->setUser(['username' => 'baker', 'password' => 'cake']); <ide> <add> $request = $this->request <add> ->withAttribute('params', ['controller' => 'Party', 'action' => 'on']) <add> ->withRequestTarget('/party/on'); <ide> $response = new Response(); <ide> $Controller = $this->getMockBuilder('Cake\Controller\Controller') <ide> ->setMethods(['on', 'redirect']) <ide> public function testNoRedirectOnLoginAction() <ide> $controller->methods = ['login']; <ide> <ide> $url = '/AuthTest/login'; <del> $this->Auth->request = $controller->request = new ServerRequest($url); <del> $this->Auth->request->addParams(['controller' => 'AuthTest', 'action' => 'login']); <add> $this->Controller->request = $this->request <add> ->withAttribute('params', ['controller' => 'AuthTest', 'action' => 'login']) <add> ->withRequestTarget($url); <add> <ide> $this->Auth->setConfig([ <ide> 'loginAction', ['controller' => 'AuthTest', 'action' => 'login'], <ide> 'authorize', ['Controller'] <ide> public function testNoRedirectOn404() <ide> { <ide> $event = new Event('Controller.startup', $this->Controller); <ide> $this->Auth->session->delete('Auth'); <del> $this->Auth->request->addParams(['controller' => 'AuthTest', 'action' => 'something_totally_wrong']); <add> $this->Controller->request = $this->request->withAttribute( <add> 'params', <add> ['controller' => 'AuthTest', 'action' => 'something_totally_wrong'] <add> ); <ide> $result = $this->Auth->startup($event); <ide> $this->assertNull($result, 'Auth redirected a missing action %s'); <ide> } <ide> public function testAdminRoute() <ide> Router::scope('/', function ($routes) { <ide> $routes->fallbacks(InflectedRoute::class); <ide> }); <del> $this->Auth->request = new ServerRequest([ <add> $this->Controller->request = new ServerRequest([ <ide> 'environment' => [ <ide> 'REQUEST_METHOD' => 'GET', <ide> ], <ide> public function testAdminRoute() <ide> 'session' => $this->Auth->session <ide> ]); <ide> <del> Router::setRequestInfo($this->Auth->request); <add> Router::setRequestInfo($this->Controller->request); <ide> <ide> $this->Auth->setConfig('loginAction', [ <ide> 'prefix' => 'admin', <ide> public function testLoginActionRedirect() <ide> public function testStatelessAuthWorksWithUser() <ide> { <ide> $event = new Event('Controller.startup', $this->Controller); <del> $this->Auth->request = new ServerRequest([ <add> $this->Controller->request = new ServerRequest([ <ide> 'environment' => [ <ide> 'REQUEST_METHOD' => 'POST', <ide> 'PHP_AUTH_USER' => 'mariano', <ide> public function testAfterIdentifyForStatelessAuthentication() <ide> { <ide> $event = new Event('Controller.startup', $this->Controller); <ide> $url = '/auth_test/add'; <del> $this->Auth->request = $this->Auth->request <add> $this->Controller->request = $this->Controller->request <ide> ->withParam('controller', 'AuthTest') <ide> ->withParam('action', 'add') <ide> ->withEnv('PHP_AUTH_USER', 'mariano') <ide> public function testSetUser() <ide> { <ide> $storage = $this->getMockBuilder('Cake\Auth\Storage\SessionStorage') <ide> ->setMethods(['write']) <del> ->setConstructorArgs([$this->Auth->request, $this->Auth->response]) <add> ->setConstructorArgs([$this->Controller->request, $this->Auth->response]) <ide> ->getMock(); <ide> $this->Auth->storage($storage); <ide> <ide> public function testRedirectSet() <ide> public function testRedirectQueryStringRead() <ide> { <ide> $this->Auth->setConfig('loginAction', ['controller' => 'users', 'action' => 'login']); <del> $this->Auth->request->query = ['redirect' => '/users/custom']; <add> $this->Controller->request->query = ['redirect' => '/users/custom']; <ide> <ide> $result = $this->Auth->redirectUrl(); <ide> $this->assertEquals('/users/custom', $result); <ide> public function testRedirectQueryStringRead() <ide> */ <ide> public function testRedirectQueryStringReadDuplicateBase() <ide> { <del> $this->Auth->request->webroot = '/waves/'; <del> $this->Auth->request->base = '/waves'; <add> $this->Controller->request->webroot = '/waves/'; <add> $this->Controller->request->base = '/waves'; <ide> <del> $this->Auth->request->query = ['redirect' => '/waves/add']; <add> $this->Controller->request->query = ['redirect' => '/waves/add']; <ide> <del> Router::setRequestInfo($this->Auth->request); <add> Router::setRequestInfo($this->Controller->request); <ide> <ide> $result = $this->Auth->redirectUrl(); <ide> $this->assertEquals('/waves/add', $result); <ide> public function testRedirectQueryStringReadEqualToLoginAction() <ide> 'loginAction' => ['controller' => 'users', 'action' => 'login'], <ide> 'loginRedirect' => ['controller' => 'users', 'action' => 'home'] <ide> ]); <del> $this->Auth->request->query = ['redirect' => '/users/login']; <add> $this->Controller->request->query = ['redirect' => '/users/login']; <ide> <ide> $result = $this->Auth->redirectUrl(); <ide> $this->assertEquals('/users/home', $result); <ide> public function testRedirectQueryStringInvalid() <ide> 'loginAction' => ['controller' => 'users', 'action' => 'login'], <ide> 'loginRedirect' => ['controller' => 'users', 'action' => 'home'] <ide> ]); <del> $this->Auth->request->query = ['redirect' => 'http://some.domain.example/users/login']; <add> $this->Controller->request->query = ['redirect' => 'http://some.domain.example/users/login']; <ide> <ide> $result = $this->Auth->redirectUrl(); <ide> $this->assertEquals('/users/home', $result); <ide> <del> $this->Auth->request->query = ['redirect' => '//some.domain.example/users/login']; <add> $this->Controller->request->query = ['redirect' => '//some.domain.example/users/login']; <ide> <ide> $result = $this->Auth->redirectUrl(); <ide> $this->assertEquals('/users/home', $result); <ide> public function testRedirectUrlWithBaseSet() <ide> ]); <ide> <ide> $url = '/users/login'; <del> $this->Auth->request = $this->Controller->request = new ServerRequest($url); <del> $this->Auth->request->addParams(['controller' => 'Users', 'action' => 'login']); <del> $this->Auth->request->url = Router::normalize($url); <del> <del> Router::setRequestInfo($this->Auth->request); <add> $this->Controller->request = $this->Controller->request = new ServerRequest([ <add> 'url' => $url, <add> 'params' => ['plugin' => null, 'controller' => 'Users', 'action' => 'login'] <add> ]); <add> Router::setRequestInfo($this->Controller->request); <ide> <ide> $this->Auth->setConfig('loginAction', ['controller' => 'users', 'action' => 'login']); <ide> $this->Auth->setConfig('loginRedirect', ['controller' => 'users', 'action' => 'home']); <ide><path>tests/TestCase/Controller/Component/PaginatorComponentTest.php <ide> public function setUp() <ide> <ide> static::setAppNamespace(); <ide> <del> $this->request = new ServerRequest('controller_posts/index'); <del> $this->request->params['pass'] = []; <del> $controller = new Controller($this->request); <del> $this->registry = new ComponentRegistry($controller); <add> $request = new ServerRequest(['url' => 'controller_posts/index']); <add> $this->controller = new Controller($request); <add> $this->registry = new ComponentRegistry($this->controller); <ide> $this->Paginator = new PaginatorComponent($this->registry, []); <ide> <ide> $this->Post = $this->getMockRepository(); <ide> public function testPageParamCasting() <ide> ->method('find') <ide> ->will($this->returnValue($query)); <ide> <del> $this->request->query = ['page' => '1 " onclick="alert(\'xss\');">']; <add> $this->controller->request = $this->controller->request->withQueryParams(['page' => '1 " onclick="alert(\'xss\');">']); <ide> $settings = ['limit' => 1, 'maxLimit' => 10]; <ide> $this->Paginator->paginate($this->Post, $settings); <del> $this->assertSame(1, $this->request->params['paging']['Posts']['page'], 'XSS exploit opened'); <add> $this->assertSame(1, $this->controller->request->getParam('paging.Posts.page'), 'XSS exploit opened'); <ide> } <ide> <ide> /** <ide> public function testPageParamCasting() <ide> */ <ide> public function testPaginateExtraParams() <ide> { <del> $this->request->query = ['page' => '-1']; <add> $this->controller->request = $this->controller->request->withQueryParams(['page' => '-1']); <ide> $settings = [ <ide> 'PaginatorPosts' => [ <ide> 'contain' => ['PaginatorAuthor'], <ide> public function testPaginateCustomFinder() <ide> ->will($this->returnValue($query)); <ide> <ide> $this->Paginator->paginate($table, $settings); <del> $this->assertEquals('popular', $this->request->params['paging']['PaginatorPosts']['finder']); <add> $this->assertEquals('popular', $this->controller->request->getParam('paging.PaginatorPosts.finder')); <ide> } <ide> <ide> /** <ide> public function testDefaultPaginateParamsIntoRequest() <ide> ]); <ide> <ide> $this->Paginator->paginate($table, $settings); <del> $this->assertEquals('PaginatorPosts.id', $this->request->params['paging']['PaginatorPosts']['sortDefault']); <del> $this->assertEquals('DESC', $this->request->params['paging']['PaginatorPosts']['directionDefault']); <add> $this->assertEquals('PaginatorPosts.id', $this->controller->request->getParam('paging.PaginatorPosts.sortDefault')); <add> $this->assertEquals('DESC', $this->controller->request->getParam('paging.PaginatorPosts.directionDefault')); <ide> } <ide> <ide> /** <ide> public function testMergeOptionsModelSpecific() <ide> */ <ide> public function testMergeOptionsCustomScope() <ide> { <del> $this->request->query = [ <add> $this->controller->request = $this->controller->request->withQueryParams([ <ide> 'page' => 10, <ide> 'limit' => 10, <ide> 'scope' => [ <ide> 'page' => 2, <ide> 'limit' => 5, <ide> ] <del> ]; <add> ]); <ide> <ide> $settings = [ <ide> 'page' => 1, <ide> public function testMergeOptionsCustomScope() <ide> */ <ide> public function testMergeOptionsCustomFindKey() <ide> { <del> $this->request->query = [ <add> $this->controller->request = $this->controller->request->withQueryParams([ <ide> 'page' => 10, <ide> 'limit' => 10 <del> ]; <add> ]); <ide> $settings = [ <ide> 'page' => 1, <ide> 'limit' => 20, <ide> public function testMergeOptionsCustomFindKey() <ide> */ <ide> public function testMergeOptionsQueryString() <ide> { <del> $this->request->query = [ <add> $this->controller->request = $this->controller->request->withQueryParams([ <ide> 'page' => 99, <ide> 'limit' => 75 <del> ]; <add> ]); <ide> $settings = [ <ide> 'page' => 1, <ide> 'limit' => 20, <ide> public function testMergeOptionsQueryString() <ide> */ <ide> public function testMergeOptionsDefaultWhiteList() <ide> { <del> $this->request->query = [ <add> $this->controller->request = $this->controller->request->withQueryParams([ <ide> 'page' => 10, <ide> 'limit' => 10, <ide> 'fields' => ['bad.stuff'], <ide> 'recursive' => 1000, <ide> 'conditions' => ['bad.stuff'], <ide> 'contain' => ['bad'] <del> ]; <add> ]); <ide> $settings = [ <ide> 'page' => 1, <ide> 'limit' => 20, <ide> public function testMergeOptionsDefaultWhiteList() <ide> */ <ide> public function testMergeOptionsExtraWhitelist() <ide> { <del> $this->request->query = [ <add> $this->controller->request = $this->controller->request->withQueryParams([ <ide> 'page' => 10, <ide> 'limit' => 10, <ide> 'fields' => ['bad.stuff'], <ide> 'recursive' => 1000, <ide> 'conditions' => ['bad.stuff'], <ide> 'contain' => ['bad'] <del> ]; <add> ]); <ide> $settings = [ <ide> 'page' => 1, <ide> 'limit' => 20, <ide> public function testValidateSortInvalid() <ide> 'scope' => null, <ide> ]); <ide> <del> $this->request->query = [ <add> $this->controller->request = $this->controller->request->withQueryParams([ <ide> 'page' => 1, <ide> 'sort' => 'id', <ide> 'direction' => 'herp' <del> ]; <add> ]); <ide> $this->Paginator->paginate($table); <del> $this->assertEquals('PaginatorPosts.id', $this->request->params['paging']['PaginatorPosts']['sort']); <del> $this->assertEquals('asc', $this->request->params['paging']['PaginatorPosts']['direction']); <add> $this->assertEquals('PaginatorPosts.id', $this->controller->request->getParam('paging.PaginatorPosts.sort')); <add> $this->assertEquals('asc', $this->controller->request->getParam('paging.PaginatorPosts.direction')); <ide> } <ide> <ide> /** <ide> public function testEmptyPaginationResult() <ide> <ide> $this->assertSame( <ide> 0, <del> $this->request->params['paging']['PaginatorPosts']['count'], <add> $this->controller->request->getParam('paging.PaginatorPosts.count'), <ide> 'Count should be 0' <ide> ); <ide> $this->assertSame( <ide> 1, <del> $this->request->params['paging']['PaginatorPosts']['page'], <add> $this->controller->request->getParam('paging.PaginatorPosts.page'), <ide> 'Page number should not be 0' <ide> ); <ide> $this->assertSame( <ide> 1, <del> $this->request->params['paging']['PaginatorPosts']['pageCount'], <add> $this->controller->request->getParam('paging.PaginatorPosts.pageCount'), <ide> 'Page count number should not be 0' <ide> ); <ide> } <ide> public function testEmptyPaginationResult() <ide> public function testOutOfRangePageNumberGetsClamped() <ide> { <ide> $this->loadFixtures('Posts'); <del> $this->request->query['page'] = 3000; <add> $this->controller->request = $this->controller->request->withQueryParams(['page' => 3000]); <ide> <ide> $table = TableRegistry::get('PaginatorPosts'); <ide> <ide> public function testOutOfRangePageNumberGetsClamped() <ide> <ide> $this->assertEquals( <ide> 1, <del> $this->request->params['paging']['PaginatorPosts']['page'], <add> $this->controller->request->getParam('paging.PaginatorPosts.page'), <ide> 'Page number should not be 0' <ide> ); <ide> <ide> public function testOutOfRangePageNumberGetsClamped() <ide> public function testOutOfRangePageNumberStillProvidesPageCount() <ide> { <ide> $this->loadFixtures('Posts'); <del> $this->request->query['limit'] = 1; <del> $this->request->query['page'] = 4; <add> $this->controller->request = $this->controller->request->withQueryParams([ <add> 'limit' => 1, <add> 'page' => '4', <add> ]); <ide> <ide> $table = TableRegistry::get('PaginatorPosts'); <ide> <ide> public function testOutOfRangePageNumberStillProvidesPageCount() <ide> <ide> $this->assertEquals( <ide> 3, <del> $this->request->params['paging']['PaginatorPosts']['pageCount'], <add> $this->controller->request->getParam('paging.PaginatorPosts.pageCount'), <ide> 'Page count number should not be 0' <ide> ); <ide> <ide> public function testOutOfVeryBigPageNumberGetsClamped() <ide> { <ide> $this->expectException(\Cake\Http\Exception\NotFoundException::class); <ide> $this->loadFixtures('Posts'); <del> $this->request->query = [ <add> $this->controller->request = $this->controller->request->withQueryParams([ <ide> 'page' => '3000000000000000000000000', <del> ]; <add> ]); <ide> <ide> $table = TableRegistry::get('PaginatorPosts'); <ide> $this->Paginator->paginate($table); <ide> public function testPaginateMaxLimit() <ide> $settings = [ <ide> 'maxLimit' => 100, <ide> ]; <del> $this->request->query = [ <add> $this->controller->request = $this->controller->request->withQueryParams([ <ide> 'limit' => '1000' <del> ]; <add> ]); <ide> $this->Paginator->paginate($table, $settings); <del> $this->assertEquals(100, $this->request->params['paging']['PaginatorPosts']['limit']); <del> $this->assertEquals(100, $this->request->params['paging']['PaginatorPosts']['perPage']); <add> $this->assertEquals(100, $this->controller->request->getParam('paging.PaginatorPosts.limit')); <add> $this->assertEquals(100, $this->controller->request->getParam('paging.PaginatorPosts.perPage')); <ide> <del> $this->request->query = [ <add> $this->controller->request = $this->controller->request->withQueryParams([ <ide> 'limit' => '10' <del> ]; <add> ]); <ide> $this->Paginator->paginate($table, $settings); <del> $this->assertEquals(10, $this->request->params['paging']['PaginatorPosts']['limit']); <del> $this->assertEquals(10, $this->request->params['paging']['PaginatorPosts']['perPage']); <add> $this->assertEquals(10, $this->controller->request->getParam('paging.PaginatorPosts.limit')); <add> $this->assertEquals(10, $this->controller->request->getParam('paging.PaginatorPosts.perPage')); <ide> } <ide> <ide> /** <ide> public function testPaginateCustomFind() <ide> $this->assertCount(4, $result, '4 rows should come back'); <ide> $this->assertEquals(['First Post', 'Second Post', 'Third Post', 'Fourth Post'], $titleExtractor($result)); <ide> <del> $result = $this->request->params['paging']['PaginatorPosts']; <add> $result = $this->controller->request->getParam('paging.PaginatorPosts'); <ide> $this->assertEquals(4, $result['current']); <ide> $this->assertEquals(4, $result['count']); <ide> <ide> public function testPaginateCustomFind() <ide> $this->assertCount(3, $result, '3 rows should come back'); <ide> $this->assertEquals(['First Post', 'Second Post', 'Third Post'], $titleExtractor($result)); <ide> <del> $result = $this->request->params['paging']['PaginatorPosts']; <add> $result = $this->controller->request->getParam('paging.PaginatorPosts'); <ide> $this->assertEquals(3, $result['current']); <ide> $this->assertEquals(3, $result['count']); <ide> <ide> public function testPaginateCustomFind() <ide> $this->assertCount(1, $result, '1 rows should come back'); <ide> $this->assertEquals(['Third Post'], $titleExtractor($result)); <ide> <del> $result = $this->request->params['paging']['PaginatorPosts']; <add> $result = $this->controller->request->getParam('paging.PaginatorPosts'); <ide> $this->assertEquals(1, $result['current']); <ide> $this->assertEquals(3, $result['count']); <ide> $this->assertEquals(2, $result['pageCount']); <ide> public function testPaginateCustomFind() <ide> $this->assertCount(2, $result, '2 rows should come back'); <ide> $this->assertEquals(['First Post', 'Second Post'], $titleExtractor($result)); <ide> <del> $result = $this->request->params['paging']['PaginatorPosts']; <add> $result = $this->controller->request->getParam('paging.PaginatorPosts'); <ide> $this->assertEquals(2, $result['current']); <ide> $this->assertEquals(3, $result['count']); <ide> $this->assertEquals(2, $result['pageCount']); <ide> public function testPaginateCustomFindFieldsArray() <ide> ]; <ide> $this->assertEquals($expected, $result); <ide> <del> $result = $this->request->params['paging']['PaginatorPosts']; <add> $result = $this->controller->request->getParam('paging.PaginatorPosts'); <ide> $this->assertEquals(2, $result['current']); <ide> $this->assertEquals(3, $result['count']); <ide> $this->assertEquals(2, $result['pageCount']); <ide> public function testPaginateCustomFindCount() <ide> */ <ide> public function testPaginateQuery() <ide> { <del> $this->request->query = ['page' => '-1']; <add> $this->controller->request = $this->controller->request->withQueryParams(['page' => '-1']); <ide> $settings = [ <ide> 'PaginatorPosts' => [ <ide> 'contain' => ['PaginatorAuthor'], <ide> public function testPaginateQueryWithBindValue() <ide> */ <ide> public function testPaginateQueryWithLimit() <ide> { <del> $this->request->query = ['page' => '-1']; <add> $this->controller->request->query = ['page' => '-1']; <ide> $settings = [ <ide> 'PaginatorPosts' => [ <ide> 'contain' => ['PaginatorAuthor'], <ide><path>tests/TestCase/Controller/Component/SecurityComponentTest.php <ide> public function testBlackholeWithBrokenCallback() <ide> $this->expectException(\Cake\Http\Exception\BadRequestException::class); <ide> $request = new ServerRequest([ <ide> 'url' => 'posts/index', <del> 'session' => $this->Security->session <del> ]); <del> $request->addParams([ <del> 'controller' => 'posts', <del> 'action' => 'index' <add> 'session' => $this->Security->session, <add> 'params' => [ <add> 'controller' => 'posts', <add> 'action' => 'index' <add> ] <ide> ]); <ide> $Controller = new \TestApp\Controller\SomePagesController($request); <ide> $event = new Event('Controller.startup', $Controller); <ide> public function testBlackholeWithBrokenCallback() <ide> */ <ide> public function testExceptionWhenActionIsBlackholeCallback() <ide> { <del> $this->Controller->request->addParams([ <del> 'controller' => 'posts', <del> 'action' => 'fail' <del> ]); <add> $this->Controller->request = $this->Controller->request <add> ->withParam('controller', 'posts') <add> ->withParam('action', 'fail'); <add> <ide> $event = new Event('Controller.startup', $this->Controller); <ide> $this->assertFalse($this->Controller->failed); <ide> $this->Controller->Security->startup($event); <ide><path>tests/TestCase/Controller/ControllerTest.php <ide> public function testInvokeActionMissingAction() <ide> { <ide> $this->expectException(\Cake\Controller\Exception\MissingActionException::class); <ide> $this->expectExceptionMessage('Action TestController::missing() could not be found, or is not accessible.'); <del> $url = new ServerRequest('test/missing'); <del> $url->addParams(['controller' => 'Test', 'action' => 'missing']); <add> $url = new ServerRequest([ <add> 'url' => 'test/missing', <add> 'params' => ['controller' => 'Test', 'action' => 'missing'] <add> ]); <ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock(); <ide> <ide> $Controller = new TestController($url, $response); <ide> public function testInvokeActionPrivate() <ide> { <ide> $this->expectException(\Cake\Controller\Exception\MissingActionException::class); <ide> $this->expectExceptionMessage('Action TestController::private_m() could not be found, or is not accessible.'); <del> $url = new ServerRequest('test/private_m/'); <del> $url->addParams(['controller' => 'Test', 'action' => 'private_m']); <add> $url = new ServerRequest([ <add> 'url' => 'test/private_m/', <add> 'params' => ['controller' => 'Test', 'action' => 'private_m'] <add> ]); <ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock(); <ide> <ide> $Controller = new TestController($url, $response); <ide> public function testInvokeActionProtected() <ide> { <ide> $this->expectException(\Cake\Controller\Exception\MissingActionException::class); <ide> $this->expectExceptionMessage('Action TestController::protected_m() could not be found, or is not accessible.'); <del> $url = new ServerRequest('test/protected_m/'); <del> $url->addParams(['controller' => 'Test', 'action' => 'protected_m']); <add> $url = new ServerRequest([ <add> 'url' => 'test/protected_m/', <add> 'params' => ['controller' => 'Test', 'action' => 'protected_m'] <add> ]); <ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock(); <ide> <ide> $Controller = new TestController($url, $response); <ide> public function testInvokeActionBaseMethods() <ide> { <ide> $this->expectException(\Cake\Controller\Exception\MissingActionException::class); <ide> $this->expectExceptionMessage('Action TestController::redirect() could not be found, or is not accessible.'); <del> $url = new ServerRequest('test/redirect/'); <del> $url->addParams(['controller' => 'Test', 'action' => 'redirect']); <add> $url = new ServerRequest([ <add> 'url' => 'test/redirect/', <add> 'params' => ['controller' => 'Test', 'action' => 'redirect'] <add> ]); <ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock(); <ide> <ide> $Controller = new TestController($url, $response); <ide> public function testInvokeActionBaseMethods() <ide> */ <ide> public function testInvokeActionReturnValue() <ide> { <del> $url = new ServerRequest('test/returner/'); <del> $url->addParams([ <del> 'controller' => 'Test', <del> 'action' => 'returner', <del> 'pass' => [] <add> $url = new ServerRequest([ <add> 'url' => 'test/returner/', <add> 'params' => [ <add> 'controller' => 'Test', <add> 'action' => 'returner', <add> 'pass' => [] <add> ] <ide> ]); <ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock(); <ide> <ide> public function testInvokeActionReturnValue() <ide> */ <ide> public function testInvokeActionWithPassedParams() <ide> { <del> $url = new ServerRequest('test/index/1/2'); <del> $url->addParams([ <del> 'controller' => 'Test', <del> 'action' => 'index', <del> 'pass' => ['param1' => '1', 'param2' => '2'] <add> $url = new ServerRequest([ <add> 'url' => 'test/index/1/2', <add> 'params' => [ <add> 'controller' => 'Test', <add> 'action' => 'index', <add> 'pass' => ['param1' => '1', 'param2' => '2'] <add> ] <ide> ]); <ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock(); <ide> <ide> public function testInvokeActionWithPassedParams() <ide> */ <ide> public function testViewPathConventions() <ide> { <del> $request = new ServerRequest('admin/posts'); <del> $request->addParams([ <del> 'prefix' => 'admin' <add> $request = new ServerRequest([ <add> 'url' => 'admin/posts', <add> 'params' => ['prefix' => 'admin'] <ide> ]); <ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock(); <ide> $Controller = new \TestApp\Controller\Admin\PostsController($request, $response); <ide> public function testViewPathConventions() <ide> $Controller->render(); <ide> $this->assertEquals('Admin' . DS . 'Posts', $Controller->viewBuilder()->templatePath()); <ide> <del> $request->addParams([ <del> 'prefix' => 'admin/super' <del> ]); <add> $request = $request->withParam('prefix', 'admin/super'); <ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock(); <ide> $Controller = new \TestApp\Controller\Admin\PostsController($request, $response); <ide> $Controller->getEventManager()->on('Controller.beforeRender', function (Event $e) { <ide> public function testViewPathConventions() <ide> $Controller->render(); <ide> $this->assertEquals('Admin' . DS . 'Super' . DS . 'Posts', $Controller->viewBuilder()->templatePath()); <ide> <del> $request = new ServerRequest('pages/home'); <del> $request->addParams([ <del> 'prefix' => false <add> $request = new ServerRequest([ <add> 'url' => 'pages/home', <add> 'params' => [ <add> 'prefix' => false <add> ] <ide> ]); <ide> $Controller = new \TestApp\Controller\PagesController($request, $response); <ide> $Controller->getEventManager()->on('Controller.beforeRender', function (Event $e) { <ide><path>tests/TestCase/View/Helper/PaginatorHelperTest.php <ide> public function setUp() <ide> Configure::write('Config.language', 'eng'); <ide> $this->View = new View(); <ide> $this->Paginator = new PaginatorHelper($this->View); <del> $this->Paginator->request = new ServerRequest(); <del> $this->Paginator->request->addParams([ <del> 'paging' => [ <del> 'Article' => [ <del> 'page' => 1, <del> 'current' => 9, <del> 'count' => 62, <del> 'prevPage' => false, <del> 'nextPage' => true, <del> 'pageCount' => 7, <del> 'sort' => null, <del> 'direction' => null, <del> 'limit' => null, <add> $this->Paginator->request = new ServerRequest([ <add> 'url' => '/', <add> 'params' => [ <add> 'paging' => [ <add> 'Article' => [ <add> 'page' => 1, <add> 'current' => 9, <add> 'count' => 62, <add> 'prevPage' => false, <add> 'nextPage' => true, <add> 'pageCount' => 7, <add> 'sort' => null, <add> 'direction' => null, <add> 'limit' => null, <add> ] <ide> ] <ide> ] <ide> ]);
9
Javascript
Javascript
add comma to line 319 for readability
212975af9647bfa76011d34df0fe7ee5b0b584d9
<ide><path>src/ng/directive/form.js <ide> function FormController(element, attrs, $scope, $animate, $interpolate) { <ide> * <ide> * # Alias: {@link ng.directive:ngForm `ngForm`} <ide> * <del> * In Angular forms can be nested. This means that the outer form is valid when all of the child <add> * In Angular, forms can be nested. This means that the outer form is valid when all of the child <ide> * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so <ide> * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to <ide> * `<form>` but can be nested. This allows you to have nested forms, which is very useful when
1
Python
Python
add control for psutil 2.0
80051c81d440f0db8e4f880e820473f496f1a8c6
<ide><path>glances/core/glances_globals.py <ide> psutil_version = tuple([int(num) for num in __psutil_version__.split('.')]) <ide> <ide> # Check PsUtil version <del># !!! Move this check outside the globals script <del># !!! PsUtil is not necessary on client side <del># Note: this is not a mistake: psutil 0.5.1 is detected as 0.5.0 <del>if psutil_version < (0, 5, 0): <del> print('PsUtil version %s detected.' % '.'.join(psutil_version)) <del> print('PsUtil 0.5.1 or higher is needed. Glances cannot start.') <add>psutil_min_version = (2, 0, 0) <add>if (psutil_version < psutil_min_version): <add> print('PsUtil version %s detected.' % __psutil_version__) <add> print('PsUtil 2.0 or higher is needed. Glances cannot start.') <ide> sys.exit(1) <ide> <ide> # Path definitions
1
Ruby
Ruby
add assertion to test_simple_valid_formula
91b67bd41d3a6fa04d5dd438b667d9bcb7e414e9
<ide><path>Library/Homebrew/test/test_cmd_audit.rb <ide> def test_simple_valid_formula <ide> assert ft =~ /\burl\b/, "The formula should match 'url'" <ide> assert_nil ft.line_number(/desc/), "The formula should not match 'desc'" <ide> assert_equal 2, ft.line_number(/\burl\b/) <add> assert ft.include?("Valid"), "The formula should include \"Valid\"" <ide> end <ide> <ide> def test_trailing_newline
1
Java
Java
remove unnecessary boxing
c5278aa359a1847b8df89da21b01dd48aa097d53
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/standard/Tokenizer.java <ide> /* <del> * Copyright 2002-2017 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> else if (isTwoCharToken(TokenKind.SAFE_NAVI)) { <ide> raiseParseException(this.pos, SpelMessage.UNEXPECTED_ESCAPE_CHAR); <ide> break; <ide> default: <del> throw new IllegalStateException("Cannot handle (" + Integer.valueOf(ch) + ") '" + ch + "'"); <add> throw new IllegalStateException("Cannot handle ('" + ch + "')"); <ide> } <ide> } <ide> }
1
Javascript
Javascript
fix bug which got introduced by accident
47ec2187776658ad9ee2a9c71a28ddb860bec43a
<ide><path>src/Compiler.js <ide> Compiler.prototype = { <ide> // process markup for text nodes only <ide> eachTextNode(element, function(textNode){ <ide> var text = textNode.text(); <del> foreach(self.textMarkup, function(markup, name){ <add> foreach(self.textMarkup, function(markup){ <ide> markup.call(selfApi, text, textNode, element); <ide> }); <ide> }); <ide> } <ide> <ide> if (directives) { <ide> // Process attributes/directives <del> eachAttribute(element, function(value){ <add> eachAttribute(element, function(value, name){ <ide> foreach(self.attrMarkup, function(markup){ <ide> markup.call(selfApi, value, name, element); <ide> });
1
Ruby
Ruby
fix homebrew_cccfg reference
4fe0adf587d8f9cc751fd991ab3370fe3ce9d49a
<ide><path>Library/Homebrew/extend/ENV/shared.rb <ide> def remove_from_cflags(val) <ide> end <ide> <ide> def append_to_cccfg(value) <del> append(HOMEBREW_CCCFG, value, "") <add> append("HOMEBREW_CCCFG", value, "") <ide> end <ide> <ide> def append(keys, value, separator = " ")
1
Java
Java
fix removal of reactshadownode
5347ecfd296cdc882c7c198e6489f7482f27a073
<ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/FabricReconciler.java <ide> private void manageChildren( <ide> indicesToRemove[indicesToRemoveIndex++] = j; <ide> if (!addedTags.contains(nodeToRemove.getReactTag())) { <ide> tagsToDelete.add(nodeToRemove.getReactTag()); <add> // TODO: T26729293 since we are not cloning ReactShadowNode's we need to "manually" remove <add> // from the ReactShadowTree when one of the nodes is deleted in JS. <add> nodeToRemove.getParent().removeChildAt(j); <ide> } <ide> } <ide>
1
Ruby
Ruby
restore sorting of formulae
97e05ae4106bc7315233d9d35f8d02e913378b1a
<ide><path>Library/Homebrew/cmd/outdated.rb <ide> def outdated_formulae_casks(args:) <ide> casks = Cask::Caskroom.casks <ide> end <ide> <del> [select_outdated(formulae, args: args), select_outdated(casks, args: args)] <add> [select_outdated(formulae, args: args).sort, select_outdated(casks, args: args)] <ide> end <ide> <ide> def select_outdated(formulae_or_casks, args:)
1
PHP
PHP
update doc blocks for cakenumber
3c9e79737d8d3f5311d11f128337e3d917a35306
<ide><path>lib/Cake/Utility/CakeNumber.php <ide> protected static function _numberFormat($number, $places = 0, $decimals = '.', $ <ide> * <ide> * ### Options <ide> * <del> * - `before` - The currency symbol to place before whole numbers ie. '$' <del> * - `after` - The currency symbol to place after decimal numbers ie. 'c'. Set to boolean false to <del> * use no decimal symbol. eg. 0.35 => $0.35. <del> * - `zero` - The text to use for zero values, can be a string or a number. ie. 0, 'Free!' <add> * - `wholeSymbol` - The currency symbol to use for whole numbers, <add> * greater than 1, or less than -1. <add> * - `wholePosition` - The position the whole symbol should be placed <add> * valid options are 'before' & 'after'. <add> * - `fractionSymbol` - The currency symbol to use for fractional numbers. <add> * - `fractionPosition` - The position the fraction symbol should be placed <add> * valid options are 'before' & 'after'. <add> * - `before` - The currency symbol to place before whole numbers <add> * ie. '$'. `before` is an alias for `wholeSymbol`. <add> * - `after` - The currency symbol to place after decimal numbers <add> * ie. 'c'. Set to boolean false to use no decimal symbol. <add> * eg. 0.35 => $0.35. `after` is an alias for `fractionSymbol` <add> * - `zero` - The text to use for zero values, can be a <add> * string or a number. ie. 0, 'Free!' <ide> * - `places` - Number of decimal places to use. ie. 2 <ide> * - `thousands` - Thousands separator ie. ',' <ide> * - `decimals` - Decimal separator symbol ie. '.' <del> * - `negative` - Symbol for negative numbers. If equal to '()', the number will be wrapped with ( and ) <add> * - `negative` - Symbol for negative numbers. If equal to '()', <add> * the number will be wrapped with ( and ) <ide> * - `escape` - Should the output be htmlentity escaped? Defaults to true <ide> * <ide> * @param float $number <del> * @param string $currency Shortcut to default options. Valid values are 'USD', 'EUR', 'GBP', otherwise <del> * set at least 'before' and 'after' options. <add> * @param string $currency Shortcut to default options. Valid values are <add> * 'USD', 'EUR', 'GBP', otherwise set at least 'before' and 'after' options. <ide> * @param array $options <ide> * @return string Number formatted as a currency. <ide> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::currency <ide> public static function currency($number, $currency = 'USD', $options = array()) <ide> * <ide> * {{{ $number->currency($value, 'NOK'); }}} <ide> * <del> * Added formats are merged with the following defaults. <del> * <del> * {{{ <del> * array( <del> * 'before' => '$', 'after' => 'c', 'zero' => 0, 'places' => 2, 'thousands' => ',', <del> * 'decimals' => '.', 'negative' => '()', 'escape' => true <del> * ) <del> * }}} <add> * Added formats are merged with the defaults defined in CakeNumber::$_currencyDefaults <add> * See CakeNumber::currency() for more information on the various options and their function. <ide> * <ide> * @param string $formatName The format name to be used in the future. <ide> * @param array $options The array of options for this format.
1
Java
Java
handle absolute uri in reactor request.uri()
203370a810fad77d33c3484dbf9e79242583bf5b
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ReactorServerHttpRequest.java <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.LinkedMultiValueMap; <ide> import org.springframework.util.MultiValueMap; <add>import org.springframework.util.StringUtils; <ide> <ide> /** <ide> * Adapt {@link ServerHttpRequest} to the Reactor {@link HttpServerRequest}. <ide> public ReactorServerHttpRequest(HttpServerRequest request, NettyDataBufferFactor <ide> <ide> private static URI initUri(HttpServerRequest request) throws URISyntaxException { <ide> Assert.notNull(request, "'request' must not be null"); <del> return new URI(resolveBaseUrl(request).toString() + request.uri()); <add> return new URI(resolveBaseUrl(request).toString() + resolveRequestUri(request)); <ide> } <ide> <ide> private static URI resolveBaseUrl(HttpServerRequest request) throws URISyntaxException { <ide> private static String getScheme(HttpServerRequest request) { <ide> return ssl ? "https" : "http"; <ide> } <ide> <add> private static String resolveRequestUri(HttpServerRequest request) { <add> String uri = request.uri(); <add> for (int i = 0; i < uri.length(); i++) { <add> char c = uri.charAt(i); <add> if (c == '/' || c == '?' || c == '#') { <add> break; <add> } <add> if (c == ':' && (i + 2 < uri.length())) { <add> if (uri.charAt(i + 1) == '/' && uri.charAt(i + 2) == '/') { <add> for (int j = i + 3; j < uri.length(); j++) { <add> c = uri.charAt(j); <add> if (c == '/' || c == '?' || c == '#') { <add> return uri.substring(j); <add> } <add> } <add> return ""; <add> } <add> } <add> } <add> return uri; <add> } <add> <ide> private static HttpHeaders initHeaders(HttpServerRequest channel) { <ide> HttpHeaders headers = new HttpHeaders(); <ide> for (String name : channel.requestHeaders().names()) {
1
Text
Text
add 3 new sections to faq.md
09352ad3c2b38609da6d7be5873f40ed6d0e45a0
<ide><path>docs/FAQ.md <ide> <ide> Read our ["How to Contribute to Open Source Guide"](https://github.com/freeCodeCamp/how-to-contribute-to-open-source). It's a comprehensive reference for first-timer-friendly projects. And it includes a lot of open source contribution tips. <ide> <add>### What do I need to know to contribute to the codebase? <add> <add>freeCodeCamp runs on a modern JavaScript stack. If you're interested in contributing to our codebase, you will need some familiarity with JavaScript and some of the technologies we use like Node.js, MongoDB, OAuth 2.0, React, Gatsby, and Webpack. <add> <ide> ### Can I translate freeCodeCamp's resources? <ide> <ide> Yes - You can contribute to any of the 30+ languages we have enabled on our translation platform. <ide> We have user-contributed translations live in some languages. We intend to local <ide> <ide> If you are interested in contributing to translations please makes sure you [read this guide](how-to-translate-files.md) first. <ide> <add>### Can I contribute articles to freeCodeCamp News or videos to freeCodeCamp's YouTube channel? <add> <add>Yes - you can contribute to our publication blog and YouTube channel. <add> <add>If you're interested in writing articles for freeCodeCamp News, please visit this [publication guide](https://www.freecodecamp.org/news/how-to-write-for-freecodecamp/). In addition, please read our [style guide](https://www.freecodecamp.org/news/developer-news-style-guide/) as this will help you write stronger and more effective articles. <add> <add>To help us make educational videos for our YouTube channel, you can follow the [YouTube channel guide here](https://www.freecodecamp.org/news/how-to-contribute-to-the-freecodecamp-community-youtube-channel-b86bce4c865/). <add> <ide> ### How can I report a new bug? <ide> <ide> If you think you've found a bug, first read the ["Help I've Found a Bug"](https://forum.freecodecamp.org/t/how-to-report-a-bug/19543) article and follow its instructions.
1
Python
Python
fix typo in glue test example code
45b4d35a0cb916c3d7072c00876ba6cdafb3bcbf
<ide><path>tests/system/providers/amazon/aws/example_glue.py <ide> def glue_cleanup(crawler_name: str, job_name: str, db_name: str) -> None: <ide> # [END howto_operator_glue] <ide> <ide> # GlueJobOperator waits by default, setting as False to test the Sensor below. <del> submit_glue_job.wait_for_completion - False <add> submit_glue_job.wait_for_completion = False <ide> <ide> # [START howto_sensor_glue] <ide> wait_for_job = GlueJobSensor(
1
Text
Text
update korean translation to e88c7bf
28261783eda1562cc469684214ea43b053af516a
<ide><path>docs/docs/10.1-animation.ko-KR.md <ide> var TodoList = React.createClass({ <ide> > <ide> > `transitionAppear` prop은 버전 `0.13`에서 `ReactCSSTransitionGroup`에 추가되었습니다. 하위 호환성을 생각해서, 기본 값은 `false`로 설정되어 있습니다. <ide> <add>### 커스텀 클래스 <add> <add>트렌지션의 각 단계에서 커스텀 클래스 이름을 사용할 수도 있습니다. transitionName에 문자열을 넘기는 대신 `enter`, `leave` 같은 클래스 이름의 객체나 `enter`, `enter-active`, `leave-active`, `leave`같은 클래스 이름의 객체를 넘길 수 있습니다. enter, leave 클래스만 있다면, enter-active, leave-active 클래스는 클래스 이름 뒤에 '-active'를 붙여서 정할 수 있습니다. 커스텀 클래스를 사용한 예제입니다. <add> <add>```javascript <add> ... <add> <ReactCSSTransitionGroup <add> transitionName={ <add> enter: 'enter', <add> enterActive: 'enterActive', <add> leave: 'leave', <add> leaveActive: 'leaveActive', <add> appear: 'appear', <add> appearActive: 'appearActive' <add> }> <add> {item} <add> </ReactCSSTransitionGroup> <add> <add> <ReactCSSTransitionGroup <add> transitionName={ <add> enter: 'enter', <add> leave: 'leave', <add> appear: 'appear' <add> }> <add> {item2} <add> </ReactCSSTransitionGroup> <add> ... <add>``` <add> <ide> ### 애니메이션 그룹이 작동하려면 마운트가 필요 <ide> <ide> 자식들에게 트랜지션을 적용하려면 `ReactCSSTransitionGroup`은 이미 DOM에 마운트되어 있거나 prop `transitionAppear`가 `true`로 설정되어야만 합니다. 예를 들어, 밑의 코드는 동작하지 않을 것입니다. 왜냐하면 `ReactCSSTransitionGroup` 안에서 새 아이템을 마운트하는 대신 새 아이템과 같이 `ReactCSSTransitionGroup`를 마운트했기 때문입니다. 이 것을 위에 있는 [시작하기](#getting-stared) 항목과 비교해보세요. <ide><path>docs/docs/ref-01-top-level-api.ko-KR.md <ide> ReactComponent render( <ide> <ide> > 주의: <ide> > <del>> `React.render()`는 넘어온 컨테이너 노드의 내용을 교체합니다. <del>> 추후에 기존 자식들을 덮어쓰지 않고 이미 있는 DOM 노드에 컴포넌트를 삽입하는 것도 지원할 가능성이 있습니다. <add>> `React.render()`는 넘어온 컨테이너 노드의 내용을 교체합니다. 안에 있는 DOM 엘리먼트는 첫 호출을 할 때 교체됩니다. 그 후의 호출에는 효율석으로 업데이트하기 위해 React의 DOM diff 알고리즘을 사용합니다. <add>> <add>> `React.render()`는 컨테이너 노드를 수정하지 않습니다. (컨테이너의 자식만 수정함) 추후에 기존 자식들을 덮어쓰지 않고 이미 있는 DOM 노드에 컴포넌트를 삽입하는 것도 지원할 가능성이 있습니다. <ide> <ide> <ide> ### React.unmountComponentAtNode <ide><path>docs/docs/ref-05-events.ko-KR.md <ide> number eventPhase <ide> boolean isTrusted <ide> DOMEvent nativeEvent <ide> void preventDefault() <add>void isDefaultPrevented() <ide> void stopPropagation() <add>void isPropagationStopped() <ide> DOMEventTarget target <ide> number timeStamp <ide> string type <ide> Number deltaX <ide> Number deltaY <ide> Number deltaZ <ide> ``` <add> <add>### 미디어 이벤트 <add> <add>이벤트 이름: <add> <add>``` <add>onAbort onCanPlay onCanPlayThrough onDurationChange onEmptied onEncrypted onEnded onError onLoadedData onLoadedMetadata onLoadStart onPause onPlay onPlaying onProgress onRateChange onSeeked onSeeking onStalled onSuspend onTimeUpdate onVolumeChange onWaiting <add>``` <ide><path>docs/tips/06-style-props-value-px.ko-KR.md <ide> React.render(<div style={divStyle}>Hello World!</div>, mountNode); <ide> <ide> - `boxFlex` <ide> - `boxFlexGroup` <add>- `boxOrdinalGroup` <ide> - `columnCount` <ide> - `fillOpacity` <ide> - `flex` <ide> - `flexGrow` <ide> - `flexPositive` <ide> - `flexShrink` <ide> - `flexNegative` <add>- `flexOrder` <ide> - `fontWeight` <ide> - `lineClamp` <ide> - `lineHeight`
4
Text
Text
add more details to invalid-next-config doc
8b4d9e652e435c1cf8864ebde587c60f615b83e1
<ide><path>errors/invalid-next-config.md <ide> <ide> #### Why This Error Occurred <ide> <del>In your `next.config.js` file you passed invalid options that either are the incorrect type or an unknown field. <add>In your `next.config.js` file you passed invalid options that either are the incorrect type or an unknown field. This warning is shown to help catch typos that cause expected configs to not be applied. <ide> <ide> #### Possible Ways to Fix It <ide> <ide> const nextConfig = { <ide> module.exports = nextConfig <ide> ``` <ide> <add>For example for the below warning, there is a typo and `rewritess` needs to be renamed to `rewrites` to resolve the issue. <add> <add>```sh <add>The root value has an unexpected property, rewritess, which is not in the list of allowed properties <add>``` <add> <ide> ### Useful Links <ide> <ide> - [`next.config.js`](https://nextjs.org/docs/api-reference/next.config.js/introduction)
1
Text
Text
add v3.8.1 to changelog
aede427fb866a6364caba37f88b5b8bfafdfa113
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v3.8.1 (April 02, 2019) <add> <add>- [#17684](https://github.com/emberjs/ember.js/pull/17684) [BUGFIX] Enable maximum rerendering limit to be customized. <add>- [#17823](https://github.com/emberjs/ember.js/pull/17823) Update router_js to 6.2.4 <add> <ide> ### v3.9.0 (April 01, 2019) <ide> <ide> - [#17470](https://github.com/emberjs/ember.js/pull/17470) [DEPRECATION] Implements the Computed Property Modifier deprecation RFCs
1
Python
Python
improve accuracy of numpy.gradient at edges
332d628744a0670234585053dbe32a3e82e0c4db
<ide><path>numpy/lib/function_base.py <ide> def gradient(f, *varargs): <ide> """ <ide> Return the gradient of an N-dimensional array. <ide> <del> The gradient is computed using central differences in the interior <del> and first differences at the boundaries. The returned gradient hence has <del> the same shape as the input array. <add> The gradient is computed using second order accurate central differences <add> in the interior and second order accurate one-sides (forward or backwards) <add> differences at the boundaries. The returned gradient hence has the same <add> shape as the input array. <ide> <ide> Parameters <ide> ---------- <ide> def gradient(f, *varargs): <ide> 0, 1, or N scalars specifying the sample distances in each direction, <ide> that is: `dx`, `dy`, `dz`, ... The default distance is 1. <ide> <del> <ide> Returns <ide> ------- <ide> gradient : ndarray <ide> def gradient(f, *varargs): <ide> array([[ 1. , 2.5, 4. ], <ide> [ 1. , 1. , 1. ]])] <ide> <add> >>> x = np.array([0,1,2,3,4]) <add> >>> dx = gradient(x) <add> >>> y = x**2 <add> >>> gradient(y,dx) <add> array([0., 2., 4., 6., 8.]) <ide> """ <ide> f = np.asanyarray(f) <ide> N = len(f.shape) # number of dimensions <ide> def gradient(f, *varargs): <ide> raise SyntaxError( <ide> "invalid number of arguments") <ide> <del> # use central differences on interior and first differences on endpoints <add> # use central differences on interior and one-sided differences on the <add> # endpoints. This preserves second order-accuracy over the full domain. <ide> <ide> outvals = [] <ide> <ide> # create slice objects --- initially all are [:, :, ..., :] <ide> slice1 = [slice(None)]*N <ide> slice2 = [slice(None)]*N <ide> slice3 = [slice(None)]*N <add> slice4 = [slice(None)]*N <ide> <ide> otype = f.dtype.char <ide> if otype not in ['f', 'd', 'F', 'D', 'm', 'M']: <ide> def gradient(f, *varargs): <ide> # Needs to keep the specific units, can't be a general unit <ide> otype = f.dtype <ide> <add> # Convert datetime64 data into ints. Make dummy variable `y` <add> # that is a view of ints if the data is datetime64, otherwise <add> # just set y equal to the the array `f`. <add> if f.dtype.char in ["M", "m"]: <add> y = f.view('int64') <add> else: <add> y = f <add> <ide> for axis in range(N): <del> # select out appropriate parts for this dimension <del> out = np.empty_like(f, dtype=otype) <del> slice1[axis] = slice(1, -1) <del> slice2[axis] = slice(2, None) <del> slice3[axis] = slice(None, -2) <del> # 1D equivalent -- out[1:-1] = (f[2:] - f[:-2])/2.0 <del> out[slice1] = (f[slice2] - f[slice3])/2.0 <del> slice1[axis] = 0 <del> slice2[axis] = 1 <del> slice3[axis] = 0 <del> # 1D equivalent -- out[0] = (f[1] - f[0]) <del> out[slice1] = (f[slice2] - f[slice3]) <del> slice1[axis] = -1 <del> slice2[axis] = -1 <del> slice3[axis] = -2 <del> # 1D equivalent -- out[-1] = (f[-1] - f[-2]) <del> out[slice1] = (f[slice2] - f[slice3]) <add> <add> if y.shape[axis] < 2: <add> raise ValueError("Shape of array too small to calculate a numerical gradient, at least two elements are required.") <add> <add> # Numerical differentiation: 1st order edges, 2nd order interior <add> if y.shape[axis] == 2: <add> # Use first order differences for time data <add> out = np.empty_like(y, dtype=otype) <add> <add> slice1[axis] = slice(1, -1) <add> slice2[axis] = slice(2, None) <add> slice3[axis] = slice(None, -2) <add> # 1D equivalent -- out[1:-1] = (y[2:] - y[:-2])/2.0 <add> out[slice1] = (y[slice2] - y[slice3])/2.0 <add> <add> slice1[axis] = 0 <add> slice2[axis] = 1 <add> slice3[axis] = 0 <add> # 1D equivalent -- out[0] = (y[1] - y[0]) <add> out[slice1] = (y[slice2] - y[slice3]) <add> <add> slice1[axis] = -1 <add> slice2[axis] = -1 <add> slice3[axis] = -2 <add> # 1D equivalent -- out[-1] = (y[-1] - y[-2]) <add> out[slice1] = (y[slice2] - y[slice3]) <add> <add> # Numerical differentiation: 2st order edges, 2nd order interior <add> else: <add> # Use second order differences where possible <add> out = np.empty_like(y, dtype=otype) <add> <add> slice1[axis] = slice(1, -1) <add> slice2[axis] = slice(2, None) <add> slice3[axis] = slice(None, -2) <add> # 1D equivalent -- out[1:-1] = (y[2:] - y[:-2])/2.0 <add> out[slice1] = (y[slice2] - y[slice3])/2.0 <add> <add> slice1[axis] = 0 <add> slice2[axis] = 0 <add> slice3[axis] = 1 <add> slice4[axis] = 2 <add> # 1D equivalent -- out[0] = -(3*y[0] - 4*y[1] + y[2]) / 2.0 <add> out[slice1] = -(3.0*y[slice2] - 4.0*y[slice3] + y[slice4])/2.0 <add> <add> slice1[axis] = -1 <add> slice2[axis] = -1 <add> slice3[axis] = -2 <add> slice4[axis] = -3 <add> # 1D equivalent -- out[-1] = (3*y[-1] - 4*y[-2] + y[-3]) <add> out[slice1] = (3.0*y[slice2] - 4.0*y[slice3] + y[slice4])/2.0 <ide> <ide> # divide by step size <ide> outvals.append(out / dx[axis]) <ide> def gradient(f, *varargs): <ide> slice1[axis] = slice(None) <ide> slice2[axis] = slice(None) <ide> slice3[axis] = slice(None) <add> slice4[axis] = slice(None) <ide> <ide> if N == 1: <ide> return outvals[0] <ide> else: <ide> return outvals <ide> <del> <ide> def diff(a, n=1, axis=-1): <ide> """ <ide> Calculate the n-th order discrete difference along given axis. <ide><path>numpy/lib/tests/test_function_base.py <ide> def test_datetime64(self): <ide> '1910-10-12', '1910-12-12', '1912-12-12'], <ide> dtype='datetime64[D]') <ide> dx = np.array( <del> [-5, -3, 0, 31, 61, 396, 731], <add> [-7, -3, 0, 31, 61, 396, 1066], <ide> dtype='timedelta64[D]') <ide> assert_array_equal(gradient(x), dx) <ide> assert_(dx.dtype == np.dtype('timedelta64[D]')) <ide> def test_timedelta64(self): <ide> [-5, -3, 10, 12, 61, 321, 300], <ide> dtype='timedelta64[D]') <ide> dx = np.array( <del> [2, 7, 7, 25, 154, 119, -21], <add> [-3, 7, 7, 25, 154, 119, -161], <ide> dtype='timedelta64[D]') <ide> assert_array_equal(gradient(x), dx) <ide> assert_(dx.dtype == np.dtype('timedelta64[D]')) <ide> <add> def test_second_order_accurate(self): <add> # Testing that the relative numerical error is less that 3% for <add> # this example problem. This corresponds to second order <add> # accurate finite differences for all interior and boundary <add> # points. <add> x = np.linspace(0, 1, 10) <add> dx = x[1] - x[0] <add> y = 2 * x ** 3 + 4 * x ** 2 + 2 * x <add> analytical = 6 * x ** 2 + 8 * x + 2 <add> num_error = np.abs((np.gradient(y, dx) / analytical) - 1) <add> assert_(np.all(num_error < 0.03) == True) <add> <ide> <ide> class TestAngle(TestCase): <ide> def test_basic(self):
2
Ruby
Ruby
use erb to generate formula template
a56466a4d34b14214f829717d98115574c81913d
<ide><path>Library/Homebrew/brew.h.rb <ide> def check_for_blacklisted_formula names <ide> def __make url, name <ide> require 'formula' <ide> require 'digest' <add> require 'erb' <ide> <del> path = Formula.path name <add> path = Formula.path(name) <ide> raise "#{path} already exists" if path.exist? <ide> <ide> if Formula.aliases.include? name and not ARGV.force? <ide> def __make url, name <ide> EOS <ide> end <ide> <add> if ARGV.include? '--cmake' <add> mode = :cmake <add> elsif ARGV.include? '--autotools' <add> mode = :autotools <add> else <add> mode = nil <add> end <add> <ide> version = Pathname.new(url).version <del> if version == nil <add> if version.nil? <ide> opoo "Version cannot be determined from URL." <ide> puts "You'll need to add an explicit 'version' to the formula." <ide> else <ide> def __make url, name <ide> end <ide> end <ide> <del> template=<<-EOS <del> require 'formula' <add> formula_template = <<-EOS <add>require 'formula' <ide> <del> class #{Formula.class_s name} <Formula <del> url '#{url}' <del> homepage '' <del> md5 '#{md5}' <add>class #{Formula.class_s name} <Formula <add> url '#{url}' <add> homepage '' <add> md5 '#{md5}' <ide> <del> cmake depends_on 'cmake' <del> <del> def install <del> autotools system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=\#{prefix}" <del> cmake system "cmake . \#{std_cmake_parameters}" <del> system "make install" <del> end <del> end <del> EOS <del> <del> mode=nil <del> if ARGV.include? '--cmake' <del> mode= :cmake <del> elsif ARGV.include? '--autotools' <del> mode= :autotools <del> end <add><% if mode == :cmake %> <add> depends_on 'cmake' <add><% elsif mode == nil %> <add> # depends_on 'cmake' <add><% end %> <ide> <del> f=File.new path, 'w' <del> template.each_line do |s| <del> if s.strip.empty? <del> f.puts <del> next <del> end <del> cmd=s[0..11].strip <del> if cmd.empty? <del> cmd=nil <del> else <del> cmd=cmd.to_sym <del> end <del> out=s[12..-1] || '' <del> <del> if mode.nil? <del> # we show both but comment out cmake as it is less common <del> # the implication being the pacakger should remove whichever is not needed <del> if cmd == :cmake and not out.empty? <del> f.print '#' <del> out = out[1..-1] <del> end <del> elsif cmd != mode and not cmd.nil? <del> next <del> end <del> f.puts out <add> def install <add> <% if mode == :cmake %> <add> system "cmake . \#{std_cmake_parameters}" <add> <% elsif mode == :autotools %> <add> system "./configure", "--prefix=\#{prefix}", "--disable-debug", "--disable-dependency-tracking" <add> <% else %> <add> system "./configure", "--prefix=\#{prefix}", "--disable-debug", "--disable-dependency-tracking" <add> # system "cmake . \#{std_cmake_parameters}" <add> <% end %> <add> system "make install" <ide> end <del> f.close <add>end <add> EOS <ide> <add> path.write(ERB.new(formula_template, nil, '>').result(binding)) <ide> return path <ide> end <ide>
1
Javascript
Javascript
avoid font lookup by id in showtext
f6eb9cecd39a85db6a3da574a13bef512e97767b
<ide><path>fonts.js <ide> function getUnicodeRangeFor(value) { <ide> var Font = (function() { <ide> var constructor = function font_constructor(name, file, properties) { <ide> this.name = name; <add> this.textMatrix = properties.textMatrix || IDENTITY_MATRIX; <ide> this.encoding = properties.encoding; <ide> <ide> // If the font is to be ignored, register it like an already loaded font <ide><path>pdf.js <ide> var CanvasGraphics = (function() { <ide> showText: function(text) { <ide> // TODO: apply charSpacing, wordSpacing, textHScale <ide> <del> this.ctx.save(); <del> this.ctx.transform.apply(this.ctx, this.current.textMatrix); <del> this.ctx.scale(1, -1); <add> var ctx = this.ctx; <add> var current = this.current; <add> <add> ctx.save(); <add> ctx.transform.apply(ctx, current.textMatrix); <add> ctx.scale(1, -1); <ide> <ide> if (this.ctx.$showText) { <del> this.ctx.$showText(this.current.y, Fonts.charsToUnicode(text)); <add> ctx.$showText(current.y, Fonts.charsToUnicode(text)); <ide> } else { <ide> text = Fonts.charsToUnicode(text); <del> this.ctx.translate(this.current.x, -1 * this.current.y); <add> ctx.translate(this.current.x, -1 * this.current.y); <ide> <ide> var font = this.current.font; <del> if (font) { <del> var fontInfo = Fonts.lookupById(font.id); <del> if (fontInfo && fontInfo.properties.textMatrix) <del> this.ctx.transform.apply(this.ctx, fontInfo.properties.textMatrix); <del> } <del> this.ctx.fillText(text, 0, 0); <del> this.current.x += Fonts.measureText(text); <add> if (font) <add> ctx.transform.apply(ctx, font.textMatrix); <add> ctx.fillText(text, 0, 0); <add> current.x += Fonts.measureText(text); <ide> } <ide> <ide> this.ctx.restore();
2
PHP
PHP
refactor the arr class to fix a few bugs
81a89604f98a90aa8fe736c0192048f55eeaf6d4
<ide><path>system/arr.php <ide> public static function get($array, $key, $default = null) <ide> */ <ide> public static function set(&$array, $key, $value) <ide> { <add> if (is_null($key)) return $array = $value; <add> <ide> $keys = explode('.', $key); <ide> <ide> while (count($keys) > 1)
1
Python
Python
fix missing output in refguide-check
c6c56447af69766dee562e66494e61981d4e6955
<ide><path>tools/refguide_check.py <ide> def temp_cwd(): <ide> success = False <ide> ns = t.globs <ide> <add> output.seek(0) <ide> return success, output.read() <ide> <ide>
1
PHP
PHP
get month() working with the new widget class
96560ea44384f6b0c81394d2b11d864b8dd3738d
<ide><path>src/View/Helper/FormHelper.php <ide> public function day($fieldName = null, $options = []) { <ide> ); <ide> $options = $off + $options; <ide> <add> if (isset($options['value'])) { <add> $options['val'] = $options['value']; <add> } <add> <ide> // If value is an integer reformat it. <del> if (isset($options['value']) && $options['value'] > 0 && $options['value'] < 31) { <del> $options['value'] = [ <add> if (isset($options['val']) && $options['val'] > 0 && $options['val'] <= 31) { <add> $options['val'] = [ <ide> 'year' => date('Y'), <ide> 'month' => date('m'), <del> 'day' => (int)$options['value'] <add> 'day' => (int)$options['val'] <ide> ]; <ide> } <ide> return $this->datetime($fieldName, $options); <ide> public function year($fieldName, $minYear = null, $maxYear = null, $attributes = <ide> /** <ide> * Returns a SELECT element for months. <ide> * <del> * ### Attributes: <add> * ### Options: <ide> * <ide> * - `monthNames` - If false, 2 digit numbers will be used instead of text. <ide> * If a array, the given array will be used. <ide> public function year($fieldName, $minYear = null, $maxYear = null, $attributes = <ide> * - `value` The selected value of the input. <ide> * <ide> * @param string $fieldName Prefix name for the SELECT element <del> * @param array $attributes Attributes for the select element <add> * @param array $options Attributes for the select element <ide> * @return string A generated month select dropdown. <ide> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::month <ide> */ <del> public function month($fieldName, $attributes = array()) { <del> $attributes += array('empty' => true, 'value' => null); <del> $attributes = $this->_dateTimeSelected('month', $fieldName, $attributes); <add> public function month($fieldName, $options = array()) { <add> $off = array_diff($this->_datetimeParts, ['month']); <add> $off = array_combine( <add> $off, <add> array_fill(0, count($off), false) <add> ); <add> $options = $off + $options; <ide> <del> if (strlen($attributes['value']) > 2) { <del> $date = date_create($attributes['value']); <del> $attributes['value'] = null; <del> if ($date) { <del> $attributes['value'] = $date->format('m'); <del> } <del> } elseif ($attributes['value'] === false) { <del> $attributes['value'] = null; <add> if (isset($options['value'])) { <add> $options['val'] = $options['value']; <ide> } <del> $defaults = array('monthNames' => true); <del> $attributes = array_merge($defaults, (array)$attributes); <del> $monthNames = $attributes['monthNames']; <del> unset($attributes['monthNames']); <ide> <del> return $this->select( <del> $fieldName . ".month", <del> $this->_generateOptions('month', array('monthNames' => $monthNames)), <del> $attributes <del> ); <add> if (isset($options['val']) && $options['val'] > 0 && $options['val'] <= 12) { <add> $options['val'] = [ <add> 'year' => date('Y'), <add> 'month' => (int)$options['val'], <add> 'day' => date('d') <add> ]; <add> } <add> return $this->datetime($fieldName, $options); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> public function testDateTimeLabelIdMatchesFirstInput() { <ide> * @return void <ide> */ <ide> public function testMonth() { <del> $result = $this->Form->month('Model.field'); <add> $result = $this->Form->month('Model.field', ['value' => '']); <ide> $expected = array( <ide> array('select' => array('name' => 'Model[field][month]')), <del> array('option' => array('value' => '')), <add> array('option' => array('value' => '', 'selected' => 'selected')), <ide> '/option', <ide> array('option' => array('value' => '01')), <ide> date('F', strtotime('2008-01-01 00:00:00')), <ide> public function testMonth() { <ide> ); <ide> $this->assertTags($result, $expected); <ide> <del> $result = $this->Form->month('Model.field', array('empty' => true)); <add> $result = $this->Form->month('Model.field', ['empty' => true, 'value' => '']); <ide> $expected = array( <ide> array('select' => array('name' => 'Model[field][month]')), <del> array('option' => array('value' => '')), <add> array('option' => array('selected' => 'selected', 'value' => '')), <ide> '/option', <ide> array('option' => array('value' => '01')), <ide> date('F', strtotime('2008-01-01 00:00:00')), <ide> public function testMonth() { <ide> ); <ide> $this->assertTags($result, $expected); <ide> <del> $result = $this->Form->month('Model.field', array('monthNames' => false)); <add> $result = $this->Form->month('Model.field', ['value' => '', 'monthNames' => false]); <ide> $expected = array( <ide> array('select' => array('name' => 'Model[field][month]')), <del> array('option' => array('value' => '')), <add> array('option' => array('selected' => 'selected', 'value' => '')), <ide> '/option', <ide> array('option' => array('value' => '01')), <del> '01', <add> '1', <ide> '/option', <ide> array('option' => array('value' => '02')), <del> '02', <add> '2', <ide> '/option', <ide> '*/select', <ide> ); <ide> $this->assertTags($result, $expected); <ide> <del> $monthNames = array( <add> $monthNames = [ <ide> '01' => 'Jan', '02' => 'Feb', '03' => 'Mar', '04' => 'Apr', '05' => 'May', '06' => 'Jun', <del> '07' => 'Jul', '08' => 'Aug', '09' => 'Sep', '10' => 'Oct', '11' => 'Nov', '12' => 'Dec'); <del> $result = $this->Form->month('Model.field', array('monthNames' => $monthNames)); <add> '07' => 'Jul', '08' => 'Aug', '09' => 'Sep', '10' => 'Oct', '11' => 'Nov', '12' => 'Dec' <add> ]; <add> $result = $this->Form->month('Model.field', array('value' => '1', 'monthNames' => $monthNames)); <ide> $expected = array( <ide> array('select' => array('name' => 'Model[field][month]')), <ide> array('option' => array('value' => '')), <ide> '/option', <del> array('option' => array('value' => '01')), <add> array('option' => array('value' => '01', 'selected' => 'selected')), <ide> 'Jan', <ide> '/option', <ide> array('option' => array('value' => '02')),
2
Javascript
Javascript
fix issues with the new fork plugin
060581b1287ea75d128f8f6b2b7bf494fe5db4fa
<ide><path>scripts/rollup/plugins/use-forks-plugin.js <ide> 'use strict'; <ide> <ide> const path = require('path'); <add>const semver = require('semver'); <add> <add>function resolveRelatively(importee, importer) { <add> if (semver.gte(process.version, '8.9.0')) { <add> return require.resolve(importee, { <add> paths: [path.dirname(importer)], <add> }); <add> } else { <add> // `paths` argument is not available in older Node. <add> // This works though. <add> // https://github.com/nodejs/node/issues/5963 <add> const Module = require('module'); <add> return Module._findPath(importee, [ <add> path.dirname(importer), <add> ...module.paths, <add> ]); <add> } <add>} <ide> <ide> let resolveCache = new Map(); <ide> function useForks(forks) { <del> let resolvedForks = {}; <add> let resolvedForks = new Map(); <ide> Object.keys(forks).forEach(srcModule => { <ide> const targetModule = forks[srcModule]; <del> resolvedForks[require.resolve(srcModule)] = require.resolve(targetModule); <add> resolvedForks.set( <add> require.resolve(srcModule), <add> require.resolve(targetModule) <add> ); <ide> }); <ide> return { <ide> resolveId(importee, importer) { <ide> if (!importer || !importee) { <ide> return null; <ide> } <add> if (importee.startsWith('\u0000')) { <add> // Internal Rollup reference, ignore. <add> // Passing that to Node file functions can fatal. <add> return null; <add> } <ide> let resolvedImportee = null; <ide> let cacheKey = `${importer}:::${importee}`; <ide> if (resolveCache.has(cacheKey)) { <ide> // Avoid hitting file system if possible. <ide> resolvedImportee = resolveCache.get(cacheKey); <ide> } else { <ide> try { <del> resolvedImportee = require.resolve(importee, { <del> paths: [path.dirname(importer)], <del> }); <add> resolvedImportee = resolveRelatively(importee, importer); <ide> } catch (err) { <ide> // Not our fault, let Rollup fail later. <ide> } <ide> if (resolvedImportee) { <ide> resolveCache.set(cacheKey, resolvedImportee); <ide> } <ide> } <del> if (resolvedImportee && resolvedForks.hasOwnProperty(resolvedImportee)) { <add> if (resolvedImportee && resolvedForks.has(resolvedImportee)) { <ide> // We found a fork! <del> return resolvedForks[resolvedImportee]; <add> return resolvedForks.get(resolvedImportee); <ide> } <ide> return null; <ide> },
1
PHP
PHP
add missing return statement
0024fc2228ac4c223fccb3696b170e3c23f74084
<ide><path>src/Illuminate/Mail/Mailable.php <ide> protected function runCallbacks($message) <ide> */ <ide> public function from($address, $name = null) <ide> { <del> $this->setAddress($address, $name, 'from'); <add> return $this->setAddress($address, $name, 'from'); <ide> } <ide> <ide> /**
1
Ruby
Ruby
allow default_timezone to vary between databases
f63545ded0499c5e62f5783e76688bd7020dc220
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/quoting.rb <ide> def unquoted_false <ide> # if the value is a Time responding to usec. <ide> def quoted_date(value) <ide> if value.acts_like?(:time) <del> if ActiveRecord.default_timezone == :utc <add> if default_timezone == :utc <ide> value = value.getutc if !value.utc? <ide> else <ide> value = value.getlocal <ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb <ide> def self.type_cast_config_to_boolean(config) <ide> end <ide> end <ide> <add> def self.validate_default_timezone(config) <add> case config <add> when nil <add> when "utc", "local" <add> config.to_sym <add> else <add> raise ArgumentError, "default_timezone must be either 'utc' or 'local'" <add> end <add> end <add> <ide> DEFAULT_READ_QUERY = [:begin, :commit, :explain, :release, :rollback, :savepoint, :select, :with] # :nodoc: <ide> private_constant :DEFAULT_READ_QUERY <ide> <ide> def initialize(connection, logger = nil, config = {}) # :nodoc: <ide> @advisory_locks_enabled = self.class.type_cast_config_to_boolean( <ide> config.fetch(:advisory_locks, true) <ide> ) <add> <add> @default_timezone = self.class.validate_default_timezone(config[:default_timezone]) <ide> end <ide> <ide> EXCEPTION_NEVER = { Exception => :never }.freeze # :nodoc: <ide> def use_metadata_table? <ide> @config.fetch(:use_metadata_table, true) <ide> end <ide> <add> def default_timezone <add> @default_timezone || ActiveRecord.default_timezone <add> end <add> <ide> # Determines whether writes are currently being prevented. <ide> # <ide> # Returns true if the connection is a replica. <ide><path>activerecord/lib/active_record/connection_adapters/mysql/database_statements.rb <ide> def high_precision_current_timestamp <ide> def raw_execute(sql, name, async: false) <ide> # make sure we carry over any changes to ActiveRecord.default_timezone that have been <ide> # made since we established the connection <del> @connection.query_options[:database_timezone] = ActiveRecord.default_timezone <add> @connection.query_options[:database_timezone] = default_timezone <ide> <ide> super <ide> end <ide> def exec_stmt_and_free(sql, name, binds, cache_stmt: false, async: false) <ide> <ide> # make sure we carry over any changes to ActiveRecord.default_timezone that have been <ide> # made since we established the connection <del> @connection.query_options[:database_timezone] = ActiveRecord.default_timezone <add> @connection.query_options[:database_timezone] = default_timezone <ide> <ide> type_casted_binds = type_casted_binds(binds) <ide> <ide><path>activerecord/lib/active_record/connection_adapters/mysql/quoting.rb <ide> def type_cast(value) # :nodoc: <ide> # We need to check explicitly for ActiveSupport::TimeWithZone because <ide> # we need to transform it to Time objects but we don't want to <ide> # transform Time objects to themselves. <del> if ActiveRecord.default_timezone == :utc <add> if default_timezone == :utc <ide> value.getutc <ide> else <ide> value.getlocal <ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb <ide> def configure_connection <ide> # If using Active Record's time zone support configure the connection to return <ide> # TIMESTAMP WITH ZONE types in UTC. <ide> unless variables["timezone"] <del> if ActiveRecord.default_timezone == :utc <add> if default_timezone == :utc <ide> variables["timezone"] = "UTC" <ide> elsif @local_tz <ide> variables["timezone"] = @local_tz <ide> def add_pg_encoders <ide> end <ide> <ide> def update_typemap_for_default_timezone <del> if @default_timezone != ActiveRecord.default_timezone && @timestamp_decoder <del> decoder_class = ActiveRecord.default_timezone == :utc ? <add> if @mapped_default_timezone != default_timezone && @timestamp_decoder <add> decoder_class = default_timezone == :utc ? <ide> PG::TextDecoder::TimestampUtc : <ide> PG::TextDecoder::TimestampWithoutTimeZone <ide> <ide> @timestamp_decoder = decoder_class.new(@timestamp_decoder.to_h) <ide> @connection.type_map_for_results.add_coder(@timestamp_decoder) <ide> <del> @default_timezone = ActiveRecord.default_timezone <add> @mapped_default_timezone = default_timezone <ide> <ide> # if default timezone has changed, we need to reconfigure the connection <ide> # (specifically, the session time zone) <ide> def update_typemap_for_default_timezone <ide> end <ide> <ide> def add_pg_decoders <del> @default_timezone = nil <add> @mapped_default_timezone = nil <ide> @timestamp_decoder = nil <ide> <ide> coders_by_name = { <ide><path>activerecord/lib/active_record/integration.rb <ide> def collection_cache_key(collection = all, timestamp_column = :updated_at) # :no <ide> def can_use_fast_cache_version?(timestamp) <ide> timestamp.is_a?(String) && <ide> cache_timestamp_format == :usec && <del> ActiveRecord.default_timezone == :utc && <add> self.class.connection.default_timezone == :utc && <ide> !updated_at_came_from_user? <ide> end <ide> <ide><path>activerecord/lib/active_record/timestamp.rb <ide> def all_timestamp_attributes_in_model <ide> end <ide> <ide> def current_time_from_proper_timezone <del> ActiveRecord.default_timezone == :utc ? Time.now.utc : Time.now <add> connection.default_timezone == :utc ? Time.now.utc : Time.now <ide> end <ide> <ide> private <ide><path>activerecord/test/cases/quoting_test.rb <ide> module ActiveRecord <ide> module ConnectionAdapters <ide> class QuotingTest < ActiveRecord::TestCase <ide> def setup <del> @quoter = Class.new { include Quoting }.new <add> @quoter = Class.new { <add> include Quoting <add> <add> def default_timezone <add> ActiveRecord.default_timezone <add> end <add> }.new <ide> end <ide> <ide> def test_quoted_true
8
Javascript
Javascript
fix coding style in page_view.js
2cf2eb0dfc64eb462710146f6bcd87413b6bb75a
<ide><path>web/page_view.js <ide> var PageView = function pageView(container, id, scale, <ide> div.style.width = Math.floor(this.viewport.width) + 'px'; <ide> div.style.height = Math.floor(this.viewport.height) + 'px'; <ide> <del> while (div.hasChildNodes()) <add> while (div.hasChildNodes()) { <ide> div.removeChild(div.lastChild); <add> } <ide> div.removeAttribute('data-loaded'); <ide> <ide> this.annotationLayer = null; <ide> var PageView = function pageView(container, id, scale, <ide> function bindLink(link, dest) { <ide> link.href = PDFView.getDestinationHash(dest); <ide> link.onclick = function pageViewSetupLinksOnclick() { <del> if (dest) <add> if (dest) { <ide> PDFView.navigateTo(dest); <add> } <ide> return false; <ide> }; <ide> link.className = 'internalLink'; <ide> var PageView = function pageView(container, id, scale, <ide> }; <ide> <ide> this.scrollIntoView = function pageViewScrollIntoView(dest) { <del> if (PDFView.isPresentationMode) { // Avoid breaking presentation mode. <del> dest = null; <del> } <del> if (!dest) { <del> scrollIntoView(div); <del> return; <del> } <add> if (PDFView.isPresentationMode) { // Avoid breaking presentation mode. <add> dest = null; <add> } <add> if (!dest) { <add> scrollIntoView(div); <add> return; <add> } <ide> <del> var x = 0, y = 0; <del> var width = 0, height = 0, widthScale, heightScale; <del> var scale = 0; <del> switch (dest[1].name) { <del> case 'XYZ': <del> x = dest[2]; <del> y = dest[3]; <del> scale = dest[4]; <del> // If x and/or y coordinates are not supplied, default to <del> // _top_ left of the page (not the obvious bottom left, <del> // since aligning the bottom of the intended page with the <del> // top of the window is rarely helpful). <del> x = x !== null ? x : 0; <del> y = y !== null ? y : this.height / this.scale; <del> break; <del> case 'Fit': <del> case 'FitB': <del> scale = 'page-fit'; <del> break; <del> case 'FitH': <del> case 'FitBH': <del> y = dest[2]; <del> scale = 'page-width'; <del> break; <del> case 'FitV': <del> case 'FitBV': <del> x = dest[2]; <del> scale = 'page-height'; <del> break; <del> case 'FitR': <del> x = dest[2]; <del> y = dest[3]; <del> width = dest[4] - x; <del> height = dest[5] - y; <del> widthScale = (PDFView.container.clientWidth - SCROLLBAR_PADDING) / <del> width / CSS_UNITS; <del> heightScale = (PDFView.container.clientHeight - SCROLLBAR_PADDING) / <del> height / CSS_UNITS; <del> scale = Math.min(widthScale, heightScale); <del> break; <del> default: <del> return; <del> } <add> var x = 0, y = 0; <add> var width = 0, height = 0, widthScale, heightScale; <add> var scale = 0; <add> switch (dest[1].name) { <add> case 'XYZ': <add> x = dest[2]; <add> y = dest[3]; <add> scale = dest[4]; <add> // If x and/or y coordinates are not supplied, default to <add> // _top_ left of the page (not the obvious bottom left, <add> // since aligning the bottom of the intended page with the <add> // top of the window is rarely helpful). <add> x = x !== null ? x : 0; <add> y = y !== null ? y : this.height / this.scale; <add> break; <add> case 'Fit': <add> case 'FitB': <add> scale = 'page-fit'; <add> break; <add> case 'FitH': <add> case 'FitBH': <add> y = dest[2]; <add> scale = 'page-width'; <add> break; <add> case 'FitV': <add> case 'FitBV': <add> x = dest[2]; <add> scale = 'page-height'; <add> break; <add> case 'FitR': <add> x = dest[2]; <add> y = dest[3]; <add> width = dest[4] - x; <add> height = dest[5] - y; <add> widthScale = (PDFView.container.clientWidth - SCROLLBAR_PADDING) / <add> width / CSS_UNITS; <add> heightScale = (PDFView.container.clientHeight - SCROLLBAR_PADDING) / <add> height / CSS_UNITS; <add> scale = Math.min(widthScale, heightScale); <add> break; <add> default: <add> return; <add> } <ide> <del> if (scale && scale !== PDFView.currentScale) { <del> PDFView.parseScale(scale, true, true); <del> } else if (PDFView.currentScale === UNKNOWN_SCALE) { <del> PDFView.parseScale(DEFAULT_SCALE, true, true); <del> } <add> if (scale && scale !== PDFView.currentScale) { <add> PDFView.parseScale(scale, true, true); <add> } else if (PDFView.currentScale === UNKNOWN_SCALE) { <add> PDFView.parseScale(DEFAULT_SCALE, true, true); <add> } <ide> <del> if (scale === 'page-fit' && !dest[4]) { <del> scrollIntoView(div); <del> return; <del> } <add> if (scale === 'page-fit' && !dest[4]) { <add> scrollIntoView(div); <add> return; <add> } <ide> <del> var boundingRect = [ <del> this.viewport.convertToViewportPoint(x, y), <del> this.viewport.convertToViewportPoint(x + width, y + height) <del> ]; <del> setTimeout(function pageViewScrollIntoViewRelayout() { <del> // letting page to re-layout before scrolling <del> var scale = PDFView.currentScale; <del> var x = Math.min(boundingRect[0][0], boundingRect[1][0]); <del> var y = Math.min(boundingRect[0][1], boundingRect[1][1]); <del> var width = Math.abs(boundingRect[0][0] - boundingRect[1][0]); <del> var height = Math.abs(boundingRect[0][1] - boundingRect[1][1]); <del> <del> scrollIntoView(div, {left: x, top: y, width: width, height: height}); <del> }, 0); <add> var boundingRect = [ <add> this.viewport.convertToViewportPoint(x, y), <add> this.viewport.convertToViewportPoint(x + width, y + height) <add> ]; <add> setTimeout(function pageViewScrollIntoViewRelayout() { <add> // letting page to re-layout before scrolling <add> var scale = PDFView.currentScale; <add> var x = Math.min(boundingRect[0][0], boundingRect[1][0]); <add> var y = Math.min(boundingRect[0][1], boundingRect[1][1]); <add> var width = Math.abs(boundingRect[0][0] - boundingRect[1][0]); <add> var height = Math.abs(boundingRect[0][1] - boundingRect[1][1]); <add> <add> scrollIntoView(div, {left: x, top: y, width: width, height: height}); <add> }, 0); <ide> }; <ide> <ide> this.getTextContent = function pageviewGetTextContent() { <ide> var PageView = function pageView(container, id, scale, <ide> <ide> self.stats = pdfPage.stats; <ide> self.updateStats(); <del> if (self.onAfterDraw) <add> if (self.onAfterDraw) { <ide> self.onAfterDraw(); <add> } <ide> <ide> cache.push(self); <ide> <ide> var PageView = function pageView(container, id, scale, <ide> console.error(error); <ide> // Tell the printEngine that rendering this canvas/page has failed. <ide> // This will make the print proces stop. <del> if ('abort' in obj) <add> if ('abort' in obj) { <ide> obj.abort(); <del> else <add> } else { <ide> obj.done(); <add> } <ide> self.pdfPage.destroy(); <ide> }); <ide> };
1
Javascript
Javascript
remove beta flash
c5af46b33f4dca67f880c653773c604e9089eda0
<ide><path>server/server.js <ide> passportConfigurator.init(); <ide> app.use(rxMiddleware()); <ide> <ide> app.use(function(req, res, next) { <del> // add beta warning <del> req.flash('info', { <del> msg: `warning: you are on experimental branch of Free Code Camp: <del> Your progress here may or may not be saved to the main site` <del> }); <ide> <ide> // Make user object available in templates. <ide> res.locals.user = req.user;
1
Ruby
Ruby
add secret token for action mailbox tests
c932850ef27ce2f42e886ca9dfd54f0d4b1518b3
<ide><path>actionmailbox/test/dummy/config/initializers/secret_token.rb <add>Rails.application.config.secret_key_base = "b3c631c314c0bbca50c1b2843150fe33"
1
PHP
PHP
add collection `sliding` method
4be33548469b417bebbdb034562877d29eb9f453
<ide><path>src/Illuminate/Collections/Collection.php <ide> public function shuffle($seed = null) <ide> return new static(Arr::shuffle($this->items, $seed)); <ide> } <ide> <add> /** <add> * Create chunks representing a "sliding window" view of the items in the collection. <add> * <add> * @param int $size <add> * @param int $step <add> * @return static <add> */ <add> public function sliding($size = 2, $step = 1) <add> { <add> $chunks = floor(($this->count() - $size) / $step) + 1; <add> <add> return static::times($chunks, function ($number) use ($size, $step) { <add> return $this->slice(($number - 1) * $step, $size); <add> }); <add> } <add> <ide> /** <ide> * Skip the first {$count} items. <ide> * <ide><path>src/Illuminate/Collections/LazyCollection.php <ide> public function shuffle($seed = null) <ide> return $this->passthru('shuffle', func_get_args()); <ide> } <ide> <add> /** <add> * Create chunks representing a "sliding window" view of the items in the collection. <add> * <add> * @param int $size <add> * @param int $step <add> * @return static <add> */ <add> public function sliding($size = 2, $step = 1) <add> { <add> return new static(function () use ($size, $step) { <add> $iterator = $this->getIterator(); <add> <add> $chunk = []; <add> <add> while ($iterator->valid()) { <add> $chunk[$iterator->key()] = $iterator->current(); <add> <add> if (count($chunk) == $size) { <add> yield tap(new static($chunk), function () use (&$chunk, $step) { <add> $chunk = array_slice($chunk, $step, null, true); <add> }); <add> <add> // If the $step between chunks is bigger than each chunk's $size, <add> // we will skip the extra items (which should never be in any <add> // chunk) before we continue to the next chunk in the loop. <add> if ($step > $size) { <add> $skip = $step - $size; <add> <add> for ($i = 0; $i < $skip && $iterator->valid(); $i++) { <add> $iterator->next(); <add> } <add> } <add> } <add> <add> $iterator->next(); <add> } <add> }); <add> } <add> <ide> /** <ide> * Skip the first {$count} items. <ide> * <ide><path>tests/Support/SupportCollectionTest.php <ide> public function testShiftReturnsAndRemovesFirstItemInCollection() <ide> $this->assertNull($data->first()); <ide> } <ide> <add> /** <add> * @dataProvider collectionClassProvider <add> */ <add> public function testSliding($collection) <add> { <add> // Default parameters: $size = 2, $step = 1 <add> $this->assertSame([], $collection::times(0)->sliding()->toArray()); <add> $this->assertSame([], $collection::times(1)->sliding()->toArray()); <add> $this->assertSame([[1, 2]], $collection::times(2)->sliding()->toArray()); <add> $this->assertSame( <add> [[1, 2], [2, 3]], <add> $collection::times(3)->sliding()->map->values()->toArray() <add> ); <add> <add> // Custom step: $size = 2, $step = 3 <add> $this->assertSame([], $collection::times(1)->sliding(2, 3)->toArray()); <add> $this->assertSame([[1, 2]], $collection::times(2)->sliding(2, 3)->toArray()); <add> $this->assertSame([[1, 2]], $collection::times(3)->sliding(2, 3)->toArray()); <add> $this->assertSame([[1, 2]], $collection::times(4)->sliding(2, 3)->toArray()); <add> $this->assertSame( <add> [[1, 2], [4, 5]], <add> $collection::times(5)->sliding(2, 3)->map->values()->toArray() <add> ); <add> <add> // Custom size: $size = 3, $step = 1 <add> $this->assertSame([], $collection::times(2)->sliding(3)->toArray()); <add> $this->assertSame([[1, 2, 3]], $collection::times(3)->sliding(3)->toArray()); <add> $this->assertSame( <add> [[1, 2, 3], [2, 3, 4]], <add> $collection::times(4)->sliding(3)->map->values()->toArray() <add> ); <add> $this->assertSame( <add> [[1, 2, 3], [2, 3, 4]], <add> $collection::times(4)->sliding(3)->map->values()->toArray() <add> ); <add> <add> // Custom size and custom step: $size = 3, $step = 2 <add> $this->assertSame([], $collection::times(2)->sliding(3, 2)->toArray()); <add> $this->assertSame([[1, 2, 3]], $collection::times(3)->sliding(3, 2)->toArray()); <add> $this->assertSame([[1, 2, 3]], $collection::times(4)->sliding(3, 2)->toArray()); <add> $this->assertSame( <add> [[1, 2, 3], [3, 4, 5]], <add> $collection::times(5)->sliding(3, 2)->map->values()->toArray() <add> ); <add> $this->assertSame( <add> [[1, 2, 3], [3, 4, 5]], <add> $collection::times(6)->sliding(3, 2)->map->values()->toArray() <add> ); <add> <add> // Ensure keys are preserved, and inner chunks are also collections <add> $chunks = $collection::times(3)->sliding(); <add> <add> $this->assertSame([[0 => 1, 1 => 2], [1 => 2, 2 => 3]], $chunks->toArray()); <add> <add> $this->assertInstanceOf($collection, $chunks); <add> $this->assertInstanceOf($collection, $chunks->first()); <add> $this->assertInstanceOf($collection, $chunks->skip(1)->first()); <add> } <add> <ide> /** <ide> * @dataProvider collectionClassProvider <ide> */ <ide><path>tests/Support/SupportLazyCollectionIsLazyTest.php <ide> public function testShuffleIsLazy() <ide> }); <ide> } <ide> <add> public function testSlidingIsLazy() <add> { <add> $this->assertDoesNotEnumerate(function ($collection) { <add> $collection->sliding(); <add> }); <add> <add> $this->assertEnumerates(2, function ($collection) { <add> $collection->sliding()->take(1)->all(); <add> }); <add> <add> $this->assertEnumerates(3, function ($collection) { <add> $collection->sliding()->take(2)->all(); <add> }); <add> <add> $this->assertEnumerates(13, function ($collection) { <add> $collection->sliding(3, 5)->take(3)->all(); <add> }); <add> <add> $this->assertEnumeratesOnce(function ($collection) { <add> $collection->sliding()->all(); <add> }); <add> } <add> <ide> public function testSkipIsLazy() <ide> { <ide> $this->assertDoesNotEnumerate(function ($collection) {
4
Python
Python
fix nan in full-fp16 label_smoothing eval
e21f89f64c0683f111572b8b9fa38ffff64885f1
<ide><path>src/transformers/trainer_pt_utils.py <ide> def __call__(self, model_output, labels): <ide> # will ignore them in any case. <ide> labels.clamp_min_(0) <ide> nll_loss = log_probs.gather(dim=-1, index=labels) <del> smoothed_loss = log_probs.sum(dim=-1, keepdim=True) <add> # works for fp16 input tensor too, by internally upcasting it to fp32 <add> smoothed_loss = log_probs.sum(dim=-1, keepdim=True, dtype=torch.float32) <ide> <ide> nll_loss.masked_fill_(padding_mask, 0.0) <ide> smoothed_loss.masked_fill_(padding_mask, 0.0)
1
PHP
PHP
add type to fix conflict with interface
eb5196027e7f33e9fcdcbaeb39f2aca6e5cce862
<ide><path>src/ORM/ResultSet.php <ide> public function unserialize($serialized) <ide> * <ide> * @return int <ide> */ <del> public function count() <add> public function count(): int <ide> { <ide> if ($this->_count !== null) { <ide> return $this->_count;
1
Text
Text
use code markup/markdown in headers
a70c3ab9c1eadf803c91efec4b71f57b6412ce22
<ide><path>doc/api/path.md <ide> example, `path.resolve('c:\\')` can potentially return a different result than <ide> `path.resolve('c:')`. For more information, see <ide> [this MSDN page][MSDN-Rel-Path]. <ide> <del>## path.basename(path\[, ext\]) <add>## `path.basename(path[, ext])` <ide> <!-- YAML <ide> added: v0.1.25 <ide> changes: <ide> path.basename('/foo/bar/baz/asdf/quux.html', '.html'); <ide> A [`TypeError`][] is thrown if `path` is not a string or if `ext` is given <ide> and is not a string. <ide> <del>## path.delimiter <add>## `path.delimiter` <ide> <!-- YAML <ide> added: v0.9.3 <ide> --> <ide> process.env.PATH.split(path.delimiter); <ide> // Returns ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\'] <ide> ``` <ide> <del>## path.dirname(path) <add>## `path.dirname(path)` <ide> <!-- YAML <ide> added: v0.1.16 <ide> changes: <ide> path.dirname('/foo/bar/baz/asdf/quux'); <ide> <ide> A [`TypeError`][] is thrown if `path` is not a string. <ide> <del>## path.extname(path) <add>## `path.extname(path)` <ide> <!-- YAML <ide> added: v0.1.25 <ide> changes: <ide> path.extname('.index.md'); <ide> <ide> A [`TypeError`][] is thrown if `path` is not a string. <ide> <del>## path.format(pathObject) <add>## `path.format(pathObject)` <ide> <!-- YAML <ide> added: v0.11.15 <ide> --> <ide> path.format({ <ide> // Returns: 'C:\\path\\dir\\file.txt' <ide> ``` <ide> <del>## path.isAbsolute(path) <add>## `path.isAbsolute(path)` <ide> <!-- YAML <ide> added: v0.11.2 <ide> --> <ide> path.isAbsolute('.'); // false <ide> <ide> A [`TypeError`][] is thrown if `path` is not a string. <ide> <del>## path.join(\[...paths\]) <add>## `path.join([...paths])` <ide> <!-- YAML <ide> added: v0.1.16 <ide> --> <ide> path.join('foo', {}, 'bar'); <ide> <ide> A [`TypeError`][] is thrown if any of the path segments is not a string. <ide> <del>## path.normalize(path) <add>## `path.normalize(path)` <ide> <!-- YAML <ide> added: v0.1.23 <ide> --> <ide> path.win32.normalize('C:////temp\\\\/\\/\\/foo/bar'); <ide> <ide> A [`TypeError`][] is thrown if `path` is not a string. <ide> <del>## path.parse(path) <add>## `path.parse(path)` <ide> <!-- YAML <ide> added: v0.11.15 <ide> --> <ide> path.parse('C:\\path\\dir\\file.txt'); <ide> <ide> A [`TypeError`][] is thrown if `path` is not a string. <ide> <del>## path.posix <add>## `path.posix` <ide> <!-- YAML <ide> added: v0.11.15 <ide> --> <ide> added: v0.11.15 <ide> The `path.posix` property provides access to POSIX specific implementations <ide> of the `path` methods. <ide> <del>## path.relative(from, to) <add>## `path.relative(from, to)` <ide> <!-- YAML <ide> added: v0.5.0 <ide> changes: <ide> path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb'); <ide> <ide> A [`TypeError`][] is thrown if either `from` or `to` is not a string. <ide> <del>## path.resolve(\[...paths\]) <add>## `path.resolve([...paths])` <ide> <!-- YAML <ide> added: v0.3.4 <ide> --> <ide> path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif'); <ide> <ide> A [`TypeError`][] is thrown if any of the arguments is not a string. <ide> <del>## path.sep <add>## `path.sep` <ide> <!-- YAML <ide> added: v0.7.9 <ide> --> <ide> On Windows, both the forward slash (`/`) and backward slash (`\`) are accepted <ide> as path segment separators; however, the `path` methods only add backward <ide> slashes (`\`). <ide> <del>## path.toNamespacedPath(path) <add>## `path.toNamespacedPath(path)` <ide> <!-- YAML <ide> added: v9.0.0 <ide> --> <ide> modifications. <ide> This method is meaningful only on Windows system. On POSIX systems, the <ide> method is non-operational and always returns `path` without modifications. <ide> <del>## path.win32 <add>## `path.win32` <ide> <!-- YAML <ide> added: v0.11.15 <ide> -->
1
PHP
PHP
remove fluff from file headers
316992435b281837136221f9acc6d98550f680fe
<ide><path>tests/Fixture/AfterTreeFixture.php <ide> <?php <ide> /** <del> * Short description for after_tree_fixture.php <del> * <del> * Long description for after_tree_fixture.php <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * <ide> * Licensed under The MIT License <ide><path>tests/Fixture/ArticlesTagFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/AttachmentFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/AuthUserCustomFieldFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/AuthUserFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/AuthorFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/BakeArticlesBakeTagFixture.php <ide> <?php <ide> /** <del> * BakeCommentFixture <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/BakeCommentFixture.php <ide> <?php <ide> /** <del> * BakeCommentFixture <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/BakeTagFixture.php <ide> <?php <ide> /** <del> * BakeTagFixture <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/BinaryTestFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/CakeSessionFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/CategoryFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/CategoryThreadFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/CommentFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/CounterCacheUserFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/DataTestFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/DatatypeFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/FlagTreeFixture.php <ide> <?php <ide> /** <del> * Tree behavior class test fixture. <del> * <del> * Enables a model object to act as a node-based tree. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/MenuLinkTreeFixture.php <ide> <?php <ide> /** <del> * Tree behavior class. <del> * <del> * Enables a model object to act as a node-based tree. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/NumberTreeFixture.php <ide> <?php <ide> /** <del> * Tree behavior class. <del> * <del> * Enables a model object to act as a node-based tree. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/NumberTreeTwoFixture.php <ide> <?php <ide> /** <del> * Tree behavior class. <del> * <del> * Enables a model object to act as a node-based tree. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/PersonFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/PostFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/PostsTagFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/SessionFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/TagFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/TestPluginArticleFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/TestPluginCommentFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/TranslateArticleFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/TranslateFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/TranslateTableFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/TranslatedArticleFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/TranslatedItemFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/UnconventionalTreeFixture.php <ide> <?php <ide> /** <del> * Unconventional Tree behavior class test fixture. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/UnsignedFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/UserFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/UuidFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/UuidTagFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/UuidTreeFixture.php <ide> <?php <ide> /** <del> * UUID Tree behavior fixture. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/UuiditemFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/UuiditemsUuidportfolioFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/UuiditemsUuidportfolioNumericidFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide><path>tests/Fixture/UuidportfolioFixture.php <ide> <?php <ide> /** <del> * Short description for file. <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> *
43
Javascript
Javascript
remove legacy dom node/ref stuff
538d0b08f2a35c216b1ef65ea7e9e9a04bf82707
<ide><path>src/renderers/dom/shared/ReactDOMComponent.js <ide> var ReactDOMSelect = require('ReactDOMSelect'); <ide> var ReactDOMTextarea = require('ReactDOMTextarea'); <ide> var ReactMultiChild = require('ReactMultiChild'); <ide> var ReactPerf = require('ReactPerf'); <del>var ReactUpdateQueue = require('ReactUpdateQueue'); <ide> <ide> var assign = require('Object.assign'); <del>var canDefineProperty = require('canDefineProperty'); <ide> var escapeTextContentForBrowser = require('escapeTextContentForBrowser'); <ide> var invariant = require('invariant'); <ide> var isEventSupported = require('isEventSupported'); <ide> function getDeclarationErrorAddendum(internalInstance) { <ide> return ''; <ide> } <ide> <del>var legacyPropsDescriptor; <del>if (__DEV__) { <del> legacyPropsDescriptor = { <del> props: { <del> enumerable: false, <del> get: function() { <del> var component = ReactDOMComponentTree.getInstanceFromNode(this); <del> warning( <del> false, <del> 'ReactDOMComponent: Do not access .props of a DOM node; instead, ' + <del> 'recreate the props as `render` did originally or read the DOM ' + <del> 'properties/attributes directly from this node (e.g., ' + <del> 'this.refs.box.className).%s', <del> getDeclarationErrorAddendum(component) <del> ); <del> return component._currentElement.props; <del> }, <del> }, <del> }; <del>} <del> <del>function legacyGetDOMNode() { <del> if (__DEV__) { <del> var component = ReactDOMComponentTree.getInstanceFromNode(this); <del> warning( <del> false, <del> 'ReactDOMComponent: Do not access .getDOMNode() of a DOM node; ' + <del> 'instead, use the node directly.%s', <del> getDeclarationErrorAddendum(component) <del> ); <del> } <del> return this; <del>} <del> <del>function legacyIsMounted() { <del> var component = ReactDOMComponentTree.getInstanceFromNode(this); <del> if (__DEV__) { <del> warning( <del> false, <del> 'ReactDOMComponent: Do not access .isMounted() of a DOM node.%s', <del> getDeclarationErrorAddendum(component) <del> ); <del> } <del> return !!component; <del>} <del> <del>function legacySetStateEtc() { <del> if (__DEV__) { <del> var component = ReactDOMComponentTree.getInstanceFromNode(this); <del> warning( <del> false, <del> 'ReactDOMComponent: Do not access .setState(), .replaceState(), or ' + <del> '.forceUpdate() of a DOM node. This is a no-op.%s', <del> getDeclarationErrorAddendum(component) <del> ); <del> } <del>} <del> <del>function legacySetProps(partialProps, callback) { <del> var component = ReactDOMComponentTree.getInstanceFromNode(this); <del> if (__DEV__) { <del> warning( <del> false, <del> 'ReactDOMComponent: Do not access .setProps() of a DOM node. ' + <del> 'Instead, call ReactDOM.render again at the top level.%s', <del> getDeclarationErrorAddendum(component) <del> ); <del> } <del> if (!component) { <del> return; <del> } <del> ReactUpdateQueue.enqueueSetPropsInternal(component, partialProps); <del> if (callback) { <del> ReactUpdateQueue.enqueueCallbackInternal(component, callback); <del> } <del>} <del> <del>function legacyReplaceProps(partialProps, callback) { <del> var component = ReactDOMComponentTree.getInstanceFromNode(this); <del> if (__DEV__) { <del> warning( <del> false, <del> 'ReactDOMComponent: Do not access .replaceProps() of a DOM node. ' + <del> 'Instead, call ReactDOM.render again at the top level.%s', <del> getDeclarationErrorAddendum(component) <del> ); <del> } <del> if (!component) { <del> return; <del> } <del> ReactUpdateQueue.enqueueReplacePropsInternal(component, partialProps); <del> if (callback) { <del> ReactUpdateQueue.enqueueCallbackInternal(component, callback); <del> } <del>} <del> <ide> function friendlyStringify(obj) { <ide> if (typeof obj === 'object') { <ide> if (Array.isArray(obj)) { <ide> ReactDOMComponent.Mixin = { <ide> context <ide> ); <ide> <del> if (!canDefineProperty && this._flags & Flags.nodeHasLegacyProperties) { <del> this._nativeNode.props = nextProps; <del> } <del> <ide> if (this._tag === 'select') { <ide> // <select> value update needs to occur after <option> children <ide> // reconciliation <ide> ReactDOMComponent.Mixin = { <ide> }, <ide> <ide> getPublicInstance: function() { <del> var node = getNode(this); <del> if (this._flags & Flags.nodeHasLegacyProperties) { <del> return node; <del> } else { <del> node.getDOMNode = legacyGetDOMNode; <del> node.isMounted = legacyIsMounted; <del> node.setState = legacySetStateEtc; <del> node.replaceState = legacySetStateEtc; <del> node.forceUpdate = legacySetStateEtc; <del> node.setProps = legacySetProps; <del> node.replaceProps = legacyReplaceProps; <del> <del> if (__DEV__) { <del> if (canDefineProperty) { <del> Object.defineProperties(node, legacyPropsDescriptor); <del> } else { <del> // updateComponent will update this property on subsequent renders <del> node.props = this._currentElement.props; <del> } <del> } else { <del> // updateComponent will update this property on subsequent renders <del> node.props = this._currentElement.props; <del> } <del> <del> this._flags |= Flags.nodeHasLegacyProperties; <del> return node; <del> } <add> return getNode(this); <ide> }, <ide> <ide> }; <ide><path>src/renderers/dom/shared/ReactDOMComponentFlags.js <ide> 'use strict'; <ide> <ide> var ReactDOMComponentFlags = { <del> nodeHasLegacyProperties: 1 << 0, <del> hasCachedChildNodes: 1 << 1, <add> hasCachedChildNodes: 1 << 0, <ide> }; <ide> <ide> module.exports = ReactDOMComponentFlags; <ide><path>src/renderers/dom/shared/__tests__/ReactDOMComponent-test.js <ide> describe('ReactDOMComponent', function() { <ide> ); <ide> }); <ide> }); <del> <del> describe('DOM nodes as refs', function() { <del> var ReactTestUtils; <del> <del> beforeEach(function() { <del> ReactTestUtils = require('ReactTestUtils'); <del> }); <del> <del> it('warns when accessing properties on DOM components', function() { <del> spyOn(console, 'error'); <del> var innerDiv; <del> var Animal = React.createClass({ <del> render: function() { <del> return <div ref="div">iguana</div>; <del> }, <del> componentDidMount: function() { <del> innerDiv = this.refs.div; <del> <del> void this.refs.div.props; <del> this.refs.div.setState(); <del> expect(this.refs.div.getDOMNode()).toBe(this.refs.div); <del> expect(this.refs.div.isMounted()).toBe(true); <del> }, <del> }); <del> var container = document.createElement('div'); <del> ReactDOM.render(<Animal />, container); <del> ReactDOM.unmountComponentAtNode(container); <del> expect(innerDiv.isMounted()).toBe(false); <del> <del> expect(console.error.calls.length).toBe(5); <del> expect(console.error.argsForCall[0][0]).toBe( <del> 'Warning: ReactDOMComponent: Do not access .props of a DOM ' + <del> 'node; instead, recreate the props as `render` did originally or ' + <del> 'read the DOM properties/attributes directly from this node (e.g., ' + <del> 'this.refs.box.className). This DOM node was rendered by `Animal`.' <del> ); <del> expect(console.error.argsForCall[1][0]).toBe( <del> 'Warning: ReactDOMComponent: Do not access .setState(), ' + <del> '.replaceState(), or .forceUpdate() of a DOM node. This is a no-op. ' + <del> 'This DOM node was rendered by `Animal`.' <del> ); <del> expect(console.error.argsForCall[2][0]).toBe( <del> 'Warning: ReactDOMComponent: Do not access .getDOMNode() of a DOM ' + <del> 'node; instead, use the node directly. This DOM node was ' + <del> 'rendered by `Animal`.' <del> ); <del> expect(console.error.argsForCall[3][0]).toBe( <del> 'Warning: ReactDOMComponent: Do not access .isMounted() of a DOM ' + <del> 'node. This DOM node was rendered by `Animal`.' <del> ); <del> expect(console.error.argsForCall[4][0]).toContain('isMounted'); <del> }); <del> <del> it('handles legacy setProps and replaceProps', function() { <del> spyOn(console, 'error'); <del> var node = ReactTestUtils.renderIntoDocument(<div>rhinoceros</div>); <del> <del> node.setProps({className: 'herbiverous'}); <del> expect(node.className).toBe('herbiverous'); <del> expect(node.textContent).toBe('rhinoceros'); <del> <del> node.replaceProps({className: 'invisible rhino'}); <del> expect(node.className).toBe('invisible rhino'); <del> expect(node.textContent).toBe(''); <del> <del> expect(console.error.calls.length).toBe(2); <del> expect(console.error.argsForCall[0][0]).toBe( <del> 'Warning: ReactDOMComponent: Do not access .setProps() of a DOM node. ' + <del> 'Instead, call ReactDOM.render again at the top level.' <del> ); <del> expect(console.error.argsForCall[1][0]).toBe( <del> 'Warning: ReactDOMComponent: Do not access .replaceProps() of a DOM ' + <del> 'node. Instead, call ReactDOM.render again at the top level.' <del> ); <del> }); <del> <del> it('does not touch ref-less nodes', function() { <del> var node = ReactTestUtils.renderIntoDocument(<div><span /></div>); <del> expect(typeof node.getDOMNode).toBe('function'); <del> expect(typeof node.firstChild.getDOMNode).toBe('undefined'); <del> }); <del> }); <ide> }); <ide><path>src/renderers/shared/reconciler/__tests__/ReactCompositeComponent-test.js <ide> describe('ReactCompositeComponent', function() { <ide> var anchor = instance.getAnchor(); <ide> var actualDOMAnchorNode = ReactDOM.findDOMNode(anchor); <ide> expect(actualDOMAnchorNode.className).toBe(''); <del> expect(actualDOMAnchorNode).toBe(anchor.getDOMNode()); <add> expect(actualDOMAnchorNode).toBe(ReactDOM.findDOMNode(anchor)); <ide> }); <ide> <ide> it('should auto bind methods and values correctly', function() {
4
Python
Python
add numpy documentation
49c8a35dfaa22b5ca29f9aa05bbe4b89f34e6da0
<ide><path>keras/backend/tensorflow_backend.py <ide> def dtype(x): <ide> >>> K.dtype(kvar) <ide> 'float32_ref' <ide> ``` <add> {{np_implementation}} <ide> """ <ide> return x.dtype.base_dtype.name <ide> <ide> def eval(x): <ide> array([[ 1., 2.], <ide> [ 3., 4.]], dtype=float32) <ide> ``` <add> {{np_implementation}} <ide> """ <ide> return to_dense(x).eval(session=get_session()) <ide> <ide> def zeros(shape, dtype=None, name=None): <ide> [ 0., 0., 0., 0.], <ide> [ 0., 0., 0., 0.]], dtype=float32) <ide> ``` <add> {{np_implementation}} <ide> """ <ide> if dtype is None: <ide> dtype = floatx() <ide> def ones(shape, dtype=None, name=None): <ide> [ 1., 1., 1., 1.], <ide> [ 1., 1., 1., 1.]], dtype=float32) <ide> ``` <add> {{np_implementation}} <ide> """ <ide> if dtype is None: <ide> dtype = floatx() <ide> def eye(size, dtype=None, name=None): <ide> [ 0., 1., 0.], <ide> [ 0., 0., 1.]], dtype=float32) <ide> ``` <del> <add> {{np_implementation}} <ide> """ <ide> if dtype is None: <ide> dtype = floatx() <ide> def zeros_like(x, dtype=None, name=None): <ide> array([[ 0., 0., 0.], <ide> [ 0., 0., 0.]], dtype=float32) <ide> ``` <add> {{np_implementation}} <ide> """ <ide> return tf.zeros_like(x, dtype=dtype, name=name) <ide> <ide> def ones_like(x, dtype=None, name=None): <ide> array([[ 1., 1., 1.], <ide> [ 1., 1., 1.]], dtype=float32) <ide> ``` <add> {{np_implementation}} <ide> """ <ide> return tf.ones_like(x, dtype=dtype, name=name) <ide> <ide> def random_uniform_variable(shape, low, high, dtype=None, <ide> array([[ 0.10940075, 0.10047495, 0.476143 ], <ide> [ 0.66137183, 0.00869417, 0.89220798]], dtype=float32) <ide> ``` <add> {{np_implementation}} <ide> """ <ide> if dtype is None: <ide> dtype = floatx() <ide> def random_normal_variable(shape, mean, scale, dtype=None, <ide> array([[ 1.19591331, 0.68685907, -0.63814116], <ide> [ 0.92629528, 0.28055015, 1.70484698]], dtype=float32) <ide> ``` <add> {{np_implementation}} <ide> """ <ide> if dtype is None: <ide> dtype = floatx() <ide> def count_params(x): <ide> array([[ 0., 0., 0.], <ide> [ 0., 0., 0.]], dtype=float32) <ide> ``` <add> {{np_implementation}} <ide> """ <ide> return np.prod(int_shape(x)) <ide> <ide> def dot(x, y): <ide> >>> K.int_shape(xy) <ide> (2, 4, 5) <ide> ``` <add> {{np_implementation}} <ide> """ <ide> if ndim(x) is not None and (ndim(x) > 2 or ndim(y) > 2): <ide> x_shape = [] <ide> def transpose(x): <ide> <tf.Tensor 'transpose_4:0' shape=(3, 2) dtype=float32> <ide> <ide> ``` <add> {{np_implementation}} <ide> """ <ide> return tf.transpose(x) <ide> <ide> def cumsum(x, axis=0): <ide> <ide> # Returns <ide> A tensor of the cumulative sum of values of `x` along `axis`. <add> {{np_implementation}} <ide> """ <ide> return tf.cumsum(x, axis=axis) <ide> <ide> def cumprod(x, axis=0): <ide> <ide> # Returns <ide> A tensor of the cumulative product of values of `x` along `axis`. <add> {{np_implementation}} <ide> """ <ide> return tf.cumprod(x, axis=axis) <ide> <ide> def var(x, axis=None, keepdims=False): <ide> <ide> # Returns <ide> A tensor with the variance of elements of `x`. <add> {{np_implementation}} <ide> """ <ide> if x.dtype.base_dtype == tf.bool: <ide> x = tf.cast(x, floatx()) <ide> def std(x, axis=None, keepdims=False): <ide> <ide> # Returns <ide> A tensor with the standard deviation of elements of `x`. <add> {{np_implementation}} <ide> """ <ide> return tf.sqrt(var(x, axis=axis, keepdims=keepdims)) <ide> <ide> def mean(x, axis=None, keepdims=False): <ide> <ide> # Returns <ide> A tensor with the mean of elements of `x`. <add> {{np_implementation}} <ide> """ <ide> if x.dtype.base_dtype == tf.bool: <ide> x = tf.cast(x, floatx()) <ide> def any(x, axis=None, keepdims=False): <ide> <ide> # Returns <ide> A uint8 tensor (0s and 1s). <add> {{np_implementation}} <ide> """ <ide> x = tf.cast(x, tf.bool) <ide> return tf.reduce_any(x, axis, keepdims) <ide> def all(x, axis=None, keepdims=False): <ide> <ide> # Returns <ide> A uint8 tensor (0s and 1s). <add> {{np_implementation}} <ide> """ <ide> x = tf.cast(x, tf.bool) <ide> return tf.reduce_all(x, axis, keepdims) <ide> def argmax(x, axis=-1): <ide> <ide> # Returns <ide> A tensor. <add> {{np_implementation}} <ide> """ <ide> return tf.argmax(x, axis) <ide> <ide> def argmin(x, axis=-1): <ide> <ide> # Returns <ide> A tensor. <add> {{np_implementation}} <ide> """ <ide> return tf.argmin(x, axis) <ide> <ide> def sqrt(x): <ide> <ide> # Returns <ide> A tensor. <add> {{np_implementation}} <ide> """ <ide> zero = _to_tensor(0., x.dtype.base_dtype) <ide> inf = _to_tensor(np.inf, x.dtype.base_dtype) <ide> def logsumexp(x, axis=None, keepdims=False): <ide> <ide> # Returns <ide> The reduced tensor. <add> {{np_implementation}} <ide> """ <ide> return tf.reduce_logsumexp(x, axis, keepdims) <ide> <ide> def pow(x, a): <ide> <ide> # Returns <ide> A tensor. <add> {{np_implementation}} <ide> """ <ide> return tf.pow(x, a) <ide> <ide> def clip(x, min_value, max_value): <ide> <ide> # Returns <ide> A tensor. <add> {{np_implementation}} <ide> """ <ide> if (isinstance(min_value, (int, float)) and <ide> isinstance(max_value, (int, float))): <ide> def dropout(x, level, noise_shape=None, seed=None): <ide> <ide> # Returns <ide> A tensor. <add> {{np_implementation}} <ide> """ <ide> retain_prob = 1. - level <ide> if seed is None: <ide> def bias_add(x, bias, data_format=None): <ide> 2. invalid bias shape. <ide> the bias should be either a vector or <ide> a tensor with ndim(x) - 1 dimension <add> {{np_implementation}} <ide> """ <ide> data_format = normalize_data_format(data_format) <ide> bias_shape = int_shape(bias)
1
Javascript
Javascript
simplify vm-module-errors test
3d6533ea02d53a11f550769c70028d00b8d2d391
<ide><path>test/parallel/test-vm-module-errors.js <ide> const assert = require('assert'); <ide> <ide> const { SourceTextModule, createContext } = require('vm'); <ide> <del>async function expectsRejection(fn, settings) { <del> const validateError = common.expectsError(settings); <del> // Retain async context. <del> const storedError = new Error('Thrown from:'); <del> try { <del> await fn(); <del> } catch (err) { <del> try { <del> validateError(err); <del> } catch (validationError) { <del> console.error(validationError); <del> console.error('Original error:'); <del> console.error(err); <del> throw storedError; <del> } <del> return; <del> } <del> assert.fail('Missing expected exception'); <del>} <del> <ide> async function createEmptyLinkedModule() { <ide> const m = new SourceTextModule(''); <ide> await m.link(common.mustNotCall()); <ide> async function checkArgType() { <ide> for (const invalidLinker of [ <ide> 0, 1, undefined, null, true, 'str', {}, Symbol.iterator <ide> ]) { <del> await expectsRejection(async () => { <add> await assert.rejects(async () => { <ide> const m = new SourceTextModule(''); <ide> await m.link(invalidLinker); <ide> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <del> type: TypeError <add> name: 'TypeError' <ide> }); <ide> } <ide> } <ide> <ide> // Check methods/properties can only be used under a specific state. <ide> async function checkModuleState() { <del> await expectsRejection(async () => { <add> await assert.rejects(async () => { <ide> const m = new SourceTextModule(''); <ide> await m.link(common.mustNotCall()); <ide> assert.strictEqual(m.linkingStatus, 'linked'); <ide> async function checkModuleState() { <ide> code: 'ERR_VM_MODULE_ALREADY_LINKED' <ide> }); <ide> <del> await expectsRejection(async () => { <add> await assert.rejects(async () => { <ide> const m = new SourceTextModule(''); <ide> m.link(common.mustNotCall()); <ide> assert.strictEqual(m.linkingStatus, 'linking'); <ide> async function checkModuleState() { <ide> code: 'ERR_VM_MODULE_NOT_LINKED' <ide> }); <ide> <del> await expectsRejection(async () => { <add> await assert.rejects(async () => { <ide> const m = new SourceTextModule('import "foo";'); <ide> try { <ide> await m.link(common.mustCall(() => ({}))); <ide> } catch { <ide> assert.strictEqual(m.linkingStatus, 'errored'); <ide> m.instantiate(); <ide> } <del> assert.fail('Unreachable'); <ide> }, { <ide> code: 'ERR_VM_MODULE_NOT_LINKED' <ide> }); <ide> async function checkModuleState() { <ide> await m.evaluate(); <ide> } <ide> <del> await expectsRejection(async () => { <add> await assert.rejects(async () => { <ide> const m = new SourceTextModule(''); <ide> await m.evaluate(); <ide> }, { <ide> code: 'ERR_VM_MODULE_STATUS', <ide> message: 'Module status must be one of instantiated, evaluated, and errored' <ide> }); <ide> <del> await expectsRejection(async () => { <add> await assert.rejects(async () => { <ide> const m = new SourceTextModule(''); <ide> await m.evaluate(false); <ide> }, { <ide> async function checkModuleState() { <ide> 'Received type boolean' <ide> }); <ide> <del> await expectsRejection(async () => { <add> await assert.rejects(async () => { <ide> const m = await createEmptyLinkedModule(); <ide> await m.evaluate(); <ide> }, { <ide> async function checkModuleState() { <ide> message: 'Module status must be errored' <ide> }); <ide> <del> await expectsRejection(async () => { <add> await assert.rejects(async () => { <ide> const m = await createEmptyLinkedModule(); <ide> m.instantiate(); <ide> await m.evaluate(); <ide> async function checkModuleState() { <ide> message: 'Module status must not be uninstantiated or instantiating' <ide> }); <ide> <del> await expectsRejection(async () => { <add> await assert.rejects(async () => { <ide> const m = await createEmptyLinkedModule(); <ide> m.namespace; <ide> }, { <ide> async function checkModuleState() { <ide> <ide> // Check link() fails when the returned module is not valid. <ide> async function checkLinking() { <del> await expectsRejection(async () => { <add> await assert.rejects(async () => { <ide> const m = new SourceTextModule('import "foo";'); <ide> try { <ide> await m.link(common.mustCall(() => ({}))); <ide> } catch (err) { <ide> assert.strictEqual(m.linkingStatus, 'errored'); <ide> throw err; <ide> } <del> assert.fail('Unreachable'); <ide> }, { <ide> code: 'ERR_VM_MODULE_NOT_MODULE' <ide> }); <ide> <del> await expectsRejection(async () => { <add> await assert.rejects(async () => { <ide> const c = createContext({ a: 1 }); <ide> const foo = new SourceTextModule('', { context: c }); <ide> await foo.link(common.mustNotCall()); <ide> async function checkLinking() { <ide> assert.strictEqual(bar.linkingStatus, 'errored'); <ide> throw err; <ide> } <del> assert.fail('Unreachable'); <ide> }, { <ide> code: 'ERR_VM_MODULE_DIFFERENT_CONTEXT' <ide> }); <ide> <del> await expectsRejection(async () => { <add> await assert.rejects(async () => { <ide> const erroredModule = new SourceTextModule('import "foo";'); <ide> try { <ide> await erroredModule.link(common.mustCall(() => ({})));
1
Java
Java
remove test class added by mistake
aef39e8954a3bde51d20eab598741898d5f7eeaa
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/client/MyTest.java <del>/* <del> * Copyright 2002-2018 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del>package org.springframework.web.reactive.function.client; <del> <del>import java.io.IOException; <del>import java.time.Duration; <del>import java.util.function.Consumer; <del> <del>import io.netty.channel.group.ChannelGroup; <del>import io.netty.channel.group.DefaultChannelGroup; <del>import io.netty.util.concurrent.ImmediateEventExecutor; <del>import okhttp3.mockwebserver.MockResponse; <del>import okhttp3.mockwebserver.MockWebServer; <del>import okhttp3.mockwebserver.RecordedRequest; <del>import reactor.core.publisher.Mono; <del>import reactor.netty.FutureMono; <del>import reactor.netty.http.client.HttpClient; <del>import reactor.netty.resources.ConnectionProvider; <del>import reactor.netty.resources.LoopResources; <del>import reactor.netty.tcp.TcpClient; <del>import reactor.test.StepVerifier; <del> <del>import org.springframework.http.HttpHeaders; <del>import org.springframework.http.client.reactive.ClientHttpConnector; <del>import org.springframework.http.client.reactive.ReactorClientHttpConnector; <del>import org.springframework.mock.web.test.server.MockWebSession; <del> <del>import static org.junit.Assert.*; <del> <del>/** <del> * <del> * @author Rossen Stoyanchev <del> */ <del>public class MyTest { <del> <del> public static void main(String[] args) throws IOException { <del> <del>LoopResources resources = LoopResources.create("test-loop"); <del>ConnectionProvider provider = ConnectionProvider.elastic("test-pool"); <del>TcpClient tcpClient = TcpClient.create(provider).runOn(resources, false); <del>HttpClient httpClient = HttpClient.from(tcpClient); <del> <del>WebClient webClient = WebClient.builder() <del> .clientConnector(new ReactorClientHttpConnector(httpClient)) <del> .build(); <del> <del>makeCalls(webClient); <del> <del>provider.dispose(); <del>resources.dispose(); <del> <del>//Mono<Void> result1 = FutureMono.from(channelGroup.close()); <del>//Mono<Void> result2 = connProvider.disposeLater(); <del>//Mono<Void> result3 = loopResources.disposeLater(); <del>//Mono.whenDelayError(result1, result2, result3).block(Duration.ofSeconds(5)); <del> <del> System.in.read(); <del> System.exit(0); <del> <del> } <del> <del> private static void makeCalls(WebClient webClient) { <del> webClient.get().uri("http://httpbin.org/ip") <del> .retrieve() <del> .bodyToMono(String.class) <del> .block(Duration.ofSeconds(5)); <del> } <del> <del>}
1
Text
Text
add devise example to readme
3816fac41d44e79b2ada7de3289a7525ca45abfd
<ide><path>README.md <ide> Beware that currently the cable server will _not_ auto-reload any changes in the <ide> <ide> We'll get all this abstracted properly when the framework is integrated into Rails. <ide> <add>The WebSocket server doesn't have access to the session, but it has access to the cookies. This can be used when you need to handle authentication. You can see one way of doing that with Devise in this [article](http://www.rubytutorial.io/actioncable-devise-authentication). <ide> <ide> ## Dependencies <ide>
1
Javascript
Javascript
use the correct ripgrep path on asar packages
0a6a798c10f4a10d3502cd1f3f90bf9e1ba51acb
<ide><path>src/ripgrep-directory-searcher.js <ide> module.exports = class RipgrepDirectorySearcher { <ide> search (directories, regexp, options) { <ide> // Delay the require of vscode-ripgrep to not mess with the snapshot creation. <ide> if (!this.rgPath) { <del> this.rgPath = require('vscode-ripgrep').rgPath <add> this.rgPath = require('vscode-ripgrep').rgPath.replace(/\bapp\.asar\b/, 'app.asar.unpacked') <ide> } <ide> <ide> const paths = directories.map(d => d.getPath())
1
Text
Text
fix small grammatical error
e872bbc4ea0aad28a942bd1664c16d4d7564d6bd
<ide><path>docs/tutorials/essentials/part-8-rtk-query-advanced.md <ide> export const UserPage = ({ match }) => { <ide> <ide> There's a key difference with the memoized selector function we've created here. Normally, [selectors expect the entire Redux `state` as their first argument](../../usage/deriving-data-selectors.md), and extract or derive a value from `state`. However, in this case we're only dealing with the "result" value that is kept in the cache. The result object has a `data` field inside with the actual values we need, as well as some of the request metadata fields. <ide> <del>Our `selectFromResult` callback receives the `result` object containing the original request metadata and the `data` from the server, and should return some extracted or derived values. Because query hooks add an additional `refetch` method to whatever is returned here, it's preferably to always return an object from `selectFromResult` with the fields inside that you need. <add>Our `selectFromResult` callback receives the `result` object containing the original request metadata and the `data` from the server, and should return some extracted or derived values. Because query hooks add an additional `refetch` method to whatever is returned here, it's preferable to always return an object from `selectFromResult` with the fields inside that you need. <ide> <ide> Since `result` is being kept in the Redux store, we can't mutate it - we need to return a new object. The query hook will do a "shallow" comparison on this returned object, and only re-render the component if one of the fields has changed. We can optimize re-renders by only returning the specific fields needed by this component - if we don't need the rest of the metadata flags, we could omit them entirely. If you do need them, you can spread the original `result` value to include them in the output. <ide>
1
Text
Text
fix mismatch description
095cf332fe776e89deb2caf950fe1cc0522eec5d
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-typography-by-building-a-nutrition-label/615f42a021625f656101ef93.md <ide> Your new `span` element should have the `class` attribute set to `right`. <ide> assert(document.querySelector('span')?.classList?.contains('right')); <ide> ``` <ide> <del>Your `.right` element should have the text `2/3 cup (55g)`. <add>Your `span` element should have the text `2/3 cup (55g)`. <ide> <ide> ```js <ide> assert(document.querySelector('span')?.textContent === '2/3 cup (55g)');
1
Javascript
Javascript
remove log statement
49579d60d7fab4a66000f3d5038fafa69e584667
<ide><path>lib/ModuleNotFoundError.js <ide> <ide> class ModuleNotFoundError extends Error { <ide> constructor(module, err, dependencies) { <del> console.log(module, err, dependencies); <ide> super(); <ide> if(Error.hasOwnProperty("captureStackTrace")) { <ide> Error.captureStackTrace(this, this.constructor);
1
Ruby
Ruby
fix renamed branches with `brew tap --repair`
4bdc11ddc97ccf2c7b822e7485bab65f940a69e9
<ide><path>Library/Homebrew/cmd/tap.rb <ide> def tap <ide> <ide> if args.repair? <ide> Tap.each(&:link_completions_and_manpages) <add> Tap.each(&:fix_remote_configuration) <ide> elsif args.list_pinned? <ide> puts Tap.select(&:pinned?).map(&:name) <ide> elsif args.no_named? <ide><path>Library/Homebrew/extend/git_repository.rb <ide> def git_branch(safe: false) <ide> popen_git("rev-parse", "--abbrev-ref", "HEAD", safe: safe) <ide> end <ide> <add> # Change the name of a local branch <add> sig { params(old: String, new: String).void } <add> def git_rename_branch(old:, new:) <add> popen_git("branch", "-m", old, new) <add> end <add> <add> # Set an upstream branch for a local branch to track <add> sig { params(local: String, origin: String).void } <add> def git_branch_set_upstream(local:, origin:) <add> popen_git("branch", "-u", "origin/#{origin}", local) <add> end <add> <ide> # Gets the name of the default origin HEAD branch. <ide> sig { returns(T.nilable(String)) } <ide> def git_origin_branch <ide> def git_last_commit_date <ide> popen_git("show", "-s", "--format=%cd", "--date=short", "HEAD") <ide> end <ide> <add> # Returns true if the given branch exists on origin <add> sig { params(branch: String).returns(T::Boolean) } <add> def git_origin_has_branch?(branch) <add> popen_git("ls-remote", "--heads", "origin", branch).present? <add> end <add> <add> sig { void } <add> def git_origin_set_head_auto <add> popen_git("remote", "set-head", "origin", "--auto") <add> end <add> <ide> # Gets the full commit message of the specified commit, or of the HEAD commit if unspecified. <ide> sig { params(commit: String, safe: T::Boolean).returns(T.nilable(String)) } <ide> def git_commit_message(commit = "HEAD", safe: false) <ide><path>Library/Homebrew/tap.rb <ide> def link_completions_and_manpages <ide> end <ide> end <ide> <add> def fix_remote_configuration <add> return unless remote.include? "github.com" <add> <add> current_upstream_head = path.git_origin_branch <add> return if path.git_origin_has_branch? current_upstream_head <add> <add> safe_system "git", "-C", path, "fetch", "origin" <add> path.git_origin_set_head_auto <add> <add> new_upstream_head = path.git_origin_branch <add> path.git_rename_branch old: current_upstream_head, new: new_upstream_head <add> path.git_branch_set_upstream local: new_upstream_head, origin: new_upstream_head <add> <add> ohai "#{name}: changed default branch name from #{current_upstream_head} to #{new_upstream_head}" <add> end <add> <ide> # Uninstall this {Tap}. <ide> def uninstall(manual: false) <ide> require "descriptions"
3
Python
Python
remove double isinstance check in force_unicode
226a3e7e00357a5c055faa5138d8338243c4c2c9
<ide><path>django/utils/encoding.py <ide> def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'): <ide> # output should be. <ide> s = ' '.join([force_unicode(arg, encoding, strings_only, <ide> errors) for arg in s]) <del> elif not isinstance(s, six.text_type): <add> else: <ide> # Note: We use .decode() here, instead of six.text_type(s, encoding, <ide> # errors), so that if s is a SafeString, it ends up being a <ide> # SafeUnicode at the end.
1
Text
Text
fix path on macos link
ab1fb2f217aa94cac98105316c7f164bfb6251bd
<ide><path>docs/README.md <ide> In this directory you can only find very specific build and API level documentat <ide> <ide> Instructions for building Atom on various platforms from source. <ide> <del>* [macOS](./build-instructions/macos.md) <add>* [macOS](./build-instructions/macOS.md) <ide> * [Windows](./build-instructions/windows.md) <ide> * [Linux](./build-instructions/linux.md) <ide> * [FreeBSD](./build-instructions/freebsd.md)
1
Javascript
Javascript
replace anonymous function with arrow
fcbff6045e8474c31d6f4ffa23187a0334ec8468
<ide><path>test/parallel/test-pipe-file-to-http.js <ide> tmpdir.refresh(); <ide> const filename = path.join(tmpdir.path || '/tmp', 'big'); <ide> let count = 0; <ide> <del>const server = http.createServer(function(req, res) { <add>const server = http.createServer((req, res) => { <ide> let timeoutId; <ide> assert.strictEqual(req.method, 'POST'); <ide> req.pause(); <ide> <del> setTimeout(function() { <add> setTimeout(() => { <ide> req.resume(); <ide> }, 1000); <ide> <del> req.on('data', function(chunk) { <add> req.on('data', (chunk) => { <ide> count += chunk.length; <ide> }); <ide> <del> req.on('end', function() { <add> req.on('end', () => { <ide> if (timeoutId) { <ide> clearTimeout(timeoutId); <ide> } <ide> const server = http.createServer(function(req, res) { <ide> }); <ide> server.listen(0); <ide> <del>server.on('listening', function() { <add>server.on('listening', () => { <ide> common.createZeroFilledFile(filename); <ide> makeRequest(); <ide> }); <ide> function makeRequest() { <ide> assert.ifError(err); <ide> })); <ide> <del> req.on('response', function(res) { <add> req.on('response', (res) => { <ide> res.resume(); <del> res.on('end', function() { <add> res.on('end', () => { <ide> server.close(); <ide> }); <ide> }); <ide> } <ide> <del>process.on('exit', function() { <add>process.on('exit', () => { <ide> assert.strictEqual(count, 1024 * 10240); <ide> });
1
Text
Text
add link to notebook
3fab17fce810431698782f0725852614ad14af52
<ide><path>notebooks/README.md <ide> You can open any page of the documentation as a notebook in colab (there is a bu <ide> | [How to export model to ONNX](https://github.com/huggingface/notebooks/blob/main/examples/onnx-export.ipynb)| Highlight how to export and run inference workloads through ONNX | <ide> | [How to use Benchmarks](https://github.com/huggingface/notebooks/blob/main/examples/benchmark.ipynb)| How to benchmark models with transformers | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/benchmark.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/benchmark.ipynb)| <ide> | [Reformer](https://github.com/huggingface/blog/blob/main/notebooks/03_reformer.ipynb)| How Reformer pushes the limits of language modeling | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/patrickvonplaten/blog/blob/main/notebooks/03_reformer.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/patrickvonplaten/blog/blob/main/notebooks/03_reformer.ipynb)| <del>| [How to fine-tune a model on image classification](https://github.com/huggingface/notebooks/blob/main/examples/image_classification.ipynb) | Show how to preprocess the data and fine-tune any pretrained Vision model on Image Classification | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb)| <add>| [How to fine-tune a model on image classification (Torchvision)](https://github.com/huggingface/notebooks/blob/main/examples/image_classification.ipynb) | Show how to preprocess the data using Torchvision and fine-tune any pretrained Vision model on Image Classification | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb)| <add>| [How to fine-tune a model on image classification (Albumentations)](https://github.com/huggingface/notebooks/blob/main/examples/image_classification_albumentations.ipynb) | Show how to preprocess the data using Albumentations and fine-tune any pretrained Vision model on Image Classification | [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification_albumentations.ipynb)| [![Open in AWS Studio](https://studiolab.sagemaker.aws/studiolab.svg)](https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/examples/image_classification_albumentations.ipynb)| <ide> <ide> ### TensorFlow Examples <ide>
1
Java
Java
fix exception in antpathmatcher for leading *
63f01c851fe9b0dfc8e3df6c9428b19b471ee99d
<ide><path>spring-core/src/main/java/org/springframework/util/AntPathMatcher.java <ide> else if (this.pattern.charAt(pos) == '*') { <ide> this.doubleWildcards++; <ide> pos += 2; <ide> } <del> else if (!this.pattern.substring(pos - 1).equals(".*")) { <add> else if (pos > 0 && !this.pattern.substring(pos - 1).equals(".*")) { <ide> this.singleWildcards++; <ide> pos++; <ide> } <ide><path>spring-core/src/test/java/org/springframework/util/AntPathMatcherTests.java <ide> public void patternComparator() { <ide> <ide> // longer is better <ide> assertEquals(1, comparator.compare("/hotels", "/hotels2")); <add> <add> //SPR-13139 <add> assertEquals(-1, comparator.compare("*", "*/**")); <add> assertEquals(1, comparator.compare("*/**", "*")); <ide> } <ide> <ide> @Test
2
Javascript
Javascript
accept either kind of nan
61935bc167cc2de57c6417bd12493775dc9c1b81
<ide><path>test/simple/test-writedouble.js <ide> function test(clazz) { <ide> <ide> buffer.writeDoubleBE(NaN, 0); <ide> buffer.writeDoubleLE(NaN, 8); <del> ASSERT.equal(0x7F, buffer[0]); <add> // Darwin ia32 does the other kind of NaN. <add> // Compiler bug. No one really cares. <add> ASSERT(0x7F === buffer[0] || 0xFF === buffer[0]); <ide> ASSERT.equal(0xF8, buffer[1]); <ide> ASSERT.equal(0x00, buffer[2]); <ide> ASSERT.equal(0x00, buffer[3]); <ide> function test(clazz) { <ide> ASSERT.equal(0x00, buffer[12]); <ide> ASSERT.equal(0x00, buffer[13]); <ide> ASSERT.equal(0xF8, buffer[14]); <del> ASSERT.equal(0x7F, buffer[15]); <add> // Darwin ia32 does the other kind of NaN. <add> // Compiler bug. No one really cares. <add> ASSERT(0x7F === buffer[15] || 0xFF === buffer[15]); <ide> ASSERT.ok(isNaN(buffer.readDoubleBE(0))); <ide> ASSERT.ok(isNaN(buffer.readDoubleLE(8))); <ide> } <ide><path>test/simple/test-writefloat.js <ide> function test(clazz) { <ide> <ide> buffer.writeFloatBE(-Infinity, 0); <ide> buffer.writeFloatLE(-Infinity, 4); <del> ASSERT.equal(0xFF, buffer[0]); <add> // Darwin ia32 does the other kind of NaN. <add> // Compiler bug. No one really cares. <add> ASSERT(0xFF === buffer[0] || 0x7F === buffer[0]); <ide> ASSERT.equal(0x80, buffer[1]); <ide> ASSERT.equal(0x00, buffer[2]); <ide> ASSERT.equal(0x00, buffer[3]); <ide> function test(clazz) { <ide> <ide> buffer.writeFloatBE(NaN, 0); <ide> buffer.writeFloatLE(NaN, 4); <del> ASSERT.equal(0x7F, buffer[0]); <add> // Darwin ia32 does the other kind of NaN. <add> // Compiler bug. No one really cares. <add> ASSERT(0x7F === buffer[0] || 0xFF === buffer[0]); <ide> ASSERT.equal(0xc0, buffer[1]); <ide> ASSERT.equal(0x00, buffer[2]); <ide> ASSERT.equal(0x00, buffer[3]); <ide> ASSERT.equal(0x00, buffer[4]); <ide> ASSERT.equal(0x00, buffer[5]); <ide> ASSERT.equal(0xc0, buffer[6]); <del> ASSERT.equal(0x7F, buffer[7]); <add> // Darwin ia32 does the other kind of NaN. <add> // Compiler bug. No one really cares. <add> ASSERT(0x7F === buffer[7] || 0xFF === buffer[7]); <ide> ASSERT.ok(isNaN(buffer.readFloatBE(0))); <ide> ASSERT.ok(isNaN(buffer.readFloatLE(4))); <ide> }
2
PHP
PHP
allow 1 second of slip
473d55f091811e8372f83f5f945d9edb58d3b18b
<ide><path>lib/Cake/Test/Case/Model/Datasource/Session/DatabaseSessionTest.php <ide> public function testWrite() { <ide> 'Session' => array( <ide> 'id' => 'foo', <ide> 'data' => 'Some value', <del> 'expires' => time() + (Configure::read('Session.timeout') * 60) <ide> ) <ide> ); <add> $expires = $result['Session']['expires']; <add> unset($result['Session']['expires']); <ide> $this->assertEquals($expected, $result); <add> <add> $expected = time() + (Configure::read('Session.timeout') * 60); <add> $this->assertWithinMargin($expires, $expected, 1); <ide> } <ide> <ide> /**
1
Javascript
Javascript
remove unnecessary line from cubecamera
af91ad963f646d6ad63015a09034424b6f2fdd07
<ide><path>src/cameras/CubeCamera.js <del>import { LinearEncoding, NoToneMapping } from '../constants.js'; <add>import { NoToneMapping } from '../constants.js'; <ide> import { Object3D } from '../core/Object3D.js'; <ide> import { Vector3 } from '../math/Vector3.js'; <ide> import { PerspectiveCamera } from './PerspectiveCamera.js'; <ide> class CubeCamera extends Object3D { <ide> const currentToneMapping = renderer.toneMapping; <ide> const currentXrEnabled = renderer.xr.enabled; <ide> <del> renderer.outputEncoding = LinearEncoding; <ide> renderer.toneMapping = NoToneMapping; <ide> renderer.xr.enabled = false; <ide>
1
Javascript
Javascript
reset goal column on all cursor changes
f60f1692fd7cb8d2733c24d662fe78213d3bc20e
<ide><path>spec/text-editor-spec.js <ide> describe('TextEditor', () => { <ide> }) <ide> }) <ide> }) <add> <add> it("clears the goal column", () => { <add> editor.setText('first\n\nthird') <add> editor.setCursorScreenPosition([0, 3]) <add> editor.moveDown() <add> editor.moveToFirstCharacterOfLine() <add> editor.moveDown() <add> expect(editor.getCursorBufferPosition()).toEqual([2, 0]) <add> }) <ide> }) <ide> <ide> describe('.moveToBeginningOfWord()', () => { <ide><path>src/cursor.js <ide> class Cursor extends Model { <ide> <ide> // Public: Moves the cursor to the bottom of the buffer. <ide> moveToBottom () { <add> const column = this.goalColumn <ide> this.setBufferPosition(this.editor.getEofBufferPosition()) <add> this.goalColumn = column <ide> } <ide> <ide> // Public: Moves the cursor to the beginning of the line. <ide> class Cursor extends Model { <ide> changePosition (options, fn) { <ide> this.clearSelection({autoscroll: false}) <ide> fn() <add> this.goalColumn = null <ide> const autoscroll = (options && options.autoscroll != null) <ide> ? options.autoscroll <ide> : this.isLastCursor()
2
Mixed
Javascript
add e2e tests for array object props
958b7aa9aa793046f28208e9a9ddb0a24f6f28f6
<ide><path>packages/react-native-codegen/buck_tests/java/ArrayPropsNativeComponentViewManager.java <ide> public void setPoints(ViewGroup view, ReadableArray value) {} <ide> <ide> @Override <ide> public void setSizes(ViewGroup view, ReadableArray value) {} <add> <add> @Override <add> public void setObject(ViewGroup view, ReadableArray value) {} <ide> } <ide><path>packages/react-native-codegen/e2e/__test_fixtures__/components/ArrayPropsNativeComponent.js <ide> type NativeProps = $ReadOnly<{| <ide> srcs?: $ReadOnlyArray<ImageSource>, <ide> points?: $ReadOnlyArray<PointValue>, <ide> sizes?: WithDefault<$ReadOnlyArray<'small' | 'large'>, 'small'>, <add> object?: $ReadOnlyArray<$ReadOnly<{|prop: string|}>>, <ide> |}>; <ide> <ide> export default (codegenNativeComponent<NativeProps>(
2
Text
Text
add multiprocessing section
c9e1a9ac174abe4c8113518955e56af6ea2c5a8d
<ide><path>website/docs/usage/processing-pipelines.md <ide> have to call `list()` on it first: <ide> <ide> </Infobox> <ide> <add>### Multiprocessing <add> <add>spaCy includes built-in support for multiprocessing with <add>[`nlp.pipe`](/api/language#pipe) using the `n_process` option: <add> <add>```python <add># Multiprocessing with 4 processes <add>docs = nlp.pipe(texts, n_process=4) <add> <add># With as many processes as CPUs (use with caution!) <add>docs = nlp.pipe(texts, n_process=-1) <add>``` <add> <add>Depending on your platform, starting many processes with multiprocessing can <add>add a lot of overhead. In particular, the default start method `spawn` used in <add>macOS/OS X (as of Python 3.8) and in Windows can be slow for larger models <add>because the model data is copied in memory for each new process. See the <add>[Python docs on <add>multiprocessing](https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods) <add>for further details. <add> <add>For shorter tasks and in particular with `spawn`, it can be faster to use a <add>smaller number of processes with a larger batch size. The optimal `batch_size` <add>setting will depend on the pipeline components, the length of your documents, <add>the number of processes and how much memory is available. <add> <add>```python <add># Default batch size is `nlp.batch_size` (typically 1000) <add>docs = nlp.pipe(texts, n_process=2, batch_size=2000) <add>``` <add> <add><Infobox title="Multiprocessing on GPU" variant="warning"> <add> <add>Multiprocessing is not generally recommended on GPU because RAM is too limited. <add>If you want to try it out, be aware that it is only possible using `spawn` due <add>to limitations in CUDA. <add> <add></Infobox> <add> <add><Infobox title="Multiprocessing with transformer models" variant="warning"> <add> <add>In Linux, transformer models may hang or deadlock with multiprocessing due to an <add>[issue in PyTorch](https://github.com/pytorch/pytorch/issues/17199). One <add>suggested workaround is to use `spawn` instead of `fork` and another is to <add>limit the number of threads before loading any models using <add>`torch.set_num_threads(1)`. <add> <add></Infobox> <add> <ide> ## Pipelines and built-in components {#pipelines} <ide> <ide> spaCy makes it very easy to create your own pipelines consisting of reusable
1
Python
Python
use logger.warning instead of logger.warn
cabd4ae5b1a0a764c821aa60299d87061b9d4525
<ide><path>spacy/pipeline/lemmatizer.py <ide> def rule_lemmatize(self, token: Token) -> List[str]: <ide> univ_pos = token.pos_.lower() <ide> if univ_pos in ("", "eol", "space"): <ide> if univ_pos == "": <del> logger.warn(Warnings.W108.format(text=string)) <add> logger.warning(Warnings.W108.format(text=string)) <ide> return [string.lower()] <ide> # See Issue #435 for example of where this logic is requied. <ide> if self.is_base_form(token): <ide><path>spacy/tests/pipeline/test_lemmatizer.py <ide> def test_lemmatizer_config(nlp): <ide> # warning if no POS assigned <ide> doc = nlp.make_doc("coping") <ide> logger = logging.getLogger("spacy") <del> with mock.patch.object(logger, "warn") as mock_warn: <add> with mock.patch.object(logger, "warning") as mock_warning: <ide> doc = lemmatizer(doc) <del> mock_warn.assert_called_once() <add> mock_warning.assert_called_once() <ide> <ide> # works with POS <ide> doc = nlp.make_doc("coping")
2
Text
Text
fix indentation in changelog [ci skip]
5755f57f3e887df93e11c4b3efb8bf21226744cc
<ide><path>actionpack/CHANGELOG.md <ide> <ide> *Michael J Coyne* <ide> <del>* Use Capybara registered `:puma` server config. <add>* Use Capybara registered `:puma` server config. <ide> <ide> The Capybara registered `:puma` server ensures the puma server is run in process so <ide> connection sharing and open request detection work correctly by default. <ide> <ide> *Thomas Walpole* <ide> <del>* Cookies `:expires` option supports `ActiveSupport::Duration` object. <add>* Cookies `:expires` option supports `ActiveSupport::Duration` object. <ide> <ide> cookies[:user_name] = { value: "assain", expires: 1.hour } <ide> cookies[:key] = { value: "a yummy cookie", expires: 6.months } <ide> <ide> *Assain Jaleel* <ide> <del>* Enforce signed/encrypted cookie expiry server side. <add>* Enforce signed/encrypted cookie expiry server side. <ide> <ide> Rails can thwart attacks by malicious clients that don't honor a cookie's expiry. <ide>
1
Javascript
Javascript
add spec for appstate
d9930897a8ab80fb49628efb2a08d1e0c4d4fee6
<ide><path>Libraries/AppState/AppState.js <ide> <ide> const EventEmitter = require('../vendor/emitter/EventEmitter'); <ide> const NativeEventEmitter = require('../EventEmitter/NativeEventEmitter'); <del>const NativeModules = require('../BatchedBridge/NativeModules'); <del>const RCTAppState = NativeModules.AppState; <add>import NativeAppState from './NativeAppState'; <ide> <ide> const logError = require('../Utilities/logError'); <ide> const invariant = require('invariant'); <ide> class AppState extends NativeEventEmitter { <ide> isAvailable: boolean; <ide> <ide> constructor() { <del> super(RCTAppState); <add> super(NativeAppState); <ide> <ide> this.isAvailable = true; <ide> this._eventHandlers = { <ide> change: new Map(), <ide> memoryWarning: new Map(), <ide> }; <ide> <del> this.currentState = RCTAppState.initialAppState; <add> this.currentState = NativeAppState.getConstants().initialAppState; <ide> <ide> let eventUpdated = false; <ide> <ide> class AppState extends NativeEventEmitter { <ide> // TODO: see above - this request just populates the value of `currentState` <ide> // when the module is first initialized. Would be better to get rid of the <ide> // prop and expose `getCurrentAppState` method directly. <del> RCTAppState.getCurrentAppState(appStateData => { <add> NativeAppState.getCurrentAppState(appStateData => { <ide> // It's possible that the state will have changed here & listeners need to be notified <ide> if (!eventUpdated && this.currentState !== appStateData.app_state) { <ide> this.currentState = appStateData.app_state; <ide> class MissingNativeAppStateShim extends EventEmitter { <ide> // This module depends on the native `RCTAppState` module. If you don't include it, <ide> // `AppState.isAvailable` will return `false`, and any method calls will throw. <ide> // We reassign the class variable to keep the autodoc generator happy. <del>if (RCTAppState) { <add>if (NativeAppState) { <ide> AppState = new AppState(); <ide> } else { <ide> AppState = new MissingNativeAppStateShim(); <ide><path>Libraries/AppState/NativeAppState.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> +getConstants: () => {| <add> initialAppState: string, <add> |}; <add> +getCurrentAppState: ( <add> success: (appState: {|app_state: string|}) => void, <add> failure: (error: Object) => void, <add> ) => void; <add> <add> // Events <add> +addListener: (eventName: string) => void; <add> +removeListeners: (count: number) => void; <add>} <add> <add>export default TurboModuleRegistry.getEnforcing<Spec>('AppState');
2
Javascript
Javascript
add missing export default on favicon
e903a0c27924b3ac0ee141fc7f1c15945d03e233
<ide><path>glances/outputs/static/js/services/favicon.js <ide> <ide> import Favico from 'favico.js'; <del>// import angular from 'angular'; <ide> <del>angular.module('glancesApp').service('favicoService', favicoService); <add>export default angular.module('glancesApp').service('favicoService', favicoService); <ide> <ide> function favicoService () { <ide>
1
Java
Java
fix javadoc link in observables/package-info
53d5a235f63ca143c11571cd538ad927c0f8f3ad
<ide><path>src/main/java/io/reactivex/observables/package-info.java <ide> <ide> /** <ide> * Classes supporting the Observable base reactive class: <del> * {@link io.reactivex.observable.ConnectableObservable} and <del> * {@link io.reactivex.observable.GroupedObservable}. <add> * {@link io.reactivex.observables.ConnectableObservable} and <add> * {@link io.reactivex.observables.GroupedObservable}. <ide> */ <ide> package io.reactivex.observables;
1
Python
Python
add cli argument for configuring labels
7f5367e0b18a56448dde3c4504278e57e6f4beae
<ide><path>examples/run_ner.py <ide> def set_seed(args): <ide> torch.cuda.manual_seed_all(args.seed) <ide> <ide> <del>def train(args, train_dataset, model, tokenizer, pad_token_label_id): <add>def train(args, train_dataset, model, tokenizer, labels, pad_token_label_id): <ide> """ Train the model """ <ide> if args.local_rank in [-1, 0]: <ide> tb_writer = SummaryWriter() <ide> def train(args, train_dataset, model, tokenizer, pad_token_label_id): <ide> if args.local_rank in [-1, 0] and args.logging_steps > 0 and global_step % args.logging_steps == 0: <ide> # Log metrics <ide> if args.local_rank == -1 and args.evaluate_during_training: # Only evaluate when single GPU otherwise metrics may not average well <del> results = evaluate(args, model, tokenizer, pad_token_label_id) <add> results = evaluate(args, model, tokenizer, labels, pad_token_label_id) <ide> for key, value in results.items(): <ide> tb_writer.add_scalar("eval_{}".format(key), value, global_step) <ide> tb_writer.add_scalar("lr", scheduler.get_lr()[0], global_step) <ide> def train(args, train_dataset, model, tokenizer, pad_token_label_id): <ide> output_dir = os.path.join(args.output_dir, "checkpoint-{}".format(global_step)) <ide> if not os.path.exists(output_dir): <ide> os.makedirs(output_dir) <del> model_to_save = model.module if hasattr(model, <del> "module") else model # Take care of distributed/parallel training <add> model_to_save = model.module if hasattr(model, "module") else model # Take care of distributed/parallel training <ide> model_to_save.save_pretrained(output_dir) <ide> torch.save(args, os.path.join(output_dir, "training_args.bin")) <ide> logger.info("Saving model checkpoint to %s", output_dir) <ide> def train(args, train_dataset, model, tokenizer, pad_token_label_id): <ide> return global_step, tr_loss / global_step <ide> <ide> <del>def evaluate(args, model, tokenizer, pad_token_label_id, prefix=""): <del> eval_dataset = load_and_cache_examples(args, tokenizer, pad_token_label_id, evaluate=True) <add>def evaluate(args, model, tokenizer, labels, pad_token_label_id, prefix=""): <add> eval_dataset = load_and_cache_examples(args, tokenizer, labels, pad_token_label_id, evaluate=True) <ide> <ide> args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu) <ide> # Note that DistributedSampler samples randomly <ide> def evaluate(args, model, tokenizer, pad_token_label_id, prefix=""): <ide> eval_loss = eval_loss / nb_eval_steps <ide> preds = np.argmax(preds, axis=2) <ide> <del> label_map = {i: label for i, label in enumerate(get_labels())} <add> label_map = {i: label for i, label in enumerate(labels)} <ide> <ide> out_label_list = [[] for _ in range(out_label_ids.shape[0])] <ide> preds_list = [[] for _ in range(out_label_ids.shape[0])] <ide> def evaluate(args, model, tokenizer, pad_token_label_id, prefix=""): <ide> return results <ide> <ide> <del>def load_and_cache_examples(args, tokenizer, pad_token_label_id, evaluate=False): <add>def load_and_cache_examples(args, tokenizer, labels, pad_token_label_id, evaluate=False): <ide> if args.local_rank not in [-1, 0] and not evaluate: <ide> torch.distributed.barrier() # Make sure only the first process in distributed training process the dataset, and the others will use the cache <ide> <ide> def load_and_cache_examples(args, tokenizer, pad_token_label_id, evaluate=False) <ide> features = torch.load(cached_features_file) <ide> else: <ide> logger.info("Creating features from dataset file at %s", args.data_dir) <del> label_list = get_labels() <ide> examples = read_examples_from_file(args.data_dir, evaluate=evaluate) <del> features = convert_examples_to_features(examples, label_list, args.max_seq_length, tokenizer, <add> features = convert_examples_to_features(examples, labels, args.max_seq_length, tokenizer, <ide> cls_token_at_end=bool(args.model_type in ["xlnet"]), <ide> # xlnet has a cls token at the end <ide> cls_token=tokenizer.cls_token, <ide> def main(): <ide> help="The output directory where the model predictions and checkpoints will be written.") <ide> <ide> ## Other parameters <add> parser.add_argument("--labels", default="", type=str, <add> help="Path to a file containing all labels. If not specified, CoNLL-2003 labels are used.") <ide> parser.add_argument("--config_name", default="", type=str, <ide> help="Pretrained config name or path if not the same as model_name") <ide> parser.add_argument("--tokenizer_name", default="", type=str, <ide> def main(): <ide> set_seed(args) <ide> <ide> # Prepare CONLL-2003 task <del> label_list = get_labels() <del> num_labels = len(label_list) <add> labels = get_labels(args.labels) <add> num_labels = len(labels) <ide> # Use cross entropy ignore index as padding label id so that only real label ids contribute to the loss later <ide> pad_token_label_id = CrossEntropyLoss().ignore_index <ide> <ide> def main(): <ide> <ide> # Training <ide> if args.do_train: <del> train_dataset = load_and_cache_examples(args, tokenizer, pad_token_label_id, evaluate=False) <del> global_step, tr_loss = train(args, train_dataset, model, tokenizer, pad_token_label_id) <add> train_dataset = load_and_cache_examples(args, tokenizer, labels, pad_token_label_id, evaluate=False) <add> global_step, tr_loss = train(args, train_dataset, model, tokenizer, labels, pad_token_label_id) <ide> logger.info(" global_step = %s, average loss = %s", global_step, tr_loss) <ide> <ide> # Saving best-practices: if you use defaults names for the model, you can reload it using from_pretrained() <ide> def main(): <ide> global_step = checkpoint.split("-")[-1] if len(checkpoints) > 1 else "" <ide> model = model_class.from_pretrained(checkpoint) <ide> model.to(args.device) <del> result = evaluate(args, model, tokenizer, pad_token_label_id, prefix=global_step) <add> result = evaluate(args, model, tokenizer, labels, pad_token_label_id, prefix=global_step) <ide> if global_step: <ide> result = {"{}_{}".format(global_step, k): v for k, v in result.items()} <ide> results.update(result) <ide><path>examples/utils_ner.py <ide> def convert_examples_to_features(examples, <ide> return features <ide> <ide> <del>def get_labels(): <del> return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] <add>def get_labels(path): <add> if path: <add> with open(path, "r") as f: <add> labels = f.read().splitlines() <add> if "O" not in labels: <add> labels = ["O"] + labels <add> return labels <add> else: <add> return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"]
2
Javascript
Javascript
fix messages and use return to skip tests
80a1cf742599ef52235171e2e32f615b6b611007
<ide><path>test/disabled/tls_server.js <ide> var certPem = fs.readFileSync(common.fixturesDir + '/cert.pem'); <ide> try { <ide> var credentials = crypto.createCredentials({key: keyPem, cert: certPem}); <ide> } catch (e) { <del> console.log('Not compiled with OPENSSL support.'); <del> process.exit(); <add> console.log('1..0 # Skipped: node compiled without OpenSSL.'); <add> return; <ide> } <ide> var i = 0; <ide> var server = net.createServer(function(connection) { <ide><path>test/parallel/test-child-process-fork-dgram.js <ide> var assert = require('assert'); <ide> var common = require('../common'); <ide> <ide> if (common.isWindows) { <del> console.error('Sending dgram sockets to child processes not supported'); <del> process.exit(0); <add> console.log('1..0 # Skipped: Sending dgram sockets to child processes is ' + <add> 'not supported'); <add> return; <ide> } <ide> <ide> if (process.argv[2] === 'child') { <ide><path>test/parallel/test-cluster-bind-privileged-port.js <ide> if (common.isWindows) { <ide> } <ide> <ide> if (process.getuid() === 0) { <del> console.log('Do not run this test as root.'); <del> process.exit(0); <add> console.log('1..0 # Skipped: Test is not supposed to be run as root.'); <add> return; <ide> } <ide> <ide> if (cluster.isMaster) { <ide><path>test/parallel/test-cluster-dgram-1.js <ide> var dgram = require('dgram'); <ide> <ide> <ide> if (common.isWindows) { <del> console.warn('dgram clustering is currently not supported on windows.'); <del> process.exit(0); <add> console.log('1..0 # Skipped: dgram clustering is currently not supported ' + <add> 'on windows.'); <add> return; <ide> } <ide> <ide> if (cluster.isMaster) <ide><path>test/parallel/test-cluster-dgram-2.js <ide> var dgram = require('dgram'); <ide> <ide> <ide> if (common.isWindows) { <del> console.warn('dgram clustering is currently not supported on windows.'); <del> process.exit(0); <add> console.log('1..0 # Skipped: dgram clustering is currently not supported ' + <add> 'on windows.'); <add> return; <ide> } <ide> <ide> if (cluster.isMaster) <ide><path>test/parallel/test-cluster-http-pipe.js <ide> const assert = require('assert'); <ide> const cluster = require('cluster'); <ide> const http = require('http'); <ide> <del>// It is not possible to send pipe handles over the IPC pipe on Windows. <ide> if (common.isWindows) { <del> process.exit(0); <add> console.log('1..0 # Skipped: It is not possible to send pipe handles over ' + <add> 'the IPC pipe on Windows'); <add> return; <ide> } <ide> <ide> if (cluster.isMaster) { <ide><path>test/parallel/test-dh-padding.js <ide> var assert = require('assert'); <ide> try { <ide> var crypto = require('crypto'); <ide> } catch (e) { <del> console.log('Not compiled with OPENSSL support.'); <del> process.exit(); <add> console.log('1..0 # Skipped: node compiled without OpenSSL.'); <add> return; <ide> } <ide> <ide> var prime = 'c51f7bf8f0e1cf899243cdf408b1bc7c09c010e33ef7f3fbe5bd5feaf906113b'; <ide><path>test/parallel/test-domain-crypto.js <ide> try { <ide> var crypto = require('crypto'); <ide> } catch (e) { <del> console.log('Not compiled with OPENSSL support.'); <del> process.exit(); <add> console.log('1..0 # Skipped: node compiled without OpenSSL.'); <add> return; <ide> } <ide> <ide> // the missing var keyword is intentional <ide><path>test/parallel/test-process-remove-all-signal-listeners.js <ide> const spawn = require('child_process').spawn; <ide> const common = require('../common'); <ide> <ide> if (common.isWindows) { <del> // Win32 doesn't have signals, just a kindof emulation, insufficient <del> // for this test to apply. <add> console.log('1..0 # Skipped: Win32 doesn\'t have signals, just a kind of ' + <add> 'emulation, insufficient for this test to apply.'); <ide> return; <ide> } <ide> <ide><path>test/parallel/test-signal-handler.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> <del>// SIGUSR1 and SIGHUP are not supported on Windows <ide> if (common.isWindows) { <del> process.exit(0); <add> console.log('1..0 # Skipped: SIGUSR1 and SIGHUP signals are not supported'); <add> return; <ide> } <ide> <ide> console.log('process.pid: ' + process.pid); <ide><path>test/parallel/test-tls-npn-server-client.js <ide> if (!process.features.tls_npn) { <ide> console.log('1..0 # Skipped: node compiled without OpenSSL or ' + <ide> 'with old OpenSSL version.'); <del> process.exit(0); <add> return; <ide> } <ide> <ide> var common = require('../common'), <ide><path>test/parallel/test-tls-ocsp-callback.js <ide> var common = require('../common'); <ide> if (!process.features.tls_ocsp) { <ide> console.log('1..0 # Skipped: node compiled without OpenSSL or ' + <ide> 'with old OpenSSL version.'); <del> process.exit(0); <add> return; <ide> } <ide> if (!common.opensslCli) { <ide> console.log('1..0 # Skipped: node compiled without OpenSSL CLI.'); <ide><path>test/parallel/test-tls-sni-option.js <ide> if (!process.features.tls_sni) { <ide> console.log('1..0 # Skipped: node compiled without OpenSSL or ' + <ide> 'with old OpenSSL version.'); <del> process.exit(0); <add> return; <ide> } <ide> <ide> var common = require('../common'), <ide><path>test/parallel/test-tls-sni-server-client.js <ide> if (!process.features.tls_sni) { <ide> console.log('1..0 # Skipped: node compiled without OpenSSL or ' + <ide> 'with old OpenSSL version.'); <del> process.exit(0); <add> return; <ide> } <ide> <ide> var common = require('../common'), <ide><path>test/pummel/test-crypto-dh.js <ide> var assert = require('assert'); <ide> try { <ide> var crypto = require('crypto'); <ide> } catch (e) { <del> console.log('Not compiled with OPENSSL support.'); <del> process.exit(); <add> console.log('1..0 # Skipped: node compiled without OpenSSL.'); <add> return; <ide> } <ide> <ide> assert.throws(function() { <ide><path>test/sequential/test-regress-GH-3542.js <ide> var common = require('../common'), <ide> <ide> // This test is only relevant on Windows. <ide> if (!common.isWindows) { <del> return process.exit(0); <add> console.log('1..0 # Skipped: Windows specific test.'); <add> return; <ide> } <ide> <ide> function test(p) {
16
Mixed
Go
set default for unix
fe8fa85074a62241640e5c2d9d2501c354517efc
<ide><path>cliconfig/credentials/default_store_linux.go <add>package credentials <add> <add>const defaultCredentialsStore = "secretservice" <add><path>cliconfig/credentials/default_store_unsupported.go <del><path>cliconfig/credentials/default_store_unix.go <del>// +build !windows,!darwin <add>// +build !windows,!darwin,!linux <ide> <ide> package credentials <ide> <ide><path>docs/reference/commandline/login.md <ide> program to be in the client's host `$PATH`. <ide> This is the list of currently available credentials helpers and where <ide> you can download them from: <ide> <add>- D-Bus Secret Service: https://github.com/docker/docker-credential-helpers/releases <ide> - Apple OS X keychain: https://github.com/docker/docker-credential-helpers/releases <ide> - Microsoft Windows Credential Manager: https://github.com/docker/docker-credential-helpers/releases <ide>
3
Javascript
Javascript
improve hotmodulereplacementplugin performance
f2e5c1e9e817cc1bd442f69f0ea8b207a450093f
<ide><path>lib/HotModuleReplacementPlugin.js <ide> const ModuleHotDeclineDependency = require("./dependencies/ModuleHotDeclineDepen <ide> const ConstDependency = require("./dependencies/ConstDependency"); <ide> const NullFactory = require("./NullFactory"); <ide> const ParserHelpers = require("./ParserHelpers"); <del>const createHash = require("./util/createHash"); <ide> <ide> module.exports = class HotModuleReplacementPlugin { <ide> constructor(options) { <ide> module.exports = class HotModuleReplacementPlugin { <ide> records.moduleHashs = {}; <ide> for (const module of compilation.modules) { <ide> const identifier = module.identifier(); <del> const hash = createHash(compilation.outputOptions.hashFunction); <del> module.updateHash(hash); <del> records.moduleHashs[identifier] = hash.digest("hex"); <add> records.moduleHashs[identifier] = module.hash; <ide> } <ide> records.chunkHashs = {}; <ide> for (const chunk of compilation.chunks) { <ide> module.exports = class HotModuleReplacementPlugin { <ide> return; <ide> for (const module of compilation.modules) { <ide> const identifier = module.identifier(); <del> let hash = createHash(compilation.outputOptions.hashFunction); <del> module.updateHash(hash); <del> hash = hash.digest("hex"); <add> let hash = module.hash; <ide> module.hotUpdate = records.moduleHashs[identifier] !== hash; <ide> } <ide> const hotUpdateMainContent = {
1
Python
Python
fix tfwav2vec2 specaugment
3886104574635ae111d4e05b1320ce9ac1e44b02
<ide><path>src/transformers/models/wav2vec2/modeling_tf_wav2vec2.py <ide> def _compute_mask_indices( <ide> tf.ones_like(spec_aug_mask_idxs), spec_aug_mask_idxs, spec_aug_mask.shape <ide> ) <ide> <del> return tf.cast(spec_aug_mask, tf.float32) <add> return spec_aug_mask <ide> <ide> <ide> def _expand_mask(mask: tf.Tensor, tgt_len: Optional[int] = None, past_key_values_length: int = 0): <ide> def _conv_out_length(input_length, kernel_size, stride): <ide> <ide> return input_lengths <ide> <del> def _mask_hidden_states( <del> self, hidden_states: tf.Tensor, mask_time_indices: Optional[tf.Tensor] = None, training: bool = False <del> ): <add> def _mask_hidden_states(self, hidden_states: tf.Tensor, mask_time_indices: Optional[tf.Tensor] = None): <ide> """ <ide> Masks extracted features along time axis and/or along feature axis according to `SpecAugment <ide> <https://arxiv.org/abs/1904.08779>`__ . <ide> """ <add> batch_size, sequence_length, hidden_size = shape_list(hidden_states) <ide> <ide> # `config.apply_spec_augment` can set masking to False <ide> if not getattr(self.config, "apply_spec_augment", True): <ide> return hidden_states <ide> <ide> if mask_time_indices is not None: <ide> # apply SpecAugment along time axis with given mask_time_indices <del> hidden_states = tf.tensor_scatter_nd_update(hidden_states, mask_time_indices, self.masked_spec_embed) <del> elif self.config.mask_time_prob > 0 and training: <del> # generate indices & apply SpecAugment along time axis <del> batch_size, sequence_length, hidden_size = hidden_states.shape <add> hidden_states = tf.where( <add> tf.cast(mask_time_indices[:, :, tf.newaxis], tf.bool), <add> self.masked_spec_embed[tf.newaxis, tf.newaxis, :], <add> hidden_states, <add> ) <ide> <add> elif self.config.mask_time_prob > 0: <add> # generate indices & apply SpecAugment along time axis <ide> mask_time_indices = _compute_mask_indices( <ide> (batch_size, sequence_length), <del> self.config.mask_time_prob, <del> self.config.mask_time_length, <add> mask_prob=self.config.mask_time_prob, <add> mask_length=self.config.mask_time_length, <ide> min_masks=2, <ide> ) <del> hidden_states = tf.tensor_scatter_nd_update(hidden_states, mask_time_indices, self.masked_spec_embed) <add> hidden_states = tf.where( <add> tf.cast(mask_time_indices[:, :, tf.newaxis], tf.bool), <add> self.masked_spec_embed[tf.newaxis, tf.newaxis, :], <add> hidden_states, <add> ) <ide> <ide> # apply SpecAugment along feature axis <del> if self.config.mask_feature_prob > 0 and training: <add> if self.config.mask_feature_prob > 0: <ide> mask_feature_indices = _compute_mask_indices( <ide> (batch_size, hidden_size), <ide> mask_prob=self.config.mask_feature_prob, <ide> mask_length=self.config.mask_feature_length, <ide> ) <del> hidden_states = tf.tensor_scatter_nd_update(hidden_states, mask_feature_indices, self.masked_spec_embed) <add> hidden_states = tf.where(mask_feature_indices[:, tf.newaxis, :], hidden_states, 0) <ide> <ide> return hidden_states <ide> <ide> def call( <ide> position_ids: Optional[tf.Tensor] = None, <ide> head_mask: Optional[tf.Tensor] = None, <ide> inputs_embeds: Optional[tf.Tensor] = None, <del> output_attentions: Optional[tf.Tensor] = None, <del> output_hidden_states: Optional[tf.Tensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <ide> return_dict: Optional[bool] = None, <ide> training: bool = False, <ide> **kwargs: Any, <ide> def call( <ide> <ide> mask_time_indices = kwargs.get("mask_time_indices", None) <ide> if mask_time_indices is not None: # apply SpecAugment along time axis with given indices <del> hidden_states = tf.tensor_scatter_nd_update(hidden_states, mask_time_indices, self.mask_spec_embed) <add> hidden_states = tf.where( <add> tf.cast(mask_time_indices[:, :, tf.newaxis], tf.bool), <add> self.masked_spec_embed[tf.newaxis, tf.newaxis, :], <add> hidden_states, <add> ) <ide> <del> hidden_states = self._mask_hidden_states(hidden_states) <add> if inputs["training"]: <add> hidden_states = self._mask_hidden_states(hidden_states, mask_time_indices=mask_time_indices) <ide> <ide> encoder_outputs = self.encoder( <ide> hidden_states, <ide> def call( <ide> # when not being attended to <ide> labels_mask = tf.cast(labels >= 0, tf.int32) <ide> target_lengths = tf.reduce_sum(labels_mask, axis=-1) <del> flattened_labels = tf.boolean_mask(labels, labels_mask) <del> flattened_labels = tf.reshape(flattened_labels, [labels.shape[0], -1]) <ide> <ide> loss = tf.nn.ctc_loss( <ide> logits=logits, <del> labels=flattened_labels, <add> labels=labels, <ide> logit_length=input_lengths, <ide> label_length=target_lengths, <ide> blank_index=self.config.pad_token_id,
1
Go
Go
add gc loop to clean exec command refs on daemon
5f017bba48e5c763157e1b35a5edea64cc41fc6a
<ide><path>daemon/daemon.go <ide> func NewDaemon(config *Config, registryService *registry.Service) (daemon *Daemo <ide> d.RegistryService = registryService <ide> d.EventsService = eventsService <ide> d.root = config.Root <add> go d.execCommandGC() <ide> <ide> if err := d.restore(); err != nil { <ide> return nil, err <ide><path>daemon/exec.go <ide> import ( <ide> "io/ioutil" <ide> "strings" <ide> "sync" <add> "time" <ide> <ide> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/daemon/execdriver" <ide> func (d *Daemon) Exec(c *Container, execConfig *execConfig, pipes *execdriver.Pi <ide> <ide> return exitStatus, err <ide> } <add> <add>// execCommandGC runs a ticker to clean up the daemon references <add>// of exec configs that are no longer part of the container. <add>func (d *Daemon) execCommandGC() { <add> for range time.Tick(5 * time.Minute) { <add> var ( <add> cleaned int <add> liveExecCommands = d.containerExecIds() <add> ids = d.execCommands.List() <add> ) <add> for _, id := range ids { <add> if _, exists := liveExecCommands[id]; !exists { <add> cleaned++ <add> d.execCommands.Delete(id) <add> } <add> } <add> logrus.Debugf("clean %d unused exec commands", cleaned) <add> } <add>} <add> <add>// containerExecIds returns a list of all the current exec ids that are in use <add>// and running inside a container. <add>func (d *Daemon) containerExecIds() map[string]struct{} { <add> ids := map[string]struct{}{} <add> for _, c := range d.containers.List() { <add> for _, id := range c.execCommands.List() { <add> ids[id] = struct{}{} <add> } <add> } <add> return ids <add>}
2
Ruby
Ruby
remove newlines from start of logs
5e4f82a5f39054b27232fbf0840496ab5ddb06a7
<ide><path>actionmailer/lib/action_mailer/log_subscriber.rb <ide> class LogSubscriber < ActiveSupport::LogSubscriber <ide> def deliver(event) <ide> info do <ide> recipients = Array(event.payload[:to]).join(', ') <del> "\nSent mail to #{recipients} (#{event.duration.round(1)}ms)" <add> "Sent mail to #{recipients} (#{event.duration.round(1)}ms)" <ide> end <ide> <ide> debug { event.payload[:mail] } <ide> end <ide> <ide> # An email was received. <ide> def receive(event) <del> info { "\nReceived mail (#{event.duration.round(1)}ms)" } <add> info { "Received mail (#{event.duration.round(1)}ms)" } <ide> debug { event.payload[:mail] } <ide> end <ide> <ide> def process(event) <ide> debug do <ide> mailer = event.payload[:mailer] <ide> action = event.payload[:action] <del> "\n#{mailer}##{action}: processed outbound mail in #{event.duration.round(1)}ms" <add> "#{mailer}##{action}: processed outbound mail in #{event.duration.round(1)}ms" <ide> end <ide> end <ide>
1
Javascript
Javascript
fix typo in test-cli-node-options.js
401a37281e63ef0164e44ce66d2c67f995bcefd1
<ide><path>test/parallel/test-cli-node-options.js <ide> function expect(opt, want) { <ide> assert.ifError(err); <ide> if (!RegExp(want).test(stdout)) { <ide> console.error('For %j, failed to find %j in: <\n%s\n>', <del> opt, expect, stdout); <del> assert(false, `Expected ${expect}`); <add> opt, want, stdout); <add> assert.fail(`Expected ${want}`); <ide> } <ide> })); <ide> }
1
Ruby
Ruby
add limit flag to reduce response size
ef8af4b0707997d38d3146c45c4cc4c5b2fa3017
<ide><path>Library/Homebrew/dev-cmd/bump.rb <ide> def bump_args <ide> <ide> Display out-of-date brew formulae, the latest version available, and whether a pull request has been opened. <ide> EOS <add> flag "--limit=", <add> description: "Limit number of package results returned." <ide> switch :verbose <ide> switch :debug <ide> end <ide> def validate_and_format_packages(outdated_repology_packages) <ide> <ide> latest_version = repositories.find { |repo| repo["status"] == "newest" }["version"] <ide> srcname = repology_homebrew_repo["srcname"] <del> packages[srcname] = format_package(srcname, latest_version) <add> package_details = format_package(srcname, latest_version) <add> packages[srcname] = package_details unless package_details.nil? <add> <add> break if packages.size == Homebrew.args.limit.to_i <ide> end <add> <ide> packages <ide> end <ide> <ide> def display(outdated_packages) <ide> ohai formula <ide> puts "Current formula version: #{package_details[:current_formula_version]}" <ide> puts "Latest repology version: #{package_details[:repology_latest_version]}" <del> puts "Latest livecheck version: #{package_details[:livecheck_latest_version]}" <del> puts "Open pull requests: #{package_details[:open_pull_requests]}" <add> puts "Latest livecheck version: #{package_details[:livecheck_latest_version] || "Not found."}" <add> puts "Open pull requests: #{package_details[:open_pull_requests] || "None."}" <ide> end <ide> end <ide> end
1
Python
Python
use textwrap.dedent for readability
5b6b1fe2f957e22162233878888e2e3d5454a6a9
<ide><path>numpy/core/code_generators/generate_umath.py <ide> def make_arrays(funcdict): <ide> funclist.append('%s_%s' % (tname, name)) <ide> if t.simd is not None: <ide> for vt in t.simd: <del> code2list.append("""\ <del>#ifdef HAVE_ATTRIBUTE_TARGET_{ISA} <del>if (NPY_CPU_SUPPORTS_{ISA}) {{ <del> {fname}_functions[{idx}] = {type}_{fname}_{isa}; <del>}} <del>#endif <del>""".format(ISA=vt.upper(), isa=vt, fname=name, type=tname, idx=k)) <add> code2list.append(textwrap.dedent("""\ <add> #ifdef HAVE_ATTRIBUTE_TARGET_{ISA} <add> if (NPY_CPU_SUPPORTS_{ISA}) {{ <add> {fname}_functions[{idx}] = {type}_{fname}_{isa}; <add> }} <add> #endif <add> """).format( <add> ISA=vt.upper(), isa=vt, <add> fname=name, type=tname, idx=k <add> )) <ide> <ide> for x in t.in_ + t.out: <ide> siglist.append('NPY_%s' % (english_upper(chartoname[x]),)) <ide> def make_ufuncs(funcdict): <ide> # string literal in C code. We split at endlines because textwrap.wrap <ide> # do not play well with \n <ide> docstring = '\\n\"\"'.join(docstring.split(r"\n")) <del> mlist.append(\ <del>r"""f = PyUFunc_FromFuncAndData(%s_functions, %s_data, %s_signatures, %d, <del> %d, %d, %s, "%s", <del> "%s", 0);""" % (name, name, name, <add> mlist.append(textwrap.dedent("""\ <add> f = PyUFunc_FromFuncAndData(%s_functions, %s_data, %s_signatures, %d, <add> %d, %d, %s, "%s", <add> "%s", 0);""") % (name, name, name, <ide> len(uf.type_descriptions), <ide> uf.nin, uf.nout, <ide> uf.identity, <ide> def make_code(funcdict, filename): <ide> code3 = make_ufuncs(funcdict) <ide> code2 = indent(code2, 4) <ide> code3 = indent(code3, 4) <del> code = r""" <add> code = textwrap.dedent(r""" <ide> <del>/** Warning this file is autogenerated!!! <add> /** Warning this file is autogenerated!!! <ide> <del> Please make changes to the code generator program (%s) <del>**/ <add> Please make changes to the code generator program (%s) <add> **/ <ide> <del>%s <add> %s <ide> <del>static void <del>InitOperators(PyObject *dictionary) { <del> PyObject *f; <add> static void <add> InitOperators(PyObject *dictionary) { <add> PyObject *f; <ide> <del>%s <del>%s <del>} <del>""" % (filename, code1, code2, code3) <add> %s <add> %s <add> } <add> """) % (filename, code1, code2, code3) <ide> return code <ide> <ide>
1
PHP
PHP
fix 0'th index file not being copied to $_files
1110e26483fd0c509b10b096d414ed82004965c0
<ide><path>lib/Cake/Network/CakeRequest.php <ide> protected function _base() { <ide> protected function _processFiles() { <ide> if (isset($_FILES) && is_array($_FILES)) { <ide> foreach ($_FILES as $name => $data) { <del> if ($name != 'data') { <add> if ($name !== 'data') { <ide> $this->params['form'][$name] = $data; <ide> } <ide> } <ide><path>lib/Cake/Test/Case/Network/CakeRequestTest.php <ide> public function testFilesParsing() { <ide> $this->assertEquals($request->params['form'], $_FILES); <ide> } <ide> <add>/** <add> * Test that files in the 0th index work. <add> */ <add> public function testFilesZeroithIndex() { <add> $_FILES = array( <add> 0 => array( <add> 'name' => 'cake_sqlserver_patch.patch', <add> 'type' => 'text/plain', <add> 'tmp_name' => '/private/var/tmp/phpy05Ywj', <add> 'error' => 0, <add> 'size' => 6271, <add> ), <add> ); <add> <add> $request = new CakeRequest('some/path'); <add> $this->assertEquals($_FILES, $request->params['form']); <add> } <add> <ide> /** <ide> * test method overrides coming in from POST data. <ide> *
2
PHP
PHP
provide session defaults
451ab1d6e1b0f3c682f967344922fde6f61228ea
<ide><path>src/Network/Request.php <ide> class Request implements \ArrayAccess { <ide> */ <ide> public static function createFromGlobals() { <ide> list($base, $webroot) = static::_base(); <add> $sessionConfig = (array)Configure::read('Session') + array('defaults' => 'php'); <ide> $config = array( <ide> 'query' => $_GET, <ide> 'post' => $_POST, <ide> public static function createFromGlobals() { <ide> 'environment' => $_SERVER + $_ENV, <ide> 'base' => $base, <ide> 'webroot' => $webroot, <del> 'session' => Session::create(Configure::read('Session')) <add> 'session' => Session::create($sessionConfig) <ide> ); <ide> $config['url'] = static::_url($config); <ide> return new static($config);
1
Javascript
Javascript
fix regression in webxr
8fb030c04113613b41fc63c3db6b698673494063
<ide><path>src/renderers/webxr/WebXRManager.js <ide> class WebXRManager extends EventDispatcher { <ide> <ide> const glSubImage = glBinding.getViewSubImage( glProjLayer, view ); <ide> <del> gl.bindFramebuffer( gl.FRAMEBUFFER, glFramebuffer ); <add> state.bindXRFramebuffer( glFramebuffer ); <ide> <ide> gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, glSubImage.colorTexture, 0 ); <ide> <ide> class WebXRManager extends EventDispatcher { <ide> <ide> } <ide> <del> gl.bindFramebuffer( gl.FRAMEBUFFER, null ); <del> <del> state.bindXRFramebuffer( glFramebuffer ); <del> <ide> viewport = glSubImage.viewport; <ide> <ide> }
1
Python
Python
update setup.py for asf things
7ccf042c8a7889abf676eaced275e61a8400049e
<ide><path>setup.py <ide> def run(self): <ide> setup(name = 'libcloud', <ide> version = '0.1.1', <ide> description = 'A unified interface into many cloud server providers', <del> author = 'Alex Polvi', <del> author_email = 'polvi@cloudkick.com', <add> author = 'Apache Software Foundation', <add> author_email = 'libcloud@incubator.apache.org', <ide> packages = ['libcloud', 'libcloud.drivers'], <ide> package_dir = {'libcloud' : 'libcloud', 'libcloud.drivers': 'libcloud/drivers' }, <ide> license = 'Apache License (2.0)', <del> url = 'http://github.com/cloudkick/libcloud', <add> url = 'http://incubator.apache.org/libcloud/', <ide> cmdclass = { 'test': TestCommand } <ide> ) <ide>
1
Java
Java
improve error reporting in scripttemplateview
158028881575fb3f00f96579a04ca52857afa375
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/script/ScriptRenderException.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.servlet.view.script; <add> <add>/** <add> * Exception thrown when an error occurs during script template rendering. <add> * <add> * <p>It does not print the java stacktrace in the logs, since it is not useful <add> * in this script context. <add> * <add> * @author Sebastien Deleuze <add> * @since 4.2.2 <add> */ <add>public class ScriptRenderException extends RuntimeException { <add> <add> private static final long serialVersionUID = 421565510962788082L; <add> <add> <add> /** <add> * Constructs a new script rendering exception with the specified detail message. <add> */ <add> public ScriptRenderException(String msg) { <add> super(msg); <add> } <add> <add> @Override <add> public synchronized Throwable fillInStackTrace() { <add> return this; <add> } <add> <add>} <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/script/ScriptTemplateView.java <ide> import javax.script.Invocable; <ide> import javax.script.ScriptEngine; <ide> import javax.script.ScriptEngineManager; <add>import javax.servlet.ServletException; <ide> import javax.servlet.http.HttpServletRequest; <ide> import javax.servlet.http.HttpServletResponse; <ide> <ide> protected void renderMergedOutputModel(Map<String, Object> model, HttpServletReq <ide> response.getWriter().write(String.valueOf(html)); <ide> } <ide> catch (Exception ex) { <del> throw new IllegalStateException("Failed to render script template", ex); <add> throw new ServletException("Failed to render script template", new ScriptRenderException(ex.getMessage())); <ide> } <ide> } <ide>
2
Ruby
Ruby
pass formats to lookup_context
face6042667c38fb8a372fa6f0bbfff88c4470f3
<ide><path>actionview/lib/action_view/layouts.rb <ide> def _write_layout_method # :nodoc: <ide> remove_possible_method(:_layout) <ide> <ide> prefixes = _implied_layout_name =~ /\blayouts/ ? [] : ["layouts"] <del> default_behavior = "lookup_context.find_all('#{_implied_layout_name}', #{prefixes.inspect}).first || super" <add> default_behavior = "lookup_context.find_all('#{_implied_layout_name}', #{prefixes.inspect}, false, [], { formats: formats }).first || super" <ide> name_clause = if name <ide> default_behavior <ide> else <ide> def _write_layout_method # :nodoc: <ide> end <ide> <ide> self.class_eval <<-RUBY, __FILE__, __LINE__ + 1 <del> def _layout <add> def _layout(formats) <ide> if _conditional_layout? <ide> #{layout_definition} <ide> else <ide> def _conditional_layout? <ide> end <ide> <ide> # This will be overwritten by _write_layout_method <del> def _layout; end <add> def _layout(*); end <ide> <ide> # Determine the layout for a given name, taking into account the name type. <ide> # <ide> def _layout_for_option(name) <ide> case name <ide> when String then _normalize_layout(name) <ide> when Proc then name <del> when true then Proc.new { _default_layout(true) } <del> when :default then Proc.new { _default_layout(false) } <add> when true then Proc.new { _default_layout(formats, true) } <add> when :default then Proc.new { _default_layout(formats, false) } <ide> when false, nil then nil <ide> else <ide> raise ArgumentError, <ide> def _normalize_layout(value) <ide> # Optionally raises an exception if the layout could not be found. <ide> # <ide> # ==== Parameters <add> # * <tt>formats</tt> - The formats accepted to this layout <ide> # * <tt>require_layout</tt> - If set to true and layout is not found, <ide> # an ArgumentError exception is raised (defaults to false) <ide> # <ide> # ==== Returns <ide> # * <tt>template</tt> - The template object for the default layout (or nil) <del> def _default_layout(require_layout = false) <add> def _default_layout(formats, require_layout = false) <ide> begin <del> value = _layout if action_has_layout? <add> value = _layout(formats) if action_has_layout? <ide> rescue NameError => e <ide> raise e, "Could not render layout: #{e.message}" <ide> end <ide><path>actionview/lib/action_view/renderer/template_renderer.rb <ide> def resolve_layout(layout, keys, formats) <ide> raise unless template_exists?(layout, nil, false, keys, all_details) <ide> end <ide> when Proc <del> resolve_layout(layout.call, keys, formats) <add> resolve_layout(layout.call(formats), keys, formats) <ide> else <ide> layout <ide> end
2
Javascript
Javascript
add support for standalonemonth in format (`llll`)
e4e30961ca1a271452ac4f2acd49b07ad8df3cf9
<ide><path>src/ng/filter/filters.js <ide> function dateGetter(name, size, offset, trim) { <ide> }; <ide> } <ide> <del>function dateStrGetter(name, shortForm) { <add>function dateStrGetter(name, shortForm, standAlone) { <ide> return function(date, formats) { <ide> var value = date['get' + name](); <del> var get = uppercase(shortForm ? ('SHORT' + name) : name); <add> var propPrefix = (standAlone ? 'STANDALONE' : '') + (shortForm ? 'SHORT' : ''); <add> var get = uppercase(propPrefix + name); <ide> <ide> return formats[get][value]; <ide> }; <ide> var DATE_FORMATS = { <ide> MMM: dateStrGetter('Month', true), <ide> MM: dateGetter('Month', 2, 1), <ide> M: dateGetter('Month', 1, 1), <add> LLLL: dateStrGetter('Month', false, true), <ide> dd: dateGetter('Date', 2), <ide> d: dateGetter('Date', 1), <ide> HH: dateGetter('Hours', 2), <ide> var DATE_FORMATS = { <ide> GGGG: longEraGetter <ide> }; <ide> <del>var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/, <add>var DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/, <ide> NUMBER_STRING = /^\-?\d+$/; <ide> <ide> /** <ide> var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+| <ide> * * `'MMM'`: Month in year (Jan-Dec) <ide> * * `'MM'`: Month in year, padded (01-12) <ide> * * `'M'`: Month in year (1-12) <add> * * `'LLLL'`: Stand-alone month in year (January-December) <ide> * * `'dd'`: Day in month, padded (01-31) <ide> * * `'d'`: Day in month (1-31) <ide> * * `'EEEE'`: Day in Week,(Sunday-Saturday) <ide><path>test/ng/filter/filtersSpec.js <ide> describe('filters', function() { <ide> toEqual('September 03, 2010 Anno Domini'); <ide> }); <ide> <add> it('should support STANDALONEMONTH in format (`LLLL`)', inject(function($locale) { <add> var standAloneMonth = $locale.DATETIME_FORMATS.STANDALONEMONTH; <add> var september = standAloneMonth[8]; <add> var standAloneSeptember = 'StandAlone' + september; <add> <add> // Overwrite September in STANDALONEMONTH <add> standAloneMonth[8] = standAloneSeptember; <add> <add> expect(date(noon, 'MMMM')).toEqual(september); <add> expect(date(noon, 'LLLL')).toEqual(standAloneSeptember); <add> <add> // Restore September in STANDALONEMONTH <add> standAloneMonth[8] = september; <add> })); <add> <ide> it('should accept negative numbers as strings', function() { <ide> //Note: this tests a timestamp set for 3 days before the unix epoch. <ide> //The behavior of `date` depends on your timezone, which is why we check just
2
Go
Go
normalize comment formatting
b95fbe7630190a89b311d10f7030822f369cbf79
<ide><path>pkg/signal/trap.go <ide> func Trap(cleanup func(), logger interface { <ide> DumpStacks("") <ide> logger.Info("Forcing docker daemon shutdown without cleanup on SIGQUIT") <ide> } <del> //for the SIGINT/TERM, and SIGQUIT non-clean shutdown case, exit with 128 + signal # <add> // for the SIGINT/TERM, and SIGQUIT non-clean shutdown case, exit with 128 + signal # <ide> os.Exit(128 + int(sig.(syscall.Signal))) <ide> }(sig) <ide> }
1
Java
Java
shortcut handling of bodytoflux(databuffer.class)
0e9ecb6c99471a1efa4deb40149e4ddc48e33b92
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/DefaultClientResponse.java <ide> <ide> import org.springframework.core.ParameterizedTypeReference; <ide> import org.springframework.core.codec.Hints; <add>import org.springframework.core.io.buffer.DataBuffer; <ide> import org.springframework.core.io.buffer.DataBufferUtils; <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.HttpRequest; <ide> class DefaultClientResponse implements ClientResponse { <ide> <ide> private final Supplier<HttpRequest> requestSupplier; <ide> <add> private final BodyExtractor.Context bodyExtractorContext; <add> <ide> <ide> public DefaultClientResponse(ClientHttpResponse response, ExchangeStrategies strategies, <ide> String logPrefix, String requestDescription, Supplier<HttpRequest> requestSupplier) { <ide> public DefaultClientResponse(ClientHttpResponse response, ExchangeStrategies str <ide> this.logPrefix = logPrefix; <ide> this.requestDescription = requestDescription; <ide> this.requestSupplier = requestSupplier; <add> this.bodyExtractorContext = new BodyExtractor.Context() { <add> @Override <add> public List<HttpMessageReader<?>> messageReaders() { <add> return strategies.messageReaders(); <add> } <add> <add> @Override <add> public Optional<ServerHttpResponse> serverResponse() { <add> return Optional.empty(); <add> } <add> <add> @Override <add> public Map<String, Object> hints() { <add> return Hints.from(Hints.LOG_PREFIX_HINT, logPrefix); <add> } <add> }; <ide> } <ide> <ide> <ide> public MultiValueMap<String, ResponseCookie> cookies() { <ide> @SuppressWarnings("unchecked") <ide> @Override <ide> public <T> T body(BodyExtractor<T, ? super ClientHttpResponse> extractor) { <del> T result = extractor.extract(this.response, new BodyExtractor.Context() { <del> @Override <del> public List<HttpMessageReader<?>> messageReaders() { <del> return strategies.messageReaders(); <del> } <del> <del> @Override <del> public Optional<ServerHttpResponse> serverResponse() { <del> return Optional.empty(); <del> } <del> <del> @Override <del> public Map<String, Object> hints() { <del> return Hints.from(Hints.LOG_PREFIX_HINT, logPrefix); <del> } <del> }); <add> T result = extractor.extract(this.response, this.bodyExtractorContext); <ide> String description = "Body from " + this.requestDescription + " [DefaultClientResponse]"; <ide> if (result instanceof Mono) { <ide> return (T) ((Mono<?>) result).checkpoint(description); <ide> public <T> Mono<T> bodyToMono(ParameterizedTypeReference<T> elementTypeRef) { <ide> } <ide> <ide> @Override <add> @SuppressWarnings("unchecked") <ide> public <T> Flux<T> bodyToFlux(Class<? extends T> elementClass) { <del> return body(BodyExtractors.toFlux(elementClass)); <add> return elementClass.equals(DataBuffer.class) ? <add> (Flux<T>) body(BodyExtractors.toDataBuffers()) : body(BodyExtractors.toFlux(elementClass)); <ide> } <ide> <ide> @Override <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/DefaultServerRequest.java <ide> import org.springframework.core.ParameterizedTypeReference; <ide> import org.springframework.core.codec.DecodingException; <ide> import org.springframework.core.codec.Hints; <add>import org.springframework.core.io.buffer.DataBuffer; <ide> import org.springframework.http.HttpCookie; <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.HttpRange; <ide> public <T> Mono<T> bodyToMono(ParameterizedTypeReference<T> typeReference) { <ide> } <ide> <ide> @Override <add> @SuppressWarnings("unchecked") <ide> public <T> Flux<T> bodyToFlux(Class<? extends T> elementClass) { <del> Flux<T> flux = body(BodyExtractors.toFlux(elementClass)); <add> Flux<T> flux = (elementClass.equals(DataBuffer.class) ? <add> (Flux<T>) request().getBody() : body(BodyExtractors.toFlux(elementClass))); <ide> return flux.onErrorMap(UnsupportedMediaTypeException.class, ERROR_MAPPER) <ide> .onErrorMap(DecodingException.class, DECODING_MAPPER); <ide> }
2
Text
Text
fix quotes in stream docs
1d3b49ec881c702151b3ba58ceb3644695072d44
<ide><path>doc/api/stream.md <ide> user programs. <ide> be written. The `chunk` will be a string if the `Writable` was created with <ide> the `decodeStrings` option set to `false` and a string was passed to `write()`. <ide> * `encoding` {string} The character encoding of the `chunk`. If `chunk` is <del> a `Buffer`, the `encoding` will be `'buffer`. <add> a `Buffer`, the `encoding` will be `'buffer'`. <ide> * `callback` {Function} A callback function (optionally with an error <ide> argument) to be invoked when processing is complete for the supplied chunks. <ide>
1
Javascript
Javascript
add devsettings to jest preset
a50f736bb6ade9ea9caae45e41ca4b92f6707b17
<ide><path>jest/setup.js <ide> jest <ide> }; <ide> }, <ide> }, <add> DevSettings: { <add> addMenuItem: jest.fn(), <add> reload: jest.fn(), <add> }, <ide> ImageLoader: { <ide> getSize: jest.fn(url => Promise.resolve({width: 320, height: 240})), <ide> prefetchImage: jest.fn(),
1
Text
Text
clarify the validation of present associations
e53d2325d52f42c4646696a4db7af472c3a1ec7b
<ide><path>guides/source/active_record_validations.md <ide> end <ide> <ide> If you want to be sure that an association is present, you'll need to test <ide> whether the associated object itself is present, and not the foreign key used <del>to map the association. <add>to map the association. This way, it is not only checked that the foreign key <add>is not empty but also that the referenced object exists. <ide> <ide> ```ruby <ide> class LineItem < ApplicationRecord
1
PHP
PHP
fix php 5.4 syntax
fb9c7c13f4b393f6598f2841d084307167a7e883
<ide><path>src/Illuminate/Database/DatabaseManager.php <ide> protected function prepare(Connection $connection) <ide> // The database connection can also utilize a cache manager instance when cache <ide> // functionality is used on queries, which provides an expressive interface <ide> // to caching both fluent queries and Eloquent queries that are executed. <del> $connection->setCacheManager(function() <add> $app = $this->app; <add> <add> $connection->setCacheManager(function() use ($app) <ide> { <del> return $this->app['cache']; <add> return $app['cache']; <ide> }); <ide> <del> $app = $this->app; <del> <ide> // We will setup a Closure to resolve the paginator instance on the connection <ide> // since the Paginator isn't sued on every request and needs quite a few of <ide> // our dependencies. It'll be more efficient to lazily resolve instances.
1
PHP
PHP
remove serializer option for now
95a8f05bb9b6769dfdad58eb550777b59f398b5b
<ide><path>src/Illuminate/Redis/Connectors/PhpRedisConnector.php <ide> protected function createClient(array $config) <ide> $client->setOption(Redis::OPT_READ_TIMEOUT, $config['read_timeout']); <ide> } <ide> <del> if (! empty($config['serializer'])) { <del> $client->setOption(Redis::OPT_SERIALIZER, $config['serializer']); <del> } <del> <ide> if (! empty($config['scan'])) { <ide> $client->setOption(Redis::OPT_SCAN, $config['scan']); <ide> } <ide> protected function createRedisClusterInstance(array $servers, array $options) <ide> $client->setOption(RedisCluster::OPT_PREFIX, $options['prefix']); <ide> } <ide> <del> if (! empty($options['serializer'])) { <del> $client->setOption(RedisCluster::OPT_SERIALIZER, $options['serializer']); <del> } <del> <del> if (! empty($config['scan'])) { <del> $client->setOption(RedisCluster::OPT_SCAN, $config['scan']); <add> if (! empty($options['scan'])) { <add> $client->setOption(RedisCluster::OPT_SCAN, $options['scan']); <ide> } <ide> <del> if (! empty($config['failover'])) { <del> $client->setOption(RedisCluster::OPT_SLAVE_FAILOVER, $config['failover']); <add> if (! empty($options['failover'])) { <add> $client->setOption(RedisCluster::OPT_SLAVE_FAILOVER, $options['failover']); <ide> } <ide> }); <ide> }
1
Javascript
Javascript
use new animation options in the animation service
e774a893da4f7be405af2926ae74499f2ab0d813
<ide><path>src/Chart.Core.js <ide> redraw: noop, <ide> render: function(duration) { <ide> <del> if (this.options.animation) { <add> if (this.options.animation.duration !== 0) { <ide> var animation = new Chart.Animation(); <del> animation.numSteps = (duration || this.options.animationDuration) / 16.66; //60 fps <del> animation.easing = this.options.animationEasing; <add> animation.numSteps = (duration || this.options.animation.duration) / 16.66; //60 fps <add> animation.easing = this.options.animation.easing; <ide> <ide> // render function <ide> animation.render = function(chartInstance, animationObject) {
1
Javascript
Javascript
change var to let/const in stream files
4fc13b016a6f1933143c97dea55d0b0443423dce
<ide><path>lib/_stream_readable.js <ide> Readable.prototype.read = function(n) { <ide> // 3. Actually pull the requested chunks out of the buffer and return. <ide> <ide> // if we need a readable event, then we need to do some reading. <del> var doRead = state.needReadable; <add> let doRead = state.needReadable; <ide> debug('need readable', doRead); <ide> <ide> // If we currently have less than the highWaterMark, then also read some <ide> Readable.prototype.read = function(n) { <ide> n = howMuchToRead(nOrig, state); <ide> } <ide> <del> var ret; <add> let ret; <ide> if (n > 0) <ide> ret = fromList(n, state); <ide> else <ide> function onEofChunk(stream, state) { <ide> debug('onEofChunk'); <ide> if (state.ended) return; <ide> if (state.decoder) { <del> var chunk = state.decoder.end(); <add> const chunk = state.decoder.end(); <ide> if (chunk && chunk.length) { <ide> state.buffer.push(chunk); <ide> state.length += state.objectMode ? 1 : chunk.length; <ide> Readable.prototype.pipe = function(dest, pipeOpts) { <ide> <ide> let ondrain; <ide> <del> var cleanedUp = false; <add> let cleanedUp = false; <ide> function cleanup() { <ide> debug('cleanup'); <ide> // Cleanup event handlers once the pipe is broken <ide> Readable.prototype.unpipe = function(dest) { <ide> <ide> if (!dest) { <ide> // remove all. <del> var dests = state.pipes; <add> const dests = state.pipes; <ide> state.pipes = []; <ide> this.pause(); <ide> <ide> function flow(stream) { <ide> // It is an ugly unfortunate mess of history. <ide> Readable.prototype.wrap = function(stream) { <ide> const state = this._readableState; <del> var paused = false; <add> let paused = false; <ide> <ide> stream.on('end', () => { <ide> debug('wrapped end'); <ide> if (state.decoder && !state.ended) { <del> var chunk = state.decoder.end(); <add> const chunk = state.decoder.end(); <ide> if (chunk && chunk.length) <ide> this.push(chunk); <ide> } <ide> function fromList(n, state) { <ide> if (state.length === 0) <ide> return null; <ide> <del> var ret; <add> let ret; <ide> if (state.objectMode) <ide> ret = state.buffer.shift(); <ide> else if (!n || n >= state.length) { <ide><path>lib/_stream_transform.js <ide> Transform.prototype._write = function(chunk, encoding, cb) { <ide> ts.writechunk = chunk; <ide> ts.writeencoding = encoding; <ide> if (!ts.transforming) { <del> var rs = this._readableState; <add> const rs = this._readableState; <ide> if (ts.needTransform || <ide> rs.needReadable || <ide> rs.length < rs.highWaterMark)
2
Javascript
Javascript
fix unused find
faea56c549647019911134368d841d9a8da87d91
<ide><path>examples/js/loaders/XLoader.js <ide> THREE.XLoader.prototype = { <ide> getNextSection: function ( _offset, _start, _end ) { <ide> <ide> var scope = this; <del> var find = scope.data.indexOf( "{", _offset ); <ide> return [ scope.data.substr( _offset, _start - _offset ).trim(), scope.data.substr( _start + 1, _end - _start - 1 ) ]; <ide> <ide> }, <ide> <ide> getNextSection2: function ( _obj, _offset, _start, _end ) { <ide> <del> var find = _obj.indexOf( "{", _offset ); <ide> return [ _obj.substr( _offset, _start - _offset ).trim(), _obj.substr( _start + 1, _end - _start - 1 ) ]; <ide> <ide> },
1
Javascript
Javascript
fix some strict warnings
76f6398e479a01e46d96572b478c6f2ffc4dd85d
<ide><path>crypto.js <ide> var CipherTransformFactory = (function() { <ide> }; <ide> } <ide> error('Unknown crypto method'); <add> return null; <ide> } <ide> <ide> constructor.prototype = { <ide><path>fonts.js <ide> var FontMeasure = (function FontMeasure() { <ide> <ide> return { <ide> setActive: function fonts_setActive(font, size) { <del> if (current = font) { <add> if (current == font) { <ide> var sizes = current.sizes; <ide> if (!(measureCache = sizes[size])) <ide> measureCache = sizes[size] = Object.create(null); <ide> var Font = (function Font() { <ide> var language = int16(font.getBytes(2)); <ide> <ide> if (format == 4) { <del> return; <add> return cmap.data; <ide> } else if (format == 0) { <ide> // Characters below 0x20 are controls characters that are hardcoded <ide> // into the platform so if some characters in the font are assigned <ide> var Font = (function Font() { <ide> return cmap.data = createCMapTable(glyphs); <ide> } <ide> } <add> return cmap.data; <ide> }; <ide> <ide> // Check that required tables are present <ide> var Type2CFF = (function() { <ide> id = (id << 8) | bytes[pos++]; <ide> charset.push(strings[id]); <ide> } <del> return charset; <add> break; <ide> case 1: <ide> while (charset.length <= length) { <ide> var first = bytes[pos++]; <ide> var Type2CFF = (function() { <ide> for (var i = 0; i <= numLeft; ++i) <ide> charset.push(strings[first++]); <ide> } <del> return charset; <add> break; <ide> case 2: <ide> while (charset.length <= length) { <ide> var first = bytes[pos++]; <ide> var Type2CFF = (function() { <ide> for (var i = 0; i <= numLeft; ++i) <ide> charset.push(strings[first++]); <ide> } <del> return charset; <add> break; <ide> default: <ide> error('Unknown charset format'); <ide> } <del> <add> return charset; <ide> }, <ide> getPrivDict: function cff_getprivdict(baseDict, strings) { <ide> var dict = {}; <ide> var Type2CFF = (function() { <ide> } else { <ide> error('Incorrect byte'); <ide> } <add> return -1; <ide> }; <ide> <ide> function parseFloatOperand() { <ide><path>pdf.js <ide> var LZWStream = (function() { <ide> var c = this.str.getByte(); <ide> if (c == null) { <ide> this.eof = true; <del> return; <add> return null; <ide> } <ide> cachedData = (cachedData << 8) | c; <ide> bitsCached += 8; <ide> var Util = (function() { <ide> return 'rgb(' + ri + ',' + gi + ',' + bi + ')'; <ide> }; <ide> constructor.makeCssCmyk = function makecmyk(c, m, y, k) { <del> var c = (new DeviceCmykCS()).getRgb([c, m, y, k]); <add> c = (new DeviceCmykCS()).getRgb([c, m, y, k]); <ide> var ri = (255 * c[0]) | 0, gi = (255 * c[1]) | 0, bi = (255 * c[2]) | 0; <ide> return 'rgb(' + ri + ',' + gi + ',' + bi + ')'; <ide> }; <ide> var ColorSpace = (function() { <ide> } else { <ide> error('unrecognized color space object: "' + cs + '"'); <ide> } <add> return null; <ide> }; <ide> <ide> return constructor; <ide> var Pattern = (function() { <ide> default: <ide> error('Unknown type of pattern: ' + typeNum); <ide> } <add> return null; <ide> }; <ide> <ide> constructor.parseShading = function pattern_shading(shading, matrix, <ide><path>web/viewer.js <ide> window.addEventListener('transitionend', function(evt) { <ide> var pagesCount = PDFView.pages.length; <ide> <ide> var container = document.getElementById('sidebarView'); <del> container._interval = window.setInterval(function() { <del> if (pageIndex >= pagesCount) <del> return window.clearInterval(container._interval); <add> container._interval = window.setInterval(function interval() { <add> if (pageIndex >= pagesCount) { <add> window.clearInterval(container._interval); <add> return; <add> } <ide> <ide> PDFView.thumbnails[pageIndex++].draw(); <ide> }, 500); <ide> }, true); <ide> <ide> <del>window.addEventListener('scalechange', function(evt) { <add>window.addEventListener('scalechange', function scalechange(evt) { <ide> var options = document.getElementById('scaleSelect').options; <ide> for (var i = 0; i < options.length; i++) { <ide> var option = options[i]; <ide> option.selected = (option.value == evt.detail); <ide> } <ide> }, true); <ide> <del>window.addEventListener('pagechange', function(evt) { <add>window.addEventListener('pagechange', function pagechange(evt) { <ide> var page = evt.detail; <ide> document.location.hash = page; <ide> document.getElementById('pageNumber').value = page;
4
Python
Python
fix import errors
cf60559f2f0fa165b77eacd5fb19c0d2cb8bfee5
<ide><path>research/differential_privacy/__init__.py <add> <ide><path>research/differential_privacy/multiple_teachers/__init__.py <add> <ide><path>research/differential_privacy/multiple_teachers/analysis.py <ide> def main(unused_argv): <ide> counts_mat = np.zeros((n, 10)).astype(np.int32) <ide> for i in range(n): <ide> for j in range(num_teachers): <del> counts_mat[i, input_mat[j, i]] += 1 <add> counts_mat[i, int(input_mat[j, i])] += 1 <ide> n = counts_mat.shape[0] <ide> num_examples = min(n, FLAGS.max_examples) <ide>
3
Python
Python
remove comment and get size defsively
57577cf95f67a84983ca67506296dd73edf95612
<ide><path>libcloud/compute/drivers/softlayer.py <ide> def _to_node(self, host, bare_metal=None): <ide> 'password': password, <ide> 'datacenter': host.get('datacenter', {}).get('name', None), <ide> 'image': image, <del> 'size': host.get('typeId'), <add> 'size': host.get('typeId', ''), <ide> 'hourlyRecurringFee': hourlyRecurringFee, <ide> 'recurringFee': recurringFee, <ide> 'recurringMonths': recurringMonths, <ide> def _to_bare_metal_size(self, size): <ide> def list_sizes(self, location=None): <ide> bm_sizes = self.connection.request('SoftLayer_Hardware', <ide> 'getCreateObjectOptions').object <del> # no cpus -- default to 1?? <ide> bm_sizes = [self._to_bare_metal_size(size['preset']) <ide> for size in bm_sizes['fixedConfigurationPresets']] <ide> cloud_sizes = [self._to_size(id, s) for id, s in SL_TEMPLATES.items()]
1
PHP
PHP
apply fixes from styleci
d750abea34ea179e920294a462ec959decb29acc
<ide><path>tests/Integration/Database/DatabaseEloquentModelCustomCastingTest.php <ide> public function testBasicCustomCasting() <ide> public function testGetOriginalWithCastValueObjects() <ide> { <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')->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> class AddressCaster implements CastsAttributes <ide> public function get($model, $key, $value, $attributes) <ide> { <ide> if (is_null($attributes['address_line_one'])) { <del> return null; <add> return; <ide> } <ide> <ide> return new Address($attributes['address_line_one'], $attributes['address_line_two']);
1
Javascript
Javascript
check end() argument to be > 0
642baf4699c3a973c073403a7f1a4c85e0197e81
<ide><path>benchmark/common.js <ide> Benchmark.prototype.end = function(operations) { <ide> if (typeof operations !== 'number') { <ide> throw new Error('called end() without specifying operation count'); <ide> } <add> if (!process.env.NODEJS_BENCHMARK_ZERO_ALLOWED && operations <= 0) { <add> throw new Error('called end() with operation count <= 0'); <add> } <ide> <ide> const time = elapsed[0] + elapsed[1] / 1e9; <ide> const rate = operations / time; <ide><path>test/sequential/test-benchmark-net.js <ide> const path = require('path'); <ide> <ide> const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); <ide> <del>const child = fork(runjs, ['--set', 'dur=0', 'net']); <add>const child = fork(runjs, ['--set', 'dur=0', 'net'], <add> {env: {NODEJS_BENCHMARK_ZERO_ALLOWED: 1}}); <ide> child.on('exit', (code, signal) => { <ide> assert.strictEqual(code, 0); <ide> assert.strictEqual(signal, null);
2
Python
Python
add encoding declaration
487ce1e20a5cd7d84e05b2e702bbae33aab2fc6f
<ide><path>spacy/de/__init__.py <add># encoding: utf8 <ide> from __future__ import unicode_literals, print_function <ide> <ide> from os import path <ide><path>spacy/en/__init__.py <add># encoding: utf8 <ide> from __future__ import unicode_literals, print_function <ide> <ide> from os import path <ide><path>spacy/es/__init__.py <add># encoding: utf8 <ide> from __future__ import unicode_literals, print_function <ide> <ide> from os import path <ide><path>spacy/fr/__init__.py <add># encoding: utf8 <ide> from __future__ import unicode_literals, print_function <ide> <ide> from os import path <ide><path>spacy/it/__init__.py <add># encoding: utf8 <ide> from __future__ import unicode_literals, print_function <ide> <ide> from os import path <ide><path>spacy/pt/__init__.py <add># encoding: utf8 <ide> from __future__ import unicode_literals, print_function <ide> <ide> from os import path
6
Javascript
Javascript
make enumerable#lastobject readonly
c31c50ee0472894a76e320a4e4f70fc357b3b740
<ide><path>packages/ember-runtime/lib/mixins/array.js <ide> export default Mixin.create(Enumerable, { <ide> <ide> lastObject: computed(function() { <ide> return objectAt(this, get(this, 'length') - 1); <del> }), <add> }).readOnly(), <ide> <ide> // optimized version from Enumerable <ide> contains(obj) { <ide><path>packages/ember-runtime/lib/mixins/enumerable.js <ide> var Enumerable = Mixin.create({ <ide> pushCtx(context); <ide> <ide> return last; <del> }), <add> }).readOnly(), <ide> <ide> /** <ide> Returns `true` if the passed object can be found in the receiver. The <ide><path>packages/ember-runtime/tests/suites/enumerable/lastObject.js <ide> import {SuiteModuleBuilder} from 'ember-runtime/tests/suites/suite'; <ide> import {get} from 'ember-metal/property_get'; <add>import {set} from 'ember-metal/property_set'; <ide> <ide> var suite = SuiteModuleBuilder.create(); <ide> <ide> suite.test('returns undefined if enumerable is empty', function() { <ide> equal(get(obj, 'lastObject'), undefined); <ide> }); <ide> <add>suite.test('can not be set', function() { <add> var obj = this.newObject(); <add> var ary = this.toArray(obj); <add> <add> equal(get(obj, 'lastObject'), ary[ary.length - 1]); <add> <add> throws(function() { <add> set(obj, 'lastObject', 'foo!'); <add> }, /Cannot set read-only property "lastObject" on object/); <add>}); <add> <ide> export default suite;
3
Python
Python
fix exception handling for python 3k
12d020070e8c6698500103889f55bd36dfcab374
<ide><path>numpy/ctypeslib.py <ide> def load_library(libname, loader_path): <ide> "with ctypes < 1.0.1") <ide> <ide> ext = os.path.splitext(libname)[1] <del> <ide> if not ext: <ide> # Try to load library with platform-specific name, otherwise <ide> # default to libname.[so|pyd]. Sometimes, these files are built <ide> def load_library(libname, loader_path): <ide> else: <ide> libdir = loader_path <ide> <add> # Need to save exception when using Python 3k, see PEP 3110. <add> exc = None <ide> for ln in libname_ext: <ide> try: <ide> libpath = os.path.join(libdir, ln) <ide> return ctypes.cdll[libpath] <ide> except OSError, e: <del> pass <del> <del> raise e <add> exc = e <add> raise exc <ide> <ide> ctypes_load_library = deprecate(load_library, 'ctypes_load_library', <ide> 'load_library')
1
Javascript
Javascript
fix newlines in integration helper test blueprint
b8914d1217ae89df13402e6973395a0c8479048b
<ide><path>blueprints/helper-test/qunit-files/tests/__testType__/helpers/__name__-test.js <del><% if (testType == 'integration') { %> <del>import { moduleForComponent, test } from 'ember-qunit'; <add><% if (testType == 'integration') { %>import { moduleForComponent, test } from 'ember-qunit'; <ide> import hbs from 'htmlbars-inline-precompile'; <ide> <ide> moduleForComponent('<%= dasherizedModuleName %>', 'helper:<%= dasherizedModuleName %>', { <ide> test('it renders', function(assert) { <ide> this.render(hbs`{{<%= dasherizedModuleName %> inputValue}}`); <ide> <ide> assert.equal(this.$().text().trim(), '1234'); <del>}); <del><% } else if (testType == 'unit') { %> <add>});<% } else if (testType == 'unit') { %> <ide> import { <%= camelizedModuleName %> } from '<%= dasherizedModulePrefix %>/helpers/<%= dasherizedModuleName %>'; <ide> import { module, test } from 'qunit'; <ide> <ide><path>node-tests/fixtures/helper-test/integration.js <del> <ide> import { moduleForComponent, test } from 'ember-qunit'; <ide> import hbs from 'htmlbars-inline-precompile'; <ide> <ide> test('it renders', function(assert) { <ide> <ide> assert.equal(this.$().text().trim(), '1234'); <ide> }); <del>
2
Ruby
Ruby
remove builder instances
d0163e99d9affeccb341e12cc7c50b599f129b5c
<ide><path>activerecord/lib/active_record/associations/builder/association.rb <ide> class << self <ide> <ide> VALID_OPTIONS = [:class_name, :class, :foreign_key, :validate] <ide> <del> attr_reader :name, :scope, :options <del> <ide> def self.build(model, name, scope, options, &block) <ide> extension = define_extensions model, name, &block <del> builder = create_builder model, name, scope, options, extension <del> reflection = builder.build(model) <add> reflection = create_reflection model, name, scope, options, extension <ide> define_accessors model, reflection <ide> define_callbacks model, reflection <ide> reflection <ide> end <ide> <del> def self.create_builder(model, name, scope, options, extension = nil) <add> def self.create_reflection(model, name, scope, options, extension = nil) <ide> raise ArgumentError, "association names must be a Symbol" unless name.kind_of?(Symbol) <ide> <ide> if scope.is_a?(Hash) <ide> options = scope <ide> scope = nil <ide> end <ide> <del> new(name, scope, options, extension) <del> end <del> <del> def initialize(name, scope, options, extension) <del> @name = name <del> @options = options <add> validate_options(options) <ide> <del> self.class.validate_options(options) <add> scope = build_scope(scope, extension) <ide> <del> @scope = self.class.build_scope(scope, extension) <add> ActiveRecord::Reflection.create(macro, name, scope, options, model) <ide> end <ide> <ide> def self.build_scope(scope, extension) <ide> def self.wrap_scope(scope, extension) <ide> scope <ide> end <ide> <del> def build(model) <del> ActiveRecord::Reflection.create(self.class.macro, name, scope, options, model) <del> end <del> <ide> def self.macro <ide> raise NotImplementedError <ide> end <ide><path>activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb <ide> def middle_reflection(join_model) <ide> middle_name = [lhs_model.name.downcase.pluralize, <ide> association_name].join('_').gsub(/::/, '_').to_sym <ide> middle_options = middle_options join_model <del> hm_builder = HasMany.create_builder(lhs_model, <del> middle_name, <del> nil, <del> middle_options) <del> hm_builder.build lhs_model <add> <add> HasMany.create_reflection(lhs_model, <add> middle_name, <add> nil, <add> middle_options) <ide> end <ide> <ide> private
2