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
Python
Python
add glossary entry for root
46982cf694bd70a53965bc02c0f5be8203f7d526
<ide><path>spacy/glossary.py <ide> def explain(term): <ide> "relcl": "relative clause modifier", <ide> "reparandum": "overridden disfluency", <ide> "root": "root", <add> "ROOT": "root", <ide> "vocative": "vocative", <ide> "xcomp": "open clausal complement", <ide> # Dependency labels (German)
1
Text
Text
change user story to match test suite
cf6e545b03a8335dd5837a080951fc8b131b520d
<ide><path>curriculum/challenges/english/01-responsive-web-design/responsive-web-design-projects/build-a-tribute-page.md <ide> You can use HTML, JavaScript, and CSS to complete this project. Plain CSS is rec <ide> <ide> **User Story #2:** I should see an element with a corresponding `id="title"`, which contains a string (i.e. text) that describes the subject of the tribute page (e.g. "Dr. Norman Borlaug"). <ide> <del>**User Story #3:** I should see a `div` element with a corresponding `id="img-div"`. <add>**User Story #3:** I should see either a `figure` or a `div` element with a corresponding `id="img-div"`. <ide> <ide> **User Story #4:** Within the `img-div` element, I should see an `img` element with a corresponding `id="image"`. <ide>
1
PHP
PHP
add support for key => value cookies
4d8dd124491d1f16b4dd3ad056a2acd760b31f4d
<ide><path>lib/Cake/Network/Http/HttpSocket.php <ide> protected function _buildHeader($header, $mode = 'standard') { <ide> public function buildCookies($cookies) { <ide> $header = array(); <ide> foreach ($cookies as $name => $cookie) { <del> $header[] = $name . '=' . $this->_escapeToken($cookie['value'], array(';')); <add> if (is_array($cookie)) { <add> $value = $this->_escapeToken($cookie['value'], array(';')); <add> } else { <add> $value = $this->_escapeToken($cookie, array(';')); <add> } <add> $header[] = $name . '=' . $value; <ide> } <ide> return $this->_buildHeader(array('Cookie' => implode('; ', $header)), 'pragmatic'); <ide> } <ide><path>lib/Cake/Test/Case/Network/Http/HttpSocketTest.php <ide> public function testBuildCookies() { <ide> 'people' => array( <ide> 'value' => 'jim,jack,johnny;', <ide> 'path' => '/accounts' <del> ) <add> ), <add> 'key' => 'value' <ide> ); <del> $expect = "Cookie: foo=bar; people=jim,jack,johnny\";\"\r\n"; <add> $expect = "Cookie: foo=bar; people=jim,jack,johnny\";\"; key=value\r\n"; <ide> $result = $this->Socket->buildCookies($cookies); <ide> $this->assertEquals($expect, $result); <ide> }
2
Javascript
Javascript
fix broken releases script
b2eb7fd77b9c553de37916cd63d95a54def96f31
<ide><path>scripts/bump-oss-version.js <ide> * After changing the files it makes a commit and tags it. <ide> * All you have to do is push changes to remote and CI will make a new build. <ide> */ <del> <add>const fs = require('fs'); <ide> const { <ide> cat, <ide> echo, <ide> if (!match) { <ide> } <ide> let [, major, minor, patch, prerelease] = match; <ide> <del>cat('scripts/versiontemplates/ReactNativeVersion.java.template') <del> .replace('${major}', major) <del> .replace('${minor}', minor) <del> .replace('${patch}', patch) <del> .replace('${prerelease}', prerelease !== undefined ? `"${prerelease}"` : 'null') <del> .to('ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/ReactNativeVersion.java'); <del> <del>cat('scripts/versiontemplates/RCTVersion.h.template') <del> .replace('${major}', `@(${major})`) <del> .replace('${minor}', `@(${minor})`) <del> .replace('${patch}', `@(${patch})`) <del> .replace('${prerelease}', prerelease !== undefined ? `@"${prerelease}"` : '[NSNull null]') <del> .to('React/Base/RCTVersion.h'); <del> <del>cat('scripts/versiontemplates/ReactNativeVersion.js.template') <del> .replace('${major}', major) <del> .replace('${minor}', minor) <del> .replace('${patch}', patch) <del> .replace('${prerelease}', prerelease !== undefined ? `'${prerelease}'` : 'null') <del> .to('Libraries/Core/ReactNativeVersion.js'); <add>fs.writeFileSync( <add> 'ReactAndroid/src/main/java/com/facebook/react/modules/systeminfo/ReactNativeVersion.java', <add> cat('scripts/versiontemplates/ReactNativeVersion.java.template') <add> .replace('${major}', major) <add> .replace('${minor}', minor) <add> .replace('${patch}', patch) <add> .replace('${prerelease}', prerelease !== undefined ? `"${prerelease}"` : 'null'), <add> 'utf-8' <add>); <add> <add>fs.writeFileSync( <add> 'React/Base/RCTVersion.h', <add> cat('scripts/versiontemplates/RCTVersion.h.template') <add> .replace('${major}', `@(${major})`) <add> .replace('${minor}', `@(${minor})`) <add> .replace('${patch}', `@(${patch})`) <add> .replace('${prerelease}', prerelease !== undefined ? `@"${prerelease}"` : '[NSNull null]'), <add> 'utf-8' <add>); <add> <add>fs.writeFileSync( <add> 'Libraries/Core/ReactNativeVersion.js', <add> cat('scripts/versiontemplates/ReactNativeVersion.js.template') <add> .replace('${major}', major) <add> .replace('${minor}', minor) <add> .replace('${patch}', patch) <add> .replace('${prerelease}', prerelease !== undefined ? `'${prerelease}'` : 'null'), <add> 'utf-8' <add>); <ide> <ide> let packageJson = JSON.parse(cat('package.json')); <ide> packageJson.version = version; <del>JSON.stringify(packageJson, null, 2).to('package.json'); <add>fs.writeFileSync('package.json', JSON.stringify(packageJson, null, 2), 'utf-8'); <ide> <ide> // - change ReactAndroid/gradle.properties <ide> if (sed('-i', /^VERSION_NAME=.*/, `VERSION_NAME=${version}`, 'ReactAndroid/gradle.properties').code) {
1
PHP
PHP
remove unused method
a1ad72fb0f24c4be6380947f7a5fb6a798c7ed1e
<ide><path>src/Routing/Router.php <ide> class Router { <ide> */ <ide> protected static $_urlFilters = []; <ide> <del>/** <del> * Sets the Routing prefixes. <del> * <del> * @return void <del> */ <del> protected static function _setPrefixes() { <del> $routing = Configure::read('Routing'); <del> if (!empty($routing['prefixes'])) { <del> static::$_prefixes = array_merge(static::$_prefixes, (array)$routing['prefixes']); <del> } <del> } <del> <ide> /** <ide> * Gets the named route patterns for use in app/Config/routes.php <ide> *
1
Python
Python
fix used_group_ids in partial_subset
1e425fe6459a39d93a9ada64278c35f7cf0eab06
<ide><path>airflow/models/dag.py <ide> def filter_task_group(group, parent_group): <ide> if isinstance(child, BaseOperator): <ide> if child.task_id in dag.task_dict: <ide> copied.children[child.task_id] = dag.task_dict[child.task_id] <add> else: <add> copied.used_group_ids.discard(child.task_id) <ide> else: <ide> filtered_child = filter_task_group(child, copied) <ide> <ide><path>tests/models/test_dag.py <ide> def test_sub_dag_updates_all_references_while_deepcopy(self): <ide> sub_dag = dag.sub_dag('t2', include_upstream=True, include_downstream=False) <ide> assert id(sub_dag.task_dict['t1'].downstream_list[0].dag) == id(sub_dag) <ide> <add> # Copied DAG should not include unused task IDs in used_group_ids <add> assert 't3' not in sub_dag._task_group.used_group_ids <add> <ide> def test_schedule_dag_no_previous_runs(self): <ide> """ <ide> Tests scheduling a dag with no previous runs
2
Text
Text
fix typo in sudoku-solver description
7defcaf58e71218507b346ba3cc69c141b3fa61a
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-projects/sudoku-solver.md <ide> Write the following tests in `tests/1_unit-tests.js`: <ide> - Logic handles an invalid region (3x3 grid) placement <ide> - Valid puzzle strings pass the solver <ide> - Invalid puzzle strings fail the solver <del>- Solver returns the the expected solution for an incomplete puzzle <add>- Solver returns the expected solution for an incomplete puzzle <ide> <ide> Write the following tests in `tests/2_functional-tests.js` <ide>
1
Javascript
Javascript
ignore socket.settimeout(infinity) (and nan)
b0950cbea282024a21c735ba20803ac8b05e0b48
<ide><path>lib/net.js <ide> Socket.prototype.listen = function() { <ide> <ide> <ide> Socket.prototype.setTimeout = function(msecs, callback) { <del> if (msecs > 0) { <add> if (msecs > 0 && !isNaN(msecs) && isFinite(msecs)) { <ide> timers.enroll(this, msecs); <ide> timers.active(this); <ide> if (callback) { <ide><path>test/simple/test-net-settimeout.js <ide> var server = net.createServer(function(c) { <ide> }); <ide> server.listen(common.PORT); <ide> <del>var socket = net.createConnection(common.PORT, 'localhost'); <del> <del>socket.setTimeout(T, function() { <del> socket.destroy(); <del> server.close(); <del> assert.ok(false); <add>var killers = [0, Infinity, NaN]; <add> <add>var left = killers.length; <add>killers.forEach(function(killer) { <add> var socket = net.createConnection(common.PORT, 'localhost'); <add> <add> socket.setTimeout(T, function() { <add> socket.destroy(); <add> if (--left === 0) server.close(); <add> assert.ok(killer !== 0); <add> clearTimeout(timeout); <add> }); <add> <add> socket.setTimeout(killer); <add> <add> var timeout = setTimeout(function() { <add> socket.destroy(); <add> if (--left === 0) server.close(); <add> assert.ok(killer === 0); <add> }, T * 2); <ide> }); <del> <del>socket.setTimeout(0); <del> <del>setTimeout(function() { <del> socket.destroy(); <del> server.close(); <del> assert.ok(true); <del>}, T * 2);
2
Java
Java
delete dead code in tests
38f6d270f8691b8026c3197a111cfede6a01379f
<ide><path>spring-web/src/test/java/org/springframework/web/filter/OncePerRequestFilterTests.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <add> <ide> package org.springframework.web.filter; <ide> <ide> import java.io.IOException; <ide> <ide> import static org.assertj.core.api.Assertions.assertThat; <ide> <del> <ide> /** <ide> * Unit tests for {@link OncePerRequestFilter}. <add> * <ide> * @author Rossen Stoyanchev <ide> * @since 5.1.9 <ide> */ <ide> private static class TestOncePerRequestFilter extends OncePerRequestFilter { <ide> private boolean didFilterNestedErrorDispatch; <ide> <ide> <del> public void setShouldNotFilter(boolean shouldNotFilter) { <del> this.shouldNotFilter = shouldNotFilter; <del> } <del> <del> public void setShouldNotFilterAsyncDispatch(boolean shouldNotFilterAsyncDispatch) { <del> this.shouldNotFilterAsyncDispatch = shouldNotFilterAsyncDispatch; <del> } <del> <ide> public void setShouldNotFilterErrorDispatch(boolean shouldNotFilterErrorDispatch) { <ide> this.shouldNotFilterErrorDispatch = shouldNotFilterErrorDispatch; <ide> } <ide> <del> <del> public boolean didFilter() { <del> return this.didFilter; <del> } <del> <del> public boolean didFilterNestedErrorDispatch() { <del> return this.didFilterNestedErrorDispatch; <del> } <del> <ide> public void reset() { <ide> this.didFilter = false; <ide> this.didFilterNestedErrorDispatch = false; <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/server/support/WebSocketHttpRequestHandlerTests.java <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <add> <ide> package org.springframework.web.socket.server.support; <ide> <ide> import java.io.IOException; <ide> import java.util.Collections; <ide> import java.util.Map; <ide> import javax.servlet.ServletException; <ide> <del>import org.junit.Before; <ide> import org.junit.Test; <ide> <ide> import org.springframework.http.server.ServerHttpRequest; <ide> <ide> /** <ide> * Unit tests for {@link WebSocketHttpRequestHandler}. <add> * <ide> * @author Rossen Stoyanchev <ide> * @since 5.1.9 <ide> */ <ide> public class WebSocketHttpRequestHandlerTests { <ide> <del> private HandshakeHandler handshakeHandler; <del> <del> private WebSocketHttpRequestHandler requestHandler; <add> private final HandshakeHandler handshakeHandler = mock(HandshakeHandler.class); <ide> <del> private MockHttpServletResponse response; <add> private final WebSocketHttpRequestHandler requestHandler = new WebSocketHttpRequestHandler(mock(WebSocketHandler.class), this.handshakeHandler); <ide> <del> <del> @Before <del> public void setUp() { <del> this.handshakeHandler = mock(HandshakeHandler.class); <del> this.requestHandler = new WebSocketHttpRequestHandler(mock(WebSocketHandler.class), this.handshakeHandler); <del> this.response = new MockHttpServletResponse(); <del> } <add> private final MockHttpServletResponse response = new MockHttpServletResponse(); <ide> <ide> <ide> @Test <ide> private static class TestInterceptor implements HandshakeInterceptor { <ide> <ide> private final boolean allowHandshake; <ide> <del> private Exception exception; <del> <del> <ide> private TestInterceptor(boolean allowHandshake) { <ide> this.allowHandshake = allowHandshake; <ide> } <ide> <ide> <del> public Exception getException() { <del> return this.exception; <del> } <del> <del> <ide> @Override <ide> public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, <ide> WebSocketHandler wsHandler, Map<String, Object> attributes) { <ide> public void afterHandshake(ServerHttpRequest request, ServerHttpResponse respons <ide> WebSocketHandler wsHandler, Exception exception) { <ide> <ide> response.getHeaders().add("exceptionHeaderName", "exceptionHeaderValue"); <del> this.exception = exception; <ide> } <ide> } <ide>
2
Javascript
Javascript
fix production tests
a1f11a4660f4f3f8b1ac09da9175390f23a168ad
<ide><path>test/integration/production/pages/about.js <add>export default () => ( <add> <div className='about-page'>About Page</div> <add>) <ide><path>test/integration/production/pages/index.js <add>import Link from 'next/link' <add> <ide> export default () => ( <del> <div>Hello World</div> <add> <div> <add> <Link href='/about'><a>About Page</a></Link> <add> <p>Hello World</p> <add> </div> <ide> ) <ide><path>test/integration/production/test/index.test.js <ide> /* global jasmine, describe, it, expect, beforeAll, afterAll */ <ide> <del>import fetch from 'node-fetch' <ide> import { join } from 'path' <ide> import { <ide> nextServer, <ide> import { <ide> stopApp, <ide> renderViaHTTP <ide> } from 'next-test-utils' <add>import webdriver from 'next-webdriver' <ide> <ide> const appDir = join(__dirname, '../') <ide> let appPort <ide> describe('Production Usage', () => { <ide> }) <ide> }) <ide> <del> describe('JSON pages', () => { <del> describe('when asked for a normal page', () => { <del> it('should serve the normal page', async () => { <del> const url = `http://localhost:${appPort}/_next/${app.renderOpts.buildId}/pages` <del> const res = await fetch(url, { compress: false }) <del> expect(res.headers.get('Content-Encoding')).toBeNull() <add> describe('With navigation', () => { <add> it('should navigate via client side', async () => { <add> const browser = await webdriver(appPort, '/') <add> const text = await browser <add> .elementByCss('a').click() <add> .waitForElementByCss('.about-page') <add> .elementByCss('div').text() <ide> <del> const page = await res.json() <del> expect(page.component).toBeDefined() <del> }) <del> }) <del> <del> describe('when asked for a page with an unknown encoding', () => { <del> it('should serve the normal page', async () => { <del> const url = `http://localhost:${appPort}/_next/${app.renderOpts.buildId}/pages` <del> const res = await fetch(url, { <del> compress: false, <del> headers: { <del> 'Accept-Encoding': 'br' <del> } <del> }) <del> expect(res.headers.get('Content-Encoding')).toBeNull() <del> <del> const page = await res.json() <del> expect(page.component).toBeDefined() <del> }) <add> expect(text).toBe('About Page') <add> browser.close() <ide> }) <ide> }) <ide> })
3
PHP
PHP
remove unused import
f05da7293b1921f40238a3e0f54c41656dfd941b
<ide><path>src/Illuminate/Foundation/Providers/FormRequestServiceProvider.php <ide> use Illuminate\Routing\Redirector; <ide> use Illuminate\Support\ServiceProvider; <ide> use Illuminate\Foundation\Http\FormRequest; <del>use Symfony\Component\HttpFoundation\Request; <ide> use Illuminate\Contracts\Validation\ValidatesWhenResolved; <ide> <ide> class FormRequestServiceProvider extends ServiceProvider
1
Text
Text
add info about setting locale folder path
6e4f4580bacf43d0c5f59bda7825928dafefb677
<ide><path>src/I18n/README.md <ide> use Cake\I18n\I18n; <ide> I18n::locale('en_US'); <ide> ``` <ide> <add>### Setting path to folder containing po files. <add> <add>```php <add>use Cake\Core\Configure; <add> <add>Configure::write('App.paths.locales', ['/path/with/trailing/slash/']); <add> <add>Please refer to the [CakePHP Manual](http://book.cakephp.org/3.0/en/core-libraries/internationalization-and-localization.html#language-files) for details <add>about expected folder structure and file naming. <add> <ide> ### Translating a Message <ide> <ide> ```php
1
Java
Java
add support for "system" stomp session
01c4e458c75bbdcff3772dce2c0fada56c8993b9
<ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/stomp/support/StompHeaderAccessor.java <ide> public class StompHeaderAccessor extends PubSubHeaderAccesssor { <ide> <ide> public static final String NACK = "nack"; <ide> <add> public static final String LOGIN = "login"; <add> <add> public static final String PASSCODE = "passcode"; <add> <ide> public static final String DESTINATION = "destination"; <ide> <ide> public static final String CONTENT_TYPE = "content-type"; <ide> public String getNack() { <ide> return getHeaderValue(NACK); <ide> } <ide> <add> public void setLogin(String login) { <add> this.headers.put(LOGIN, login); <add> } <add> <add> public String getLogin() { <add> return getHeaderValue(LOGIN); <add> } <add> <add> <add> public void setPasscode(String passcode) { <add> this.headers.put(PASSCODE, passcode); <add> } <add> <add> public String getPasscode() { <add> return getHeaderValue(PASSCODE); <add> } <add> <ide> public void setReceiptId(String receiptId) { <ide> this.headers.put(RECEIPT_ID, receiptId); <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/stomp/support/StompRelayPubSubMessageHandler.java <ide> import java.util.concurrent.ConcurrentHashMap; <ide> import java.util.concurrent.LinkedBlockingQueue; <ide> <add>import org.springframework.context.SmartLifecycle; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.messaging.Message; <ide> import org.springframework.messaging.MessageChannel; <ide> * @since 4.0 <ide> */ <ide> @SuppressWarnings("rawtypes") <del>public class StompRelayPubSubMessageHandler<M extends Message> extends AbstractPubSubMessageHandler<M> { <add>public class StompRelayPubSubMessageHandler<M extends Message> extends AbstractPubSubMessageHandler<M> <add> implements SmartLifecycle { <add> <add> private static final String STOMP_RELAY_SYSTEM_SESSION_ID = "stompRelaySystemSessionId"; <ide> <ide> private MessageChannel<M> clientChannel; <ide> <ide> private final StompMessageConverter<M> stompMessageConverter = new StompMessageConverter<M>(); <ide> <ide> private MessageConverter payloadConverter; <ide> <del> private final TcpClient<String, String> tcpClient; <add> private TcpClient<String, String> tcpClient; <ide> <ide> private final Map<String, RelaySession> relaySessions = new ConcurrentHashMap<String, RelaySession>(); <ide> <add> private Object lifecycleMonitor = new Object(); <add> <add> private boolean running = false; <add> <ide> <ide> /** <ide> * @param clientChannel a channel for sending messages from the remote message broker <ide> * back to clients <ide> */ <ide> public StompRelayPubSubMessageHandler(PubSubChannelRegistry<M, ?> registry) { <del> <ide> Assert.notNull(registry, "registry is required"); <ide> this.clientChannel = registry.getClientOutputChannel(); <del> <del> this.tcpClient = new TcpClient.Spec<String, String>(NettyTcpClient.class) <del> .using(new Environment()) <del> .codec(new DelimitedCodec<String, String>((byte) 0, true, StandardCodecs.STRING_CODEC)) <del> .connect("127.0.0.1", 61613) <del> .get(); <del> <ide> this.payloadConverter = new CompositeMessageConverter(null); <ide> } <ide> <ide> protected Collection<MessageType> getSupportedMessageTypes() { <ide> return null; <ide> } <ide> <add> @Override <add> public boolean isAutoStartup() { <add> return true; <add> } <add> <add> @Override <add> public int getPhase() { <add> return Integer.MAX_VALUE; <add> } <add> <add> @Override <add> public boolean isRunning() { <add> synchronized (this.lifecycleMonitor) { <add> return this.running; <add> } <add> } <add> <add> @Override <add> public void start() { <add> synchronized (this.lifecycleMonitor) { <add> <add> // TODO: make this configurable <add> <add> this.tcpClient = new TcpClient.Spec<String, String>(NettyTcpClient.class) <add> .using(new Environment()) <add> .codec(new DelimitedCodec<String, String>((byte) 0, true, StandardCodecs.STRING_CODEC)) <add> .connect("127.0.0.1", 61613) <add> .get(); <add> <add> StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECT); <add> headers.setAcceptVersion("1.1,1.2"); <add> headers.setLogin("guest"); <add> headers.setPasscode("guest"); <add> headers.setHeartbeat(0, 0); <add> @SuppressWarnings("unchecked") <add> M message = (M) MessageBuilder.withPayload(new byte[0]).copyHeaders(headers.toStompMessageHeaders()).build(); <add> <add> RelaySession session = new RelaySession(message, headers) { <add> @Override <add> protected void sendMessageToClient(M message) { <add> // TODO: check for ERROR frame (reconnect?) <add> } <add> }; <add> this.relaySessions.put(STOMP_RELAY_SYSTEM_SESSION_ID, session); <add> <add> this.running = true; <add> } <add> } <add> <add> @Override <add> public void stop() { <add> synchronized (this.lifecycleMonitor) { <add> this.running = false; <add> this.tcpClient.close(); <add> } <add> } <add> <add> @Override <add> public void stop(Runnable callback) { <add> synchronized (this.lifecycleMonitor) { <add> stop(); <add> callback.run(); <add> } <add> } <add> <ide> @Override <ide> public void handleConnect(M message) { <ide> StompHeaderAccessor stompHeaders = StompHeaderAccessor.wrap(message); <ide> private void forwardMessage(M message, StompCommand command) { <ide> StompHeaderAccessor headers = StompHeaderAccessor.wrap(message); <ide> headers.setStompCommandIfNotSet(command); <ide> <add> if (headers.getSessionId() == null && (StompCommand.SEND.equals(command))) { <add> <add> } <add> <ide> String sessionId = headers.getSessionId(); <ide> if (sessionId == null) { <del> logger.error("No sessionId in message " + message); <del> return; <add> if (StompCommand.SEND.equals(command)) { <add> sessionId = STOMP_RELAY_SYSTEM_SESSION_ID; <add> } <add> else { <add> logger.error("No sessionId in message " + message); <add> return; <add> } <ide> } <ide> <ide> RelaySession session = this.relaySessions.get(sessionId); <ide> private void forwardMessage(M message, StompCommand command) { <ide> } <ide> <ide> <del> private final class RelaySession { <add> private class RelaySession { <ide> <ide> private final String sessionId; <ide> <ide> private void readStompFrame(String stompFrame) { <ide> } <ide> relaySessions.remove(this.sessionId); <ide> } <add> sendMessageToClient(message); <add> } <add> <add> protected void sendMessageToClient(M message) { <ide> clientChannel.send(message); <ide> } <ide> <ide> private void sendError(String sessionId, String errorText) { <ide> headers.setMessage(errorText); <ide> @SuppressWarnings("unchecked") <ide> M errorMessage = (M) MessageBuilder.withPayload(new byte[0]).copyHeaders(headers.toHeaders()).build(); <del> clientChannel.send(errorMessage); <add> sendMessageToClient(errorMessage); <ide> } <ide> <ide> public void forward(M message, StompHeaderAccessor headers) { <ide> private boolean forwardInternal(Message<?> message, StompHeaderAccessor headers, <ide> return true; <ide> } <ide> } <add> <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/support/PubSubHeaderAccesssor.java <ide> private Object getHeaderValue(String headerName) { <ide> if (this.headers.get(headerName) != null) { <ide> return this.headers.get(headerName); <ide> } <del> else if (this.originalHeaders.get(headerName) != null) { <add> else if ((this.originalHeaders != null) && (this.originalHeaders.get(headerName) != null)) { <ide> return this.originalHeaders.get(headerName); <ide> } <ide> return null;
3
Javascript
Javascript
improve testing for uniquely named initializers
bcbec4f47a10112829e3183cb562f5b9d71e5f20
<ide><path>packages/ember-application/tests/system/engine_initializers_test.js <ide> QUnit.test('initializers are concatenated', function() { <ide> }); <ide> <ide> QUnit.test('initializers are per-engine', function() { <del> expect(0); <add> expect(2); <add> <ide> let FirstEngine = Engine.extend(); <add> <ide> FirstEngine.initializer({ <del> name: 'shouldNotCollide', <add> name: 'abc', <ide> initialize(engine) {} <ide> }); <ide> <add> throws(function() { <add> FirstEngine.initializer({ <add> name: 'abc', <add> initialize(engine) {} <add> }); <add> }, Error, /Assertion Failed: The initializer 'abc' has already been registered'/); <add> <ide> let SecondEngine = Engine.extend(); <del> SecondEngine.initializer({ <del> name: 'shouldNotCollide', <add> SecondEngine.instanceInitializer({ <add> name: 'abc', <ide> initialize(engine) {} <ide> }); <add> <add> ok(true, 'Two engines can have initializers named the same.'); <ide> }); <ide> <ide> QUnit.test('initializers are executed in their own context', function() { <ide><path>packages/ember-application/tests/system/engine_instance_initializers_test.js <ide> QUnit.test('initializers are concatenated', function() { <ide> }); <ide> <ide> QUnit.test('initializers are per-engine', function() { <del> expect(0); <add> expect(2); <add> <ide> let FirstEngine = Engine.extend(); <add> <ide> FirstEngine.instanceInitializer({ <del> name: 'shouldNotCollide', <add> name: 'abc', <ide> initialize(engine) {} <ide> }); <ide> <add> throws(function() { <add> FirstEngine.instanceInitializer({ <add> name: 'abc', <add> initialize(engine) {} <add> }); <add> }, Error, /Assertion Failed: The instance initializer 'abc' has already been registered'/); <add> <ide> let SecondEngine = Engine.extend(); <ide> SecondEngine.instanceInitializer({ <del> name: 'shouldNotCollide', <add> name: 'abc', <ide> initialize(engine) {} <ide> }); <add> <add> ok(true, 'Two engines can have initializers named the same.'); <ide> }); <ide> <ide> QUnit.test('initializers are executed in their own context', function() { <ide><path>packages/ember-application/tests/system/initializers_test.js <ide> QUnit.test('initializers are concatenated', function() { <ide> }); <ide> <ide> QUnit.test('initializers are per-app', function() { <del> expect(0); <del> var FirstApp = Application.extend(); <add> expect(2); <add> <add> let FirstApp = Application.extend(); <add> <ide> FirstApp.initializer({ <del> name: 'shouldNotCollide', <del> initialize(application) {} <add> name: 'abc', <add> initialize(app) {} <ide> }); <ide> <del> var SecondApp = Application.extend(); <del> SecondApp.initializer({ <del> name: 'shouldNotCollide', <del> initialize(application) {} <add> throws(function() { <add> FirstApp.initializer({ <add> name: 'abc', <add> initialize(app) {} <add> }); <add> }, Error, /Assertion Failed: The initializer 'abc' has already been registered'/); <add> <add> let SecondApp = Application.extend(); <add> SecondApp.instanceInitializer({ <add> name: 'abc', <add> initialize(app) {} <ide> }); <add> <add> ok(true, 'Two apps can have initializers named the same.'); <ide> }); <ide> <ide> QUnit.test('initializers are executed in their own context', function() { <ide><path>packages/ember-application/tests/system/instance_initializers_test.js <ide> QUnit.test('initializers are concatenated', function() { <ide> }); <ide> <ide> QUnit.test('initializers are per-app', function() { <del> expect(0); <del> var FirstApp = Application.extend(); <add> expect(2); <add> <add> let FirstApp = Application.extend(); <add> <ide> FirstApp.instanceInitializer({ <del> name: 'shouldNotCollide', <del> initialize(registry) {} <add> name: 'abc', <add> initialize(app) {} <ide> }); <ide> <del> var SecondApp = Application.extend(); <add> throws(function() { <add> FirstApp.instanceInitializer({ <add> name: 'abc', <add> initialize(app) {} <add> }); <add> }, Error, /Assertion Failed: The instance initializer 'abc' has already been registered'/); <add> <add> let SecondApp = Application.extend(); <ide> SecondApp.instanceInitializer({ <del> name: 'shouldNotCollide', <del> initialize(registry) {} <add> name: 'abc', <add> initialize(app) {} <ide> }); <add> <add> ok(true, 'Two apps can have initializers named the same.'); <ide> }); <ide> <ide> QUnit.test('initializers are run before ready hook', function() {
4
Java
Java
fix compiler warning
8d8d47fb4e36a667c02f79c1936c882b60c4584e
<ide><path>spring-context-support/src/test/java/org/springframework/cache/jcache/support/TestableCacheKeyGenerator.java <ide> public GeneratedCacheKey generateCacheKey(CacheKeyInvocationContext<? extends An <ide> } <ide> <ide> <add> @SuppressWarnings("serial") <ide> private static class SimpleGeneratedCacheKey extends SimpleKey implements GeneratedCacheKey { <ide> <ide> public SimpleGeneratedCacheKey(Object... elements) {
1
Javascript
Javascript
remove unused variables
1de089bdbbff3dde332034e4e7c9d5fa4ac1569b
<ide><path>packages/container/lib/main.js <ide> define("container", <ide> [], <ide> function() { <ide> <del> var objectCreate = Object.create || function(parent) { <del> function F() {} <del> F.prototype = parent; <del> return new F(); <del> }; <del> <ide> function InheritingDict(parent) { <ide> this.parent = parent; <ide> this.dict = {}; <ide><path>packages/ember-handlebars/lib/loader.js <ide> Ember.Handlebars.bootstrap = function(ctx) { <ide> Ember.$(selectors, ctx) <ide> .each(function() { <ide> // Get a reference to the script tag <del> var script = Ember.$(this), <del> type = script.attr('type'); <add> var script = Ember.$(this); <ide> <ide> var compile = (script.attr('type') === 'text/x-raw-handlebars') ? <ide> Ember.$.proxy(Handlebars.compile, Handlebars) :
2
PHP
PHP
use new concern
264845d0a480b943db3cc40f5a252b39c694a20a
<ide><path>src/Illuminate/View/Compilers/BladeCompiler.php <ide> class BladeCompiler extends Compiler implements CompilerInterface <ide> Concerns\CompilesEchos, <ide> Concerns\CompilesIncludes, <ide> Concerns\CompilesInjections, <add> Concerns\CompilesJson, <ide> Concerns\CompilesLayouts, <ide> Concerns\CompilesLoops, <ide> Concerns\CompilesRawPhp,
1
PHP
PHP
replace duplicated method with result
7d64dee369fcfd9e576ced09a7c666e9827b10c1
<ide><path>src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php <ide> protected function loadConfigurationFiles(Application $app, RepositoryContract $ <ide> throw new Exception('Unable to load the "app" configuration file.'); <ide> } <ide> <del> foreach ($this->getConfigurationFiles($app) as $key => $path) { <add> foreach ($files as $key => $path) { <ide> $repository->set($key, require $path); <ide> } <ide> }
1
PHP
PHP
allow orderbyraw on union
b6c821f23b006042f2f966a0701013b88c874187
<ide><path>src/Illuminate/Database/Query/Builder.php <ide> public function oldest($column = 'created_at') <ide> */ <ide> public function orderByRaw($sql, $bindings = []) <ide> { <add> $property = $this->unions ? 'unionOrders' : 'orders'; <add> <ide> $type = 'raw'; <ide> <del> $this->orders[] = compact('type', 'sql'); <add> $this->{$property}[] = compact('type', 'sql'); <ide> <ide> $this->addBinding($bindings, 'order'); <ide>
1
Go
Go
nullify container rwlayer upon release
e9b9e4ace294230c6b8eb010eda564a2541c4564
<ide><path>daemon/delete.go <ide> func (daemon *Daemon) cleanupContainer(container *container.Container, forceRemo <ide> container.SetRemovalError(e) <ide> return e <ide> } <add> container.RWLayer = nil <ide> } <ide> <ide> if err := system.EnsureRemoveAll(container.Root); err != nil {
1
Javascript
Javascript
serialize bigint64array and biguint64array
1643b9ed1943d2854e3d5c10a3e07eafbe75f051
<ide><path>lib/v8.js <ide> <ide> const { <ide> Array, <del> ArrayBuffer, <del> ArrayPrototypeForEach, <del> ArrayPrototypePush, <add> BigInt64Array, <add> BigUint64Array, <ide> DataView, <ide> Error, <ide> Float32Array, <ide> const { <ide> Int32Array, <ide> Int8Array, <ide> ObjectPrototypeToString, <del> SafeMap, <ide> Uint16Array, <ide> Uint32Array, <ide> Uint8Array, <ide> Deserializer.prototype.readRawBytes = function readRawBytes(length) { <ide> length); <ide> }; <ide> <del>/* Keep track of how to handle different ArrayBufferViews. <del> * The default Serializer for Node does not use the V8 methods for serializing <del> * those objects because Node's `Buffer` objects use pooled allocation in many <del> * cases, and their underlying `ArrayBuffer`s would show up in the <del> * serialization. Because a) those may contain sensitive data and the user <del> * may not be aware of that and b) they are often much larger than the `Buffer` <del> * itself, custom serialization is applied. */ <del>const arrayBufferViewTypes = [Int8Array, Uint8Array, Uint8ClampedArray, <del> Int16Array, Uint16Array, Int32Array, Uint32Array, <del> Float32Array, Float64Array, DataView]; <del> <del>const arrayBufferViewTypeToIndex = new SafeMap(); <del> <del>{ <del> const dummy = new ArrayBuffer(); <del> ArrayPrototypeForEach(arrayBufferViewTypes, (ctor, i) => { <del> const tag = ObjectPrototypeToString(new ctor(dummy)); <del> arrayBufferViewTypeToIndex.set(tag, i); <del> }); <add>function arrayBufferViewTypeToIndex(abView) { <add> const type = ObjectPrototypeToString(abView); <add> if (type === '[object Int8Array]') return 0; <add> if (type === '[object Uint8Array]') return 1; <add> if (type === '[object Uint8ClampedArray]') return 2; <add> if (type === '[object Int16Array]') return 3; <add> if (type === '[object Uint16Array]') return 4; <add> if (type === '[object Int32Array]') return 5; <add> if (type === '[object Uint32Array]') return 6; <add> if (type === '[object Float32Array]') return 7; <add> if (type === '[object Float64Array]') return 8; <add> if (type === '[object DataView]') return 9; <add> // Index 10 is FastBuffer. <add> if (type === '[object BigInt64Array]') return 11; <add> if (type === '[object BigUint64Array]') return 12; <add> return -1; <ide> } <ide> <del>const bufferConstructorIndex = <del> ArrayPrototypePush(arrayBufferViewTypes, FastBuffer) - 1; <add>function arrayBufferViewIndexToType(index) { <add> if (index === 0) return Int8Array; <add> if (index === 1) return Uint8Array; <add> if (index === 2) return Uint8ClampedArray; <add> if (index === 3) return Int16Array; <add> if (index === 4) return Uint16Array; <add> if (index === 5) return Int32Array; <add> if (index === 6) return Uint32Array; <add> if (index === 7) return Float32Array; <add> if (index === 8) return Float64Array; <add> if (index === 9) return DataView; <add> if (index === 10) return FastBuffer; <add> if (index === 11) return BigInt64Array; <add> if (index === 12) return BigUint64Array; <add> return undefined; <add>} <ide> <ide> class DefaultSerializer extends Serializer { <ide> constructor() { <ide> class DefaultSerializer extends Serializer { <ide> * @returns {void} <ide> */ <ide> _writeHostObject(abView) { <del> let i = 0; <del> if (abView.constructor === Buffer) { <del> i = bufferConstructorIndex; <del> } else { <del> const tag = ObjectPrototypeToString(abView); <del> i = arrayBufferViewTypeToIndex.get(tag); <del> <del> if (i === undefined) { <add> // Keep track of how to handle different ArrayBufferViews. The default <add> // Serializer for Node does not use the V8 methods for serializing those <add> // objects because Node's `Buffer` objects use pooled allocation in many <add> // cases, and their underlying `ArrayBuffer`s would show up in the <add> // serialization. Because a) those may contain sensitive data and the user <add> // may not be aware of that and b) they are often much larger than the <add> // `Buffer` itself, custom serialization is applied. <add> let i = 10; // FastBuffer <add> if (abView.constructor !== Buffer) { <add> i = arrayBufferViewTypeToIndex(abView); <add> if (i === -1) { <ide> throw new this._getDataCloneError( <ide> `Unserializable host object: ${inspect(abView)}`); <ide> } <ide> class DefaultDeserializer extends Deserializer { <ide> */ <ide> _readHostObject() { <ide> const typeIndex = this.readUint32(); <del> const ctor = arrayBufferViewTypes[typeIndex]; <add> const ctor = arrayBufferViewIndexToType(typeIndex); <ide> const byteLength = this.readUint32(); <ide> const byteOffset = this._readRawBytes(byteLength); <ide> const BYTES_PER_ELEMENT = ctor.BYTES_PER_ELEMENT || 1; <ide><path>test/parallel/test-v8-serdes.js <ide> circular.circular = circular; <ide> const objects = [ <ide> { foo: 'bar' }, <ide> { bar: 'baz' }, <add> new Int8Array([1, 2, 3, 4]), <ide> new Uint8Array([1, 2, 3, 4]), <add> new Int16Array([1, 2, 3, 4]), <add> new Uint16Array([1, 2, 3, 4]), <add> new Int32Array([1, 2, 3, 4]), <ide> new Uint32Array([1, 2, 3, 4]), <add> new Float32Array([1, 2, 3, 4]), <add> new Float64Array([1, 2, 3, 4]), <ide> new DataView(new ArrayBuffer(42)), <ide> Buffer.from([1, 2, 3, 4]), <add> new BigInt64Array([42n]), <add> new BigUint64Array([42n]), <ide> undefined, <ide> null, <ide> 42,
2
Text
Text
add faq section to built-in css support
a89afc2ec6f83cb6d7d7a6e09699e311ddafdb3f
<ide><path>docs/basic-features/built-in-css-support.md <ide> In development, expressing stylesheets this way allows your styles to be hot rel <ide> <ide> In production, all CSS files will be automatically concatenated into a single minified `.css` file. <ide> <add>### Import styles from `node_modules` <add> <add>If you’d like to import CSS files from `node_modules`, you must do so inside `pages/_app.js`. <add> <ide> ## Adding Component-Level CSS <ide> <ide> Next.js supports [CSS Modules](https://github.com/css-modules/css-modules) using the `[name].module.css` file naming convention. <ide> export default HelloWorld <ide> <ide> Please see the [styled-jsx documentation](https://github.com/zeit/styled-jsx) for more examples. <ide> <add>## FAQ <add> <add>### Does it work with JavaScript disabled? <add> <add>Yes, if you disable JavaScript the CSS will still be loaded in the production build (`next start`). During development, we require JavaScript to be enabled to provide the best developer experience with [Fast Refresh](https://nextjs.org/blog/next-9-4#fast-refresh). <add> <ide> ## Related <ide> <ide> For more information on what to do next, we recommend the following sections:
1
Javascript
Javascript
handle export mangling in concatenated modules
277d4b1b67331ae81ba4e0c7217d43e6e37184b0
<ide><path>lib/optimize/ConcatenatedModule.js <ide> const getFinalBinding = ( <ide> const exportId = exportName[0]; <ide> const directExport = info.exportMap.get(exportId); <ide> if (directExport) { <add> const usedName = /** @type {string[]} */ (exportsInfo.getUsedName( <add> exportName, <add> runtime <add> )); <ide> return { <ide> info, <ide> name: directExport, <del> ids: exportName.slice(1), <add> ids: usedName.slice(1), <ide> exportName <ide> }; <ide> } <ide> const getFinalBinding = ( <ide> ); <ide> } <ide> if (info.namespaceExportSymbol) { <add> const usedName = /** @type {string[]} */ (exportsInfo.getUsedName( <add> exportName, <add> runtime <add> )); <ide> return { <ide> info, <ide> rawName: info.namespaceObjectName, <del> ids: exportName, <add> ids: usedName, <ide> exportName <ide> }; <ide> }
1
Text
Text
fix changelog [ci skip]
331a0684aa8107a77613c8e1a36202a3cc287f62
<ide><path>activerecord/CHANGELOG.md <ide> <ide> * Make schema cache methods return consistent results. <ide> <del> Previously the schema cache methods `primary_keys`, `columns, `columns_hash`, and `indexes` <add> Previously the schema cache methods `primary_keys`, `columns`, `columns_hash`, and `indexes` <ide> would behave differently than one another when a table didn't exist and differently across <ide> database adapters. This change unifies the behavior so each method behaves the same regardless <ide> of adapter.
1
Javascript
Javascript
convert `src/core/chunked_stream.js` to es6 syntax
47344197f4224e4d1036365afbe53f82ac6c0fdd
<ide><path>src/core/chunked_stream.js <ide> import { <ide> MissingDataException <ide> } from '../shared/util'; <ide> <del>var ChunkedStream = (function ChunkedStreamClosure() { <del> function ChunkedStream(length, chunkSize, manager) { <add>class ChunkedStream { <add> constructor(length, chunkSize, manager) { <ide> this.bytes = new Uint8Array(length); <ide> this.start = 0; <ide> this.pos = 0; <ide> var ChunkedStream = (function ChunkedStreamClosure() { <ide> this.numChunks = Math.ceil(length / chunkSize); <ide> this.manager = manager; <ide> this.progressiveDataLength = 0; <del> this.lastSuccessfulEnsureByteChunk = -1; // a single-entry cache <add> this.lastSuccessfulEnsureByteChunk = -1; // Single-entry cache <ide> } <ide> <del> // required methods for a stream. if a particular stream does not <del> // implement these, an error should be thrown <del> ChunkedStream.prototype = { <del> <del> getMissingChunks: function ChunkedStream_getMissingChunks() { <del> var chunks = []; <del> for (var chunk = 0, n = this.numChunks; chunk < n; ++chunk) { <del> if (!this.loadedChunks[chunk]) { <del> chunks.push(chunk); <del> } <add> // If a particular stream does not implement one or more of these methods, <add> // an error should be thrown. <add> getMissingChunks() { <add> const chunks = []; <add> for (let chunk = 0, n = this.numChunks; chunk < n; ++chunk) { <add> if (!this.loadedChunks[chunk]) { <add> chunks.push(chunk); <ide> } <del> return chunks; <del> }, <add> } <add> return chunks; <add> } <ide> <del> getBaseStreams: function ChunkedStream_getBaseStreams() { <del> return [this]; <del> }, <add> getBaseStreams() { <add> return [this]; <add> } <ide> <del> allChunksLoaded: function ChunkedStream_allChunksLoaded() { <del> return this.numChunksLoaded === this.numChunks; <del> }, <add> allChunksLoaded() { <add> return this.numChunksLoaded === this.numChunks; <add> } <ide> <del> onReceiveData: function ChunkedStream_onReceiveData(begin, chunk) { <del> var end = begin + chunk.byteLength; <add> onReceiveData(begin, chunk) { <add> const chunkSize = this.chunkSize; <add> if (begin % chunkSize !== 0) { <add> throw new Error(`Bad begin offset: ${begin}`); <add> } <add> <add> // Using `this.length` is inaccurate here since `this.start` can be moved <add> // (see the `moveStart` method). <add> const end = begin + chunk.byteLength; <add> if (end % chunkSize !== 0 && end !== this.bytes.length) { <add> throw new Error(`Bad end offset: ${end}`); <add> } <add> <add> this.bytes.set(new Uint8Array(chunk), begin); <add> const beginChunk = Math.floor(begin / chunkSize); <add> const endChunk = Math.floor((end - 1) / chunkSize) + 1; <add> <add> for (let curChunk = beginChunk; curChunk < endChunk; ++curChunk) { <add> if (!this.loadedChunks[curChunk]) { <add> this.loadedChunks[curChunk] = true; <add> ++this.numChunksLoaded; <add> } <add> } <add> } <ide> <del> if (begin % this.chunkSize !== 0) { <del> throw new Error(`Bad begin offset: ${begin}`); <del> } <del> // Using this.length is inaccurate here since this.start can be moved <del> // See ChunkedStream.moveStart() <del> var length = this.bytes.length; <del> if (end % this.chunkSize !== 0 && end !== length) { <del> throw new Error(`Bad end offset: ${end}`); <del> } <add> onReceiveProgressiveData(data) { <add> let position = this.progressiveDataLength; <add> const beginChunk = Math.floor(position / this.chunkSize); <ide> <del> this.bytes.set(new Uint8Array(chunk), begin); <del> var chunkSize = this.chunkSize; <del> var beginChunk = Math.floor(begin / chunkSize); <del> var endChunk = Math.floor((end - 1) / chunkSize) + 1; <del> var curChunk; <add> this.bytes.set(new Uint8Array(data), position); <add> position += data.byteLength; <add> this.progressiveDataLength = position; <add> const endChunk = position >= this.end ? this.numChunks : <add> Math.floor(position / this.chunkSize); <ide> <del> for (curChunk = beginChunk; curChunk < endChunk; ++curChunk) { <del> if (!this.loadedChunks[curChunk]) { <del> this.loadedChunks[curChunk] = true; <del> ++this.numChunksLoaded; <del> } <add> for (let curChunk = beginChunk; curChunk < endChunk; ++curChunk) { <add> if (!this.loadedChunks[curChunk]) { <add> this.loadedChunks[curChunk] = true; <add> ++this.numChunksLoaded; <ide> } <del> }, <del> <del> onReceiveProgressiveData: <del> function ChunkedStream_onReceiveProgressiveData(data) { <del> var position = this.progressiveDataLength; <del> var beginChunk = Math.floor(position / this.chunkSize); <add> } <add> } <ide> <del> this.bytes.set(new Uint8Array(data), position); <del> position += data.byteLength; <del> this.progressiveDataLength = position; <del> var endChunk = position >= this.end ? this.numChunks : <del> Math.floor(position / this.chunkSize); <del> var curChunk; <del> for (curChunk = beginChunk; curChunk < endChunk; ++curChunk) { <del> if (!this.loadedChunks[curChunk]) { <del> this.loadedChunks[curChunk] = true; <del> ++this.numChunksLoaded; <del> } <del> } <del> }, <add> ensureByte(pos) { <add> const chunk = Math.floor(pos / this.chunkSize); <add> if (chunk === this.lastSuccessfulEnsureByteChunk) { <add> return; <add> } <ide> <del> ensureByte: function ChunkedStream_ensureByte(pos) { <del> var chunk = Math.floor(pos / this.chunkSize); <del> if (chunk === this.lastSuccessfulEnsureByteChunk) { <del> return; <del> } <add> if (!this.loadedChunks[chunk]) { <add> throw new MissingDataException(pos, pos + 1); <add> } <add> this.lastSuccessfulEnsureByteChunk = chunk; <add> } <ide> <add> ensureRange(begin, end) { <add> if (begin >= end) { <add> return; <add> } <add> if (end <= this.progressiveDataLength) { <add> return; <add> } <add> <add> const chunkSize = this.chunkSize; <add> const beginChunk = Math.floor(begin / chunkSize); <add> const endChunk = Math.floor((end - 1) / chunkSize) + 1; <add> for (let chunk = beginChunk; chunk < endChunk; ++chunk) { <ide> if (!this.loadedChunks[chunk]) { <del> throw new MissingDataException(pos, pos + 1); <del> } <del> this.lastSuccessfulEnsureByteChunk = chunk; <del> }, <del> <del> ensureRange: function ChunkedStream_ensureRange(begin, end) { <del> if (begin >= end) { <del> return; <add> throw new MissingDataException(begin, end); <ide> } <add> } <add> } <ide> <del> if (end <= this.progressiveDataLength) { <del> return; <add> nextEmptyChunk(beginChunk) { <add> const numChunks = this.numChunks; <add> for (let i = 0; i < numChunks; ++i) { <add> const chunk = (beginChunk + i) % numChunks; // Wrap around to beginning. <add> if (!this.loadedChunks[chunk]) { <add> return chunk; <ide> } <add> } <add> return null; <add> } <ide> <del> var chunkSize = this.chunkSize; <del> var beginChunk = Math.floor(begin / chunkSize); <del> var endChunk = Math.floor((end - 1) / chunkSize) + 1; <del> for (var chunk = beginChunk; chunk < endChunk; ++chunk) { <del> if (!this.loadedChunks[chunk]) { <del> throw new MissingDataException(begin, end); <del> } <del> } <del> }, <add> hasChunk(chunk) { <add> return !!this.loadedChunks[chunk]; <add> } <ide> <del> nextEmptyChunk: function ChunkedStream_nextEmptyChunk(beginChunk) { <del> var chunk, numChunks = this.numChunks; <del> for (var i = 0; i < numChunks; ++i) { <del> chunk = (beginChunk + i) % numChunks; // Wrap around to beginning <del> if (!this.loadedChunks[chunk]) { <del> return chunk; <del> } <del> } <del> return null; <del> }, <add> get length() { <add> return this.end - this.start; <add> } <ide> <del> hasChunk: function ChunkedStream_hasChunk(chunk) { <del> return !!this.loadedChunks[chunk]; <del> }, <add> get isEmpty() { <add> return this.length === 0; <add> } <ide> <del> get length() { <del> return this.end - this.start; <del> }, <add> getByte() { <add> const pos = this.pos; <add> if (pos >= this.end) { <add> return -1; <add> } <add> this.ensureByte(pos); <add> return this.bytes[this.pos++]; <add> } <ide> <del> get isEmpty() { <del> return this.length === 0; <del> }, <add> getUint16() { <add> const b0 = this.getByte(); <add> const b1 = this.getByte(); <add> if (b0 === -1 || b1 === -1) { <add> return -1; <add> } <add> return (b0 << 8) + b1; <add> } <ide> <del> getByte: function ChunkedStream_getByte() { <del> var pos = this.pos; <del> if (pos >= this.end) { <del> return -1; <del> } <del> this.ensureByte(pos); <del> return this.bytes[this.pos++]; <del> }, <del> <del> getUint16: function ChunkedStream_getUint16() { <del> var b0 = this.getByte(); <del> var b1 = this.getByte(); <del> if (b0 === -1 || b1 === -1) { <del> return -1; <del> } <del> return (b0 << 8) + b1; <del> }, <del> <del> getInt32: function ChunkedStream_getInt32() { <del> var b0 = this.getByte(); <del> var b1 = this.getByte(); <del> var b2 = this.getByte(); <del> var b3 = this.getByte(); <del> return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3; <del> }, <del> <del> // Returns subarray of original buffer, should only be read. <del> getBytes(length, forceClamped = false) { <del> var bytes = this.bytes; <del> var pos = this.pos; <del> var strEnd = this.end; <del> <del> if (!length) { <del> this.ensureRange(pos, strEnd); <del> let subarray = bytes.subarray(pos, strEnd); <del> // `this.bytes` is always a `Uint8Array` here. <del> return (forceClamped ? new Uint8ClampedArray(subarray) : subarray); <del> } <add> getInt32() { <add> const b0 = this.getByte(); <add> const b1 = this.getByte(); <add> const b2 = this.getByte(); <add> const b3 = this.getByte(); <add> return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3; <add> } <ide> <del> var end = pos + length; <del> if (end > strEnd) { <del> end = strEnd; <del> } <del> this.ensureRange(pos, end); <add> // Returns subarray of original buffer, should only be read. <add> getBytes(length, forceClamped = false) { <add> const bytes = this.bytes; <add> const pos = this.pos; <add> const strEnd = this.end; <ide> <del> this.pos = end; <del> let subarray = bytes.subarray(pos, end); <add> if (!length) { <add> this.ensureRange(pos, strEnd); <add> const subarray = bytes.subarray(pos, strEnd); <ide> // `this.bytes` is always a `Uint8Array` here. <ide> return (forceClamped ? new Uint8ClampedArray(subarray) : subarray); <del> }, <del> <del> peekByte: function ChunkedStream_peekByte() { <del> var peekedByte = this.getByte(); <del> this.pos--; <del> return peekedByte; <del> }, <del> <del> peekBytes(length, forceClamped = false) { <del> var bytes = this.getBytes(length, forceClamped); <del> this.pos -= bytes.length; <del> return bytes; <del> }, <del> <del> getByteRange: function ChunkedStream_getBytes(begin, end) { <del> this.ensureRange(begin, end); <del> return this.bytes.subarray(begin, end); <del> }, <del> <del> skip: function ChunkedStream_skip(n) { <del> if (!n) { <del> n = 1; <del> } <del> this.pos += n; <del> }, <del> <del> reset: function ChunkedStream_reset() { <del> this.pos = this.start; <del> }, <del> <del> moveStart: function ChunkedStream_moveStart() { <del> this.start = this.pos; <del> }, <del> <del> makeSubStream: function ChunkedStream_makeSubStream(start, length, dict) { <del> this.ensureRange(start, start + length); <del> <del> function ChunkedStreamSubstream() {} <del> ChunkedStreamSubstream.prototype = Object.create(this); <del> ChunkedStreamSubstream.prototype.getMissingChunks = function() { <del> var chunkSize = this.chunkSize; <del> var beginChunk = Math.floor(this.start / chunkSize); <del> var endChunk = Math.floor((this.end - 1) / chunkSize) + 1; <del> var missingChunks = []; <del> for (var chunk = beginChunk; chunk < endChunk; ++chunk) { <del> if (!this.loadedChunks[chunk]) { <del> missingChunks.push(chunk); <del> } <add> } <add> <add> let end = pos + length; <add> if (end > strEnd) { <add> end = strEnd; <add> } <add> this.ensureRange(pos, end); <add> <add> this.pos = end; <add> const subarray = bytes.subarray(pos, end); <add> // `this.bytes` is always a `Uint8Array` here. <add> return (forceClamped ? new Uint8ClampedArray(subarray) : subarray); <add> } <add> <add> peekByte() { <add> const peekedByte = this.getByte(); <add> this.pos--; <add> return peekedByte; <add> } <add> <add> peekBytes(length, forceClamped = false) { <add> const bytes = this.getBytes(length, forceClamped); <add> this.pos -= bytes.length; <add> return bytes; <add> } <add> <add> getByteRange(begin, end) { <add> this.ensureRange(begin, end); <add> return this.bytes.subarray(begin, end); <add> } <add> <add> skip(n) { <add> if (!n) { <add> n = 1; <add> } <add> this.pos += n; <add> } <add> <add> reset() { <add> this.pos = this.start; <add> } <add> <add> moveStart() { <add> this.start = this.pos; <add> } <add> <add> makeSubStream(start, length, dict) { <add> this.ensureRange(start, start + length); <add> <add> function ChunkedStreamSubstream() {} <add> ChunkedStreamSubstream.prototype = Object.create(this); <add> ChunkedStreamSubstream.prototype.getMissingChunks = function() { <add> const chunkSize = this.chunkSize; <add> const beginChunk = Math.floor(this.start / chunkSize); <add> const endChunk = Math.floor((this.end - 1) / chunkSize) + 1; <add> const missingChunks = []; <add> for (let chunk = beginChunk; chunk < endChunk; ++chunk) { <add> if (!this.loadedChunks[chunk]) { <add> missingChunks.push(chunk); <ide> } <del> return missingChunks; <del> }; <del> var subStream = new ChunkedStreamSubstream(); <del> subStream.pos = subStream.start = start; <del> subStream.end = start + length || this.end; <del> subStream.dict = dict; <del> return subStream; <del> }, <del> }; <del> <del> return ChunkedStream; <del>})(); <del> <del>var ChunkedStreamManager = (function ChunkedStreamManagerClosure() { <del> <del> function ChunkedStreamManager(pdfNetworkStream, args) { <del> var chunkSize = args.rangeChunkSize; <del> var length = args.length; <del> this.stream = new ChunkedStream(length, chunkSize, this); <del> this.length = length; <del> this.chunkSize = chunkSize; <add> } <add> return missingChunks; <add> }; <add> <add> const subStream = new ChunkedStreamSubstream(); <add> subStream.pos = subStream.start = start; <add> subStream.end = start + length || this.end; <add> subStream.dict = dict; <add> return subStream; <add> } <add>} <add> <add>class ChunkedStreamManager { <add> constructor(pdfNetworkStream, args) { <add> this.length = args.length; <add> this.chunkSize = args.rangeChunkSize; <add> this.stream = new ChunkedStream(this.length, this.chunkSize, this); <ide> this.pdfNetworkStream = pdfNetworkStream; <ide> this.url = args.url; <ide> this.disableAutoFetch = args.disableAutoFetch; <ide> var ChunkedStreamManager = (function ChunkedStreamManagerClosure() { <ide> this._loadedStreamCapability = createPromiseCapability(); <ide> } <ide> <del> ChunkedStreamManager.prototype = { <del> onLoadedStream: function ChunkedStreamManager_getLoadedStream() { <del> return this._loadedStreamCapability.promise; <del> }, <add> onLoadedStream() { <add> return this._loadedStreamCapability.promise; <add> } <ide> <del> sendRequest: function ChunkedStreamManager_sendRequest(begin, end) { <del> var rangeReader = this.pdfNetworkStream.getRangeReader(begin, end); <del> if (!rangeReader.isStreamingSupported) { <del> rangeReader.onProgress = this.onProgress.bind(this); <del> } <del> var chunks = [], loaded = 0; <del> var manager = this; <del> var promise = new Promise(function (resolve, reject) { <del> var readChunk = function (chunk) { <del> try { <del> if (!chunk.done) { <del> var data = chunk.value; <del> chunks.push(data); <del> loaded += arrayByteLength(data); <del> if (rangeReader.isStreamingSupported) { <del> manager.onProgress({ loaded, }); <del> } <del> rangeReader.read().then(readChunk, reject); <del> return; <add> sendRequest(begin, end) { <add> const rangeReader = this.pdfNetworkStream.getRangeReader(begin, end); <add> if (!rangeReader.isStreamingSupported) { <add> rangeReader.onProgress = this.onProgress.bind(this); <add> } <add> <add> let chunks = [], loaded = 0; <add> const promise = new Promise((resolve, reject) => { <add> const readChunk = (chunk) => { <add> try { <add> if (!chunk.done) { <add> const data = chunk.value; <add> chunks.push(data); <add> loaded += arrayByteLength(data); <add> if (rangeReader.isStreamingSupported) { <add> this.onProgress({ loaded, }); <ide> } <del> var chunkData = arraysToBytes(chunks); <del> chunks = null; <del> resolve(chunkData); <del> } catch (e) { <del> reject(e); <add> rangeReader.read().then(readChunk, reject); <add> return; <ide> } <del> }; <del> rangeReader.read().then(readChunk, reject); <del> }); <del> promise.then((data) => { <del> if (this.aborted) { <del> return; // ignoring any data after abort <del> } <del> this.onReceiveData({ chunk: data, begin, }); <del> }); <del> // TODO check errors <del> }, <del> <del> // Get all the chunks that are not yet loaded and groups them into <del> // contiguous ranges to load in as few requests as possible <del> requestAllChunks: function ChunkedStreamManager_requestAllChunks() { <del> var missingChunks = this.stream.getMissingChunks(); <del> this._requestChunks(missingChunks); <del> return this._loadedStreamCapability.promise; <del> }, <del> <del> _requestChunks: function ChunkedStreamManager_requestChunks(chunks) { <del> var requestId = this.currRequestId++; <del> <del> var i, ii; <del> var chunksNeeded = Object.create(null); <del> this.chunksNeededByRequest[requestId] = chunksNeeded; <del> for (i = 0, ii = chunks.length; i < ii; i++) { <del> if (!this.stream.hasChunk(chunks[i])) { <del> chunksNeeded[chunks[i]] = true; <add> const chunkData = arraysToBytes(chunks); <add> chunks = null; <add> resolve(chunkData); <add> } catch (e) { <add> reject(e); <ide> } <del> } <add> }; <add> rangeReader.read().then(readChunk, reject); <add> }); <add> promise.then((data) => { <add> if (this.aborted) { <add> return; // Ignoring any data after abort. <add> } <add> this.onReceiveData({ chunk: data, begin, }); <add> }); <add> // TODO check errors <add> } <ide> <del> if (isEmptyObj(chunksNeeded)) { <del> return Promise.resolve(); <del> } <add> /** <add> * Get all the chunks that are not yet loaded and group them into <add> * contiguous ranges to load in as few requests as possible. <add> */ <add> requestAllChunks() { <add> const missingChunks = this.stream.getMissingChunks(); <add> this._requestChunks(missingChunks); <add> return this._loadedStreamCapability.promise; <add> } <ide> <del> var capability = createPromiseCapability(); <del> this.promisesByRequest[requestId] = capability; <add> _requestChunks(chunks) { <add> const requestId = this.currRequestId++; <ide> <del> var chunksToRequest = []; <del> for (var chunk in chunksNeeded) { <del> chunk = chunk | 0; <del> if (!(chunk in this.requestsByChunk)) { <del> this.requestsByChunk[chunk] = []; <del> chunksToRequest.push(chunk); <del> } <del> this.requestsByChunk[chunk].push(requestId); <add> const chunksNeeded = Object.create(null); <add> this.chunksNeededByRequest[requestId] = chunksNeeded; <add> for (const chunk of chunks) { <add> if (!this.stream.hasChunk(chunk)) { <add> chunksNeeded[chunk] = true; <ide> } <add> } <ide> <del> if (!chunksToRequest.length) { <del> return capability.promise; <del> } <add> if (isEmptyObj(chunksNeeded)) { <add> return Promise.resolve(); <add> } <ide> <del> var groupedChunksToRequest = this.groupChunks(chunksToRequest); <add> const capability = createPromiseCapability(); <add> this.promisesByRequest[requestId] = capability; <ide> <del> for (i = 0; i < groupedChunksToRequest.length; ++i) { <del> var groupedChunk = groupedChunksToRequest[i]; <del> var begin = groupedChunk.beginChunk * this.chunkSize; <del> var end = Math.min(groupedChunk.endChunk * this.chunkSize, this.length); <del> this.sendRequest(begin, end); <add> const chunksToRequest = []; <add> for (let chunk in chunksNeeded) { <add> chunk = chunk | 0; <add> if (!(chunk in this.requestsByChunk)) { <add> this.requestsByChunk[chunk] = []; <add> chunksToRequest.push(chunk); <ide> } <add> this.requestsByChunk[chunk].push(requestId); <add> } <ide> <add> if (!chunksToRequest.length) { <ide> return capability.promise; <del> }, <del> <del> getStream: function ChunkedStreamManager_getStream() { <del> return this.stream; <del> }, <add> } <ide> <del> // Loads any chunks in the requested range that are not yet loaded <del> requestRange: function ChunkedStreamManager_requestRange(begin, end) { <add> const groupedChunksToRequest = this.groupChunks(chunksToRequest); <add> for (const groupedChunk of groupedChunksToRequest) { <add> const begin = groupedChunk.beginChunk * this.chunkSize; <add> const end = Math.min(groupedChunk.endChunk * this.chunkSize, this.length); <add> this.sendRequest(begin, end); <add> } <ide> <del> end = Math.min(end, this.length); <add> return capability.promise; <add> } <ide> <del> var beginChunk = this.getBeginChunk(begin); <del> var endChunk = this.getEndChunk(end); <add> getStream() { <add> return this.stream; <add> } <ide> <del> var chunks = []; <del> for (var chunk = beginChunk; chunk < endChunk; ++chunk) { <del> chunks.push(chunk); <del> } <add> /** <add> * Loads any chunks in the requested range that are not yet loaded. <add> */ <add> requestRange(begin, end) { <add> end = Math.min(end, this.length); <ide> <del> return this._requestChunks(chunks); <del> }, <add> const beginChunk = this.getBeginChunk(begin); <add> const endChunk = this.getEndChunk(end); <ide> <del> requestRanges: function ChunkedStreamManager_requestRanges(ranges) { <del> ranges = ranges || []; <del> var chunksToRequest = []; <add> const chunks = []; <add> for (let chunk = beginChunk; chunk < endChunk; ++chunk) { <add> chunks.push(chunk); <add> } <add> return this._requestChunks(chunks); <add> } <ide> <del> for (var i = 0; i < ranges.length; i++) { <del> var beginChunk = this.getBeginChunk(ranges[i].begin); <del> var endChunk = this.getEndChunk(ranges[i].end); <del> for (var chunk = beginChunk; chunk < endChunk; ++chunk) { <del> if (!chunksToRequest.includes(chunk)) { <del> chunksToRequest.push(chunk); <del> } <add> requestRanges(ranges = []) { <add> const chunksToRequest = []; <add> for (const range of ranges) { <add> const beginChunk = this.getBeginChunk(range.begin); <add> const endChunk = this.getEndChunk(range.end); <add> for (let chunk = beginChunk; chunk < endChunk; ++chunk) { <add> if (!chunksToRequest.includes(chunk)) { <add> chunksToRequest.push(chunk); <ide> } <ide> } <add> } <ide> <del> chunksToRequest.sort(function(a, b) { <del> return a - b; <del> }); <del> return this._requestChunks(chunksToRequest); <del> }, <del> <del> // Groups a sorted array of chunks into as few contiguous larger <del> // chunks as possible <del> groupChunks: function ChunkedStreamManager_groupChunks(chunks) { <del> var groupedChunks = []; <del> var beginChunk = -1; <del> var prevChunk = -1; <del> for (var i = 0; i < chunks.length; ++i) { <del> var chunk = chunks[i]; <del> <del> if (beginChunk < 0) { <del> beginChunk = chunk; <del> } <add> chunksToRequest.sort(function(a, b) { <add> return a - b; <add> }); <add> return this._requestChunks(chunksToRequest); <add> } <ide> <del> if (prevChunk >= 0 && prevChunk + 1 !== chunk) { <del> groupedChunks.push({ beginChunk, <del> endChunk: prevChunk + 1, }); <del> beginChunk = chunk; <del> } <del> if (i + 1 === chunks.length) { <del> groupedChunks.push({ beginChunk, <del> endChunk: chunk + 1, }); <del> } <add> /** <add> * Groups a sorted array of chunks into as few contiguous larger <add> * chunks as possible. <add> */ <add> groupChunks(chunks) { <add> const groupedChunks = []; <add> let beginChunk = -1; <add> let prevChunk = -1; <ide> <del> prevChunk = chunk; <add> for (let i = 0, ii = chunks.length; i < ii; ++i) { <add> const chunk = chunks[i]; <add> if (beginChunk < 0) { <add> beginChunk = chunk; <ide> } <del> return groupedChunks; <del> }, <del> <del> onProgress: function ChunkedStreamManager_onProgress(args) { <del> var bytesLoaded = (this.stream.numChunksLoaded * this.chunkSize + <del> args.loaded); <del> this.msgHandler.send('DocProgress', { <del> loaded: bytesLoaded, <del> total: this.length, <del> }); <del> }, <del> <del> onReceiveData: function ChunkedStreamManager_onReceiveData(args) { <del> var chunk = args.chunk; <del> var isProgressive = args.begin === undefined; <del> var begin = isProgressive ? this.progressiveDataLength : args.begin; <del> var end = begin + chunk.byteLength; <del> <del> var beginChunk = Math.floor(begin / this.chunkSize); <del> var endChunk = end < this.length ? Math.floor(end / this.chunkSize) : <del> Math.ceil(end / this.chunkSize); <ide> <del> if (isProgressive) { <del> this.stream.onReceiveProgressiveData(chunk); <del> this.progressiveDataLength = end; <del> } else { <del> this.stream.onReceiveData(begin, chunk); <add> if (prevChunk >= 0 && prevChunk + 1 !== chunk) { <add> groupedChunks.push({ beginChunk, <add> endChunk: prevChunk + 1, }); <add> beginChunk = chunk; <ide> } <del> <del> if (this.stream.allChunksLoaded()) { <del> this._loadedStreamCapability.resolve(this.stream); <add> if (i + 1 === chunks.length) { <add> groupedChunks.push({ beginChunk, <add> endChunk: chunk + 1, }); <ide> } <ide> <del> var loadedRequests = []; <del> var i, requestId; <del> for (chunk = beginChunk; chunk < endChunk; ++chunk) { <del> // The server might return more chunks than requested <del> var requestIds = this.requestsByChunk[chunk] || []; <del> delete this.requestsByChunk[chunk]; <del> <del> for (i = 0; i < requestIds.length; ++i) { <del> requestId = requestIds[i]; <del> var chunksNeeded = this.chunksNeededByRequest[requestId]; <del> if (chunk in chunksNeeded) { <del> delete chunksNeeded[chunk]; <del> } <add> prevChunk = chunk; <add> } <add> return groupedChunks; <add> } <ide> <del> if (!isEmptyObj(chunksNeeded)) { <del> continue; <del> } <add> onProgress(args) { <add> this.msgHandler.send('DocProgress', { <add> loaded: this.stream.numChunksLoaded * this.chunkSize + args.loaded, <add> total: this.length, <add> }); <add> } <add> <add> onReceiveData(args) { <add> let chunk = args.chunk; <add> const isProgressive = args.begin === undefined; <add> const begin = isProgressive ? this.progressiveDataLength : args.begin; <add> const end = begin + chunk.byteLength; <ide> <del> loadedRequests.push(requestId); <add> const beginChunk = Math.floor(begin / this.chunkSize); <add> const endChunk = end < this.length ? Math.floor(end / this.chunkSize) : <add> Math.ceil(end / this.chunkSize); <add> <add> if (isProgressive) { <add> this.stream.onReceiveProgressiveData(chunk); <add> this.progressiveDataLength = end; <add> } else { <add> this.stream.onReceiveData(begin, chunk); <add> } <add> <add> if (this.stream.allChunksLoaded()) { <add> this._loadedStreamCapability.resolve(this.stream); <add> } <add> <add> const loadedRequests = []; <add> for (let chunk = beginChunk; chunk < endChunk; ++chunk) { <add> // The server might return more chunks than requested. <add> const requestIds = this.requestsByChunk[chunk] || []; <add> delete this.requestsByChunk[chunk]; <add> <add> for (const requestId of requestIds) { <add> const chunksNeeded = this.chunksNeededByRequest[requestId]; <add> if (chunk in chunksNeeded) { <add> delete chunksNeeded[chunk]; <ide> } <del> } <ide> <del> // If there are no pending requests, automatically fetch the next <del> // unfetched chunk of the PDF <del> if (!this.disableAutoFetch && isEmptyObj(this.requestsByChunk)) { <del> var nextEmptyChunk; <del> if (this.stream.numChunksLoaded === 1) { <del> // This is a special optimization so that after fetching the first <del> // chunk, rather than fetching the second chunk, we fetch the last <del> // chunk. <del> var lastChunk = this.stream.numChunks - 1; <del> if (!this.stream.hasChunk(lastChunk)) { <del> nextEmptyChunk = lastChunk; <del> } <del> } else { <del> nextEmptyChunk = this.stream.nextEmptyChunk(endChunk); <add> if (!isEmptyObj(chunksNeeded)) { <add> continue; <ide> } <del> if (Number.isInteger(nextEmptyChunk)) { <del> this._requestChunks([nextEmptyChunk]); <add> loadedRequests.push(requestId); <add> } <add> } <add> <add> // If there are no pending requests, automatically fetch the next <add> // unfetched chunk of the PDF file. <add> if (!this.disableAutoFetch && isEmptyObj(this.requestsByChunk)) { <add> let nextEmptyChunk; <add> if (this.stream.numChunksLoaded === 1) { <add> // This is a special optimization so that after fetching the first <add> // chunk, rather than fetching the second chunk, we fetch the last <add> // chunk. <add> const lastChunk = this.stream.numChunks - 1; <add> if (!this.stream.hasChunk(lastChunk)) { <add> nextEmptyChunk = lastChunk; <ide> } <add> } else { <add> nextEmptyChunk = this.stream.nextEmptyChunk(endChunk); <ide> } <del> <del> for (i = 0; i < loadedRequests.length; ++i) { <del> requestId = loadedRequests[i]; <del> var capability = this.promisesByRequest[requestId]; <del> delete this.promisesByRequest[requestId]; <del> capability.resolve(); <add> if (Number.isInteger(nextEmptyChunk)) { <add> this._requestChunks([nextEmptyChunk]); <ide> } <add> } <ide> <del> this.msgHandler.send('DocProgress', { <del> loaded: this.stream.numChunksLoaded * this.chunkSize, <del> total: this.length, <del> }); <del> }, <del> <del> onError: function ChunkedStreamManager_onError(err) { <del> this._loadedStreamCapability.reject(err); <del> }, <del> <del> getBeginChunk: function ChunkedStreamManager_getBeginChunk(begin) { <del> var chunk = Math.floor(begin / this.chunkSize); <del> return chunk; <del> }, <del> <del> getEndChunk: function ChunkedStreamManager_getEndChunk(end) { <del> var chunk = Math.floor((end - 1) / this.chunkSize) + 1; <del> return chunk; <del> }, <del> <del> abort: function ChunkedStreamManager_abort() { <del> this.aborted = true; <del> if (this.pdfNetworkStream) { <del> this.pdfNetworkStream.cancelAllRequests('abort'); <del> } <del> for (var requestId in this.promisesByRequest) { <del> var capability = this.promisesByRequest[requestId]; <del> capability.reject(new Error('Request was aborted')); <del> } <del> }, <del> }; <add> for (const requestId of loadedRequests) { <add> const capability = this.promisesByRequest[requestId]; <add> delete this.promisesByRequest[requestId]; <add> capability.resolve(); <add> } <add> <add> this.msgHandler.send('DocProgress', { <add> loaded: this.stream.numChunksLoaded * this.chunkSize, <add> total: this.length, <add> }); <add> } <ide> <del> return ChunkedStreamManager; <del>})(); <add> onError(err) { <add> this._loadedStreamCapability.reject(err); <add> } <add> <add> getBeginChunk(begin) { <add> return Math.floor(begin / this.chunkSize); <add> } <add> <add> getEndChunk(end) { <add> return Math.floor((end - 1) / this.chunkSize) + 1; <add> } <add> <add> abort() { <add> this.aborted = true; <add> if (this.pdfNetworkStream) { <add> this.pdfNetworkStream.cancelAllRequests('abort'); <add> } <add> for (const requestId in this.promisesByRequest) { <add> this.promisesByRequest[requestId].reject( <add> new Error('Request was aborted')); <add> } <add> } <add>} <ide> <ide> export { <ide> ChunkedStream,
1
Javascript
Javascript
fix bug in clonehook
f1bf281605444b342f4c37718092accbe3f98702
<ide><path>packages/react-reconciler/src/ReactFiberHooks.js <ide> function cloneHook(hook: Hook): Hook { <ide> return { <ide> memoizedState: hook.memoizedState, <ide> <del> baseState: hook.memoizedState, <add> baseState: hook.baseState, <ide> queue: hook.queue, <ide> baseUpdate: hook.baseUpdate, <ide> <ide><path>packages/react-reconciler/src/__tests__/ReactHooksWithNoopRenderer-test.internal.js <ide> describe('ReactHooksWithNoopRenderer', () => { <ide> ReactNoop.flush(); <ide> expect(ReactNoop.getChildren()).toEqual([span('Count: 8')]); <ide> }); <add> <add> // Regression test for https://github.com/facebook/react/issues/14360 <add> it('handles dispatches with mixed priorities', () => { <add> const INCREMENT = 'INCREMENT'; <add> <add> function reducer(state, action) { <add> return action === INCREMENT ? state + 1 : state; <add> } <add> <add> function Counter(props, ref) { <add> const [count, dispatch] = useReducer(reducer, 0); <add> useImperativeMethods(ref, () => ({dispatch})); <add> return <Text text={'Count: ' + count} />; <add> } <add> <add> Counter = forwardRef(Counter); <add> const counter = React.createRef(null); <add> ReactNoop.render(<Counter ref={counter} />); <add> <add> ReactNoop.flush(); <add> expect(ReactNoop.getChildren()).toEqual([span('Count: 0')]); <add> <add> counter.current.dispatch(INCREMENT); <add> counter.current.dispatch(INCREMENT); <add> counter.current.dispatch(INCREMENT); <add> ReactNoop.flushSync(() => { <add> counter.current.dispatch(INCREMENT); <add> }); <add> expect(ReactNoop.getChildren()).toEqual([span('Count: 1')]); <add> <add> ReactNoop.flush(); <add> expect(ReactNoop.getChildren()).toEqual([span('Count: 4')]); <add> }); <ide> }); <ide> <ide> describe('useEffect', () => {
2
Text
Text
fix typo in index.md
8c9c8ae5ad514907774210d324191857085dd83c
<ide><path>docs/sources/index.md <ide> Once your model looks good, configure its learning process with `.compile()`: <ide> model.compile(loss='categorical_crossentropy', optimizer='sgd') <ide> ``` <ide> <del>If you need to, you can further configure your optimizer. A core principle of Keras is make things things reasonably simple, while allowing the user to be fully in control when they need to (the ultimate control being the easy extensibility of the source code). <add>If you need to, you can further configure your optimizer. A core principle of Keras is to make things reasonably simple, while allowing the user to be fully in control when they need to (the ultimate control being the easy extensibility of the source code). <ide> ```python <ide> from keras.optimizers import SGD <ide> model.compile(loss='categorical_crossentropy', optimizer=SGD(lr=0.01, momentum=0.9, nesterov=True))
1
Go
Go
make checking of help text smarter
969ba5c7edfdca1d97a836e9549d80ce547a86a0
<ide><path>integration-cli/docker_cli_help_test.go <ide> import ( <ide> "runtime" <ide> "strings" <ide> "testing" <add> "unicode" <ide> ) <ide> <ide> func TestMainHelpWidth(t *testing.T) { <ide> func TestCmdHelpWidth(t *testing.T) { <ide> home = os.Getenv("HOME") <ide> } <ide> <del> for _, command := range []string{ <del> "attach", <del> "build", <del> "commit", <del> "cp", <del> "create", <del> "diff", <del> "events", <del> "exec", <del> "export", <del> "history", <del> "images", <del> "import", <del> "info", <del> "inspect", <del> "kill", <del> "load", <del> "login", <del> "logout", <del> "logs", <del> "port", <del> "pause", <del> "ps", <del> "pull", <del> "push", <del> "rename", <del> "restart", <del> "rm", <del> "rmi", <del> "run", <del> "save", <del> "search", <del> "start", <del> "stats", <del> "stop", <del> "tag", <del> "top", <del> "unpause", <del> "version", <del> "wait", <del> } { <add> // Pull the list of commands from the "Commands:" section of docker help <add> helpCmd := exec.Command(dockerBinary, "help") <add> out, ec, err := runCommandWithOutput(helpCmd) <add> if err != nil || ec != 0 { <add> t.Fatalf("docker help should have worked\nout:%s\nec:%d", out, ec) <add> } <add> i := strings.Index(out, "Commands:") <add> if i < 0 { <add> t.Fatalf("Missing 'Commands:' in:\n%s", out) <add> } <add> <add> // Grab all chars starting at "Commands:" <add> // Skip first line, its "Commands:" <add> count := 0 <add> cmds := "" <add> for _, command := range strings.Split(out[i:], "\n")[1:] { <add> // Stop on blank line or non-idented line <add> if command == "" || !unicode.IsSpace(rune(command[0])) { <add> break <add> } <add> <add> // Grab just the first word of each line <add> command = strings.Split(strings.TrimSpace(command), " ")[0] <add> <add> count++ <add> cmds = cmds + "\n" + command <add> <ide> helpCmd := exec.Command(dockerBinary, command, "--help") <ide> out, ec, err := runCommandWithOutput(helpCmd) <ide> if err != nil || ec != 0 { <ide> func TestCmdHelpWidth(t *testing.T) { <ide> } <ide> } <ide> <add> expected := 39 <add> if count != expected { <add> t.Fatalf("Wrong # of commands (%d), it should be: %d\nThe list:\n%s", <add> len(cmds), expected, cmds) <add> } <add> <ide> logDone("help - cmd widths") <ide> }
1
Text
Text
fix minor typo
87d0d8c7d48e7261157fde1cb130ca460dba406c
<ide><path>doc/api/worker_threads.md <ide> In particular, the significant differences to `JSON` are: <ide> - `value` may contain circular references. <ide> - `value` may contain instances of builtin JS types such as `RegExp`s, <ide> `BigInt`s, `Map`s, `Set`s, etc. <del>- `value` may contained typed arrays, both using `ArrayBuffer`s <add>- `value` may contain typed arrays, both using `ArrayBuffer`s <ide> and `SharedArrayBuffer`s. <ide> - `value` may contain [`WebAssembly.Module`][] instances. <ide> - `value` may not contain native (C++-backed) objects other than `MessagePort`s.
1
Python
Python
find python.h when build_ext --include-dirs is set
b08f369554e6d6b231c941740f6c852a45edcc12
<ide><path>numpy/distutils/command/build_ext.py <ide> def finalize_options(self): <ide> self.jobs = int(self.jobs) <ide> except ValueError: <ide> raise ValueError("--jobs/-j argument must be an integer") <del> incl_dirs = self.include_dirs <add> <add> # Ensure that self.include_dirs and self.distribution.include_dirs <add> # refer to the same list object. finalize_options will modify <add> # self.include_dirs, but self.distribution.include_dirs is used <add> # during the actual build. <add> # self.include_dirs is None unless paths are specified with <add> # --include-dirs. <add> # The include paths will be passed to the compiler in the order: <add> # numpy paths, --include-dirs paths, Python include path. <add> if isinstance(self.include_dirs, str): <add> self.include_dirs = self.include_dirs.split(os.pathsep) <add> incl_dirs = self.include_dirs or [] <add> if self.distribution.include_dirs is None: <add> self.distribution.include_dirs = [] <add> self.include_dirs = self.distribution.include_dirs <add> self.include_dirs.extend(incl_dirs) <add> <ide> old_build_ext.finalize_options(self) <del> if incl_dirs is not None: <del> self.include_dirs.extend(self.distribution.include_dirs or []) <ide> self.set_undefined_options('build', ('jobs', 'jobs')) <ide> <ide> def run(self):
1
Python
Python
use word_ids to get labels in run_ner
7f9ccffc5b9da6b2eb5631fef81b85fc52269f6f
<ide><path>examples/token-classification/run_ner.py <ide> AutoTokenizer, <ide> DataCollatorForTokenClassification, <ide> HfArgumentParser, <add> PreTrainedTokenizerFast, <ide> Trainer, <ide> TrainingArguments, <ide> set_seed, <ide> def get_label_list(labels): <ide> cache_dir=model_args.cache_dir, <ide> ) <ide> <add> # Tokenizer check: this script requires a fast tokenizer. <add> if not isinstance(tokenizer, PreTrainedTokenizerFast): <add> raise ValueError( <add> "This example script only works for models that have a fast tokenizer. Checkout the big table of models " <add> "at https://huggingface.co/transformers/index.html#bigtable to find the model types that meet this " <add> "requirement" <add> ) <add> <ide> # Preprocessing the dataset <ide> # Padding strategy <ide> padding = "max_length" if data_args.pad_to_max_length else False <ide> def tokenize_and_align_labels(examples): <ide> truncation=True, <ide> # We use this argument because the texts in our dataset are lists of words (with a label for each word). <ide> is_split_into_words=True, <del> return_offsets_mapping=True, <ide> ) <del> offset_mappings = tokenized_inputs.pop("offset_mapping") <ide> labels = [] <del> for label, offset_mapping in zip(examples[label_column_name], offset_mappings): <del> label_index = 0 <del> current_label = -100 <add> for i, label in enumerate(examples[label_column_name]): <add> word_ids = tokenized_inputs.word_ids(batch_index=i) <add> previous_word_idx = None <ide> label_ids = [] <del> for offset in offset_mapping: <del> # We set the label for the first token of each word. Special characters will have an offset of (0, 0) <del> # so the test ignores them. <del> if offset[0] == 0 and offset[1] != 0: <del> current_label = label_to_id[label[label_index]] <del> label_index += 1 <del> label_ids.append(current_label) <del> # For special tokens, we set the label to -100 so it's automatically ignored in the loss function. <del> elif offset[0] == 0 and offset[1] == 0: <add> for word_idx in word_ids: <add> # Special tokens have a word id that is None. We set the label to -100 so they are automatically <add> # ignored in the loss function. <add> if word_idx is None: <ide> label_ids.append(-100) <add> # We set the label for the first token of each word. <add> elif word_idx != previous_word_idx: <add> label_ids.append(label_to_id[label[word_idx]]) <ide> # For the other tokens in a word, we set the label to either the current label or -100, depending on <ide> # the label_all_tokens flag. <ide> else: <del> label_ids.append(current_label if data_args.label_all_tokens else -100) <add> label_ids.append(label_to_id[label[word_idx]] if data_args.label_all_tokens else -100) <add> previous_word_idx = word_idx <ide> <ide> labels.append(label_ids) <ide> tokenized_inputs["labels"] = labels
1
PHP
PHP
update hash param
0c7879c305c2ad65fab1a617fabcee68d91cf6f5
<ide><path>src/Illuminate/Auth/AuthManager.php <ide> public function createTokenDriver($name, $config) <ide> $this->createUserProvider($config['provider'] ?? null), <ide> $this->app['request'], <ide> $config['input_key'] ?? 'api_token', <del> $config['storage_key'] ?? 'api_token' <add> $config['storage_key'] ?? 'api_token', <add> $config['hash'] ?? false <ide> ); <ide> <ide> $this->app->refresh('request', $guard, 'setRequest');
1
Text
Text
add windows installation instructions
e3c44bf551cd6ab4b3d571bd5cc894eb0b49d677
<ide><path>README.md <ide> Visit [atom.io](https://atom.io) to learn more. <ide> <ide> ## Installing <ide> <add>### Mac OS X <add> <ide> Download the latest [Atom release](https://github.com/atom/atom/releases/latest). <ide> <ide> Atom will automatically update when a new release is available. <ide> <add>### Windows <add> <add>Install the [Atom chocolatey package](https://chocolatey.org/packages/Atom). <add> <add>1. Install [chocolatey](https://chocolatey.org). <add>2. Close and reopen your command prompt or PowerShell window. <add>3. Run `cinst Atom` <add>4. In the future run `cup Atom` to upgrade to the latest release. <add> <ide> ## Building <ide> <ide> * [Linux](docs/build-instructions/linux.md) <ide> Atom will automatically update when a new release is available. <ide> * [Windows](docs/build-instructions/windows.md) <ide> <ide> ## Developing <add> <ide> Check out the [guides](https://atom.io/docs/latest) and the [API reference](https://atom.io/docs/api).
1
PHP
PHP
remove deprecation notice
4e0b39e5f0d6d7e38657dbdc419605623437853d
<ide><path>src/Http/ServerRequest.php <ide> public static function createFromGlobals() <ide> * - `files` Uploaded file data formatted like $_FILES. <ide> * - `cookies` Cookies for this request. <ide> * - `environment` $_SERVER and $_ENV data. <del> * - ~~`url`~~ The URL without the base path for the request. This option is deprecated and will be removed in 4.0.0 <add> * - `url` The URL without the base path for the request. <ide> * - `uri` The PSR7 UriInterface object. If null, one will be created. <ide> * - `base` The base URL for the request. <ide> * - `webroot` The webroot directory for the request.
1
Ruby
Ruby
use formulacellarchecks module
897607b3d7f95f9d6ffe0a0fd79b0fcb34be1742
<ide><path>Library/Homebrew/cmd/audit.rb <ide> require 'formula' <ide> require 'utils' <ide> require 'superenv' <add>require 'formula_cellar_checks' <ide> <ide> module Homebrew extend self <ide> def audit <ide> def has_trailing_newline? <ide> end <ide> <ide> class FormulaAuditor <add> include FormulaCellarChecks <add> <ide> attr_reader :f, :text, :problems <ide> <ide> BUILD_TIME_DEPS = %W[ <ide> def audit_python <ide> <ide> end <ide> <add> def audit_check_output warning_and_description <add> return unless warning_and_description <add> warning, _ = *warning_and_description <add> problem warning <add> end <add> <add> def audit_installed <add> audit_check_output(check_manpages) <add> audit_check_output(check_infopages) <add> audit_check_output(check_jars) <add> audit_check_output(check_non_libraries) <add> audit_check_output(check_non_executables(f.bin)) <add> audit_check_output(check_non_executables(f.sbin)) <add> end <add> <ide> def audit <ide> audit_file <ide> audit_specs <ide> def audit <ide> audit_patches <ide> audit_text <ide> audit_python <add> audit_installed <ide> end <ide> <ide> private <ide><path>Library/Homebrew/formula_installer.rb <ide> def print_check_output warning_and_description <ide> end <ide> <ide> def audit_bin <del> return unless f.bin.directory? <ide> print_check_output(check_PATH(f.bin)) unless f.keg_only? <ide> print_check_output(check_non_executables(f.bin)) <ide> end <ide> <ide> def audit_sbin <del> return unless f.sbin.directory? <ide> print_check_output(check_PATH(f.sbin)) unless f.keg_only? <ide> print_check_output(check_non_executables(f.sbin)) <ide> end
2
Text
Text
suggest simplehttpserver instead of tornado
787e80a25c70c6da9b6ee9fa2049c05bacc605b8
<ide><path>README.md <ide> compatibility layer. The examples should work on Firefox, Chrome (Chromium), <ide> Safari (WebKit), Opera and IE9. <ide> <ide> Note: Chrome has strict permissions for reading files out of the local file <del>system. To view some of the examples locally, you will need to start a local web <del>server. One easy way to do that is to install Tornado: <add>system. Also some examples use AJAX which works differently via HTTP <add>instead of local files. For the best experience, load the D3 examples from <add>your own machine via HTTP. Any static file web server will work, for example <add>you can run Python's built-in server: <ide> <del> cd .. <del> git clone https://github.com/facebook/tornado.git <del> cd tornado <del> sudo python setup.py install <del> cd ../d3 <add> python -m SimpleHTTPServer 8888 <ide> <del>We have provided a Tornado script for serving static files: <del> <del> python examples <del> <del>Once this is running, go to: <http://0.0.0.0:8888/examples/index.html> <add>Once this is running, go to: <http://127.0.0.1:8888/examples/index.html>
1
Javascript
Javascript
enable data vis cert
b0768b1005736565bc2b10980271377a005d1d13
<ide><path>config/i18n/all-langs.js <ide> const auditedCerts = { <ide> espanol: [ <ide> 'responsive-web-design', <ide> 'javascript-algorithms-and-data-structures', <del> 'front-end-development-libraries' <add> 'front-end-development-libraries', <add> 'data-visualization' <ide> ], <ide> chinese: [ <ide> 'responsive-web-design',
1
Text
Text
fix structure and formatting in inspector.md
c18a9d1cb8fe94e39f2826de7edd9c44c9be9ce2
<ide><path>doc/api/inspector.md <ide> It can be accessed using: <ide> const inspector = require('inspector'); <ide> ``` <ide> <add>## inspector.close() <add> <add>Deactivate the inspector. Blocks until there are no active connections. <add> <add>## inspector.console <add> <add>* {Object} An object to send messages to the remote inspector console. <add> <add>```js <add>require('inspector').console.log('a message'); <add>``` <add> <add>The inspector console does not have API parity with Node.js <add>console. <add> <ide> ## inspector.open([port[, host[, wait]]]) <ide> <ide> * `port` {number} Port to listen on for inspector connections. Optional. <ide> started. <ide> If wait is `true`, will block until a client has connected to the inspect port <ide> and flow control has been passed to the debugger client. <ide> <del>### inspector.console <del> <del>An object to send messages to the remote inspector console. <del> <del>```js <del>require('inspector').console.log('a message'); <del>``` <del> <del>The inspector console does not have API parity with Node.js <del>console. <del> <del>### inspector.close() <del> <del>Deactivate the inspector. Blocks until there are no active connections. <del> <del>### inspector.url() <add>## inspector.url() <ide> <ide> * Returns: {string|undefined} <ide> <ide> Connects a session to the inspector back-end. An exception will be thrown <ide> if there is already a connected session established either through the API or by <ide> a front-end connected to the Inspector WebSocket port. <ide> <add>### session.disconnect() <add><!-- YAML <add>added: v8.0.0 <add>--> <add> <add>Immediately close the session. All pending message callbacks will be called <add>with an error. [`session.connect()`] will need to be called to be able to send <add>messages again. Reconnected session will lose all inspector state, such as <add>enabled agents or configured breakpoints. <add> <ide> ### session.post(method[, params][, callback]) <ide> <!-- YAML <ide> added: v8.0.0 <ide> by V8. Chrome DevTools Protocol domain provides an interface for interacting <ide> with one of the runtime agents used to inspect the application state and listen <ide> to the run-time events. <ide> <del>### session.disconnect() <del><!-- YAML <del>added: v8.0.0 <del>--> <del> <del>Immediately close the session. All pending message callbacks will be called <del>with an error. [`session.connect()`] will need to be called to be able to send <del>messages again. Reconnected session will lose all inspector state, such as <del>enabled agents or configured breakpoints. <del> <ide> ## Example usage <ide> <ide> ### CPU Profiler
1
PHP
PHP
add dump() to phpreader
578dac92598a585beea27840d513832bd5d5be3a
<ide><path>lib/Cake/Configure/PhpReader.php <ide> public function read($key) { <ide> return $config; <ide> } <ide> <add>/** <add> * Converts the provided $data into a string of PHP code that can <add> * be used saved into a file and loaded later. <add> * <add> * @param array $data Data to dump. <add> * @return string String or PHP code. <add> */ <add> public function dump($data) { <add> return '<?php' . "\n" . '$config = ' . var_export($data, true) . ';'; <add> } <add> <ide> } <ide><path>lib/Cake/Test/Case/Configure/PhpReaderTest.php <ide> public function testReadPluginValue() { <ide> $this->assertTrue(isset($result['plugin_load'])); <ide> CakePlugin::unload(); <ide> } <add> <add>/** <add> * Test dumping data to PHP format. <add> * <add> * @return void <add> */ <add> public function testDump() { <add> $reader = new PhpReader($this->path); <add> $data = array( <add> 'One' => array( <add> 'two' => 'value', <add> 'three' => array( <add> 'four' => 'value four' <add> ), <add> 'null' => null <add> ), <add> 'Asset' => array( <add> 'timestamp' => 'force' <add> ), <add> ); <add> $result = $reader->dump($data); <add> $expected = <<<PHP <add><?php <add>\$config = array ( <add> 'One' => <add> array ( <add> 'two' => 'value', <add> 'three' => <add> array ( <add> 'four' => 'value four', <add> ), <add> 'null' => NULL, <add> ), <add> 'Asset' => <add> array ( <add> 'timestamp' => 'force', <add> ), <add>); <add>PHP; <add> $this->assertEquals($expected, $result); <add> } <add> <ide> }
2
PHP
PHP
pass positional arguments into shell methods
9e0da22a584a3bcdf2a6afa86fd4ca235127abde
<ide><path>src/Console/Shell.php <ide> public function runCommand($command, $argv) { <ide> return $this->{$command}->runCommand('execute', $argv); <ide> } <ide> if ($isMethod) { <del> return $this->{$command}(); <add> return call_user_func_array([$this, $command], $this->args); <ide> } <ide> if ($isMain) { <del> return $this->main(); <add> return call_user_func_array([$this, 'main'], $this->args); <ide> } <ide> $this->out($this->OptionParser->help($command)); <ide> return false; <ide><path>tests/TestCase/Console/ShellTest.php <ide> public function testHasMethod() { <ide> * @return void <ide> */ <ide> public function testRunCommandMain() { <del> $Mock = $this->getMock('Cake\Console\Shell', array('main', 'startup'), array(), '', false); <add> $io = $this->getMock('Cake\Console\ConsoleIo'); <add> $Mock = $this->getMock('Cake\Console\Shell', ['main', 'startup'], [$io]); <ide> <del> $Mock->expects($this->once())->method('main')->will($this->returnValue(true)); <del> $result = $Mock->runCommand(null, array()); <add> $Mock->expects($this->once())->method('startup'); <add> $Mock->expects($this->once())->method('main') <add> ->with('cakes') <add> ->will($this->returnValue(true)); <add> $result = $Mock->runCommand(null, ['cakes', '--verbose']); <ide> $this->assertTrue($result); <ide> } <ide> <ide> public function testRunCommandMain() { <ide> * @return void <ide> */ <ide> public function testRunCommandWithMethod() { <del> $Mock = $this->getMock('Cake\Console\Shell', array('hit_me', 'startup'), array(), '', false); <add> $io = $this->getMock('Cake\Console\ConsoleIo'); <add> $Mock = $this->getMock('Cake\Console\Shell', ['hit_me', 'startup'], [$io]); <ide> <del> $Mock->expects($this->once())->method('hit_me')->will($this->returnValue(true)); <del> $result = $Mock->runCommand('hit_me', array()); <add> $Mock->expects($this->once())->method('startup'); <add> $Mock->expects($this->once())->method('hit_me') <add> ->with('cakes') <add> ->will($this->returnValue(true)); <add> $result = $Mock->runCommand('hit_me', ['hit_me', 'cakes', '--verbose']); <ide> $this->assertTrue($result); <ide> } <ide> <ide> public function testRunCommandTriggeringHelp() { <ide> * @return void <ide> */ <ide> public function testRunCommandHittingTask() { <del> $Shell = $this->getMock('Cake\Console\Shell', array('hasTask', 'startup'), array(), '', false); <del> $task = $this->getMock('Cake\Console\Shell', array('execute', 'runCommand'), array(), '', false); <add> $Shell = $this->getMock('Cake\Console\Shell', ['hasTask', 'startup'], [], '', false); <add> $task = $this->getMock('Cake\Console\Shell', ['execute', 'runCommand'], [], '', false); <ide> $task->expects($this->any()) <ide> ->method('runCommand') <del> ->with('execute', array('one', 'value')); <add> ->with('execute', ['one', 'value']); <ide> <ide> $Shell->expects($this->once())->method('startup'); <ide> $Shell->expects($this->any()) <ide> public function testRunCommandHittingTask() { <ide> <ide> $Shell->RunCommand = $task; <ide> <del> $Shell->runCommand('run_command', array('run_command', 'one', 'value')); <add> $Shell->runCommand('run_command', ['run_command', 'one', 'value']); <ide> } <ide> <ide> /**
2
Go
Go
remove old debug from tarsum
360078d7613e1939c6d2f949ccac14c6ab9d568e
<ide><path>utils/tarsum.go <ide> package utils <ide> <ide> import ( <add> "archive/tar" <ide> "bytes" <ide> "compress/gzip" <ide> "crypto/sha256" <ide> "encoding/hex" <del> "archive/tar" <ide> "hash" <ide> "io" <ide> "sort" <ide> "strconv" <ide> ) <ide> <del>type verboseHash struct { <del> hash.Hash <del>} <del> <del>func (h verboseHash) Write(buf []byte) (int, error) { <del> Debugf("--->%s<---", buf) <del> return h.Hash.Write(buf) <del>} <del> <ide> type TarSum struct { <ide> io.Reader <ide> tarR *tar.Reader <ide> type TarSum struct { <ide> bufTar *bytes.Buffer <ide> bufGz *bytes.Buffer <ide> h hash.Hash <del> h2 verboseHash <ide> sums []string <ide> finished bool <ide> first bool <ide> func (ts *TarSum) encodeHeader(h *tar.Header) error { <ide> // {"atime", strconv.Itoa(int(h.AccessTime.UTC().Unix()))}, <ide> // {"ctime", strconv.Itoa(int(h.ChangeTime.UTC().Unix()))}, <ide> } { <del> // Debugf("-->%s<-- -->%s<--", elem[0], elem[1]) <ide> if _, err := ts.h.Write([]byte(elem[0] + elem[1])); err != nil { <ide> return err <ide> } <ide> func (ts *TarSum) Read(buf []byte) (int, error) { <ide> ts.tarW = tar.NewWriter(ts.bufTar) <ide> ts.gz = gzip.NewWriter(ts.bufGz) <ide> ts.h = sha256.New() <del> // ts.h = verboseHash{sha256.New()} <ide> ts.h.Reset() <ide> ts.first = true <ide> }
1
Text
Text
add comment to code block in readme
117489665089027841ad37b961e55ae31e43649b
<ide><path>README.md <ide> RCT_EXPORT_VIEW_PROPERTY(myCustomProperty); <ide> ``` <ide> <ide> ```javascript <add>// JavaScript <ide> module.exports = createReactIOSNativeComponentClass({ <ide> validAttributes: { myCustomProperty: true }, <ide> uiViewClassName: 'MyCustomView',
1
Python
Python
remove input preprocessing
b883761820e86903ce6132a458ee95e23427f7fa
<ide><path>examples/neural_style_transfer.py <ide> def preprocess_image(image_path): <ide> img = imresize(imread(image_path), (img_width, img_height)) <ide> img = img.transpose((2, 0, 1)).astype('float64') <del> img[0, :, :] -= 103.939 <del> img[1, :, :] -= 116.779 <del> img[2, :, :] -= 123.68 <ide> img = np.expand_dims(img, axis=0) <ide> return img <ide> <ide> # util function to convert a tensor into a valid image <ide> def deprocess_image(x): <del> x[0, :, :] += 103.939 <del> x[1, :, :] += 116.779 <del> x[2, :, :] += 123.68 <ide> x = x.transpose((1, 2, 0)) <ide> x = np.clip(x, 0, 255).astype('uint8') <ide> return x
1
Text
Text
fix 5am typo
0e24ede2fe2a2ead259907597de393b6a2d4f46d
<ide><path>docs/introduction/Examples.md <ide> It covers: <ide> * Normalized state <ide> * Reducer composition <ide> * State representing a tree view <del>* Granual re-rendering of a large subtree <add>* Granular re-rendering of a large subtree <ide> <ide> ## More Examples <ide>
1
Javascript
Javascript
give java 2g of memory
a59a5f386a96f6b208acea78ab8233cb88180ce7
<ide><path>lib/grunt/utils.js <ide> module.exports = { <ide> shell.exec( <ide> 'java ' + <ide> this.java32flags() + ' ' + <add> '-Xmx2g ' + <ide> '-classpath ./components/closure-compiler/compiler.jar' + classPathSep + <ide> './components/ng-closure-runner/ngcompiler.jar ' + <ide> 'org.angularjs.closurerunner.NgClosureRunner ' +
1
Ruby
Ruby
pass options onto key file generator
059d1edcbc6a556237fa31c6547f0faa11da328e
<ide><path>railties/lib/rails/generators/rails/master_key/master_key_generator.rb <ide> def ignore_master_key_file <ide> <ide> private <ide> def key_file_generator <del> EncryptionKeyFileGenerator.new <add> EncryptionKeyFileGenerator.new([], options) <ide> end <ide> <ide> def key_ignore
1
Javascript
Javascript
use a semantic name for the variable
9b174520cce97a0cb9835b0e0b7d40be0f828212
<ide><path>src/ajax.js <ide> var r20 = /%20/g, <ide> ajaxLocParts, <ide> <ide> // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression <del> starSlashStar = "*/".concat("*"); <add> allTypes = "*/".concat("*"); <ide> <ide> // #8138, IE may throw an exception when accessing <ide> // a field from window.location if document.domain has been set <ide> jQuery.extend({ <ide> html: "text/html", <ide> text: "text/plain", <ide> json: "application/json, text/javascript", <del> "*": starSlashStar <add> "*": allTypes <ide> }, <ide> <ide> contents: { <ide> jQuery.extend({ <ide> jqXHR.setRequestHeader( <ide> "Accept", <ide> s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? <del> s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + starSlashStar + "; q=0.01" : "" ) : <add> s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : <ide> s.accepts[ "*" ] <ide> ); <ide>
1
Java
Java
replay additional overloads
5915fb3df3ddb708efd7e74a91f76237cfa9bc62
<ide><path>rxjava-core/src/main/java/rx/Observable.java <ide> import rx.operators.OperationOnExceptionResumeNextViaObservable; <ide> import rx.operators.OperationParallel; <ide> import rx.operators.OperationParallelMerge; <add>import rx.operators.OperationReplay; <ide> import rx.operators.OperationRetry; <ide> import rx.operators.OperationSample; <ide> import rx.operators.OperationScan; <ide> public <R> ConnectableObservable<R> multicast(Subject<? super T, ? extends R> su <ide> return OperationMulticast.multicast(this, subject); <ide> } <ide> <add> /** <add> * Returns an observable sequence that contains the elements of a sequence <add> * produced by multicasting the source sequence within a selector function. <add> * <add> * @param subjectFactory the subject factory <add> * @param selector The selector function which can use the multicasted <add> * source sequence subject to the policies enforced by the <add> * created subject. <add> * @return the Observable sequence that contains the elements of a sequence <add> * produced by multicasting the source sequence within a selector function. <add> * <add> * @see <a href='http://msdn.microsoft.com/en-us/library/hh229708.aspx'>MSDN: Observable.Multicast</a> <add> */ <add> public <TIntermediate, TResult> Observable<TResult> multicast( <add> final Func0<? extends Subject<? super T, ? extends TIntermediate>> subjectFactory, <add> final Func1<? super Observable<TIntermediate>, ? extends Observable<TResult>> selector) { <add> return OperationMulticast.multicast(this, subjectFactory, selector); <add> } <ide> /** <ide> * Allow the {@link RxJavaErrorHandler} to receive the exception from <ide> * onError. <ide> public <R> Observable<List<T>> maxBy(Func1<T, R> selector, Comparator<? super R> <ide> public ConnectableObservable<T> replay() { <ide> return OperationMulticast.multicast(this, ReplaySubject.<T> create()); <ide> } <del> <add> <ide> /** <ide> * Returns a {@link ConnectableObservable} that shares a single subscription <ide> * to the underlying Observable that will replay all of its items and <del> * notifications to any future {@link Observer} on the given scheduler <add> * notifications to any future {@link Observer} on the given scheduler. <ide> * <del> * @param scheduler <del> * @return <add> * @param scheduler the scheduler where the Observers will receive the events <add> * @return a {@link ConnectableObservable} that shares a single subscription <add> * to the underlying Observable that will replay all of its items and <add> * notifications to any future {@link Observer} on the given scheduler <ide> * <ide> * @see <a href='http://msdn.microsoft.com/en-us/library/hh211699.aspx'>MSDN: Observable.Replay</a> <ide> */ <ide> public ConnectableObservable<T> replay(Scheduler scheduler) { <del> return OperationMulticast.multicast(this, ReplaySubject.<T> create()); <add> return OperationMulticast.multicast(this, OperationReplay.createScheduledSubject(ReplaySubject.<T>create(), scheduler)); <add> } <add> <add> /** <add> * Returns a connectable observable sequence that shares a single subscription <add> * to the underlying sequence replaying bufferSize notifications. <add> * <add> * @param bufferSize the buffer size <add> * @return a connectable observable sequence that shares a single subscription <add> * to the underlying sequence replaying bufferSize notifications <add> * <add> * @see <a href='http://msdn.microsoft.com/en-us/library/hh211976.aspx'>MSDN: Observable.Replay</a> <add> */ <add> public ConnectableObservable<T> replay(int bufferSize) { <add> return OperationMulticast.multicast(this, OperationReplay.<T>replayBuffered(bufferSize)); <add> } <add> <add> /** <add> * Returns a connectable observable sequence that shares a single <add> * subscription to the underlying sequence replaying bufferSize notifications. <add> * <add> * @param bufferSize the buffer size <add> * @param scheduler the scheduler where the Observers will receive the events <add> * @return a connectable observable sequence that shares a single <add> * subscription to the underlying sequence replaying bufferSize notifications <add> * <add> * @see <a href='http://msdn.microsoft.com/en-us/library/hh229814.aspx'>MSDN: Observable.Replay</a> <add> */ <add> public ConnectableObservable<T> replay(int bufferSize, Scheduler scheduler) { <add> return OperationMulticast.multicast(this, <add> OperationReplay.createScheduledSubject( <add> OperationReplay.<T>replayBuffered(bufferSize), scheduler)); <add> } <add> <add> /** <add> * Returns a connectable observable sequence that shares a single <add> * subscription to the underlying sequence replaying all notifications within window. <add> * <add> * @param time the window length <add> * @param unit the window length time unit <add> * @return a connectable observable sequence that shares a single <add> * subscription to the underlying sequence replaying all notifications within window <add> * @see <a href='http://msdn.microsoft.com/en-us/library/hh229232.aspx'>MSDN: Observable.Replay</a> <add> */ <add> public ConnectableObservable<T> replay(long time, TimeUnit unit) { <add> return replay(time, unit, Schedulers.threadPoolForComputation()); <add> } <add> <add> /** <add> * Returns a connectable observable sequence that shares a single <add> * subscription to the underlying sequence replaying all notifications within window. <add> * <add> * @param time the window length <add> * @param unit the window length time unit <add> * @param scheduler the scheduler which is used as a time source for the window <add> * @return a connectable observable sequence that shares a single <add> * subscription to the underlying sequence replaying all notifications within window <add> * @see <a href='http://msdn.microsoft.com/en-us/library/hh211811.aspx'>MSDN: Observable.Replay</a> <add> */ <add> public ConnectableObservable<T> replay(long time, TimeUnit unit, Scheduler scheduler) { <add> return OperationMulticast.multicast(this, OperationReplay.<T>replayWindowed(time, unit, -1, scheduler)); <add> } <add> <add> /** <add> * Returns a connectable observable sequence that shares a single <add> * subscription to the underlying sequence replaying bufferSize notifications within window. <add> * <add> * @param bufferSize the buffer size <add> * @param time the window length <add> * @param unit the window length time unit <add> * @return Returns a connectable observable sequence that shares a single <add> * subscription to the underlying sequence replaying bufferSize notifications within window <add> * <add> * @see <a href='http://msdn.microsoft.com/en-us/library/hh229874.aspx'>MSDN: Observable.Replay</a> <add> */ <add> public ConnectableObservable<T> replay(int bufferSize, long time, TimeUnit unit) { <add> return replay(bufferSize, time, unit, Schedulers.threadPoolForComputation()); <add> } <add> <add> /** <add> * Returns a connectable observable sequence that shares a single <add> * subscription to the underlying sequence replaying bufferSize notifications within window. <add> * <add> * @param bufferSize the buffer size <add> * @param time the window length <add> * @param unit the window length time unit <add> * @param scheduler the scheduler which is used as a time source for the window <add> * @return a connectable observable sequence that shares a single <add> * subscription to the underlying sequence replaying bufferSize notifications within window <add> * <add> * @see <a href='http://msdn.microsoft.com/en-us/library/hh211759.aspx'>MSDN: Observable.Replay</a> <add> */ <add> public ConnectableObservable<T> replay(int bufferSize, long time, TimeUnit unit, Scheduler scheduler) { <add> if (bufferSize < 0) { <add> throw new IllegalArgumentException("bufferSize < 0"); <add> } <add> return OperationMulticast.multicast(this, OperationReplay.<T>replayWindowed(time, unit, bufferSize, scheduler)); <add> } <add> <add> /** <add> * Returns an observable sequence that is the result of invoking the selector <add> * on a connectable observable sequence that shares a single subscription to <add> * the underlying sequence and starts with initial value. <add> * <add> * @param <R> the return element type <add> * @param selector The selector function which can use the multicasted <add> * this sequence as many times as needed, without causing <add> * multiple subscriptions to this sequence. <add> * @return an observable sequence that is the result of invoking the selector <add> * on a connectable observable sequence that shares a single subscription to <add> * the underlying sequence and starts with initial value <add> * <add> * @see <a href='http://msdn.microsoft.com/en-us/library/hh229653.aspx'>MSDN: Observable.Replay</a> <add> */ <add> public <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector) { <add> return OperationMulticast.multicast(this, new Func0<Subject<T, T>>() { <add> @Override <add> public Subject<T, T> call() { <add> return ReplaySubject.create(); <add> } <add> }, selector); <add> } <add> <add> /** <add> * Returns an observable sequence that is the result of invoking the <add> * selector on a connectable observable sequence that shares a single <add> * subscription to the underlying sequence replaying all notifications. <add> * <add> * @param <R> the return element type <add> * @param selector The selector function which can use the multicasted <add> * this sequence as many times as needed, without causing <add> * multiple subscriptions to this sequence. <add> * @param scheduler the scheduler where the replay is observed <add> * @return an observable sequence that is the result of invoking the <add> * selector on a connectable observable sequence that shares a single <add> * subscription to the underlying sequence replaying all notifications <add> * <add> * @see <a href='http://msdn.microsoft.com/en-us/library/hh211644.aspx'>MSDN: Observable.Replay</a> <add> */ <add> public <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, final Scheduler scheduler) { <add> return OperationMulticast.multicast(this, new Func0<Subject<T, T>>() { <add> @Override <add> public Subject<T, T> call() { <add> return OperationReplay.createScheduledSubject(ReplaySubject.<T>create(), scheduler); <add> } <add> }, selector); <add> } <add> <add> /** <add> * Returns an observable sequence that is the result of invoking the <add> * selector on a connectable observable sequence that shares a single <add> * subscription to the underlying sequence replaying bufferSize notifications. <add> * <add> * @param <R> the return element type <add> * @param selector The selector function which can use the multicasted <add> * this sequence as many times as needed, without causing <add> * multiple subscriptions to this sequence. <add> * @param bufferSize the buffer size <add> * @return an observable sequence that is the result of invoking the <add> * selector on a connectable observable sequence that shares a single <add> * subscription to the underlying sequence replaying bufferSize notifications <add> * <add> * @see <a href='http://msdn.microsoft.com/en-us/library/hh211675.aspx'>MSDN: Observable.Replay</a> <add> */ <add> public <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, final int bufferSize) { <add> return OperationMulticast.multicast(this, new Func0<Subject<T, T>>() { <add> @Override <add> public Subject<T, T> call() { <add> return OperationReplay.replayBuffered(bufferSize); <add> } <add> }, selector); <add> } <add> <add> /** <add> * Returns an observable sequence that is the result of invoking the <add> * selector on a connectable observable sequence that shares a single <add> * subscription to the underlying sequence replaying bufferSize notifications. <add> * <add> * @param <R> the return element type <add> * @param selector The selector function which can use the multicasted <add> * this sequence as many times as needed, without causing <add> * multiple subscriptions to this sequence. <add> * @param bufferSize the buffer size <add> * @param scheduler the scheduler where the replay is observed <add> * @return an observable sequence that is the result of invoking the <add> * selector on a connectable observable sequence that shares a single <add> * subscription to the underlying sequence replaying bufferSize notifications <add> * <add> * @see <a href='http://msdn.microsoft.com/en-us/library/hh229928.aspx'>MSDN: Observable.Replay</a> <add> */ <add> public <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, final int bufferSize, final Scheduler scheduler) { <add> return OperationMulticast.multicast(this, new Func0<Subject<T, T>>() { <add> @Override <add> public Subject<T, T> call() { <add> return OperationReplay.<T>createScheduledSubject(OperationReplay.<T>replayBuffered(bufferSize), scheduler); <add> } <add> }, selector); <add> } <add> <add> /** <add> * Returns an observable sequence that is the result of invoking <add> * the selector on a connectable observable sequence that shares a single <add> * subscription to the underlying sequence replaying all notifications within window. <add> * <add> * @param <R> the return element type <add> * @param selector The selector function which can use the multicasted <add> * this sequence as many times as needed, without causing <add> * multiple subscriptions to this sequence. <add> * @param time the window length <add> * @param unit the window length time unit <add> * @return an observable sequence that is the result of invoking <add> * the selector on a connectable observable sequence that shares a single <add> * subscription to the underlying sequence replaying all notifications within window <add> * <add> * @see <a href='http://msdn.microsoft.com/en-us/library/hh229526.aspx'>MSDN: Observable.Replay</a> <add> */ <add> public <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, long time, TimeUnit unit) { <add> return replay(selector, time, unit, Schedulers.threadPoolForComputation()); <ide> } <add> <add> /** <add> * Returns an observable sequence that is the result of invoking the <add> * selector on a connectable observable sequence that shares a single <add> * subscription to the underlying sequence replaying all notifications within window. <add> * <add> * @param <R> the return element type <add> * @param selector The selector function which can use the multicasted <add> * this sequence as many times as needed, without causing <add> * multiple subscriptions to this sequence. <add> * @param time the window length <add> * @param unit the window length time unit <add> * @param scheduler the scheduler which is used as a time source for the window <add> * @return an observable sequence that is the result of invoking the <add> * selector on a connectable observable sequence that shares a single <add> * subscription to the underlying sequence replaying all notifications within window <add> * <add> * @see <a href='http://msdn.microsoft.com/en-us/library/hh244327.aspx'>MSDN: Observable.Replay</a> <add> */ <add> public <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, final long time, final TimeUnit unit, final Scheduler scheduler) { <add> return OperationMulticast.multicast(this, new Func0<Subject<T, T>>() { <add> @Override <add> public Subject<T, T> call() { <add> return OperationReplay.replayWindowed(time, unit, -1, scheduler); <add> } <add> }, selector); <add> } <add> <add> /** <add> * Returns an observable sequence that is the result of invoking the <add> * selector on a connectable observable sequence that shares a single <add> * subscription to the underlying sequence replaying bufferSize notifications <add> * within window. <add> * <add> * @param <R> the return element type <add> * @param selector The selector function which can use the multicasted <add> * this sequence as many times as needed, without causing <add> * multiple subscriptions to this sequence. <add> * @param bufferSize the buffer size <add> * @param time the window length <add> * @param unit the window length time unit <add> * <add> * @return an observable sequence that is the result of invoking the <add> * selector on a connectable observable sequence that shares a single <add> * subscription to the underlying sequence replaying bufferSize notifications <add> * within window <add> * <add> * @see <a href='http://msdn.microsoft.com/en-us/library/hh228952.aspx'>MSDN: Observable.Replay</a> <add> */ <add> public <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, int bufferSize, long time, TimeUnit unit) { <add> return replay(selector, bufferSize, time, unit, Schedulers.threadPoolForComputation()); <add> } <add> <add> <add> /** <add> * Returns an observable sequence that is the result of invoking the <add> * selector on a connectable observable sequence that shares a single <add> * subscription to the underlying sequence replaying bufferSize notifications <add> * within window. <add> * <add> * @param <R> the return element type <add> * @param selector The selector function which can use the multicasted <add> * this sequence as many times as needed, without causing <add> * multiple subscriptions to this sequence. <add> * @param bufferSize the buffer size <add> * @param time the window length <add> * @param unit the window length time unit <add> * @param scheduler the scheduler which is used as a time source for the window <add> * <add> * @return an observable sequence that is the result of invoking the <add> * selector on a connectable observable sequence that shares a single <add> * subscription to the underlying sequence replaying bufferSize notifications <add> * within window <add> * <add> * @see <a href='http://msdn.microsoft.com/en-us/library/hh229404.aspx'>MSDN: Observable.Replay</a> <add> */ <add> public <R> Observable<R> replay(Func1<? super Observable<T>, ? extends Observable<R>> selector, final int bufferSize, final long time, final TimeUnit unit, final Scheduler scheduler) { <add> if (bufferSize < 0) { <add> throw new IllegalArgumentException("bufferSize < 0"); <add> } <add> return OperationMulticast.multicast(this, new Func0<Subject<T, T>>() { <add> @Override <add> public Subject<T, T> call() { <add> return OperationReplay.replayWindowed(time, unit, bufferSize, scheduler); <add> } <add> }, selector); <add> } <add> <ide> /** <ide> * Retry subscription to the source Observable when it calls <ide> * <code>onError</code> up to a certain number of retries. <ide><path>rxjava-core/src/main/java/rx/operators/OperationMulticast.java <ide> package rx.operators; <ide> <ide> import rx.Observable; <add>import rx.Observable.OnSubscribeFunc; <ide> import rx.Observer; <ide> import rx.Subscription; <ide> import rx.observables.ConnectableObservable; <ide> import rx.subjects.Subject; <add>import rx.subscriptions.CompositeSubscription; <add>import rx.subscriptions.Subscriptions; <add>import rx.util.functions.Func0; <add>import rx.util.functions.Func1; <ide> <ide> public class OperationMulticast { <ide> public static <T, R> ConnectableObservable<R> multicast(Observable<? extends T> source, final Subject<? super T, ? extends R> subject) { <ide> public void unsubscribe() { <ide> } <ide> <ide> } <add> /** <add> * Returns an observable sequence that contains the elements of a sequence <add> * produced by multicasting the source sequence within a selector function. <add> * <add> * @param source <add> * @param subjectFactory <add> * @param selector <add> * @return <add> * <add> * @see <a href='http://msdn.microsoft.com/en-us/library/hh229708(v=vs.103).aspx'>MSDN: Observable.Multicast</a> <add> */ <add> public static <TInput, TIntermediate, TResult> Observable<TResult> multicast( <add> final Observable<? extends TInput> source, <add> final Func0<? extends Subject<? super TInput, ? extends TIntermediate>> subjectFactory, <add> final Func1<? super Observable<TIntermediate>, ? extends Observable<TResult>> selector) { <add> return Observable.create(new MulticastSubscribeFunc<TInput, TIntermediate, TResult>(source, subjectFactory, selector)); <add> } <add> /** The multicast subscription function. */ <add> private static final class MulticastSubscribeFunc<TInput, TIntermediate, TResult> implements OnSubscribeFunc<TResult> { <add> final Observable<? extends TInput> source; <add> final Func0<? extends Subject<? super TInput, ? extends TIntermediate>> subjectFactory; <add> final Func1<? super Observable<TIntermediate>, ? extends Observable<TResult>> resultSelector; <add> public MulticastSubscribeFunc(Observable<? extends TInput> source, <add> Func0<? extends Subject<? super TInput, ? extends TIntermediate>> subjectFactory, <add> Func1<? super Observable<TIntermediate>, ? extends Observable<TResult>> resultSelector) { <add> this.source = source; <add> this.subjectFactory = subjectFactory; <add> this.resultSelector = resultSelector; <add> } <add> @Override <add> public Subscription onSubscribe(Observer<? super TResult> t1) { <add> Observable<TResult> observable; <add> ConnectableObservable<TIntermediate> connectable; <add> try { <add> Subject<? super TInput, ? extends TIntermediate> subject = subjectFactory.call(); <add> <add> connectable = new MulticastConnectableObservable<TInput, TIntermediate>(source, subject); <add> <add> observable = resultSelector.call(connectable); <add> } catch (Throwable t) { <add> t1.onError(t); <add> return Subscriptions.empty(); <add> } <add> <add> CompositeSubscription csub = new CompositeSubscription(); <add> <add> csub.add(observable.subscribe(new SafeObserver<TResult>( <add> new SafeObservableSubscription(csub), t1))); <add> csub.add(connectable.connect()); <add> <add> return csub; <add> } <add> } <ide> } <ide><path>rxjava-core/src/main/java/rx/operators/OperationReplay.java <ide> public final class OperationReplay { <ide> /** <ide> * Create a BoundedReplaySubject with the given buffer size. <ide> */ <del> public static <T> Subject<T, T> replayWithBufferSize(int bufferSize) { <add> public static <T> Subject<T, T> replayBuffered(int bufferSize) { <ide> return CustomReplaySubject.create(bufferSize); <ide> } <ide> /** <ide> public static <T> Subject<T, T> createScheduledSubject(Subject<T, T> subject, Sc <ide> SubjectWrapper<T> s = new SubjectWrapper<T>(subscriberOf(observedOn), subject); <ide> return s; <ide> } <del> /** <del> * Return an OnSubscribeFunc which delegates the subscription to the given observable. <del> */ <del> public static <T> OnSubscribeFunc<T> subscriberOf(final Observable<T> target) { <del> return new OnSubscribeFunc<T>() { <del> @Override <del> public Subscription onSubscribe(Observer<? super T> t1) { <del> return target.subscribe(t1); <del> } <del> }; <del> } <ide> <ide> /** <ide> * Create a CustomReplaySubject with the given time window length <ide> * and optional buffer size. <ide> * <add> * @param <T> the source and return type <ide> * @param time the length of the time window <ide> * @param unit the unit of the time window length <ide> * @param bufferSize the buffer size if >= 0, otherwise, the buffer will be unlimited <ide> * @param scheduler the scheduler from where the current time is retrieved. The <ide> * observers will not observe on this scheduler. <ide> * @return a Subject with the required replay behavior <ide> */ <del> public static <T> Subject<T, T> replayWithTimeWindowOrBufferSize(long time, TimeUnit unit, int bufferSize, final Scheduler scheduler) { <add> public static <T> Subject<T, T> replayWindowed(long time, TimeUnit unit, int bufferSize, final Scheduler scheduler) { <ide> final long ms = unit.toMillis(time); <ide> if (ms <= 0) { <ide> throw new IllegalArgumentException("The time window is less than 1 millisecond!"); <ide> public void call() { <ide> <ide> return brs; <ide> } <add> <add> /** <add> * Return an OnSubscribeFunc which delegates the subscription to the given observable. <add> */ <add> public static <T> OnSubscribeFunc<T> subscriberOf(final Observable<T> target) { <add> return new OnSubscribeFunc<T>() { <add> @Override <add> public Subscription onSubscribe(Observer<? super T> t1) { <add> return target.subscribe(t1); <add> } <add> }; <add> } <add> <ide> /** <ide> * Subject that wraps another subject and uses a mapping function <ide> * to transform the received values. <ide> public void unlock() { <ide> } <ide> /** <ide> * Base interface for logically indexing a list. <del> * @param <T> <add> * @param <T> the value type <ide> */ <ide> public interface VirtualList<T> { <ide> /** @return the number of elements in this list */ <ide> int size(); <del> /** Add an element to the list. */ <add> /** <add> * Add an element to the list. <add> * @param value the value to add <add> */ <ide> void add(T value); <ide> /** <ide> * Retrieve an element at the specified logical index. <ide> public void unlock() { <ide> * Clears and resets the indexes of the list. <ide> */ <ide> void reset(); <add> /** <add> * Returns the current content as a list. <add> * @return <add> */ <add> List<T> toList(); <ide> } <ide> /** <ide> * Behaves like a normal, unbounded ArrayList but with virtual index. <ide> public void reset() { <ide> list.clear(); <ide> startIndex = 0; <ide> } <add> @Override <add> public List<T> toList() { <add> return new ArrayList<T>(list); <add> } <ide> <ide> } <ide> /** <ide> public void removeBefore(int index) { <ide> startIndex = index; <ide> head = head2 % maxSize; <ide> } <del> /** <del> * Returns a list with the current elements in this bounded list. <del> * @return <del> */ <add> @Override <ide> public List<T> toList() { <ide> List<T> r = new ArrayList<T>(list.size() + 1); <ide> for (int i = head; i < head + count; i++) { <ide><path>rxjava-core/src/test/java/rx/operators/OperationReplayTest.java <ide> package rx.operators; <ide> <ide> import java.util.Arrays; <add>import java.util.concurrent.TimeUnit; <ide> import org.junit.Assert; <ide> import org.junit.Test; <add>import org.mockito.InOrder; <add>import static org.mockito.Mockito.*; <add>import rx.Observable; <add>import rx.Observer; <add>import rx.observables.ConnectableObservable; <ide> import rx.operators.OperationReplay.VirtualBoundedList; <add>import rx.schedulers.TestScheduler; <add>import rx.subjects.PublishSubject; <add>import rx.util.functions.Func1; <ide> <ide> public class OperationReplayTest { <ide> @Test <ide> public void testReadAfter() { <ide> <ide> list.get(4); <ide> } <add> @Test <add> public void testBufferedReplay() { <add> PublishSubject<Integer> source = PublishSubject.create(); <add> <add> ConnectableObservable<Integer> co = source.replay(3); <add> co.connect(); <add> <add> { <add> Observer<Object> observer1 = mock(Observer.class); <add> InOrder inOrder = inOrder(observer1); <add> <add> co.subscribe(observer1); <add> <add> source.onNext(1); <add> source.onNext(2); <add> source.onNext(3); <add> <add> inOrder.verify(observer1, times(1)).onNext(1); <add> inOrder.verify(observer1, times(1)).onNext(2); <add> inOrder.verify(observer1, times(1)).onNext(3); <add> <add> source.onNext(4); <add> source.onCompleted(); <add> inOrder.verify(observer1, times(1)).onNext(4); <add> inOrder.verify(observer1, times(1)).onCompleted(); <add> inOrder.verifyNoMoreInteractions(); <add> verify(observer1, never()).onError(any(Throwable.class)); <add> <add> } <add> <add> { <add> Observer<Object> observer1 = mock(Observer.class); <add> InOrder inOrder = inOrder(observer1); <add> <add> co.subscribe(observer1); <add> <add> inOrder.verify(observer1, times(1)).onNext(2); <add> inOrder.verify(observer1, times(1)).onNext(3); <add> inOrder.verify(observer1, times(1)).onNext(4); <add> inOrder.verify(observer1, times(1)).onCompleted(); <add> inOrder.verifyNoMoreInteractions(); <add> verify(observer1, never()).onError(any(Throwable.class)); <add> } <add> } <add> @Test <add> public void testWindowedReplay() { <add> TestScheduler scheduler = new TestScheduler(); <add> <add> PublishSubject<Integer> source = PublishSubject.create(); <add> <add> ConnectableObservable<Integer> co = source.replay(100, TimeUnit.MILLISECONDS, scheduler); <add> co.connect(); <add> <add> { <add> Observer<Object> observer1 = mock(Observer.class); <add> InOrder inOrder = inOrder(observer1); <add> <add> co.subscribe(observer1); <add> <add> source.onNext(1); <add> scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS); <add> source.onNext(2); <add> scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS); <add> source.onNext(3); <add> scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS); <add> source.onCompleted(); <add> scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS); <add> <add> inOrder.verify(observer1, times(1)).onNext(1); <add> inOrder.verify(observer1, times(1)).onNext(2); <add> inOrder.verify(observer1, times(1)).onNext(3); <add> <add> inOrder.verify(observer1, times(1)).onCompleted(); <add> inOrder.verifyNoMoreInteractions(); <add> verify(observer1, never()).onError(any(Throwable.class)); <add> <add> } <add> { <add> Observer<Object> observer1 = mock(Observer.class); <add> InOrder inOrder = inOrder(observer1); <add> <add> co.subscribe(observer1); <add> inOrder.verify(observer1, times(1)).onNext(3); <add> <add> inOrder.verify(observer1, times(1)).onCompleted(); <add> inOrder.verifyNoMoreInteractions(); <add> verify(observer1, never()).onError(any(Throwable.class)); <add> } <add> } <add> @Test <add> public void testReplaySelector() { <add> final Func1<Integer, Integer> dbl = new Func1<Integer, Integer>() { <add> <add> @Override <add> public Integer call(Integer t1) { <add> return t1 * 2; <add> } <add> <add> }; <add> <add> Func1<Observable<Integer>, Observable<Integer>> selector = new Func1<Observable<Integer>, Observable<Integer>>() { <add> <add> @Override <add> public Observable<Integer> call(Observable<Integer> t1) { <add> return t1.map(dbl); <add> } <add> <add> }; <add> <add> PublishSubject<Integer> source = PublishSubject.create(); <add> <add> Observable<Integer> co = source.replay(selector); <add> <add> { <add> Observer<Object> observer1 = mock(Observer.class); <add> InOrder inOrder = inOrder(observer1); <add> <add> co.subscribe(observer1); <add> <add> source.onNext(1); <add> source.onNext(2); <add> source.onNext(3); <add> <add> inOrder.verify(observer1, times(1)).onNext(2); <add> inOrder.verify(observer1, times(1)).onNext(4); <add> inOrder.verify(observer1, times(1)).onNext(6); <add> <add> source.onNext(4); <add> source.onCompleted(); <add> inOrder.verify(observer1, times(1)).onNext(8); <add> inOrder.verify(observer1, times(1)).onCompleted(); <add> inOrder.verifyNoMoreInteractions(); <add> verify(observer1, never()).onError(any(Throwable.class)); <add> <add> } <add> <add> { <add> Observer<Object> observer1 = mock(Observer.class); <add> InOrder inOrder = inOrder(observer1); <add> <add> co.subscribe(observer1); <add> <add> inOrder.verify(observer1, times(1)).onCompleted(); <add> inOrder.verifyNoMoreInteractions(); <add> verify(observer1, never()).onError(any(Throwable.class)); <add> <add> } <add> <add> } <add> <add> @Test <add> public void testBufferedReplaySelector() { <add> <add> final Func1<Integer, Integer> dbl = new Func1<Integer, Integer>() { <add> <add> @Override <add> public Integer call(Integer t1) { <add> return t1 * 2; <add> } <add> <add> }; <add> <add> Func1<Observable<Integer>, Observable<Integer>> selector = new Func1<Observable<Integer>, Observable<Integer>>() { <add> <add> @Override <add> public Observable<Integer> call(Observable<Integer> t1) { <add> return t1.map(dbl); <add> } <add> <add> }; <add> <add> PublishSubject<Integer> source = PublishSubject.create(); <add> <add> Observable<Integer> co = source.replay(selector, 3); <add> <add> { <add> Observer<Object> observer1 = mock(Observer.class); <add> InOrder inOrder = inOrder(observer1); <add> <add> co.subscribe(observer1); <add> <add> source.onNext(1); <add> source.onNext(2); <add> source.onNext(3); <add> <add> inOrder.verify(observer1, times(1)).onNext(2); <add> inOrder.verify(observer1, times(1)).onNext(4); <add> inOrder.verify(observer1, times(1)).onNext(6); <add> <add> source.onNext(4); <add> source.onCompleted(); <add> inOrder.verify(observer1, times(1)).onNext(8); <add> inOrder.verify(observer1, times(1)).onCompleted(); <add> inOrder.verifyNoMoreInteractions(); <add> verify(observer1, never()).onError(any(Throwable.class)); <add> <add> } <add> <add> { <add> Observer<Object> observer1 = mock(Observer.class); <add> InOrder inOrder = inOrder(observer1); <add> <add> co.subscribe(observer1); <add> <add> inOrder.verify(observer1, times(1)).onCompleted(); <add> inOrder.verifyNoMoreInteractions(); <add> verify(observer1, never()).onError(any(Throwable.class)); <add> } <add> } <add> @Test <add> public void testWindowedReplaySelector() { <add> <add> final Func1<Integer, Integer> dbl = new Func1<Integer, Integer>() { <add> <add> @Override <add> public Integer call(Integer t1) { <add> return t1 * 2; <add> } <add> <add> }; <add> <add> Func1<Observable<Integer>, Observable<Integer>> selector = new Func1<Observable<Integer>, Observable<Integer>>() { <add> <add> @Override <add> public Observable<Integer> call(Observable<Integer> t1) { <add> return t1.map(dbl); <add> } <add> <add> }; <add> <add> TestScheduler scheduler = new TestScheduler(); <add> <add> PublishSubject<Integer> source = PublishSubject.create(); <add> <add> Observable<Integer> co = source.replay(selector, 100, TimeUnit.MILLISECONDS, scheduler); <add> <add> { <add> Observer<Object> observer1 = mock(Observer.class); <add> InOrder inOrder = inOrder(observer1); <add> <add> co.subscribe(observer1); <add> <add> source.onNext(1); <add> scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS); <add> source.onNext(2); <add> scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS); <add> source.onNext(3); <add> scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS); <add> source.onCompleted(); <add> scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS); <add> <add> inOrder.verify(observer1, times(1)).onNext(2); <add> inOrder.verify(observer1, times(1)).onNext(4); <add> inOrder.verify(observer1, times(1)).onNext(6); <add> <add> inOrder.verify(observer1, times(1)).onCompleted(); <add> inOrder.verifyNoMoreInteractions(); <add> verify(observer1, never()).onError(any(Throwable.class)); <add> <add> } <add> { <add> Observer<Object> observer1 = mock(Observer.class); <add> InOrder inOrder = inOrder(observer1); <add> <add> co.subscribe(observer1); <add> <add> inOrder.verify(observer1, times(1)).onCompleted(); <add> inOrder.verifyNoMoreInteractions(); <add> verify(observer1, never()).onError(any(Throwable.class)); <add> } <add> } <add> @Test <add> public void testBufferedReplayError() { <add> PublishSubject<Integer> source = PublishSubject.create(); <add> <add> ConnectableObservable<Integer> co = source.replay(3); <add> co.connect(); <add> <add> { <add> Observer<Object> observer1 = mock(Observer.class); <add> InOrder inOrder = inOrder(observer1); <add> <add> co.subscribe(observer1); <add> <add> source.onNext(1); <add> source.onNext(2); <add> source.onNext(3); <add> <add> inOrder.verify(observer1, times(1)).onNext(1); <add> inOrder.verify(observer1, times(1)).onNext(2); <add> inOrder.verify(observer1, times(1)).onNext(3); <add> <add> source.onNext(4); <add> source.onError(new RuntimeException("Forced failure")); <add> <add> inOrder.verify(observer1, times(1)).onNext(4); <add> inOrder.verify(observer1, times(1)).onError(any(RuntimeException.class)); <add> inOrder.verifyNoMoreInteractions(); <add> verify(observer1, never()).onCompleted(); <add> <add> } <add> <add> { <add> Observer<Object> observer1 = mock(Observer.class); <add> InOrder inOrder = inOrder(observer1); <add> <add> co.subscribe(observer1); <add> <add> inOrder.verify(observer1, times(1)).onNext(2); <add> inOrder.verify(observer1, times(1)).onNext(3); <add> inOrder.verify(observer1, times(1)).onNext(4); <add> inOrder.verify(observer1, times(1)).onError(any(RuntimeException.class)); <add> inOrder.verifyNoMoreInteractions(); <add> verify(observer1, never()).onCompleted(); <add> } <add> } <add> @Test <add> public void testWindowedReplayError() { <add> TestScheduler scheduler = new TestScheduler(); <add> <add> PublishSubject<Integer> source = PublishSubject.create(); <add> <add> ConnectableObservable<Integer> co = source.replay(100, TimeUnit.MILLISECONDS, scheduler); <add> co.connect(); <add> <add> { <add> Observer<Object> observer1 = mock(Observer.class); <add> InOrder inOrder = inOrder(observer1); <add> <add> co.subscribe(observer1); <add> <add> source.onNext(1); <add> scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS); <add> source.onNext(2); <add> scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS); <add> source.onNext(3); <add> scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS); <add> source.onError(new RuntimeException("Forced failure")); <add> scheduler.advanceTimeBy(60, TimeUnit.MILLISECONDS); <add> <add> inOrder.verify(observer1, times(1)).onNext(1); <add> inOrder.verify(observer1, times(1)).onNext(2); <add> inOrder.verify(observer1, times(1)).onNext(3); <add> <add> inOrder.verify(observer1, times(1)).onError(any(RuntimeException.class)); <add> inOrder.verifyNoMoreInteractions(); <add> verify(observer1, never()).onCompleted(); <add> <add> } <add> { <add> Observer<Object> observer1 = mock(Observer.class); <add> InOrder inOrder = inOrder(observer1); <add> <add> co.subscribe(observer1); <add> inOrder.verify(observer1, times(1)).onNext(3); <add> <add> inOrder.verify(observer1, times(1)).onError(any(RuntimeException.class)); <add> inOrder.verifyNoMoreInteractions(); <add> verify(observer1, never()).onCompleted(); <add> } <add> } <ide> }
4
Javascript
Javascript
require statement nits
76ec746341b2ce3a98f8ca2183cfdd23fcd2d783
<ide><path>src/core/ReactEventTopLevelCallback.js <ide> <ide> var ExecutionEnvironment = require('ExecutionEnvironment'); <ide> var ReactEventEmitter = require('ReactEventEmitter'); <add>var ReactID = require('ReactID'); <ide> var ReactInstanceHandles = require('ReactInstanceHandles'); <ide> <del>var ReactID = require('ReactID'); <ide> var getEventTarget = require('getEventTarget'); <ide> <ide> /** <ide><path>src/core/ReactInstanceHandles.js <ide> "use strict"; <ide> <ide> var ReactID = require('ReactID'); <add> <ide> var invariant = require('invariant'); <ide> <ide> var SEPARATOR = '.';
2
Python
Python
fix channel_first layout for efficientnet
6d16ae2e1edaf7fbe7e73aa6706b0d4c0c7938f5
<ide><path>official/vision/image_classification/classifier_trainer.py <ide> def initialize(params: base_configs.ExperimentConfig, <ide> datasets_num_private_threads=params.runtime.dataset_num_private_threads) <ide> <ide> performance.set_mixed_precision_policy(dataset_builder.dtype) <del> <del> if dataset_builder.config.data_format: <del> data_format = dataset_builder.config.data_format <ide> if tf.config.list_physical_devices('GPU'): <ide> data_format = 'channels_first' <ide> else: <ide><path>official/vision/image_classification/classifier_trainer_test.py <ide> class EmptyClass: <ide> fake_ds_builder = EmptyClass() <ide> fake_ds_builder.dtype = dtype <ide> fake_ds_builder.config = EmptyClass() <del> fake_ds_builder.config.data_format = None <ide> classifier_trainer.initialize(config, fake_ds_builder) <ide> <ide> def test_resume_from_checkpoint(self): <ide><path>official/vision/image_classification/dataset_factory.py <ide> class DatasetConfig(base_config.Config): <ide> (e.g., the number of GPUs or TPU cores). <ide> num_devices: The number of replica devices to use. This should be set by <ide> `strategy.num_replicas_in_sync` when using a distribution strategy. <del> data_format: The data format of the images. Should be 'channels_last' or <del> 'channels_first'. <ide> dtype: The desired dtype of the dataset. This will be set during <ide> preprocessing. <ide> one_hot: Whether to apply one hot encoding. Set to `True` to be able to use <ide> class DatasetConfig(base_config.Config): <ide> batch_size: int = 128 <ide> use_per_replica_batch_size: bool = False <ide> num_devices: int = 1 <del> data_format: str = 'channels_last' <ide> dtype: str = 'float32' <ide> one_hot: bool = True <ide> augmenter: AugmentConfig = AugmentConfig() <ide><path>official/vision/image_classification/efficientnet/efficientnet_model.py <ide> def conv2d_block(inputs: tf.Tensor, <ide> batch_norm = common_modules.get_batch_norm(config.batch_norm) <ide> bn_momentum = config.bn_momentum <ide> bn_epsilon = config.bn_epsilon <del> data_format = config.data_format <add> data_format = tf.keras.backend.image_data_format() <ide> weight_decay = config.weight_decay <ide> <ide> name = name or '' <ide> def mb_conv_block(inputs: tf.Tensor, <ide> use_se = config.use_se <ide> activation = tf_utils.get_activation(config.activation) <ide> drop_connect_rate = config.drop_connect_rate <del> data_format = config.data_format <add> data_format = tf.keras.backend.image_data_format() <ide> use_depthwise = block.conv_type != 'no_depthwise' <ide> prefix = prefix or '' <ide> <ide> def efficientnet(image_input: tf.keras.layers.Input, <ide> num_classes = config.num_classes <ide> input_channels = config.input_channels <ide> rescale_input = config.rescale_input <del> data_format = config.data_format <add> data_format = tf.keras.backend.image_data_format() <ide> dtype = config.dtype <ide> weight_decay = config.weight_decay <ide> <ide> x = image_input <del> <add> if data_format == 'channels_first': <add> # Happens on GPU/TPU if available. <add> x = tf.keras.layers.Permute((3, 1, 2))(x) <ide> if rescale_input: <ide> x = preprocessing.normalize_images(x, <ide> num_channels=input_channels,
4
Mixed
Ruby
permit yaml classes and unsafe load per attribute
e313fc5a4d8891149b8c7b1a66c882d22c22c348
<ide><path>activerecord/CHANGELOG.md <add>* Allow per attribute setting of YAML permitted classes (safe load) and unsafe load. <add> <add> *Carlos Palhares* <add> <ide> * Add a build persistence method <ide> <ide> Provides a wrapper for `new`, to provide feature parity with `create`s <ide><path>activerecord/lib/active_record/attribute_methods/serialization.rb <ide> module ClassMethods <ide> # using the coder's <tt>dump(value)</tt> method, and will be <ide> # deserialized using the coder's <tt>load(string)</tt> method. The <ide> # +dump+ method may return +nil+ to serialize the value as +NULL+. <add> # * +yaml+ - Optional. Yaml specific options. The allowed config is: <add> # * +:permitted_classes+ - +Array+ with the permitted classes. <add> # * +:unsafe_load+ - Unsafely load YAML blobs, allow YAML to load any class <ide> # <ide> # ==== Options <ide> # <ide> module ClassMethods <ide> # serialize :preferences, Hash <ide> # end <ide> # <add> # ===== Serializes +preferences+ to YAML, permitting select classes <add> # <add> # class User < ActiveRecord::Base <add> # serialize :preferences, yaml: { permitted_classes: [Symbol, Time] } <add> # end <add> # <ide> # ===== Serialize the +preferences+ attribute using a custom coder <ide> # <ide> # class Rot13JSON <ide> module ClassMethods <ide> # serialize :preferences, Rot13JSON <ide> # end <ide> # <del> def serialize(attr_name, class_name_or_coder = Object, **options) <add> def serialize(attr_name, class_name_or_coder = Object, yaml: {}, **options) <ide> # When ::JSON is used, force it to go through the Active Support JSON encoder <ide> # to ensure special objects (e.g. Active Record models) are dumped correctly <ide> # using the #as_json hook. <ide> def serialize(attr_name, class_name_or_coder = Object, **options) <ide> elsif [:load, :dump].all? { |x| class_name_or_coder.respond_to?(x) } <ide> class_name_or_coder <ide> else <del> Coders::YAMLColumn.new(attr_name, class_name_or_coder) <add> Coders::YAMLColumn.new(attr_name, class_name_or_coder, **yaml) <ide> end <ide> <ide> attribute(attr_name, **options) do |cast_type| <ide><path>activerecord/lib/active_record/coders/yaml_column.rb <ide> module Coders # :nodoc: <ide> class YAMLColumn # :nodoc: <ide> attr_accessor :object_class <ide> <del> def initialize(attr_name, object_class = Object) <add> def initialize(attr_name, object_class = Object, permitted_classes: [], unsafe_load: nil) <ide> @attr_name = attr_name <ide> @object_class = object_class <add> @permitted_classes = permitted_classes <add> @unsafe_load = unsafe_load <ide> check_arity_of_constructor <ide> end <ide> <ide> def assert_valid_value(obj, action:) <ide> end <ide> <ide> private <add> def permitted_classes <add> [*ActiveRecord.yaml_column_permitted_classes, *@permitted_classes] <add> end <add> <add> def unsafe_load? <add> @unsafe_load.nil? ? ActiveRecord.use_yaml_unsafe_load : @unsafe_load <add> end <add> <ide> def check_arity_of_constructor <ide> load(nil) <ide> rescue ArgumentError <ide> def check_arity_of_constructor <ide> <ide> if YAML.respond_to?(:unsafe_load) <ide> def yaml_load(payload) <del> if ActiveRecord.use_yaml_unsafe_load <add> if unsafe_load? <ide> YAML.unsafe_load(payload) <ide> else <del> YAML.safe_load(payload, permitted_classes: ActiveRecord.yaml_column_permitted_classes, aliases: true) <add> YAML.safe_load(payload, permitted_classes: permitted_classes, aliases: true) <ide> end <ide> end <ide> else <ide> def yaml_load(payload) <del> if ActiveRecord.use_yaml_unsafe_load <add> if unsafe_load? <ide> YAML.load(payload) <ide> else <del> YAML.safe_load(payload, permitted_classes: ActiveRecord.yaml_column_permitted_classes, aliases: true) <add> YAML.safe_load(payload, permitted_classes: permitted_classes, aliases: true) <ide> end <ide> end <ide> end <ide><path>activerecord/test/cases/coders/yaml_column_test.rb <ide> def test_yaml_column_permitted_classes_are_consumed_by_safe_load <ide> ActiveRecord.yaml_column_permitted_classes = @yaml_column_permitted_classes_default <ide> end <ide> <add> def test_yaml_column_permitted_classes_option <add> ActiveRecord.yaml_column_permitted_classes = [Symbol] <add> <add> coder = YAMLColumn.new("attr_name", permitted_classes: [Time]) <add> time_yaml = YAML.dump(Time.new) <add> symbol_yaml = YAML.dump(:somesymbol) <add> <add> assert_nothing_raised do <add> coder.load(time_yaml) <add> coder.load(symbol_yaml) <add> end <add> <add> ActiveRecord.yaml_column_permitted_classes = @yaml_column_permitted_classes_default <add> end <add> <add> def test_yaml_column_unsafe_load_option <add> ActiveRecord.use_yaml_unsafe_load = false <add> ActiveRecord.yaml_column_permitted_classes = [] <add> <add> coder = YAMLColumn.new("attr_name", unsafe_load: true) <add> time_yaml = YAML.dump(Time.new) <add> symbol_yaml = YAML.dump(:somesymbol) <add> <add> assert_nothing_raised do <add> coder.load(time_yaml) <add> coder.load(symbol_yaml) <add> end <add> <add> ActiveRecord.yaml_column_permitted_classes = @yaml_column_permitted_classes_default <add> end <add> <add> def test_yaml_column_override_unsafe_load_option <add> ActiveRecord.use_yaml_unsafe_load = true <add> ActiveRecord.yaml_column_permitted_classes = [] <add> <add> coder = YAMLColumn.new("attr_name", unsafe_load: false) <add> time_yaml = YAML.dump(Time.new) <add> <add> assert_raises(Psych::DisallowedClass) do <add> coder.load(time_yaml) <add> end <add> <add> ActiveRecord.yaml_column_permitted_classes = @yaml_column_permitted_classes_default <add> end <add> <ide> def test_load_doesnt_handle_undefined_class_or_module <ide> coder = YAMLColumn.new("attr_name") <ide> missing_class_yaml = '--- !ruby/object:DoesNotExistAndShouldntEver {}\n'
4
PHP
PHP
simplify merges and cs
f9a44170ee0c979d1bbd229833e0472430aba0da
<ide><path>src/Console/Command/Task/TestTask.php <ide> public function generateConstructor($type, $fullClassName) { <ide> public function generateUses($type, $fullClassName) { <ide> $uses = []; <ide> $type = strtolower($type); <del> if ($type == 'component') { <add> if ($type === 'component') { <ide> $uses[] = 'Cake\Controller\ComponentRegistry'; <ide> } <del> if ($type == 'table') { <add> if ($type === 'table') { <ide> $uses[] = 'Cake\ORM\TableRegistry'; <ide> } <del> if ($type == 'helper') { <add> if ($type === 'helper') { <ide> $uses[] = 'Cake\View\View'; <ide> } <ide> $uses[] = $fullClassName; <ide><path>src/Console/ConsoleInput.php <ide> class ConsoleInput { <ide> * @param string $handle The location of the stream to use as input. <ide> */ <ide> public function __construct($handle = 'php://stdin') { <del> $this->_canReadline = extension_loaded('readline') && $handle == 'php://stdin' ? true : false; <add> $this->_canReadline = extension_loaded('readline') && $handle === 'php://stdin' ? true : false; <ide> $this->_input = fopen($handle, 'r'); <ide> } <ide> <ide><path>src/Console/ConsoleOutput.php <ide> class ConsoleOutput { <ide> public function __construct($stream = 'php://stdout') { <ide> $this->_output = fopen($stream, 'w'); <ide> <del> if (DS == '\\' && !(bool)env('ANSICON')) { <add> if (DS === '\\' && !(bool)env('ANSICON')) { <ide> $this->_outputAs = static::PLAIN; <ide> } <ide> } <ide><path>src/Controller/Component/RequestHandlerComponent.php <ide> public function renderAs(Controller $controller, $type, $options = array()) { <ide> */ <ide> public function respondAs($type, $options = array()) { <ide> $defaults = array('index' => null, 'charset' => null, 'attachment' => false); <del> $options = $options + $defaults; <add> $options += $defaults; <ide> <ide> $cType = $type; <ide> if (strpos($type, '/') === false) { <ide><path>src/Database/Expression/QueryExpression.php <ide> protected function _parseCondition($field, $value) { <ide> if (in_array(strtolower(trim($operator)), ['in', 'not in']) || $typeMultiple) { <ide> $type = $type ?: 'string'; <ide> $type .= $typeMultiple ? null : '[]'; <del> $operator = $operator == '=' ? 'IN' : $operator; <del> $operator = $operator == '!=' ? 'NOT IN' : $operator; <add> $operator = $operator === '=' ? 'IN' : $operator; <add> $operator = $operator === '!=' ? 'NOT IN' : $operator; <ide> $typeMultiple = true; <ide> } <ide> <ide><path>src/Event/EventManager.php <ide> public function attach($callable, $eventKey = null, $options = array()) { <ide> $this->_attachSubscriber($callable); <ide> return; <ide> } <del> $options = $options + array('priority' => static::$defaultPriority); <add> $options += array('priority' => static::$defaultPriority); <ide> $this->_listeners[$eventKey][$options['priority']][] = array( <ide> 'callable' => $callable, <ide> ); <ide><path>src/Log/Engine/FileLog.php <ide> protected function _getFilename($level) { <ide> <ide> if (!empty($this->_file)) { <ide> $filename = $this->_file; <del> } elseif ($level == 'error' || $level == 'warning') { <add> } elseif ($level === 'error' || $level === 'warning') { <ide> $filename = 'error.log'; <ide> } elseif (in_array($level, $debugTypes)) { <ide> $filename = 'debug.log'; <ide><path>src/Network/Http/Response.php <ide> public function __get($name) { <ide> return false; <ide> } <ide> $key = $this->_exposedProperties[$name]; <del> if (substr($key, 0, 4) == '_get') { <add> if (substr($key, 0, 4) === '_get') { <ide> return $this->{$key}(); <ide> } <ide> return $this->{$key}; <ide> public function __isset($name) { <ide> return false; <ide> } <ide> $key = $this->_exposedProperties[$name]; <del> if (substr($key, 0, 4) == '_get') { <add> if (substr($key, 0, 4) === '_get') { <ide> $val = $this->{$key}(); <ide> return $val !== null; <ide> } <ide><path>src/Network/Request.php <ide> public function __construct($config = array()) { <ide> * @return void <ide> */ <ide> protected function _setConfig($config) { <del> if (!empty($config['url']) && $config['url'][0] == '/') { <add> if (!empty($config['url']) && $config['url'][0] === '/') { <ide> $config['url'] = substr($config['url'], 1); <ide> } <ide> <ide><path>src/ORM/Association/SelectableAssociationTrait.php <ide> public function requiresKeys($options = []) { <ide> * <ide> */ <ide> public function eagerLoader(array $options) { <del> $options = $options + $this->_defaultOptions(); <add> $options += $this->_defaultOptions(); <ide> $queryBuilder = false; <ide> if (!empty($options['queryBuilder'])) { <ide> $queryBuilder = $options['queryBuilder']; <ide><path>src/TestSuite/TestCase.php <ide> public function getMockForModel($alias, $methods = array(), $options = array()) <ide> } <ide> <ide> list($plugin, $baseClass) = pluginSplit($alias); <del> $options = $options + ['alias' => $baseClass] + TableRegistry::config($alias); <add> $options += ['alias' => $baseClass] + TableRegistry::config($alias); <ide> <ide> $mock = $this->getMock($options['className'], $methods, array($options)); <ide> TableRegistry::set($alias, $mock); <ide><path>src/View/Helper/FormHelper.php <ide> public function create($model = null, $options = []) { <ide> <ide> $isCreate = $context->isCreate(); <ide> <del> $options = $options + [ <add> $options += [ <ide> 'type' => $isCreate ? 'post' : 'put', <ide> 'action' => null, <ide> 'url' => null, <ide><path>src/View/Helper/HtmlHelper.php <ide> public function css($path, $options = array()) { <ide> $options = array_diff_key($options, array('fullBase' => null, 'pathPrefix' => null)); <ide> } <ide> <del> if ($options['rel'] == 'import') { <add> if ($options['rel'] === 'import') { <ide> $out = $this->formatTemplate('style', [ <ide> 'attrs' => $this->templater()->formatAttributes($options, ['rel', 'block']), <ide> 'content' => '@import url(' . $url . ');', <ide><path>tests/TestCase/BasicsTest.php <ide> public function testDebug() { <ide> * @return void <ide> */ <ide> public function testPr() { <del> $this->skipIf(php_sapi_name() == 'cli', 'Skipping web test in cli mode'); <add> $this->skipIf(php_sapi_name() === 'cli', 'Skipping web test in cli mode'); <ide> ob_start(); <ide> pr('this is a test'); <ide> $result = ob_get_clean(); <ide><path>tests/TestCase/Log/Engine/ConsoleLogTest.php <ide> public function testWriteToFileStream() { <ide> * test default value of stream 'outputAs' <ide> */ <ide> public function testDefaultOutputAs() { <del> if (DS == '\\' && !(bool)env('ANSICON')) { <add> if (DS === '\\' && !(bool)env('ANSICON')) { <ide> $expected = ConsoleOutput::PLAIN; <ide> } else { <ide> $expected = ConsoleOutput::COLOR; <ide><path>tests/TestCase/Network/RequestTest.php <ide> public function testAddDetector() { <ide> $this->assertTrue($request->is('closure')); <ide> <ide> Request::addDetector('get', function ($request) { <del> return $request->env('REQUEST_METHOD') == 'GET'; <add> return $request->env('REQUEST_METHOD') === 'GET'; <ide> }); <ide> $request->env('REQUEST_METHOD', 'GET'); <ide> $this->assertTrue($request->is('get')); <ide><path>tests/TestCase/Routing/DispatcherTest.php <ide> protected function _loadEnvironment($env) { <ide> */ <ide> protected function _cachePath($here) { <ide> $path = $here; <del> if ($here == '/') { <add> if ($here === '/') { <ide> $path = 'home'; <ide> } <ide> $path = strtolower(Inflector::slug($path)); <ide><path>tests/TestCase/Utility/DebuggerTest.php <ide> public function testDump() { <ide> Debugger::dump($var); <ide> $result = ob_get_clean(); <ide> <del> $open = php_sapi_name() == 'cli' ? "\n" : '<pre>'; <del> $close = php_sapi_name() == 'cli' ? "\n" : '</pre>'; <add> $open = php_sapi_name() === 'cli' ? "\n" : '<pre>'; <add> $close = php_sapi_name() === 'cli' ? "\n" : '</pre>'; <ide> $expected = <<<TEXT <ide> {$open}[ <ide> 'People' => [ <ide> public function testDump() { <ide> Debugger::dump($var, 1); <ide> $result = ob_get_clean(); <ide> <del> $open = php_sapi_name() == 'cli' ? "\n" : '<pre>'; <del> $close = php_sapi_name() == 'cli' ? "\n" : '</pre>'; <add> $open = php_sapi_name() === 'cli' ? "\n" : '<pre>'; <add> $close = php_sapi_name() === 'cli' ? "\n" : '</pre>'; <ide> $expected = <<<TEXT <ide> {$open}[ <ide> 'People' => [ <ide> public function testDebugInfo() { <ide> 'inner' => object(Cake\Test\TestCase\Utility\DebuggableThing) { <ide> <ide> [maximum depth reached] <del> <add> <ide> } <ide> <ide> } <ide><path>tests/test_app/TestApp/Controller/SomePostsController.php <ide> class SomePostsController extends Controller { <ide> * @return void <ide> */ <ide> public function beforeFilter(Event $event) { <del> if ($this->request->params['action'] == 'index') { <add> if ($this->request->params['action'] === 'index') { <ide> $this->request->params['action'] = 'view'; <ide> } else { <ide> $this->request->params['action'] = 'change';
19
Javascript
Javascript
check mustcall errors in test-fs-read-type
d7b18662c6a4e88f4d942662903a63a9c6bed46b
<ide><path>test/parallel/test-fs-read-type.js <ide> fs.read(fd, <ide> 0, <ide> expected.length, <ide> 0n, <del> common.mustCall()); <add> common.mustSucceed()); <ide> <ide> fs.read(fd, <ide> Buffer.allocUnsafe(expected.length), <ide> 0, <ide> expected.length, <ide> 2n ** 53n - 1n, <del> common.mustCall()); <add> common.mustCall((err) => { <add> if (err) { <add> assert.strictEqual(err.code, 'EFBIG'); <add> } <add> })); <ide> <ide> assert.throws( <ide> () => fs.readSync(fd, expected.length, 0, 'utf-8'),
1
PHP
PHP
remove trailing whitespace from comments
4090c2e9323e5e3d2112ee7f2f831bd5e5d292a4
<ide><path>app/Config/acl.php <ide> /** <ide> * Example <ide> * ------- <del> * <add> * <ide> * Assumptions: <ide> * <del> * 1. In your application you created a User model with the following properties: <add> * 1. In your application you created a User model with the following properties: <ide> * username, group_id, password, email, firstname, lastname and so on. <del> * 2. You configured AuthComponent to authorize actions via <del> * $this->Auth->authorize = array('Actions' => array('actionPath' => 'controllers/'),...) <del> * <add> * 2. You configured AuthComponent to authorize actions via <add> * $this->Auth->authorize = array('Actions' => array('actionPath' => 'controllers/'),...) <add> * <ide> * Now, when a user (i.e. jeff) authenticates successfully and requests a controller action (i.e. /invoices/delete) <del> * that is not allowed by default (e.g. via $this->Auth->allow('edit') in the Invoices controller) then AuthComponent <del> * will ask the configured ACL interface if access is granted. Under the assumptions 1. and 2. this will be <del> * done via a call to Acl->check() with <add> * that is not allowed by default (e.g. via $this->Auth->allow('edit') in the Invoices controller) then AuthComponent <add> * will ask the configured ACL interface if access is granted. Under the assumptions 1. and 2. this will be <add> * done via a call to Acl->check() with <ide> * <ide> * array('User' => array('username' => 'jeff', 'group_id' => 4, ...)) <ide> * <ide> * '/controllers/invoices/delete' <ide> * <ide> * as ACO. <del> * <add> * <ide> * If the configured map looks like <ide> * <ide> * $config['map'] = array( <ide> * 'User' => 'User/username', <ide> * 'Role' => 'User/group_id', <ide> * ); <ide> * <del> * then PhpAcl will lookup if we defined a role like User/jeff. If that role is not found, PhpAcl will try to <del> * find a definition for Role/4. If the definition isn't found then a default role (Role/default) will be used to <add> * then PhpAcl will lookup if we defined a role like User/jeff. If that role is not found, PhpAcl will try to <add> * find a definition for Role/4. If the definition isn't found then a default role (Role/default) will be used to <ide> * check rules for the given ACO. The search can be expanded by defining aliases in the alias configuration. <ide> * E.g. if you want to use a more readable name than Role/4 in your definitions you can define an alias like <ide> * <ide> * $config['alias'] = array( <ide> * 'Role/4' => 'Role/editor', <ide> * ); <del> * <add> * <ide> * In the roles configuration you can define roles on the lhs and inherited roles on the rhs: <del> * <add> * <ide> * $config['roles'] = array( <ide> * 'Role/admin' => null, <ide> * 'Role/accountant' => null, <ide> * 'Role/editor' => null, <ide> * 'Role/manager' => 'Role/editor, Role/accountant', <ide> * 'User/jeff' => 'Role/manager', <ide> * ); <del> * <add> * <ide> * In this example manager inherits all rules from editor and accountant. Role/admin doesn't inherit from any role. <ide> * Lets define some rules: <ide> * <ide> * ), <ide> * ); <ide> * <del> * Ok, so as jeff inherits from Role/manager he's matched every rule that references User/jeff, Role/manager, <del> * Role/editor, Role/accountant and Role/default. However, for jeff, rules for User/jeff are more specific than <add> * Ok, so as jeff inherits from Role/manager he's matched every rule that references User/jeff, Role/manager, <add> * Role/editor, Role/accountant and Role/default. However, for jeff, rules for User/jeff are more specific than <ide> * rules for Role/manager, rules for Role/manager are more specific than rules for Role/editor and so on. <del> * This is important when allow and deny rules match for a role. E.g. Role/accountant is allowed <add> * This is important when allow and deny rules match for a role. E.g. Role/accountant is allowed <ide> * controllers/invoices/* but at the same time controllers/invoices/delete is denied. But there is a more <ide> * specific rule defined for Role/manager which is allowed controllers/invoices/delete. However, the most specific <ide> * rule denies access to the delete action explicitly for User/jeff, so he'll be denied access to the resource. <ide> <ide> /** <ide> * The role map defines how to resolve the user record from your application <del> * to the roles you defined in the roles configuration. <add> * to the roles you defined in the roles configuration. <ide> */ <ide> $config['map'] = array( <ide> 'User' => 'User/username', <ide><path>app/Config/bootstrap.php <ide> /** <ide> * This file is loaded automatically by the app/webroot/index.php file after core.php <ide> * <del> * This file should load/create any application wide configuration settings, such as <add> * This file should load/create any application wide configuration settings, such as <ide> * Caching, Logging, loading additional configuration files. <ide> * <ide> * You should also use this file to include any files that provide global functions/constants <ide><path>app/Config/core.php <ide> Configure::write('Acl.database', 'default'); <ide> <ide> /** <del> * Uncomment this line and correct your server timezone to fix <add> * Uncomment this line and correct your server timezone to fix <ide> * any date & time related errors. <ide> */ <ide> //date_default_timezone_set('UTC'); <ide> * If running via cli - apc is disabled by default. ensure it's available and enabled in this case <ide> * <ide> * Note: 'default' and other application caches should be configured in app/Config/bootstrap.php. <del> * Please check the comments in boostrap.php for more info on the cache engines available <add> * Please check the comments in boostrap.php for more info on the cache engines available <ide> * and their setttings. <ide> */ <ide> $engine = 'File'; <ide><path>app/Config/routes.php <ide> Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display')); <ide> <ide> /** <del> * Load all plugin routes. See the CakePlugin documentation on <add> * Load all plugin routes. See the CakePlugin documentation on <ide> * how to customize the loading of plugin routes. <ide> */ <ide> CakePlugin::routes(); <ide><path>lib/Cake/Cache/CacheEngine.php <ide> public function init($settings = array()) { <ide> * Garbage collection <ide> * <ide> * Permanently remove all expired and deleted data <del> * <add> * <ide> * @param integer $expires [optional] An expires timestamp, invalidataing all data before. <ide> * @return void <ide> */ <ide><path>lib/Cake/Cache/Engine/FileEngine.php <ide> public function init($settings = array()) { <ide> <ide> /** <ide> * Garbage collection. Permanently remove all expired and deleted data <del> * <add> * <ide> * @param integer $expires [optional] An expires timestamp, invalidataing all data before. <ide> * @return boolean True if garbage collection was successful, false on failure <ide> */ <ide><path>lib/Cake/Console/Command/Task/TemplateTask.php <ide> public function initialize() { <ide> * <ide> * Bake themes are directories not named `skel` inside a `Console/Templates` path. <ide> * They are listed in this order: app -> plugin -> default <del> * <add> * <ide> * @return array Array of bake themes that are installed. <ide> */ <ide> protected function _findThemes() { <ide><path>lib/Cake/Console/Command/TestShell.php <ide> public function available() { <ide> * Find the test case for the passed file. The file could itself be a test. <ide> * <ide> * @param string $file <del> * @param string $category <del> * @param boolean $throwOnMissingFile <add> * @param string $category <add> * @param boolean $throwOnMissingFile <ide> * @access protected <ide> * @return array(type, case) <ide> * @throws Exception <ide><path>lib/Cake/Console/Templates/skel/Config/core.php <ide> Configure::write('Acl.database', 'default'); <ide> <ide> /** <del> * Uncomment this line and correct your server timezone to fix <add> * Uncomment this line and correct your server timezone to fix <ide> * any date & time related errors. <ide> */ <ide> //date_default_timezone_set('UTC'); <ide><path>lib/Cake/Controller/Component.php <ide> public function startup(Controller $controller) { <ide> } <ide> <ide> /** <del> * Called before the Controller::beforeRender(), and before <add> * Called before the Controller::beforeRender(), and before <ide> * the view class is loaded, and before Controller::render() <ide> * <ide> * @param Controller $controller Controller with components to beforeRender <ide><path>lib/Cake/Controller/Component/Acl/IniAcl.php <ide> public function check($aro, $aco, $action = null) { <ide> } <ide> <ide> /** <del> * Parses an INI file and returns an array that reflects the <add> * Parses an INI file and returns an array that reflects the <ide> * INI file's section structure. Double-quote friendly. <ide> * <ide> * @param string $filename File <ide><path>lib/Cake/Controller/Component/Acl/PhpAcl.php <ide> */ <ide> <ide> /** <del> * PhpAcl implements an access control system using a plain PHP configuration file. <add> * PhpAcl implements an access control system using a plain PHP configuration file. <ide> * An example file can be found in app/Config/acl.php <ide> * <ide> * @package Cake.Controller.Component.Acl <ide> class PhpAcl extends Object implements AclInterface { <ide> <ide> /** <ide> * Aco Object <del> * <add> * <ide> * @var PhpAco <ide> */ <ide> public $Aco = null; <ide> public function __construct() { <ide> <ide> /** <ide> * Initialize method <del> * <del> * @param AclComponent $Component Component instance <add> * <add> * @param AclComponent $Component Component instance <ide> * @return void <ide> */ <ide> public function initialize(Component $Component) { <ide> class PhpAco { <ide> <ide> /** <ide> * map modifiers for ACO paths to their respective PCRE pattern <del> * <add> * <ide> * @var array <ide> */ <ide> public static $modifiers = array( <ide> public function path($aco) { <ide> /** <ide> * allow/deny ARO access to ARO <ide> * <del> * @return void <add> * @return void <ide> */ <ide> public function access($aro, $aco, $action, $type = 'deny') { <ide> $aco = $this->resolve($aco); <ide> public function resolve($aco) { <ide> * <ide> * @param array $allow ACO allow rules <ide> * @param array $deny ACO deny rules <del> * @return void <add> * @return void <ide> */ <ide> public function build(array $allow, array $deny = array()) { <ide> $this->_tree = array(); <ide> public function build(array $allow, array $deny = array()) { <ide> class PhpAro { <ide> <ide> /** <del> * role to resolve to when a provided ARO is not listed in <add> * role to resolve to when a provided ARO is not listed in <ide> * the internal tree <ide> * <ide> * @var string <ide> class PhpAro { <ide> /** <ide> * map external identifiers. E.g. if <ide> * <del> * array('User' => array('username' => 'jeff', 'role' => 'editor')) <add> * array('User' => array('username' => 'jeff', 'role' => 'editor')) <ide> * <del> * is passed as an ARO to one of the methods of AclComponent, PhpAcl <add> * is passed as an ARO to one of the methods of AclComponent, PhpAcl <ide> * will check if it can be resolved to an User or a Role defined in the <del> * configuration file. <del> * <add> * configuration file. <add> * <ide> * @var array <ide> * @see app/Config/acl.php <ide> */ <ide> class PhpAro { <ide> <ide> /** <ide> * aliases to map <del> * <add> * <ide> * @var array <ide> */ <ide> public $aliases = array(); <ide> public function __construct(array $aro = array(), array $map = array(), array $a <ide> * From the perspective of the given ARO, walk down the tree and <ide> * collect all inherited AROs levelwise such that AROs from different <ide> * branches with equal distance to the requested ARO will be collected at the same <del> * index. The resulting array will contain a prioritized list of (list of) roles ordered from <add> * index. The resulting array will contain a prioritized list of (list of) roles ordered from <ide> * the most distant AROs to the requested one itself. <del> * <add> * <ide> * @param string|array $aro An ARO identifier <ide> * @return array prioritized AROs <ide> */ <ide> public function roles($aro) { <ide> <ide> /** <ide> * resolve an ARO identifier to an internal ARO string using <del> * the internal mapping information. <add> * the internal mapping information. <ide> * <ide> * @param string|array $aro ARO identifier (User.jeff, array('User' => ...), etc) <ide> * @return string internal aro string (e.g. User/jeff, Role/default) <ide> public function addAlias(array $alias) { <ide> * build an ARO tree structure for internal processing <ide> * <ide> * @param array $aros array of AROs as key and their inherited AROs as values <del> * @return void <add> * @return void <ide> */ <ide> public function build(array $aros) { <ide> $this->_tree = array(); <ide><path>lib/Cake/Controller/Component/Auth/DigestAuthenticate.php <ide> class DigestAuthenticate extends BaseAuthenticate { <ide> * - `realm` The realm authentication is for, Defaults to the servername. <ide> * - `nonce` A nonce used for authentication. Defaults to `uniqid()`. <ide> * - `qop` Defaults to auth, no other values are supported at this time. <del> * - `opaque` A string that must be returned unchanged by clients. <add> * - `opaque` A string that must be returned unchanged by clients. <ide> * Defaults to `md5($settings['realm'])` <ide> * <ide> * @var array <ide><path>lib/Cake/Controller/Component/CookieComponent.php <ide> class CookieComponent extends Component { <ide> <ide> /** <ide> * A reference to the Controller's CakeResponse object <del> * <add> * <ide> * @var CakeResponse <ide> */ <ide> protected $_response = null; <ide><path>lib/Cake/Controller/Component/SecurityComponent.php <ide> App::uses('Security', 'Utility'); <ide> <ide> /** <del> * The Security Component creates an easy way to integrate tighter security in <add> * The Security Component creates an easy way to integrate tighter security in <ide> * your application. It provides methods for various tasks like: <ide> * <ide> * - Restricting which HTTP methods your application accepts. <ide><path>lib/Cake/Controller/Component/SessionComponent.php <ide> App::uses('CakeSession', 'Model/Datasource'); <ide> <ide> /** <del> * The CakePHP SessionComponent provides a way to persist client data between <del> * page requests. It acts as a wrapper for the `$_SESSION` as well as providing <add> * The CakePHP SessionComponent provides a way to persist client data between <add> * page requests. It acts as a wrapper for the `$_SESSION` as well as providing <ide> * convenience methods for several `$_SESSION` related functions. <ide> * <ide> * @package Cake.Controller.Component <ide><path>lib/Cake/Core/CakePlugin.php <ide> */ <ide> <ide> /** <del> * CakePlugin is responsible for loading and unloading plugins. It also can <add> * CakePlugin is responsible for loading and unloading plugins. It also can <ide> * retrieve plugin paths and load their bootstrap and routes files. <ide> * <ide> * @package Cake.Core <ide><path>lib/Cake/Event/CakeEvent.php <ide> class CakeEvent { <ide> <ide> /** <ide> * Name of the event <del> * <add> * <ide> * @var string $name <ide> */ <ide> protected $_name = null; <ide><path>lib/Cake/Event/CakeEventManager.php <ide> class CakeEventManager { <ide> protected $_listeners = array(); <ide> <ide> /** <del> * Internal flag to distinguish a common manager from the sigleton <add> * Internal flag to distinguish a common manager from the sigleton <ide> * <ide> * @var boolean <ide> */ <ide> class CakeEventManager { <ide> * <ide> * If called with a first params, it will be set as the globally available instance <ide> * <del> * @param CakeEventManager $manager <add> * @param CakeEventManager $manager <ide> * @return CakeEventManager the global event manager <ide> */ <ide> public static function instance($manager = null) { <ide> public static function instance($manager = null) { <ide> } <ide> <ide> /** <del> * Adds a new listener to an event. Listeners <add> * Adds a new listener to an event. Listeners <ide> * <ide> * @param callback|CakeEventListener $callable PHP valid callback type or instance of CakeEventListener to be called <ide> * when the event named with $eventKey is triggered. If a CakeEventListener instances is passed, then the `implementedEvents` <ide><path>lib/Cake/Model/Behavior/ContainableBehavior.php <ide> */ <ide> <ide> /** <del> * Behavior to allow for dynamic and atomic manipulation of a Model's associations <del> * used for a find call. Most useful for limiting the amount of associations and <add> * Behavior to allow for dynamic and atomic manipulation of a Model's associations <add> * used for a find call. Most useful for limiting the amount of associations and <ide> * data returned. <ide> * <ide> * @package Cake.Model.Behavior <ide><path>lib/Cake/Model/ConnectionManager.php <ide> /** <ide> * Manages loaded instances of DataSource objects <ide> * <del> * Provides an interface for loading and enumerating connections defined in <add> * Provides an interface for loading and enumerating connections defined in <ide> * app/Config/database.php <ide> * <ide> * @package Cake.Model <ide><path>lib/Cake/Model/Datasource/DataSource.php <ide> public function getSchemaName() { <ide> <ide> /** <ide> * Closes a connection. Override in subclasses <del> * <add> * <ide> * @return boolean <ide> * @access public <ide> */ <ide><path>lib/Cake/Model/Datasource/Database/Sqlserver.php <ide> public function insertMulti($table, $fields, $values) { <ide> /** <ide> * Generate a database-native column schema string <ide> * <del> * @param array $column An array structured like the <add> * @param array $column An array structured like the <ide> * following: array('name'=>'value', 'type'=>'value'[, options]), <ide> * where options can be 'default', 'length', or 'key'. <ide> * @return string <ide><path>lib/Cake/Network/Email/CakeEmail.php <ide> public function config($config = null) { <ide> <ide> /** <ide> * Send an email using the specified content, template and layout <del> * <add> * <ide> * @param string|array $content String with message or array with messages <ide> * @return array <ide> * @throws SocketException <ide> protected function _createBoundary() { <ide> /** <ide> * Attach non-embedded files by adding file contents inside boundaries. <ide> * <del> * @param string $boundary Boundary to use. If null, will default to $this->_boundary <add> * @param string $boundary Boundary to use. If null, will default to $this->_boundary <ide> * @return array An array of lines to add to the message <ide> */ <ide> protected function _attachFiles($boundary = null) { <ide> protected function _readFile($file) { <ide> /** <ide> * Attach inline/embedded files to the message. <ide> * <del> * @param string $boundary Boundary to use. If null, will default to $this->_boundary <add> * @param string $boundary Boundary to use. If null, will default to $this->_boundary <ide> * @return array An array of lines to add to the message <ide> */ <ide> protected function _attachInlineFiles($boundary = null) { <ide><path>lib/Cake/Test/Case/Cache/Engine/FileEngineTest.php <ide> public function testReadAndWriteCache() { <ide> <ide> /** <ide> * Test read/write on the same cache key. Ensures file handles are re-wound. <del> * <add> * <ide> * @return void <ide> */ <ide> public function testConsecutiveReadWrite() { <ide><path>lib/Cake/Test/Case/Console/Command/TestShellTest.php <ide> public function tearDown() { <ide> <ide> /** <ide> * testMapCoreFileToCategory <del> * <add> * <ide> * @return void <ide> */ <ide> public function testMapCoreFileToCategory() { <ide> public function testMapCoreFileToCategory() { <ide> * testMapCoreFileToCase <ide> * <ide> * basics.php is a slightly special case - it's the only file in the core with a test that isn't Capitalized <del> * <add> * <ide> * @return void <ide> */ <ide> public function testMapCoreFileToCase() { <ide> public function testMapCoreFileToCase() { <ide> <ide> /** <ide> * testMapAppFileToCategory <del> * <add> * <ide> * @return void <ide> */ <ide> public function testMapAppFileToCategory() { <ide> public function testMapAppFileToCase() { <ide> <ide> /** <ide> * testMapPluginFileToCategory <del> * <add> * <ide> * @return void <ide> */ <ide> public function testMapPluginFileToCategory() { <ide> public function testMapPluginFileToCase() { <ide> <ide> /** <ide> * testMapCoreTestToCategory <del> * <add> * <ide> * @return void <ide> */ <ide> public function testMapCoreTestToCategory() { <ide> public function testMapCoreTestToCategory() { <ide> * testMapCoreTestToCase <ide> * <ide> * basics.php is a slightly special case - it's the only file in the core with a test that isn't Capitalized <del> * <add> * <ide> * @return void <ide> */ <ide> public function testMapCoreTestToCase() { <ide> public function testMapCoreTestToCase() { <ide> <ide> /** <ide> * testMapAppTestToCategory <del> * <add> * <ide> * @return void <ide> */ <ide> public function testMapAppTestToCategory() { <ide> public function testMapAppTestToCase() { <ide> <ide> /** <ide> * testMapPluginTestToCategory <del> * <add> * <ide> * @return void <ide> */ <ide> public function testMapPluginTestToCategory() { <ide><path>lib/Cake/Test/Case/Event/CakeEventManagerTest.php <ide> public function secondListenerFunction() { <ide> /** <ide> * Auxiliary function to help in stopPropagation testing <ide> * <del> * @param CakeEvent $event <add> * @param CakeEvent $event <ide> * @return void <ide> */ <ide> public function stopListener($event) { <ide><path>lib/Cake/Test/Case/Model/Datasource/DataSourceTest.php <ide> class TestSource extends DataSource { <ide> <ide> /** <ide> * _schema <del> * @var type <add> * @var type <ide> */ <ide> protected $_schema = array( <ide> 'id' => array( <ide><path>lib/Cake/Test/Case/TestSuite/CakeTestFixtureTest.php <ide> public function testInit() { <ide> } <ide> <ide> /** <del> * test that init() correctly sets the fixture table when the connection <add> * test that init() correctly sets the fixture table when the connection <ide> * or model have prefixes defined. <ide> * <ide> * @return void <ide><path>lib/Cake/Test/Case/TestSuite/CakeTestSuiteTest.php <ide> class CakeTestSuiteTest extends CakeTestCase { <ide> <ide> /** <ide> * testAddTestDirectory <del> * <add> * <ide> * @return void <ide> */ <ide> public function testAddTestDirectory() { <ide> public function testAddTestDirectory() { <ide> <ide> /** <ide> * testAddTestDirectoryRecursive <del> * <add> * <ide> * @return void <ide> */ <ide> public function testAddTestDirectoryRecursive() { <ide> public function testAddTestDirectoryRecursive() { <ide> <ide> /** <ide> * testAddTestDirectoryRecursiveWithHidden <del> * <add> * <ide> * @return void <ide> */ <ide> public function testAddTestDirectoryRecursiveWithHidden() { <ide> public function testAddTestDirectoryRecursiveWithHidden() { <ide> <ide> /** <ide> * testAddTestDirectoryRecursiveWithNonPhp <del> * <add> * <ide> * @return void <ide> */ <ide> public function testAddTestDirectoryRecursiveWithNonPhp() { <ide><path>lib/Cake/TestSuite/Fixture/CakeTestFixture.php <ide> App::uses('CakeSchema', 'Model'); <ide> <ide> /** <del> * CakeTestFixture is responsible for building and destroying tables to be used <add> * CakeTestFixture is responsible for building and destroying tables to be used <ide> * during testing. <ide> * <ide> * @package Cake.TestSuite.Fixture <ide><path>lib/Cake/Utility/File.php <ide> public function copy($dest, $overwrite = true) { <ide> } <ide> <ide> /** <del> * Get the mime type of the file. Uses the finfo extension if <add> * Get the mime type of the file. Uses the finfo extension if <ide> * its available, otherwise falls back to mime_content_type <ide> * <ide> * @return false|string The mimetype of the file, or false if reading fails. <ide><path>lib/Cake/View/Helper/SessionHelper.php <ide> public function error() { <ide> * echo $this->Session->flash('flash', array('element' => 'my_custom_element')); <ide> * }}} <ide> * <del> * If you want to use an element from a plugin for rendering your flash message you can do that using the <add> * If you want to use an element from a plugin for rendering your flash message you can do that using the <ide> * plugin param: <ide> * <ide> * {{{ <ide><path>lib/Cake/View/JsonView.php <ide> * <ide> * `$this->set(array('posts' => $posts, '_serialize' => 'posts'));` <ide> * <del> * When the view is rendered, the `$posts` view variable will be serialized <add> * When the view is rendered, the `$posts` view variable will be serialized <ide> * into JSON. <ide> * <ide> * You can also define `'_serialize'` as an array. This will create a top level object containing <ide> * $this->set(compact('posts', 'users', 'stuff')); <ide> * $this->set('_serialize', array('posts', 'users')); <ide> * }}} <del> * <add> * <ide> * The above would generate a JSON object that looks like: <ide> * <ide> * `{"posts": [...], "users": [...]}` <ide> class JsonView extends View { <ide> <ide> /** <del> * JSON views are always located in the 'json' sub directory for a <add> * JSON views are always located in the 'json' sub directory for a <ide> * controllers views. <del> * <add> * <ide> * @var string <ide> */ <ide> public $subDir = 'json'; <ide> public function __construct(Controller $controller = null) { <ide> * Render a JSON view. <ide> * <ide> * Uses the special '_serialize' parameter to convert a set of <del> * view variables into a JSON response. Makes generating simple <del> * JSON responses very easy. You can omit the '_serialize' parameter, <add> * view variables into a JSON response. Makes generating simple <add> * JSON responses very easy. You can omit the '_serialize' parameter, <ide> * and use a normal view + layout as well. <ide> * <ide> * @param string $view The view being rendered. <ide><path>lib/Cake/View/ViewBlock.php <ide> public function end() { <ide> } <ide> <ide> /** <del> * Append to an existing or new block. Appending to a new <add> * Append to an existing or new block. Appending to a new <ide> * block will create the block. <ide> * <ide> * Calling append() without a value will create a new capturing
35
Python
Python
fix init of language without model
83ba6c247c47fc1fc1fce5d45e1c4f94b6fe3d9b
<ide><path>spacy/language.py <ide> def __init__(self, **overrides): <ide> path = pathlib.Path(path) <ide> if path is True: <ide> path = util.get_data_path() / self.lang <del> <add> if not path.exists() and 'path' not in overrides: <add> path = None <ide> self.meta = overrides.get('meta', {}) <ide> self.path = path <ide>
1
Text
Text
add laravel bootcamp to learning laravel
4a73b5d57e518bd907875e97d5261c8546703e79
<ide><path>README.md <ide> Laravel is accessible, powerful, and provides tools required for large, robust a <ide> <ide> Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework. <ide> <add>You may also try the [Laravel Bootcamp](https://bootcamp.laravel.com), where you will be guided through building a modern Laravel application from scratch. <add> <ide> If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains over 2000 video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library. <ide> <ide> ## Laravel Sponsors
1
Javascript
Javascript
move type domcontainer to hostconfig
ccab49473897aacae43bb4d55c1061065892403c
<ide><path>packages/react-dom/src/client/ReactDOM.js <ide> * @flow <ide> */ <ide> <del>import type {RootType} from './ReactDOMRoot'; <ide> import type {ReactNodeList} from 'shared/ReactTypes'; <add>import type {Container} from './ReactDOMHostConfig'; <ide> <ide> import '../shared/checkReact'; <ide> import './ReactDOMClientInjection'; <ide> setBatchingImplementation( <ide> batchedEventUpdates, <ide> ); <ide> <del>export type DOMContainer = <del> | (Element & {_reactRootContainer: ?RootType, ...}) <del> | (Document & {_reactRootContainer: ?RootType, ...}); <del> <ide> function createPortal( <ide> children: ReactNodeList, <del> container: DOMContainer, <add> container: Container, <ide> key: ?string = null, <ide> ) { <ide> invariant( <ide><path>packages/react-dom/src/client/ReactDOMHostConfig.js <ide> * @flow <ide> */ <ide> <add>import type {RootType} from './ReactDOMRoot'; <add> <ide> import { <ide> precacheFiberNode, <ide> updateFiberProps, <ide> import { <ide> } from '../shared/HTMLNodeType'; <ide> import dangerousStyleValue from '../shared/dangerousStyleValue'; <ide> <del>import type {DOMContainer} from './ReactDOM'; <ide> import type { <ide> ReactDOMEventResponder, <ide> ReactDOMEventResponderInstance, <ide> export type EventTargetChildElement = { <ide> }, <ide> ... <ide> }; <del>export type Container = DOMContainer; <add>export type Container = <add> | (Element & {_reactRootContainer: ?RootType, ...}) <add> | (Document & {_reactRootContainer: ?RootType, ...}); <ide> export type Instance = Element; <ide> export type TextInstance = Text; <ide> export type SuspenseInstance = Comment & {_reactRetry?: () => void, ...}; <ide> export function appendChild( <ide> } <ide> <ide> export function appendChildToContainer( <del> container: DOMContainer, <add> container: Container, <ide> child: Instance | TextInstance, <ide> ): void { <ide> let parentNode; <ide><path>packages/react-dom/src/client/ReactDOMLegacy.js <ide> * @flow <ide> */ <ide> <del>import type {DOMContainer} from './ReactDOM'; <add>import type {Container} from './ReactDOMHostConfig'; <ide> import type {RootType} from './ReactDOMRoot'; <ide> import type {ReactNodeList} from 'shared/ReactTypes'; <ide> <ide> let topLevelUpdateWarnings; <ide> let warnedAboutHydrateAPI = false; <ide> <ide> if (__DEV__) { <del> topLevelUpdateWarnings = (container: DOMContainer) => { <add> topLevelUpdateWarnings = (container: Container) => { <ide> if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) { <ide> const hostInstance = findHostInstanceWithNoPortals( <ide> container._reactRootContainer._internalRoot.current, <ide> function shouldHydrateDueToLegacyHeuristic(container) { <ide> } <ide> <ide> function legacyCreateRootFromDOMContainer( <del> container: DOMContainer, <add> container: Container, <ide> forceHydrate: boolean, <ide> ): RootType { <ide> const shouldHydrate = <ide> function warnOnInvalidCallback(callback: mixed, callerName: string): void { <ide> function legacyRenderSubtreeIntoContainer( <ide> parentComponent: ?React$Component<any, any>, <ide> children: ReactNodeList, <del> container: DOMContainer, <add> container: Container, <ide> forceHydrate: boolean, <ide> callback: ?Function, <ide> ) { <ide> export function findDOMNode( <ide> <ide> export function hydrate( <ide> element: React$Node, <del> container: DOMContainer, <add> container: Container, <ide> callback: ?Function, <ide> ) { <ide> invariant( <ide> export function hydrate( <ide> <ide> export function render( <ide> element: React$Element<any>, <del> container: DOMContainer, <add> container: Container, <ide> callback: ?Function, <ide> ) { <ide> invariant( <ide> export function render( <ide> export function unstable_renderSubtreeIntoContainer( <ide> parentComponent: React$Component<any, any>, <ide> element: React$Element<any>, <del> containerNode: DOMContainer, <add> containerNode: Container, <ide> callback: ?Function, <ide> ) { <ide> invariant( <ide> export function unstable_renderSubtreeIntoContainer( <ide> ); <ide> } <ide> <del>export function unmountComponentAtNode(container: DOMContainer) { <add>export function unmountComponentAtNode(container: Container) { <ide> invariant( <ide> isValidContainer(container), <ide> 'unmountComponentAtNode(...): Target container is not a DOM element.', <ide><path>packages/react-dom/src/client/ReactDOMRoot.js <ide> * @flow <ide> */ <ide> <del>import type {DOMContainer} from './ReactDOM'; <add>import type {Container} from './ReactDOMHostConfig'; <ide> import type {RootTag} from 'shared/ReactRootTags'; <ide> import type {ReactNodeList} from 'shared/ReactTypes'; <ide> // TODO: This type is shared between the reconciler and ReactDOM, but will <ide> import {createContainer, updateContainer} from 'react-reconciler/inline.dom'; <ide> import invariant from 'shared/invariant'; <ide> import {BlockingRoot, ConcurrentRoot, LegacyRoot} from 'shared/ReactRootTags'; <ide> <del>function ReactDOMRoot(container: DOMContainer, options: void | RootOptions) { <add>function ReactDOMRoot(container: Container, options: void | RootOptions) { <ide> this._internalRoot = createRootImpl(container, ConcurrentRoot, options); <ide> } <ide> <ide> function ReactDOMBlockingRoot( <del> container: DOMContainer, <add> container: Container, <ide> tag: RootTag, <ide> options: void | RootOptions, <ide> ) { <ide> ReactDOMRoot.prototype.unmount = ReactDOMBlockingRoot.prototype.unmount = functi <ide> }; <ide> <ide> function createRootImpl( <del> container: DOMContainer, <add> container: Container, <ide> tag: RootTag, <ide> options: void | RootOptions, <ide> ) { <ide> function createRootImpl( <ide> } <ide> <ide> export function createRoot( <del> container: DOMContainer, <add> container: Container, <ide> options?: RootOptions, <ide> ): RootType { <ide> invariant( <ide> export function createRoot( <ide> } <ide> <ide> export function createBlockingRoot( <del> container: DOMContainer, <add> container: Container, <ide> options?: RootOptions, <ide> ): RootType { <ide> invariant( <ide> export function createBlockingRoot( <ide> } <ide> <ide> export function createLegacyRoot( <del> container: DOMContainer, <add> container: Container, <ide> options?: RootOptions, <ide> ): RootType { <ide> return new ReactDOMBlockingRoot(container, LegacyRoot, options); <ide><path>packages/react-dom/src/events/ReactDOMEventReplaying.js <ide> import type {Container, SuspenseInstance} from '../client/ReactDOMHostConfig'; <ide> import type {DOMTopLevelEventType} from 'legacy-events/TopLevelEventTypes'; <ide> import type {EventSystemFlags} from 'legacy-events/EventSystemFlags'; <ide> import type {FiberRoot} from 'react-reconciler/src/ReactFiberRoot'; <del>import type {DOMContainer} from '../client/ReactDOM'; <ide> <ide> import { <ide> enableDeprecatedFlareAPI, <ide> function trapReplayableEventForDocument( <ide> } <ide> <ide> export function eagerlyTrapReplayableEvents( <del> container: DOMContainer, <add> container: Container, <ide> document: Document, <ide> ) { <ide> const listenerMapForDoc = getListenerMapForElement(document);
5
PHP
PHP
add expire option by default
3646070dc125f65dad2b1e1ec4877e3849e1781e
<ide><path>config/queue.php <ide> 'redis' => [ <ide> 'driver' => 'redis', <ide> 'queue' => 'default', <add> 'expire' => 60, <ide> ], <ide> <ide> ],
1
Ruby
Ruby
fix rubocop warnings
fc7ac2f07b93a4037652df673cafce6619598f6b
<ide><path>Library/Homebrew/test/test_resource.rb <ide> def test_checksum_setters <ide> <ide> def test_download_strategy <ide> strategy = Object.new <del> DownloadStrategyDetector. <del> expects(:detect).with("foo", nil).returns(strategy) <add> DownloadStrategyDetector <add> .expects(:detect).with("foo", nil).returns(strategy) <ide> @resource.url("foo") <ide> assert_equal strategy, @resource.download_strategy <ide> end <ide> def test_verify_download_integrity_mismatch <ide> fn = stub(:file? => true) <ide> checksum = @resource.sha256(TEST_SHA256) <ide> <del> fn.expects(:verify_checksum).with(checksum). <del> raises(ChecksumMismatchError.new(fn, checksum, Object.new)) <add> fn.expects(:verify_checksum).with(checksum) <add> .raises(ChecksumMismatchError.new(fn, checksum, Object.new)) <ide> <ide> shutup do <ide> assert_raises(ChecksumMismatchError) do
1
PHP
PHP
fix failing tests and missing boundary markers
83b28c42cf1470924b47df6e88e0282d05ecc441
<ide><path>lib/Cake/Network/Email/CakeEmail.php <ide> public function getHeaders($include = array()) { <ide> } <ide> <ide> $headers['MIME-Version'] = '1.0'; <del> if (!empty($this->_attachments)) { <add> if (!empty($this->_attachments) || $this->_emailFormat === 'both') { <ide> $headers['Content-Type'] = 'multipart/mixed; boundary="' . $this->_boundary . '"'; <ide> } elseif ($this->_emailFormat === 'text') { <ide> $headers['Content-Type'] = 'text/plain; charset=' . $this->charset; <ide> } elseif ($this->_emailFormat === 'html') { <ide> $headers['Content-Type'] = 'text/html; charset=' . $this->charset; <del> } elseif ($this->_emailFormat === 'both') { <del> $headers['Content-Type'] = 'multipart/alternative; boundary="alt-' . $this->_boundary . '"'; <ide> } <ide> $headers['Content-Transfer-Encoding'] = $this->_getContentTransferEncoding(); <ide> <ide> protected function _render($content) { <ide> if ($hasAttachments) { <ide> $attachments = $this->_attachFiles(); <ide> $msg = array_merge($msg, $attachments); <add> } <add> if ($hasAttachments || $hasMultipleTypes) { <ide> $msg[] = ''; <ide> $msg[] = '--' . $boundary . '--'; <ide> $msg[] = ''; <ide><path>lib/Cake/Test/Case/Controller/Component/EmailComponentTest.php <ide> public function testSendFormats() { <ide> $expect = str_replace('{CONTENTTYPE}', 'text/html; charset=UTF-8', $message); <ide> $this->assertTrue($this->Controller->EmailTest->send('This is the body of the message')); <ide> $this->assertEquals(DebugCompTransport::$lastEmail, $this->__osFix($expect)); <del> <del> // TODO: better test for format of message sent? <del> $this->Controller->EmailTest->sendAs = 'both'; <del> $expect = str_replace('{CONTENTTYPE}', 'multipart/alternative; boundary="alt-"', $message); <del> $this->assertTrue($this->Controller->EmailTest->send('This is the body of the message')); <del> $this->assertEquals(preg_replace('/alt-[a-z0-9]{32}/i', 'alt-', DebugCompTransport::$lastEmail), $this->__osFix($expect)); <ide> } <ide> <ide> /** <ide> public function testTemplates() { <ide> $this->assertEquals(DebugCompTransport::$lastEmail, $this->__osFix($expect)); <ide> <ide> $this->Controller->EmailTest->sendAs = 'both'; <del> $expect = str_replace('{CONTENTTYPE}', 'multipart/alternative; boundary="alt-"', $header); <del> $expect .= '--alt-' . "\n" . 'Content-Type: text/plain; charset=UTF-8' . "\n" . 'Content-Transfer-Encoding: 8bit' . "\n\n" . $text . "\n\n"; <del> $expect .= '--alt-' . "\n" . 'Content-Type: text/html; charset=UTF-8' . "\n" . 'Content-Transfer-Encoding: 8bit' . "\n\n" . $html . "\n\n"; <del> $expect = '<pre>' . $expect . '--alt---' . "\n\n" . '</pre>'; <add> $expect = str_replace('{CONTENTTYPE}', 'multipart/mixed; boundary="{boundary}"', $header); <add> $expect .= "--{boundary}\n" . <add> 'Content-Type: multipart/alternative; boundary="alt-{boundary}"' . "\n\n" . <add> '--alt-{boundary}' . "\n" . <add> 'Content-Type: text/plain; charset=UTF-8' . "\n" . <add> 'Content-Transfer-Encoding: 8bit' . "\n\n" . <add> $text . <add> "\n\n" . <add> '--alt-{boundary}' . "\n" . <add> 'Content-Type: text/html; charset=UTF-8' . "\n" . <add> 'Content-Transfer-Encoding: 8bit' . "\n\n" . <add> $html . <add> "\n\n" . <add> '--alt-{boundary}--' . "\n\n\n" . <add> '--{boundary}--' . "\n"; <add> <add> $expect = '<pre>' . $expect . '</pre>'; <ide> <ide> $this->assertTrue($this->Controller->EmailTest->send('This is the body of the message')); <del> $this->assertEquals(preg_replace('/alt-[a-z0-9]{32}/i', 'alt-', DebugCompTransport::$lastEmail), $this->__osFix($expect)); <add> $this->assertEquals( <add> $this->__osFix($expect), <add> preg_replace('/[a-z0-9]{32}/i', '{boundary}', DebugCompTransport::$lastEmail) <add> ); <ide> <ide> $html = <<<HTMLBLOC <ide> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"> <ide> public function testMessageRetrievalWithoutTemplate() { <ide> <ide> $this->Controller->EmailTest->delivery = 'DebugComp'; <ide> <del> $text = $html = 'This is the body of the message'; <add> $text = $html = "This is the body of the message\n"; <ide> <ide> $this->Controller->EmailTest->sendAs = 'both'; <ide> $this->assertTrue($this->Controller->EmailTest->send('This is the body of the message')); <ide> public function testSendAsIsNotIgnoredIfAttachmentsPresent() { <ide> $this->assertTrue($this->Controller->EmailTest->send($body)); <ide> $msg = DebugCompTransport::$lastEmail; <ide> <del> $this->assertNotRegExp('/text\/plain/', $msg); <del> $this->assertNotRegExp('/text\/html/', $msg); <add> $this->assertRegExp('/text\/plain/', $msg); <add> $this->assertRegExp('/text\/html/', $msg); <ide> $this->assertRegExp('/multipart\/alternative/', $msg); <ide> } <ide> <ide><path>lib/Cake/Test/Case/Network/Email/CakeEmailTest.php <ide> public function testSendMultipleMIME() { <ide> $boundary = $this->CakeEmail->getBoundary(); <ide> $this->assertFalse(empty($boundary)); <ide> $this->assertContains('--' . $boundary, $message); <del> $this->assertNotContains('--' . $boundary . '--', $message); <add> $this->assertContains('--' . $boundary . '--', $message); <ide> $this->assertContains('--alt-' . $boundary, $message); <ide> $this->assertContains('--alt-' . $boundary . '--', $message); <ide>
3
Javascript
Javascript
prevent computedproperty shape from changing
a542ca8a699419247f3c7106278aa53673fccf49
<ide><path>packages/ember-metal/lib/computed.js <ide> ComputedProperty.prototype = new Ember.Descriptor(); <ide> var ComputedPropertyPrototype = ComputedProperty.prototype; <ide> ComputedPropertyPrototype._dependentKeys = undefined; <ide> ComputedPropertyPrototype._suspended = undefined; <add>ComputedPropertyPrototype._meta = undefined; <ide> <ide> if (Ember.FEATURES.isEnabled('composable-computed-properties')) { <ide> ComputedPropertyPrototype._dependentCPs = undefined;
1
PHP
PHP
resolvepolicycallback()
52d126abce14b9b2152b74318f7e1f0e260c5246
<ide><path>src/Illuminate/Auth/Access/Gate.php <ide> protected function resolvePolicyCallback($user, $ability, array $arguments) <ide> } <ide> } <ide> <del> if (! method_exists($instance, $ability)) { <add> if (! is_callable([$instance, $ability])) { <ide> return false; <ide> } <ide>
1
PHP
PHP
fix autolinkurls so it re-capture query strings
b1dfab87e44f4248ea9263627456cab23eb63b5c
<ide><path>lib/Cake/Test/Case/View/Helper/TextHelperTest.php <ide> public function testAutoLinkUrls() { <ide> $result = $this->Text->autoLinkUrls($text); <ide> $this->assertEquals($expected, $result); <ide> <add> $text = 'This is a test that includes www.cakephp.org:8080'; <add> $expected = 'This is a test that includes <a href="http://www.cakephp.org:8080">www.cakephp.org:8080</a>'; <add> $result = $this->Text->autoLinkUrls($text); <add> $this->assertEquals($expected, $result); <add> <ide> $text = 'This is a test that includes http://de.wikipedia.org/wiki/Kanton_(Schweiz)#fragment'; <ide> $expected = 'This is a test that includes <a href="http://de.wikipedia.org/wiki/Kanton_(Schweiz)#fragment">http://de.wikipedia.org/wiki/Kanton_(Schweiz)#fragment</a>'; <ide> $result = $this->Text->autoLinkUrls($text); <ide> public function testAutoLinkUrls() { <ide> $result = $this->Text->autoLinkUrls($text); <ide> $this->assertEquals($expected, $result); <ide> <add> $text = 'This is a test that includes http://example.com/test.php?foo=bar text'; <add> $expected = 'This is a test that includes <a href="http://example.com/test.php?foo=bar">http://example.com/test.php?foo=bar</a> text'; <add> $result = $this->Text->autoLinkUrls($text); <add> $this->assertEquals($expected, $result); <add> <add> $text = 'This is a test that includes www.example.com/test.php?foo=bar text'; <add> $expected = 'This is a test that includes <a href="http://www.example.com/test.php?foo=bar">www.example.com/test.php?foo=bar</a> text'; <add> $result = $this->Text->autoLinkUrls($text); <add> $this->assertEquals($expected, $result); <add> <ide> $text = 'Text with a partial www.cakephp.org URL'; <ide> $expected = 'Text with a partial <a href="http://www.cakephp.org"\s*>www.cakephp.org</a> URL'; <ide> $result = $this->Text->autoLinkUrls($text); <ide><path>lib/Cake/View/Helper/TextHelper.php <ide> public function autoLinkUrls($text, $options = array()) { <ide> $this->_placeholders = array(); <ide> $options += array('escape' => true); <ide> <del> $pattern = '#(?<!href="|src="|">)((?:https?|ftp|nntp)://[^\s<>()]+\.[a-z]+(?:\/[^\s]+)?)#i'; <add> $pattern = '#(?<!href="|src="|">)((?:https?|ftp|nntp)://[a-z0-9.\-:]+(?:/[^\s]*)?)#i'; <ide> $text = preg_replace_callback( <ide> $pattern, <ide> array(&$this, '_insertPlaceHolder'),
2
Javascript
Javascript
fix unnecessary coercion in lib/net.js
657cd2c4e5940d32883a6791be41978a6d07afb8
<ide><path>lib/net.js <ide> function connect(self, address, port, addressType, localAddress) { <ide> <ide> var err; <ide> if (localAddress) { <del> if (addressType == 6) { <add> if (addressType === 6) { <ide> err = self._handle.bind6(localAddress); <ide> } else { <ide> err = self._handle.bind(localAddress); <ide> var createServerHandle = exports._createServerHandle = <ide> handle.writable = true; <ide> return handle; <ide> <del> } else if (port == -1 && addressType == -1) { <add> } else if (port === -1 && addressType === -1) { <ide> handle = createPipe(); <ide> if (process.platform === 'win32') { <ide> var instances = parseInt(process.env.NODE_PENDING_PIPE_INSTANCES); <ide> var createServerHandle = exports._createServerHandle = <ide> <ide> if (address || port) { <ide> debug('bind to ' + address); <del> if (addressType == 6) { <add> if (addressType === 6) { <ide> err = handle.bind6(address, port); <ide> } else { <ide> err = handle.bind(address, port);
1
Javascript
Javascript
add more spaces for more pretty code
283b8ba703529799daab9812a5a0242ab0b80334
<ide><path>test/cases/chunks/inline-options/index.js <ide> it("should be able to use eager mode", function(done) { <ide> function load(name) { <del> return import(/* webpackMode: "eager" */"./dir1/" + name); <add> return import(/* webpackMode: "eager" */ "./dir1/" + name); <ide> } <ide> testChunkLoading(load, true, true, done); <ide> }); <ide> <ide> it("should be able to use lazy-once mode", function(done) { <ide> function load(name) { <del> return import(/* webpackMode: "lazy-once" */"./dir2/" + name); <add> return import(/* webpackMode: "lazy-once" */ "./dir2/" + name); <ide> } <ide> testChunkLoading(load, false, true, done); <ide> }); <ide> <ide> it("should be able to use lazy-once mode with name", function(done) { <ide> function load(name) { <del> return import(/* webpackMode: "lazy-once", webpackChunkName: "name-lazy-once" */"./dir3/" + name); <add> return import(/* webpackMode: "lazy-once", webpackChunkName: "name-lazy-once" */ "./dir3/" + name); <ide> } <ide> testChunkLoading(load, false, true, done); <ide> }); <ide> <ide> it("should be able to use lazy mode", function(done) { <ide> function load(name) { <del> return import(/* webpackMode: "lazy" */"./dir4/" + name); <add> return import(/* webpackMode: "lazy" */ "./dir4/" + name); <ide> } <ide> testChunkLoading(load, false, false, done); <ide> }); <ide> <ide> it("should be able to use lazy mode with name", function(done) { <ide> function load(name) { <del> return import(/* webpackMode: "lazy", webpackChunkName: "name-lazy" */"./dir5/" + name); <add> return import(/* webpackMode: "lazy", webpackChunkName: "name-lazy" */ "./dir5/" + name); <ide> } <ide> testChunkLoading(load, false, false, done); <ide> }); <ide> <ide> it("should be able to use lazy mode with name and placeholder", function(done) { <ide> function load(name) { <del> return import(/* webpackMode: "lazy", webpackChunkName: "name-lazy-[request]" */"./dir6/" + name); <add> return import(/* webpackMode: "lazy", webpackChunkName: "name-lazy-[request]" */ "./dir6/" + name); <ide> } <ide> testChunkLoading(load, false, false, done); <ide> });
1
Javascript
Javascript
improve assert message in test-dh-regr
42dfde827b39f4298ee8491dedf588d103662dc9
<ide><path>test/pummel/test-dh-regr.js <ide> for (let i = 0; i < 2000; i++) { <ide> a.generateKeys(); <ide> b.generateKeys(); <ide> <add> const aSecret = a.computeSecret(b.getPublicKey()); <add> const bSecret = b.computeSecret(a.getPublicKey()); <add> <ide> assert.deepStrictEqual( <del> a.computeSecret(b.getPublicKey()), <del> b.computeSecret(a.getPublicKey()), <del> 'secrets should be equal!' <add> aSecret, <add> bSecret, <add> 'Secrets should be equal.\n' + <add> `aSecret: ${aSecret.toString('base64')}\n` + <add> `bSecret: ${bSecret.toString('base64')}` <ide> ); <ide> }
1
Text
Text
add note about mkdtemp() platform differences
dd9cad9cb34f37ad47bf67996118efbc07787a2b
<ide><path>doc/api/fs.md <ide> changes: <ide> Creates a unique temporary directory. <ide> <ide> Generates six random characters to be appended behind a required <del>`prefix` to create a unique temporary directory. <add>`prefix` to create a unique temporary directory. Due to platform <add>inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms, <add>notably the BSDs, can return more than six random characters, and replace <add>trailing `X` characters in `prefix` with random characters. <ide> <ide> The created folder path is passed as a string to the callback's second <ide> parameter. <ide> added: v10.0.0 <ide> <ide> Creates a unique temporary directory and resolves the `Promise` with the created <ide> folder path. A unique directory name is generated by appending six random <del>characters to the end of the provided `prefix`. <add>characters to the end of the provided `prefix`. Due to platform <add>inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms, <add>notably the BSDs, can return more than six random characters, and replace <add>trailing `X` characters in `prefix` with random characters. <ide> <ide> The optional `options` argument can be a string specifying an encoding, or an <ide> object with an `encoding` property specifying the character encoding to use.
1
Go
Go
fix copy file . after workdir
f0b93b6ed8b4c0776065be972b4d5b4611f25fbf
<ide><path>daemon/create_windows.go <ide> func (daemon *Daemon) createContainerPlatformSpecificSettings(container *contain <ide> hostConfig.Isolation = daemon.defaultIsolation <ide> } <ide> <add> if err := daemon.Mount(container); err != nil { <add> return nil <add> } <add> defer daemon.Unmount(container) <add> if err := container.SetupWorkingDirectory(0, 0); err != nil { <add> return err <add> } <add> <ide> for spec := range config.Volumes { <ide> <ide> mp, err := volume.ParseMountRaw(spec, hostConfig.VolumeDriver) <ide><path>integration-cli/docker_cli_build_test.go <ide> func (s *DockerSuite) TestBuildWindowsWorkdirProcessing(c *check.C) { <ide> func (s *DockerSuite) TestBuildWindowsAddCopyPathProcessing(c *check.C) { <ide> testRequires(c, DaemonIsWindows) <ide> name := "testbuildwindowsaddcopypathprocessing" <del> // TODO Windows (@jhowardmsft). Needs a follow-up PR to 22181 to <del> // support backslash such as .\\ being equivalent to ./ and c:\\ being <del> // equivalent to c:/. This is not currently (nor ever has been) supported <del> // by docker on the Windows platform. <ide> dockerfile := ` <ide> FROM busybox <ide> # No trailing slash on COPY/ADD <ide> func (s *DockerSuite) TestBuildWindowsAddCopyPathProcessing(c *check.C) { <ide> WORKDIR /wc2 <ide> ADD wc2 c:/wc2 <ide> WORKDIR c:/ <del> RUN sh -c "[ $(cat c:/wc1) = 'hellowc1' ]" <del> RUN sh -c "[ $(cat c:/wc2) = 'worldwc2' ]" <add> RUN sh -c "[ $(cat c:/wc1/wc1) = 'hellowc1' ]" <add> RUN sh -c "[ $(cat c:/wc2/wc2) = 'worldwc2' ]" <ide> <ide> # Trailing slash on COPY/ADD, Windows-style path. <ide> WORKDIR /wd1 <ide> RUN echo vegeta <ide> c.Assert(out, checker.Contains, "Step 2/3 : RUN echo grafana && echo raintank") <ide> c.Assert(out, checker.Contains, "Step 3/3 : RUN echo vegeta") <ide> } <add> <add>// Verifies if COPY file . when WORKDIR is set to a non-existing directory, <add>// the directory is created and the file is copied into the directory, <add>// as opposed to the file being copied as a file with the name of the <add>// directory. Fix for 27545 (found on Windows, but regression good for Linux too) <add>func (s *DockerSuite) TestBuildCopyFileDotWithWorkdir(c *check.C) { <add> name := "testbuildcopyfiledotwithworkdir" <add> <add> ctx, err := fakeContext(`FROM busybox <add>WORKDIR /foo <add>COPY file . <add>RUN ["cat", "/foo/file"] <add>`, <add> map[string]string{}) <add> if err != nil { <add> c.Fatal(err) <add> } <add> defer ctx.Close() <add> if err := ctx.Add("file", "content"); err != nil { <add> c.Fatal(err) <add> } <add> if _, err = buildImageFromContext(name, ctx, true); err != nil { <add> c.Fatal(err) <add> } <add>}
2
Text
Text
fix objc syntax error
ed370eeaad84895efa99d2efba9bcc461ae21312
<ide><path>README.md <ide> It is certainly possible to create a great app using React Native without writin <ide> - (void)processString:(NSString *)input callback:(RCTResponseSenderBlock)callback <ide> { <ide> RCT_EXPORT(); // available as NativeModules.MyCustomModule.processString <del> callback(@[[input stringByReplacingOccurrencesOfString:@"Goodbye" withString:@"Hello"];]]); <add> callback(@[[input stringByReplacingOccurrencesOfString:@"Goodbye" withString:@"Hello"]]); <ide> } <ide> @end <ide> ```
1
Javascript
Javascript
fix missing parameter for radialaxialshading
8572c29c55ce74c728400b1b5408e1d2bed97975
<ide><path>pdf.js <ide> var RadialAxialShading = (function() { <ide> var p0 = raw[3]; <ide> var p1 = raw[4]; <ide> var r0 = raw[5]; <add> var r1 = raw[6]; <ide> <ide> var curMatrix = ctx.mozCurrentTransform; <ide> if (curMatrix) { <ide> var RadialAxialShading = (function() { <ide> var p0 = [coordsArr[0], coordsArr[1]]; <ide> var p1 = [coordsArr[2], coordsArr[3]]; <ide> var r0 = null; <add> var r1 = null; <ide> } else if (type == 3) { <ide> var p0 = [coordsArr[0], coordsArr[1]]; <ide> var p1 = [coordsArr[3], coordsArr[4]]; <del> var r0 = coordsArr[2], r1 = coordsArr[5]; <add> var r0 = coordsArr[2]; <add> var r1 = coordsArr[5]; <ide> } else { <ide> error('getPattern type unknown: ' + type); <ide> } <ide> var RadialAxialShading = (function() { <ide> p1 = Util.applyTransform(p1, matrix); <ide> } <ide> <del> return [ "RadialAxialShading", type, this.colorStops, p0, p1, r0 ]; <add> return [ "RadialAxialShading", type, this.colorStops, p0, p1, r0, r1 ]; <ide> } <ide> }; <ide>
1
Go
Go
use same hash for same secret
a579ce8ed307024ededd527819bfdbf38e970fbf
<ide><path>daemon/cluster/convert/swarm.go <ide> func SwarmSpecToGRPCandMerge(s types.Spec, existingSpec *swarmapi.ClusterSpec) ( <ide> // SwarmSpecUpdateAcceptancePolicy updates a grpc ClusterSpec using AcceptancePolicy. <ide> func SwarmSpecUpdateAcceptancePolicy(spec *swarmapi.ClusterSpec, acceptancePolicy types.AcceptancePolicy, oldSpec *swarmapi.ClusterSpec) error { <ide> spec.AcceptancePolicy.Policies = nil <add> hashs := make(map[string][]byte) <add> <ide> for _, p := range acceptancePolicy.Policies { <ide> role, ok := swarmapi.NodeRole_value[strings.ToUpper(string(p.Role))] <ide> if !ok { <ide> func SwarmSpecUpdateAcceptancePolicy(spec *swarmapi.ClusterSpec, acceptancePolic <ide> if *p.Secret == "" { // if provided secret is empty, it means erase previous secret. <ide> policy.Secret = nil <ide> } else { // if provided secret is not empty, we generate a new one. <del> hashPwd, _ := bcrypt.GenerateFromPassword([]byte(*p.Secret), 0) <add> hashPwd, ok := hashs[*p.Secret] <add> if !ok { <add> hashPwd, _ = bcrypt.GenerateFromPassword([]byte(*p.Secret), 0) <add> hashs[*p.Secret] = hashPwd <add> } <ide> policy.Secret = &swarmapi.AcceptancePolicy_RoleAdmissionPolicy_HashedSecret{ <ide> Data: hashPwd, <ide> Alg: "bcrypt",
1
Ruby
Ruby
use tempfile and some style fixes
28072021031836937a01e9fd995b03995fe49443
<ide><path>Library/Homebrew/cask/lib/hbc/artifact/pkg.rb <ide> def run_installer(pkg_description) <ide> args << "-verboseR" if Hbc.verbose <ide> args << "-allowUntrusted" if pkg_install_opts :allow_untrusted <ide> if pkg_install_opts :choices <del> args << "-applyChoiceChangesXML" <del> args << choices_xml <add> choices_file = choices_xml <add> args << "-applyChoiceChangesXML" << choices_file.path <ide> end <ide> @command.run!("/usr/sbin/installer", sudo: true, args: args, print_stdout: true) <ide> end <ide> <ide> def choices_xml <del> path = @cask.staged_path.join("Choices.xml") <del> unless File.exist? path <del> choices = pkg_install_opts :choices <del> IO.write path, Plist::Emit.dump(choices) <del> end <del> path <add> file = Tempfile.open(["", ".xml"]) <add> file.write Plist::Emit.dump(pkg_install_opts(:choices)) <add> file <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/cask/test/cask/artifact/pkg_test.rb <ide> end <ide> <ide> it "passes the choice changes xml to the system installer" do <del> pkg = Hbc::Artifact::Pkg.new(@cask, <del> command: Hbc::FakeSystemCommand) <del> <del> Hbc::FakeSystemCommand.expects_command(["/usr/bin/sudo", "-E", "--", "/usr/sbin/installer", "-pkg", @cask.staged_path.join("MyFancyPkg", "Fancy.pkg"), "-target", "/", "-applyChoiceChangesXML", @cask.staged_path.join("Choices.xml")]) <add> pkg = Hbc::Artifact::Pkg.new(@cask, command: Hbc::FakeSystemCommand) <ide> <del> shutup do <del> pkg.install_phase <del> end <del> <del> IO.read(@cask.staged_path.join("Choices.xml")).must_equal <<-EOS.undent <add> file = mock <add> file.expects(:write).with <<-EOS.undent <ide> <?xml version="1.0" encoding="UTF-8"?> <ide> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <ide> <plist version="1.0"> <ide> <array> <del> <dict> <del> <key>attributeSetting</key> <del> <integer>1</integer> <del> <key>choiceAttribute</key> <del> <string>selected</string> <del> <key>choiceIdentifier</key> <del> <string>choice1</string> <del> </dict> <add> \t<dict> <add> \t\t<key>attributeSetting</key> <add> \t\t<integer>1</integer> <add> \t\t<key>choiceAttribute</key> <add> \t\t<string>selected</string> <add> \t\t<key>choiceIdentifier</key> <add> \t\t<string>choice1</string> <add> \t</dict> <ide> </array> <ide> </plist> <ide> EOS <add> file.stubs path: Pathname.new("/tmp/choices.xml") <add> Tempfile.expects(:open).returns(file) <add> Hbc::FakeSystemCommand.expects_command(["/usr/bin/sudo", "-E", "--", "/usr/sbin/installer", "-pkg", @cask.staged_path.join("MyFancyPkg", "Fancy.pkg"), "-target", "/", "-applyChoiceChangesXML", @cask.staged_path.join("/tmp/choices.xml")]) <add> <add> shutup do <add> pkg.install_phase <add> end <ide> end <ide> end <ide> end
2
Javascript
Javascript
use arrow function for callback
7bc5300e2be74424347e0072bf22f6fbfe5cd0b9
<ide><path>lib/internal/streams/async_iterator.js <ide> function onReadable(iter) { <ide> } <ide> <ide> function wrapForNext(lastPromise, iter) { <del> return function(resolve, reject) { <del> lastPromise.then(function() { <add> return (resolve, reject) => { <add> lastPromise.then(() => { <ide> iter[kHandlePromise](resolve, reject); <ide> }, reject); <ide> };
1
Python
Python
add ptvsd to run_squad
2499b0a5fcdb168ccb0095e837b2022953935af2
<ide><path>examples/run_squad.py <ide> def main(): <ide> parser.add_argument('--null_score_diff_threshold', <ide> type=float, default=0.0, <ide> help="If null_score - best_non_null is greater than the threshold predict null.") <add> parser.add_argument('--server_ip', type=str, default='', help="Can be used for distant debugging.") <add> parser.add_argument('--server_port', type=str, default='', help="Can be used for distant debugging.") <ide> args = parser.parse_args() <add> print(args) <add> <add> if args.server_ip and args.server_port: <add> # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script <add> import ptvsd <add> print("Waiting for debugger attach") <add> ptvsd.enable_attach(address=(args.server_ip, args.server_port), redirect_output=True) <add> ptvsd.wait_for_attach() <ide> <ide> if args.local_rank == -1 or args.no_cuda: <ide> device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
1
Javascript
Javascript
add flow directive to index.android.js
cd9271567fb0467df7c34057d3a330cba5a847a9
<ide><path>local-cli/generator/templates/index.android.js <ide> /** <ide> * Sample React Native App <ide> * https://github.com/facebook/react-native <add> * @flow <ide> */ <ide> <ide> import React, { Component } from 'react';
1
Go
Go
fix typos in comments
53e5f33279c6f21cfd9e8366d240124e62f8a11a
<ide><path>builder/evaluator.go <ide> func (b *builder) isBuildArgAllowed(arg string) bool { <ide> // <ide> // ONBUILD is a special case; in this case the parser will emit: <ide> // Child[Node, Child[Node, Node...]] where the first node is the literal <del>// "onbuild" and the child entrypoint is the command of the ONBUILD statmeent, <add>// "onbuild" and the child entrypoint is the command of the ONBUILD statement, <ide> // such as `RUN` in ONBUILD RUN foo. There is special case logic in here to <ide> // deal with that, at least until it becomes more of a general concern with new <ide> // features. <ide> func (b *builder) dispatch(stepN int, ast *parser.Node) error { <ide> cmd := ast.Value <ide> <del> // To ensure the user is give a decent error message if the platform <add> // To ensure the user is given a decent error message if the platform <ide> // on which the daemon is running does not support a builder command. <ide> if err := platformSupports(strings.ToLower(cmd)); err != nil { <ide> return err
1
Text
Text
fix missing newline character
f91218c58f6b3aa13e162f3cda5a82a0941ff45c
<ide><path>COLLABORATOR_GUIDE.md <ide> LTS working group and the Release team. <ide> [backporting guide]: doc/guides/backporting-to-release-lines.md <ide> [Stability Index]: doc/api/documentation.md#stability-index <ide> [Enhancement Proposal]: https://github.com/nodejs/node-eps <del>[git-username]: https://help.github.com/articles/setting-your-username-in-git/ <ide>\ No newline at end of file <add>[git-username]: https://help.github.com/articles/setting-your-username-in-git/
1
Java
Java
fix crash in sapienz bot for interpolator type
9737774b965d1b4e875f697b9c004fdcbafe7698
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/layoutanimation/AbstractLayoutAnimation.java <ide> <ide> package com.facebook.react.uimanager.layoutanimation; <ide> <del>import android.os.Build; <ide> import android.view.View; <ide> import android.view.animation.AccelerateDecelerateInterpolator; <ide> import android.view.animation.AccelerateInterpolator; <ide> public void initializeFromConfig(ReadableMap data, int globalDuration) { <ide> } <ide> <ide> private static Interpolator getInterpolator(InterpolatorType type, ReadableMap params) { <del> Interpolator interpolator = null; <add> Interpolator interpolator; <ide> if (type.equals(InterpolatorType.SPRING)) { <ide> interpolator = new SimpleSpringInterpolator(SimpleSpringInterpolator.getSpringDamping(params)); <ide> } else { <del> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { <del> // Conversion from BaseInterpolator to Interpolator is only possible on this Android versions <del> interpolator = INTERPOLATOR.get(type); <del> } <add> interpolator = INTERPOLATOR.get(type); <ide> } <ide> if (interpolator == null) { <ide> throw new IllegalArgumentException("Missing interpolator for type : " + type);
1
Javascript
Javascript
remove redundant call to socket.settimeout()
cc5de5a5cc08551c54a2c1c40c05aa934d2156eb
<ide><path>lib/_http_server.js <ide> function resOnFinish(req, res, socket, state, server) { <ide> } <ide> } else if (state.outgoing.length === 0) { <ide> if (server.keepAliveTimeout && typeof socket.setTimeout === 'function') { <del> socket.setTimeout(0); <ide> socket.setTimeout(server.keepAliveTimeout); <ide> state.keepAliveTimeoutSet = true; <ide> }
1
Ruby
Ruby
define __setobj__ for delegator
828914a062d3fd6cd51ebd3881acea11eede45cc
<ide><path>activesupport/lib/active_support/deprecation.rb <ide> def warn(callstack, called, args) <ide> <ide> class DeprecatedInstanceVariable < Delegator #:nodoc: <ide> def initialize(value, method) <del> super(value) <ide> @method = method <del> @value = value <add> super(value) <add> __setobj__(value) <ide> end <ide> <ide> def __getobj__ <ide> ActiveSupport::Deprecation.warn("Instance variable @#{@method} is deprecated! Call instance method #{@method} instead.") <ide> @value <ide> end <add> <add> def __setobj__(value) <add> @value = value <add> end <ide> end <ide> <ide> end
1
PHP
PHP
update exception class
dbfbcbadd4a3957059fb94f2fbe5efa34b460311
<ide><path>src/Datasource/ModelAwareTrait.php <ide> protected function _setModelClass($name) <ide> * @param string $type The type of repository to load. Defaults to 'Table' which <ide> * delegates to Cake\ORM\TableRegistry. <ide> * @return object The model instance created. <del> * @throws \Cake\Model\Exception\MissingModelException If the model class cannot be found. <add> * @throws \Cake\Datasource\Exception\MissingModelException If the model class cannot be found. <ide> * @throws \InvalidArgumentException When using a type that has not been registered. <ide> */ <ide> public function loadModel($modelClass = null, $type = 'Table')
1
PHP
PHP
add flatmap method to collection
5ad598c6b445630895743844695b0a0ada732e66
<ide><path>src/Illuminate/Support/Collection.php <ide> public function map(callable $callback) <ide> return new static(array_combine($keys, $items)); <ide> } <ide> <add> /** <add> * Map a collection and flatten the result by a single level. <add> * <add> * @param callable $callback <add> * @return static <add> */ <add> public function flatMap(callable $callback) <add> { <add> return $this->map($callback)->collapse(); <add> } <add> <ide> /** <ide> * Get the max value of a given key. <ide> * <ide><path>tests/Support/SupportCollectionTest.php <ide> public function testMap() <ide> $this->assertEquals(['first' => 'first-rolyat', 'last' => 'last-llewto'], $data->all()); <ide> } <ide> <add> public function testFlatMap() <add> { <add> $data = new Collection([ <add> ['name' => 'taylor', 'hobbies' => ['programming', 'basketball']], <add> ['name' => 'adam', 'hobbies' => ['music', 'powerlifting']], <add> ]); <add> $data = $data->flatMap(function ($person) { return $person['hobbies']; }); <add> $this->assertEquals(['programming', 'basketball', 'music', 'powerlifting'], $data->all()); <add> } <add> <ide> public function testTransform() <ide> { <ide> $data = new Collection(['first' => 'taylor', 'last' => 'otwell']);
2
Ruby
Ruby
use the direct accessor
dda013050fe559e2e9432ae836c1239eac48fbce
<ide><path>test/variation_test.rb <ide> class ActiveStorage::VariationTest < ActiveSupport::TestCase <ide> blob = ActiveStorage::Blob.create_after_upload! \ <ide> io: File.open(File.expand_path("../fixtures/files/racecar.jpg", __FILE__)), filename: "racecar.jpg", content_type: "image/jpeg" <ide> <del> variation_key = ActiveStorage::Variant.encode_key(resize: "500x500") <del> <del> variant = ActiveStorage::Variant.lookup(blob_key: blob.key, variation_key: variation_key) <add> variant = blob.variant(resize: "100x100") <ide> <ide> assert_match /racecar.jpg/, variant.url <ide> end
1
Javascript
Javascript
change concatenated string to template
23afa3067258dd20ad76643158caf508e7480032
<ide><path>lib/dns.js <ide> function errnoException(err, syscall, hostname) { <ide> } <ide> var ex = null; <ide> if (typeof err === 'string') { // c-ares error code. <del> const errHost = hostname ? ' ' + hostname : ''; <add> const errHost = hostname ? ` ${hostname}` : ''; <ide> ex = new Error(`${syscall} ${err}${errHost}`); <ide> ex.code = err; <ide> ex.errno = err;
1
PHP
PHP
improve test reliability
e11fda05616f1ed6c18b7d8a948acdedca3627dc
<ide><path>tests/TestCase/Http/Client/Adapter/CurlTest.php <ide> public function testBuildOptionsCurlOptions() <ide> public function testNetworkException() <ide> { <ide> $this->expectException(NetworkException::class); <del> $this->expectExceptionMessage('cURL Error (6) Could not resolve host: dummy'); <add> $this->expectExceptionMessage('cURL Error (6) Could not resolve'); <add> $this->expectExceptionMessage('dummy'); <add> <ide> $request = new Request('http://dummy/?sleep'); <ide> $options = [ <ide> 'timeout' => 2,
1
Text
Text
add the error message the user will run into
3e5575c91c3f27bec06f6a64a3b3b7a9eb55d343
<ide><path>official/mnist/README.md <ide> APIs. <ide> ## Setup <ide> <ide> To begin, you'll simply need the latest version of TensorFlow installed. <del>First make sure you've [added the models folder to your Python path](/official/#running-the-models). <add>First make sure you've [added the models folder to your Python path](/official/#running-the-models); otherwise you may encounter an error like `ImportError: No module named official.mnist`. <ide> <ide> Then to train the model, run the following: <ide> <ide><path>official/resnet/README.md <ide> Please proceed according to which dataset you would like to train/evaluate on: <ide> ### Setup <ide> <ide> You simply need to have the latest version of TensorFlow installed. <del>First make sure you've [added the models folder to your Python path](/official/#running-the-models). <add>First make sure you've [added the models folder to your Python path](/official/#running-the-models); otherwise you may encounter an error like `ImportError: No module named official.resnet`. <ide> <ide> Then download and extract the CIFAR-10 data from Alex's website, specifying the location with the `--data_dir` flag. Run the following: <ide> <ide><path>official/wide_deep/README.md <ide> The input function for the `Estimator` uses `tf.contrib.data.TextLineDataset`, w <ide> The `Estimator` and `Dataset` APIs are both highly encouraged for fast development and efficient training. <ide> <ide> ## Running the code <del>First make sure you've [added the models folder to your Python path](/official/#running-the-models). <add>First make sure you've [added the models folder to your Python path](/official/#running-the-models); otherwise you may encounter an error like `ImportError: No module named official.wide_deep`. <ide> <ide> ### Setup <ide> The [Census Income Data Set](https://archive.ics.uci.edu/ml/datasets/Census+Income) that this sample uses for training is hosted by the [UC Irvine Machine Learning Repository](https://archive.ics.uci.edu/ml/datasets/). We have provided a script that downloads and cleans the necessary files.
3
Text
Text
remove example code from challenge seed
2aee480c467127e594f0af1bd7121fa7ac83e3f0
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/generate-random-whole-numbers-with-javascript.english.md <ide> Use this technique to generate and return a random whole number between <code>0< <ide> tests: <ide> - text: The result of <code>randomWholeNum</code> should be a whole number. <ide> testString: assert(typeof randomWholeNum() === "number" && (function(){var r = randomWholeNum();return Math.floor(r) === r;})()); <del> - text: You should be using <code>Math.random</code> to generate a random number. <del> testString: assert(code.match(/Math.random/g).length > 1); <add> - text: You should use <code>Math.random</code> to generate a random number. <add> testString: assert(code.match(/Math.random/g).length >= 1); <ide> - text: You should have multiplied the result of <code>Math.random</code> by 10 to make it a number that is between zero and nine. <ide> testString: assert(code.match(/\s*?Math.random\s*?\(\s*?\)\s*?\*\s*?10[\D]\s*?/g) || code.match(/\s*?10\s*?\*\s*?Math.random\s*?\(\s*?\)\s*?/g)); <ide> - text: You should use <code>Math.floor</code> to remove the decimal part of the number. <del> testString: assert(code.match(/Math.floor/g).length > 1); <add> testString: assert(code.match(/Math.floor/g).length >= 1); <ide> <ide> ``` <ide> <ide> tests: <ide> <div id='js-seed'> <ide> <ide> ```js <del>var randomNumberBetween0and19 = Math.floor(Math.random() * 20); <del> <ide> function randomWholeNum() { <ide> <ide> // Only change code below this line <ide> function randomWholeNum() { <ide> <ide> <ide> ```js <del>var randomNumberBetween0and19 = Math.floor(Math.random() * 20); <ide> function randomWholeNum() { <ide> return Math.floor(Math.random() * 10); <ide> }
1
Text
Text
add note to packagers.md about libseccomp version
35667c3826d111babdeb35c7ab54609813fdb464
<ide><path>project/PACKAGERS.md <ide> To build the Docker daemon, you will additionally need: <ide> 2.02.89 or later <ide> * btrfs-progs version 3.16.1 or later (unless using an older version is <ide> absolutely necessary, in which case 3.8 is the minimum) <add>* libseccomp version 2.2.1 or later (for build tag seccomp) <ide> * yubico-piv-tool version 1.1.0 or later (for experimental) <ide> <ide> Be sure to also check out Docker's Dockerfile for the most up-to-date list of
1
Ruby
Ruby
fix keyword arguments warnings on `try`
9ee8d9160f965be9ad6d9fb0ecbe282734ec523c
<ide><path>activesupport/lib/active_support/core_ext/object/try.rb <ide> def try(method_name = nil, *args, &b) <ide> public_send(method_name, *args, &b) <ide> end <ide> end <add> ruby2_keywords(:try) if respond_to?(:ruby2_keywords, true) <ide> <ide> def try!(method_name = nil, *args, &b) <ide> if method_name.nil? && block_given? <ide> def try!(method_name = nil, *args, &b) <ide> public_send(method_name, *args, &b) <ide> end <ide> end <add> ruby2_keywords(:try!) if respond_to?(:ruby2_keywords, true) <ide> end <ide> end <ide>
1
Javascript
Javascript
add a regression test for
75491a8f4b5924424b94198e7a56b3519f6430c6
<ide><path>packages/react-dom/src/__tests__/ReactDOMSelect-test.js <ide> describe('ReactDOMSelect', () => { <ide> <ide> document.body.removeChild(container); <ide> }); <add> <add> it('should not select first option by default when multiple is set and no defaultValue is set', () => { <add> const stub = ( <add> <select multiple={true} onChange={noop}> <add> <option value="a">a</option> <add> <option value="b">b</option> <add> <option value="c">c</option> <add> </select> <add> ); <add> const container = document.createElement('div'); <add> const node = ReactDOM.render(stub, container); <add> <add> expect(node.options[0].selected).toBe(false); // a <add> expect(node.options[1].selected).toBe(false); // b <add> expect(node.options[2].selected).toBe(false); // c <add> }); <ide> });
1
Python
Python
add tests for non-int slice deprecation
5de9999d82fa2353fce4518a83c187a168bf2aa3
<ide><path>numpy/core/tests/test_deprecations.py <ide> def check_does_not_raise(f, category): <ide> np.testing.assert_(not raised) <ide> <ide> <del>class TestFloatIndexDeprecation(object): <add>class TestFloatScalarIndexDeprecation(object): <ide> """ <ide> These test that DeprecationWarnings get raised when you <ide> try to use scalar indices that are not integers e.g. a[0.0], <ide> class TestFloatIndexDeprecation(object): <ide> be removed from npy_pycompat.h and changed to just PyIndex_Check. <ide> """ <ide> def setUp(self): <del> warnings.filterwarnings("error", message="non-integer", <add> warnings.filterwarnings("error", message="non-integer scalar index", <ide> category=DeprecationWarning) <ide> <ide> def tearDown(self): <del> warnings.filterwarnings("default", message="non-integer", <add> warnings.filterwarnings("default", message="non-integer scalar index", <ide> category=DeprecationWarning) <ide> <ide> def test_deprecations(self): <ide> def test_deprecations(self): <ide> yield check_for_warning, lambda: a[0, 0, -1.4], DeprecationWarning <ide> yield check_for_warning, lambda: a[-1.4, 0, 0], DeprecationWarning <ide> yield check_for_warning, lambda: a[0, -1.4, 0], DeprecationWarning <add> # Test that the slice parameter deprecation warning doesn't mask <add> # the scalar index warning. <add> yield check_for_warning, lambda: a[0.0:, 0.0], DeprecationWarning <add> yield check_for_warning, lambda: a[0.0:, 0.0, :], DeprecationWarning <ide> <ide> def test_valid_not_deprecated(self): <ide> a = np.array([[[5]]]) <ide> def test_valid_not_deprecated(self): <ide> DeprecationWarning) <ide> yield (check_does_not_raise, lambda: a[:, :, :], <ide> DeprecationWarning) <add> <add> <add>class TestFloatSliceParameterDeprecation(object): <add> def setUp(self): <add> warnings.filterwarnings("error", message="non-integer slice param", <add> category=DeprecationWarning) <add> <add> def tearDown(self): <add> warnings.filterwarnings("default", message="non-integer slice param", <add> category=DeprecationWarning) <add> <add> def test_deprecations(self): <add> a = np.array([[5]]) <add> if sys.version_info[:2] < (2, 5): <add> raise SkipTest() <add> # start as float. <add> yield check_for_warning, lambda: a[0.0:], DeprecationWarning <add> yield check_for_warning, lambda: a[0:, 0.0:2], DeprecationWarning <add> yield check_for_warning, lambda: a[0.0::2, :0], DeprecationWarning <add> yield check_for_warning, lambda: a[0.0:1:2, :], DeprecationWarning <add> yield check_for_warning, lambda: a[:, 0.0:], DeprecationWarning <add> # stop as float. <add> yield check_for_warning, lambda: a[:0.0], DeprecationWarning <add> yield check_for_warning, lambda: a[:0, 1:2.0], DeprecationWarning <add> yield check_for_warning, lambda: a[:0.0:2, :0], DeprecationWarning <add> yield check_for_warning, lambda: a[:0.0, :], DeprecationWarning <add> yield check_for_warning, lambda: a[:, 0:4.0:2], DeprecationWarning <add> # step as float. <add> yield check_for_warning, lambda: a[::1.0], DeprecationWarning <add> yield check_for_warning, lambda: a[0:, :2:2.0], DeprecationWarning <add> yield check_for_warning, lambda: a[1::4.0, :0], DeprecationWarning <add> yield check_for_warning, lambda: a[::5.0, :], DeprecationWarning <add> yield check_for_warning, lambda: a[:, 0:4:2.0], DeprecationWarning <add> # mixed. <add> yield check_for_warning, lambda: a[1.0:2:2.0], DeprecationWarning <add> yield check_for_warning, lambda: a[1.0::2.0], DeprecationWarning <add> yield check_for_warning, lambda: a[0:, :2.0:2.0], DeprecationWarning <add> yield check_for_warning, lambda: a[1.0:1:4.0, :0], DeprecationWarning <add> yield check_for_warning, lambda: a[1.0:5.0:5.0, :], DeprecationWarning <add> yield check_for_warning, lambda: a[:, 0.4:4.0:2.0], DeprecationWarning <add> # should still get the DeprecationWarning if step = 0. <add> yield check_for_warning, lambda: a[::0.0], DeprecationWarning <add> <add> def test_valid_not_deprecated(self): <add> a = np.array([[[5]]]) <add> yield (check_does_not_raise, lambda: a[::], <add> DeprecationWarning) <add> yield (check_does_not_raise, lambda: a[0:], <add> DeprecationWarning) <add> yield (check_does_not_raise, lambda: a[:2], <add> DeprecationWarning) <add> yield (check_does_not_raise, lambda: a[0:2], <add> DeprecationWarning) <add> yield (check_does_not_raise, lambda: a[::2], <add> DeprecationWarning) <add> yield (check_does_not_raise, lambda: a[1::2], <add> DeprecationWarning) <add> yield (check_does_not_raise, lambda: a[:2:2], <add> DeprecationWarning) <add> yield (check_does_not_raise, lambda: a[1:2:2], <add> DeprecationWarning)
1
Javascript
Javascript
improve mixin function, remove object require
13260bf514863b5453ee5bd5073c1dabd16d94c9
<ide><path>packages/sproutcore-runtime/lib/system/binding.js <ide> // ========================================================================== <ide> /*globals sc_assert */ <ide> <del>require('sproutcore-runtime/system/object'); <ide> require('sproutcore-runtime/system/run_loop'); <ide> <ide> // .......................................................... <ide> Binding.prototype = { <ide> <ide> }; <ide> <del>function mixinClassMethods(obj, classMethods) { <del> for (var key in classMethods) { <del> if (typeof classMethods[key] === 'function') { <del> obj[key] = classMethods[key]; <add>function mixinProperties(to, from) { <add> for (var key in from) { <add> if (from.hasOwnProperty(key)) { <add> to[key] = from[key]; <ide> } <ide> } <ide> }; <ide> <del>mixinClassMethods(Binding, { <add>mixinProperties(Binding, { <ide> <ide> /** <ide> @see SC.Binding.prototype.from
1
Ruby
Ruby
use correct filename for schema cache on load
e95b3fd21f4af7fdb180365b4516c4efe513eb8e
<ide><path>activerecord/lib/active_record/railtie.rb <ide> class Railtie < Rails::Railtie # :nodoc: <ide> if config.active_record.delete(:use_schema_cache_dump) <ide> config.after_initialize do |app| <ide> ActiveSupport.on_load(:active_record) do <del> filename = File.join(app.config.paths["db"].first, "schema_cache.yml") <add> db_config = ActiveRecord::Base.configurations.configs_for( <add> env_name: Rails.env, <add> spec_name: "primary", <add> ) <add> filename = ActiveRecord::Tasks::DatabaseTasks.cache_dump_filename( <add> db_config.spec_name, <add> schema_cache_path: db_config.schema_cache_path, <add> ) <ide> <ide> if File.file?(filename) <ide> current_version = ActiveRecord::Migrator.current_version <ide><path>railties/test/application/loading_test.rb <ide> class Post < ApplicationRecord <ide> setup_ar! <ide> <ide> initial = [ActiveStorage::Blob, ActiveStorage::Attachment, ActiveRecord::SchemaMigration, ActiveRecord::InternalMetadata, ApplicationRecord, "primary::SchemaMigration"].collect(&:to_s).sort <del> assert_equal initial, ActiveRecord::Base.descendants.collect(&:to_s).sort <add> assert_equal initial, ActiveRecord::Base.descendants.collect(&:to_s).sort.uniq <ide> get "/load" <ide> assert_equal [Post].collect(&:to_s).sort, ActiveRecord::Base.descendants.collect(&:to_s).sort - initial <ide> get "/unload"
2
Javascript
Javascript
use soundmanager in pressability and touchable
9dbe5e241e3137196102fb808c181c57554fedfe
<ide><path>Libraries/Components/Touchable/Touchable.js <ide> const StyleSheet = require('../../StyleSheet/StyleSheet'); <ide> const TVEventHandler = require('../AppleTV/TVEventHandler'); <ide> const UIManager = require('../../ReactNative/UIManager'); <ide> const View = require('../View/View'); <add>const SoundManager = require('../Sound/SoundManager'); <ide> <ide> const keyMirror = require('fbjs/lib/keyMirror'); <ide> const normalizeColor = require('../../Color/normalizeColor'); <ide> const TouchableMixin = { <ide> this._endHighlight(e); <ide> } <ide> if (Platform.OS === 'android' && !this.props.touchSoundDisabled) { <del> this._playTouchSound(); <add> SoundManager.playTouchSound(); <ide> } <ide> this.touchableHandlePress(e); <ide> } <ide> const TouchableMixin = { <ide> this.touchableDelayTimeout = null; <ide> }, <ide> <del> _playTouchSound: function() { <del> UIManager.playTouchSound(); <del> }, <del> <ide> _startHighlight: function(e: PressEvent) { <ide> this._savePressInLocation(e); <ide> this.touchableHandleActivePressIn && this.touchableHandleActivePressIn(e);
1
Ruby
Ruby
cache the result
4529df1246a8db82ee07c4945f62b801ba6bf655
<ide><path>Library/Homebrew/utils/git.rb <ide> module Utils <ide> def self.git_available? <add> return @git if instance_variable_defined?(:@git) <ide> git = which("git") <ide> # git isn't installed by older Xcodes <del> return false if git.nil? <add> return @git = false if git.nil? <ide> # /usr/bin/git is a popup stub when Xcode/CLT aren't installed, so bail out <del> return false if git == "/usr/bin/git" && !OS::Mac.has_apple_developer_tools? <del> true <add> return @git = false if git == "/usr/bin/git" && !OS::Mac.has_apple_developer_tools? <add> @git = true <ide> end <ide> <ide> def self.ensure_git_installed!
1
Python
Python
improve coverage of nd_grid
18a0fab98ffe4f11fbeb2c3db60bbd69b3b957e5
<ide><path>numpy/lib/tests/test_index_tricks.py <ide> from __future__ import division, absolute_import, print_function <ide> <add>import pytest <add> <ide> import numpy as np <ide> from numpy.testing import ( <ide> assert_, assert_equal, assert_array_equal, assert_almost_equal, <ide> def test_sparse(self): <ide> for f, b in zip(grid_full, grid_broadcast): <ide> assert_equal(f, b) <ide> <add> @pytest.mark.parametrize("start, stop, step, expected", [ <add> (None, 10, 10j, (200, 10)), <add> (-10, 20, None, (1800, 30)), <add> ]) <add> def test_mgrid_size_none_handling(self, start, stop, step, expected): <add> # regression test None value handling for <add> # start and step values used by mgrid; <add> # internally, this aims to cover previously <add> # unexplored code paths in nd_grid() <add> grid = mgrid[start:stop:step, start:stop:step] <add> # need a smaller grid to explore one of the <add> # untested code paths <add> grid_small = mgrid[start:stop:step] <add> assert_equal(grid.size, expected[0]) <add> assert_equal(grid_small.size, expected[1]) <add> <ide> <ide> class TestConcatenator(object): <ide> def test_1d(self):
1
Python
Python
improve efficiency of backprop of padding variable
260e6ee3fbc829b04b269f9960e6cb676d0c33ff
<ide><path>spacy/_ml.py <ide> def _add_padding(self, Yf): <ide> <ide> def _backprop_padding(self, dY, ids): <ide> # (1, nF, nO, nP) += (nN, nF, nO, nP) where IDs (nN, nF) < 0 <del> for i in range(ids.shape[0]): <del> for j in range(ids.shape[1]): <del> if ids[i,j] < 0: <del> self.d_pad[0,j] += dY[i, j] <add> d_pad = dY * (ids.reshape((ids.shape[0], self.nF, 1, 1)) < 0.) <add> self.d_pad += d_pad.sum(axis=0) <ide> return dY, ids <ide> <ide> @staticmethod
1
PHP
PHP
alter wrong doc-block
046fd7c7710e4f89dfb9b8e47b1edd0e980eb6bb
<ide><path>src/Validation/Validation.php <ide> public static function imageWidth($file, string $operator, int $width): bool <ide> } <ide> <ide> /** <del> * Validates the image width. <add> * Validates the image height. <ide> * <ide> * @param mixed $file The uploaded file data from PHP. <ide> * @param string $operator Comparison operator. <del> * @param int $height Min or max width. <add> * @param int $height Min or max height. <ide> * @return bool <ide> */ <ide> public static function imageHeight($file, string $operator, int $height): bool
1
Ruby
Ruby
remove unneeded rubocop comment
e2d8e3c6ee2e3d35d808ec5f7a12449118a2306c
<ide><path>Library/Homebrew/utils/fork.rb <ide> def self.safe_fork(&_block) <ide> ignore_interrupts(:quietly) do # the child will receive the interrupt and marshal it back <ide> begin <ide> socket = server.accept_nonblock <del> # rubocop:disable Lint/ShadowedException <del> # FIXME: https://github.com/bbatsov/rubocop/issues/4843 <ide> rescue Errno::EAGAIN, Errno::EWOULDBLOCK, Errno::ECONNABORTED, Errno::EPROTO, Errno::EINTR <ide> retry unless Process.waitpid(pid, Process::WNOHANG) <del> # rubocop:enable Lint/ShadowedException <ide> else <ide> socket.send_io(write) <ide> socket.close
1
PHP
PHP
fix default formatter key name check
6b2cb9db2b5c22d3e1772ed94cf727121f2a2610
<ide><path>src/I18n/I18n.php <ide> protected static function _fallbackTranslator($name, $locale) { <ide> new MessagesFileLoader($name, $locale, 'po') <ide> ]); <ide> <del> if (static::$_defaultFormatter !== 'default') { <add> // \Aura\Intl\Package by default uses formatter configured with key "basic". <add> if (static::$_defaultFormatter !== 'basic') { <ide> $formatter = static::$_defaultFormatter; <ide> $chain = function() use ($formatter, $chain) { <ide> $package = $chain();
1