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
Javascript
Javascript
return all morph targets
015573fc37d2e306873a26b6f442bc62591711af
<ide><path>examples/js/loaders/FBXLoader.js <ide> THREE.FBXLoader = ( function () { <ide> <ide> } <ide> <del> console.log( fbxTree ); <add> // console.log( fbxTree ); <ide> <ide> var textureLoader = new THREE.TextureLoader( this.manager ).setPath( resourceDirectory ).setCrossOrigin( this.crossOrigin ); <ide> <ide> THREE.FBXLoader = ( function () { <ide> <ide> for ( var i = 0; i < relationships.children.length; i ++ ) { <ide> <del> if ( i === 8 ) { <del> <del> console.warn( 'FBXLoader: maximum of 8 morph targets supported. Ignoring additional targets.' ); <del> <del> break; <del> <del> } <del> <ide> var child = relationships.children[ i ]; <ide> <ide> var morphTargetNode = deformerNodes[ child.ID ]; <ide> THREE.FBXLoader = ( function () { <ide> <ide> } ); <ide> <del> console.log('rawMorphTarget', rawMorphTarget); <del> <ide> rawMorphTargets.push( rawMorphTarget ); <ide> <ide> } <ide> THREE.FBXLoader = ( function () { <ide> <ide> } ); <ide> <del> console.log('rawTracks', rawTracks.morphName); <del> <ide> var morphNum = sceneGraph.getObjectByName( rawTracks.modelName ).morphTargetDictionary[ rawTracks.morphName ]; <ide> <ide> return new THREE.NumberKeyframeTrack( rawTracks.modelName + '.morphTargetInfluences[' + morphNum + ']', curves.times, values ); <ide> THREE.FBXLoader = ( function () { <ide> parse: function ( text ) { <ide> <ide> this.currentIndent = 0; <del> console.log("FBXTree: ", FBXTree); <add> <ide> this.allNodes = new FBXTree(); <ide> this.nodeStack = []; <ide> this.currentProp = [];
1
PHP
PHP
improve console parser. add tests
8c21f3ca3faf66a7f75d0ec40d4a34d9bca0e9c0
<ide><path>src/Illuminate/Console/Parser.php <ide> public static function parse($expression) <ide> throw new InvalidArgumentException('Console command definition is empty.'); <ide> } <ide> <del> $tokens = array_values(array_filter( <del> array_map('trim', explode(' ', $expression)) <del> )); <add> preg_match('/.*?\s/', $expression, $matches); <add> <add> if (isset($matches[0])) { <add> $name = trim($matches[0]); <add> } else { <add> throw new InvalidArgumentException('Unable to determine command name from signature.'); <add> } <add> <add> preg_match_all('/\{.*?\}/', $expression, $matches); <add> <add> $tokens = isset($matches[0]) ? $matches[0] : []; <ide> <ide> return [ <del> array_shift($tokens), static::arguments($tokens), static::options($tokens), <add> $name, static::arguments($tokens), static::options($tokens), <ide> ]; <ide> } <ide> <ide> public static function parse($expression) <ide> */ <ide> protected static function arguments(array $tokens) <ide> { <del> return array_filter(array_map(function ($token) { <add> return array_values(array_filter(array_map(function ($token) { <ide> if (starts_with($token, '{') && !starts_with($token, '{--')) { <ide> return static::parseArgument(trim($token, '{}')); <ide> } <del> }, $tokens)); <add> }, $tokens))); <ide> } <ide> <ide> /** <ide> protected static function arguments(array $tokens) <ide> */ <ide> protected static function options(array $tokens) <ide> { <del> return array_filter(array_map(function ($token) { <add> return array_values(array_filter(array_map(function ($token) { <ide> if (starts_with($token, '{--')) { <ide> return static::parseOption(ltrim(trim($token, '{}'), '-')); <ide> } <del> }, $tokens)); <add> }, $tokens))); <ide> } <ide> <ide> /** <ide> protected static function options(array $tokens) <ide> */ <ide> protected static function parseArgument($token) <ide> { <add> $description = null; <add> <add> if (str_contains($token, ' : ')) { <add> list($token, $description) = explode(' : ', $token); <add> <add> $token = trim($token); <add> <add> $description = trim($description); <add> } <add> <ide> switch (true) { <ide> case ends_with($token, '?*'): <del> return new InputArgument(trim($token, '?*'), InputArgument::IS_ARRAY); <add> return new InputArgument(trim($token, '?*'), InputArgument::IS_ARRAY, $description); <ide> <ide> case ends_with($token, '*'): <del> return new InputArgument(trim($token, '*'), InputArgument::IS_ARRAY | InputArgument::REQUIRED); <add> return new InputArgument(trim($token, '*'), InputArgument::IS_ARRAY | InputArgument::REQUIRED, $description); <ide> <ide> case ends_with($token, '?'): <del> return new InputArgument(trim($token, '?'), InputArgument::OPTIONAL); <add> return new InputArgument(trim($token, '?'), InputArgument::OPTIONAL, $description); <ide> <ide> case (preg_match('/(.+)\=(.+)/', $token, $matches)): <del> return new InputArgument($matches[1], InputArgument::OPTIONAL, '', $matches[2]); <add> return new InputArgument($matches[1], InputArgument::OPTIONAL, $description, $matches[2]); <ide> <ide> default: <del> return new InputArgument($token, InputArgument::REQUIRED); <add> return new InputArgument($token, InputArgument::REQUIRED, $description); <ide> } <ide> } <ide> <ide> protected static function parseArgument($token) <ide> */ <ide> protected static function parseOption($token) <ide> { <add> $description = null; <add> <add> if (str_contains($token, ' : ')) { <add> list($token, $description) = explode(' : ', $token); <add> <add> $token = trim($token); <add> <add> $description = trim($description); <add> } <add> <ide> switch (true) { <ide> case ends_with($token, '='): <del> return new InputOption(trim($token, '='), null, InputOption::VALUE_OPTIONAL); <add> return new InputOption(trim($token, '='), null, InputOption::VALUE_OPTIONAL, $description); <ide> <ide> case ends_with($token, '=*'): <del> return new InputOption(trim($token, '=*'), null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY); <add> return new InputOption(trim($token, '=*'), null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, $description); <ide> <ide> case (preg_match('/(.+)\=(.+)/', $token, $matches)): <del> return new InputOption($matches[1], null, InputOption::VALUE_OPTIONAL, '', $matches[2]); <add> return new InputOption($matches[1], null, InputOption::VALUE_OPTIONAL, $description, $matches[2]); <ide> <ide> default: <del> return new InputOption($token, null, InputOption::VALUE_NONE); <add> return new InputOption($token, null, InputOption::VALUE_NONE, $description); <ide> } <ide> } <ide> } <ide><path>tests/Console/ConsoleParserTest.php <add><?php <add> <add>use Illuminate\Console\Parser; <add> <add>class ConsoleParserTest extends PHPUnit_Framework_TestCase <add>{ <add> public function testBasicParameterParsing() <add> { <add> $results = Parser::parse('command:name {argument} {--option}'); <add> <add> $this->assertEquals('command:name', $results[0]); <add> $this->assertEquals('argument', $results[1][0]->getName()); <add> $this->assertEquals('option', $results[2][0]->getName()); <add> $this->assertFalse($results[2][0]->acceptValue()); <add> <add> $results = Parser::parse('command:name {argument*} {--option=}'); <add> <add> $this->assertEquals('command:name', $results[0]); <add> $this->assertEquals('argument', $results[1][0]->getName()); <add> $this->assertTrue($results[1][0]->isArray()); <add> $this->assertTrue($results[1][0]->isRequired()); <add> $this->assertEquals('option', $results[2][0]->getName()); <add> $this->assertTrue($results[2][0]->acceptValue()); <add> <add> $results = Parser::parse('command:name {argument?*} {--option=*}'); <add> <add> $this->assertEquals('command:name', $results[0]); <add> $this->assertEquals('argument', $results[1][0]->getName()); <add> $this->assertTrue($results[1][0]->isArray()); <add> $this->assertFalse($results[1][0]->isRequired()); <add> $this->assertEquals('option', $results[2][0]->getName()); <add> $this->assertTrue($results[2][0]->acceptValue()); <add> $this->assertTrue($results[2][0]->isArray()); <add> <add> $results = Parser::parse('command:name <add> {argument?* : The argument description.} <add> {--option=* : The option description.}'); <add> <add> $this->assertEquals('command:name', $results[0]); <add> $this->assertEquals('argument', $results[1][0]->getName()); <add> $this->assertEquals('The argument description.', $results[1][0]->getDescription()); <add> $this->assertTrue($results[1][0]->isArray()); <add> $this->assertFalse($results[1][0]->isRequired()); <add> $this->assertEquals('option', $results[2][0]->getName()); <add> $this->assertEquals('The option description.', $results[2][0]->getDescription()); <add> $this->assertTrue($results[2][0]->acceptValue()); <add> $this->assertTrue($results[2][0]->isArray()); <add> } <add>}
2
Javascript
Javascript
fix labels for release sections
f9d05fb1ecee4380566e4de29d8191b7eddd5c55
<ide><path>release.js <ide> // section -> label <ide> const sectionLabelMap = { <ide> 'Core Changes': 'type: next', <del> 'Documentation Changes': 'type: documentation', <del> 'Example Changes': 'type: example', <add> 'Documentation Changes': 'area: documentation', <add> 'Example Changes': 'area: examples', <ide> } <ide> <ide> const fallbackSection = 'Misc Changes'
1
Javascript
Javascript
add deprecation for this.$() in curly components
c0b6b95fa000bf87a9109253099325e5f2607aeb
<ide><path>packages/@ember/-internals/glimmer/tests/integration/components/curly-components-test.js <ide> if (jQueryDisabled) { <ide> class extends RenderingTestCase { <ide> ['@test it has a jQuery proxy to the element']() { <ide> let instance; <add> let element1; <add> let element2; <ide> <ide> let FooBarComponent = Component.extend({ <ide> init() { <ide> if (jQueryDisabled) { <ide> <ide> this.render('{{foo-bar}}'); <ide> <del> let element1 = instance.$()[0]; <add> expectDeprecation(() => { <add> element1 = instance.$()[0]; <add> }, 'Using this.$() in a component has been deprecated, consider using this.element'); <ide> <ide> this.assertComponentElement(element1, { content: 'hello' }); <ide> <ide> runTask(() => this.rerender()); <ide> <del> let element2 = instance.$()[0]; <add> expectDeprecation(() => { <add> element2 = instance.$()[0]; <add> }, 'Using this.$() in a component has been deprecated, consider using this.element'); <ide> <ide> this.assertComponentElement(element2, { content: 'hello' }); <ide> <ide> if (jQueryDisabled) { <ide> <ide> ['@test it scopes the jQuery proxy to the component element'](assert) { <ide> let instance; <add> let $span; <ide> <ide> let FooBarComponent = Component.extend({ <ide> init() { <ide> if (jQueryDisabled) { <ide> <ide> this.render('<span class="outer">outer</span>{{foo-bar}}'); <ide> <del> let $span = instance.$('span'); <add> expectDeprecation(() => { <add> $span = instance.$('span'); <add> }, 'Using this.$() in a component has been deprecated, consider using this.element'); <ide> <ide> assert.equal($span.length, 1); <ide> assert.equal($span.attr('class'), 'inner'); <ide> <ide> runTask(() => this.rerender()); <ide> <del> $span = instance.$('span'); <add> expectDeprecation(() => { <add> $span = instance.$('span'); <add> }, 'Using this.$() in a component has been deprecated, consider using this.element'); <ide> <ide> assert.equal($span.length, 1); <ide> assert.equal($span.attr('class'), 'inner'); <ide><path>packages/@ember/-internals/glimmer/tests/integration/components/dynamic-components-test.js <ide> if (jQueryDisabled) { <ide> class extends RenderingTestCase { <ide> ['@test it has a jQuery proxy to the element']() { <ide> let instance; <add> let element1; <add> let element2; <ide> <ide> let FooBarComponent = Component.extend({ <ide> init() { <ide> if (jQueryDisabled) { <ide> <ide> this.render('{{component "foo-bar"}}'); <ide> <del> let element1 = instance.$()[0]; <add> expectDeprecation(() => { <add> element1 = instance.$()[0]; <add> }, 'Using this.$() in a component has been deprecated, consider using this.element'); <ide> <ide> this.assertComponentElement(element1, { content: 'hello' }); <ide> <ide> runTask(() => this.rerender()); <ide> <del> let element2 = instance.$()[0]; <add> expectDeprecation(() => { <add> element2 = instance.$()[0]; <add> }, 'Using this.$() in a component has been deprecated, consider using this.element'); <ide> <ide> this.assertComponentElement(element2, { content: 'hello' }); <ide> <ide> if (jQueryDisabled) { <ide> <ide> ['@test it scopes the jQuery proxy to the component element'](assert) { <ide> let instance; <add> let $span; <ide> <ide> let FooBarComponent = Component.extend({ <ide> init() { <ide> if (jQueryDisabled) { <ide> <ide> this.render('<span class="outer">outer</span>{{component "foo-bar"}}'); <ide> <del> let $span = instance.$('span'); <add> expectDeprecation(() => { <add> $span = instance.$('span'); <add> }, 'Using this.$() in a component has been deprecated, consider using this.element'); <ide> <ide> assert.equal($span.length, 1); <ide> assert.equal($span.attr('class'), 'inner'); <ide> <ide> runTask(() => this.rerender()); <ide> <del> $span = instance.$('span'); <add> expectDeprecation(() => { <add> $span = instance.$('span'); <add> }, 'Using this.$() in a component has been deprecated, consider using this.element'); <ide> <ide> assert.equal($span.length, 1); <ide> assert.equal($span.attr('class'), 'inner'); <ide><path>packages/@ember/-internals/glimmer/tests/integration/components/life-cycle-test.js <ide> if (!jQueryDisabled) { <ide> 'Run loop and lifecycle hooks - jQuery only', <ide> class extends RenderingTestCase { <ide> ['@test lifecycle hooks have proper access to this.$()'](assert) { <del> assert.expect(6); <add> assert.expect(7); <ide> let component; <ide> let FooBarComponent = Component.extend({ <ide> tagName: 'div', <ide> if (!jQueryDisabled) { <ide> template: 'hello', <ide> }); <ide> let { owner } = this; <del> let comp = owner.lookup('component:foo-bar'); <del> runAppend(comp); <add> <add> expectDeprecation(() => { <add> let comp = owner.lookup('component:foo-bar'); <add> runAppend(comp); <add> runTask(() => tryInvoke(component, 'destroy')); <add> }, 'Using this.$() in a component has been deprecated, consider using this.element'); <ide> runTask(() => tryInvoke(component, 'destroy')); <ide> } <ide> } <ide><path>packages/@ember/-internals/views/lib/mixins/view_support.js <ide> import { assert } from '@ember/debug'; <ide> import { hasDOM } from '@ember/-internals/browser-environment'; <ide> import { matches } from '../system/utils'; <ide> import { default as jQuery, jQueryDisabled } from '../system/jquery'; <add>import { deprecate } from '@ember/debug'; <ide> <ide> function K() { <ide> return this; <ide> export default Mixin.create({ <ide> this.tagName !== '' <ide> ); <ide> assert('You cannot access this.$() with `jQuery` disabled.', !jQueryDisabled); <add> deprecate( <add> 'Using this.$() in a component has been deprecated, consider using this.element', <add> false, <add> { <add> id: 'ember-views.curly-components.jquery-element', <add> until: '4.0.0', <add> url: 'https://emberjs.com/deprecations/v3.x#toc_jquery-apis', <add> } <add> ); <ide> if (this.element) { <ide> return sel ? jQuery(sel, this.element) : jQuery(this.element); <ide> }
4
Javascript
Javascript
remove timer from test/simple/test-dgram-unix.js
f188b9d6d77d51e8023853d4828b07b0cac3f24e
<ide><path>test/simple/test-dgram-unix.js <ide> var Buffer = require("buffer").Buffer, <ide> dgram = require("dgram"), server, client, <ide> server_path = "/tmp/dgram_server_sock", <ide> client_path = "/tmp/dgram_client_sock", <del> message_to_send = new Buffer("A message to send"), <del> timer; <add> message_to_send = new Buffer("A message to send"); <ide> <ide> server = dgram.createSocket("unix_dgram"); <ide> server.on("message", function (msg, rinfo) { <ide> server.on("listening", function () { <ide> assert.strictEqual(bytes, message_to_send.length); <ide> }); <ide> }); <del> client.on("close", function () { <del> if (server.fd === null) { <del> clearTimeout(timer); <del> } <del> }); <add> <ide> client.bind(client_path); <ide> }); <del>server.on("close", function () { <del> if (client.fd === null) { <del> clearTimeout(timer); <del> } <del>}); <del>server.bind(server_path); <ide> <del>timer = setTimeout(function () { <del> throw new Error("Timeout"); <del>}, 200); <add>server.bind(server_path);
1
Java
Java
add userproperties to standardwebsocketclient
222f6998e4013370f6179ffdd8353b2e9afcd1f5
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/client/standard/StandardWebSocketClient.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import java.net.URI; <ide> import java.net.UnknownHostException; <ide> import java.util.ArrayList; <add>import java.util.HashMap; <ide> import java.util.List; <ide> import java.util.Locale; <ide> import java.util.Map; <ide> import java.util.concurrent.Callable; <add> <ide> import javax.websocket.ClientEndpointConfig; <ide> import javax.websocket.ClientEndpointConfig.Configurator; <ide> import javax.websocket.ContainerProvider; <ide> import org.springframework.web.socket.adapter.standard.WebSocketToStandardExtensionAdapter; <ide> import org.springframework.web.socket.client.AbstractWebSocketClient; <ide> <add> <ide> /** <del> * Initiates WebSocket requests to a WebSocket server programmatically <del> * through the standard Java WebSocket API. <add> * A WebSocketClient based on standard Java WebSocket API. <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> public class StandardWebSocketClient extends AbstractWebSocketClient { <ide> <ide> private final WebSocketContainer webSocketContainer; <ide> <add> private final Map<String,Object> userProperties = new HashMap<String, Object>(); <add> <ide> private AsyncListenableTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor(); <ide> <ide> <ide> public StandardWebSocketClient(WebSocketContainer webSocketContainer) { <ide> } <ide> <ide> <add> /** <add> * The standard Java WebSocket API allows passing "user properties" to the <add> * server via {@link ClientEndpointConfig#getUserProperties() userProperties}. <add> * Use this property to configure one or more properties to be passed on <add> * every handshake. <add> */ <add> public void setUserProperties(Map<String, Object> userProperties) { <add> if (userProperties != null) { <add> this.userProperties.putAll(userProperties); <add> } <add> } <add> <add> /** <add> * The configured user properties, or {@code null}. <add> */ <add> public Map<String, Object> getUserProperties() { <add> return this.userProperties; <add> } <add> <ide> /** <ide> * Set an {@link AsyncListenableTaskExecutor} to use when opening connections. <ide> * If this property is set to {@code null}, calls to any of the <ide> protected ListenableFuture<WebSocketSession> doHandshakeInternal(WebSocketHandle <ide> final StandardWebSocketSession session = new StandardWebSocketSession(headers, <ide> attributes, localAddress, remoteAddress); <ide> <del> final ClientEndpointConfig.Builder configBuilder = ClientEndpointConfig.Builder.create(); <del> configBuilder.configurator(new StandardWebSocketClientConfigurator(headers)); <del> configBuilder.preferredSubprotocols(protocols); <del> configBuilder.extensions(adaptExtensions(extensions)); <add> final ClientEndpointConfig endpointConfig = ClientEndpointConfig.Builder.create() <add> .configurator(new StandardWebSocketClientConfigurator(headers)) <add> .preferredSubprotocols(protocols) <add> .extensions(adaptExtensions(extensions)).build(); <add> <add> endpointConfig.getUserProperties().putAll(getUserProperties()); <add> <ide> final Endpoint endpoint = new StandardWebSocketHandlerAdapter(webSocketHandler, session); <ide> <ide> Callable<WebSocketSession> connectTask = new Callable<WebSocketSession>() { <ide> @Override <ide> public WebSocketSession call() throws Exception { <del> webSocketContainer.connectToServer(endpoint, configBuilder.build(), uri); <add> webSocketContainer.connectToServer(endpoint, endpointConfig, uri); <ide> return session; <ide> } <ide> }; <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/client/standard/StandardWebSocketClientTests.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> package org.springframework.web.socket.client.standard; <ide> <add>import static org.junit.Assert.*; <add>import static org.mockito.Mockito.*; <add> <ide> import java.net.URI; <del>import java.util.Arrays; <ide> import java.util.Collections; <ide> import java.util.HashMap; <ide> import java.util.List; <ide> import java.util.Map; <add> <ide> import javax.websocket.ClientEndpointConfig; <ide> import javax.websocket.Endpoint; <ide> import javax.websocket.WebSocketContainer; <ide> import org.springframework.web.socket.WebSocketSession; <ide> import org.springframework.web.socket.handler.AbstractWebSocketHandler; <ide> <del>import static org.junit.Assert.*; <del>import static org.mockito.Mockito.*; <del> <ide> /** <ide> * Test fixture for {@link StandardWebSocketClient}. <ide> * <ide> public void setup() { <ide> <ide> <ide> @Test <del> public void localAddress() throws Exception { <del> URI uri = new URI("ws://example.com/abc"); <add> public void testGetLocalAddress() throws Exception { <add> URI uri = new URI("ws://localhost/abc"); <ide> WebSocketSession session = this.wsClient.doHandshake(this.wsHandler, this.headers, uri).get(); <ide> <ide> assertNotNull(session.getLocalAddress()); <ide> assertEquals(80, session.getLocalAddress().getPort()); <ide> } <ide> <ide> @Test <del> public void localAddressWss() throws Exception { <del> URI uri = new URI("wss://example.com/abc"); <add> public void testGetLocalAddressWss() throws Exception { <add> URI uri = new URI("wss://localhost/abc"); <ide> WebSocketSession session = this.wsClient.doHandshake(this.wsHandler, this.headers, uri).get(); <ide> <ide> assertNotNull(session.getLocalAddress()); <ide> assertEquals(443, session.getLocalAddress().getPort()); <ide> } <ide> <ide> @Test(expected=IllegalArgumentException.class) <del> public void localAddressNoScheme() throws Exception { <del> URI uri = new URI("example.com/abc"); <add> public void testGetLocalAddressNoScheme() throws Exception { <add> URI uri = new URI("localhost/abc"); <ide> this.wsClient.doHandshake(this.wsHandler, this.headers, uri); <ide> } <ide> <ide> @Test <del> public void remoteAddress() throws Exception { <del> URI uri = new URI("wss://example.com/abc"); <add> public void testGetRemoteAddress() throws Exception { <add> URI uri = new URI("wss://localhost/abc"); <ide> WebSocketSession session = this.wsClient.doHandshake(this.wsHandler, this.headers, uri).get(); <ide> <ide> assertNotNull(session.getRemoteAddress()); <del> assertEquals("example.com", session.getRemoteAddress().getHostName()); <add> assertEquals("localhost", session.getRemoteAddress().getHostName()); <ide> assertEquals(443, session.getLocalAddress().getPort()); <ide> } <ide> <ide> @Test <del> public void headersWebSocketSession() throws Exception { <add> public void handshakeHeaders() throws Exception { <ide> <del> URI uri = new URI("ws://example.com/abc"); <del> List<String> protocols = Arrays.asList("abc"); <add> URI uri = new URI("ws://localhost/abc"); <add> List<String> protocols = Collections.singletonList("abc"); <ide> this.headers.setSecWebSocketProtocol(protocols); <ide> this.headers.add("foo", "bar"); <ide> <ide> WebSocketSession session = this.wsClient.doHandshake(this.wsHandler, this.headers, uri).get(); <ide> <del> assertEquals(Collections.singletonMap("foo", Arrays.asList("bar")), session.getHandshakeHeaders()); <add> assertEquals(1, session.getHandshakeHeaders().size()); <add> assertEquals("bar", session.getHandshakeHeaders().getFirst("foo")); <ide> } <ide> <ide> @Test <del> public void headersClientEndpointConfigurator() throws Exception { <add> public void clientEndpointConfig() throws Exception { <ide> <del> URI uri = new URI("ws://example.com/abc"); <del> List<String> protocols = Arrays.asList("abc"); <add> URI uri = new URI("ws://localhost/abc"); <add> List<String> protocols = Collections.singletonList("abc"); <ide> this.headers.setSecWebSocketProtocol(protocols); <del> this.headers.add("foo", "bar"); <ide> <ide> this.wsClient.doHandshake(this.wsHandler, this.headers, uri).get(); <ide> <del> ArgumentCaptor<Endpoint> arg1 = ArgumentCaptor.forClass(Endpoint.class); <del> ArgumentCaptor<ClientEndpointConfig> arg2 = ArgumentCaptor.forClass(ClientEndpointConfig.class); <del> ArgumentCaptor<URI> arg3 = ArgumentCaptor.forClass(URI.class); <del> verify(this.wsContainer).connectToServer(arg1.capture(), arg2.capture(), arg3.capture()); <add> ArgumentCaptor<ClientEndpointConfig> captor = ArgumentCaptor.forClass(ClientEndpointConfig.class); <add> verify(this.wsContainer).connectToServer(any(Endpoint.class), captor.capture(), any(URI.class)); <add> ClientEndpointConfig endpointConfig = captor.getValue(); <ide> <del> ClientEndpointConfig endpointConfig = arg2.getValue(); <ide> assertEquals(protocols, endpointConfig.getPreferredSubprotocols()); <add> } <add> <add> @Test <add> public void clientEndpointConfigWithUserProperties() throws Exception { <add> <add> Map<String,Object> userProperties = Collections.singletonMap("foo", "bar"); <add> <add> URI uri = new URI("ws://localhost/abc"); <add> this.wsClient.setUserProperties(userProperties); <add> this.wsClient.doHandshake(this.wsHandler, this.headers, uri).get(); <add> <add> ArgumentCaptor<ClientEndpointConfig> captor = ArgumentCaptor.forClass(ClientEndpointConfig.class); <add> verify(this.wsContainer).connectToServer(any(Endpoint.class), captor.capture(), any(URI.class)); <add> ClientEndpointConfig endpointConfig = captor.getValue(); <add> <add> assertEquals(userProperties, endpointConfig.getUserProperties()); <add> } <add> <add> @Test <add> public void standardWebSocketClientConfiguratorInsertsHandshakeHeaders() throws Exception { <add> <add> URI uri = new URI("ws://localhost/abc"); <add> this.headers.add("foo", "bar"); <add> <add> this.wsClient.doHandshake(this.wsHandler, this.headers, uri).get(); <add> <add> ArgumentCaptor<ClientEndpointConfig> captor = ArgumentCaptor.forClass(ClientEndpointConfig.class); <add> verify(this.wsContainer).connectToServer(any(Endpoint.class), captor.capture(), any(URI.class)); <add> ClientEndpointConfig endpointConfig = captor.getValue(); <ide> <del> Map<String, List<String>> map = new HashMap<>(); <del> endpointConfig.getConfigurator().beforeRequest(map); <del> assertEquals(Collections.singletonMap("foo", Arrays.asList("bar")), map); <add> Map<String, List<String>> headers = new HashMap<>(); <add> endpointConfig.getConfigurator().beforeRequest(headers); <add> assertEquals(1, headers.size()); <ide> } <ide> <ide> @Test <ide> public void taskExecutor() throws Exception { <ide> <del> URI uri = new URI("ws://example.com/abc"); <add> URI uri = new URI("ws://localhost/abc"); <ide> this.wsClient.setTaskExecutor(new SimpleAsyncTaskExecutor()); <ide> WebSocketSession session = this.wsClient.doHandshake(this.wsHandler, this.headers, uri).get(); <ide>
2
Javascript
Javascript
fix unbound helper when used with {{this}}
a0fadf121fe08bec3cca433057374dbd466d2308
<ide><path>packages/ember-handlebars/tests/handlebars_test.js <ide> test("should be able to use standard Handlebars #each helper", function() { <ide> equals(view.$().html(), "abc"); <ide> }); <ide> <add>test("should be able to use unbound helper in #each helper", function() { <add> view = Ember.View.create({ <add> items: Ember.A(['a', 'b', 'c']), <add> template: Ember.Handlebars.compile("{{#each items}}{{unbound this}}{{/each}}") <add> }); <add> <add> appendView(); <add> <add> equals(view.$().text(), "abc"); <add>}); <add> <ide> module("Templates redrawing and bindings", { <ide> setup: function(){ <ide> MyApp = Ember.Object.create({}); <ide><path>packages/ember-metal/lib/accessors.js <ide> Ember.getPath = function(root, path) { <ide> var hasThis, hasStar, isGlobal; <ide> <ide> if (!path && 'string'===typeof root) { <add> // Helpers that operate with 'this' within an #each <add> if (path === '') { <add> return root; <add> } <add> <ide> path = root; <ide> root = null; <ide> }
2
Javascript
Javascript
fix logarighmic test to use correct scale
d3860137fe236b9c8d92ef7be7147ac976b9c545
<ide><path>test/specs/scale.logarithmic.tests.js <ide> describe('Logarithmic Scale tests', function() { <ide> } <ide> }); <ide> <del> expect(chart.scales.yScale1.getLabelForIndex(0, 2)).toBe(150); <add> expect(chart.scales.yScale0.getLabelForIndex(0, 2)).toBe(150); <ide> }); <ide> <ide> describe('when', function() {
1
Text
Text
update the docs to reflect the new feature
fd2344dd5f9de7b4aebff48fb21af3670705551f
<ide><path>docs/05-Pie-Doughnut-Chart.md <ide> myDoughnutChart.update(); <ide> <ide> Calling `addData(segmentData, index)` on your Chart instance passing an object in the same format as in the constructor. There is an optional second argument of 'index', this determines at what index the new segment should be inserted into the chart. <ide> <add>If you don't specify a color and highliht, one will be chosen from the global default array: segmentColorDefault and the corresponding segmentHighlightColorDefault. The index of the addded data is used to lookup a corresponding color from the defaults. <add> <ide> ```javascript <ide> // An object in the same format as the original data source <ide> myDoughnutChart.addData({
1
Text
Text
improve displayname documentation
617f8810ba8e5ce6ba2f2917e06eea3425b2e0d5
<ide><path>docs/docs/reference-react-component.md <ide> If `props.color` is set to null, it will remain null: <ide> <ide> ### `displayName` <ide> <del>The `displayName` string is used in debugging messages. JSX sets this value automatically; see [JSX in Depth](/react/docs/jsx-in-depth.html). <add>The `displayName` string is used in debugging messages. Usually, you don't need to set it explicitly because it's inferred from the name of the function or class that defines the component. You might want to set it explicitly if you want to display a different name for debugging purposes or when you create a higher-order component, see [Wrap the Display Name for Easy Debugging](/react/docs/higher-order-components.html#convention-wrap-the-display-name-for-easy-debugging) for details. <ide> <ide> * * * <ide>
1
Python
Python
update einsum docs
2804c03bdc135b70cbcc24755d450123274b4850
<ide><path>numpy/add_newdocs.py <ide> def luf(lamdaexpr, *args, **kwargs): <ide> <ide> """) <ide> <add>add_newdoc('numpy.core', 'vdot', <add> """ <add> vdot(a, b) <add> <add> Return the dot product of two vectors. <add> <add> The vdot(`a`, `b`) function handles complex numbers differently than <add> dot(`a`, `b`). If the first argument is complex the complex conjugate <add> of the first argument is used for the calculation of the dot product. <ide> <del>add_newdoc('numpy.core', 'c_einsum', <add> Note that `vdot` handles multidimensional arrays differently than `dot`: <add> it does *not* perform a matrix product, but flattens input arguments <add> to 1-D vectors first. Consequently, it should only be used for vectors. <add> <add> Parameters <add> ---------- <add> a : array_like <add> If `a` is complex the complex conjugate is taken before calculation <add> of the dot product. <add> b : array_like <add> Second argument to the dot product. <add> <add> Returns <add> ------- <add> output : ndarray <add> Dot product of `a` and `b`. Can be an int, float, or <add> complex depending on the types of `a` and `b`. <add> <add> See Also <add> -------- <add> dot : Return the dot product without using the complex conjugate of the <add> first argument. <add> <add> Examples <add> -------- <add> >>> a = np.array([1+2j,3+4j]) <add> >>> b = np.array([5+6j,7+8j]) <add> >>> np.vdot(a, b) <add> (70-8j) <add> >>> np.vdot(b, a) <add> (70+8j) <add> <add> Note that higher-dimensional arrays are flattened! <add> <add> >>> a = np.array([[1, 4], [5, 6]]) <add> >>> b = np.array([[4, 1], [2, 2]]) <add> >>> np.vdot(a, b) <add> 30 <add> >>> np.vdot(b, a) <add> 30 <add> >>> 1*4 + 4*1 + 5*2 + 6*2 <add> 30 <add> <add> """) <add> <add>add_newdoc('numpy.core.multiarray', 'c_einsum', <ide> """ <del> c_einsum(subscripts, *operands, out=None, dtype=None, order='K', casting='safe') <add> c_einsum(subscripts, *operands, out=None, dtype=None, order='K', <add> casting='safe') <add> <add> *This documentation shadows that of the native python implementation of the `einsum` function, <add> except all references and examples related to the `optimize` argument (v 0.12.0) have been removed.* <ide> <ide> Evaluates the Einstein summation convention on the operands. <ide> <del> Using the Einstein summation convention, many common multi-dimensional <del> array operations can be represented in a simple fashion. This function <del> provides a way to compute such summations. The best way to understand this <del> function is to try the examples below, which show how many common NumPy <del> functions can be implemented as calls to `einsum`. <add> Using the Einstein summation convention, many common multi-dimensional, <add> linear algebraic array operations can be represented in a simple fashion. <add> In *implicit* mode `einsum` computes these values. <add> <add> In *explicit* mode, `einsum` provides further flexibility to compute <add> other array operations that might not be considered classical Einstein <add> summation operations, by disabling, or forcing summation over specified <add> subscript labels. <ide> <del> This is the core C function. <add> See the notes and examples for clarification. <ide> <ide> Parameters <ide> ---------- <ide> subscripts : str <del> Specifies the subscripts for summation. <add> Specifies the subscripts for summation as comma separated list of <add> subscript labels. An implicit (classical Einstein summation) <add> calculation is performed unless the explicit indicator '->' is <add> included as well as subscript labels of the precise output form. <ide> operands : list of array_like <ide> These are the arrays for the operation. <ide> out : ndarray, optional <ide> def luf(lamdaexpr, *args, **kwargs): <ide> * 'unsafe' means any data conversions may be done. <ide> <ide> Default is 'safe'. <add> optimize : {False, True, 'greedy', 'optimal'}, optional <add> Controls if intermediate optimization should occur. No optimization <add> will occur if False and True will default to the 'greedy' algorithm. <add> Also accepts an explicit contraction list from the ``np.einsum_path`` <add> function. See ``np.einsum_path`` for more details. Defaults to False. <ide> <ide> Returns <ide> ------- <ide> def luf(lamdaexpr, *args, **kwargs): <ide> <ide> See Also <ide> -------- <del> einsum, dot, inner, outer, tensordot <add> einsum_path, dot, inner, outer, tensordot, linalg.multi_dot <ide> <ide> Notes <ide> ----- <ide> .. versionadded:: 1.6.0 <ide> <del> The subscripts string is a comma-separated list of subscript labels, <del> where each label refers to a dimension of the corresponding operand. <del> Repeated subscripts labels in one operand take the diagonal. For example, <del> ``np.einsum('ii', a)`` is equivalent to ``np.trace(a)``. <add> The Einstein summation convention can be used to compute <add> many multi-dimensional, linear algebraic array operations. `einsum` <add> provides a succinct way of representing these. <ide> <del> Whenever a label is repeated, it is summed, so ``np.einsum('i,i', a, b)`` <del> is equivalent to ``np.inner(a,b)``. If a label appears only once, <del> it is not summed, so ``np.einsum('i', a)`` produces a view of ``a`` <del> with no changes. <add> A non-exhaustive list of these operations, <add> which can be computed by `einsum`, is shown below along with examples: <ide> <del> The order of labels in the output is by default alphabetical. This <del> means that ``np.einsum('ij', a)`` doesn't affect a 2D array, while <del> ``np.einsum('ji', a)`` takes its transpose. <add> * Trace of an array, :py:func:`numpy.trace`. <add> * Return a diagonal, :py:func:`numpy.diag`. <add> * Array axis summations, :py:func:`numpy.sum`. <add> * Transpositions and permutations, :py:func:`numpy.transpose`. <add> * Matrix multiplication and dot product, :py:func:`numpy.matmul` :py:func:`numpy.dot`. <add> * Vector inner and outer products, :py:func:`numpy.inner` :py:func:`numpy.outer`. <add> * Broadcasting, element-wise and scalar multiplication, :py:func:`numpy.multiply`. <add> * Tensor contractions, :py:func:`numpy.tensordot`. <add> * Chained array operations, in efficient calculation order, :py:func:`numpy.einsum_path`. <ide> <del> The output can be controlled by specifying output subscript labels <del> as well. This specifies the label order, and allows summing to <del> be disallowed or forced when desired. The call ``np.einsum('i->', a)`` <del> is like ``np.sum(a, axis=-1)``, and ``np.einsum('ii->i', a)`` <del> is like ``np.diag(a)``. The difference is that `einsum` does not <del> allow broadcasting by default. <add> The subscripts string is a comma-separated list of subscript labels, <add> where each label refers to a dimension of the corresponding operand. <add> Whenever a label is repeated it is summed, so ``np.einsum('i,i', a, b)`` <add> is equivalent to :py:func:`np.inner(a,b) <numpy.inner>`. If a label <add> appears only once, it is not summed, so ``np.einsum('i', a)`` produces a <add> view of ``a`` with no changes. A further example ``np.einsum('ij,jk', a, b)`` <add> describes traditional matrix multiplication and is equivalent to <add> :py:func:`np.matmul(a,b) <numpy.matmul>`. Repeated subscript labels in one <add> operand take the diagonal. For example, ``np.einsum('ii', a)`` is equivalent <add> to :py:func:`np.trace(a) <numpy.trace>`. <add> <add> In *implicit mode*, the chosen subscripts are important <add> since the axes of the output are reordered alphabetically. This <add> means that ``np.einsum('ij', a)`` doesn't affect a 2D array, while <add> ``np.einsum('ji', a)`` takes its transpose. Additionally, <add> ``np.einsum('ij,jk', a, b)`` returns a matrix multiplication, while, <add> ``np.einsum('ij,jh', a, b)`` returns the transpose of the <add> multiplication since subscript 'h' precedes subscript 'i'. <add> <add> In *explicit mode* the output can be directly controlled by <add> specifying output subscript labels. This requires the <add> identifier '->' as well as the list of output subscript labels. <add> This feature increases the flexibility of the function since <add> summing can be disabled or forced when required. The call <add> ``np.einsum('i->', a)`` is like :py:func:`np.sum(a, axis=-1) <numpy.sum>`, <add> and ``np.einsum('ii->i', a)`` is like :py:func:`np.diag(a) <numpy.diag>`. <add> The difference is that `einsum` does not allow broadcasting by default. <add> Additionally ``np.einsum('ij,jh->ih', a, b)`` directly specifies the <add> order of the output subscript labels and therefore returns matrix <add> multiplication, unlike the example above in implicit mode. <ide> <ide> To enable and control broadcasting, use an ellipsis. Default <ide> NumPy-style broadcasting is done by adding an ellipsis <ide> to the left of each term, like ``np.einsum('...ii->...i', a)``. <ide> To take the trace along the first and last axes, <ide> you can do ``np.einsum('i...i', a)``, or to do a matrix-matrix <del> product with the left-most indices instead of rightmost, you can do <add> product with the left-most indices instead of rightmost, one can do <ide> ``np.einsum('ij...,jk...->ik...', a, b)``. <ide> <ide> When there is only one operand, no axes are summed, and no output <ide> parameter is provided, a view into the operand is returned instead <ide> of a new array. Thus, taking the diagonal as ``np.einsum('ii->i', a)`` <del> produces a view. <add> produces a view (changed in version 1.10.0). <ide> <del> An alternative way to provide the subscripts and operands is as <del> ``einsum(op0, sublist0, op1, sublist1, ..., [sublistout])``. The examples <del> below have corresponding `einsum` calls with the two parameter methods. <add> `einsum` also provides an alternative way to provide the subscripts <add> and operands as ``einsum(op0, sublist0, op1, sublist1, ..., [sublistout])``. <add> If the output shape is not provided in this format `einsum` will be <add> calculated in implicit mode, otherwise it will be performed explicitly. <add> The examples below have corresponding `einsum` calls with the two <add> parameter methods. <ide> <ide> .. versionadded:: 1.10.0 <ide> <ide> Views returned from einsum are now writeable whenever the input array <ide> is writeable. For example, ``np.einsum('ijk...->kji...', a)`` will now <del> have the same effect as ``np.swapaxes(a, 0, 2)`` and <del> ``np.einsum('ii->i', a)`` will return a writeable view of the diagonal <add> have the same effect as :py:func:`np.swapaxes(a, 0, 2) <numpy.swapaxes>` <add> and ``np.einsum('ii->i', a)`` will return a writeable view of the diagonal <ide> of a 2D array. <ide> <ide> Examples <ide> def luf(lamdaexpr, *args, **kwargs): <ide> >>> b = np.arange(5) <ide> >>> c = np.arange(6).reshape(2,3) <ide> <add> Trace of a matrix: <add> <ide> >>> np.einsum('ii', a) <ide> 60 <ide> >>> np.einsum(a, [0,0]) <ide> 60 <ide> >>> np.trace(a) <ide> 60 <ide> <add> Extract the diagonal (requires explicit form): <add> <ide> >>> np.einsum('ii->i', a) <ide> array([ 0, 6, 12, 18, 24]) <ide> >>> np.einsum(a, [0,0], [0]) <ide> array([ 0, 6, 12, 18, 24]) <ide> >>> np.diag(a) <ide> array([ 0, 6, 12, 18, 24]) <ide> <del> >>> np.einsum('ij,j', a, b) <del> array([ 30, 80, 130, 180, 230]) <del> >>> np.einsum(a, [0,1], b, [1]) <del> array([ 30, 80, 130, 180, 230]) <del> >>> np.dot(a, b) <del> array([ 30, 80, 130, 180, 230]) <del> >>> np.einsum('...j,j', a, b) <del> array([ 30, 80, 130, 180, 230]) <add> Sum over an axis (requires explicit form): <add> <add> >>> np.einsum('ij->i', a) <add> array([ 10, 35, 60, 85, 110]) <add> >>> np.einsum(a, [0,1], [0]) <add> array([ 10, 35, 60, 85, 110]) <add> >>> np.sum(a, axis=1) <add> array([ 10, 35, 60, 85, 110]) <add> <add> For higher dimensional arrays summing a single axis can be done with ellipsis: <add> <add> >>> np.einsum('...j->...', a) <add> array([ 10, 35, 60, 85, 110]) <add> >>> np.einsum(a, [Ellipsis,1], [Ellipsis]) <add> array([ 10, 35, 60, 85, 110]) <add> <add> Compute a matrix transpose, or reorder any number of axes: <ide> <ide> >>> np.einsum('ji', c) <add> array([[0, 3], <add> [1, 4], <add> [2, 5]]) <add> >>> np.einsum('ij->ji', c) <ide> array([[0, 3], <ide> [1, 4], <ide> [2, 5]]) <ide> >>> np.einsum(c, [1,0]) <ide> array([[0, 3], <ide> [1, 4], <ide> [2, 5]]) <del> >>> c.T <add> >>> np.transpose(c) <ide> array([[0, 3], <ide> [1, 4], <ide> [2, 5]]) <ide> <add> Vector inner products: <add> <add> >>> np.einsum('i,i', b, b) <add> 30 <add> >>> np.einsum(b, [0], b, [0]) <add> 30 <add> >>> np.inner(b,b) <add> 30 <add> <add> Matrix vector multiplication: <add> <add> >>> np.einsum('ij,j', a, b) <add> array([ 30, 80, 130, 180, 230]) <add> >>> np.einsum(a, [0,1], b, [1]) <add> array([ 30, 80, 130, 180, 230]) <add> >>> np.dot(a, b) <add> array([ 30, 80, 130, 180, 230]) <add> >>> np.einsum('...j,j', a, b) <add> array([ 30, 80, 130, 180, 230]) <add> <add> Broadcasting and scalar multiplication: <add> <ide> >>> np.einsum('..., ...', 3, c) <add> array([[ 0, 3, 6], <add> [ 9, 12, 15]]) <add> >>> np.einsum(',ij', 3, c) <ide> array([[ 0, 3, 6], <ide> [ 9, 12, 15]]) <ide> >>> np.einsum(3, [Ellipsis], c, [Ellipsis]) <ide> def luf(lamdaexpr, *args, **kwargs): <ide> array([[ 0, 3, 6], <ide> [ 9, 12, 15]]) <ide> <del> >>> np.einsum('i,i', b, b) <del> 30 <del> >>> np.einsum(b, [0], b, [0]) <del> 30 <del> >>> np.inner(b,b) <del> 30 <add> Vector outer product: <ide> <ide> >>> np.einsum('i,j', np.arange(2)+1, b) <ide> array([[0, 1, 2, 3, 4], <ide> def luf(lamdaexpr, *args, **kwargs): <ide> array([[0, 1, 2, 3, 4], <ide> [0, 2, 4, 6, 8]]) <ide> <del> >>> np.einsum('i...->...', a) <del> array([50, 55, 60, 65, 70]) <del> >>> np.einsum(a, [0,Ellipsis], [Ellipsis]) <del> array([50, 55, 60, 65, 70]) <del> >>> np.sum(a, axis=0) <del> array([50, 55, 60, 65, 70]) <add> Tensor contraction: <ide> <ide> >>> a = np.arange(60.).reshape(3,4,5) <ide> >>> b = np.arange(24.).reshape(4,3,2) <ide> def luf(lamdaexpr, *args, **kwargs): <ide> [ 4796., 5162.], <ide> [ 4928., 5306.]]) <ide> <add> Writeable returned arrays (since version 1.10.0): <add> <add> >>> a = np.zeros((3, 3)) <add> >>> np.einsum('ii->i', a)[:] = 1 <add> >>> a <add> array([[ 1., 0., 0.], <add> [ 0., 1., 0.], <add> [ 0., 0., 1.]]) <add> <add> Example of ellipsis use: <add> <ide> >>> a = np.arange(6).reshape((3,2)) <ide> >>> b = np.arange(12).reshape((4,3)) <ide> >>> np.einsum('ki,jk->ij', a, b) <ide> def luf(lamdaexpr, *args, **kwargs): <ide> array([[10, 28, 46, 64], <ide> [13, 40, 67, 94]]) <ide> <del> >>> # since version 1.10.0 <del> >>> a = np.zeros((3, 3)) <del> >>> np.einsum('ii->i', a)[:] = 1 <del> >>> a <del> array([[ 1., 0., 0.], <del> [ 0., 1., 0.], <del> [ 0., 0., 1.]]) <del> <del> """) <del> <del>add_newdoc('numpy.core', 'vdot', <del> """ <del> vdot(a, b) <del> <del> Return the dot product of two vectors. <del> <del> The vdot(`a`, `b`) function handles complex numbers differently than <del> dot(`a`, `b`). If the first argument is complex the complex conjugate <del> of the first argument is used for the calculation of the dot product. <del> <del> Note that `vdot` handles multidimensional arrays differently than `dot`: <del> it does *not* perform a matrix product, but flattens input arguments <del> to 1-D vectors first. Consequently, it should only be used for vectors. <del> <del> Parameters <del> ---------- <del> a : array_like <del> If `a` is complex the complex conjugate is taken before calculation <del> of the dot product. <del> b : array_like <del> Second argument to the dot product. <del> <del> Returns <del> ------- <del> output : ndarray <del> Dot product of `a` and `b`. Can be an int, float, or <del> complex depending on the types of `a` and `b`. <del> <del> See Also <del> -------- <del> dot : Return the dot product without using the complex conjugate of the <del> first argument. <del> <del> Examples <del> -------- <del> >>> a = np.array([1+2j,3+4j]) <del> >>> b = np.array([5+6j,7+8j]) <del> >>> np.vdot(a, b) <del> (70-8j) <del> >>> np.vdot(b, a) <del> (70+8j) <del> <del> Note that higher-dimensional arrays are flattened! <del> <del> >>> a = np.array([[1, 4], [5, 6]]) <del> >>> b = np.array([[4, 1], [2, 2]]) <del> >>> np.vdot(a, b) <del> 30 <del> >>> np.vdot(b, a) <del> 30 <del> >>> 1*4 + 4*1 + 5*2 + 6*2 <del> 30 <del> <ide> """) <ide> <ide> <ide><path>numpy/core/einsumfunc.py <ide> def _can_dot(inputs, result, idx_removed): <ide> # We are a matrix-matrix product, but we need to copy data <ide> return True <ide> <add> <ide> def _parse_einsum_input(operands): <ide> """ <ide> A reproduction of einsum c side einsum parsing in python. <ide> def einsum(*operands, **kwargs): <ide> <ide> Evaluates the Einstein summation convention on the operands. <ide> <del> Using the Einstein summation convention, many common multi-dimensional <del> array operations can be represented in a simple fashion. This function <del> provides a way to compute such summations. The best way to understand this <del> function is to try the examples below, which show how many common NumPy <del> functions can be implemented as calls to `einsum`. <add> Using the Einstein summation convention, many common multi-dimensional, <add> linear algebraic array operations can be represented in a simple fashion. <add> In *implicit* mode `einsum` computes these values. <add> <add> In *explicit* mode, `einsum` provides further flexibility to compute <add> other array operations that might not be considered classical Einstein <add> summation operations, by disabling, or forcing summation over specified <add> subscript labels. <add> <add> See the notes and examples for clarification. <ide> <ide> Parameters <ide> ---------- <ide> subscripts : str <del> Specifies the subscripts for summation. <add> Specifies the subscripts for summation as comma separated list of <add> subscript labels. An implicit (classical Einstein summation) <add> calculation is performed unless the explicit indicator '->' is <add> included as well as subscript labels of the precise output form. <ide> operands : list of array_like <ide> These are the arrays for the operation. <del> out : {ndarray, None}, optional <add> out : ndarray, optional <ide> If provided, the calculation is done into this array. <ide> dtype : {data-type, None}, optional <ide> If provided, forces the calculation to use the data type specified. <ide> def einsum(*operands, **kwargs): <ide> Controls if intermediate optimization should occur. No optimization <ide> will occur if False and True will default to the 'greedy' algorithm. <ide> Also accepts an explicit contraction list from the ``np.einsum_path`` <del> function. See ``np.einsum_path`` for more details. Default is True. <add> function. See ``np.einsum_path`` for more details. Defaults to False. <ide> <ide> Returns <ide> ------- <ide> def einsum(*operands, **kwargs): <ide> ----- <ide> .. versionadded:: 1.6.0 <ide> <del> The subscripts string is a comma-separated list of subscript labels, <del> where each label refers to a dimension of the corresponding operand. <del> Repeated subscripts labels in one operand take the diagonal. For example, <del> ``np.einsum('ii', a)`` is equivalent to ``np.trace(a)``. <add> The Einstein summation convention can be used to compute <add> many multi-dimensional, linear algebraic array operations. `einsum` <add> provides a succinct way of representing these. <ide> <del> Whenever a label is repeated, it is summed, so ``np.einsum('i,i', a, b)`` <del> is equivalent to ``np.inner(a,b)``. If a label appears only once, <del> it is not summed, so ``np.einsum('i', a)`` produces a view of ``a`` <del> with no changes. <add> A non-exhaustive list of these operations, <add> which can be computed by `einsum`, is shown below along with examples: <ide> <del> The order of labels in the output is by default alphabetical. This <del> means that ``np.einsum('ij', a)`` doesn't affect a 2D array, while <del> ``np.einsum('ji', a)`` takes its transpose. <add> * Trace of an array, :py:func:`numpy.trace`. <add> * Return a diagonal, :py:func:`numpy.diag`. <add> * Array axis summations, :py:func:`numpy.sum`. <add> * Transpositions and permutations, :py:func:`numpy.transpose`. <add> * Matrix multiplication and dot product, :py:func:`numpy.matmul` :py:func:`numpy.dot`. <add> * Vector inner and outer products, :py:func:`numpy.inner` :py:func:`numpy.outer`. <add> * Broadcasting, element-wise and scalar multiplication, :py:func:`numpy.multiply`. <add> * Tensor contractions, :py:func:`numpy.tensordot`. <add> * Chained array operations, in efficient calculation order, :py:func:`numpy.einsum_path`. <ide> <del> The output can be controlled by specifying output subscript labels <del> as well. This specifies the label order, and allows summing to <del> be disallowed or forced when desired. The call ``np.einsum('i->', a)`` <del> is like ``np.sum(a, axis=-1)``, and ``np.einsum('ii->i', a)`` <del> is like ``np.diag(a)``. The difference is that `einsum` does not <del> allow broadcasting by default. <add> The subscripts string is a comma-separated list of subscript labels, <add> where each label refers to a dimension of the corresponding operand. <add> Whenever a label is repeated it is summed, so ``np.einsum('i,i', a, b)`` <add> is equivalent to :py:func:`np.inner(a,b) <numpy.inner>`. If a label <add> appears only once, it is not summed, so ``np.einsum('i', a)`` produces a <add> view of ``a`` with no changes. A further example ``np.einsum('ij,jk', a, b)`` <add> describes traditional matrix multiplication and is equivalent to <add> :py:func:`np.matmul(a,b) <numpy.matmul>`. Repeated subscript labels in one <add> operand take the diagonal. For example, ``np.einsum('ii', a)`` is equivalent <add> to :py:func:`np.trace(a) <numpy.trace>`. <add> <add> In *implicit mode*, the chosen subscripts are important <add> since the axes of the output are reordered alphabetically. This <add> means that ``np.einsum('ij', a)`` doesn't affect a 2D array, while <add> ``np.einsum('ji', a)`` takes its transpose. Additionally, <add> ``np.einsum('ij,jk', a, b)`` returns a matrix multiplication, while, <add> ``np.einsum('ij,jh', a, b)`` returns the transpose of the <add> multiplication since subscript 'h' precedes subscript 'i'. <add> <add> In *explicit mode* the output can be directly controlled by <add> specifying output subscript labels. This requires the <add> identifier '->' as well as the list of output subscript labels. <add> This feature increases the flexibility of the function since <add> summing can be disabled or forced when required. The call <add> ``np.einsum('i->', a)`` is like :py:func:`np.sum(a, axis=-1) <numpy.sum>`, <add> and ``np.einsum('ii->i', a)`` is like :py:func:`np.diag(a) <numpy.diag>`. <add> The difference is that `einsum` does not allow broadcasting by default. <add> Additionally ``np.einsum('ij,jh->ih', a, b)`` directly specifies the <add> order of the output subscript labels and therefore returns matrix <add> multiplication, unlike the example above in implicit mode. <ide> <ide> To enable and control broadcasting, use an ellipsis. Default <ide> NumPy-style broadcasting is done by adding an ellipsis <ide> to the left of each term, like ``np.einsum('...ii->...i', a)``. <ide> To take the trace along the first and last axes, <ide> you can do ``np.einsum('i...i', a)``, or to do a matrix-matrix <del> product with the left-most indices instead of rightmost, you can do <add> product with the left-most indices instead of rightmost, one can do <ide> ``np.einsum('ij...,jk...->ik...', a, b)``. <ide> <ide> When there is only one operand, no axes are summed, and no output <ide> parameter is provided, a view into the operand is returned instead <ide> of a new array. Thus, taking the diagonal as ``np.einsum('ii->i', a)`` <del> produces a view. <add> produces a view (changed in version 1.10.0). <ide> <del> An alternative way to provide the subscripts and operands is as <del> ``einsum(op0, sublist0, op1, sublist1, ..., [sublistout])``. The examples <del> below have corresponding `einsum` calls with the two parameter methods. <add> `einsum` also provides an alternative way to provide the subscripts <add> and operands as ``einsum(op0, sublist0, op1, sublist1, ..., [sublistout])``. <add> If the output shape is not provided in this format `einsum` will be <add> calculated in implicit mode, otherwise it will be performed explicitly. <add> The examples below have corresponding `einsum` calls with the two <add> parameter methods. <ide> <ide> .. versionadded:: 1.10.0 <ide> <ide> Views returned from einsum are now writeable whenever the input array <ide> is writeable. For example, ``np.einsum('ijk...->kji...', a)`` will now <del> have the same effect as ``np.swapaxes(a, 0, 2)`` and <del> ``np.einsum('ii->i', a)`` will return a writeable view of the diagonal <add> have the same effect as :py:func:`np.swapaxes(a, 0, 2) <numpy.swapaxes>` <add> and ``np.einsum('ii->i', a)`` will return a writeable view of the diagonal <ide> of a 2D array. <ide> <ide> .. versionadded:: 1.12.0 <ide> def einsum(*operands, **kwargs): <ide> can greatly increase the computational efficiency at the cost of a larger <ide> memory footprint during computation. <ide> <del> See ``np.einsum_path`` for more details. <add> Typically a 'greedy' algorithm is applied which empirical tests have shown <add> returns the optimal path in the majority of cases. In some cases 'optimal' <add> will return the superlative path through a more expensive, exhaustive search. <add> For iterative calculations it may be advisable to calculate the optimal path <add> once and reuse that path by supplying it as an argument. An example is given <add> below. <add> <add> See :py:func:`numpy.einsum_path` for more details. <ide> <ide> Examples <ide> -------- <ide> >>> a = np.arange(25).reshape(5,5) <ide> >>> b = np.arange(5) <ide> >>> c = np.arange(6).reshape(2,3) <ide> <add> Trace of a matrix: <add> <ide> >>> np.einsum('ii', a) <ide> 60 <ide> >>> np.einsum(a, [0,0]) <ide> 60 <ide> >>> np.trace(a) <ide> 60 <ide> <add> Extract the diagonal (requires explicit form): <add> <ide> >>> np.einsum('ii->i', a) <ide> array([ 0, 6, 12, 18, 24]) <ide> >>> np.einsum(a, [0,0], [0]) <ide> array([ 0, 6, 12, 18, 24]) <ide> >>> np.diag(a) <ide> array([ 0, 6, 12, 18, 24]) <ide> <del> >>> np.einsum('ij,j', a, b) <del> array([ 30, 80, 130, 180, 230]) <del> >>> np.einsum(a, [0,1], b, [1]) <del> array([ 30, 80, 130, 180, 230]) <del> >>> np.dot(a, b) <del> array([ 30, 80, 130, 180, 230]) <del> >>> np.einsum('...j,j', a, b) <del> array([ 30, 80, 130, 180, 230]) <add> Sum over an axis (requires explicit form): <add> <add> >>> np.einsum('ij->i', a) <add> array([ 10, 35, 60, 85, 110]) <add> >>> np.einsum(a, [0,1], [0]) <add> array([ 10, 35, 60, 85, 110]) <add> >>> np.sum(a, axis=1) <add> array([ 10, 35, 60, 85, 110]) <add> <add> For higher dimensional arrays summing a single axis can be done with ellipsis: <add> <add> >>> np.einsum('...j->...', a) <add> array([ 10, 35, 60, 85, 110]) <add> >>> np.einsum(a, [Ellipsis,1], [Ellipsis]) <add> array([ 10, 35, 60, 85, 110]) <add> <add> Compute a matrix transpose, or reorder any number of axes: <ide> <ide> >>> np.einsum('ji', c) <add> array([[0, 3], <add> [1, 4], <add> [2, 5]]) <add> >>> np.einsum('ij->ji', c) <ide> array([[0, 3], <ide> [1, 4], <ide> [2, 5]]) <ide> >>> np.einsum(c, [1,0]) <ide> array([[0, 3], <ide> [1, 4], <ide> [2, 5]]) <del> >>> c.T <add> >>> np.transpose(c) <ide> array([[0, 3], <ide> [1, 4], <ide> [2, 5]]) <ide> <add> Vector inner products: <add> <add> >>> np.einsum('i,i', b, b) <add> 30 <add> >>> np.einsum(b, [0], b, [0]) <add> 30 <add> >>> np.inner(b,b) <add> 30 <add> <add> Matrix vector multiplication: <add> <add> >>> np.einsum('ij,j', a, b) <add> array([ 30, 80, 130, 180, 230]) <add> >>> np.einsum(a, [0,1], b, [1]) <add> array([ 30, 80, 130, 180, 230]) <add> >>> np.dot(a, b) <add> array([ 30, 80, 130, 180, 230]) <add> >>> np.einsum('...j,j', a, b) <add> array([ 30, 80, 130, 180, 230]) <add> <add> Broadcasting and scalar multiplication: <add> <ide> >>> np.einsum('..., ...', 3, c) <ide> array([[ 0, 3, 6], <ide> [ 9, 12, 15]]) <del> >>> np.einsum(',ij', 3, C) <add> >>> np.einsum(',ij', 3, c) <ide> array([[ 0, 3, 6], <ide> [ 9, 12, 15]]) <ide> >>> np.einsum(3, [Ellipsis], c, [Ellipsis]) <ide> def einsum(*operands, **kwargs): <ide> array([[ 0, 3, 6], <ide> [ 9, 12, 15]]) <ide> <del> >>> np.einsum('i,i', b, b) <del> 30 <del> >>> np.einsum(b, [0], b, [0]) <del> 30 <del> >>> np.inner(b,b) <del> 30 <add> Vector outer product: <ide> <ide> >>> np.einsum('i,j', np.arange(2)+1, b) <ide> array([[0, 1, 2, 3, 4], <ide> def einsum(*operands, **kwargs): <ide> array([[0, 1, 2, 3, 4], <ide> [0, 2, 4, 6, 8]]) <ide> <del> >>> np.einsum('i...->...', a) <del> array([50, 55, 60, 65, 70]) <del> >>> np.einsum(a, [0,Ellipsis], [Ellipsis]) <del> array([50, 55, 60, 65, 70]) <del> >>> np.sum(a, axis=0) <del> array([50, 55, 60, 65, 70]) <add> Tensor contraction: <ide> <ide> >>> a = np.arange(60.).reshape(3,4,5) <ide> >>> b = np.arange(24.).reshape(4,3,2) <ide> def einsum(*operands, **kwargs): <ide> [ 4796., 5162.], <ide> [ 4928., 5306.]]) <ide> <add> Writeable returned arrays (since version 1.10.0): <add> <add> >>> a = np.zeros((3, 3)) <add> >>> np.einsum('ii->i', a)[:] = 1 <add> >>> a <add> array([[ 1., 0., 0.], <add> [ 0., 1., 0.], <add> [ 0., 0., 1.]]) <add> <add> Example of ellipsis use: <add> <ide> >>> a = np.arange(6).reshape((3,2)) <ide> >>> b = np.arange(12).reshape((4,3)) <ide> >>> np.einsum('ki,jk->ij', a, b) <ide> def einsum(*operands, **kwargs): <ide> array([[10, 28, 46, 64], <ide> [13, 40, 67, 94]]) <ide> <del> >>> # since version 1.10.0 <del> >>> a = np.zeros((3, 3)) <del> >>> np.einsum('ii->i', a)[:] = 1 <del> >>> a <del> array([[ 1., 0., 0.], <del> [ 0., 1., 0.], <del> [ 0., 0., 1.]]) <add> Chained array operations. For more complicated contractions, speed ups <add> might be achieved by repeatedly computing a 'greedy' path or pre-computing the <add> 'optimal' path and repeatedly applying it, using an <add> `einsum_path` insertion (since version 1.12.0). Performance improvements can be <add> particularly significant with larger arrays: <add> <add> >>> a = np.ones(64).reshape(2,4,8) <add> # Basic `einsum`: ~1520ms (benchmarked on 3.1GHz Intel i5.) <add> >>> for iteration in range(500): <add> ... np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a) <add> # Sub-optimal `einsum` (due to repeated path calculation time): ~330ms <add> >>> for iteration in range(500): <add> ... np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize='optimal') <add> # Greedy `einsum` (faster optimal path approximation): ~160ms <add> >>> for iteration in range(500): <add> ... np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize='greedy') <add> # Optimal `einsum` (best usage pattern in some use cases): ~110ms <add> >>> path = np.einsum_path('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize='optimal')[0] <add> >>> for iteration in range(500): <add> ... np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize=path) <ide> <ide> """ <ide>
2
Mixed
Text
add props for overriding native component
f426a83d1bcc33e2e920bf855aee190fceaa1d12
<ide><path>Libraries/Components/WebView/WebView.android.js <ide> var defaultRenderLoading = () => ( <ide> * Renders a native WebView. <ide> */ <ide> class WebView extends React.Component { <add> static get extraNativeComponentConfig() { <add> return { <add> nativeOnly: { <add> messagingEnabled: PropTypes.bool, <add> }, <add> }; <add> } <add> <ide> static propTypes = { <ide> ...ViewPropTypes, <ide> renderError: PropTypes.func, <ide> class WebView extends React.Component { <ide> saveFormDataDisabled: PropTypes.bool, <ide> <ide> /** <add> * Override the native component used to render the WebView. Enables a custom native <add> * WebView which uses the same JavaScript as the original WebView. <add> */ <add> nativeConfig: PropTypes.shape({ <add> /* <add> * The native component used to render the WebView. <add> */ <add> component: PropTypes.any, <add> /* <add> * Set props directly on the native component WebView. Enables custom props which the <add> * original WebView doesn't pass through. <add> */ <add> props: PropTypes.object, <add> /* <add> * Set the ViewManager to use for communcation with the native side. <add> * @platform ios <add> */ <add> viewManager: PropTypes.object, <add> }), <add> /* <ide> * Used on Android only, controls whether the given list of URL prefixes should <ide> * make {@link com.facebook.react.views.webview.ReactWebViewClient} to launch a <ide> * default activity intent for those URL instead of loading it within the webview. <ide> class WebView extends React.Component { <ide> console.warn('WebView: `source.body` is not supported when using GET.'); <ide> } <ide> <add> const nativeConfig = this.props.nativeConfig || {}; <add> <add> let NativeWebView = nativeConfig.component || RCTWebView; <add> <ide> var webView = <del> <RCTWebView <add> <NativeWebView <ide> ref={RCT_WEBVIEW_REF} <ide> key="webViewKey" <ide> style={webViewStyles} <ide> class WebView extends React.Component { <ide> mixedContentMode={this.props.mixedContentMode} <ide> saveFormDataDisabled={this.props.saveFormDataDisabled} <ide> urlPrefixesForDefaultIntent={this.props.urlPrefixesForDefaultIntent} <add> {...nativeConfig.props} <ide> />; <ide> <ide> return ( <ide> class WebView extends React.Component { <ide> } <ide> } <ide> <del>var RCTWebView = requireNativeComponent('RCTWebView', WebView, { <del> nativeOnly: { <del> messagingEnabled: PropTypes.bool, <del> }, <del>}); <add>var RCTWebView = requireNativeComponent('RCTWebView', WebView, WebView.extraNativeComponentConfig); <ide> <ide> var styles = StyleSheet.create({ <ide> container: { <ide><path>Libraries/Components/WebView/WebView.ios.js <ide> var defaultRenderError = (errorDomain, errorCode, errorDesc) => ( <ide> class WebView extends React.Component { <ide> static JSNavigationScheme = JSNavigationScheme; <ide> static NavigationType = NavigationType; <add> static get extraNativeComponentConfig() { <add> return { <add> nativeOnly: { <add> onLoadingStart: true, <add> onLoadingError: true, <add> onLoadingFinish: true, <add> onMessage: true, <add> messagingEnabled: PropTypes.bool, <add> }, <add> }; <add> } <ide> <ide> static propTypes = { <ide> ...ViewPropTypes, <ide> class WebView extends React.Component { <ide> style: ViewPropTypes.style, <ide> <ide> /** <del> * Determines the types of data converted to clickable URLs in the web view’s content. <add> * Determines the types of data converted to clickable URLs in the web view's content. <ide> * By default only phone numbers are detected. <ide> * <ide> * You can provide one type or an array of many types. <ide> class WebView extends React.Component { <ide> 'always', <ide> 'compatibility' <ide> ]), <add> <add> /** <add> * Override the native component used to render the WebView. Enables a custom native <add> * WebView which uses the same JavaScript as the original WebView. <add> */ <add> nativeConfig: PropTypes.shape({ <add> /* <add> * The native component used to render the WebView. <add> */ <add> component: PropTypes.any, <add> /* <add> * Set props directly on the native component WebView. Enables custom props which the <add> * original WebView doesn't pass through. <add> */ <add> props: PropTypes.object, <add> /* <add> * Set the ViewManager to use for communcation with the native side. <add> * @platform ios <add> */ <add> viewManager: PropTypes.object, <add> }), <ide> }; <ide> <ide> static defaultProps = { <ide> class WebView extends React.Component { <ide> webViewStyles.push(styles.hidden); <ide> } <ide> <add> const nativeConfig = this.props.nativeConfig || {}; <add> <add> const viewManager = nativeConfig.viewManager || RCTWebViewManager; <add> <ide> var onShouldStartLoadWithRequest = this.props.onShouldStartLoadWithRequest && ((event: Event) => { <ide> var shouldStart = this.props.onShouldStartLoadWithRequest && <ide> this.props.onShouldStartLoadWithRequest(event.nativeEvent); <del> RCTWebViewManager.startLoadWithResult(!!shouldStart, event.nativeEvent.lockIdentifier); <add> viewManager.startLoadWithResult(!!shouldStart, event.nativeEvent.lockIdentifier); <ide> }); <ide> <ide> var decelerationRate = processDecelerationRate(this.props.decelerationRate); <ide> class WebView extends React.Component { <ide> <ide> const messagingEnabled = typeof this.props.onMessage === 'function'; <ide> <add> const NativeWebView = nativeConfig.component || RCTWebView; <add> <ide> var webView = <del> <RCTWebView <add> <NativeWebView <ide> ref={RCT_WEBVIEW_REF} <ide> key="webViewKey" <ide> style={webViewStyles} <ide> class WebView extends React.Component { <ide> allowsInlineMediaPlayback={this.props.allowsInlineMediaPlayback} <ide> mediaPlaybackRequiresUserAction={this.props.mediaPlaybackRequiresUserAction} <ide> dataDetectorTypes={this.props.dataDetectorTypes} <add> {...nativeConfig.props} <ide> />; <ide> <ide> return ( <ide> class WebView extends React.Component { <ide> } <ide> } <ide> <del>var RCTWebView = requireNativeComponent('RCTWebView', WebView, { <del> nativeOnly: { <del> onLoadingStart: true, <del> onLoadingError: true, <del> onLoadingFinish: true, <del> onMessage: true, <del> messagingEnabled: PropTypes.bool, <del> }, <del>}); <add>var RCTWebView = requireNativeComponent('RCTWebView', WebView, WebView.extraNativeComponentConfig); <ide> <ide> var styles = StyleSheet.create({ <ide> container: { <ide><path>docs/CustomWebViewAndroid.md <add>--- <add>id: custom-webview-android <add>title: Custom WebView <add>layout: docs <add>category: Guides (Android) <add>permalink: docs/custom-webview-android.html <add>banner: ejected <add>next: headless-js-android <add>previous: native-components-android <add>--- <add> <add>While the built-in web view has a lot of features, it is not possible to handle every use-case in React Native. You can, however, extend the web view with native code without forking React Native or duplicating all the existing web view code. <add> <add>Before you do this, you should be familiar with the concepts in [native UI components](native-components-android). You should also familiarise yourself with the [native code for web views](https://github.com/facebook/react-native/blob/master/ReactAndroid/src/main/java/com/facebook/react/views/webview/ReactWebViewManager.java), as you will have to use this as a reference when implementing new features—although a deep understanding is not required. <add> <add>## Native Code <add> <add>To get started, you'll need to create a subclass of `ReactWebViewManager`, `ReactWebView`, and `ReactWebViewClient`. In your view manager, you'll then need to override: <add> <add>* `createReactWebViewInstance` <add>* `getName` <add>* `addEventEmitters` <add> <add>```java <add>@ReactModule(name = CustomWebViewManager.REACT_CLASS) <add>public class CustomWebViewManager extends ReactWebViewManager { <add> /* This name must match what we're referring to in JS */ <add> protected static final String REACT_CLASS = "RCTCustomWebView"; <add> <add> protected static class CustomWebViewClient extends ReactWebViewClient { } <add> <add> protected static class CustomWebView extends ReactWebView { <add> public CustomWebView(ThemedReactContext reactContext) { <add> super(reactContext); <add> } <add> } <add> <add> @Override <add> protected ReactWebView createReactWebViewInstance(ThemedReactContext reactContext) { <add> return new CustomWebView(reactContext); <add> } <add> <add> @Override <add> public String getName() { <add> return REACT_CLASS; <add> } <add> <add> @Override <add> protected void addEventEmitters(ThemedReactContext reactContext, WebView view) { <add> view.setWebViewClient(new CustomWebViewClient()); <add> } <add>} <add>``` <add> <add>You'll need to follow the usual steps to [register the module](docs/native-modules-android.html#register-the-module). <add> <add>### Adding New Properties <add> <add>To add a new property, you'll need to add it to `CustomWebView`, and then expose it in `CustomWebViewManager`. <add> <add>```java <add>public class CustomWebViewManager extends ReactWebViewManager { <add> ... <add> <add> protected static class CustomWebView extends ReactWebView { <add> public CustomWebView(ThemedReactContext reactContext) { <add> super(reactContext); <add> } <add> <add> protected @Nullable String mFinalUrl; <add> <add> public void setFinalUrl(String url) { <add> mFinalUrl = url; <add> } <add> <add> public String getFinalUrl() { <add> return mFinalUrl; <add> } <add> } <add> <add> ... <add> <add> @ReactProp(name = "finalUrl") <add> public void setFinalUrl(WebView view, String url) { <add> ((CustomWebView) view).setFinalUrl(url); <add> } <add>} <add>``` <add> <add>### Adding New Events <add> <add>For events, you'll first need to make create event subclass. <add> <add>```java <add>// NavigationCompletedEvent.java <add>public class NavigationCompletedEvent extends Event<NavigationCompletedEvent> { <add> private WritableMap mParams; <add> <add> public NavigationCompletedEvent(int viewTag, WritableMap params) { <add> super(viewTag); <add> this.mParams = params; <add> } <add> <add> @Override <add> public String getEventName() { <add> return "navigationCompleted"; <add> } <add> <add> @Override <add> public void dispatch(RCTEventEmitter rctEventEmitter) { <add> init(getViewTag()); <add> rctEventEmitter.receiveEvent(getViewTag(), getEventName(), mParams); <add> } <add>} <add>``` <add> <add>You can trigger the event in your web view client. You can hook existing handlers if your events are based on them. <add> <add>You should refer to [ReactWebViewManager.java](https://github.com/facebook/react-native/blob/master/ReactAndroid/src/main/java/com/facebook/react/views/webview/ReactWebViewManager.java) in the React Native codebase to see what handlers are available and how they are implemented. You can extend any methods here to provide extra functionality. <add> <add>```java <add>public class NavigationCompletedEvent extends Event<NavigationCompletedEvent> { <add> private WritableMap mParams; <add> <add> public NavigationCompletedEvent(int viewTag, WritableMap params) { <add> super(viewTag); <add> this.mParams = params; <add> } <add> <add> @Override <add> public String getEventName() { <add> return "navigationCompleted"; <add> } <add> <add> @Override <add> public void dispatch(RCTEventEmitter rctEventEmitter) { <add> init(getViewTag()); <add> rctEventEmitter.receiveEvent(getViewTag(), getEventName(), mParams); <add> } <add>} <add> <add>// CustomWebViewManager.java <add>protected static class CustomWebViewClient extends ReactWebViewClient { <add> @Override <add> public boolean shouldOverrideUrlLoading(WebView view, String url) { <add> boolean shouldOverride = super.shouldOverrideUrlLoading(view, url); <add> String finalUrl = ((CustomWebView) view).getFinalUrl(); <add> <add> if (!shouldOverride && url != null && finalUrl != null && new String(url).equals(finalUrl)) { <add> final WritableMap params = Arguments.createMap(); <add> dispatchEvent(view, new NavigationCompletedEvent(view.getId(), params)); <add> } <add> <add> return shouldOverride; <add> } <add>} <add>``` <add> <add>Finally, you'll need to expose the events in `CustomWebViewManager` through `getExportedCustomDirectEventTypeConstants`. Note that currently, the default implementation returns `null`, but this may change in the future. <add> <add>```java <add>public class CustomWebViewManager extends ReactWebViewManager { <add> ... <add> <add> @Override <add> public @Nullable <add> Map getExportedCustomDirectEventTypeConstants() { <add> Map<String, Object> export = super.getExportedCustomDirectEventTypeConstants(); <add> if (export == null) { <add> export = MapBuilder.newHashMap(); <add> } <add> export.put("navigationCompleted", MapBuilder.of("registrationName", "onNavigationCompleted")); <add> return export; <add> } <add>} <add>``` <add> <add>## JavaScript Interface <add> <add>To use your custom web view, you'll need to create a class for it. Your class must: <add> <add>* Export all the prop types from `WebView.propTypes` <add>* Return a `WebView` component with the prop `nativeConfig.component` set to your native component (see below) <add> <add>To get your native component, you must use `requireNativeComponent`: the same as for regular custom components. However, you must pass in an extra third argument, `WebView.extraNativeComponentConfig`. This third argument contains prop types that are only required for native code. <add> <add>```js <add>import React, { Component, PropTypes } from 'react'; <add>import { WebView, requireNativeComponent } from 'react-native'; <add> <add>export default class CustomWebView extends Component { <add> static propTypes = WebView.propTypes <add> <add> render() { <add> return ( <add> <WebView <add> {...this.props} <add> nativeConfig={{ component: RCTCustomWebView }} <add> /> <add> ); <add> } <add>} <add> <add>const RCTCustomWebView = requireNativeComponent( <add> 'RCTCustomWebView', <add> CustomWebView, <add> WebView.extraNativeComponentConfig <add>); <add>``` <add> <add>If you want to add custom props to your native component, you can use `nativeConfig.props` on the web view. <add> <add>For events, the event handler must always be set to a function. This means it isn't safe to use the event handler directly from `this.props`, as the user might not have provided one. The standard approach is to create a event handler in your class, and then invoking the event handler given in `this.props` if it exists. <add> <add>If you are unsure how something should be implemented from the JS side, look at [WebView.android.js](https://github.com/facebook/react-native/blob/master/Libraries/Components/WebView/WebView.android.js) in the React Native source. <add> <add>```js <add>export default class CustomWebView extends Component { <add> static propTypes = { <add> ...WebView.propTypes, <add> finalUrl: PropTypes.string, <add> onNavigationCompleted: PropTypes.func, <add> }; <add> <add> static defaultProps = { <add> finalUrl: 'about:blank', <add> }; <add> <add> _onNavigationCompleted = (event) => { <add> const { onNavigationCompleted } = this.props; <add> onNavigationCompleted && onNavigationCompleted(event); <add> } <add> <add> render() { <add> return ( <add> <WebView <add> {...this.props} <add> nativeConfig={{ <add> component: RCTCustomWebView, <add> props: { <add> finalUrl: this.props.finalUrl, <add> onNavigationCompleted: this._onNavigationCompleted, <add> } <add> }} <add> /> <add> ); <add> } <add>} <add>``` <add> <add>Just like for regular native components, you must provide all your prop types in the component to have them forwarded on to the native component. However, if you have some prop types that are only used internally in component, you can add them to the `nativeOnly` property of the third argument previously mentioned. For event handlers, you have to use the value `true` instead of a regular prop type. <add> <add>For example, if you wanted to add an internal event handler called `onScrollToBottom`, you would use, <add> <add>```js <add>const RCTCustomWebView = requireNativeComponent( <add> 'RCTCustomWebView', <add> CustomWebView, <add> { <add> ...WebView.extraNativeComponentConfig, <add> nativeOnly: { <add> ...WebView.extraNativeComponentConfig.nativeOnly, <add> onScrollToBottom: true, <add> }, <add> } <add>); <add>``` <ide><path>docs/CustomWebViewIOS.md <add>--- <add>id: custom-webview-ios <add>title: Custom WebView <add>layout: docs <add>category: Guides (iOS) <add>permalink: docs/custom-webview-ios.html <add>banner: ejected <add>next: linking-libraries-ios <add>previous: native-components-ios <add>--- <add> <add>While the built-in web view has a lot of features, it is not possible to handle every use-case in React Native. You can, however, extend the web view with native code without forking React Native or duplicating all the existing web view code. <add> <add>Before you do this, you should be familiar with the concepts in [native UI components](native-components-ios). You should also familiarise yourself with the [native code for web views](https://github.com/facebook/react-native/blob/master/React/Views/RCTWebViewManager.m), as you will have to use this as a reference when implementing new features—although a deep understanding is not required. <add> <add>## Native Code <add> <add>Like for regular native components, you need a view manager and an web view. <add> <add>For the view, you'll need to make a subclass of `RCTWebView`. <add> <add>```objc <add>// RCTCustomWebView.h <add>#import <React/RCTWebView.h> <add> <add>@interface RCTCustomWebView : RCTWebView <add> <add>@end <add> <add>// RCTCustomWebView.m <add>#import "RCTCustomWebView.h" <add> <add>@interface RCTCustomWebView () <add> <add>@end <add> <add>@implementation RCTCustomWebView { } <add> <add>@end <add>``` <add> <add>For the view manager, you need to make a subclass `RCTWebViewManager`. You must still include: <add> <add>* `(UIView *)view` that returns your custom view <add>* The `RCT_EXPORT_MODULE()` tag <add> <add>```objc <add>// RCTCustomWebViewManager.h <add>#import <React/RCTWebViewManager.h> <add> <add>@interface RCTCustomWebViewManager : RCTWebViewManager <add> <add>@end <add> <add>// RCTCustomWebViewManager.m <add>#import "RCTCustomWebViewManager.h" <add>#import "RCTCustomWebView.h" <add> <add>@interface RCTCustomWebViewManager () <RCTWebViewDelegate> <add> <add>@end <add> <add>@implementation RCTCustomWebViewManager { } <add> <add>RCT_EXPORT_MODULE() <add> <add>- (UIView *)view <add>{ <add> RCTCustomWebView *webView = [RCTCustomWebView new]; <add> webView.delegate = self; <add> return webView; <add>} <add> <add>@end <add>``` <add> <add>### Adding New Events and Properties <add> <add>Adding new properties and events is the same as regular UI components. For properties, you define an `@property` in the header. For events, you define a `RCTDirectEventBlock` in the view's `@interface`. <add> <add>```objc <add>// RCTCustomWebView.h <add>@property (nonatomic, copy) NSString *finalUrl; <add> <add>// RCTCustomWebView.m <add>@interface RCTCustomWebView () <add> <add>@property (nonatomic, copy) RCTDirectEventBlock onNavigationCompleted; <add> <add>@end <add>``` <add> <add>Then expose it in the view manager's `@implementation`. <add> <add>```objc <add>// RCTCustomWebViewManager.m <add>RCT_EXPORT_VIEW_PROPERTY(onNavigationCompleted, RCTDirectEventBlock) <add>RCT_EXPORT_VIEW_PROPERTY(finalUrl, NSString) <add>``` <add> <add>### Extending Existing Events <add> <add>You should refer to [RCTWebView.m](https://github.com/facebook/react-native/blob/master/React/Views/RCTWebView.m) in the React Native codebase to see what handlers are available and how they are implemented. You can extend any methods here to provide extra functionality. <add> <add>By default, most methods aren't exposed from RCTWebView. If you need to expose them, you need to create an [Objective C category](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/CustomizingExistingClasses/CustomizingExistingClasses.html), and then expose all the methods you need to use. <add> <add>```objc <add>// RCTWebView+Custom.h <add>#import <React/RCTWebView.h> <add> <add>@interface RCTWebView (Custom) <add>- (BOOL)webView:(__unused UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType; <add>- (NSMutableDictionary<NSString *, id> *)baseEvent; <add>@end <add>``` <add> <add>Once these are exposed, you can reference them in your custom web view class. <add> <add>```objc <add>// RCTCustomWebView.m <add> <add>// Remember to import the category file. <add>#import "RCTWebView+Custom.h" <add> <add>- (BOOL)webView:(__unused UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request <add> navigationType:(UIWebViewNavigationType)navigationType <add>{ <add> BOOL allowed = [super webView:webView shouldStartLoadWithRequest:request navigationType:navigationType]; <add> <add> if (allowed) { <add> NSString* url = request.URL.absoluteString; <add> if (url && [url isEqualToString:_finalUrl]) { <add> if (_onNavigationCompleted) { <add> NSMutableDictionary<NSString *, id> *event = [self baseEvent]; <add> _onNavigationCompleted(event); <add> } <add> } <add> } <add> <add> return allowed; <add>} <add>``` <add> <add>## JavaScript Interface <add> <add>To use your custom web view, you'll need to create a class for it. Your class must: <add> <add>* Export all the prop types from `WebView.propTypes` <add>* Return a `WebView` component with the prop `nativeConfig.component` set to your native component (see below) <add> <add>To get your native component, you must use `requireNativeComponent`: the same as for regular custom components. However, you must pass in an extra third argument, `WebView.extraNativeComponentConfig`. This third argument contains prop types that are only required for native code. <add> <add>```js <add>import React, { Component, PropTypes } from 'react'; <add>import { WebView, requireNativeComponent, NativeModules } from 'react-native'; <add>const { CustomWebViewManager } = NativeModules; <add> <add>export default class CustomWebView extends Component { <add> static propTypes = WebView.propTypes <add> <add> render() { <add> return ( <add> <WebView <add> {...this.props} <add> nativeConfig={{ <add> component: RCTCustomWebView, <add> viewManager: CustomWebViewManager <add> }} <add> /> <add> ); <add> } <add>} <add> <add>const RCTCustomWebView = requireNativeComponent( <add> 'RCTCustomWebView', <add> CustomWebView, <add> WebView.extraNativeComponentConfig <add>); <add>``` <add> <add>If you want to add custom props to your native component, you can use `nativeConfig.props` on the web view. For iOS, you should also set the `nativeConfig.viewManager` prop with your custom WebView ViewManager as in the example above. <add> <add>For events, the event handler must always be set to a function. This means it isn't safe to use the event handler directly from `this.props`, as the user might not have provided one. The standard approach is to create a event handler in your class, and then invoking the event handler given in `this.props` if it exists. <add> <add>If you are unsure how something should be implemented from the JS side, look at [WebView.ios.js](https://github.com/facebook/react-native/blob/master/Libraries/Components/WebView/WebView.ios.js) in the React Native source. <add> <add>```js <add>export default class CustomWebView extends Component { <add> static propTypes = { <add> ...WebView.propTypes, <add> finalUrl: PropTypes.string, <add> onNavigationCompleted: PropTypes.func, <add> }; <add> <add> static defaultProps = { <add> finalUrl: 'about:blank', <add> }; <add> <add> _onNavigationCompleted = (event) => { <add> const { onNavigationCompleted } = this.props; <add> onNavigationCompleted && onNavigationCompleted(event); <add> } <add> <add> render() { <add> return ( <add> <WebView <add> {...this.props} <add> nativeConfig={{ <add> component: RCTCustomWebView, <add> props: { <add> finalUrl: this.props.finalUrl, <add> onNavigationCompleted: this._onNavigationCompleted, <add> }, <add> viewManager: CustomWebViewManager <add> }} <add> /> <add> ); <add> } <add>} <add>``` <add> <add>Just like for regular native components, you must provide all your prop types in the component to have them forwarded on to the native component. However, if you have some prop types that are only used internally in component, you can add them to the `nativeOnly` property of the third argument previously mentioned. For event handlers, you have to use the value `true` instead of a regular prop type. <add> <add>For example, if you wanted to add an internal event handler called `onScrollToBottom`, you would use, <add> <add>```js <add>const RCTCustomWebView = requireNativeComponent( <add> 'RCTCustomWebView', <add> CustomWebView, <add> { <add> ...WebView.extraNativeComponentConfig, <add> nativeOnly: { <add> ...WebView.extraNativeComponentConfig.nativeOnly, <add> onScrollToBottom: true, <add> }, <add> } <add>); <add>``` <ide><path>docs/HeadlessJSAndroid.md <ide> category: Guides (Android) <ide> permalink: docs/headless-js-android.html <ide> banner: ejected <ide> next: signed-apk-android <del>previous: native-components-android <add>previous: custom-webview-android <ide> --- <ide> <ide> Headless JS is a way to run tasks in JavaScript while your app is in the background. It can be used, for example, to sync fresh data, handle push notifications, or play music. <ide><path>docs/LinkingLibraries.md <ide> category: Guides (iOS) <ide> permalink: docs/linking-libraries-ios.html <ide> banner: ejected <ide> next: running-on-simulator-ios <del>previous: native-components-ios <add>previous: custom-webview-ios <ide> --- <ide> <ide> Not every app uses all the native capabilities, and including the code to support <ide><path>docs/NativeComponentsAndroid.md <ide> layout: docs <ide> category: Guides (Android) <ide> permalink: docs/native-components-android.html <ide> banner: ejected <del>next: headless-js-android <add>next: custom-webview-android <ide> previous: native-modules-android <ide> --- <ide> <ide><path>docs/NativeComponentsIOS.md <ide> layout: docs <ide> category: Guides (iOS) <ide> permalink: docs/native-components-ios.html <ide> banner: ejected <del>next: linking-libraries-ios <add>next: custom-webview-ios <ide> previous: native-modules-ios <ide> --- <ide>
8
Python
Python
add class docs for nodeauth classes
792790c554c43b4d9e73ffb9d7fec096373797e7
<ide><path>libcloud/base.py <ide> def __repr__(self): <ide> % (self.id, self.name, self.country, self.driver.name)) <ide> <ide> class NodeAuthSSHKey(object): <add> """ <add> An SSH key to be installed for authentication to a node. <add> """ <ide> def __init__(self, pubkey): <ide> self.pubkey = pubkey <ide> def __repr__(self): <ide> return '<NodeAuthSSHKey>' <ide> <ide> class NodeAuthPassword(object): <add> """ <add> A password to be used for authentication to a node. <add> """ <ide> def __init__(self, password): <ide> self.password = password <ide> def __repr__(self):
1
Javascript
Javascript
replace var with let
411c1a679d7a6c47dadc257a5ed35b6f7589688b
<ide><path>lib/internal/streams/end-of-stream.js <ide> function eos(stream, opts, callback) { <ide> if (!stream.writable) onfinish(); <ide> }; <ide> <del> var writableEnded = stream._writableState && stream._writableState.finished; <add> let writableEnded = stream._writableState && stream._writableState.finished; <ide> const onfinish = () => { <ide> writable = false; <ide> writableEnded = true; <ide> if (!readable) callback.call(stream); <ide> }; <ide> <del> var readableEnded = stream.readableEnded || <add> let readableEnded = stream.readableEnded || <ide> (stream._readableState && stream._readableState.endEmitted); <ide> const onend = () => { <ide> readable = false;
1
Text
Text
fix several typos in distil* readme
5bc99e7f33c83b23b88740877283098ef7964b73
<ide><path>examples/distillation/README.md <ide> This folder contains the original code used to train Distil* as well as examples <ide> <ide> **October 23, 2019 - Update** We release **DistilRoBERTa**: 95% of `RoBERTa-base`'s performance on GLUE, twice as fast as RoBERTa while being 35% smaller. <ide> <del>**October 3, 2019 - Update** We release our [NeurIPS workshop paper](https://arxiv.org/abs/1910.01108) explaining our approach on **DistilBERT**. It includes updated results and further experiments. We applied the same method to GPT2 and release the weights of **DistilGPT2**. DistilGPT2 is two times faster and 33% smaller than GPT2. **The paper superseeds our [previous blogpost](https://medium.com/huggingface/distilbert-8cf3380435b5) with a different distillation loss and better performances. Please use the paper as a reference when comparing/reporting results on DistilBERT.** <add>**October 3, 2019 - Update** We release our [NeurIPS workshop paper](https://arxiv.org/abs/1910.01108) explaining our approach on **DistilBERT**. It includes updated results and further experiments. We applied the same method to GPT2 and release the weights of **DistilGPT2**. DistilGPT2 is two times faster and 33% smaller than GPT2. **The paper supersedes our [previous blogpost](https://medium.com/huggingface/distilbert-8cf3380435b5) with a different distillation loss and better performances. Please use the paper as a reference when comparing/reporting results on DistilBERT.** <ide> <ide> **September 19, 2019 - Update:** We fixed bugs in the code and released an upadted version of the weights trained with a modification of the distillation loss. DistilBERT now reaches 99% of `BERT-base`'s performance on GLUE, and 86.9 F1 score on SQuAD v1.1 dev set (compared to 88.5 for `BERT-base`). We will publish a formal write-up of our approach in the near future! <ide> <ide> Here are the results on the dev sets of GLUE: <ide> | RoBERTa-base (reported) | **83.2**/**86.4**<sup>2</sup> | 63.6 | 87.6 | 90.2 | 92.8 | 91.9 | 78.7 | 94.8 | 91.2 | 57.7<sup>3</sup> | <ide> | DistilRoBERTa<sup>1</sup> | **79.0**/**82.3**<sup>2</sup> | 59.3 | 84.0 | 86.6 | 90.8 | 89.4 | 67.9 | 92.5 | 88.3 | 52.1 | <ide> <del><sup>1</sup> We did not use the MNLI checkpoint for fine-tuning but directy perform transfer learning on the pre-trained DistilRoBERTa. <add><sup>1</sup> We did not use the MNLI checkpoint for fine-tuning but directly perform transfer learning on the pre-trained DistilRoBERTa. <ide> <ide> <sup>2</sup> Macro-score computed without WNLI. <ide> <ide> This part of the library has only be tested with Python3.6+. There are few speci <ide> Transformers includes five pre-trained Distil* models, currently only provided for English and German (we are investigating the possibility to train and release a multilingual version of DistilBERT): <ide> <ide> - `distilbert-base-uncased`: DistilBERT English language model pretrained on the same data used to pretrain Bert (concatenation of the Toronto Book Corpus and full English Wikipedia) using distillation with the supervision of the `bert-base-uncased` version of Bert. The model has 6 layers, 768 dimension and 12 heads, totalizing 66M parameters. <del>- `distilbert-base-uncased-distilled-squad`: A finetuned version of `distilbert-base-uncased` finetuned using (a second step of) knwoledge distillation on SQuAD 1.0. This model reaches a F1 score of 79.8 on the dev set (for comparison, Bert `bert-base-uncased` version reaches a 82.3 F1 score). <add>- `distilbert-base-uncased-distilled-squad`: A finetuned version of `distilbert-base-uncased` finetuned using (a second step of) knowledge distillation on SQuAD 1.0. This model reaches a F1 score of 79.8 on the dev set (for comparison, Bert `bert-base-uncased` version reaches a 82.3 F1 score). <ide> - `distilbert-base-cased`: DistilBERT English language model pretrained on the same data used to pretrain Bert (concatenation of the Toronto Book Corpus and full English Wikipedia) using distillation with the supervision of the `bert-base-cased` version of Bert. The model has 6 layers, 768 dimension and 12 heads, totalizing 65M parameters. <del>- `distilbert-base-cased-distilled-squad`: A finetuned version of `distilbert-base-cased` finetuned using (a second step of) knwoledge distillation on SQuAD 1.0. This model reaches a F1 score of 87.1 on the dev set (for comparison, Bert `bert-base-cased` version reaches a 88.7 F1 score). <add>- `distilbert-base-cased-distilled-squad`: A finetuned version of `distilbert-base-cased` finetuned using (a second step of) knowledge distillation on SQuAD 1.0. This model reaches a F1 score of 87.1 on the dev set (for comparison, Bert `bert-base-cased` version reaches a 88.7 F1 score). <ide> - `distilbert-base-german-cased`: DistilBERT German language model pretrained on 1/2 of the data used to pretrain Bert using distillation with the supervision of the `bert-base-german-dbmdz-cased` version of German DBMDZ Bert. For NER tasks the model reaches a F1 score of 83.49 on the CoNLL-2003 test set (for comparison, `bert-base-german-dbmdz-cased` reaches a 84.52 F1 score), and a F1 score of 85.23 on the GermEval 2014 test set (`bert-base-german-dbmdz-cased` reaches a 86.89 F1 score). <ide> - `distilgpt2`: DistilGPT2 English language model pretrained with the supervision of `gpt2` (the smallest version of GPT2) on [OpenWebTextCorpus](https://skylion007.github.io/OpenWebTextCorpus/), a reproduction of OpenAI's WebText dataset. The model has 6 layers, 768 dimension and 12 heads, totalizing 82M parameters (compared to 124M parameters for GPT2). On average, DistilGPT2 is two times faster than GPT2. <ide> - `distilroberta-base`: DistilRoBERTa English language model pretrained with the supervision of `roberta-base` solely on [OpenWebTextCorpus](https://skylion007.github.io/OpenWebTextCorpus/), a reproduction of OpenAI's WebText dataset (it is ~4 times less training data than the teacher RoBERTa). The model has 6 layers, 768 dimension and 12 heads, totalizing 82M parameters (compared to 125M parameters for RoBERTa-base). On average DistilRoBERTa is twice as fast as Roberta-base. <ide> python scripts/binarized_data.py \ <ide> --dump_file data/binarized_text <ide> ``` <ide> <del>Our implementation of masked language modeling loss follows [XLM](https://github.com/facebookresearch/XLM)'s one and smoothes the probability of masking with a factor that put more emphasis on rare words. Thus we count the occurences of each tokens in the data: <add>Our implementation of masked language modeling loss follows [XLM](https://github.com/facebookresearch/XLM)'s one and smoothes the probability of masking with a factor that put more emphasis on rare words. Thus we count the occurrences of each tokens in the data: <ide> <ide> ```bash <ide> python scripts/token_counts.py \
1
Text
Text
fix internal links
f64661fb18e3147bb0ab70c3741e5403ad1e600a
<ide><path>share/doc/homebrew/Homebrew-0.9.3.md <ide> Because we are working with a practically virgin environment, we are essentially <ide> <ide> So: <ide> <del>* We no longer worry about MacPorts/Fink being installed<sup>[†](#_†)</sup> <del>* We no longer worry about system duplicates<sup>[†](#_†)</sup> <add>* We no longer worry about MacPorts/Fink being installed<sup>[0](#_0)</sup> <add>* We no longer worry about system duplicates<sup>[0](#_0)</sup> <ide> * We override common tools and fix them—we no longer have to do so with workarounds in affected formula, waiting for a fix from Apple. <ide> * Builds are forcibly optimized how we want, and debug info forcibly removed. <ide> <ide> So: <ide> ## Footnotes <ide> <div style="color: #555; font-size: 85%"> <ide> <ul> <del> <li><a id="_†"><sup>†</sup></a>: Nearly as much, anyway.</li> <add> <li><a id="_0"><sup>0</sup></a>: Nearly as much, anyway.</li> <ide> <li><a id="_1"><sup>1</sup></a>: Formula can opt-into re-adding the user’s <code>PATH</code> again. Some formulae need this.</li> <ide> <li><a id="_2"><sup>2</sup></a>: Indeed; this is selected based on Xcode version.</li> <ide> </ul>
1
Text
Text
update maxpooling1d documentation
e1d8b1ba094a0766e703f89d4cf7c8b1d3e7cd6c
<ide><path>docs/sources/layers/convolutional.md <ide> keras.layers.convolutional.MaxPooling1D(pool_length=2, stride=None, ignore_borde <ide> <ide> - __Input shape__: 3D tensor with shape: `(nb_samples, steps, dim)`. <ide> <del>- __Output shape__: 3D tensor with shape: `(nb_samples, steps, new_dim)`. <add>- __Output shape__: 3D tensor with shape: `(nb_samples, downsampled_steps, dim)`. <ide> <ide> - __Arguments__: <ide>
1
Javascript
Javascript
fix some nits
fb31dc3f86e137fd0a56dba711033d70c0b97210
<ide><path>extensions/firefox/components/PdfStreamConverter.js <ide> function log(aMsg) { <ide> Services.console.logStringMessage(msg); <ide> dump(msg + '\n'); <ide> } <del>function getWindow(top, id) top.QueryInterface(Ci.nsIInterfaceRequestor) <del> .getInterface(Ci.nsIDOMWindowUtils) <del> .getOuterWindowWithId(id); <del>function windowID(win) win.QueryInterface(Ci.nsIInterfaceRequestor) <del> .getInterface(Ci.nsIDOMWindowUtils) <del> .outerWindowID; <del>function topWindow(win) win.QueryInterface(Ci.nsIInterfaceRequestor) <del> .getInterface(Ci.nsIWebNavigation) <del> .QueryInterface(Ci.nsIDocShellTreeItem) <del> .rootTreeItem <del> .QueryInterface(Ci.nsIInterfaceRequestor) <del> .getInterface(Ci.nsIDOMWindow); <add>function getWindow(top, id) { <add> return top.QueryInterface(Ci.nsIInterfaceRequestor) <add> .getInterface(Ci.nsIDOMWindowUtils) <add> .getOuterWindowWithId(id); <add>} <add>function windowID(win) { <add> return win.QueryInterface(Ci.nsIInterfaceRequestor) <add> .getInterface(Ci.nsIDOMWindowUtils) <add> .outerWindowID; <add>} <add>function topWindow(win) { <add> return win.QueryInterface(Ci.nsIInterfaceRequestor) <add> .getInterface(Ci.nsIWebNavigation) <add> .QueryInterface(Ci.nsIDocShellTreeItem) <add> .rootTreeItem <add> .QueryInterface(Ci.nsIInterfaceRequestor) <add> .getInterface(Ci.nsIDOMWindow); <add>} <ide> let application = Cc['@mozilla.org/fuel/application;1'] <ide> .getService(Ci.fuelIApplication); <ide> let privateBrowsing = Cc['@mozilla.org/privatebrowsing;1'] <ide> PdfStreamConverter.prototype = { <ide> // an event listener on that window for the pdf.js events that require <ide> // chrome priviledges. Code snippet from John Galt. <ide> let window = aRequest.loadGroup.groupObserver <del> .QueryInterface(Ci.nsIWebProgress) <del> .DOMWindow; <add> .QueryInterface(Ci.nsIWebProgress) <add> .DOMWindow; <ide> let top = topWindow(window); <ide> let id = windowID(window); <ide> window = null; <ide> PdfStreamConverter.prototype = { <ide> let win = doc.defaultView; <ide> <ide> if (id == windowID(win)) { <del> top.removeEventListener('DOMWindowCreated', onDOMWinCreated, true); <del> if (!doc.documentURIObject.equals(aRequest.URI)) <del> return; <del> <del> let requestListener = new RequestListener(new ChromeActions); <del> win.addEventListener(PDFJS_EVENT_ID, function(event) { <del> requestListener.receive(event); <del> }, false, true); <add> top.removeEventListener('DOMWindowCreated', onDOMWinCreated, true); <add> if (!doc.documentURIObject.equals(aRequest.URI)) <add> return; <add> <add> let requestListener = new RequestListener(new ChromeActions); <add> win.addEventListener(PDFJS_EVENT_ID, function(event) { <add> requestListener.receive(event); <add> }, false, true); <ide> } else if (!getWindow(top, id)) { <ide> top.removeEventListener('DOMWindowCreated', onDOMWinCreated, true); <ide> }
1
Javascript
Javascript
remove http 1223 handling
a9831131c307a050a27d29d75925d7d4ad162da5
<ide><path>lib/adapters/xhr.js <ide> module.exports = function xhrAdapter(config) { <ide> var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response; <ide> var response = { <ide> data: responseData, <del> // IE sends 1223 instead of 204 (https://github.com/axios/axios/issues/201) <del> status: request.status === 1223 ? 204 : request.status, <del> statusText: request.status === 1223 ? 'No Content' : request.statusText, <add> status: request.status, <add> statusText: request.statusText, <ide> headers: responseHeaders, <ide> config: config, <ide> request: request <ide><path>test/specs/requests.spec.js <ide> describe('requests', function () { <ide> }); <ide> }); <ide> <del> // https://github.com/axios/axios/issues/201 <del> it('should fix IE no content error', function (done) { <del> var response; <del> <del> axios('/foo').then(function (res) { <del> response = res <del> }); <del> <del> getAjaxRequest().then(function (request) { <del> request.respondWith({ <del> status: 1223, <del> statusText: 'Unknown' <del> }); <del> <del> setTimeout(function () { <del> expect(response.status).toEqual(204); <del> expect(response.statusText).toEqual('No Content'); <del> done(); <del> }, 100); <del> }); <del> }); <del> <ide> it('should allow overriding Content-Type header case-insensitive', function (done) { <ide> var response; <ide> var contentType = 'application/vnd.myapp.type+json';
2
Text
Text
create github support file
f46952289a35ccfb4ff6a9ebfb31f40a5de449f6
<ide><path>.github/SUPPORT.md <add># Support <add> <add>Node.js contributors have limited availability to address general support <add>questions. Please make sure you are using a [currently-supported version of <add>Node.js](https://github.com/nodejs/Release#release-schedule). <add> <add>When looking for support, please first search for your question in these venues: <add> <add>* [Node.js Website](https://nodejs.org/en/), especially the <add> [API docs](https://nodejs.org/api/) <add>* [Node.js Help](https://github.com/nodejs/help) <add>* [Open or closed issues in the Node.js GitHub organization](https://github.com/issues?utf8=%E2%9C%93&q=sort%3Aupdated-desc+org%3Anodejs+is%3Aissue) <add> <add>If you didn't find an answer in the resources above, try these unofficial <add>resources: <add> <add>* [Questions tagged 'node.js' on Stack Overflow](https://stackoverflow.com/questions/tagged/node.js) <add>* [#node.js channel on chat.freenode.net](https://webchat.freenode.net?channels=node.js&uio=d4) <add>* [Node.js Slack Community](https://node-js.slack.com/) <add> * To register: [nodeslackers.com](http://www.nodeslackers.com/) <add> <add>GitHub issues are for tracking enhancements and bugs, not general support. <add> <add>The open source license grants you the freedom to use Node.js. It does not <add>guarantee commitments of other people's time. Please be respectful and manage <add>your expectations. <ide><path>README.md <ide> The Node.js project uses an [open governance model](./GOVERNANCE.md). The <ide> <ide> ## Support <ide> <del>Node.js contributors have limited availability to address general support <del>questions. Please make sure you are using a [currently-supported version of <del>Node.js](https://github.com/nodejs/Release#release-schedule). <del> <del>When looking for support, please first search for your question in these venues: <del> <del>* [Node.js Website][] <del>* [Node.js Help][] <del>* [Open or closed issues in the Node.js GitHub organization](https://github.com/issues?utf8=%E2%9C%93&q=sort%3Aupdated-desc+org%3Anodejs+is%3Aissue) <del> <del>If you didn't find an answer in the resources above, try these unofficial <del>resources: <del> <del>* [Questions tagged 'node.js' on StackOverflow][] <del>* [#node.js channel on chat.freenode.net][] <del>* [Node.js Slack Community](https://node-js.slack.com/) <del> * To register: [nodeslackers.com](http://www.nodeslackers.com/) <del> <del>GitHub issues are for tracking enhancements and bugs, not general support. <del> <del>The open source license grants you the freedom to use Node.js. It does not <del>guarantee commitments of other people's time. Please be respectful and manage <del>your expectations. <add>Looking for help? Check out the <add>[instructions for getting support](.github/SUPPORT.md). <ide> <ide> ## Release Types <ide> <ide> Other keys used to sign some previous releases: <ide> <ide> [Code of Conduct]: https://github.com/nodejs/admin/blob/master/CODE_OF_CONDUCT.md <ide> [Contributing to the project]: CONTRIBUTING.md <del>[Node.js Help]: https://github.com/nodejs/help <ide> [Node.js Foundation]: https://nodejs.org/en/foundation/ <del>[Node.js Website]: https://nodejs.org/en/ <del>[Questions tagged 'node.js' on StackOverflow]: https://stackoverflow.com/questions/tagged/node.js <ide> [Working Groups]: https://github.com/nodejs/TSC/blob/master/WORKING_GROUPS.md <ide> [Strategic Initiatives]: https://github.com/nodejs/TSC/blob/master/Strategic-Initiatives.md <del>[#node.js channel on chat.freenode.net]: https://webchat.freenode.net?channels=node.js&uio=d4
2
Go
Go
remove unneeded alias
881e326f7ae05c8c5de07f2ef6dbd79b23327a62
<ide><path>daemon/config/config_linux.go <ide> import ( <ide> "net" <ide> <ide> "github.com/docker/docker/api/types" <del> containertypes "github.com/docker/docker/api/types/container" <add> "github.com/docker/docker/api/types/container" <ide> "github.com/docker/docker/opts" <ide> units "github.com/docker/go-units" <ide> ) <ide> <ide> const ( <ide> // DefaultIpcMode is default for container's IpcMode, if not set otherwise <del> DefaultIpcMode = containertypes.IPCModePrivate <add> DefaultIpcMode = container.IPCModePrivate <ide> <ide> // DefaultCgroupNamespaceMode is the default mode for containers cgroup namespace when using cgroups v2. <del> DefaultCgroupNamespaceMode = containertypes.CgroupnsModePrivate <add> DefaultCgroupNamespaceMode = container.CgroupnsModePrivate <ide> <ide> // DefaultCgroupV1NamespaceMode is the default mode for containers cgroup namespace when using cgroups v1. <del> DefaultCgroupV1NamespaceMode = containertypes.CgroupnsModeHost <add> DefaultCgroupV1NamespaceMode = container.CgroupnsModeHost <ide> <ide> // StockRuntimeName is the reserved name/alias used to represent the <ide> // OCI runtime being shipped with the docker daemon package. <ide> func (conf *Config) IsSwarmCompatible() error { <ide> func verifyDefaultIpcMode(mode string) error { <ide> const hint = `use "shareable" or "private"` <ide> <del> dm := containertypes.IpcMode(mode) <add> dm := container.IpcMode(mode) <ide> if !dm.Valid() { <ide> return fmt.Errorf("default IPC mode setting (%v) is invalid; "+hint, dm) <ide> } <ide> func verifyDefaultIpcMode(mode string) error { <ide> } <ide> <ide> func verifyDefaultCgroupNsMode(mode string) error { <del> cm := containertypes.CgroupnsMode(mode) <add> cm := container.CgroupnsMode(mode) <ide> if !cm.Valid() { <ide> return fmt.Errorf(`default cgroup namespace mode (%v) is invalid; use "host" or "private"`, cm) <ide> }
1
Javascript
Javascript
convert non-error errors into errors
6a7e79a443cb1f1adde675ee5321302b0c5cff1b
<ide><path>lib/NormalModule.js <ide> class NormalModule extends Module { <ide> } <ide> <ide> if (err) { <add> if (!(err instanceof Error)) { <add> err = new NonErrorEmittedError(err); <add> } <ide> const currentLoader = this.getCurrentLoader(loaderContext); <ide> const error = new ModuleBuildError(this, err, { <ide> from:
1
Python
Python
add test for negative axis values in np.insert
9d6caf9710e98af2a99cc72650b95dd7ea0727ee
<ide><path>numpy/lib/tests/test_function_base.py <ide> def test_multidim(self): <ide> assert_raises(IndexError, insert, a, 1, a[:, 2, :], axis=3) <ide> assert_raises(IndexError, insert, a, 1, a[:, 2, :], axis=-4) <ide> <add> # negative axis value <add> a = np.arange(24).reshape((2,3,4)) <add> assert_equal(insert(a, 1, a[:,:,3], axis=-1), <add> insert(a, 1, a[:,:,3], axis=2)) <add> assert_equal(insert(a, 1, a[:,2,:], axis=-2), <add> insert(a, 1, a[:,2,:], axis=1)) <add> <ide> def test_0d(self): <ide> # This is an error in the future <ide> a = np.array(1)
1
PHP
PHP
driver @return directive
c78004514e56822eec94e006862caf2ff1622aef
<ide><path>src/Illuminate/Cache/CacheManager.php <ide> public function store($name = null) <ide> * Get a cache driver instance. <ide> * <ide> * @param string|null $driver <del> * @return mixed <add> * @return \Illuminate\Contracts\Cache\Repository <ide> */ <ide> public function driver($driver = null) <ide> {
1
Mixed
Javascript
use unique tmpdirs for each test
d3f20a47255a0f88fa85ee4f9c18a77aeb8f7475
<ide><path>test/common/tmpdir.js <ide> const testRoot = process.env.NODE_TEST_DIR ? <ide> <ide> // Using a `.` prefixed name, which is the convention for "hidden" on POSIX, <ide> // gets tools to ignore it by default or by simple rules, especially eslint. <del>const tmpdirName = '.tmp.' + (process.env.TEST_THREAD_ID || '0'); <add>const tmpdirName = '.tmp.' + <add> (process.env.TEST_SERIAL_ID || process.env.TEST_THREAD_ID || '0'); <ide> const tmpPath = path.join(testRoot, tmpdirName); <ide> <ide> function refresh(opts = {}) { <ide><path>tools/test.py <ide> class ProgressIndicator(object): <ide> <ide> def __init__(self, cases, flaky_tests_mode): <ide> self.cases = cases <add> self.serial_id = 0 <ide> self.flaky_tests_mode = flaky_tests_mode <ide> self.parallel_queue = Queue(len(cases)) <ide> self.sequential_queue = Queue(len(cases)) <ide> def RunSingle(self, parallel, thread_id): <ide> case = test <ide> case.thread_id = thread_id <ide> self.lock.acquire() <add> case.serial_id = self.serial_id <add> self.serial_id += 1 <ide> self.AboutToRun(case) <ide> self.lock.release() <ide> try: <ide> def __init__(self, context, path, arch, mode): <ide> self.mode = mode <ide> self.parallel = False <ide> self.disable_core_files = False <add> self.serial_id = 0 <ide> self.thread_id = 0 <ide> <ide> def IsNegative(self): <ide> def RunCommand(self, command, env): <ide> def Run(self): <ide> try: <ide> result = self.RunCommand(self.GetCommand(), { <add> "TEST_SERIAL_ID": "%d" % self.serial_id, <ide> "TEST_THREAD_ID": "%d" % self.thread_id, <ide> "TEST_PARALLEL" : "%d" % self.parallel <ide> })
2
Javascript
Javascript
emit key info unconditionally
0a62f929da0cff816d79d2ed2b9b3b4ecdd50586
<ide><path>lib/internal/readline.js <ide> function* emitKeys(stream) { <ide> stream.emit('keypress', escaped ? undefined : s, key); <ide> } else if (s.length === 1) { <ide> /* Single unnamed character, e.g. "." */ <del> stream.emit('keypress', s); <del> } else { <del> /* Unrecognized or broken escape sequence, don't emit anything */ <add> stream.emit('keypress', s, key); <ide> } <add> /* Unrecognized or broken escape sequence, don't emit anything */ <ide> } <ide> } <ide><path>test/parallel/test-readline-keys.js <ide> function addTest(sequences, expectedKeys) { <ide> addTest('io.JS', [ <ide> { name: 'i', sequence: 'i' }, <ide> { name: 'o', sequence: 'o' }, <del> undefined, // emitted as `emit('keypress', '.', undefined)` <add> { name: undefined, sequence: '.' }, <ide> { name: 'j', sequence: 'J', shift: true }, <ide> { name: 's', sequence: 'S', shift: true }, <ide> ]);
2
PHP
PHP
detect mysql galera deadblocks.
5434f834cfa9411401003786fada6f30ff748a6d
<ide><path>src/Illuminate/Database/DetectsDeadlocks.php <ide> protected function causedByDeadlock(Exception $e) <ide> 'A table in the database is locked', <ide> 'has been chosen as the deadlock victim', <ide> 'Lock wait timeout exceeded; try restarting transaction', <add> 'WSREP detected deadlock/conflict and aborted the transaction. Try restarting the transaction', <ide> ]); <ide> } <ide> }
1
PHP
PHP
add automatic generation of uuid primary keys
339ff2da433e424d53b06397bbd7bd65f50ac6f9
<ide><path>Cake/ORM/Table.php <ide> <ide> use Cake\Core\App; <ide> use Cake\Database\Schema\Table as Schema; <add>use Cake\Database\Type; <ide> use Cake\Event\Event; <ide> use Cake\Event\EventManager; <ide> use Cake\ORM\Association\BelongsTo; <ide> protected function _processSave($entity, $options) { <ide> */ <ide> protected function _insert($entity, $data) { <ide> $query = $this->_buildQuery(); <add> <add> $id = null; <add> $primary = $this->primaryKey(); <add> if ($primary) { <add> $typeName = $this->schema()->columnType($primary); <add> $type = Type::build($typeName); <add> $id = $type->newId(); <add> } <add> if ($id !== null) { <add> $data[$primary] = $id; <add> } <add> <ide> $statement = $query->insert($this->table(), array_keys($data)) <ide> ->values($data) <ide> ->executeStatement(); <ide> <ide> $success = false; <ide> if ($statement->rowCount() > 0) { <del> $primary = $this->primaryKey(); <del> $id = $statement->lastInsertId($this->table(), $primary); <del> $entity->set($primary, $id); <add> if (!isset($data[$primary])) { <add> $id = $statement->lastInsertId($this->table(), $primary); <add> } <add> if ($id !== null) { <add> $entity->set($primary, $id); <add> } <ide> $entity->clean(); <ide> $success = $entity; <ide> } <ide><path>Cake/Test/TestCase/ORM/TableUuidTest.php <add><?php <add>/** <add> * PHP Version 5.4 <add> * <add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * @link http://cakephp.org CakePHP(tm) Project <add> * @since CakePHP(tm) v 3.0.0 <add> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) <add> */ <add>namespace Cake\Test\TestCase\ORM; <add> <add>use Cake\Core\Configure; <add>use Cake\Database\ConnectionManager; <add>use Cake\Database\Expression\QueryExpression; <add>use Cake\ORM\Table; <add>use Cake\ORM\TableRegistry; <add>use Cake\Utility\String; <add> <add>/** <add> * Integration tests for Table class with uuid primary keys. <add> * <add> */ <add>class UuidTableTest extends \Cake\TestSuite\TestCase { <add> <add>/** <add> * Fixtures <add> * <add> * @var array <add> */ <add> public $fixtures = [ <add> 'core.uuiditem', 'core.uuidportfolio' <add> ]; <add> <add>/** <add> * setup <add> * <add> * @return void <add> */ <add> public function setUp() { <add> parent::setUp(); <add> $this->connection = ConnectionManager::get('test'); <add> Configure::write('App.namespace', 'TestApp'); <add> } <add> <add>/** <add> * teardown <add> * <add> * @return void <add> */ <add> public function tearDown() { <add> parent::tearDown(); <add> TableRegistry::clear(); <add> } <add> <add>/** <add> * Test saving new records sets uuids <add> * <add> * @return void <add> */ <add> public function testSaveNew() { <add> $entity = new \Cake\ORM\Entity([ <add> 'name' => 'shiny new', <add> 'published' => true, <add> ]); <add> $table = TableRegistry::get('uuiditems'); <add> $this->assertSame($entity, $table->save($entity)); <add> $this->assertRegExp('/^[a-f0-9-]{36}$/', $entity->id, 'Should be 36 characters'); <add> <add> $row = $table->find('all')->where(['id' => $entity->id])->first(); <add> $this->assertEquals($entity->toArray(), $row->toArray()); <add> } <add> <add>/** <add> * Test saving existing records works <add> * <add> * @return void <add> */ <add> public function testSaveUpdate() { <add> $id = '481fc6d0-b920-43e0-a40d-6d1740cf8569'; <add> $entity = new \Cake\ORM\Entity([ <add> 'id' => $id, <add> 'name' => 'shiny update', <add> 'published' => true, <add> ]); <add> <add> $table = TableRegistry::get('uuiditems'); <add> $this->assertSame($entity, $table->save($entity)); <add> $this->assertEquals($id, $entity->id, 'Should be 36 characters'); <add> <add> $row = $table->find('all')->where(['id' => $entity->id])->first(); <add> $this->assertEquals($entity->toArray(), $row->toArray()); <add> } <add> <add>/** <add> * Test delete with string pk. <add> * <add> * @return void <add> */ <add> public function testDelete() { <add> $id = '481fc6d0-b920-43e0-a40d-6d1740cf8569'; <add> $table = TableRegistry::get('uuiditems'); <add> $entity = $table->find('all')->where(['id' => $id])->first(); <add> <add> $this->assertTrue($table->delete($entity)); <add> $query = $table->find('all')->where(['id' => $id]); <add> $this->assertCount(0, $query->execute(), 'No rows left'); <add> } <add> <add>}
2
Python
Python
remove use of unittest in numpy tests
ed6c0dd342c7d6def2600db00c3eaf75e16a39d2
<ide><path>numpy/core/tests/test_multiarray.py <ide> else: <ide> import __builtin__ as builtins <ide> from decimal import Decimal <del>from unittest import TestCase <ide> <ide> import numpy as np <ide> from numpy.compat import strchar, unicode <ide> def assert_dot_close(A, X, desired): <ide> class MatmulCommon(object): <ide> """Common tests for '@' operator and numpy.matmul. <ide> <del> Do not derive from TestCase to avoid nose running it. <del> <ide> """ <ide> # Should work with these types. Will want to add <ide> # "O" at some point <ide> def test_ctypes_is_not_available(self): <ide> _internal.ctypes = ctypes <ide> <ide> <del>class TestWritebackIfCopy(TestCase): <add>class TestWritebackIfCopy(object): <ide> # all these tests use the WRITEBACKIFCOPY mechanism <ide> def test_argmax_with_out(self): <ide> mat = np.eye(5) <ide><path>numpy/core/tests/test_umath.py <ide> def on_powerpc(): <ide> <ide> <ide> class _FilterInvalids(object): <del> def setUp(self): <add> def setup(self): <ide> self.olderr = np.seterr(invalid='ignore') <ide> <del> def tearDown(self): <add> def teardown(self): <ide> np.seterr(**self.olderr) <ide> <ide> <ide><path>numpy/core/tests/test_umath_complex.py <ide> def _check_ninf_nan(dummy): <ide> # cuts first) <ide> <ide> class TestCpow(object): <del> def setUp(self): <add> def setup(self): <ide> self.olderr = np.seterr(invalid='ignore') <ide> <del> def tearDown(self): <add> def teardown(self): <ide> np.seterr(**self.olderr) <ide> <ide> def test_simple(self): <ide> def test_array(self): <ide> assert_almost_equal(n_r[i], p_r[i], err_msg='Loop %d\n' % i) <ide> <ide> class TestCabs(object): <del> def setUp(self): <add> def setup(self): <ide> self.olderr = np.seterr(invalid='ignore') <ide> <del> def tearDown(self): <add> def teardown(self): <ide> np.seterr(**self.olderr) <ide> <ide> def test_simple(self): <ide><path>numpy/distutils/tests/test_system_info.py <ide> def site_and_parse(c, site_cfg): <ide> self.c_temp1 = site_and_parse(get_class('temp1'), self._sitecfg) <ide> self.c_temp2 = site_and_parse(get_class('temp2'), self._sitecfg) <ide> <del> def tearDown(self): <add> def teardown(self): <ide> # Do each removal separately <ide> try: <ide> shutil.rmtree(self._dir1) <ide><path>numpy/lib/tests/test_io.py <ide> def test_converters_nodecode(self): <ide> class TestLoadTxt(LoadTxtBase): <ide> loadfunc = staticmethod(np.loadtxt) <ide> <del> def setUp(self): <add> def setup(self): <ide> # lower chunksize for testing <ide> self.orig_chunk = np.lib.npyio._loadtxt_chunksize <ide> np.lib.npyio._loadtxt_chunksize = 1 <del> def tearDown(self): <add> def teardown(self): <ide> np.lib.npyio._loadtxt_chunksize = self.orig_chunk <ide> <ide> def test_record(self): <ide><path>numpy/ma/testutils.py <ide> import numpy.core.umath as umath <ide> import numpy.testing <ide> from numpy.testing import ( <del> TestCase, assert_, assert_allclose, assert_array_almost_equal_nulp, <add> assert_, assert_allclose, assert_array_almost_equal_nulp, <ide> assert_raises, build_err_msg, run_module_suite <ide> ) <ide> from .core import mask_or, getmask, masked_array, nomask, masked, filled <ide> # have mistakenly included them from this file. SciPy is one. That is <ide> # unfortunate, as some of these functions are not intended to work with <ide> # masked arrays. But there was no way to tell before. <add>from unittest import TestCase <ide> __some__from_testing = [ <ide> 'TestCase', 'assert_', 'assert_allclose', <ide> 'assert_array_almost_equal_nulp', 'assert_raises', 'run_module_suite', <ide><path>numpy/testing/tests/test_utils.py <ide> clear_and_catch_warnings, suppress_warnings, run_module_suite, <ide> assert_string_equal, assert_, tempdir, temppath, <ide> ) <del>import unittest <ide> <ide> <ide> class _GenericTest(object): <ide> def test_array_likes(self): <ide> self._test_equal([1, 2, 3], (1, 2, 3)) <ide> <ide> <del>class TestArrayEqual(_GenericTest, unittest.TestCase): <add>class TestArrayEqual(_GenericTest): <ide> <del> def setUp(self): <add> def setup(self): <ide> self._assert_func = assert_array_equal <ide> <ide> def test_generic_rank1(self): <ide> def test_recarrays(self): <ide> with suppress_warnings() as sup: <ide> l = sup.record(FutureWarning, message="elementwise == ") <ide> self._test_not_equal(c, b) <del> assert_(len(l) == 1) <add> assert_equal(len(l), 1) <ide> <ide> <del>class TestBuildErrorMessage(unittest.TestCase): <add>class TestBuildErrorMessage(object): <ide> <ide> def test_build_err_msg_defaults(self): <ide> x = np.array([1.00001, 2.00002, 3.00003]) <ide> def test_build_err_msg_defaults(self): <ide> b = ('\nItems are not equal: There is a mismatch\n ACTUAL: array([' <ide> '1.00001, 2.00002, 3.00003])\n DESIRED: array([1.00002, ' <ide> '2.00003, 3.00004])') <del> self.assertEqual(a, b) <add> assert_equal(a, b) <ide> <ide> def test_build_err_msg_no_verbose(self): <ide> x = np.array([1.00001, 2.00002, 3.00003]) <ide> def test_build_err_msg_no_verbose(self): <ide> <ide> a = build_err_msg([x, y], err_msg, verbose=False) <ide> b = '\nItems are not equal: There is a mismatch' <del> self.assertEqual(a, b) <add> assert_equal(a, b) <ide> <ide> def test_build_err_msg_custom_names(self): <ide> x = np.array([1.00001, 2.00002, 3.00003]) <ide> def test_build_err_msg_custom_names(self): <ide> b = ('\nItems are not equal: There is a mismatch\n FOO: array([' <ide> '1.00001, 2.00002, 3.00003])\n BAR: array([1.00002, 2.00003, ' <ide> '3.00004])') <del> self.assertEqual(a, b) <add> assert_equal(a, b) <ide> <ide> def test_build_err_msg_custom_precision(self): <ide> x = np.array([1.000000001, 2.00002, 3.00003]) <ide> def test_build_err_msg_custom_precision(self): <ide> b = ('\nItems are not equal: There is a mismatch\n ACTUAL: array([' <ide> '1.000000001, 2.00002 , 3.00003 ])\n DESIRED: array([' <ide> '1.000000002, 2.00003 , 3.00004 ])') <del> self.assertEqual(a, b) <add> assert_equal(a, b) <ide> <ide> <ide> class TestEqual(TestArrayEqual): <ide> <del> def setUp(self): <add> def setup(self): <ide> self._assert_func = assert_equal <ide> <ide> def test_nan_items(self): <ide> def test_error_message(self): <ide> x: array([1, 2]) <ide> y: matrix([[1, 2]])""") <ide> try: <del> self.assertEqual(msg, msg_reference) <add> assert_equal(msg, msg_reference) <ide> except AssertionError: <del> self.assertEqual(msg2, msg_reference) <add> assert_equal(msg2, msg_reference) <ide> else: <ide> raise AssertionError("Did not raise") <ide> <ide> <del>class TestArrayAlmostEqual(_GenericTest, unittest.TestCase): <add>class TestArrayAlmostEqual(_GenericTest): <ide> <del> def setUp(self): <add> def setup(self): <ide> self._assert_func = assert_array_almost_equal <ide> <ide> def test_closeness(self): <ide> def test_closeness(self): <ide> <ide> # test scalars <ide> self._assert_func(1.499999, 0.0, decimal=0) <del> self.assertRaises(AssertionError, <add> assert_raises(AssertionError, <ide> lambda: self._assert_func(1.5, 0.0, decimal=0)) <ide> <ide> # test arrays <ide> self._assert_func([1.499999], [0.0], decimal=0) <del> self.assertRaises(AssertionError, <add> assert_raises(AssertionError, <ide> lambda: self._assert_func([1.5], [0.0], decimal=0)) <ide> <ide> def test_simple(self): <ide> def test_simple(self): <ide> <ide> self._assert_func(x, y, decimal=3) <ide> self._assert_func(x, y, decimal=4) <del> self.assertRaises(AssertionError, <add> assert_raises(AssertionError, <ide> lambda: self._assert_func(x, y, decimal=5)) <ide> <ide> def test_nan(self): <ide> anan = np.array([np.nan]) <ide> aone = np.array([1]) <ide> ainf = np.array([np.inf]) <ide> self._assert_func(anan, anan) <del> self.assertRaises(AssertionError, <add> assert_raises(AssertionError, <ide> lambda: self._assert_func(anan, aone)) <del> self.assertRaises(AssertionError, <add> assert_raises(AssertionError, <ide> lambda: self._assert_func(anan, ainf)) <del> self.assertRaises(AssertionError, <add> assert_raises(AssertionError, <ide> lambda: self._assert_func(ainf, anan)) <ide> <ide> def test_inf(self): <ide> a = np.array([[1., 2.], [3., 4.]]) <ide> b = a.copy() <ide> a[0, 0] = np.inf <del> self.assertRaises(AssertionError, <add> assert_raises(AssertionError, <ide> lambda: self._assert_func(a, b)) <ide> b[0, 0] = -np.inf <del> self.assertRaises(AssertionError, <add> assert_raises(AssertionError, <ide> lambda: self._assert_func(a, b)) <ide> <ide> def test_subclass(self): <ide> def all(self, *args, **kwargs): <ide> self._assert_func(a, a) <ide> <ide> <del>class TestAlmostEqual(_GenericTest, unittest.TestCase): <add>class TestAlmostEqual(_GenericTest): <ide> <del> def setUp(self): <add> def setup(self): <ide> self._assert_func = assert_almost_equal <ide> <ide> def test_closeness(self): <ide> def test_closeness(self): <ide> <ide> # test scalars <ide> self._assert_func(1.499999, 0.0, decimal=0) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(1.5, 0.0, decimal=0)) <add> assert_raises(AssertionError, <add> lambda: self._assert_func(1.5, 0.0, decimal=0)) <ide> <ide> # test arrays <ide> self._assert_func([1.499999], [0.0], decimal=0) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func([1.5], [0.0], decimal=0)) <add> assert_raises(AssertionError, <add> lambda: self._assert_func([1.5], [0.0], decimal=0)) <ide> <ide> def test_nan_item(self): <ide> self._assert_func(np.nan, np.nan) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(np.nan, 1)) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(np.nan, np.inf)) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(np.inf, np.nan)) <add> assert_raises(AssertionError, <add> lambda: self._assert_func(np.nan, 1)) <add> assert_raises(AssertionError, <add> lambda: self._assert_func(np.nan, np.inf)) <add> assert_raises(AssertionError, <add> lambda: self._assert_func(np.inf, np.nan)) <ide> <ide> def test_inf_item(self): <ide> self._assert_func(np.inf, np.inf) <ide> self._assert_func(-np.inf, -np.inf) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(np.inf, 1)) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(-np.inf, np.inf)) <add> assert_raises(AssertionError, <add> lambda: self._assert_func(np.inf, 1)) <add> assert_raises(AssertionError, <add> lambda: self._assert_func(-np.inf, np.inf)) <ide> <ide> def test_simple_item(self): <ide> self._test_not_equal(1, 2) <ide> def test_error_message(self): <ide> self._assert_func(x, y, decimal=12) <ide> except AssertionError as e: <ide> # remove anything that's not the array string <del> self.assertEqual(str(e).split('%)\n ')[1], b) <add> assert_equal(str(e).split('%)\n ')[1], b) <ide> <ide> # with the default value of decimal digits, only the 3rd element differs <ide> # note that we only check for the formatting of the arrays themselves <ide> def test_error_message(self): <ide> self._assert_func(x, y) <ide> except AssertionError as e: <ide> # remove anything that's not the array string <del> self.assertEqual(str(e).split('%)\n ')[1], b) <add> assert_equal(str(e).split('%)\n ')[1], b) <ide> <ide> def test_matrix(self): <ide> # Matrix slicing keeps things 2-D, while array does not necessarily. <ide> def all(self, *args, **kwargs): <ide> self._assert_func(a, a) <ide> <ide> <del>class TestApproxEqual(unittest.TestCase): <add>class TestApproxEqual(object): <ide> <del> def setUp(self): <add> def setup(self): <ide> self._assert_func = assert_approx_equal <ide> <ide> def test_simple_arrays(self): <ide> def test_simple_arrays(self): <ide> <ide> self._assert_func(x, y, significant=5) <ide> self._assert_func(x, y, significant=6) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(x, y, significant=7)) <add> assert_raises(AssertionError, <add> lambda: self._assert_func(x, y, significant=7)) <ide> <ide> def test_simple_items(self): <ide> x = 1234.22 <ide> def test_simple_items(self): <ide> self._assert_func(x, y, significant=4) <ide> self._assert_func(x, y, significant=5) <ide> self._assert_func(x, y, significant=6) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(x, y, significant=7)) <add> assert_raises(AssertionError, <add> lambda: self._assert_func(x, y, significant=7)) <ide> <ide> def test_nan_array(self): <ide> anan = np.array(np.nan) <ide> aone = np.array(1) <ide> ainf = np.array(np.inf) <ide> self._assert_func(anan, anan) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(anan, aone)) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(anan, ainf)) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(ainf, anan)) <add> assert_raises(AssertionError, lambda: self._assert_func(anan, aone)) <add> assert_raises(AssertionError, lambda: self._assert_func(anan, ainf)) <add> assert_raises(AssertionError, lambda: self._assert_func(ainf, anan)) <ide> <ide> def test_nan_items(self): <ide> anan = np.array(np.nan) <ide> aone = np.array(1) <ide> ainf = np.array(np.inf) <ide> self._assert_func(anan, anan) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(anan, aone)) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(anan, ainf)) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(ainf, anan)) <add> assert_raises(AssertionError, lambda: self._assert_func(anan, aone)) <add> assert_raises(AssertionError, lambda: self._assert_func(anan, ainf)) <add> assert_raises(AssertionError, lambda: self._assert_func(ainf, anan)) <ide> <ide> <del>class TestArrayAssertLess(unittest.TestCase): <add>class TestArrayAssertLess(object): <ide> <del> def setUp(self): <add> def setup(self): <ide> self._assert_func = assert_array_less <ide> <ide> def test_simple_arrays(self): <ide> x = np.array([1.1, 2.2]) <ide> y = np.array([1.2, 2.3]) <ide> <ide> self._assert_func(x, y) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(y, x)) <add> assert_raises(AssertionError, lambda: self._assert_func(y, x)) <ide> <ide> y = np.array([1.0, 2.3]) <ide> <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(x, y)) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(y, x)) <add> assert_raises(AssertionError, lambda: self._assert_func(x, y)) <add> assert_raises(AssertionError, lambda: self._assert_func(y, x)) <ide> <ide> def test_rank2(self): <ide> x = np.array([[1.1, 2.2], [3.3, 4.4]]) <ide> y = np.array([[1.2, 2.3], [3.4, 4.5]]) <ide> <ide> self._assert_func(x, y) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(y, x)) <add> assert_raises(AssertionError, lambda: self._assert_func(y, x)) <ide> <ide> y = np.array([[1.0, 2.3], [3.4, 4.5]]) <ide> <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(x, y)) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(y, x)) <add> assert_raises(AssertionError, lambda: self._assert_func(x, y)) <add> assert_raises(AssertionError, lambda: self._assert_func(y, x)) <ide> <ide> def test_rank3(self): <ide> x = np.ones(shape=(2, 2, 2)) <ide> y = np.ones(shape=(2, 2, 2))+1 <ide> <ide> self._assert_func(x, y) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(y, x)) <add> assert_raises(AssertionError, lambda: self._assert_func(y, x)) <ide> <ide> y[0, 0, 0] = 0 <ide> <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(x, y)) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(y, x)) <add> assert_raises(AssertionError, lambda: self._assert_func(x, y)) <add> assert_raises(AssertionError, lambda: self._assert_func(y, x)) <ide> <ide> def test_simple_items(self): <ide> x = 1.1 <ide> y = 2.2 <ide> <ide> self._assert_func(x, y) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(y, x)) <add> assert_raises(AssertionError, lambda: self._assert_func(y, x)) <ide> <ide> y = np.array([2.2, 3.3]) <ide> <ide> self._assert_func(x, y) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(y, x)) <add> assert_raises(AssertionError, lambda: self._assert_func(y, x)) <ide> <ide> y = np.array([1.0, 3.3]) <ide> <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(x, y)) <add> assert_raises(AssertionError, lambda: self._assert_func(x, y)) <ide> <ide> def test_nan_noncompare(self): <ide> anan = np.array(np.nan) <ide> aone = np.array(1) <ide> ainf = np.array(np.inf) <ide> self._assert_func(anan, anan) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(aone, anan)) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(anan, aone)) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(anan, ainf)) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(ainf, anan)) <add> assert_raises(AssertionError, lambda: self._assert_func(aone, anan)) <add> assert_raises(AssertionError, lambda: self._assert_func(anan, aone)) <add> assert_raises(AssertionError, lambda: self._assert_func(anan, ainf)) <add> assert_raises(AssertionError, lambda: self._assert_func(ainf, anan)) <ide> <ide> def test_nan_noncompare_array(self): <ide> x = np.array([1.1, 2.2, 3.3]) <ide> anan = np.array(np.nan) <ide> <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(x, anan)) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(anan, x)) <add> assert_raises(AssertionError, lambda: self._assert_func(x, anan)) <add> assert_raises(AssertionError, lambda: self._assert_func(anan, x)) <ide> <ide> x = np.array([1.1, 2.2, np.nan]) <ide> <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(x, anan)) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(anan, x)) <add> assert_raises(AssertionError, lambda: self._assert_func(x, anan)) <add> assert_raises(AssertionError, lambda: self._assert_func(anan, x)) <ide> <ide> y = np.array([1.0, 2.0, np.nan]) <ide> <ide> self._assert_func(y, x) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(x, y)) <add> assert_raises(AssertionError, lambda: self._assert_func(x, y)) <ide> <ide> def test_inf_compare(self): <ide> aone = np.array(1) <ide> def test_inf_compare(self): <ide> self._assert_func(aone, ainf) <ide> self._assert_func(-ainf, aone) <ide> self._assert_func(-ainf, ainf) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(ainf, aone)) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(aone, -ainf)) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(ainf, ainf)) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(ainf, -ainf)) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(-ainf, -ainf)) <add> assert_raises(AssertionError, lambda: self._assert_func(ainf, aone)) <add> assert_raises(AssertionError, lambda: self._assert_func(aone, -ainf)) <add> assert_raises(AssertionError, lambda: self._assert_func(ainf, ainf)) <add> assert_raises(AssertionError, lambda: self._assert_func(ainf, -ainf)) <add> assert_raises(AssertionError, lambda: self._assert_func(-ainf, -ainf)) <ide> <ide> def test_inf_compare_array(self): <ide> x = np.array([1.1, 2.2, np.inf]) <ide> ainf = np.array(np.inf) <ide> <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(x, ainf)) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(ainf, x)) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(x, -ainf)) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(-x, -ainf)) <del> self.assertRaises(AssertionError, <del> lambda: self._assert_func(-ainf, -x)) <add> assert_raises(AssertionError, lambda: self._assert_func(x, ainf)) <add> assert_raises(AssertionError, lambda: self._assert_func(ainf, x)) <add> assert_raises(AssertionError, lambda: self._assert_func(x, -ainf)) <add> assert_raises(AssertionError, lambda: self._assert_func(-x, -ainf)) <add> assert_raises(AssertionError, lambda: self._assert_func(-ainf, -x)) <ide> self._assert_func(-ainf, x) <ide> <ide> <del>class TestRaises(unittest.TestCase): <add>class TestRaises(object): <ide> <del> def setUp(self): <add> def setup(self): <ide> class MyException(Exception): <ide> pass <ide> <ide> def test_catch_no_raise(self): <ide> raise AssertionError("should have raised an AssertionError") <ide> <ide> <del>class TestWarns(unittest.TestCase): <add>class TestWarns(object): <ide> <ide> def test_warn(self): <ide> def f(): <ide> def f(): <ide> raise AssertionError("wrong warning caught by assert_warn") <ide> <ide> <del>class TestAssertAllclose(unittest.TestCase): <add>class TestAssertAllclose(object): <ide> <ide> def test_simple(self): <ide> x = 1e-3 <ide> y = 1e-9 <ide> <ide> assert_allclose(x, y, atol=1) <del> self.assertRaises(AssertionError, assert_allclose, x, y) <add> assert_raises(AssertionError, assert_allclose, x, y) <ide> <ide> a = np.array([x, y, x, y]) <ide> b = np.array([x, y, x, x]) <ide> <ide> assert_allclose(a, b, atol=1) <del> self.assertRaises(AssertionError, assert_allclose, a, b) <add> assert_raises(AssertionError, assert_allclose, a, b) <ide> <ide> b[-1] = y * (1 + 1e-8) <ide> assert_allclose(a, b) <del> self.assertRaises(AssertionError, assert_allclose, a, b, <del> rtol=1e-9) <add> assert_raises(AssertionError, assert_allclose, a, b, rtol=1e-9) <ide> <ide> assert_allclose(6, 10, rtol=0.5) <del> self.assertRaises(AssertionError, assert_allclose, 10, 6, rtol=0.5) <add> assert_raises(AssertionError, assert_allclose, 10, 6, rtol=0.5) <ide> <ide> def test_min_int(self): <ide> a = np.array([np.iinfo(np.int_).min], dtype=np.int_) <ide> def test_report_fail_percentage(self): <ide> msg = '' <ide> except AssertionError as exc: <ide> msg = exc.args[0] <del> self.assertTrue("mismatch 25.0%" in msg) <add> assert_("mismatch 25.0%" in msg) <ide> <ide> def test_equal_nan(self): <ide> a = np.array([np.nan]) <ide> def test_equal_nan(self): <ide> def test_not_equal_nan(self): <ide> a = np.array([np.nan]) <ide> b = np.array([np.nan]) <del> self.assertRaises(AssertionError, assert_allclose, a, b, <del> equal_nan=False) <add> assert_raises(AssertionError, assert_allclose, a, b, equal_nan=False) <ide> <ide> def test_equal_nan_default(self): <ide> # Make sure equal_nan default behavior remains unchanged. (All <ide> def test_equal_nan_default(self): <ide> assert_allclose(a, b) <ide> <ide> <del>class TestArrayAlmostEqualNulp(unittest.TestCase): <add>class TestArrayAlmostEqualNulp(object): <ide> <ide> def test_float64_pass(self): <ide> # The number of units of least precision <ide> def test_float64_fail(self): <ide> <ide> eps = np.finfo(x.dtype).eps <ide> y = x + x*eps*nulp*2. <del> self.assertRaises(AssertionError, assert_array_almost_equal_nulp, <del> x, y, nulp) <add> assert_raises(AssertionError, assert_array_almost_equal_nulp, <add> x, y, nulp) <ide> <ide> epsneg = np.finfo(x.dtype).epsneg <ide> y = x - x*epsneg*nulp*2. <del> self.assertRaises(AssertionError, assert_array_almost_equal_nulp, <del> x, y, nulp) <add> assert_raises(AssertionError, assert_array_almost_equal_nulp, <add> x, y, nulp) <ide> <ide> def test_float32_pass(self): <ide> nulp = 5 <ide> def test_float32_fail(self): <ide> <ide> eps = np.finfo(x.dtype).eps <ide> y = x + x*eps*nulp*2. <del> self.assertRaises(AssertionError, assert_array_almost_equal_nulp, <del> x, y, nulp) <add> assert_raises(AssertionError, assert_array_almost_equal_nulp, <add> x, y, nulp) <ide> <ide> epsneg = np.finfo(x.dtype).epsneg <ide> y = x - x*epsneg*nulp*2. <del> self.assertRaises(AssertionError, assert_array_almost_equal_nulp, <del> x, y, nulp) <add> assert_raises(AssertionError, assert_array_almost_equal_nulp, <add> x, y, nulp) <ide> <ide> def test_float16_pass(self): <ide> nulp = 5 <ide> def test_float16_fail(self): <ide> <ide> eps = np.finfo(x.dtype).eps <ide> y = x + x*eps*nulp*2. <del> self.assertRaises(AssertionError, assert_array_almost_equal_nulp, <del> x, y, nulp) <add> assert_raises(AssertionError, assert_array_almost_equal_nulp, <add> x, y, nulp) <ide> <ide> epsneg = np.finfo(x.dtype).epsneg <ide> y = x - x*epsneg*nulp*2. <del> self.assertRaises(AssertionError, assert_array_almost_equal_nulp, <del> x, y, nulp) <add> assert_raises(AssertionError, assert_array_almost_equal_nulp, <add> x, y, nulp) <ide> <ide> def test_complex128_pass(self): <ide> nulp = 5 <ide> def test_complex128_fail(self): <ide> <ide> eps = np.finfo(x.dtype).eps <ide> y = x + x*eps*nulp*2. <del> self.assertRaises(AssertionError, assert_array_almost_equal_nulp, <del> xi, x + y*1j, nulp) <del> self.assertRaises(AssertionError, assert_array_almost_equal_nulp, <del> xi, y + x*1j, nulp) <add> assert_raises(AssertionError, assert_array_almost_equal_nulp, <add> xi, x + y*1j, nulp) <add> assert_raises(AssertionError, assert_array_almost_equal_nulp, <add> xi, y + x*1j, nulp) <ide> # The test condition needs to be at least a factor of sqrt(2) smaller <ide> # because the real and imaginary parts both change <ide> y = x + x*eps*nulp <del> self.assertRaises(AssertionError, assert_array_almost_equal_nulp, <del> xi, y + y*1j, nulp) <add> assert_raises(AssertionError, assert_array_almost_equal_nulp, <add> xi, y + y*1j, nulp) <ide> <ide> epsneg = np.finfo(x.dtype).epsneg <ide> y = x - x*epsneg*nulp*2. <del> self.assertRaises(AssertionError, assert_array_almost_equal_nulp, <del> xi, x + y*1j, nulp) <del> self.assertRaises(AssertionError, assert_array_almost_equal_nulp, <del> xi, y + x*1j, nulp) <add> assert_raises(AssertionError, assert_array_almost_equal_nulp, <add> xi, x + y*1j, nulp) <add> assert_raises(AssertionError, assert_array_almost_equal_nulp, <add> xi, y + x*1j, nulp) <ide> y = x - x*epsneg*nulp <del> self.assertRaises(AssertionError, assert_array_almost_equal_nulp, <del> xi, y + y*1j, nulp) <add> assert_raises(AssertionError, assert_array_almost_equal_nulp, <add> xi, y + y*1j, nulp) <ide> <ide> def test_complex64_pass(self): <ide> nulp = 5 <ide> def test_complex64_fail(self): <ide> <ide> eps = np.finfo(x.dtype).eps <ide> y = x + x*eps*nulp*2. <del> self.assertRaises(AssertionError, assert_array_almost_equal_nulp, <del> xi, x + y*1j, nulp) <del> self.assertRaises(AssertionError, assert_array_almost_equal_nulp, <del> xi, y + x*1j, nulp) <add> assert_raises(AssertionError, assert_array_almost_equal_nulp, <add> xi, x + y*1j, nulp) <add> assert_raises(AssertionError, assert_array_almost_equal_nulp, <add> xi, y + x*1j, nulp) <ide> y = x + x*eps*nulp <del> self.assertRaises(AssertionError, assert_array_almost_equal_nulp, <del> xi, y + y*1j, nulp) <add> assert_raises(AssertionError, assert_array_almost_equal_nulp, <add> xi, y + y*1j, nulp) <ide> <ide> epsneg = np.finfo(x.dtype).epsneg <ide> y = x - x*epsneg*nulp*2. <del> self.assertRaises(AssertionError, assert_array_almost_equal_nulp, <del> xi, x + y*1j, nulp) <del> self.assertRaises(AssertionError, assert_array_almost_equal_nulp, <del> xi, y + x*1j, nulp) <add> assert_raises(AssertionError, assert_array_almost_equal_nulp, <add> xi, x + y*1j, nulp) <add> assert_raises(AssertionError, assert_array_almost_equal_nulp, <add> xi, y + x*1j, nulp) <ide> y = x - x*epsneg*nulp <del> self.assertRaises(AssertionError, assert_array_almost_equal_nulp, <del> xi, y + y*1j, nulp) <add> assert_raises(AssertionError, assert_array_almost_equal_nulp, <add> xi, y + y*1j, nulp) <ide> <ide> <del>class TestULP(unittest.TestCase): <add>class TestULP(object): <ide> <ide> def test_equal(self): <ide> x = np.random.randn(10) <ide> def test_nan(self): <ide> tiny = np.array([np.finfo(dt).tiny]) <ide> zero = np.array([np.PZERO]).astype(dt) <ide> nzero = np.array([np.NZERO]).astype(dt) <del> self.assertRaises(AssertionError, <del> lambda: assert_array_max_ulp(nan, inf, <del> maxulp=maxulp)) <del> self.assertRaises(AssertionError, <del> lambda: assert_array_max_ulp(nan, big, <del> maxulp=maxulp)) <del> self.assertRaises(AssertionError, <del> lambda: assert_array_max_ulp(nan, tiny, <del> maxulp=maxulp)) <del> self.assertRaises(AssertionError, <del> lambda: assert_array_max_ulp(nan, zero, <del> maxulp=maxulp)) <del> self.assertRaises(AssertionError, <del> lambda: assert_array_max_ulp(nan, nzero, <del> maxulp=maxulp)) <del> <del> <del>class TestStringEqual(unittest.TestCase): <add> assert_raises(AssertionError, <add> lambda: assert_array_max_ulp(nan, inf, <add> maxulp=maxulp)) <add> assert_raises(AssertionError, <add> lambda: assert_array_max_ulp(nan, big, <add> maxulp=maxulp)) <add> assert_raises(AssertionError, <add> lambda: assert_array_max_ulp(nan, tiny, <add> maxulp=maxulp)) <add> assert_raises(AssertionError, <add> lambda: assert_array_max_ulp(nan, zero, <add> maxulp=maxulp)) <add> assert_raises(AssertionError, <add> lambda: assert_array_max_ulp(nan, nzero, <add> maxulp=maxulp)) <add> <add> <add>class TestStringEqual(object): <ide> def test_simple(self): <ide> assert_string_equal("hello", "hello") <ide> assert_string_equal("hello\nmultiline", "hello\nmultiline") <ide> def test_simple(self): <ide> else: <ide> raise AssertionError("exception not raised") <ide> <del> self.assertRaises(AssertionError, <del> lambda: assert_string_equal("foo", "hello")) <add> assert_raises(AssertionError, <add> lambda: assert_string_equal("foo", "hello")) <ide> <ide> <ide> def assert_warn_len_equal(mod, n_in_context, py34=None, py37=None): <ide> def warn(arr): <ide> warn_other_module() <ide> # Check that the suppression did test the file correctly (this module <ide> # got filtered) <del> assert_(len(sup.log) == 1) <del> assert_(sup.log[0].message.args[0] == "Some warning") <add> assert_equal(len(sup.log), 1) <add> assert_equal(sup.log[0].message.args[0], "Some warning") <ide> assert_warn_len_equal(my_mod, 0, py37=0) <ide> sup = suppress_warnings() <ide> # Will have to be changed if apply_along_axis is moved: <ide> def warn(category): <ide> warnings.simplefilter("always") <ide> warn(UserWarning) # should be supppressed <ide> warn(RuntimeWarning) <del> assert_(len(w) == 1) <add> assert_equal(len(w), 1) <ide> <ide> <ide> def test_suppress_warnings_record(): <ide> def test_suppress_warnings_record(): <ide> warnings.warn('Some other warning') <ide> warnings.warn('Some other warning 2') <ide> <del> assert_(len(sup.log) == 2) <del> assert_(len(log1) == 1) <del> assert_(len(log2) == 1) <del> assert_(log2[0].message.args[0] == 'Some other warning 2') <add> assert_equal(len(sup.log), 2) <add> assert_equal(len(log1), 1) <add> assert_equal(len(log2),1) <add> assert_equal(log2[0].message.args[0], 'Some other warning 2') <ide> <ide> # Do it again, with the same context to see if some warnings survived: <ide> with sup: <ide> def test_suppress_warnings_record(): <ide> warnings.warn('Some other warning') <ide> warnings.warn('Some other warning 2') <ide> <del> assert_(len(sup.log) == 2) <del> assert_(len(log1) == 1) <del> assert_(len(log2) == 1) <del> assert_(log2[0].message.args[0] == 'Some other warning 2') <add> assert_equal(len(sup.log), 2) <add> assert_equal(len(log1), 1) <add> assert_equal(len(log2), 1) <add> assert_equal(log2[0].message.args[0], 'Some other warning 2') <ide> <ide> # Test nested: <ide> with suppress_warnings() as sup: <ide> def test_suppress_warnings_record(): <ide> sup2.record(message='Some warning') <ide> warnings.warn('Some warning') <ide> warnings.warn('Some other warning') <del> assert_(len(sup2.log) == 1) <del> assert_(len(sup.log) == 1) <add> assert_equal(len(sup2.log), 1) <add> assert_equal(len(sup.log), 1) <ide> <ide> <ide> def test_suppress_warnings_forwarding(): <ide> def warn(arr): <ide> for i in range(2): <ide> warnings.warn("Some warning") <ide> <del> assert_(len(sup.log) == 2) <add> assert_equal(len(sup.log), 2) <ide> <ide> with suppress_warnings() as sup: <ide> sup.record() <ide> def warn(arr): <ide> warnings.warn("Some warning") <ide> warnings.warn("Some warning") <ide> <del> assert_(len(sup.log) == 2) <add> assert_equal(len(sup.log), 2) <ide> <ide> with suppress_warnings() as sup: <ide> sup.record() <ide> def warn(arr): <ide> warnings.warn("Some warning") <ide> warn_other_module() <ide> <del> assert_(len(sup.log) == 2) <add> assert_equal(len(sup.log), 2) <ide> <ide> with suppress_warnings() as sup: <ide> sup.record() <ide> def warn(arr): <ide> warnings.warn("Some other warning") <ide> warn_other_module() <ide> <del> assert_(len(sup.log) == 2) <add> assert_equal(len(sup.log), 2) <ide> <ide> <ide> def test_tempdir():
7
Mixed
Javascript
add heap snapshot tests
1009118d27b069411016df4ca6915aac3c36a41f
<ide><path>test/common/README.md <ide> This directory contains modules used to test the Node.js implementation. <ide> * [DNS module](#dns-module) <ide> * [Duplex pair helper](#duplex-pair-helper) <ide> * [Fixtures module](#fixtures-module) <add>* [Heap dump checker module](#heap-dump-checker-module) <ide> * [HTTP2 module](#http2-module) <ide> * [Internet module](#internet-module) <ide> * [tmpdir module](#tmpdir-module) <ide> Returns the result of <ide> Returns the result of <ide> `fs.readFileSync(path.join(fixtures.fixturesDir, 'keys', arg), 'enc')`. <ide> <add>## Heap dump checker module <add> <add>This provides utilities for checking the validity of heap dumps. <add>This requires the usage of `--expose-internals`. <add> <add>### heap.recordState() <add> <add>Create a heap dump and an embedder graph copy for inspection. <add>The returned object has a `validateSnapshotNodes` function similar to the <add>one listed below. (`heap.validateSnapshotNodes(...)` is a shortcut for <add>`heap.recordState().validateSnapshotNodes(...)`.) <add> <add>### heap.validateSnapshotNodes(name, expected, options) <add> <add>* `name` [&lt;string>] Look for this string as the name of heap dump nodes. <add>* `expected` [&lt;Array>] A list of objects, possibly with an `children` <add> property that points to expected other adjacent nodes. <add>* `options` [&lt;Array>] <add> * `loose` [&lt;boolean>] Do not expect an exact listing of occurrences <add> of nodes with name `name` in `expected`. <add> <add>Create a heap dump and an embedder graph copy and validate occurrences. <add> <add><!-- eslint-disable no-undef, no-unused-vars, node-core/required-modules, strict --> <add>```js <add>validateSnapshotNodes('TLSWRAP', [ <add> { <add> children: [ <add> { name: 'enc_out' }, <add> { name: 'enc_in' }, <add> { name: 'TLSWrap' } <add> ] <add> } <add>]); <add>``` <add> <ide> ## HTTP/2 Module <ide> <ide> The http2.js module provides a handful of utilities for creating mock HTTP/2 <ide><path>test/common/heap.js <add>/* eslint-disable node-core/required-modules */ <add>'use strict'; <add>const assert = require('assert'); <add>const util = require('util'); <add> <add>let internalTestHeap; <add>try { <add> internalTestHeap = require('internal/test/heap'); <add>} catch (e) { <add> console.log('using `test/common/heap.js` requires `--expose-internals`'); <add> throw e; <add>} <add>const { createJSHeapDump, buildEmbedderGraph } = internalTestHeap; <add> <add>class State { <add> constructor() { <add> this.snapshot = createJSHeapDump(); <add> this.embedderGraph = buildEmbedderGraph(); <add> } <add> <add> validateSnapshotNodes(name, expected, { loose = false } = {}) { <add> const snapshot = this.snapshot.filter( <add> (node) => node.name === 'Node / ' + name && node.type !== 'string'); <add> if (loose) <add> assert(snapshot.length >= expected.length); <add> else <add> assert.strictEqual(snapshot.length, expected.length); <add> for (const expectedNode of expected) { <add> if (expectedNode.children) { <add> for (const expectedChild of expectedNode.children) { <add> const check = typeof expectedChild === 'function' ? <add> expectedChild : <add> (node) => [expectedChild.name, 'Node / ' + expectedChild.name] <add> .includes(node.name); <add> <add> assert(snapshot.some((node) => { <add> return node.outgoingEdges.map((edge) => edge.toNode).some(check); <add> }), `expected to find child ${util.inspect(expectedChild)} ` + <add> `in ${util.inspect(snapshot)}`); <add> } <add> } <add> } <add> <add> const graph = this.embedderGraph.filter((node) => node.name === name); <add> if (loose) <add> assert(graph.length >= expected.length); <add> else <add> assert.strictEqual(graph.length, expected.length); <add> for (const expectedNode of expected) { <add> if (expectedNode.edges) { <add> for (const expectedChild of expectedNode.children) { <add> const check = typeof expectedChild === 'function' ? <add> expectedChild : (node) => { <add> return node.name === expectedChild.name || <add> (node.value && <add> node.value.constructor && <add> node.value.constructor.name === expectedChild.name); <add> }; <add> <add> assert(graph.some((node) => node.edges.some(check)), <add> `expected to find child ${util.inspect(expectedChild)} ` + <add> `in ${util.inspect(snapshot)}`); <add> } <add> } <add> } <add> } <add>} <add> <add>function recordState() { <add> return new State(); <add>} <add> <add>function validateSnapshotNodes(...args) { <add> return recordState().validateSnapshotNodes(...args); <add>} <add> <add>module.exports = { <add> recordState, <add> validateSnapshotNodes <add>}; <ide><path>test/parallel/test-heapdump-dns.js <add>// Flags: --expose-internals <add>'use strict'; <add>require('../common'); <add>const { validateSnapshotNodes } = require('../common/heap'); <add> <add>validateSnapshotNodes('DNSCHANNEL', []); <add>const dns = require('dns'); <add>validateSnapshotNodes('DNSCHANNEL', [{}]); <add>dns.resolve('localhost', () => {}); <add>validateSnapshotNodes('DNSCHANNEL', [ <add> { <add> children: [ <add> { name: 'task list' }, <add> { name: 'ChannelWrap' } <add> ] <add> } <add>]); <ide><path>test/parallel/test-heapdump-fs-promise.js <add>// Flags: --expose-internals <add>'use strict'; <add>require('../common'); <add>const { validateSnapshotNodes } = require('../common/heap'); <add>const fs = require('fs').promises; <add> <add>validateSnapshotNodes('FSREQPROMISE', []); <add>fs.stat(__filename); <add>validateSnapshotNodes('FSREQPROMISE', [ <add> { <add> children: [ <add> { name: 'FSReqPromise' }, <add> { name: 'Float64Array' } // Stat array <add> ] <add> } <add>]); <ide><path>test/parallel/test-heapdump-http2.js <add>// Flags: --expose-internals <add>'use strict'; <add>const common = require('../common'); <add>const { recordState } = require('../common/heap'); <add>const http2 = require('http2'); <add>if (!common.hasCrypto) <add> common.skip('missing crypto'); <add> <add>{ <add> const state = recordState(); <add> state.validateSnapshotNodes('HTTP2SESSION', []); <add> state.validateSnapshotNodes('HTTP2STREAM', []); <add>} <add> <add>const server = http2.createServer(); <add>server.on('stream', (stream) => { <add> stream.respondWithFile(__filename); <add>}); <add>server.listen(0, () => { <add> const client = http2.connect(`http://localhost:${server.address().port}`); <add> const req = client.request(); <add> <add> req.on('response', common.mustCall(() => { <add> const state = recordState(); <add> state.validateSnapshotNodes('HTTP2STREAM', [ <add> { <add> children: [ <add> { name: 'Http2Stream' } <add> ] <add> }, <add> ], { loose: true }); <add> state.validateSnapshotNodes('FILEHANDLE', [ <add> { <add> children: [ <add> { name: 'FileHandle' } <add> ] <add> } <add> ]); <add> state.validateSnapshotNodes('TCPWRAP', [ <add> { <add> children: [ <add> { name: 'TCP' } <add> ] <add> } <add> ], { loose: true }); <add> state.validateSnapshotNodes('TCPSERVERWRAP', [ <add> { <add> children: [ <add> { name: 'TCP' } <add> ] <add> } <add> ], { loose: true }); <add> state.validateSnapshotNodes('STREAMPIPE', [ <add> { <add> children: [ <add> { name: 'StreamPipe' } <add> ] <add> } <add> ]); <add> state.validateSnapshotNodes('HTTP2SESSION', [ <add> { <add> children: [ <add> { name: 'Http2Session' }, <add> { name: 'streams' } <add> ] <add> } <add> ], { loose: true }); <add> })); <add> <add> req.resume(); <add> req.on('end', common.mustCall(() => { <add> client.close(); <add> server.close(); <add> })); <add> req.end(); <add>}); <ide><path>test/parallel/test-heapdump-inspector.js <add>// Flags: --expose-internals <add>'use strict'; <add>const common = require('../common'); <add> <add>common.skipIfInspectorDisabled(); <add> <add>const { validateSnapshotNodes } = require('../common/heap'); <add>const inspector = require('inspector'); <add> <add>const session = new inspector.Session(); <add>validateSnapshotNodes('INSPECTORJSBINDING', []); <add>session.connect(); <add>validateSnapshotNodes('INSPECTORJSBINDING', [ <add> { <add> children: [ <add> { name: 'session' }, <add> { name: 'Connection' }, <add> (node) => node.type === 'closure' || typeof node.value === 'function' <add> ] <add> } <add>]); <ide><path>test/parallel/test-heapdump-tls.js <add>// Flags: --expose-internals <add>'use strict'; <add>const common = require('../common'); <add> <add>if (!common.hasCrypto) <add> common.skip('missing crypto'); <add> <add>const { validateSnapshotNodes } = require('../common/heap'); <add>const net = require('net'); <add>const tls = require('tls'); <add> <add>validateSnapshotNodes('TLSWRAP', []); <add> <add>const server = net.createServer(common.mustCall((c) => { <add> c.end(); <add>})).listen(0, common.mustCall(() => { <add> const c = tls.connect({ port: server.address().port }); <add> <add> c.on('error', common.mustCall(() => { <add> server.close(); <add> })); <add> c.write('hello'); <add> <add> validateSnapshotNodes('TLSWRAP', [ <add> { <add> children: [ <add> { name: 'enc_out' }, <add> { name: 'enc_in' }, <add> { name: 'TLSWrap' } <add> ] <add> } <add> ]); <add>})); <ide><path>test/parallel/test-heapdump-worker.js <add>// Flags: --expose-internals --experimental-worker <add>'use strict'; <add>require('../common'); <add>const { validateSnapshotNodes } = require('../common/heap'); <add>const { Worker } = require('worker_threads'); <add> <add>validateSnapshotNodes('WORKER', []); <add>const worker = new Worker('setInterval(() => {}, 100);', { eval: true }); <add>validateSnapshotNodes('WORKER', [ <add> { <add> children: [ <add> { name: 'thread_exit_async' }, <add> { name: 'env' }, <add> { name: 'MESSAGEPORT' }, <add> { name: 'Worker' } <add> ] <add> } <add>]); <add>validateSnapshotNodes('MESSAGEPORT', [ <add> { <add> children: [ <add> { name: 'data' }, <add> { name: 'MessagePort' } <add> ] <add> } <add>], { loose: true }); <add>worker.terminate(); <ide><path>test/parallel/test-heapdump-zlib.js <add>// Flags: --expose-internals <add>'use strict'; <add>require('../common'); <add>const { validateSnapshotNodes } = require('../common/heap'); <add>const zlib = require('zlib'); <add> <add>validateSnapshotNodes('ZLIB', []); <add>// eslint-disable-next-line no-unused-vars <add>const gunzip = zlib.createGunzip(); <add>validateSnapshotNodes('ZLIB', [ <add> { <add> children: [ <add> { name: 'Zlib' }, <add> { name: 'zlib memory' } <add> ] <add> } <add>]);
9
Ruby
Ruby
use rbconfig instead of ruby_platform
d6dd63d1a04cad16d2a6faa17a6d71e4baa8f95f
<ide><path>Library/Homebrew/os.rb <add>require "rbconfig" <add> <ide> module OS <ide> def self.mac? <ide> return false if ENV["HOMEBREW_TEST_GENERIC_OS"] <del> RUBY_PLATFORM.to_s.downcase.include? "darwin" <add> RbConfig::CONFIG["host_os"].include? "darwin" <ide> end <ide> <ide> def self.linux? <ide> return false if ENV["HOMEBREW_TEST_GENERIC_OS"] <del> RUBY_PLATFORM.to_s.downcase.include? "linux" <add> RbConfig::CONFIG["host_os"].include? "linux" <ide> end <ide> <ide> ::OS_VERSION = ENV["HOMEBREW_OS_VERSION"]
1
Java
Java
remove use of boolean constructors
19e77cd140d6efd2736a43b8688a8a3ffb6f2a7b
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxTagTests.java <ide> public void withSingleValueBooleanChecked() throws Exception { <ide> <ide> @Test <ide> public void withSingleValueBooleanObjectUnchecked() throws Exception { <del> this.bean.setSomeBoolean(new Boolean(false)); <add> this.bean.setSomeBoolean(Boolean.FALSE); <ide> this.tag.setPath("someBoolean"); <ide> int result = this.tag.doStartTag(); <ide> assertEquals(Tag.SKIP_BODY, result); <ide> protected TestBean createTestBean() { <ide> this.bean.setDate(getDate()); <ide> this.bean.setName("Rob Harrop"); <ide> this.bean.setJedi(true); <del> this.bean.setSomeBoolean(new Boolean(true)); <add> this.bean.setSomeBoolean(Boolean.TRUE); <ide> this.bean.setStringArray(new String[] {"bar", "foo"}); <ide> this.bean.setSomeIntegerArray(new Integer[] {new Integer(2), new Integer(1)}); <ide> this.bean.setOtherColours(colours); <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxesTagTests.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 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> protected TestBean createTestBean() { <ide> this.bean.setDate(getDate()); <ide> this.bean.setName("Rob Harrop"); <ide> this.bean.setJedi(true); <del> this.bean.setSomeBoolean(new Boolean(true)); <add> this.bean.setSomeBoolean(Boolean.TRUE); <ide> this.bean.setStringArray(new String[] {"bar", "foo"}); <ide> this.bean.setSomeIntegerArray(new Integer[] {new Integer(2), new Integer(1)}); <ide> this.bean.setOtherColours(colours); <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/RadioButtonsTagTests.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 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> protected TestBean createTestBean() { <ide> this.bean.setDate(getDate()); <ide> this.bean.setName("Rob Harrop"); <ide> this.bean.setJedi(true); <del> this.bean.setSomeBoolean(new Boolean(true)); <add> this.bean.setSomeBoolean(Boolean.TRUE); <ide> this.bean.setStringArray(new String[] {"bar", "foo"}); <ide> this.bean.setSomeIntegerArray(new Integer[] {new Integer(2), new Integer(1)}); <ide> this.bean.setOtherColours(colours);
3
Text
Text
imply an additional element in infinite lists
674c9029c1b0f3680bfc04dd87b58f9bd21988de
<ide><path>docs/tutorial/1-serialization.md <ide> We'll also need to add our new `snippets` app and the `rest_framework` app to `I <ide> INSTALLED_APPS = ( <ide> ... <ide> 'rest_framework', <del> 'snippets' <add> 'snippets', <ide> ) <ide> <ide> We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our snippet app's URLs. <ide> Finally we need to wire these views up. Create the `snippets/urls.py` file: <ide> <ide> urlpatterns = patterns('snippets.views', <ide> url(r'^snippets/$', 'snippet_list'), <del> url(r'^snippets/(?P<pk>[0-9]+)/$', 'snippet_detail') <add> url(r'^snippets/(?P<pk>[0-9]+)/$', 'snippet_detail'), <ide> ) <ide> <ide> It's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we send malformed `json`, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 "server error" response. Still, this'll do for now. <ide><path>docs/tutorial/2-requests-and-responses.md <ide> Now update the `urls.py` file slightly, to append a set of `format_suffix_patter <ide> <ide> urlpatterns = patterns('snippets.views', <ide> url(r'^snippets/$', 'snippet_list'), <del> url(r'^snippets/(?P<pk>[0-9]+)$', 'snippet_detail') <add> url(r'^snippets/(?P<pk>[0-9]+)$', 'snippet_detail'), <ide> ) <ide> <ide> urlpatterns = format_suffix_patterns(urlpatterns) <ide><path>docs/tutorial/3-class-based-views.md <ide> We'll also need to refactor our URLconf slightly now we're using class based vie <ide> <ide> urlpatterns = patterns('', <ide> url(r'^snippets/$', views.SnippetList.as_view()), <del> url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()) <add> url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()), <ide> ) <ide> <ide> urlpatterns = format_suffix_patterns(urlpatterns) <ide><path>docs/tutorial/4-authentication-and-permissions.md <ide> We'll also add a couple of views. We'd like to just use read-only views for the <ide> Finally we need to add those views into the API, by referencing them from the URL conf. <ide> <ide> url(r'^users/$', views.UserList.as_view()), <del> url(r'^users/(?P<pk>[0-9]+)/$', views.UserInstance.as_view()) <add> url(r'^users/(?P<pk>[0-9]+)/$', views.UserInstance.as_view()), <ide> <ide> ## Associating Snippets with Users <ide> <ide> And, at the end of the file, add a pattern to include the login and logout views <ide> <ide> urlpatterns += patterns('', <ide> url(r'^api-auth/', include('rest_framework.urls', <del> namespace='rest_framework')) <add> namespace='rest_framework')), <ide> ) <ide> <ide> The `r'^api-auth/'` part of pattern can actually be whatever URL you want to use. The only restriction is that the included urls must use the `'rest_framework'` namespace. <ide><path>docs/tutorial/5-relationships-and-hyperlinked-apis.md <ide> After adding all those names into our URLconf, our final `'urls.py'` file should <ide> url(r'^snippets/(?P<pk>[0-9]+)/$', <ide> views.SnippetDetail.as_view(), <ide> name='snippet-detail'), <del> url(r'^snippets/(?P<pk>[0-9]+)/highlight/$' <add> url(r'^snippets/(?P<pk>[0-9]+)/highlight/$', <ide> views.SnippetHighlight.as_view(), <ide> name='snippet-highlight'), <ide> url(r'^users/$', <ide> After adding all those names into our URLconf, our final `'urls.py'` file should <ide> # Login and logout views for the browsable API <ide> urlpatterns += patterns('', <ide> url(r'^api-auth/', include('rest_framework.urls', <del> namespace='rest_framework')) <add> namespace='rest_framework')), <ide> ) <ide> <ide> ## Adding pagination
5
Text
Text
fix minor grammar issues in dockervolumes.md
4ac6375790fe0c7bc9c1bb9c3fdc67db233ff8cb
<ide><path>docs/sources/userguide/dockervolumes.md <ide> absolute path and if the directory doesn't exist Docker will automatically <ide> create it for you. <ide> <ide> > **Note:** <del>> This is not available from a `Dockerfile` due the portability <add>> This is not available from a `Dockerfile` due to the portability <ide> > and sharing purpose of it. As the host directory is, by its nature, <del>> host-dependent it might not work all hosts. <add>> host-dependent, a host directory specified in a `Dockerfile` probably <add>> wouldn't work on all hosts. <ide> <ide> Docker defaults to a read-write volume but we can also mount a directory <ide> read-only.
1
Python
Python
remove a bunch of deadcode/dead imports
345c4c4629c8d17a8b4826fb4b97a61f19326e9f
<ide><path>django/db/backends/creation.py <ide> def sql_create_model(self, model, style, known_models=set()): <ide> if f.rel: <ide> ref_output, pending = self.sql_for_inline_foreign_key_references(f, known_models, style) <ide> if pending: <del> pr = pending_references.setdefault(f.rel.to, []).append((model, f)) <add> pending_references.setdefault(f.rel.to, []).append((model, f)) <ide> else: <ide> field_output.extend(ref_output) <ide> table_output.append(' '.join(field_output)) <ide> def create_test_db(self, verbosity=1, autoclobber=False): <ide> <ide> # Get a cursor (even though we don't need one yet). This has <ide> # the side effect of initializing the test database. <del> cursor = self.connection.cursor() <add> self.connection.cursor() <ide> <ide> return test_database_name <ide> <ide><path>django/db/models/base.py <ide> def save_base(self, raw=False, cls=None, origin=None, force_insert=False, <ide> ('raw', 'cls', and 'origin'). <ide> """ <ide> using = using or router.db_for_write(self.__class__, instance=self) <del> connection = connections[using] <ide> assert not (force_insert and force_update) <ide> if cls is None: <ide> cls = self.__class__ <ide><path>django/db/models/query.py <ide> from django.db.models.query_utils import (Q, select_related_descend, <ide> deferred_class_factory, InvalidQuery) <ide> from django.db.models.deletion import Collector <del>from django.db.models import signals, sql <add>from django.db.models import sql <ide> from django.utils.functional import partition <ide> <ide> # Used to control how many objects are worked with at once in some cases (e.g. <ide><path>django/db/models/sql/compiler.py <ide> from itertools import izip <ide> <ide> from django.core.exceptions import FieldError <del>from django.db import connections <ide> from django.db import transaction <ide> from django.db.backends.util import truncate_name <add>from django.db.models.query_utils import select_related_descend <ide> from django.db.models.sql.constants import * <ide> from django.db.models.sql.datastructures import EmptyResultSet <ide> from django.db.models.sql.expressions import SQLEvaluator <del>from django.db.models.sql.query import (get_proxied_model, get_order_dir, <del> select_related_descend, Query) <add>from django.db.models.sql.query import get_proxied_model, get_order_dir, Query <ide> from django.db.utils import DatabaseError <ide> <ide> <ide> def as_sql(self): <ide> Creates the SQL for this query. Returns the SQL string and list of <ide> parameters. <ide> """ <del> from django.db.models.base import Model <del> <ide> self.pre_sql_setup() <ide> if not self.query.values: <ide> return '', () <ide><path>django/db/models/sql/query.py <ide> from django.db import connections, DEFAULT_DB_ALIAS <ide> from django.db.models import signals <ide> from django.db.models.fields import FieldDoesNotExist <del>from django.db.models.query_utils import select_related_descend, InvalidQuery <add>from django.db.models.query_utils import InvalidQuery <ide> from django.db.models.sql import aggregates as base_aggregates_module <ide> from django.db.models.sql.constants import * <ide> from django.db.models.sql.datastructures import EmptyResultSet, Empty, MultiJoin <ide> def deferred_to_data(self, target, callback): <ide> field_names, defer = self.deferred_loading <ide> if not field_names: <ide> return <del> columns = set() <ide> orig_opts = self.model._meta <ide> seen = {} <ide> if orig_opts.proxy:
5
Text
Text
change == to === as suggested from codesandbox
75ec204e64d3eef63b275dccc3e6fa8298f12181
<ide><path>docs/tutorials/essentials/part-4-using-data.md <ide> import { postUpdated } from './postsSlice' <ide> export const EditPostForm = ({ match }) => { <ide> const { postId } = match.params <ide> <del> const post = useSelector(state => state.posts.find(post => post.id == postId)) <add> const post = useSelector(state => state.posts.find(post => post.id === postId)) <ide> <ide> const [title, setTitle] = useState(post.title) <ide> const [content, setContent] = useState(post.content)
1
PHP
PHP
add missing type cast
3c1fbeff4732a60bb5f9b78556dfb961eed908c8
<ide><path>src/Controller/Component/FlashComponent.php <ide> public function set($message, array $options = []) <ide> <ide> $messages = []; <ide> if ($options['clear'] === false) { <del> $messages = $this->_session->read('Flash.' . $options['key']); <add> $messages = (array)$this->_session->read('Flash.' . $options['key']); <ide> } <ide> <ide> $messages[] = [
1
Text
Text
remove internal docs for beta
e9cf8d46470478920a6d2bfa561e41a3b7cd7213
<ide><path>docs/building-atom.md <del>## Building Atom <del> <del>These guide is meant only for users who wish to help develop atom core, <del>if you're just interested in using atom you should just [download <del>atom][download]. <del> <del>## OSX <del> <del>* Use OS X 10.8 or later <del>* Install the latest node 0.10.x release (32bit preferable) <del>* Clone [atom][atom-git] to `~/github/atom` <del>* Run `~/github/atom/script/build` <del> <del>## Windows <del> <del>* Install [Visual C++ 2010 Express][win-vs2010] <del>* Install the [latest 32bit Node 0.10.x][win-node] <del>* Install the [latest Python 2.7.x][win-python] <del>* Install [GitHub for Windows][win-github] <del>* Clone [atom/atom][atom-git] to `C:\Users\<user>\github\atom\` <del>* Add `C:\Python27;C:\Program Files\nodejs;C:\Users\<user>\github\atom\node_modules\` <del> to your PATH <del>* Set ATOM_ACCESS_TOKEN to your oauth2 credentials (run `security -q <del> find-generic-password -ws 'GitHub API Token'` on OSX to get your <del> credentials). <del>* Use the Windows GitHub shell and cd into `C:\Users\<user>\github\atom` <del>* Run `script\bootstrap` <del> <del>[download]: https://github.com/atom/atom/releases/latest <del>[win-node]: http://nodejs.org/download/ <del>[win-python]: http://www.python.org/download/ <del>[win-github]: http://windows.github.com/ <del>[win-vs2010]: http://www.microsoft.com/visualstudio/eng/products/visual-studio-2010-express <del>[atom-git]: https://github.com/atom/atom/ <ide><path>docs/setting-up-travis.md <del># Setting up Travis CI <del> <del>Packages under the [atom org][atom-org] should use [Travis CI][travis-ci] for <del>builds. <del> <del>Currently we have a [Travis Pro][travis-pro] account since the repositories <del>are private. This process will be simpler and have fewer steps once the <del>package repos are made public. <del> <del>Each package builds using the [build-package][build-package] script, any <del>changes to the build should be made in that script and will affect all <del>package builds immediately. <del> <del>Each package builds against the latest successful build of atom@master. The <del>master builds are stored in the [atom-master-builds][atom-master-builds] repo <del>as releases named by the SHA-1 built. <del> <del>## Configuring a package <del> <del>* Run `cd ~/github/my-package` to navigate to the package repo locally <del>* Run `apm test` to verify that the package currently builds via [apm][apm] <del>* Add the package repo to the [Travis CI team][travis-ci-team] <del>* Run `gem install travis` to install the [travis gem][travis-gem] <del>* Run `travis login --pro` and log in using the [atom-build][atom-build] user <del> and the password from the *Shared-Developers* folder in LastPass <del>* Run `apm ci` to add a `.travis.yml` file to the repo and to configure Travis <del>* Log into [Travis][travis-ci] as the `atom-build` user and you should now see <del> the package listed and building <del> <del> <del>[apm]: https://github.com/atom/apm <del>[build-package]: https://github.com/atom/apm/blob/master/script/build-package <del>[atom-build]: https://github.com/atom-build <del>[atom-master-builds]: https://github.com/atom/atom-master-builds/releases <del>[atom-org]: https://github.com/atom <del>[travis-ci]: https://magnum.travis-ci.com <del>[travis-ci-team]: https://github.com/organizations/atom/teams/596636 <del>[travis-gem]: https://rubygems.org/gems/travis <del>[travis-pro]: http://about.travis-ci.org/docs/user/travis-pro
2
PHP
PHP
fix return tag
47b9687777e0807cf507e5c120f1a2a6fc64ccc7
<ide><path>src/Event/EventDispatcherInterface.php <ide> public function dispatchEvent(string $name, $data = null, $subject = null): Even <ide> * object events, or create your own events and trigger them at will. <ide> * <ide> * @param \Cake\Event\EventManagerInterface $eventManager the eventManager to set <del> * @return \Cake\Event\EventManagerInterface <add> * @return \Cake\Event\EventDispatcherInterface <ide> */ <ide> public function setEventManager(EventManagerInterface $eventManager): self; <ide>
1
Text
Text
add v4.8.0-beta.4 to changelog
3ec17789315fec24f63de0e0ab3177feb8906d83
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v4.8.0-beta.4 (September 26, 2022) <add> <add>- [#20201](https://github.com/emberjs/ember.js/pull/20201) [BUGFIX] Fix type definition for `Route` <add> <ide> ### v4.8.0-beta.3 (September 19, 2022) <ide> <ide> - [#20194](https://github.com/emberjs/ember.js/pull/20194) [BUGFIX] Provide a `.d.ts` file at types/stable
1
Javascript
Javascript
add a comment with a link to pr
3f68e221937cd45836a4fdaee3d33e1e1eb55ac6
<ide><path>src/core/Clock.js <ide> Object.assign( Clock.prototype, { <ide> <ide> start: function () { <ide> <del> this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); <add> this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732 <ide> <ide> this.oldTime = this.startTime; <ide> this.elapsedTime = 0;
1
Javascript
Javascript
remove multiview attribute from renderer
709fe8964b13fe3b357142547493c1b9927c92d3
<ide><path>src/renderers/WebGLRenderer.js <ide> function WebGLRenderer( parameters ) { <ide> <ide> var multiview = new WebGLMultiview( _this, _gl ); <ide> <del> this.multiview = multiview; <del> <ide> // shadow map <ide> <ide> var shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize ); <ide><path>src/renderers/webgl/WebGLMultiview.js <ide> function WebGLMultiview( renderer, gl ) { <ide> <ide> } <ide> <del> function getNumViews() { <del> <del> if ( renderTarget && renderer.getRenderTarget() === renderTarget ) { <del> <del> return renderTarget.numViews; <del> <del> } <del> <del> return 0; <del> <del> } <del> <ide> function getCameraArray( camera ) { <ide> <ide> if ( camera.isArrayCamera ) return camera.cameras; <ide> function WebGLMultiview( renderer, gl ) { <ide> <ide> this.attachRenderTarget = attachRenderTarget; <ide> this.detachRenderTarget = detachRenderTarget; <del> this.getNumViews = getNumViews; <ide> this.updateCameraProjectionMatricesUniform = updateCameraProjectionMatricesUniform; <ide> this.updateCameraViewMatricesUniform = updateCameraViewMatricesUniform; <ide> this.updateObjectMatricesUniforms = updateObjectMatricesUniforms; <ide><path>src/renderers/webgl/WebGLProgram.js <ide> import { WebGLUniforms } from './WebGLUniforms.js'; <ide> import { WebGLShader } from './WebGLShader.js'; <ide> import { ShaderChunk } from '../shaders/ShaderChunk.js'; <add>import { WebGLMultiviewRenderTarget } from '../WebGLMultiviewRenderTarget.js'; <ide> import { NoToneMapping, AddOperation, MixOperation, MultiplyOperation, EquirectangularRefractionMapping, CubeRefractionMapping, SphericalReflectionMapping, EquirectangularReflectionMapping, CubeUVRefractionMapping, CubeUVReflectionMapping, CubeReflectionMapping, PCFSoftShadowMap, PCFShadowMap, ACESFilmicToneMapping, CineonToneMapping, Uncharted2ToneMapping, ReinhardToneMapping, LinearToneMapping, GammaEncoding, RGBDEncoding, RGBM16Encoding, RGBM7Encoding, RGBEEncoding, sRGBEncoding, LinearEncoding } from '../../constants.js'; <ide> <ide> var programIdCount = 0; <ide> function WebGLProgram( renderer, extensions, code, material, shader, parameters, <ide> <ide> var prefixVertex, prefixFragment; <ide> <del> var numMultiviewViews = renderer.multiview.getNumViews(); <add> var renderTarget = renderer.getRenderTarget(); <add> var numMultiviewViews = renderTarget instanceof WebGLMultiviewRenderTarget ? renderTarget.numViews : 0; <ide> <ide> if ( material.isRawShaderMaterial ) { <ide>
3
PHP
PHP
return a `closure` from `routes.php` files
8aac86b1bedef9d3da473138879d94950bfcc6d7
<ide><path>src/Core/BasePlugin.php <ide> use Cake\Console\CommandCollection; <ide> use Cake\Http\MiddlewareQueue; <ide> use Cake\Routing\RouteBuilder; <add>use Closure; <ide> use InvalidArgumentException; <ide> use ReflectionClass; <ide> <ide> public function routes(RouteBuilder $routes): void <ide> { <ide> $path = $this->getConfigPath() . 'routes.php'; <ide> if (is_file($path)) { <del> require $path; <add> $return = require $path; <add> if ($return instanceof Closure) { <add> $return($routes); <add> } <ide> } <ide> } <ide> <ide><path>src/Http/BaseApplication.php <ide> use Cake\Routing\RouteBuilder; <ide> use Cake\Routing\Router; <ide> use Cake\Routing\RoutingApplicationInterface; <add>use Closure; <ide> use Psr\Http\Message\ResponseInterface; <ide> use Psr\Http\Message\ServerRequestInterface; <ide> <ide> public function routes(RouteBuilder $routes): void <ide> { <ide> // Only load routes if the router is empty <ide> if (!Router::routes()) { <del> require $this->configDir . 'routes.php'; <add> $return = require $this->configDir . 'routes.php'; <add> if ($return instanceof Closure) { <add> $return($routes); <add> } <ide> } <ide> } <ide> <ide><path>tests/test_app/Plugin/TestPlugin/config/routes.php <ide> <?php <ide> <ide> use Cake\Core\Configure; <add>use Cake\Routing\RouteBuilder; <ide> <ide> Configure::write('PluginTest.test_plugin.routes', 'loaded plugin routes'); <ide> <del>if (isset($routes)) { <add>return function (RouteBuilder $routes) { <ide> $routes->get( <ide> '/test_plugin', <ide> ['controller' => 'TestPlugin', 'plugin' => 'TestPlugin', 'action' => 'index'], <ide> 'test_plugin:index' <ide> ); <del>} <add>}; <ide><path>tests/test_app/config/routes.php <ide> <ide> use Cake\Routing\RouteBuilder; <ide> <del>$routes->setExtensions('json'); <del>$routes->scope('/', function (RouteBuilder $routes): void { <del> $routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']); <del> $routes->connect( <del> '/some_alias', <del> [ <del> 'controller' => 'tests_apps', <del> 'action' => 'some_method'], <del> [ <del> '_name' => 'some_alias', <del> 'routeClass' => 'InflectedRoute', <del> ] <del> ); <del> $routes->fallbacks(); <del>}); <add>return function (RouteBuilder $routes) { <add> $routes->setExtensions('json'); <add> $routes->scope('/', function (RouteBuilder $routes): void { <add> $routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']); <add> $routes->connect( <add> '/some_alias', <add> [ <add> 'controller' => 'tests_apps', <add> 'action' => 'some_method'], <add> [ <add> '_name' => 'some_alias', <add> 'routeClass' => 'InflectedRoute', <add> ] <add> ); <add> $routes->fallbacks(); <add> }); <add>}; <ide><path>tests/test_app/invalid_routes/routes.php <ide> <?php <ide> declare(strict_types=1); <ide> <add>use Cake\Routing\RouteBuilder; <add> <ide> /* <ide> * Test routes file with routes that trigger a missing route class error. <ide> * Application requests should have InvalidArgument error rendered. <ide> */ <ide> <del>$routes->setRouteClass('DoesNotExist'); <del>$routes->get('/', ['controller' => 'Pages']); <add>return function (RouteBuilder $routes) { <add> $routes->setRouteClass('DoesNotExist'); <add> $routes->get('/', ['controller' => 'Pages']); <add>};
5
Javascript
Javascript
add emitexperimentalwarning function
b08c7321bd014ca8fe46aecf35eea66f2aea5b3b
<ide><path>lib/internal/util.js <ide> const { <ide> <ide> const noCrypto = !process.versions.openssl; <ide> <add>const experimentalWarnings = new Set(); <add> <ide> function isError(e) { <ide> return objectToString(e) === '[object Error]' || e instanceof Error; <ide> } <ide> function normalizeEncoding(enc) { <ide> } <ide> } <ide> <add>function emitExperimentalWarning(feature) { <add> if (experimentalWarnings.has(feature)) return; <add> const msg = `${feature} is an experimental feature. This feature could ` + <add> 'change at any time'; <add> experimentalWarnings.add(feature); <add> process.emitWarning(msg, 'ExperimentalWarning'); <add>} <add> <ide> function filterDuplicateStrings(items, low) { <ide> const map = new Map(); <ide> for (var i = 0; i < items.length; i++) { <ide> module.exports = { <ide> createClassWrapper, <ide> decorateErrorStack, <ide> deprecate, <add> emitExperimentalWarning, <ide> filterDuplicateStrings, <ide> getConstructorOf, <ide> isError,
1
Ruby
Ruby
remove loaderror#path hack for ruby 1.9
36effd916c1f372ae94bcff54e947050538aa12d
<ide><path>activesupport/test/dependencies_test.rb <ide> class DependenciesTest < ActiveSupport::TestCase <ide> end <ide> <ide> def test_depend_on_path <del> skip "LoadError#path does not exist" if RUBY_VERSION < '2.0.0' <del> <ide> expected = assert_raises(LoadError) do <ide> Kernel.require 'omgwtfbbq' <ide> end
1
Javascript
Javascript
fix a warning about snapshotview
59e670e4535e69ba727796a4850fffd0552ab5f1
<ide><path>Libraries/RCTTest/SnapshotViewIOS.ios.js <ide> var Platform = require('Platform'); <ide> var React = require('React'); <ide> var StyleSheet = require('StyleSheet'); <del>var { TestModule } = require('NativeModules'); <add>var { TestModule, UIManager } = require('NativeModules'); <ide> var View = require('View'); <ide> <ide> var requireNativeComponent = require('requireNativeComponent'); <ide> var style = StyleSheet.create({ <ide> }, <ide> }); <ide> <del>var RCTSnapshot = Platform.OS === 'ios' ? <add>// Verify that RCTSnapshot is part of the UIManager since it is only loaded <add>// if you have linked against RCTTest like in tests, otherwise we will have <add>// a warning printed out <add>var RCTSnapshot = UIManager.RCTSnapshot ? <ide> requireNativeComponent('RCTSnapshot', SnapshotViewIOS) : <ide> View; <ide>
1
Javascript
Javascript
reset statenode in resetworkinprogress
0f334553c9558a56037b481fedc9b9fcad3643e7
<ide><path>packages/react-reconciler/src/ReactFiber.js <ide> export function resetWorkInProgress( <ide> <ide> workInProgress.dependencies = null; <ide> <add> workInProgress.stateNode = null; <add> <ide> if (enableProfilerTimer) { <ide> // Note: We don't reset the actualTime counts. It's useful to accumulate <ide> // actual time across multiple render passes. <ide><path>packages/react-reconciler/src/__tests__/ReactSuspenseList-test.internal.js <ide> describe('ReactSuspenseList', () => { <ide> </>, <ide> ); <ide> }); <add> <add> it('can resume class components when revealed together', async () => { <add> let A = createAsyncText('A'); <add> let B = createAsyncText('B'); <add> <add> class ClassComponent extends React.Component { <add> render() { <add> return this.props.children; <add> } <add> } <add> <add> function Foo() { <add> return ( <add> <Suspense fallback={<Text text="Loading" />}> <add> <SuspenseList revealOrder="together"> <add> <ClassComponent> <add> <Suspense fallback={<Text text="Loading A" />}> <add> <A /> <add> </Suspense> <add> </ClassComponent> <add> <ClassComponent> <add> <Suspense fallback={<Text text="Loading B" />}> <add> <B /> <add> </Suspense> <add> </ClassComponent> <add> </SuspenseList> <add> </Suspense> <add> ); <add> } <add> <add> await A.resolve(); <add> <add> ReactNoop.render(<Foo />); <add> <add> expect(Scheduler).toFlushAndYield([ <add> 'A', <add> 'Suspend! [B]', <add> 'Loading B', <add> 'Loading A', <add> 'Loading B', <add> ]); <add> <add> expect(ReactNoop).toMatchRenderedOutput( <add> <> <add> <span>Loading A</span> <add> <span>Loading B</span> <add> </>, <add> ); <add> <add> await B.resolve(); <add> <add> ReactNoop.render(<Foo />); <add> <add> expect(Scheduler).toFlushAndYield(['A', 'B']); <add> <add> expect(ReactNoop).toMatchRenderedOutput( <add> <> <add> <span>A</span> <add> <span>B</span> <add> </>, <add> ); <add> }); <ide> });
2
PHP
PHP
fix digestauthenticate component usermodel setting
1e9bcbbd05a5308cec275952bfdc853208f79890
<ide><path>src/Controller/Component/Auth/DigestAuthenticate.php <ide> class DigestAuthenticate extends BasicAuthenticate { <ide> * Settings for this object. <ide> * <ide> * - `fields` The fields to use to identify a user by. <del> * - `userModel` The model name of the User, defaults to User. <add> * - `userModel` The model name of the User, defaults to Users. <ide> * - `scope` Additional conditions to use when looking up and authenticating users, <ide> * i.e. `array('User.is_active' => 1).` <ide> * - `recursive` The value of the recursive key passed to find(). Defaults to 0. <ide> class DigestAuthenticate extends BasicAuthenticate { <ide> 'username' => 'username', <ide> 'password' => 'password' <ide> ), <del> 'userModel' => 'User', <add> 'userModel' => 'Users', <ide> 'scope' => array(), <ide> 'recursive' => 0, <ide> 'contain' => null, <ide><path>tests/TestCase/Controller/Component/Auth/DigestAuthenticateTest.php <ide> public function setUp() { <ide> <ide> $this->Collection = $this->getMock('Cake\Controller\ComponentRegistry'); <ide> $this->auth = new DigestAuthenticate($this->Collection, array( <del> 'fields' => array('username' => 'username', 'password' => 'password'), <del> 'userModel' => 'Users', <ide> 'realm' => 'localhost', <ide> 'nonce' => 123, <ide> 'opaque' => '123abc' <ide> public function setUp() { <ide> public function testConstructor() { <ide> $object = new DigestAuthenticate($this->Collection, array( <ide> 'userModel' => 'AuthUser', <del> 'fields' => array('username' => 'user', 'password' => 'password'), <add> 'fields' => array('username' => 'user', 'password' => 'pass'), <ide> 'nonce' => 123456 <ide> )); <ide> $this->assertEquals('AuthUser', $object->settings['userModel']); <del> $this->assertEquals(array('username' => 'user', 'password' => 'password'), $object->settings['fields']); <add> $this->assertEquals(array('username' => 'user', 'password' => 'pass'), $object->settings['fields']); <ide> $this->assertEquals(123456, $object->settings['nonce']); <ide> $this->assertEquals(env('SERVER_NAME'), $object->settings['realm']); <ide> }
2
Javascript
Javascript
add ability to fast track natively supported jpegs
7d1cddf371c968ec03bc116e4af273971ca2dcdc
<ide><path>src/canvas.js <ide> var CanvasGraphics = (function canvasGraphics() { <ide> this.restore(); <ide> }, <ide> <add> paintJpegXObject: function canvasGraphicsPaintJpegXObject(objId, w, h) { <add> var domImage = this.objs.get(objId); <add> if (!domImage) { <add> error('Dependent image isn\'t ready yet'); <add> } <add> <add> this.save(); <add> <add> var ctx = this.ctx; <add> // scale the image to the unit square <add> ctx.scale(1 / w, -1 / h); <add> <add> ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height, <add> 0, -h, w, h); <add> <add> this.restore(); <add> }, <ide> paintImageMaskXObject: function canvasGraphicsPaintImageMaskXObject( <ide> imgArray, inverseDecode, width, height) { <ide> function applyStencilMask(buffer, inverseDecode) { <ide><path>src/core.js <ide> var PDFDoc = (function pdfDoc() { <ide> var type = data[1]; <ide> <ide> switch (type) { <add> case 'JpegStream': <add> var imageData = data[2]; <add> loadJpegStream(id, imageData, this.objs); <add> break; <ide> case 'Image': <ide> var imageData = data[2]; <ide> this.objs.resolve(id, imageData); <ide><path>src/evaluator.js <ide> var PartialEvaluator = (function partialEvaluator() { <ide> // of image processing can be done here. <ide> var objId = 'img_' + uniquePrefix + (++self.objIdCounter); <ide> insertDependency([objId]); <del> fn = 'paintImageXObject'; <ide> args = [objId, w, h]; <del> var resolve = (function(objId) { <del> return function resolve(data) { <del> handler.send('obj', [objId, 'Image', data]); <del> }; <del> })(objId); <ide> <add> var softMask = dict.get('SMask', 'IM') || false; <add> if (!softMask && image instanceof JpegStream && image.isNative) { <add> // These JPEGs don't need any more processing so we can just send it. <add> fn = 'paintJpegXObject'; <add> handler.send('obj', [objId, 'JpegStream', image.getIR()]); <add> return; <add> } <add> <add> fn = 'paintImageXObject'; <ide> var imageObj = new PDFImage(xref, resources, image, inline, handler); <ide> <del> imageObj.ready(function() { <del> var imgData = { <del> width: w, <del> height: h, <del> data: new Uint8Array(w * h * 4) <add> imageObj.ready((function() { <add> return function(data) { <add> var imgData = { <add> width: w, <add> height: h, <add> data: new Uint8Array(w * h * 4) <add> }; <add> var pixels = imgData.data; <add> imageObj.fillRgbaBuffer(pixels, imageObj.decode); <add> handler.send('obj', [objId, 'Image', imgData]); <ide> }; <del> var pixels = imgData.data; <del> imageObj.fillRgbaBuffer(pixels, imageObj.decode); <del> resolve(imgData); <del> }); <add> })(objId)); <ide> } <ide> <ide> uniquePrefix = uniquePrefix || ''; <ide><path>src/image.js <ide> var PDFImage = (function pdfImage() { <ide> var buf = new Uint8Array(width * height); <ide> <ide> if (smask) { <add> if (!smask.isReady()) <add> error('Soft mask is not ready.'); <ide> var sw = smask.width; <ide> var sh = smask.height; <ide> if (sw != this.width || sh != this.height) <ide> var PDFImage = (function pdfImage() { <ide> applyStencilMask: function applyStencilMask(buffer, inverseDecode) { <ide> var width = this.width, height = this.height; <ide> var bitStrideLength = (width + 7) >> 3; <del> this.image.reset(); <del> var imgArray = this.image.getBytes(bitStrideLength * height); <add> var imgArray = this.getImageBytes(bitStrideLength * height); <ide> var imgArrayPos = 0; <ide> var i, j, mask, buf; <ide> // removing making non-masked pixels transparent <ide> var PDFImage = (function pdfImage() { <ide> <ide> // rows start at byte boundary; <ide> var rowBytes = (width * numComps * bpc + 7) >> 3; <del> this.image.reset(); <del> var imgArray = this.image.getBytes(height * rowBytes); <add> var imgArray = this.getImageBytes(height * rowBytes); <ide> <ide> var comps = this.colorSpace.getRgbBuffer( <ide> this.getComponents(imgArray, decodeMap), bpc); <ide> var PDFImage = (function pdfImage() { <ide> <ide> // rows start at byte boundary; <ide> var rowBytes = (width * numComps * bpc + 7) >> 3; <del> this.image.reset(); <del> var imgArray = this.image.getBytes(height * rowBytes); <add> var imgArray = this.getImageBytes(height * rowBytes); <ide> <ide> var comps = this.getComponents(imgArray); <ide> var length = width * height; <ide> <ide> for (var i = 0; i < length; ++i) <ide> buffer[i] = comps[i]; <ide> }, <add> getImageBytes: function getImageBytes(length) { <add> if (!this.isReady()) <add> error('Image is not ready to be read.'); <add> this.image.reset(); <add> return this.image.getBytes(length); <add> }, <ide> isReady: function isReady() { <ide> return this.imageReady && this.smaskReady; <ide> }, <ide> var PDFImage = (function pdfImage() { <ide> }; <ide> return constructor; <ide> })(); <add>function loadJpegStream(id, imageData, objs) { <add> var img = new Image(); <add> img.onload = (function jpegImageLoaderOnload() { <add> objs.resolve(id, img); <add> }); <add> img.src = 'data:image/jpeg;base64,' + window.btoa(imageData); <add>} <ide><path>src/stream.js <ide> var JpegStream = (function jpegStream() { <ide> <ide> this.colorTransform = -1; <ide> <del> this.bytes = bytes; <del> <ide> if (isAdobeImage(bytes)) { <ide> // when bug 674619 land, let's check if browser can do <ide> // normal cmyk and then we won't have to the following
5
Javascript
Javascript
accomodate additional webxr changes
b4734f2dad51aecf65d3d764f45751e42162da83
<ide><path>examples/js/vr/WebVR.js <ide> var WEBVR = { <ide> <ide> if ( currentSession === null ) { <ide> <del> device.requestSession( { immersive: true, exclusive: true /* DEPRECATED */ } ).then( onSessionStarted ); <add> if (device) { <add> <add> device.requestSession( { immersive: true, exclusive: true /* DEPRECATED */ } ).then( onSessionStarted ); <add> <add> } else { <add> <add> navigator.xr.requestSession( { mode: 'immersive-vr' } ).then( onSessionStarted ); <add> <add> } <ide> <ide> } else { <ide> <ide> var WEBVR = { <ide> <ide> }; <ide> <del> renderer.vr.setDevice( device ); <add> if ( device ) { <add> <add> renderer.vr.setDevice( device ); <add> <add> } <ide> <ide> } <ide> <ide> var WEBVR = { <ide> <ide> stylizeElement( button ); <ide> <del> navigator.xr.requestDevice().then( function ( device ) { <add> if (navigator.xr.supportsSessionMode) { <add> <add> navigator.xr.supportsSessionMode( 'immersive-vr' ).then( function () { <add> showEnterXR( ); <add> }); <add> <add> } else { <ide> <del> device.supportsSession( { immersive: true, exclusive: true /* DEPRECATED */ } ) <del> .then( function () { showEnterXR( device ); } ) <del> .catch( showVRNotFound ); <add> navigator.xr.requestDevice().then( function ( device ) { <ide> <del> } ).catch( showVRNotFound ); <add> device.supportsSession( { immersive: true, exclusive: true /* DEPRECATED */ } ) <add> .then( function () { showEnterXR( device ); } ) <add> .catch( showVRNotFound ); <add> <add> } ).catch( showVRNotFound ); <add> <add> } <ide> <ide> return button; <ide> <ide><path>src/renderers/WebGLRenderer.js <ide> function WebGLRenderer( parameters ) { <ide> antialias: _antialias, <ide> premultipliedAlpha: _premultipliedAlpha, <ide> preserveDrawingBuffer: _preserveDrawingBuffer, <del> powerPreference: _powerPreference <add> powerPreference: _powerPreference, <add> xrCompatible: true <ide> }; <ide> <ide> // event listeners must be registered before WebGL context is created, see #12753 <ide><path>src/renderers/webvr/WebXRManager.js <ide> function WebXRManager( renderer ) { <ide> <ide> frameOfReference = value; <ide> <del> renderer.setFramebuffer( session.baseLayer.framebuffer ); <add> if ( session.baseLayer && session.baseLayer.framebuffer ) { <ide> <add> renderer.setFramebuffer( session.baseLayer.framebuffer ); <add> <add> } <ide> animation.setContext( session ); <ide> animation.start(); <ide> <ide> function WebXRManager( renderer ) { <ide> session.addEventListener( 'selectend', onSessionEvent ); <ide> session.addEventListener( 'end', onSessionEnd ); <ide> <del> session.baseLayer = new XRWebGLLayer( session, gl, { framebufferScaleFactor: framebufferScaleFactor } ); <add> if ( session.updateRenderState !== undefined ) { <add> <add> session.updateRenderState( { baseLayer: new XRWebGLLayer( session, gl ) } ); <add> <add> } else { <add> <add> session.baseLayer = new XRWebGLLayer( session, gl, { framebufferScaleFactor: framebufferScaleFactor } ); <add> <add> } <ide> <ide> if ( session.requestFrameOfReference !== undefined ) { <ide> <ide> function WebXRManager( renderer ) { <ide> <ide> if ( pose !== null ) { <ide> <del> var layer = session.baseLayer; <add> var layer = 'renderState' in session ? session.renderState.baseLayer : session.baseLayer; <ide> var views = frame.views || pose.views; <ide> <add> if ( 'renderState' in session ) { <add> <add> renderer.setFramebuffer( session.renderState.baseLayer.framebuffer ); <add> <add> } <add> <ide> for ( var i = 0; i < views.length; i ++ ) { <ide> <ide> var view = views[ i ];
3
Java
Java
improve setting of websocket error status
b6144e5682c966759e7fd16dbac4d4948d332161
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/socket/adapter/AbstractListenerWebSocketSession.java <ide> import org.springframework.http.server.reactive.AbstractListenerWriteProcessor; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.Assert; <add>import org.springframework.util.StringUtils; <ide> import org.springframework.web.reactive.socket.CloseStatus; <ide> import org.springframework.web.reactive.socket.HandshakeInfo; <ide> import org.springframework.web.reactive.socket.WebSocketHandler; <ide> public void onError(Throwable ex) { <ide> if (this.handlerCompletionMono != null) { <ide> this.handlerCompletionMono.onError(ex); <ide> } <del> close(CloseStatus.SERVER_ERROR.withReason(ex.getMessage())); <add> if(!StringUtils.hasText(ex.getMessage())) { <add> close(CloseStatus.SERVER_ERROR); <add> } <add> else { <add> close(CloseStatus.SERVER_ERROR.withReason(ex.getMessage())); <add> } <ide> } <ide> <ide> @Override
1
PHP
PHP
add a convention for dispatcher filter names
7db068c945a94718d0bdb430745927aa373626a7
<ide><path>src/Routing/DispatcherFactory.php <ide> public static function add($filter) { <ide> * <ide> * @param string $name The name of the filter to build. <ide> * @return \Cake\Routing\DispatcherFilter <add> * @throws \Cake\Routing\Error\MissingDispatcherFilterException When filters cannot be found. <ide> */ <ide> protected static function _createFilter($name) { <del> $className = App::className($name, 'Routing/Filter'); <add> $className = App::className($name, 'Routing/Filter', 'Filter'); <ide> if (!$className) { <ide> $msg = sprintf('Cannot locate dispatcher filter named "%s".', $name); <ide> throw new MissingDispatcherFilterException($msg); <ide><path>src/Routing/DispatcherFilter.php <ide> class DispatcherFilter implements EventListener { <ide> * Constructor. <ide> * <ide> * @param array $config Settings for the filter. <add> * @throws \Cake\Error\Exception When 'when' conditions are not callable. <ide> */ <ide> public function __construct($config = []) { <ide> if (!isset($config['priority'])) { <ide> public function implementedEvents() { <ide> */ <ide> public function handle(Event $event) { <ide> $name = $event->name(); <del> list($_, $method) = explode('.', $name); <add> list($unused, $method) = explode('.', $name); <ide> if (empty($this->_config['for']) && empty($this->_config['when'])) { <ide> return $this->{$method}($event); <ide> } <add><path>src/Routing/Filter/AssetFilter.php <del><path>src/Routing/Filter/AssetDispatcher.php <ide> * serves the file to the client if appropriate. <ide> * <ide> */ <del>class AssetDispatcher extends DispatcherFilter { <add>class AssetFilter extends DispatcherFilter { <ide> <ide> /** <ide> * Default priority for all methods in this filter <add><path>src/Routing/Filter/CacheFilter.php <del><path>src/Routing/Filter/CacheDispatcher.php <ide> * and served it back to the client if appropriate. <ide> * <ide> */ <del>class CacheDispatcher extends DispatcherFilter { <add>class CacheFilter extends DispatcherFilter { <ide> <ide> /** <ide> * Default priority for all methods in this filter <ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php <ide> class RequestHandlerComponentTest extends TestCase { <ide> public function setUp() { <ide> parent::setUp(); <ide> Configure::write('App.namespace', 'TestApp'); <del> DispatcherFactory::add('RoutingFilter'); <add> DispatcherFactory::add('Routing'); <ide> $this->_init(); <ide> } <ide> <ide><path>tests/TestCase/Controller/Component/SessionComponentTest.php <ide> public static function setupBeforeClass() { <ide> 'timeout' => 100, <ide> 'cookie' => 'test' <ide> )); <del> DispatcherFactory::add('RoutingFilter'); <add> DispatcherFactory::add('Routing'); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Routing/DispatcherFactoryTest.php <ide> public function testAddFilter() { <ide> * @return void <ide> */ <ide> public function testAddFilterString() { <del> $result = DispatcherFactory::add('RoutingFilter'); <add> $result = DispatcherFactory::add('Routing'); <ide> $this->assertInstanceOf('Cake\Routing\Filter\RoutingFilter', $result); <ide> } <ide> <ide><path>tests/TestCase/Routing/DispatcherTest.php <ide> use Cake\Network\Request; <ide> use Cake\Network\Response; <ide> use Cake\Routing\Dispatcher; <del>use Cake\Routing\Filter\AssetDispatcher; <del>use Cake\Routing\Error\MissingDispatcherFilterException; <ide> use Cake\Routing\Router; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\Utility\Inflector; <add><path>tests/TestCase/Routing/Filter/AssetFilterTest.php <del><path>tests/TestCase/Routing/Filter/AssetDispatcherTest.php <ide> use Cake\Event\Event; <ide> use Cake\Network\Request; <ide> use Cake\Network\Response; <del>use Cake\Routing\Filter\AssetDispatcher; <add>use Cake\Routing\Filter\AssetFilter; <ide> use Cake\TestSuite\TestCase; <ide> <del>class AssetDispatcherTest extends TestCase { <del> <del>/** <del> * tearDown method <del> * <del> * @return void <del> */ <del> public function tearDown() { <del> parent::tearDown(); <del> <del> Configure::write('Dispatcher.filters', array()); <del> } <add>class AssetFilterTest extends TestCase { <ide> <ide> /** <ide> * Tests that $response->checkNotModified() is called and bypasses <ide> public function tearDown() { <ide> * @return void <ide> */ <ide> public function testNotModified() { <del> $filter = new AssetDispatcher(); <add> $filter = new AssetFilter(); <ide> $time = filemtime(App::themePath('TestTheme') . 'webroot/img/cake.power.gif'); <ide> $time = new \DateTime('@' . $time); <ide> <ide> public function testNotModified() { <ide> * @return void <ide> */ <ide> public function test404OnDoubleSlash() { <del> $filter = new AssetDispatcher(); <add> $filter = new AssetFilter(); <ide> <ide> $response = $this->getMock('Response', array('_sendHeader')); <ide> $request = new Request('//index.php'); <ide> public function test404OnDoubleSlash() { <ide> * @return voi <ide> */ <ide> public function test404OnDoubleDot() { <del> $filter = new AssetDispatcher(); <add> $filter = new AssetFilter(); <ide> <ide> $response = $this->getMock('Response', array('_sendHeader')); <ide> $request = new Request('theme/test_theme/../webroot/css/test_asset.css'); <ide> public static function assetProvider() { <ide> public function testAsset($url, $file) { <ide> Plugin::load(array('TestPlugin', 'PluginJs')); <ide> <del> $filter = new AssetDispatcher(); <add> $filter = new AssetFilter(); <ide> $response = $this->getMock('Cake\Network\Response', array('_sendHeader')); <ide> $request = new Request($url); <ide> $event = new Event('Dispatcher.beforeDispatch', $this, compact('request', 'response')); <add><path>tests/TestCase/Routing/Filter/CacheFilterTest.php <del><path>tests/TestCase/Routing/Filter/CacheDispatcherTest.php <ide> use Cake\Network\Request; <ide> use Cake\Network\Response; <ide> use Cake\Routing\Dispatcher; <del>use Cake\Routing\Filter\CacheDispatcher; <add>use Cake\Routing\Filter\CacheFilter; <ide> use Cake\Routing\Filter\RoutingFilter; <ide> use Cake\Routing\Router; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\Utility\Inflector; <ide> <ide> /** <del> * CacheDispatcherTest class <add> * CacheFilterTest class <ide> * <ide> */ <del>class CacheDispatcherTest extends TestCase { <add>class CacheFilterTest extends TestCase { <ide> <ide> /** <ide> * setUp method <ide> public function testFullPageCachingDispatch($url) { <ide> $response = $this->getMock('Cake\Network\Response', array('send')); <ide> $dispatcher = new Dispatcher(); <ide> $dispatcher->add(new RoutingFilter()); <del> $dispatcher->add(new CacheDispatcher()); <add> $dispatcher->add(new CacheFilter()); <ide> $dispatcher->dispatch($request, $response); <ide> $cached = $response->body(); <ide> <ide><path>tests/TestCase/Routing/Filter/RoutingFilterTest.php <ide> <ide> use Cake\Event\Event; <ide> use Cake\Network\Request; <del>use Cake\Routing\Router; <ide> use Cake\Routing\Filter\RoutingFilter; <add>use Cake\Routing\Router; <ide> use Cake\TestSuite\TestCase; <ide> <ide> /** <ide><path>tests/TestCase/Routing/RequestActionTraitTest.php <ide> public function setUp() { <ide> parent::setUp(); <ide> Configure::write('App.namespace', 'TestApp'); <ide> Configure::write('Security.salt', 'not-the-default'); <del> DispatcherFactory::add('RoutingFilter'); <add> DispatcherFactory::add('Routing'); <ide> $this->object = $this->getObjectForTrait('Cake\Routing\RequestActionTrait'); <ide> } <ide> <ide><path>tests/TestCase/TestSuite/ControllerTestCaseTest.php <ide> public function setUp() { <ide> Plugin::load(array('TestPlugin', 'TestPluginTwo')); <ide> <ide> $this->Case = $this->getMockForAbstractClass('Cake\TestSuite\ControllerTestCase'); <del> DispatcherFactory::add('RoutingFilter'); <add> DispatcherFactory::add('Routing'); <ide> Router::reload(); <ide> TableRegistry::clear(); <ide> }
13
Python
Python
find lowercased forms of numeric words
9bc524982e33bb9bc8dcd881ce5cff5f3f54eae4
<ide><path>spacy/lang/da/lex_attrs.py <ide> def like_num(text): <ide> num, denom = text.split('/') <ide> if num.isdigit() and denom.isdigit(): <ide> return True <del> if text in _num_words: <add> if text.lower() in _num_words: <ide> return True <del> if text in _ordinal_words: <add> if text.lower() in _ordinal_words: <ide> return True <ide> return False <ide> <ide><path>spacy/lang/en/lex_attrs.py <ide> def like_num(text): <ide> num, denom = text.split('/') <ide> if num.isdigit() and denom.isdigit(): <ide> return True <del> if text in _num_words: <add> if text.lower() in _num_words: <ide> return True <ide> return False <ide> <ide><path>spacy/lang/fr/lex_attrs.py <ide> def like_num(text): <ide> num, denom = text.split('/') <ide> if num.isdigit() and denom.isdigit(): <ide> return True <del> if text in _num_words: <add> if text.lower() in _num_words: <ide> return True <ide> return False <ide> <ide><path>spacy/lang/id/lex_attrs.py <ide> def like_num(text): <ide> num, denom = text.split('/') <ide> if num.isdigit() and denom.isdigit(): <ide> return True <del> if text in _num_words: <add> if text.lower() in _num_words: <ide> return True <ide> if text.count('-') == 1: <ide> _, num = text.split('-') <ide><path>spacy/lang/nl/lex_attrs.py <ide> def like_num(text): <ide> num, denom = text.split('/') <ide> if num.isdigit() and denom.isdigit(): <ide> return True <del> if text in _num_words: <add> if text.lower() in _num_words: <ide> return True <ide> return False <ide> <ide><path>spacy/lang/pt/lex_attrs.py <ide> def like_num(text): <ide> num, denom = text.split('/') <ide> if num.isdigit() and denom.isdigit(): <ide> return True <del> if text in _num_words: <add> if text.lower() in _num_words: <ide> return True <ide> return False <ide> <ide><path>spacy/lang/ru/lex_attrs.py <ide> def like_num(text): <ide> num, denom = text.split('/') <ide> if num.isdigit() and denom.isdigit(): <ide> return True <del> if text in _num_words: <add> if text.lower() in _num_words: <ide> return True <ide> return False <ide>
7
Javascript
Javascript
add test cases
52d8fbc8c115d48d39a0a647dc39d59c9d71f0e8
<ide><path>test/cases/parsing/template-string/abc/abcTest.js <add>export default "ok"; <ide>\ No newline at end of file <ide><path>test/cases/parsing/template-string/index.js <add>var should = require('should') <add> <add>it("should parse template strings in System.import", function(done) { <add> var name = "abc".split(""); <add> Promise.all([ <add> System.import(`./abc/${name[0]}${name[1]}${name[2]}Test`), <add> System.import(String.raw`./${name.join("")}/${name.join("")}Test`) <add> ]) <add> .then(function (imports) { <add> for (var i = 0; i < imports.length; i++) { <add> imports[i].default.should.eql("ok"); <add> } <add> }) <add> .then(function () { done(); }, done) <add>}); <ide><path>test/cases/parsing/template-string/test.filter.js <add>var supportsTemplateStrings = require("../../../helpers/supportsTemplateStrings"); <add> <add>module.exports = function(config) { <add> return !config.minimize && supportsTemplateStrings(); <add>}; <ide><path>test/helpers/supportsTemplateStrings.js <add>module.exports = function supportsTemplateStrings() { <add> try { <add> var f = eval("(function f() { return String.raw`a\\b`; })"); <add> return f() === "a\\b"; <add> } catch(e) { <add> return false; <add> } <add>};
4
PHP
PHP
fix json queries with table names on sql server
8dd376c3ffb1de29c0e421db1bda29a988768b0c
<ide><path>src/Illuminate/Database/Query/Grammars/Grammar.php <ide> <ide> use RuntimeException; <ide> use Illuminate\Support\Arr; <add>use Illuminate\Support\Str; <ide> use Illuminate\Database\Query\Builder; <ide> use Illuminate\Database\Query\JoinClause; <ide> use Illuminate\Database\Grammar as BaseGrammar; <ide> class Grammar extends BaseGrammar <ide> 'lock', <ide> ]; <ide> <add> /** <add> * Wrap a value in keyword identifiers. <add> * <add> * @param \Illuminate\Database\Query\Expression|string $value <add> * @param bool $prefixAlias <add> * @return string <add> */ <add> public function wrap($value, $prefixAlias = false) <add> { <add> if ($this->isExpression($value)) { <add> return $this->getValue($value); <add> } <add> <add> // If the value being wrapped has a column alias we will need to separate out <add> // the pieces so we can wrap each of the segments of the expression on its <add> // own, and then join these both back together using the "as" connector. <add> if (strpos(strtolower($value), ' as ') !== false) { <add> return $this->wrapAliasedValue($value, $prefixAlias); <add> } <add> <add> // If the given value is a JSON selector we will wrap it differently than a <add> // traditional value. We will need to split this path and wrap each part <add> // wrapped, etc. Otherwise, we will simply wrap the value as a string. <add> if ($this->isJsonSelector($value)) { <add> return $this->wrapJsonSelector($value); <add> } <add> <add> return $this->wrapSegments(explode('.', $value)); <add> } <add> <add> /** <add> * Wrap the given JSON selector. <add> * <add> * @param string $value <add> * @return string <add> */ <add> protected function wrapJsonSelector($value) <add> { <add> throw new RuntimeException('This database engine does not support JSON operations.'); <add> } <add> <add> /** <add> * Determine if the given string is a JSON selector. <add> * <add> * @param string $value <add> * @return bool <add> */ <add> protected function isJsonSelector($value) <add> { <add> return Str::contains($value, '->'); <add> } <add> <ide> /** <ide> * Compile a select query into SQL. <ide> * <ide> protected function whereJsonContains(Builder $query, $where) <ide> $not = $where['not'] ? 'not ' : ''; <ide> <ide> return $not.$this->compileJsonContains( <del> $this->wrap($where['column']), $this->parameter($where['value']) <add> $where['column'], $this->parameter($where['value']) <ide> ); <ide> } <ide> <ide><path>src/Illuminate/Database/Query/Grammars/MySqlGrammar.php <ide> namespace Illuminate\Database\Query\Grammars; <ide> <ide> use Illuminate\Support\Arr; <del>use Illuminate\Support\Str; <ide> use Illuminate\Database\Query\Builder; <ide> use Illuminate\Database\Query\JsonExpression; <ide> <ide> public function compileSelect(Builder $query) <ide> */ <ide> protected function compileJsonContains($column, $value) <ide> { <del> return 'json_contains('.$column.', '.$value.')'; <add> return 'json_contains('.$this->wrap($column).', '.$value.')'; <ide> } <ide> <ide> /** <ide> protected function compileDeleteWithJoins($query, $table, $where) <ide> */ <ide> protected function wrapValue($value) <ide> { <del> if ($value === '*') { <del> return $value; <del> } <del> <del> // If the given value is a JSON selector we will wrap it differently than a <del> // traditional value. We will need to split this path and wrap each part <del> // wrapped, etc. Otherwise, we will simply wrap the value as a string. <del> if ($this->isJsonSelector($value)) { <del> return $this->wrapJsonSelector($value); <del> } <del> <del> return '`'.str_replace('`', '``', $value).'`'; <add> return $value === '*' ? $value : '`'.str_replace('`', '``', $value).'`'; <ide> } <ide> <ide> /** <ide> protected function wrapJsonSelector($value) <ide> { <ide> $path = explode('->', $value); <ide> <del> $field = $this->wrapValue(array_shift($path)); <add> $field = $this->wrapSegments(explode('.', array_shift($path))); <ide> <ide> return sprintf('%s->\'$.%s\'', $field, collect($path)->map(function ($part) { <ide> return '"'.$part.'"'; <ide> })->implode('.')); <ide> } <del> <del> /** <del> * Determine if the given string is a JSON selector. <del> * <del> * @param string $value <del> * @return bool <del> */ <del> protected function isJsonSelector($value) <del> { <del> return Str::contains($value, '->'); <del> } <ide> } <ide><path>src/Illuminate/Database/Query/Grammars/PostgresGrammar.php <ide> namespace Illuminate\Database\Query\Grammars; <ide> <ide> use Illuminate\Support\Arr; <del>use Illuminate\Support\Str; <ide> use Illuminate\Database\Query\Builder; <ide> <ide> class PostgresGrammar extends Grammar <ide> protected function dateBasedWhere($type, Builder $query, $where) <ide> */ <ide> protected function compileJsonContains($column, $value) <ide> { <del> $column = str_replace('->>', '->', $column); <add> $column = str_replace('->>', '->', $this->wrap($column)); <ide> <ide> return '('.$column.')::jsonb @> '.$value; <ide> } <ide> public function compileTruncate(Builder $query) <ide> return ['truncate '.$this->wrapTable($query->from).' restart identity' => []]; <ide> } <ide> <del> /** <del> * Wrap a single string in keyword identifiers. <del> * <del> * @param string $value <del> * @return string <del> */ <del> protected function wrapValue($value) <del> { <del> if ($value === '*') { <del> return $value; <del> } <del> <del> // If the given value is a JSON selector we will wrap it differently than a <del> // traditional value. We will need to split this path and wrap each part <del> // wrapped, etc. Otherwise, we will simply wrap the value as a string. <del> if (Str::contains($value, '->')) { <del> return $this->wrapJsonSelector($value); <del> } <del> <del> return '"'.str_replace('"', '""', $value).'"'; <del> } <del> <ide> /** <ide> * Wrap the given JSON selector. <ide> * <ide> protected function wrapJsonSelector($value) <ide> { <ide> $path = explode('->', $value); <ide> <del> $field = $this->wrapValue(array_shift($path)); <add> $field = $this->wrapSegments(explode('.', array_shift($path))); <ide> <ide> $wrappedPath = $this->wrapJsonPathAttributes($path); <ide> <ide><path>src/Illuminate/Database/Query/Grammars/SqlServerGrammar.php <ide> namespace Illuminate\Database\Query\Grammars; <ide> <ide> use Illuminate\Support\Arr; <del>use Illuminate\Support\Str; <ide> use Illuminate\Database\Query\Builder; <ide> <ide> class SqlServerGrammar extends Grammar <ide> protected function whereDate(Builder $query, $where) <ide> */ <ide> protected function compileJsonContains($column, $value) <ide> { <del> $from = $column[0] == '[' <del> ? 'openjson('.$column.')' <del> : substr_replace($column, 'openjson', 0, strlen('json_value')); <add> $parts = explode('->', $column, 2); <ide> <del> return $value.' in (select [value] from '.$from.')'; <add> $field = $this->wrap($parts[0]); <add> <add> $path = count($parts) > 1 ? ', '.$this->wrapJsonPath($parts[1]) : ''; <add> <add> return $value.' in (select [value] from openjson('.$field.$path.'))'; <ide> } <ide> <ide> /** <ide> public function getDateFormat() <ide> */ <ide> protected function wrapValue($value) <ide> { <del> if ($value === '*') { <del> return $value; <del> } <del> <del> // If the given value is a JSON selector we will wrap it differently than a <del> // traditional value. We will need to split this path and wrap each part <del> // wrapped, etc. Otherwise, we will simply wrap the value as a string. <del> if (Str::contains($value, '->')) { <del> return $this->wrapJsonSelector($value); <del> } <del> <del> return '['.str_replace(']', ']]', $value).']'; <add> return $value === '*' ? $value : '['.str_replace(']', ']]', $value).']'; <ide> } <ide> <ide> /** <ide> protected function wrapValue($value) <ide> */ <ide> protected function wrapJsonSelector($value) <ide> { <del> $path = explode('->', $value); <add> $parts = explode('->', $value, 2); <add> <add> $field = $this->wrapSegments(explode('.', array_shift($parts))); <ide> <del> $field = $this->wrapValue(array_shift($path)); <add> return 'json_value('.$field.', '.$this->wrapJsonPath($parts[0]).')'; <add> } <ide> <del> return sprintf('json_value(%s, \'$.%s\')', $field, collect($path)->map(function ($part) { <del> return '"'.$part.'"'; <del> })->implode('.')); <add> /** <add> * Wrap the given JSON path. <add> * <add> * @param string $value <add> * @return string <add> */ <add> protected function wrapJsonPath($value) <add> { <add> return '\'$."'.str_replace('->', '"."', $value).'"\''; <ide> } <ide> <ide> /** <ide><path>tests/Database/DatabaseQueryBuilderTest.php <ide> public function testMySqlWrappingJson() <ide> $this->assertEquals('select * from `users` where items->\'$."price"\' = 1', $builder->toSql()); <ide> <ide> $builder = $this->getMySqlBuilder(); <del> $builder->select('items->price')->from('users')->where('items->price', '=', 1)->orderBy('items->price'); <del> $this->assertEquals('select `items`->\'$."price"\' from `users` where `items`->\'$."price"\' = ? order by `items`->\'$."price"\' asc', $builder->toSql()); <add> $builder->select('items->price')->from('users')->where('users.items->price', '=', 1)->orderBy('items->price'); <add> $this->assertEquals('select `items`->\'$."price"\' from `users` where `users`.`items`->\'$."price"\' = ? order by `items`->\'$."price"\' asc', $builder->toSql()); <ide> <ide> $builder = $this->getMySqlBuilder(); <ide> $builder->select('*')->from('users')->where('items->price->in_usd', '=', 1); <ide> public function testMySqlWrappingJson() <ide> public function testPostgresWrappingJson() <ide> { <ide> $builder = $this->getPostgresBuilder(); <del> $builder->select('items->price')->from('users')->where('items->price', '=', 1)->orderBy('items->price'); <del> $this->assertEquals('select "items"->>\'price\' from "users" where "items"->>\'price\' = ? order by "items"->>\'price\' asc', $builder->toSql()); <add> $builder->select('items->price')->from('users')->where('users.items->price', '=', 1)->orderBy('items->price'); <add> $this->assertEquals('select "items"->>\'price\' from "users" where "users"."items"->>\'price\' = ? order by "items"->>\'price\' asc', $builder->toSql()); <ide> <ide> $builder = $this->getPostgresBuilder(); <ide> $builder->select('*')->from('users')->where('items->price->in_usd', '=', 1); <ide> public function testPostgresWrappingJson() <ide> public function testSqlServerWrappingJson() <ide> { <ide> $builder = $this->getSqlServerBuilder(); <del> $builder->select('items->price')->from('users')->where('items->price', '=', 1)->orderBy('items->price'); <del> $this->assertEquals('select json_value([items], \'$."price"\') from [users] where json_value([items], \'$."price"\') = ? order by json_value([items], \'$."price"\') asc', $builder->toSql()); <add> $builder->select('items->price')->from('users')->where('users.items->price', '=', 1)->orderBy('items->price'); <add> $this->assertEquals('select json_value([items], \'$."price"\') from [users] where json_value([users].[items], \'$."price"\') = ? order by json_value([items], \'$."price"\') asc', $builder->toSql()); <ide> <ide> $builder = $this->getSqlServerBuilder(); <ide> $builder->select('*')->from('users')->where('items->price->in_usd', '=', 1); <ide> public function testWhereJsonContainsMySql() <ide> $this->assertEquals(['["en"]'], $builder->getBindings()); <ide> <ide> $builder = $this->getMySqlBuilder(); <del> $builder->select('*')->from('users')->whereJsonContains('options->languages', ['en']); <del> $this->assertEquals('select * from `users` where json_contains(`options`->\'$."languages"\', ?)', $builder->toSql()); <add> $builder->select('*')->from('users')->whereJsonContains('users.options->languages', ['en']); <add> $this->assertEquals('select * from `users` where json_contains(`users`.`options`->\'$."languages"\', ?)', $builder->toSql()); <ide> $this->assertEquals(['["en"]'], $builder->getBindings()); <ide> <ide> $builder = $this->getMySqlBuilder(); <ide> public function testWhereJsonContainsPostgres() <ide> $this->assertEquals(['["en"]'], $builder->getBindings()); <ide> <ide> $builder = $this->getPostgresBuilder(); <del> $builder->select('*')->from('users')->whereJsonContains('options->languages', ['en']); <del> $this->assertEquals('select * from "users" where ("options"->\'languages\')::jsonb @> ?', $builder->toSql()); <add> $builder->select('*')->from('users')->whereJsonContains('users.options->languages', ['en']); <add> $this->assertEquals('select * from "users" where ("users"."options"->\'languages\')::jsonb @> ?', $builder->toSql()); <ide> $this->assertEquals(['["en"]'], $builder->getBindings()); <ide> <ide> $builder = $this->getPostgresBuilder(); <ide> public function testWhereJsonContainsSqlServer() <ide> $this->assertEquals(['true'], $builder->getBindings()); <ide> <ide> $builder = $this->getSqlServerBuilder(); <del> $builder->select('*')->from('users')->whereJsonContains('options->languages', 'en'); <del> $this->assertEquals('select * from [users] where ? in (select [value] from openjson([options], \'$."languages"\'))', $builder->toSql()); <add> $builder->select('*')->from('users')->whereJsonContains('users.options->languages', 'en'); <add> $this->assertEquals('select * from [users] where ? in (select [value] from openjson([users].[options], \'$."languages"\'))', $builder->toSql()); <ide> $this->assertEquals(['en'], $builder->getBindings()); <ide> <ide> $builder = $this->getSqlServerBuilder();
5
Text
Text
add instructions for including files in sidebar
b19147fc8ba01f084352d2c70e0c1ffe159f6c08
<ide><path>docs/how-to-work-on-the-docs-theme.md <ide> <ide> To work on the contributing guidelines, you can edit or add files in the `docs` directory [available here](https://github.com/freeCodeCamp/freeCodeCamp/tree/main/docs). When your changes are merged, they will be made available automatically at the documentation site. <ide> <add>When adding a new file to the `docs` directory, you should evaluate if the file should also be added to the sidebar navigation. We typically create a link in the [`_sidebar.md`](_sidebar.md) file for new and independent guides. Alternatively, You may follow the instructions below on creating an internal link for supporting guides. <add> <ide> ### How to create an internal link <ide> <ide> If you want to create a link targeting a different section of the contributing guidelines, follow this format: <ide> Typically you would not need to change any configuration or build the site local <ide> - We serve this file as a SPA using `docsify` and GitHub Pages. <ide> - The `docsify` script generates the content of `markdown` files in the `docs` directory on demand. <ide> - The homepage is generated from the [`_coverpage.md`](_coverpage.md). <del>- the sidebar navigation is generated from [`_sidebar.md`](_sidebar.md). <add>- The sidebar navigation is generated from [`_sidebar.md`](_sidebar.md). <ide> <ide> ### Serving the documentation site locally <ide>
1
Go
Go
fix race in testrun
ad9710685ca3ae101c84a57c7d68a25cba4bede2
<ide><path>container.go <ide> func (container *Container) monitor() { <ide> exitCode := container.process.GetExitCode() <ide> container.State.SetStopped(exitCode) <ide> <del> close(container.waitLock) <ide> if err := container.ToDisk(); err != nil { <ide> // FIXME: there is a race condition here which causes this to fail during the unit tests. <ide> // If another goroutine was waiting for Wait() to return before removing the container's root <ide> func (container *Container) monitor() { <ide> // FIXME: why are we serializing running state to disk in the first place? <ide> //log.Printf("%s: Failed to dump configuration to the disk: %s", container.ID, err) <ide> } <add> close(container.waitLock) <ide> } <ide> <ide> func (container *Container) cleanup() { <ide><path>execdriver/driver.go <ide> func (c *Process) Pid() int { <ide> } <ide> <ide> func (c *Process) GetExitCode() int { <add> if c.ProcessState == nil { <add> return -1 <add> } <ide> return c.ProcessState.Sys().(syscall.WaitStatus).ExitStatus() <del> return -1 <ide> } <ide><path>execdriver/lxc/driver.go <ide> func (d *driver) waitForStart(c *execdriver.Process) error { <ide> // Note: The container can run and finish correctly before <ide> // the end of this loop <ide> for now := time.Now(); time.Since(now) < 5*time.Second; { <del> // If the process dies while waiting for it, just return <del> if c.ProcessState != nil && c.ProcessState.Exited() { <del> return nil <add> select { <add> case <-c.WaitLock: <add> // If the process dies while waiting for it, just return <add> if c.ProcessState != nil && c.ProcessState.Exited() { <add> return nil <add> } <add> default: <ide> } <ide> <ide> output, err = d.getInfo(c)
3
Text
Text
fix typos for incorrect spelling of ethereum
5f566b20aeae3030eec9d6a14016ed71c85dac3d
<ide><path>client/src/pages/guide/english/blockchain/smart-contracts/index.md <ide> title: Smart Contracts <ide> ## Smart Contracts <ide> <ide> Transactions in a blockchain are a very basic contract - One party sends resources to another. <del>In the Etherium blockchain transactions can support any kind of logic. They have the expressive <add>In the Ethereum blockchain, transactions can support any kind of logic. They have the expressive <ide> power of a Turing-Complete machine - meaning they can be steps for a task that a computer can do. <ide> <ide> As a piece of code that sits on the blockchain, a smart contract can automate tasks. <ide> This is entirely transparent so all the nodes(miners) can see what logic is bein <ide> ## Blockchain Technologies <ide> <ide> Two of the most common technologies used are : <del>- Etherium <add>- Ethereum <ide> - Hyperledger <ide>
1
Python
Python
add test_connection to azure batch hook
eab0167f1beb81de8e613685da79ef9a04eef5b3
<ide><path>airflow/providers/microsoft/azure/hooks/batch.py <ide> def wait_for_job_tasks_to_complete(self, job_id: str, timeout: int) -> None: <ide> self.log.info("Waiting for %s to complete, currently on %s state", task.id, task.state) <ide> time.sleep(15) <ide> raise TimeoutError("Timed out waiting for tasks to complete") <add> <add> def test_connection(self): <add> """Test a configured Azure Batch connection.""" <add> try: <add> # Attempt to list existing jobs under the configured Batch account and retrieve <add> # the first in the returned iterator. The Azure Batch API does allow for creation of a <add> # BatchServiceClient with incorrect values but then will fail properly once items are <add> # retrieved using the client. We need to _actually_ try to retrieve an object to properly <add> # test the connection. <add> next(self.get_conn().job.list(), None) <add> except Exception as e: <add> return False, str(e) <add> return True, "Successfully connected to Azure Batch." <ide><path>tests/providers/microsoft/azure/hooks/test_azure_batch.py <ide> import json <ide> import unittest <ide> from unittest import mock <add>from unittest.mock import PropertyMock <ide> <ide> from azure.batch import BatchServiceClient, models as batch_models <ide> <ide> def test_add_single_task_to_job(self, mock_batch): <ide> def test_wait_for_all_task_to_complete(self, mock_batch): <ide> # TODO: Add test <ide> pass <add> <add> @mock.patch('airflow.providers.microsoft.azure.hooks.batch.BatchServiceClient') <add> def test_connection_success(self, mock_batch): <add> hook = AzureBatchHook(azure_batch_conn_id=self.test_cloud_conn_id) <add> hook.get_conn().job.return_value = {} <add> status, msg = hook.test_connection() <add> assert status is True <add> assert msg == "Successfully connected to Azure Batch." <add> <add> @mock.patch('airflow.providers.microsoft.azure.hooks.batch.BatchServiceClient') <add> def test_connection_failure(self, mock_batch): <add> hook = AzureBatchHook(azure_batch_conn_id=self.test_cloud_conn_id) <add> hook.get_conn().job.list = PropertyMock(side_effect=Exception("Authentication failed.")) <add> status, msg = hook.test_connection() <add> assert status is False <add> assert msg == "Authentication failed."
2
Text
Text
fix typos, consistent styling w/ english version
e3bdcd68a4553901440b00fd8af480099504a408
<ide><path>guide/spanish/python/string-methods/index.md <ide> --- <ide> title: String Methods <del>localeTitle: Métodos de cuerda <add>localeTitle: Métodos String <ide> --- <del>**TODO: `string` información básica** <add>**TODO: información básica sobre `string`** <ide> <del>[Python Docs - Cuerdas](https://docs.python.org/3/library/stdtypes.html#strings) <add>[Python Docs - Strings](https://docs.python.org/3/library/stdtypes.html#strings) <ide> <ide> **Creación:** <ide> <ide> Una `string` vacía se crea utilizando un par de comillas o apóstrofes: <del> <ide> ```shell <ide> >>> new_string = '' <ide> >>> type(new_string) <ide> Una `string` vacía se crea utilizando un par de comillas o apóstrofes: <ide> 0 <ide> ``` <ide> <del>[Python Docs - Más sobre cuerdas](https://docs.python.org/3/tutorial/datastructures.html#more-on-strings) <add>[Python Docs - Más sobre Strings](https://docs.python.org/3/tutorial/datastructures.html#more-on-strings) <ide> <del>* `string.find('you')` Devuelve la posición más baja en la que se encuentra la subcadena. <add>* `string.find('you')` Devuelve la posición más baja en la que se encuentra la *substring*. <ide> <del>* `str.join(iterable)` Une todos los elementos en un `iterable` con una cadena especificada. <add>* `str.join(iterable)` Une todos los elementos en un `iterable` con una *string* especificada. <ide> <del>* `str.replace(old, new, max)` se usa para reemplazar la subcadena `old` con la cadena `new` por un total de `max` veces. Este método devuelve una nueva copia de la cadena con el reemplazo, y la `str` original no se modifica. <add>* `str.replace(old, new, max)` se usa para reemplazar la *substring* `old` con la *string* `new` por un total de `max` veces. Este método devuelve una nueva copia de la *string* con el reemplazo, y la `str` original no se modifica. <ide> <del>* `string.split(separator, maxsplit)` Devuelve una lista de subcadenas delimitadas por el `separator` , un número de `maxsplit` opcional de veces, y si no se especifica, la cadena se dividirá en todas las instancias del `separator` . <add>* `string.split(separator, maxsplit)` Devuelve una lista de *substrings* delimitadas por el `separator` , un número de `maxsplit` opcional de veces, y si no se especifica, la *string* se dividirá en todas las instancias del `separator`. <ide> <del>* `string.strip(to_strip)` Devuelve una cadena con `to_strip` eliminada tanto del principio como del final de la cadena. Si no se especifica `to_strip` , esto eliminará todos los caracteres de espacio en blanco. <ide>\ No newline at end of file <add>* `string.strip(to_strip)` Devuelve una *string* con `to_strip` eliminado tanto del principio como del final de la *string*. Si no se especifica `to_strip`, esto eliminará todos los caracteres en blanco.
1
Ruby
Ruby
optimize big sur bottles for ivy bridge
095798be405be47429877f9d92f416153f86e147
<ide><path>Library/Homebrew/extend/os/mac/hardware.rb <ide> module Hardware <ide> def self.oldest_cpu(version = MacOS.version) <ide> if CPU.arch == :arm64 <ide> :arm_vortex_tempest <add> elsif version >= :big_sur <add> :ivybridge <ide> elsif version >= :mojave <ide> :nehalem <ide> else <ide><path>Library/Homebrew/hardware.rb <ide> class << self <ide> def optimization_flags <ide> @optimization_flags ||= { <ide> native: arch_flag("native"), <del> nehalem: "-march=nehalem", <add> ivybridge: "-march=ivybridge", <ide> sandybridge: "-march=sandybridge", <add> nehalem: "-march=nehalem", <ide> core2: "-march=core2", <ide> core: "-march=prescott", <ide> arm_vortex_tempest: "",
2
Java
Java
fix trampolinescheduler nullpointerexception
2cf434944540d66ea683bdcb84499eb5f7edd2eb
<ide><path>src/main/java/rx/schedulers/TrampolineScheduler.java <ide> private Subscription enqueue(Action0 action, long execTime) { <ide> <ide> if (wip.getAndIncrement() == 0) { <ide> do { <del> queue.poll().action.call(); <add> TimedAction polled = queue.poll(); <add> // check for null as it could have been unsubscribed and removed <add> if (polled != null) { <add> polled.action.call(); <add> } <ide> } while (wip.decrementAndGet() > 0); <ide> return Subscriptions.empty(); <ide> } else {
1
Javascript
Javascript
add tooltip if any in annotations layer
20b12d2bda2ca270884900f3b1b9ff7d4cf4f3a9
<ide><path>src/core/annotation.js <ide> class ButtonWidgetAnnotation extends WidgetAnnotation { <ide> this.hasFieldFlag(AnnotationFieldFlag.RADIO) && <ide> !this.hasFieldFlag(AnnotationFieldFlag.PUSHBUTTON); <ide> this.data.pushButton = this.hasFieldFlag(AnnotationFieldFlag.PUSHBUTTON); <add> this.data.isTooltipOnly = false; <ide> <ide> if (this.data.checkBox) { <ide> this._processCheckBox(params); <ide> class ButtonWidgetAnnotation extends WidgetAnnotation { <ide> } <ide> <ide> _processPushButton(params) { <del> if (!params.dict.has("A")) { <add> if (!params.dict.has("A") && !this.data.alternativeText) { <ide> warn("Push buttons without action dictionaries are not supported"); <ide> return; <ide> } <ide> <add> this.data.isTooltipOnly = !params.dict.has("A"); <add> <ide> Catalog.parseDestDictionary({ <ide> destDict: params.dict, <ide> resultObj: this.data, <ide><path>src/display/annotation_layer.js <ide> class LinkAnnotationElement extends AnnotationElement { <ide> const isRenderable = !!( <ide> parameters.data.url || <ide> parameters.data.dest || <del> parameters.data.action <add> parameters.data.action || <add> parameters.data.isTooltipOnly <ide> ); <ide> super(parameters, isRenderable); <ide> } <ide> class LinkAnnotationElement extends AnnotationElement { <ide> }); <ide> } else if (data.action) { <ide> this._bindNamedAction(link, data.action); <del> } else { <add> } else if (data.dest) { <ide> this._bindLink(link, data.dest); <add> } else { <add> this._bindLink(link, ""); <ide> } <ide> <ide> this.container.appendChild(link); <ide> class WidgetAnnotationElement extends AnnotationElement { <ide> */ <ide> render() { <ide> // Show only the container for unsupported field types. <add> if (this.data.alternativeText) { <add> this.container.title = this.data.alternativeText; <add> } <add> <ide> return this.container; <ide> } <ide> } <ide> class PushButtonWidgetAnnotationElement extends LinkAnnotationElement { <ide> // as performing actions on form fields (resetting, submitting, et cetera). <ide> const container = super.render(); <ide> container.className = "buttonWidgetAnnotation pushButton"; <add> <add> if (this.data.alternativeText) { <add> container.title = this.data.alternativeText; <add> } <add> <ide> return container; <ide> } <ide> } <ide><path>test/unit/annotation_spec.js <ide> describe("annotation", function () { <ide> }) <ide> .catch(done.fail); <ide> }); <add> <add> it("should handle push buttons", function (done) { <add> const buttonWidgetRef = Ref.get(124, 0); <add> buttonWidgetDict.set("Ff", AnnotationFieldFlag.PUSHBUTTON); <add> buttonWidgetDict.set("A", "whatever"); <add> <add> const xref = new XRefMock([ <add> { ref: buttonWidgetRef, data: buttonWidgetDict }, <add> ]); <add> <add> AnnotationFactory.create( <add> xref, <add> buttonWidgetRef, <add> pdfManagerMock, <add> idFactoryMock <add> ).then(({ data }) => { <add> expect(data.annotationType).toEqual(AnnotationType.WIDGET); <add> expect(data.pushButton).toEqual(true); <add> done(); <add> }, done.fail); <add> }); <add> <add> it("should handle push buttons that act as a tooltip only", function (done) { <add> const buttonWidgetRef = Ref.get(124, 0); <add> buttonWidgetDict.set("Ff", AnnotationFieldFlag.PUSHBUTTON); <add> buttonWidgetDict.set("TU", "An alternative text"); <add> <add> const xref = new XRefMock([ <add> { ref: buttonWidgetRef, data: buttonWidgetDict }, <add> ]); <add> <add> AnnotationFactory.create( <add> xref, <add> buttonWidgetRef, <add> pdfManagerMock, <add> idFactoryMock <add> ).then(({ data }) => { <add> expect(data.annotationType).toEqual(AnnotationType.WIDGET); <add> expect(data.pushButton).toEqual(true); <add> expect(data.alternativeText).toEqual("An alternative text"); <add> done(); <add> }, done.fail); <add> }); <ide> }); <ide> <ide> describe("ChoiceWidgetAnnotation", function () {
3
Javascript
Javascript
pass arg in test
ffeca24412b5586d9b0d4d4e25ef4d05918d5484
<ide><path>test/cases/wasm/imports-multiple/module.js <ide> import { getResult } from "./wasm.wasm"; <ide> <del>export var result = getResult(); <add>export var result = getResult(1); <ide> <ide> export function getNumber() { <ide> return 20;
1
Text
Text
add the w3 org global struct
9a5e3c5e0e7cc248c80d4be9be10fb2aa2cf4063
<ide><path>guide/english/html/page-structure/index.md <ide> Instead of using the generic `<div>` for every other container, use the semantic <ide> <ide> #### More Information: <ide> [HTML: Introduction](https://www.w3schools.com/html/html_intro.asp) <add>[HTML: Introduction](https://www.w3.org/TR/html401/struct/global.html)
1
Text
Text
fix gtag syntax in measuring docs
d4a8d4fc880e94101c260d703570e603ae92beee
<ide><path>docs/advanced-features/measuring-performance.md <ide> export function reportWebVitals(metric) { <ide> > export function reportWebVitals({ id, name, label, value }) { <ide> > // Use `window.gtag` if you initialized Google Analytics as this example: <ide> > // https://github.com/vercel/next.js/blob/canary/examples/with-google-analytics/pages/_document.js <del>> window.gtag('send', 'event', { <del>> eventCategory: <add>> window.gtag('event', name, { <add>> event_category: <ide> > label === 'web-vital' ? 'Web Vitals' : 'Next.js custom metric', <del>> eventAction: name, <del>> eventValue: Math.round(name === 'CLS' ? value * 1000 : value), // values must be integers <del>> eventLabel: id, // id unique to current page load <del>> nonInteraction: true, // avoids affecting bounce rate. <add>> value: Math.round(name === 'CLS' ? value * 1000 : value), // values must be integers <add>> event_label: id, // id unique to current page load <add>> non_interaction: true, // avoids affecting bounce rate. <ide> > }) <ide> > } <ide> > ```
1
Python
Python
add generate kwargs to seq2seqtrainingarguments
c76de1053e76010340a3cf152e51d4d9f5a1f755
<ide><path>examples/pytorch/summarization/run_summarization.py <ide> def compute_metrics(eval_preds): <ide> <ide> # Evaluation <ide> results = {} <add> max_length = ( <add> training_args.generation_max_length <add> if training_args.generation_max_length is not None <add> else data_args.val_max_target_length <add> ) <add> num_beams = data_args.num_beams if data_args.num_beams is not None else training_args.generation_num_beams <ide> if training_args.do_eval: <ide> logger.info("*** Evaluate ***") <del> <del> metrics = trainer.evaluate( <del> max_length=data_args.val_max_target_length, num_beams=data_args.num_beams, metric_key_prefix="eval" <del> ) <add> metrics = trainer.evaluate(max_length=max_length, num_beams=num_beams, metric_key_prefix="eval") <ide> max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset) <ide> metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset)) <ide> <ide> def compute_metrics(eval_preds): <ide> logger.info("*** Predict ***") <ide> <ide> predict_results = trainer.predict( <del> predict_dataset, <del> metric_key_prefix="predict", <del> max_length=data_args.val_max_target_length, <del> num_beams=data_args.num_beams, <add> predict_dataset, metric_key_prefix="predict", max_length=max_length, num_beams=num_beams <ide> ) <ide> metrics = predict_results.metrics <ide> max_predict_samples = ( <ide><path>examples/pytorch/translation/run_translation.py <ide> def compute_metrics(eval_preds): <ide> <ide> # Evaluation <ide> results = {} <add> max_length = ( <add> training_args.generation_max_length <add> if training_args.generation_max_length is not None <add> else data_args.val_max_target_length <add> ) <add> num_beams = data_args.num_beams if data_args.num_beams is not None else training_args.generation_num_beams <ide> if training_args.do_eval: <ide> logger.info("*** Evaluate ***") <ide> <del> metrics = trainer.evaluate( <del> max_length=data_args.val_max_target_length, num_beams=data_args.num_beams, metric_key_prefix="eval" <del> ) <add> metrics = trainer.evaluate(max_length=max_length, num_beams=num_beams, metric_key_prefix="eval") <ide> max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset) <ide> metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset)) <ide> <ide> def compute_metrics(eval_preds): <ide> logger.info("*** Predict ***") <ide> <ide> predict_results = trainer.predict( <del> predict_dataset, <del> metric_key_prefix="predict", <del> max_length=data_args.val_max_target_length, <del> num_beams=data_args.num_beams, <add> predict_dataset, metric_key_prefix="predict", max_length=max_length, num_beams=num_beams <ide> ) <ide> metrics = predict_results.metrics <ide> max_predict_samples = ( <ide><path>src/transformers/trainer_seq2seq.py <ide> def evaluate( <ide> A dictionary containing the evaluation loss and the potential metrics computed from the predictions. The <ide> dictionary also contains the epoch number which comes from the training state. <ide> """ <del> if max_length is not None or not hasattr(self, "_max_length"): <del> self._max_length = max_length <del> if num_beams is not None or not hasattr(self, "_num_beams"): <del> self._num_beams = num_beams <add> self._max_length = max_length if max_length is not None else self.args.generation_max_length <add> self._num_beams = num_beams if num_beams is not None else self.args.generation_num_beams <ide> return super().evaluate(eval_dataset, ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix) <ide> <ide> def predict( <ide> def predict( <ide> - metrics (:obj:`Dict[str, float]`, `optional`): The potential dictionary of metrics (if the dataset <ide> contained labels). <ide> """ <del> if max_length is not None or not hasattr(self, "_max_length"): <del> self._max_length = max_length <del> if num_beams is not None or not hasattr(self, "_num_beams"): <del> self._num_beams = num_beams <add> self._max_length = max_length if max_length is not None else self.args.generation_max_length <add> self._num_beams = num_beams if num_beams is not None else self.args.generation_num_beams <ide> return super().predict(test_dataset, ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix) <ide> <ide> def prediction_step( <ide><path>src/transformers/training_args_seq2seq.py <ide> <ide> import logging <ide> from dataclasses import dataclass, field <add>from typing import Optional <ide> <ide> from .file_utils import add_start_docstrings <ide> from .training_args import TrainingArguments <ide> class Seq2SeqTrainingArguments(TrainingArguments): <ide> the training set. <ide> predict_with_generate (:obj:`bool`, `optional`, defaults to :obj:`False`): <ide> Whether to use generate to calculate generative metrics (ROUGE, BLEU). <add> generation_max_length (:obj:`int`, `optional`): <add> The :obj:`max_length` to use on each evaluation loop when :obj:`predict_with_generate=True`. Will default to <add> the :obj:`max_length` value of the model configuration. <add> generation_num_beams (:obj:`int`, `optional`): <add> The :obj:`num_beams` to use on each evaluation loop when :obj:`predict_with_generate=True`. Will default to the <add> :obj:`num_beams` value of the model configuration. <ide> """ <ide> <ide> sortish_sampler: bool = field(default=False, metadata={"help": "Whether to use SortishSampler or not."}) <ide> predict_with_generate: bool = field( <ide> default=False, metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} <ide> ) <add> generation_max_length: Optional[int] = field( <add> default=None, <add> metadata={ <add> "help": "The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default " <add> "to the `max_length` value of the model configuration." <add> }, <add> ) <add> generation_num_beams: Optional[int] = field( <add> default=None, <add> metadata={ <add> "help": "The `num_beams` to use on each evaluation loop when `predict_with_generate=True`. Will default " <add> "to the `num_beams` value of the model configuration." <add> }, <add> )
4
Text
Text
add @daviwil focus for the week
7a232a23e3e09b70bccb9d80b40cddf1722dee1f
<ide><path>docs/focus/2018-04-09.md <ide> <ide> ## Focus for week ahead <ide> <add>- Atom <add> - Add UI for managing .atomproject.json files <add> - Continue work on project root configuration files <ide> - GitHub Package <ide> - Get "Create pull request" [atom/github#1376](https://github.com/atom/github/pull/1376) merged. @smashwilson <ide> - Get "Add dialog for new co-author" [atom/github#1374](https://github.com/atom/github/pull/1374) merged. @annthurium / @kuychaco
1
Java
Java
fix reactinstancemanager unmountapplication
4a9b2a73021fb547febe1fa193c3effb7ff8da4e
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java <ide> public void runGuarded() { <ide> public void unmountReactApplication() { <ide> if (mReactInstanceManager != null && mIsAttachedToInstance) { <ide> mReactInstanceManager.detachRootView(this); <add> mReactInstanceManager = null; <ide> mIsAttachedToInstance = false; <ide> } <ide> mShouldLogContentAppeared = false; <ide><path>ReactAndroid/src/test/java/com/facebook/react/RootViewTest.java <ide> public void testTouchEmitter() { <ide> MotionEvent.obtain(50, new Date().getTime(), MotionEvent.ACTION_HOVER_MOVE, 0, 0, 0)); <ide> verifyNoMoreInteractions(eventDispatcher); <ide> } <add> <add> @Test <add> public void testRemountApplication() { <add> ReactInstanceManager instanceManager = mock(ReactInstanceManager.class); <add> <add> ReactRootView rootView = new ReactRootView(mReactContext); <add> <add> rootView.startReactApplication(instanceManager, ""); <add> rootView.unmountReactApplication(); <add> rootView.startReactApplication(instanceManager, ""); <add> } <ide> }
2
PHP
PHP
add hints for app facade methods
4d2ca2029a4fc02b0376bff786052f5be7d10c21
<ide><path>src/Illuminate/Support/Facades/App.php <ide> /** <ide> * @method static string version() <ide> * @method static string basePath() <del> * @method static string environment() <add> * @method static string bootstrapPath(string $path = '') <add> * @method static string configPath(string $path = '') <add> * @method static string databasePath(string $path = '') <add> * @method static string environmentPath() <add> * @method static string resourcePath(string $path = '') <add> * @method static string storagePath(string $path = '') <add> * @method static string|bool environment(string|array ...$environments) <add> * @method static bool runningInConsole() <add> * @method static bool runningUnitTests() <ide> * @method static bool isDownForMaintenance() <ide> * @method static void registerConfiguredProviders() <del> * @method static \Illuminate\Support\ServiceProvider register(\Illuminate\Support\ServiceProvider|string $provider, array $options = [], bool $force = false) <add> * @method static \Illuminate\Support\ServiceProvider register(\Illuminate\Support\ServiceProvider|string $provider, bool $force = false) <ide> * @method static void registerDeferredProvider(string $provider, string $service = null) <add> * @method static \Illuminate\Support\ServiceProvider resolveProvider(string $provider) <ide> * @method static void boot() <del> * @method static void booting(mixed $callback) <del> * @method static void booted(mixed $callback) <add> * @method static void booting(callable $callback) <add> * @method static void booted(callable $callback) <add> * @method static void bootstrapWith(array $bootstrappers) <add> * @method static bool configurationIsCached() <add> * @method static string detectEnvironment(callable $callback) <add> * @method static string environmentFile() <add> * @method static string environmentFilePath() <add> * @method static string getCachedConfigPath() <ide> * @method static string getCachedServicesPath() <add> * @method static string getCachedPackagesPath() <add> * @method static string getCachedRoutesPath() <add> * @method static string getLocale() <add> * @method static string getNamespace() <add> * @method static array getProviders(\Illuminate\Support\ServiceProvider|string $provider) <add> * @method static bool hasBeenBootstrapped() <add> * @method static void loadDeferredProviders() <add> * @method static \Illuminate\Contracts\Foundation\Application loadEnvironmentFrom(string $file) <add> * @method static bool routesAreCached() <add> * @method static void setLocale(string $locale) <add> * @method static bool shouldSkipMiddleware() <add> * @method static void terminate() <ide> * <ide> * @see \Illuminate\Contracts\Foundation\Application <ide> */
1
PHP
PHP
add warnings for moved classes
37bbe08abb3a025350794c29c04377a1401687a9
<ide><path>src/Cache/Engine/ApcEngine.php <ide> <ide> // @deprecated Add backwards compat alias. <ide> class_alias('Cake\Cache\Engine\ApcuEngine', 'Cake\Cache\Engine\ApcEngine'); <add> <add>deprecationWarning('Use Cake\Cache\Engine\ApcuEngine instead of Cake\Cache\Engine\ApcEngine.'); <ide><path>src/Database/Schema/Table.php <ide> <?php <ide> // @deprecated Load new class and alias <ide> class_exists('Cake\Database\Schema\TableSchema'); <add>deprecationWarning('Use Cake\Database\Schema\TableSchema instead of Cake\Database\Schema\Table.'); <ide><path>src/Network/Email/AbstractTransport.php <ide> <?php <ide> // @deprecated Backward compatibility with 2.x, 3.0.x <ide> class_alias('Cake\Mailer\AbstractTransport', 'Cake\Network\Email\AbstractTransport'); <add>deprecationWarning('Use Cake\Mailer\AbstractTransport instead of Cake\Network\Email\AbstractTransport.'); <ide><path>src/Network/Email/DebugTransport.php <ide> <?php <ide> // @deprecated Backward compatibility with 2.x, 3.0.x <ide> class_alias('Cake\Mailer\Transport\DebugTransport', 'Cake\Network\Email\DebugTransport'); <add>deprecationWarning('Use Cake\Mailer\Transport\DebugTransport instead of Cake\Network\Email\DebugTransport.'); <ide><path>src/Network/Email/Email.php <ide> <?php <ide> // @deprecated Backward compatibility with 2.x, 3.0.x <ide> class_alias('Cake\Mailer\Email', 'Cake\Network\Email\Email'); <add>deprecationWarning('Use Cake\Mailer\Email instead of Cake\Network\Email\Email.'); <ide><path>src/Network/Email/MailTransport.php <ide> <?php <ide> // @deprecated Backward compatibility with 2.x, 3.0.x <ide> class_alias('Cake\Mailer\Transport\MailTransport', 'Cake\Network\Email\MailTransport'); <add>deprecationWarning('Use Cake\Mailer\Transport\MailTransport instead of Cake\Network\Email\MailTransport.'); <ide><path>src/Network/Email/SmtpTransport.php <ide> <?php <ide> // @deprecated Backward compatibility with 2.x, 3.0.x <ide> class_alias('Cake\Mailer\Transport\SmtpTransport', 'Cake\Network\Email\SmtpTransport'); <add>deprecationWarning('Use Cake\Mailer\Transport\SmtpTransport instead of Cake\Network\Email\SmtpTransport.'); <ide><path>src/Network/Http/Adapter/Stream.php <ide> <?php <ide> // @deprecated Load new class and alias. <ide> class_exists('Cake\Http\Client\Adapter\Stream'); <add>deprecationWarning('Use Cake\Http\Client\Adapter\Stream instead of Cake\Network\Http\Adapter\Stream.'); <ide><path>src/Network/Http/Auth/Basic.php <ide> <?php <ide> // @deprecated Load new class and alias. <ide> class_exists('Cake\Http\Client\Auth\Basic'); <add>deprecationWarning('Use Cake\Http\Client\Auth\Basic instead of Cake\Network\Http\Auth\Basic.'); <ide><path>src/Network/Http/Auth/Digest.php <ide> <?php <ide> // @deprecated Load new class and alias. <ide> class_exists('Cake\Http\Client\Auth\Digest'); <add>deprecationWarning('Use Cake\Http\Client\Auth\Digest instead of Cake\Network\Http\Auth\Digest.'); <ide><path>src/Network/Http/Auth/Oauth.php <ide> <?php <ide> // @deprecated Load new class and alias. <ide> class_exists('Cake\Http\Client\Auth\Oauth'); <add>deprecationWarning('Use Cake\Http\Client\Auth\Oauth instead of Cake\Network\Http\Auth\Oauth.'); <ide><path>src/Network/Http/Client.php <ide> <?php <ide> // @deprecated Load new class and alias. <ide> class_exists('Cake\Http\Client'); <add>deprecationWarning('Use Cake\Http\Client instead of Cake\Network\Http\Client.'); <ide><path>src/Network/Http/CookieCollection.php <ide> <?php <ide> // @deprecated Load new class and alias. <ide> class_exists('Cake\Http\Client\CookieCollection'); <add>deprecationWarning('Use Cake\Http\Client\CookieCollection instead of Cake\Network\Http\CookieCollection.'); <ide><path>src/Network/Http/FormData.php <ide> <?php <ide> // @deprecated Load new class and alias. <ide> class_exists('Cake\Http\Client\FormData'); <add>deprecationWarning('Use Cake\Http\Client\FormData instead of Cake\Network\Http\FormData.'); <ide><path>src/Network/Http/FormData/Part.php <ide> <?php <ide> // @deprecated Load new class and alias. <ide> class_exists('Cake\Http\Client\FormDataPart'); <add>deprecationWarning('Use Cake\Http\Client\FormDataPart instead of Cake\Network\Http\FormData\Part.'); <ide><path>src/Network/Http/Message.php <ide> <?php <ide> // @deprecated Load new class and alias. <ide> class_exists('Cake\Http\Client\Message'); <add>deprecationWarning('Use Cake\Http\Client\Message instead of Cake\Network\Http\Message.'); <ide><path>src/Network/Http/Request.php <ide> <?php <ide> // @deprecated Load new class and alias. <ide> class_exists('Cake\Http\Client\Request'); <add>deprecationWarning('Use Cake\Http\Client\Request instead of Cake\Network\Http\Request.'); <ide><path>src/Network/Http/Response.php <ide> <?php <ide> // @deprecated Load new class and alias. <ide> class_exists('Cake\Http\Client\Response'); <add>deprecationWarning('Use Cake\Http\Client\Response instead of Cake\Network\Http\Response.'); <ide><path>src/Network/Request.php <ide> <?php <ide> // @deprecated Load new class and alias <ide> class_exists('Cake\Http\ServerRequest'); <add>deprecationWarning('Use Cake\Http\ServerRequest instead of Cake\Network\Request.'); <ide><path>src/Network/Response.php <ide> <?php <ide> // @deprecated Load new class and alias <ide> class_exists('Cake\Http\Response'); <add>deprecationWarning('Use Cake\Http\Response instead of Cake\Network\Response.'); <ide><path>src/Utility/String.php <ide> // @deprecated Backward compatibility with 2.x series <ide> if (PHP_VERSION_ID < 70000) { <ide> class_alias('Cake\Utility\Text', 'Cake\Utility\String'); <add> deprecationWarning('Use Cake\Utility\Text instead of Cake\Utility\String.'); <ide> } <ide><path>tests/TestCase/Network/MoveToHttpTest.php <del><?php <del>/** <del> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <del> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * For full copyright and license information, please see the LICENSE.txt <del> * Redistributions of files must retain the above copyright notice. <del> * <del> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <del> * @link https://cakephp.org CakePHP(tm) Project <del> * @since 3.4.3 <del> * @license https://opensource.org/licenses/mit-license.php MIT License <del> */ <del>namespace Cake\Test\TestCase\Network; <del> <del>use Cake\Http\Response as HttpResponse; <del>use Cake\Http\ServerRequest as HttpRequest; <del>use Cake\Network\Request as NetworkRequest; <del>use Cake\Network\Response as NetworkResponse; <del>use Cake\TestSuite\TestCase; <del> <del>/** <del> * ensure that backwards compatibility was ensured for old Cake\Network\* classes <del> */ <del>class MoveToHttpTest extends TestCase <del>{ <del> /** <del> * Tests the Cake\Http\Response loaded from Cake\Network\Response correctly <del> * <del> * @return void <del> */ <del> public function testResponse() <del> { <del> $response = new NetworkResponse(); <del> $this->assertInstanceOf('Cake\Http\Response', $response); <del> $this->assertInstanceOf('Cake\Network\Response', $response); <del> <del> $response = new HttpResponse(); <del> $this->assertInstanceOf('Cake\Http\Response', $response); <del> $this->assertInstanceOf('Cake\Network\Response', $response); <del> } <del> <del> /** <del> * Tests the Cake\Http\ServerRequest loaded from Cake\Network\Request correctly <del> * <del> * @return void <del> */ <del> public function testRequest() <del> { <del> $request = new NetworkRequest(); <del> $this->assertInstanceOf('Cake\Http\ServerRequest', $request); <del> $this->assertInstanceOf('Cake\Network\Request', $request); <del> <del> $request = new HttpRequest(); <del> $this->assertInstanceOf('Cake\Http\ServerRequest', $request); <del> $this->assertInstanceOf('Cake\Network\Request', $request); <del> } <del>}
22
Mixed
Ruby
add sockets and keepalive variants
3d5d12e8b9fad28d2923ade47ac970dfd7144843
<ide><path>Library/Homebrew/service.rb <ide> class Service <ide> PROCESS_TYPE_INTERACTIVE = :interactive <ide> PROCESS_TYPE_ADAPTIVE = :adaptive <ide> <add> KEEP_ALIVE_KEYS = [:always, :successful_exit, :crashed, :path].freeze <add> <ide> # sig { params(formula: Formula).void } <ide> def initialize(formula, &block) <ide> @formula = formula <ide> def error_log_path(path = nil) <ide> end <ide> end <ide> <del> sig { params(value: T.nilable(T::Boolean)).returns(T.nilable(T::Boolean)) } <add> sig { <add> params(value: T.nilable(T.any(T::Boolean, T::Hash[Symbol, T.untyped]))) <add> .returns(T.nilable(T::Hash[Symbol, T.untyped])) <add> } <ide> def keep_alive(value = nil) <ide> case T.unsafe(value) <ide> when nil <ide> @keep_alive <ide> when true, false <add> @keep_alive = { always: value } <add> when Hash <add> hash = T.cast(value, Hash) <add> unless (hash.keys - KEEP_ALIVE_KEYS).empty? <add> raise TypeError, "Service#keep_alive allows only #{KEEP_ALIVE_KEYS}" <add> end <add> <ide> @keep_alive = value <ide> else <del> raise TypeError, "Service#keep_alive expects a Boolean" <add> raise TypeError, "Service#keep_alive expects a Boolean or Hash" <add> end <add> end <add> <add> sig { params(value: T.nilable(String)).returns(T.nilable(T::Hash[Symbol, String])) } <add> def sockets(value = nil) <add> case T.unsafe(value) <add> when nil <add> @sockets <add> when String <add> match = T.must(value).match(%r{([a-z]+)://([a-z0-9.]+):([0-9]+)}i) <add> raise TypeError, "Service#sockets a formatted socket definition as <type>://<host>:<port>" if match.blank? <add> <add> type, host, port = match.captures <add> @sockets = { host: host, port: port, type: type } <add> else <add> raise TypeError, "Service#sockets expects a String" <ide> end <ide> end <ide> <ide> def keep_alive(value = nil) <ide> sig { returns(T::Boolean) } <ide> def keep_alive? <ide> instance_eval(&@service_block) <del> @keep_alive == true <add> @keep_alive.present? && @keep_alive[:always] != false <ide> end <ide> <ide> sig { params(value: T.nilable(T::Boolean)).returns(T.nilable(T::Boolean)) } <ide> def to_plist <ide> RunAtLoad: @run_type == RUN_TYPE_IMMEDIATE, <ide> } <ide> <del> base[:KeepAlive] = @keep_alive if @keep_alive == true <ide> base[:LaunchOnlyOnce] = @launch_only_once if @launch_only_once == true <ide> base[:LegacyTimers] = @macos_legacy_timers if @macos_legacy_timers == true <ide> base[:TimeOut] = @restart_delay if @restart_delay.present? <ide> def to_plist <ide> base[:StandardErrorPath] = @error_log_path if @error_log_path.present? <ide> base[:EnvironmentVariables] = @environment_variables unless @environment_variables.empty? <ide> <add> if keep_alive? <add> if (always = @keep_alive[:always].presence) <add> base[:KeepAlive] = always <add> elsif @keep_alive.key?(:successful_exit) <add> base[:KeepAlive] = { SuccessfulExit: @keep_alive[:successful_exit] } <add> elsif @keep_alive.key?(:crashed) <add> base[:KeepAlive] = { Crashed: @keep_alive[:crashed] } <add> elsif @keep_alive.key?(:path) && @keep_alive[:path].present? <add> base[:KeepAlive] = { PathState: @keep_alive[:path].to_s } <add> end <add> end <add> <add> if @sockets.present? <add> base[:Sockets] = {} <add> base[:Sockets][:Listeners] = { <add> SockNodeName: @sockets[:host], <add> SockServiceName: @sockets[:port], <add> SockProtocol: @sockets[:type].upcase, <add> SockFamily: "IPv4v6", <add> } <add> end <add> <ide> if @cron.present? && @run_type == RUN_TYPE_CRON <ide> base[:StartCalendarInterval] = @cron.reject { |_, value| value == "*" } <ide> end <ide> def to_systemd_unit <ide> options = [] <ide> options << "Type=#{@launch_only_once == true ? "oneshot" : "simple"}" <ide> options << "ExecStart=#{cmd}" <del> options << "Restart=always" if @keep_alive == true <add> <add> options << "Restart=always" if @keep_alive.present? && @keep_alive[:always].present? <ide> options << "RestartSec=#{restart_delay}" if @restart_delay.present? <ide> options << "WorkingDirectory=#{@working_dir}" if @working_dir.present? <ide> options << "RootDirectory=#{@root_dir}" if @root_dir.present? <ide><path>Library/Homebrew/test/service_spec.rb <ide> end <ide> end <ide> <add> describe "#keep_alive" do <add> it "throws for unexpected keys" do <add> f.class.service do <add> run opt_bin/"beanstalkd" <add> keep_alive test: "key" <add> end <add> <add> expect { <add> f.service.manual_command <add> }.to raise_error TypeError, "Service#keep_alive allows only [:always, :successful_exit, :crashed, :path]" <add> end <add> end <add> <ide> describe "#run_type" do <ide> it "throws for unexpected type" do <ide> f.class.service do <ide> end <ide> end <ide> <add> describe "#sockets" do <add> it "throws for missing type" do <add> f.class.service do <add> run opt_bin/"beanstalkd" <add> sockets "127.0.0.1:80" <add> end <add> <add> expect { <add> f.service.manual_command <add> }.to raise_error TypeError, "Service#sockets a formatted socket definition as <type>://<host>:<port>" <add> end <add> <add> it "throws for missing host" do <add> f.class.service do <add> run opt_bin/"beanstalkd" <add> sockets "tcp://:80" <add> end <add> <add> expect { <add> f.service.manual_command <add> }.to raise_error TypeError, "Service#sockets a formatted socket definition as <type>://<host>:<port>" <add> end <add> <add> it "throws for missing port" do <add> f.class.service do <add> run opt_bin/"beanstalkd" <add> sockets "tcp://127.0.0.1" <add> end <add> <add> expect { <add> f.service.manual_command <add> }.to raise_error TypeError, "Service#sockets a formatted socket definition as <type>://<host>:<port>" <add> end <add> end <add> <ide> describe "#manual_command" do <ide> it "returns valid manual_command" do <ide> f.class.service do <ide> expect(plist).to eq(plist_expect) <ide> end <ide> <add> it "returns valid plist with socket" do <add> f.class.service do <add> run [opt_bin/"beanstalkd", "test"] <add> sockets "tcp://127.0.0.1:80" <add> end <add> <add> plist = f.service.to_plist <add> plist_expect = <<~EOS <add> <?xml version="1.0" encoding="UTF-8"?> <add> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <add> <plist version="1.0"> <add> <dict> <add> \t<key>Label</key> <add> \t<string>homebrew.mxcl.formula_name</string> <add> \t<key>ProgramArguments</key> <add> \t<array> <add> \t\t<string>#{HOMEBREW_PREFIX}/opt/formula_name/bin/beanstalkd</string> <add> \t\t<string>test</string> <add> \t</array> <add> \t<key>RunAtLoad</key> <add> \t<true/> <add> \t<key>Sockets</key> <add> \t<dict> <add> \t\t<key>Listeners</key> <add> \t\t<dict> <add> \t\t\t<key>SockFamily</key> <add> \t\t\t<string>IPv4v6</string> <add> \t\t\t<key>SockNodeName</key> <add> \t\t\t<string>127.0.0.1</string> <add> \t\t\t<key>SockProtocol</key> <add> \t\t\t<string>TCP</string> <add> \t\t\t<key>SockServiceName</key> <add> \t\t\t<string>80</string> <add> \t\t</dict> <add> \t</dict> <add> </dict> <add> </plist> <add> EOS <add> expect(plist).to eq(plist_expect) <add> end <add> <ide> it "returns valid partial plist" do <ide> f.class.service do <ide> run opt_bin/"beanstalkd" <ide> EOS <ide> expect(plist).to eq(plist_expect) <ide> end <add> <add> it "returns valid keepalive-exit plist" do <add> f.class.service do <add> run opt_bin/"beanstalkd" <add> keep_alive successful_exit: false <add> end <add> <add> plist = f.service.to_plist <add> plist_expect = <<~EOS <add> <?xml version="1.0" encoding="UTF-8"?> <add> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <add> <plist version="1.0"> <add> <dict> <add> \t<key>KeepAlive</key> <add> \t<dict> <add> \t\t<key>SuccessfulExit</key> <add> \t\t<false/> <add> \t</dict> <add> \t<key>Label</key> <add> \t<string>homebrew.mxcl.formula_name</string> <add> \t<key>ProgramArguments</key> <add> \t<array> <add> \t\t<string>#{HOMEBREW_PREFIX}/opt/formula_name/bin/beanstalkd</string> <add> \t</array> <add> \t<key>RunAtLoad</key> <add> \t<true/> <add> </dict> <add> </plist> <add> EOS <add> expect(plist).to eq(plist_expect) <add> end <add> <add> it "returns valid keepalive-crashed plist" do <add> f.class.service do <add> run opt_bin/"beanstalkd" <add> keep_alive crashed: true <add> end <add> <add> plist = f.service.to_plist <add> plist_expect = <<~EOS <add> <?xml version="1.0" encoding="UTF-8"?> <add> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <add> <plist version="1.0"> <add> <dict> <add> \t<key>KeepAlive</key> <add> \t<dict> <add> \t\t<key>Crashed</key> <add> \t\t<true/> <add> \t</dict> <add> \t<key>Label</key> <add> \t<string>homebrew.mxcl.formula_name</string> <add> \t<key>ProgramArguments</key> <add> \t<array> <add> \t\t<string>#{HOMEBREW_PREFIX}/opt/formula_name/bin/beanstalkd</string> <add> \t</array> <add> \t<key>RunAtLoad</key> <add> \t<true/> <add> </dict> <add> </plist> <add> EOS <add> expect(plist).to eq(plist_expect) <add> end <add> <add> it "returns valid keepalive-path plist" do <add> f.class.service do <add> run opt_bin/"beanstalkd" <add> keep_alive path: opt_pkgshare/"test-path" <add> end <add> <add> plist = f.service.to_plist <add> plist_expect = <<~EOS <add> <?xml version="1.0" encoding="UTF-8"?> <add> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <add> <plist version="1.0"> <add> <dict> <add> \t<key>KeepAlive</key> <add> \t<dict> <add> \t\t<key>PathState</key> <add> \t\t<string>#{HOMEBREW_PREFIX}/opt/formula_name/share/formula_name/test-path</string> <add> \t</dict> <add> \t<key>Label</key> <add> \t<string>homebrew.mxcl.formula_name</string> <add> \t<key>ProgramArguments</key> <add> \t<array> <add> \t\t<string>#{HOMEBREW_PREFIX}/opt/formula_name/bin/beanstalkd</string> <add> \t</array> <add> \t<key>RunAtLoad</key> <add> \t<true/> <add> </dict> <add> </plist> <add> EOS <add> expect(plist).to eq(plist_expect) <add> end <ide> end <ide> <ide> describe "#to_systemd_unit" do <ide> end <ide> <ide> describe "#keep_alive?" do <add> it "returns true when keep_alive set to hash" do <add> f.class.service do <add> run [opt_bin/"beanstalkd", "test"] <add> keep_alive crashed: true <add> end <add> <add> expect(f.service.keep_alive?).to be(true) <add> end <add> <ide> it "returns true when keep_alive set to true" do <ide> f.class.service do <ide> run [opt_bin/"beanstalkd", "test"] <ide><path>docs/Formula-Cookbook.md <ide> The only required field in a `service` block is the `run` field to indicate what <ide> | `restart_delay` | - | yes | yes | The delay before restarting a process | <ide> | `process_type` | - | yes | no-op | The type of process to manage, `:background`, `:standard`, `:interactive` or `:adaptive` | <ide> | `macos_legacy_timers` | - | yes | no-op | Timers created by launchd jobs are coalesced unless this is set | <add>| `sockets` | - | yes | no-op | A socket that is created as an accesspoint to the service | <ide> <ide> For services that start and keep running alive you can use the default `run_type :` like so: <ide> ```ruby <ide> This method will set the path to `#{HOMEBREW_PREFIX}/bin:#{HOMEBREW_PREFIX}/sbin <ide> end <ide> ``` <ide> <add>#### KeepAlive options <add>The standard options, keep alive regardless of any status or circomstances <add>```rb <add> service do <add> run [opt_bin/"beanstalkd", "test"] <add> keep_alive true # or false <add> end <add>``` <add> <add>Same as above in hash form <add>```rb <add> service do <add> run [opt_bin/"beanstalkd", "test"] <add> keep_alive { always: true } <add> end <add>``` <add> <add>Keep alive until the job exits with a non-zero return code <add>```rb <add> service do <add> run [opt_bin/"beanstalkd", "test"] <add> keep_alive { succesful_exit: true } <add> end <add>``` <add> <add>Keep alive only if the job crashed <add>```rb <add> service do <add> run [opt_bin/"beanstalkd", "test"] <add> keep_alive { crashed: true } <add> end <add>``` <add> <add>Keep alive as long as a file exists <add>```rb <add> service do <add> run [opt_bin/"beanstalkd", "test"] <add> keep_alive { path: "/some/path" } <add> end <add>``` <add> <add>#### Socket format <add>The sockets method accepts a formatted socket definition as `<type>://<host>:<port>`. <add>- `type`: `udp` or `tcp` <add>- `host`: The host to run the socket on. For example `0.0.0.0` <add>- `port`: The port the socket should listen on. <add> <add>Please note that sockets will be accessible on IPv4 and IPv6 addresses by default. <add> <ide> ### Using environment variables <ide> <ide> Homebrew has multiple levels of environment variable filtering which affects variables available to formulae.
3
PHP
PHP
remove unneeded method
636032616fd8a6af13f9186b6535dea96d244575
<ide><path>src/Illuminate/View/Engines/Engine.php <ide> abstract class Engine { <ide> */ <ide> protected $lastRendered; <ide> <del> /** <del> * Determine if the engine is sectionable. <del> * <del> * @return bool <del> */ <del> public function isSectionable() <del> { <del> return $this instanceof SectionableInterface; <del> } <del> <ide> /** <ide> * Get the last view that was rendered. <ide> *
1
Ruby
Ruby
revert streaming params parser support
5ebfa6242726bd186452640ed5704f2adc1a5007
<ide><path>actionpack/lib/action_dispatch/middleware/params_parser.rb <ide> def parse_formatted_parameters(env) <ide> when Proc <ide> strategy.call(request.raw_post) <ide> when :xml_simple, :xml_node <del> request.body.size == 0 ? {} : Hash.from_xml(request.body).with_indifferent_access <add> request.body.size == 0 ? {} : Hash.from_xml(request.raw_post).with_indifferent_access <ide> when :yaml <del> YAML.load(request.body) <add> YAML.load(request.raw_post) <ide> when :json <ide> if request.body.size == 0 <ide> {} <ide> else <del> data = ActiveSupport::JSON.decode(request.body) <add> data = ActiveSupport::JSON.decode(request.raw_post) <ide> data = {:_json => data} unless data.is_a?(Hash) <ide> data.with_indifferent_access <ide> end
1
Javascript
Javascript
replace deprecated substr() with slice()
eef2f9728145aa27b8cd92f5fac7328a9e0e574d
<ide><path>lib/adapters/http.js <ide> module.exports = function httpAdapter(config) { <ide> return true; <ide> } <ide> if (proxyElement[0] === '.' && <del> parsed.hostname.substr(parsed.hostname.length - proxyElement.length) === proxyElement) { <add> parsed.hostname.slice(parsed.hostname.length - proxyElement.length) === proxyElement) { <ide> return true; <ide> } <ide> <ide><path>lib/helpers/parseHeaders.js <ide> module.exports = function parseHeaders(headers) { <ide> <ide> utils.forEach(headers.split('\n'), function parser(line) { <ide> i = line.indexOf(':'); <del> key = utils.trim(line.substr(0, i)).toLowerCase(); <del> val = utils.trim(line.substr(i + 1)); <add> key = utils.trim(line.slice(0, i)).toLowerCase(); <add> val = utils.trim(line.slice(i + 1)); <ide> <ide> if (key) { <ide> if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
2
Javascript
Javascript
fix missing scope in mmdloader
a9720c710acbdb245afff7eda29d892b7c623876
<ide><path>examples/js/loaders/MMDLoader.js <ide> THREE.MMDLoader.prototype.createMesh = function ( model, texturePath, onProgress <ide> var initMaterials = function () { <ide> <ide> var textures = []; <del> var textureLoader = new THREE.TextureLoader( this.manager ); <del> var tgaLoader = new THREE.TGALoader( this.manager ); <add> var textureLoader = new THREE.TextureLoader( scope.manager ); <add> var tgaLoader = new THREE.TGALoader( scope.manager ); <ide> var offset = 0; <ide> var materialParams = []; <ide>
1
Ruby
Ruby
assert valid keys
f52253cbebf0124bb74925e91bcca75325eaa502
<ide><path>activerecord/lib/active_record/relation.rb <ide> class Relation <ide> SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :from, :reordering, <ide> :reverse_order, :uniq, :create_with] <ide> <add> VALUE_METHODS = MULTI_VALUE_METHODS + SINGLE_VALUE_METHODS <add> <ide> include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches, Explain, Delegation <ide> <ide> attr_reader :table, :klass, :loaded <ide><path>activerecord/lib/active_record/relation/merger.rb <add>require 'active_support/core_ext/object/blank' <add>require 'active_support/core_ext/hash/keys' <add> <ide> module ActiveRecord <ide> class Relation <ide> class Merger <ide> class HashMerger <ide> attr_reader :relation, :values <ide> <ide> def initialize(relation, values) <add> values.assert_valid_keys(*Relation::VALUE_METHODS) <add> <ide> @relation = relation <ide> @values = values <ide> end <ide><path>activerecord/test/cases/relation_test.rb <ide> def test_apply_finder_options_takes_references <ide> test 'merging an empty hash into a relation' do <ide> assert_equal [], Relation.new(:a, :b).merge({}).where_values <ide> end <add> <add> test 'merging a hash with unknown keys raises' do <add> assert_raises(ArgumentError) { Relation::HashMerger.new(nil, omg: 'lol') } <add> end <ide> end <ide> <ide> class RelationMutationTest < ActiveSupport::TestCase
3
Go
Go
add imagelistoptions and pass context
bf9c76f0a8ff296c71d32bb46c1ea03f8ec1dd14
<ide><path>api/server/router/image/backend.go <ide> type Backend interface { <ide> type imageBackend interface { <ide> ImageDelete(imageRef string, force, prune bool) ([]types.ImageDeleteResponseItem, error) <ide> ImageHistory(imageName string) ([]*image.HistoryResponseItem, error) <del> Images(imageFilters filters.Args, all bool, withExtraAttrs bool) ([]*types.ImageSummary, error) <add> Images(ctx context.Context, opts types.ImageListOptions) ([]*types.ImageSummary, error) <ide> LookupImage(name string) (*types.ImageInspect, error) <ide> TagImage(imageName, repository, tag string) (string, error) <ide> ImagesPrune(ctx context.Context, pruneFilters filters.Args) (*types.ImagesPruneReport, error) <ide><path>api/server/router/image/image_routes.go <ide> func (s *imageRouter) getImagesJSON(ctx context.Context, w http.ResponseWriter, <ide> <ide> version := httputils.VersionFromContext(ctx) <ide> if versions.LessThan(version, "1.41") { <add> // NOTE: filter is a shell glob string applied to repository names. <ide> filterParam := r.Form.Get("filter") <ide> if filterParam != "" { <ide> imageFilters.Add("reference", filterParam) <ide> } <ide> } <ide> <del> images, err := s.backend.Images(imageFilters, httputils.BoolValue(r, "all"), false) <add> images, err := s.backend.Images(ctx, types.ImageListOptions{ <add> Filters: imageFilters, <add> All: httputils.BoolValue(r, "all"), <add> }) <ide> if err != nil { <ide> return err <ide> } <ide><path>api/types/client.go <ide> type ImageImportOptions struct { <ide> Platform string // Platform is the target platform of the image <ide> } <ide> <del>// ImageListOptions holds parameters to filter the list of images with. <add>// ImageListOptions holds parameters to list images with. <ide> type ImageListOptions struct { <del> All bool <add> // All controls whether all images in the graph are filtered, or just <add> // the heads. <add> All bool <add> <add> // Filters is a JSON-encoded set of filter arguments. <ide> Filters filters.Args <add> <add> // SharedSize indicates whether the shared size of images should be computed. <add> SharedSize bool <add> <add> // ContainerCount indicates whether container count should be computed. <add> ContainerCount bool <ide> } <ide> <ide> // ImageLoadResponse returns information to the client about a load process. <ide><path>daemon/disk_usage.go <ide> func (daemon *Daemon) SystemDiskUsage(ctx context.Context) (*types.DiskUsage, er <ide> } <ide> <ide> // Get all top images with extra attributes <del> allImages, err := daemon.imageService.Images(filters.NewArgs(), false, true) <add> allImages, err := daemon.imageService.Images(ctx, types.ImageListOptions{ <add> Filters: filters.NewArgs(), <add> SharedSize: true, <add> ContainerCount: true, <add> }) <ide> if err != nil { <ide> return nil, fmt.Errorf("failed to retrieve image list: %v", err) <ide> } <ide><path>daemon/images/images.go <ide> package images // import "github.com/docker/docker/daemon/images" <ide> <ide> import ( <add> "context" <ide> "encoding/json" <ide> "fmt" <ide> "sort" <ide> import ( <ide> <ide> "github.com/docker/distribution/reference" <ide> "github.com/docker/docker/api/types" <del> "github.com/docker/docker/api/types/filters" <ide> "github.com/docker/docker/container" <ide> "github.com/docker/docker/image" <ide> "github.com/docker/docker/layer" <ide> func (i *ImageService) Map() map[image.ID]*image.Image { <ide> return i.imageStore.Map() <ide> } <ide> <del>// Images returns a filtered list of images. filterArgs is a JSON-encoded set <del>// of filter arguments which will be interpreted by api/types/filters. <del>// filter is a shell glob string applied to repository names. The argument <del>// named all controls whether all images in the graph are filtered, or just <del>// the heads. <del>func (i *ImageService) Images(imageFilters filters.Args, all bool, withExtraAttrs bool) ([]*types.ImageSummary, error) { <del> if err := imageFilters.Validate(acceptedImageFilterTags); err != nil { <add>// Images returns a filtered list of images. <add>func (i *ImageService) Images(_ context.Context, opts types.ImageListOptions) ([]*types.ImageSummary, error) { <add> if err := opts.Filters.Validate(acceptedImageFilterTags); err != nil { <ide> return nil, err <ide> } <ide> <ide> var danglingOnly bool <del> if imageFilters.Contains("dangling") { <del> if imageFilters.ExactMatch("dangling", "true") { <add> if opts.Filters.Contains("dangling") { <add> if opts.Filters.ExactMatch("dangling", "true") { <ide> danglingOnly = true <del> } else if !imageFilters.ExactMatch("dangling", "false") { <del> return nil, invalidFilter{"dangling", imageFilters.Get("dangling")} <add> } else if !opts.Filters.ExactMatch("dangling", "false") { <add> return nil, invalidFilter{"dangling", opts.Filters.Get("dangling")} <ide> } <ide> } <ide> <ide> var ( <ide> beforeFilter, sinceFilter *image.Image <ide> err error <ide> ) <del> err = imageFilters.WalkValues("before", func(value string) error { <add> err = opts.Filters.WalkValues("before", func(value string) error { <ide> beforeFilter, err = i.GetImage(value, nil) <ide> return err <ide> }) <ide> if err != nil { <ide> return nil, err <ide> } <ide> <del> err = imageFilters.WalkValues("since", func(value string) error { <add> err = opts.Filters.WalkValues("since", func(value string) error { <ide> sinceFilter, err = i.GetImage(value, nil) <ide> return err <ide> }) <ide> func (i *ImageService) Images(imageFilters filters.Args, all bool, withExtraAttr <ide> } <ide> } <ide> <del> if imageFilters.Contains("label") { <add> if opts.Filters.Contains("label") { <ide> // Very old image that do not have image.Config (or even labels) <ide> if img.Config == nil { <ide> continue <ide> } <ide> // We are now sure image.Config is not nil <del> if !imageFilters.MatchKVList("label", img.Config.Labels) { <add> if !opts.Filters.MatchKVList("label", img.Config.Labels) { <ide> continue <ide> } <ide> } <ide> func (i *ImageService) Images(imageFilters filters.Args, all bool, withExtraAttr <ide> summary := newImageSummary(img, size) <ide> <ide> for _, ref := range i.referenceStore.References(id.Digest()) { <del> if imageFilters.Contains("reference") { <add> if opts.Filters.Contains("reference") { <ide> var found bool <ide> var matchErr error <del> for _, pattern := range imageFilters.Get("reference") { <add> for _, pattern := range opts.Filters.Get("reference") { <ide> found, matchErr = reference.FamiliarMatch(pattern, ref) <ide> if matchErr != nil { <ide> return nil, matchErr <ide> func (i *ImageService) Images(imageFilters filters.Args, all bool, withExtraAttr <ide> } <ide> } <ide> if summary.RepoDigests == nil && summary.RepoTags == nil { <del> if all || len(i.imageStore.Children(id)) == 0 { <add> if opts.All || len(i.imageStore.Children(id)) == 0 { <ide> <del> if imageFilters.Contains("dangling") && !danglingOnly { <add> if opts.Filters.Contains("dangling") && !danglingOnly { <ide> // dangling=false case, so dangling image is not needed <ide> continue <ide> } <del> if imageFilters.Contains("reference") { // skip images with no references if filtering by reference <add> if opts.Filters.Contains("reference") { // skip images with no references if filtering by reference <ide> continue <ide> } <ide> summary.RepoDigests = []string{"<none>@<none>"} <ide> func (i *ImageService) Images(imageFilters filters.Args, all bool, withExtraAttr <ide> continue <ide> } <ide> <del> if withExtraAttrs { <del> // Lazily init summaryMap and allContainers <del> if summaryMap == nil { <del> summaryMap = make(map[*image.Image]*types.ImageSummary, len(selectedImages)) <add> if opts.ContainerCount { <add> // Lazily init allContainers. <add> if allContainers == nil { <ide> allContainers = i.containers.List() <ide> } <ide> <ide> func (i *ImageService) Images(imageFilters filters.Args, all bool, withExtraAttr <ide> } <ide> // NOTE: By default, Containers is -1, or "not set" <ide> summary.Containers = containers <add> } <ide> <add> if opts.ContainerCount || opts.SharedSize { <add> // Lazily init summaryMap. <add> if summaryMap == nil { <add> summaryMap = make(map[*image.Image]*types.ImageSummary, len(selectedImages)) <add> } <ide> summaryMap[img] = summary <ide> } <ide> summaries = append(summaries, summary) <ide> } <ide> <del> if withExtraAttrs { <add> if opts.SharedSize { <ide> allLayers := i.layerStore.Map() <ide> layerRefs := make(map[layer.ChainID]int, len(allLayers)) <ide>
5
PHP
PHP
add more tests
a9caebc58dd9d9d064946f5866d7df3c8ac65946
<ide><path>tests/Database/DatabaseEloquentFactoryTest.php <ide> public function createSchema() <ide> $table->string('name'); <ide> $table->timestamps(); <ide> }); <add> <add> $this->schema()->create('posts', function ($table) { <add> $table->increments('id'); <add> $table->foreignId('user_id'); <add> $table->string('title'); <add> $table->timestamps(); <add> }); <ide> } <ide> <ide> /** <ide> public function test_basic_model_can_be_created() <ide> $this->assertCount(10, $users); <ide> } <ide> <add> public function test_make_creates_unpersisted_model_instance() <add> { <add> $user = FactoryTestUserFactory::new()->make(['name' => 'Taylor Otwell']); <add> <add> $this->assertInstanceOf(Eloquent::class, $user); <add> $this->assertEquals('Taylor Otwell', $user->name); <add> $this->assertCount(0, FactoryTestUser::all()); <add> } <add> <add> public function test_after_creating_and_making_callbacks_are_called() <add> { <add> $user = FactoryTestUserFactory::new() <add> ->afterMaking(function ($user) { <add> $_SERVER['__test.user.making'] = $user; <add> }) <add> ->afterCreating(function ($user) { <add> $_SERVER['__test.user.creating'] = $user; <add> }) <add> ->create(); <add> <add> $this->assertSame($user, $_SERVER['__test.user.making']); <add> $this->assertSame($user, $_SERVER['__test.user.creating']); <add> <add> unset($_SERVER['__test.user.making']); <add> unset($_SERVER['__test.user.creating']); <add> } <add> <add> public function test_has_many_relationship() <add> { <add> $users = FactoryTestUserFactory::times(10) <add> ->has( <add> FactoryTestPostFactory::times(3) <add> // Test parents passed to callback... <add> ->afterCreating(function ($post, $user) { <add> $_SERVER['__test.post.creating-post'] = $post; <add> $_SERVER['__test.post.creating-user'] = $user; <add> }), <add> 'posts' <add> ) <add> ->create(); <add> <add> $this->assertCount(10, FactoryTestUser::all()); <add> $this->assertCount(30, FactoryTestPost::all()); <add> $this->assertCount(3, FactoryTestUser::latest()->first()->posts); <add> <add> $this->assertInstanceOf(Eloquent::class, $_SERVER['__test.post.creating-post']); <add> $this->assertInstanceOf(Eloquent::class, $_SERVER['__test.post.creating-user']); <add> <add> unset($_SERVER['__test.post.creating-post']); <add> unset($_SERVER['__test.post.creating-user']); <add> } <add> <add> public function test_belongs_to_relationship() <add> { <add> $posts = FactoryTestPostFactory::times(3) <add> ->for(FactoryTestUserFactory::new(['name' => 'Taylor Otwell']), 'user') <add> ->create(); <add> <add> $this->assertCount(3, $posts->filter(function ($post) { <add> return $post->user->name == 'Taylor Otwell'; <add> })); <add> <add> $this->assertCount(1, FactoryTestUser::all()); <add> } <add> <ide> /** <ide> * Get a database connection instance. <ide> * <ide> public function definition() <ide> class FactoryTestUser extends Eloquent <ide> { <ide> protected $table = 'users'; <add> <add> public function posts() <add> { <add> return $this->hasMany(FactoryTestPost::class, 'user_id'); <add> } <add>} <add> <add>class FactoryTestPostFactory extends Factory <add>{ <add> protected $model = FactoryTestPost::class; <add> <add> public function definition() <add> { <add> return [ <add> 'user_id' => FactoryTestUserFactory::new(), <add> 'title' => $this->faker->name, <add> ]; <add> } <add>} <add> <add>class FactoryTestPost extends Eloquent <add>{ <add> protected $table = 'posts'; <add> <add> public function user() <add> { <add> return $this->belongsTo(FactoryTestUser::class, 'user_id'); <add> } <ide> }
1
Javascript
Javascript
append sha to dev versions
ba0ecffcb042e0dfd42eb85cc27617717c66ec89
<ide><path>build/config.js <ide> 'use strict' <ide> <ide> const path = require('path') <add>const childProcess = require('child_process') <ide> <ide> const appMetadata = require('../package.json') <ide> <ide> const repositoryRootPath = path.resolve(__dirname, '..') <ide> const buildOutputPath = path.join(repositoryRootPath, 'out') <ide> const intermediateAppPath = path.join(buildOutputPath, 'app') <ide> const cachePath = path.join(repositoryRootPath, 'cache') <del>const channel = getChannel() <ide> <ide> module.exports = { <del> appMetadata, channel, <add> appMetadata, getAppVersion, getChannel, <ide> repositoryRootPath, buildOutputPath, intermediateAppPath, <ide> cachePath <ide> } <ide> <add>function getAppVersion () { <add> let version = appMetadata.version <add> if (getChannel() === 'dev') { <add> const result = childProcess.spawnSync('git', ['rev-parse', '--short', 'HEAD'], {cwd: repositoryRootPath}) <add> const commitHash = result.stdout.toString().trim() <add> version += '-' + commitHash <add> } <add> return version <add>} <add> <ide> function getChannel () { <ide> if (appMetadata.version.match(/dev/) || isBuildingPR()) { <ide> return 'dev' <ide><path>build/lib/copy-assets.js <ide> module.exports = function () { <ide> } <ide> <ide> fs.copySync( <del> path.join(CONFIG.repositoryRootPath, 'resources', 'app-icons', CONFIG.channel, 'png', '1024.png'), <add> path.join(CONFIG.repositoryRootPath, 'resources', 'app-icons', CONFIG.getChannel(), 'png', '1024.png'), <ide> path.join(CONFIG.intermediateAppPath, 'resources', 'atom.png') <ide> ) <ide> } <ide><path>build/lib/package-application.js <ide> const CONFIG = require('../config') <ide> module.exports = async function () { <ide> console.log(`Running electron-packager on ${CONFIG.intermediateAppPath}`) <ide> const packagedAppPath = await runPackager({ <del> 'app-version': CONFIG.appMetadata.version, <add> 'app-version': CONFIG.getAppVersion(), <ide> 'arch': process.arch, <ide> 'asar': {unpack: buildAsarUnpackGlobExpression()}, <del> 'build-version': CONFIG.appMetadata.version, <add> 'build-version': CONFIG.getAppVersion(), <ide> 'download': {cache: CONFIG.cachePath}, <ide> 'dir': CONFIG.intermediateAppPath, <del> 'icon': path.join(CONFIG.repositoryRootPath, 'resources', 'app-icons', CONFIG.channel, 'atom.icns'), <add> 'icon': path.join(CONFIG.repositoryRootPath, 'resources', 'app-icons', CONFIG.getChannel(), 'atom.icns'), <ide> 'out': CONFIG.buildOutputPath, <ide> 'overwrite': true, <ide> 'platform': process.platform, <ide> function buildAsarUnpackGlobExpression () { <ide> <ide> function runPackager (options) { <ide> return new Promise((resolve, reject) => { <del> electronPackager({ <del> 'app-version': CONFIG.appMetadata.version, <del> 'arch': process.arch, <del> 'asar': {unpack: buildAsarUnpackGlobExpression()}, <del> 'build-version': CONFIG.appMetadata.version, <del> 'download': {cache: CONFIG.cachePath}, <del> 'dir': CONFIG.intermediateAppPath, <del> 'icon': path.join(CONFIG.repositoryRootPath, 'resources', 'app-icons', CONFIG.channel, 'atom.icns'), <del> 'out': CONFIG.buildOutputPath, <del> 'overwrite': true, <del> 'platform': process.platform, <del> 'version': CONFIG.appMetadata.electronVersion <del> }, (err, packagedAppPaths) => { <add> electronPackager(options, (err, packagedAppPaths) => { <ide> if (err) { <ide> reject(err) <ide> throw new Error(err)
3
Python
Python
remove link_components flag again
f6383065986d93081a437406f7d8d60f68d5c52e
<ide><path>spacy/language.py <ide> def initialize( <ide> get_examples: Optional[Callable[[], Iterable[Example]]] = None, <ide> *, <ide> sgd: Optional[Optimizer] = None, <del> link_components: bool = True, <ide> ) -> Optimizer: <ide> """Initialize the pipe for training, using data examples if available. <ide> <ide> get_examples (Callable[[], Iterable[Example]]): Optional function that <ide> returns gold-standard Example objects. <ide> sgd (Optional[Optimizer]): An optimizer to use for updates. If not <ide> provided, will be created using the .create_optimizer() method. <del> link_components (bool): Link listener components automatically or not <del> (default True) <ide> RETURNS (thinc.api.Optimizer): The optimizer. <ide> <ide> DOCS: https://spacy.io/api/language#initialize <ide> def initialize( <ide> proc.initialize, p_settings, section="components", name=name <ide> ) <ide> proc.initialize(get_examples, nlp=self, **p_settings) <del> if link_components: <del> self._link_components() <add> self._link_components() <ide> self._optimizer = sgd <ide> if sgd is not None: <ide> self._optimizer = sgd <ide><path>spacy/pipeline/tok2vec.py <ide> def listening_components(self) -> List[str]: <ide> def add_listener(self, listener: "Tok2VecListener", component_name: str) -> None: <ide> """Add a listener for a downstream component. Usually internals.""" <ide> self.listener_map.setdefault(component_name, []) <del> self.listener_map[component_name].append(listener) <add> if listener not in self.listener_map[component_name]: <add> self.listener_map[component_name].append(listener) <ide> <ide> def remove_listener(self, listener: "Tok2VecListener", component_name: str) -> bool: <ide> """Remove a listener for a downstream component. Usually internals.""" <ide><path>spacy/training/initialize.py <ide> def init_nlp(config: Config, *, use_gpu: int = -1) -> "Language": <ide> # Make sure that listeners are defined before initializing further <ide> nlp._link_components() <ide> with nlp.select_pipes(disable=[*frozen_components, *resume_components]): <del> nlp.initialize(lambda: train_corpus(nlp), sgd=optimizer, link_components=False) <add> nlp.initialize(lambda: train_corpus(nlp), sgd=optimizer) <ide> logger.info(f"Initialized pipeline components: {nlp.pipe_names}") <ide> # Detect components with listeners that are not frozen consistently <ide> for name, proc in nlp.pipeline:
3
PHP
PHP
add getvisible method
63957edb932abda1d11b5cd0f383e3b0dfd24813
<ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> public function addHidden($attributes = null) <ide> <ide> $this->hidden = array_merge($this->hidden, $attributes); <ide> } <add> <add> /** <add> * Get the visible attributes for the model. <add> * <add> * @return array <add> */ <add> public function getVisible() <add> { <add> return $this->visible; <add> } <ide> <ide> /** <ide> * Set the visible attributes for the model.
1
Java
Java
revert the change in recursiveaction
c694a2adaafa52514e88cfdf6379516c9494379a
<ide><path>src/main/java/rx/Scheduler.java <ide> public void call() { <ide> if (!mas.isUnsubscribed()) { <ide> action.call(); <ide> long nextTick = startInNanos + (++count * periodInNanos); <del> SerialSubscription s = new SerialSubscription(); <del> // Should call `mas.set` before `schedule`, or the new Subscription may replace the old one. <del> mas.set(s); <del> s.set(schedule(this, nextTick - TimeUnit.MILLISECONDS.toNanos(now()), TimeUnit.NANOSECONDS)); <add> mas.set(schedule(this, nextTick - TimeUnit.MILLISECONDS.toNanos(now()), TimeUnit.NANOSECONDS)); <ide> } <ide> } <ide> };
1
Mixed
Javascript
add info on points and pointsmaterial
eada0c6ef3001e42c25d574f561ad066e8daaf32
<ide><path>threejs/lessons/resources/threejs-primitives.js <ide> import {threejsLessonUtils} from './threejs-lesson-utils.js'; <ide> }, <ide> nonBuffer: false, <ide> }, <add> Points: { <add> create() { <add> const radius = 7; <add> const widthSegments = 12; <add> const heightSegments = 8; <add> const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments); <add> const material = new THREE.PointsMaterial({ <add> color: 'red', <add> size: 0.2, <add> }); <add> const points = new THREE.Points(geometry, material); <add> return { <add> showLines: false, <add> mesh: points, <add> }; <add> }, <add> }, <add> PointsUniformSize: { <add> create() { <add> const radius = 7; <add> const widthSegments = 12; <add> const heightSegments = 8; <add> const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments); <add> const material = new THREE.PointsMaterial({ <add> color: 'red', <add> size: 3 * window.devicePixelRatio, <add> sizeAttenuation: false, <add> }); <add> const points = new THREE.Points(geometry, material); <add> return { <add> showLines: false, <add> mesh: points, <add> }; <add> }, <add> }, <ide> SphereBufferGeometryLow: { <ide> create() { <ide> const radius = 7; <ide> import {threejsLessonUtils} from './threejs-lesson-utils.js'; <ide> <ide> const root = new THREE.Object3D(); <ide> <del> const boxGeometry = geometryInfo.geometry || geometryInfo.lineGeometry; <del> boxGeometry.computeBoundingBox(); <del> const centerOffset = new THREE.Vector3(); <del> boxGeometry.boundingBox.getCenter(centerOffset).multiplyScalar(-1); <del> <del> if (geometryInfo.geometry) { <del> const material = new THREE.MeshPhongMaterial({ <del> flatShading: info.flatShading === false ? false : true, <del> side: THREE.DoubleSide, <del> }); <del> material.color.setHSL(Math.random(), .5, .5); <del> const mesh = new THREE.Mesh(geometryInfo.geometry, material); <del> mesh.position.copy(centerOffset); <del> root.add(mesh); <del> } <del> if (info.showLines !== false) { <del> const lineMesh = new THREE.LineSegments( <del> geometryInfo.lineGeometry || geometryInfo.geometry, <del> new THREE.LineBasicMaterial({ <del> color: geometryInfo.geometry ? 0xffffff : colors.lines, <del> transparent: true, <del> opacity: 0.5, <del> })); <del> lineMesh.position.copy(centerOffset); <del> root.add(lineMesh); <add> if (geometry.mesh) { <add> root.add(geometry.mesh); <add> } else { <add> const boxGeometry = geometryInfo.geometry || geometryInfo.lineGeometry; <add> boxGeometry.computeBoundingBox(); <add> const centerOffset = new THREE.Vector3(); <add> boxGeometry.boundingBox.getCenter(centerOffset).multiplyScalar(-1); <add> <add> if (geometryInfo.geometry) { <add> const material = new THREE.MeshPhongMaterial({ <add> flatShading: info.flatShading === false ? false : true, <add> side: THREE.DoubleSide, <add> }); <add> material.color.setHSL(Math.random(), .5, .5); <add> const mesh = new THREE.Mesh(geometryInfo.geometry, material); <add> mesh.position.copy(centerOffset); <add> root.add(mesh); <add> } <add> <add> if (info.showLines !== false) { <add> const lineMesh = new THREE.LineSegments( <add> geometryInfo.lineGeometry || geometryInfo.geometry, <add> new THREE.LineBasicMaterial({ <add> color: geometryInfo.geometry ? 0xffffff : colors.lines, <add> transparent: true, <add> opacity: 0.5, <add> })); <add> lineMesh.position.copy(centerOffset); <add> root.add(lineMesh); <add> } <ide> } <ide> <ide> threejsLessonUtils.addDiagram(elem, {create: () => root}); <ide><path>threejs/lessons/threejs-primitives.md <ide> and it's best to [look in the documentation](https://threejs.org/docs/) for all <ide> repeat them here. You can also click the links above next to each shape <ide> to take you directly to the docs for that shape. <ide> <add>There is one other pair of classes that doesn't really fit the patterns above. Those are <add>the `PointsMaterial` and the `Points` class. `Points` is like `LineSegments` above in that it takes a <add>a `Geometry` or `BufferGeometry` but draws points at each vertex instead of lines. <add>To use it you also need to pass it a `PointsMaterial` which <add>take a [`size`](PointsMaterial.size) for how large to make the points. <add> <add>```js <add>const radius = 7; <add>const widthSegments = 12; <add>const heightSegments = 8; <add>const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments); <add>const material = new THREE.PointsMaterial({ <add> color: 'red', <add> size: 0.2, // in world units <add>}); <add>const points = new THREE.Points(geometry, material); <add>scene.add(points); <add>``` <add> <add><div class="spread"> <add><div data-diagram="Points"></div> <add></div> <add> <add>You can turn off [`sizeAttenuation`](PointsMaterial.sizeAttenuation) by setting it to false if you want the points to <add>be the same size regardless of their distance from the camera. <add> <add>```js <add>const material = new THREE.PointsMaterial({ <add> color: 'red', <add>+ sizeAttenuation: false, <add>+ size: 3, // in pixels <add>- size: 0.2, // in world units <add>}); <add>... <add>``` <add> <add><div class="spread"> <add><div data-diagram="PointsUniformSize"></div> <add></div> <add> <ide> One other thing that's important to cover is that almost all shapes <ide> have various settings for how much to subdivide them. A good example <ide> might be the sphere geometries. Spheres take parameters for <ide> subdivisions you choose the more likely things will run smoothly and the less <ide> memory they'll take. You'll have to decide for yourself what the correct <ide> tradeoff is for your particular situation. <ide> <add>If none of the shapes above fit your use case you can load <add>geometry for example from a [.obj file](threejs-load-obj.html) <add>or a [.gltf file](threejs-load-gltf.html). <add>You can also create your own [custom Geometry](threejs-custom-geometry.html) <add>or [custom BufferGeometry](threejs-custom-buffergeometry.html). <add> <ide> Next up let's go over [how three's scene graph works and how <ide> to use it](threejs-scenegraph.html). <ide>
2
Mixed
Python
add doc_cleaner component
9ac6d4991eb34d47f2e42bf7418918d49cf76219
<ide><path>spacy/errors.py <ide> class Warnings(metaclass=ErrorsWithCodes): <ide> "lead to errors.") <ide> W115 = ("Skipping {method}: the floret vector table cannot be modified. " <ide> "Vectors are calculated from character ngrams.") <add> W116 = ("Unable to clean attribute '{attr}'.") <ide> <ide> <ide> class Errors(metaclass=ErrorsWithCodes): <ide><path>spacy/pipeline/functions.py <ide> from typing import Dict, Any <ide> import srsly <add>import warnings <ide> <add>from ..errors import Warnings <ide> from ..language import Language <ide> from ..matcher import Matcher <ide> from ..tokens import Doc <ide> def from_disk(self, path, **kwargs): <ide> "cfg": lambda p: self._set_config(srsly.read_json(p)), <ide> } <ide> util.from_disk(path, serializers, []) <add> <add> <add>@Language.factory( <add> "doc_cleaner", <add> default_config={"attrs": {"tensor": None, "_.trf_data": None}, "silent": True}, <add>) <add>def make_doc_cleaner(nlp: Language, name: str, *, attrs: Dict[str, Any], silent: bool): <add> return DocCleaner(attrs, silent=silent) <add> <add> <add>class DocCleaner: <add> def __init__(self, attrs: Dict[str, Any], *, silent: bool = True): <add> self.cfg: Dict[str, Any] = {"attrs": dict(attrs), "silent": silent} <add> <add> def __call__(self, doc: Doc) -> Doc: <add> attrs: dict = self.cfg["attrs"] <add> silent: bool = self.cfg["silent"] <add> for attr, value in attrs.items(): <add> obj = doc <add> parts = attr.split(".") <add> skip = False <add> for part in parts[:-1]: <add> if hasattr(obj, part): <add> obj = getattr(obj, part) <add> else: <add> skip = True <add> if not silent: <add> warnings.warn(Warnings.W116.format(attr=attr)) <add> if not skip: <add> if hasattr(obj, parts[-1]): <add> setattr(obj, parts[-1], value) <add> else: <add> if not silent: <add> warnings.warn(Warnings.W116.format(attr=attr)) <add> return doc <add> <add> def to_bytes(self, **kwargs): <add> serializers = { <add> "cfg": lambda: srsly.json_dumps(self.cfg), <add> } <add> return util.to_bytes(serializers, []) <add> <add> def from_bytes(self, data, **kwargs): <add> deserializers = { <add> "cfg": lambda b: self.cfg.update(srsly.json_loads(b)), <add> } <add> util.from_bytes(data, deserializers, []) <add> return self <add> <add> def to_disk(self, path, **kwargs): <add> path = util.ensure_path(path) <add> serializers = { <add> "cfg": lambda p: srsly.write_json(p, self.cfg), <add> } <add> return util.to_disk(path, serializers, []) <add> <add> def from_disk(self, path, **kwargs): <add> path = util.ensure_path(path) <add> serializers = { <add> "cfg": lambda p: self.cfg.update(srsly.read_json(p)), <add> } <add> util.from_disk(path, serializers, []) <ide><path>spacy/tests/pipeline/test_functions.py <ide> from spacy.language import Language <ide> from spacy.tokens import Span, Doc <ide> <add>from ..doc.test_underscore import clean_underscore # noqa: F401 <add> <ide> <ide> @pytest.fixture <ide> def doc(en_vocab): <ide> def test_token_splitter(): <ide> "i", <ide> ] <ide> assert all(len(t.text) <= token_splitter.split_length for t in doc) <add> <add> <add>@pytest.mark.usefixtures("clean_underscore") <add>def test_factories_doc_cleaner(): <add> nlp = Language() <add> nlp.add_pipe("doc_cleaner") <add> doc = nlp.make_doc("text") <add> doc.tensor = [1, 2, 3] <add> doc = nlp(doc) <add> assert doc.tensor is None <add> <add> nlp = Language() <add> nlp.add_pipe("doc_cleaner", config={"silent": False}) <add> with pytest.warns(UserWarning): <add> doc = nlp("text") <add> <add> Doc.set_extension("test_attr", default=-1) <add> nlp = Language() <add> nlp.add_pipe("doc_cleaner", config={"attrs": {"_.test_attr": 0}}) <add> doc = nlp.make_doc("text") <add> doc._.test_attr = 100 <add> doc = nlp(doc) <add> assert doc._.test_attr == 0 <ide><path>website/docs/api/pipeline-functions.md <ide> exceed the transformer model max length. <ide> | `min_length` | The minimum length for a token to be split. Defaults to `25`. ~~int~~ | <ide> | `split_length` | The length of the split tokens. Defaults to `5`. ~~int~~ | <ide> | **RETURNS** | The modified `Doc` with the split tokens. ~~Doc~~ | <add> <add>## doc_cleaner {#doc_cleaner tag="function" new="3.2.1"} <add> <add>Clean up `Doc` attributes. Intended for use at the end of pipelines with <add>`tok2vec` or `transformer` pipeline components that store tensors and other <add>values that can require a lot of memory and frequently aren't needed after the <add>whole pipeline has run. <add> <add>> #### Example <add>> <add>> ```python <add>> config = {"attrs": {"tensor": None}} <add>> nlp.add_pipe("doc_cleaner", config=config) <add>> doc = nlp("text") <add>> assert doc.tensor is None <add>> ``` <add> <add>| Setting | Description | <add>| ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | <add>| `attrs` | A dict of the `Doc` attributes and the values to set them to. Defaults to `{"tensor": None, "_.trf_data": None}` to clean up after `tok2vec` and `transformer` components. ~~dict~~ | <add>| `silent` | If `False`, show warnings if attributes aren't found or can't be set. Defaults to `True`. ~~bool~~ | <add>| **RETURNS** | The modified `Doc` with the modified attributes. ~~Doc~~ |
4
Python
Python
fix the bug that created the node at ecs driver
eafeccc4baa742001ffe19e400ed7879a6537661
<ide><path>libcloud/compute/drivers/ecs.py <ide> def create_node(self, name, size, image, auth=None, <ide> <ide> if ex_io_optimized is not None: <ide> optimized = ex_io_optimized <del> if not isinstance(optimized, bool): <del> optimized = str(optimized).lower() == 'true' <del> params['IoOptimized'] = 'true' if optimized else 'false' <add> if isinstance(optimized, bool): <add> optimized = 'optimized' if optimized else 'none' <add> params['IoOptimized'] = optimized <ide> <ide> if ex_system_disk: <ide> system_disk = self._get_system_disk(ex_system_disk)
1
Javascript
Javascript
log unhandled promise rejections in testing
80bbf7b27ca105b4d487fce50f93c41833b6e6ee
<ide><path>packages/ember-runtime/lib/ext/rsvp.js <ide> RSVP.onerrorDefault = function (error) { <ide> <ide> if (Test && Test.adapter) { <ide> Test.adapter.exception(error); <add> Logger.error(error.stack); <ide> } else { <ide> throw error; <ide> }
1
Python
Python
implement len in iterabledatasetshard
a21ee1f99003f49f411b3b62a087c4da5d839843
<ide><path>src/transformers/trainer_pt_utils.py <ide> def __iter__(self): <ide> for i in process_slice: <ide> yield current_batch[i] <ide> <add> def __len__(self): <add> # Will raise an error if the underlying dataset is not sized. <add> if self.drop_last: <add> return len(self.dataset) // self.num_processes <add> else: <add> return math.ceil(len(self.dataset) / self.num_processes) <add> <ide> <ide> # In order to keep `trainer.py` compact and easy to understand, place any secondary PT Trainer <ide> # helper methods here
1
Go
Go
add unit test for darwin
818e0b2fcf1ec69b28a215526a2682ed042044c4
<ide><path>pkg/parsers/kernel/kernel_darwin_test.go <add>package kernel <add> <add>import ( <add> "testing" <add> <add> "gotest.tools/v3/assert" <add>) <add> <add>func TestGetRelease(t *testing.T) { <add> // example output of "system_profiler SPSoftwareDataType" <add> const spSoftwareDataType = `Software: <add> <add> System Software Overview: <add> <add> System Version: macOS 10.14.6 (18G4032) <add> Kernel Version: Darwin 18.7.0 <add> Boot Volume: fastfood <add> Boot Mode: Normal <add> Computer Name: Macintosh <add> User Name: Foobar (foobar) <add> Secure Virtual Memory: Enabled <add> System Integrity Protection: Enabled <add> Time since boot: 6 days 23:16 <add>` <add> release, err := getRelease(spSoftwareDataType) <add> assert.NilError(t, err) <add> assert.Equal(t, release, "18.7.0") <add>}
1
Go
Go
allow docker build from stdin
33ea1483d5b89559e1fe9a9556e3ea757f673e16
<ide><path>commands.go <ide> func (cli *DockerCli) CmdInsert(args ...string) error { <ide> } <ide> <ide> func (cli *DockerCli) CmdBuild(args ...string) error { <del> cmd := Subcmd("build", "[CONTEXT]", "Build an image from a Dockerfile") <add> cmd := Subcmd("build", "[CONTEXT|-]", "Build an image from a Dockerfile") <ide> if err := cmd.Parse(args); err != nil { <ide> return nil <ide> } <ide> <del> var multipartBody io.Reader <add> var ( <add> multipartBody io.Reader <add> file io.ReadCloser <add> contextPath string <add> ) <ide> <ide> // Init the needed component for the Multipart <ide> buff := bytes.NewBuffer([]byte{}) <ide> func (cli *DockerCli) CmdBuild(args ...string) error { <ide> <ide> dockerfile := "Dockerfile" <ide> <del> if cmd.Arg(0) != "" { <add> if cmd.Arg(0) != "" && cmd.Arg(0) != "-" { <add> contextPath = cmd.Arg(0) <ide> dockerfile = path.Join(cmd.Arg(0), dockerfile) <ide> } <add> if cmd.Arg(0) != "-" { <add> f, err := os.Open(dockerfile) <add> if err != nil { <add> return err <add> } <add> defer f.Close() <add> file = f <add> } else { <add> contextPath = cmd.Arg(1) <add> file = os.Stdin <add> } <ide> <ide> // Create a FormFile multipart for the Dockerfile <del> file, err := os.Open(dockerfile) <del> if err != nil { <del> return err <del> } <del> defer file.Close() <ide> if wField, err := w.CreateFormFile("Dockerfile", "Dockerfile"); err != nil { <ide> return err <ide> } else { <ide> func (cli *DockerCli) CmdBuild(args ...string) error { <ide> compression := Bzip2 <ide> <ide> // Create a FormFile multipart for the context if needed <del> if cmd.Arg(0) != "" { <add> if contextPath != "" { <ide> // FIXME: Use NewTempArchive in order to have the size and avoid too much memory usage? <del> context, err := Tar(cmd.Arg(0), compression) <add> context, err := Tar(contextPath, compression) <ide> if err != nil { <ide> return err <ide> } <ide> // NOTE: Do this in case '.' or '..' is input <del> absPath, err := filepath.Abs(cmd.Arg(0)) <add> absPath, err := filepath.Abs(contextPath) <ide> if err != nil { <ide> return err <ide> } <ide> func (cli *DockerCli) CmdBuild(args ...string) error { <ide> return err <ide> } <ide> req.Header.Set("Content-Type", w.FormDataContentType()) <del> if cmd.Arg(0) != "" { <add> if contextPath != "" { <ide> req.Header.Set("X-Docker-Context-Compression", compression.Flag()) <ide> fmt.Println("Uploading Context...") <ide> }
1
Python
Python
add disk size in disks.initializeparams
74f937dd07570c29d4f5906236a5513d1530725d
<ide><path>libcloud/compute/drivers/gce.py <ide> def ex_create_network(self, name, cidr=None, description=None, <ide> def create_node( <ide> self, name, size, image, location=None, ex_network='default', <ide> ex_subnetwork=None, ex_tags=None, ex_metadata=None, <del> ex_boot_disk=None, use_existing_disk=True, external_ip='ephemeral', <del> internal_ip=None, ex_disk_type='pd-standard', <add> ex_boot_disk=None, disk_size=10, use_existing_disk=True, <add> external_ip='ephemeral', internal_ip=None, ex_disk_type='pd-standard', <ide> ex_disk_auto_delete=True, ex_service_accounts=None, <ide> description=None, ex_can_ip_forward=None, <ide> ex_disks_gce_struct=None, ex_nic_gce_struct=None, <ide> def create_node( <ide> 'initializeParams': { <ide> 'diskName': name, <ide> 'diskType': ex_disk_type.extra['selfLink'], <del> 'sourceImage': image.extra['selfLink'] <add> 'sourceImage': image.extra['selfLink'], <add> 'diskSizeGb': disk_size <ide> } <ide> }] <ide>
1
Javascript
Javascript
stop tests running after navigating away
d626e898ee2e6295cb593654b1d104f3fee2b7b3
<ide><path>client/src/templates/Challenges/classic/Show.js <ide> import { <ide> updateChallengeMeta, <ide> challengeMounted, <ide> consoleOutputSelector, <del> executeChallenge <add> executeChallenge, <add> cancelTests <ide> } from '../redux'; <ide> <ide> import './classic.css'; <ide> const mapDispatchToProps = dispatch => <ide> initTests, <ide> updateChallengeMeta, <ide> challengeMounted, <del> executeChallenge <add> executeChallenge, <add> cancelTests <ide> }, <ide> dispatch <ide> ); <ide> <ide> const propTypes = { <add> cancelTests: PropTypes.func.isRequired, <ide> challengeMounted: PropTypes.func.isRequired, <ide> createFiles: PropTypes.func.isRequired, <ide> data: PropTypes.shape({ <ide> class ShowClassic extends Component { <ide> } <ide> <ide> componentWillUnmount() { <del> const { createFiles } = this.props; <add> const { createFiles, cancelTests } = this.props; <ide> createFiles({}); <add> cancelTests(); <ide> } <ide> <ide> getChallenge = () => this.props.data.challengeNode; <ide><path>client/src/templates/Challenges/redux/execute-challenge-saga.js <ide> import { <ide> takeLatest, <ide> takeEvery, <ide> fork, <del> getContext <add> getContext, <add> take, <add> cancel <ide> } from 'redux-saga/effects'; <ide> import { channel } from 'redux-saga'; <ide> import escape from 'lodash/escape'; <ide> import { <ide> logsToConsole, <ide> updateTests, <ide> isBuildEnabledSelector, <del> disableBuildOnError <add> disableBuildOnError, <add> types <ide> } from './'; <ide> <ide> import { <ide> import { <ide> // How long before bailing out of a preview. <ide> const previewTimeout = 2500; <ide> <add>export function* executeCancellableChallengeSaga() { <add> const task = yield fork(executeChallengeSaga); <add> <add> yield take(types.cancelTests); <add> yield cancel(task); <add>} <add> <ide> export function* executeChallengeSaga() { <ide> const isBuildEnabled = yield select(isBuildEnabledSelector); <ide> if (!isBuildEnabled) { <ide> function* previewChallengeSaga() { <ide> <ide> export function createExecuteChallengeSaga(types) { <ide> return [ <del> takeLatest(types.executeChallenge, executeChallengeSaga), <add> takeLatest(types.executeChallenge, executeCancellableChallengeSaga), <ide> takeLatest( <ide> [ <ide> types.updateFile, <ide><path>client/src/templates/Challenges/redux/index.js <ide> export const types = createTypes( <ide> 'updateSuccessMessage', <ide> 'updateTests', <ide> 'updateLogs', <add> 'cancelTests', <ide> <ide> 'logsToConsole', <ide> <ide> export const createFiles = createAction(types.createFiles, challengeFiles => <ide> export const createQuestion = createAction(types.createQuestion); <ide> export const initTests = createAction(types.initTests); <ide> export const updateTests = createAction(types.updateTests); <add>export const cancelTests = createAction(types.cancelTests); <ide> <ide> export const initConsole = createAction(types.initConsole); <ide> export const initLogs = createAction(types.initLogs);
3
Javascript
Javascript
fix failing test written in 9d3ecef - fixes
5ee0487184539babef74afa92f20e8a11c3f80e5
<ide><path>packages/ember-runtime/lib/controllers/array_controller.js <ide> Ember.ArrayController = Ember.ArrayProxy.extend(Ember.ControllerMixin, <ide> <ide> objectAtContent: function(idx) { <ide> var length = get(this, 'length'), <del> object = get(this,'arrangedContent').objectAt(idx), <del> controllerClass = this.lookupItemController(object); <del> <del> if (controllerClass && idx < length) { <del> return this.controllerAt(idx, object, controllerClass); <del> } else { <del> // When controllerClass is falsy we have not opted in to using item <del> // controllers, so return the object directly. However, when <del> // controllerClass is defined but the index is out of range, we want to <del> // return the "out of range" value, whatever that might be. Rather than <del> // make assumptions (e.g. guessing `null` or `undefined`) we defer this to <del> // `arrangedContent`. <del> return object; <add> object = get(this,'arrangedContent').objectAt(idx); <add> <add> if (idx < length) { <add> var controllerClass = this.lookupItemController(object); <add> if (controllerClass) { <add> return this.controllerAt(idx, object, controllerClass); <add> } <ide> } <add> <add> // When `controllerClass` is falsy, we have not opted in to using item <add> // controllers, so return the object directly. <add> <add> // When the index is out of range, we want to return the "out of range" <add> // value, whatever that might be. Rather than make assumptions <add> // (e.g. guessing `null` or `undefined`) we defer this to `arrangedContent`. <add> return object; <ide> }, <ide> <ide> arrangedContentDidChange: function() {
1
Text
Text
add ephraimbuddy to inthewild
82b876bbe2fa1f44b89dac3a13c71cf828ee0417
<ide><path>INTHEWILD.md <ide> Currently, **officially** using Airflow: <ide> 1. [Arrive](https://www.arrive.com/) <ide> 1. [Artelys](https://www.artelys.com/) [[@fortierq](https://github.com/fortierq)] <ide> 1. [Asana](https://asana.com/) [[@chang](https://github.com/chang), [@dima-asana](https://github.com/dima-asana), [@jdavidheiser](https://github.com/jdavidheiser), [@ricardoandresrojas](https://github.com/ricardoandresrojas)] <del>1. [Astronomer](https://www.astronomer.io) [[@schnie](https://github.com/schnie), [@ashb](https://github.com/ashb), [@kaxil](https://github.com/kaxil), [@dimberman](https://github.com/dimberman), [@andriisoldatenko](https://github.com/andriisoldatenko), [@ryw](https://github.com/ryw), [@ryanahamilton](https://github.com/ryanahamilton), [@jhtimmins](https://github.com/jhtimmins), [@vikramkoka](https://github.com/vikramkoka), [@jedcunningham](https://github.com/jedcunningham), [@BasPH](https://github.com/basph)] <add>1. [Astronomer](https://www.astronomer.io) [[@schnie](https://github.com/schnie), [@ashb](https://github.com/ashb), [@kaxil](https://github.com/kaxil), [@dimberman](https://github.com/dimberman), [@andriisoldatenko](https://github.com/andriisoldatenko), [@ryw](https://github.com/ryw), [@ryanahamilton](https://github.com/ryanahamilton), [@jhtimmins](https://github.com/jhtimmins), [@vikramkoka](https://github.com/vikramkoka), [@jedcunningham](https://github.com/jedcunningham), [@BasPH](https://github.com/basph), [@ephraimbuddy](https://github.com/ephraimbuddy)] <ide> 1. [Auth0](https://auth0.com) [[@scottypate](https://github.com/scottypate)], [[@dm03514](https://github.com/dm03514)], [[@karangale](https://github.com/karangale)] <ide> 1. [Automattic](https://automattic.com/) [[@anandnalya](https://github.com/anandnalya), [@bperson](https://github.com/bperson), [@khrol](https://github.com/Khrol), [@xyu](https://github.com/xyu)] <ide> 1. [Avesta Technologies](https://avestatechnologies.com) [[@TheRum](https://github.com/TheRum)]
1
Python
Python
adjust spacing and sizing in compact mode
32c6f05de91b8ae7a189bec4c4efb11f50d78947
<ide><path>spacy/displacy/render.py <ide> def __init__(self, options={}): <ide> offset_x, color, bg, font) <ide> """ <ide> self.compact = options.get('compact', False) <del> distance, arrow_width = (85, 8) if self.compact else (175, 10) <ide> self.word_spacing = options.get('word_spacing', 45) <del> self.arrow_spacing = options.get('arrow_spacing', 20) <del> self.arrow_width = options.get('arrow_width', arrow_width) <add> self.arrow_spacing = options.get('arrow_spacing', 12 if self.compact else 20) <add> self.arrow_width = options.get('arrow_width', 6 if self.compact else 10) <ide> self.arrow_stroke = options.get('arrow_stroke', 2) <del> self.distance = options.get('distance', distance) <add> self.distance = options.get('distance', 150 if self.compact else 175) <ide> self.offset_x = options.get('offset_x', 50) <ide> self.color = options.get('color', '#000000') <ide> self.bg = options.get('bg', '#ffffff') <ide> def render_arrow(self, label, start, end, direction, i): <ide> x_end = (self.offset_x+(end-start)*self.distance+start*self.distance <ide> -self.arrow_spacing*(self.highest_level-level)/4) <ide> y_curve = self.offset_y-level*self.distance/2 <add> if self.compact: <add> y_curve = self.offset_y-level*self.distance/6 <ide> if y_curve == 0 and len(self.levels) > 5: <ide> y_curve = -self.distance <ide> arrowhead = self.get_arrowhead(direction, x_start, y, x_end)
1
Ruby
Ruby
prefer formula#name method over formula#to_s
9a83f63c21880f782233b23abac2f820a2c3c18d
<ide><path>Library/Homebrew/build.rb <ide> def install <ide> end <ide> <ide> if superenv? <del> ENV.keg_only_deps = keg_only_deps.map(&:to_s) <del> ENV.deps = deps.map { |d| d.to_formula.to_s } <add> ENV.keg_only_deps = keg_only_deps.map(&:name) <add> ENV.deps = deps.map { |d| d.to_formula.name } <ide> ENV.x11 = reqs.any? { |rq| rq.kind_of?(X11Dependency) } <ide> ENV.setup_build_environment(f) <ide> post_superenv_hacks
1
Javascript
Javascript
remove obsolete eslint comments
35a8906964dc4544dd59ad99b2c1f58a09d484f3
<ide><path>test/js-native-api/test_general/testInstanceOf.js <ide> const common = require('../../common'); <ide> const assert = require('assert'); <ide> <ide> // Addon is referenced through the eval expression in testFile <del>// eslint-disable-next-line no-unused-vars <ide> const addon = require(`./build/${common.buildType}/test_general`); <ide> const path = require('path'); <ide> <ide><path>test/parallel/test-require-extensions-same-filename-as-dir-trailing-slash.js <ide> // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <ide> // USE OR OTHER DEALINGS IN THE SOFTWARE. <ide> <del>/* eslint-disable max-len */ <ide> 'use strict'; <ide> require('../common'); <ide> const assert = require('assert');
2
Python
Python
fix nanpercentile crash on all-nan slices
6e699948c2b6098ec1a6e135241bc24e4df9a4d1
<ide><path>numpy/lib/nanfunctions.py <ide> def _nanpercentile(a, q, axis=None, out=None, overwrite_input=False, <ide> else: <ide> result = np.apply_along_axis(_nanpercentile1d, axis, a, q, <ide> overwrite_input, interpolation) <del> <add> # apply_along_axis fills in collapsed axis with results. <add> # Move that axis to the beginning to match percentile's <add> # convention. <add> if q.ndim != 0: <add> result = np.swapaxes(result, 0, axis) <ide> if out is not None: <ide> out[...] = result <ide> return result <ide> def _nanpercentile1d(arr1d, q, overwrite_input=False, interpolation='linear'): <ide> s = np.where(c)[0] <ide> if s.size == arr1d.size: <ide> warnings.warn("All-NaN slice encountered", RuntimeWarning) <del> return np.nan <add> if q.ndim == 0: <add> return np.nan <add> else: <add> return np.nan * np.ones((len(q),)) <ide> elif s.size == 0: <ide> return np.percentile(arr1d, q, overwrite_input=overwrite_input, <ide> interpolation=interpolation) <ide><path>numpy/lib/tests/test_nanfunctions.py <ide> def test_result_values(self): <ide> tgt = [np.percentile(d, 28) for d in _rdat] <ide> res = np.nanpercentile(_ndat, 28, axis=1) <ide> assert_almost_equal(res, tgt) <del> tgt = [np.percentile(d, (28, 98)) for d in _rdat] <add> # Transpose the array to fit the output convention of numpy.percentile <add> tgt = np.transpose([np.percentile(d, (28, 98)) for d in _rdat]) <ide> res = np.nanpercentile(_ndat, (28, 98), axis=1) <ide> assert_almost_equal(res, tgt) <ide> <ide> def test_extended_axis_invalid(self): <ide> assert_raises(IndexError, np.nanpercentile, d, q=5, axis=(0, 4)) <ide> assert_raises(ValueError, np.nanpercentile, d, q=5, axis=(1, 1)) <ide> <add> def test_multiple_percentiles(self): <add> perc = [50, 100] <add> mat = np.ones((4, 3)) <add> nan_mat = np.nan * mat <add> # For checking consistency in higher dimensional case <add> large_mat = np.ones((3, 4, 5)) <add> large_mat[:, 0:2:4, :] = 0 <add> large_mat[:, :, 3:] = 2*large_mat[:, :, 3:] <add> for axis in [None, 0, 1]: <add> for keepdim in [False, True]: <add> with warnings.catch_warnings(record=True) as w: <add> warnings.simplefilter('always') <add> val = np.percentile(mat, perc, axis=axis, keepdims=keepdim) <add> nan_val = np.nanpercentile(nan_mat, perc, axis=axis, <add> keepdims=keepdim) <add> assert_equal(nan_val.shape, val.shape) <add> <add> val = np.percentile(large_mat, perc, axis=axis, <add> keepdims=keepdim) <add> nan_val = np.nanpercentile(large_mat, perc, axis=axis, <add> keepdims=keepdim) <add> assert_equal(nan_val, val) <add> <ide> <ide> if __name__ == "__main__": <ide> run_module_suite()
2
PHP
PHP
add callonce to seeder
63bb589b760b6497c840858409e3b5da0ee287de
<ide><path>src/Illuminate/Database/Seeder.php <ide> abstract class Seeder <ide> */ <ide> protected $command; <ide> <add> /** <add> * Seeders that have been called at least one time. <add> * <add> * @var array <add> */ <add> protected static $called = []; <add> <ide> /** <ide> * Run the given seeder class. <ide> * <ide> public function call($class, $silent = false, array $parameters = []) <ide> if ($silent === false && isset($this->command)) { <ide> $this->command->getOutput()->writeln("<info>Seeded:</info> {$name} ({$runTime}ms)"); <ide> } <add> <add> static::$called[] = $class; <ide> } <ide> <ide> return $this; <ide> public function callSilent($class, array $parameters = []) <ide> $this->call($class, true, $parameters); <ide> } <ide> <add> /** <add> * Run the given seeder class once. <add> * <add> * @param array|string $class <add> * @param bool $silent <add> * @return void <add> */ <add> public function callOnce($class, $silent = false, array $parameters = []) <add> { <add> if (in_array($class, static::$called)) { <add> return; <add> } <add> <add> $this->call($class, $silent, $parameters); <add> } <add> <ide> /** <ide> * Resolve an instance of the given seeder class. <ide> *
1
Javascript
Javascript
remove unused base.js script
be0e196e65cf50ab8be1e6aa8d56e5f4d13def7e
<ide><path>rest_framework/static/rest_framework/docs/js/base.js <del>function getSearchTerm() <del>{ <del> var sPageURL = window.location.search.substring(1); <del> var sURLVariables = sPageURL.split('&'); <del> for (var i = 0; i < sURLVariables.length; i++) <del> { <del> var sParameterName = sURLVariables[i].split('='); <del> if (sParameterName[0] == 'q') <del> { <del> return sParameterName[1]; <del> } <del> } <del>} <del> <del>$(document).ready(function() { <del> <del> var search_term = getSearchTerm(), <del> $search_modal = $('#mkdocs_search_modal'); <del> <del> if(search_term){ <del> $search_modal.modal(); <del> } <del> <del> // make sure search input gets autofocus everytime modal opens. <del> $search_modal.on('shown.bs.modal', function () { <del> $search_modal.find('#mkdocs-search-query').focus(); <del> }); <del> <del> // Highlight.js <del> hljs.initHighlightingOnLoad(); <del> $('table').addClass('table table-striped table-hover'); <del>}); <del> <del> <del>$('body').scrollspy({ <del> target: '.bs-sidebar', <del>}); <del> <del>/* Prevent disabled links from causing a page reload */ <del>$("li.disabled a").click(function() { <del> event.preventDefault(); <del>});
1