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
apply fixes from styleci
48cf1e1af27e91a27ed47c6e49905889307c6751
<ide><path>src/Illuminate/Foundation/Testing/Concerns/InteractsWithExceptionHandling.php <ide> protected function withoutExceptionHandling() <ide> $this->previousExceptionHandler = app(ExceptionHandler::class); <ide> <ide> $this->app->instance(ExceptionHandler::class, new class implements ExceptionHandler { <del> public function __construct() {} <del> public function report(Exception $e) {} <del> public function render($request, Exception $e) { <add> public function __construct() <add> { <add> } <add> <add> public function report(Exception $e) <add> { <add> } <add> <add> public function render($request, Exception $e) <add> { <ide> throw $e; <ide> } <del> public function renderForConsole($output, Exception $e) { <add> <add> public function renderForConsole($output, Exception $e) <add> { <ide> (new ConsoleApplication)->renderException($e, $output); <ide> } <ide> });
1
Python
Python
fix typos in corrcoef()
aca82609af048971de362eb74a5f8873a45898cf
<ide><path>numpy/lib/function_base.py <ide> def corrcoef(x, y=None, rowvar=1, bias=0, ddof=None): <ide> ---------- <ide> x : array_like <ide> A 1-D or 2-D array containing multiple variables and observations. <del> Each row of `m` represents a variable, and each column a single <add> Each row of `x` represents a variable, and each column a single <ide> observation of all those variables. Also see `rowvar` below. <ide> y : array_like, optional <ide> An additional set of variables and observations. `y` has the same <del> shape as `m`. <add> shape as `x`. <ide> rowvar : int, optional <ide> If `rowvar` is non-zero (default), then each row represents a <ide> variable, with observations in the columns. Otherwise, the relationship
1
Javascript
Javascript
warn user if we change their texture settings
d45049f2f71b49f1202e9f29642c7473a4450fed
<ide><path>src/renderers/WebGLRenderer.js <ide> THREE.WebGLRenderer = function ( parameters ) { <ide> <ide> _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); <ide> _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); <add> <add> if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping) { <add> console.warn('Texture is not power of two. Texture.wrapS and Texture.wrapT is set to THREE.ClampToEdgeWrapping. ('+texture.sourceFile+')'); <add> } <ide> <ide> _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) ); <ide> _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) ); <ide> <add> if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter) { <add> console.warn('Texture is not power of two. Texture.minFilter is set to THREE.LinearFilter or THREE.NearestFilter. ('+texture.sourceFile+')'); <add> } <ide> } <ide> <ide> extension = extensions.get( 'EXT_texture_filter_anisotropic' );
1
Python
Python
add strftime config option
54e8e7b8dcb8c9ebda1f6840f6a86f1486fda52f
<ide><path>glances/config.py <ide> def __init__(self, config_dir=None): <ide> # Re patern for optimize research of `foo` <ide> self.re_pattern = re.compile(r'(\`.+?\`)') <ide> <del> self.parser = ConfigParser() <add> self.parser = ConfigParser(interpolation=None) <ide> self.read() <ide> <ide> def config_file_paths(self): <ide> def read(self): <ide> self.set_default_cwc('processlist', 'cpu') <ide> self.set_default_cwc('processlist', 'mem') <ide> <add> # Now <add> if not self.parser.has_section('strftime'): <add> self.parser.add_section('strftime') <add> self.set_default('strftime', 'format', '') <add> <ide> @property <ide> def loaded_config_file(self): <ide> """Return the loaded configuration file.""" <ide><path>glances/plugins/glances_now.py <ide> def __init__(self, args=None, config=None): <ide> # Set the message position <ide> self.align = 'bottom' <ide> <add> if config is not None: <add> if 'strftime' in config.as_dict(): <add> self.strftime = config.as_dict()['strftime']['format'] <add> <ide> def reset(self): <ide> """Reset/init the stats.""" <ide> self.stats = '' <ide> def update(self): <ide> """Update current date/time.""" <ide> # Had to convert it to string because datetime is not JSON serializable <ide> # Add the time zone (issue #1249 / #1337 / #1598) <del> if (len(tzname[1]) > 6): <del> self.stats = strftime('%Y-%m-%d %H:%M:%S %z') <add> <add> if self.strftime: <add> self.stats = strftime(self.strftime) <ide> else: <del> self.stats = strftime('%Y-%m-%d %H:%M:%S %Z') <add> if (len(tzname[1]) > 6): <add> self.stats = strftime('%Y-%m-%d %H:%M:%S %z') <add> else: <add> self.stats = strftime('%Y-%m-%d %H:%M:%S %Z') <ide> <ide> return self.stats <ide>
2
Ruby
Ruby
prefer brewed tools [linux]
447baab9a05ca7f860a70adf52017ec69e687a8b
<ide><path>Library/Homebrew/extend/os/linux/development_tools.rb <ide> class DevelopmentTools <ide> class << self <add> def locate(tool) <add> (@locate ||= {}).fetch(tool) do |key| <add> @locate[key] = if (path = HOMEBREW_PREFIX/"bin/#{tool}").executable? <add> path <add> elsif File.executable?(path = "/usr/bin/#{tool}") <add> Pathname.new path <add> end <add> end <add> end <add> <ide> def default_compiler <ide> :gcc <ide> end
1
Java
Java
introduce listenablefuture to websocketclient
62921683fd1b2994302c5c80c16eacd6dc419fe1
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/handler/AnnotationMethodIntegrationTests.java <ide> protected Class<?>[] getAnnotatedConfigClasses() { <ide> public void simpleController() throws Exception { <ide> <ide> TextMessage message = create(StompCommand.SEND).headers("destination:/app/simple").build(); <del> WebSocketSession session = doHandshake(new TestClientWebSocketHandler(0, message), "/ws"); <add> WebSocketSession session = doHandshake(new TestClientWebSocketHandler(0, message), "/ws").get(); <ide> <ide> SimpleController controller = this.wac.getBean(SimpleController.class); <ide> try { <ide> public void incrementController() throws Exception { <ide> "destination:/app/topic/increment").body("5").build(); <ide> <ide> TestClientWebSocketHandler clientHandler = new TestClientWebSocketHandler(1, message1, message2); <del> WebSocketSession session = doHandshake(clientHandler, "/ws"); <add> WebSocketSession session = doHandshake(clientHandler, "/ws").get(); <ide> <ide> try { <ide> assertTrue(clientHandler.latch.await(2, TimeUnit.SECONDS)); <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/client/AbstractWebSocketClient.java <ide> import org.apache.commons.logging.LogFactory; <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.util.Assert; <add>import org.springframework.util.concurrent.ListenableFuture; <ide> import org.springframework.web.socket.WebSocketHandler; <ide> import org.springframework.web.socket.WebSocketSession; <ide> import org.springframework.web.util.UriComponentsBuilder; <ide> public abstract class AbstractWebSocketClient implements WebSocketClient { <ide> <ide> <ide> @Override <del> public WebSocketSession doHandshake(WebSocketHandler webSocketHandler, String uriTemplate, <del> Object... uriVars) throws WebSocketConnectFailureException { <add> public ListenableFuture<WebSocketSession> doHandshake(WebSocketHandler webSocketHandler, <add> String uriTemplate, Object... uriVars) { <ide> <ide> Assert.notNull(uriTemplate, "uriTemplate must not be null"); <ide> URI uri = UriComponentsBuilder.fromUriString(uriTemplate).buildAndExpand(uriVars).encode().toUri(); <ide> return doHandshake(webSocketHandler, null, uri); <ide> } <ide> <ide> @Override <del> public final WebSocketSession doHandshake(WebSocketHandler webSocketHandler, <del> HttpHeaders headers, URI uri) throws WebSocketConnectFailureException { <add> public final ListenableFuture<WebSocketSession> doHandshake(WebSocketHandler webSocketHandler, <add> HttpHeaders headers, URI uri) { <ide> <ide> Assert.notNull(webSocketHandler, "webSocketHandler must not be null"); <ide> Assert.notNull(uri, "uri must not be null"); <ide> public final WebSocketSession doHandshake(WebSocketHandler webSocketHandler, <ide> * @param handshakeAttributes attributes to make available via <ide> * {@link WebSocketSession#getHandshakeAttributes()}; currently always an empty map. <ide> * <del> * @return the established WebSocket session <del> * <del> * @throws WebSocketConnectFailureException <add> * @return the established WebSocket session wrapped in a ListenableFuture. <ide> */ <del> protected abstract WebSocketSession doHandshakeInternal(WebSocketHandler webSocketHandler, <del> HttpHeaders headers, URI uri, List<String> subProtocols, <del> Map<String, Object> handshakeAttributes) throws WebSocketConnectFailureException; <add> protected abstract ListenableFuture<WebSocketSession> doHandshakeInternal(WebSocketHandler webSocketHandler, <add> HttpHeaders headers, URI uri, List<String> subProtocols, Map<String, Object> handshakeAttributes); <ide> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/client/ConnectionManagerSupport.java <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <ide> import org.springframework.context.SmartLifecycle; <del>import org.springframework.core.task.SimpleAsyncTaskExecutor; <del>import org.springframework.core.task.TaskExecutor; <ide> import org.springframework.web.util.UriComponentsBuilder; <ide> <ide> /** <ide> public abstract class ConnectionManagerSupport implements SmartLifecycle { <ide> <ide> private int phase = Integer.MAX_VALUE; <ide> <del> private final TaskExecutor taskExecutor = new SimpleAsyncTaskExecutor("EndpointConnectionManager-"); <del> <ide> private final Object lifecycleMonitor = new Object(); <ide> <ide> <ide> public final void start() { <ide> } <ide> <ide> protected void startInternal() { <del> if (logger.isDebugEnabled()) { <del> logger.debug("Starting " + this.getClass().getSimpleName()); <del> } <del> this.isRunning = true; <del> this.taskExecutor.execute(new Runnable() { <del> @Override <del> public void run() { <del> synchronized (lifecycleMonitor) { <del> try { <del> logger.info("Connecting to WebSocket at " + uri); <del> openConnection(); <del> logger.info("Successfully connected"); <del> } <del> catch (Throwable ex) { <del> logger.error("Failed to connect", ex); <del> } <del> } <add> synchronized (lifecycleMonitor) { <add> if (logger.isDebugEnabled()) { <add> logger.debug("Starting " + this.getClass().getSimpleName()); <ide> } <del> }); <add> this.isRunning = true; <add> openConnection(); <add> } <ide> } <ide> <del> protected abstract void openConnection() throws Exception; <add> protected abstract void openConnection(); <ide> <ide> @Override <ide> public final void stop() { <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/client/WebSocketClient.java <ide> import java.net.URI; <ide> <ide> import org.springframework.http.HttpHeaders; <add>import org.springframework.util.concurrent.ListenableFuture; <ide> import org.springframework.web.socket.WebSocketHandler; <ide> import org.springframework.web.socket.WebSocketSession; <ide> <ide> */ <ide> public interface WebSocketClient { <ide> <del> WebSocketSession doHandshake(WebSocketHandler webSocketHandler, <del> String uriTemplate, Object... uriVariables) throws WebSocketConnectFailureException; <add> ListenableFuture<WebSocketSession> doHandshake(WebSocketHandler webSocketHandler, <add> String uriTemplate, Object... uriVariables); <ide> <del> WebSocketSession doHandshake(WebSocketHandler webSocketHandler, HttpHeaders headers, URI uri) <del> throws WebSocketConnectFailureException; <add> ListenableFuture<WebSocketSession> doHandshake(WebSocketHandler webSocketHandler, HttpHeaders headers, URI uri); <ide> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/client/WebSocketConnectFailureException.java <del>/* <del> * Copyright 2002-2013 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> <del>package org.springframework.web.socket.client; <del> <del>import org.springframework.core.NestedRuntimeException; <del> <del>/** <del> * Thrown when a WebSocket connection to a server could not be established. <del> * <del> * @author Rossen Stoyanchev <del> * @since 4.0 <del> */ <del>@SuppressWarnings("serial") <del>public class WebSocketConnectFailureException extends NestedRuntimeException { <del> <del> public WebSocketConnectFailureException(String msg, Throwable cause) { <del> super(msg, cause); <del> } <del> <del> public WebSocketConnectFailureException(String msg) { <del> super(msg); <del> } <del> <del>} <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/client/WebSocketConnectionManager.java <ide> <ide> import org.springframework.context.SmartLifecycle; <ide> import org.springframework.http.HttpHeaders; <add>import org.springframework.util.concurrent.ListenableFuture; <add>import org.springframework.util.concurrent.ListenableFutureCallback; <ide> import org.springframework.web.socket.WebSocketHandler; <ide> import org.springframework.web.socket.WebSocketSession; <ide> import org.springframework.web.socket.support.LoggingWebSocketHandlerDecorator; <ide> public void stopInternal() throws Exception { <ide> } <ide> <ide> @Override <del> protected void openConnection() throws Exception { <del> this.webSocketSession = this.client.doHandshake(this.webSocketHandler, this.headers, getUri()); <add> protected void openConnection() { <add> <add> logger.info("Connecting to WebSocket at " + getUri()); <add> <add> ListenableFuture<WebSocketSession> future = <add> this.client.doHandshake(this.webSocketHandler, this.headers, getUri()); <add> <add> future.addCallback(new ListenableFutureCallback<WebSocketSession>() { <add> @Override <add> public void onSuccess(WebSocketSession result) { <add> webSocketSession = result; <add> logger.info("Successfully connected"); <add> } <add> @Override <add> public void onFailure(Throwable t) { <add> logger.error("Failed to connect", t); <add> } <add> }); <ide> } <ide> <ide> @Override <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/client/endpoint/AnnotatedEndpointConnectionManager.java <ide> import org.springframework.beans.BeansException; <ide> import org.springframework.beans.factory.BeanFactory; <ide> import org.springframework.beans.factory.BeanFactoryAware; <add>import org.springframework.core.task.SimpleAsyncTaskExecutor; <add>import org.springframework.core.task.TaskExecutor; <add>import org.springframework.util.Assert; <ide> import org.springframework.web.socket.client.ConnectionManagerSupport; <ide> import org.springframework.web.socket.support.BeanCreatingHandlerProvider; <ide> <ide> public class AnnotatedEndpointConnectionManager extends ConnectionManagerSupport <ide> <ide> private Session session; <ide> <add> private TaskExecutor taskExecutor = new SimpleAsyncTaskExecutor("AnnotatedEndpointConnectionManager-"); <add> <ide> <ide> public AnnotatedEndpointConnectionManager(Object endpoint, String uriTemplate, Object... uriVariables) { <ide> super(uriTemplate, uriVariables); <ide> public void setBeanFactory(BeanFactory beanFactory) throws BeansException { <ide> } <ide> } <ide> <add> /** <add> * Set a {@link TaskExecutor} to use to open the connection. <add> * By default {@link SimpleAsyncTaskExecutor} is used. <add> */ <add> public void setTaskExecutor(TaskExecutor taskExecutor) { <add> Assert.notNull(taskExecutor, "taskExecutor is required"); <add> this.taskExecutor = taskExecutor; <add> } <add> <add> /** <add> * Return the configured {@link TaskExecutor}. <add> */ <add> public TaskExecutor getTaskExecutor() { <add> return this.taskExecutor; <add> } <add> <ide> @Override <del> protected void openConnection() throws Exception { <del> Object endpoint = (this.endpoint != null) ? this.endpoint : this.endpointProvider.getHandler(); <del> this.session = this.webSocketContainer.connectToServer(endpoint, getUri()); <add> protected void openConnection() { <add> this.taskExecutor.execute(new Runnable() { <add> @Override <add> public void run() { <add> try { <add> logger.info("Connecting to WebSocket at " + getUri()); <add> Object endpointToUse = (endpoint != null) ? endpoint : endpointProvider.getHandler(); <add> session = webSocketContainer.connectToServer(endpointToUse, getUri()); <add> logger.info("Successfully connected"); <add> } <add> catch (Throwable ex) { <add> logger.error("Failed to connect", ex); <add> } <add> } <add> }); <ide> } <ide> <ide> @Override <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/client/endpoint/EndpointConnectionManager.java <ide> import org.springframework.beans.BeansException; <ide> import org.springframework.beans.factory.BeanFactory; <ide> import org.springframework.beans.factory.BeanFactoryAware; <add>import org.springframework.core.task.SimpleAsyncTaskExecutor; <add>import org.springframework.core.task.TaskExecutor; <ide> import org.springframework.util.Assert; <ide> import org.springframework.web.socket.client.ConnectionManagerSupport; <ide> import org.springframework.web.socket.support.BeanCreatingHandlerProvider; <ide> public class EndpointConnectionManager extends ConnectionManagerSupport implemen <ide> <ide> private Session session; <ide> <add> private TaskExecutor taskExecutor = new SimpleAsyncTaskExecutor("EndpointConnectionManager-"); <add> <ide> <ide> public EndpointConnectionManager(Endpoint endpoint, String uriTemplate, Object... uriVariables) { <ide> super(uriTemplate, uriVariables); <ide> public void setBeanFactory(BeanFactory beanFactory) throws BeansException { <ide> } <ide> } <ide> <add> /** <add> * Set a {@link TaskExecutor} to use to open connections. <add> * By default {@link SimpleAsyncTaskExecutor} is used. <add> */ <add> public void setTaskExecutor(TaskExecutor taskExecutor) { <add> Assert.notNull(taskExecutor, "taskExecutor is required"); <add> this.taskExecutor = taskExecutor; <add> } <add> <add> /** <add> * Return the configured {@link TaskExecutor}. <add> */ <add> public TaskExecutor getTaskExecutor() { <add> return this.taskExecutor; <add> } <add> <add> <ide> @Override <del> protected void openConnection() throws Exception { <del> Endpoint endpoint = (this.endpoint != null) ? this.endpoint : this.endpointProvider.getHandler(); <del> ClientEndpointConfig endpointConfig = this.configBuilder.build(); <del> this.session = getWebSocketContainer().connectToServer(endpoint, endpointConfig, getUri()); <add> protected void openConnection() { <add> this.taskExecutor.execute(new Runnable() { <add> @Override <add> public void run() { <add> try { <add> logger.info("Connecting to WebSocket at " + getUri()); <add> Endpoint endpointToUse = (endpoint != null) ? endpoint : endpointProvider.getHandler(); <add> ClientEndpointConfig endpointConfig = configBuilder.build(); <add> session = getWebSocketContainer().connectToServer(endpointToUse, endpointConfig, getUri()); <add> logger.info("Successfully connected"); <add> } <add> catch (Throwable ex) { <add> logger.error("Failed to connect", ex); <add> } <add> } <add> }); <ide> } <ide> <ide> @Override <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/client/endpoint/StandardWebSocketClient.java <ide> import java.util.List; <ide> import java.util.Locale; <ide> import java.util.Map; <add>import java.util.concurrent.Callable; <ide> <ide> import javax.websocket.ClientEndpointConfig; <ide> import javax.websocket.ClientEndpointConfig.Configurator; <ide> import javax.websocket.HandshakeResponse; <ide> import javax.websocket.WebSocketContainer; <ide> <add>import org.springframework.core.task.AsyncListenableTaskExecutor; <add>import org.springframework.core.task.SimpleAsyncTaskExecutor; <add>import org.springframework.core.task.TaskExecutor; <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.util.Assert; <add>import org.springframework.util.concurrent.ListenableFuture; <ide> import org.springframework.web.socket.WebSocketHandler; <ide> import org.springframework.web.socket.WebSocketSession; <ide> import org.springframework.web.socket.adapter.StandardWebSocketHandlerAdapter; <ide> import org.springframework.web.socket.adapter.StandardWebSocketSession; <ide> import org.springframework.web.socket.client.AbstractWebSocketClient; <del>import org.springframework.web.socket.client.WebSocketConnectFailureException; <ide> <ide> /** <ide> * Initiates WebSocket requests to a WebSocket server programatically through the standard <ide> public class StandardWebSocketClient extends AbstractWebSocketClient { <ide> <ide> private final WebSocketContainer webSocketContainer; <ide> <add> private AsyncListenableTaskExecutor taskExecutor = <add> new SimpleAsyncTaskExecutor("WebSocketClient-"); <add> <ide> <ide> /** <ide> * Default constructor that calls {@code ContainerProvider.getWebSocketContainer()} to <ide> public StandardWebSocketClient(WebSocketContainer webSocketContainer) { <ide> this.webSocketContainer = webSocketContainer; <ide> } <ide> <add> /** <add> * Set a {@link TaskExecutor} to use to open the connection. <add> * By default {@link SimpleAsyncTaskExecutor} is used. <add> */ <add> public void setTaskExecutor(AsyncListenableTaskExecutor taskExecutor) { <add> Assert.notNull(taskExecutor, "taskExecutor is required"); <add> this.taskExecutor = taskExecutor; <add> } <add> <add> /** <add> * Return the configured {@link TaskExecutor}. <add> */ <add> public AsyncListenableTaskExecutor getTaskExecutor() { <add> return this.taskExecutor; <add> } <ide> <ide> @Override <del> protected WebSocketSession doHandshakeInternal(WebSocketHandler webSocketHandler, <del> HttpHeaders headers, URI uri, List<String> protocols, <del> Map<String, Object> handshakeAttributes) throws WebSocketConnectFailureException { <add> protected ListenableFuture<WebSocketSession> doHandshakeInternal(WebSocketHandler webSocketHandler, <add> HttpHeaders headers, final URI uri, List<String> protocols, Map<String, Object> handshakeAttributes) { <ide> <ide> int port = getPort(uri); <ide> InetSocketAddress localAddress = new InetSocketAddress(getLocalHost(), port); <ide> InetSocketAddress remoteAddress = new InetSocketAddress(uri.getHost(), port); <ide> <del> StandardWebSocketSession session = new StandardWebSocketSession(headers, <add> final StandardWebSocketSession session = new StandardWebSocketSession(headers, <ide> handshakeAttributes, localAddress, remoteAddress); <ide> <del> ClientEndpointConfig.Builder configBuidler = ClientEndpointConfig.Builder.create(); <add> final ClientEndpointConfig.Builder configBuidler = ClientEndpointConfig.Builder.create(); <ide> configBuidler.configurator(new StandardWebSocketClientConfigurator(headers)); <ide> configBuidler.preferredSubprotocols(protocols); <add> final Endpoint endpoint = new StandardWebSocketHandlerAdapter(webSocketHandler, session); <ide> <del> try { <del> Endpoint endpoint = new StandardWebSocketHandlerAdapter(webSocketHandler, session); <del> this.webSocketContainer.connectToServer(endpoint, configBuidler.build(), uri); <del> return session; <del> } <del> catch (Exception e) { <del> throw new WebSocketConnectFailureException("Failed to connect to " + uri, e); <del> } <add> return this.taskExecutor.submitListenable(new Callable<WebSocketSession>() { <add> @Override <add> public WebSocketSession call() throws Exception { <add> webSocketContainer.connectToServer(endpoint, configBuidler.build(), uri); <add> return session; <add> } <add> }); <ide> } <ide> <ide> private InetAddress getLocalHost() { <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/client/jetty/JettyWebSocketClient.java <ide> import java.security.Principal; <ide> import java.util.List; <ide> import java.util.Map; <add>import java.util.concurrent.Callable; <ide> import java.util.concurrent.Future; <ide> <ide> import org.eclipse.jetty.websocket.api.Session; <ide> import org.eclipse.jetty.websocket.client.ClientUpgradeRequest; <ide> import org.eclipse.jetty.websocket.client.WebSocketClient; <ide> import org.springframework.context.SmartLifecycle; <add>import org.springframework.core.task.AsyncListenableTaskExecutor; <add>import org.springframework.core.task.SimpleAsyncTaskExecutor; <add>import org.springframework.core.task.TaskExecutor; <ide> import org.springframework.http.HttpHeaders; <add>import org.springframework.util.Assert; <add>import org.springframework.util.concurrent.ListenableFuture; <ide> import org.springframework.web.socket.WebSocketHandler; <ide> import org.springframework.web.socket.WebSocketSession; <ide> import org.springframework.web.socket.adapter.JettyWebSocketHandlerAdapter; <ide> import org.springframework.web.socket.adapter.JettyWebSocketSession; <ide> import org.springframework.web.socket.client.AbstractWebSocketClient; <del>import org.springframework.web.socket.client.WebSocketConnectFailureException; <ide> import org.springframework.web.util.UriComponents; <ide> import org.springframework.web.util.UriComponentsBuilder; <ide> <ide> public class JettyWebSocketClient extends AbstractWebSocketClient implements Sma <ide> <ide> private final Object lifecycleMonitor = new Object(); <ide> <add> private AsyncListenableTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor("WebSocketClient-"); <add> <ide> <ide> /** <ide> * Default constructor that creates an instance of <ide> public JettyWebSocketClient(WebSocketClient client) { <ide> } <ide> <ide> <add> /** <add> * Set a {@link TaskExecutor} to use to open the connection. <add> * By default {@link SimpleAsyncTaskExecutor} is used. <add> */ <add> public void setTaskExecutor(AsyncListenableTaskExecutor taskExecutor) { <add> Assert.notNull(taskExecutor, "taskExecutor is required"); <add> this.taskExecutor = taskExecutor; <add> } <add> <add> /** <add> * Return the configured {@link TaskExecutor}. <add> */ <add> public AsyncListenableTaskExecutor getTaskExecutor() { <add> return this.taskExecutor; <add> } <add> <ide> public void setAutoStartup(boolean autoStartup) { <ide> this.autoStartup = autoStartup; <ide> } <ide> public void stop(Runnable callback) { <ide> } <ide> <ide> @Override <del> public WebSocketSession doHandshake(WebSocketHandler webSocketHandler, String uriTemplate, Object... uriVars) <del> throws WebSocketConnectFailureException { <add> public ListenableFuture<WebSocketSession> doHandshake(WebSocketHandler webSocketHandler, <add> String uriTemplate, Object... uriVars) { <ide> <ide> UriComponents uriComponents = UriComponentsBuilder.fromUriString(uriTemplate).buildAndExpand(uriVars).encode(); <ide> return doHandshake(webSocketHandler, null, uriComponents.toUri()); <ide> } <ide> <ide> @Override <del> public WebSocketSession doHandshakeInternal(WebSocketHandler wsHandler, HttpHeaders headers, <del> URI uri, List<String> protocols, Map<String, Object> handshakeAttributes) <del> throws WebSocketConnectFailureException { <add> public ListenableFuture<WebSocketSession> doHandshakeInternal(WebSocketHandler wsHandler, <add> HttpHeaders headers, final URI uri, List<String> protocols, Map<String, Object> handshakeAttributes) { <ide> <del> ClientUpgradeRequest request = new ClientUpgradeRequest(); <add> final ClientUpgradeRequest request = new ClientUpgradeRequest(); <ide> request.setSubProtocols(protocols); <ide> for (String header : headers.keySet()) { <ide> request.setHeader(header, headers.get(header)); <ide> } <ide> <ide> Principal user = getUser(); <del> JettyWebSocketSession wsSession = new JettyWebSocketSession(user, handshakeAttributes); <del> JettyWebSocketHandlerAdapter listener = new JettyWebSocketHandlerAdapter(wsHandler, wsSession); <del> <del> try { <del> Future<Session> future = this.client.connect(listener, uri, request); <del> future.get(); <del> return wsSession; <del> } <del> catch (Exception e) { <del> throw new WebSocketConnectFailureException("Failed to connect to " + uri, e); <del> } <add> final JettyWebSocketSession wsSession = new JettyWebSocketSession(user, handshakeAttributes); <add> final JettyWebSocketHandlerAdapter listener = new JettyWebSocketHandlerAdapter(wsHandler, wsSession); <add> <add> return this.taskExecutor.submitListenable(new Callable<WebSocketSession>() { <add> @Override <add> public WebSocketSession call() throws Exception { <add> Future<Session> future = client.connect(listener, uri, request); <add> future.get(); <add> return wsSession; <add> } <add> }); <ide> } <ide> <del> <ide> /** <ide> * @return the user to make available through {@link WebSocketSession#getPrincipal()}; <ide> * by default this method returns {@code null} <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/AbstractWebSocketIntegrationTests.java <ide> import org.springframework.context.Lifecycle; <ide> import org.springframework.context.annotation.Bean; <ide> import org.springframework.context.annotation.Configuration; <add>import org.springframework.util.concurrent.ListenableFuture; <ide> import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; <ide> import org.springframework.web.socket.client.WebSocketClient; <ide> import org.springframework.web.socket.server.DefaultHandshakeHandler; <ide> protected String getWsBaseUrl() { <ide> return "ws://localhost:" + this.server.getPort(); <ide> } <ide> <del> protected WebSocketSession doHandshake(WebSocketHandler clientHandler, String endpointPath) { <add> protected ListenableFuture<WebSocketSession> doHandshake(WebSocketHandler clientHandler, String endpointPath) { <ide> return this.webSocketClient.doHandshake(clientHandler, getWsBaseUrl() + endpointPath); <ide> } <ide> <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/TomcatWebSocketTestServer.java <ide> import org.apache.coyote.http11.Http11NioProtocol; <ide> import org.apache.tomcat.util.descriptor.web.ApplicationListener; <ide> import org.apache.tomcat.websocket.server.WsListener; <del>import org.springframework.core.NestedRuntimeException; <ide> import org.springframework.util.SocketUtils; <ide> import org.springframework.web.context.WebApplicationContext; <ide> import org.springframework.web.servlet.DispatcherServlet; <ide> private File createTempDir(String prefix) { <ide> return tempFolder; <ide> } <ide> catch (IOException ex) { <del> throw new NestedRuntimeException("Unable to create temp directory", ex) {}; <add> throw new RuntimeException("Unable to create temp directory", ex); <ide> } <ide> } <ide> <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/client/WebSocketConnectionManagerTests.java <ide> import java.net.URI; <ide> import java.util.Arrays; <ide> import java.util.List; <add>import java.util.concurrent.Callable; <ide> <ide> import org.junit.Test; <del>import org.mockito.ArgumentCaptor; <ide> import org.springframework.context.SmartLifecycle; <ide> import org.springframework.http.HttpHeaders; <add>import org.springframework.util.concurrent.ListenableFuture; <add>import org.springframework.util.concurrent.ListenableFutureTask; <ide> import org.springframework.web.socket.WebSocketHandler; <ide> import org.springframework.web.socket.WebSocketSession; <ide> import org.springframework.web.socket.adapter.WebSocketHandlerAdapter; <ide> import org.springframework.web.socket.support.LoggingWebSocketHandlerDecorator; <ide> import org.springframework.web.socket.support.WebSocketHandlerDecorator; <add>import org.springframework.web.util.UriComponentsBuilder; <ide> <ide> import static org.junit.Assert.*; <del>import static org.mockito.Mockito.*; <ide> <ide> /** <ide> * Test fixture for {@link WebSocketConnectionManager}. <ide> public void openConnection() throws Exception { <ide> <ide> List<String> subprotocols = Arrays.asList("abc"); <ide> <del> WebSocketClient client = mock(WebSocketClient.class); <add> TestLifecycleWebSocketClient client = new TestLifecycleWebSocketClient(false); <ide> WebSocketHandler handler = new WebSocketHandlerAdapter(); <ide> <ide> WebSocketConnectionManager manager = new WebSocketConnectionManager(client, handler , "/path/{id}", "123"); <ide> manager.setSubProtocols(subprotocols); <ide> manager.openConnection(); <ide> <del> ArgumentCaptor<WebSocketHandlerDecorator> captor = ArgumentCaptor.forClass(WebSocketHandlerDecorator.class); <del> ArgumentCaptor<HttpHeaders> headersCaptor = ArgumentCaptor.forClass(HttpHeaders.class); <del> ArgumentCaptor<URI> uriCaptor = ArgumentCaptor.forClass(URI.class); <del> <del> verify(client).doHandshake(captor.capture(), headersCaptor.capture(), uriCaptor.capture()); <del> <ide> HttpHeaders expectedHeaders = new HttpHeaders(); <ide> expectedHeaders.setSecWebSocketProtocol(subprotocols); <ide> <del> assertEquals(expectedHeaders, headersCaptor.getValue()); <del> assertEquals(new URI("/path/123"), uriCaptor.getValue()); <add> assertEquals(expectedHeaders, client.headers); <add> assertEquals(new URI("/path/123"), client.uri); <ide> <del> WebSocketHandlerDecorator loggingHandler = captor.getValue(); <add> WebSocketHandlerDecorator loggingHandler = (WebSocketHandlerDecorator) client.webSocketHandler; <ide> assertEquals(LoggingWebSocketHandlerDecorator.class, loggingHandler.getClass()); <ide> <ide> assertSame(handler, loggingHandler.getDelegate()); <ide> private static class TestLifecycleWebSocketClient implements WebSocketClient, Sm <ide> <ide> private boolean running; <ide> <add> private WebSocketHandler webSocketHandler; <add> <add> private HttpHeaders headers; <add> <add> private URI uri; <add> <add> <ide> public TestLifecycleWebSocketClient(boolean running) { <ide> this.running = running; <ide> } <ide> public void stop(Runnable callback) { <ide> } <ide> <ide> @Override <del> public WebSocketSession doHandshake(WebSocketHandler webSocketHandler, String uriTemplate, Object... uriVariables) <del> throws WebSocketConnectFailureException { <del> return null; <add> public ListenableFuture<WebSocketSession> doHandshake(WebSocketHandler webSocketHandler, <add> String uriTemplate, Object... uriVars) { <add> <add> URI uri = UriComponentsBuilder.fromUriString(uriTemplate).buildAndExpand(uriVars).encode().toUri(); <add> return doHandshake(webSocketHandler, null, uri); <ide> } <ide> <ide> @Override <del> public WebSocketSession doHandshake(WebSocketHandler webSocketHandler, HttpHeaders headers, URI uri) <del> throws WebSocketConnectFailureException { <del> return null; <add> public ListenableFuture<WebSocketSession> doHandshake(WebSocketHandler webSocketHandler, <add> HttpHeaders headers, URI uri) { <add> <add> this.webSocketHandler = webSocketHandler; <add> this.headers = headers; <add> this.uri = uri; <add> <add> return new ListenableFutureTask<WebSocketSession>(new Callable<WebSocketSession>() { <add> @Override <add> public WebSocketSession call() throws Exception { <add> return null; <add> } <add> }); <ide> } <ide> } <ide> <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/client/endpoint/StandardWebSocketClientTests.java <ide> public void setup() { <ide> @Test <ide> public void localAddress() throws Exception { <ide> URI uri = new URI("ws://example.com/abc"); <del> WebSocketSession session = this.wsClient.doHandshake(this.wsHandler, this.headers, uri); <add> WebSocketSession session = this.wsClient.doHandshake(this.wsHandler, this.headers, uri).get(); <ide> <ide> assertNotNull(session.getLocalAddress()); <ide> assertEquals(80, session.getLocalAddress().getPort()); <ide> public void localAddress() throws Exception { <ide> @Test <ide> public void localAddressWss() throws Exception { <ide> URI uri = new URI("wss://example.com/abc"); <del> WebSocketSession session = this.wsClient.doHandshake(this.wsHandler, this.headers, uri); <add> WebSocketSession session = this.wsClient.doHandshake(this.wsHandler, this.headers, uri).get(); <ide> <ide> assertNotNull(session.getLocalAddress()); <ide> assertEquals(443, session.getLocalAddress().getPort()); <ide> public void localAddressNoScheme() throws Exception { <ide> @Test <ide> public void remoteAddress() throws Exception { <ide> URI uri = new URI("wss://example.com/abc"); <del> WebSocketSession session = this.wsClient.doHandshake(this.wsHandler, this.headers, uri); <add> WebSocketSession session = this.wsClient.doHandshake(this.wsHandler, this.headers, uri).get(); <ide> <ide> assertNotNull(session.getRemoteAddress()); <ide> assertEquals("example.com", session.getRemoteAddress().getHostName()); <ide> public void headersWebSocketSession() throws Exception { <ide> this.headers.setSecWebSocketProtocol(protocols); <ide> this.headers.add("foo", "bar"); <ide> <del> WebSocketSession session = this.wsClient.doHandshake(this.wsHandler, this.headers, uri); <add> WebSocketSession session = this.wsClient.doHandshake(this.wsHandler, this.headers, uri).get(); <ide> <ide> assertEquals(Collections.singletonMap("foo", Arrays.asList("bar")), session.getHandshakeHeaders()); <ide> } <ide> public void headersClientEndpointConfigurator() throws Exception { <ide> this.headers.setSecWebSocketProtocol(protocols); <ide> this.headers.add("foo", "bar"); <ide> <del> this.wsClient.doHandshake(this.wsHandler, this.headers, uri); <add> this.wsClient.doHandshake(this.wsHandler, this.headers, uri).get(); <ide> <ide> ArgumentCaptor<Endpoint> arg1 = ArgumentCaptor.forClass(Endpoint.class); <ide> ArgumentCaptor<ClientEndpointConfig> arg2 = ArgumentCaptor.forClass(ClientEndpointConfig.class); <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/client/jetty/JettyWebSocketClientTests.java <ide> public void doHandshake() throws Exception { <ide> HttpHeaders headers = new HttpHeaders(); <ide> headers.setSecWebSocketProtocol(Arrays.asList("echo")); <ide> <del> this.wsSession = this.client.doHandshake(new TextWebSocketHandlerAdapter(), headers, new URI(this.wsUrl)); <add> this.wsSession = this.client.doHandshake(new TextWebSocketHandlerAdapter(), headers, new URI(this.wsUrl)).get(); <ide> <ide> assertEquals(this.wsUrl, this.wsSession.getUri().toString()); <ide> assertEquals("echo", this.wsSession.getAcceptedProtocol()); <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/server/config/WebSocketConfigurationTests.java <ide> protected Class<?>[] getAnnotatedConfigClasses() { <ide> @Test <ide> public void registerWebSocketHandler() throws Exception { <ide> <del> WebSocketSession session = <del> this.webSocketClient.doHandshake(new WebSocketHandlerAdapter(), getWsBaseUrl() + "/ws"); <add> WebSocketSession session = this.webSocketClient.doHandshake( <add> new WebSocketHandlerAdapter(), getWsBaseUrl() + "/ws").get(); <ide> <ide> TestWebSocketHandler serverHandler = this.wac.getBean(TestWebSocketHandler.class); <ide> assertTrue(serverHandler.latch.await(2, TimeUnit.SECONDS)); <ide> public void registerWebSocketHandler() throws Exception { <ide> @Test <ide> public void registerWebSocketHandlerWithSockJS() throws Exception { <ide> <del> WebSocketSession session = <del> this.webSocketClient.doHandshake(new WebSocketHandlerAdapter(), getWsBaseUrl() + "/sockjs/websocket"); <add> WebSocketSession session = this.webSocketClient.doHandshake( <add> new WebSocketHandlerAdapter(), getWsBaseUrl() + "/sockjs/websocket").get(); <ide> <ide> TestWebSocketHandler serverHandler = this.wac.getBean(TestWebSocketHandler.class); <ide> assertTrue(serverHandler.latch.await(2, TimeUnit.SECONDS));
16
Ruby
Ruby
improve docs for formula#python (python_helper)
5bb82e30713683a81955435f02724dad6c20663a
<ide><path>Library/Homebrew/formula.rb <ide> def std_cmake_args <ide> ] <ide> end <ide> <add> # Install python bindings inside of a block given to this method and/or <add> # call python so: `system python, "setup.py", "install", "--prefix=#{prefix}" <add> # Note that there are no quotation marks around python! <add> # <https://github.com/mxcl/homebrew/wiki/Homebrew-and-Python> <ide> def python(options={:allowed_major_versions => [2, 3]}, &block) <ide> require 'python_helper' <ide> python_helper(options, &block)
1
Javascript
Javascript
add test case verifying the repl options usage
a33d1c959a449115883b42753f5140541561ba2b
<ide><path>test/simple/test-repl-options.js <add>// Copyright Joyent, Inc. and other Node contributors. <add>// <add>// Permission is hereby granted, free of charge, to any person obtaining a <add>// copy of this software and associated documentation files (the <add>// "Software"), to deal in the Software without restriction, including <add>// without limitation the rights to use, copy, modify, merge, publish, <add>// distribute, sublicense, and/or sell copies of the Software, and to permit <add>// persons to whom the Software is furnished to do so, subject to the <add>// following conditions: <add>// <add>// The above copyright notice and this permission notice shall be included <add>// in all copies or substantial portions of the Software. <add>// <add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS <add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF <add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN <add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, <add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR <add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <add>// USE OR OTHER DEALINGS IN THE SOFTWARE. <add> <add>var common = require('../common'), <add> assert = require('assert'), <add> Stream = require('stream'), <add> repl = require('repl'); <add> <add>// create a dummy stream that does nothing <add>var stream = new Stream(); <add>stream.write = stream.pause = stream.resume = function(){}; <add>stream.readable = stream.writable = true; <add> <add>// 1, mostly defaults <add>var r1 = repl.start({ <add> input: stream, <add> output: stream, <add> terminal: true <add>}); <add>assert.equal(r1.rli.input, stream); <add>assert.equal(r1.rli.output, stream); <add>assert.equal(r1.rli.input, r1.inputStream); <add>assert.equal(r1.rli.output, r1.outputStream); <add>assert.equal(r1.rli.terminal, true); <add>assert.equal(r1.useGlobal, false); <add>assert.equal(r1.ignoreUndefined, false); <add> <add>// 2 <add>function writer() {} <add>function evaler() {} <add>var r2 = repl.start({ <add> input: stream, <add> output: stream, <add> terminal: false, <add> useGlobal: true, <add> ignoreUndefined: true, <add> eval: evaler, <add> writer: writer <add>}); <add>assert.equal(r2.rli.input, stream); <add>assert.equal(r2.rli.output, stream); <add>assert.equal(r2.rli.input, r2.inputStream); <add>assert.equal(r2.rli.output, r2.outputStream); <add>assert.equal(r2.rli.terminal, false); <add>assert.equal(r2.useGlobal, true); <add>assert.equal(r2.ignoreUndefined, true); <add>assert.equal(r2.eval, evaler); <add>assert.equal(r2.writer, writer);
1
Javascript
Javascript
add isolates support
42281124d4b83b0e99baf5d56b696ef242399f51
<ide><path>lib/child_process.js <ide> exports.fork = function(modulePath, args, options) { <ide> args = args ? args.slice(0) : []; <ide> args.unshift(modulePath); <ide> <del> if (options.thread) { <del> if (!process.features.isolates) { <del> throw new Error('node compiled without isolate support'); <del> } <del> } <del> <ide> if (options.stdinStream) { <ide> throw new Error('stdinStream not allowed for fork()'); <ide> } <ide> exports.fork = function(modulePath, args, options) { <ide> options.env.NODE_CHANNEL_FD = 42; <ide> <ide> // stdin is the IPC channel. <del> options.stdinStream = createPipe(true); <add> if (!options.thread) options.stdinStream = createPipe(true); <ide> <ide> var child = spawn(process.execPath, args, options); <ide> <del> setupChannel(child, options.stdinStream); <add> if (!options.thread) setupChannel(child, options.stdinStream); <ide> <ide> child.on('exit', function() { <ide> if (child._channel) { <ide> var spawn = exports.spawn = function(file, args, options) { <ide> envPairs.push(key + '=' + env[key]); <ide> } <ide> <del> var child = new ChildProcess(); <add> var child = (options && options.thread) ? (new Isolate) : (new ChildProcess); <ide> <ide> child.spawn({ <ide> file: file, <ide> ChildProcess.prototype.kill = function(sig) { <ide> // TODO: raise error if r == -1? <ide> } <ide> }; <add> <add> <add>// Lazy loaded. <add>var isolates = null; <add> <add> <add>function Isolate() { <add> if (!process.features.isolates) { <add> throw new Error('Compiled without isolates support.'); <add> } <add> <add> if (!isolates) { <add> isolates = process.binding('isolates'); <add> } <add> <add> this._handle = null; <add>} <add>inherits(Isolate, EventEmitter); // maybe inherit from ChildProcess? <add> <add> <add>Isolate.prototype.spawn = function(options) { <add> var self = this; <add> <add> if (self._handle) throw new Error('Isolate already running.'); <add> self._handle = isolates.create(options.args); <add> if (!self._handle) throw new Error('Cannot create isolate.'); <add> <add> self._handle.onmessage = function(msg) { <add> msg = JSON.parse('' + msg); <add> self.emit('message', msg); <add> }; <add> <add> self._handle.onexit = function() { <add> self._handle = null; <add> self.emit('exit'); <add> }; <add>}; <add> <add> <add>Isolate.prototype.kill = function(sig) { <add> if (!this._handle) throw new Error('Isolate not running.'); <add> // ignore silently for now, need a way to signal the other thread <add>}; <add> <add> <add>Isolate.prototype.send = function(msg) { <add> if (typeof msg === 'undefined') throw new TypeError('Bad argument.'); <add> if (!this._handle) throw new Error('Isolate not running.'); <add> msg = JSON.stringify(msg); <add> msg = new Buffer(msg); <add> return this._handle.send(msg); <add>}; <ide><path>src/node.js <ide> }); <ide> } <ide> } <add> <add> if (process.tid === 1) return; <add> <add> // isolate initialization <add> process.send = function(msg) { <add> if (typeof msg === 'undefined') throw new TypeError('Bad argument.'); <add> msg = JSON.stringify(msg); <add> msg = new Buffer(msg); <add> return process._send(msg); <add> }; <add> <add> process._onmessage = function(msg) { <add> msg = JSON.parse('' + msg); <add> process.emit('message', msg); <add> }; <ide> } <ide> <ide> startup.globalVariables = function() {
2
Go
Go
add basic integration tests for plugins
a2d48c9e4e2abadcba582de47891837b0a80b24c
<ide><path>api/client/plugin/install.go <ide> func newInstallCommand(dockerCli *client.DockerCli) *cobra.Command { <ide> } <ide> <ide> flags := cmd.Flags() <del> flags.BoolVar(&options.grantPerms, "grant-permissions", true, "grant all permissions necessary to run the plugin") <add> flags.BoolVar(&options.grantPerms, "grant-all-permissions", true, "grant all permissions necessary to run the plugin") <ide> <ide> return cmd <ide> } <ide><path>integration-cli/docker_cli_plugins_test.go <add>package main <add> <add>import ( <add> "github.com/docker/docker/pkg/integration/checker" <add> "github.com/go-check/check" <add>) <add> <add>func (s *DockerSuite) TestPluginBasicOps(c *check.C) { <add> testRequires(c, DaemonIsLinux, ExperimentalDaemon) <add> name := "tiborvass/no-remove" <add> tag := "latest" <add> nameWithTag := name + ":" + tag <add> <add> _, _, err := dockerCmdWithError("plugin", "install", name) <add> c.Assert(err, checker.IsNil) <add> <add> out, _, err := dockerCmdWithError("plugin", "ls") <add> c.Assert(err, checker.IsNil) <add> c.Assert(out, checker.Contains, name) <add> c.Assert(out, checker.Contains, tag) <add> c.Assert(out, checker.Contains, "true") <add> <add> out, _, err = dockerCmdWithError("plugin", "inspect", nameWithTag) <add> c.Assert(err, checker.IsNil) <add> c.Assert(out, checker.Contains, "A test plugin for Docker") <add> <add> out, _, err = dockerCmdWithError("plugin", "remove", nameWithTag) <add> c.Assert(out, checker.Contains, "is active") <add> <add> _, _, err = dockerCmdWithError("plugin", "disable", nameWithTag) <add> c.Assert(err, checker.IsNil) <add> <add> out, _, err = dockerCmdWithError("plugin", "remove", nameWithTag) <add> c.Assert(err, checker.IsNil) <add> c.Assert(out, checker.Contains, nameWithTag) <add>} <ide><path>integration-cli/requirements.go <ide> var ( <ide> func() bool { return daemonPlatform == "linux" }, <ide> "Test requires a Linux daemon", <ide> } <add> ExperimentalDaemon = testRequirement{ <add> func() bool { return utils.ExperimentalBuild() }, <add> "Test requires an experimental daemon", <add> } <ide> NotExperimentalDaemon = testRequirement{ <ide> func() bool { return !utils.ExperimentalBuild() }, <ide> "Test requires a non experimental daemon",
3
Python
Python
fix breakage due to early stopping callback
719eec7bb5545baf32e4034d5c06403b6bc9a17d
<ide><path>official/recommendation/ncf_keras_main.py <ide> def __init__(self, monitor, desired_value): <ide> <ide> self.monitor = monitor <ide> self.desired = desired_value <add> self.stopped_epoch = 0 <ide> <ide> def on_epoch_end(self, epoch, logs=None): <ide> current = self.get_monitor_value(logs)
1
Java
Java
use offset adjusted value in modulusanimatednode
fedc002c21fc4d01b3698e9390d968661ccc7801
<ide><path>ReactAndroid/src/main/java/com/facebook/react/animated/ModulusAnimatedNode.java <ide> public ModulusAnimatedNode( <ide> public void update() { <ide> AnimatedNode animatedNode = mNativeAnimatedNodesManager.getNodeById(mInputNode); <ide> if (animatedNode != null && animatedNode instanceof ValueAnimatedNode) { <del> mValue = ((ValueAnimatedNode) animatedNode).mValue % mModulus; <add> mValue = ((ValueAnimatedNode) animatedNode).getValue() % mModulus; <ide> } else { <ide> throw new JSApplicationCausedNativeException("Illegal node ID set as an input for " + <ide> "Animated.modulus node");
1
Python
Python
use stable functions
4225740a7b93115d8db478e6a95b67e9c4d96697
<ide><path>src/transformers/benchmark/benchmark_args_tf.py <ide> def _setup_strategy(self) -> Tuple["tf.distribute.Strategy", "tf.distribute.clus <ide> tf.config.experimental_connect_to_cluster(self._setup_tpu) <ide> tf.tpu.experimental.initialize_tpu_system(self._setup_tpu) <ide> <del> strategy = tf.distribute.experimental.TPUStrategy(self._setup_tpu) <add> strategy = tf.distribute.TPUStrategy(self._setup_tpu) <ide> else: <ide> # currently no multi gpu is allowed <ide> if self.is_gpu: <ide> # TODO: Currently only single GPU is supported <del> tf.config.experimental.set_visible_devices(self.gpu_list[self.device_idx], "GPU") <add> tf.config.set_visible_devices(self.gpu_list[self.device_idx], "GPU") <ide> strategy = tf.distribute.OneDeviceStrategy(device=f"/gpu:{self.device_idx}") <ide> else: <del> tf.config.experimental.set_visible_devices([], "GPU") # disable GPU <add> tf.config.set_visible_devices([], "GPU") # disable GPU <ide> strategy = tf.distribute.OneDeviceStrategy(device=f"/cpu:{self.device_idx}") <ide> <ide> return strategy <ide><path>src/transformers/trainer_tf.py <ide> <ide> import numpy as np <ide> import tensorflow as tf <del>from packaging.version import parse <ide> from tensorflow.python.distribute.values import PerReplica <ide> <ide> from .modeling_tf_utils import TFPreTrainedModel <ide> def __init__( <ide> None, <ide> ), <ide> ): <del> assert parse(tf.__version__).release >= (2, 2, 0), ( <del> "You need to run the TensorFlow trainer with at least the version 2.2.0, your version is %r " <del> % tf.__version__ <del> ) <del> <ide> self.model = model <ide> self.args = args <ide> self.train_dataset = train_dataset <ide> def get_train_tfdataset(self) -> tf.data.Dataset: <ide> raise ValueError("Trainer: training requires a train_dataset.") <ide> <ide> self.total_train_batch_size = self.args.train_batch_size * self.args.gradient_accumulation_steps <del> self.num_train_examples = tf.data.experimental.cardinality(self.train_dataset).numpy() <add> self.num_train_examples = self.train_dataset.cardinality(self.train_dataset).numpy() <ide> <ide> if self.num_train_examples < 0: <ide> raise ValueError("The training dataset must have an asserted cardinality") <ide> def get_eval_tfdataset(self, eval_dataset: Optional[tf.data.Dataset] = None) -> <ide> raise ValueError("Trainer: evaluation requires an eval_dataset.") <ide> <ide> eval_dataset = eval_dataset if eval_dataset is not None else self.eval_dataset <del> num_examples = tf.data.experimental.cardinality(eval_dataset).numpy() <add> num_examples = eval_dataset.cardinality(eval_dataset).numpy() <ide> <ide> if num_examples < 0: <ide> raise ValueError("The training dataset must have an asserted cardinality") <ide> def get_test_tfdataset(self, test_dataset: tf.data.Dataset) -> tf.data.Dataset: <ide> Subclass and override this method if you want to inject some custom behavior. <ide> """ <ide> <del> num_examples = tf.data.experimental.cardinality(test_dataset).numpy() <add> num_examples = test_dataset.cardinality(test_dataset).numpy() <ide> <ide> if num_examples < 0: <ide> raise ValueError("The training dataset must have an asserted cardinality") <ide><path>src/transformers/training_args_tf.py <ide> def _setup_strategy(self) -> Tuple["tf.distribute.Strategy", int]: <ide> tf.config.experimental_connect_to_cluster(tpu) <ide> tf.tpu.experimental.initialize_tpu_system(tpu) <ide> <del> strategy = tf.distribute.experimental.TPUStrategy(tpu) <add> strategy = tf.distribute.TPUStrategy(tpu) <ide> <ide> elif len(gpus) == 0: <ide> strategy = tf.distribute.OneDeviceStrategy(device="/cpu:0") <ide><path>tests/test_modeling_tf_common.py <ide> for gpu in gpus: <ide> # Restrict TensorFlow to only allocate x GB of memory on the GPUs <ide> try: <del> tf.config.experimental.set_virtual_device_configuration( <del> gpu, [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=_tf_gpu_memory_limit)] <add> tf.config.set_logical_device_configuration( <add> gpu, [tf.config.LogicalDeviceConfiguration(memory_limit=_tf_gpu_memory_limit)] <ide> ) <del> logical_gpus = tf.config.experimental.list_logical_devices("GPU") <add> logical_gpus = tf.config.list_logical_devices("GPU") <ide> print("Logical GPUs", logical_gpus) <ide> except RuntimeError as e: <ide> # Virtual devices must be set before GPUs have been initialized <ide><path>tests/test_optimization_tf.py <ide> <ide> import unittest <ide> <del>from packaging import version <del> <ide> from transformers import is_tf_available <ide> from transformers.testing_utils import require_tf <ide> <ide> def accumulate(grad1, grad2): <ide> local_variables = strategy.experimental_local_results(gradient_placeholder) <ide> local_variables[0].assign(grad1) <ide> local_variables[1].assign(grad2) <del> if version.parse(tf.version.VERSION) >= version.parse("2.2"): <del> strategy.run(accumulate_on_replica, args=(gradient_placeholder,)) <del> else: <del> strategy.experimental_run_v2(accumulate_on_replica, args=(gradient_placeholder,)) <add> strategy.run(accumulate_on_replica, args=(gradient_placeholder,)) <ide> <ide> @tf.function <ide> def apply_grad(): <ide> with strategy.scope(): <del> if version.parse(tf.version.VERSION) >= version.parse("2.2"): <del> strategy.run(apply_on_replica) <del> else: <del> strategy.experimental_run_v2(apply_on_replica) <add> strategy.run(apply_on_replica) <ide> <ide> def _check_local_values(grad1, grad2): <ide> values = strategy.experimental_local_results(accumulator._gradients[0])
5
Javascript
Javascript
move content into files
302d4b3ffb6df2e0ccccda6a08277fb195fec72f
<ide><path>common/app/routes/challenges/redux/actions.js <ide> export const updateFilter = createAction( <ide> ); <ide> <ide> export const clearFilter = createAction(types.clearFilter); <add> <add>// files <add>export const updateFile = createAction(types.updateFile); <add>export const updateFiles = createAction(types.updateFiles); <ide><path>common/app/routes/challenges/redux/reducer.js <ide> import { handleActions } from 'redux-actions'; <add>import { createPoly } from '../../../../utils/polyvinyl'; <ide> <ide> import types from './types'; <ide> <ide> const initialState = { <ide> currentStep: 0, <ide> previousStep: -1, <ide> filter: '', <del> content: null, <add> files: {}, <ide> superBlocks: [] <ide> }; <ide> <ide> function arrayToNewLineString(seedData = []) { <ide> seedData = Array.isArray(seedData) ? seedData : [seedData]; <del> return seedData.reduce((seed, line) => '' + seed + line + '\n', '\n'); <add> return seedData.reduce((seed, line) => '' + seed + line + '\n', ''); <ide> } <ide> <ide> function buildSeed({ challengeSeed = [] } = {}) { <ide> return arrayToNewLineString(challengeSeed); <ide> } <ide> <del>export default handleActions( <add>const mainReducer = handleActions( <ide> { <ide> [types.fetchChallengeCompleted]: (state, { payload = '' }) => ({ <ide> ...state, <ide> challenge: payload <ide> }), <ide> [types.updateCurrentChallenge]: (state, { payload: challenge }) => ({ <ide> ...state, <del> challenge: challenge.dashedName, <del> content: buildSeed(challenge) <add> challenge: challenge.dashedName <ide> }), <ide> <ide> // map <ide> export default handleActions( <ide> }, <ide> initialState <ide> ); <add> <add>const filesReducer = handleActions( <add> { <add> [types.updateFile]: (state, { payload: file }) => ({ <add> ...state, <add> [file.path]: file <add> }), <add> [types.updateFiles]: (state, { payload: files }) => { <add> return files <add> .reduce((files, file) => { <add> files[file.path] = file; <add> return files; <add> }, { ...state }); <add> }, <add> [types.updateCurrentChallenge]: (state, { payload: challenge }) => { <add> const path = challenge.dashedName + challenge.type; <add> return { <add> ...state, <add> [path]: createPoly({ path, contents: buildSeed(challenge) }) <add> }; <add> } <add> }, <add> {} <add>); <add> <add>export default function challengeReducers(state, action) { <add> const newState = mainReducer(state, action); <add> const files = filesReducer(state && state.files || {}, action); <add> return newState.files !== files ? { ...newState, files } : newState; <add>} <ide><path>common/app/routes/challenges/redux/types.js <ide> export default createTypes([ <ide> <ide> // map <ide> 'updateFilter', <del> 'clearFilter' <add> 'clearFilter', <add> <add> // files <add> 'updateFile', <add> 'updateFiles' <ide> ], 'challenges');
3
Javascript
Javascript
handle bind errors on windows
3da36fe00e5d85414031ae812e473f16629d8645
<ide><path>lib/net.js <ide> exports.Server = Server; <ide> <ide> function toNumber(x) { return (x = Number(x)) >= 0 ? x : false; } <ide> <add>function _listen(handle, backlog) { <add> // Use a backlog of 512 entries. We pass 511 to the listen() call because <add> // the kernel does: backlogsize = roundup_pow_of_two(backlogsize + 1); <add> // which will thus give us a backlog of 512 entries. <add> return handle.listen(backlog || 511); <add>} <ide> <ide> var createServerHandle = exports._createServerHandle = <ide> function(address, port, addressType, fd) { <ide> var createServerHandle = exports._createServerHandle = <ide> return err; <ide> } <ide> <add> if (process.platform === 'win32') { <add> // On Windows, we always listen to the socket before sending it to <add> // the worker (see uv_tcp_duplicate_socket). So we better do it here <add> // so that we can handle any bind-time or listen-time errors early. <add> err = _listen(handle); <add> if (err) { <add> handle.close(); <add> return err; <add> } <add> } <add> <ide> return handle; <ide> }; <ide> <ide> Server.prototype._listen2 = function(address, port, addressType, backlog, fd) { <ide> debug('listen2', address, port, addressType, backlog); <ide> var self = this; <ide> <add> var alreadyListening = false; <add> <ide> // If there is not yet a handle, we need to create one and bind. <ide> // In the case of a server sent via IPC, we don't need to do this. <ide> if (!self._handle) { <ide> Server.prototype._listen2 = function(address, port, addressType, backlog, fd) { <ide> }); <ide> return; <ide> } <add> alreadyListening = (process.platform === 'win32'); <ide> self._handle = rval; <ide> } else { <ide> debug('_listen2: have a handle already'); <ide> Server.prototype._listen2 = function(address, port, addressType, backlog, fd) { <ide> self._handle.onconnection = onconnection; <ide> self._handle.owner = self; <ide> <del> // Use a backlog of 512 entries. We pass 511 to the listen() call because <del> // the kernel does: backlogsize = roundup_pow_of_two(backlogsize + 1); <del> // which will thus give us a backlog of 512 entries. <del> var err = self._handle.listen(backlog || 511); <add> var err = 0; <add> if (!alreadyListening) <add> err = _listen(self._handle, backlog); <ide> <ide> if (err) { <ide> var ex = errnoException(err, 'listen');
1
Python
Python
fix types in docstrings
05324d0e986a1012a342e2650b3883e13a285029
<ide><path>numpy/core/defchararray.py <ide> def equal(x1, x2): <ide> <ide> Parameters <ide> ---------- <del> x1, x2 : array_like of string_ or unicode_ <add> x1, x2 : array_like of str or unicode <ide> Input arrays of the same shape. <ide> <ide> Returns <ide> def not_equal(x1, x2): <ide> <ide> Parameters <ide> ---------- <del> x1, x2 : array_like of string_ or unicode_ <add> x1, x2 : array_like of str or unicode <ide> Input arrays of the same shape. <ide> <ide> Returns <ide> def greater_equal(x1, x2): <ide> <ide> Parameters <ide> ---------- <del> x1, x2 : array_like of string_ or unicode_ <add> x1, x2 : array_like of str or unicode <ide> Input arrays of the same shape. <ide> <ide> Returns <ide> def less_equal(x1, x2): <ide> <ide> Parameters <ide> ---------- <del> x1, x2 : array_like of string_ or unicode_ <add> x1, x2 : array_like of str or unicode <ide> Input arrays of the same shape. <ide> <ide> Returns <ide> def greater(x1, x2): <ide> <ide> Parameters <ide> ---------- <del> x1, x2 : array_like of string_ or unicode_ <add> x1, x2 : array_like of str or unicode <ide> Input arrays of the same shape. <ide> <ide> Returns <ide> def less(x1, x2): <ide> <ide> Parameters <ide> ---------- <del> x1, x2 : array_like of string_ or unicode_ <add> x1, x2 : array_like of str or unicode <ide> Input arrays of the same shape. <ide> <ide> Returns <ide> def str_len(a): <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string_ or unicode_ <add> a : array_like of str or unicode <ide> <ide> Returns <ide> ------- <ide> def str_len(a): <ide> def add(x1, x2): <ide> """ <ide> Return (x1 + x2), that is string concatenation, element-wise for a <del> pair of array_likes of string_ or unicode_. <add> pair of array_likes of str or unicode. <ide> <ide> Parameters <ide> ---------- <del> x1 : array_like of string_ or unicode_ <del> x2 : array_like of string_ or unicode_ <add> x1 : array_like of str or unicode <add> x2 : array_like of str or unicode <ide> <ide> Returns <ide> ------- <ide> def multiply(a, i): <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string_ or unicode_ <del> i : array_like of integers <add> a : array_like of str or unicode <add> i : array_like of ints <ide> <ide> Returns <ide> ------- <ide> def multiply(a, i): <ide> def mod(a, values): <ide> """ <ide> Return (a % i), that is pre-Python 2.6 string formatting <del> (iterpolation), element-wise for a pair of array_likes of string_ <del> or unicode_. <add> (iterpolation), element-wise for a pair of array_likes of str <add> or unicode. <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string_ or unicode_ <add> a : array_like of str or unicode <ide> values : array_like of values <ide> These values will be element-wise interpolated into the string. <ide> <ide> Returns <ide> ------- <ide> out : ndarray <del> Output array of string_ or unicode_, depending on input types <add> Output array of str or unicode, depending on input types <ide> <ide> See also <ide> -------- <ide> def capitalize(a): <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string_ or unicode_ <add> a : array_like of str or unicode <ide> <ide> Returns <ide> ------- <ide> out : ndarray <del> Output array of string_ or unicode_, depending on input types <add> Output array of str or unicode, depending on input <add> types <ide> <ide> See also <ide> -------- <ide> def center(a, width, fillchar=' '): <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string_ or unicode_ <add> a : array_like of str or unicode <ide> width : int <ide> The length of the resulting strings <ide> fillchar : str or unicode, optional <ide> def center(a, width, fillchar=' '): <ide> Returns <ide> ------- <ide> out : ndarray <del> Output array of string_ or unicode_, depending on input types <add> Output array of str or unicode, depending on input <add> types <ide> <ide> See also <ide> -------- <ide> def center(a, width): <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string_ or unicode_ <add> a : array_like of str or unicode <ide> width : int <ide> The length of the resulting strings <ide> <ide> Returns <ide> ------- <ide> out : ndarray, str or unicode <del> Output array of string_ or unicode_, depending on input types <add> Output array of str or unicode, depending on input types <ide> <ide> See also <ide> -------- <ide> def count(a, sub, start=0, end=None): <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string_ or unicode_ <add> a : array_like of str or unicode <ide> sub : str or unicode <ide> The substring to search for <ide> start, end : int, optional <ide> def count(a, sub, start=0, end=None): <ide> Returns <ide> ------- <ide> out : ndarray <del> Output array of integers. <add> Output array of ints. <ide> <ide> See also <ide> -------- <ide> def decode(a, encoding=None, errors=None): <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string_ or unicode_ <add> a : array_like of str or unicode <ide> encoding : str, optional <ide> The name of an encoding <ide> errors : str, optional <ide> def encode(a, encoding=None, errors=None): <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string_ or unicode_ <add> a : array_like of str or unicode <ide> encoding : str, optional <ide> The name of an encoding <ide> errors : str, optional <ide> def endswith(a, suffix, start=0, end=None): <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string or unicode <add> a : array_like of str or unicode <ide> suffix : str <ide> start, end : int, optional <ide> With optional `start`, test beginning at that position. With <ide> def endswith(a, suffix, start=0, end=None): <ide> Returns <ide> ------- <ide> out : ndarray <del> Outputs an array of booleans. <add> Outputs an array of bools. <ide> <ide> See also <ide> -------- <ide> def expandtabs(a, tabsize=8): <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string or unicode <add> a : array_like of str or unicode <ide> tabsize : int, optional <ide> <ide> Returns <ide> def find(a, sub, start=0, end=None): <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string_ or unicode_ <add> a : array_like of str or unicode <ide> sub : str or unicode <ide> start, end : int, optional <ide> Optional arguments `start` and `end` are interpreted as in <ide> def find(a, sub, start=0, end=None): <ide> Returns <ide> ------- <ide> out : {ndarray, integer} <del> Output array of integers. Returns -1 if `sub` is not found. <add> Output array of ints. Returns -1 if `sub` is not found. <ide> <ide> See also <ide> -------- <ide> def index(a, sub, start=0, end=None): <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string_ or unicode_ <add> a : array_like of str or unicode <ide> sub : str or unicode <ide> start, end : int, optional <ide> <ide> Returns <ide> ------- <ide> out : ndarray <del> Output array of integers. Returns -1 if `sub` is not found. <add> Output array of ints. Returns -1 if `sub` is not found. <ide> <ide> See also <ide> -------- <ide> def isalnum(a): <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string_ or unicode_ <add> a : array_like of str or unicode <ide> <ide> Returns <ide> ------- <ide> def isalpha(a): <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string_ or unicode_ <add> a : array_like of str or unicode <ide> <ide> Returns <ide> ------- <ide> out : ndarray <del> Output array of booleans <add> Output array of bools <ide> <ide> See also <ide> -------- <ide> def isdigit(a): <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string_ or unicode_ <add> a : array_like of str or unicode <ide> <ide> Returns <ide> ------- <ide> out : ndarray <del> Output array of booleans <add> Output array of bools <ide> <ide> See also <ide> -------- <ide> def islower(a): <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string_ or unicode_ <add> a : array_like of str or unicode <ide> <ide> Returns <ide> ------- <ide> out : ndarray <del> Output array of booleans <add> Output array of bools <ide> <ide> See also <ide> -------- <ide> def isspace(a): <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string_ or unicode_ <add> a : array_like of str or unicode <ide> <ide> Returns <ide> ------- <ide> out : ndarray <del> Output array of booleans <add> Output array of bools <ide> <ide> See also <ide> -------- <ide> def istitle(a): <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string_ or unicode_ <add> a : array_like of str or unicode <ide> <ide> Returns <ide> ------- <ide> out : ndarray <del> Output array of booleans <add> Output array of bools <ide> <ide> See also <ide> -------- <ide> def isupper(a): <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string_ or unicode_ <add> a : array_like of str or unicode <ide> <ide> Returns <ide> ------- <ide> out : ndarray <del> Output array of booleans <add> Output array of bools <ide> <ide> See also <ide> -------- <ide> def join(sep, seq): <ide> <ide> Parameters <ide> ---------- <del> sep : array_like of string_ or unicode_ <del> seq : array_like of string_ or unicode_ <add> sep : array_like of str or unicode <add> seq : array_like of str or unicode <ide> <ide> Returns <ide> ------- <ide> out : ndarray <del> Output array of string_ or unicode_, depending on input types <add> Output array of str or unicode, depending on input types <ide> <ide> See also <ide> -------- <ide> def ljust(a, width, fillchar=' '): <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string_ or unicode_ <add> a : array_like of str or unicode <ide> width : int <ide> The length of the resulting strings <ide> fillchar : str or unicode, optional <ide> def ljust(a, width): <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string_ or unicode_ <add> a : array_like of str or unicode <ide> width : int <ide> The length of the resulting strings <ide> <ide> def partition(a, sep): <ide> Returns <ide> ------- <ide> out : ndarray <del> Output array of string or unicode, depending on input <del> type. The output array will have an extra dimension with <del> 3 elements per input element. <add> Output array of str or unicode, depending on input type. <add> The output array will have an extra dimension with 3 <add> elements per input element. <ide> <ide> See also <ide> -------- <ide> def rfind(a, sub, start=0, end=None): <ide> Returns <ide> ------- <ide> out : ndarray <del> Output array of integers. Return -1 on failure. <add> Output array of ints. Return -1 on failure. <ide> <ide> See also <ide> -------- <ide> def rindex(a, sub, start=0, end=None): <ide> Returns <ide> ------- <ide> out : ndarray <del> Output array of integers. <add> Output array of ints. <ide> <ide> See also <ide> -------- <ide> def rjust(a, width, fillchar=' '): <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string_ or unicode_ <add> a : array_like of str or unicode <ide> width : int <ide> The length of the resulting strings <ide> fillchar : str or unicode, optional <ide> def rjust(a, width): <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string_ or unicode_ <add> a : array_like of str or unicode <ide> width : int <ide> The length of the resulting strings <ide> <ide> def rsplit(a, sep=None, maxsplit=None): <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string_ or unicode_ <add> a : array_like of str or unicode <ide> sep : str or unicode, optional <ide> If `sep` is not specified or `None`, any whitespace string <ide> is a separator. <ide> def split(a, sep=None, maxsplit=None): <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string_ or unicode_ <add> a : array_like of str or unicode <ide> sep : str or unicode, optional <ide> If `sep` is not specified or `None`, any whitespace string is a <ide> separator. <ide> def splitlines(a, keepends=None): <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string_ or unicode_ <add> a : array_like of str or unicode <ide> keepends : bool, optional <ide> Line breaks are not included in the resulting list unless <ide> keepends is given and true. <ide> def startswith(a, prefix, start=0, end=None): <ide> <ide> Parameters <ide> ---------- <del> a : array_like of string or unicode <add> a : array_like of str or unicode <ide> suffix : str <ide> start, end : int, optional <ide> end : int, optional <ide> class chararray(ndarray): <ide> functions in :mod:`numpy.char <numpy.core.defchararray>` for <ide> fast vectorized string operations instead. <ide> <del> Versus a regular Numpy array of type 'string_' or 'unicode_', this <add> Versus a regular Numpy array of type `str` or `unicode`, this <ide> class adds the following functionality: <ide> <del> <ide> 1) values automatically have whitespace removed from the end <ide> when indexed <ide> <ide> class adds the following functionality: <ide> itemsize : int_like, > 0, optional <ide> Length of each array element, in number of characters. Default is 1. <ide> <del> unicode : {True, False}, optional <del> Are the array elements of unicode-type (``True``) or string-type <del> (``False``, the default). <add> unicode : bool, optional <add> Are the array elements of unicode-type (`True`) or string-type <add> (`False`, the default). <ide> <del> buffer : integer, > 0, optional <del> Memory address of the start of the array data. If ``None`` <add> buffer : int, > 0, optional <add> Memory address of the start of the array data. If `None` <ide> (the default), a new array is created. <ide> <del> offset : integer, >= 0, optional <add> offset : int, >= 0, optional <ide> Fixed stride displacement from the beginning of an axis? <ide> Default is 0. <ide> <del> strides : array_like(?), optional <add> strides : array_like, optional <ide> Strides for the array (see `numpy.ndarray.strides` for full <del> description), default is ``None``. <add> description), default is `None`. <ide> <ide> order : {'C', 'F'}, optional <ide> The order in which the array data is stored in memory: 'C' -> <ide> def __lt__(self, other): <ide> def __add__(self, other): <ide> """ <ide> Return (self + other), that is string concatenation, <del> element-wise for a pair of array_likes of string_ or unicode_. <add> element-wise for a pair of array_likes of str or unicode. <ide> <ide> See also <ide> -------- <ide> def array(obj, itemsize=None, copy=True, unicode=None, order=None): <ide> in :mod:`numpy.char <numpy.core.defchararray>` for fast <ide> vectorized string operations instead. <ide> <del> Versus a regular Numpy array of type `string_` or `unicode_`, this <add> Versus a regular Numpy array of type `str` or `unicode`, this <ide> class adds the following functionality: <ide> <ide> 1) values automatically have whitespace removed from the end <ide> class adds the following functionality: <ide> resulting array. If `itemsize` is None, and `obj` is an <ide> object array or a Python list, the `itemsize` will be <ide> automatically determined. If `itemsize` is provided and `obj` <del> is of type `str` or `unicode`, then the `obj` string will be <add> is of type str or unicode, then the `obj` string will be <ide> chunked into `itemsize` pieces. <ide> <ide> copy : bool, optional <ide> If true (default), then the object is copied. Otherwise, a copy <ide> will only be made if __array__ returns a copy, if obj is a <ide> nested sequence, or if a copy is needed to satisfy any of the other <del> requirements (`itemsize`, `unicode`, `order`, etc.). <add> requirements (`itemsize`, unicode, `order`, etc.). <ide> <ide> unicode : bool, optional <ide> When true, the resulting `chararray` can contain Unicode <del> characters, when false only 8-bit characters. If `unicode` is <add> characters, when false only 8-bit characters. If unicode is <ide> `None` and `obj` is one of the following: <ide> <ide> - a `chararray`, <del> - an ndarray of type `string_` or `unicode_` <add> - an ndarray of type `str` or `unicode` <ide> - a Python str or unicode object, <ide> <ide> then the unicode setting of the output array will be <ide> def asarray(obj, itemsize=None, unicode=None, order=None): <ide> Convert the input to a `chararray`, copying the data only if <ide> necessary. <ide> <del> Versus a regular Numpy array of type `string_` or `unicode_`, this <add> Versus a regular Numpy array of type `str` or `unicode`, this <ide> class adds the following functionality: <ide> <ide> 1) values automatically have whitespace removed from the end <ide> class adds the following functionality: <ide> resulting array. If `itemsize` is None, and `obj` is an <ide> object array or a Python list, the `itemsize` will be <ide> automatically determined. If `itemsize` is provided and `obj` <del> is of type `str` or `unicode`, then the `obj` string will be <add> is of type str or unicode, then the `obj` string will be <ide> chunked into `itemsize` pieces. <ide> <ide> unicode : bool, optional <ide> When true, the resulting `chararray` can contain Unicode <del> characters, when false only 8-bit characters. If `unicode` is <add> characters, when false only 8-bit characters. If unicode is <ide> `None` and `obj` is one of the following: <ide> <ide> - a `chararray`, <del> - an ndarray of type `string_` or 'unicode_` <add> - an ndarray of type `str` or 'unicode` <ide> - a Python str or unicode object, <ide> <ide> then the unicode setting of the output array will be
1
Javascript
Javascript
fix jshint issue
0b260d57cce124597d2f4186629a1409c98f8da5
<ide><path>src/core/core.controller.js <ide> } else { <ide> <ide> var _this = this; <del> function getItemsForMode(mode) { <add> var getItemsForMode = function(mode) { <ide> switch (mode) { <ide> case 'single': <ide> return _this.getElementAtEvent(e); <ide> default: <ide> return e; <ide> } <del> } <add> }; <ide> <ide> this.active = getItemsForMode(this.options.hover.mode); <ide> this.tooltipActive = getItemsForMode(this.options.tooltips.mode);
1
PHP
PHP
add unit tests for date_format validator rule
49331d74e24b018fc45a310060aa063093f3a16d
<ide><path>laravel/tests/cases/validator.test.php <ide> public function testExistsRule() <ide> $this->assertFalse(Validator::make($input, $rules)->valid()); <ide> } <ide> <add> /** <add> * Tests the date_format validation rule. <add> * <add> * @group laravel <add> */ <add> public function testTheDateFormatRule() <add> { <add> $input = array('date' => '15-Feb-2009'); <add> $rules = array('date' => 'date_format:j-M-Y'); <add> $this->assertTrue(Validator::make($input, $rules)->valid()); <add> <add> $input['date'] = '2009-02-15 15:16:17'; <add> $rules = array('date' => 'date_format:Y-m-d H\\:i\\:s'); <add> $this->assertTrue(Validator::make($input, $rules)->valid()); <add> <add> $input['date'] = '2009-02-15'; <add> $this->assertFalse(Validator::make($input, $rules)->valid()); <add> <add> $input['date'] = '15:16:17'; <add> $this->assertFalse(Validator::make($input, $rules)->valid()); <add> } <add> <ide> /** <ide> * Test that the validator sets the correct messages. <ide> *
1
PHP
PHP
fix wrong method
19e4b7da688b2ea3aa2110a82d037ec2e72a69e2
<ide><path>src/Illuminate/Auth/AuthServiceProvider.php <ide> protected function registerAuthenticator() <ide> }); <ide> <ide> $this->app->singleton('auth.driver', function ($app) { <del> return $app['auth']->driver(); <add> return $app['auth']->guard(); <ide> }); <ide> } <ide>
1
Python
Python
fix import sorting problem
8bcff10b5aaca6aa9698939f7049d4db0461710c
<ide><path>tests/schema/fields.py <ide> from django.db import models <ide> from django.db.models.fields.related import ( <del> RECURSIVE_RELATIONSHIP_CONSTANT, ManyToManyDescriptor, <del> ManyToManyField, ManyToManyRel, RelatedField, <del> create_many_to_many_intermediary_model, <add> RECURSIVE_RELATIONSHIP_CONSTANT, ManyToManyDescriptor, ManyToManyField, <add> ManyToManyRel, RelatedField, create_many_to_many_intermediary_model, <ide> ) <ide> from django.utils.functional import curry <ide>
1
Javascript
Javascript
simplify check for empty set in jquery#dommanip
9256ba5380fca27ebc70e4d1e798fa45cb30e3a2
<ide><path>src/manipulation.js <ide> jQuery.fn.extend({ <ide> }); <ide> } <ide> <del> if ( this[0] ) { <del> doc = this[0].ownerDocument; <add> if ( l ) { <add> doc = this[ 0 ].ownerDocument; <ide> fragment = doc.createDocumentFragment(); <ide> jQuery.clean( args, doc, fragment, undefined, this ); <ide> first = fragment.firstChild;
1
Ruby
Ruby
create caskroom without sudo in writable parent
d51cd15e0c748d1b2a35f6327a131622b6ee48b7
<ide><path>Library/Homebrew/cask/lib/hbc/caskroom.rb <ide> def migrate_caskroom_from_repo_to_prefix <ide> FileUtils.mv repo_caskroom, Hbc.caskroom <ide> else <ide> opoo "#{Hbc.caskroom.parent} is not writable, sudo is needed to move the Caskroom." <del> sudo "/bin/mv", repo_caskroom.to_s, Hbc.caskroom.parent.to_s <add> command "/bin/mv", repo_caskroom, Hbc.caskroom.parent, :use_sudo => true <ide> end <ide> end <ide> <ide> def ensure_caskroom_exists <ide> <ide> ohai "Creating Caskroom at #{Hbc.caskroom}" <ide> ohai "We'll set permissions properly so we won't need sudo in the future" <add> use_sudo = !Hbc.caskroom.parent.writable? <ide> <del> sudo "/bin/mkdir", "-p", Hbc.caskroom <del> sudo "/bin/chmod", "g+rwx", Hbc.caskroom <del> sudo "/usr/sbin/chown", Utils.current_user, Hbc.caskroom <del> sudo "/usr/bin/chgrp", "admin", Hbc.caskroom <add> command "/bin/mkdir", "-p", Hbc.caskroom, :use_sudo => use_sudo <add> command "/bin/chmod", "g+rwx", Hbc.caskroom, :use_sudo => use_sudo <add> command "/usr/sbin/chown", Utils.current_user, Hbc.caskroom, :use_sudo => use_sudo <add> command "/usr/bin/chgrp", "admin", Hbc.caskroom, :use_sudo => use_sudo <ide> end <ide> <del> def sudo(*args) <del> ohai "/usr/bin/sudo #{args.join(" ")}" <del> system "/usr/bin/sudo", *args <add> def command(*args) <add> options = args.last.is_a?(Hash) ? args.pop : {} <add> <add> if options[:use_sudo] <add> args.unshift "/usr/bin/sudo" <add> end <add> <add> ohai args.join(" ") <add> system *args <ide> end <ide> end <ide> end
1
Python
Python
fix retry-after header handling
bd32dfc2016d0308065e9a002a4793cc407262b0
<ide><path>libcloud/common/base.py <ide> def __init__(self, response, connection): <ide> <ide> if not self.success(): <ide> raise exception_from_message(code=self.status, <del> message=self.parse_error()) <add> message=self.parse_error(), <add> headers=self.headers) <ide> <ide> self.object = self.parse_body() <ide> <ide><path>libcloud/common/exceptions.py <ide> # See the License for the specific language governing permissions and <ide> # limitations under the License. <ide> <add>import time <add> <add>from email.utils import parsedate_tz, mktime_tz <add> <ide> __all__ = [ <ide> 'BaseHTTPError', <ide> 'RateLimitReachedError', <ide> class RateLimitReachedError(BaseHTTPError): <ide> message = '%s Rate limit exceeded' % (code) <ide> <ide> def __init__(self, *args, **kwargs): <del> self.retry_after = int(kwargs.pop('retry_after', 0)) <add> self.retry_after = int(kwargs.pop('headers', {}).get('retry-after', 0)) <ide> <ide> <ide> _error_classes = [RateLimitReachedError] <ide> def exception_from_message(code, message, headers=None): <ide> 'headers': headers <ide> } <ide> <del> if headers and 'retry_after' in headers: <del> kwargs['retry_after'] = headers['retry_after'] <add> if headers and 'retry-after' in headers: <add> http_date = parsedate_tz(headers['retry-after']) <add> if http_date is not None: <add> # Convert HTTP-date to delay-seconds <add> delay = max(0, int(mktime_tz(http_date) - time.time())) <add> headers['retry-after'] = str(delay) <ide> cls = _code_map.get(code, BaseHTTPError) <ide> return cls(**kwargs) <ide><path>libcloud/test/common/test_base.py <ide> <ide> import mock <ide> <del>from libcloud.common.base import LazyObject <add>from libcloud.common.base import LazyObject, Response <add>from libcloud.common.exceptions import BaseHTTPError, RateLimitReachedError <ide> from libcloud.test import LibcloudTestCase <ide> <ide> <ide> def test_setattr(self): <ide> self.assertEqual(wrapped_lazy_obj.z, 'baz') <ide> <ide> <add>class ErrorResponseTest(LibcloudTestCase): <add> def mock_response(self, code, headers={}): <add> m = mock.MagicMock() <add> m.request = mock.Mock() <add> m.headers = headers <add> m.status_code = code <add> m.text = None <add> return m <add> <add> def test_rate_limit_response(self): <add> resp_mock = self.mock_response(429, {'Retry-After': '120'}) <add> try: <add> Response(resp_mock, mock.MagicMock()) <add> except RateLimitReachedError as e: <add> self.assertEqual(e.retry_after, 120) <add> except: <add> # We should have got a RateLimitReachedError <add> self.fail("Catched exception should have been RateLimitReachedError") <add> else: <add> # We should have got an exception <add> self.fail("HTTP Status 429 response didn't raised an exception") <add> <add> def test_error_with_retry_after(self): <add> # 503 Service Unavailable may include Retry-After header <add> resp_mock = self.mock_response(503, {'Retry-After': '300'}) <add> try: <add> Response(resp_mock, mock.MagicMock()) <add> except BaseHTTPError as e: <add> self.assertIn('retry-after', e.headers) <add> self.assertEqual(e.headers['retry-after'], '300') <add> else: <add> # We should have got an exception <add> self.fail("HTTP Status 503 response didn't raised an exception") <add> <add> @mock.patch('time.time', return_value=1231006505) <add> def test_error_with_retry_after_http_date_format(self, time_mock): <add> retry_after = 'Sat, 03 Jan 2009 18:20:05 -0000' <add> # 503 Service Unavailable may include Retry-After header <add> resp_mock = self.mock_response(503, {'Retry-After': retry_after}) <add> try: <add> Response(resp_mock, mock.MagicMock()) <add> except BaseHTTPError as e: <add> self.assertIn('retry-after', e.headers) <add> # HTTP-date got translated to delay-secs <add> self.assertEqual(e.headers['retry-after'], '300') <add> else: <add> # We should have got an exception <add> self.fail("HTTP Status 503 response didn't raised an exception") <add> <add> <ide> if __name__ == '__main__': <ide> sys.exit(unittest.main())
3
Python
Python
return provider ids for cluster's node
c98bba0266eea693e79b43e39e10889eec7b9c77
<ide><path>libcloud/container/drivers/kubernetes.py <ide> def _to_node(self, data): <ide> extra = {"memory": memory, "cpu": cpu} <ide> extra["os"] = data["status"]["nodeInfo"].get("operatingSystem") <ide> extra["kubeletVersion"] = data["status"]["nodeInfo"]["kubeletVersion"] <add> extra["provider_id"] = data["spec"]["providerID"] <ide> for condition in data["status"]["conditions"]: <ide> if condition["type"] == "Ready" and condition["status"] == "True": <ide> state = NodeState.RUNNING
1
PHP
PHP
fix auth docblocks
b546fbe937ad997fa9071e51c3522687a6cbeaf9
<ide><path>src/Illuminate/Auth/EloquentUserProvider.php <ide> public function __construct(HasherContract $hasher, $model) <ide> * Retrieve a user by their unique identifier. <ide> * <ide> * @param mixed $identifier <del> * @return \Illuinate\Contracts\Auth\User|null <add> * @return \Illuminate\Contracts\Auth\User|null <ide> */ <ide> public function retrieveById($identifier) <ide> { <ide> public function retrieveById($identifier) <ide> * <ide> * @param mixed $identifier <ide> * @param string $token <del> * @return \Illuinate\Contracts\Auth\User|null <add> * @return \Illuminate\Contracts\Auth\User|null <ide> */ <ide> public function retrieveByToken($identifier, $token) <ide> { <ide> public function retrieveByToken($identifier, $token) <ide> /** <ide> * Update the "remember me" token for the given user in storage. <ide> * <del> * @param \Illuinate\Contracts\Auth\User $user <add> * @param \Illuminate\Contracts\Auth\User $user <ide> * @param string $token <ide> * @return void <ide> */ <ide> public function updateRememberToken(UserContract $user, $token) <ide> * Retrieve a user by the given credentials. <ide> * <ide> * @param array $credentials <del> * @return \Illuinate\Contracts\Auth\User|null <add> * @return \Illuminate\Contracts\Auth\User|null <ide> */ <ide> public function retrieveByCredentials(array $credentials) <ide> { <ide> public function retrieveByCredentials(array $credentials) <ide> /** <ide> * Validate a user against the given credentials. <ide> * <del> * @param \Illuinate\Contracts\Auth\User $user <add> * @param \Illuminate\Contracts\Auth\User $user <ide> * @param array $credentials <ide> * @return bool <ide> */
1
PHP
PHP
abort(404)
04308b7c4435d96f05822f76b1d652ca565c9783
<ide><path>src/Illuminate/Foundation/Application.php <ide> public function setLocale($locale) <ide> */ <ide> public function abort($code, $message = '', array $headers = array()) <ide> { <del> throw new HttpException($code, $message, null, $headers); <add> if ($code == 404) <add> { <add> throw new NotFoundHttpException($message); <add> } <add> else <add> { <add> throw new HttpException($code, $message, null, $headers); <add> } <ide> } <ide> <ide> /**
1
Python
Python
add test for weight modification
008e5e9c6ee24b6675dc582373c4a14cbe5ec22e
<ide><path>numpy/ma/tests/test_extras.py <ide> def test_polyfit(self): <ide> assert_almost_equal(a, a_) <ide> # <ide> w = np.random.rand(10) + 1 <add> wo = w.copy() <ide> xs = x[1:-1] <ide> ys = y[1:-1] <ide> ws = w[1:-1] <ide> (C, R, K, S, D) = polyfit(x, y, 3, full=True, w=w) <ide> (c, r, k, s, d) = np.polyfit(xs, ys, 3, full=True, w=ws) <add> assert_equal(w, wo) <ide> for (a, a_) in zip((C, R, K, S, D), (c, r, k, s, d)): <ide> assert_almost_equal(a, a_) <ide>
1
Python
Python
register vit architecture hyperparams
7c917ef24d2ffc844818d1462f3ebabba8c57c89
<ide><path>official/projects/vit/modeling/vit.py <ide> def __init__(self, <ide> original_init: bool = True, <ide> pos_embed_shape: Optional[Tuple[int, int]] = None): <ide> """VisionTransformer initialization function.""" <add> self._mlp_dim = mlp_dim <add> self._num_heads = num_heads <add> self._num_layers = num_layers <add> self._hidden_size = hidden_size <add> self._patch_size = patch_size <add> <ide> inputs = tf.keras.Input(shape=input_specs.shape[1:]) <ide> <ide> x = layers.Conv2D(
1
Ruby
Ruby
remove default parameters from method signature
793455e594dc98ea026c7665dd0de3ae8829cf73
<ide><path>actionview/lib/action_view/renderer/template_renderer.rb <ide> def render(context, options) <ide> <ide> @lookup_context.rendered_format ||= (template.formats.first || formats.first) <ide> <del> render_template(context, template, options[:layout], options[:locals]) <add> render_template(context, template, options[:layout], options[:locals] || {}) <ide> end <ide> <ide> private <ide> def determine_template(options) <ide> <ide> # Renders the given template. A string representing the layout can be <ide> # supplied as well. <del> def render_template(view, template, layout_name = nil, locals = nil) <del> locals ||= {} <del> <add> def render_template(view, template, layout_name, locals) <ide> render_with_layout(view, layout_name, locals) do |layout| <ide> instrument(:template, identifier: template.identifier, layout: layout.try(:virtual_path)) do <ide> template.render(view, locals) { |*name| view._layout_for(*name) }
1
Text
Text
add turkish contribution guidelines
f102c88a976e26f50ad613b7f6784c9e16095bbb
<ide><path>docs/i18n-languages/turkish/CONTRIBUTING.md <add><!-- do not translate this --> <add>| [Read these guidelines in other languages](/docs/i18n-languages) | <add>|-| <add><!-- do not translate this --> <add> <add># Katkıda Bulunma Kuralları <add> <add>Merhaba. 👋 <add> <add>freeCodeCamp.org, sizin gibi binlerce gönüllü sayesinde mümkün olmaktadır. Katkılarınızdan dolayı minnettarız ve sizi ağırlamaktan mutluluk duyarız. <add> <add>["Davranış Kurallarımıza"](https://www.freecodecamp.org/code-of-conduct) kesinlikle uyarız. Okumak için bir dakikanızı ayırın. Sadece 196 kelime. <add> <add>İyi eğlenceler! 🎉 <add> <add>## İşte size katkıda bulunabileceğiniz bir kaç eğlenceli yol <add> <add>Bunlardan herhangi birine katkıda bulunabilirsiniz: <add> <add>1. [Bu Open-Source-Codebase'e katkıda bulunun](#Bu-Open-Source-Codebase'e-katkıda-bulunun). Karşılaştığımız problemlerin üstesinden gelmemize ve öğrenme platformundaki hataları düzeltmemize yardımcı olun. <add> <add>2. [Public forumuzdaki](https://www.freecodecamp.org/forum/) kampçılara yardım edin. [Sorularını cevaplayın](https://www.freecodecamp.org/forum/?max_posts=1) ya da [kodlarına geri bildirimler yapın](https://www.freecodecamp.org/forum/c/project-feedback?max_posts=1). <add> <add>3. [YouTube videolarımıza](https://www.youtube.com/channel/UC8butISFwT-Wl7EV0hUK0BQ/videos) altyazı eklenmesinde bize yardımcı olun. <add> <add>## Bu Open-Source-Codebase'e katkıda bulunun <add> <add>Open-Source-Codebase'imizde binlerce [coding challenges](https://learn.freecodecamp.org) ve öğrenme platformumuzu destekleyen diğer kaynak kodları yer almaktadır. <add> <add>### Yarat, güncelle ve coding challenges'lardaki hataları düzelt <add> <add>Tüm coding challenges'larımız, sizin gibi gönüllülerden uzman bilgisini getirerek topluluk tarafından küratörlüğünü sürdürüyor. <add> <add>Onları geliştirebilir ve ifadelerini netleştirmeye yardımcı olabilirsiniz. Konsepti daha iyi açıklamak için kullanıcı hikayelerini güncelleyebilirsiniz hatta gereksiz olanları kaldırabilirisiniz. Ayrıca insanların kodlarını daha tutartlı hale getirmek için, challenge testlerini geliştirebilirsin. <add> <add>**Eğer bu coding challenge'ları geliştirmek ilgini çekerse, işte [Coding challenge'lar üzerine nasıl çalılır](/docs/how-to-work-on-coding-challenges.md).** <add> <add>### freeCodeCamp.org öğrenme platformundaki hataları düzeltmemize yardım edin <add> <add>Öğrenme platformumuz modern bir JavaScript-Stack üzerinde çalışmaktadır. Node.js, MongoDB, LoopBack, OAuth 2.0, React, Gatsby, Webpack ve diğerleri dahil ancak bunlarla sınırlı olmamak üzere çeşitli bileşenleri, araçları ve kütüphaneleri vardır. <add> <add>Açıkça, <add> <add>- Node.js tabanlı bir API server'ımız, <add>- Bir dizi React tabanlı client uygulamarı, <add>- Front-end projelerimizi değerlendirmek için kullandığımız bir script. <add> <add>Katkıda bulunmak için API'lerin anlaşılması, ES6 Syntax ve fazlasıyla merak gerektirir. <add> <add>Katkıda bulunabilmek için bahsi geçen teknolojilerde, araçlarda ve kütüphanelerde uzman olmanız gerekmiyor fakat bunlara aşina olmanızı bekliyoruz. <add> <add>**Eğer codebase'imizi geliştirmemizde bize yardım etmek isterseniz, [freeCodeCamp'i lokal olarak kurabilir](/docs/how-to-setup-freecodecamp-locally.md) ya da ücretsiz online geliştirme ortamı Gitpod'u kullanabilirsiniz.** <add> <add>[![Gitpod'da Aç](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/freeCodeCamp/freeCodeCamp) <add> <add>(Freecodecamp için kodlamaya hazır geliştirme ortamını tarayıcınızda başlatır.) <add> <add>## Sıkça sorulan sorular <add> <add>**Panoda olmayan bir hatayı nasıl bildirebilirim?** <add> <add>Eğer bir hata bulduğunuz düşünüyorsanız, ["Yardım, Bir Hata Buldum"](https://forum.freecodecamp.org/t/how-to-report-a-bug/19543) yazısındaki talimatları takip edin. <add> <add>Bunun yeni bir hata olduğundan eminseniz, yeni bir GitHub issue yaratın. Hatayı tekrarlayabilmemiz için olabildiğince fazla bilgi eklediğinizden emin olun. Bu konuda, size yardımcı olmak için önceden tanımlanmış bir sorun şablonumuz bulunmaktadır. <add> <add>Lütfen bir sorun için kodlama yardımı isteyen issue'ların kapatılacağını unutmayın. Issue-tracker codebase ile alakalı sorunlar ve tartışmalar içindir. Bir şüphe durumunda, sorunu bildirmeden önce [forum üzerinde yardım aramalısınız](https://www.freecodecamp.org/forum). <add> <add>**Bir güvenlik sorununu nasıl bildirebilirim?** <add> <add>Güvenlik sorunları için herhangi bir GitHub issue yaratmak yerine lütfen, `[email protected]` adresine mail atınız. Sorunu derhal inceleyeceğiz. <add> <add>**Sorunlara etiketlenen etiketler ne anlama geliyor?** <add> <add>Topluluk moderotörlerimiz, issue'ları [aciliyetine göre sıralar](https://en.wikipedia.org/wiki/Software_bug#Bug_management) ve istekleri önceliklerine, ciddiyetine ve diğer faktörlere incelemeye alırlar. Etiketlerin [anlamlarının sözlüğünü buradan bulabilirsiniz](https://github.com/freecodecamp/freecodecamp/labels). <add> <add>[**`yardım aranıyor`**](https://github.com/freeCodeCamp/freeCodeCamp/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22) ya da [**`ilk kez gelenler hoş geldiniz`**](https://github.com/freeCodeCamp/freeCodeCamp/issues?q=is%3Aopen+is%3Aissue+label%3A%22first+timers+welcome%22), çalışmanız için neyin uygun olduğuna hızlı bir bakış atın. Bunlar üzerinde çalışmak için izin almanız gerekmez. <add> <add>Eğere bu issue'lar üzerine ne yapılacağı net değilse, yorumlarda soru sormaktan çekinmeyin. <add> <add>**Bir yazım yanlışı buldum, pull request yapmadan önce bir issue açmalı mıyım?** <add> <add>Yazım yanlışları ve kelime değişiklikleri için yeni bir issue yaratmadan, direkt olarak pull request açabilirsiniz. <add> <add>**GitHub'da ve genel olarak Open-Source'ta yeniyim:** <add> <add>[Açık Kaynak Kılavuzuna Nasıl Katkıda Bulunur](https://github.com/freeCodeCamp/how-to-contribute-to-open-source) yazımızı okuyun. <add> <add> <add>**Bu dökümantasyonda olmayan bir konuda takıldığımda nasıl yardım alabilirim?** <add> <add>Yardım istemek için çekinmeyin: <add> <add>- [Public forumumuzun "Katkıda bulunanlar" kategorisi](https://www.freecodecamp.org/forum/c/contributors) <add>- [Katkıda bulunan kişilerimiz Gitter'deki sohbet odası](https://gitter.im/FreeCodeCamp/Contributors) <add> <add>Üzerinde çalışmak istediğiniz konulardan herhangi birine katkıda bulunmanıza yardımcı olmaktan büyük heyecan duyuyoruz. İlgili konu başlıkları hakkında bize sorular sormaktan çekinmeyin, açıklığa kavuşturmaktan memnuniyet duyarız. Yeni bir tane göndermeden önce sorgunuzu aradığınızdan emin olun. Kibar ve sabırlı olun. Gönüllüler ve moderatörler topluluğumuz, sorularınız için size yol göstermek için her zaman yanındadır. <add> <add>Şüphe duyduğunuzda, bu konuda size yardımcı olmak için platform geliştirme ekibimize ulaşabilirsiniz: <add> <add>| Name | GitHub | Twitter | <add>|:----------------|:-------|:--------| <add>| Mrugesh Mohapatra | [`@raisedadead`](https://github.com/raisedadead) | [`@raisedadead`](https://twitter.com/raisedadead)| <add>| Ahmad Abdolsaheb | [`@ahmadabdolsaheb`](https://github.com/ahmadabdolsaheb) | [`@Abdolsaheb`](https://twitter.com/Abdolsaheb) | <add>| Kristofer Koishigawa | [`@scissorsneedfoodtoo`](https://github.com/scissorsneedfoodtoo) | [`@kriskoishigawa`](https://twitter.com/kriskoishigawa) | <add> <add>> **Email: `[email protected]`**
1
Text
Text
update nan urls in roadmap.md and doc/releases.md
0eda5f503a2fae915ae152bd221b523762a0ef97
<ide><path>ROADMAP.md <ide> Node.js does not remove stdlib JS API. <ide> Shipping with current and well supported dependencies is the best way to ensure long term stability of the platform. When those dependencies are no longer maintained Node.js will take on their continued maintenance as part of our [Long Term Support policy](#long-term-support). <ide> <ide> Node.js will continue to adopt new V8 releases. <del>* When V8 ships a breaking change to their C++ API that can be handled by [`nan`](https://github.com/rvagg/nan) <add>* When V8 ships a breaking change to their C++ API that can be handled by [`nan`](https://github.com/nodejs/nan) <ide> the *minor* version of Node.js will be increased. <del>* When V8 ships a breaking change to their C++ API that can NOT be handled by [`nan`](https://github.com/rvagg/nan) <add>* When V8 ships a breaking change to their C++ API that can NOT be handled by [`nan`](https://github.com/nodejs/nan) <ide> the *major* version of Node.js will be increased. <ide> * When new features in the JavaScript language are introduced by V8 the <ide> *minor* version number will be increased. TC39 has stated clearly that no <ide><path>doc/releases.md <ide> Set the `NODE_VERSION_IS_RELEASE` macro value to `1`. This causes the build to b <ide> <ide> This macro is used to signal an ABI version for native addons. It currently has two common uses in the community: <ide> <del>* Determining what API to work against for compiling native addons, e.g. [NAN](https://github.com/rvagg/nan) uses it to form a compatibility-layer for much of what it wraps. <add>* Determining what API to work against for compiling native addons, e.g. [NAN](https://github.com/nodejs/nan) uses it to form a compatibility-layer for much of what it wraps. <ide> * Determining the ABI for downloading pre-built binaries of native addons, e.g. [node-pre-gyp](https://github.com/mapbox/node-pre-gyp) uses this value as exposed via `process.versions.modules` to help determine the appropriate binary to download at install-time. <ide> <ide> The general rule is to bump this version when there are _breaking ABI_ changes and also if there are non-trivial API changes. The rules are not yet strictly defined, so if in doubt, please confer with someone that will have a more informed perspective, such as a member of the NAN team.
2
Go
Go
add plugingetter to pkg
d599d53db27f4a24b18f51464c39707eae383c7e
<ide><path>pkg/plugingetter/getter.go <add>package plugingetter <add> <add>import "github.com/docker/docker/pkg/plugins" <add> <add>const ( <add> // LOOKUP doesn't update RefCount <add> LOOKUP = 0 <add> // CREATE increments RefCount <add> CREATE = 1 <add> // REMOVE decrements RefCount <add> REMOVE = -1 <add>) <add> <add>// CompatPlugin is a abstraction to handle both v2(new) and v1(legacy) plugins. <add>type CompatPlugin interface { <add> Client() *plugins.Client <add> Name() string <add> IsV1() bool <add>} <add> <add>// PluginGetter is the interface implemented by Store <add>type PluginGetter interface { <add> Get(name, capability string, mode int) (CompatPlugin, error) <add> GetAllByCap(capability string) ([]CompatPlugin, error) <add> Handle(capability string, callback func(string, *plugins.Client)) <add>}
1
Python
Python
add num_workers arg to dataloader
2d7c1bb192bafba6fbc81b6b02489a1d08228076
<ide><path>src/transformers/trainer.py <ide> def get_test_dataloader(self, test_dataset: Dataset) -> DataLoader: <ide> batch_size=self.args.eval_batch_size, <ide> collate_fn=data_collator, <ide> drop_last=self.args.dataloader_drop_last, <add> num_workers=self.args.dataloader_num_workers, <ide> pin_memory=self.args.dataloader_pin_memory, <ide> ) <ide>
1
Javascript
Javascript
fix typo in comment
6c61ca5325a411c4b64177c5bca58030ea5b97a4
<ide><path>lib/url.js <ide> Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { <ide> // <ide> // ex: <ide> // http://a@b@c/ => user:a@b host:c <del> // http://a@b?@c => user:a host:c path:/?@c <add> // http://a@b?@c => user:a host:b path:/?@c <ide> <ide> // v0.12 TODO(isaacs): This is not quite how Chrome does things. <ide> // Review our test case against browsers more comprehensively.
1
Text
Text
remove references to pinning
d666b8554d8f59d06cfb6c284c220b6e3254f4bc
<ide><path>docs/Taps.md <ide> dunn/emacs <ide> version: `brew tap username/homebrew-foobar`. `brew` will automatically add <ide> back the 'homebrew-' prefix whenever it's necessary. <ide> <del>## Formula duplicate names <add>## Formula with duplicate names <ide> <ide> If your tap contains a formula that is also present in <ide> [homebrew/core](https://github.com/Homebrew/homebrew-core), that's fine, <ide> but it means that you must install it explicitly by default. <ide> <del>If you would like to prioritise a tap over `homebrew/core`, you can use <del>`brew tap-pin username/repo` to pin the tap, <del>and use `brew tap-unpin username/repo` to revert the pin. <del> <ide> Whenever a `brew install foo` command is issued, `brew` will find which formula <ide> to use by searching in the following order: <ide> <del>* pinned taps <ide> * core formulae <ide> * other taps <ide> <ide> If you need a formula to be installed from a particular tap, you can use fully <ide> qualified names to refer to them. <ide> <del>For example, you can create a tap for an alternative `vim` formula. Without <del>pinning it, the behaviour will be: <add>You can create a tap for an alternative `vim` formula. The behaviour will be: <ide> <ide> ```sh <ide> brew install vim # installs from homebrew/core <ide> brew install username/repo/vim # installs from your custom repository <ide> ``` <ide> <del>However if you pin the tap with `brew tap-pin username/repo`, you will need to <del>use `homebrew/core` to refer to the core formula. <del> <del>```sh <del>brew install vim # installs from your custom repository <del>brew install homebrew/core/vim # installs from homebrew/core <del>``` <del> <del>Note that pinned taps are prioritized only when the formula name is directly <del>given by you, i.e. it will not influence formulae automatically installed as <del>dependencies. <add>As a result, we recommend you give formulae a different name if you want to make <add>them easier to install. Note that there is (intentionally) no way of replacing <add>dependencies of core formulae with those from taps.
1
Text
Text
update verb form "learning"
446be9460c368f6cd6a3e2affa480d8db9a2e3e1
<ide><path>guide/english/working-in-tech/dunning-kruger-effect/index.md <ide> DK Effect is exactly opposite of [Imposter Syndrome](https://en.wikipedia.org/wi <ide> Sorry, but there isn't a straight answer to this question. You can ask following questions to yourself: <ide> <ide> - Are you able to give accurate estimates? <del> - Are you open to learn new concepts? <add> - Are you open to learning new concepts? <ide> - Are you open to implement or try new design paradigms? <ide> - Are you humble? <ide> - Are you able to take criticism and objectively evaluate feedback?
1
PHP
PHP
adjust type hint
8ac01ded45adaf88519d65285e009d8826e82964
<ide><path>src/Illuminate/Foundation/helpers.php <ide> function redirect($to = null, $status = 302, $headers = [], $secure = null) <ide> /** <ide> * Get an instance of the current request or an input item from the request. <ide> * <del> * @param string $key <add> * @param array|string $key <ide> * @param mixed $default <ide> * @return \Illuminate\Http\Request|string|array <ide> */
1
PHP
PHP
use splfileinfo instead of file in response
a4dfd960b91c8bd2d303acc69e5818d679ab171a
<ide><path>src/Http/Response.php <ide> namespace Cake\Http; <ide> <ide> use Cake\Core\Configure; <del>use Cake\Filesystem\File; <ide> use Cake\Http\Cookie\CookieCollection; <ide> use Cake\Http\Cookie\CookieInterface; <ide> use Cake\Http\Exception\NotFoundException; <ide> use InvalidArgumentException; <ide> use Psr\Http\Message\ResponseInterface; <ide> use Psr\Http\Message\StreamInterface; <add>use SplFileInfo; <ide> use Zend\Diactoros\MessageTrait; <ide> use Zend\Diactoros\Stream; <ide> <ide> class Response implements ResponseInterface <ide> /** <ide> * File object for file to be read out as response <ide> * <del> * @var \Cake\Filesystem\File|null <add> * @var \SplFileInfo|null <ide> */ <ide> protected $_file; <ide> <ide> public function withFile(string $path, array $options = []): self <ide> 'download' => null, <ide> ]; <ide> <del> $extension = strtolower($file->ext()); <add> $extension = strtolower($file->getExtension()); <ide> $mapped = $this->getMimeType($extension); <ide> if ((!$extension || !$mapped) && $options['download'] === null) { <ide> $options['download'] = true; <ide> public function withFile(string $path, array $options = []): self <ide> $new = $new->withType($extension); <ide> } <ide> <del> $fileSize = $file->size(); <add> $fileSize = $file->getSize(); <ide> if ($options['download']) { <ide> $agent = env('HTTP_USER_AGENT'); <ide> <ide> public function withFile(string $path, array $options = []): self <ide> if (isset($contentType)) { <ide> $new = $new->withType($contentType); <ide> } <del> $name = $options['name'] ?: $file->name; <add> $name = $options['name'] ?: $file->getFileName(); <ide> $new = $new->withDownload($name) <ide> ->withHeader('Content-Transfer-Encoding', 'binary'); <ide> } <ide> public function withFile(string $path, array $options = []): self <ide> $new = $new->withHeader('Content-Length', (string)$fileSize); <ide> } <ide> $new->_file = $file; <del> $new->stream = new Stream($file->path, 'rb'); <add> $new->stream = new Stream($file->getPathname(), 'rb'); <ide> <ide> return $new; <ide> } <ide> public function withStringBody(?string $string): self <ide> * <ide> * @param string $path The path to the file. <ide> * @throws \Cake\Http\Exception\NotFoundException <del> * @return \Cake\Filesystem\File <add> * @return \SplFileInfo <ide> */ <del> protected function validateFile(string $path): File <add> protected function validateFile(string $path): SplFileInfo <ide> { <ide> if (strpos($path, '../') !== false || strpos($path, '..\\') !== false) { <ide> throw new NotFoundException(__d('cake', 'The requested file contains `..` and will not be read.')); <ide> } <ide> <del> $file = new File($path); <del> if (!$file->exists() || !$file->readable()) { <add> $file = new SplFileInfo($path); <add> if (!$file->isFile() || !$file->isReadable()) { <ide> if (Configure::read('debug')) { <ide> throw new NotFoundException(sprintf('The requested file %s was not found or not readable', $path)); <ide> } <ide> protected function validateFile(string $path): File <ide> /** <ide> * Get the current file if one exists. <ide> * <del> * @return \Cake\Filesystem\File|null The file to use in the response or null <add> * @return \SplFileInfo|null The file to use in the response or null <ide> */ <del> public function getFile(): ?File <add> public function getFile(): ?SplFileInfo <ide> { <ide> return $this->_file; <ide> } <ide> public function getFile(): ?File <ide> * If an invalid range is requested a 416 Status code will be used <ide> * in the response. <ide> * <del> * @param \Cake\Filesystem\File $file The file to set a range on. <add> * @param \SplFileInfo $file The file to set a range on. <ide> * @param string $httpRange The range to use. <ide> * @return void <ide> */ <del> protected function _fileRange(File $file, string $httpRange): void <add> protected function _fileRange(SplFileInfo $file, string $httpRange): void <ide> { <del> $fileSize = $file->size(); <add> $fileSize = $file->getSize(); <ide> $lastByte = $fileSize - 1; <ide> $start = 0; <ide> $end = $lastByte; <ide><path>src/TestSuite/Constraint/Response/FileSentAs.php <ide> class FileSentAs extends ResponseBase <ide> */ <ide> public function matches($other): bool <ide> { <del> return $this->response->getFile()->path === $other; <add> return $this->response->getFile()->getPathName() === $other; <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Http/ResponseTest.php <ide> public function testWithFileDownloadAndName() <ide> <ide> $expected = '/* this is the test asset css file */'; <ide> $this->assertEquals($expected, trim($body->getContents())); <del> $this->assertEquals($expected, trim($new->getFile()->read())); <add> $file = $new->getFile()->openFile(); <add> $this->assertEquals($expected, trim($file->fread(100))); <ide> } <ide> <ide> /**
3
Javascript
Javascript
link warning to error boundary post
9a290fb1a704701d089c948a5c72f3ed8c663db1
<ide><path>src/renderers/shared/fiber/ReactFiberErrorLogger.js <ide> function logCapturedError(capturedError: CapturedError): void { <ide> `Recreating the tree from scratch failed so React will unmount the tree.`; <ide> } <ide> } else { <del> // TODO Link to componentDidCatch() documentation once it exists. <ide> errorBoundaryMessage = <del> 'Consider adding an error boundary to your tree to customize error handling behavior.'; <add> 'Consider adding an error boundary to your tree to customize error handling behavior. ' + <add> 'See https://fb.me/react-error-boundaries for more information.'; <ide> } <ide> <ide> console.error(
1
Ruby
Ruby
reduce method calls in the dynamic finder matcher
9e652b65c2c481f2b4ae0cda9df42d4bb56b9f3c
<ide><path>activerecord/lib/active_record/dynamic_finder_match.rb <ide> module ActiveRecord <ide> # <ide> class DynamicFinderMatch <ide> def self.match(method) <del> df_match = self.new(method) <del> df_match.finder ? df_match : nil <add> df_match = new(method) <add> df_match.finder && df_match <ide> end <ide> <ide> def initialize(method) <ide> def initialize(method) <ide> attr_reader :finder, :attribute_names, :instantiator <ide> <ide> def finder? <del> [email protected]? && @instantiator.nil? <add> @finder && !@instantiator <ide> end <ide> <ide> def instantiator? <del> @finder == :first && [email protected]? <add> @finder == :first && @instantiator <ide> end <ide> <ide> def creator?
1
Javascript
Javascript
remove leftover {{debugger}}
998eaa68defd4ec62ad4f371026a4bbe55145ac5
<ide><path>packages/ember-htmlbars/tests/integration/component_lifecycle_test.js <ide> styles.forEach(style => { <ide> <ide> QUnit.test('changing a component\'s displayed properties inside didInsertElement() is deprecated', function(assert) { <ide> let component = style.class.extend({ <del> layout: compile('<div>{{debugger}}{{handle}}</div>'), <add> layout: compile('<div>{{handle}}</div>'), <ide> handle: '@wycats', <ide> container: container, <ide>
1
Javascript
Javascript
fix timeout in write-stream-throughput
b43a496092379edc450cb7aebe3528686a3f41d2
<ide><path>benchmark/fs/write-stream-throughput.js <ide> function main(conf) { <ide> var started = false; <ide> var ending = false; <ide> var ended = false; <del> setTimeout(function() { <del> ending = true; <del> f.end(); <del> }, dur * 1000); <ide> <ide> var f = fs.createWriteStream(filename); <ide> f.on('drain', write); <ide> function main(conf) { <ide> <ide> if (!started) { <ide> started = true; <add> setTimeout(function() { <add> ending = true; <add> f.end(); <add> }, dur * 1000); <ide> bench.start(); <ide> } <ide>
1
Javascript
Javascript
add required settings to test-benchmark-buffer
b9ff6a3fb1db4868473f9b326cb6038f3e1823a9
<ide><path>test/benchmark/test-benchmark-buffer.js <ide> runBenchmark('buffers', <ide> 'aligned=true', <ide> 'args=1', <ide> 'buffer=fast', <add> 'bytes=0', <ide> 'byteLength=1', <ide> 'charsPerLine=6', <ide> 'encoding=utf8', <ide> runBenchmark('buffers', <ide> 'linesCount=1', <ide> 'method=', <ide> 'n=1', <add> 'partial=true', <ide> 'pieces=1', <ide> 'pieceSize=1', <ide> 'search=@',
1
Python
Python
remove u-prefix for former unicode strings
13d55a3c2f016a58a6e9d6b8086f338e07c7478f
<ide><path>benchmarks/benchmarks/bench_io.py <ide> class LoadtxtCSVComments(Benchmark): <ide> param_names = ['num_lines'] <ide> <ide> def setup(self, num_lines): <del> data = [u'1,2,3 # comment'] * num_lines <add> data = ['1,2,3 # comment'] * num_lines <ide> # unfortunately, timeit will only run setup() <ide> # between repeat events, but not for iterations <ide> # within repeats, so the StringIO object <ide> # will have to be rewinded in the benchmark proper <del> self.data_comments = StringIO(u'\n'.join(data)) <add> self.data_comments = StringIO('\n'.join(data)) <ide> <ide> def time_comment_loadtxt_csv(self, num_lines): <ide> # benchmark handling of lines with comments <ide> def time_comment_loadtxt_csv(self, num_lines): <ide> # confounding timing result somewhat) for every <ide> # call to timing test proper <ide> np.loadtxt(self.data_comments, <del> delimiter=u',') <add> delimiter=',') <ide> self.data_comments.seek(0) <ide> <ide> class LoadtxtCSVdtypes(Benchmark): <ide> class LoadtxtCSVdtypes(Benchmark): <ide> param_names = ['dtype', 'num_lines'] <ide> <ide> def setup(self, dtype, num_lines): <del> data = [u'5, 7, 888'] * num_lines <del> self.csv_data = StringIO(u'\n'.join(data)) <add> data = ['5, 7, 888'] * num_lines <add> self.csv_data = StringIO('\n'.join(data)) <ide> <ide> def time_loadtxt_dtypes_csv(self, dtype, num_lines): <ide> # benchmark loading arrays of various dtypes <ide> def time_loadtxt_dtypes_csv(self, dtype, num_lines): <ide> # rewind of StringIO object <ide> <ide> np.loadtxt(self.csv_data, <del> delimiter=u',', <add> delimiter=',', <ide> dtype=dtype) <ide> self.csv_data.seek(0) <ide> <ide> class LoadtxtCSVStructured(Benchmark): <ide> <ide> def setup(self): <ide> num_lines = 50000 <del> data = [u"M, 21, 72, X, 155"] * num_lines <del> self.csv_data = StringIO(u'\n'.join(data)) <add> data = ["M, 21, 72, X, 155"] * num_lines <add> self.csv_data = StringIO('\n'.join(data)) <ide> <ide> def time_loadtxt_csv_struct_dtype(self): <ide> # obligate rewind of StringIO object <ide> # between iterations of a repeat: <ide> <ide> np.loadtxt(self.csv_data, <del> delimiter=u',', <add> delimiter=',', <ide> dtype=[('category_1', 'S1'), <ide> ('category_2', 'i4'), <ide> ('category_3', 'f8'), <ide> class LoadtxtReadUint64Integers(Benchmark): <ide> <ide> def setup(self, size): <ide> arr = np.arange(size).astype('uint64') + 2**63 <del> self.data1 = StringIO(u'\n'.join(arr.astype(str).tolist())) <add> self.data1 = StringIO('\n'.join(arr.astype(str).tolist())) <ide> arr = arr.astype(object) <ide> arr[500] = -1 <del> self.data2 = StringIO(u'\n'.join(arr.astype(str).tolist())) <add> self.data2 = StringIO('\n'.join(arr.astype(str).tolist())) <ide> <ide> def time_read_uint64(self, size): <ide> # mandatory rewind of StringIO object <ide> class LoadtxtUseColsCSV(Benchmark): <ide> <ide> def setup(self, usecols): <ide> num_lines = 5000 <del> data = [u'0, 1, 2, 3, 4, 5, 6, 7, 8, 9'] * num_lines <del> self.csv_data = StringIO(u'\n'.join(data)) <add> data = ['0, 1, 2, 3, 4, 5, 6, 7, 8, 9'] * num_lines <add> self.csv_data = StringIO('\n'.join(data)) <ide> <ide> def time_loadtxt_usecols_csv(self, usecols): <ide> # must rewind StringIO because of state <ide> # dependence of file reading <ide> np.loadtxt(self.csv_data, <del> delimiter=u',', <add> delimiter=',', <ide> usecols=usecols) <ide> self.csv_data.seek(0) <ide> <ide> def setup(self, num_lines): <ide> dates = np.arange('today', 20, dtype=np.datetime64) <ide> np.random.seed(123) <ide> values = np.random.rand(20) <del> date_line = u'' <add> date_line = '' <ide> <ide> for date, value in zip(dates, values): <ide> date_line += (str(date) + ',' + str(value) + '\n') <ide> def time_loadtxt_csv_datetime(self, num_lines): <ide> # rewind StringIO object -- the timing iterations <ide> # are state-dependent <ide> X = np.loadtxt(self.csv_data, <del> delimiter=u',', <add> delimiter=',', <ide> dtype=([('dates', 'M8[us]'), <ide> ('values', 'float64')])) <ide> self.csv_data.seek(0) <ide><path>doc/neps/conf.py <ide> master_doc = 'content' <ide> <ide> # General information about the project. <del>project = u'NumPy Enhancement Proposals' <del>copyright = u'2017-2018, NumPy Developers' <del>author = u'NumPy Developers' <add>project = 'NumPy Enhancement Proposals' <add>copyright = '2017-2018, NumPy Developers' <add>author = 'NumPy Developers' <add>title = 'NumPy Enhancement Proposals Documentation' <ide> <ide> # The version info for the project you're documenting, acts as replacement for <ide> # |version| and |release|, also used in various other places throughout the <ide> # built documents. <ide> # <ide> # The short X.Y version. <del>version = u'' <add>version = '' <ide> # The full version, including alpha/beta/rc tags. <del>release = u'' <add>release = '' <ide> <ide> # The language for content autogenerated by Sphinx. Refer to documentation <ide> # for a list of supported languages. <ide> # (source start file, target name, title, <ide> # author, documentclass [howto, manual, or own class]). <ide> latex_documents = [ <del> (master_doc, 'NumPyEnhancementProposals.tex', u'NumPy Enhancement Proposals Documentation', <del> u'NumPy Developers', 'manual'), <add> (master_doc, 'NumPyEnhancementProposals.tex', title, <add> 'NumPy Developers', 'manual'), <ide> ] <ide> <ide> <ide> # One entry per manual page. List of tuples <ide> # (source start file, name, description, authors, manual section). <ide> man_pages = [ <del> (master_doc, 'numpyenhancementproposals', u'NumPy Enhancement Proposals Documentation', <add> (master_doc, 'numpyenhancementproposals', title, <ide> [author], 1) <ide> ] <ide> <ide> # (source start file, target name, title, author, <ide> # dir menu entry, description, category) <ide> texinfo_documents = [ <del> (master_doc, 'NumPyEnhancementProposals', u'NumPy Enhancement Proposals Documentation', <add> (master_doc, 'NumPyEnhancementProposals', title, <ide> author, 'NumPyEnhancementProposals', 'One line description of project.', <ide> 'Miscellaneous'), <ide> ] <ide><path>numpy/core/tests/test_api.py <ide> class MyNDArray(np.ndarray): <ide> b = a.astype('S') <ide> assert_equal(a, b) <ide> assert_equal(b.dtype, np.dtype('S100')) <del> a = np.array([u'a'*100], dtype='O') <add> a = np.array(['a'*100], dtype='O') <ide> b = a.astype('U') <ide> assert_equal(a, b) <ide> assert_equal(b.dtype, np.dtype('U100')) <ide> class MyNDArray(np.ndarray): <ide> b = a.astype('S') <ide> assert_equal(a, b) <ide> assert_equal(b.dtype, np.dtype('S10')) <del> a = np.array([u'a'*10], dtype='O') <add> a = np.array(['a'*10], dtype='O') <ide> b = a.astype('U') <ide> assert_equal(a, b) <ide> assert_equal(b.dtype, np.dtype('U10')) <ide> <ide> a = np.array(123456789012345678901234567890, dtype='O').astype('S') <ide> assert_array_equal(a, np.array(b'1234567890' * 3, dtype='S30')) <ide> a = np.array(123456789012345678901234567890, dtype='O').astype('U') <del> assert_array_equal(a, np.array(u'1234567890' * 3, dtype='U30')) <add> assert_array_equal(a, np.array('1234567890' * 3, dtype='U30')) <ide> <ide> a = np.array([123456789012345678901234567890], dtype='O').astype('S') <ide> assert_array_equal(a, np.array(b'1234567890' * 3, dtype='S30')) <ide> a = np.array([123456789012345678901234567890], dtype='O').astype('U') <del> assert_array_equal(a, np.array(u'1234567890' * 3, dtype='U30')) <add> assert_array_equal(a, np.array('1234567890' * 3, dtype='U30')) <ide> <ide> a = np.array(123456789012345678901234567890, dtype='S') <ide> assert_array_equal(a, np.array(b'1234567890' * 3, dtype='S30')) <ide> a = np.array(123456789012345678901234567890, dtype='U') <del> assert_array_equal(a, np.array(u'1234567890' * 3, dtype='U30')) <add> assert_array_equal(a, np.array('1234567890' * 3, dtype='U30')) <ide> <del> a = np.array(u'a\u0140', dtype='U') <add> a = np.array('a\u0140', dtype='U') <ide> b = np.ndarray(buffer=a, dtype='uint32', shape=2) <ide> assert_(b.size == 2) <ide> <ide><path>numpy/core/tests/test_arrayprint.py <ide> def test_formatter_reset(self): <ide> assert_equal(repr(x), "array([0., 1., 2.])") <ide> <ide> def test_0d_arrays(self): <del> assert_equal(str(np.array(u'café', '<U4')), u'café') <add> assert_equal(str(np.array('café', '<U4')), 'café') <ide> <ide> assert_equal(repr(np.array('café', '<U4')), <ide> "array('café', dtype='<U4')") <ide> def test_bad_args(self): <ide> <ide> def test_unicode_object_array(): <ide> expected = "array(['é'], dtype=object)" <del> x = np.array([u'\xe9'], dtype=object) <add> x = np.array(['\xe9'], dtype=object) <ide> assert_equal(repr(x), expected) <ide> <ide> <ide><path>numpy/core/tests/test_defchararray.py <del> <ide> import numpy as np <ide> from numpy.core.multiarray import _vec_string <ide> from numpy.testing import ( <ide> def test_from_object_array(self): <ide> [b'long', b'0123456789']]) <ide> <ide> def test_from_object_array_unicode(self): <del> A = np.array([['abc', u'Sigma \u03a3'], <add> A = np.array([['abc', 'Sigma \u03a3'], <ide> ['long ', '0123456789']], dtype='O') <ide> assert_raises(ValueError, np.char.array, (A,)) <ide> B = np.char.array(A, **kw_unicode_true) <ide> assert_equal(B.dtype.itemsize, 10 * np.array('a', 'U').dtype.itemsize) <del> assert_array_equal(B, [['abc', u'Sigma \u03a3'], <add> assert_array_equal(B, [['abc', 'Sigma \u03a3'], <ide> ['long', '0123456789']]) <ide> <ide> def test_from_string_array(self): <ide> def test_from_string_array(self): <ide> assert_(C[0, 0] == A[0, 0]) <ide> <ide> def test_from_unicode_array(self): <del> A = np.array([['abc', u'Sigma \u03a3'], <add> A = np.array([['abc', 'Sigma \u03a3'], <ide> ['long ', '0123456789']]) <ide> assert_equal(A.dtype.type, np.unicode_) <ide> B = np.char.array(A) <ide> def fail(): <ide> <ide> def test_unicode_upconvert(self): <ide> A = np.char.array(['abc']) <del> B = np.char.array([u'\u03a3']) <add> B = np.char.array(['\u03a3']) <ide> assert_(issubclass((A + B).dtype.type, np.unicode_)) <ide> <ide> def test_from_string(self): <ide> def test_from_string(self): <ide> assert_(issubclass(A.dtype.type, np.string_)) <ide> <ide> def test_from_unicode(self): <del> A = np.char.array(u'\u03a3') <add> A = np.char.array('\u03a3') <ide> assert_equal(len(A), 1) <ide> assert_equal(len(A[0]), 1) <ide> assert_equal(A.itemsize, 4) <ide> def setup(self): <ide> self.A = np.array([[' abc ', ''], <ide> ['12345', 'MixedCase'], <ide> ['123 \t 345 \0 ', 'UPPER']]).view(np.chararray) <del> self.B = np.array([[u' \u03a3 ', u''], <del> [u'12345', u'MixedCase'], <del> [u'123 \t 345 \0 ', u'UPPER']]).view(np.chararray) <add> self.B = np.array([[' \u03a3 ', ''], <add> ['12345', 'MixedCase'], <add> ['123 \t 345 \0 ', 'UPPER']]).view(np.chararray) <ide> <ide> def test_len(self): <ide> assert_(issubclass(np.char.str_len(self.A).dtype.type, np.integer)) <ide> def setup(self): <ide> ['12345', 'MixedCase'], <ide> ['123 \t 345 \0 ', 'UPPER']], <ide> dtype='S').view(np.chararray) <del> self.B = np.array([[u' \u03a3 ', u''], <del> [u'12345', u'MixedCase'], <del> [u'123 \t 345 \0 ', u'UPPER']]).view(np.chararray) <add> self.B = np.array([[' \u03a3 ', ''], <add> ['12345', 'MixedCase'], <add> ['123 \t 345 \0 ', 'UPPER']]).view(np.chararray) <ide> <ide> def test_capitalize(self): <ide> tgt = [[b' abc ', b''], <ide> def test_capitalize(self): <ide> assert_(issubclass(self.A.capitalize().dtype.type, np.string_)) <ide> assert_array_equal(self.A.capitalize(), tgt) <ide> <del> tgt = [[u' \u03c3 ', ''], <add> tgt = [[' \u03c3 ', ''], <ide> ['12345', 'Mixedcase'], <ide> ['123 \t 345 \0 ', 'Upper']] <ide> assert_(issubclass(self.B.capitalize().dtype.type, np.unicode_)) <ide> def test_lower(self): <ide> assert_(issubclass(self.A.lower().dtype.type, np.string_)) <ide> assert_array_equal(self.A.lower(), tgt) <ide> <del> tgt = [[u' \u03c3 ', u''], <del> [u'12345', u'mixedcase'], <del> [u'123 \t 345 \0 ', u'upper']] <add> tgt = [[' \u03c3 ', ''], <add> ['12345', 'mixedcase'], <add> ['123 \t 345 \0 ', 'upper']] <ide> assert_(issubclass(self.B.lower().dtype.type, np.unicode_)) <ide> assert_array_equal(self.B.lower(), tgt) <ide> <ide> def test_lstrip(self): <ide> [b'23 \t 345 \x00', b'UPPER']] <ide> assert_array_equal(self.A.lstrip([b'1', b'M']), tgt) <ide> <del> tgt = [[u'\u03a3 ', ''], <add> tgt = [['\u03a3 ', ''], <ide> ['12345', 'MixedCase'], <ide> ['123 \t 345 \0 ', 'UPPER']] <ide> assert_(issubclass(self.B.lstrip().dtype.type, np.unicode_)) <ide> def test_rstrip(self): <ide> ] <ide> assert_array_equal(self.A.rstrip([b'5', b'ER']), tgt) <ide> <del> tgt = [[u' \u03a3', ''], <add> tgt = [[' \u03a3', ''], <ide> ['12345', 'MixedCase'], <ide> ['123 \t 345', 'UPPER']] <ide> assert_(issubclass(self.B.rstrip().dtype.type, np.unicode_)) <ide> def test_strip(self): <ide> [b'23 \t 345 \x00', b'UPP']] <ide> assert_array_equal(self.A.strip([b'15', b'EReM']), tgt) <ide> <del> tgt = [[u'\u03a3', ''], <add> tgt = [['\u03a3', ''], <ide> ['12345', 'MixedCase'], <ide> ['123 \t 345', 'UPPER']] <ide> assert_(issubclass(self.B.strip().dtype.type, np.unicode_)) <ide> def test_swapcase(self): <ide> assert_(issubclass(self.A.swapcase().dtype.type, np.string_)) <ide> assert_array_equal(self.A.swapcase(), tgt) <ide> <del> tgt = [[u' \u03c3 ', u''], <del> [u'12345', u'mIXEDcASE'], <del> [u'123 \t 345 \0 ', u'upper']] <add> tgt = [[' \u03c3 ', ''], <add> ['12345', 'mIXEDcASE'], <add> ['123 \t 345 \0 ', 'upper']] <ide> assert_(issubclass(self.B.swapcase().dtype.type, np.unicode_)) <ide> assert_array_equal(self.B.swapcase(), tgt) <ide> <ide> def test_title(self): <ide> assert_(issubclass(self.A.title().dtype.type, np.string_)) <ide> assert_array_equal(self.A.title(), tgt) <ide> <del> tgt = [[u' \u03a3 ', u''], <del> [u'12345', u'Mixedcase'], <del> [u'123 \t 345 \0 ', u'Upper']] <add> tgt = [[' \u03a3 ', ''], <add> ['12345', 'Mixedcase'], <add> ['123 \t 345 \0 ', 'Upper']] <ide> assert_(issubclass(self.B.title().dtype.type, np.unicode_)) <ide> assert_array_equal(self.B.title(), tgt) <ide> <ide> def test_upper(self): <ide> assert_(issubclass(self.A.upper().dtype.type, np.string_)) <ide> assert_array_equal(self.A.upper(), tgt) <ide> <del> tgt = [[u' \u03a3 ', u''], <del> [u'12345', u'MIXEDCASE'], <del> [u'123 \t 345 \0 ', u'UPPER']] <add> tgt = [[' \u03a3 ', ''], <add> ['12345', 'MIXEDCASE'], <add> ['123 \t 345 \0 ', 'UPPER']] <ide> assert_(issubclass(self.B.upper().dtype.type, np.unicode_)) <ide> assert_array_equal(self.B.upper(), tgt) <ide> <ide><path>numpy/core/tests/test_dtype.py <ide> def test_dtypes_are_true(): <ide> def test_invalid_dtype_string(): <ide> # test for gh-10440 <ide> assert_raises(TypeError, np.dtype, 'f8,i8,[f8,i8]') <del> assert_raises(TypeError, np.dtype, u'Fl\xfcgel') <add> assert_raises(TypeError, np.dtype, 'Fl\xfcgel') <ide> <ide> <ide> def test_keyword_argument(): <ide><path>numpy/core/tests/test_einsum.py <ide> def test_einsum_misc(self): <ide> assert_equal(np.einsum('ij...,j...->i...', a, b, optimize=True), [[[2], [2]]]) <ide> <ide> # Regression test for issue #10369 (test unicode inputs with Python 2) <del> assert_equal(np.einsum(u'ij...,j...->i...', a, b), [[[2], [2]]]) <add> assert_equal(np.einsum('ij...,j...->i...', a, b), [[[2], [2]]]) <ide> assert_equal(np.einsum('...i,...i', [1, 2, 3], [2, 3, 4]), 20) <del> assert_equal(np.einsum(u'...i,...i', [1, 2, 3], [2, 3, 4]), 20) <ide> assert_equal(np.einsum('...i,...i', [1, 2, 3], [2, 3, 4], <del> optimize=u'greedy'), 20) <add> optimize='greedy'), 20) <ide> <ide> # The iterator had an issue with buffering this reduction <ide> a = np.ones((5, 12, 4, 2, 3), np.int64) <ide><path>numpy/core/tests/test_multiarray.py <ide> def inject_str(s): <ide> finally: <ide> set_string_function(None, repr=False) <ide> <del> a1d = np.array([u'test']) <del> a0d = np.array(u'done') <del> with inject_str(u'bad'): <add> a1d = np.array(['test']) <add> a0d = np.array('done') <add> with inject_str('bad'): <ide> a1d[0] = a0d # previously this would invoke __str__ <del> assert_equal(a1d[0], u'done') <add> assert_equal(a1d[0], 'done') <ide> <ide> # this would crash for the same reason <del> np.array([np.array(u'\xe5\xe4\xf6')]) <add> np.array([np.array('\xe5\xe4\xf6')]) <ide> <ide> def test_stringlike_empty_list(self): <ide> # gh-8902 <del> u = np.array([u'done']) <add> u = np.array(['done']) <ide> b = np.array([b'done']) <ide> <ide> class bad_sequence: <ide> def test_mixed(self): <ide> assert_array_equal(g1 >= g2, [x >= g2 for x in g1]) <ide> <ide> def test_unicode(self): <del> g1 = np.array([u"This", u"is", u"example"]) <del> g2 = np.array([u"This", u"was", u"example"]) <add> g1 = np.array(["This", "is", "example"]) <add> g2 = np.array(["This", "was", "example"]) <ide> assert_array_equal(g1 == g2, [g1[i] == g2[i] for i in [0, 1, 2]]) <ide> assert_array_equal(g1 != g2, [g1[i] != g2[i] for i in [0, 1, 2]]) <ide> assert_array_equal(g1 <= g2, [g1[i] <= g2[i] for i in [0, 1, 2]]) <ide> def test_dtype_unicode(): <ide> def test_fromarrays_unicode(self): <ide> # A single name string provided to fromarrays() is allowed to be unicode <ide> # on both Python 2 and 3: <del> x = np.core.records.fromarrays([[0], [1]], names=u'a,b', formats=u'i4,i4') <add> x = np.core.records.fromarrays( <add> [[0], [1]], names='a,b', formats='i4,i4') <ide> assert_equal(x['a'][0], 0) <ide> assert_equal(x['b'][0], 1) <ide> <ide> def test_unicode_order(self): <ide> # Test that we can sort with order as a unicode field name in both Python 2 and <ide> # 3: <del> name = u'b' <add> name = 'b' <ide> x = np.array([1, 3, 2], dtype=[(name, int)]) <ide> x.sort(order=name) <del> assert_equal(x[u'b'], np.array([1, 2, 3])) <add> assert_equal(x['b'], np.array([1, 2, 3])) <ide> <ide> def test_field_names(self): <ide> # Test unicode and 8-bit / byte strings can be used <ide> def test_field_names(self): <ide> assert_equal(b[['f1', 'f3']][0].tolist(), (2, (1,))) <ide> <ide> # non-ascii unicode field indexing is well behaved <del> assert_raises(ValueError, a.__setitem__, u'\u03e0', 1) <del> assert_raises(ValueError, a.__getitem__, u'\u03e0') <add> assert_raises(ValueError, a.__setitem__, '\u03e0', 1) <add> assert_raises(ValueError, a.__getitem__, '\u03e0') <ide> <ide> def test_record_hash(self): <ide> a = np.array([(1, 2), (1, 2)], dtype='i1,i2') <ide> def test_to_int_scalar(self): <ide> # gh-9972 <ide> assert_equal(4, int_func(np.array('4'))) <ide> assert_equal(5, int_func(np.bytes_(b'5'))) <del> assert_equal(6, int_func(np.unicode_(u'6'))) <add> assert_equal(6, int_func(np.unicode_('6'))) <ide> <ide> # The delegation of int() to __trunc__ was deprecated in <ide> # Python 3.11. <ide> def __array_finalize__(self, obj): <ide> def test_orderconverter_with_nonASCII_unicode_ordering(): <ide> # gh-7475 <ide> a = np.arange(5) <del> assert_raises(ValueError, a.flatten, order=u'\xe2') <add> assert_raises(ValueError, a.flatten, order='\xe2') <ide> <ide> <ide> def test_equal_override(): <ide><path>numpy/core/tests/test_nditer.py <ide> def test_iter_buffering_string(): <ide> assert_raises(TypeError, nditer, a, ['buffered'], ['readonly'], <ide> op_dtypes='U2') <ide> i = nditer(a, ['buffered'], ['readonly'], op_dtypes='U6') <del> assert_equal(i[0], u'abc') <add> assert_equal(i[0], 'abc') <ide> assert_equal(i[0].dtype, np.dtype('U6')) <ide> <ide> def test_iter_buffering_growinner(): <ide><path>numpy/core/tests/test_numerictypes.py <ide> # x Info color info y z <ide> # value y2 Info2 name z2 Name Value <ide> # name value y3 z3 <del> ([3, 2], (6j, 6., (b'nn', [6j, 4j], [6., 4.], [1, 2]), b'NN', True), b'cc', (u'NN', 6j), [[6., 4.], [6., 4.]], 8), <del> ([4, 3], (7j, 7., (b'oo', [7j, 5j], [7., 5.], [2, 1]), b'OO', False), b'dd', (u'OO', 7j), [[7., 5.], [7., 5.]], 9), <add> ([3, 2], (6j, 6., (b'nn', [6j, 4j], [6., 4.], [1, 2]), b'NN', True), <add> b'cc', ('NN', 6j), [[6., 4.], [6., 4.]], 8), <add> ([4, 3], (7j, 7., (b'oo', [7j, 5j], [7., 5.], [2, 1]), b'OO', False), <add> b'dd', ('OO', 7j), [[7., 5.], [7., 5.]], 9), <ide> ] <ide> <ide> <ide><path>numpy/core/tests/test_overrides.py <ide> def test_array_like_not_implemented(self): <ide> ('fromiter', *func_args(range(3), dtype=int)), <ide> ('fromstring', *func_args('1,2', dtype=int, sep=',')), <ide> ('loadtxt', *func_args(lambda: StringIO('0 1\n2 3'))), <del> ('genfromtxt', *func_args(lambda: StringIO(u'1,2.1'), <add> ('genfromtxt', *func_args(lambda: StringIO('1,2.1'), <ide> dtype=[('int', 'i8'), ('float', 'f8')], <ide> delimiter=',')), <ide> ] <ide><path>numpy/core/tests/test_regression.py <ide> def test_scalar_compare(self): <ide> def test_unicode_swapping(self): <ide> # Ticket #79 <ide> ulen = 1 <del> ucs_value = u'\U0010FFFF' <add> ucs_value = '\U0010FFFF' <ide> ua = np.array([[[ucs_value*ulen]*2]*3]*4, dtype='U%s' % ulen) <ide> ua.newbyteorder() # Should succeed. <ide> <ide> def test_unaligned_unicode_access(self): <ide> for i in range(1, 9): <ide> msg = 'unicode offset: %d chars' % i <ide> t = np.dtype([('a', 'S%d' % i), ('b', 'U2')]) <del> x = np.array([(b'a', u'b')], dtype=t) <add> x = np.array([(b'a', 'b')], dtype=t) <ide> assert_equal(str(x), "[(b'a', 'b')]", err_msg=msg) <ide> <ide> def test_sign_for_complex_nan(self): <ide> def test_object_array_to_fixed_string(self): <ide> <ide> def test_unicode_to_string_cast(self): <ide> # Ticket #1240. <del> a = np.array([[u'abc', u'\u03a3'], <del> [u'asdf', u'erw']], <add> a = np.array([['abc', '\u03a3'], <add> ['asdf', 'erw']], <ide> dtype='U') <ide> assert_raises(UnicodeEncodeError, np.array, a, 'S4') <ide> <ide> def test_unicode_to_string_cast_error(self): <ide> # gh-15790 <del> a = np.array([u'\x80'] * 129, dtype='U3') <add> a = np.array(['\x80'] * 129, dtype='U3') <ide> assert_raises(UnicodeEncodeError, np.array, a, 'S') <ide> b = a.reshape(3, 43)[:-1, :-1] <ide> assert_raises(UnicodeEncodeError, np.array, b, 'S') <ide> <del> def test_mixed_string_unicode_array_creation(self): <del> a = np.array(['1234', u'123']) <add> def test_mixed_string_byte_array_creation(self): <add> a = np.array(['1234', b'123']) <ide> assert_(a.itemsize == 16) <del> a = np.array([u'123', '1234']) <add> a = np.array([b'123', '1234']) <ide> assert_(a.itemsize == 16) <del> a = np.array(['1234', u'123', '12345']) <add> a = np.array(['1234', b'123', '12345']) <ide> assert_(a.itemsize == 20) <del> a = np.array([u'123', '1234', u'12345']) <add> a = np.array([b'123', '1234', b'12345']) <ide> assert_(a.itemsize == 20) <del> a = np.array([u'123', '1234', u'1234']) <add> a = np.array([b'123', '1234', b'1234']) <ide> assert_(a.itemsize == 16) <ide> <ide> def test_misaligned_objects_segfault(self): <ide> def test_fortran_order_buffer(self): <ide> import numpy as np <ide> a = np.array([['Hello', 'Foob']], dtype='U5', order='F') <ide> arr = np.ndarray(shape=[1, 2, 5], dtype='U1', buffer=a) <del> arr2 = np.array([[[u'H', u'e', u'l', u'l', u'o'], <del> [u'F', u'o', u'o', u'b', u'']]]) <add> arr2 = np.array([[['H', 'e', 'l', 'l', 'o'], <add> ['F', 'o', 'o', 'b', '']]]) <ide> assert_array_equal(arr, arr2) <ide> <ide> def test_assign_from_sequence_error(self): <ide><path>numpy/core/tests/test_scalarinherit.py <ide> def test_char_radd(self): <ide> np_s = np.string_('abc') <ide> np_u = np.unicode_('abc') <ide> s = b'def' <del> u = u'def' <add> u = 'def' <ide> assert_(np_s.__radd__(np_s) is NotImplemented) <ide> assert_(np_s.__radd__(np_u) is NotImplemented) <ide> assert_(np_s.__radd__(s) is NotImplemented) <ide> def test_char_radd(self): <ide> assert_(np_u.__radd__(s) is NotImplemented) <ide> assert_(np_u.__radd__(u) is NotImplemented) <ide> assert_(s + np_s == b'defabc') <del> assert_(u + np_u == u'defabc') <add> assert_(u + np_u == 'defabc') <ide> <ide> class MyStr(str, np.generic): <ide> # would segfault <ide> def test_char_repeat(self): <ide> np_s = np.string_('abc') <ide> np_u = np.unicode_('abc') <ide> res_s = b'abc' * 5 <del> res_u = u'abc' * 5 <add> res_u = 'abc' * 5 <ide> assert_(np_s * 5 == res_s) <ide> assert_(np_u * 5 == res_u) <ide><path>numpy/core/tests/test_ufunc.py <ide> def test_signature2(self): <ide> <ide> def test_signature3(self): <ide> enabled, num_dims, ixs, flags, sizes = umt.test_signature( <del> 2, 1, u"(i1, i12), (J_1)->(i12, i2)") <add> 2, 1, "(i1, i12), (J_1)->(i12, i2)") <ide> assert_equal(enabled, 1) <ide> assert_equal(num_dims, (2, 1, 2)) <ide> assert_equal(ixs, (0, 1, 2, 1, 3)) <ide><path>numpy/core/tests/test_unicode.py <ide> def buffer_length(arr): <ide> else: <ide> return np.prod(v.shape) * v.itemsize <ide> <add> <ide> # In both cases below we need to make sure that the byte swapped value (as <ide> # UCS4) is still a valid unicode: <ide> # Value that can be represented in UCS2 interpreters <del>ucs2_value = u'\u0900' <add>ucs2_value = '\u0900' <ide> # Value that cannot be represented in UCS2 interpreters (but can in UCS4) <del>ucs4_value = u'\U00100900' <add>ucs4_value = '\U00100900' <ide> <ide> <ide> def test_string_cast(): <ide> def content_check(self, ua, ua_scalar, nbytes): <ide> # Check the length of the data buffer <ide> assert_(buffer_length(ua) == nbytes) <ide> # Small check that data in array element is ok <del> assert_(ua_scalar == u'') <add> assert_(ua_scalar == '') <ide> # Encode to ascii and double check <ide> assert_(ua_scalar.encode('ascii') == b'') <ide> # Check buffer lengths for scalars <ide><path>numpy/lib/tests/test_arraypad.py <ide> def _padwithtens(vector, pad_width, iaxis, kwargs): <ide> <ide> <ide> def test_unicode_mode(): <del> a = np.pad([1], 2, mode=u'constant') <add> a = np.pad([1], 2, mode='constant') <ide> b = np.array([0, 0, 1, 0, 0]) <ide> assert_array_equal(a, b) <ide> <ide><path>numpy/lib/tests/test_format.py <ide> def test_pickle_python2_python3(): <ide> # Python 2 and Python 3 and vice versa <ide> data_dir = os.path.join(os.path.dirname(__file__), 'data') <ide> <del> expected = np.array([None, range, u'\u512a\u826f', <add> expected = np.array([None, range, '\u512a\u826f', <ide> b'\xe4\xb8\x8d\xe8\x89\xaf'], <ide> dtype=object) <ide> <ide> def test_unicode_field_names(tmpdir): <ide> (1, 2) <ide> ], dtype=[ <ide> ('int', int), <del> (u'\N{CJK UNIFIED IDEOGRAPH-6574}\N{CJK UNIFIED IDEOGRAPH-5F62}', int) <add> ('\N{CJK UNIFIED IDEOGRAPH-6574}\N{CJK UNIFIED IDEOGRAPH-5F62}', int) <ide> ]) <ide> fname = os.path.join(tmpdir, "unicode.npy") <ide> with open(fname, 'wb') as f: <ide><path>numpy/lib/tests/test_io.py <ide> def test_unicode_stringstream(self): <ide> s.seek(0) <ide> assert_equal(s.read(), utf8 + '\n') <ide> <del> @pytest.mark.parametrize("fmt", [u"%f", b"%f"]) <add> @pytest.mark.parametrize("fmt", ["%f", b"%f"]) <ide> @pytest.mark.parametrize("iotype", [StringIO, BytesIO]) <ide> def test_unicode_and_bytes_fmt(self, fmt, iotype): <ide> # string type of fmt should not matter, see also gh-4053 <ide> def test_unicode_and_bytes_fmt(self, fmt, iotype): <ide> np.savetxt(s, a, fmt=fmt) <ide> s.seek(0) <ide> if iotype is StringIO: <del> assert_equal(s.read(), u"%f\n" % 1.) <add> assert_equal(s.read(), "%f\n" % 1.) <ide> else: <ide> assert_equal(s.read(), b"%f\n" % 1.) <ide> <ide> def test_comments_unicode(self): <ide> c.write('# comment\n1,2,3,5\n') <ide> c.seek(0) <ide> x = np.loadtxt(c, dtype=int, delimiter=',', <del> comments=u'#') <add> comments='#') <ide> a = np.array([1, 2, 3, 5], int) <ide> assert_array_equal(x, a) <ide> <ide> def test_file_is_closed_on_error(self): <ide> with tempdir() as tmpdir: <ide> fpath = os.path.join(tmpdir, "test.csv") <ide> with open(fpath, "wb") as f: <del> f.write(u'\N{GREEK PI SYMBOL}'.encode('utf8')) <add> f.write('\N{GREEK PI SYMBOL}'.encode()) <ide> <ide> # ResourceWarnings are emitted from a destructor, so won't be <ide> # detected by regular propagation to errors. <ide> def test_latin1(self): <ide> test = np.genfromtxt(TextIO(s), <ide> dtype=None, comments=None, delimiter=',', <ide> encoding='latin1') <del> assert_equal(test[1, 0], u"test1") <del> assert_equal(test[1, 1], u"testNonethe" + latin1.decode('latin1')) <del> assert_equal(test[1, 2], u"test3") <add> assert_equal(test[1, 0], "test1") <add> assert_equal(test[1, 1], "testNonethe" + latin1.decode('latin1')) <add> assert_equal(test[1, 2], "test3") <ide> <ide> with warnings.catch_warnings(record=True) as w: <ide> warnings.filterwarnings('always', '', np.VisibleDeprecationWarning) <ide> def test_utf8_file(self): <ide> <ide> def test_utf8_file_nodtype_unicode(self): <ide> # bytes encoding with non-latin1 -> unicode upcast <del> utf8 = u'\u03d6' <del> latin1 = u'\xf6\xfc\xf6' <add> utf8 = '\u03d6' <add> latin1 = '\xf6\xfc\xf6' <ide> <ide> # skip test if cannot encode utf8 test string with preferred <ide> # encoding. The preferred encoding is assumed to be the default <ide> def test_utf8_file_nodtype_unicode(self): <ide> <ide> with temppath() as path: <ide> with io.open(path, "wt") as f: <del> f.write(u"norm1,norm2,norm3\n") <del> f.write(u"norm1," + latin1 + u",norm3\n") <del> f.write(u"test1,testNonethe" + utf8 + u",test3\n") <add> f.write("norm1,norm2,norm3\n") <add> f.write("norm1," + latin1 + ",norm3\n") <add> f.write("test1,testNonethe" + utf8 + ",test3\n") <ide> with warnings.catch_warnings(record=True) as w: <ide> warnings.filterwarnings('always', '', <ide> np.VisibleDeprecationWarning) <ide> def test_recfromtxt(self): <ide> with temppath(suffix='.txt') as path: <ide> path = Path(path) <ide> with path.open('w') as f: <del> f.write(u'A,B\n0,1\n2,3') <add> f.write('A,B\n0,1\n2,3') <ide> <ide> kwargs = dict(delimiter=",", missing_values="N/A", names=True) <ide> test = np.recfromtxt(path, **kwargs) <ide> def test_recfromcsv(self): <ide> with temppath(suffix='.txt') as path: <ide> path = Path(path) <ide> with path.open('w') as f: <del> f.write(u'A,B\n0,1\n2,3') <add> f.write('A,B\n0,1\n2,3') <ide> <ide> kwargs = dict(missing_values="N/A", names=True, case_sensitive=True) <ide> test = np.recfromcsv(path, dtype=None, **kwargs) <ide><path>numpy/ma/core.py <ide> class MaskError(MAError): <ide> 'S': b'N/A', <ide> 'u': 999999, <ide> 'V': b'???', <del> 'U': u'N/A' <add> 'U': 'N/A' <ide> } <ide> <ide> # Add datetime64 and timedelta64 types <ide><path>numpy/ma/tests/test_core.py <ide> def test_str_repr_legacy(self): <ide> np.set_printoptions(**oldopts) <ide> <ide> def test_0d_unicode(self): <del> u = u'caf\xe9' <add> u = 'caf\xe9' <ide> utype = type(u) <ide> <ide> arr_nomask = np.ma.array(u) <ide> arr_masked = np.ma.array(u, mask=True) <ide> <ide> assert_equal(utype(arr_nomask), u) <del> assert_equal(utype(arr_masked), u'--') <add> assert_equal(utype(arr_masked), '--') <ide> <ide> def test_pickling(self): <ide> # Tests pickling <ide> def test_coercion_float(self): <ide> def test_coercion_unicode(self): <ide> a_u = np.zeros((), 'U10') <ide> a_u[()] = np.ma.masked <del> assert_equal(a_u[()], u'--') <add> assert_equal(a_u[()], '--') <ide> <ide> @pytest.mark.xfail(reason="See gh-9750") <ide> def test_coercion_bytes(self): <ide><path>numpy/ma/tests/test_regression.py <ide> def test_masked_array_repeat(self): <ide> <ide> def test_masked_array_repr_unicode(self): <ide> # Ticket #1256 <del> repr(np.ma.array(u"Unicode")) <add> repr(np.ma.array("Unicode")) <ide> <ide> def test_atleast_2d(self): <ide> # Ticket #1559
21
Python
Python
prevent loss keyerror for non-trainable components
dc06912c764991d2d6718919e5e96cae867a472d
<ide><path>spacy/training/loggers.py <ide> def log_step(info: Optional[Dict[str, Any]]) -> None: <ide> if progress is not None: <ide> progress.update(1) <ide> return <del> try: <del> losses = [ <del> "{0:.2f}".format(float(info["losses"][pipe_name])) <del> for pipe_name in logged_pipes <del> ] <del> except KeyError as e: <del> raise KeyError( <del> Errors.E983.format( <del> dict="scores (losses)", <del> key=str(e), <del> keys=list(info["losses"].keys()), <del> ) <del> ) from None <add> losses = [ <add> "{0:.2f}".format(float(info["losses"][pipe_name])) <add> for pipe_name in logged_pipes if pipe_name in info["losses"] <add> ] <ide> <ide> scores = [] <ide> for col in score_cols: <ide><path>spacy/training/loop.py <ide> def train_while_improving( <ide> and hasattr(proc, "model") <ide> and proc.model not in (True, False, None) <ide> ): <del> proc.model.finish_update(optimizer) <add> proc.finish_update(optimizer) <ide> optimizer.step_schedules() <ide> if not (step % eval_frequency): <ide> if optimizer.averages: <ide> def update_meta( <ide> if metric is not None: <ide> nlp.meta["performance"][metric] = info["other_scores"].get(metric, 0.0) <ide> for pipe_name in nlp.pipe_names: <del> nlp.meta["performance"][f"{pipe_name}_loss"] = info["losses"][pipe_name] <add> if pipe_name in info["losses"]: <add> nlp.meta["performance"][f"{pipe_name}_loss"] = info["losses"][pipe_name] <ide> <ide> <ide> def create_before_to_disk_callback(
2
Javascript
Javascript
fix subtle.importkey jwk okp public key import
51249a11c09c7ec23eda17327f650fa59a72cba5
<ide><path>lib/internal/crypto/ec.js <ide> async function ecImportKey( <ide> keyObject = createECRawKey( <ide> namedCurve, <ide> Buffer.from( <del> isPublic ? keyData.k : keyData.d, <add> isPublic ? keyData.x : keyData.d, <ide> 'base64'), <ide> isPublic); <ide> break; <ide><path>test/parallel/test-webcrypto-x25519-x448.js <ide> assert.rejects( <ide> { <ide> message: /Unsupported named curves for ECDH/ <ide> }); <add> <add>{ <add> // Private JWK import <add> subtle.importKey( <add> 'jwk', <add> { <add> crv: 'X25519', <add> d: '8CE-XY7cvbR-Pu7mILHq8YZ4hLGAA2-RD01he5q2wUA', <add> x: '42IbTo34ZYANub5o42547vB6OxdEd44ztwZewoRch0Q', <add> kty: 'OKP' <add> }, <add> { <add> name: 'ECDH', <add> namedCurve: 'NODE-X25519' <add> }, <add> true, <add> ['deriveBits']).then(common.mustCall()); <add> <add> // Public JWK import <add> subtle.importKey( <add> 'jwk', <add> { <add> crv: 'X25519', <add> x: '42IbTo34ZYANub5o42547vB6OxdEd44ztwZewoRch0Q', <add> kty: 'OKP' <add> }, <add> { <add> name: 'ECDH', <add> namedCurve: 'NODE-X25519' <add> }, <add> true, <add> []).then(common.mustCall()); <add>}
2
Javascript
Javascript
add test cases to ensure methods are walked too
cb320c201d2b86d6af9fe7833ae1a53e3f46a201
<ide><path>test/cases/inner-graph/extend-class2/dep1.js <ide> import { A, B, getC, getD, getE, getF } from "./dep2"; <add>import { A3, B3, C3, D3, E3, F3 } from "./dep3"; <ide> <ide> export class A1 extends A { <ide> render() { <ide> export class F1 extends getF() { <ide> } <ide> } <ide> <del>export class A2 {} <del>export class B2 {} <del>export class C2 {} <del>export class D2 {} <del>export class E2 {} <del>export class F2 {} <add>export class A2 extends A3 {} <add>export class B2 extends B3 {} <add>export class C2 extends C3 {} <add>export class D2 extends D3 {} <add>export class E2 extends E3 {} <add>export class F2 extends F3 {} <ide><path>test/cases/inner-graph/extend-class2/dep3.js <add>export class A3 {} <add>export class B3 {} <add>export class C3 {} <add>export class D3 {} <add>export class E3 {} <add>export class F3 {} <ide><path>test/cases/inner-graph/extend-class2/module.js <ide> import { A1, C1, E1 } from "./dep1"; <ide> <del>export default [new A1(), new C1(), new E1()]; <add>export default [new A1().render(), new C1().render(), new E1().render()];
3
Javascript
Javascript
respect original spacing and newlines better
f69112cb3f080fc92ddb6543cca58282fd5e6c0b
<ide><path>vendor/fbtransform/transforms/react.js <ide> var Syntax = require('esprima-fb').Syntax; <ide> <ide> var catchup = require('jstransform/src/utils').catchup; <add>var catchupWhiteSpace = require('jstransform/src/utils').catchupWhiteSpace; <ide> var append = require('jstransform/src/utils').append; <ide> var move = require('jstransform/src/utils').move; <ide> var getDocblock = require('jstransform/src/utils').getDocblock; <ide> function visitReactTag(traverse, object, path, state) { <ide> if (!isLast) { <ide> append(',', state); <ide> } <del> } else if (JSX_ATTRIBUTE_TRANSFORMS[attr.name.name]) { <del> move(attr.value.range[0], state); <del> append(JSX_ATTRIBUTE_TRANSFORMS[attr.name.name](attr), state); <del> move(attr.value.range[1], state); <del> if (!isLast) { <del> append(',', state); <del> } <del> } else if (attr.value.type === Syntax.Literal) { <del> move(attr.value.range[0], state); <del> renderXJSLiteral(attr.value, isLast, state); <ide> } else { <del> move(attr.value.range[0], state); <del> renderXJSExpressionContainer(traverse, attr.value, isLast, path, state); <add> move(attr.name.range[1], state); <add> // Use catchupWhiteSpace to skip over the '=' in the attribute <add> catchupWhiteSpace(attr.value.range[0], state); <add> if (JSX_ATTRIBUTE_TRANSFORMS[attr.name.name]) { <add> append(JSX_ATTRIBUTE_TRANSFORMS[attr.name.name](attr), state); <add> move(attr.value.range[1], state); <add> if (!isLast) { <add> append(',', state); <add> } <add> } else if (attr.value.type === Syntax.Literal) { <add> renderXJSLiteral(attr.value, isLast, state); <add> } else { <add> renderXJSExpressionContainer(traverse, attr.value, isLast, path, state); <add> } <ide> } <ide> <ide> if (isLast) { <ide><path>vendor/fbtransform/transforms/xjs.js <ide> function trimWithSingleSpace(string) { <ide> function renderXJSLiteral(object, isLast, state, start, end) { <ide> /** Added blank check filtering and triming*/ <ide> var trimmedChildValue = safeTrim(object.value); <add> var hasFinalNewLine = false; <ide> <ide> if (trimmedChildValue) { <ide> // head whitespace <ide> function renderXJSLiteral(object, isLast, state, start, end) { <ide> }); <ide> <ide> var hasInitialNewLine = initialLines[0] !== lines[0]; <del> var hasFinalNewLine = <add> hasFinalNewLine = <ide> initialLines[initialLines.length - 1] !== lines[lines.length - 1]; <ide> <ide> var numLines = lines.length; <ide> function renderXJSLiteral(object, isLast, state, start, end) { <ide> } else { <ide> var preString = ''; <ide> var postString = ''; <del> var leading = ''; <add> var leading = line.match(/^[ \t]*/)[0]; <ide> <ide> if (ii === 0) { <ide> if (hasInitialNewLine) { <ide> preString = ' '; <del> leading = '\n'; <add> leading = '\n' + leading; <ide> } <ide> if (trimmedChildValueWithSpace.substring(0, 1) === ' ') { <ide> // If this is the first line, and the original content starts with <ide> // whitespace, place a single space at the beginning. <ide> preString = ' '; <ide> } <del> } else { <del> leading = line.match(/^[ \t]*/)[0]; <ide> } <ide> if (!lastLine || trimmedChildValueWithSpace.substr( <ide> trimmedChildValueWithSpace.length - 1, 1) === ' ' || <ide> function renderXJSLiteral(object, isLast, state, start, end) { <ide> } <ide> <ide> // tail whitespace <add> if (hasFinalNewLine) { <add> append('\n', state); <add> } <ide> append(object.value.match(/[ \t]*$/)[0], state); <ide> move(object.range[1], state); <ide> }
2
Javascript
Javascript
add strict equalities in src/core/evaluator.js
87038e44cd4f29dc40a8a152120dc44f351fa0ec
<ide><path>src/core/evaluator.js <ide> var PartialEvaluator = (function PartialEvaluatorClosure() { <ide> firstWidth = glyphWidth; <ide> continue; <ide> } <del> if (firstWidth != glyphWidth) { <add> if (firstWidth !== glyphWidth) { <ide> isMonospace = false; <ide> break; <ide> }
1
Javascript
Javascript
avoid memory leak
523ddd7220b837af409fdbd4e0d5ffe10b81f863
<ide><path>test/helpers/createLazyTestEnv.js <add>// this function allows to release memory in fn context <add>// after the function has been called. <add>const createOnceFn = fn => { <add> if (!fn) return null; <add> if (fn.length >= 1) { <add> return done => { <add> fn(done); <add> fn = null; <add> }; <add> } <add> return () => { <add> const r = fn(); <add> fn = null; <add> return r; <add> }; <add>}; <add> <add>// this function allows to release memory in fn context <add>// manually, usually after the suite has been run. <add>const createDisposableFn = fn => { <add> if (!fn) return null; <add> let rfn; <add> if (fn.length >= 1) { <add> rfn = done => { <add> fn(done); <add> }; <add> } else { <add> rfn = () => { <add> return fn(); <add> }; <add> } <add> rfn.dispose = () => { <add> fn = null; <add> }; <add> return rfn; <add>}; <add> <ide> module.exports = (env, globalTimeout = 2000, nameSuffix = "") => { <ide> const suite = env.describe( <ide> nameSuffix ? `exported tests ${nameSuffix}` : "exported tests", <ide> module.exports = (env, globalTimeout = 2000, nameSuffix = "") => { <ide> return numberOfTests; <ide> }, <ide> it(title, fn, timeout = globalTimeout) { <add> fn = createOnceFn(fn); <ide> numberOfTests++; <ide> let spec; <ide> if(fn) { <ide> module.exports = (env, globalTimeout = 2000, nameSuffix = "") => { <ide> spec.result.fullName = spec.getFullName(); <ide> }, <ide> beforeEach(fn, timeout = globalTimeout) { <add> fn = createDisposableFn(fn); <ide> suite.beforeEach({ <ide> fn, <ide> timeout: () => timeout <ide> }); <add> suite.afterAll({ <add> fn: done => { <add> fn.dispose(); <add> done(); <add> }, <add> timeout: () => 1000 <add> }); <ide> }, <ide> afterEach(fn, timeout = globalTimeout) { <add> fn = createDisposableFn(fn); <ide> suite.afterEach({ <ide> fn, <ide> timeout: () => timeout <ide> }); <add> suite.afterAll({ <add> fn: done => { <add> fn.dispose(); <add> done(); <add> }, <add> timeout: () => 1000 <add> }); <ide> } <ide> }; <ide> };
1
Ruby
Ruby
move erb parsing to core_ext
1d39573a9fc2ed7f5914d7b67597d6cb1ed4781b
<ide><path>actionview/lib/action_view/template/handlers/erb.rb <ide> def handles_encoding? <ide> # source location inside the template. <ide> def translate_location(spot, backtrace_location, source) <ide> # Tokenize the source line <del> tokens = tokenize(source.lines[backtrace_location.lineno - 1]) <add> tokens = ERB::Util.tokenize(source.lines[backtrace_location.lineno - 1]) <ide> new_first_column = find_offset(spot[:snippet], tokens, spot[:first_column]) <ide> lineno_delta = spot[:first_lineno] - backtrace_location.lineno <ide> spot[:first_lineno] -= lineno_delta <ide> def valid_encoding(string, encoding) <ide> raise WrongEncodingError.new(string, string.encoding) <ide> end <ide> <del> def tokenize(source) <del> source = StringScanner.new(source.chomp) <del> tokens = [] <del> <del> start_re = /<%(?:={1,2}|-|\#|%)?/ <del> finish_re = /(?:[-=])?%>/ <del> <del> while !source.eos? <del> pos = source.pos <del> source.scan_until(/(?:#{start_re}|#{finish_re})/) <del> len = source.pos - source.matched.bytesize - pos <del> <del> case source.matched <del> when start_re <del> tokens << [:TEXT, source.string[pos, len]] if len > 0 <del> tokens << [:OPEN, source.matched] <del> if source.scan(/(.*?)(?=#{finish_re}|$)/m) <del> tokens << [:CODE, source.matched] <del> tokens << [:CLOSE, source.scan(finish_re)] unless source.eos? <del> else <del> raise NotImplemented <del> end <del> when finish_re <del> tokens << [:CODE, source.string[pos, len]] if len > 0 <del> tokens << [:CLOSE, source.matched] <del> else <del> raise NotImplemented, source.matched <del> end <del> end <del> <del> tokens <del> end <del> <ide> def find_offset(compiled, source_tokens, error_column) <ide> compiled = StringScanner.new(compiled) <ide> <ide><path>activesupport/lib/active_support/core_ext/string/output_safety.rb <ide> def xml_name_escape(name) <ide> starting_char << following_chars <ide> end <ide> module_function :xml_name_escape <add> <add> # Tokenizes a line of ERB. This is really just for error reporting and <add> # nobody should use it. <add> def self.tokenize(source) # :nodoc: <add> require "strscan" <add> source = StringScanner.new(source.chomp) <add> tokens = [] <add> <add> start_re = /<%(?:={1,2}|-|\#|%)?/m <add> finish_re = /(?:[-=])?%>/m <add> <add> while !source.eos? <add> pos = source.pos <add> source.scan_until(/(?:#{start_re}|#{finish_re})/) <add> len = source.pos - source.matched.bytesize - pos <add> <add> case source.matched <add> when start_re <add> tokens << [:TEXT, source.string[pos, len]] if len > 0 <add> tokens << [:OPEN, source.matched] <add> if source.scan(/(.*?)(?=#{finish_re}|\z)/m) <add> tokens << [:CODE, source.matched] unless source.matched.empty? <add> tokens << [:CLOSE, source.scan(finish_re)] unless source.eos? <add> else <add> raise NotImplemented <add> end <add> when finish_re <add> tokens << [:CODE, source.string[pos, len]] if len > 0 <add> tokens << [:CLOSE, source.matched] <add> else <add> raise NotImplemented, source.matched <add> end <add> end <add> <add> tokens <add> end <ide> end <ide> end <ide> <ide><path>activesupport/test/core_ext/erb_util_test.rb <add># frozen_string_literal: true <add> <add>require_relative "../abstract_unit" <add>require "active_support/core_ext/string" <add> <add>module ActiveSupport <add> class ERBUtilTest < ActiveSupport::TestCase <add> def test_template_output <add> first_column = 46 <add> compiled = "Posts: '.freeze; @output_buffer.append=( @post.length ); @output_buffer.safe_append='" <add> source = "Posts: <%= @post.length %>" <add> actual_tokens = tokenize source <add> assert_equal [[:TEXT, "Posts: "], [:OPEN, "<%="], [:CODE, " @post.length "], [:CLOSE, "%>"]], actual_tokens <add> end <add> <add> def test_multi_tag <add> source = "Posts: <%= @post.length %> <% puts 'hi' %>" <add> actual_tokens = tokenize source <add> assert_equal [[:TEXT, "Posts: "], <add> [:OPEN, "<%="], <add> [:CODE, " @post.length "], <add> [:CLOSE, "%>"], <add> [:TEXT, " "], <add> [:OPEN, "<%"], <add> [:CODE, " puts 'hi' "], <add> [:CLOSE, "%>"], <add> ], actual_tokens <add> end <add> <add> def test_multi_line <add> source = "Posts: <%= @post.length %> <% puts 'hi' %>\nfoo <%" <add> actual_tokens = tokenize source <add> assert_equal [[:TEXT, "Posts: "], <add> [:OPEN, "<%="], <add> [:CODE, " @post.length "], <add> [:CLOSE, "%>"], <add> [:TEXT, " "], <add> [:OPEN, "<%"], <add> [:CODE, " puts 'hi' "], <add> [:CLOSE, "%>"], <add> [:TEXT, "\nfoo "], <add> [:OPEN, "<%"], <add> ], actual_tokens <add> end <add> <add> def test_starts_with_newline <add> source = "\nPosts: <%= @post.length %> <% puts 'hi' %>\nfoo <%" <add> actual_tokens = tokenize source <add> assert_equal [[:TEXT, "\nPosts: "], <add> [:OPEN, "<%="], <add> [:CODE, " @post.length "], <add> [:CLOSE, "%>"], <add> [:TEXT, " "], <add> [:OPEN, "<%"], <add> [:CODE, " puts 'hi' "], <add> [:CLOSE, "%>"], <add> [:TEXT, "\nfoo "], <add> [:OPEN, "<%"], <add> ], actual_tokens <add> end <add> <add> def test_newline_inside_tag <add> source = "Posts: <%= \n @post.length %> <% puts 'hi' %>\nfoo <%" <add> actual_tokens = tokenize source <add> assert_equal [[:TEXT, "Posts: "], <add> [:OPEN, "<%="], <add> [:CODE, " \n @post.length "], <add> [:CLOSE, "%>"], <add> [:TEXT, " "], <add> [:OPEN, "<%"], <add> [:CODE, " puts 'hi' "], <add> [:CLOSE, "%>"], <add> [:TEXT, "\nfoo "], <add> [:OPEN, "<%"], <add> ], actual_tokens <add> end <add> <add> def test_start <add> source = "<%= @post.length %> <% puts 'hi' %>" <add> actual_tokens = tokenize source <add> assert_equal [[:OPEN, "<%="], <add> [:CODE, " @post.length "], <add> [:CLOSE, "%>"], <add> [:TEXT, " "], <add> [:OPEN, "<%"], <add> [:CODE, " puts 'hi' "], <add> [:CLOSE, "%>"], <add> ], actual_tokens <add> end <add> <add> def test_mid <add> source = "@post.length %> <% puts 'hi' %>" <add> actual_tokens = tokenize source <add> assert_equal [[:CODE, "@post.length "], <add> [:CLOSE, "%>"], <add> [:TEXT, " "], <add> [:OPEN, "<%"], <add> [:CODE, " puts 'hi' "], <add> [:CLOSE, "%>"], <add> ], actual_tokens <add> end <add> <add> def test_mid_start <add> source = "%> <% puts 'hi' %>" <add> actual_tokens = tokenize source <add> assert_equal [[:CLOSE, "%>"], <add> [:TEXT, " "], <add> [:OPEN, "<%"], <add> [:CODE, " puts 'hi' "], <add> [:CLOSE, "%>"], <add> ], actual_tokens <add> end <add> <add> def test_no_end <add> source = "%> <% puts 'hi'" <add> actual_tokens = tokenize source <add> assert_equal [[:CLOSE, "%>"], <add> [:TEXT, " "], <add> [:OPEN, "<%"], <add> [:CODE, " puts 'hi'"], <add> ], actual_tokens <add> <add> source = "<% puts 'hi'" <add> actual_tokens = tokenize source <add> assert_equal [[:OPEN, "<%"], <add> [:CODE, " puts 'hi'"], <add> ], actual_tokens <add> end <add> <add> def tokenize(source) <add> ERB::Util.tokenize source <add> end <add> end <add>end
3
Ruby
Ruby
add skylake to linux hardware list
573aeff11513a679577994cce84d31011090902b
<ide><path>Library/Homebrew/extend/os/linux/hardware/cpu.rb <ide> def family <ide> :haswell <ide> when 0x3d, 0x47, 0x4f, 0x56 <ide> :broadwell <add> when 0x5e <add> :skylake <ide> when 0x8e <ide> :kabylake <ide> else
1
Python
Python
fix doctest for full_like
11f051a37bed48c341849e79cac1863a03626f73
<ide><path>numpy/core/numeric.py <ide> def full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None): <ide> <ide> >>> y = np.arange(6, dtype=np.double) <ide> >>> np.full_like(y, 0.1) <del> array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) <add> array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1]) <ide> <ide> """ <ide> res = empty_like(a, dtype=dtype, order=order, subok=subok, shape=shape)
1
Javascript
Javascript
use "clean" objects
298a40e04ee496dbd6b2324a20d9ff745fef74cb
<ide><path>lib/module.js <ide> function Module(id, parent) { <ide> } <ide> module.exports = Module; <ide> <del>Module._cache = {}; <del>Module._pathCache = {}; <del>Module._extensions = {}; <add>Module._cache = Object.create(null); <add>Module._pathCache = Object.create(null); <add>Module._extensions = Object.create(null); <ide> var modulePaths = []; <ide> Module.globalPaths = []; <ide>
1
Ruby
Ruby
fix where_clause#except with specific where value
19dc69cb07572f8b17ae15c8bc0b5a29bc8a281f
<ide><path>activerecord/lib/active_record/relation/where_clause.rb <ide> def except_predicates_and_binds(columns) <ide> (binds_index...(binds_index + binds_contains)).each do |i| <ide> except_binds[i] = true <ide> end <del> <del> binds_index += binds_contains <ide> end <ide> <add> binds_index += binds_contains if binds_contains <add> <ide> except <ide> end <ide> <ide><path>activerecord/test/cases/relations_test.rb <ide> def test_unscope_with_subquery <ide> assert_equal p2.first.comments, comments <ide> end <ide> <add> def test_unscope_specific_where_value <add> posts = Post.where(title: "Welcome to the weblog", body: "Such a lovely day") <add> <add> assert_equal 1, posts.count <add> assert_equal 1, posts.unscope(where: :title).count <add> assert_equal 1, posts.unscope(where: :body).count <add> end <add> <ide> def test_unscope_removes_binds <ide> left = Post.where(id: Arel::Nodes::BindParam.new) <ide> column = Post.columns_hash["id"]
2
Text
Text
clarify sentence in event loop doc
88ed3d260e3f111a5a100a377af55317388fcea0
<ide><path>doc/topics/the-event-loop-timers-and-nexttick.md <ide> order of operations. <ide> │ ┌──────────┴────────────┐ │ incoming: │ <ide> │ │ poll │<─────┤ connections, │ <ide> │ └──────────┬────────────┘ │ data, etc. │ <del> │ ┌──────────┴────────────┐ └───────────────┘ <add> │ ┌──────────┴────────────┐ └───────────────┘ <ide> │ │ check │ <ide> │ └──────────┬────────────┘ <ide> │ ┌──────────┴────────────┐ <ide> └──┤ close callbacks │ <del> └───────────────────────┘ <add> └───────────────────────┘ <ide> <ide> *note: each box will be referred to as a "phase" of the event loop.* <ide> <ide> actually uses - are those above._ <ide> <ide> * **timers**: this phase executes callbacks scheduled by `setTimeout()` <ide> and `setInterval()`. <del>* **I/O callbacks**: most types of callback except timers, `setImmediate()`, close <del>* **idle, prepare**: only used internally <del>* **poll**: retrieve new I/O events; node will block here when appropriate <del>* **check**: `setImmediate()` callbacks are invoked here <del>* **close callbacks**: e.g socket.on('close', ...) <add>* **I/O callbacks**: executes almost all callbacks with the exception of <add> close callbacks, the ones scheduled by timers, and `setImmediate()`. <add>* **idle, prepare**: only used internally. <add>* **poll**: retrieve new I/O events; node will block here when appropriate. <add>* **check**: `setImmediate()` callbacks are invoked here. <add>* **close callbacks**: e.g. `socket.on('close', ...)`. <ide> <ide> Between each run of the event loop, Node.js checks if it is waiting for <ide> any asynchronous I/O or timers and shuts down cleanly if there are not
1
Go
Go
factorize sleeping containers
777ee34b075292e5aee16c4088444508899f8f35
<ide><path>integration-cli/docker_api_containers_test.go <ide> import ( <ide> "github.com/go-check/check" <ide> ) <ide> <del>func init() { <del> if daemonPlatform == "windows" { <del> sleepCmd = "sleep" <del> } <del>} <del> <ide> func (s *DockerSuite) TestContainerApiGetAll(c *check.C) { <ide> startCount, err := getContainerCount() <ide> c.Assert(err, checker.IsNil, check.Commentf("Cannot query container count")) <ide> func (s *DockerSuite) TestContainerApiPsOmitFields(c *check.C) { <ide> testRequires(c, DaemonIsLinux) <ide> name := "pstest" <ide> port := 80 <del> dockerCmd(c, "run", "-d", "--name", name, "--expose", strconv.Itoa(port), "busybox", sleepCmd, "60") <add> runSleepingContainer(c, "--name", name, "--expose", strconv.Itoa(port)) <ide> <ide> status, body, err := sockRequest("GET", "/containers/json?all=1", nil) <ide> c.Assert(err, checker.IsNil) <ide> func (s *DockerSuite) TestContainerApiRename(c *check.C) { <ide> <ide> func (s *DockerSuite) TestContainerApiKill(c *check.C) { <ide> name := "test-api-kill" <del> dockerCmd(c, "run", "-di", "--name", name, "busybox", sleepCmd, "60") <add> runSleepingContainer(c, "-i", "--name", name) <ide> <ide> status, _, err := sockRequest("POST", "/containers/"+name+"/kill", nil) <ide> c.Assert(err, checker.IsNil) <ide> func (s *DockerSuite) TestContainerApiStart(c *check.C) { <ide> name := "testing-start" <ide> config := map[string]interface{}{ <ide> "Image": "busybox", <del> "Cmd": []string{"/bin/sh", "-c", sleepCmd, "60"}, <add> "Cmd": append([]string{"/bin/sh", "-c"}, defaultSleepCommand...), <ide> "OpenStdin": true, <ide> } <ide> <ide> func (s *DockerSuite) TestContainerApiStart(c *check.C) { <ide> <ide> func (s *DockerSuite) TestContainerApiStop(c *check.C) { <ide> name := "test-api-stop" <del> dockerCmd(c, "run", "-di", "--name", name, "busybox", sleepCmd, "60") <add> runSleepingContainer(c, "-i", "--name", name) <ide> <ide> status, _, err := sockRequest("POST", "/containers/"+name+"/stop?t=30", nil) <ide> c.Assert(err, checker.IsNil) <ide> func (s *DockerSuite) TestContainerApiStop(c *check.C) { <ide> <ide> func (s *DockerSuite) TestContainerApiWait(c *check.C) { <ide> name := "test-api-wait" <add> <add> sleepCmd := "/bin/sleep" <add> if daemonPlatform == "windows" { <add> sleepCmd = "sleep" <add> } <ide> dockerCmd(c, "run", "--name", name, "busybox", sleepCmd, "5") <ide> <ide> status, body, err := sockRequest("POST", "/containers/"+name+"/wait", nil) <ide> func (s *DockerSuite) TestContainerApiCopyContainerNotFound(c *check.C) { <ide> } <ide> <ide> func (s *DockerSuite) TestContainerApiDelete(c *check.C) { <del> out, _ := dockerCmd(c, "run", "-d", "busybox", sleepCmd, "60") <add> out, _ := runSleepingContainer(c) <ide> <ide> id := strings.TrimSpace(out) <ide> c.Assert(waitRun(id), checker.IsNil) <ide> func (s *DockerSuite) TestContainerApiDeleteNotExist(c *check.C) { <ide> } <ide> <ide> func (s *DockerSuite) TestContainerApiDeleteForce(c *check.C) { <del> out, _ := dockerCmd(c, "run", "-d", "busybox", sleepCmd, "60") <add> out, _ := runSleepingContainer(c) <ide> <ide> id := strings.TrimSpace(out) <ide> c.Assert(waitRun(id), checker.IsNil) <ide> func (s *DockerSuite) TestContainerApiDeleteRemoveLinks(c *check.C) { <ide> } <ide> <ide> func (s *DockerSuite) TestContainerApiDeleteConflict(c *check.C) { <del> out, _ := dockerCmd(c, "run", "-d", "busybox", sleepCmd, "60") <add> out, _ := runSleepingContainer(c) <ide> <ide> id := strings.TrimSpace(out) <ide> c.Assert(waitRun(id), checker.IsNil) <ide> func (s *DockerSuite) TestContainerApiDeleteRemoveVolume(c *check.C) { <ide> vol = `c:\testvolume` <ide> } <ide> <del> out, _ := dockerCmd(c, "run", "-d", "-v", vol, "busybox", sleepCmd, "60") <add> out, _ := runSleepingContainer(c, "-v", vol) <ide> <ide> id := strings.TrimSpace(out) <ide> c.Assert(waitRun(id), checker.IsNil) <ide> func (s *DockerSuite) TestContainerApiChunkedEncoding(c *check.C) { <ide> } <ide> <ide> func (s *DockerSuite) TestContainerApiPostContainerStop(c *check.C) { <del> out, _ := dockerCmd(c, "run", "-d", "busybox", sleepCmd, "60") <add> out, _ := runSleepingContainer(c) <ide> <ide> containerID := strings.TrimSpace(out) <ide> c.Assert(waitRun(containerID), checker.IsNil) <ide> func (s *DockerSuite) TestPostContainersStartWithoutLinksInHostConfig(c *check.C <ide> // An alternate test could be written to validate the negative testing aspect of this <ide> testRequires(c, DaemonIsLinux) <ide> name := "test-host-config-links" <del> dockerCmd(c, "create", "--name", name, "busybox", sleepCmd, "60") <add> dockerCmd(c, append([]string{"create", "--name", name, "busybox"}, defaultSleepCommand...)...) <ide> <ide> hc, err := inspectFieldJSON(name, "HostConfig") <ide> c.Assert(err, checker.IsNil) <ide><path>integration-cli/docker_cli_ps_test.go <ide> import ( <ide> "github.com/go-check/check" <ide> ) <ide> <del>func init() { <del> if daemonPlatform == "windows" { <del> sleepCmd = "sleep" <del> } <del>} <del> <ide> func (s *DockerSuite) TestPsListContainersBase(c *check.C) { <ide> // Problematic on Windows as busybox doesn't support top <ide> testRequires(c, DaemonIsLinux) <ide> func (s *DockerSuite) TestPsListContainersFilterID(c *check.C) { <ide> firstID := strings.TrimSpace(out) <ide> <ide> // start another container <del> dockerCmd(c, "run", "-d", "busybox", sleepCmd, "60") <add> runSleepingContainer(c) <ide> <ide> // filter containers by id <ide> out, _ = dockerCmd(c, "ps", "-a", "-q", "--filter=id="+firstID) <ide> func (s *DockerSuite) TestPsListContainersFilterName(c *check.C) { <ide> firstID := strings.TrimSpace(out) <ide> <ide> // start another container <del> dockerCmd(c, "run", "-d", "--name=b_name_to_match", "busybox", sleepCmd, "60") <add> runSleepingContainer(c, "--name=b_name_to_match") <ide> <ide> // filter containers by name <ide> out, _ = dockerCmd(c, "ps", "-a", "-q", "--filter=name=a_name_to_match") <ide> func (s *DockerSuite) TestPsListContainersFilterLabel(c *check.C) { <ide> func (s *DockerSuite) TestPsListContainersFilterExited(c *check.C) { <ide> // TODO Windows CI: Enable for TP5. Fails on TP4 <ide> testRequires(c, DaemonIsLinux) <del> dockerCmd(c, "run", "-d", "--name", "sleep", "busybox", sleepCmd, "60") <add> runSleepingContainer(c, "--name=sleep") <ide> <ide> dockerCmd(c, "run", "--name", "zero1", "busybox", "true") <ide> firstZero, err := getIDByName("zero1") <ide> func (s *DockerSuite) TestPsRightTagName(c *check.C) { <ide> dockerCmd(c, "tag", "busybox", tag) <ide> <ide> var id1 string <del> out, _ := dockerCmd(c, "run", "-d", "busybox", sleepCmd, "60") <add> out, _ := runSleepingContainer(c) <ide> id1 = strings.TrimSpace(string(out)) <ide> <ide> var id2 string <del> out, _ = dockerCmd(c, "run", "-d", tag, sleepCmd, "60") <add> out, _ = runSleepingContainerInImage(c, tag) <ide> id2 = strings.TrimSpace(string(out)) <ide> <ide> var imageID string <ide> out, _ = dockerCmd(c, "inspect", "-f", "{{.Id}}", "busybox") <ide> imageID = strings.TrimSpace(string(out)) <ide> <ide> var id3 string <del> out, _ = dockerCmd(c, "run", "-d", imageID, sleepCmd, "60") <add> out, _ = runSleepingContainerInImage(c, imageID) <ide> id3 = strings.TrimSpace(string(out)) <ide> <ide> out, _ = dockerCmd(c, "ps", "--no-trunc") <ide> func (s *DockerSuite) TestPsRightTagName(c *check.C) { <ide> func (s *DockerSuite) TestPsLinkedWithNoTrunc(c *check.C) { <ide> // Problematic on Windows as it doesn't support links as of Jan 2016 <ide> testRequires(c, DaemonIsLinux) <del> dockerCmd(c, "run", "--name=first", "-d", "busybox", sleepCmd, "60") <del> dockerCmd(c, "run", "--name=second", "--link=first:first", "-d", "busybox", sleepCmd, "60") <add> runSleepingContainer(c, "--name=first") <add> runSleepingContainer(c, "--name=second", "--link=first:first") <ide> <ide> out, _ := dockerCmd(c, "ps", "--no-trunc") <ide> lines := strings.Split(strings.TrimSpace(string(out)), "\n") <ide> func (s *DockerSuite) TestPsFormatHeaders(c *check.C) { <ide> c.Assert(out, checker.Equals, "CONTAINER ID\n", check.Commentf(`Expected 'CONTAINER ID\n', got %v`, out)) <ide> <ide> // verify that "docker ps" with a container still prints the header row also <del> dockerCmd(c, "run", "--name=test", "-d", "busybox", sleepCmd, "60") <add> runSleepingContainer(c, "--name=test") <ide> out, _ = dockerCmd(c, "ps", "--format", "table {{.Names}}") <ide> c.Assert(out, checker.Equals, "NAMES\ntest\n", check.Commentf(`Expected 'NAMES\ntest\n', got %v`, out)) <ide> } <ide> func (s *DockerSuite) TestPsDefaultFormatAndQuiet(c *check.C) { <ide> err = ioutil.WriteFile(filepath.Join(d, "config.json"), []byte(config), 0644) <ide> c.Assert(err, checker.IsNil) <ide> <del> out, _ := dockerCmd(c, "run", "--name=test", "-d", "busybox", sleepCmd, "60") <add> out, _ := runSleepingContainer(c, "--name=test") <ide> id := strings.TrimSpace(out) <ide> <ide> out, _ = dockerCmd(c, "--config", d, "ps", "-q") <ide> func (s *DockerSuite) TestPsImageIDAfterUpdate(c *check.C) { <ide> originalImageID, err := getIDByName(originalImageName) <ide> c.Assert(err, checker.IsNil) <ide> <del> runCmd = exec.Command(dockerBinary, "run", "-d", originalImageName, sleepCmd, "60") <add> runCmd = exec.Command(dockerBinary, append([]string{"run", "-d", originalImageName}, defaultSleepCommand...)...) <ide> out, _, err = runCommandWithOutput(runCmd) <ide> c.Assert(err, checker.IsNil) <ide> containerID := strings.TrimSpace(out) <ide><path>integration-cli/docker_cli_rename_test.go <ide> import ( <ide> "github.com/go-check/check" <ide> ) <ide> <del>var sleepCmd = "/bin/sleep" <del> <del>func init() { <del> if daemonPlatform == "windows" { <del> sleepCmd = "sleep" <del> } <del>} <del> <ide> func (s *DockerSuite) TestRenameStoppedContainer(c *check.C) { <ide> out, _ := dockerCmd(c, "run", "--name", "first_name", "-d", "busybox", "sh") <ide> <ide> func (s *DockerSuite) TestRenameRunningContainer(c *check.C) { <ide> } <ide> <ide> func (s *DockerSuite) TestRenameRunningContainerAndReuse(c *check.C) { <del> out, _ := dockerCmd(c, "run", "--name", "first_name", "-d", "busybox", sleepCmd, "60") <add> out, _ := runSleepingContainer(c, "--name", "first_name") <ide> c.Assert(waitRun("first_name"), check.IsNil) <ide> <ide> newName := "new_name" <ide> func (s *DockerSuite) TestRenameRunningContainerAndReuse(c *check.C) { <ide> c.Assert(err, checker.IsNil, check.Commentf("Failed to rename container %s", name)) <ide> c.Assert(name, checker.Equals, "/"+newName, check.Commentf("Failed to rename container")) <ide> <del> out, _ = dockerCmd(c, "run", "--name", "first_name", "-d", "busybox", sleepCmd, "60") <add> out, _ = runSleepingContainer(c, "--name", "first_name") <ide> c.Assert(waitRun("first_name"), check.IsNil) <ide> newContainerID := strings.TrimSpace(out) <ide> name, err = inspectField(newContainerID, "Name") <ide> func (s *DockerSuite) TestRenameCheckNames(c *check.C) { <ide> } <ide> <ide> func (s *DockerSuite) TestRenameInvalidName(c *check.C) { <del> dockerCmd(c, "run", "--name", "myname", "-d", "busybox", sleepCmd, "60") <add> runSleepingContainer(c, "--name", "myname") <ide> <ide> out, _, err := dockerCmdWithError("rename", "myname", "new:invalid") <ide> c.Assert(err, checker.NotNil, check.Commentf("Renaming container to invalid name should have failed: %s", out)) <ide><path>integration-cli/docker_cli_rmi_test.go <ide> import ( <ide> "github.com/go-check/check" <ide> ) <ide> <del>func init() { <del> if daemonPlatform == "windows" { <del> sleepCmd = "sleep" <del> } <del>} <del> <ide> func (s *DockerSuite) TestRmiWithContainerFails(c *check.C) { <ide> errSubstr := "is using it" <ide> <ide> func (s *DockerSuite) TestRmiImgIDMultipleTag(c *check.C) { <ide> c.Assert(err, checker.IsNil) <ide> <ide> // run a container with the image <del> out, _ = dockerCmd(c, "run", "-d", "busybox-one", sleepCmd, "60") <add> out, _ = runSleepingContainerInImage(c, "busybox-one") <ide> <ide> containerID = strings.TrimSpace(out) <ide> <ide> func (s *DockerSuite) TestRmiImageIDForceWithRunningContainersAndMultipleTags(c <ide> <ide> newTag := "newtag" <ide> dockerCmd(c, "tag", imgID, newTag) <del> dockerCmd(c, "run", "-d", imgID, sleepCmd, "60") <add> runSleepingContainerInImage(c, imgID) <ide> <ide> out, _, err := dockerCmdWithError("rmi", "-f", imgID) <ide> // rmi -f should not delete image with running containers <ide> func (s *DockerSuite) TestRmiContainerImageNotFound(c *check.C) { <ide> } <ide> <ide> // Create a long-running container. <del> dockerCmd(c, "run", "-d", imageNames[0], sleepCmd, "60") <add> runSleepingContainerInImage(c, imageNames[0]) <ide> <ide> // Create a stopped container, and then force remove its image. <ide> dockerCmd(c, "run", imageNames[1], "true") <ide><path>integration-cli/docker_utils.go <ide> func getInspectBody(c *check.C, version, id string) []byte { <ide> c.Assert(status, check.Equals, http.StatusOK) <ide> return body <ide> } <add> <add>// Run a long running idle task in a background container using the <add>// system-specific default image and command. <add>func runSleepingContainer(c *check.C, extraArgs ...string) (string, int) { <add> return runSleepingContainerInImage(c, defaultSleepImage, extraArgs...) <add>} <add> <add>// Run a long running idle task in a background container using the specified <add>// image and the system-specific command. <add>func runSleepingContainerInImage(c *check.C, image string, extraArgs ...string) (string, int) { <add> args := []string{"run", "-d"} <add> args = append(args, extraArgs...) <add> args = append(args, image) <add> args = append(args, defaultSleepCommand...) <add> return dockerCmd(c, args...) <add>} <ide><path>integration-cli/test_vars_unix.go <ide> const ( <ide> isUnixCli = true <ide> <ide> expectedFileChmod = "-rw-r--r--" <add> <add> // On Unix variants, the busybox image comes with the `top` command which <add> // runs indefinitely while still being interruptible by a signal. <add> defaultSleepImage = "busybox" <ide> ) <add> <add>var defaultSleepCommand = []string{"top"} <ide><path>integration-cli/test_vars_windows.go <ide> const ( <ide> <ide> // this is the expected file permission set on windows: gh#11395 <ide> expectedFileChmod = "-rwxr-xr-x" <add> <add> // On Windows, the busybox image doesn't have the `top` command, so we rely <add> // on `sleep` with a high duration. <add> defaultSleepImage = "busybox" <ide> ) <add> <add>var defaultSleepCommand = []string{"sleep", "60"}
7
Ruby
Ruby
fix impractical i18n lookup in nested fields_for
c2b6f63bbe2740fd63a36eeefe17d51813a17324
<ide><path>actionpack/lib/action_view/helpers/form_helper.rb <ide> def to_label_tag(text = nil, options = {}, &block) <ide> label_tag(name_and_id["id"], options, &block) <ide> else <ide> content = if text.blank? <add> object_name.gsub!(/\[(.*)_attributes\]\[\d\]/, '.\1') <ide> method_and_value = tag_value.present? ? "#{method_name}.#{tag_value}" : method_name <del> I18n.t("helpers.label.#{object_name}.#{method_and_value}", :default => "").presence <add> <add> if object.respond_to?(:to_model) <add> key = object.class.model_name.i18n_key <add> i18n_default = ["#{key}.#{method_and_value}".to_sym, ""] <add> end <add> <add> i18n_default ||= "" <add> I18n.t("#{object_name}.#{method_and_value}", :default => i18n_default, :scope => "helpers.label").presence <ide> else <ide> text.to_s <ide> end <ide><path>actionpack/test/template/form_helper_test.rb <ide> def setup <ide> :body => "Write entire text here", <ide> :color => { <ide> :red => "Rojo" <add> }, <add> :comments => { <add> :body => "Write body here" <ide> } <add> }, <add> :tag => { <add> :value => "Tag" <ide> } <ide> } <ide> } <ide> def @post.to_param; '123'; end <ide> @post.secret = 1 <ide> @post.written_on = Date.new(2004, 6, 15) <ide> <add> @post.comments = [] <add> @post.comments << @comment <add> <add> @post.tags = [] <add> @post.tags << Tag.new <add> <ide> @blog_post = Blog::Post.new("And his name will be forty and four.", 44) <ide> end <ide> <ide> def test_label_with_locales_and_value <ide> I18n.locale = old_locale <ide> end <ide> <add> def test_label_with_locales_and_nested_attributes <add> old_locale, I18n.locale = I18n.locale, :label <add> form_for(@post, :html => { :id => 'create-post' }) do |f| <add> f.fields_for(:comments) do |cf| <add> concat cf.label(:body) <add> end <add> end <add> <add> expected = whole_form("/posts/123", "create-post" , "edit_post", :method => "put") do <add> "<label for=\"post_comments_attributes_0_body\">Write body here</label>" <add> end <add> <add> assert_dom_equal expected, output_buffer <add> ensure <add> I18n.locale = old_locale <add> end <add> <add> def test_label_with_locales_fallback_and_nested_attributes <add> old_locale, I18n.locale = I18n.locale, :label <add> form_for(@post, :html => { :id => 'create-post' }) do |f| <add> f.fields_for(:tags) do |cf| <add> concat cf.label(:value) <add> end <add> end <add> <add> expected = whole_form("/posts/123", "create-post" , "edit_post", :method => "put") do <add> "<label for=\"post_tags_attributes_0_value\">Tag</label>" <add> end <add> <add> assert_dom_equal expected, output_buffer <add> ensure <add> I18n.locale = old_locale <add> end <add> <ide> def test_label_with_for_attribute_as_symbol <ide> assert_dom_equal('<label for="my_for">Title</label>', label(:post, :title, nil, :for => "my_for")) <ide> end
2
Go
Go
cleanup some statements from exec driver work
9e3da87a3a6fea21194ceb9dbd30a39d043a48a4
<ide><path>execdriver/lxc/init.go <ide> func changeUser(args *execdriver.InitArgs) error { <ide> } <ide> <ide> func setupCapabilities(args *execdriver.InitArgs) error { <del> <ide> if args.Privileged { <ide> return nil <ide> } <ide><path>runtime.go <ide> import ( <ide> "github.com/dotcloud/docker/dockerversion" <ide> "github.com/dotcloud/docker/engine" <ide> "github.com/dotcloud/docker/execdriver" <del> "github.com/dotcloud/docker/execdriver/chroot" <ide> "github.com/dotcloud/docker/execdriver/lxc" <ide> "github.com/dotcloud/docker/graphdriver" <ide> "github.com/dotcloud/docker/graphdriver/aufs" <ide> func NewRuntimeFromDirectory(config *DaemonConfig, eng *engine.Engine) (*Runtime <ide> <ide> sysInfo := sysinfo.New(false) <ide> <del> /* <del> temporarilly disabled. <del> */ <del> if false { <del> var ed execdriver.Driver <del> if driver := os.Getenv("EXEC_DRIVER"); driver == "lxc" { <del> ed, err = lxc.NewDriver(config.Root, sysInfo.AppArmor) <del> } else { <del> ed, err = chroot.NewDriver() <del> } <del> if ed != nil { <del> } <del> } <ide> ed, err := lxc.NewDriver(config.Root, sysInfo.AppArmor) <ide> if err != nil { <ide> return nil, err <ide><path>sysinit/sysinit.go <ide> func setupEnv(args *execdriver.InitArgs) { <ide> <ide> func executeProgram(args *execdriver.InitArgs) error { <ide> setupEnv(args) <add> <ide> dockerInitFct, err := execdriver.GetInitFunc(args.Driver) <ide> if err != nil { <ide> panic(err) <ide> } <ide> return dockerInitFct(args) <del> <del> if args.Driver == "lxc" { <del> // Will never reach <del> } else if args.Driver == "chroot" { <del> } <del> <del> return nil <ide> } <ide> <ide> // Sys Init code
3
PHP
PHP
update exceptionhandler.php
3bfc5703728191b0fd6a6c07420ca881aef706a7
<ide><path>src/Illuminate/Contracts/Debug/ExceptionHandler.php <ide> public function render($request, Throwable $e); <ide> * @param \Symfony\Component\Console\Output\OutputInterface $output <ide> * @param \Throwable $e <ide> * @return void <add> * <add> * @internal This method is not meant to be used or overwritten outside the framework. <ide> */ <ide> public function renderForConsole($output, Throwable $e); <ide> }
1
Mixed
Text
change http to https in docs
8e19d0aa8b30cef025c248c8e6253cc20fa133d6
<ide><path>CONTRIBUTING.md <ide> # Have a question? <ide> <del>Please ask questions on [Stack Overflow](http://stackoverflow.com/questions/tagged/immutable.js) instead of opening a Github Issue. There are more people on Stack Overflow who <add>Please ask questions on [Stack Overflow](https://stackoverflow.com/questions/tagged/immutable.js) instead of opening a Github Issue. There are more people on Stack Overflow who <ide> can answer questions, and good answers can be searchable and canonical. <ide> <ide> # Issues <ide><path>ISSUE_TEMPLATE.md <ide> <!-- <ide> Have a general question? <ide> <del>First check out the Docs: http://facebook.github.io/immutable-js/docs/ <del>Or ask on Stack Overflow: http://stackoverflow.com/questions/tagged/immutable.js?sort=votes <add>First check out the Docs: https://facebook.github.io/immutable-js/docs/ <add>Or ask on Stack Overflow: https://stackoverflow.com/questions/tagged/immutable.js?sort=votes <ide> Stack Overflow gets more attention than this issue list, and is much easier to search. <ide> <ide> Found a bug? <ide><path>contrib/cursor/README.md <ide> aware of changes to the entire data structure: an `onChange` function which is <ide> called whenever a cursor or sub-cursor calls `update`. <ide> <ide> This is particularly useful when used in conjuction with component-based UI <del>libraries like [React](http://facebook.github.io/react/) or to simulate <add>libraries like [React](https://facebook.github.io/react/) or to simulate <ide> "state" throughout an application while maintaining a single flow of logic. <ide> <ide> <ide><path>pages/src/docs/src/DocHeader.js <ide> var DocHeader = React.createClass({ <ide> </SVGSet> <ide> </a> <ide> <a href="./" target="_self">Docs</a> <del> <a href="http://stackoverflow.com/questions/tagged/immutable.js?sort=votes">Questions</a> <add> <a href="https://stackoverflow.com/questions/tagged/immutable.js?sort=votes">Questions</a> <ide> <a href="https://github.com/facebook/immutable-js/">Github</a> <ide> </div> <ide> </div> <ide><path>pages/src/src/Header.js <ide> var Header = React.createClass({ <ide> </SVGSet> <ide> </a> <ide> <a href="docs/" target="_self">Docs</a> <del> <a href="http://stackoverflow.com/questions/tagged/immutable.js?sort=votes">Questions</a> <add> <a href="https://stackoverflow.com/questions/tagged/immutable.js?sort=votes">Questions</a> <ide> <a href="https://github.com/facebook/immutable-js/">GitHub</a> <ide> </div> <ide> </div> <ide> var Header = React.createClass({ <ide> <div className="filler"> <ide> <div className="miniHeaderContents"> <ide> <a href="docs/" target="_self">Docs</a> <del> <a href="http://stackoverflow.com/questions/tagged/immutable.js?sort=votes">Questions</a> <add> <a href="https://stackoverflow.com/questions/tagged/immutable.js?sort=votes">Questions</a> <ide> <a href="https://github.com/facebook/immutable-js/">GitHub</a> <ide> </div> <ide> </div> <ide><path>pages/third_party/typescript/README.md <ide> <ide> # TypeScript <ide> <del>[TypeScript](http://www.typescriptlang.org/) is a language for application-scale JavaScript. TypeScript adds optional types, classes, and modules to JavaScript. TypeScript supports tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to readable, standards-based JavaScript. Try it out at the [playground](http://www.typescriptlang.org/Playground), and stay up to date via [our blog](http://blogs.msdn.com/typescript) and [twitter account](https://twitter.com/typescriptlang). <add>[TypeScript](https://www.typescriptlang.org/) is a language for application-scale JavaScript. TypeScript adds optional types, classes, and modules to JavaScript. TypeScript supports tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to readable, standards-based JavaScript. Try it out at the [playground](https://www.typescriptlang.org/Playground), and stay up to date via [our blog](https://blogs.msdn.microsoft.com/typescript/) and [twitter account](https://twitter.com/typescriptlang). <ide> <ide> <ide> ## Contribute <ide> <ide> There are many ways to [contribute](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md) to TypeScript. <ide> * [Submit bugs](https://github.com/Microsoft/TypeScript/issues) and help us verify fixes as they are checked in. <ide> * Review the [source code changes](https://github.com/Microsoft/TypeScript/pulls). <del>* Engage with other TypeScript users and developers on [StackOverflow](http://stackoverflow.com/questions/tagged/typescript). <del>* Join the [#typescript](http://twitter.com/#!/search/realtime/%23typescript) discussion on Twitter. <add>* Engage with other TypeScript users and developers on [StackOverflow](https://stackoverflow.com/questions/tagged/typescript). <add>* Join the [#typescript](https://twitter.com/#!/search/realtime/%23typescript) discussion on Twitter. <ide> * [Contribute bug fixes](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md). <del>* Read the language specification ([docx](http://go.microsoft.com/fwlink/?LinkId=267121), [pdf](http://go.microsoft.com/fwlink/?LinkId=267238)). <add>* Read the [language specification](https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md) ([docx](https://github.com/Microsoft/TypeScript/raw/master/doc/TypeScript%20Language%20Specification.docx), [pdf](https://github.com/Microsoft/TypeScript/raw/master/doc/TypeScript%20Language%20Specification.pdf)). <ide> <ide> <ide> ## Documentation <ide> <del>* [Quick tutorial](http://www.typescriptlang.org/Tutorial) <del>* [Programming handbook](http://www.typescriptlang.org/Handbook) <add>* [Quick tutorial](https://www.typescriptlang.org/Tutorial) <add>* [Programming handbook](https://www.typescriptlang.org/Handbook) <ide> * [Language specification](https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md) <del>* [Homepage](http://www.typescriptlang.org/) <add>* [Homepage](https://www.typescriptlang.org/) <ide> <ide> ## Building <ide> <del>In order to build the TypeScript compiler, ensure that you have [Git](http://git-scm.com/downloads) and [Node.js](http://nodejs.org/) installed. <add>In order to build the TypeScript compiler, ensure that you have [Git](https://git-scm.com/downloads) and [Node.js](https://nodejs.org/) installed. <ide> <ide> Clone a copy of the repo: <ide>
6
Mixed
Javascript
add enfile to rimraf retry logic
74f819612f1e9a061bf5b12c419e0e9ac00652d6
<ide><path>doc/api/fs.md <ide> changes: <ide> description: The `maxBusyTries` option is renamed to `maxRetries`, and its <ide> default is 0. The `emfileWait` option has been removed, and <ide> `EMFILE` errors use the same retry logic as other errors. The <del> `retryDelay` option is now supported. <add> `retryDelay` option is now supported. `ENFILE` errors are now <add> retried. <ide> - version: v12.10.0 <ide> pr-url: https://github.com/nodejs/node/pull/29168 <ide> description: The `recursive`, `maxBusyTries`, and `emfileWait` options are <ide> changes: <ide> <ide> * `path` {string|Buffer|URL} <ide> * `options` {Object} <del> * `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENOTEMPTY`, or `EPERM` <del> error is encountered, Node.js will retry the operation with a linear backoff <del> wait of `retryDelay` ms longer on each try. This option represents the number <del> of retries. This option is ignored if the `recursive` option is not `true`. <del> **Default:** `0`. <add> * `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or <add> `EPERM` error is encountered, Node.js will retry the operation with a linear <add> backoff wait of `retryDelay` ms longer on each try. This option represents the <add> number of retries. This option is ignored if the `recursive` option is not <add> `true`. **Default:** `0`. <ide> * `recursive` {boolean} If `true`, perform a recursive directory removal. In <ide> recursive mode, errors are not reported if `path` does not exist, and <ide> operations are retried on failure. **Default:** `false`. <ide> changes: <ide> description: The `maxBusyTries` option is renamed to `maxRetries`, and its <ide> default is 0. The `emfileWait` option has been removed, and <ide> `EMFILE` errors use the same retry logic as other errors. The <del> `retryDelay` option is now supported. <add> `retryDelay` option is now supported. `ENFILE` errors are now <add> retried. <ide> - version: v12.10.0 <ide> pr-url: https://github.com/nodejs/node/pull/29168 <ide> description: The `recursive`, `maxBusyTries`, and `emfileWait` options are <ide> changes: <ide> <ide> * `path` {string|Buffer|URL} <ide> * `options` {Object} <del> * `maxRetries` {integer} If an `EBUSY`, `ENOTEMPTY`, or `EPERM` error is <del> encountered, Node.js will retry the operation. This option represents the <add> * `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or <add> `EPERM` error is encountered, Node.js will retry the operation with a linear <add> backoff wait of `retryDelay` ms longer on each try. This option represents the <ide> number of retries. This option is ignored if the `recursive` option is not <ide> `true`. **Default:** `0`. <ide> * `recursive` {boolean} If `true`, perform a recursive directory removal. In <ide> changes: <ide> description: The `maxBusyTries` option is renamed to `maxRetries`, and its <ide> default is 0. The `emfileWait` option has been removed, and <ide> `EMFILE` errors use the same retry logic as other errors. The <del> `retryDelay` option is now supported. <add> `retryDelay` option is now supported. `ENFILE` errors are now <add> retried. <ide> - version: v12.10.0 <ide> pr-url: https://github.com/nodejs/node/pull/29168 <ide> description: The `recursive`, `maxBusyTries`, and `emfileWait` options are <ide> changes: <ide> <ide> * `path` {string|Buffer|URL} <ide> * `options` {Object} <del> * `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENOTEMPTY`, or `EPERM` <del> error is encountered, Node.js will retry the operation with a linear backoff <del> wait of `retryDelay` ms longer on each try. This option represents the number <del> of retries. This option is ignored if the `recursive` option is not `true`. <del> **Default:** `0`. <add> * `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or <add> `EPERM` error is encountered, Node.js will retry the operation with a linear <add> backoff wait of `retryDelay` ms longer on each try. This option represents the <add> number of retries. This option is ignored if the `recursive` option is not <add> `true`. **Default:** `0`. <ide> * `recursive` {boolean} If `true`, perform a recursive directory removal. In <ide> recursive mode, errors are not reported if `path` does not exist, and <ide> operations are retried on failure. **Default:** `false`. <ide><path>lib/internal/fs/rimraf.js <ide> const { <ide> const { join } = require('path'); <ide> const { setTimeout } = require('timers'); <ide> const notEmptyErrorCodes = new Set(['ENOTEMPTY', 'EEXIST', 'EPERM']); <del>const retryErrorCodes = new Set(['EBUSY', 'EMFILE', 'ENOTEMPTY', 'EPERM']); <add>const retryErrorCodes = new Set( <add> ['EBUSY', 'EMFILE', 'ENFILE', 'ENOTEMPTY', 'EPERM']); <ide> const isWindows = process.platform === 'win32'; <ide> const epermHandler = isWindows ? fixWinEPERM : _rmdir; <ide> const epermHandlerSync = isWindows ? fixWinEPERMSync : _rmdirSync;
2
Javascript
Javascript
adjust assertions based on the new soft-wrap logic
bf5a0d8c8cca9c4c2d51006ef0727c64accf60d8
<ide><path>spec/text-editor-component-spec.js <ide> describe('TextEditorComponent', function () { <ide> gutterNode.dispatchEvent(buildMouseEvent('mousedown', clientCoordinatesForScreenRowInGutter(11), { <ide> shiftKey: true <ide> })) <del> expect(editor.getSelectedScreenRange()).toEqual([[7, 4], [16, 0]]) <add> expect(editor.getSelectedScreenRange()).toEqual([[7, 4], [17, 0]]) <ide> }) <ide> }) <ide> }) <ide> describe('TextEditorComponent', function () { <ide> gutterNode.dispatchEvent(buildMouseEvent('mouseup', clientCoordinatesForScreenRowInGutter(11), { <ide> metaKey: true <ide> })) <del> expect(editor.getSelectedScreenRanges()).toEqual([[[7, 4], [7, 6]], [[11, 4], [19, 0]]]) <add> expect(editor.getSelectedScreenRanges()).toEqual([[[7, 4], [7, 6]], [[11, 4], [20, 0]]]) <ide> }) <ide> <ide> it('merges overlapping selections on mouseup', async function () { <ide> describe('TextEditorComponent', function () { <ide> gutterNode.dispatchEvent(buildMouseEvent('mouseup', clientCoordinatesForScreenRowInGutter(5), { <ide> metaKey: true <ide> })) <del> expect(editor.getSelectedScreenRanges()).toEqual([[[5, 0], [19, 0]]]) <add> expect(editor.getSelectedScreenRanges()).toEqual([[[5, 0], [20, 0]]]) <ide> }) <ide> }) <ide> }) <ide> describe('TextEditorComponent', function () { <ide> })) <ide> gutterNode.dispatchEvent(buildMouseEvent('mousemove', clientCoordinatesForScreenRowInGutter(11))) <ide> await nextAnimationFramePromise() <del> expect(editor.getSelectedScreenRange()).toEqual([[1, 4], [11, 14]]) <add> expect(editor.getSelectedScreenRange()).toEqual([[1, 4], [11, 5]]) <ide> }) <ide> }) <ide>
1
Ruby
Ruby
remove another reference to subformulae
3b76987fd79be6c0ed6516bcfb3b6f870909bf9d
<ide><path>Library/Contributions/example-formula.rb <ide> # Ruby classes have to start Upper case and dashes are not allowed. <ide> # So we transform: `example-formula.rb` into `ExampleFormula`. Further, <ide> # Homebrew does enforce that the name of the file and the class correspond. <del># Check with `brew search` that the name is free. A file may contain multiple <del># classes (we call them sub-formulae) but the main one is the class that <del># corresponds to the filename. <add># Check with `brew search` that the name is free. <ide> class ExampleFormula < Formula <ide> <ide> homepage 'http://www.example.com' # used by `brew home example-formula`.
1
Python
Python
remove asarray call on a known array
dbaca82d6d8c63f4d48ec08ae07e45e5b7bc2000
<ide><path>numpy/lib/histograms.py <ide> def histogramdd(sample, bins=10, range=None, normed=False, weights=None): <ide> nbin[i] = len(edges[i]) + 1 # includes an outlier on each end <ide> dedges[i] = np.diff(edges[i]) <ide> <del> nbin = np.asarray(nbin) <del> <ide> # Handle empty input. <ide> if N == 0: <ide> return np.zeros(nbin-2), edges
1
Javascript
Javascript
ignore extra compilation while testing watching
e299d600f79cd314296e2d9cf5094e43e9277ce4
<ide><path>test/WatchTestCases.test.js <ide> describe("WatchTestCases", function() { <ide> <ide> var runIdx = 0; <ide> var run = runs[runIdx]; <add> var lastHash = ""; <ide> copyDiff(path.join(testDirectory, run.name), tempDirectory); <ide> <ide> var compiler = webpack(options); <ide> compiler.watch({}, function(err, stats) { <del> if(run.done) return; <add> if(stats.hash === lastHash) <add> return; <add> lastHash = stats.hash; <add> if(run.done) <add> return done(new Error("Compilation changed but no change was issued " + lastHash + " != " + stats.hash + " (run " + runIdx + ")")); <ide> run.done = true; <ide> if(err) return done(err); <ide> var statOptions = Stats.presetToOptions("verbose");
1
Text
Text
modify serial number and fix some typos
9ddd1242dbaeaa990c060b7b88ed859fa3b2d981
<ide><path>experimental/plugins_graphdriver.md <ide> Docker graph driver plugins enable admins to use an external/out-of-process <ide> graph driver for use with Docker engine. This is an alternative to using the <ide> built-in storage drivers, such as aufs/overlay/devicemapper/btrfs. <ide> <del>A graph driver plugin is used for image and container fs storage, as such <add>A graph driver plugin is used for image and container filesystem storage, as such <ide> the plugin must be started and available for connections prior to Docker Engine <ide> being started. <ide> <ide> Get a list of changes between the filesystem layers specified by the `ID` and <ide> } <ide> ``` <ide> <del>Responds with a list of changes. The structure of a change is: <add>Respond with a list of changes. The structure of a change is: <ide> ``` <ide> "Path": "/some/path", <ide> "Kind": 0,
1
Ruby
Ruby
fix rubocop warnings
8271e357867692edfddf3d70328dd568bd7eebf2
<ide><path>Library/Homebrew/os/mac/xcode.rb <ide> module Mac <ide> module Xcode <ide> extend self <ide> <del> V4_BUNDLE_ID = "com.apple.dt.Xcode" <del> V3_BUNDLE_ID = "com.apple.Xcode" <add> V4_BUNDLE_ID = "com.apple.dt.Xcode".freeze <add> V3_BUNDLE_ID = "com.apple.Xcode".freeze <ide> <ide> def latest_version <ide> case MacOS.version <ide> def uncached_version <ide> #{prefix}/usr/bin/xcodebuild <ide> #{which("xcodebuild")} <ide> ].uniq.each do |xcodebuild_path| <del> if File.executable? xcodebuild_path <del> xcodebuild_output = Utils.popen_read(xcodebuild_path, "-version") <del> next unless $?.success? <add> next unless File.executable? xcodebuild_path <add> xcodebuild_output = Utils.popen_read(xcodebuild_path, "-version") <add> next unless $?.success? <ide> <del> xcode_version = xcodebuild_output[/Xcode (\d(\.\d)*)/, 1] <del> return xcode_version if xcode_version <add> xcode_version = xcodebuild_output[/Xcode (\d(\.\d)*)/, 1] <add> return xcode_version if xcode_version <ide> <del> # Xcode 2.x's xcodebuild has a different version string <del> case xcodebuild_output[/DevToolsCore-(\d+\.\d)/, 1] <del> when "515.0" then return "2.0" <del> when "798.0" then return "2.5" <del> end <add> # Xcode 2.x's xcodebuild has a different version string <add> case xcodebuild_output[/DevToolsCore-(\d+\.\d)/, 1] <add> when "515.0" then return "2.0" <add> when "798.0" then return "2.5" <ide> end <ide> end <ide> <ide> def uncached_version <ide> # be removed in a future version. To remain compatible, guard usage of <ide> # Xcode.version with an Xcode.installed? check. <ide> case (DevelopmentTools.clang_version.to_f * 10).to_i <del> when 0 then "dunno" <del> when 1..14 then "3.2.2" <del> when 15 then "3.2.4" <del> when 16 then "3.2.5" <del> when 17..20 then "4.0" <del> when 21 then "4.1" <del> when 22..30 then "4.2" <del> when 31 then "4.3" <del> when 40 then "4.4" <del> when 41 then "4.5" <del> when 42 then "4.6" <del> when 50 then "5.0" <del> when 51 then "5.1" <del> when 60 then "6.0" <del> when 61 then "6.1" <del> when 70 then "7.0" <del> when 73 then "7.3" <del> when 80 then "8.0" <del> else "8.0" <add> when 0 then "dunno" <add> when 1..14 then "3.2.2" <add> when 15 then "3.2.4" <add> when 16 then "3.2.5" <add> when 17..20 then "4.0" <add> when 21 then "4.1" <add> when 22..30 then "4.2" <add> when 31 then "4.3" <add> when 40 then "4.4" <add> when 41 then "4.5" <add> when 42 then "4.6" <add> when 50 then "5.0" <add> when 51 then "5.1" <add> when 60 then "6.0" <add> when 61 then "6.1" <add> when 70 then "7.0" <add> when 73 then "7.3" <add> when 80 then "8.0" <add> else "8.0" <ide> end <ide> end <ide> <ide> def default_prefix? <ide> module CLT <ide> extend self <ide> <del> STANDALONE_PKG_ID = "com.apple.pkg.DeveloperToolsCLILeo" <del> FROM_XCODE_PKG_ID = "com.apple.pkg.DeveloperToolsCLI" <del> MAVERICKS_PKG_ID = "com.apple.pkg.CLTools_Executables" <del> MAVERICKS_NEW_PKG_ID = "com.apple.pkg.CLTools_Base" # obsolete <del> MAVERICKS_PKG_PATH = "/Library/Developer/CommandLineTools" <add> STANDALONE_PKG_ID = "com.apple.pkg.DeveloperToolsCLILeo".freeze <add> FROM_XCODE_PKG_ID = "com.apple.pkg.DeveloperToolsCLI".freeze <add> MAVERICKS_PKG_ID = "com.apple.pkg.CLTools_Executables".freeze <add> MAVERICKS_NEW_PKG_ID = "com.apple.pkg.CLTools_Base".freeze # obsolete <add> MAVERICKS_PKG_PATH = "/Library/Developer/CommandLineTools".freeze <ide> <ide> # Returns true even if outdated tools are installed, e.g. <ide> # tools from Xcode 4.x on 10.9
1
Ruby
Ruby
prefer deprecate_constant over constant proxy
1e68400930afdf983f5de47e124451ef15ee6889
<ide><path>actionview/lib/action_view/template/resolver.rb <ide> module ActionView <ide> # = Action View Resolver <ide> class Resolver <del> Path = ActiveSupport::Deprecation::DeprecatedConstantProxy.new("ActionView::Resolver::Path", "ActionView::TemplatePath", ActionView.deprecator) <add> include ActiveSupport::Deprecation::DeprecatedConstantAccessor <add> deprecate_constant "Path", "ActionView::TemplatePath", deprecator: ActionView.deprecator <ide> <ide> class PathParser # :nodoc: <ide> ParsedPath = Struct.new(:path, :details) <ide><path>railties/lib/rails/generators/testing/behavior.rb <ide> def migration_file_name(relative) <ide> end <ide> end <ide> <del> Behaviour = ActiveSupport::Deprecation::DeprecatedConstantProxy.new("Rails::Generators::Testing::Behaviour", "Rails::Generators::Testing::Behavior", Rails.deprecator) <add> include ActiveSupport::Deprecation::DeprecatedConstantAccessor <add> deprecate_constant "Behaviour", "Rails::Generators::Testing::Behavior", deprecator: Rails.deprecator <ide> end <ide> end <ide> end <ide><path>railties/test/generators_test.rb <ide> def test_hide_namespace <ide> <ide> def test_behaviour_aliases_behavior <ide> assert_deprecated(Rails.deprecator) do <del> assert_same Rails::Generators::Testing::Behavior, Rails::Generators::Testing::Behaviour.itself <add> assert_same Rails::Generators::Testing::Behavior, Rails::Generators::Testing::Behaviour <ide> end <ide> end <ide> end
3
Javascript
Javascript
use document fragments to grow repeaters
15ec78f5eff3f8fa74714fe10986be094915c800
<ide><path>src/jqLite.js <ide> function JQLite(element) { <ide> div.innerHTML = '<div>&nbsp;</div>' + element; // IE insanity to make NoScope elements work! <ide> div.removeChild(div.firstChild); // remove the superfluous div <ide> JQLiteAddNodes(this, div.childNodes); <del> this.remove(); // detach the elements form the temporary DOM div. <add> this.remove(); // detach the elements from the temporary DOM div. <ide> } else { <ide> JQLiteAddNodes(this, element); <ide> } <ide> function JQLiteAddNodes(root, elements) { <ide> ? elements <ide> : [ elements ]; <ide> for(var i=0; i < elements.length; i++) { <del> if (elements[i].nodeType != 11) <del> root.push(elements[i]); <add> root.push(elements[i]); <ide> } <ide> } <ide> } <ide><path>src/widgets.js <ide> angularWidget('@ng:repeat', function(expression, element){ <ide> lastIterElement = iterStartElement, <ide> collection = this.$tryEval(rhs, iterStartElement), <ide> collectionLength = size(collection, true), <add> fragment = (element[0].nodeName != 'OPTION') ? document.createDocumentFragment() : null, <add> addFragment, <ide> childScope, <ide> key; <ide> <ide> angularWidget('@ng:repeat', function(expression, element){ <ide> children.push(childScope); <ide> linker(childScope, function(clone){ <ide> clone.attr('ng:repeat-index', index); <del> lastIterElement.after(clone); <del> lastIterElement = clone; <add> <add> if (fragment) { <add> fragment.appendChild(clone[0]); <add> addFragment = true; <add> } else { <add> //temporarily preserve old way for option element <add> lastIterElement.after(clone); <add> lastIterElement = clone; <add> } <ide> }); <ide> } <ide> index ++; <ide> } <ide> } <add> <add> //attach new nodes buffered in doc fragment <add> if (addFragment) { <add> lastIterElement.after(jqLite(fragment)); <add> } <add> <ide> // shrink children <ide> while(children.length > index) { <ide> children.pop().$element.remove();
2
Text
Text
add accenture to the inthewild file
b8abf1425004410ba8ca37385d294c650a2a7e06
<ide><path>INTHEWILD.md <ide> Currently, **officially** using Airflow: <ide> 1. [8fit](https://8fit.com/) [[@nicor88](https://github.com/nicor88), [@frnzska](https://github.com/frnzska)] <ide> 1. [90 Seconds](https://90seconds.tv/) [[@aaronmak](https://github.com/aaronmak)] <ide> 1. [99](https://99taxis.com) [[@fbenevides](https://github.com/fbenevides), [@gustavoamigo](https://github.com/gustavoamigo) & [@mmmaia](https://github.com/mmmaia)] <add>1. [Accenture](https://www.accenture.com/au-en) [[@nijanthanvijayakumar](https://github.com/nijanthanvijayakumar)] <ide> 1. [AdBOOST](https://www.adboost.sk) [[AdBOOST](https://github.com/AdBOOST)] <ide> 1. [Adobe](https://www.adobe.com/) [[@mishikaSingh](https://github.com/mishikaSingh), [@ramandumcs](https://github.com/ramandumcs), [@vardancse](https://github.com/vardancse)] <ide> 1. [Agari](https://github.com/agaridata) [[@r39132](https://github.com/r39132)]
1
Javascript
Javascript
build api toc using raw headers
46de34b8c27d8dca1f88388d608bbf56af06ceec
<ide><path>tools/doc/html.js <ide> function buildToc({ filename }) { <ide> <ide> depth = node.depth; <ide> const realFilename = path.basename(realFilenames[0], '.md'); <del> const headingText = node.children.map((child) => child.value) <del> .join().trim(); <add> const headingText = node.children.map((child) => <add> file.contents.slice(child.position.start.offset, <add> child.position.end.offset) <add> ).join('').trim(); <ide> const id = getId(`${realFilename}_${headingText}`, idCounters); <ide> <ide> const hasStability = node.stability !== undefined;
1
Javascript
Javascript
remove `controller#content` alias
a155b309541e7077c31cf0a7e1a4302d4c87fb17
<ide><path>packages/ember-runtime/lib/mixins/controller.js <ide> export default Mixin.create(ActionHandler, { <ide> @public <ide> */ <ide> model: null, <del> <del> /** <del> @private <del> */ <del> content: deprecatingAlias('model', { <del> id: 'ember-runtime.controller.content-alias', <del> until: '2.17.0', <del> url: 'https://emberjs.com/deprecations/v2.x/#toc_controller-content-alias' <del> }) <ide> }); <ide><path>packages/ember-runtime/tests/controllers/controller_test.js <ide> QUnit.module('Controller deprecations'); <ide> <ide> QUnit.module('Controller Content -> Model Alias'); <ide> <del>QUnit.test('`content` is a deprecated alias of `model`', function(assert) { <del> assert.expect(2); <del> let controller = Controller.extend({ <del> model: 'foo-bar' <del> }).create(); <del> <del> expectDeprecation(function () { <del> assert.equal(controller.get('content'), 'foo-bar', 'content is an alias of model'); <del> }); <del>}); <del> <ide> QUnit.test('`content` is not moved to `model` when `model` is unset', function(assert) { <ide> assert.expect(2); <ide> let controller;
2
Javascript
Javascript
use flat array in `dsl`
6d9a9735eeb04182589ff9bd98569288667cb8d8
<ide><path>packages/ember-routing/lib/system/dsl.js <ide> class DSL { <ide> <ide> if (url === '' || url === '/' || parts[parts.length - 1] === 'index') { this.explicitIndex = true; } <ide> <del> this.matches.push([url, name, callback]); <add> this.matches.push(url, name, callback); <ide> } <ide> <ide> resource(name, options = {}, callback) { <ide> class DSL { <ide> } <ide> <ide> return match => { <del> for (let i = 0; i < dslMatches.length; i++) { <del> let dslMatch = dslMatches[i]; <del> match(dslMatch[0]).to(dslMatch[1], dslMatch[2]); <add> for (let i = 0; i < dslMatches.length; i += 3) { <add> match(dslMatches[i]).to(dslMatches[i + 1], dslMatches[i + 2]); <ide> } <ide> }; <ide> } <ide> class DSL { <ide> createRoute(childDSL, 'loading'); <ide> createRoute(childDSL, 'error', { path: dummyErrorRoute }); <ide> <del> <ide> engineRouteMap.class.call(childDSL); <ide> <ide> callback = childDSL.generate(); <ide> class DSL { <ide> export default DSL; <ide> <ide> function canNest(dsl) { <del> return dsl.parent && dsl.parent !== 'application'; <add> return dsl.parent !== 'application'; <ide> } <ide> <ide> function getFullName(dsl, name, resetNamespace) {
1
Go
Go
remove redundant code and better error msg
5c0ea56d56065ee737557650fa797a61f52e8378
<ide><path>client/swarm_unlock.go <ide> import ( <ide> // SwarmUnlock unlockes locked swarm. <ide> func (cli *Client) SwarmUnlock(ctx context.Context, req swarm.UnlockRequest) error { <ide> serverResp, err := cli.post(ctx, "/swarm/unlock", nil, req, nil) <del> if err != nil { <del> return err <del> } <del> <ide> ensureReaderClosed(serverResp) <ide> return err <ide> } <ide><path>client/volume_prune.go <ide> func (cli *Client) VolumesPrune(ctx context.Context, pruneFilters filters.Args) <ide> defer ensureReaderClosed(serverResp) <ide> <ide> if err := json.NewDecoder(serverResp.body).Decode(&report); err != nil { <del> return report, fmt.Errorf("Error retrieving disk usage: %v", err) <add> return report, fmt.Errorf("Error retrieving volume prune report:: %v", err) <ide> } <ide> <ide> return report, nil
2
PHP
PHP
add array key
50380ce3b5e06d099546b0a66edf50bfb85423a9
<ide><path>src/Illuminate/Foundation/Auth/AuthenticatesAndRegistersUsers.php <ide> public function postLogin(Request $request) <ide> return redirect($this->loginPath()) <ide> ->withInput($request->only('email', 'remember')) <ide> ->withErrors([ <del> $this->getFailedLoginMesssage(), <add> 'email' => $this->getFailedLoginMesssage(), <ide> ]); <ide> } <ide>
1
PHP
PHP
fix bug in appnamecommand
f7e9277d33b4efee11f4a8170c53f84c739876e1
<ide><path>src/Illuminate/Foundation/Console/AppNameCommand.php <ide> protected function setBootstrapNamespaces() <ide> $search = [ <ide> $this->currentRoot.'\\Http', <ide> $this->currentRoot.'\\Console', <del> $this->currentRoot.'\\Exception', <add> $this->currentRoot.'\\Exceptions', <ide> ]; <ide> <ide> $replace = [
1
Javascript
Javascript
apply suggestions from code review
d8754873f668b40cec703284047228490c8002ff
<ide><path>lib/TemplatedPathPlugin.js <ide> const getReplacer = (value, allowEmpty) => { <ide> const escapePathVariables = value => { <ide> return typeof value === "string" <ide> ? value.replace( <del> /\[(name|id|moduleid|file|query|filebase|url|hash|chunkhash|modulehash|contenthash)\]/g, <add> /\[(\\*[\w:]+\\*)\]/gi, <ide> "[\\$1\\]" <ide> ) <ide> : value; <ide><path>test/HotModuleReplacementPlugin.test.js <ide> describe("HotModuleReplacementPlugin", () => { <ide> }); <ide> fs.writeFileSync(entryFile, "1", "utf-8"); <ide> compiler.run((err, stats) => { <del> if (err) throw err; <add> if (err) return done(err); <ide> fs.writeFileSync(statsFile3, stats.toString()); <ide> compiler.run((err, stats) => { <del> if (err) throw err; <add> if (err) return done(err); <ide> fs.writeFileSync(statsFile4, stats.toString()); <ide> fs.writeFileSync(entryFile, "2", "utf-8"); <ide> compiler.run((err, stats) => { <del> if (err) throw err; <add> if (err) return done(err); <ide> fs.writeFileSync(statsFile3, stats.toString()); <ide> <ide> let foundUpdates = false;
2
PHP
PHP
fix variable name in test
71872d40cdf7a1e2dcbd8beb9e9fa864eb4804fa
<ide><path>tests/TestCase/Error/DebuggerTest.php <ide> public function testLogDepth(): void <ide> $veryRandomName = [ <ide> 'test' => ['key' => 'val'], <ide> ]; <del> Debugger::log($val, 'debug', 0); <add> Debugger::log($veryRandomName, 'debug', 0); <ide> <ide> $messages = Log::engine('test')->read(); <ide> $this->assertStringContainsString('DebuggerTest::testLogDepth', $messages[0]);
1
Javascript
Javascript
remove unused deprecation code
3ad7c1ae9778fd9a61b4e99eeab4291827700d55
<ide><path>test/parallel/test-process-assert.js <ide> const assert = require('assert'); <ide> <ide> common.expectWarning( <ide> 'DeprecationWarning', <del> 'process.assert() is deprecated. Please use the `assert` module instead.', <del> 'DEP0100' <add> 'process.assert() is deprecated. Please use the `assert` module instead.' <ide> ); <ide> <ide> assert.strictEqual(process.assert(1, 'error'), undefined); <ide><path>test/parallel/test-process-env-deprecation.js <ide> common.expectWarning( <ide> 'DeprecationWarning', <ide> 'Assigning any value other than a string, number, or boolean to a ' + <ide> 'process.env property is deprecated. Please make sure to convert the value ' + <del> 'to a string before setting process.env with it.', <del> 'DEP0104' <add> 'to a string before setting process.env with it.' <ide> ); <ide> <ide> process.env.ABC = undefined;
2
Go
Go
add 32bit syscalls to whitelist
a1747b3cc861c00803a67e5a61dce73db6ac8eee
<ide><path>daemon/execdriver/native/seccomp_default.go <ide> var defaultSeccompProfile = &configs.Seccomp{ <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "chown32", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "chroot", <ide> Action: configs.Allow, <ide> var defaultSeccompProfile = &configs.Seccomp{ <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "fadvise64_64", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "fallocate", <ide> Action: configs.Allow, <ide> var defaultSeccompProfile = &configs.Seccomp{ <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "fchown32", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "fchownat", <ide> Action: configs.Allow, <ide> var defaultSeccompProfile = &configs.Seccomp{ <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "fcntl64", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "fdatasync", <ide> Action: configs.Allow, <ide> var defaultSeccompProfile = &configs.Seccomp{ <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "fstat64", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <add> { <add> Name: "fstatat64", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "fstatfs", <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "fstatfs64", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "fsync", <ide> Action: configs.Allow, <ide> var defaultSeccompProfile = &configs.Seccomp{ <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "ftruncate64", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "futex", <ide> Action: configs.Allow, <ide> var defaultSeccompProfile = &configs.Seccomp{ <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "getegid32", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "geteuid", <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "geteuid32", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "getgid", <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "getgid32", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "getgroups", <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "getgroups32", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "getitimer", <ide> Action: configs.Allow, <ide> var defaultSeccompProfile = &configs.Seccomp{ <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "getresgid32", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "getresuid", <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "getresuid32", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "getrlimit", <ide> Action: configs.Allow, <ide> var defaultSeccompProfile = &configs.Seccomp{ <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "getuid32", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "getxattr", <ide> Action: configs.Allow, <ide> var defaultSeccompProfile = &configs.Seccomp{ <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "lchown32", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "lgetxattr", <ide> Action: configs.Allow, <ide> var defaultSeccompProfile = &configs.Seccomp{ <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "lstat64", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "madvise", <ide> Action: configs.Allow, <ide> var defaultSeccompProfile = &configs.Seccomp{ <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "_newselect", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "open", <ide> Action: configs.Allow, <ide> var defaultSeccompProfile = &configs.Seccomp{ <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "sendfile64", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "sendmmsg", <ide> Action: configs.Allow, <ide> var defaultSeccompProfile = &configs.Seccomp{ <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "setfsgid32", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "setfsuid", <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "setfsuid32", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "setgid", <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "setgid32", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "setgroups", <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "setgroups32", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "sethostname", <ide> Action: configs.Allow, <ide> var defaultSeccompProfile = &configs.Seccomp{ <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "setregid32", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "setresgid", <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "setresgid32", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "setresuid", <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "setresuid32", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "setreuid", <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "setreuid32", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "setrlimit", <ide> Action: configs.Allow, <ide> var defaultSeccompProfile = &configs.Seccomp{ <ide> Args: []*configs.Arg{}, <ide> }, <ide> { <del> Name: "settimeofday", <add> Name: "setuid", <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <ide> { <del> Name: "setuid", <add> Name: "setuid32", <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <ide> var defaultSeccompProfile = &configs.Seccomp{ <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "stat64", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "statfs", <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "statfs64", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "symlink", <ide> Action: configs.Allow, <ide> var defaultSeccompProfile = &configs.Seccomp{ <ide> Action: configs.Allow, <ide> Args: []*configs.Arg{}, <ide> }, <add> { <add> Name: "truncate64", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <add> { <add> Name: "ugetrlimit", <add> Action: configs.Allow, <add> Args: []*configs.Arg{}, <add> }, <ide> { <ide> Name: "umask", <ide> Action: configs.Allow,
1
PHP
PHP
wrap when calling seeders
532c49d1dbcd63decd9fa5037fc2510e5f955103
<ide><path>src/Illuminate/Database/Seeder.php <ide> <ide> namespace Illuminate\Database; <ide> <add>use Illuminate\Support\Arr; <ide> use InvalidArgumentException; <ide> use Illuminate\Console\Command; <ide> use Illuminate\Container\Container; <ide> abstract class Seeder <ide> */ <ide> public function call($class, $silent = false) <ide> { <del> $classes = is_array($class) ? $class : (array) $class; <add> $classes = Arr::wrap($class); <ide> <ide> foreach ($classes as $class) { <ide> if ($silent === false && isset($this->command)) {
1
Javascript
Javascript
remove workaround for adreno bug
d9a8da2290719e6224104ebd55ab71b38e578d74
<ide><path>src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl.js <ide> export default /* glsl */` <ide> <ide> vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) { <ide> <del> // Workaround for Adreno 3XX dFd*( vec3 ) bug. See #9988 <del> <del> vec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) ); <del> vec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) ); <del> vec3 vN = surf_norm; // normalized <add> vec3 vSigmaX = dFdx( surf_pos.xyz ); <add> vec3 vSigmaY = dFdy( surf_pos.xyz ); <add> vec3 vN = surf_norm; // normalized <ide> <ide> vec3 R1 = cross( vSigmaY, vN ); <ide> vec3 R2 = cross( vN, vSigmaX ); <ide><path>src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl.js <ide> export default /* glsl */` <ide> <ide> vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) { <ide> <del> // Workaround for Adreno 3XX dFd*( vec3 ) bug. See #9988 <del> <del> vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) ); <del> vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) ); <add> vec3 q0 = dFdx( eye_pos.xyz ); <add> vec3 q1 = dFdy( eye_pos.xyz ); <ide> vec2 st0 = dFdx( vUv.st ); <ide> vec2 st1 = dFdy( vUv.st ); <ide>
2
Java
Java
fix resourceurlencodingfilter lifecycle
50a4769162061f2e16dca7176f8b431093f08a27
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceUrlEncodingFilter.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> import javax.servlet.ServletRequest; <ide> import javax.servlet.ServletResponse; <ide> import javax.servlet.http.HttpServletRequest; <add>import javax.servlet.http.HttpServletRequestWrapper; <ide> import javax.servlet.http.HttpServletResponse; <ide> import javax.servlet.http.HttpServletResponseWrapper; <ide> <ide> public class ResourceUrlEncodingFilter extends GenericFilterBean { <ide> public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) <ide> throws IOException, ServletException { <ide> if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) { <del> throw new ServletException("ResourceUrlEncodingFilter just supports HTTP requests"); <add> throw new ServletException("ResourceUrlEncodingFilter only supports HTTP requests"); <ide> } <del> HttpServletRequest httpRequest = (HttpServletRequest) request; <del> HttpServletResponse httpResponse = (HttpServletResponse) response; <del> filterChain.doFilter(httpRequest, new ResourceUrlEncodingResponseWrapper(httpRequest, httpResponse)); <add> ResourceUrlEncodingRequestWrapper wrappedRequest = <add> new ResourceUrlEncodingRequestWrapper((HttpServletRequest) request); <add> ResourceUrlEncodingResponseWrapper wrappedResponse = <add> new ResourceUrlEncodingResponseWrapper(wrappedRequest, (HttpServletResponse) response); <add> filterChain.doFilter(wrappedRequest, wrappedResponse); <ide> } <ide> <add> private static class ResourceUrlEncodingRequestWrapper extends HttpServletRequestWrapper { <ide> <del> private static class ResourceUrlEncodingResponseWrapper extends HttpServletResponseWrapper { <del> <del> private final HttpServletRequest request; <add> @Nullable <add> private ResourceUrlProvider resourceUrlProvider; <ide> <del> /* Cache the index and prefix of the path within the DispatcherServlet mapping */ <ide> @Nullable <ide> private Integer indexLookupPath; <ide> <ide> private String prefixLookupPath = ""; <ide> <del> public ResourceUrlEncodingResponseWrapper(HttpServletRequest request, HttpServletResponse wrapped) { <del> super(wrapped); <del> this.request = request; <add> ResourceUrlEncodingRequestWrapper(HttpServletRequest request) { <add> super(request); <ide> } <ide> <ide> @Override <del> public String encodeURL(String url) { <del> ResourceUrlProvider resourceUrlProvider = getResourceUrlProvider(); <del> if (resourceUrlProvider == null) { <del> logger.trace("ResourceUrlProvider not available via " + <del> "request attribute ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR"); <del> return super.encodeURL(url); <del> } <del> <del> int index = initLookupPath(resourceUrlProvider); <del> if (url.startsWith(this.prefixLookupPath)) { <del> int suffixIndex = getQueryParamsIndex(url); <del> String suffix = url.substring(suffixIndex); <del> String lookupPath = url.substring(index, suffixIndex); <del> lookupPath = resourceUrlProvider.getForLookupPath(lookupPath); <del> if (lookupPath != null) { <del> return super.encodeURL(this.prefixLookupPath + lookupPath + suffix); <add> public void setAttribute(String name, Object o) { <add> super.setAttribute(name, o); <add> if (ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR.equals(name)) { <add> if(o instanceof ResourceUrlProvider) { <add> initLookupPath((ResourceUrlProvider) o); <ide> } <ide> } <ide> <del> return super.encodeURL(url); <del> } <del> <del> @Nullable <del> private ResourceUrlProvider getResourceUrlProvider() { <del> return (ResourceUrlProvider) this.request.getAttribute( <del> ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR); <ide> } <ide> <del> private int initLookupPath(ResourceUrlProvider urlProvider) { <add> private void initLookupPath(ResourceUrlProvider urlProvider) { <add> this.resourceUrlProvider = urlProvider; <ide> if (this.indexLookupPath == null) { <del> UrlPathHelper pathHelper = urlProvider.getUrlPathHelper(); <del> String requestUri = pathHelper.getRequestUri(this.request); <del> String lookupPath = pathHelper.getLookupPathForRequest(this.request); <add> UrlPathHelper pathHelper = this.resourceUrlProvider.getUrlPathHelper(); <add> String requestUri = pathHelper.getRequestUri(this); <add> String lookupPath = pathHelper.getLookupPathForRequest(this); <ide> this.indexLookupPath = requestUri.lastIndexOf(lookupPath); <ide> this.prefixLookupPath = requestUri.substring(0, this.indexLookupPath); <ide> if ("/".equals(lookupPath) && !"/".equals(requestUri)) { <del> String contextPath = pathHelper.getContextPath(this.request); <add> String contextPath = pathHelper.getContextPath(this); <ide> if (requestUri.equals(contextPath)) { <ide> this.indexLookupPath = requestUri.length(); <ide> this.prefixLookupPath = requestUri; <ide> } <ide> } <ide> } <del> return this.indexLookupPath; <add> } <add> <add> @Nullable <add> public String resolveUrlPath(String url) { <add> if (this.resourceUrlProvider == null) { <add> logger.trace("ResourceUrlProvider not available via " + <add> "request attribute ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR"); <add> return null; <add> } <add> if (url.startsWith(this.prefixLookupPath)) { <add> int suffixIndex = getQueryParamsIndex(url); <add> String suffix = url.substring(suffixIndex); <add> String lookupPath = url.substring(this.indexLookupPath, suffixIndex); <add> lookupPath = this.resourceUrlProvider.getForLookupPath(lookupPath); <add> if (lookupPath != null) { <add> return this.prefixLookupPath + lookupPath + suffix; <add> } <add> } <add> return null; <ide> } <ide> <ide> private int getQueryParamsIndex(String url) { <ide> private int getQueryParamsIndex(String url) { <ide> } <ide> } <ide> <add> <add> private static class ResourceUrlEncodingResponseWrapper extends HttpServletResponseWrapper { <add> <add> private final ResourceUrlEncodingRequestWrapper request; <add> <add> ResourceUrlEncodingResponseWrapper(ResourceUrlEncodingRequestWrapper request, HttpServletResponse wrapped) { <add> super(wrapped); <add> this.request = request; <add> } <add> <add> @Override <add> public String encodeURL(String url) { <add> String urlPath = this.request.resolveUrlPath(url); <add> if (urlPath != null) { <add> return super.encodeURL(urlPath); <add> } <add> return super.encodeURL(url); <add> } <add> } <add> <ide> } <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceUrlEncodingFilterTests.java <ide> private ResourceUrlProvider createResourceUrlProvider(List<ResourceResolver> res <ide> @Test <ide> public void encodeURL() throws Exception { <ide> MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); <del> request.setAttribute(ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR, this.urlProvider); <ide> MockHttpServletResponse response = new MockHttpServletResponse(); <ide> <ide> this.filter.doFilter(request, response, (req, res) -> { <add> req.setAttribute(ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR, this.urlProvider); <ide> String result = ((HttpServletResponse) res).encodeURL("/resources/bar.css"); <ide> assertEquals("/resources/bar-11e16cf79faee7ac698c805cf28248d2.css", result); <ide> }); <ide> public void encodeURL() throws Exception { <ide> public void encodeURLWithContext() throws Exception { <ide> MockHttpServletRequest request = new MockHttpServletRequest("GET", "/context/foo"); <ide> request.setContextPath("/context"); <del> request.setAttribute(ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR, this.urlProvider); <ide> MockHttpServletResponse response = new MockHttpServletResponse(); <ide> <ide> this.filter.doFilter(request, response, (req, res) -> { <add> req.setAttribute(ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR, this.urlProvider); <add> String result = ((HttpServletResponse) res).encodeURL("/context/resources/bar.css"); <add> assertEquals("/context/resources/bar-11e16cf79faee7ac698c805cf28248d2.css", result); <add> }); <add> } <add> <add> <add> @Test <add> public void encodeUrlWithContextAndForwardedRequest() throws Exception { <add> MockHttpServletRequest request = new MockHttpServletRequest("GET", "/context/foo"); <add> request.setContextPath("/context"); <add> MockHttpServletResponse response = new MockHttpServletResponse(); <add> <add> this.filter.doFilter(request, response, (req, res) -> { <add> req.setAttribute(ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR, this.urlProvider); <add> request.setRequestURI("/forwarded"); <add> request.setContextPath("/"); <ide> String result = ((HttpServletResponse) res).encodeURL("/context/resources/bar.css"); <ide> assertEquals("/context/resources/bar-11e16cf79faee7ac698c805cf28248d2.css", result); <ide> }); <ide> public void encodeURLWithContext() throws Exception { <ide> public void encodeContextPathUrlWithoutSuffix() throws Exception { <ide> MockHttpServletRequest request = new MockHttpServletRequest("GET", "/context"); <ide> request.setContextPath("/context"); <del> request.setAttribute(ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR, this.urlProvider); <ide> MockHttpServletResponse response = new MockHttpServletResponse(); <ide> <ide> this.filter.doFilter(request, response, (req, res) -> { <add> req.setAttribute(ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR, this.urlProvider); <ide> String result = ((HttpServletResponse) res).encodeURL("/context/resources/bar.css"); <ide> assertEquals("/context/resources/bar-11e16cf79faee7ac698c805cf28248d2.css", result); <ide> }); <ide> public void encodeContextPathUrlWithoutSuffix() throws Exception { <ide> public void encodeContextPathUrlWithSuffix() throws Exception { <ide> MockHttpServletRequest request = new MockHttpServletRequest("GET", "/context/"); <ide> request.setContextPath("/context"); <del> request.setAttribute(ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR, this.urlProvider); <ide> MockHttpServletResponse response = new MockHttpServletResponse(); <ide> <ide> this.filter.doFilter(request, response, (req, res) -> { <add> req.setAttribute(ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR, this.urlProvider); <ide> String result = ((HttpServletResponse) res).encodeURL("/context/resources/bar.css"); <ide> assertEquals("/context/resources/bar-11e16cf79faee7ac698c805cf28248d2.css", result); <ide> }); <ide> public void encodeContextPathUrlWithSuffix() throws Exception { <ide> public void encodeEmptyURLWithContext() throws Exception { <ide> MockHttpServletRequest request = new MockHttpServletRequest("GET", "/context/foo"); <ide> request.setContextPath("/context"); <del> request.setAttribute(ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR, this.urlProvider); <ide> MockHttpServletResponse response = new MockHttpServletResponse(); <ide> <ide> this.filter.doFilter(request, response, (req, res) -> { <add> req.setAttribute(ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR, this.urlProvider); <ide> String result = ((HttpServletResponse) res).encodeURL("?foo=1"); <ide> assertEquals("?foo=1", result); <ide> }); <ide> public void encodeEmptyURLWithContext() throws Exception { <ide> public void encodeURLWithRequestParams() throws Exception { <ide> MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo"); <ide> request.setContextPath("/"); <del> request.setAttribute(ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR, this.urlProvider); <ide> MockHttpServletResponse response = new MockHttpServletResponse(); <ide> <ide> this.filter.doFilter(request, response, (req, res) -> { <add> req.setAttribute(ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR, this.urlProvider); <ide> String result = ((HttpServletResponse) res).encodeURL("/resources/bar.css?foo=bar&url=http://example.org"); <ide> assertEquals("/resources/bar-11e16cf79faee7ac698c805cf28248d2.css?foo=bar&url=http://example.org", result); <ide> }); <ide> public void encodeUrlPreventStringOutOfBounds() throws Exception { <ide> MockHttpServletRequest request = new MockHttpServletRequest("GET", "/context-path/index"); <ide> request.setContextPath("/context-path"); <ide> request.setServletPath(""); <del> request.setAttribute(ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR, this.urlProvider); <ide> MockHttpServletResponse response = new MockHttpServletResponse(); <ide> <ide> this.filter.doFilter(request, response, (req, res) -> { <add> req.setAttribute(ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR, this.urlProvider); <ide> String result = ((HttpServletResponse) res).encodeURL("index?key=value"); <ide> assertEquals("index?key=value", result); <ide> }); <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceUrlProviderJavaConfigTests.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public class ResourceUrlProviderJavaConfigTests { <ide> @Before <ide> @SuppressWarnings("resource") <ide> public void setup() throws Exception { <del> this.filterChain = new MockFilterChain(this.servlet, new ResourceUrlEncodingFilter()); <del> <ide> AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); <ide> context.setServletContext(new MockServletContext()); <ide> context.register(WebConfig.class); <ide> public void setup() throws Exception { <ide> this.request.setContextPath("/myapp"); <ide> this.response = new MockHttpServletResponse(); <ide> <del> Object urlProvider = context.getBean(ResourceUrlProvider.class); <del> this.request.setAttribute(ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR, urlProvider); <add> this.filterChain = new MockFilterChain(this.servlet, <add> new ResourceUrlEncodingFilter(), <add> (request, response, chain) -> { <add> Object urlProvider = context.getBean(ResourceUrlProvider.class); <add> request.setAttribute(ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR, urlProvider); <add> chain.doFilter(request, response); <add> }); <ide> } <ide> <ide> @Test
3
Mixed
Python
remove outdated examples
db843735d3a94826784492709afa0d26129eddd6
<ide><path>examples/inventory_count/Instructions.md <del>An example of inventory counting using SpaCy.io NLP library. Meant to show how to instantiate Spacy's English class, and allow reusability by reloading the main module. <del> <del>In the future, a better implementation of this library would be to apply machine learning to each query and learn what to classify as the quantitative statement (55 kgs OF), vs the actual item of count (how likely is a preposition object to be the item of count if x,y,z qualifications appear in the statement). <del> <del> <ide><path>examples/inventory_count/inventory.py <del>class Inventory: <del> """ <del> Inventory class - a struct{} like feature to house inventory counts <del> across modules. <del> """ <del> originalQuery = None <del> item = "" <del> unit = "" <del> amount = "" <del> <del> def __init__(self, statement): <del> """ <del> Constructor - only takes in the original query/statement <del> :return: new Inventory object <del> """ <del> <del> self.originalQuery = statement <del> pass <del> <del> def __str__(self): <del> return str(self.amount) + ' ' + str(self.unit) + ' ' + str(self.item) <del> <del> def printInfo(self): <del> print '-------------Inventory Count------------' <del> print "Original Query: " + str(self.originalQuery) <del> print 'Amount: ' + str(self.amount) <del> print 'Unit: ' + str(self.unit) <del> print 'Item: ' + str(self.item) <del> print '----------------------------------------' <del> <del> def isValid(self): <del> if not self.item or not self.unit or not self.amount or not self.originalQuery: <del> return False <del> else: <del> return True <ide><path>examples/inventory_count/inventoryCount.py <del>from inventory import Inventory <del> <del> <del>def runTest(nlp): <del> testset = [] <del> testset += [nlp(u'6 lobster cakes')] <del> testset += [nlp(u'6 avacados')] <del> testset += [nlp(u'fifty five carrots')] <del> testset += [nlp(u'i have 55 carrots')] <del> testset += [nlp(u'i got me some 9 cabbages')] <del> testset += [nlp(u'i got 65 kgs of carrots')] <del> <del> result = [] <del> for doc in testset: <del> c = decodeInventoryEntry_level1(doc) <del> if not c.isValid(): <del> c = decodeInventoryEntry_level2(doc) <del> result.append(c) <del> <del> for i in result: <del> i.printInfo() <del> <del> <del>def decodeInventoryEntry_level1(document): <del> """ <del> Decodes a basic entry such as: '6 lobster cake' or '6' cakes <del> @param document : NLP Doc object <del> :return: Status if decoded correctly (true, false), and Inventory object <del> """ <del> count = Inventory(str(document)) <del> for token in document: <del> if token.pos_ == (u'NOUN' or u'NNS' or u'NN'): <del> item = str(token) <del> <del> for child in token.children: <del> if child.dep_ == u'compound' or child.dep_ == u'ad': <del> item = str(child) + str(item) <del> elif child.dep_ == u'nummod': <del> count.amount = str(child).strip() <del> for numerical_child in child.children: <del> # this isn't arithmetic rather than treating it such as a string <del> count.amount = str(numerical_child) + str(count.amount).strip() <del> else: <del> print "WARNING: unknown child: " + str(child) + ':'+str(child.dep_) <del> <del> count.item = item <del> count.unit = item <del> <del> return count <del> <del> <del>def decodeInventoryEntry_level2(document): <del> """ <del> Entry level 2, a more complicated parsing scheme that covers examples such as <del> 'i have 80 boxes of freshly baked pies' <del> <del> @document @param document : NLP Doc object <del> :return: Status if decoded correctly (true, false), and Inventory object- <del> """ <del> <del> count = Inventory(str(document)) <del> <del> for token in document: <del> # Look for a preposition object that is a noun (this is the item we are counting). <del> # If found, look at its' dependency (if a preposition that is not indicative of <del> # inventory location, the dependency of the preposition must be a noun <del> <del> if token.dep_ == (u'pobj' or u'meta') and token.pos_ == (u'NOUN' or u'NNS' or u'NN'): <del> item = '' <del> <del> # Go through all the token's children, these are possible adjectives and other add-ons <del> # this deals with cases such as 'hollow rounded waffle pancakes" <del> for i in token.children: <del> item += ' ' + str(i) <del> <del> item += ' ' + str(token) <del> count.item = item <del> <del> # Get the head of the item: <del> if token.head.dep_ != u'prep': <del> # Break out of the loop, this is a confusing entry <del> break <del> else: <del> amountUnit = token.head.head <del> count.unit = str(amountUnit) <del> <del> for inner in amountUnit.children: <del> if inner.pos_ == u'NUM': <del> count.amount += str(inner) <del> return count <del> <del> <ide><path>examples/inventory_count/main.py <del>import inventoryCount as mainModule <del>import os <del>from spacy.en import English <del> <del>if __name__ == '__main__': <del> """ <del> Main module for this example - loads the English main NLP class, <del> and keeps it in RAM while waiting for the user to re-run it. Allows the <del> developer to re-edit their module under testing without having <del> to wait as long to load the English class <del> """ <del> <del> # Set the NLP object here for the parameters you want to see, <del> # or just leave it blank and get all the opts <del> print "Loading English module... this will take a while." <del> nlp = English() <del> print "Done loading English module." <del> while True: <del> try: <del> reload(mainModule) <del> mainModule.runTest(nlp) <del> raw_input('================ To reload main module, press Enter ================') <del> <del> <del> except Exception, e: <del> print "Unexpected error: " + str(e) <del> continue <del> <del> <del> <ide><path>examples/matcher_example.py <del>from __future__ import unicode_literals, print_function <del> <del>import spacy.en <del>import spacy.matcher <del>from spacy.attrs import ORTH, TAG, LOWER, IS_ALPHA, FLAG63 <del> <del>import plac <del> <del> <del>def main(): <del> nlp = spacy.en.English() <del> example = u"I prefer Siri to Google Now. I'll google now to find out how the google now service works." <del> before = nlp(example) <del> print("Before") <del> for ent in before.ents: <del> print(ent.text, ent.label_, [w.tag_ for w in ent]) <del> # Output: <del> # Google ORG [u'NNP'] <del> # google ORG [u'VB'] <del> # google ORG [u'NNP'] <del> nlp.matcher.add( <del> "GoogleNow", # Entity ID: Not really used at the moment. <del> "PRODUCT", # Entity type: should be one of the types in the NER data <del> {"wiki_en": "Google_Now"}, # Arbitrary attributes. Currently unused. <del> [ # List of patterns that can be Surface Forms of the entity <del> <del> # This Surface Form matches "Google Now", verbatim <del> [ # Each Surface Form is a list of Token Specifiers. <del> { # This Token Specifier matches tokens whose orth field is "Google" <del> ORTH: "Google" <del> }, <del> { # This Token Specifier matches tokens whose orth field is "Now" <del> ORTH: "Now" <del> } <del> ], <del> [ # This Surface Form matches "google now", verbatim, and requires <del> # "google" to have the NNP tag. This helps prevent the pattern from <del> # matching cases like "I will google now to look up the time" <del> { <del> ORTH: "google", <del> TAG: "NNP" <del> }, <del> { <del> ORTH: "now" <del> } <del> ] <del> ] <del> ) <del> after = nlp(example) <del> print("After") <del> for ent in after.ents: <del> print(ent.text, ent.label_, [w.tag_ for w in ent]) <del> # Output <del> # Google Now PRODUCT [u'NNP', u'RB'] <del> # google ORG [u'VB'] <del> # google now PRODUCT [u'NNP', u'RB'] <del> # <del> # You can customize attribute values in the lexicon, and then refer to the <del> # new attributes in your Token Specifiers. <del> # This is particularly good for word-set membership. <del> # <del> australian_capitals = ['Brisbane', 'Sydney', 'Canberra', 'Melbourne', 'Hobart', <del> 'Darwin', 'Adelaide', 'Perth'] <del> # Internally, the tokenizer immediately maps each token to a pointer to a <del> # LexemeC struct. These structs hold various features, e.g. the integer IDs <del> # of the normalized string forms. <del> # For our purposes, the key attribute is a 64-bit integer, used as a bit field. <del> # spaCy currently only uses 12 of the bits for its built-in features, so <del> # the others are available for use. It's best to use the higher bits, as <del> # future versions of spaCy may add more flags. For instance, we might add <del> # a built-in IS_MONTH flag, taking up FLAG13. So, we bind our user-field to <del> # FLAG63 here. <del> is_australian_capital = FLAG63 <del> # Now we need to set the flag value. It's False on all tokens by default, <del> # so we just need to set it to True for the tokens we want. <del> # Here we iterate over the strings, and set it on only the literal matches. <del> for string in australian_capitals: <del> lexeme = nlp.vocab[string] <del> lexeme.set_flag(is_australian_capital, True) <del> print('Sydney', nlp.vocab[u'Sydney'].check_flag(is_australian_capital)) <del> print('sydney', nlp.vocab[u'sydney'].check_flag(is_australian_capital)) <del> # If we want case-insensitive matching, we have to be a little bit more <del> # round-about, as there's no case-insensitive index to the vocabulary. So <del> # we have to iterate over the vocabulary. <del> # We'll be looking up attribute IDs in this set a lot, so it's good to pre-build it <del> target_ids = {nlp.vocab.strings[s.lower()] for s in australian_capitals} <del> for lexeme in nlp.vocab: <del> if lexeme.lower in target_ids: <del> lexeme.set_flag(is_australian_capital, True) <del> print('Sydney', nlp.vocab[u'Sydney'].check_flag(is_australian_capital)) <del> print('sydney', nlp.vocab[u'sydney'].check_flag(is_australian_capital)) <del> print('SYDNEY', nlp.vocab[u'SYDNEY'].check_flag(is_australian_capital)) <del> # Output <del> # Sydney True <del> # sydney False <del> # Sydney True <del> # sydney True <del> # SYDNEY True <del> # <del> # The key thing to note here is that we're setting these attributes once, <del> # over the vocabulary --- and then reusing them at run-time. This means the <del> # amortized complexity of anything we do this way is going to be O(1). You <del> # can match over expressions that need to have sets with tens of thousands <del> # of values, e.g. "all the street names in Germany", and you'll still have <del> # O(1) complexity. Most regular expression algorithms don't scale well to <del> # this sort of problem. <del> # <del> # Now, let's use this in a pattern <del> nlp.matcher.add("AuCitySportsTeam", "ORG", {}, <del> [ <del> [ <del> {LOWER: "the"}, <del> {is_australian_capital: True}, <del> {TAG: "NNS"} <del> ], <del> [ <del> {LOWER: "the"}, <del> {is_australian_capital: True}, <del> {TAG: "NNPS"} <del> ], <del> [ <del> {LOWER: "the"}, <del> {IS_ALPHA: True}, # Allow a word in between, e.g. The Western Sydney <del> {is_australian_capital: True}, <del> {TAG: "NNS"} <del> ], <del> [ <del> {LOWER: "the"}, <del> {IS_ALPHA: True}, # Allow a word in between, e.g. The Western Sydney <del> {is_australian_capital: True}, <del> {TAG: "NNPS"} <del> ] <del> ]) <del> doc = nlp(u'The pattern should match the Brisbane Broncos and the South Darwin Spiders, but not the Colorado Boulders') <del> for ent in doc.ents: <del> print(ent.text, ent.label_) <del> # Output <del> # the Brisbane Broncos ORG <del> # the South Darwin Spiders ORG <del> <del> <del># Output <del># Before <del># Google ORG [u'NNP'] <del># google ORG [u'VB'] <del># google ORG [u'NNP'] <del># After <del># Google Now PRODUCT [u'NNP', u'RB'] <del># google ORG [u'VB'] <del># google now PRODUCT [u'NNP', u'RB'] <del># Sydney True <del># sydney False <del># Sydney True <del># sydney True <del># SYDNEY True <del># the Brisbane Broncos ORG <del># the South Darwin Spiders ORG <del> <del>if __name__ == '__main__': <del> main() <del> <ide><path>examples/twitter_filter.py <del># encoding: utf8 <del>from __future__ import unicode_literals, print_function <del>import plac <del>import codecs <del>import pathlib <del>import random <del> <del>import twython <del>import spacy.en <del> <del>import _handler <del> <del> <del>class Connection(twython.TwythonStreamer): <del> def __init__(self, keys_dir, nlp, query): <del> keys_dir = pathlib.Path(keys_dir) <del> read = lambda fn: (keys_dir / (fn + '.txt')).open().read().strip() <del> api_key = map(read, ['key', 'secret', 'token', 'token_secret']) <del> twython.TwythonStreamer.__init__(self, *api_key) <del> self.nlp = nlp <del> self.query = query <del> <del> def on_success(self, data): <del> _handler.handle_tweet(self.nlp, data, self.query) <del> if random.random() >= 0.1: <del> reload(_handler) <del> <del> <del>def main(keys_dir, term): <del> nlp = spacy.en.English() <del> twitter = Connection(keys_dir, nlp, term) <del> twitter.statuses.filter(track=term, language='en') <del> <del> <del>if __name__ == '__main__': <del> plac.call(main)
6
Python
Python
check decorator order
1ff5bd38a3c66084710eb315a5322692fd1fab2f
<ide><path>tests/test_tokenization_bert_generation.py <ide> def test_tokenization_base_hard_symbols(self): <ide> <ide> self.assertListEqual(original_tokenizer_encodings, self.big_tokenizer.encode(symbols)) <ide> <del> @slow <ide> @require_torch <add> @slow <ide> def test_torch_encode_plus_sent_to_model(self): <ide> import torch <ide> <ide><path>tests/test_tokenization_common.py <ide> def _check_no_pad_token_padding(self, tokenizer, sequences): <ide> # add pad_token_id to pass subsequent tests <ide> tokenizer.add_special_tokens({"pad_token": "<PAD>"}) <ide> <del> @slow <ide> @require_torch <add> @slow <ide> def test_torch_encode_plus_sent_to_model(self): <ide> import torch <ide> <ide> def test_torch_encode_plus_sent_to_model(self): <ide> # model(**encoded_sequence_fast) <ide> # model(**batch_encoded_sequence_fast) <ide> <del> @slow <ide> @require_tf <add> @slow <ide> def test_tf_encode_plus_sent_to_model(self): <ide> from transformers import TF_MODEL_MAPPING, TOKENIZER_MAPPING <ide> <ide> def test_tf_encode_plus_sent_to_model(self): <ide> model(batch_encoded_sequence) <ide> <ide> # TODO: Check if require_torch is the best to test for numpy here ... Maybe move to require_flax when available <del> @slow <ide> @require_torch <add> @slow <ide> def test_np_encode_plus_sent_to_model(self): <ide> from transformers import MODEL_MAPPING, TOKENIZER_MAPPING <ide> <ide><path>tests/test_tokenization_reformer.py <ide> def test_tokenization_base_hard_symbols(self): <ide> <ide> self.assertListEqual(original_tokenizer_encodings, self.big_tokenizer.encode(symbols)) <ide> <del> @slow <ide> @require_torch <add> @slow <ide> def test_torch_encode_plus_sent_to_model(self): <ide> import torch <ide> <ide><path>utils/check_repo.py <ide> def check_all_models_are_documented(): <ide> raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures)) <ide> <ide> <add>_re_decorator = re.compile(r"^\s*@(\S+)\s+$") <add> <add> <add>def check_decorator_order(filename): <add> """ Check that in the test file `filename` the slow decorator is always last.""" <add> with open(filename, "r", encoding="utf-8") as f: <add> lines = f.readlines() <add> decorator_before = None <add> errors = [] <add> for i, line in enumerate(lines): <add> search = _re_decorator.search(line) <add> if search is not None: <add> decorator_name = search.groups()[0] <add> if decorator_before is not None and decorator_name.startswith("parameterized"): <add> errors.append(i) <add> decorator_before = decorator_name <add> elif decorator_before is not None: <add> decorator_before = None <add> return errors <add> <add> <add>def check_all_decorator_order(): <add> """ Check that in all test files, the slow decorator is always last.""" <add> errors = [] <add> for fname in os.listdir(PATH_TO_TESTS): <add> if fname.endswith(".py"): <add> filename = os.path.join(PATH_TO_TESTS, fname) <add> new_errors = check_decorator_order(filename) <add> errors += [f"- {filename}, line {i}" for i in new_errors] <add> if len(errors) > 0: <add> msg = "\n".join(errors) <add> raise ValueError( <add> f"The parameterized decorator (and its variants) should always be first, but this is not the case in the following files:\n{msg}" <add> ) <add> <add> <ide> def check_repo_quality(): <ide> """ Check all models are properly tested and documented.""" <ide> print("Checking all models are properly tested.") <add> check_all_decorator_order() <ide> check_all_models_are_tested() <ide> print("Checking all models are properly documented.") <ide> check_all_models_are_documented()
4
Text
Text
fix useragent type error in readme.md
6faf0d18fb69704c82a70290a735dcfd6f143a64
<ide><path>packages/next/README.md <ide> Next.js provides `NextPage` type that can be used for pages in the `pages` direc <ide> import { NextPage } from 'next' <ide> <ide> interface Props { <del> userAgent: string <add> userAgent?: string <ide> } <ide> <ide> const Page: NextPage<Props> = ({ userAgent }) => ( <ide> import React from 'react' <ide> import { NextPageContext } from 'next' <ide> <ide> interface Props { <del> userAgent: string <add> userAgent?: string <ide> } <ide> <ide> export default class Page extends React.Component<Props> {
1
Python
Python
remove redundant reversal of eigenvalues order
be29802e9b6027c5959149b5357f8969effc3bef
<ide><path>numpy/linalg/linalg.py <ide> def svd(a, full_matrices=True, compute_uv=True, hermitian=False): <ide> return wrap(u), s, wrap(vt) <ide> else: <ide> s = eigvalsh(a) <del> s = s[..., ::-1] <ide> s = abs(s) <ide> return sort(s)[..., ::-1] <ide>
1
Java
Java
update todos for spr-11598
6e10f7c8cf8c3edf573e9f04541f691c499b1a43
<ide><path>spring-core/src/test/java/org/springframework/core/annotation/AnnotatedElementUtilsTests.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public void getAnnotationAttributesFavorsInheritedAnnotationsOverMoreLocallyDecl <ide> Transactional.class.getName()); <ide> assertNotNull("AnnotationAttributes for @Transactional on SubSubClassWithInheritedAnnotation", attributes); <ide> <del> // TODO [SPR-11475] Set expected to true. <add> // TODO [SPR-11598] Set expected to true. <ide> boolean expected = false; <ide> assertEquals("readOnly flag for SubSubClassWithInheritedAnnotation.", expected, attributes.getBoolean("readOnly")); <ide> } <ide> public void getAnnotationAttributesFavorsInheritedComposedAnnotationsOverMoreLoc <ide> assertNotNull("AnnotationAttributtes for @Transactional on SubSubClassWithInheritedComposedAnnotation.", <ide> attributes); <ide> <del> // TODO [SPR-11475] Set expected to true. <add> // TODO [SPR-11598] Set expected to true. <ide> boolean expected = false; <ide> assertEquals("readOnly flag for SubSubClassWithInheritedComposedAnnotation.", expected, <ide> attributes.getBoolean("readOnly"));
1
Ruby
Ruby
fix #has_secure_token documentation [ci skip]
673653d44c9bba69fc73209e6320dd88dbeaf75f
<ide><path>activerecord/lib/active_record/secure_token.rb <ide> module ClassMethods <ide> # SecureRandom::base58 is used to generate the 24-character unique token, so collisions are highly unlikely. <ide> # <ide> # Note that it's still possible to generate a race condition in the database in the same way that <del> # validates_presence_of can. You're encouraged to add a unique index in the database to deal with <del> # this even more unlikely scenario. <add> # <tt>validates_uniqueness_of</tt> can. You're encouraged to add a unique index in the database to deal <add> # with this even more unlikely scenario. <ide> def has_secure_token(attribute = :token) <ide> # Load securerandom only when has_secure_token is used. <ide> require 'active_support/core_ext/securerandom'
1
Text
Text
fix upgrading guide [ci skip]
51908718227f2cef80113d85a0fb9eb65ded3f4e
<ide><path>guides/source/upgrading_ruby_on_rails.md <ide> The following changes are meant for upgrading your application to Rails 4.0. <ide> <ide> ### Gemfile <ide> <del>Rails 4.0 removed the *group :assets* from Gemfile (now you can use only :test, :development and/or :production groups). So change your Gemfile from: <del>```ruby <del>group :assets do <del> gem 'sass-rails', '~> 4.0.0.beta1' <del> gem 'coffee-rails', '~> 4.0.0.beta1' <del> <del> # See https://github.com/sstephenson/execjs#readme for more supported runtimes <del> # gem 'therubyracer', platforms: :ruby <del> <del> gem 'uglifier', '>= 1.0.3' <del>end <del>``` <del>to: <del>```ruby <del>gem 'sass-rails', '~> 4.0.0.beta1' <del>gem 'coffee-rails', '~> 4.0.0.beta1' <del> <del># See https://github.com/sstephenson/execjs#readme for more supported runtimes <del># gem 'therubyracer', platforms: :ruby <del> <del>gem 'uglifier', '>= 1.0.3' <del>``` <del>**note:** don't removing the *group assets* from the Gemfile will cause your assets stop compiling <add>Rails 4.0 removed the `assets` group from Gemfile. You'd need to remove that line from your Gemfile when upgrading. <ide> <ide> ### vendor/plugins <ide>
1
Text
Text
fix typo in ipam doc
8059597722ac6fe42821fd9128e41887374e4b1e
<ide><path>libnetwork/docs/ipam.md <ide> On network creation, libnetwork will iterate the list and perform the following <ide> <ide> If the list of IPv4 configurations is empty, libnetwork will automatically add one empty `IpamConf` structure. This will cause libnetwork to request IPAM driver an IPv4 address pool of the driver's choice on the configured address space, if specified, or on the IPAM driver default address space otherwise. If the IPAM driver is not able to provide an address pool, network creation will fail. <ide> If the list of IPv6 configurations is empty, libnetwork will not take any action. <del>The data retrieved from the IPAM driver during the execution of point 1) to 3) will be stored in the network structure as a list of `IpamInfo` structures for IPv6 and for IPv6. <add>The data retrieved from the IPAM driver during the execution of point 1) to 3) will be stored in the network structure as a list of `IpamInfo` structures for IPv4 and a list for IPv6. <ide> <ide> On endpoint creation, libnetwork will iterate over the list of configs and perform the following operation: <ide>
1
Javascript
Javascript
add missing semicolon
217a9919c3adcde198774301aa082e5be8a6489d
<ide><path>src/effects.js <ide> function defaultDisplay( nodeName ) { <ide> // create a temp element and check it's default display, this <ide> // will ensure that the value returned is not a user-tampered <ide> // value. <del> elem = jQuery("<" + nodeName + ">").appendTo("body"), <add> elem = jQuery("<" + nodeName + ">").appendTo("body"); <ide> display = elem.css("display"); <ide> <ide> // Remove temp element
1
Python
Python
add persian language
bb6bd3d8aea5139d90b95cd0d3ac657ac1f49686
<ide><path>spacy/lang/fa/__init__.py <ide> <ide> class PersianDefaults(Language.Defaults): <ide> lex_attr_getters = dict(Language.Defaults.lex_attr_getters) <del> lex_attr_getters[LANG] = lambda text: 'fa' # ISO code <add> lex_attr_getters[LANG] = lambda text: 'fa' <ide> lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM], BASE_NORMS) <ide> tokenizer_exceptions = update_exc(BASE_EXCEPTIONS) <ide> stop_words = STOP_WORDS <ide><path>spacy/lang/fa/examples.py <ide> """ <ide> Example sentences to test spaCy and its language models. <ide> <del>>>> from spacy.lang.en.examples import sentences <add>>>> from spacy.lang.fa.examples import sentences <ide> >>> docs = nlp.pipe(sentences) <ide> """ <ide> <ide><path>spacy/lang/fa/stop_words.py <ide> from __future__ import unicode_literals <ide> <ide> <del># Stop words <del> <ide> STOP_WORDS = set(""" <ide> آباد آره آری آسانی آمد آمده آن آنان آنجا آنها آن‌ها آنچه آنکه آورد آورده آیا آید <del>ات اثر از است استفاده اش اطلاعند الاسف البته الظاهر ام اما امروز امسال اند انکه او اول اکنون اگر الواقع ای ایشان ایم این اینک اینکه <add>ات اثر از است استفاده اش اطلاعند الاسف البته الظاهر ام اما امروز امسال اند انکه او اول اکنون <add>اگر الواقع ای ایشان ایم این اینک اینکه <ide> <del>ب با بااین بار بارة باره بارها باز بازهم بازی باش باشد باشم باشند باشی باشید باشیم بالا بالاخره بالاخص بالاست بالای بالطبع بالعکس باوجودی باورند باید بتدریج بتوان بتواند بتوانی بتوانیم بجز بخش بخشه بخشی بخصوص بخواه بخواهد بخواهم بخواهند بخواهی بخواهید بخواهیم بخوبی بد بدان بدانجا بدانها بدون بدین بدینجا بر برآن برآنند برا برابر براحتی براساس براستی برای برایت برایش برایشان برایم برایمان برخوردار برخوردارند برخی برداری برداشتن بردن برعکس برنامه بروز بروشنی بزرگ بزودی بس بسا بسادگی بسته بسختی بسوی بسی بسیار بسیاری بشدت بطور بطوری بعد بعدا بعدازظهر بعدها بعری بعضا بعضی بعضیهایشان بعضی‌ها بعلاوه بعید بفهمی بلافاصله بله بلکه بلی بنابراین بندی به بهت بهتر بهترین بهش بود بودم بودن بودند بوده بودی بودید بودیم بویژه بپا بکار بکن بکند بکنم بکنند بکنی بکنید بکنیم بگو بگوید بگویم بگویند بگویی بگویید بگوییم بگیر بگیرد بگیرم بگیرند بگیری بگیرید بگیریم بی بیا بیاب بیابد بیابم بیابند بیابی بیابید بیابیم بیاور بیاورد بیاورم بیاورند بیاوری بیاورید بیاوریم بیاید بیایم بیایند بیایی بیایید بیاییم بیرون بیست بیش بیشتر بیشتری بین بیگمان <add>ب با بااین بار بارة باره بارها باز بازهم بازی باش باشد باشم باشند باشی باشید باشیم بالا بالاخره <add>بالاخص بالاست بالای بالطبع بالعکس باوجودی باورند باید بتدریج بتوان بتواند بتوانی بتوانیم بجز بخش بخشه بخشی بخصوص بخواه <add>بخواهد بخواهم بخواهند بخواهی بخواهید بخواهیم بخوبی بد بدان بدانجا بدانها بدون بدین بدینجا بر برآن برآنند برا برابر <add>براحتی براساس براستی برای برایت برایش برایشان برایم برایمان برخوردار برخوردارند برخی برداری برداشتن بردن برعکس برنامه <add>بروز بروشنی بزرگ بزودی بس بسا بسادگی بسته بسختی بسوی بسی بسیار بسیاری بشدت بطور بطوری بعد بعدا بعدازظهر بعدها بعری <add>بعضا بعضی بعضیهایشان بعضی‌ها بعلاوه بعید بفهمی بلافاصله بله بلکه بلی بنابراین بندی به بهت بهتر بهترین بهش بود بودم بودن <add>بودند بوده بودی بودید بودیم بویژه بپا بکار بکن بکند بکنم بکنند بکنی بکنید بکنیم بگو بگوید بگویم بگویند بگویی بگویید <add>بگوییم بگیر بگیرد بگیرم بگیرند بگیری بگیرید بگیریم بی بیا بیاب بیابد بیابم بیابند بیابی بیابید بیابیم بیاور بیاورد <add>بیاورم بیاورند بیاوری بیاورید بیاوریم بیاید بیایم بیایند بیایی بیایید بیاییم بیرون بیست بیش بیشتر بیشتری بین بیگمان <ide> <del>پ پا پارسال پارسایانه پاره‌ای پاعین پایین پدرانه پدیده پرسان پروردگارا پریروز پس پشت پشتوانه پشیمونی پنج پهن پی پیدا پیداست پیرامون پیش پیشاپیش پیشتر پیوسته <add>پ پا پارسال پارسایانه پاره‌ای پاعین پایین پدرانه پدیده پرسان پروردگارا پریروز پس پشت پشتوانه پشیمونی پنج پهن پی پیدا <add>پیداست پیرامون پیش پیشاپیش پیشتر پیوسته <ide> <del>ت تا تازه تازگی تان تاکنون تحت تحریم تدریج تر ترتیب تردید ترند ترین تصریحا تعدادی تعمدا تفاوتند تقریبا تک تلویحا تمام تماما تمامشان تمامی تند تنها تو توؤما تواند توانست توانستم توانستن توانستند توانسته توانستی توانستیم توانم توانند توانی توانید توانیم توسط تول توی <add>ت تا تازه تازگی تان تاکنون تحت تحریم تدریج تر ترتیب تردید ترند ترین تصریحا تعدادی تعمدا تفاوتند تقریبا تک تلویحا تمام <add>تماما تمامشان تمامی تند تنها تو توؤما تواند توانست توانستم توانستن توانستند توانسته توانستی توانستیم توانم توانند توانی <add>توانید توانیم توسط تول توی <ide> <del>ث ثالثا ثانی ثانیا <add>ث ثالثا ثانی ثانیا <ide> <ide> ج جا جای جایی جدا جداگانه جدید جدیدا جریان جز جلو جلوگیری جلوی جمع جمعا جمعی جنابعالی جناح جنس جهت جور جوری <ide> <del>چ چاله چاپلوسانه چت چته چرا چشم چطور چقدر چنان چنانچه چنانکه چند چندان چنده چندین چنین چه چهار چو چون چکار چگونه چی چیز چیزهاست چیزی چیزیست چیست چیه <add>چ چاله چاپلوسانه چت چته چرا چشم چطور چقدر چنان چنانچه چنانکه چند چندان چنده چندین چنین چه چهار چو چون چکار چگونه چی چیز <add>چیزهاست چیزی چیزیست چیست چیه <ide> <del>ح حاشیه‌ حاشیه‌ای حاضر حاضرم حال حالا حاکیست حتما حتی حداقل حداکثر حدود حدودا حسابگرانه حسابی حضرتعالی حق حقیرانه حول حکما <add>ح حاشیه‌ حاشیه‌ای حاضر حاضرم حال حالا حاکیست حتما حتی حداقل حداکثر حدود حدودا حسابگرانه حسابی حضرتعالی حق حقیرانه حول <add>حکما <ide> <del>خ خارج خالصانه خب خداحافظ خداست خدمات خسته‌ای خصوصا خلاصه خواست خواستم خواستن خواستند خواسته خواستی خواستید خواستیم خواهد خواهم خواهند خواهی خواهید خواهیم خوب خوبی خود خودبه خودت خودتان خودتو خودش خودشان خودم خودمان خودمو خودی خوش خوشبختانه خویش خویشتن خویشتنم خیاه خیر خیره خیلی <add>خ خارج خالصانه خب خداحافظ خداست خدمات خسته‌ای خصوصا خلاصه خواست خواستم خواستن خواستند خواسته خواستی خواستید خواستیم <add>خواهد خواهم خواهند خواهی خواهید خواهیم خوب خوبی خود خودبه خودت خودتان خودتو خودش خودشان خودم خودمان خودمو خودی خوش <add>خوشبختانه خویش خویشتن خویشتنم خیاه خیر خیره خیلی <ide> <del>د دا داام دااما داخل داد دادم دادن دادند داده دادی دادید دادیم دار داراست دارد دارم دارند داری دارید داریم داشت داشتم داشتن داشتند داشته داشتی داشتید داشتیم دامم دانست دانند دایم دایما در دراین درباره درحالی درحالیکه درست درسته درشتی درصورتی درعین درمجموع درواقع درون درپی دریغ دریغا دسته دشمنیم دقیقا دلخواه دم دنبال ده دهد دهم دهند دهی دهید دهیم دو دوباره دوم دیده دیر دیرت دیرم دیروز دیشب دیوی دیگر دیگران دیگری دیگه <add>د دا داام دااما داخل داد دادم دادن دادند داده دادی دادید دادیم دار داراست دارد دارم دارند داری دارید داریم داشت داشتم <add>داشتن داشتند داشته داشتی داشتید داشتیم دامم دانست دانند دایم دایما در دراین درباره درحالی درحالیکه درست درسته درشتی <add>درصورتی درعین درمجموع درواقع درون درپی دریغ دریغا دسته دشمنیم دقیقا دلخواه دم دنبال ده دهد دهم دهند دهی دهید دهیم دو <add>دوباره دوم دیده دیر دیرت دیرم دیروز دیشب دیوی دیگر دیگران دیگری دیگه <ide> <ide> ذ ذاتا ذلک ذیل <ide> <del>ر را راجع راحت راسا راست راستی راه رسما رسید رشته رغم رفت رفتارهاست رفته رنجند رهگشاست رو رواست روب روبروست روز روزانه روزه روزهای روزه‌ای روش روشنی روی رویش ریزی <add>ر را راجع راحت راسا راست راستی راه رسما رسید رشته رغم رفت رفتارهاست رفته رنجند رهگشاست رو رواست روب روبروست روز روزانه <add>روزه روزهای روزه‌ای روش روشنی روی رویش ریزی <ide> <ide> ز زدن زده زشتکارانند زمان زمانی زمینه زنند زهی زود زودتر زودی زیاد زیاده زیر زیرا <ide> <del>س سابق ساختن ساخته ساده سادگی سازی سالانه سالته سالم‌تر ساله سالهاست سالها سالیانه سایر ست سخت سخته سر سراسر سرانجام سراپا سرعت سری سریع سریعا سعی سمت سه سهوا سوم سوی سپس سیاه <add>س سابق ساختن ساخته ساده سادگی سازی سالانه سالته سالم‌تر ساله سالهاست سالها سالیانه سایر ست سخت سخته سر سراسر سرانجام <add>سراپا سرعت سری سریع سریعا سعی سمت سه سهوا سوم سوی سپس سیاه <ide> <del>ش شان شاهدند شاهدیم شاید شبهاست شخصا شد شدت شدم شدن شدند شده شدی شدید شدیدا شدیم شش شما شماری شماست شمایند شناسی شود شوراست شوم شوند شونده شوی شوید شویم شیرین شیرینه <add>ش شان شاهدند شاهدیم شاید شبهاست شخصا شد شدت شدم شدن شدند شده شدی شدید شدیدا شدیم شش شما شماری شماست شمایند شناسی شود <add>شوراست شوم شوند شونده شوی شوید شویم شیرین شیرینه <ide> <ide> ص صددرصد صرفا صریحا صندوق صورت صورتی <ide> <ide> <ide> ظ ظاهرا <ide> <del>ع عاجزانه عاقبت عبارتند عجب عجولانه عدم عرفانی عقب علاوه علت علنا علی علیه عمدا عمدتا عمده عمل عملا عملی عموم عموما عنقریب عنوان عینا <add>ع عاجزانه عاقبت عبارتند عجب عجولانه عدم عرفانی عقب علاوه علت علنا علی علیه عمدا عمدتا عمده عمل عملا عملی عموم عموما <add>عنقریب عنوان عینا <ide> <ide> غ غالبا غیر غیرقانونی <ide> <ide> ف فاقد فبها فر فردا فعلا فقط فلان فلذا فوق فکر فی فی‌الواقع <ide> <ide> ق قاالند قابل قاطبه قاطعانه قاعدتا قانونا قبل قبلا قبلند قد قدر قدری قراردادن قصد قطعا <ide> <del>ک کارند کاش کاشکی کامل کاملا کتبا کجا کجاست کدام کرات کرد کردم کردن کردند کرده کردی کردید کردیم کس کسانی کسی کشیدن کل کلا کلی کلیشه کلیه کم کمااینکه کماکان کمتر کمتره کمتری کمی کن کنار کنارش کنان کنایه‌ای کند کنم کنند کننده کنون کنونی کنی کنید کنیم که کو کی كي <add>ک کارند کاش کاشکی کامل کاملا کتبا کجا کجاست کدام کرات کرد کردم کردن کردند کرده کردی کردید کردیم کس کسانی کسی کشیدن کل <add>کلا کلی کلیشه کلیه کم کمااینکه کماکان کمتر کمتره کمتری کمی کن کنار کنارش کنان کنایه‌ای کند کنم کنند کننده کنون کنونی <add>کنی کنید کنیم که کو کی كي <ide> <del>گ گاه گاهی گذاری گذاشتن گذاشته گذشته گردد گرفت گرفتارند گرفتم گرفتن گرفتند گرفته گرفتی گرفتید گرفتیم گرمی گروهی گرچه گفت گفتم گفتن گفتند گفته گفتی گفتید گفتیم گه گهگاه گو گونه گویا گویان گوید گویم گویند گویی گویید گوییم گیرد گیرم گیرند گیری گیرید گیریم <add>گ گاه گاهی گذاری گذاشتن گذاشته گذشته گردد گرفت گرفتارند گرفتم گرفتن گرفتند گرفته گرفتی گرفتید گرفتیم گرمی گروهی گرچه <add>گفت گفتم گفتن گفتند گفته گفتی گفتید گفتیم گه گهگاه گو گونه گویا گویان گوید گویم گویند گویی گویید گوییم گیرد گیرم گیرند <add>گیری گیرید گیریم <ide> <ide> ل لا لااقل لاجرم لب لذا لزوما لطفا لیکن لکن <ide> <del>م ما مادامی ماست مامان مان مانند مبادا متاسفانه متعاقبا متفاوتند مثل مثلا مجبورند مجددا مجموع مجموعا محتاجند محکم محکم‌تر مخالفند مختلف مخصوصا مدام مدت مدتهاست مدتی مذهبی مرا مراتب مرتب مردانه مردم مرسی مستحضرید مستقیما مستند مسلما مشت مشترکا مشغولند مطمانا مطمانم مطمینا مع معتقدم معتقدند معتقدیم معدود معذوریم معلومه معمولا معمولی مغرضانه مفیدند مقابل مقدار مقصرند مقصری ممکن من منتهی منطقی مواجهند موارد موجودند مورد موقتا مکرر مکررا مگر می مي میان میزان میلیارد میلیون می‌رسد می‌رود می‌شود می‌کنیم <add>م ما مادامی ماست مامان مان مانند مبادا متاسفانه متعاقبا متفاوتند مثل مثلا مجبورند مجددا مجموع مجموعا محتاجند محکم <add>محکم‌تر مخالفند مختلف مخصوصا مدام مدت مدتهاست مدتی مذهبی مرا مراتب مرتب مردانه مردم مرسی مستحضرید مستقیما مستند مسلما <add>مشت مشترکا مشغولند مطمانا مطمانم مطمینا مع معتقدم معتقدند معتقدیم معدود معذوریم معلومه معمولا معمولی مغرضانه مفیدند <add>مقابل مقدار مقصرند مقصری ممکن من منتهی منطقی مواجهند موارد موجودند مورد موقتا مکرر مکررا مگر می مي میان میزان میلیارد <add>میلیون می‌رسد می‌رود می‌شود می‌کنیم <ide> <del>ن ناامید ناخواسته ناراضی ناشی نام ناچار ناگاه ناگزیر ناگهان ناگهانی نباید نبش نبود نخست نخستین نخواهد نخواهم نخواهند نخواهی نخواهید نخواهیم نخودی ندارد ندارم ندارند نداری ندارید نداریم نداشت نداشتم نداشتند نداشته نداشتی نداشتید نداشتیم نزد نزدیک نسبتا نشان نشده نظیر نفرند نفهمی نماید نمی نمی‌شود نه نهایت نهایتا نوع نوعا نوعی نکرده نگاه نیازمندانه نیازمندند نیز نیست نیمی <add>ن ناامید ناخواسته ناراضی ناشی نام ناچار ناگاه ناگزیر ناگهان ناگهانی نباید نبش نبود نخست نخستین نخواهد نخواهم نخواهند <add>نخواهی نخواهید نخواهیم نخودی ندارد ندارم ندارند نداری ندارید نداریم نداشت نداشتم نداشتند نداشته نداشتی نداشتید نداشتیم <add>نزد نزدیک نسبتا نشان نشده نظیر نفرند نفهمی نماید نمی نمی‌شود نه نهایت نهایتا نوع نوعا نوعی نکرده نگاه نیازمندانه <add>نیازمندند نیز نیست نیمی <ide> <ide> و وابسته واقع واقعا واقعی واقفند وای وجه وجود وحشت وسط وضع وضوح وقتی وقتیکه ولی وگرنه وگو وی ویا ویژه <ide> <del>ه ها هاست های هایی هبچ هدف هر هرحال هرچند هرچه هرکس هرگاه هرگز هزار هست هستم هستند هستی هستید هستیم هفت هق هم همان همانند همانها همدیگر همزمان همه همه‌اش همواره همچنان همچنین همچون همچین همگان همگی همیشه همین هنوز هنگام هنگامی هوی هی هیچ هیچکدام هیچکس هیچگاه هیچگونه هیچی <add>ه ها هاست های هایی هبچ هدف هر هرحال هرچند هرچه هرکس هرگاه هرگز هزار هست هستم هستند هستی هستید هستیم هفت هق هم همان <add>همانند همانها همدیگر همزمان همه همه‌اش همواره همچنان همچنین همچون همچین همگان همگی همیشه همین هنوز هنگام هنگامی هوی هی <add>هیچ هیچکدام هیچکس هیچگاه هیچگونه هیچی <ide> <del>ی یا یابد یابم یابند یابی یابید یابیم یارب یافت یافتم یافتن یافته یافتی یافتید یافتیم یعنی یقینا یواش یک یکدیگر یکریز یکسال یکی یکي <add>ی یا یابد یابم یابند یابی یابید یابیم یارب یافت یافتم یافتن یافته یافتی یافتید یافتیم یعنی یقینا یواش یک یکدیگر یکریز <add>یکسال یکی یکي <ide> """.split())
3
Ruby
Ruby
extract common word "for" in `reason`
9ef52080e37091467b477e3eb79dc9c9fb495591
<ide><path>Library/Homebrew/dev-cmd/bottle.rb <ide> def setup_tar_and_args!(args) <ide> return default_tar_args <ide> end <ide> <del> ensure_formula_installed!(gnu_tar, reason: "for bottling") <add> ensure_formula_installed!(gnu_tar, reason: "bottling") <ide> <ide> ["#{gnu_tar.opt_bin}/gtar", gnutar_args].freeze <ide> end <ide><path>Library/Homebrew/dev-cmd/bump.rb <ide> def bump <ide> unless Utils::Curl.curl_supports_tls13? <ide> begin <ide> unless Pathname.new(ENV["HOMEBREW_BREWED_CURL_PATH"]).exist? <del> ensure_formula_installed!("curl", reason: "for Repology queries") <add> ensure_formula_installed!("curl", reason: "Repology queries") <ide> end <ide> rescue FormulaUnavailableError <ide> opoo "A `curl` with TLS 1.3 support is required for Repology queries." <ide><path>Library/Homebrew/dev-cmd/cat.rb <ide> def cat <ide> ENV["BAT_CONFIG_PATH"] = Homebrew::EnvConfig.bat_config_path <ide> ensure_formula_installed!( <ide> "bat", <del> reason: "for displaying <formula>/<cask> source", <add> reason: "displaying <formula>/<cask> source", <ide> # The user might want to capture the output of `brew cat ...` <ide> # Redirect stdout to stderr <ide> output_to_stderr: true, <ide><path>Library/Homebrew/dev-cmd/tests.rb <ide> def run_buildpulse <ide> <ide> with_env(HOMEBREW_NO_AUTO_UPDATE: "1", HOMEBREW_NO_BOOTSNAP: "1") do <ide> ensure_formula_installed!("buildpulse-test-reporter", <del> reason: "for reporting test flakiness") <add> reason: "reporting test flakiness") <ide> end <ide> <ide> ENV["BUILDPULSE_ACCESS_KEY_ID"] = ENV["HOMEBREW_BUILDPULSE_ACCESS_KEY_ID"] <ide><path>Library/Homebrew/github_packages.rb <ide> def upload_bottles(bottles_hash, keep_old:, dry_run:, warn_on_error:) <ide> raise UsageError, "HOMEBREW_GITHUB_PACKAGES_USER is unset." if user.blank? <ide> raise UsageError, "HOMEBREW_GITHUB_PACKAGES_TOKEN is unset." if token.blank? <ide> <del> skopeo = ensure_executable!("skopeo", reason: "for upload") <add> skopeo = ensure_executable!("skopeo", reason: "upload") <ide> <ide> require "json_schemer" <ide> <ide><path>Library/Homebrew/style.rb <ide> def shell_scripts <ide> def shellcheck <ide> # Always use the latest brewed shellcheck <ide> ensure_formula_installed!("shellcheck", latest: true, <del> reason: "for shell style checks").opt_bin/"shellcheck" <add> reason: "shell style checks").opt_bin/"shellcheck" <ide> end <ide> <ide> def shfmt <ide> # Always use the latest brewed shfmt <ide> ensure_formula_installed!("shfmt", latest: true, <del> reason: "to format shell scripts") <add> reason: "formatting shell scripts") <ide> HOMEBREW_LIBRARY/"Homebrew/utils/shfmt.sh" <ide> end <ide> <ide><path>Library/Homebrew/utils.rb <ide> def ensure_formula_installed!(formula_or_name, latest: false, reason: "", <ide> Formula[formula_or_name] <ide> end <ide> <del> reason = " #{reason}" if reason.present? # add a whitespace <add> reason = " for #{reason}" if reason.present? <ide> <ide> unless formula.any_version_installed? <ide> ohai "Installing `#{formula.name}`#{reason}..."
7
Ruby
Ruby
remove duplicate 'select' database statement
ec981aa1f05983754d661723e7d910ed4e1d4b28
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb <ide> def subquery_for(key, select) <ide> <ide> # Returns an ActiveRecord::Result instance. <ide> def select(sql, name = nil, binds = []) <add> exec_query(sql, name, binds) <ide> end <del> undef_method :select <add> <ide> <ide> # Returns the last auto-generated ID from the affected table. <ide> def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) <ide><path>activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb <ide> def exec_query(sql, name = 'SQL', binds = []) <ide> <ide> alias exec_without_stmt exec_query <ide> <del> # Returns an ActiveRecord::Result instance. <del> def select(sql, name = nil, binds = []) <del> exec_query(sql, name) <del> end <del> <ide> def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) <ide> super <ide> id_value || @connection.last_id <ide><path>activerecord/lib/active_record/connection_adapters/mysql_adapter.rb <ide> def configure_connection <ide> <ide> def select(sql, name = nil, binds = []) <ide> @connection.query_with_result = true <del> rows = exec_query(sql, name, binds) <add> rows = super <ide> @connection.more_results && @connection.next_result # invoking stored procedures with CLIENT_MULTI_RESULTS requires this to tidy up else connection will be dropped <ide> rows <ide> end <ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb <ide> def last_insert_id_result(sequence_name) #:nodoc: <ide> exec_query("SELECT currval('#{sequence_name}')", 'SQL') <ide> end <ide> <del> # Executes a SELECT query and returns the results, performing any data type <del> # conversions that are required to be performed here instead of in PostgreSQLColumn. <del> def select(sql, name = nil, binds = []) <del> exec_query(sql, name, binds) <del> end <del> <ide> # Returns the list of a table's column names, data types, and default values. <ide> # <ide> # The underlying query is roughly: <ide><path>activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb <ide> def initialize_type_map(m) <ide> register_class_with_limit m, %r(char)i, SQLite3String <ide> end <ide> <del> def select(sql, name = nil, binds = []) #:nodoc: <del> exec_query(sql, name, binds) <del> end <del> <ide> def table_structure(table_name) <ide> structure = exec_query("PRAGMA table_info(#{quote_table_name(table_name)})", 'SCHEMA').to_hash <ide> raise(ActiveRecord::StatementInvalid, "Could not find table '#{table_name}'") if structure.empty?
5
Java
Java
fix uri construction in undertowserverhttprequest
141e04aa0f43d221aa0a80569df70301fe294304
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/UndertowServerHttpRequest.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 Undertow {@link HttpServerExchange}. <ide> public UndertowServerHttpRequest(HttpServerExchange exchange, DataBufferFactory <ide> private static URI initUri(HttpServerExchange exchange) { <ide> Assert.notNull(exchange, "HttpServerExchange is required."); <ide> try { <add> String query = exchange.getQueryString(); <ide> return new URI(exchange.getRequestScheme(), null, <ide> exchange.getHostName(), exchange.getHostPort(), <del> exchange.getRequestURI(), exchange.getQueryString(), null); <add> exchange.getRequestURI(), StringUtils.hasText(query) ? query : null, null); <ide> } <ide> catch (URISyntaxException ex) { <ide> throw new IllegalStateException("Could not get URI: " + ex.getMessage(), ex);
1
Python
Python
use kombu.async.timer directly
75e5acca9481cc972d48493b39bc0812181037be
<ide><path>celery/concurrency/eventlet.py <ide> import warnings <ide> warnings.warn(RuntimeWarning(W_RACE % side)) <ide> <add>from kombu.async import timer as _timer <add> <ide> <ide> from celery import signals <del>from celery.utils import timer2 <ide> <ide> from . import base <ide> <ide> def apply_target(target, args=(), kwargs={}, callback=None, <ide> pid=getpid()) <ide> <ide> <del>class Schedule(timer2.Schedule): <add>class Timer(_timer.Timer): <ide> <ide> def __init__(self, *args, **kwargs): <ide> from eventlet.greenthread import spawn_after <ide> from greenlet import GreenletExit <del> super(Schedule, self).__init__(*args, **kwargs) <add> super(Timer, self).__init__(*args, **kwargs) <ide> <ide> self.GreenletExit = GreenletExit <ide> self._spawn_after = spawn_after <ide> def clear(self): <ide> except (KeyError, self.GreenletExit): <ide> pass <ide> <del> @property <del> def queue(self): <del> return self._queue <del> <del> <del>class Timer(timer2.Timer): <del> Schedule = Schedule <del> <del> def ensure_started(self): <del> pass <del> <del> def stop(self): <del> self.schedule.clear() <del> <ide> def cancel(self, tref): <ide> try: <ide> tref.cancel() <del> except self.schedule.GreenletExit: <add> except self.GreenletExit: <ide> pass <ide> <del> def start(self): <del> pass <add> @property <add> def queue(self): <add> return self._queue <ide> <ide> <ide> class TaskPool(base.BasePool): <ide><path>celery/concurrency/gevent.py <ide> except ImportError: # pragma: no cover <ide> Timeout = None # noqa <ide> <del>from celery.utils import timer2 <add>from kombu.async import timer as _timer <ide> <ide> from .base import apply_target, BasePool <ide> <ide> def apply_timeout(target, args=(), kwargs={}, callback=None, <ide> return timeout_callback(False, timeout) <ide> <ide> <del>class Schedule(timer2.Schedule): <add>class Timer(_timer.Timer): <ide> <ide> def __init__(self, *args, **kwargs): <ide> from gevent.greenlet import Greenlet, GreenletExit <ide> class _Greenlet(Greenlet): <ide> <ide> self._Greenlet = _Greenlet <ide> self._GreenletExit = GreenletExit <del> super(Schedule, self).__init__(*args, **kwargs) <add> super(Timer, self).__init__(*args, **kwargs) <ide> self._queue = set() <ide> <ide> def _enter(self, eta, priority, entry): <ide> def queue(self): <ide> return self._queue <ide> <ide> <del>class Timer(timer2.Timer): <del> Schedule = Schedule <del> <del> def ensure_started(self): <del> pass <del> <del> def stop(self): <del> self.schedule.clear() <del> <del> def start(self): <del> pass <del> <del> <ide> class TaskPool(BasePool): <ide> Timer = Timer <ide>
2
Javascript
Javascript
remove isoldie check in tests
962c38b2a6780fb89dc66d3f2d5ed341d19a22b2
<ide><path>test/specs/__helpers.js <ide> axios = require('../../index'); <ide> jasmine.DEFAULT_TIMEOUT_INTERVAL = 20000; <ide> jasmine.getEnv().defaultTimeoutInterval = 20000; <ide> <del>// Is this an old version of IE that lacks standard objects like DataView, ArrayBuffer, FormData, etc. <del>isOldIE = /MSIE (8|9)\.0/.test(navigator.userAgent); <del> <ide> // Get Ajax request using an increasing timeout to retry <ide> getAjaxRequest = (function () { <ide> var attempts = 0;
1
PHP
PHP
trim exception message in database manager
a6bb5f26a3d72a823166cb816bfa45afcb10fb19
<ide><path>laravel/database/manager.php <ide> public static function connection($connection = null) <ide> <ide> if (is_null($config)) <ide> { <del> throw new \OutOfBoundsException("Database connection is not defined for connection [$connection]."); <add> throw new \OutOfBoundsException("Connection is not defined for [$connection]."); <ide> } <ide> <ide> static::$connections[$connection] = new Connection(static::connect($config), $config); <ide> public static function __callStatic($method, $parameters) <ide> return call_user_func_array(array(static::connection(), $method), $parameters); <ide> } <ide> <del>} <add>} <ide>\ No newline at end of file
1