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 |
|---|---|---|---|---|---|
Ruby | Ruby | implement directory? on keg | 58e5ac6835fb0901f01180aeb2169e7f30a44443 | <ide><path>Library/Homebrew/keg.rb
<ide> def abv
<ide> path.abv
<ide> end
<ide>
<add> def directory?
<add> path.directory?
<add> end
<add>
<ide> def exist?
<ide> path.exist?
<ide> end | 1 |
Javascript | Javascript | remove unused variables | ac35b416fb818faba73ee4cbdf5837b4d9f31f38 | <ide><path>src/Angular.js
<ide> function copy(source, destination) {
<ide>
<ide> function copyRecurse(source, destination) {
<ide> var h = destination.$$hashKey;
<del> var result, key;
<add> var key;
<ide> if (isArray(source)) {
<ide> for (var i = 0, ii = source.length; i < ii; i++) {
<ide> destination.push(copyElement(source[i]));
<ide><path>src/ng/browser.js
<ide> */
<ide> function Browser(window, document, $log, $sniffer) {
<ide> var self = this,
<del> rawDocument = document[0],
<ide> location = window.location,
<ide> history = window.history,
<ide> setTimeout = window.setTimeout,
<ide><path>src/ng/directive/input.js
<ide> function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
<ide> if (!$sniffer.android) {
<ide> var composing = false;
<ide>
<del> element.on('compositionstart', function(data) {
<add> element.on('compositionstart', function() {
<ide> composing = true;
<ide> });
<ide>
<ide><path>src/ng/directive/ngModel.js
<ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
<ide> setValidity(name, undefined);
<ide> validatorPromises.push(promise.then(function() {
<ide> setValidity(name, true);
<del> }, function(error) {
<add> }, function() {
<ide> allValid = false;
<ide> setValidity(name, false);
<ide> }));
<ide> var ngModelDirective = ['$rootScope', function($rootScope) {
<ide> });
<ide> }
<ide>
<del> element.on('blur', function(ev) {
<add> element.on('blur', function() {
<ide> if (modelCtrl.$touched) return;
<ide>
<ide> if ($rootScope.$$phase) {
<ide><path>src/ng/directive/select.js
<ide> function chromeHack(optionElement) {
<ide> * added `<option>` elements, perhaps by an `ngRepeat` directive.
<ide> */
<ide> var SelectController =
<del> ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
<add> ['$element', '$scope', function($element, $scope) {
<ide>
<ide> var self = this,
<ide> optionsMap = new HashMap();
<ide><path>src/ng/http.js
<ide> function $HttpParamSerializerProvider() {
<ide> forEachSorted(params, function(value, key) {
<ide> if (value === null || isUndefined(value)) return;
<ide> if (isArray(value)) {
<del> forEach(value, function(v, k) {
<add> forEach(value, function(v) {
<ide> parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
<ide> });
<ide> } else {
<ide><path>src/ng/parse.js
<ide> ASTInterpreter.prototype = {
<ide> return context ? {value: locals} : locals;
<ide> };
<ide> case AST.NGValueParameter:
<del> return function(scope, locals, assign, inputs) {
<add> return function(scope, locals, assign) {
<ide> return context ? {value: assign} : assign;
<ide> };
<ide> }
<ide><path>src/ng/rootScope.js
<ide> function $RootScopeProvider() {
<ide> dirty, ttl = TTL,
<ide> next, current, target = this,
<ide> watchLog = [],
<del> logIdx, logMsg, asyncTask;
<add> logIdx, asyncTask;
<ide>
<ide> beginPhase('$digest');
<ide> // Check for changes to browser url that happened in sync before the call to $digest | 8 |
Mixed | Javascript | add diagnostics channel and perf hooks detail | 60898eed65d49ce7a1a4a43791451ddc17876222 | <ide><path>doc/api/diagnostics_channel.md
<ide> Emitted when server receives a request.
<ide>
<ide> Emitted when server sends a response.
<ide>
<add>`net.client.socket`
<add>
<add>* `socket` {net.Socket}
<add>
<add>Emitted when a new TCP or pipe client socket is created.
<add>
<add>`net.server.socket`
<add>
<add>* `socket` {net.Socket}
<add>
<add>Emitted when a new TCP or pipe connection is received.
<add>
<add>`udp.socket`
<add>
<add>* `socket` {dgram.Socket}
<add>
<add>Emitted when a new UDP socket is created.
<add>
<ide> [`'uncaughtException'`]: process.md#event-uncaughtexception
<ide> [`channel.subscribe(onMessage)`]: #channelsubscribeonmessage
<ide> [`diagnostics_channel.channel(name)`]: #diagnostics_channelchannelname
<ide><path>doc/api/perf_hooks.md
<ide> When `performanceEntry.type` is equal to `'dns'`, the
<ide> additional information.
<ide>
<ide> If `performanceEntry.name` is equal to `lookup`, the `detail`
<del>will contain the following properties: `hostname`, `family`, `hints`, `verbatim`.
<add>will contain the following properties: `hostname`, `family`, `hints`, `verbatim`,
<add>`addresses`.
<ide>
<ide> If `performanceEntry.name` is equal to `lookupService`, the `detail` will
<del>contain the following properties: `host`, `port`.
<add>contain the following properties: `host`, `port`, `hostname`, `service`.
<ide>
<ide> If `performanceEntry.name` is equal to `queryxxx` or `getHostByAddr`, the `detail` will
<del>contain the following properties: `host`, `ttl`.
<add>contain the following properties: `host`, `ttl`, `result`. The value of `result` is
<add>same as the result of `queryxxx` or `getHostByAddr`.
<ide>
<ide> ## Class: `PerformanceNodeTiming`
<ide>
<ide><path>lib/dgram.js
<ide> const {
<ide> SendWrap
<ide> } = internalBinding('udp_wrap');
<ide>
<add>const dc = require('diagnostics_channel');
<add>const udpSocketChannel = dc.channel('udp.socket');
<add>
<ide> const BIND_STATE_UNBOUND = 0;
<ide> const BIND_STATE_BINDING = 1;
<ide> const BIND_STATE_BOUND = 2;
<ide> function Socket(type, listener) {
<ide> this.once('close', () => signal.removeEventListener('abort', onAborted));
<ide> }
<ide> }
<add> if (udpSocketChannel.hasSubscribers) {
<add> udpSocketChannel.publish({
<add> socket: this,
<add> });
<add> }
<ide> }
<ide> ObjectSetPrototypeOf(Socket.prototype, EventEmitter.prototype);
<ide> ObjectSetPrototypeOf(Socket, EventEmitter);
<ide><path>lib/dns.js
<ide> function onlookup(err, addresses) {
<ide> }
<ide> this.callback(null, addresses[0], this.family || isIP(addresses[0]));
<ide> if (this[kPerfHooksDnsLookupContext] && hasObserver('dns')) {
<del> stopPerf(this, kPerfHooksDnsLookupContext);
<add> stopPerf(this, kPerfHooksDnsLookupContext, { detail: { addresses } });
<ide> }
<ide> }
<ide>
<ide> function onlookupall(err, addresses) {
<ide>
<ide> this.callback(null, addresses);
<ide> if (this[kPerfHooksDnsLookupContext] && hasObserver('dns')) {
<del> stopPerf(this, kPerfHooksDnsLookupContext);
<add> stopPerf(this, kPerfHooksDnsLookupContext, { detail: { addresses } });
<ide> }
<ide> }
<ide>
<ide> function onlookupservice(err, hostname, service) {
<ide>
<ide> this.callback(null, hostname, service);
<ide> if (this[kPerfHooksDnsLookupServiceContext] && hasObserver('dns')) {
<del> stopPerf(this, kPerfHooksDnsLookupServiceContext);
<add> stopPerf(this, kPerfHooksDnsLookupServiceContext, { detail: { hostname, service } });
<ide> }
<ide> }
<ide>
<ide> function onresolve(err, result, ttls) {
<ide> else {
<ide> this.callback(null, result);
<ide> if (this[kPerfHooksDnsLookupResolveContext] && hasObserver('dns')) {
<del> stopPerf(this, kPerfHooksDnsLookupResolveContext);
<add> stopPerf(this, kPerfHooksDnsLookupResolveContext, { detail: { result } });
<ide> }
<ide> }
<ide> }
<ide><path>lib/internal/dns/promises.js
<ide> function onlookup(err, addresses) {
<ide> const family = this.family || isIP(addresses[0]);
<ide> this.resolve({ address: addresses[0], family });
<ide> if (this[kPerfHooksDnsLookupContext] && hasObserver('dns')) {
<del> stopPerf(this, kPerfHooksDnsLookupContext);
<add> stopPerf(this, kPerfHooksDnsLookupContext, { detail: { addresses } });
<ide> }
<ide> }
<ide>
<ide> function onlookupall(err, addresses) {
<ide>
<ide> this.resolve(addresses);
<ide> if (this[kPerfHooksDnsLookupContext] && hasObserver('dns')) {
<del> stopPerf(this, kPerfHooksDnsLookupContext);
<add> stopPerf(this, kPerfHooksDnsLookupContext, { detail: { addresses } });
<ide> }
<ide> }
<ide>
<ide> function onlookupservice(err, hostname, service) {
<ide>
<ide> this.resolve({ hostname, service });
<ide> if (this[kPerfHooksDnsLookupServiceContext] && hasObserver('dns')) {
<del> stopPerf(this, kPerfHooksDnsLookupServiceContext);
<add> stopPerf(this, kPerfHooksDnsLookupServiceContext, { detail: { hostname, service } });
<ide> }
<ide> }
<ide>
<ide> function onresolve(err, result, ttls) {
<ide>
<ide> this.resolve(result);
<ide> if (this[kPerfHooksDnsLookupResolveContext] && hasObserver('dns')) {
<del> stopPerf(this, kPerfHooksDnsLookupResolveContext);
<add> stopPerf(this, kPerfHooksDnsLookupResolveContext, { detail: { result } });
<ide> }
<ide> }
<ide>
<ide><path>lib/net.js
<ide> const isWindows = process.platform === 'win32';
<ide> const noop = () => {};
<ide>
<ide> const kPerfHooksNetConnectContext = Symbol('kPerfHooksNetConnectContext');
<add>
<add>const dc = require('diagnostics_channel');
<add>const netClientSocketChannel = dc.channel('net.client.socket');
<add>const netServerSocketChannel = dc.channel('net.server.socket');
<add>
<ide> const {
<ide> hasObserver,
<ide> startPerf,
<ide> function connect(...args) {
<ide> const options = normalized[0];
<ide> debug('createConnection', normalized);
<ide> const socket = new Socket(options);
<del>
<add> if (netClientSocketChannel.hasSubscribers) {
<add> netClientSocketChannel.publish({
<add> socket,
<add> });
<add> }
<ide> if (options.timeout) {
<ide> socket.setTimeout(options.timeout);
<ide> }
<ide> function onconnection(err, clientHandle) {
<ide> self._connections++;
<ide> socket.server = self;
<ide> socket._server = self;
<del>
<ide> self.emit('connection', socket);
<add> if (netServerSocketChannel.hasSubscribers) {
<add> netServerSocketChannel.publish({
<add> socket,
<add> });
<add> }
<ide> }
<ide>
<ide> /**
<ide><path>test/parallel/test-bootstrap-modules.js
<ide> const expectedModules = new Set([
<ide> 'NativeModule v8',
<ide> 'NativeModule internal/v8/startup_snapshot',
<ide> 'NativeModule vm',
<add> 'NativeModule diagnostics_channel',
<ide> ]);
<ide>
<ide> if (!common.isMainThread) {
<ide><path>test/parallel/test-diagnostics-channel-net.js
<add>'use strict';
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const net = require('net');
<add>const dc = require('diagnostics_channel');
<add>
<add>const netClientSocketChannel = dc.channel('net.client.socket');
<add>const netServerSocketChannel = dc.channel('net.server.socket');
<add>
<add>const isNetSocket = (socket) => socket instanceof net.Socket;
<add>
<add>netClientSocketChannel.subscribe(common.mustCall(({ socket }) => {
<add> assert.strictEqual(isNetSocket(socket), true);
<add>}));
<add>
<add>netServerSocketChannel.subscribe(common.mustCall(({ socket }) => {
<add> assert.strictEqual(isNetSocket(socket), true);
<add>}));
<add>
<add>const server = net.createServer(common.mustCall((socket) => {
<add> socket.destroy();
<add> server.close();
<add>}));
<add>
<add>server.listen(() => {
<add> const { port } = server.address();
<add> net.connect(port);
<add>});
<ide><path>test/parallel/test-diagnostics-channel-udp.js
<add>'use strict';
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const dgram = require('dgram');
<add>const dc = require('diagnostics_channel');
<add>
<add>const udpSocketChannel = dc.channel('udp.socket');
<add>
<add>const isUDPSocket = (socket) => socket instanceof dgram.Socket;
<add>
<add>udpSocketChannel.subscribe(common.mustCall(({ socket }) => {
<add> assert.strictEqual(isUDPSocket(socket), true);
<add>}));
<add>const socket = dgram.createSocket('udp4');
<add>socket.close();
<ide><path>test/parallel/test-dns-perf_hooks.js
<ide> const dns = require('dns');
<ide> const { PerformanceObserver } = require('perf_hooks');
<ide>
<ide> const entries = [];
<del>const obs = new PerformanceObserver(common.mustCallAtLeast((items) => {
<add>const obs = new PerformanceObserver((items) => {
<ide> entries.push(...items.getEntries());
<del>}));
<add>});
<ide>
<ide> obs.observe({ type: 'dns' });
<ide>
<del>dns.lookup('localhost', () => {});
<add>let count = 0;
<add>
<add>function inc() {
<add> count++;
<add>}
<add>
<add>// If DNS resolution fails, skip it
<add>// https://github.com/nodejs/node/issues/44003
<add>dns.lookup('localhost', common.mustCall((err) => { !err && inc(); }));
<add>dns.lookupService('127.0.0.1', 80, common.mustCall((err) => { !err && inc(); }));
<add>dns.resolveAny('localhost', common.mustCall((err) => { !err && inc(); }));
<add>
<add>dns.promises.lookup('localhost').then(inc).catch(() => {});
<add>dns.promises.lookupService('127.0.0.1', 80).then(inc).catch(() => {});
<add>dns.promises.resolveAny('localhost').then(inc).catch(() => {});
<ide>
<ide> process.on('exit', () => {
<del> assert.strictEqual(entries.length, 1);
<add> assert.strictEqual(entries.length, count);
<ide> entries.forEach((entry) => {
<ide> assert.strictEqual(!!entry.name, true);
<ide> assert.strictEqual(entry.entryType, 'dns');
<ide> assert.strictEqual(typeof entry.startTime, 'number');
<ide> assert.strictEqual(typeof entry.duration, 'number');
<ide> assert.strictEqual(typeof entry.detail, 'object');
<add> switch (entry.name) {
<add> case 'lookup':
<add> assert.strictEqual(typeof entry.detail.hostname, 'string');
<add> assert.strictEqual(typeof entry.detail.family, 'number');
<add> assert.strictEqual(typeof entry.detail.hints, 'number');
<add> assert.strictEqual(typeof entry.detail.verbatim, 'boolean');
<add> assert.strictEqual(Array.isArray(entry.detail.addresses), true);
<add> break;
<add> case 'lookupService':
<add> assert.strictEqual(typeof entry.detail.host, 'string');
<add> assert.strictEqual(typeof entry.detail.port, 'number');
<add> assert.strictEqual(typeof entry.detail.hostname, 'string');
<add> assert.strictEqual(typeof entry.detail.service, 'string');
<add> break;
<add> case 'queryAny':
<add> assert.strictEqual(typeof entry.detail.host, 'string');
<add> assert.strictEqual(typeof entry.detail.ttl, 'boolean');
<add> assert.strictEqual(Array.isArray(entry.detail.result), true);
<add> break;
<add> }
<ide> });
<ide> }); | 10 |
Text | Text | fix a typo | ecf8324c828c12d3d3adbf8a28d1af6c34a6e3da | <ide><path>docs/Homebrew-on-Linux.md
<ide> Homebrew does not currently support 32-bit x86 platforms. It would be possible f
<ide>
<ide> ## Alternative Installation
<ide>
<del>Extract or `git clone` Homebrew wherever you want. Use `/home/linuxbrew/.linuxbrew` if possible (to enabled the use of binary packages).
<add>Extract or `git clone` Homebrew wherever you want. Use `/home/linuxbrew/.linuxbrew` if possible (to enable the use of binary packages).
<ide>
<ide> ```sh
<ide> git clone https://github.com/Homebrew/brew ~/.linuxbrew/Homebrew | 1 |
Go | Go | move entrypoint build test to integration-cli | b25a9b7138e44950bee646c1bcb691a3dd273ea1 | <ide><path>integration-cli/docker_cli_build_test.go
<ide> func TestBuildExpose(t *testing.T) {
<ide> logDone("build - expose")
<ide> }
<ide>
<add>func TestBuildEntrypoint(t *testing.T) {
<add> checkSimpleBuild(t,
<add> `
<add> FROM scratch
<add> ENTRYPOINT ["/bin/echo"]
<add> `,
<add> "testbuildimg",
<add> "{{json .config.Entrypoint}}",
<add> `["/bin/echo"]`)
<add>
<add> deleteImages("testbuildimg")
<add> logDone("build - entrypoint")
<add>}
<add>
<ide> // TODO: TestCaching
<ide>
<ide> // TODO: TestADDCacheInvalidation
<ide><path>integration/buildfile_test.go
<ide> func buildImage(context testContextTemplate, t *testing.T, eng *engine.Engine, u
<ide> return image, err
<ide> }
<ide>
<del>func TestBuildEntrypoint(t *testing.T) {
<del> img, err := buildImage(testContextTemplate{`
<del> from {IMAGE}
<del> entrypoint ["/bin/echo"]
<del> `,
<del> nil, nil}, t, nil, true)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> if img.Config.Entrypoint[0] != "/bin/echo" {
<del> t.Log(img.Config.Entrypoint[0])
<del> t.Fail()
<del> }
<del>}
<del>
<ide> // testing #1405 - config.Cmd does not get cleaned up if
<ide> // utilizing cache
<ide> func TestBuildEntrypointRunCleanup(t *testing.T) { | 2 |
Javascript | Javascript | add comment for future intrepid travelers | 6fb0f61316b70e918fc3fe107a15ea8451fc2bd6 | <ide><path>packages/ember-metal-views/lib/renderer.js
<ide> var domHelper = environment.hasDOM ? new DOMHelper() : null;
<ide>
<ide> function Renderer() {
<ide> this._uuid = 0;
<add>
<add> // These sizes and values are somewhat arbitrary (but sensible)
<add> // pre-allocation defaults.
<ide> this._views = new Array(2000);
<ide> this._queue = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
<ide> this._parents = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; | 1 |
Python | Python | add tests for pickling doc | 45d1dd90b1794897d72b25d9090bed785387560f | <ide><path>spacy/tests/doc/test_pickle_doc.py
<add>from __future__ import unicode_literals
<add>
<add>import pickle
<add>
<add>from ...language import Language
<add>
<add>
<add>def test_pickle_single_doc():
<add> nlp = Language()
<add> doc = nlp(u'pickle roundtrip')
<add> data = pickle.dumps(doc, 1)
<add> doc2 = pickle.loads(data)
<add> assert doc2.text == 'pickle roundtrip'
<add>
<add>
<add>def test_list_of_docs_pickles_efficiently():
<add> nlp = Language()
<add> one_pickled = pickle.dumps(nlp(u'0'), -1)
<add> docs = list(nlp.pipe(str(i) for i in range(100)))
<add> many_pickled = pickle.dumps(docs, -1)
<add> assert len(many_pickled) < (len(one_pickled) * 2)
<add> many_unpickled = pickle.loads(many_pickled)
<add> assert many_unpickled[0].text == '0'
<add> assert many_unpickled[-1].text == '99'
<add> assert len(many_unpickled) == 99 | 1 |
PHP | PHP | return command from test stub | 73944943476aef81a7c98b9d0615d551cf8226ba | <ide><path>tests/Bus/BusDispatcherTest.php
<ide> public function testDispatcherCanDispatchStandAloneHandler()
<ide>
<ide> $response = $dispatcher->dispatch(new StandAloneCommand);
<ide>
<del> $this->assertEquals('stone-alone-handler', $response);
<add> $this->assertInstanceOf(StandAloneCommand::class, $response);
<ide> }
<ide> }
<ide>
<ide> class StandAloneCommand
<ide>
<ide> class StandAloneHandler
<ide> {
<del> public function handle()
<add> public function handle(StandAloneCommand $command)
<ide> {
<del> return 'stone-alone-handler';
<add> return $command;
<ide> }
<ide> } | 1 |
Text | Text | add changelog entry | 171b1f390d0150893d39ecc3f64742b284daffe0 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### Master
<add>
<add>* [BREAKING] Require Handlebars 2.0. See [blog post](http://emberjs.com/blog/2014/10/16/handlebars-update.html) for details.
<add>
<ide> ### Ember 1.8.0-beta.3 (September, 27, 2014)
<ide>
<ide> * [BUGFIX] Use contextualElements to properly handle omitted optional start tags. | 1 |
PHP | PHP | apply fixes from styleci | 9352d1edc22747417209adb4c314b7ec81120b4c | <ide><path>tests/Support/SupportTestingNotificationFakeTest.php
<ide>
<ide> use PHPUnit\Framework\TestCase;
<ide> use Illuminate\Foundation\Auth\User;
<del>use Illuminate\Support\Testing\Fakes\NotificationFake;
<ide> use Illuminate\Notifications\Notification;
<add>use Illuminate\Support\Testing\Fakes\NotificationFake;
<ide>
<ide> class NotificationFakeTest extends TestCase
<ide> {
<ide> public function via($notifiable)
<ide>
<ide> class UserStub extends User
<ide> {
<del>
<ide> } | 1 |
Text | Text | add v3.7.0 to changelog | b025751325a93d61278c96952aaea220da1e8d88 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<del>### v3.7.0-beta.3 (December 24, 2018)
<add>### v3.7.0 (January 7, 2019)
<ide>
<add>- [#17254](https://github.com/emberjs/ember.js/pull/17254) [BREAKING] Explicitly drop support for Node 4
<add>- [#17426](https://github.com/emberjs/ember.js/pull/17426) [BUGFIX] Fix 'strict mode does not allow function declarations'
<add>- [#17431](https://github.com/emberjs/ember.js/pull/17431) [BUGFIX] Fix ability to override a computed.volatile
<ide> - [#17398](https://github.com/emberjs/ember.js/pull/17398) [BUGFIX] Avoid console.trace for every Ember.warn
<ide> - [#17399](https://github.com/emberjs/ember.js/pull/17399) [BUGFIX] Local variable shadowing assert
<ide> - [#17403](https://github.com/emberjs/ember.js/pull/17403) [BUGFIX] Ensure legacy build of template compiler can be loaded.
<del>
<del>### v3.7.0-beta.2 (December 17, 2018)
<del>
<ide> - [#17328](https://github.com/emberjs/ember.js/pull/17328) [BUGFIX] Ensure that delayed transition retrys work
<ide> - [#17374](https://github.com/emberjs/ember.js/pull/17374) [BUGFIX] Fix cyclic references on Array.prototype
<del>
<del>### v3.7.0-beta.1 (December 6, 2018)
<del>
<del>- [#17254](https://github.com/emberjs/ember.js/pull/17254) [BREAKING] Explicitly drop support for Node 4
<del>- [#16898](https://github.com/emberjs/ember.js/pull/16898) Add RFC 232 style util test blueprint for Mocha
<del>- [#17128](https://github.com/emberjs/ember.js/pull/17128) [BUGFIX] Fix Sourcemaps build
<ide> - [#17134](https://github.com/emberjs/ember.js/pull/17134) [CLEANUP] Remove deprecated '_router'
<ide> - [#17133](https://github.com/emberjs/ember.js/pull/17133) [CLEANUP] Remove deprecated 'property{Did,Will}Change'
<add>- [#16898](https://github.com/emberjs/ember.js/pull/16898) Add RFC 232 style util test blueprint for Mocha
<ide>
<ide> ### v3.6.1 (December 18, 2018)
<ide> | 1 |
Javascript | Javascript | check reason chars in writehead | ca5f8f80e31784fc2883b352d0c22d4b74200e7e | <ide><path>lib/_http_server.js
<ide> ServerResponse.prototype.writeHead = function(statusCode, reason, obj) {
<ide> if (statusCode < 100 || statusCode > 999)
<ide> throw new RangeError(`Invalid status code: ${statusCode}`);
<ide>
<add> if (common._checkInvalidHeaderChar(this.statusMessage))
<add> throw new Error('Invalid character in statusMessage.');
<add>
<ide> var statusLine = 'HTTP/1.1 ' + statusCode.toString() + ' ' +
<ide> this.statusMessage + CRLF;
<ide>
<ide><path>test/parallel/test-http-status-reason-invalid-chars.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const http = require('http');
<add>
<add>function explicit(req, res) {
<add> assert.throws(() => {
<add> res.writeHead(200, `OK\r\nContent-Type: text/html\r\n`);
<add> }, /Invalid character in statusMessage/);
<add>
<add> assert.throws(() => {
<add> res.writeHead(200, 'OK\u010D\u010AContent-Type: gotcha\r\n');
<add> }, /Invalid character in statusMessage/);
<add>
<add> res.statusMessage = 'OK';
<add> res.end();
<add>}
<add>
<add>function implicit(req, res) {
<add> assert.throws(() => {
<add> res.statusMessage = `OK\r\nContent-Type: text/html\r\n`;
<add> res.writeHead(200);
<add> }, /Invalid character in statusMessage/);
<add> res.statusMessage = 'OK';
<add> res.end();
<add>}
<add>
<add>const server = http.createServer((req, res) => {
<add> if (req.url === '/explicit') {
<add> explicit(req, res);
<add> } else {
<add> implicit(req, res);
<add> }
<add>}).listen(common.PORT, common.mustCall(() => {
<add> const url = `http://localhost:${common.PORT}`;
<add> let left = 2;
<add> const check = common.mustCall((res) => {
<add> left--;
<add> assert.notEqual(res.headers['content-type'], 'text/html');
<add> assert.notEqual(res.headers['content-type'], 'gotcha');
<add> if (left === 0) server.close();
<add> }, 2);
<add> http.get(`${url}/explicit`, check).end();
<add> http.get(`${url}/implicit`, check).end();
<add>})); | 2 |
Ruby | Ruby | add a new line after the textarea opening tag | a6074c34e5e27b8d2b242808b7eb4e3f3ccf5f6e | <ide><path>actionpack/lib/action_view/helpers/tags/text_area.rb
<ide> def render
<ide> options["cols"], options["rows"] = size.split("x") if size.respond_to?(:split)
<ide> end
<ide>
<del> content_tag("textarea", ERB::Util.html_escape(options.delete('value') || value_before_type_cast(object)), options)
<add> content_tag("textarea", "\n#{options.delete('value') || value_before_type_cast(object)}", options)
<ide> end
<ide> end
<ide> end
<ide><path>actionpack/test/template/active_model_helper_test.rb
<ide> def setup
<ide>
<ide> def test_text_area_with_errors
<ide> assert_dom_equal(
<del> %(<div class="field_with_errors"><textarea cols="40" id="post_body" name="post[body]" rows="20">Back to the hill and over it again!</textarea></div>),
<add> %(<div class="field_with_errors"><textarea cols="40" id="post_body" name="post[body]" rows="20">\nBack to the hill and over it again!</textarea></div>),
<ide> text_area("post", "body")
<ide> )
<ide> end
<ide><path>actionpack/test/template/form_helper_test.rb
<ide> def test_radio_button_with_booleans
<ide>
<ide> def test_text_area
<ide> assert_dom_equal(
<del> '<textarea cols="40" id="post_body" name="post[body]" rows="20">Back to the hill and over it again!</textarea>',
<add> %{<textarea cols="40" id="post_body" name="post[body]" rows="20">\nBack to the hill and over it again!</textarea>},
<ide> text_area("post", "body")
<ide> )
<ide> end
<ide>
<ide> def test_text_area_with_escapes
<ide> @post.body = "Back to <i>the</i> hill and over it again!"
<ide> assert_dom_equal(
<del> '<textarea cols="40" id="post_body" name="post[body]" rows="20">Back to <i>the</i> hill and over it again!</textarea>',
<add> %{<textarea cols="40" id="post_body" name="post[body]" rows="20">\nBack to <i>the</i> hill and over it again!</textarea>},
<ide> text_area("post", "body")
<ide> )
<ide> end
<ide>
<ide> def test_text_area_with_alternate_value
<ide> assert_dom_equal(
<del> '<textarea cols="40" id="post_body" name="post[body]" rows="20">Testing alternate values.</textarea>',
<add> %{<textarea cols="40" id="post_body" name="post[body]" rows="20">\nTesting alternate values.</textarea>},
<ide> text_area("post", "body", :value => 'Testing alternate values.')
<ide> )
<ide> end
<ide>
<ide> def test_text_area_with_html_entities
<ide> @post.body = "The HTML Entity for & is &"
<ide> assert_dom_equal(
<del> '<textarea cols="40" id="post_body" name="post[body]" rows="20">The HTML Entity for & is &amp;</textarea>',
<add> %{<textarea cols="40" id="post_body" name="post[body]" rows="20">\nThe HTML Entity for & is &amp;</textarea>},
<ide> text_area("post", "body")
<ide> )
<ide> end
<ide>
<ide> def test_text_area_with_size_option
<ide> assert_dom_equal(
<del> '<textarea cols="183" id="post_body" name="post[body]" rows="820">Back to the hill and over it again!</textarea>',
<add> %{<textarea cols="183" id="post_body" name="post[body]" rows="820">\nBack to the hill and over it again!</textarea>},
<ide> text_area("post", "body", :size => "183x820")
<ide> )
<ide> end
<ide> def test_explicit_name
<ide> '<input id="post_title" name="dont guess" size="30" type="text" value="Hello World" />', text_field("post", "title", "name" => "dont guess")
<ide> )
<ide> assert_dom_equal(
<del> '<textarea cols="40" id="post_body" name="really!" rows="20">Back to the hill and over it again!</textarea>',
<add> %{<textarea cols="40" id="post_body" name="really!" rows="20">\nBack to the hill and over it again!</textarea>},
<ide> text_area("post", "body", "name" => "really!")
<ide> )
<ide> assert_dom_equal(
<ide> def test_explicit_id
<ide> '<input id="dont guess" name="post[title]" size="30" type="text" value="Hello World" />', text_field("post", "title", "id" => "dont guess")
<ide> )
<ide> assert_dom_equal(
<del> '<textarea cols="40" id="really!" name="post[body]" rows="20">Back to the hill and over it again!</textarea>',
<add> %{<textarea cols="40" id="really!" name="post[body]" rows="20">\nBack to the hill and over it again!</textarea>},
<ide> text_area("post", "body", "id" => "really!")
<ide> )
<ide> assert_dom_equal(
<ide> def test_nil_id
<ide> '<input name="post[title]" size="30" type="text" value="Hello World" />', text_field("post", "title", "id" => nil)
<ide> )
<ide> assert_dom_equal(
<del> '<textarea cols="40" name="post[body]" rows="20">Back to the hill and over it again!</textarea>',
<add> %{<textarea cols="40" name="post[body]" rows="20">\nBack to the hill and over it again!</textarea>},
<ide> text_area("post", "body", "id" => nil)
<ide> )
<ide> assert_dom_equal(
<ide> def test_index
<ide> text_field("post", "title", "index" => 5)
<ide> )
<ide> assert_dom_equal(
<del> '<textarea cols="40" name="post[5][body]" id="post_5_body" rows="20">Back to the hill and over it again!</textarea>',
<add> %{<textarea cols="40" name="post[5][body]" id="post_5_body" rows="20">\nBack to the hill and over it again!</textarea>},
<ide> text_area("post", "body", "index" => 5)
<ide> )
<ide> assert_dom_equal(
<ide> def test_index_with_nil_id
<ide> text_field("post", "title", "index" => 5, 'id' => nil)
<ide> )
<ide> assert_dom_equal(
<del> '<textarea cols="40" name="post[5][body]" rows="20">Back to the hill and over it again!</textarea>',
<add> %{<textarea cols="40" name="post[5][body]" rows="20">\nBack to the hill and over it again!</textarea>},
<ide> text_area("post", "body", "index" => 5, 'id' => nil)
<ide> )
<ide> assert_dom_equal(
<ide> def test_auto_index
<ide> "<input id=\"post_#{pid}_title\" name=\"post[#{pid}][title]\" size=\"30\" type=\"text\" value=\"Hello World\" />", text_field("post[]","title")
<ide> )
<ide> assert_dom_equal(
<del> "<textarea cols=\"40\" id=\"post_#{pid}_body\" name=\"post[#{pid}][body]\" rows=\"20\">Back to the hill and over it again!</textarea>",
<add> "<textarea cols=\"40\" id=\"post_#{pid}_body\" name=\"post[#{pid}][body]\" rows=\"20\">\nBack to the hill and over it again!</textarea>",
<ide> text_area("post[]", "body")
<ide> )
<ide> assert_dom_equal(
<ide> "<input name=\"post[#{pid}][secret]\" type=\"hidden\" value=\"0\" /><input checked=\"checked\" id=\"post_#{pid}_secret\" name=\"post[#{pid}][secret]\" type=\"checkbox\" value=\"1\" />",
<ide> check_box("post[]", "secret")
<ide> )
<ide> assert_dom_equal(
<del>"<input checked=\"checked\" id=\"post_#{pid}_title_hello_world\" name=\"post[#{pid}][title]\" type=\"radio\" value=\"Hello World\" />",
<add> "<input checked=\"checked\" id=\"post_#{pid}_title_hello_world\" name=\"post[#{pid}][title]\" type=\"radio\" value=\"Hello World\" />",
<ide> radio_button("post[]", "title", "Hello World")
<ide> )
<ide> assert_dom_equal("<input id=\"post_#{pid}_title_goodbye_world\" name=\"post[#{pid}][title]\" type=\"radio\" value=\"Goodbye World\" />",
<ide> def test_auto_index_with_nil_id
<ide> text_field("post[]","title", :id => nil)
<ide> )
<ide> assert_dom_equal(
<del> "<textarea cols=\"40\" name=\"post[#{pid}][body]\" rows=\"20\">Back to the hill and over it again!</textarea>",
<add> "<textarea cols=\"40\" name=\"post[#{pid}][body]\" rows=\"20\">\nBack to the hill and over it again!</textarea>",
<ide> text_area("post[]", "body", :id => nil)
<ide> )
<ide> assert_dom_equal(
<ide> def test_form_for
<ide> expected = whole_form("/posts/123", "create-post" , "edit_post", :method => 'patch') do
<ide> "<label for='post_title'>The Title</label>" +
<ide> "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
<del> "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
<add> "<textarea name='post[body]' id='post_body' rows='20' cols='40'>\nBack to the hill and over it again!</textarea>" +
<ide> "<input name='post[secret]' type='hidden' value='0' />" +
<ide> "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" +
<ide> "<input name='commit' type='submit' value='Create post' />" +
<ide> def test_form_for_with_symbol_object_name
<ide> expected = whole_form("/posts/123", "create-post", "edit_other_name", :method => 'patch') do
<ide> "<label for='other_name_title' class='post_title'>Title</label>" +
<ide> "<input name='other_name[title]' size='30' id='other_name_title' value='Hello World' type='text' />" +
<del> "<textarea name='other_name[body]' id='other_name_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
<add> "<textarea name='other_name[body]' id='other_name_body' rows='20' cols='40'>\nBack to the hill and over it again!</textarea>" +
<ide> "<input name='other_name[secret]' value='0' type='hidden' />" +
<ide> "<input name='other_name[secret]' checked='checked' id='other_name_secret' value='1' type='checkbox' />" +
<ide> "<input name='commit' value='Create post' type='submit' />"
<ide> def test_form_for_with_method_as_part_of_html_options
<ide>
<ide> expected = whole_form("/", "create-post", "edit_post", "delete") do
<ide> "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
<del> "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
<add> "<textarea name='post[body]' id='post_body' rows='20' cols='40'>\nBack to the hill and over it again!</textarea>" +
<ide> "<input name='post[secret]' type='hidden' value='0' />" +
<ide> "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />"
<ide> end
<ide> def test_form_for_with_method
<ide>
<ide> expected = whole_form("/", "create-post", "edit_post", "delete") do
<ide> "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
<del> "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
<add> "<textarea name='post[body]' id='post_body' rows='20' cols='40'>\nBack to the hill and over it again!</textarea>" +
<ide> "<input name='post[secret]' type='hidden' value='0' />" +
<ide> "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />"
<ide> end
<ide> def test_form_for_with_remote
<ide>
<ide> expected = whole_form("/", "create-post", "edit_post", :method => 'patch', :remote => true) do
<ide> "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
<del> "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
<add> "<textarea name='post[body]' id='post_body' rows='20' cols='40'>\nBack to the hill and over it again!</textarea>" +
<ide> "<input name='post[secret]' type='hidden' value='0' />" +
<ide> "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />"
<ide> end
<ide> def test_form_for_with_remote_in_html
<ide>
<ide> expected = whole_form("/", "create-post", "edit_post", :method => 'patch', :remote => true) do
<ide> "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
<del> "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
<add> "<textarea name='post[body]' id='post_body' rows='20' cols='40'>\nBack to the hill and over it again!</textarea>" +
<ide> "<input name='post[secret]' type='hidden' value='0' />" +
<ide> "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />"
<ide> end
<ide> def test_form_for_with_remote_without_html
<ide>
<ide> expected = whole_form("/posts", 'new_post', 'new_post', :remote => true) do
<ide> "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
<del> "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
<add> "<textarea name='post[body]' id='post_body' rows='20' cols='40'>\nBack to the hill and over it again!</textarea>" +
<ide> "<input name='post[secret]' type='hidden' value='0' />" +
<ide> "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />"
<ide> end
<ide> def test_form_for_without_object
<ide>
<ide> expected = whole_form("/", "create-post") do
<ide> "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
<del> "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
<add> "<textarea name='post[body]' id='post_body' rows='20' cols='40'>\nBack to the hill and over it again!</textarea>" +
<ide> "<input name='post[secret]' type='hidden' value='0' />" +
<ide> "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />"
<ide> end
<ide> def test_form_for_with_index
<ide> expected = whole_form('/posts/123', 'edit_post[]', 'edit_post[]', 'patch') do
<ide> "<label for='post_123_title'>Title</label>" +
<ide> "<input name='post[123][title]' size='30' type='text' id='post_123_title' value='Hello World' />" +
<del> "<textarea name='post[123][body]' id='post_123_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
<add> "<textarea name='post[123][body]' id='post_123_body' rows='20' cols='40'>\nBack to the hill and over it again!</textarea>" +
<ide> "<input name='post[123][secret]' type='hidden' value='0' />" +
<ide> "<input name='post[123][secret]' checked='checked' type='checkbox' id='post_123_secret' value='1' />"
<ide> end
<ide> def test_form_for_with_nil_index_option_override
<ide>
<ide> expected = whole_form('/posts/123', 'edit_post[]', 'edit_post[]', 'patch') do
<ide> "<input name='post[][title]' size='30' type='text' id='post__title' value='Hello World' />" +
<del> "<textarea name='post[][body]' id='post__body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
<add> "<textarea name='post[][body]' id='post__body' rows='20' cols='40'>\nBack to the hill and over it again!</textarea>" +
<ide> "<input name='post[][secret]' type='hidden' value='0' />" +
<ide> "<input name='post[][secret]' checked='checked' type='checkbox' id='post__secret' value='1' />"
<ide> end
<ide> def test_form_for_with_namespace
<ide>
<ide> expected = whole_form('/posts/123', 'namespace_edit_post_123', 'edit_post', 'patch') do
<ide> "<input name='post[title]' size='30' type='text' id='namespace_post_title' value='Hello World' />" +
<del> "<textarea name='post[body]' id='namespace_post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
<add> "<textarea name='post[body]' id='namespace_post_body' rows='20' cols='40'>\nBack to the hill and over it again!</textarea>" +
<ide> "<input name='post[secret]' type='hidden' value='0' />" +
<ide> "<input name='post[secret]' checked='checked' type='checkbox' id='namespace_post_secret' value='1' />"
<ide> end
<ide> def test_fields_for_with_namespace
<ide>
<ide> expected = whole_form('/posts/123', 'namespace_edit_post_123', 'edit_post', 'patch') do
<ide> "<input name='post[title]' size='30' type='text' id='namespace_post_title' value='Hello World' />" +
<del> "<textarea name='post[body]' id='namespace_post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
<add> "<textarea name='post[body]' id='namespace_post_body' rows='20' cols='40'>\nBack to the hill and over it again!</textarea>" +
<ide> "<input name='post[comment][body]' size='30' type='text' id='namespace_post_comment_body' value='Hello World' />"
<ide> end
<ide>
<ide> def test_fields_for
<ide>
<ide> expected =
<ide> "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
<del> "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
<add> "<textarea name='post[body]' id='post_body' rows='20' cols='40'>\nBack to the hill and over it again!</textarea>" +
<ide> "<input name='post[secret]' type='hidden' value='0' />" +
<ide> "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />"
<ide>
<ide> def test_fields_for_with_index
<ide>
<ide> expected =
<ide> "<input name='post[123][title]' size='30' type='text' id='post_123_title' value='Hello World' />" +
<del> "<textarea name='post[123][body]' id='post_123_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
<add> "<textarea name='post[123][body]' id='post_123_body' rows='20' cols='40'>\nBack to the hill and over it again!</textarea>" +
<ide> "<input name='post[123][secret]' type='hidden' value='0' />" +
<ide> "<input name='post[123][secret]' checked='checked' type='checkbox' id='post_123_secret' value='1' />"
<ide>
<ide> def test_fields_for_with_nil_index_option_override
<ide>
<ide> expected =
<ide> "<input name='post[][title]' size='30' type='text' id='post__title' value='Hello World' />" +
<del> "<textarea name='post[][body]' id='post__body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
<add> "<textarea name='post[][body]' id='post__body' rows='20' cols='40'>\nBack to the hill and over it again!</textarea>" +
<ide> "<input name='post[][secret]' type='hidden' value='0' />" +
<ide> "<input name='post[][secret]' checked='checked' type='checkbox' id='post__secret' value='1' />"
<ide>
<ide> def test_fields_for_with_index_option_override
<ide>
<ide> expected =
<ide> "<input name='post[abc][title]' size='30' type='text' id='post_abc_title' value='Hello World' />" +
<del> "<textarea name='post[abc][body]' id='post_abc_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
<add> "<textarea name='post[abc][body]' id='post_abc_body' rows='20' cols='40'>\nBack to the hill and over it again!</textarea>" +
<ide> "<input name='post[abc][secret]' type='hidden' value='0' />" +
<ide> "<input name='post[abc][secret]' checked='checked' type='checkbox' id='post_abc_secret' value='1' />"
<ide>
<ide> def test_fields_for_without_object
<ide>
<ide> expected =
<ide> "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
<del> "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
<add> "<textarea name='post[body]' id='post_body' rows='20' cols='40'>\nBack to the hill and over it again!</textarea>" +
<ide> "<input name='post[secret]' type='hidden' value='0' />" +
<ide> "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />"
<ide>
<ide> def test_fields_for_with_only_object
<ide>
<ide> expected =
<ide> "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
<del> "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
<add> "<textarea name='post[body]' id='post_body' rows='20' cols='40'>\nBack to the hill and over it again!</textarea>" +
<ide> "<input name='post[secret]' type='hidden' value='0' />" +
<ide> "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />"
<ide>
<ide> def test_form_for_and_fields_for
<ide>
<ide> expected = whole_form('/posts/123', 'create-post', 'edit_post', :method => 'patch') do
<ide> "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
<del> "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
<add> "<textarea name='post[body]' id='post_body' rows='20' cols='40'>\nBack to the hill and over it again!</textarea>" +
<ide> "<input name='parent_post[secret]' type='hidden' value='0' />" +
<ide> "<input name='parent_post[secret]' checked='checked' type='checkbox' id='parent_post_secret' value='1' />"
<ide> end
<ide> def test_form_for_and_fields_for_with_object
<ide>
<ide> expected = whole_form('/posts/123', 'create-post', 'edit_post', :method => 'patch') do
<ide> "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" +
<del> "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" +
<add> "<textarea name='post[body]' id='post_body' rows='20' cols='40'>\nBack to the hill and over it again!</textarea>" +
<ide> "<input name='post[comment][name]' type='text' id='post_comment_name' value='new comment' size='30' />"
<ide> end
<ide>
<ide> def test_form_for_with_labelled_builder
<ide>
<ide> expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do
<ide> "<label for='title'>Title:</label> <input name='post[title]' size='30' type='text' id='post_title' value='Hello World' /><br/>" +
<del> "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea><br/>" +
<add> "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>\nBack to the hill and over it again!</textarea><br/>" +
<ide> "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>"
<ide> end
<ide>
<ide> def test_default_form_builder
<ide>
<ide> expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'patch') do
<ide> "<label for='title'>Title:</label> <input name='post[title]' size='30' type='text' id='post_title' value='Hello World' /><br/>" +
<del> "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea><br/>" +
<add> "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>\nBack to the hill and over it again!</textarea><br/>" +
<ide> "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>"
<ide> end
<ide>
<ide> def test_fields_for_with_labelled_builder
<ide>
<ide> expected =
<ide> "<label for='title'>Title:</label> <input name='post[title]' size='30' type='text' id='post_title' value='Hello World' /><br/>" +
<del> "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea><br/>" +
<add> "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>\nBack to the hill and over it again!</textarea><br/>" +
<ide> "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>"
<ide>
<ide> assert_dom_equal expected, output_buffer | 3 |
PHP | PHP | use collection to remove soft delete scope | fdef01ac600d3f8aa83a2537ce95ccb165a98c8d | <ide><path>src/Illuminate/Database/Eloquent/SoftDeletingScope.php
<ide> public function remove(Builder $builder, Model $model)
<ide>
<ide> $query = $builder->getQuery();
<ide>
<del> foreach ((array) $query->wheres as $key => $where)
<add> $query->wheres = collect($query->wheres)->reject(function($where) use ($column)
<ide> {
<del> // If the where clause is a soft delete date constraint, we will remove it from
<del> // the query and reset the keys on the wheres. This allows this developer to
<del> // include deleted model in a relationship result set that is lazy loaded.
<del> if ($this->isSoftDeleteConstraint($where, $column))
<del> {
<del> unset($query->wheres[$key]);
<del>
<del> $query->wheres = array_values($query->wheres);
<del> }
<del> }
<add> return $this->isSoftDeleteConstraint($where, $column);
<add> })->values()->all();
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | fix bug with getting the id of the track | 20e9a9feb58097ab91e2ee9ef785128fee43e623 | <ide><path>src/js/tracks.js
<ide> goog.inherits(vjs.TextTrackMenuItem, vjs.MenuItem);
<ide>
<ide> vjs.TextTrackMenuItem.prototype.onClick = function(){
<ide> goog.base(this, 'onClick');
<del> this.player_.showTextTrack(this.track.id(), this.track.kind());
<add> this.player_.showTextTrack(this.track.id_, this.track.kind());
<ide> };
<ide>
<ide> vjs.TextTrackMenuItem.prototype.update = function(){
<ide> goog.inherits(vjs.OffTextTrackMenuItem, vjs.TextTrackMenuItem);
<ide>
<ide> vjs.OffTextTrackMenuItem.prototype.onClick = function(){
<ide> goog.base(this, 'onClick');
<del> this.player_.showTextTrack(this.track.id(), this.track.kind());
<add> this.player_.showTextTrack(this.track.id_, this.track.kind());
<ide> };
<ide>
<ide> vjs.OffTextTrackMenuItem.prototype.update = function(){ | 1 |
Python | Python | remove dead code backporting py2.6 warnings | d4e4f1f39fba4bfa1df4ebd357f91ccdb35ebdaf | <ide><path>numpy/testing/_private/utils.py
<ide> def integer_repr(x):
<ide> raise ValueError("Unsupported dtype %s" % x.dtype)
<ide>
<ide>
<del># The following two classes are copied from python 2.6 warnings module (context
<del># manager)
<del>class WarningMessage(object):
<del>
<del> """
<del> Holds the result of a single showwarning() call.
<del>
<del> Deprecated in 1.8.0
<del>
<del> Notes
<del> -----
<del> `WarningMessage` is copied from the Python 2.6 warnings module,
<del> so it can be used in NumPy with older Python versions.
<del>
<del> """
<del>
<del> _WARNING_DETAILS = ("message", "category", "filename", "lineno", "file",
<del> "line")
<del>
<del> def __init__(self, message, category, filename, lineno, file=None,
<del> line=None):
<del> local_values = locals()
<del> for attr in self._WARNING_DETAILS:
<del> setattr(self, attr, local_values[attr])
<del> if category:
<del> self._category_name = category.__name__
<del> else:
<del> self._category_name = None
<del>
<del> def __str__(self):
<del> return ("{message : %r, category : %r, filename : %r, lineno : %s, "
<del> "line : %r}" % (self.message, self._category_name,
<del> self.filename, self.lineno, self.line))
<del>
<del>
<del>class WarningManager(object):
<del> """
<del> A context manager that copies and restores the warnings filter upon
<del> exiting the context.
<del>
<del> The 'record' argument specifies whether warnings should be captured by a
<del> custom implementation of ``warnings.showwarning()`` and be appended to a
<del> list returned by the context manager. Otherwise None is returned by the
<del> context manager. The objects appended to the list are arguments whose
<del> attributes mirror the arguments to ``showwarning()``.
<del>
<del> The 'module' argument is to specify an alternative module to the module
<del> named 'warnings' and imported under that name. This argument is only useful
<del> when testing the warnings module itself.
<del>
<del> Deprecated in 1.8.0
<del>
<del> Notes
<del> -----
<del> `WarningManager` is a copy of the ``catch_warnings`` context manager
<del> from the Python 2.6 warnings module, with slight modifications.
<del> It is copied so it can be used in NumPy with older Python versions.
<del>
<del> """
<del>
<del> def __init__(self, record=False, module=None):
<del> self._record = record
<del> if module is None:
<del> self._module = sys.modules['warnings']
<del> else:
<del> self._module = module
<del> self._entered = False
<del>
<del> def __enter__(self):
<del> if self._entered:
<del> raise RuntimeError("Cannot enter %r twice" % self)
<del> self._entered = True
<del> self._filters = self._module.filters
<del> self._module.filters = self._filters[:]
<del> self._showwarning = self._module.showwarning
<del> if self._record:
<del> log = []
<del>
<del> def showwarning(*args, **kwargs):
<del> log.append(WarningMessage(*args, **kwargs))
<del> self._module.showwarning = showwarning
<del> return log
<del> else:
<del> return None
<del>
<del> def __exit__(self):
<del> if not self._entered:
<del> raise RuntimeError("Cannot exit %r without entering first" % self)
<del> self._module.filters = self._filters
<del> self._module.showwarning = self._showwarning
<del>
<del>
<ide> @contextlib.contextmanager
<ide> def _assert_warns_context(warning_class, name=None):
<ide> __tracebackhide__ = True # Hide traceback for py.test | 1 |
Python | Python | fix mypy errors at greedy best first algo | a4b7d12262d41969cf1fc9d5dbf9b9a01f165f4c | <ide><path>graphs/greedy_best_first.py
<ide>
<ide> from __future__ import annotations
<ide>
<add>from typing import Optional
<add>
<add>Path = list[tuple[int, int]]
<add>
<ide> grid = [
<ide> [0, 0, 0, 0, 0, 0, 0],
<ide> [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles
<ide> class Node:
<ide> True
<ide> """
<ide>
<del> def __init__(self, pos_x, pos_y, goal_x, goal_y, g_cost, parent):
<add> def __init__(
<add> self,
<add> pos_x: int,
<add> pos_y: int,
<add> goal_x: int,
<add> goal_y: int,
<add> g_cost: float,
<add> parent: Optional[Node],
<add> ):
<ide> self.pos_x = pos_x
<ide> self.pos_y = pos_y
<ide> self.pos = (pos_y, pos_x)
<ide> class GreedyBestFirst:
<ide> (6, 2), (6, 3), (5, 3), (5, 4), (5, 5), (6, 5), (6, 6)]
<ide> """
<ide>
<del> def __init__(self, start, goal):
<add> def __init__(self, start: tuple[int, int], goal: tuple[int, int]):
<ide> self.start = Node(start[1], start[0], goal[1], goal[0], 0, None)
<ide> self.target = Node(goal[1], goal[0], goal[1], goal[0], 99999, None)
<ide>
<ide> self.open_nodes = [self.start]
<del> self.closed_nodes = []
<add> self.closed_nodes: list[Node] = []
<ide>
<ide> self.reached = False
<ide>
<del> def search(self) -> list[tuple[int]]:
<add> def search(self) -> Optional[Path]:
<ide> """
<ide> Search for the path,
<ide> if a path is not found, only the starting position is returned
<ide> def search(self) -> list[tuple[int]]:
<ide> else:
<ide> self.open_nodes.append(better_node)
<ide>
<del> if not (self.reached):
<add> if not self.reached:
<ide> return [self.start.pos]
<add> return None
<ide>
<ide> def get_successors(self, parent: Node) -> list[Node]:
<ide> """
<ide> def get_successors(self, parent: Node) -> list[Node]:
<ide> )
<ide> return successors
<ide>
<del> def retrace_path(self, node: Node) -> list[tuple[int]]:
<add> def retrace_path(self, node: Optional[Node]) -> Path:
<ide> """
<ide> Retrace the path from parents to parents until start node
<ide> """
<ide> def retrace_path(self, node: Node) -> list[tuple[int]]:
<ide>
<ide> greedy_bf = GreedyBestFirst(init, goal)
<ide> path = greedy_bf.search()
<add> if path:
<add> for pos_x, pos_y in path:
<add> grid[pos_x][pos_y] = 2
<ide>
<del> for elem in path:
<del> grid[elem[0]][elem[1]] = 2
<del>
<del> for elem in grid:
<del> print(elem)
<add> for elem in grid:
<add> print(elem) | 1 |
PHP | PHP | improve tests for mockservice() | 765a5a6927f600cf2ae99b9ad8bd4f801f5fe1d7 | <ide><path>tests/TestCase/TestSuite/IntegrationTestTraitTest.php
<ide> use Cake\Utility\Security;
<ide> use Laminas\Diactoros\UploadedFile;
<ide> use PHPUnit\Framework\AssertionFailedError;
<add>use stdClass;
<ide>
<ide> /**
<ide> * Self test of the IntegrationTestTrait
<ide> public function testViewVariableNotFoundShouldReturnNull()
<ide> */
<ide> public function testHandleWithContainerDependencies()
<ide> {
<del> $this->get('/dependencies/');
<add> $this->get('/dependencies/requiredDep');
<add> $this->assertResponseOk();
<ide> $this->assertResponseContains('"key":"value"', 'Contains the data from the stdClass container object.');
<ide> }
<ide>
<del> public function testHandleWithMockedDependencies()
<add> /**
<add> * Test that mockService() injects into controllers.
<add> *
<add> * @return void
<add> */
<add> public function testHandleWithMockServices()
<ide> {
<ide> $this->mockService(stdClass::class, function () {
<ide> return json_decode('{"mock":true}');
<ide> });
<del> $this->get('/dependencies/');
<add> $this->get('/dependencies/requiredDep');
<add> $this->assertResponseOk();
<ide> $this->assertResponseContains('"mock":true', 'Contains the data from the stdClass mock container.');
<ide> }
<add>
<add> /**
<add> * Test that mockService() injects into controllers.
<add> *
<add> * @return void
<add> */
<add> public function testHandleWithMockServicesOverwrite()
<add> {
<add> $this->mockService(stdClass::class, function () {
<add> return json_decode('{"first":true}');
<add> });
<add> $this->mockService(stdClass::class, function () {
<add> return json_decode('{"second":true}');
<add> });
<add> $this->get('/dependencies/requiredDep');
<add> $this->assertResponseOk();
<add> $this->assertResponseContains('"second":true', 'Contains the data from the stdClass mock container.');
<add> }
<add>
<add> /**
<add> * Test that removeMock() unsets mocks
<add> *
<add> * @return void
<add> */
<add> public function testHandleWithMockServicesUnset()
<add> {
<add> $this->mockService(stdClass::class, function () {
<add> return json_decode('{"first":true}');
<add> });
<add> $this->removeMockService(stdClass::class);
<add>
<add> $this->get('/dependencies/requiredDep');
<add> $this->assertResponseOk();
<add> $this->assertResponseNotContains('"first":true');
<add> }
<ide> } | 1 |
Go | Go | replace `imagemutex` with `locker` pkg | 2764839ae1ccc55e08d6290ecbf7b58d837bbdd2 | <ide><path>graph/graph.go
<ide> import (
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/pkg/archive"
<ide> "github.com/docker/docker/pkg/idtools"
<add> "github.com/docker/docker/pkg/locker"
<ide> "github.com/docker/docker/pkg/progressreader"
<ide> "github.com/docker/docker/pkg/streamformatter"
<ide> "github.com/docker/docker/pkg/stringid"
<ide> type Graph struct {
<ide> idIndex *truncindex.TruncIndex
<ide> driver graphdriver.Driver
<ide> imagesMutex sync.Mutex
<del> imageMutex imageMutex // protect images in driver.
<add> imageMutex locker.Locker // protect images in driver.
<ide> retained *retainedLayers
<ide> tarSplitDisabled bool
<ide> uidMaps []idtools.IDMap
<ide><path>graph/mutex.go
<del>package graph
<del>
<del>import "sync"
<del>
<del>// imageMutex provides a lock per image id to protect shared resources in the
<del>// graph. This is only used with registration but should be used when
<del>// manipulating the layer store.
<del>type imageMutex struct {
<del> mus map[string]*sync.Mutex // mutexes by image id.
<del> mu sync.Mutex // protects lock map
<del>
<del> // NOTE(stevvooe): The map above will grow to the size of all images ever
<del> // registered during a daemon run. To free these resources, we must
<del> // deallocate after unlock. Doing this safely is non-trivial in the face
<del> // of a very minor leak.
<del>}
<del>
<del>// Lock the provided id.
<del>func (im *imageMutex) Lock(id string) {
<del> im.getImageLock(id).Lock()
<del>}
<del>
<del>// Unlock the provided id.
<del>func (im *imageMutex) Unlock(id string) {
<del> im.getImageLock(id).Unlock()
<del>}
<del>
<del>// getImageLock returns the mutex for the given id. This method will never
<del>// return nil.
<del>func (im *imageMutex) getImageLock(id string) *sync.Mutex {
<del> im.mu.Lock()
<del> defer im.mu.Unlock()
<del>
<del> if im.mus == nil { // lazy
<del> im.mus = make(map[string]*sync.Mutex)
<del> }
<del>
<del> mu, ok := im.mus[id]
<del> if !ok {
<del> mu = new(sync.Mutex)
<del> im.mus[id] = mu
<del> }
<del>
<del> return mu
<del>} | 2 |
Javascript | Javascript | add space between error name and code | 7b4a72d797cc57bc69aa6be22c34505a456f7b3a | <ide><path>lib/internal/errors.js
<ide> function makeNodeError(Base) {
<ide> }
<ide>
<ide> get name() {
<del> return `${super.name}[${this[kCode]}]`;
<add> return `${super.name} [${this[kCode]}]`;
<ide> }
<ide>
<ide> get code() {
<ide><path>test/parallel/test-internal-errors.js
<ide> const err4 = new errors.Error('TEST_ERROR_2', 'abc', 'xyz');
<ide> const err5 = new errors.Error('TEST_ERROR_1');
<ide>
<ide> assert(err1 instanceof Error);
<del>assert.strictEqual(err1.name, 'Error[TEST_ERROR_1]');
<add>assert.strictEqual(err1.name, 'Error [TEST_ERROR_1]');
<ide> assert.strictEqual(err1.message, 'Error for testing purposes: test');
<ide> assert.strictEqual(err1.code, 'TEST_ERROR_1');
<ide>
<ide> assert(err2 instanceof TypeError);
<del>assert.strictEqual(err2.name, 'TypeError[TEST_ERROR_1]');
<add>assert.strictEqual(err2.name, 'TypeError [TEST_ERROR_1]');
<ide> assert.strictEqual(err2.message, 'Error for testing purposes: test');
<ide> assert.strictEqual(err2.code, 'TEST_ERROR_1');
<ide>
<ide> assert(err3 instanceof RangeError);
<del>assert.strictEqual(err3.name, 'RangeError[TEST_ERROR_1]');
<add>assert.strictEqual(err3.name, 'RangeError [TEST_ERROR_1]');
<ide> assert.strictEqual(err3.message, 'Error for testing purposes: test');
<ide> assert.strictEqual(err3.code, 'TEST_ERROR_1');
<ide>
<ide> assert(err4 instanceof Error);
<del>assert.strictEqual(err4.name, 'Error[TEST_ERROR_2]');
<add>assert.strictEqual(err4.name, 'Error [TEST_ERROR_2]');
<ide> assert.strictEqual(err4.message, 'abc xyz');
<ide> assert.strictEqual(err4.code, 'TEST_ERROR_2');
<ide>
<ide> assert(err5 instanceof Error);
<del>assert.strictEqual(err5.name, 'Error[TEST_ERROR_1]');
<add>assert.strictEqual(err5.name, 'Error [TEST_ERROR_1]');
<ide> assert.strictEqual(err5.message, 'Error for testing purposes: %s');
<ide> assert.strictEqual(err5.code, 'TEST_ERROR_1');
<ide> | 2 |
Python | Python | add missing period in train data | 1e8147aec72e4187ac153562ec2b197d3f83e7eb | <ide><path>examples/training/train_parser.py
<ide> 'heads': [1, 1, 4, 4, 5, 1, 1],
<ide> 'deps': ['nsubj', 'ROOT', 'compound', 'punct', 'nmod', 'dobj', 'punct']
<ide> }),
<del> ("I like London and Berlin", {
<add> ("I like London and Berlin.", {
<ide> 'heads': [1, 1, 1, 2, 2, 1],
<ide> 'deps': ['nsubj', 'ROOT', 'dobj', 'cc', 'conj', 'punct']
<ide> }) | 1 |
Ruby | Ruby | fix bug in usage example of #unscoped | 2bfeda3f0905e01bcdebdb8814f6dfb3d95b384c | <ide><path>activerecord/lib/active_record/base.rb
<ide> def arel_engine
<ide> # not use the default_scope:
<ide> #
<ide> # Post.unscoped {
<del> # limit(10) # Fires "SELECT * FROM posts LIMIT 10"
<add> # Post.limit(10) # Fires "SELECT * FROM posts LIMIT 10"
<ide> # }
<ide> #
<ide> # It is recommended to use block form of unscoped because chaining unscoped with <tt>scope</tt> | 1 |
Python | Python | accept small error in threaded random test | 3ea3dece5a5ef586a07310e12236669220eada07 | <ide><path>numpy/random/tests/test_random.py
<ide> assert_warns)
<ide> from numpy import random
<ide> from numpy.compat import asbytes
<add>import sys
<ide>
<ide> class TestSeed(TestCase):
<ide> def test_scalar(self):
<ide> def check_function(self, function, sz):
<ide> for s, o in zip(self.seeds, out2):
<ide> function(np.random.RandomState(s), o)
<ide>
<del> np.testing.assert_array_equal(out1, out2)
<add> # these platforms change x87 fpu precision mode in threads
<add> if (np.intp().dtype.itemsize == 4 and
<add> (sys.platform == "win32" or
<add> sys.platform.startswith("gnukfreebsd"))):
<add> np.testing.assert_array_almost_equal(out1, out2)
<add> else:
<add> np.testing.assert_array_equal(out1, out2)
<ide>
<ide> def test_normal(self):
<ide> def gen_random(state, out): | 1 |
Javascript | Javascript | fix some issues with the webgl renderer | caa4066afb1b2fbda8335aa69c2bffe3a46de8a1 | <ide><path>src/extras/renderers/plugins/DepthPassPlugin.js
<ide> THREE.DepthPassPlugin = function () {
<ide>
<ide> _renderList.length = 0;
<ide> projectObject(scene,scene,camera);
<del>
<del> /*_renderList = scene.__webglObjects;
<del>
<del> for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
<del>
<del> webglObject = renderList[ j ];
<del> object = webglObject.object;
<del>
<del> webglObject.render = false;
<del>
<del> if ( object.visible ) {
<del>
<del> if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
<del>
<del> object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
<del>
<del> webglObject.render = true;
<del>
<del> }
<del>
<del> }
<del>
<del> }*/
<del>
<ide>
<ide> // render regular objects
<ide>
<ide> var objectMaterial, useMorphing, useSkinning;
<ide>
<del> for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
<add> for ( j = 0, jl = _renderList.length; j < jl; j ++ ) {
<ide>
<ide> webglObject = _renderList[ j ];
<ide>
<ide><path>src/renderers/WebGLRenderer.js
<ide> THREE.WebGLRenderer = function ( parameters ) {
<ide> var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
<ide> var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
<ide>
<del> /*
<del> var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
<del> var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
<del> var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
<del>
<del> var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
<del> var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
<del> var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
<del> */
<del>
<ide> // clamp precision to maximum available
<ide>
<ide> var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
<ide> THREE.WebGLRenderer = function ( parameters ) {
<ide> _frustum.setFromMatrix( _projScreenMatrix );
<ide>
<ide> // update WebGL objects
<del>
<ide> if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
<ide>
<del> // custom render plugins (pre pass)
<ide>
<add> opaqueObjects.length = 0;
<add> transparentObjects.length = 0;
<add> _sortObjects = this.sortObjects;
<add>
<add> projectObject(scene,scene,camera);
<add>
<add> if ( this.sortObjects ) {
<add>
<add> opaqueObjects.sort( painterSortStable );
<add> transparentObjects.sort( reversePainterSortStable );
<add>
<add> }
<add>
<add> // custom render plugins (pre pass)
<add>
<ide> renderPlugins( this.renderPluginsPre, scene, camera );
<ide>
<ide> //
<ide> THREE.WebGLRenderer = function ( parameters ) {
<ide> // set matrices for regular objects (frustum culled)
<ide>
<ide>
<del> opaqueObjects.length = 0;
<del> transparentObjects.length = 0;
<del> _sortObjects = this.sortObjects;
<del>
<del> projectObject(scene,scene,camera);
<del>
<del> if ( this.sortObjects ) {
<del>
<del> opaqueObjects.sort( painterSortStable );
<del> transparentObjects.sort( reversePainterSortStable );
<ide>
<del> }
<ide>
<ide> // set matrices for immediate objects
<ide>
<ide> THREE.WebGLRenderer = function ( parameters ) {
<ide>
<ide> updateObject(scene, object);
<ide>
<del> setupMatrices( object, camera );
<del>
<ide> for (var i = 0, l = webglObjects.length; i < l; i++){
<ide>
<ide> var webglObject = webglObjects[i];
<ide>
<ide> unrollBufferMaterial( webglObject );
<del>
<ide>
<ide> webglObject.render = true;
<ide>
<ide> THREE.WebGLRenderer = function ( parameters ) {
<ide>
<ide> object = webglObject.object;
<ide> buffer = webglObject.buffer;
<add>
<add> setupMatrices( object, camera );
<ide>
<ide> if ( overrideMaterial ) {
<ide> | 2 |
Mixed | Python | remove references to django-crispy-forms | 6aac9d2be1f3a40a85ca8068ceabf5d4507994e4 | <ide><path>docs/index.md
<ide> The following packages are optional:
<ide> * [coreapi][coreapi] (1.32.0+) - Schema generation support.
<ide> * [Markdown][markdown] (2.6.0+) - Markdown support for the browsable API.
<ide> * [django-filter][django-filter] (1.0.1+) - Filtering support.
<del>* [django-crispy-forms][django-crispy-forms] - Improved HTML display for filtering.
<ide> * [django-guardian][django-guardian] (1.1.1+) - Object level permissions support.
<ide>
<ide> ## Installation
<ide> OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
<ide> [coreapi]: https://pypi.org/project/coreapi/
<ide> [markdown]: https://pypi.org/project/Markdown/
<ide> [django-filter]: https://pypi.org/project/django-filter/
<del>[django-crispy-forms]: https://github.com/maraujop/django-crispy-forms
<ide> [django-guardian]: https://github.com/django-guardian/django-guardian
<ide> [index]: .
<ide> [oauth1-section]: api-guide/authentication/#django-rest-framework-oauth
<ide><path>rest_framework/compat.py
<ide> def distinct(queryset, base):
<ide> yaml = None
<ide>
<ide>
<del># django-crispy-forms is optional
<del>try:
<del> import crispy_forms
<del>except ImportError:
<del> crispy_forms = None
<del>
<del>
<ide> # requests is optional
<ide> try:
<ide> import requests | 2 |
Javascript | Javascript | fix stale values in before compile | 35101131b7cbc66b1ed377597a27c49a4051c0a1 | <ide><path>examples/jsm/csm/CSM.js
<ide> export default class CSM {
<ide> }
<ide>
<ide> const breaksVec2 = [];
<del> this.getExtendedBreaks( breaksVec2 );
<del>
<del> const far = Math.min( this.camera.far, this.maxFar );
<add> const self = this;
<ide> const shaders = this.shaders;
<del> const camera = this.camera;
<ide>
<ide> material.onBeforeCompile = function ( shader ) {
<ide>
<add> const far = Math.min( self.camera.far, self.maxFar );
<add> self.getExtendedBreaks( breaksVec2 );
<add>
<ide> shader.uniforms.CSM_cascades = { value: breaksVec2 };
<del> shader.uniforms.cameraNear = { value: camera.near };
<add> shader.uniforms.cameraNear = { value: self.camera.near };
<ide> shader.uniforms.shadowFar = { value: far };
<ide>
<ide> shaders.set( material, shader ); | 1 |
Python | Python | add sunos support | fe7e00d51a05f379ad6323628226ea1b7c0ed339 | <ide><path>tools/gyp/pylib/gyp/generator/make.py
<ide>
<ide> def GetFlavor(params):
<ide> """Returns |params.flavor| if it's set, the system's default flavor else."""
<del> return params.get('flavor', 'mac' if sys.platform == 'darwin' else 'linux')
<add> flavors = {
<add> 'darwin': 'mac',
<add> 'sunos5': 'solaris',
<add> }
<add> flavor = flavors.get(sys.platform, 'linux')
<add> return params.get('flavor', flavor)
<ide>
<ide>
<ide> def CalculateVariables(default_variables, params):
<ide> def CalculateVariables(default_variables, params):
<ide> default_variables['LINKER_SUPPORTS_ICF'] = \
<ide> gyp.system_test.TestLinkerSupportsICF(cc_command=cc_target)
<ide>
<del> if GetFlavor(params) == 'mac':
<add> flavor = GetFlavor(params)
<add> if flavor == 'mac':
<ide> default_variables.setdefault('OS', 'mac')
<ide> default_variables.setdefault('SHARED_LIB_SUFFIX', '.dylib')
<ide> default_variables.setdefault('SHARED_LIB_DIR',
<ide> def CalculateVariables(default_variables, params):
<ide> global COMPILABLE_EXTENSIONS
<ide> COMPILABLE_EXTENSIONS.update({'.m': 'objc', '.mm' : 'objcxx'})
<ide> else:
<del> default_variables.setdefault('OS', 'linux')
<add> default_variables.setdefault('OS', flavor)
<ide> default_variables.setdefault('SHARED_LIB_SUFFIX', '.so')
<ide> default_variables.setdefault('SHARED_LIB_DIR','$(builddir)/lib.$(TOOLSET)')
<ide> default_variables.setdefault('LIB_DIR', '$(obj).$(TOOLSET)')
<ide> def ensure_directory_exists(path):
<ide>
<ide> quiet_cmd_cxx = CXX($(TOOLSET)) $@
<ide> cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
<del>%(mac_commands)s
<add>%(extra_commands)s
<ide> quiet_cmd_touch = TOUCH $@
<ide> cmd_touch = touch $@
<ide>
<ide> def ensure_directory_exists(path):
<ide> cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4)
<ide> """
<ide>
<add>SHARED_HEADER_SUN_COMMANDS = """
<add># gyp-sun-tool is written next to the root Makefile by gyp.
<add># Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd
<add># already.
<add>quiet_cmd_sun_tool = SUNTOOL $(4) $<
<add>cmd_sun_tool = ./gyp-sun-tool $(4) $< "$@"
<add>"""
<add>
<ide>
<ide> def WriteRootHeaderSuffixRules(writer):
<ide> extensions = sorted(COMPILABLE_EXTENSIONS.keys(), key=str.lower)
<ide> def RunSystemTests(flavor):
<ide> 'LINK_flags': link_flags }
<ide>
<ide>
<del>def CopyMacTool(out_path):
<del> """Finds mac_tool.gyp in the gyp directory and copies it to |out_path|."""
<add>def CopyTool(flavor, out_path):
<add> """Finds (mac|sun)_tool.gyp in the gyp directory and copies it to |out_path|."""
<add> prefix = { 'solaris': 'sun', 'mac': 'mac' }.get(flavor, None)
<add> if not prefix:
<add> return
<add>
<add> tool_path = os.path.join(out_path, 'gyp-%s-tool' % prefix)
<add> if os.path.exists(tool_path):
<add> os.remove(tool_path)
<add>
<add> # Slurp input file.
<ide> source_path = os.path.join(
<del> os.path.dirname(os.path.abspath(__file__)), '..', 'mac_tool.py')
<add> os.path.dirname(os.path.abspath(__file__)), '..', '%s_tool.py' % prefix)
<ide> source_file = open(source_path)
<ide> source = source_file.readlines()
<ide> source_file.close()
<del> mactool_file = open(out_path, 'w')
<del> mactool_file.write(
<add>
<add> # Add header and write it out.
<add> tool_file = open(tool_path, 'w')
<add> tool_file.write(
<ide> ''.join([source[0], '# Generated by gyp. Do not edit.\n'] + source[1:]))
<del> mactool_file.close()
<add> tool_file.close()
<add>
<add> # Make file executable.
<add> os.chmod(tool_path, 0o755)
<ide>
<ide>
<ide> def GenerateOutput(target_list, target_dicts, data, params):
<ide> def CalculateMakefilePath(build_file, base_name):
<ide> 'flock': 'flock',
<ide> 'flock_index': 1,
<ide> 'link_commands': LINK_COMMANDS_LINUX,
<del> 'mac_commands': '',
<add> 'extra_commands': '',
<ide> 'srcdir': srcdir,
<ide> }
<ide> if flavor == 'mac':
<ide> header_params.update({
<ide> 'flock': './gyp-mac-tool flock',
<ide> 'flock_index': 2,
<ide> 'link_commands': LINK_COMMANDS_MAC,
<del> 'mac_commands': SHARED_HEADER_MAC_COMMANDS,
<add> 'extra_commands': SHARED_HEADER_MAC_COMMANDS,
<ide> })
<add> elif flavor == 'solaris':
<add> header_params.update({
<add> 'flock': './gyp-sun-tool flock',
<add> 'flock_index': 2,
<add> 'extra_commands': SHARED_HEADER_SUN_COMMANDS,
<add> })
<add>
<ide> header_params.update(RunSystemTests(flavor))
<ide>
<ide> build_file, _, _ = gyp.common.ParseQualifiedTarget(target_list[0])
<ide> def CalculateMakefilePath(build_file, base_name):
<ide> WriteRootHeaderSuffixRules(root_makefile)
<ide>
<ide> # Put mac_tool next to the root Makefile.
<del> if flavor == 'mac':
<del> mactool_path = os.path.join(os.path.dirname(makefile_path), 'gyp-mac-tool')
<del> if os.path.exists(mactool_path):
<del> os.remove(mactool_path)
<del> CopyMacTool(mactool_path)
<del> os.chmod(mactool_path, 0o755) # Make file executable.
<add> dest_path = os.path.dirname(makefile_path)
<add> CopyTool(flavor, dest_path)
<ide>
<ide> # Find the list of targets that derive from the gyp file(s) being built.
<ide> needed_targets = set()
<ide><path>tools/gyp/pylib/gyp/sun_tool.py
<add>#!/usr/bin/env python
<add># Copyright (c) 2011 Google Inc. All rights reserved.
<add># Use of this source code is governed by a BSD-style license that can be
<add># found in the LICENSE file.
<add>
<add>"""These functions are executed via gyp-sun-tool when using the Makefile generator."""
<add>
<add>import os
<add>import fcntl
<add>import plistlib
<add>import shutil
<add>import string
<add>import subprocess
<add>import sys
<add>
<add>def main(args):
<add> executor = SunTool()
<add> executor.Dispatch(args)
<add>
<add>class SunTool(object):
<add> """This class performs all the SunOS tooling steps. The methods can either be
<add> executed directly, or dispatched from an argument list."""
<add>
<add> def Dispatch(self, args):
<add> """Dispatches a string command to a method."""
<add> if len(args) < 1:
<add> raise Exception("Not enough arguments")
<add>
<add> method = "Exec%s" % self._CommandifyName(args[0])
<add> getattr(self, method)(*args[1:])
<add>
<add> def _CommandifyName(self, name_string):
<add> """Transforms a tool name like copy-info-plist to CopyInfoPlist"""
<add> return name_string.title().replace('-', '')
<add>
<add> def ExecFlock(self, lockfile, *cmd_list):
<add> """Emulates the most basic behavior of Linux's flock(1)."""
<add> # Rely on exception handling to report errors.
<add> fd = os.open(lockfile, os.O_RDONLY|os.O_NOCTTY|os.O_CREAT, 0o666)
<add> fcntl.flock(fd, fcntl.LOCK_EX)
<add> return subprocess.call(cmd_list) | 2 |
Javascript | Javascript | add shouldcomponentupdate to functional components | b717db00fbea7a8f12dba360c37f81278988f139 | <ide><path>src/renderers/shared/fiber/ReactFiberBeginWork.js
<ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) {
<ide> var fn = workInProgress.type;
<ide> var props = workInProgress.pendingProps;
<ide>
<add> // TODO: Disable this before release, since it is not part of the public API
<add> // I use this for testing to compare the relative overhead of classes.
<add> if (typeof fn.shouldComponentUpdate === 'function') {
<add> if (workInProgress.memoizedProps !== null) {
<add> if (!fn.shouldComponentUpdate(workInProgress.memoizedProps, props)) {
<add> return bailoutOnAlreadyFinishedWork(current, workInProgress);
<add> }
<add> }
<add> }
<add>
<ide> var nextChildren = fn(props);
<ide> reconcileChildren(current, workInProgress, nextChildren);
<ide> return workInProgress.child; | 1 |
Javascript | Javascript | remove undocumented api | 5462373b5bbc5a0137054838ea6af3d236cfc8ac | <ide><path>src/ngResource/resource.js
<ide> angular.module('ngResource', ['ng']).
<ide> };
<ide> });
<ide>
<del> Resource.bind = function(additionalParamDefaults) {
<del> var extendedParamDefaults = extend({}, paramDefaults, additionalParamDefaults);
<del> return resourceFactory(url, extendedParamDefaults, actions, options);
<del> };
<del>
<ide> return Resource;
<ide> }
<ide>
<ide><path>test/ngResource/resourceSpec.js
<ide> describe('basic usage', function() {
<ide> });
<ide>
<ide>
<del> it('should bind default parameters', function() {
<del> $httpBackend.expect('GET', '/CreditCard/123.visa?minimum=0.05').respond({id: 123});
<del> var Visa = CreditCard.bind({verb: '.visa', minimum: 0.05});
<del> var visa = Visa.get({id: 123});
<del> $httpBackend.flush();
<del> expect(visa).toEqualData({id: 123});
<del> });
<del>
<del>
<del> it('should pass all original arguments when binding default params', function() {
<del> $httpBackend.expect('GET', '/CancellableCreditCard/123.visa').respond({id: 123});
<del>
<del> var CancellableCreditCard = $resource('/CancellableCreditCard/:id:verb', {},
<del> {charge: {method: 'POST'}}, {cancellable: true});
<del> var CancellableVisa = CancellableCreditCard.bind({verb: '.visa'});
<del> var visa = CancellableVisa.get({id: 123});
<del>
<del> $httpBackend.flush();
<del>
<del> expect(visa.$charge).toEqual(jasmine.any(Function));
<del> expect(visa.$cancelRequest).toEqual(jasmine.any(Function));
<del> });
<del>
<del>
<ide> it('should support dynamic default parameters (global)', function() {
<ide> var currentGroup = 'students',
<ide> Person = $resource('/Person/:group/:id', { group: function() { return currentGroup; }}); | 2 |
Javascript | Javascript | add extra caching layer | 0f190a5bed14bf9f7392af889f3f83306bedae97 | <ide><path>lib/internal/modules/cjs/loader.js
<ide> const {
<ide>
<ide> const isWindows = process.platform === 'win32';
<ide>
<add>const relativeResolveCache = Object.create(null);
<add>
<ide> let requireDepth = 0;
<ide> let statCache = null;
<ide> function stat(filename) {
<ide> Module._resolveLookupPaths = function(request, parent, newReturn) {
<ide> // Then have it load the file contents before returning its exports
<ide> // object.
<ide> Module._load = function(request, parent, isMain) {
<add> let relResolveCacheIdentifier;
<ide> if (parent) {
<ide> debug('Module._load REQUEST %s parent: %s', request, parent.id);
<add> // Fast path for (lazy loaded) modules in the same directory. The indirect
<add> // caching is required to allow cache invalidation without changing the old
<add> // cache key names.
<add> relResolveCacheIdentifier = `${parent.path}\x00${request}`;
<add> const filename = relativeResolveCache[relResolveCacheIdentifier];
<add> if (filename !== undefined) {
<add> const cachedModule = Module._cache[filename];
<add> if (cachedModule !== undefined) {
<add> updateChildren(parent, cachedModule, true);
<add> return cachedModule.exports;
<add> }
<add> delete relativeResolveCache[relResolveCacheIdentifier];
<add> }
<ide> }
<ide>
<ide> const filename = Module._resolveFilename(request, parent, isMain);
<ide>
<ide> const cachedModule = Module._cache[filename];
<del> if (cachedModule) {
<add> if (cachedModule !== undefined) {
<ide> updateChildren(parent, cachedModule, true);
<ide> return cachedModule.exports;
<ide> }
<ide> Module._load = function(request, parent, isMain) {
<ide> }
<ide>
<ide> Module._cache[filename] = module;
<add> if (parent !== undefined) {
<add> relativeResolveCache[relResolveCacheIdentifier] = filename;
<add> }
<ide>
<ide> let threw = true;
<ide> try {
<ide> Module._load = function(request, parent, isMain) {
<ide> } finally {
<ide> if (threw) {
<ide> delete Module._cache[filename];
<add> if (parent !== undefined) {
<add> delete relativeResolveCache[relResolveCacheIdentifier];
<add> }
<ide> }
<ide> }
<ide> | 1 |
PHP | PHP | make phpunit methods protected as per docs | 4745ce813ad3c727a208b18dfeb97c9710baa690 | <ide><path>src/TestSuite/TestCase.php
<ide> public function deprecated(callable $callable): void
<ide> *
<ide> * @return void
<ide> */
<del> public function setUp(): void
<add> protected function setUp(): void
<ide> {
<ide> parent::setUp();
<ide>
<ide> public function setUp(): void
<ide> *
<ide> * @return void
<ide> */
<del> public function tearDown(): void
<add> protected function tearDown(): void
<ide> {
<ide> parent::tearDown();
<ide> if ($this->_configure) { | 1 |
Text | Text | apply suggestions from code review | 78bf62ee5d05ca6d1fdaa30f48e2a6728968dce9 | <ide><path>docs/Formula-Cookbook.md
<ide> on_linux do
<ide> end
<ide> ```
<ide>
<del>Components can also be declared for specific macOS versions or version ranges. For example, to declare a dependency only on High Sierra, nest the `depends_on` call inside an `on_high_sierra` block. Add an `:or_older` or `:or_newer` parameter to the `on_high_sierra` method to add the dependency to all macOS versions that meet the condition. For example, to add `gettext` as a build dependency on Mojave and all macOS versions that are newer than Mojave, use:
<add>Components can also be declared for specific macOS versions or version ranges. For example, to declare a dependency only on High Sierra, nest the `depends_on` call inside an `on_high_sierra` block. Add an `:or_older` or `:or_newer` parameter to the `on_high_sierra` method to add the dependency to all macOS versions that meet the condition. For example, to add `gettext` as a build dependency on Mojave and all later macOS versions, use:
<ide>
<ide> ```ruby
<ide> on_mojave :or_newer do
<ide> To check multiple conditions, nest the corresponding blocks. For example, the fo
<ide>
<ide> ```ruby
<ide> on_macos do
<del> on_intel do
<add> on_arm do
<ide> depends_on "gettext" => :build
<ide> end
<ide> end
<ide> ```
<ide>
<ide> #### Inside `def install` and `test do`
<ide>
<del>Inside `def install` and `test` do, don't use these `on_*` methods. Instead, use `if` statements and the following conditionals:
<add>Inside `def install` and `test do`, don't use these `on_*` methods. Instead, use `if` statements and the following conditionals:
<ide>
<ide> * `OS.mac?` and `OS.linux?` return `true` or `false` based on the OS
<ide> * `Hardware::CPU.intel?` and `Hardware::CPU.arm?` return `true` or `false` based on the arch | 1 |
Javascript | Javascript | fix linting issues | b3e86a97e3659144c91eded04f7978e9ad986e7f | <ide><path>test/Compiler.test.js
<ide> describe("Compiler", () => {
<ide> done();
<ide> });
<ide> compiler.run((err, stats) => {
<del> if(err) return done(err);
<add> if (err) return done(err);
<ide> runCb();
<ide> });
<ide> });
<ide> it("should call afterDone hook after other callbacks (instance cb)", function(done) {
<ide> const instanceCb = jest.fn();
<del> const compiler = webpack({
<del> context: __dirname,
<del> mode: "production",
<del> entry: "./c",
<del> output: {
<del> path: "/",
<del> filename: "bundle.js"
<add> const compiler = webpack(
<add> {
<add> context: __dirname,
<add> mode: "production",
<add> entry: "./c",
<add> output: {
<add> path: "/",
<add> filename: "bundle.js"
<add> }
<add> },
<add> (err, stats) => {
<add> if (err) return done(err);
<add> instanceCb();
<ide> }
<del> }, (err, stats) => {
<del> if(err) return done(err);
<del> instanceCb();
<del> });
<add> );
<ide> compiler.outputFileSystem = new MemoryFs();
<ide> const doneHookCb = jest.fn();
<ide> compiler.hooks.done.tap("afterDoneRunTest", doneHookCb); | 1 |
Go | Go | allow push by id when using a custom registry | e095a1572fb8a2ba17ea231abcb3704cf83a96e4 | <ide><path>commands.go
<ide> func (cli *DockerCli) CmdPush(args ...string) error {
<ide> return err
<ide> }
<ide>
<del> if len(strings.SplitN(name, "/", 2)) == 1 {
<del> return fmt.Errorf("Impossible to push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)", cli.authConfig.Username, name)
<add> if *registry == "" {
<add> // If we're not using a custom registry, we know the restrictions
<add> // applied to repository names and can warn the user in advance.
<add> // Custom repositories can have different rules, and we must also
<add> // allow pushing by image ID.
<add> if len(strings.SplitN(name, "/", 2)) == 1 {
<add> return fmt.Errorf("Impossible to push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)", cli.authConfig.Username, name)
<add> }
<add>
<add> nameParts := strings.SplitN(name, "/", 2)
<add> validNamespace := regexp.MustCompile(`^([a-z0-9_]{4,30})$`)
<add> if !validNamespace.MatchString(nameParts[0]) {
<add> return fmt.Errorf("Invalid namespace name (%s), only [a-z0-9_] are allowed, size between 4 and 30", nameParts[0])
<add> }
<add> validRepo := regexp.MustCompile(`^([a-zA-Z0-9-_.]+)$`)
<add> if !validRepo.MatchString(nameParts[1]) {
<add> return fmt.Errorf("Invalid repository name (%s), only [a-zA-Z0-9-_.] are allowed", nameParts[1])
<add> }
<ide> }
<ide>
<ide> buf, err := json.Marshal(cli.authConfig)
<ide> if err != nil {
<ide> return err
<ide> }
<del> nameParts := strings.SplitN(name, "/", 2)
<del> validNamespace := regexp.MustCompile(`^([a-z0-9_]{4,30})$`)
<del> if !validNamespace.MatchString(nameParts[0]) {
<del> return fmt.Errorf("Invalid namespace name (%s), only [a-z0-9_] are allowed, size between 4 and 30", nameParts[0])
<del> }
<del> validRepo := regexp.MustCompile(`^([a-zA-Z0-9-_.]+)$`)
<del> if !validRepo.MatchString(nameParts[1]) {
<del> return fmt.Errorf("Invalid repository name (%s), only [a-zA-Z0-9-_.] are allowed", nameParts[1])
<del> }
<ide>
<ide> v := url.Values{}
<ide> v.Set("registry", *registry) | 1 |
Mixed | Javascript | expose stream api in clearscreendown() | c31f7e595af85da8ada5d278e6e96e8537b57435 | <ide><path>doc/api/readline.md
<ide> added: v0.7.7
<ide> The `readline.clearLine()` method clears current line of given [TTY][] stream
<ide> in a specified direction identified by `dir`.
<ide>
<del>## readline.clearScreenDown(stream)
<add>## readline.clearScreenDown(stream[, callback])
<ide> <!-- YAML
<ide> added: v0.7.7
<add>changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/28641
<add> description: The stream's write() callback and return value are exposed.
<ide> -->
<ide>
<ide> * `stream` {stream.Writable}
<add>* `callback` {Function} Invoked once the operation completes.
<add>* Returns: {boolean} `false` if `stream` wishes for the calling code to wait for
<add> the `'drain'` event to be emitted before continuing to write additional data;
<add> otherwise `true`.
<ide>
<ide> The `readline.clearScreenDown()` method clears the given [TTY][] stream from
<ide> the current position of the cursor down.
<ide><path>lib/readline.js
<ide> const { Math, Object } = primordials;
<ide>
<ide> const {
<add> ERR_INVALID_CALLBACK,
<ide> ERR_INVALID_CURSOR_POS,
<ide> ERR_INVALID_OPT_VALUE
<ide> } = require('internal/errors').codes;
<ide> function clearLine(stream, dir) {
<ide> * clears the screen from the current position of the cursor down
<ide> */
<ide>
<del>function clearScreenDown(stream) {
<del> if (stream === null || stream === undefined)
<del> return;
<add>function clearScreenDown(stream, callback) {
<add> if (callback !== undefined && typeof callback !== 'function')
<add> throw new ERR_INVALID_CALLBACK(callback);
<add>
<add> if (stream === null || stream === undefined) {
<add> if (typeof callback === 'function')
<add> process.nextTick(callback);
<add> return true;
<add> }
<ide>
<del> stream.write(kClearScreenDown);
<add> return stream.write(kClearScreenDown, callback);
<ide> }
<ide>
<ide> module.exports = {
<ide><path>test/parallel/test-readline-csi.js
<ide> class TestWritable extends Writable {
<ide>
<ide> const writable = new TestWritable();
<ide>
<del>readline.clearScreenDown(writable);
<add>assert.strictEqual(readline.clearScreenDown(writable), true);
<ide> assert.deepStrictEqual(writable.data, CSI.kClearScreenDown);
<add>assert.strictEqual(readline.clearScreenDown(writable, common.mustCall()), true);
<add>
<add>// Verify that clearScreenDown() throws on invalid callback.
<add>assert.throws(() => {
<add> readline.clearScreenDown(writable, null);
<add>}, /ERR_INVALID_CALLBACK/);
<add>
<add>// Verify that clearScreenDown() does not throw on null or undefined stream.
<add>assert.strictEqual(readline.clearScreenDown(null, common.mustCall()), true);
<add>assert.strictEqual(readline.clearScreenDown(undefined, common.mustCall()),
<add> true);
<ide>
<ide> writable.data = '';
<ide> readline.clearLine(writable, -1); | 3 |
Javascript | Javascript | fix bad ops.length assignment in tests | e6a0de54635ee003a29efa55e51dd6e97587d40e | <ide><path>src/renderers/shared/fiber/__tests__/ReactIncremental-test.js
<ide> describe('ReactIncremental', () => {
<ide> }
<ide> }
<ide>
<del> ops.length = [];
<add> ops.length = 0;
<ide> ReactNoop.render(
<ide> <Intl locale="fr">
<ide> <ShowLocale />
<ide> describe('ReactIncremental', () => {
<ide> 'ShowBoth {"locale":"fr"}',
<ide> ]);
<ide>
<del> ops.length = [];
<add> ops.length = 0;
<ide> ReactNoop.render(
<ide> <Intl locale="de">
<ide> <ShowLocale />
<ide> describe('ReactIncremental', () => {
<ide> 'ShowBoth {"locale":"de"}',
<ide> ]);
<ide>
<del> ops.length = [];
<add> ops.length = 0;
<ide> ReactNoop.render(
<ide> <Intl locale="sv">
<ide> <ShowLocale />
<ide> describe('ReactIncremental', () => {
<ide> 'Intl null',
<ide> ]);
<ide>
<del> ops.length = [];
<add> ops.length = 0;
<ide> ReactNoop.render(
<ide> <Intl locale="en">
<ide> <ShowLocale /> | 1 |
Javascript | Javascript | handle node_path in require('.') | 3ad82c335deff29a1db5a391f893dc6d2ff1e63a | <ide><path>lib/module.js
<ide> function tryExtensions(p, exts) {
<ide> }
<ide>
<ide>
<add>const noopDeprecateRequireDot = util.deprecate(function() {},
<add> "warning: require('.') resolved outside the package directory. " +
<add> "This functionality is deprecated and will be removed soon.");
<add>
<add>
<ide> Module._findPath = function(request, paths) {
<ide> var exts = Object.keys(Module._extensions);
<ide>
<ide> Module._findPath = function(request, paths) {
<ide> }
<ide>
<ide> if (filename) {
<add> // Warn once if '.' resolved outside the module dir
<add> if (request === '.' && i > 0) noopDeprecateRequireDot();
<ide> Module._pathCache[cacheKey] = filename;
<ide> return filename;
<ide> }
<ide> Module._resolveLookupPaths = function(request, parent) {
<ide> }
<ide>
<ide> var start = request.substring(0, 2);
<del> if (start !== '.' && start !== './' && start !== '..') {
<add> if (start !== './' && start !== '..') {
<ide> var paths = modulePaths;
<ide> if (parent) {
<ide> if (!parent.paths) parent.paths = [];
<ide> paths = parent.paths.concat(paths);
<ide> }
<add>
<add> // Maintain backwards compat with certain broken uses of require('.')
<add> // by putting the module's directory in front of the lookup paths.
<add> if (request === '.') {
<add> if (parent && parent.filename) {
<add> paths.splice(0, 0, path.dirname(parent.filename));
<add> } else {
<add> paths.splice(0, 0, path.resolve(request));
<add> }
<add> }
<add>
<ide> return [request, paths];
<ide> }
<ide>
<ide><path>test/parallel/test-require-dot.js
<add>var common = require('../common');
<add>var assert = require('assert');
<add>var module = require('module');
<add>
<add>var a = require(common.fixturesDir + '/module-require/relative/dot.js');
<add>var b = require(common.fixturesDir + '/module-require/relative/dot-slash.js');
<add>
<add>assert.equal(a.value, 42);
<add>assert.equal(a, b, 'require(".") should resolve like require("./")');
<add>
<add>process.env.NODE_PATH = common.fixturesDir + '/module-require/relative';
<add>module._initPaths();
<add>
<add>var c = require('.');
<add>
<add>assert.equal(c.value, 42, 'require(".") should honor NODE_PATH');
<ide>\ No newline at end of file
<ide><path>test/parallel/test-require-extensions-main.js
<ide> var common = require('../common');
<ide> var assert = require('assert');
<ide>
<del>require(common.fixturesDir + '/require-bin/bin/req.js');
<del>
<del>var a = require(common.fixturesDir + '/module-require/relative/dot.js');
<del>var b = require(common.fixturesDir + '/module-require/relative/dot-slash.js');
<del>
<del>assert.equal(a.value, 42);
<del>assert.equal(a, b, 'require(".") should resolve like require("./")');
<add>require(common.fixturesDir + '/require-bin/bin/req.js');
<ide>\ No newline at end of file | 3 |
Python | Python | remove unused private members | 5d6763496f6214c4a3240d3894328adf0e4cbebc | <ide><path>numpy/lib/_iotools.py
<ide> class StringConverter:
<ide> (nx.floating, float, nx.nan),
<ide> (nx.complexfloating, complex, nx.nan + 0j),])
<ide>
<del> (_defaulttype, _defaultfunc, _defaultfill) = zip(*_mapper)
<del>
<ide> @classmethod
<ide> def _getdtype(cls, val):
<ide> """Returns the dtype of the input variable.""" | 1 |
Javascript | Javascript | fix uiexplorer drawer list | 893e9e315e055de52c7d625e81cb85b79d4a2480 | <ide><path>Examples/UIExplorer/UIExplorerApp.android.js
<ide> const styles = StyleSheet.create({
<ide> height: 56,
<ide> },
<ide> drawerContentWrapper: {
<add> flex: 1,
<ide> paddingTop: StatusBar.currentHeight,
<ide> backgroundColor: 'white',
<ide> }, | 1 |
Ruby | Ruby | adjust installer for updated link error handling | 4b4fc003df6771a5b9279f5935633d70a9d2a7b9 | <ide><path>Library/Homebrew/formula_installer.rb
<ide> def link
<ide>
<ide> begin
<ide> keg.link
<del> rescue Exception => e
<add> rescue Keg::LinkError => e
<ide> onoe "The `brew link` step did not complete successfully"
<ide> puts "The formula built, but is not symlinked into #{HOMEBREW_PREFIX}"
<del> puts "You can try again using `brew link #{f.name}'"
<add> puts "You can try again using:"
<add> puts " brew link #{f.name}"
<ide> puts
<ide> puts "Possible conflicting files are:"
<ide> mode = OpenStruct.new(:dry_run => true, :overwrite => true)
<ide> keg.link(mode)
<del> ohai e, e.backtrace if debug?
<ide> @show_summary_heading = true
<del> ignore_interrupts{ keg.unlink }
<del> raise unless e.kind_of? RuntimeError
<add> rescue Exception => e
<add> onoe "An unexpected error occurred during the `brew link` step"
<add> puts "The formula built, but is not symlinked into #{HOMEBREW_PREFIX}"
<add> puts e
<add> puts e.backtrace if debug?
<add> @show_summary_heading = true
<add> ignore_interrupts { keg.unlink }
<add> raise
<ide> end
<ide> end
<ide> | 1 |
Ruby | Ruby | add new tests for fails_with dsl | 9dd6d74b44d857d9b5906dffd896d4109229b1df | <ide><path>Library/Homebrew/test/test_fails_with.rb
<add>require 'testing_env'
<add>require 'test/testball'
<add>
<add>class FailsWithTests < Test::Unit::TestCase
<add> class Double < Compiler
<add> attr_accessor :name, :build
<add> end
<add>
<add> def assert_fails_with(cc)
<add> assert @f.new.fails_with?(cc)
<add> end
<add>
<add> def assert_does_not_fail_with(cc)
<add> assert !@f.new.fails_with?(cc)
<add> end
<add>
<add> def fails_with(*args, &block)
<add> @f.send(:fails_with, *args, &block)
<add> end
<add>
<add> def build_cc(sym, build)
<add> cc = Double.new
<add> cc.name = sym
<add> cc.build = build
<add> cc
<add> end
<add>
<add> def setup
<add> @f = Class.new(TestBall)
<add> end
<add>
<add> def test_fails_with_symbol
<add> fails_with :clang
<add> cc = build_cc(:clang, 425)
<add> assert_fails_with cc
<add> end
<add>
<add> def test_fails_with_build
<add> fails_with(:clang) { build 211 }
<add> cc = build_cc(:clang, 318)
<add> assert_does_not_fail_with cc
<add> end
<add>
<add> def test_fails_with_block_without_build
<add> fails_with(:clang) { }
<add> cc = build_cc(:clang, 425)
<add> assert_fails_with cc
<add> end
<add>
<add> def test_multiple_failures
<add> fails_with(:llvm)
<add> fails_with(:clang)
<add> gcc = build_cc(:gcc, 5666)
<add> llvm = build_cc(:llvm, 2336)
<add> clang = build_cc(:clang, 425)
<add> assert_fails_with llvm
<add> assert_fails_with clang
<add> assert_does_not_fail_with gcc
<add> end
<add>end | 1 |
Python | Python | fix mypy for cli package | f7a9fd757454e4e6e9686b765cb088caccaba8c3 | <ide><path>airflow/cli/commands/cheat_sheet_command.py
<ide> from airflow.cli.cli_parser import ActionCommand, GroupCommand, airflow_commands
<ide> from airflow.cli.simple_table import AirflowConsole, SimpleTable
<ide> from airflow.utils.cli import suppress_logs_and_warning
<del>from airflow.utils.helpers import partition
<ide>
<ide>
<ide> @suppress_logs_and_warning
<ide> def display_recursive(
<ide> ):
<ide> actions: List[ActionCommand]
<ide> groups: List[GroupCommand]
<del> actions_iter, groups_iter = partition(lambda x: isinstance(x, GroupCommand), commands)
<del> actions, groups = list(actions_iter), list(groups_iter)
<add> actions: List[ActionCommand] = []
<add> groups: List[GroupCommand] = []
<add> for command in commands:
<add> if isinstance(command, GroupCommand):
<add> groups.append(command)
<add> else:
<add> actions.append(command)
<ide>
<ide> console = AirflowConsole()
<ide> if actions:
<ide><path>airflow/cli/commands/info_command.py
<ide> def process_url(self, value) -> str:
<ide> class NullAnonymizer(Anonymizer):
<ide> """Do nothing."""
<ide>
<del> def _identity(self, value):
<add> def _identity(self, value) -> str:
<ide> return value
<ide>
<ide> process_path = process_username = process_url = _identity
<ide> def __init__(self):
<ide> username = getuser()
<ide> self._path_replacements = {home_path: "${HOME}", username: "${USER}"}
<ide>
<del> def process_path(self, value):
<add> def process_path(self, value) -> str:
<ide> if not value:
<ide> return value
<ide> for src, target in self._path_replacements.items():
<ide> value = value.replace(src, target)
<ide> return value
<ide>
<del> def process_username(self, value):
<add> def process_username(self, value) -> str:
<ide> if not value:
<ide> return value
<ide> return value[0] + "..." + value[-1]
<ide>
<del> def process_url(self, value):
<add> def process_url(self, value) -> str:
<ide> if not value:
<ide> return value
<ide>
<ide><path>airflow/cli/simple_table.py
<ide> def print_as_plain_table(self, data: List[Dict]):
<ide> self.print("No data found")
<ide> return
<ide> rows = [d.values() for d in data]
<del> output = tabulate(rows, tablefmt="plain", headers=data[0].keys())
<add> output = tabulate(rows, tablefmt="plain", headers=list(data[0].keys()))
<ide> print(output)
<ide>
<ide> def _normalize_data(self, value: Any, output: str) -> Optional[Union[list, str, dict]]:
<ide> if isinstance(value, (tuple, list)):
<ide> if output == "table":
<del> return ",".join(self._normalize_data(x, output) for x in value)
<add> return ",".join(str(self._normalize_data(x, output)) for x in value)
<ide> return [self._normalize_data(x, output) for x in value]
<ide> if isinstance(value, dict) and output != "table":
<ide> return {k: self._normalize_data(v, output) for k, v in value.items()}
<ide> def _normalize_data(self, value: Any, output: str) -> Optional[Union[list, str,
<ide>
<ide> def print_as(self, data: List[Union[Dict, Any]], output: str, mapper: Optional[Callable] = None):
<ide> """Prints provided using format specified by output argument"""
<del> output_to_renderer = {
<add> output_to_renderer: Dict[str, Callable[[Any], None]] = {
<ide> "json": self.print_as_json,
<ide> "yaml": self.print_as_yaml,
<ide> "table": self.print_as_table,
<ide> def print_as(self, data: List[Union[Dict, Any]], output: str, mapper: Optional[C
<ide> if mapper:
<ide> dict_data: List[Dict] = [mapper(d) for d in data]
<ide> else:
<del> dict_data: List[Dict] = data
<add> dict_data = data
<ide> dict_data = [{k: self._normalize_data(v, output) for k, v in d.items()} for d in dict_data]
<ide> renderer(dict_data)
<ide> | 3 |
Python | Python | add missing unicode declaration | 337f9601f26d463f4f2ba6349a1ec81a60515c35 | <ide><path>spacy/tests/regression/test_issue743.py
<add># coding: utf8
<ide> from __future__ import unicode_literals
<ide> from ...vocab import Vocab
<ide> from ...tokens.doc import Doc | 1 |
Python | Python | fix custom init sorting script | 175da8d1821f108da7c0a61b32b6db861730f15f | <ide><path>src/transformers/__init__.py
<ide> # tokenizers-backed objects
<ide> if is_tokenizers_available():
<ide> # Fast tokenizers
<del> _import_structure["models.realm"].append("RealmTokenizerFast")
<del> _import_structure["models.xglm"].append("XGLMTokenizerFast")
<del> _import_structure["models.fnet"].append("FNetTokenizerFast")
<del> _import_structure["models.roformer"].append("RoFormerTokenizerFast")
<del> _import_structure["models.clip"].append("CLIPTokenizerFast")
<del> _import_structure["models.convbert"].append("ConvBertTokenizerFast")
<del> _import_structure["models.blenderbot_small"].append("BlenderbotSmallTokenizerFast")
<ide> _import_structure["models.albert"].append("AlbertTokenizerFast")
<ide> _import_structure["models.bart"].append("BartTokenizerFast")
<ide> _import_structure["models.barthez"].append("BarthezTokenizerFast")
<ide> _import_structure["models.bert"].append("BertTokenizerFast")
<ide> _import_structure["models.big_bird"].append("BigBirdTokenizerFast")
<ide> _import_structure["models.blenderbot"].append("BlenderbotTokenizerFast")
<add> _import_structure["models.blenderbot_small"].append("BlenderbotSmallTokenizerFast")
<ide> _import_structure["models.camembert"].append("CamembertTokenizerFast")
<add> _import_structure["models.clip"].append("CLIPTokenizerFast")
<add> _import_structure["models.convbert"].append("ConvBertTokenizerFast")
<ide> _import_structure["models.deberta"].append("DebertaTokenizerFast")
<ide> _import_structure["models.deberta_v2"].append("DebertaV2TokenizerFast")
<ide> _import_structure["models.distilbert"].append("DistilBertTokenizerFast")
<ide> _import_structure["models.dpr"].extend(
<ide> ["DPRContextEncoderTokenizerFast", "DPRQuestionEncoderTokenizerFast", "DPRReaderTokenizerFast"]
<ide> )
<ide> _import_structure["models.electra"].append("ElectraTokenizerFast")
<add> _import_structure["models.fnet"].append("FNetTokenizerFast")
<ide> _import_structure["models.funnel"].append("FunnelTokenizerFast")
<ide> _import_structure["models.gpt2"].append("GPT2TokenizerFast")
<ide> _import_structure["models.herbert"].append("HerbertTokenizerFast")
<ide> _import_structure["models.mt5"].append("MT5TokenizerFast")
<ide> _import_structure["models.openai"].append("OpenAIGPTTokenizerFast")
<ide> _import_structure["models.pegasus"].append("PegasusTokenizerFast")
<add> _import_structure["models.realm"].append("RealmTokenizerFast")
<ide> _import_structure["models.reformer"].append("ReformerTokenizerFast")
<ide> _import_structure["models.rembert"].append("RemBertTokenizerFast")
<ide> _import_structure["models.retribert"].append("RetriBertTokenizerFast")
<ide> _import_structure["models.roberta"].append("RobertaTokenizerFast")
<add> _import_structure["models.roformer"].append("RoFormerTokenizerFast")
<ide> _import_structure["models.splinter"].append("SplinterTokenizerFast")
<ide> _import_structure["models.squeezebert"].append("SqueezeBertTokenizerFast")
<ide> _import_structure["models.t5"].append("T5TokenizerFast")
<add> _import_structure["models.xglm"].append("XGLMTokenizerFast")
<ide> _import_structure["models.xlm_roberta"].append("XLMRobertaTokenizerFast")
<ide> _import_structure["models.xlnet"].append("XLNetTokenizerFast")
<ide> _import_structure["tokenization_utils_fast"] = ["PreTrainedTokenizerFast"]
<ide><path>src/transformers/models/marian/__init__.py
<ide>
<ide> if is_flax_available():
<ide> _import_structure["modeling_flax_marian"] = ["FlaxMarianModel", "FlaxMarianMTModel", "FlaxMarianPreTrainedModel"]
<add>
<ide> if TYPE_CHECKING:
<ide> from .configuration_marian import MARIAN_PRETRAINED_CONFIG_ARCHIVE_MAP, MarianConfig, MarianOnnxConfig
<ide>
<ide><path>utils/custom_init_isort.py
<ide> def sort_imports(file, check_only=True):
<ide> # Check if the block contains some `_import_structure`s thingy to sort.
<ide> block = main_blocks[block_idx]
<ide> block_lines = block.split("\n")
<del> if len(block_lines) < 3 or "_import_structure" not in "".join(block_lines[:2]):
<add>
<add> # Get to the start of the imports.
<add> line_idx = 0
<add> while line_idx < len(block_lines) and "_import_structure" not in block_lines[line_idx]:
<add> # Skip dummy import blocks
<add> if "import dummy" in block_lines[line_idx]:
<add> line_idx = len(block_lines)
<add> else:
<add> line_idx += 1
<add> if line_idx >= len(block_lines):
<ide> continue
<ide>
<del> # Ignore first and last line: they don't contain anything.
<del> internal_block_code = "\n".join(block_lines[1:-1])
<add> # Ignore beginning and last line: they don't contain anything.
<add> internal_block_code = "\n".join(block_lines[line_idx:-1])
<ide> indent = get_indent(block_lines[1])
<ide> # Slit the internal block into blocks of indent level 1.
<ide> internal_blocks = split_code_in_indented_blocks(internal_block_code, indent_level=indent)
<ide> def sort_imports(file, check_only=True):
<ide> count += 1
<ide>
<ide> # And we put our main block back together with its first and last line.
<del> main_blocks[block_idx] = "\n".join([block_lines[0]] + reorderded_blocks + [block_lines[-1]])
<add> main_blocks[block_idx] = "\n".join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]])
<ide>
<ide> if code != "\n".join(main_blocks):
<ide> if check_only: | 3 |
Javascript | Javascript | avoid object.defineproperties for nodes | 95fb798980d7e404c413e29e20016db9052e2bf2 | <ide><path>src/data/Data.js
<ide> Data.prototype = {
<ide> return 0;
<ide> }
<ide>
<del> var descriptor = {},
<del> // Check if the owner object already has a cache key
<del> unlock = owner[ this.expando ];
<add> // Check if the owner object already has a cache key
<add> var unlock = owner[ this.expando ];
<ide>
<ide> // If not, create one
<ide> if ( !unlock ) {
<ide> unlock = Data.uid++;
<ide>
<del> // Secure it in a non-enumerable, non-writable property
<del> try {
<del> descriptor[ this.expando ] = { value: unlock };
<del> Object.defineProperties( owner, descriptor );
<del>
<del> // Support: Android<4
<del> // Fallback to a less secure definition
<del> } catch ( e ) {
<del> descriptor[ this.expando ] = unlock;
<del> jQuery.extend( owner, descriptor );
<add> // If it is a node unlikely to be stringify-ed or looped over
<add> // use plain assignment
<add> if ( owner.nodeType ) {
<add> owner[ this.expando ] = unlock;
<add> // Otherwise secure it in a non-enumerable, non-writable property
<add> } else {
<add> Object.defineProperty( owner, this.expando, { value: unlock } );
<ide> }
<ide> }
<ide> | 1 |
Python | Python | adjust info message | 761bd60d43748c5b85399d5c1a484f188c6a08de | <ide><path>spacy/cli/project/assets.py
<ide> def project_assets(project_dir: Path) -> None:
<ide> if dest.exists():
<ide> # If there's already a file, check for checksum
<ide> if checksum and checksum == get_checksum(dest):
<del> msg.good(f"Skipping download with matching checksum: {dest}")
<add> msg.good(
<add> f"Skipping download with matching checksum: {asset['dest']}"
<add> )
<ide> continue
<ide> else:
<ide> if dest.is_dir(): | 1 |
Javascript | Javascript | fix non-determinism in test-crypto-domains | 1f11983350a7da56bb1d0ca560a7e5ec5c1c0d43 | <ide><path>test/simple/test-crypto-domains.js
<ide> var domain = require('domain');
<ide> var assert = require('assert');
<ide> var d = domain.create();
<ide> var expect = ['pbkdf2', 'randomBytes', 'pseudoRandomBytes']
<add>var errors = 0;
<add>
<add>process.on('exit', function() {
<add> assert.equal(errors, 3);
<add>});
<ide>
<ide> d.on('error', function (e) {
<ide> assert.equal(e.message, expect.shift());
<add> errors += 1;
<ide> });
<ide>
<ide> d.run(function () {
<del> crypto.pbkdf2('a', 'b', 1, 8, function () {
<del> throw new Error('pbkdf2');
<del> });
<del>
<del> crypto.randomBytes(4, function () {
<del> throw new Error('randomBytes');
<del> });
<del>
<del> crypto.pseudoRandomBytes(4, function () {
<del> throw new Error('pseudoRandomBytes');
<del> });
<add> one();
<add>
<add> function one() {
<add> crypto.pbkdf2('a', 'b', 1, 8, function () {
<add> two();
<add> throw new Error('pbkdf2');
<add> });
<add> }
<add>
<add> function two() {
<add> crypto.randomBytes(4, function () {
<add> three();
<add> throw new Error('randomBytes');
<add> });
<add> }
<add>
<add> function three() {
<add> crypto.pseudoRandomBytes(4, function () {
<add> throw new Error('pseudoRandomBytes');
<add> });
<add> }
<ide> }); | 1 |
Javascript | Javascript | remove unreachable code | 6a8cedf9858cfef73f70784a377d5c008360e5a0 | <ide><path>src/renderers/shared/fiber/ReactFiberPendingWork.js
<ide> exports.findNextUnitOfWorkAtPriority = function(currentRoot : Fiber, priorityLev
<ide> current.pendingWorkPriority = NoWork;
<ide> }
<ide> if (current === currentRoot) {
<del> if (current.pendingWorkPriority <= priorityLevel) {
<del> current.pendingWorkPriority = NoWork;
<del> }
<ide> return null;
<ide> }
<ide> while (!current.sibling) { | 1 |
Ruby | Ruby | fix inconsistent behavior from string#first/#last | 9e67954dcfdc92f1087a03c0b1c61251d993e270 | <ide><path>activesupport/lib/active_support/core_ext/string/access.rb
<ide> def to(position)
<ide>
<ide> # Returns the first character. If a limit is supplied, returns a substring
<ide> # from the beginning of the string until it reaches the limit value. If the
<del> # given limit is greater than or equal to the string length, returns self.
<add> # given limit is greater than or equal to the string length, returns a copy of self.
<ide> #
<ide> # str = "hello"
<ide> # str.first # => "h"
<ide> def first(limit = 1)
<ide> if limit == 0
<ide> ''
<ide> elsif limit >= size
<del> self
<add> self.dup
<ide> else
<ide> to(limit - 1)
<ide> end
<ide> end
<ide>
<ide> # Returns the last character of the string. If a limit is supplied, returns a substring
<ide> # from the end of the string until it reaches the limit value (counting backwards). If
<del> # the given limit is greater than or equal to the string length, returns self.
<add> # the given limit is greater than or equal to the string length, returns a copy of self.
<ide> #
<ide> # str = "hello"
<ide> # str.last # => "o"
<ide> def last(limit = 1)
<ide> if limit == 0
<ide> ''
<ide> elsif limit >= size
<del> self
<add> self.dup
<ide> else
<ide> from(-limit)
<ide> end
<ide><path>activesupport/test/core_ext/string_ext_test.rb
<ide> class StringAccessTest < ActiveSupport::TestCase
<ide> assert_equal 'x', 'x'.first(4)
<ide> end
<ide>
<add> test "#first with Fixnum >= string length still returns a new string" do
<add> string = "hello"
<add> different_string = string.first(5)
<add> assert_not_same different_string, string
<add> end
<add>
<ide> test "#last returns the last character" do
<ide> assert_equal "o", "hello".last
<ide> assert_equal 'x', 'x'.last
<ide> class StringAccessTest < ActiveSupport::TestCase
<ide> assert_equal 'x', 'x'.last(4)
<ide> end
<ide>
<add> test "#last with Fixnum >= string length still returns a new string" do
<add> string = "hello"
<add> different_string = string.last(5)
<add> assert_not_same different_string, string
<add> end
<add>
<ide> test "access returns a real string" do
<ide> hash = {}
<ide> hash["h"] = true | 2 |
Text | Text | remove redux comment | 6de3ff9d78108dc439cb49bbc22c8cf1bbcd8a5b | <ide><path>examples/with-apollo/README.md
<ide> In this simple example, we integrate Apollo seamlessly with Next by wrapping our
<ide> On initial page load, while on the server and inside `getInitialProps`, we invoke the Apollo method, [`getDataFromTree`](http://dev.apollodata.com/react/server-side-rendering.html#getDataFromTree). This method returns a promise; at the point in which the promise resolves, our Apollo Client store is completely initialized.
<ide>
<ide> This example relies on [graph.cool](https://www.graph.cool) for its GraphQL backend.
<del>
<del>*Note: Apollo uses Redux internally; if you're interested in integrating the client with your existing Redux store check out the [`with-apollo-and-redux`](https://github.com/zeit/next.js/tree/master/examples/with-apollo-and-redux) example.* | 1 |
Text | Text | fix typo in arm.md | 25cfa80119df7e2859729bdac4bae4a753b82d62 | <ide><path>ARM.md
<ide> A Scaleway C1 server can be easily purchased on demand on the Scaleway website:
<ide>
<ide> https://www.scaleway.com
<ide>
<del>It is a cheap and fast way to get access to a pysical ARM server.
<add>It is a cheap and fast way to get access to a physical ARM server.
<ide> It features a 4-cores ARMv7 CPU with 2GB of RAM and a 1 Gbit/s network card.
<ide>
<ide> Scaleway servers can be started we prepared images from their image hub. | 1 |
Javascript | Javascript | add view_type meta to analytics | 3cee5509e61ef335f2ef86c9d98fc7d1eca9f832 | <ide><path>client/src/redux/ga-saga.js
<ide> import ga from '../analytics';
<ide> import {
<ide> emailSelector,
<ide> completionCountSelector,
<del> completedChallengesSelector
<add> completedChallengesSelector,
<add> recentlyClaimedBlockSelector
<ide> } from '../redux';
<ide> import { emailToABVariant } from '../utils/A-B-tester';
<ide>
<ide> function* callGaType({ payload: { type, data } }) {
<ide> if (email) {
<ide> const completedChallengeTotal = yield select(completedChallengesSelector);
<ide> const completedChallengeSession = yield select(completionCountSelector);
<add> let viewType = null;
<add>
<add> // set the modal type
<add> if (data.action.includes('Modal')) {
<add> const recentlyClaimedBlock = yield select(recentlyClaimedBlockSelector);
<add> viewType = recentlyClaimedBlock ? 'block' : 'progress';
<add> }
<add>
<ide> const customDimensions = {
<ide> // URL;
<ide> dimension1: window.location.href,
<ide> function* callGaType({ payload: { type, data } }) {
<ide> // Test_Type
<ide> dimension4: aBTestConfig.type,
<ide> // Test_Variation
<del> dimension5: emailToABVariant(email).isAVariant ? 'A' : 'B'
<add> dimension5: emailToABVariant(email).isAVariant ? 'A' : 'B',
<add> // View_Type
<add> dimension6: viewType
<ide> };
<ide> ga.set(customDimensions);
<ide> } | 1 |
Text | Text | add 2.9.0-beta.1 to changelog.md | cb917916c9c69ad44e02905d7961f812b7aceab9 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### 2.9.0-beta.1 (September 8, 2012)
<add>
<add>- [#14156](https://github.com/emberjs/ember.js/pull/14156) [FEATURE ember-glimmer] Enable by default.
<add>
<ide> ### 2.8.0 (September 8, 2016)
<ide>
<ide> - [#14229](https://github.com/emberjs/ember.js/pull/14229) [BUGFIX] Fix boot errors with `location: 'auto'` when using IE9. | 1 |
Javascript | Javascript | switch the param order in the assertion | 23416936bc3fd4c3d3d49e4025e82d42dc18036f | <ide><path>test/parallel/test-tls-sni-option.js
<ide> test({
<ide> function test(options, clientResult, serverResult, clientError, serverError) {
<ide> const server = tls.createServer(serverOptions, (c) => {
<ide> assert.deepStrictEqual(
<del> { sni: c.servername, authorized: c.authorized },
<del> serverResult
<add> serverResult,
<add> { sni: c.servername, authorized: c.authorized }
<ide> );
<ide> });
<ide> | 1 |
Python | Python | update hooks to use parameters | 19b6544a4d267494e95652ae264c443511524222 | <ide><path>airflow/operators/jdbc_operator.py
<ide> class JdbcOperator(BaseOperator):
<ide> @apply_defaults
<ide> def __init__(
<ide> self, sql,
<del> jdbc_conn_id='jdbc_default', autocommit=False,
<add> jdbc_conn_id='jdbc_default', autocommit=False, parameters=None,
<ide> *args, **kwargs):
<ide> super(JdbcOperator, self).__init__(*args, **kwargs)
<add> self.parameters = parameters
<ide>
<ide> self.sql = sql
<ide> self.jdbc_conn_id = jdbc_conn_id
<ide> def __init__(
<ide> def execute(self, context):
<ide> logging.info('Executing: ' + str(self.sql))
<ide> self.hook = JdbcHook(jdbc_conn_id=self.jdbc_conn_id)
<del> self.hook.run(self.sql, self.autocommit)
<add> self.hook.run(self.sql, self.autocommit, parameters=self.parameters)
<ide><path>airflow/operators/mssql_operator.py
<ide> class MsSqlOperator(BaseOperator):
<ide> ui_color = '#ededed'
<ide>
<ide> @apply_defaults
<del> def __init__(self, sql, mssql_conn_id='mssql_default', *args, **kwargs):
<add> def __init__(
<add> self, sql, mssql_conn_id='mssql_default', parameters=None,
<add> *args, **kwargs):
<ide> super(MsSqlOperator, self).__init__(*args, **kwargs)
<ide> self.mssql_conn_id = mssql_conn_id
<ide> self.sql = sql
<add> self.parameters = parameters
<ide>
<ide> def execute(self, context):
<ide> logging.info('Executing: ' + str(self.sql))
<ide> hook = MsSqlHook(mssql_conn_id=self.mssql_conn_id)
<del> hook.run(self.sql)
<add> hook.run(self.sql, parameters=self.parameters)
<ide><path>airflow/operators/mysql_operator.py
<ide> class MySqlOperator(BaseOperator):
<ide> ui_color = '#ededed'
<ide>
<ide> @apply_defaults
<del> def __init__(self, sql, mysql_conn_id='mysql_default', *args, **kwargs):
<add> def __init__(
<add> self, sql, mysql_conn_id='mysql_default', parameters=None,
<add> *args, **kwargs):
<ide> super(MySqlOperator, self).__init__(*args, **kwargs)
<ide> self.mysql_conn_id = mysql_conn_id
<ide> self.sql = sql
<add> self.parameters = parameters
<ide>
<ide> def execute(self, context):
<ide> logging.info('Executing: ' + str(self.sql))
<ide> hook = MySqlHook(mysql_conn_id=self.mysql_conn_id)
<del> hook.run(self.sql)
<add> hook.run(self.sql, parameters=self.parameters)
<ide><path>airflow/operators/postgres_operator.py
<ide> class PostgresOperator(BaseOperator):
<ide> def __init__(
<ide> self, sql,
<ide> postgres_conn_id='postgres_default', autocommit=False,
<add> parameters=None,
<ide> *args, **kwargs):
<ide> super(PostgresOperator, self).__init__(*args, **kwargs)
<del>
<ide> self.sql = sql
<ide> self.postgres_conn_id = postgres_conn_id
<ide> self.autocommit = autocommit
<add> self.parameters = parameters
<ide>
<ide> def execute(self, context):
<ide> logging.info('Executing: ' + str(self.sql))
<ide> self.hook = PostgresHook(postgres_conn_id=self.postgres_conn_id)
<del> self.hook.run(self.sql, self.autocommit)
<add> self.hook.run(self.sql, self.autocommit, parameters=self.parameters)
<ide><path>airflow/operators/sqlite_operator.py
<ide> class SqliteOperator(BaseOperator):
<ide> ui_color = '#cdaaed'
<ide>
<ide> @apply_defaults
<del> def __init__(self, sql, sqlite_conn_id='sqlite_default', *args, **kwargs):
<add> def __init__(
<add> self, sql, sqlite_conn_id='sqlite_default', parameters=None,
<add> *args, **kwargs):
<ide> super(SqliteOperator, self).__init__(*args, **kwargs)
<ide> self.sqlite_conn_id = sqlite_conn_id
<ide> self.sql = sql
<add> self.parameters = parameters
<ide>
<ide> def execute(self, context):
<ide> logging.info('Executing: ' + self.sql)
<ide> hook = SqliteHook(sqlite_conn_id=self.sqlite_conn_id)
<del> hook.run(self.sql)
<add> hook.run(self.sql, parameters=self.parameters) | 5 |
PHP | PHP | add tests for schemavalue | 3649d42c2d250aad87f230dbc82b23c999682c74 | <ide><path>lib/Cake/Test/TestCase/Database/Driver/SqliteTest.php
<ide> public function testConnectionConfigCustom() {
<ide> $driver->connect($config);
<ide> }
<ide>
<add>/**
<add> * Data provider for schemaValue()
<add> *
<add> * @return array
<add> */
<add> public static function schemaValueProvider() {
<add> return [
<add> [null, 'NULL'],
<add> [false, 'FALSE'],
<add> [true, 'TRUE'],
<add> [3.14159, '3.14159'],
<add> ['33', '33'],
<add> [66, 66],
<add> [0, 0],
<add> [10e5, '1000000'],
<add> ['farts', '"farts"'],
<add> ];
<add> }
<add>/**
<add> * Test the schemaValue method on Driver.
<add> *
<add> * @dataProvider schemaValueProvider
<add> * @return void
<add> */
<add> public function testSchemaValue($input, $expected) {
<add> $driver = new Sqlite();
<add> $mock = $this->getMock('FakePdo', ['quote', 'quoteIdentifier']);
<add> $mock->expects($this->any())
<add> ->method('quote')
<add> ->will($this->returnCallback(function ($value) {
<add> return '"' . $value . '"';
<add> }));
<add> $driver->connection($mock);
<add> $this->assertEquals($expected, $driver->schemaValue($input));
<add> }
<add>
<ide> } | 1 |
PHP | PHP | fix tests on postgres | a5fb82d4da9ddf86b1d951ed074833fa6d1f94bc | <ide><path>tests/TestCase/ORM/TableTest.php
<ide> public function testSaveManyResultSet()
<ide> {
<ide> $table = TableRegistry::get('authors');
<ide>
<del> $entities = $table->find()->all();
<add> $entities = $table->find()
<add> ->order(['id' => 'ASC'])
<add> ->all();
<ide> $entities->first()->name = 'admad';
<ide>
<ide> $result = $table->saveMany($entities);
<ide> $this->assertSame($entities, $result);
<ide>
<del> $first = $table->find()->first();
<add> $first = $table->find()
<add> ->order(['id' => 'ASC'])
<add> ->first();
<ide> $this->assertSame('admad', $first->name);
<ide> }
<ide> | 1 |
Python | Python | fix oov_char=none case in imdb/reuters datasets | bcbfcc000ce07078786bae5f66f8b30dbe82fb64 | <ide><path>keras/datasets/imdb.py
<ide> def load_data(path='imdb.npz', num_words=None, skip_top=0,
<ide> for x in xs:
<ide> nx = []
<ide> for w in x:
<del> if w >= num_words or w < skip_top:
<add> if skip_top <= w < num_words:
<ide> nx.append(w)
<ide> new_xs.append(nx)
<ide> xs = new_xs
<ide><path>keras/datasets/reuters.py
<ide> def load_data(path='reuters.npz', num_words=None, skip_top=0,
<ide> for x in xs:
<ide> nx = []
<ide> for w in x:
<del> if w >= num_words or w < skip_top:
<add> if skip_top <= w < num_words:
<ide> nx.append(w)
<ide> new_xs.append(nx)
<ide> xs = new_xs | 2 |
Go | Go | fix libdm logging | e07d3cd9acf14219f33e12375fb8c2e3fe02ad0c | <ide><path>daemon/graphdriver/devmapper/deviceset.go
<ide> var (
<ide> DefaultThinpBlockSize uint32 = 128 // 64K = 128 512b sectors
<ide> MaxDeviceId int = 0xffffff // 24 bit, pool limit
<ide> DeviceIdMapSz int = (MaxDeviceId + 1) / 8
<add> // We retry device removal so many a times that even error messages
<add> // will fill up console during normal operation. So only log Fatal
<add> // messages by default.
<add> DMLogLevel int = devicemapper.LogLevelFatal
<ide> )
<ide>
<ide> const deviceSetMetaFile string = "deviceset-metadata"
<ide> func setCloseOnExec(name string) {
<ide> }
<ide>
<ide> func (devices *DeviceSet) DMLog(level int, file string, line int, dmError int, message string) {
<del> if level >= devicemapper.LogLevelDebug {
<del> // (vbatts) libdm debug is very verbose. If you're debugging libdm, you can
<del> // comment out this check yourself
<del> level = devicemapper.LogLevelInfo
<add> // By default libdm sends us all the messages including debug ones.
<add> // We need to filter out messages here and figure out which one
<add> // should be printed.
<add> if level > DMLogLevel {
<add> return
<ide> }
<ide>
<ide> // FIXME(vbatts) push this back into ./pkg/devicemapper/
<del> logrus.Debugf("libdevmapper(%d): %s:%d (%d) %s", level, file, line, dmError, message)
<add> if level <= devicemapper.LogLevelErr {
<add> logrus.Errorf("libdevmapper(%d): %s:%d (%d) %s", level, file, line, dmError, message)
<add> } else if level <= devicemapper.LogLevelInfo {
<add> logrus.Infof("libdevmapper(%d): %s:%d (%d) %s", level, file, line, dmError, message)
<add> } else {
<add> // FIXME(vbatts) push this back into ./pkg/devicemapper/
<add> logrus.Debugf("libdevmapper(%d): %s:%d (%d) %s", level, file, line, dmError, message)
<add> }
<ide> }
<ide>
<ide> func major(device uint64) uint64 {
<ide> func (devices *DeviceSet) closeTransaction() error {
<ide> }
<ide>
<ide> func (devices *DeviceSet) initDevmapper(doInit bool) error {
<del> if os.Getenv("DEBUG") != "" {
<del> devicemapper.LogInitVerbose(devicemapper.LogLevelDebug)
<del> } else {
<del> devicemapper.LogInitVerbose(devicemapper.LogLevelWarn)
<del> }
<ide> // give ourselves to libdm as a log handler
<ide> devicemapper.LogInit(devices)
<ide> | 1 |
Mixed | Javascript | add pertinent info for fresh flatlisters | 2161f92aaf37e126c6906e7ae6202d196b72648c | <ide><path>Libraries/Lists/FlatList.js
<ide> type OptionalProps<ItemT> = {
<ide> * {length: ITEM_HEIGHT, offset: ITEM_HEIGHT * index, index}
<ide> * )}
<ide> *
<add> * Adding `getItemLayout` can be a great performance boost for lists of several hundred items.
<ide> * Remember to include separator length (height or width) in your offset calculation if you
<ide> * specify `ItemSeparatorComponent`.
<ide> */
<ide><path>docs/Performance.md
<ide> Use the new [`FlatList`](docs/flatlist.html) or [`SectionList`](docs/sectionlist
<ide> Besides simplifying the API, the new list components also have significant performance enhancements,
<ide> the main one being nearly constant memory usage for any number of rows.
<ide>
<add>If your [`FlatList`](docs/flatlist.html) is rendering slow, be sure that you've implemented
<add>[`getItemLayout`](https://facebook.github.io/react-native/docs/flatlist.html#getitemlayout) to
<add>optimize rendering speed by skipping measurement of the rendered items.
<add>
<ide> ### JS FPS plunges when re-rendering a view that hardly changes
<ide>
<ide> If you are using a ListView, you must provide a `rowHasChanged` function that can reduce a lot of work by quickly determining whether or not a row needs to be re-rendered. If you are using immutable data structures, this would be as simple as a reference equality check. | 2 |
Python | Python | fix cloudsigma tests | d0f6d22dbefe1de31cd13bdff813bb82c18f1a3d | <ide><path>libcloud/test/compute/test_cloudsigma_v1_0.py
<ide> class CloudSigmaAPI10BaseTestCase(object):
<ide> driver_kwargs = {}
<ide>
<ide> def setUp(self):
<add> self.driver_klass.connectionCls.conn_class = CloudSigmaHttp
<add> CloudSigmaHttp.type = None
<ide> self.driver = self.driver_klass(*self.driver_args,
<ide> **self.driver_kwargs)
<del> CloudSigmaHttp.type = None
<del> self.driver.connectionCls.conn_class = CloudSigmaHttp
<ide>
<ide> def test_list_nodes(self):
<ide> nodes = self.driver.list_nodes() | 1 |
Javascript | Javascript | remove unused variable | 2de0611b43f1587c511de65ef50c647e77e28abb | <ide><path>lib/crypto.js
<ide> function Credentials(secureProtocol, context) {
<ide>
<ide> if (context) {
<ide> this.context = context;
<del> this.reuseContext = true;
<ide> } else {
<ide> this.context = new SecureContext();
<ide> | 1 |
PHP | PHP | allow connection in 'exists' validation | 94f11c1d741d921e25c6fb6cbb8373f7d97ad161 | <ide><path>src/Illuminate/Validation/Validator.php
<ide> protected function validateUnique($attribute, $value, $parameters)
<ide> {
<ide> $this->requireParameterCount(1, $parameters, 'unique');
<ide>
<del> list($connection, $table) = $this->parseUniqueTable($parameters[0]);
<add> list($connection, $table) = $this->parseTable($parameters[0]);
<ide>
<ide> // The second parameter position holds the name of the column that needs to
<ide> // be verified as unique. If this parameter isn't specified we will just
<ide> protected function validateUnique($attribute, $value, $parameters)
<ide> }
<ide>
<ide> /**
<del> * Parse the connection / table for the unique rule.
<add> * Parse the connection / table for the unique / exists rules.
<ide> *
<ide> * @param string $table
<ide> * @return array
<ide> */
<del> protected function parseUniqueTable($table)
<add> protected function parseTable($table)
<ide> {
<ide> return Str::contains($table, '.') ? explode('.', $table, 2) : [null, $table];
<ide> }
<ide> protected function validateExists($attribute, $value, $parameters)
<ide> {
<ide> $this->requireParameterCount(1, $parameters, 'exists');
<ide>
<del> $table = $parameters[0];
<add> list($connection, $table) = $this->parseTable($parameters[0]);
<ide>
<ide> // The second parameter position holds the name of the column that should be
<ide> // verified as existing. If this parameter is not specified we will guess
<ide> protected function validateExists($attribute, $value, $parameters)
<ide>
<ide> $expected = (is_array($value)) ? count($value) : 1;
<ide>
<del> return $this->getExistCount($table, $column, $value, $parameters) >= $expected;
<add> return $this->getExistCount($connection, $table, $column, $value, $parameters) >= $expected;
<ide> }
<ide>
<ide> /**
<ide> * Get the number of records that exist in storage.
<ide> *
<add> * @param mixed $connection
<ide> * @param string $table
<ide> * @param string $column
<ide> * @param mixed $value
<ide> * @param array $parameters
<ide> * @return int
<ide> */
<del> protected function getExistCount($table, $column, $value, $parameters)
<add> protected function getExistCount($connection, $table, $column, $value, $parameters)
<ide> {
<ide> $verifier = $this->getPresenceVerifier();
<ide>
<add> if (! is_null($connection)) {
<add> $verifier->setConnection($connection);
<add> }
<add>
<ide> $extra = $this->getExtraExistConditions($parameters);
<ide>
<ide> if (is_array($value)) { | 1 |
Ruby | Ruby | remove unused variable - offset_bind | f2d66cddce16e6fb6a91085f01e79044dd5f7db7 | <ide><path>lib/arel/visitors/oracle.rb
<ide> def visit_Arel_Nodes_SelectStatement o, collector
<ide> collector = super(o, collector)
<ide>
<ide> if offset.expr.is_a? Nodes::BindParam
<del> offset_bind = nil
<ide> collector << ') raw_sql_ WHERE rownum <= ('
<ide> collector = visit offset.expr, collector
<ide> collector << ' + ' | 1 |
Java | Java | fix typo in abstractdelegatingsmartcontextloader | fe6a9826c57705149610fd678f71f0f6e423ff9f | <ide><path>spring-test/src/main/java/org/springframework/test/context/support/AbstractDelegatingSmartContextLoader.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * files nor annotated classes and instead declare only {@linkplain
<ide> * ContextConfiguration#initializers application context initializers}. In such
<ide> * cases, an attempt will still be made to detect defaults, but their absence will
<del> * not result an an exception.
<add> * not result in an exception.
<ide> *
<ide> * @author Sam Brannen
<ide> * @since 3.2 | 1 |
Javascript | Javascript | add http_simple_auto benchmark | 7535e3930a6d78674fb163d62ab818f8cb924df1 | <ide><path>benchmark/http_simple_auto.js
<add>//
<add>// Usage:
<add>// node benchmark/http_simple_auto.js <args> <target>
<add>//
<add>// Where:
<add>// <args> Arguments to pass to `ab`.
<add>// <target> Target to benchmark, e.g. `bytes/1024` or `buffer/8192`.
<add>//
<add>
<add>var path = require("path");
<add>var http = require("http");
<add>var spawn = require("child_process").spawn;
<add>
<add>var port = parseInt(process.env.PORT || 8000);
<add>
<add>var fixed = ""
<add>for (var i = 0; i < 20*1024; i++) {
<add> fixed += "C";
<add>}
<add>
<add>var stored = {};
<add>var storedBuffer = {};
<add>
<add>var server = http.createServer(function (req, res) {
<add> var commands = req.url.split("/");
<add> var command = commands[1];
<add> var body = "";
<add> var arg = commands[2];
<add> var n_chunks = parseInt(commands[3], 10);
<add> var status = 200;
<add>
<add> if (command == "bytes") {
<add> var n = parseInt(arg, 10)
<add> if (n <= 0)
<add> throw "bytes called with n <= 0"
<add> if (stored[n] === undefined) {
<add> stored[n] = "";
<add> for (var i = 0; i < n; i++) {
<add> stored[n] += "C"
<add> }
<add> }
<add> body = stored[n];
<add>
<add> } else if (command == "buffer") {
<add> var n = parseInt(arg, 10)
<add> if (n <= 0) throw new Error("bytes called with n <= 0");
<add> if (storedBuffer[n] === undefined) {
<add> storedBuffer[n] = new Buffer(n);
<add> for (var i = 0; i < n; i++) {
<add> storedBuffer[n][i] = "C".charCodeAt(0);
<add> }
<add> }
<add> body = storedBuffer[n];
<add>
<add> } else if (command == "quit") {
<add> res.connection.server.close();
<add> body = "quitting";
<add>
<add> } else if (command == "fixed") {
<add> body = fixed;
<add>
<add> } else if (command == "echo") {
<add> res.writeHead(200, { "Content-Type": "text/plain",
<add> "Transfer-Encoding": "chunked" });
<add> req.pipe(res);
<add> return;
<add>
<add> } else {
<add> status = 404;
<add> body = "not found\n";
<add> }
<add>
<add> // example: http://localhost:port/bytes/512/4
<add> // sends a 512 byte body in 4 chunks of 128 bytes
<add> if (n_chunks > 0) {
<add> res.writeHead(status, { "Content-Type": "text/plain",
<add> "Transfer-Encoding": "chunked" });
<add> // send body in chunks
<add> var len = body.length;
<add> var step = ~~(len / n_chunks) || len;
<add>
<add> for (var i = 0; i < len; i += step) {
<add> res.write(body.slice(i, i + step));
<add> }
<add>
<add> res.end();
<add> } else {
<add> var content_length = body.length.toString();
<add>
<add> res.writeHead(status, { "Content-Type": "text/plain",
<add> "Content-Length": content_length });
<add> res.end(body);
<add> }
<add>
<add>});
<add>
<add>server.listen(port, function () {
<add> var url = 'http://127.0.0.1:' + port + '/';
<add>
<add> var n = process.argv.length - 1;
<add> process.argv[n] = url + process.argv[n];
<add>
<add> var cp = spawn('ab', process.argv.slice(2));
<add> cp.stdout.pipe(process.stdout);
<add> cp.stderr.pipe(process.stderr);
<add> cp.on('exit', function() {
<add> server.close();
<add> });
<add>}); | 1 |
Ruby | Ruby | make current_url? work with a head method | f7277d99bf76e947fd404ac316eafeb993cc5bcd | <ide><path>actionpack/lib/action_view/helpers/url_helper.rb
<ide> def current_page?(options)
<ide> "in a #request method"
<ide> end
<ide>
<del> return false unless request.get?
<add> return false unless request.get? || request.head?
<ide>
<ide> url_string = url_for(options)
<ide>
<ide><path>actionpack/test/template/url_helper_test.rb
<ide> def request_for_url(url, opts = {})
<ide> ActionDispatch::Request.new(env)
<ide> end
<ide>
<add> def test_current_page_with_http_head_method
<add> @request = request_for_url("/", :method => :head)
<add> assert current_page?(url_hash)
<add> assert current_page?("http://www.example.com/")
<add> end
<add>
<ide> def test_current_page_with_simple_url
<ide> @request = request_for_url("/")
<ide> assert current_page?(url_hash) | 2 |
Java | Java | fix handshake handling issue | 9ca4672300aa59949ac1073c56feedee783af6ec | <ide><path>spring-websocket/src/main/java/org/springframework/websocket/CloseStatus.java
<ide> public boolean equals(Object other) {
<ide> return (this.code == otherStatus.code && ObjectUtils.nullSafeEquals(this.reason, otherStatus.reason));
<ide> }
<ide>
<add> public boolean equalsCode(CloseStatus other) {
<add> return this.code == other.code;
<add> }
<add>
<ide> @Override
<ide> public String toString() {
<ide> return "CloseStatus [code=" + this.code + ", reason=" + this.reason + "]";
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/client/endpoint/StandardWebSocketClient.java
<ide> import javax.websocket.ClientEndpointConfig.Configurator;
<ide> import javax.websocket.ContainerProvider;
<ide> import javax.websocket.Endpoint;
<add>import javax.websocket.HandshakeResponse;
<ide> import javax.websocket.Session;
<ide> import javax.websocket.WebSocketContainer;
<ide>
<add>import org.apache.commons.logging.Log;
<add>import org.apache.commons.logging.LogFactory;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.web.util.UriComponentsBuilder;
<ide> import org.springframework.websocket.WebSocketHandler;
<ide> */
<ide> public class StandardWebSocketClient implements WebSocketClient {
<ide>
<add> private static final Log logger = LogFactory.getLog(StandardWebSocketClient.class);
<add>
<ide> private static final Set<String> EXCLUDED_HEADERS = new HashSet<String>(
<ide> Arrays.asList("Sec-WebSocket-Accept", "Sec-WebSocket-Extensions", "Sec-WebSocket-Key",
<ide> "Sec-WebSocket-Protocol", "Sec-WebSocket-Version"));
<ide> public WebSocketSession doHandshake(WebSocketHandler webSocketHandler,
<ide> public void beforeRequest(Map<String, List<String>> headers) {
<ide> for (String headerName : httpHeaders.keySet()) {
<ide> if (!EXCLUDED_HEADERS.contains(headerName)) {
<del> headers.put(headerName, httpHeaders.get(headerName));
<add> List<String> value = httpHeaders.get(headerName);
<add> if (logger.isTraceEnabled()) {
<add> logger.trace("Adding header [" + headerName + "=" + value + "]");
<add> }
<add> headers.put(headerName, value);
<ide> }
<ide> }
<add> if (logger.isTraceEnabled()) {
<add> logger.trace("Handshake request headers: " + headers);
<add> }
<add> }
<add> @Override
<add> public void afterResponse(HandshakeResponse handshakeResponse) {
<add> if (logger.isTraceEnabled()) {
<add> logger.trace("Handshake response headers: " + handshakeResponse.getHeaders());
<add> }
<ide> }
<ide> });
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/client/jetty/JettyWebSocketClient.java
<ide> public WebSocketSession doHandshake(WebSocketHandler webSocketHandler, String ur
<ide> public WebSocketSession doHandshake(WebSocketHandler webSocketHandler, HttpHeaders headers, URI uri)
<ide> throws WebSocketConnectFailureException {
<ide>
<add> // TODO: populate headers
<add>
<ide> JettyWebSocketListenerAdapter listener = new JettyWebSocketListenerAdapter(webSocketHandler);
<ide>
<ide> try {
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/server/DefaultHandshakeHandler.java
<ide> import java.nio.charset.Charset;
<ide> import java.security.MessageDigest;
<ide> import java.security.NoSuchAlgorithmException;
<add>import java.util.ArrayList;
<ide> import java.util.Arrays;
<ide> import java.util.Collections;
<ide> import java.util.List;
<ide> import org.springframework.http.server.ServerHttpRequest;
<ide> import org.springframework.http.server.ServerHttpResponse;
<ide> import org.springframework.util.ClassUtils;
<add>import org.springframework.util.CollectionUtils;
<ide> import org.springframework.util.StringUtils;
<ide> import org.springframework.websocket.WebSocketHandler;
<ide>
<ide> public class DefaultHandshakeHandler implements HandshakeHandler {
<ide>
<ide> protected Log logger = LogFactory.getLog(getClass());
<ide>
<del> private List<String> supportedProtocols;
<add> private List<String> supportedProtocols = new ArrayList<String>();
<ide>
<ide> private RequestUpgradeStrategy requestUpgradeStrategy;
<ide>
<ide> public final boolean doHandshake(ServerHttpRequest request, ServerHttpResponse r
<ide> handleInvalidUpgradeHeader(request, response);
<ide> return false;
<ide> }
<del> if (!request.getHeaders().getConnection().contains("Upgrade")) {
<add> if (!request.getHeaders().getConnection().contains("Upgrade") &&
<add> !request.getHeaders().getConnection().contains("upgrade")) {
<ide> handleInvalidConnectHeader(request, response);
<ide> return false;
<ide> }
<ide> protected boolean isValidOrigin(ServerHttpRequest request) {
<ide> }
<ide>
<ide> protected String selectProtocol(List<String> requestedProtocols) {
<del> if (requestedProtocols != null) {
<add> if (CollectionUtils.isEmpty(requestedProtocols)) {
<ide> for (String protocol : requestedProtocols) {
<ide> if (this.supportedProtocols.contains(protocol)) {
<ide> return protocol; | 4 |
Ruby | Ruby | move mydumper to the boneyard | 174a9a76b48605904e37bce6b588230f8eadbe45 | <ide><path>Library/Homebrew/tap_migrations.rb
<ide> "lmutil" => "homebrew/binary",
<ide> "mlkit" => "homebrew/boneyard",
<ide> "mlton" => "homebrew/boneyard",
<add> "mydumper" => "homebrew/boneyard",
<ide> "nlopt" => "homebrew/science",
<ide> "octave" => "homebrew/science",
<ide> "opencv" => "homebrew/science", | 1 |
Text | Text | add v5.6.14 release notes | 0ebe9fede1566e4357b337da978bf5336b9c774e | <ide><path>CHANGELOG-5.6.md
<ide> # Release Notes for 5.6.x
<ide>
<add>## v5.6.14 (2018-03-28)
<add>
<add>### Added
<add>- Added `SlackMessage::info()` method ([#23711](https://github.com/laravel/framework/pull/23711))
<add>- Added `SessionGuard::logoutOtherDevices()` method ([9c51e49](https://github.com/laravel/framework/commit/9c51e49a56ff15fc47ac1a6bf232c32c25d14fd0))
<add>
<add>### Changed
<add>- Replaced Blade's `or` operator with null-coalescing operator ([13f732e](https://github.com/laravel/framework/commit/13f732ed617e41608e4ae021efc9d13e43375a26))
<add>
<add>### Fixed
<add>- Get Blade compiler from engine resolver ([#23710](https://github.com/laravel/framework/pull/23710))
<add>- Default to an empty string when validating the URL signatures ([#23721](https://github.com/laravel/framework/pull/23721))
<add>
<add>
<ide> ## v5.6.13 (2018-03-26)
<ide>
<ide> ### Added | 1 |
Python | Python | ignore the issue | 2f2197dece910fb72861423e419e2efaf1cbd399 | <ide><path>tests/plugins/test_plugins_manager.py
<ide> import importlib.metadata
<ide>
<ide> # only when we do not have importlib_metadata, the importlib.metadata is actually used
<del> importlib_metadata = 'importlib.metadata'
<add> importlib_metadata = 'importlib.metadata' # type: ignore
<ide> except ImportError:
<ide> raise Exception(
<ide> "Either importlib_metadata must be installed or importlib.metadata must be" | 1 |
Java | Java | add observable switchmapx and concatmapx operators | f6f6d82782b145ac4155707400db1b2f38cc221f | <ide><path>src/main/java/io/reactivex/Observable.java
<ide> import io.reactivex.internal.fuseable.ScalarCallable;
<ide> import io.reactivex.internal.observers.*;
<ide> import io.reactivex.internal.operators.flowable.*;
<add>import io.reactivex.internal.operators.mixed.*;
<ide> import io.reactivex.internal.operators.observable.*;
<ide> import io.reactivex.internal.util.*;
<ide> import io.reactivex.observables.*;
<ide> public final Completable concatMapCompletable(Function<? super T, ? extends Comp
<ide> public final Completable concatMapCompletable(Function<? super T, ? extends CompletableSource> mapper, int capacityHint) {
<ide> ObjectHelper.requireNonNull(mapper, "mapper is null");
<ide> ObjectHelper.verifyPositive(capacityHint, "capacityHint");
<del> return RxJavaPlugins.onAssembly(new ObservableConcatMapCompletable<T>(this, mapper, capacityHint));
<add> return RxJavaPlugins.onAssembly(new ObservableConcatMapCompletable<T>(this, mapper, ErrorMode.IMMEDIATE, capacityHint));
<add> }
<add>
<add> /**
<add> * Maps the upstream items into {@link CompletableSource}s and subscribes to them one after the
<add> * other terminates, delaying all errors till both this {@code Observable} and all
<add> * inner {@code CompletableSource}s terminate.
<add> * <p>
<add> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatMap.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code concatMapCompletableDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @param mapper the function called with the upstream item and should return
<add> * a {@code CompletableSource} to become the next source to
<add> * be subscribed to
<add> * @return a new Completable instance
<add> * @since 2.1.11 - experimental
<add> * @see #concatMapCompletable(Function, int)
<add> */
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @Experimental
<add> public final Completable concatMapCompletableDelayError(Function<? super T, ? extends CompletableSource> mapper) {
<add> return concatMapCompletableDelayError(mapper, true, 2);
<add> }
<add>
<add> /**
<add> * Maps the upstream items into {@link CompletableSource}s and subscribes to them one after the
<add> * other terminates, optionally delaying all errors till both this {@code Observable} and all
<add> * inner {@code CompletableSource}s terminate.
<add> * <p>
<add> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatMap.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code concatMapCompletableDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @param mapper the function called with the upstream item and should return
<add> * a {@code CompletableSource} to become the next source to
<add> * be subscribed to
<add> * @param tillTheEnd If {@code true}, errors from this {@code Observable} or any of the
<add> * inner {@code CompletableSource}s are delayed until all
<add> * of them terminate. If {@code false}, an error from this
<add> * {@code Observable} is delayed until the current inner
<add> * {@code CompletableSource} terminates and only then is
<add> * it emitted to the downstream.
<add> * @return a new Completable instance
<add> * @since 2.1.11 - experimental
<add> * @see #concatMapCompletable(Function)
<add> */
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @Experimental
<add> public final Completable concatMapCompletableDelayError(Function<? super T, ? extends CompletableSource> mapper, boolean tillTheEnd) {
<add> return concatMapCompletableDelayError(mapper, tillTheEnd, 2);
<add> }
<add>
<add> /**
<add> * Maps the upstream items into {@link CompletableSource}s and subscribes to them one after the
<add> * other terminates, optionally delaying all errors till both this {@code Observable} and all
<add> * inner {@code CompletableSource}s terminate.
<add> * <p>
<add> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatMap.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code concatMapCompletableDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @param mapper the function called with the upstream item and should return
<add> * a {@code CompletableSource} to become the next source to
<add> * be subscribed to
<add> * @param tillTheEnd If {@code true}, errors from this {@code Observable} or any of the
<add> * inner {@code CompletableSource}s are delayed until all
<add> * of them terminate. If {@code false}, an error from this
<add> * {@code Observable} is delayed until the current inner
<add> * {@code CompletableSource} terminates and only then is
<add> * it emitted to the downstream.
<add> * @param prefetch The number of upstream items to prefetch so that fresh items are
<add> * ready to be mapped when a previous {@code CompletableSource} terminates.
<add> * The operator replenishes after half of the prefetch amount has been consumed
<add> * and turned into {@code CompletableSource}s.
<add> * @return a new Completable instance
<add> * @since 2.1.11 - experimental
<add> * @see #concatMapCompletable(Function, int)
<add> */
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @Experimental
<add> public final Completable concatMapCompletableDelayError(Function<? super T, ? extends CompletableSource> mapper, boolean tillTheEnd, int prefetch) {
<add> ObjectHelper.requireNonNull(mapper, "mapper is null");
<add> ObjectHelper.verifyPositive(prefetch, "prefetch");
<add> return RxJavaPlugins.onAssembly(new ObservableConcatMapCompletable<T>(this, mapper, tillTheEnd ? ErrorMode.END : ErrorMode.BOUNDARY, prefetch));
<ide> }
<ide>
<ide> /**
<ide> public final <U> Observable<U> concatMapIterable(final Function<? super T, ? ext
<ide> return concatMap(ObservableInternalHelper.flatMapIntoIterable(mapper), prefetch);
<ide> }
<ide>
<add> /**
<add> * Maps the upstream items into {@link MaybeSource}s and subscribes to them one after the
<add> * other succeeds or completes, emits their success value if available or terminates immediately if
<add> * either this {@code Observable} or the current inner {@code MaybeSource} fail.
<add> * <p>
<add> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatMap.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code concatMapMaybe} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @param <R> the result type of the inner {@code MaybeSource}s
<add> * @param mapper the function called with the upstream item and should return
<add> * a {@code MaybeSource} to become the next source to
<add> * be subscribed to
<add> * @return a new Observable instance
<add> * @since 2.1.11 - experimental
<add> * @see #concatMapMaybeDelayError(Function)
<add> * @see #concatMapMaybe(Function, int)
<add> */
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @Experimental
<add> public final <R> Observable<R> concatMapMaybe(Function<? super T, ? extends MaybeSource<? extends R>> mapper) {
<add> return concatMapMaybe(mapper, 2);
<add> }
<add>
<add> /**
<add> * Maps the upstream items into {@link MaybeSource}s and subscribes to them one after the
<add> * other succeeds or completes, emits their success value if available or terminates immediately if
<add> * either this {@code Observable} or the current inner {@code MaybeSource} fail.
<add> * <p>
<add> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatMap.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code concatMapMaybe} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @param <R> the result type of the inner {@code MaybeSource}s
<add> * @param mapper the function called with the upstream item and should return
<add> * a {@code MaybeSource} to become the next source to
<add> * be subscribed to
<add> * @param prefetch The number of upstream items to prefetch so that fresh items are
<add> * ready to be mapped when a previous {@code MaybeSource} terminates.
<add> * The operator replenishes after half of the prefetch amount has been consumed
<add> * and turned into {@code MaybeSource}s.
<add> * @return a new Observable instance
<add> * @since 2.1.11 - experimental
<add> * @see #concatMapMaybe(Function)
<add> * @see #concatMapMaybeDelayError(Function, boolean, int)
<add> */
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @Experimental
<add> public final <R> Observable<R> concatMapMaybe(Function<? super T, ? extends MaybeSource<? extends R>> mapper, int prefetch) {
<add> ObjectHelper.requireNonNull(mapper, "mapper is null");
<add> ObjectHelper.verifyPositive(prefetch, "prefetch");
<add> return RxJavaPlugins.onAssembly(new ObservableConcatMapMaybe<T, R>(this, mapper, ErrorMode.IMMEDIATE, prefetch));
<add> }
<add>
<add> /**
<add> * Maps the upstream items into {@link MaybeSource}s and subscribes to them one after the
<add> * other terminates, emits their success value if available and delaying all errors
<add> * till both this {@code Observable} and all inner {@code MaybeSource}s terminate.
<add> * <p>
<add> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatMap.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code concatMapMaybeDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @param <R> the result type of the inner {@code MaybeSource}s
<add> * @param mapper the function called with the upstream item and should return
<add> * a {@code MaybeSource} to become the next source to
<add> * be subscribed to
<add> * @return a new Observable instance
<add> * @since 2.1.11 - experimental
<add> * @see #concatMapMaybe(Function)
<add> * @see #concatMapMaybeDelayError(Function, boolean)
<add> */
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @Experimental
<add> public final <R> Observable<R> concatMapMaybeDelayError(Function<? super T, ? extends MaybeSource<? extends R>> mapper) {
<add> return concatMapMaybeDelayError(mapper, true, 2);
<add> }
<add>
<add> /**
<add> * Maps the upstream items into {@link MaybeSource}s and subscribes to them one after the
<add> * other terminates, emits their success value if available and optionally delaying all errors
<add> * till both this {@code Observable} and all inner {@code MaybeSource}s terminate.
<add> * <p>
<add> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatMap.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code concatMapMaybeDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @param <R> the result type of the inner {@code MaybeSource}s
<add> * @param mapper the function called with the upstream item and should return
<add> * a {@code MaybeSource} to become the next source to
<add> * be subscribed to
<add> * @param tillTheEnd If {@code true}, errors from this {@code Observable} or any of the
<add> * inner {@code MaybeSource}s are delayed until all
<add> * of them terminate. If {@code false}, an error from this
<add> * {@code Observable} is delayed until the current inner
<add> * {@code MaybeSource} terminates and only then is
<add> * it emitted to the downstream.
<add> * @return a new Observable instance
<add> * @since 2.1.11 - experimental
<add> * @see #concatMapMaybe(Function, int)
<add> * @see #concatMapMaybeDelayError(Function, boolean, int)
<add> */
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @Experimental
<add> public final <R> Observable<R> concatMapMaybeDelayError(Function<? super T, ? extends MaybeSource<? extends R>> mapper, boolean tillTheEnd) {
<add> return concatMapMaybeDelayError(mapper, tillTheEnd, 2);
<add> }
<add>
<add> /**
<add> * Maps the upstream items into {@link MaybeSource}s and subscribes to them one after the
<add> * other terminates, emits their success value if available and optionally delaying all errors
<add> * till both this {@code Observable} and all inner {@code MaybeSource}s terminate.
<add> * <p>
<add> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatMap.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code concatMapMaybeDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @param <R> the result type of the inner {@code MaybeSource}s
<add> * @param mapper the function called with the upstream item and should return
<add> * a {@code MaybeSource} to become the next source to
<add> * be subscribed to
<add> * @param tillTheEnd If {@code true}, errors from this {@code Observable} or any of the
<add> * inner {@code MaybeSource}s are delayed until all
<add> * of them terminate. If {@code false}, an error from this
<add> * {@code Observable} is delayed until the current inner
<add> * {@code MaybeSource} terminates and only then is
<add> * it emitted to the downstream.
<add> * @param prefetch The number of upstream items to prefetch so that fresh items are
<add> * ready to be mapped when a previous {@code MaybeSource} terminates.
<add> * The operator replenishes after half of the prefetch amount has been consumed
<add> * and turned into {@code MaybeSource}s.
<add> * @return a new Observable instance
<add> * @since 2.1.11 - experimental
<add> * @see #concatMapMaybe(Function, int)
<add> */
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @Experimental
<add> public final <R> Observable<R> concatMapMaybeDelayError(Function<? super T, ? extends MaybeSource<? extends R>> mapper, boolean tillTheEnd, int prefetch) {
<add> ObjectHelper.requireNonNull(mapper, "mapper is null");
<add> ObjectHelper.verifyPositive(prefetch, "prefetch");
<add> return RxJavaPlugins.onAssembly(new ObservableConcatMapMaybe<T, R>(this, mapper, tillTheEnd ? ErrorMode.END : ErrorMode.BOUNDARY, prefetch));
<add> }
<add>
<add> /**
<add> * Maps the upstream items into {@link SingleSource}s and subscribes to them one after the
<add> * other succeeds, emits their success values or terminates immediately if
<add> * either this {@code Observable} or the current inner {@code SingleSource} fail.
<add> * <p>
<add> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatMap.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code concatMapSingle} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @param <R> the result type of the inner {@code SingleSource}s
<add> * @param mapper the function called with the upstream item and should return
<add> * a {@code SingleSource} to become the next source to
<add> * be subscribed to
<add> * @return a new Observable instance
<add> * @since 2.1.11 - experimental
<add> * @see #concatMapSingleDelayError(Function)
<add> * @see #concatMapSingle(Function, int)
<add> */
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @Experimental
<add> public final <R> Observable<R> concatMapSingle(Function<? super T, ? extends SingleSource<? extends R>> mapper) {
<add> return concatMapSingle(mapper, 2);
<add> }
<add>
<add> /**
<add> * Maps the upstream items into {@link SingleSource}s and subscribes to them one after the
<add> * other succeeds, emits their success values or terminates immediately if
<add> * either this {@code Observable} or the current inner {@code SingleSource} fail.
<add> * <p>
<add> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatMap.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code concatMapSingle} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @param <R> the result type of the inner {@code SingleSource}s
<add> * @param mapper the function called with the upstream item and should return
<add> * a {@code SingleSource} to become the next source to
<add> * be subscribed to
<add> * @param prefetch The number of upstream items to prefetch so that fresh items are
<add> * ready to be mapped when a previous {@code SingleSource} terminates.
<add> * The operator replenishes after half of the prefetch amount has been consumed
<add> * and turned into {@code SingleSource}s.
<add> * @return a new Observable instance
<add> * @since 2.1.11 - experimental
<add> * @see #concatMapSingle(Function)
<add> * @see #concatMapSingleDelayError(Function, boolean, int)
<add> */
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @Experimental
<add> public final <R> Observable<R> concatMapSingle(Function<? super T, ? extends SingleSource<? extends R>> mapper, int prefetch) {
<add> ObjectHelper.requireNonNull(mapper, "mapper is null");
<add> ObjectHelper.verifyPositive(prefetch, "prefetch");
<add> return RxJavaPlugins.onAssembly(new ObservableConcatMapSingle<T, R>(this, mapper, ErrorMode.IMMEDIATE, prefetch));
<add> }
<add>
<add> /**
<add> * Maps the upstream items into {@link SingleSource}s and subscribes to them one after the
<add> * other succeeds or fails, emits their success values and delays all errors
<add> * till both this {@code Observable} and all inner {@code SingleSource}s terminate.
<add> * <p>
<add> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatMap.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code concatMapSingleDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @param <R> the result type of the inner {@code SingleSource}s
<add> * @param mapper the function called with the upstream item and should return
<add> * a {@code SingleSource} to become the next source to
<add> * be subscribed to
<add> * @return a new Observable instance
<add> * @since 2.1.11 - experimental
<add> * @see #concatMapSingle(Function)
<add> * @see #concatMapSingleDelayError(Function, boolean)
<add> */
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @Experimental
<add> public final <R> Observable<R> concatMapSingleDelayError(Function<? super T, ? extends SingleSource<? extends R>> mapper) {
<add> return concatMapSingleDelayError(mapper, true, 2);
<add> }
<add>
<add> /**
<add> * Maps the upstream items into {@link SingleSource}s and subscribes to them one after the
<add> * other succeeds or fails, emits their success values and optionally delays all errors
<add> * till both this {@code Observable} and all inner {@code SingleSource}s terminate.
<add> * <p>
<add> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatMap.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code concatMapSingleDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @param <R> the result type of the inner {@code SingleSource}s
<add> * @param mapper the function called with the upstream item and should return
<add> * a {@code SingleSource} to become the next source to
<add> * be subscribed to
<add> * @param tillTheEnd If {@code true}, errors from this {@code Observable} or any of the
<add> * inner {@code SingleSource}s are delayed until all
<add> * of them terminate. If {@code false}, an error from this
<add> * {@code Observable} is delayed until the current inner
<add> * {@code SingleSource} terminates and only then is
<add> * it emitted to the downstream.
<add> * @return a new Observable instance
<add> * @since 2.1.11 - experimental
<add> * @see #concatMapSingle(Function, int)
<add> * @see #concatMapSingleDelayError(Function, boolean, int)
<add> */
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @Experimental
<add> public final <R> Observable<R> concatMapSingleDelayError(Function<? super T, ? extends SingleSource<? extends R>> mapper, boolean tillTheEnd) {
<add> return concatMapSingleDelayError(mapper, tillTheEnd, 2);
<add> }
<add>
<add> /**
<add> * Maps the upstream items into {@link SingleSource}s and subscribes to them one after the
<add> * other succeeds or fails, emits their success values and optionally delays errors
<add> * till both this {@code Observable} and all inner {@code SingleSource}s terminate.
<add> * <p>
<add> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatMap.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code concatMapSingleDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @param <R> the result type of the inner {@code SingleSource}s
<add> * @param mapper the function called with the upstream item and should return
<add> * a {@code SingleSource} to become the next source to
<add> * be subscribed to
<add> * @param tillTheEnd If {@code true}, errors from this {@code Observable} or any of the
<add> * inner {@code SingleSource}s are delayed until all
<add> * of them terminate. If {@code false}, an error from this
<add> * {@code Observable} is delayed until the current inner
<add> * {@code SingleSource} terminates and only then is
<add> * it emitted to the downstream.
<add> * @param prefetch The number of upstream items to prefetch so that fresh items are
<add> * ready to be mapped when a previous {@code SingleSource} terminates.
<add> * The operator replenishes after half of the prefetch amount has been consumed
<add> * and turned into {@code SingleSource}s.
<add> * @return a new Observable instance
<add> * @since 2.1.11 - experimental
<add> * @see #concatMapSingle(Function, int)
<add> */
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @Experimental
<add> public final <R> Observable<R> concatMapSingleDelayError(Function<? super T, ? extends SingleSource<? extends R>> mapper, boolean tillTheEnd, int prefetch) {
<add> ObjectHelper.requireNonNull(mapper, "mapper is null");
<add> ObjectHelper.verifyPositive(prefetch, "prefetch");
<add> return RxJavaPlugins.onAssembly(new ObservableConcatMapSingle<T, R>(this, mapper, tillTheEnd ? ErrorMode.END : ErrorMode.BOUNDARY, prefetch));
<add> }
<add>
<ide> /**
<ide> * Returns an Observable that emits the items emitted from the current ObservableSource, then the next, one after
<ide> * the other, without interleaving them.
<ide> public final <R> Observable<R> switchMap(Function<? super T, ? extends Observabl
<ide> return RxJavaPlugins.onAssembly(new ObservableSwitchMap<T, R>(this, mapper, bufferSize, false));
<ide> }
<ide>
<add> /**
<add> * Maps the upstream values into {@link CompletableSource}s, subscribes to the newer one while
<add> * disposing the subscription to the previous {@code CompletableSource}, thus keeping at most one
<add> * active {@code CompletableSource} running.
<add> * <p>
<add> * <img width="640" height="521" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/switchMapCompletable.f.png" alt="">
<add> * <p>
<add> * Since a {@code CompletableSource} doesn't produce any items, the resulting reactive type of
<add> * this operator is a {@link Completable} that can only indicate successful completion or
<add> * a failure in any of the inner {@code CompletableSource}s or the failure of the current
<add> * {@link Observable}.
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code switchMapCompletable} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * <dt><b>Error handling:</b></dt>
<add> * <dd>If either this {@code Observable} or the active {@code CompletableSource} signals an {@code onError},
<add> * the resulting {@code Completable} is terminated immediately with that {@code Throwable}.
<add> * Use the {@link #switchMapCompletableDelayError(Function)} to delay such inner failures until
<add> * every inner {@code CompletableSource}s and the main {@code Observable} terminates in some fashion.
<add> * If they fail concurrently, the operator may combine the {@code Throwable}s into a
<add> * {@link io.reactivex.exceptions.CompositeException CompositeException}
<add> * and signal it to the downstream instead. If any inactivated (switched out) {@code CompletableSource}
<add> * signals an {@code onError} late, the {@code Throwable}s will be signalled to the global error handler via
<add> * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors.
<add> * </dd>
<add> * </dl>
<add> * @param mapper the function called with each upstream item and should return a
<add> * {@link CompletableSource} to be subscribed to and awaited for
<add> * (non blockingly) for its terminal event
<add> * @return the new Completable instance
<add> * @since 2.1.11 - experimental
<add> * @see #switchMapCompletableDelayError(Function)
<add> */
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @Experimental
<add> public final Completable switchMapCompletable(@NonNull Function<? super T, ? extends CompletableSource> mapper) {
<add> ObjectHelper.requireNonNull(mapper, "mapper is null");
<add> return RxJavaPlugins.onAssembly(new ObservableSwitchMapCompletable<T>(this, mapper, false));
<add> }
<add>
<add> /**
<add> * Maps the upstream values into {@link CompletableSource}s, subscribes to the newer one while
<add> * disposing the subscription to the previous {@code CompletableSource}, thus keeping at most one
<add> * active {@code CompletableSource} running and delaying any main or inner errors until all
<add> * of them terminate.
<add> * <p>
<add> * <img width="640" height="453" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/switchMapCompletableDelayError.f.png" alt="">
<add> * <p>
<add> * Since a {@code CompletableSource} doesn't produce any items, the resulting reactive type of
<add> * this operator is a {@link Completable} that can only indicate successful completion or
<add> * a failure in any of the inner {@code CompletableSource}s or the failure of the current
<add> * {@link Observable}.
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code switchMapCompletableDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * <dt><b>Error handling:</b></dt>
<add> * <dd>Errors of this {@code Observable} and all the {@code CompletableSource}s, who had the chance
<add> * to run to their completion, are delayed until
<add> * all of them terminate in some fashion. At this point, if there was only one failure, the respective
<add> * {@code Throwable} is emitted to the dowstream. It there were more than one failures, the
<add> * operator combines all {@code Throwable}s into a {@link io.reactivex.exceptions.CompositeException CompositeException}
<add> * and signals that to the downstream.
<add> * If any inactivated (switched out) {@code CompletableSource}
<add> * signals an {@code onError} late, the {@code Throwable}s will be signalled to the global error handler via
<add> * {@link RxJavaPlugins#onError(Throwable)} method as {@code UndeliverableException} errors.
<add> * </dd>
<add> * </dl>
<add> * @param mapper the function called with each upstream item and should return a
<add> * {@link CompletableSource} to be subscribed to and awaited for
<add> * (non blockingly) for its terminal event
<add> * @return the new Completable instance
<add> * @since 2.1.11 - experimental
<add> * @see #switchMapCompletableDelayError(Function)
<add> */
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @Experimental
<add> public final Completable switchMapCompletableDelayError(@NonNull Function<? super T, ? extends CompletableSource> mapper) {
<add> ObjectHelper.requireNonNull(mapper, "mapper is null");
<add> return RxJavaPlugins.onAssembly(new ObservableSwitchMapCompletable<T>(this, mapper, true));
<add> }
<add>
<add> /**
<add> * Maps the upstream items into {@link MaybeSource}s and switches (subscribes) to the newer ones
<add> * while disposing the older ones (and ignoring their signals) and emits the latest success value of the current one if
<add> * available while failing immediately if this {@code Observable} or any of the
<add> * active inner {@code MaybeSource}s fail.
<add> * <p>
<add> * <img width="640" height="350" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/switchMap.o.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code switchMapMaybe} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * <dt><b>Error handling:</b></dt>
<add> * <dd>This operator terminates with an {@code onError} if this {@code Observable} or any of
<add> * the inner {@code MaybeSource}s fail while they are active. When this happens concurrently, their
<add> * individual {@code Throwable} errors may get combined and emitted as a single
<add> * {@link io.reactivex.exceptions.CompositeException CompositeException}. Otherwise, a late
<add> * (i.e., inactive or switched out) {@code onError} from this {@code Observable} or from any of
<add> * the inner {@code MaybeSource}s will be forwarded to the global error handler via
<add> * {@link io.reactivex.plugins.RxJavaPlugins#onError(Throwable)} as
<add> * {@link io.reactivex.exceptions.UndeliverableException UndeliverableException}</dd>
<add> * </dl>
<add> * @param <R> the output value type
<add> * @param mapper the function called with the current upstream event and should
<add> * return a {@code MaybeSource} to replace the current active inner source
<add> * and get subscribed to.
<add> * @return the new Observable instance
<add> * @since 2.1.11 - experimental
<add> * @see #switchMapMaybe(Function)
<add> */
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @Experimental
<add> public final <R> Observable<R> switchMapMaybe(@NonNull Function<? super T, ? extends MaybeSource<? extends R>> mapper) {
<add> ObjectHelper.requireNonNull(mapper, "mapper is null");
<add> return RxJavaPlugins.onAssembly(new ObservableSwitchMapMaybe<T, R>(this, mapper, false));
<add> }
<add>
<add> /**
<add> * Maps the upstream items into {@link MaybeSource}s and switches (subscribes) to the newer ones
<add> * while disposing the older ones (and ignoring their signals) and emits the latest success value of the current one if
<add> * available, delaying errors from this {@code Observable} or the inner {@code MaybeSource}s until all terminate.
<add> * <p>
<add> * <img width="640" height="350" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/switchMap.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code switchMapMaybeDelayError} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @param <R> the output value type
<add> * @param mapper the function called with the current upstream event and should
<add> * return a {@code MaybeSource} to replace the current active inner source
<add> * and get subscribed to.
<add> * @return the new Observable instance
<add> * @since 2.1.11 - experimental
<add> * @see #switchMapMaybe(Function)
<add> */
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @Experimental
<add> public final <R> Observable<R> switchMapMaybeDelayError(@NonNull Function<? super T, ? extends MaybeSource<? extends R>> mapper) {
<add> ObjectHelper.requireNonNull(mapper, "mapper is null");
<add> return RxJavaPlugins.onAssembly(new ObservableSwitchMapMaybe<T, R>(this, mapper, true));
<add> }
<add>
<ide> /**
<ide> * Returns a new ObservableSource by applying a function that you supply to each item emitted by the source
<ide> * ObservableSource that returns a SingleSource, and then emitting the item emitted by the most recently emitted
<ide> public final <R> Observable<R> switchMap(Function<? super T, ? extends Observabl
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> @NonNull
<ide> public final <R> Observable<R> switchMapSingle(@NonNull Function<? super T, ? extends SingleSource<? extends R>> mapper) {
<del> return ObservableInternalHelper.switchMapSingle(this, mapper);
<add> ObjectHelper.requireNonNull(mapper, "mapper is null");
<add> return RxJavaPlugins.onAssembly(new ObservableSwitchMapSingle<T, R>(this, mapper, false));
<ide> }
<ide>
<ide> /**
<ide> public final <R> Observable<R> switchMapSingle(@NonNull Function<? super T, ? ex
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> @NonNull
<ide> public final <R> Observable<R> switchMapSingleDelayError(@NonNull Function<? super T, ? extends SingleSource<? extends R>> mapper) {
<del> return ObservableInternalHelper.switchMapSingleDelayError(this, mapper);
<add> ObjectHelper.requireNonNull(mapper, "mapper is null");
<add> return RxJavaPlugins.onAssembly(new ObservableSwitchMapSingle<T, R>(this, mapper, true));
<ide> }
<ide>
<ide> /**
<ide><path>src/main/java/io/reactivex/internal/operators/mixed/FlowableConcatMapSingle.java
<ide> void drain() {
<ide> consumed = c;
<ide> }
<ide>
<del> SingleSource<? extends R> ms;
<add> SingleSource<? extends R> ss;
<ide>
<ide> try {
<del> ms = ObjectHelper.requireNonNull(mapper.apply(v), "The mapper returned a null SingleSource");
<add> ss = ObjectHelper.requireNonNull(mapper.apply(v), "The mapper returned a null SingleSource");
<ide> } catch (Throwable ex) {
<ide> Exceptions.throwIfFatal(ex);
<ide> upstream.cancel();
<ide> void drain() {
<ide> }
<ide>
<ide> state = STATE_ACTIVE;
<del> ms.subscribe(inner);
<add> ss.subscribe(inner);
<ide> break;
<ide> } else if (s == STATE_RESULT_VALUE) {
<ide> long e = emitted;
<ide><path>src/main/java/io/reactivex/internal/operators/mixed/FlowableSwitchMapSingle.java
<ide> public void onNext(T t) {
<ide> current.dispose();
<ide> }
<ide>
<del> SingleSource<? extends R> ms;
<add> SingleSource<? extends R> ss;
<ide>
<ide> try {
<del> ms = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null SingleSource");
<add> ss = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null SingleSource");
<ide> } catch (Throwable ex) {
<ide> Exceptions.throwIfFatal(ex);
<ide> upstream.cancel();
<ide> public void onNext(T t) {
<ide> break;
<ide> }
<ide> if (inner.compareAndSet(current, observer)) {
<del> ms.subscribe(observer);
<add> ss.subscribe(observer);
<ide> break;
<ide> }
<ide> }
<ide><path>src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletable.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.mixed;
<add>
<add>import java.util.concurrent.atomic.*;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.annotations.Experimental;
<add>import io.reactivex.disposables.Disposable;
<add>import io.reactivex.exceptions.*;
<add>import io.reactivex.functions.Function;
<add>import io.reactivex.internal.disposables.DisposableHelper;
<add>import io.reactivex.internal.functions.ObjectHelper;
<add>import io.reactivex.internal.fuseable.SimplePlainQueue;
<add>import io.reactivex.internal.queue.SpscLinkedArrayQueue;
<add>import io.reactivex.internal.util.*;
<add>import io.reactivex.plugins.RxJavaPlugins;
<add>
<add>/**
<add> * Maps the upstream intems into {@link CompletableSource}s and subscribes to them one after the
<add> * other completes or terminates (in error-delaying mode).
<add> * @param <T> the upstream value type
<add> * @since 2.1.11 - experimental
<add> */
<add>@Experimental
<add>public final class ObservableConcatMapCompletable<T> extends Completable {
<add>
<add> final Observable<T> source;
<add>
<add> final Function<? super T, ? extends CompletableSource> mapper;
<add>
<add> final ErrorMode errorMode;
<add>
<add> final int prefetch;
<add>
<add> public ObservableConcatMapCompletable(Observable<T> source,
<add> Function<? super T, ? extends CompletableSource> mapper,
<add> ErrorMode errorMode,
<add> int prefetch) {
<add> this.source = source;
<add> this.mapper = mapper;
<add> this.errorMode = errorMode;
<add> this.prefetch = prefetch;
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(CompletableObserver s) {
<add> source.subscribe(new ConcatMapCompletableObserver<T>(s, mapper, errorMode, prefetch));
<add> }
<add>
<add> static final class ConcatMapCompletableObserver<T>
<add> extends AtomicInteger
<add> implements Observer<T>, Disposable {
<add>
<add> private static final long serialVersionUID = 3610901111000061034L;
<add>
<add> final CompletableObserver downstream;
<add>
<add> final Function<? super T, ? extends CompletableSource> mapper;
<add>
<add> final ErrorMode errorMode;
<add>
<add> final AtomicThrowable errors;
<add>
<add> final ConcatMapInnerObserver inner;
<add>
<add> final int prefetch;
<add>
<add> final SimplePlainQueue<T> queue;
<add>
<add> Disposable upstream;
<add>
<add> volatile boolean active;
<add>
<add> volatile boolean done;
<add>
<add> volatile boolean disposed;
<add>
<add> ConcatMapCompletableObserver(CompletableObserver downstream,
<add> Function<? super T, ? extends CompletableSource> mapper,
<add> ErrorMode errorMode, int prefetch) {
<add> this.downstream = downstream;
<add> this.mapper = mapper;
<add> this.errorMode = errorMode;
<add> this.prefetch = prefetch;
<add> this.errors = new AtomicThrowable();
<add> this.inner = new ConcatMapInnerObserver(this);
<add> this.queue = new SpscLinkedArrayQueue<T>(prefetch);
<add> }
<add>
<add> @Override
<add> public void onSubscribe(Disposable s) {
<add> if (DisposableHelper.validate(upstream, s)) {
<add> this.upstream = s;
<add> downstream.onSubscribe(this);
<add> }
<add> }
<add>
<add> @Override
<add> public void onNext(T t) {
<add> queue.offer(t);
<add> drain();
<add> }
<add>
<add> @Override
<add> public void onError(Throwable t) {
<add> if (errors.addThrowable(t)) {
<add> if (errorMode == ErrorMode.IMMEDIATE) {
<add> disposed = true;
<add> inner.dispose();
<add> t = errors.terminate();
<add> if (t != ExceptionHelper.TERMINATED) {
<add> downstream.onError(t);
<add> }
<add> if (getAndIncrement() == 0) {
<add> queue.clear();
<add> }
<add> } else {
<add> done = true;
<add> drain();
<add> }
<add> } else {
<add> RxJavaPlugins.onError(t);
<add> }
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> done = true;
<add> drain();
<add> }
<add>
<add> @Override
<add> public void dispose() {
<add> disposed = true;
<add> upstream.dispose();
<add> inner.dispose();
<add> if (getAndIncrement() == 0) {
<add> queue.clear();
<add> }
<add> }
<add>
<add> @Override
<add> public boolean isDisposed() {
<add> return disposed;
<add> }
<add>
<add> void innerError(Throwable ex) {
<add> if (errors.addThrowable(ex)) {
<add> if (errorMode == ErrorMode.IMMEDIATE) {
<add> disposed = true;
<add> upstream.dispose();
<add> ex = errors.terminate();
<add> if (ex != ExceptionHelper.TERMINATED) {
<add> downstream.onError(ex);
<add> }
<add> if (getAndIncrement() == 0) {
<add> queue.clear();
<add> }
<add> } else {
<add> active = false;
<add> drain();
<add> }
<add> } else {
<add> RxJavaPlugins.onError(ex);
<add> }
<add> }
<add>
<add> void innerComplete() {
<add> active = false;
<add> drain();
<add> }
<add>
<add> void drain() {
<add> if (getAndIncrement() != 0) {
<add> return;
<add> }
<add>
<add> do {
<add> if (disposed) {
<add> queue.clear();
<add> return;
<add> }
<add>
<add> if (!active) {
<add>
<add> if (errorMode == ErrorMode.BOUNDARY) {
<add> if (errors.get() != null) {
<add> disposed = true;
<add> queue.clear();
<add> Throwable ex = errors.terminate();
<add> downstream.onError(ex);
<add> return;
<add> }
<add> }
<add>
<add> boolean d = done;
<add> T v = queue.poll();
<add> boolean empty = v == null;
<add>
<add> if (d && empty) {
<add> disposed = true;
<add> Throwable ex = errors.terminate();
<add> if (ex != null) {
<add> downstream.onError(ex);
<add> } else {
<add> downstream.onComplete();
<add> }
<add> return;
<add> }
<add>
<add> if (!empty) {
<add>
<add> CompletableSource cs;
<add>
<add> try {
<add> cs = ObjectHelper.requireNonNull(mapper.apply(v), "The mapper returned a null CompletableSource");
<add> } catch (Throwable ex) {
<add> Exceptions.throwIfFatal(ex);
<add> disposed = true;
<add> queue.clear();
<add> upstream.dispose();
<add> errors.addThrowable(ex);
<add> ex = errors.terminate();
<add> downstream.onError(ex);
<add> return;
<add> }
<add> active = true;
<add> cs.subscribe(inner);
<add> }
<add> }
<add> } while (decrementAndGet() != 0);
<add> }
<add>
<add> static final class ConcatMapInnerObserver extends AtomicReference<Disposable>
<add> implements CompletableObserver {
<add>
<add> private static final long serialVersionUID = 5638352172918776687L;
<add>
<add> final ConcatMapCompletableObserver<?> parent;
<add>
<add> ConcatMapInnerObserver(ConcatMapCompletableObserver<?> parent) {
<add> this.parent = parent;
<add> }
<add>
<add> @Override
<add> public void onSubscribe(Disposable d) {
<add> DisposableHelper.replace(this, d);
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> parent.innerError(e);
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> parent.innerComplete();
<add> }
<add>
<add> void dispose() {
<add> DisposableHelper.dispose(this);
<add> }
<add> }
<add> }
<add>}
<ide><path>src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybe.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.mixed;
<add>
<add>import java.util.concurrent.atomic.*;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.annotations.Experimental;
<add>import io.reactivex.disposables.Disposable;
<add>import io.reactivex.exceptions.Exceptions;
<add>import io.reactivex.functions.Function;
<add>import io.reactivex.internal.disposables.DisposableHelper;
<add>import io.reactivex.internal.functions.ObjectHelper;
<add>import io.reactivex.internal.fuseable.SimplePlainQueue;
<add>import io.reactivex.internal.queue.SpscLinkedArrayQueue;
<add>import io.reactivex.internal.util.*;
<add>import io.reactivex.plugins.RxJavaPlugins;
<add>
<add>/**
<add> * Maps each upstream item into a {@link MaybeSource}, subscribes to them one after the other terminates
<add> * and relays their success values, optionally delaying any errors till the main and inner sources
<add> * terminate.
<add> *
<add> * @param <T> the upstream element type
<add> * @param <R> the output element type
<add> *
<add> * @since 2.1.11 - experimental
<add> */
<add>@Experimental
<add>public final class ObservableConcatMapMaybe<T, R> extends Observable<R> {
<add>
<add> final Observable<T> source;
<add>
<add> final Function<? super T, ? extends MaybeSource<? extends R>> mapper;
<add>
<add> final ErrorMode errorMode;
<add>
<add> final int prefetch;
<add>
<add> public ObservableConcatMapMaybe(Observable<T> source,
<add> Function<? super T, ? extends MaybeSource<? extends R>> mapper,
<add> ErrorMode errorMode, int prefetch) {
<add> this.source = source;
<add> this.mapper = mapper;
<add> this.errorMode = errorMode;
<add> this.prefetch = prefetch;
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(Observer<? super R> s) {
<add> source.subscribe(new ConcatMapMaybeMainObserver<T, R>(s, mapper, prefetch, errorMode));
<add> }
<add>
<add> static final class ConcatMapMaybeMainObserver<T, R>
<add> extends AtomicInteger
<add> implements Observer<T>, Disposable {
<add>
<add> private static final long serialVersionUID = -9140123220065488293L;
<add>
<add> final Observer<? super R> downstream;
<add>
<add> final Function<? super T, ? extends MaybeSource<? extends R>> mapper;
<add>
<add> final AtomicThrowable errors;
<add>
<add> final ConcatMapMaybeObserver<R> inner;
<add>
<add> final SimplePlainQueue<T> queue;
<add>
<add> final ErrorMode errorMode;
<add>
<add> Disposable upstream;
<add>
<add> volatile boolean done;
<add>
<add> volatile boolean cancelled;
<add>
<add> R item;
<add>
<add> volatile int state;
<add>
<add> /** No inner MaybeSource is running. */
<add> static final int STATE_INACTIVE = 0;
<add> /** An inner MaybeSource is running but there are no results yet. */
<add> static final int STATE_ACTIVE = 1;
<add> /** The inner MaybeSource succeeded with a value in {@link #item}. */
<add> static final int STATE_RESULT_VALUE = 2;
<add>
<add> ConcatMapMaybeMainObserver(Observer<? super R> downstream,
<add> Function<? super T, ? extends MaybeSource<? extends R>> mapper,
<add> int prefetch, ErrorMode errorMode) {
<add> this.downstream = downstream;
<add> this.mapper = mapper;
<add> this.errorMode = errorMode;
<add> this.errors = new AtomicThrowable();
<add> this.inner = new ConcatMapMaybeObserver<R>(this);
<add> this.queue = new SpscLinkedArrayQueue<T>(prefetch);
<add> }
<add>
<add> @Override
<add> public void onSubscribe(Disposable s) {
<add> if (DisposableHelper.validate(upstream, s)) {
<add> upstream = s;
<add> downstream.onSubscribe(this);
<add> }
<add> }
<add>
<add> @Override
<add> public void onNext(T t) {
<add> queue.offer(t);
<add> drain();
<add> }
<add>
<add> @Override
<add> public void onError(Throwable t) {
<add> if (errors.addThrowable(t)) {
<add> if (errorMode == ErrorMode.IMMEDIATE) {
<add> inner.dispose();
<add> }
<add> done = true;
<add> drain();
<add> } else {
<add> RxJavaPlugins.onError(t);
<add> }
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> done = true;
<add> drain();
<add> }
<add>
<add> @Override
<add> public void dispose() {
<add> cancelled = true;
<add> upstream.dispose();
<add> inner.dispose();
<add> if (getAndIncrement() != 0) {
<add> queue.clear();
<add> item = null;
<add> }
<add> }
<add>
<add> @Override
<add> public boolean isDisposed() {
<add> return cancelled;
<add> }
<add>
<add> void innerSuccess(R item) {
<add> this.item = item;
<add> this.state = STATE_RESULT_VALUE;
<add> drain();
<add> }
<add>
<add> void innerComplete() {
<add> this.state = STATE_INACTIVE;
<add> drain();
<add> }
<add>
<add> void innerError(Throwable ex) {
<add> if (errors.addThrowable(ex)) {
<add> if (errorMode != ErrorMode.END) {
<add> upstream.dispose();
<add> }
<add> this.state = STATE_INACTIVE;
<add> drain();
<add> } else {
<add> RxJavaPlugins.onError(ex);
<add> }
<add> }
<add>
<add> void drain() {
<add> if (getAndIncrement() != 0) {
<add> return;
<add> }
<add>
<add> int missed = 1;
<add> Observer<? super R> downstream = this.downstream;
<add> ErrorMode errorMode = this.errorMode;
<add> SimplePlainQueue<T> queue = this.queue;
<add> AtomicThrowable errors = this.errors;
<add>
<add> for (;;) {
<add>
<add> for (;;) {
<add> if (cancelled) {
<add> queue.clear();
<add> item = null;
<add> }
<add>
<add> int s = state;
<add>
<add> if (errors.get() != null) {
<add> if (errorMode == ErrorMode.IMMEDIATE
<add> || (errorMode == ErrorMode.BOUNDARY && s == STATE_INACTIVE)) {
<add> queue.clear();
<add> item = null;
<add> Throwable ex = errors.terminate();
<add> downstream.onError(ex);
<add> return;
<add> }
<add> }
<add>
<add> if (s == STATE_INACTIVE) {
<add> boolean d = done;
<add> T v = queue.poll();
<add> boolean empty = v == null;
<add>
<add> if (d && empty) {
<add> Throwable ex = errors.terminate();
<add> if (ex == null) {
<add> downstream.onComplete();
<add> } else {
<add> downstream.onError(ex);
<add> }
<add> return;
<add> }
<add>
<add> if (empty) {
<add> break;
<add> }
<add>
<add> MaybeSource<? extends R> ms;
<add>
<add> try {
<add> ms = ObjectHelper.requireNonNull(mapper.apply(v), "The mapper returned a null MaybeSource");
<add> } catch (Throwable ex) {
<add> Exceptions.throwIfFatal(ex);
<add> upstream.dispose();
<add> queue.clear();
<add> errors.addThrowable(ex);
<add> ex = errors.terminate();
<add> downstream.onError(ex);
<add> return;
<add> }
<add>
<add> state = STATE_ACTIVE;
<add> ms.subscribe(inner);
<add> break;
<add> } else if (s == STATE_RESULT_VALUE) {
<add> R w = item;
<add> item = null;
<add> downstream.onNext(w);
<add>
<add> state = STATE_INACTIVE;
<add> } else {
<add> break;
<add> }
<add> }
<add>
<add> missed = addAndGet(-missed);
<add> if (missed == 0) {
<add> break;
<add> }
<add> }
<add> }
<add>
<add> static final class ConcatMapMaybeObserver<R>
<add> extends AtomicReference<Disposable>
<add> implements MaybeObserver<R> {
<add>
<add> private static final long serialVersionUID = -3051469169682093892L;
<add>
<add> final ConcatMapMaybeMainObserver<?, R> parent;
<add>
<add> ConcatMapMaybeObserver(ConcatMapMaybeMainObserver<?, R> parent) {
<add> this.parent = parent;
<add> }
<add>
<add> @Override
<add> public void onSubscribe(Disposable d) {
<add> DisposableHelper.replace(this, d);
<add> }
<add>
<add> @Override
<add> public void onSuccess(R t) {
<add> parent.innerSuccess(t);
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> parent.innerError(e);
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> parent.innerComplete();
<add> }
<add>
<add> void dispose() {
<add> DisposableHelper.dispose(this);
<add> }
<add> }
<add> }
<add>}
<ide><path>src/main/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingle.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.mixed;
<add>
<add>import java.util.concurrent.atomic.*;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.annotations.Experimental;
<add>import io.reactivex.disposables.Disposable;
<add>import io.reactivex.exceptions.*;
<add>import io.reactivex.functions.Function;
<add>import io.reactivex.internal.disposables.DisposableHelper;
<add>import io.reactivex.internal.functions.ObjectHelper;
<add>import io.reactivex.internal.fuseable.SimplePlainQueue;
<add>import io.reactivex.internal.queue.SpscArrayQueue;
<add>import io.reactivex.internal.util.*;
<add>import io.reactivex.plugins.RxJavaPlugins;
<add>
<add>/**
<add> * Maps each upstream item into a {@link SingleSource}, subscribes to them one after the other terminates
<add> * and relays their success values, optionally delaying any errors till the main and inner sources
<add> * terminate.
<add> *
<add> * @param <T> the upstream element type
<add> * @param <R> the output element type
<add> *
<add> * @since 2.1.11 - experimental
<add> */
<add>@Experimental
<add>public final class ObservableConcatMapSingle<T, R> extends Observable<R> {
<add>
<add> final Observable<T> source;
<add>
<add> final Function<? super T, ? extends SingleSource<? extends R>> mapper;
<add>
<add> final ErrorMode errorMode;
<add>
<add> final int prefetch;
<add>
<add> public ObservableConcatMapSingle(Observable<T> source,
<add> Function<? super T, ? extends SingleSource<? extends R>> mapper,
<add> ErrorMode errorMode, int prefetch) {
<add> this.source = source;
<add> this.mapper = mapper;
<add> this.errorMode = errorMode;
<add> this.prefetch = prefetch;
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(Observer<? super R> s) {
<add> source.subscribe(new ConcatMapSingleMainObserver<T, R>(s, mapper, prefetch, errorMode));
<add> }
<add>
<add> static final class ConcatMapSingleMainObserver<T, R>
<add> extends AtomicInteger
<add> implements Observer<T>, Disposable {
<add>
<add> private static final long serialVersionUID = -9140123220065488293L;
<add>
<add> final Observer<? super R> downstream;
<add>
<add> final Function<? super T, ? extends SingleSource<? extends R>> mapper;
<add>
<add> final AtomicThrowable errors;
<add>
<add> final ConcatMapSingleObserver<R> inner;
<add>
<add> final SimplePlainQueue<T> queue;
<add>
<add> final ErrorMode errorMode;
<add>
<add> Disposable upstream;
<add>
<add> volatile boolean done;
<add>
<add> volatile boolean cancelled;
<add>
<add> R item;
<add>
<add> volatile int state;
<add>
<add> /** No inner SingleSource is running. */
<add> static final int STATE_INACTIVE = 0;
<add> /** An inner SingleSource is running but there are no results yet. */
<add> static final int STATE_ACTIVE = 1;
<add> /** The inner SingleSource succeeded with a value in {@link #item}. */
<add> static final int STATE_RESULT_VALUE = 2;
<add>
<add> ConcatMapSingleMainObserver(Observer<? super R> downstream,
<add> Function<? super T, ? extends SingleSource<? extends R>> mapper,
<add> int prefetch, ErrorMode errorMode) {
<add> this.downstream = downstream;
<add> this.mapper = mapper;
<add> this.errorMode = errorMode;
<add> this.errors = new AtomicThrowable();
<add> this.inner = new ConcatMapSingleObserver<R>(this);
<add> this.queue = new SpscArrayQueue<T>(prefetch);
<add> }
<add>
<add> @Override
<add> public void onSubscribe(Disposable s) {
<add> if (DisposableHelper.validate(upstream, s)) {
<add> upstream = s;
<add> downstream.onSubscribe(this);
<add> }
<add> }
<add>
<add> @Override
<add> public void onNext(T t) {
<add> queue.offer(t);
<add> drain();
<add> }
<add>
<add> @Override
<add> public void onError(Throwable t) {
<add> if (errors.addThrowable(t)) {
<add> if (errorMode == ErrorMode.IMMEDIATE) {
<add> inner.dispose();
<add> }
<add> done = true;
<add> drain();
<add> } else {
<add> RxJavaPlugins.onError(t);
<add> }
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> done = true;
<add> drain();
<add> }
<add>
<add> @Override
<add> public void dispose() {
<add> cancelled = true;
<add> upstream.dispose();
<add> inner.dispose();
<add> if (getAndIncrement() != 0) {
<add> queue.clear();
<add> item = null;
<add> }
<add> }
<add>
<add> @Override
<add> public boolean isDisposed() {
<add> return cancelled;
<add> }
<add>
<add> void innerSuccess(R item) {
<add> this.item = item;
<add> this.state = STATE_RESULT_VALUE;
<add> drain();
<add> }
<add>
<add> void innerError(Throwable ex) {
<add> if (errors.addThrowable(ex)) {
<add> if (errorMode != ErrorMode.END) {
<add> upstream.dispose();
<add> }
<add> this.state = STATE_INACTIVE;
<add> drain();
<add> } else {
<add> RxJavaPlugins.onError(ex);
<add> }
<add> }
<add>
<add> void drain() {
<add> if (getAndIncrement() != 0) {
<add> return;
<add> }
<add>
<add> int missed = 1;
<add> Observer<? super R> downstream = this.downstream;
<add> ErrorMode errorMode = this.errorMode;
<add> SimplePlainQueue<T> queue = this.queue;
<add> AtomicThrowable errors = this.errors;
<add>
<add> for (;;) {
<add>
<add> for (;;) {
<add> if (cancelled) {
<add> queue.clear();
<add> item = null;
<add> }
<add>
<add> int s = state;
<add>
<add> if (errors.get() != null) {
<add> if (errorMode == ErrorMode.IMMEDIATE
<add> || (errorMode == ErrorMode.BOUNDARY && s == STATE_INACTIVE)) {
<add> queue.clear();
<add> item = null;
<add> Throwable ex = errors.terminate();
<add> downstream.onError(ex);
<add> return;
<add> }
<add> }
<add>
<add> if (s == STATE_INACTIVE) {
<add> boolean d = done;
<add> T v = queue.poll();
<add> boolean empty = v == null;
<add>
<add> if (d && empty) {
<add> Throwable ex = errors.terminate();
<add> if (ex == null) {
<add> downstream.onComplete();
<add> } else {
<add> downstream.onError(ex);
<add> }
<add> return;
<add> }
<add>
<add> if (empty) {
<add> break;
<add> }
<add>
<add> SingleSource<? extends R> ss;
<add>
<add> try {
<add> ss = ObjectHelper.requireNonNull(mapper.apply(v), "The mapper returned a null SingleSource");
<add> } catch (Throwable ex) {
<add> Exceptions.throwIfFatal(ex);
<add> upstream.dispose();
<add> queue.clear();
<add> errors.addThrowable(ex);
<add> ex = errors.terminate();
<add> downstream.onError(ex);
<add> return;
<add> }
<add>
<add> state = STATE_ACTIVE;
<add> ss.subscribe(inner);
<add> break;
<add> } else if (s == STATE_RESULT_VALUE) {
<add> R w = item;
<add> item = null;
<add> downstream.onNext(w);
<add>
<add> state = STATE_INACTIVE;
<add> } else {
<add> break;
<add> }
<add> }
<add>
<add> missed = addAndGet(-missed);
<add> if (missed == 0) {
<add> break;
<add> }
<add> }
<add> }
<add>
<add> static final class ConcatMapSingleObserver<R>
<add> extends AtomicReference<Disposable>
<add> implements SingleObserver<R> {
<add>
<add> private static final long serialVersionUID = -3051469169682093892L;
<add>
<add> final ConcatMapSingleMainObserver<?, R> parent;
<add>
<add> ConcatMapSingleObserver(ConcatMapSingleMainObserver<?, R> parent) {
<add> this.parent = parent;
<add> }
<add>
<add> @Override
<add> public void onSubscribe(Disposable d) {
<add> DisposableHelper.replace(this, d);
<add> }
<add>
<add> @Override
<add> public void onSuccess(R t) {
<add> parent.innerSuccess(t);
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> parent.innerError(e);
<add> }
<add>
<add> void dispose() {
<add> DisposableHelper.dispose(this);
<add> }
<add> }
<add> }
<add>}
<ide><path>src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletable.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.mixed;
<add>
<add>import java.util.concurrent.atomic.AtomicReference;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.annotations.Experimental;
<add>import io.reactivex.disposables.Disposable;
<add>import io.reactivex.exceptions.Exceptions;
<add>import io.reactivex.functions.Function;
<add>import io.reactivex.internal.disposables.DisposableHelper;
<add>import io.reactivex.internal.functions.ObjectHelper;
<add>import io.reactivex.internal.util.*;
<add>import io.reactivex.plugins.RxJavaPlugins;
<add>
<add>/**
<add> * Maps the upstream values into {@link CompletableSource}s, subscribes to the newer one while
<add> * disposing the subscription to the previous {@code CompletableSource}, thus keeping at most one
<add> * active {@code CompletableSource} running.
<add> *
<add> * @param <T> the upstream value type
<add> * @since 2.1.11 - experimental
<add> */
<add>@Experimental
<add>public final class ObservableSwitchMapCompletable<T> extends Completable {
<add>
<add> final Observable<T> source;
<add>
<add> final Function<? super T, ? extends CompletableSource> mapper;
<add>
<add> final boolean delayErrors;
<add>
<add> public ObservableSwitchMapCompletable(Observable<T> source,
<add> Function<? super T, ? extends CompletableSource> mapper, boolean delayErrors) {
<add> this.source = source;
<add> this.mapper = mapper;
<add> this.delayErrors = delayErrors;
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(CompletableObserver s) {
<add> source.subscribe(new SwitchMapCompletableObserver<T>(s, mapper, delayErrors));
<add> }
<add>
<add> static final class SwitchMapCompletableObserver<T> implements Observer<T>, Disposable {
<add>
<add> final CompletableObserver downstream;
<add>
<add> final Function<? super T, ? extends CompletableSource> mapper;
<add>
<add> final boolean delayErrors;
<add>
<add> final AtomicThrowable errors;
<add>
<add> final AtomicReference<SwitchMapInnerObserver> inner;
<add>
<add> static final SwitchMapInnerObserver INNER_DISPOSED = new SwitchMapInnerObserver(null);
<add>
<add> volatile boolean done;
<add>
<add> Disposable upstream;
<add>
<add> SwitchMapCompletableObserver(CompletableObserver downstream,
<add> Function<? super T, ? extends CompletableSource> mapper, boolean delayErrors) {
<add> this.downstream = downstream;
<add> this.mapper = mapper;
<add> this.delayErrors = delayErrors;
<add> this.errors = new AtomicThrowable();
<add> this.inner = new AtomicReference<SwitchMapInnerObserver>();
<add> }
<add>
<add> @Override
<add> public void onSubscribe(Disposable s) {
<add> if (DisposableHelper.validate(upstream, s)) {
<add> this.upstream = s;
<add> downstream.onSubscribe(this);
<add> }
<add> }
<add>
<add> @Override
<add> public void onNext(T t) {
<add> CompletableSource c;
<add>
<add> try {
<add> c = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null CompletableSource");
<add> } catch (Throwable ex) {
<add> Exceptions.throwIfFatal(ex);
<add> upstream.dispose();
<add> onError(ex);
<add> return;
<add> }
<add>
<add> SwitchMapInnerObserver o = new SwitchMapInnerObserver(this);
<add>
<add> for (;;) {
<add> SwitchMapInnerObserver current = inner.get();
<add> if (current == INNER_DISPOSED) {
<add> break;
<add> }
<add> if (inner.compareAndSet(current, o)) {
<add> if (current != null) {
<add> current.dispose();
<add> }
<add> c.subscribe(o);
<add> break;
<add> }
<add> }
<add> }
<add>
<add> @Override
<add> public void onError(Throwable t) {
<add> if (errors.addThrowable(t)) {
<add> if (delayErrors) {
<add> onComplete();
<add> } else {
<add> disposeInner();
<add> Throwable ex = errors.terminate();
<add> if (ex != ExceptionHelper.TERMINATED) {
<add> downstream.onError(ex);
<add> }
<add> }
<add> } else {
<add> RxJavaPlugins.onError(t);
<add> }
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> done = true;
<add> if (inner.get() == null) {
<add> Throwable ex = errors.terminate();
<add> if (ex == null) {
<add> downstream.onComplete();
<add> } else {
<add> downstream.onError(ex);
<add> }
<add> }
<add> }
<add>
<add> void disposeInner() {
<add> SwitchMapInnerObserver o = inner.getAndSet(INNER_DISPOSED);
<add> if (o != null && o != INNER_DISPOSED) {
<add> o.dispose();
<add> }
<add> }
<add>
<add> @Override
<add> public void dispose() {
<add> upstream.dispose();
<add> disposeInner();
<add> }
<add>
<add> @Override
<add> public boolean isDisposed() {
<add> return inner.get() == INNER_DISPOSED;
<add> }
<add>
<add> void innerError(SwitchMapInnerObserver sender, Throwable error) {
<add> if (inner.compareAndSet(sender, null)) {
<add> if (errors.addThrowable(error)) {
<add> if (delayErrors) {
<add> if (done) {
<add> Throwable ex = errors.terminate();
<add> downstream.onError(ex);
<add> }
<add> } else {
<add> dispose();
<add> Throwable ex = errors.terminate();
<add> if (ex != ExceptionHelper.TERMINATED) {
<add> downstream.onError(ex);
<add> }
<add> }
<add> return;
<add> }
<add> }
<add> RxJavaPlugins.onError(error);
<add> }
<add>
<add> void innerComplete(SwitchMapInnerObserver sender) {
<add> if (inner.compareAndSet(sender, null)) {
<add> if (done) {
<add> Throwable ex = errors.terminate();
<add> if (ex == null) {
<add> downstream.onComplete();
<add> } else {
<add> downstream.onError(ex);
<add> }
<add> }
<add> }
<add> }
<add>
<add> static final class SwitchMapInnerObserver extends AtomicReference<Disposable>
<add> implements CompletableObserver {
<add>
<add> private static final long serialVersionUID = -8003404460084760287L;
<add>
<add> final SwitchMapCompletableObserver<?> parent;
<add>
<add> SwitchMapInnerObserver(SwitchMapCompletableObserver<?> parent) {
<add> this.parent = parent;
<add> }
<add>
<add> @Override
<add> public void onSubscribe(Disposable d) {
<add> DisposableHelper.setOnce(this, d);
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> parent.innerError(this, e);
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> parent.innerComplete(this);
<add> }
<add>
<add> void dispose() {
<add> DisposableHelper.dispose(this);
<add> }
<add> }
<add> }
<add>}
<ide><path>src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybe.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.mixed;
<add>
<add>import java.util.concurrent.atomic.*;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.annotations.Experimental;
<add>import io.reactivex.disposables.Disposable;
<add>import io.reactivex.exceptions.Exceptions;
<add>import io.reactivex.functions.Function;
<add>import io.reactivex.internal.disposables.DisposableHelper;
<add>import io.reactivex.internal.functions.ObjectHelper;
<add>import io.reactivex.internal.util.AtomicThrowable;
<add>import io.reactivex.plugins.RxJavaPlugins;
<add>
<add>/**
<add> * Maps the upstream items into {@link MaybeSource}s and switches (subscribes) to the newer ones
<add> * while disposing the older ones and emits the latest success value if available, optionally delaying
<add> * errors from the main source or the inner sources.
<add> *
<add> * @param <T> the upstream value type
<add> * @param <R> the downstream value type
<add> * @since 2.1.11 - experimental
<add> */
<add>@Experimental
<add>public final class ObservableSwitchMapMaybe<T, R> extends Observable<R> {
<add>
<add> final Observable<T> source;
<add>
<add> final Function<? super T, ? extends MaybeSource<? extends R>> mapper;
<add>
<add> final boolean delayErrors;
<add>
<add> public ObservableSwitchMapMaybe(Observable<T> source,
<add> Function<? super T, ? extends MaybeSource<? extends R>> mapper,
<add> boolean delayErrors) {
<add> this.source = source;
<add> this.mapper = mapper;
<add> this.delayErrors = delayErrors;
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(Observer<? super R> s) {
<add> source.subscribe(new SwitchMapMaybeMainObserver<T, R>(s, mapper, delayErrors));
<add> }
<add>
<add> static final class SwitchMapMaybeMainObserver<T, R> extends AtomicInteger
<add> implements Observer<T>, Disposable {
<add>
<add> private static final long serialVersionUID = -5402190102429853762L;
<add>
<add> final Observer<? super R> downstream;
<add>
<add> final Function<? super T, ? extends MaybeSource<? extends R>> mapper;
<add>
<add> final boolean delayErrors;
<add>
<add> final AtomicThrowable errors;
<add>
<add> final AtomicReference<SwitchMapMaybeObserver<R>> inner;
<add>
<add> static final SwitchMapMaybeObserver<Object> INNER_DISPOSED =
<add> new SwitchMapMaybeObserver<Object>(null);
<add>
<add> Disposable upstream;
<add>
<add> volatile boolean done;
<add>
<add> volatile boolean cancelled;
<add>
<add> SwitchMapMaybeMainObserver(Observer<? super R> downstream,
<add> Function<? super T, ? extends MaybeSource<? extends R>> mapper,
<add> boolean delayErrors) {
<add> this.downstream = downstream;
<add> this.mapper = mapper;
<add> this.delayErrors = delayErrors;
<add> this.errors = new AtomicThrowable();
<add> this.inner = new AtomicReference<SwitchMapMaybeObserver<R>>();
<add> }
<add>
<add> @Override
<add> public void onSubscribe(Disposable s) {
<add> if (DisposableHelper.validate(upstream, s)) {
<add> upstream = s;
<add> downstream.onSubscribe(this);
<add> }
<add> }
<add>
<add> @Override
<add> @SuppressWarnings({ "unchecked", "rawtypes" })
<add> public void onNext(T t) {
<add> SwitchMapMaybeObserver<R> current = inner.get();
<add> if (current != null) {
<add> current.dispose();
<add> }
<add>
<add> MaybeSource<? extends R> ms;
<add>
<add> try {
<add> ms = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null MaybeSource");
<add> } catch (Throwable ex) {
<add> Exceptions.throwIfFatal(ex);
<add> upstream.dispose();
<add> inner.getAndSet((SwitchMapMaybeObserver)INNER_DISPOSED);
<add> onError(ex);
<add> return;
<add> }
<add>
<add> SwitchMapMaybeObserver<R> observer = new SwitchMapMaybeObserver<R>(this);
<add>
<add> for (;;) {
<add> current = inner.get();
<add> if (current == INNER_DISPOSED) {
<add> break;
<add> }
<add> if (inner.compareAndSet(current, observer)) {
<add> ms.subscribe(observer);
<add> break;
<add> }
<add> }
<add> }
<add>
<add> @Override
<add> public void onError(Throwable t) {
<add> if (errors.addThrowable(t)) {
<add> if (!delayErrors) {
<add> disposeInner();
<add> }
<add> done = true;
<add> drain();
<add> } else {
<add> RxJavaPlugins.onError(t);
<add> }
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> done = true;
<add> drain();
<add> }
<add>
<add> @SuppressWarnings({ "unchecked", "rawtypes" })
<add> void disposeInner() {
<add> SwitchMapMaybeObserver<R> current = inner.getAndSet((SwitchMapMaybeObserver)INNER_DISPOSED);
<add> if (current != null && current != INNER_DISPOSED) {
<add> current.dispose();
<add> }
<add> }
<add>
<add> @Override
<add> public void dispose() {
<add> cancelled = true;
<add> upstream.dispose();
<add> disposeInner();
<add> }
<add>
<add> @Override
<add> public boolean isDisposed() {
<add> return cancelled;
<add> }
<add>
<add> void innerError(SwitchMapMaybeObserver<R> sender, Throwable ex) {
<add> if (inner.compareAndSet(sender, null)) {
<add> if (errors.addThrowable(ex)) {
<add> if (!delayErrors) {
<add> upstream.dispose();
<add> disposeInner();
<add> }
<add> drain();
<add> return;
<add> }
<add> }
<add> RxJavaPlugins.onError(ex);
<add> }
<add>
<add> void innerComplete(SwitchMapMaybeObserver<R> sender) {
<add> if (inner.compareAndSet(sender, null)) {
<add> drain();
<add> }
<add> }
<add>
<add> void drain() {
<add> if (getAndIncrement() != 0) {
<add> return;
<add> }
<add>
<add> int missed = 1;
<add> Observer<? super R> downstream = this.downstream;
<add> AtomicThrowable errors = this.errors;
<add> AtomicReference<SwitchMapMaybeObserver<R>> inner = this.inner;
<add>
<add> for (;;) {
<add>
<add> for (;;) {
<add> if (cancelled) {
<add> return;
<add> }
<add>
<add> if (errors.get() != null) {
<add> if (!delayErrors) {
<add> Throwable ex = errors.terminate();
<add> downstream.onError(ex);
<add> return;
<add> }
<add> }
<add>
<add> boolean d = done;
<add> SwitchMapMaybeObserver<R> current = inner.get();
<add> boolean empty = current == null;
<add>
<add> if (d && empty) {
<add> Throwable ex = errors.terminate();
<add> if (ex != null) {
<add> downstream.onError(ex);
<add> } else {
<add> downstream.onComplete();
<add> }
<add> return;
<add> }
<add>
<add> if (empty || current.item == null) {
<add> break;
<add> }
<add>
<add> inner.compareAndSet(current, null);
<add>
<add> downstream.onNext(current.item);
<add> }
<add>
<add> missed = addAndGet(-missed);
<add> if (missed == 0) {
<add> break;
<add> }
<add> }
<add> }
<add>
<add> static final class SwitchMapMaybeObserver<R>
<add> extends AtomicReference<Disposable> implements MaybeObserver<R> {
<add>
<add> private static final long serialVersionUID = 8042919737683345351L;
<add>
<add> final SwitchMapMaybeMainObserver<?, R> parent;
<add>
<add> volatile R item;
<add>
<add> SwitchMapMaybeObserver(SwitchMapMaybeMainObserver<?, R> parent) {
<add> this.parent = parent;
<add> }
<add>
<add> @Override
<add> public void onSubscribe(Disposable d) {
<add> DisposableHelper.setOnce(this, d);
<add> }
<add>
<add> @Override
<add> public void onSuccess(R t) {
<add> item = t;
<add> parent.drain();
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> parent.innerError(this, e);
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> parent.innerComplete(this);
<add> }
<add>
<add> void dispose() {
<add> DisposableHelper.dispose(this);
<add> }
<add> }
<add> }
<add>}
<ide><path>src/main/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingle.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.mixed;
<add>
<add>import java.util.concurrent.atomic.*;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.annotations.Experimental;
<add>import io.reactivex.disposables.Disposable;
<add>import io.reactivex.exceptions.Exceptions;
<add>import io.reactivex.functions.Function;
<add>import io.reactivex.internal.disposables.DisposableHelper;
<add>import io.reactivex.internal.functions.ObjectHelper;
<add>import io.reactivex.internal.util.AtomicThrowable;
<add>import io.reactivex.plugins.RxJavaPlugins;
<add>
<add>/**
<add> * Maps the upstream items into {@link SingleSource}s and switches (subscribes) to the newer ones
<add> * while disposing the older ones and emits the latest success value if available, optionally delaying
<add> * errors from the main source or the inner sources.
<add> *
<add> * @param <T> the upstream value type
<add> * @param <R> the downstream value type
<add> * @since 2.1.11 - experimental
<add> */
<add>@Experimental
<add>public final class ObservableSwitchMapSingle<T, R> extends Observable<R> {
<add>
<add> final Observable<T> source;
<add>
<add> final Function<? super T, ? extends SingleSource<? extends R>> mapper;
<add>
<add> final boolean delayErrors;
<add>
<add> public ObservableSwitchMapSingle(Observable<T> source,
<add> Function<? super T, ? extends SingleSource<? extends R>> mapper,
<add> boolean delayErrors) {
<add> this.source = source;
<add> this.mapper = mapper;
<add> this.delayErrors = delayErrors;
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(Observer<? super R> s) {
<add> source.subscribe(new SwitchMapSingleMainObserver<T, R>(s, mapper, delayErrors));
<add> }
<add>
<add> static final class SwitchMapSingleMainObserver<T, R> extends AtomicInteger
<add> implements Observer<T>, Disposable {
<add>
<add> private static final long serialVersionUID = -5402190102429853762L;
<add>
<add> final Observer<? super R> downstream;
<add>
<add> final Function<? super T, ? extends SingleSource<? extends R>> mapper;
<add>
<add> final boolean delayErrors;
<add>
<add> final AtomicThrowable errors;
<add>
<add> final AtomicReference<SwitchMapSingleObserver<R>> inner;
<add>
<add> static final SwitchMapSingleObserver<Object> INNER_DISPOSED =
<add> new SwitchMapSingleObserver<Object>(null);
<add>
<add> Disposable upstream;
<add>
<add> volatile boolean done;
<add>
<add> volatile boolean cancelled;
<add>
<add> SwitchMapSingleMainObserver(Observer<? super R> downstream,
<add> Function<? super T, ? extends SingleSource<? extends R>> mapper,
<add> boolean delayErrors) {
<add> this.downstream = downstream;
<add> this.mapper = mapper;
<add> this.delayErrors = delayErrors;
<add> this.errors = new AtomicThrowable();
<add> this.inner = new AtomicReference<SwitchMapSingleObserver<R>>();
<add> }
<add>
<add> @Override
<add> public void onSubscribe(Disposable s) {
<add> if (DisposableHelper.validate(upstream, s)) {
<add> upstream = s;
<add> downstream.onSubscribe(this);
<add> }
<add> }
<add>
<add> @Override
<add> @SuppressWarnings({ "unchecked", "rawtypes" })
<add> public void onNext(T t) {
<add> SwitchMapSingleObserver<R> current = inner.get();
<add> if (current != null) {
<add> current.dispose();
<add> }
<add>
<add> SingleSource<? extends R> ss;
<add>
<add> try {
<add> ss = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null SingleSource");
<add> } catch (Throwable ex) {
<add> Exceptions.throwIfFatal(ex);
<add> upstream.dispose();
<add> inner.getAndSet((SwitchMapSingleObserver)INNER_DISPOSED);
<add> onError(ex);
<add> return;
<add> }
<add>
<add> SwitchMapSingleObserver<R> observer = new SwitchMapSingleObserver<R>(this);
<add>
<add> for (;;) {
<add> current = inner.get();
<add> if (current == INNER_DISPOSED) {
<add> break;
<add> }
<add> if (inner.compareAndSet(current, observer)) {
<add> ss.subscribe(observer);
<add> break;
<add> }
<add> }
<add> }
<add>
<add> @Override
<add> public void onError(Throwable t) {
<add> if (errors.addThrowable(t)) {
<add> if (!delayErrors) {
<add> disposeInner();
<add> }
<add> done = true;
<add> drain();
<add> } else {
<add> RxJavaPlugins.onError(t);
<add> }
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> done = true;
<add> drain();
<add> }
<add>
<add> @SuppressWarnings({ "unchecked", "rawtypes" })
<add> void disposeInner() {
<add> SwitchMapSingleObserver<R> current = inner.getAndSet((SwitchMapSingleObserver)INNER_DISPOSED);
<add> if (current != null && current != INNER_DISPOSED) {
<add> current.dispose();
<add> }
<add> }
<add>
<add> @Override
<add> public void dispose() {
<add> cancelled = true;
<add> upstream.dispose();
<add> disposeInner();
<add> }
<add>
<add> @Override
<add> public boolean isDisposed() {
<add> return cancelled;
<add> }
<add>
<add> void innerError(SwitchMapSingleObserver<R> sender, Throwable ex) {
<add> if (inner.compareAndSet(sender, null)) {
<add> if (errors.addThrowable(ex)) {
<add> if (!delayErrors) {
<add> upstream.dispose();
<add> disposeInner();
<add> }
<add> drain();
<add> return;
<add> }
<add> }
<add> RxJavaPlugins.onError(ex);
<add> }
<add>
<add> void drain() {
<add> if (getAndIncrement() != 0) {
<add> return;
<add> }
<add>
<add> int missed = 1;
<add> Observer<? super R> downstream = this.downstream;
<add> AtomicThrowable errors = this.errors;
<add> AtomicReference<SwitchMapSingleObserver<R>> inner = this.inner;
<add>
<add> for (;;) {
<add>
<add> for (;;) {
<add> if (cancelled) {
<add> return;
<add> }
<add>
<add> if (errors.get() != null) {
<add> if (!delayErrors) {
<add> Throwable ex = errors.terminate();
<add> downstream.onError(ex);
<add> return;
<add> }
<add> }
<add>
<add> boolean d = done;
<add> SwitchMapSingleObserver<R> current = inner.get();
<add> boolean empty = current == null;
<add>
<add> if (d && empty) {
<add> Throwable ex = errors.terminate();
<add> if (ex != null) {
<add> downstream.onError(ex);
<add> } else {
<add> downstream.onComplete();
<add> }
<add> return;
<add> }
<add>
<add> if (empty || current.item == null) {
<add> break;
<add> }
<add>
<add> inner.compareAndSet(current, null);
<add>
<add> downstream.onNext(current.item);
<add> }
<add>
<add> missed = addAndGet(-missed);
<add> if (missed == 0) {
<add> break;
<add> }
<add> }
<add> }
<add>
<add> static final class SwitchMapSingleObserver<R>
<add> extends AtomicReference<Disposable> implements SingleObserver<R> {
<add>
<add> private static final long serialVersionUID = 8042919737683345351L;
<add>
<add> final SwitchMapSingleMainObserver<?, R> parent;
<add>
<add> volatile R item;
<add>
<add> SwitchMapSingleObserver(SwitchMapSingleMainObserver<?, R> parent) {
<add> this.parent = parent;
<add> }
<add>
<add> @Override
<add> public void onSubscribe(Disposable d) {
<add> DisposableHelper.setOnce(this, d);
<add> }
<add>
<add> @Override
<add> public void onSuccess(R t) {
<add> item = t;
<add> parent.drain();
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> parent.innerError(this, e);
<add> }
<add>
<add> void dispose() {
<add> DisposableHelper.dispose(this);
<add> }
<add> }
<add> }
<add>}
<ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMapCompletable.java
<del>/**
<del> * Copyright (c) 2016-present, RxJava Contributors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<del> * compliance with the License. You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<del> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<del> * the License for the specific language governing permissions and limitations under the License.
<del> */
<del>package io.reactivex.internal.operators.observable;
<del>
<del>import java.util.concurrent.atomic.*;
<del>
<del>import io.reactivex.*;
<del>import io.reactivex.disposables.Disposable;
<del>import io.reactivex.exceptions.Exceptions;
<del>import io.reactivex.functions.Function;
<del>import io.reactivex.internal.disposables.DisposableHelper;
<del>import io.reactivex.internal.functions.ObjectHelper;
<del>import io.reactivex.internal.fuseable.*;
<del>import io.reactivex.internal.queue.SpscLinkedArrayQueue;
<del>import io.reactivex.plugins.RxJavaPlugins;
<del>
<del>public final class ObservableConcatMapCompletable<T> extends Completable {
<del>
<del> final ObservableSource<T> source;
<del> final Function<? super T, ? extends CompletableSource> mapper;
<del> final int bufferSize;
<del>
<del> public ObservableConcatMapCompletable(ObservableSource<T> source,
<del> Function<? super T, ? extends CompletableSource> mapper, int bufferSize) {
<del> this.source = source;
<del> this.mapper = mapper;
<del> this.bufferSize = Math.max(8, bufferSize);
<del> }
<del> @Override
<del> public void subscribeActual(CompletableObserver observer) {
<del> source.subscribe(new SourceObserver<T>(observer, mapper, bufferSize));
<del> }
<del>
<del> static final class SourceObserver<T> extends AtomicInteger implements Observer<T>, Disposable {
<del>
<del> private static final long serialVersionUID = 6893587405571511048L;
<del> final CompletableObserver actual;
<del> final Function<? super T, ? extends CompletableSource> mapper;
<del> final InnerObserver inner;
<del> final int bufferSize;
<del>
<del> SimpleQueue<T> queue;
<del>
<del> Disposable s;
<del>
<del> volatile boolean active;
<del>
<del> volatile boolean disposed;
<del>
<del> volatile boolean done;
<del>
<del> int sourceMode;
<del>
<del> SourceObserver(CompletableObserver actual,
<del> Function<? super T, ? extends CompletableSource> mapper, int bufferSize) {
<del> this.actual = actual;
<del> this.mapper = mapper;
<del> this.bufferSize = bufferSize;
<del> this.inner = new InnerObserver(actual, this);
<del> }
<del> @Override
<del> public void onSubscribe(Disposable s) {
<del> if (DisposableHelper.validate(this.s, s)) {
<del> this.s = s;
<del> if (s instanceof QueueDisposable) {
<del> @SuppressWarnings("unchecked")
<del> QueueDisposable<T> qd = (QueueDisposable<T>) s;
<del>
<del> int m = qd.requestFusion(QueueDisposable.ANY);
<del> if (m == QueueDisposable.SYNC) {
<del> sourceMode = m;
<del> queue = qd;
<del> done = true;
<del>
<del> actual.onSubscribe(this);
<del>
<del> drain();
<del> return;
<del> }
<del>
<del> if (m == QueueDisposable.ASYNC) {
<del> sourceMode = m;
<del> queue = qd;
<del>
<del> actual.onSubscribe(this);
<del>
<del> return;
<del> }
<del> }
<del>
<del> queue = new SpscLinkedArrayQueue<T>(bufferSize);
<del>
<del> actual.onSubscribe(this);
<del> }
<del> }
<del> @Override
<del> public void onNext(T t) {
<del> if (done) {
<del> return;
<del> }
<del> if (sourceMode == QueueDisposable.NONE) {
<del> queue.offer(t);
<del> }
<del> drain();
<del> }
<del> @Override
<del> public void onError(Throwable t) {
<del> if (done) {
<del> RxJavaPlugins.onError(t);
<del> return;
<del> }
<del> done = true;
<del> dispose();
<del> actual.onError(t);
<del> }
<del> @Override
<del> public void onComplete() {
<del> if (done) {
<del> return;
<del> }
<del> done = true;
<del> drain();
<del> }
<del>
<del> void innerComplete() {
<del> active = false;
<del> drain();
<del> }
<del>
<del> @Override
<del> public boolean isDisposed() {
<del> return disposed;
<del> }
<del>
<del> @Override
<del> public void dispose() {
<del> disposed = true;
<del> inner.dispose();
<del> s.dispose();
<del>
<del> if (getAndIncrement() == 0) {
<del> queue.clear();
<del> }
<del> }
<del>
<del> void drain() {
<del> if (getAndIncrement() != 0) {
<del> return;
<del> }
<del>
<del> for (;;) {
<del> if (disposed) {
<del> queue.clear();
<del> return;
<del> }
<del> if (!active) {
<del>
<del> boolean d = done;
<del>
<del> T t;
<del>
<del> try {
<del> t = queue.poll();
<del> } catch (Throwable ex) {
<del> Exceptions.throwIfFatal(ex);
<del> dispose();
<del> queue.clear();
<del> actual.onError(ex);
<del> return;
<del> }
<del>
<del> boolean empty = t == null;
<del>
<del> if (d && empty) {
<del> disposed = true;
<del> actual.onComplete();
<del> return;
<del> }
<del>
<del> if (!empty) {
<del> CompletableSource c;
<del>
<del> try {
<del> c = ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null CompletableSource");
<del> } catch (Throwable ex) {
<del> Exceptions.throwIfFatal(ex);
<del> dispose();
<del> queue.clear();
<del> actual.onError(ex);
<del> return;
<del> }
<del>
<del> active = true;
<del> c.subscribe(inner);
<del> }
<del> }
<del>
<del> if (decrementAndGet() == 0) {
<del> break;
<del> }
<del> }
<del> }
<del>
<del> static final class InnerObserver extends AtomicReference<Disposable> implements CompletableObserver {
<del> private static final long serialVersionUID = -5987419458390772447L;
<del> final CompletableObserver actual;
<del> final SourceObserver<?> parent;
<del>
<del> InnerObserver(CompletableObserver actual, SourceObserver<?> parent) {
<del> this.actual = actual;
<del> this.parent = parent;
<del> }
<del>
<del> @Override
<del> public void onSubscribe(Disposable s) {
<del> DisposableHelper.set(this, s);
<del> }
<del>
<del> @Override
<del> public void onError(Throwable t) {
<del> parent.dispose();
<del> actual.onError(t);
<del> }
<del> @Override
<del> public void onComplete() {
<del> parent.innerComplete();
<del> }
<del>
<del> void dispose() {
<del> DisposableHelper.dispose(this);
<del> }
<del> }
<del> }
<del>}
<ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableInternalHelper.java
<ide>
<ide> import io.reactivex.*;
<ide> import io.reactivex.functions.*;
<del>import io.reactivex.internal.functions.Functions;
<del>import io.reactivex.internal.functions.ObjectHelper;
<del>import io.reactivex.internal.operators.single.SingleToObservable;
<add>import io.reactivex.internal.functions.*;
<ide> import io.reactivex.observables.ConnectableObservable;
<del>import io.reactivex.plugins.RxJavaPlugins;
<ide>
<ide> /**
<ide> * Helper utility class to support Observable with inner classes.
<ide> public static <T, R> Function<List<ObservableSource<? extends T>>, ObservableSou
<ide> return new ZipIterableFunction<T, R>(zipper);
<ide> }
<ide>
<del> public static <T,R> Observable<R> switchMapSingle(Observable<T> source, final Function<? super T, ? extends SingleSource<? extends R>> mapper) {
<del> return source.switchMap(convertSingleMapperToObservableMapper(mapper), 1);
<del> }
<del>
<del> public static <T,R> Observable<R> switchMapSingleDelayError(Observable<T> source,
<del> Function<? super T, ? extends SingleSource<? extends R>> mapper) {
<del> return source.switchMapDelayError(convertSingleMapperToObservableMapper(mapper), 1);
<del> }
<del>
<del> private static <T, R> Function<T, Observable<R>> convertSingleMapperToObservableMapper(
<del> final Function<? super T, ? extends SingleSource<? extends R>> mapper) {
<del> ObjectHelper.requireNonNull(mapper, "mapper is null");
<del> return new ObservableMapper<T,R>(mapper);
<del> }
<del>
<del> static final class ObservableMapper<T,R> implements Function<T,Observable<R>> {
<del>
<del> final Function<? super T, ? extends SingleSource<? extends R>> mapper;
<del>
<del> ObservableMapper(Function<? super T, ? extends SingleSource<? extends R>> mapper) {
<del> this.mapper = mapper;
<del> }
<del>
<del> @Override
<del> public Observable<R> apply(T t) throws Exception {
<del> return RxJavaPlugins.onAssembly(new SingleToObservable<R>(
<del> ObjectHelper.requireNonNull(mapper.apply(t), "The mapper returned a null SingleSource")));
<del> }
<del>
<del> }
<del>
<ide> static final class ReplayCallable<T> implements Callable<ConnectableObservable<T>> {
<ide> private final Observable<T> parent;
<ide>
<ide><path>src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapCompletableTest.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.mixed;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>import java.util.List;
<add>import java.util.concurrent.atomic.AtomicInteger;
<add>
<add>import org.junit.Test;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.exceptions.*;
<add>import io.reactivex.functions.*;
<add>import io.reactivex.internal.functions.Functions;
<add>import io.reactivex.observers.TestObserver;
<add>import io.reactivex.plugins.RxJavaPlugins;
<add>import io.reactivex.subjects.*;
<add>
<add>public class ObservableConcatMapCompletableTest {
<add>
<add> @Test
<add> public void simple() {
<add> Observable.range(1, 5)
<add> .concatMapCompletable(Functions.justFunction(Completable.complete()))
<add> .test()
<add> .assertResult();
<add> }
<add>
<add> @Test
<add> public void simple2() {
<add> final AtomicInteger counter = new AtomicInteger();
<add> Observable.range(1, 5)
<add> .concatMapCompletable(Functions.justFunction(Completable.fromAction(new Action() {
<add> @Override
<add> public void run() throws Exception {
<add> counter.incrementAndGet();
<add> }
<add> })))
<add> .test()
<add> .assertResult();
<add>
<add> assertEquals(5, counter.get());
<add> }
<add>
<add> @Test
<add> public void simpleLongPrefetch() {
<add> Observable.range(1, 1024)
<add> .concatMapCompletable(Functions.justFunction(Completable.complete()), 32)
<add> .test()
<add> .assertResult();
<add> }
<add>
<add> @Test
<add> public void mainError() {
<add> Observable.<Integer>error(new TestException())
<add> .concatMapCompletable(Functions.justFunction(Completable.complete()))
<add> .test()
<add> .assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void innerError() {
<add> Observable.just(1)
<add> .concatMapCompletable(Functions.justFunction(Completable.error(new TestException())))
<add> .test()
<add> .assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void innerErrorDelayed() {
<add> Observable.range(1, 5)
<add> .concatMapCompletableDelayError(
<add> new Function<Integer, CompletableSource>() {
<add> @Override
<add> public CompletableSource apply(Integer v) throws Exception {
<add> return Completable.error(new TestException());
<add> }
<add> }
<add> )
<add> .test()
<add> .assertFailure(CompositeException.class)
<add> .assertOf(new Consumer<TestObserver<Void>>() {
<add> @Override
<add> public void accept(TestObserver<Void> to) throws Exception {
<add> assertEquals(5, ((CompositeException)to.errors().get(0)).getExceptions().size());
<add> }
<add> });
<add> }
<add>
<add> @Test
<add> public void mapperCrash() {
<add> Observable.just(1)
<add> .concatMapCompletable(new Function<Integer, CompletableSource>() {
<add> @Override
<add> public CompletableSource apply(Integer v) throws Exception {
<add> throw new TestException();
<add> }
<add> })
<add> .test()
<add> .assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void immediateError() {
<add> PublishSubject<Integer> ps = PublishSubject.create();
<add> CompletableSubject cs = CompletableSubject.create();
<add>
<add> TestObserver<Void> to = ps.concatMapCompletable(
<add> Functions.justFunction(cs)).test();
<add>
<add> to.assertEmpty();
<add>
<add> assertTrue(ps.hasObservers());
<add> assertFalse(cs.hasObservers());
<add>
<add> ps.onNext(1);
<add>
<add> assertTrue(cs.hasObservers());
<add>
<add> ps.onError(new TestException());
<add>
<add> assertFalse(cs.hasObservers());
<add>
<add> to.assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void immediateError2() {
<add> PublishSubject<Integer> ps = PublishSubject.create();
<add> CompletableSubject cs = CompletableSubject.create();
<add>
<add> TestObserver<Void> to = ps.concatMapCompletable(
<add> Functions.justFunction(cs)).test();
<add>
<add> to.assertEmpty();
<add>
<add> assertTrue(ps.hasObservers());
<add> assertFalse(cs.hasObservers());
<add>
<add> ps.onNext(1);
<add>
<add> assertTrue(cs.hasObservers());
<add>
<add> cs.onError(new TestException());
<add>
<add> assertFalse(ps.hasObservers());
<add>
<add> to.assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void boundaryError() {
<add> PublishSubject<Integer> ps = PublishSubject.create();
<add> CompletableSubject cs = CompletableSubject.create();
<add>
<add> TestObserver<Void> to = ps.concatMapCompletableDelayError(
<add> Functions.justFunction(cs), false).test();
<add>
<add> to.assertEmpty();
<add>
<add> assertTrue(ps.hasObservers());
<add> assertFalse(cs.hasObservers());
<add>
<add> ps.onNext(1);
<add>
<add> assertTrue(cs.hasObservers());
<add>
<add> ps.onError(new TestException());
<add>
<add> assertTrue(cs.hasObservers());
<add>
<add> to.assertEmpty();
<add>
<add> cs.onComplete();
<add>
<add> to.assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void endError() {
<add> PublishSubject<Integer> ps = PublishSubject.create();
<add> final CompletableSubject cs = CompletableSubject.create();
<add> final CompletableSubject cs2 = CompletableSubject.create();
<add>
<add> TestObserver<Void> to = ps.concatMapCompletableDelayError(
<add> new Function<Integer, CompletableSource>() {
<add> @Override
<add> public CompletableSource apply(Integer v) throws Exception {
<add> if (v == 1) {
<add> return cs;
<add> }
<add> return cs2;
<add> }
<add> }, true, 32
<add> )
<add> .test();
<add>
<add> to.assertEmpty();
<add>
<add> assertTrue(ps.hasObservers());
<add> assertFalse(cs.hasObservers());
<add>
<add> ps.onNext(1);
<add>
<add> assertTrue(cs.hasObservers());
<add>
<add> cs.onError(new TestException());
<add>
<add> assertTrue(ps.hasObservers());
<add>
<add> ps.onNext(2);
<add>
<add> to.assertEmpty();
<add>
<add> cs2.onComplete();
<add>
<add> assertTrue(ps.hasObservers());
<add>
<add> to.assertEmpty();
<add>
<add> ps.onComplete();
<add>
<add> to.assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void doubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeObservableToCompletable(
<add> new Function<Observable<Object>, Completable>() {
<add> @Override
<add> public Completable apply(Observable<Object> f)
<add> throws Exception {
<add> return f.concatMapCompletable(
<add> Functions.justFunction(Completable.complete()));
<add> }
<add> }
<add> );
<add> }
<add>
<add> @Test
<add> public void disposed() {
<add> TestHelper.checkDisposed(
<add> Observable.never()
<add> .concatMapCompletable(
<add> Functions.justFunction(Completable.complete()))
<add> );
<add> }
<add>
<add> @Test
<add> public void immediateOuterInnerErrorRace() {
<add> final TestException ex = new TestException();
<add> for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) {
<add> List<Throwable> errors = TestHelper.trackPluginErrors();
<add> try {
<add> final PublishSubject<Integer> ps = PublishSubject.create();
<add> final CompletableSubject cs = CompletableSubject.create();
<add>
<add> TestObserver<Void> to = ps.concatMapCompletable(
<add> Functions.justFunction(cs)
<add> )
<add> .test();
<add>
<add> ps.onNext(1);
<add>
<add> Runnable r1 = new Runnable() {
<add> @Override
<add> public void run() {
<add> ps.onError(ex);
<add> }
<add> };
<add>
<add> Runnable r2 = new Runnable() {
<add> @Override
<add> public void run() {
<add> cs.onError(ex);
<add> }
<add> };
<add>
<add> TestHelper.race(r1, r2);
<add>
<add> to.assertError(new Predicate<Throwable>() {
<add> @Override
<add> public boolean test(Throwable e) throws Exception {
<add> return e instanceof TestException || e instanceof CompositeException;
<add> }
<add> })
<add> .assertNotComplete();
<add>
<add> if (!errors.isEmpty()) {
<add> TestHelper.assertUndeliverable(errors, 0, TestException.class);
<add> }
<add> } finally {
<add> RxJavaPlugins.reset();
<add> }
<add> }
<add> }
<add>
<add> @Test
<add> public void disposeInDrainLoop() {
<add> for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) {
<add> final PublishSubject<Integer> ps = PublishSubject.create();
<add> final CompletableSubject cs = CompletableSubject.create();
<add>
<add> final TestObserver<Void> to = ps.concatMapCompletable(
<add> Functions.justFunction(cs)
<add> )
<add> .test();
<add>
<add> ps.onNext(1);
<add>
<add> Runnable r1 = new Runnable() {
<add> @Override
<add> public void run() {
<add> ps.onNext(2);
<add> }
<add> };
<add>
<add> Runnable r2 = new Runnable() {
<add> @Override
<add> public void run() {
<add> cs.onComplete();
<add> to.cancel();
<add> }
<add> };
<add>
<add> TestHelper.race(r1, r2);
<add>
<add> to.assertEmpty();
<add> }
<add> }
<add>
<add> @Test
<add> public void doneButNotEmpty() {
<add> final PublishSubject<Integer> ps = PublishSubject.create();
<add> final CompletableSubject cs = CompletableSubject.create();
<add>
<add> final TestObserver<Void> to = ps.concatMapCompletable(
<add> Functions.justFunction(cs)
<add> )
<add> .test();
<add>
<add> ps.onNext(1);
<add> ps.onNext(2);
<add> ps.onComplete();
<add>
<add> cs.onComplete();
<add>
<add> to.assertResult();
<add> }
<add>}
<ide><path>src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapMaybeTest.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.mixed;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>import java.util.List;
<add>import java.util.concurrent.TimeUnit;
<add>import java.util.concurrent.atomic.AtomicReference;
<add>
<add>import org.junit.Test;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.disposables.Disposables;
<add>import io.reactivex.exceptions.*;
<add>import io.reactivex.functions.*;
<add>import io.reactivex.internal.functions.Functions;
<add>import io.reactivex.observers.TestObserver;
<add>import io.reactivex.plugins.RxJavaPlugins;
<add>import io.reactivex.schedulers.Schedulers;
<add>import io.reactivex.subjects.*;
<add>
<add>public class ObservableConcatMapMaybeTest {
<add>
<add> @Test
<add> public void simple() {
<add> Observable.range(1, 5)
<add> .concatMapMaybe(new Function<Integer, MaybeSource<Integer>>() {
<add> @Override
<add> public MaybeSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return Maybe.just(v);
<add> }
<add> })
<add> .test()
<add> .assertResult(1, 2, 3, 4, 5);
<add> }
<add>
<add> @Test
<add> public void simpleLong() {
<add> Observable.range(1, 1024)
<add> .concatMapMaybe(new Function<Integer, MaybeSource<Integer>>() {
<add> @Override
<add> public MaybeSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return Maybe.just(v);
<add> }
<add> }, 32)
<add> .test()
<add> .assertValueCount(1024)
<add> .assertNoErrors()
<add> .assertComplete();
<add> }
<add>
<add> @Test
<add> public void empty() {
<add> Observable.range(1, 10)
<add> .concatMapMaybe(new Function<Integer, MaybeSource<Integer>>() {
<add> @Override
<add> public MaybeSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return Maybe.empty();
<add> }
<add> })
<add> .test()
<add> .assertResult();
<add> }
<add>
<add> @Test
<add> public void mixed() {
<add> Observable.range(1, 10)
<add> .concatMapMaybe(new Function<Integer, MaybeSource<Integer>>() {
<add> @Override
<add> public MaybeSource<Integer> apply(Integer v)
<add> throws Exception {
<add> if (v % 2 == 0) {
<add> return Maybe.just(v);
<add> }
<add> return Maybe.empty();
<add> }
<add> })
<add> .test()
<add> .assertResult(2, 4, 6, 8, 10);
<add> }
<add>
<add> @Test
<add> public void mixedLong() {
<add> Observable.range(1, 1024)
<add> .concatMapMaybe(new Function<Integer, MaybeSource<Integer>>() {
<add> @Override
<add> public MaybeSource<Integer> apply(Integer v)
<add> throws Exception {
<add> if (v % 2 == 0) {
<add> return Maybe.just(v).subscribeOn(Schedulers.computation());
<add> }
<add> return Maybe.<Integer>empty().subscribeOn(Schedulers.computation());
<add> }
<add> })
<add> .test()
<add> .awaitDone(5, TimeUnit.SECONDS)
<add> .assertValueCount(512)
<add> .assertNoErrors()
<add> .assertComplete()
<add> .assertOf(new Consumer<TestObserver<Integer>>() {
<add> @Override
<add> public void accept(TestObserver<Integer> ts) throws Exception {
<add> for (int i = 0; i < 512; i ++) {
<add> ts.assertValueAt(i, (i + 1) * 2);
<add> }
<add> }
<add> });
<add> }
<add>
<add> @Test
<add> public void mainError() {
<add> Observable.error(new TestException())
<add> .concatMapMaybe(Functions.justFunction(Maybe.just(1)))
<add> .test()
<add> .assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void innerError() {
<add> Observable.just(1)
<add> .concatMapMaybe(Functions.justFunction(Maybe.error(new TestException())))
<add> .test()
<add> .assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void mainBoundaryErrorInnerSuccess() {
<add> PublishSubject<Integer> ps = PublishSubject.create();
<add> MaybeSubject<Integer> ms = MaybeSubject.create();
<add>
<add> TestObserver<Integer> ts = ps.concatMapMaybeDelayError(Functions.justFunction(ms), false).test();
<add>
<add> ts.assertEmpty();
<add>
<add> ps.onNext(1);
<add>
<add> assertTrue(ms.hasObservers());
<add>
<add> ps.onError(new TestException());
<add>
<add> assertTrue(ms.hasObservers());
<add>
<add> ts.assertEmpty();
<add>
<add> ms.onSuccess(1);
<add>
<add> ts.assertFailure(TestException.class, 1);
<add> }
<add>
<add> @Test
<add> public void mainBoundaryErrorInnerEmpty() {
<add> PublishSubject<Integer> ps = PublishSubject.create();
<add> MaybeSubject<Integer> ms = MaybeSubject.create();
<add>
<add> TestObserver<Integer> ts = ps.concatMapMaybeDelayError(Functions.justFunction(ms), false).test();
<add>
<add> ts.assertEmpty();
<add>
<add> ps.onNext(1);
<add>
<add> assertTrue(ms.hasObservers());
<add>
<add> ps.onError(new TestException());
<add>
<add> assertTrue(ms.hasObservers());
<add>
<add> ts.assertEmpty();
<add>
<add> ms.onComplete();
<add>
<add> ts.assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void doubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeObservable(
<add> new Function<Observable<Object>, Observable<Object>>() {
<add> @Override
<add> public Observable<Object> apply(Observable<Object> f)
<add> throws Exception {
<add> return f.concatMapMaybeDelayError(
<add> Functions.justFunction(Maybe.empty()));
<add> }
<add> }
<add> );
<add> }
<add>
<add> @Test
<add> public void take() {
<add> Observable.range(1, 5)
<add> .concatMapMaybe(new Function<Integer, MaybeSource<Integer>>() {
<add> @Override
<add> public MaybeSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return Maybe.just(v);
<add> }
<add> })
<add> .take(3)
<add> .test()
<add> .assertResult(1, 2, 3);
<add> }
<add>
<add> @Test
<add> public void cancel() {
<add> Observable.range(1, 5).concatWith(Observable.<Integer>never())
<add> .concatMapMaybe(new Function<Integer, MaybeSource<Integer>>() {
<add> @Override
<add> public MaybeSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return Maybe.just(v);
<add> }
<add> })
<add> .test()
<add> .assertValues(1, 2, 3, 4, 5)
<add> .assertNoErrors()
<add> .assertNotComplete()
<add> .cancel();
<add> }
<add>
<add> @Test
<add> public void mainErrorAfterInnerError() {
<add> List<Throwable> errors = TestHelper.trackPluginErrors();
<add> try {
<add> new Observable<Integer>() {
<add> @Override
<add> protected void subscribeActual(Observer<? super Integer> s) {
<add> s.onSubscribe(Disposables.empty());
<add> s.onNext(1);
<add> s.onError(new TestException("outer"));
<add> }
<add> }
<add> .concatMapMaybe(
<add> Functions.justFunction(Maybe.error(new TestException("inner"))), 1
<add> )
<add> .test()
<add> .assertFailureAndMessage(TestException.class, "inner");
<add>
<add> TestHelper.assertUndeliverable(errors, 0, TestException.class, "outer");
<add> } finally {
<add> RxJavaPlugins.reset();
<add> }
<add> }
<add>
<add> @Test
<add> public void innerErrorAfterMainError() {
<add> List<Throwable> errors = TestHelper.trackPluginErrors();
<add> try {
<add> final PublishSubject<Integer> ps = PublishSubject.create();
<add>
<add> final AtomicReference<MaybeObserver<? super Integer>> obs = new AtomicReference<MaybeObserver<? super Integer>>();
<add>
<add> TestObserver<Integer> ts = ps.concatMapMaybe(
<add> new Function<Integer, MaybeSource<Integer>>() {
<add> @Override
<add> public MaybeSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return new Maybe<Integer>() {
<add> @Override
<add> protected void subscribeActual(
<add> MaybeObserver<? super Integer> observer) {
<add> observer.onSubscribe(Disposables.empty());
<add> obs.set(observer);
<add> }
<add> };
<add> }
<add> }
<add> ).test();
<add>
<add> ps.onNext(1);
<add>
<add> ps.onError(new TestException("outer"));
<add> obs.get().onError(new TestException("inner"));
<add>
<add> ts.assertFailureAndMessage(TestException.class, "outer");
<add>
<add> TestHelper.assertUndeliverable(errors, 0, TestException.class, "inner");
<add> } finally {
<add> RxJavaPlugins.reset();
<add> }
<add> }
<add>
<add> @Test
<add> public void delayAllErrors() {
<add> Observable.range(1, 5)
<add> .concatMapMaybeDelayError(new Function<Integer, MaybeSource<? extends Object>>() {
<add> @Override
<add> public MaybeSource<? extends Object> apply(Integer v)
<add> throws Exception {
<add> return Maybe.error(new TestException());
<add> }
<add> })
<add> .test()
<add> .assertFailure(CompositeException.class)
<add> .assertOf(new Consumer<TestObserver<Object>>() {
<add> @Override
<add> public void accept(TestObserver<Object> ts) throws Exception {
<add> CompositeException ce = (CompositeException)ts.errors().get(0);
<add> assertEquals(5, ce.getExceptions().size());
<add> }
<add> });
<add> }
<add>
<add> @Test
<add> public void mapperCrash() {
<add> final PublishSubject<Integer> ps = PublishSubject.create();
<add>
<add> TestObserver<Object> ts = ps
<add> .concatMapMaybe(new Function<Integer, MaybeSource<? extends Object>>() {
<add> @Override
<add> public MaybeSource<? extends Object> apply(Integer v)
<add> throws Exception {
<add> throw new TestException();
<add> }
<add> })
<add> .test();
<add>
<add> ts.assertEmpty();
<add>
<add> assertTrue(ps.hasObservers());
<add>
<add> ps.onNext(1);
<add>
<add> ts.assertFailure(TestException.class);
<add>
<add> assertFalse(ps.hasObservers());
<add> }
<add>
<add> @Test
<add> public void disposed() {
<add> TestHelper.checkDisposed(Observable.just(1)
<add> .concatMapMaybe(Functions.justFunction(Maybe.never()))
<add> );
<add> }
<add>}
<ide><path>src/test/java/io/reactivex/internal/operators/mixed/ObservableConcatMapSingleTest.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.mixed;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>import java.util.List;
<add>import java.util.concurrent.atomic.AtomicReference;
<add>
<add>import org.junit.Test;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.disposables.Disposables;
<add>import io.reactivex.exceptions.*;
<add>import io.reactivex.functions.*;
<add>import io.reactivex.internal.functions.Functions;
<add>import io.reactivex.observers.TestObserver;
<add>import io.reactivex.plugins.RxJavaPlugins;
<add>import io.reactivex.subjects.*;
<add>
<add>public class ObservableConcatMapSingleTest {
<add>
<add> @Test
<add> public void simple() {
<add> Observable.range(1, 5)
<add> .concatMapSingle(new Function<Integer, SingleSource<Integer>>() {
<add> @Override
<add> public SingleSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return Single.just(v);
<add> }
<add> })
<add> .test()
<add> .assertResult(1, 2, 3, 4, 5);
<add> }
<add>
<add> @Test
<add> public void simpleLong() {
<add> Observable.range(1, 1024)
<add> .concatMapSingle(new Function<Integer, SingleSource<Integer>>() {
<add> @Override
<add> public SingleSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return Single.just(v);
<add> }
<add> }, 32)
<add> .test()
<add> .assertValueCount(1024)
<add> .assertNoErrors()
<add> .assertComplete();
<add> }
<add>
<add> @Test
<add> public void mainError() {
<add> Observable.error(new TestException())
<add> .concatMapSingle(Functions.justFunction(Single.just(1)))
<add> .test()
<add> .assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void innerError() {
<add> Observable.just(1)
<add> .concatMapSingle(Functions.justFunction(Single.error(new TestException())))
<add> .test()
<add> .assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void mainBoundaryErrorInnerSuccess() {
<add> PublishSubject<Integer> ps = PublishSubject.create();
<add> SingleSubject<Integer> ms = SingleSubject.create();
<add>
<add> TestObserver<Integer> ts = ps.concatMapSingleDelayError(Functions.justFunction(ms), false).test();
<add>
<add> ts.assertEmpty();
<add>
<add> ps.onNext(1);
<add>
<add> assertTrue(ms.hasObservers());
<add>
<add> ps.onError(new TestException());
<add>
<add> assertTrue(ms.hasObservers());
<add>
<add> ts.assertEmpty();
<add>
<add> ms.onSuccess(1);
<add>
<add> ts.assertFailure(TestException.class, 1);
<add> }
<add>
<add> @Test
<add> public void doubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeObservable(
<add> new Function<Observable<Object>, Observable<Object>>() {
<add> @Override
<add> public Observable<Object> apply(Observable<Object> f)
<add> throws Exception {
<add> return f.concatMapSingleDelayError(
<add> Functions.justFunction(Single.never()));
<add> }
<add> }
<add> );
<add> }
<add>
<add> @Test
<add> public void take() {
<add> Observable.range(1, 5)
<add> .concatMapSingle(new Function<Integer, SingleSource<Integer>>() {
<add> @Override
<add> public SingleSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return Single.just(v);
<add> }
<add> })
<add> .take(3)
<add> .test()
<add> .assertResult(1, 2, 3);
<add> }
<add>
<add> @Test
<add> public void cancel() {
<add> Observable.range(1, 5).concatWith(Observable.<Integer>never())
<add> .concatMapSingle(new Function<Integer, SingleSource<Integer>>() {
<add> @Override
<add> public SingleSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return Single.just(v);
<add> }
<add> })
<add> .test()
<add> .assertValues(1, 2, 3, 4, 5)
<add> .assertNoErrors()
<add> .assertNotComplete()
<add> .cancel();
<add> }
<add>
<add> @Test
<add> public void mainErrorAfterInnerError() {
<add> List<Throwable> errors = TestHelper.trackPluginErrors();
<add> try {
<add> new Observable<Integer>() {
<add> @Override
<add> protected void subscribeActual(Observer<? super Integer> s) {
<add> s.onSubscribe(Disposables.empty());
<add> s.onNext(1);
<add> s.onError(new TestException("outer"));
<add> }
<add> }
<add> .concatMapSingle(
<add> Functions.justFunction(Single.error(new TestException("inner"))), 1
<add> )
<add> .test()
<add> .assertFailureAndMessage(TestException.class, "inner");
<add>
<add> TestHelper.assertUndeliverable(errors, 0, TestException.class, "outer");
<add> } finally {
<add> RxJavaPlugins.reset();
<add> }
<add> }
<add>
<add> @Test
<add> public void innerErrorAfterMainError() {
<add> List<Throwable> errors = TestHelper.trackPluginErrors();
<add> try {
<add> final PublishSubject<Integer> ps = PublishSubject.create();
<add>
<add> final AtomicReference<SingleObserver<? super Integer>> obs = new AtomicReference<SingleObserver<? super Integer>>();
<add>
<add> TestObserver<Integer> ts = ps.concatMapSingle(
<add> new Function<Integer, SingleSource<Integer>>() {
<add> @Override
<add> public SingleSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return new Single<Integer>() {
<add> @Override
<add> protected void subscribeActual(
<add> SingleObserver<? super Integer> observer) {
<add> observer.onSubscribe(Disposables.empty());
<add> obs.set(observer);
<add> }
<add> };
<add> }
<add> }
<add> ).test();
<add>
<add> ps.onNext(1);
<add>
<add> ps.onError(new TestException("outer"));
<add> obs.get().onError(new TestException("inner"));
<add>
<add> ts.assertFailureAndMessage(TestException.class, "outer");
<add>
<add> TestHelper.assertUndeliverable(errors, 0, TestException.class, "inner");
<add> } finally {
<add> RxJavaPlugins.reset();
<add> }
<add> }
<add>
<add> @Test
<add> public void delayAllErrors() {
<add> Observable.range(1, 5)
<add> .concatMapSingleDelayError(new Function<Integer, SingleSource<? extends Object>>() {
<add> @Override
<add> public SingleSource<? extends Object> apply(Integer v)
<add> throws Exception {
<add> return Single.error(new TestException());
<add> }
<add> })
<add> .test()
<add> .assertFailure(CompositeException.class)
<add> .assertOf(new Consumer<TestObserver<Object>>() {
<add> @Override
<add> public void accept(TestObserver<Object> ts) throws Exception {
<add> CompositeException ce = (CompositeException)ts.errors().get(0);
<add> assertEquals(5, ce.getExceptions().size());
<add> }
<add> });
<add> }
<add>
<add> @Test
<add> public void mapperCrash() {
<add> final PublishSubject<Integer> ps = PublishSubject.create();
<add>
<add> TestObserver<Object> ts = ps
<add> .concatMapSingle(new Function<Integer, SingleSource<? extends Object>>() {
<add> @Override
<add> public SingleSource<? extends Object> apply(Integer v)
<add> throws Exception {
<add> throw new TestException();
<add> }
<add> })
<add> .test();
<add>
<add> ts.assertEmpty();
<add>
<add> assertTrue(ps.hasObservers());
<add>
<add> ps.onNext(1);
<add>
<add> ts.assertFailure(TestException.class);
<add>
<add> assertFalse(ps.hasObservers());
<add> }
<add>
<add> @Test
<add> public void disposed() {
<add> TestHelper.checkDisposed(Observable.just(1)
<add> .concatMapSingle(Functions.justFunction(Single.never()))
<add> );
<add> }
<add>
<add> @Test
<add> public void mainCompletesWhileInnerActive() {
<add> PublishSubject<Integer> ps = PublishSubject.create();
<add> SingleSubject<Integer> ms = SingleSubject.create();
<add>
<add> TestObserver<Integer> ts = ps.concatMapSingleDelayError(Functions.justFunction(ms), false).test();
<add>
<add> ts.assertEmpty();
<add>
<add> ps.onNext(1);
<add> ps.onNext(2);
<add> ps.onComplete();
<add>
<add> assertTrue(ms.hasObservers());
<add>
<add> ts.assertEmpty();
<add>
<add> ms.onSuccess(1);
<add>
<add> ts.assertResult(1, 1);
<add> }
<add>}
<ide><path>src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapCompletableTest.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.mixed;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>import java.util.List;
<add>
<add>import org.junit.Test;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.disposables.Disposables;
<add>import io.reactivex.exceptions.*;
<add>import io.reactivex.functions.*;
<add>import io.reactivex.internal.functions.Functions;
<add>import io.reactivex.observers.TestObserver;
<add>import io.reactivex.plugins.RxJavaPlugins;
<add>import io.reactivex.subjects.*;
<add>
<add>public class ObservableSwitchMapCompletableTest {
<add>
<add> @Test
<add> public void normal() {
<add> Observable.range(1, 10)
<add> .switchMapCompletable(new Function<Integer, CompletableSource>() {
<add> @Override
<add> public CompletableSource apply(Integer v) throws Exception {
<add> return Completable.complete();
<add> }
<add> })
<add> .test()
<add> .assertResult();
<add> }
<add>
<add> @Test
<add> public void mainError() {
<add> Observable.<Integer>error(new TestException())
<add> .switchMapCompletable(new Function<Integer, CompletableSource>() {
<add> @Override
<add> public CompletableSource apply(Integer v) throws Exception {
<add> return Completable.complete();
<add> }
<add> })
<add> .test()
<add> .assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void innerError() {
<add> PublishSubject<Integer> ps = PublishSubject.create();
<add> CompletableSubject cs = CompletableSubject.create();
<add>
<add> TestObserver<Void> to = ps.switchMapCompletable(Functions.justFunction(cs))
<add> .test();
<add>
<add> assertTrue(ps.hasObservers());
<add> assertFalse(cs.hasObservers());
<add>
<add> ps.onNext(1);
<add>
<add> assertTrue(cs.hasObservers());
<add>
<add> to.assertEmpty();
<add>
<add> cs.onError(new TestException());
<add>
<add> to.assertFailure(TestException.class);
<add>
<add> assertFalse(ps.hasObservers());
<add> assertFalse(cs.hasObservers());
<add> }
<add>
<add> @Test
<add> public void switchOver() {
<add> final CompletableSubject[] css = {
<add> CompletableSubject.create(),
<add> CompletableSubject.create()
<add> };
<add>
<add> PublishSubject<Integer> ps = PublishSubject.create();
<add>
<add> TestObserver<Void> to = ps.switchMapCompletable(new Function<Integer, CompletableSource>() {
<add> @Override
<add> public CompletableSource apply(Integer v) throws Exception {
<add> return css[v];
<add> }
<add> })
<add> .test();
<add>
<add> to.assertEmpty();
<add>
<add> ps.onNext(0);
<add>
<add> assertTrue(css[0].hasObservers());
<add>
<add> ps.onNext(1);
<add>
<add> assertFalse(css[0].hasObservers());
<add> assertTrue(css[1].hasObservers());
<add>
<add> ps.onComplete();
<add>
<add> to.assertEmpty();
<add>
<add> assertTrue(css[1].hasObservers());
<add>
<add> css[1].onComplete();
<add>
<add> to.assertResult();
<add> }
<add>
<add> @Test
<add> public void dispose() {
<add> PublishSubject<Integer> ps = PublishSubject.create();
<add> CompletableSubject cs = CompletableSubject.create();
<add>
<add> TestObserver<Void> to = ps.switchMapCompletable(Functions.justFunction(cs))
<add> .test();
<add>
<add> ps.onNext(1);
<add>
<add> assertTrue(ps.hasObservers());
<add> assertTrue(cs.hasObservers());
<add>
<add> to.dispose();
<add>
<add> assertFalse(ps.hasObservers());
<add> assertFalse(cs.hasObservers());
<add> }
<add>
<add> @Test
<add> public void checkDisposed() {
<add> PublishSubject<Integer> ps = PublishSubject.create();
<add> CompletableSubject cs = CompletableSubject.create();
<add>
<add> TestHelper.checkDisposed(ps.switchMapCompletable(Functions.justFunction(cs)));
<add> }
<add>
<add> @Test
<add> public void checkBadSource() {
<add> TestHelper.checkDoubleOnSubscribeObservableToCompletable(new Function<Observable<Object>, Completable>() {
<add> @Override
<add> public Completable apply(Observable<Object> f) throws Exception {
<add> return f.switchMapCompletable(Functions.justFunction(Completable.never()));
<add> }
<add> });
<add> }
<add>
<add> @Test
<add> public void mapperCrash() {
<add> Observable.range(1, 5).switchMapCompletable(new Function<Integer, CompletableSource>() {
<add> @Override
<add> public CompletableSource apply(Integer f) throws Exception {
<add> throw new TestException();
<add> }
<add> })
<add> .test()
<add> .assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void mapperCancels() {
<add> final TestObserver<Void> to = new TestObserver<Void>();
<add>
<add> Observable.range(1, 5).switchMapCompletable(new Function<Integer, CompletableSource>() {
<add> @Override
<add> public CompletableSource apply(Integer f) throws Exception {
<add> to.cancel();
<add> return Completable.complete();
<add> }
<add> })
<add> .subscribe(to);
<add>
<add> to.assertEmpty();
<add> }
<add>
<add> @Test
<add> public void onNextInnerCompleteRace() {
<add> for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) {
<add> final PublishSubject<Integer> ps = PublishSubject.create();
<add> final CompletableSubject cs = CompletableSubject.create();
<add>
<add> TestObserver<Void> to = ps.switchMapCompletable(Functions.justFunction(cs)).test();
<add>
<add> ps.onNext(1);
<add>
<add> Runnable r1 = new Runnable() {
<add> @Override
<add> public void run() {
<add> ps.onNext(2);
<add> }
<add> };
<add>
<add> Runnable r2 = new Runnable() {
<add> @Override
<add> public void run() {
<add> cs.onComplete();
<add> }
<add> };
<add>
<add> TestHelper.race(r1, r2);
<add>
<add> to.assertEmpty();
<add> }
<add> }
<add>
<add> @Test
<add> public void onNextInnerErrorRace() {
<add> final TestException ex = new TestException();
<add> for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) {
<add> List<Throwable> errors = TestHelper.trackPluginErrors();
<add> try {
<add> final PublishSubject<Integer> ps = PublishSubject.create();
<add> final CompletableSubject cs = CompletableSubject.create();
<add>
<add> TestObserver<Void> to = ps.switchMapCompletable(Functions.justFunction(cs)).test();
<add>
<add> ps.onNext(1);
<add>
<add> Runnable r1 = new Runnable() {
<add> @Override
<add> public void run() {
<add> ps.onNext(2);
<add> }
<add> };
<add>
<add> Runnable r2 = new Runnable() {
<add> @Override
<add> public void run() {
<add> cs.onError(ex);
<add> }
<add> };
<add>
<add> TestHelper.race(r1, r2);
<add>
<add> to.assertError(new Predicate<Throwable>() {
<add> @Override
<add> public boolean test(Throwable e) throws Exception {
<add> return e instanceof TestException || e instanceof CompositeException;
<add> }
<add> });
<add>
<add> if (!errors.isEmpty()) {
<add> TestHelper.assertUndeliverable(errors, 0, TestException.class);
<add> }
<add> } finally {
<add> RxJavaPlugins.reset();
<add> }
<add> }
<add> }
<add>
<add> @Test
<add> public void onErrorInnerErrorRace() {
<add> final TestException ex0 = new TestException();
<add> final TestException ex = new TestException();
<add> for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) {
<add> List<Throwable> errors = TestHelper.trackPluginErrors();
<add> try {
<add> final PublishSubject<Integer> ps = PublishSubject.create();
<add> final CompletableSubject cs = CompletableSubject.create();
<add>
<add> TestObserver<Void> to = ps.switchMapCompletable(Functions.justFunction(cs)).test();
<add>
<add> ps.onNext(1);
<add>
<add> Runnable r1 = new Runnable() {
<add> @Override
<add> public void run() {
<add> ps.onError(ex0);
<add> }
<add> };
<add>
<add> Runnable r2 = new Runnable() {
<add> @Override
<add> public void run() {
<add> cs.onError(ex);
<add> }
<add> };
<add>
<add> TestHelper.race(r1, r2);
<add>
<add> to.assertError(new Predicate<Throwable>() {
<add> @Override
<add> public boolean test(Throwable e) throws Exception {
<add> return e instanceof TestException || e instanceof CompositeException;
<add> }
<add> });
<add>
<add> if (!errors.isEmpty()) {
<add> TestHelper.assertUndeliverable(errors, 0, TestException.class);
<add> }
<add> } finally {
<add> RxJavaPlugins.reset();
<add> }
<add> }
<add> }
<add>
<add> @Test
<add> public void innerErrorThenMainError() {
<add> List<Throwable> errors = TestHelper.trackPluginErrors();
<add> try {
<add> new Observable<Integer>() {
<add> @Override
<add> protected void subscribeActual(Observer<? super Integer> s) {
<add> s.onSubscribe(Disposables.empty());
<add> s.onNext(1);
<add> s.onError(new TestException("main"));
<add> }
<add> }
<add> .switchMapCompletable(Functions.justFunction(Completable.error(new TestException("inner"))))
<add> .test()
<add> .assertFailureAndMessage(TestException.class, "inner");
<add>
<add> TestHelper.assertUndeliverable(errors, 0, TestException.class, "main");
<add> } finally {
<add> RxJavaPlugins.reset();
<add> }
<add> }
<add>
<add> @Test
<add> public void innerErrorDelayed() {
<add> final PublishSubject<Integer> ps = PublishSubject.create();
<add> final CompletableSubject cs = CompletableSubject.create();
<add>
<add> TestObserver<Void> to = ps.switchMapCompletableDelayError(Functions.justFunction(cs)).test();
<add>
<add> ps.onNext(1);
<add>
<add> cs.onError(new TestException());
<add>
<add> to.assertEmpty();
<add>
<add> assertTrue(ps.hasObservers());
<add>
<add> ps.onComplete();
<add>
<add> to.assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void mainCompletesinnerErrorDelayed() {
<add> final PublishSubject<Integer> ps = PublishSubject.create();
<add> final CompletableSubject cs = CompletableSubject.create();
<add>
<add> TestObserver<Void> to = ps.switchMapCompletableDelayError(Functions.justFunction(cs)).test();
<add>
<add> ps.onNext(1);
<add> ps.onComplete();
<add>
<add> to.assertEmpty();
<add>
<add> cs.onError(new TestException());
<add>
<add> to.assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void mainErrorDelayed() {
<add> final PublishSubject<Integer> ps = PublishSubject.create();
<add> final CompletableSubject cs = CompletableSubject.create();
<add>
<add> TestObserver<Void> to = ps.switchMapCompletableDelayError(Functions.justFunction(cs)).test();
<add>
<add> ps.onNext(1);
<add>
<add> ps.onError(new TestException());
<add>
<add> to.assertEmpty();
<add>
<add> assertTrue(cs.hasObservers());
<add>
<add> cs.onComplete();
<add>
<add> to.assertFailure(TestException.class);
<add> }
<add>}
<ide><path>src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapMaybeTest.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.mixed;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>import java.util.List;
<add>import java.util.concurrent.atomic.AtomicReference;
<add>
<add>import org.junit.Test;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.disposables.Disposables;
<add>import io.reactivex.exceptions.*;
<add>import io.reactivex.functions.*;
<add>import io.reactivex.internal.functions.Functions;
<add>import io.reactivex.observers.TestObserver;
<add>import io.reactivex.plugins.RxJavaPlugins;
<add>import io.reactivex.subjects.*;
<add>
<add>public class ObservableSwitchMapMaybeTest {
<add>
<add> @Test
<add> public void simple() {
<add> Observable.range(1, 5)
<add> .switchMapMaybe(new Function<Integer, MaybeSource<Integer>>() {
<add> @Override
<add> public MaybeSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return Maybe.just(v);
<add> }
<add> })
<add> .test()
<add> .assertResult(1, 2, 3, 4, 5);
<add> }
<add>
<add> @Test
<add> public void simpleEmpty() {
<add> Observable.range(1, 5)
<add> .switchMapMaybe(new Function<Integer, MaybeSource<Integer>>() {
<add> @Override
<add> public MaybeSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return Maybe.empty();
<add> }
<add> })
<add> .test()
<add> .assertResult();
<add> }
<add>
<add> @Test
<add> public void simpleMixed() {
<add> Observable.range(1, 10)
<add> .switchMapMaybe(new Function<Integer, MaybeSource<Integer>>() {
<add> @Override
<add> public MaybeSource<Integer> apply(Integer v)
<add> throws Exception {
<add> if (v % 2 == 0) {
<add> return Maybe.just(v);
<add> }
<add> return Maybe.empty();
<add> }
<add> })
<add> .test()
<add> .assertResult(2, 4, 6, 8, 10);
<add> }
<add>
<add> @Test
<add> public void mainError() {
<add> Observable.error(new TestException())
<add> .switchMapMaybe(Functions.justFunction(Maybe.never()))
<add> .test()
<add> .assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void innerError() {
<add> Observable.just(1)
<add> .switchMapMaybe(Functions.justFunction(Maybe.error(new TestException())))
<add> .test()
<add> .assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void doubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Object>, Observable<Object>>() {
<add> @Override
<add> public Observable<Object> apply(Observable<Object> f)
<add> throws Exception {
<add> return f
<add> .switchMapMaybe(Functions.justFunction(Maybe.never()));
<add> }
<add> }
<add> );
<add> }
<add>
<add> @Test
<add> public void take() {
<add> Observable.range(1, 5)
<add> .switchMapMaybe(new Function<Integer, MaybeSource<Integer>>() {
<add> @Override
<add> public MaybeSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return Maybe.just(v);
<add> }
<add> })
<add> .take(3)
<add> .test()
<add> .assertResult(1, 2, 3);
<add> }
<add>
<add> @Test
<add> public void switchOver() {
<add> PublishSubject<Integer> ps = PublishSubject.create();
<add>
<add> final MaybeSubject<Integer> ms1 = MaybeSubject.create();
<add> final MaybeSubject<Integer> ms2 = MaybeSubject.create();
<add>
<add> TestObserver<Integer> ts = ps.switchMapMaybe(new Function<Integer, MaybeSource<Integer>>() {
<add> @Override
<add> public MaybeSource<Integer> apply(Integer v)
<add> throws Exception {
<add> if (v == 1) {
<add> return ms1;
<add> }
<add> return ms2;
<add> }
<add> }).test();
<add>
<add> ts.assertEmpty();
<add>
<add> ps.onNext(1);
<add>
<add> ts.assertEmpty();
<add>
<add> assertTrue(ms1.hasObservers());
<add>
<add> ps.onNext(2);
<add>
<add> assertFalse(ms1.hasObservers());
<add> assertTrue(ms2.hasObservers());
<add>
<add> ms2.onError(new TestException());
<add>
<add> assertFalse(ps.hasObservers());
<add>
<add> ts.assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void switchOverDelayError() {
<add> PublishSubject<Integer> ps = PublishSubject.create();
<add>
<add> final MaybeSubject<Integer> ms1 = MaybeSubject.create();
<add> final MaybeSubject<Integer> ms2 = MaybeSubject.create();
<add>
<add> TestObserver<Integer> ts = ps.switchMapMaybeDelayError(new Function<Integer, MaybeSource<Integer>>() {
<add> @Override
<add> public MaybeSource<Integer> apply(Integer v)
<add> throws Exception {
<add> if (v == 1) {
<add> return ms1;
<add> }
<add> return ms2;
<add> }
<add> }).test();
<add>
<add> ts.assertEmpty();
<add>
<add> ps.onNext(1);
<add>
<add> ts.assertEmpty();
<add>
<add> assertTrue(ms1.hasObservers());
<add>
<add> ps.onNext(2);
<add>
<add> assertFalse(ms1.hasObservers());
<add> assertTrue(ms2.hasObservers());
<add>
<add> ms2.onError(new TestException());
<add>
<add> ts.assertEmpty();
<add>
<add> assertTrue(ps.hasObservers());
<add>
<add> ps.onComplete();
<add>
<add> ts.assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void mainErrorInnerCompleteDelayError() {
<add> PublishSubject<Integer> ps = PublishSubject.create();
<add>
<add> final MaybeSubject<Integer> ms = MaybeSubject.create();
<add>
<add> TestObserver<Integer> ts = ps.switchMapMaybeDelayError(new Function<Integer, MaybeSource<Integer>>() {
<add> @Override
<add> public MaybeSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return ms;
<add> }
<add> }).test();
<add>
<add> ts.assertEmpty();
<add>
<add> ps.onNext(1);
<add>
<add> ts.assertEmpty();
<add>
<add> assertTrue(ms.hasObservers());
<add>
<add> ps.onError(new TestException());
<add>
<add> assertTrue(ms.hasObservers());
<add>
<add> ts.assertEmpty();
<add>
<add> ms.onComplete();
<add>
<add> ts.assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void mainErrorInnerSuccessDelayError() {
<add> PublishSubject<Integer> ps = PublishSubject.create();
<add>
<add> final MaybeSubject<Integer> ms = MaybeSubject.create();
<add>
<add> TestObserver<Integer> ts = ps.switchMapMaybeDelayError(new Function<Integer, MaybeSource<Integer>>() {
<add> @Override
<add> public MaybeSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return ms;
<add> }
<add> }).test();
<add>
<add> ts.assertEmpty();
<add>
<add> ps.onNext(1);
<add>
<add> ts.assertEmpty();
<add>
<add> assertTrue(ms.hasObservers());
<add>
<add> ps.onError(new TestException());
<add>
<add> assertTrue(ms.hasObservers());
<add>
<add> ts.assertEmpty();
<add>
<add> ms.onSuccess(1);
<add>
<add> ts.assertFailure(TestException.class, 1);
<add> }
<add>
<add> @Test
<add> public void mapperCrash() {
<add> Observable.just(1)
<add> .switchMapMaybe(new Function<Integer, MaybeSource<? extends Object>>() {
<add> @Override
<add> public MaybeSource<? extends Object> apply(Integer v)
<add> throws Exception {
<add> throw new TestException();
<add> }
<add> })
<add> .test()
<add> .assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void disposeBeforeSwitchInOnNext() {
<add> final TestObserver<Integer> ts = new TestObserver<Integer>();
<add>
<add> Observable.just(1)
<add> .switchMapMaybe(new Function<Integer, MaybeSource<Integer>>() {
<add> @Override
<add> public MaybeSource<Integer> apply(Integer v)
<add> throws Exception {
<add> ts.cancel();
<add> return Maybe.just(1);
<add> }
<add> }).subscribe(ts);
<add>
<add> ts.assertEmpty();
<add> }
<add>
<add> @Test
<add> public void disposeOnNextAfterFirst() {
<add> final TestObserver<Integer> ts = new TestObserver<Integer>();
<add>
<add> Observable.just(1, 2)
<add> .switchMapMaybe(new Function<Integer, MaybeSource<Integer>>() {
<add> @Override
<add> public MaybeSource<Integer> apply(Integer v)
<add> throws Exception {
<add> if (v == 2) {
<add> ts.cancel();
<add> }
<add> return Maybe.just(1);
<add> }
<add> }).subscribe(ts);
<add>
<add> ts.assertValue(1)
<add> .assertNoErrors()
<add> .assertNotComplete();
<add> }
<add>
<add> @Test
<add> public void cancel() {
<add> PublishSubject<Integer> ps = PublishSubject.create();
<add>
<add> final MaybeSubject<Integer> ms = MaybeSubject.create();
<add>
<add> TestObserver<Integer> ts = ps.switchMapMaybeDelayError(new Function<Integer, MaybeSource<Integer>>() {
<add> @Override
<add> public MaybeSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return ms;
<add> }
<add> }).test();
<add>
<add> ts.assertEmpty();
<add>
<add> ps.onNext(1);
<add>
<add> ts.assertEmpty();
<add>
<add> assertTrue(ps.hasObservers());
<add> assertTrue(ms.hasObservers());
<add>
<add> ts.cancel();
<add>
<add> assertFalse(ps.hasObservers());
<add> assertFalse(ms.hasObservers());
<add> }
<add>
<add> @Test
<add> public void mainErrorAfterTermination() {
<add> List<Throwable> errors = TestHelper.trackPluginErrors();
<add> try {
<add> new Observable<Integer>() {
<add> @Override
<add> protected void subscribeActual(Observer<? super Integer> s) {
<add> s.onSubscribe(Disposables.empty());
<add> s.onNext(1);
<add> s.onError(new TestException("outer"));
<add> }
<add> }
<add> .switchMapMaybe(new Function<Integer, MaybeSource<Integer>>() {
<add> @Override
<add> public MaybeSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return Maybe.error(new TestException("inner"));
<add> }
<add> })
<add> .test()
<add> .assertFailureAndMessage(TestException.class, "inner");
<add>
<add> TestHelper.assertUndeliverable(errors, 0, TestException.class, "outer");
<add> } finally {
<add> RxJavaPlugins.reset();
<add> }
<add> }
<add>
<add>
<add> @Test
<add> public void innerErrorAfterTermination() {
<add> List<Throwable> errors = TestHelper.trackPluginErrors();
<add> try {
<add> final AtomicReference<MaybeObserver<? super Integer>> moRef = new AtomicReference<MaybeObserver<? super Integer>>();
<add>
<add> TestObserver<Integer> ts = new Observable<Integer>() {
<add> @Override
<add> protected void subscribeActual(Observer<? super Integer> s) {
<add> s.onSubscribe(Disposables.empty());
<add> s.onNext(1);
<add> s.onError(new TestException("outer"));
<add> }
<add> }
<add> .switchMapMaybe(new Function<Integer, MaybeSource<Integer>>() {
<add> @Override
<add> public MaybeSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return new Maybe<Integer>() {
<add> @Override
<add> protected void subscribeActual(
<add> MaybeObserver<? super Integer> observer) {
<add> observer.onSubscribe(Disposables.empty());
<add> moRef.set(observer);
<add> }
<add> };
<add> }
<add> })
<add> .test();
<add>
<add> ts.assertFailureAndMessage(TestException.class, "outer");
<add>
<add> moRef.get().onError(new TestException("inner"));
<add> moRef.get().onComplete();
<add>
<add> TestHelper.assertUndeliverable(errors, 0, TestException.class, "inner");
<add> } finally {
<add> RxJavaPlugins.reset();
<add> }
<add> }
<add>
<add> @Test
<add> public void nextCancelRace() {
<add> for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) {
<add>
<add> final PublishSubject<Integer> ps = PublishSubject.create();
<add>
<add> final MaybeSubject<Integer> ms = MaybeSubject.create();
<add>
<add> final TestObserver<Integer> ts = ps.switchMapMaybeDelayError(new Function<Integer, MaybeSource<Integer>>() {
<add> @Override
<add> public MaybeSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return ms;
<add> }
<add> }).test();
<add>
<add> Runnable r1 = new Runnable() {
<add> @Override
<add> public void run() {
<add> ps.onNext(1);
<add> }
<add> };
<add>
<add> Runnable r2 = new Runnable() {
<add> @Override
<add> public void run() {
<add> ts.cancel();
<add> }
<add> };
<add>
<add> TestHelper.race(r1, r2);
<add>
<add> ts.assertNoErrors()
<add> .assertNotComplete();
<add> }
<add> }
<add>
<add> @Test
<add> public void nextInnerErrorRace() {
<add> final TestException ex = new TestException();
<add>
<add> for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) {
<add>
<add> List<Throwable> errors = TestHelper.trackPluginErrors();
<add> try {
<add> final PublishSubject<Integer> ps = PublishSubject.create();
<add>
<add> final MaybeSubject<Integer> ms = MaybeSubject.create();
<add>
<add> final TestObserver<Integer> ts = ps.switchMapMaybeDelayError(new Function<Integer, MaybeSource<Integer>>() {
<add> @Override
<add> public MaybeSource<Integer> apply(Integer v)
<add> throws Exception {
<add> if (v == 1) {
<add> return ms;
<add> }
<add> return Maybe.never();
<add> }
<add> }).test();
<add>
<add> ps.onNext(1);
<add>
<add> Runnable r1 = new Runnable() {
<add> @Override
<add> public void run() {
<add> ps.onNext(2);
<add> }
<add> };
<add>
<add> Runnable r2 = new Runnable() {
<add> @Override
<add> public void run() {
<add> ms.onError(ex);
<add> }
<add> };
<add>
<add> TestHelper.race(r1, r2);
<add>
<add> if (ts.errorCount() != 0) {
<add> assertTrue(errors.isEmpty());
<add> ts.assertFailure(TestException.class);
<add> } else if (!errors.isEmpty()) {
<add> TestHelper.assertUndeliverable(errors, 0, TestException.class);
<add> }
<add> } finally {
<add> RxJavaPlugins.reset();
<add> }
<add> }
<add> }
<add>
<add> @Test
<add> public void mainErrorInnerErrorRace() {
<add> final TestException ex = new TestException();
<add> final TestException ex2 = new TestException();
<add>
<add> for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) {
<add>
<add> List<Throwable> errors = TestHelper.trackPluginErrors();
<add> try {
<add> final PublishSubject<Integer> ps = PublishSubject.create();
<add>
<add> final MaybeSubject<Integer> ms = MaybeSubject.create();
<add>
<add> final TestObserver<Integer> ts = ps.switchMapMaybeDelayError(new Function<Integer, MaybeSource<Integer>>() {
<add> @Override
<add> public MaybeSource<Integer> apply(Integer v)
<add> throws Exception {
<add> if (v == 1) {
<add> return ms;
<add> }
<add> return Maybe.never();
<add> }
<add> }).test();
<add>
<add> ps.onNext(1);
<add>
<add> Runnable r1 = new Runnable() {
<add> @Override
<add> public void run() {
<add> ps.onError(ex);
<add> }
<add> };
<add>
<add> Runnable r2 = new Runnable() {
<add> @Override
<add> public void run() {
<add> ms.onError(ex2);
<add> }
<add> };
<add>
<add> TestHelper.race(r1, r2);
<add>
<add> ts.assertError(new Predicate<Throwable>() {
<add> @Override
<add> public boolean test(Throwable e) throws Exception {
<add> return e instanceof TestException || e instanceof CompositeException;
<add> }
<add> });
<add>
<add> if (!errors.isEmpty()) {
<add> TestHelper.assertUndeliverable(errors, 0, TestException.class);
<add> }
<add> } finally {
<add> RxJavaPlugins.reset();
<add> }
<add> }
<add> }
<add>
<add> @Test
<add> public void nextInnerSuccessRace() {
<add> for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) {
<add>
<add> final PublishSubject<Integer> ps = PublishSubject.create();
<add>
<add> final MaybeSubject<Integer> ms = MaybeSubject.create();
<add>
<add> final TestObserver<Integer> ts = ps.switchMapMaybeDelayError(new Function<Integer, MaybeSource<Integer>>() {
<add> @Override
<add> public MaybeSource<Integer> apply(Integer v)
<add> throws Exception {
<add> if (v == 1) {
<add> return ms;
<add> }
<add> return Maybe.empty();
<add> }
<add> }).test();
<add>
<add> ps.onNext(1);
<add>
<add> Runnable r1 = new Runnable() {
<add> @Override
<add> public void run() {
<add> ps.onNext(2);
<add> }
<add> };
<add>
<add> Runnable r2 = new Runnable() {
<add> @Override
<add> public void run() {
<add> ms.onSuccess(3);
<add> }
<add> };
<add>
<add> TestHelper.race(r1, r2);
<add>
<add> ts.assertNoErrors()
<add> .assertNotComplete();
<add> }
<add> }
<add>
<add> @Test
<add> public void checkDisposed() {
<add> PublishSubject<Integer> ps = PublishSubject.create();
<add> MaybeSubject<Integer> ms = MaybeSubject.create();
<add>
<add> TestHelper.checkDisposed(ps.switchMapMaybe(Functions.justFunction(ms)));
<add> }
<add>
<add> @Test
<add> public void drainReentrant() {
<add> final PublishSubject<Integer> ps = PublishSubject.create();
<add>
<add> TestObserver<Integer> to = new TestObserver<Integer>() {
<add> @Override
<add> public void onNext(Integer t) {
<add> super.onNext(t);
<add> if (t == 1) {
<add> ps.onNext(2);
<add> }
<add> }
<add> };
<add>
<add> ps.switchMapMaybe(new Function<Integer, MaybeSource<Integer>>() {
<add> @Override
<add> public MaybeSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return Maybe.just(v);
<add> }
<add> }).subscribe(to);
<add>
<add> ps.onNext(1);
<add> ps.onComplete();
<add>
<add> to.assertResult(1, 2);
<add> }
<add>}
<ide><path>src/test/java/io/reactivex/internal/operators/mixed/ObservableSwitchMapSingleTest.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.mixed;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>import java.util.List;
<add>import java.util.concurrent.atomic.AtomicReference;
<add>
<add>import org.junit.Test;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.disposables.Disposables;
<add>import io.reactivex.exceptions.*;
<add>import io.reactivex.functions.*;
<add>import io.reactivex.internal.functions.Functions;
<add>import io.reactivex.observers.TestObserver;
<add>import io.reactivex.plugins.RxJavaPlugins;
<add>import io.reactivex.subjects.*;
<add>
<add>public class ObservableSwitchMapSingleTest {
<add>
<add> @Test
<add> public void simple() {
<add> Observable.range(1, 5)
<add> .switchMapSingle(new Function<Integer, SingleSource<Integer>>() {
<add> @Override
<add> public SingleSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return Single.just(v);
<add> }
<add> })
<add> .test()
<add> .assertResult(1, 2, 3, 4, 5);
<add> }
<add>
<add> @Test
<add> public void mainError() {
<add> Observable.error(new TestException())
<add> .switchMapSingle(Functions.justFunction(Single.never()))
<add> .test()
<add> .assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void innerError() {
<add> Observable.just(1)
<add> .switchMapSingle(Functions.justFunction(Single.error(new TestException())))
<add> .test()
<add> .assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void doubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Object>, Observable<Object>>() {
<add> @Override
<add> public Observable<Object> apply(Observable<Object> f)
<add> throws Exception {
<add> return f
<add> .switchMapSingle(Functions.justFunction(Single.never()));
<add> }
<add> }
<add> );
<add> }
<add>
<add> @Test
<add> public void take() {
<add> Observable.range(1, 5)
<add> .switchMapSingle(new Function<Integer, SingleSource<Integer>>() {
<add> @Override
<add> public SingleSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return Single.just(v);
<add> }
<add> })
<add> .take(3)
<add> .test()
<add> .assertResult(1, 2, 3);
<add> }
<add>
<add> @Test
<add> public void switchOver() {
<add> PublishSubject<Integer> ps = PublishSubject.create();
<add>
<add> final SingleSubject<Integer> ms1 = SingleSubject.create();
<add> final SingleSubject<Integer> ms2 = SingleSubject.create();
<add>
<add> TestObserver<Integer> ts = ps.switchMapSingle(new Function<Integer, SingleSource<Integer>>() {
<add> @Override
<add> public SingleSource<Integer> apply(Integer v)
<add> throws Exception {
<add> if (v == 1) {
<add> return ms1;
<add> }
<add> return ms2;
<add> }
<add> }).test();
<add>
<add> ts.assertEmpty();
<add>
<add> ps.onNext(1);
<add>
<add> ts.assertEmpty();
<add>
<add> assertTrue(ms1.hasObservers());
<add>
<add> ps.onNext(2);
<add>
<add> assertFalse(ms1.hasObservers());
<add> assertTrue(ms2.hasObservers());
<add>
<add> ms2.onError(new TestException());
<add>
<add> assertFalse(ps.hasObservers());
<add>
<add> ts.assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void switchOverDelayError() {
<add> PublishSubject<Integer> ps = PublishSubject.create();
<add>
<add> final SingleSubject<Integer> ms1 = SingleSubject.create();
<add> final SingleSubject<Integer> ms2 = SingleSubject.create();
<add>
<add> TestObserver<Integer> ts = ps.switchMapSingleDelayError(new Function<Integer, SingleSource<Integer>>() {
<add> @Override
<add> public SingleSource<Integer> apply(Integer v)
<add> throws Exception {
<add> if (v == 1) {
<add> return ms1;
<add> }
<add> return ms2;
<add> }
<add> }).test();
<add>
<add> ts.assertEmpty();
<add>
<add> ps.onNext(1);
<add>
<add> ts.assertEmpty();
<add>
<add> assertTrue(ms1.hasObservers());
<add>
<add> ps.onNext(2);
<add>
<add> assertFalse(ms1.hasObservers());
<add> assertTrue(ms2.hasObservers());
<add>
<add> ms2.onError(new TestException());
<add>
<add> ts.assertEmpty();
<add>
<add> assertTrue(ps.hasObservers());
<add>
<add> ps.onComplete();
<add>
<add> ts.assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void mainErrorInnerCompleteDelayError() {
<add> PublishSubject<Integer> ps = PublishSubject.create();
<add>
<add> final SingleSubject<Integer> ms = SingleSubject.create();
<add>
<add> TestObserver<Integer> ts = ps.switchMapSingleDelayError(new Function<Integer, SingleSource<Integer>>() {
<add> @Override
<add> public SingleSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return ms;
<add> }
<add> }).test();
<add>
<add> ts.assertEmpty();
<add>
<add> ps.onNext(1);
<add>
<add> ts.assertEmpty();
<add>
<add> assertTrue(ms.hasObservers());
<add>
<add> ps.onError(new TestException());
<add>
<add> assertTrue(ms.hasObservers());
<add>
<add> ts.assertEmpty();
<add>
<add> ms.onSuccess(1);
<add>
<add> ts.assertFailure(TestException.class, 1);
<add> }
<add>
<add> @Test
<add> public void mainErrorInnerSuccessDelayError() {
<add> PublishSubject<Integer> ps = PublishSubject.create();
<add>
<add> final SingleSubject<Integer> ms = SingleSubject.create();
<add>
<add> TestObserver<Integer> ts = ps.switchMapSingleDelayError(new Function<Integer, SingleSource<Integer>>() {
<add> @Override
<add> public SingleSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return ms;
<add> }
<add> }).test();
<add>
<add> ts.assertEmpty();
<add>
<add> ps.onNext(1);
<add>
<add> ts.assertEmpty();
<add>
<add> assertTrue(ms.hasObservers());
<add>
<add> ps.onError(new TestException());
<add>
<add> assertTrue(ms.hasObservers());
<add>
<add> ts.assertEmpty();
<add>
<add> ms.onSuccess(1);
<add>
<add> ts.assertFailure(TestException.class, 1);
<add> }
<add>
<add> @Test
<add> public void mapperCrash() {
<add> Observable.just(1)
<add> .switchMapSingle(new Function<Integer, SingleSource<? extends Object>>() {
<add> @Override
<add> public SingleSource<? extends Object> apply(Integer v)
<add> throws Exception {
<add> throw new TestException();
<add> }
<add> })
<add> .test()
<add> .assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void disposeBeforeSwitchInOnNext() {
<add> final TestObserver<Integer> ts = new TestObserver<Integer>();
<add>
<add> Observable.just(1)
<add> .switchMapSingle(new Function<Integer, SingleSource<Integer>>() {
<add> @Override
<add> public SingleSource<Integer> apply(Integer v)
<add> throws Exception {
<add> ts.cancel();
<add> return Single.just(1);
<add> }
<add> }).subscribe(ts);
<add>
<add> ts.assertEmpty();
<add> }
<add>
<add> @Test
<add> public void disposeOnNextAfterFirst() {
<add> final TestObserver<Integer> ts = new TestObserver<Integer>();
<add>
<add> Observable.just(1, 2)
<add> .switchMapSingle(new Function<Integer, SingleSource<Integer>>() {
<add> @Override
<add> public SingleSource<Integer> apply(Integer v)
<add> throws Exception {
<add> if (v == 2) {
<add> ts.cancel();
<add> }
<add> return Single.just(1);
<add> }
<add> }).subscribe(ts);
<add>
<add> ts.assertValue(1)
<add> .assertNoErrors()
<add> .assertNotComplete();
<add> }
<add>
<add> @Test
<add> public void cancel() {
<add> PublishSubject<Integer> ps = PublishSubject.create();
<add>
<add> final SingleSubject<Integer> ms = SingleSubject.create();
<add>
<add> TestObserver<Integer> ts = ps.switchMapSingleDelayError(new Function<Integer, SingleSource<Integer>>() {
<add> @Override
<add> public SingleSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return ms;
<add> }
<add> }).test();
<add>
<add> ts.assertEmpty();
<add>
<add> ps.onNext(1);
<add>
<add> ts.assertEmpty();
<add>
<add> assertTrue(ps.hasObservers());
<add> assertTrue(ms.hasObservers());
<add>
<add> ts.cancel();
<add>
<add> assertFalse(ps.hasObservers());
<add> assertFalse(ms.hasObservers());
<add> }
<add>
<add> @Test
<add> public void mainErrorAfterTermination() {
<add> List<Throwable> errors = TestHelper.trackPluginErrors();
<add> try {
<add> new Observable<Integer>() {
<add> @Override
<add> protected void subscribeActual(Observer<? super Integer> s) {
<add> s.onSubscribe(Disposables.empty());
<add> s.onNext(1);
<add> s.onError(new TestException("outer"));
<add> }
<add> }
<add> .switchMapSingle(new Function<Integer, SingleSource<Integer>>() {
<add> @Override
<add> public SingleSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return Single.error(new TestException("inner"));
<add> }
<add> })
<add> .test()
<add> .assertFailureAndMessage(TestException.class, "inner");
<add>
<add> TestHelper.assertUndeliverable(errors, 0, TestException.class, "outer");
<add> } finally {
<add> RxJavaPlugins.reset();
<add> }
<add> }
<add>
<add>
<add> @Test
<add> public void innerErrorAfterTermination() {
<add> List<Throwable> errors = TestHelper.trackPluginErrors();
<add> try {
<add> final AtomicReference<SingleObserver<? super Integer>> moRef = new AtomicReference<SingleObserver<? super Integer>>();
<add>
<add> TestObserver<Integer> ts = new Observable<Integer>() {
<add> @Override
<add> protected void subscribeActual(Observer<? super Integer> s) {
<add> s.onSubscribe(Disposables.empty());
<add> s.onNext(1);
<add> s.onError(new TestException("outer"));
<add> }
<add> }
<add> .switchMapSingle(new Function<Integer, SingleSource<Integer>>() {
<add> @Override
<add> public SingleSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return new Single<Integer>() {
<add> @Override
<add> protected void subscribeActual(
<add> SingleObserver<? super Integer> observer) {
<add> observer.onSubscribe(Disposables.empty());
<add> moRef.set(observer);
<add> }
<add> };
<add> }
<add> })
<add> .test();
<add>
<add> ts.assertFailureAndMessage(TestException.class, "outer");
<add>
<add> moRef.get().onError(new TestException("inner"));
<add>
<add> TestHelper.assertUndeliverable(errors, 0, TestException.class, "inner");
<add> } finally {
<add> RxJavaPlugins.reset();
<add> }
<add> }
<add>
<add> @Test
<add> public void nextCancelRace() {
<add> for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) {
<add>
<add> final PublishSubject<Integer> ps = PublishSubject.create();
<add>
<add> final SingleSubject<Integer> ms = SingleSubject.create();
<add>
<add> final TestObserver<Integer> ts = ps.switchMapSingleDelayError(new Function<Integer, SingleSource<Integer>>() {
<add> @Override
<add> public SingleSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return ms;
<add> }
<add> }).test();
<add>
<add> Runnable r1 = new Runnable() {
<add> @Override
<add> public void run() {
<add> ps.onNext(1);
<add> }
<add> };
<add>
<add> Runnable r2 = new Runnable() {
<add> @Override
<add> public void run() {
<add> ts.cancel();
<add> }
<add> };
<add>
<add> TestHelper.race(r1, r2);
<add>
<add> ts.assertNoErrors()
<add> .assertNotComplete();
<add> }
<add> }
<add>
<add> @Test
<add> public void nextInnerErrorRace() {
<add> final TestException ex = new TestException();
<add>
<add> for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) {
<add>
<add> List<Throwable> errors = TestHelper.trackPluginErrors();
<add> try {
<add> final PublishSubject<Integer> ps = PublishSubject.create();
<add>
<add> final SingleSubject<Integer> ms = SingleSubject.create();
<add>
<add> final TestObserver<Integer> ts = ps.switchMapSingleDelayError(new Function<Integer, SingleSource<Integer>>() {
<add> @Override
<add> public SingleSource<Integer> apply(Integer v)
<add> throws Exception {
<add> if (v == 1) {
<add> return ms;
<add> }
<add> return Single.never();
<add> }
<add> }).test();
<add>
<add> ps.onNext(1);
<add>
<add> Runnable r1 = new Runnable() {
<add> @Override
<add> public void run() {
<add> ps.onNext(2);
<add> }
<add> };
<add>
<add> Runnable r2 = new Runnable() {
<add> @Override
<add> public void run() {
<add> ms.onError(ex);
<add> }
<add> };
<add>
<add> TestHelper.race(r1, r2);
<add>
<add> if (ts.errorCount() != 0) {
<add> assertTrue(errors.isEmpty());
<add> ts.assertFailure(TestException.class);
<add> } else if (!errors.isEmpty()) {
<add> TestHelper.assertUndeliverable(errors, 0, TestException.class);
<add> }
<add> } finally {
<add> RxJavaPlugins.reset();
<add> }
<add> }
<add> }
<add>
<add> @Test
<add> public void mainErrorInnerErrorRace() {
<add> final TestException ex = new TestException();
<add> final TestException ex2 = new TestException();
<add>
<add> for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) {
<add>
<add> List<Throwable> errors = TestHelper.trackPluginErrors();
<add> try {
<add> final PublishSubject<Integer> ps = PublishSubject.create();
<add>
<add> final SingleSubject<Integer> ms = SingleSubject.create();
<add>
<add> final TestObserver<Integer> ts = ps.switchMapSingleDelayError(new Function<Integer, SingleSource<Integer>>() {
<add> @Override
<add> public SingleSource<Integer> apply(Integer v)
<add> throws Exception {
<add> if (v == 1) {
<add> return ms;
<add> }
<add> return Single.never();
<add> }
<add> }).test();
<add>
<add> ps.onNext(1);
<add>
<add> Runnable r1 = new Runnable() {
<add> @Override
<add> public void run() {
<add> ps.onError(ex);
<add> }
<add> };
<add>
<add> Runnable r2 = new Runnable() {
<add> @Override
<add> public void run() {
<add> ms.onError(ex2);
<add> }
<add> };
<add>
<add> TestHelper.race(r1, r2);
<add>
<add> ts.assertError(new Predicate<Throwable>() {
<add> @Override
<add> public boolean test(Throwable e) throws Exception {
<add> return e instanceof TestException || e instanceof CompositeException;
<add> }
<add> });
<add>
<add> if (!errors.isEmpty()) {
<add> TestHelper.assertUndeliverable(errors, 0, TestException.class);
<add> }
<add> } finally {
<add> RxJavaPlugins.reset();
<add> }
<add> }
<add> }
<add>
<add> @Test
<add> public void nextInnerSuccessRace() {
<add> for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) {
<add>
<add> final PublishSubject<Integer> ps = PublishSubject.create();
<add>
<add> final SingleSubject<Integer> ms = SingleSubject.create();
<add>
<add> final TestObserver<Integer> ts = ps.switchMapSingleDelayError(new Function<Integer, SingleSource<Integer>>() {
<add> @Override
<add> public SingleSource<Integer> apply(Integer v)
<add> throws Exception {
<add> if (v == 1) {
<add> return ms;
<add> }
<add> return Single.never();
<add> }
<add> }).test();
<add>
<add> ps.onNext(1);
<add>
<add> Runnable r1 = new Runnable() {
<add> @Override
<add> public void run() {
<add> ps.onNext(2);
<add> }
<add> };
<add>
<add> Runnable r2 = new Runnable() {
<add> @Override
<add> public void run() {
<add> ms.onSuccess(3);
<add> }
<add> };
<add>
<add> TestHelper.race(r1, r2);
<add>
<add> ts.assertNoErrors()
<add> .assertNotComplete();
<add> }
<add> }
<add>
<add> @Test
<add> public void checkDisposed() {
<add> PublishSubject<Integer> ps = PublishSubject.create();
<add> SingleSubject<Integer> ms = SingleSubject.create();
<add>
<add> TestHelper.checkDisposed(ps.switchMapSingle(Functions.justFunction(ms)));
<add> }
<add>
<add> @Test
<add> public void drainReentrant() {
<add> final PublishSubject<Integer> ps = PublishSubject.create();
<add>
<add> TestObserver<Integer> to = new TestObserver<Integer>() {
<add> @Override
<add> public void onNext(Integer t) {
<add> super.onNext(t);
<add> if (t == 1) {
<add> ps.onNext(2);
<add> }
<add> }
<add> };
<add>
<add> ps.switchMapSingle(new Function<Integer, SingleSource<Integer>>() {
<add> @Override
<add> public SingleSource<Integer> apply(Integer v)
<add> throws Exception {
<add> return Single.just(v);
<add> }
<add> }).subscribe(to);
<add>
<add> ps.onNext(1);
<add> ps.onComplete();
<add>
<add> to.assertResult(1, 2);
<add> }
<add>}
<ide><path>src/test/java/io/reactivex/tck/ConcatMapMaybeTckTest.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.tck;
<add>
<add>import org.reactivestreams.Publisher;
<add>import org.testng.annotations.Test;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.functions.Function;
<add>
<add>@Test
<add>public class ConcatMapMaybeTckTest extends BaseTck<Integer> {
<add>
<add> @Override
<add> public Publisher<Integer> createPublisher(long elements) {
<add> return
<add> Flowable.range(0, (int)elements)
<add> .concatMapMaybe(new Function<Integer, Maybe<Integer>>() {
<add> @Override
<add> public Maybe<Integer> apply(Integer v) throws Exception {
<add> return Maybe.just(v);
<add> }
<add> })
<add> ;
<add> }
<add>}
<ide><path>src/test/java/io/reactivex/tck/ConcatMapSingleTckTest.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.tck;
<add>
<add>import org.reactivestreams.Publisher;
<add>import org.testng.annotations.Test;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.functions.Function;
<add>
<add>@Test
<add>public class ConcatMapSingleTckTest extends BaseTck<Integer> {
<add>
<add> @Override
<add> public Publisher<Integer> createPublisher(long elements) {
<add> return
<add> Flowable.range(0, (int)elements)
<add> .concatMapSingle(new Function<Integer, Single<Integer>>() {
<add> @Override
<add> public Single<Integer> apply(Integer v) throws Exception {
<add> return Single.just(v);
<add> }
<add> })
<add> ;
<add> }
<add>} | 19 |
Python | Python | remove an unnecessary indexing | 7c5380d61e31db60f44bdc86047c71f2b1f63458 | <ide><path>numpy/_array_api/_creation_functions.py
<ide> def full(shape: Union[int, Tuple[int, ...]], fill_value: Union[int, float], *, d
<ide> # Note: Device support is not yet implemented on Array
<ide> raise NotImplementedError("Device support is not yet implemented")
<ide> if isinstance(fill_value, Array) and fill_value.ndim == 0:
<del> fill_value = fill_value._array[...]
<add> fill_value = fill_value._array
<ide> res = np.full(shape, fill_value, dtype=dtype)
<ide> if res.dtype not in _all_dtypes:
<ide> # This will happen if the fill value is not something that NumPy | 1 |
Text | Text | fix typo in readme.md | 3ef5d575f33b0ae9ccd65521f298e2c39b335623 | <ide><path>README.md
<ide> The Node.js project maintains multiple types of releases:
<ide> and security. Every second Stable release line (major version) will become an
<ide> LTS line and receive 18 months of _Active LTS_ support and a further 12
<ide> months of _Maintenance_. LTS release lines are given alphabetically
<del> ordered codenames, begining with v4 Argon. LTS releases are less frequent
<add> ordered codenames, beginning with v4 Argon. LTS releases are less frequent
<ide> and will attempt to maintain consistent major and minor version numbers,
<ide> only incrementing patch version numbers. There are no breaking changes or
<ide> feature additions, except in some special circumstances. More information | 1 |
Python | Python | fix examples/mnist_net2net.py for keras 2 | f569c75b7dfd3d7ccc3510a8717fb4f63a603a7b | <ide><path>examples/mnist_net2net.py
<ide> - Net2WiderNet experiment:
<ide> + Student model has a wider Conv2D layer and a wider FC layer.
<ide> + Comparison of 'random-padding' vs 'net2wider' weight initialization.
<del> + With both methods, student model should immediately perform as well as
<add> + With both methods, after 1 epoch, student model should perform as well as
<ide> teacher model, but 'net2wider' is slightly better.
<ide> - Net2DeeperNet experiment:
<ide> + Student model has an extra Conv2D layer and an extra FC layer.
<ide> + Comparison of 'random-init' vs 'net2deeper' weight initialization.
<del> + Starting performance of 'net2deeper' is better than 'random-init'.
<add> + After 1 epoch, performance of 'net2deeper' is better than 'random-init'.
<ide> - Hyper-parameters:
<ide> + SGD with momentum=0.9 is used for training teacher and student models.
<ide> + Learning rate adjustment: it's suggested to reduce learning rate
<ide> when a Dropout layer is used.
<ide>
<ide> Results
<del>- Tested with 'Theano' backend and 'channels_first' image_data_format.
<del>- Running on GPU GeForce GTX 980M
<add>- Tested with TF backend and 'channels_last' image_data_format.
<add>- Running on GPU GeForce GTX Titan X Maxwell
<ide> - Performance Comparisons - validation loss values during first 3 epochs:
<del>(1) teacher_model: 0.075 0.041 0.041
<del>(2) wider_random_pad: 0.036 0.034 0.032
<del>(3) wider_net2wider: 0.032 0.030 0.030
<del>(4) deeper_random_init: 0.061 0.043 0.041
<del>(5) deeper_net2deeper: 0.032 0.031 0.029
<add>
<add>Experiment of Net2WiderNet ...
<add>(1) teacher_model: 0.0537 0.0354 0.0356
<add>(2) wider_random_pad: 0.0320 0.0317 0.0289
<add>(3) wider_net2wider: 0.0271 0.0274 0.0270
<add>
<add>Experiment of Net2DeeperNet ...
<add>(4) teacher_model: 0.0522 0.0386 0.0358
<add>(5) deeper_random_init: 0.0682 0.0506 0.0468
<add>(4) deeper_net2deeper: 0.0292 0.0294 0.0286
<ide> '''
<ide>
<ide> from __future__ import print_function
<ide> def wider2net_conv2d(teacher_w1, teacher_b1, teacher_w2, new_width, init):
<ide> '''
<ide> assert teacher_w1.shape[0] == teacher_w2.shape[1], (
<ide> 'successive layers from teacher model should have compatible shapes')
<del> assert teacher_w1.shape[0] == teacher_b1.shape[0], (
<add> assert teacher_w1.shape[3] == teacher_b1.shape[0], (
<ide> 'weight and bias from same layer should have compatible shapes')
<del> assert new_width > teacher_w1.shape[0], (
<add> assert new_width > teacher_w1.shape[3], (
<ide> 'new width (filters) should be bigger than the existing one')
<ide>
<del> n = new_width - teacher_w1.shape[0]
<add> n = new_width - teacher_w1.shape[3]
<ide> if init == 'random-pad':
<del> new_w1 = np.random.normal(0, 0.1, size=(n, ) + teacher_w1.shape[1:])
<add> new_w1 = np.random.normal(0, 0.1, size=teacher_w1.shape[:3] + (n,))
<ide> new_b1 = np.ones(n) * 0.1
<del> new_w2 = np.random.normal(0, 0.1, size=(
<del> teacher_w2.shape[0], n) + teacher_w2.shape[2:])
<add> new_w2 = np.random.normal(0, 0.1,
<add> size=teacher_w2.shape[:2] + (n, teacher_w2.shape[3]))
<ide> elif init == 'net2wider':
<del> index = np.random.randint(teacher_w1.shape[0], size=n)
<add> index = np.random.randint(teacher_w1.shape[3], size=n)
<ide> factors = np.bincount(index)[index] + 1.
<del> new_w1 = teacher_w1[index, :, :, :]
<add> new_w1 = teacher_w1[:, :, :, index]
<ide> new_b1 = teacher_b1[index]
<del> new_w2 = teacher_w2[:, index, :, :] / factors.reshape((1, -1, 1, 1))
<add> new_w2 = teacher_w2[:, :, index, :] / factors.reshape((1, 1, -1, 1))
<ide> else:
<ide> raise ValueError('Unsupported weight initializer: %s' % init)
<ide>
<del> student_w1 = np.concatenate((teacher_w1, new_w1), axis=0)
<add> student_w1 = np.concatenate((teacher_w1, new_w1), axis=3)
<ide> if init == 'random-pad':
<del> student_w2 = np.concatenate((teacher_w2, new_w2), axis=1)
<add> student_w2 = np.concatenate((teacher_w2, new_w2), axis=2)
<ide> elif init == 'net2wider':
<ide> # add small noise to break symmetry, so that student model will have
<ide> # full capacity later
<ide> noise = np.random.normal(0, 5e-2 * new_w2.std(), size=new_w2.shape)
<del> student_w2 = np.concatenate((teacher_w2, new_w2 + noise), axis=1)
<del> student_w2[:, index, :, :] = new_w2
<add> student_w2 = np.concatenate((teacher_w2, new_w2 + noise), axis=2)
<add> student_w2[:, :, index, :] = new_w2
<ide> student_b1 = np.concatenate((teacher_b1, new_b1), axis=0)
<ide>
<ide> return student_w1, student_b1, student_w2
<ide> def deeper2net_conv2d(teacher_w):
<ide>
<ide> # Arguments
<ide> teacher_w: `weight` of previous conv2d layer,
<del> of shape (filters, num_channel, kh, kw)
<add> of shape (kh, kw, num_channel, filters)
<ide> '''
<del> filters, num_channel, kh, kw = teacher_w.shape
<del> student_w = np.zeros((filters, filters, kh, kw))
<add> kh, kw, num_channel, filters = teacher_w.shape
<add> student_w = np.zeros_like(teacher_w)
<ide> for i in range(filters):
<del> student_w[i, i, (kh - 1) / 2, (kw - 1) / 2] = 1.
<add> student_w[(kh - 1) / 2, (kw - 1) / 2, i, i] = 1.
<ide> student_b = np.zeros(filters)
<ide> return student_w, student_b
<ide> | 1 |
Ruby | Ruby | remove ignored flag, fixes warnings | 9c4532bf74604ae1c52a44d1aa8c1022a312ff88 | <ide><path>actionpack/lib/action_dispatch/middleware/remote_ip.rb
<ide> def initialize(app, check_ip_spoofing = true, custom_proxies = nil)
<ide> @app = app
<ide> @check_ip_spoofing = check_ip_spoofing
<ide> if custom_proxies
<del> custom_regexp = Regexp.new(custom_proxies, "i")
<add> custom_regexp = Regexp.new(custom_proxies)
<ide> @trusted_proxies = Regexp.union(TRUSTED_PROXIES, custom_regexp)
<ide> else
<ide> @trusted_proxies = TRUSTED_PROXIES | 1 |
Javascript | Javascript | improve tests related to custom `tostring` | f5917763130e2dedeb02ee4a09bc19323d1c1675 | <ide><path>test/ng/filter/filterSpec.js
<ide> describe('Filter: filter', function() {
<ide>
<ide> describe('should support comparator', function() {
<ide>
<del> it('not consider `object === "[object Object]"` in non-strict comparison', function() {
<add> it('not consider objects without a custom `toString` in non-strict comparison', function() {
<ide> var items = [{test: {}}];
<ide> var expr = '[object';
<ide> expect(filter(items, expr).length).toBe(0);
<ide> });
<ide>
<ide>
<del> it('should consider custom `toString()` in non-strict comparison', function() {
<add> it('should consider objects with custom `toString()` in non-strict comparison', function() {
<ide> var obj = new Date(1970, 0);
<ide> var items = [{test: obj}];
<ide> expect(filter(items, '1970').length).toBe(1);
<ide> expect(filter(items, 1970).length).toBe(1);
<ide>
<del> obj = {};
<del> obj.toString = function() { return 'custom'; };
<add> obj = {
<add> toString: function() { return 'custom'; }
<add> };
<ide> items = [{test: obj}];
<ide> expect(filter(items, 'custom').length).toBe(1);
<ide> });
<ide>
<ide>
<del> it('should not throw on missing `toString()` in non-strict comparison', function() {
<add> it('should cope with objects that have no `toString()` in non-strict comparison', function() {
<ide> var obj = Object.create(null);
<ide> var items = [{test: obj}];
<ide> expect(function() {
<ide> describe('Filter: filter', function() {
<ide> });
<ide>
<ide>
<add> it('should cope with objects where `toString` is not a function in non-strict comparison', function() {
<add> var obj = {
<add> toString: 'moo'
<add> };
<add> var items = [{test: obj}];
<add> expect(function() {
<add> filter(items, 'foo');
<add> }).not.toThrow();
<add> expect(filter(items, 'foo').length).toBe(0);
<add> });
<add>
<add>
<ide> it('as equality when true', function() {
<ide> var items = ['misko', 'adam', 'adamson'];
<ide> var expr = 'adam'; | 1 |
Text | Text | add docs for new prop types | 30646c9c1e207f813d97465068f03ea401353b20 | <ide><path>docs/docs/05-reusable-components.md
<ide> React.createClass({
<ide>
<ide> // You can ensure that your prop is limited to specific values by treating
<ide> // it as an enum.
<del> optionalEnum: React.PropTypes.oneOf(['News','Photos']),
<add> optionalEnum: React.PropTypes.oneOf(['News', 'Photos']),
<ide>
<del> // Expect an array of a certain propType
<add> // An object that could be one of many types
<add> optionalUnion: React.PropTypes.oneOfType([
<add> React.PropTypes.string,
<add> React.PropTypes.number
<add> ])
<add>
<add> // An array of a certain type
<ide> optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number)
<ide>
<add> // An object taking on a particular shape
<add> optionalObjectWithShape: React.PropTypes.shape({
<add> color: React.PropTypes.string,
<add> fontSize: React.PropTypes.number
<add> }),
<add>
<ide> // You can also declare that a prop is an instance of a class. This uses
<ide> // JS's instanceof operator.
<ide> someClass: React.PropTypes.instanceOf(SomeClass),
<ide> React.createClass({
<ide> // shown if the prop isn't provided.
<ide> requiredFunc: React.PropTypes.func.isRequired
<ide>
<add> // An object of any kind
<add> requiredAny: React.PropTypes.any.isRequired
<add>
<ide> // You can also specify a custom validator.
<ide> customProp: function(props, propName, componentName) {
<ide> if (!/matchme/.test(props[propName])) { | 1 |
Java | Java | add rfc-5681 support to cachecontrol | 6c282096c68426c1f926ff3682a0bdca9a23ea21 | <ide><path>spring-web/src/main/java/org/springframework/http/CacheControl.java
<ide> public class CacheControl {
<ide>
<ide> private boolean proxyRevalidate = false;
<ide>
<add> private long staleWhileRevalidate = -1;
<add>
<add> private long staleIfError = -1;
<add>
<ide> private long sMaxAge = -1;
<ide>
<ide>
<ide> public CacheControl sMaxAge(long sMaxAge, TimeUnit unit) {
<ide> return this;
<ide> }
<ide>
<add> /**
<add> * Add an "stale-while-revalidate" directive.
<add> * <p>This directive indicates that caches MAY serve the response in
<add> * which it appears after it becomes stale, up to the indicated number of seconds.
<add> * If a cached response is served stale due to the presence of this extension,
<add> * the cache SHOULD attempt to revalidate it while still serving stale responses (i.e., without blocking).
<add> * @param staleWhileRevalidate the maximum time the response should be used while being revalidated
<add> * @param unit the time unit of the {@code sMaxAge} argument
<add> * @return {@code this}, to facilitate method chaining
<add> * @see <a href="http://tools.ietf.org/html/rfc5861#section-3">rfc5861 section 3</a>
<add> */
<add> public CacheControl staleWhileRevalidate(long staleWhileRevalidate, TimeUnit unit) {
<add> this.staleWhileRevalidate = unit.toSeconds(staleWhileRevalidate);
<add> return this;
<add> }
<add>
<add> /**
<add> * Add an "stale-if-error" directive.
<add> * <p>This directive indicates that that when an error is encountered, a cached stale response MAY be used to satisfy
<add> * the request, regardless of other freshness information..
<add> * @param staleIfError the maximum time the response should be used when errors are encountered
<add> * @param unit the time unit of the {@code sMaxAge} argument
<add> * @return {@code this}, to facilitate method chaining
<add> * @see <a href="http://tools.ietf.org/html/rfc5861#section-4">rfc5861 section 4</a>
<add> */
<add> public CacheControl staleIfError(long staleIfError, TimeUnit unit) {
<add> this.staleIfError = unit.toSeconds(staleIfError);
<add> return this;
<add> }
<add>
<ide>
<ide> /**
<ide> * Return the "Cache-Control" header value.
<ide> public String getHeaderValue() {
<ide> if (this.sMaxAge != -1) {
<ide> appendDirective(ccValue, "s-maxage=" + Long.toString(this.sMaxAge));
<ide> }
<add> if(this.staleIfError != -1) {
<add> appendDirective(ccValue, "stale-if-error=" + Long.toString(this.staleIfError));
<add> }
<add> if(this.staleWhileRevalidate != -1) {
<add> appendDirective(ccValue, "stale-while-revalidate=" + Long.toString(this.staleWhileRevalidate));
<add> }
<add>
<ide> String ccHeaderValue = ccValue.toString();
<ide> return (StringUtils.hasText(ccHeaderValue) ? ccHeaderValue : null);
<ide> }
<ide><path>spring-web/src/test/java/org/springframework/http/CacheControlTests.java
<ide> public void noStore() throws Exception {
<ide> CacheControl cc = CacheControl.noStore();
<ide> assertThat(cc.getHeaderValue(), Matchers.equalTo("no-store"));
<ide> }
<add>
<add> @Test
<add> public void staleIfError() throws Exception {
<add> CacheControl cc = CacheControl.maxAge(1, TimeUnit.HOURS).staleIfError(2, TimeUnit.HOURS);
<add> assertThat(cc.getHeaderValue(), Matchers.equalTo("max-age=3600, stale-if-error=7200"));
<add> }
<add>
<add> @Test
<add> public void staleWhileRevalidate() throws Exception {
<add> CacheControl cc = CacheControl.maxAge(1, TimeUnit.HOURS).staleWhileRevalidate(2, TimeUnit.HOURS);
<add> assertThat(cc.getHeaderValue(), Matchers.equalTo("max-age=3600, stale-while-revalidate=7200"));
<add> }
<add>
<ide> } | 2 |
PHP | PHP | apply fixes from styleci | f0504da67feda7c77fcdddb5c3130d6308b50308 | <ide><path>tests/Database/DatabaseEloquentModelTest.php
<ide> use Mockery as m;
<ide> use LogicException;
<ide> use ReflectionClass;
<del>use RuntimeException;
<ide> use DateTimeImmutable;
<ide> use DateTimeInterface;
<ide> use InvalidArgumentException; | 1 |
Python | Python | fix connection.description migration for mysql8 | cdaaff12c7c80311eba22dcb856fe9c24d7f49aa | <ide><path>airflow/migrations/versions/61ec73d9401f_add_description_field_to_connection.py
<ide>
<ide> def upgrade():
<ide> """Apply Add description field to connection"""
<add> conn = op.get_bind() # pylint: disable=no-member
<add>
<ide> with op.batch_alter_table('connection') as batch_op:
<del> batch_op.add_column(sa.Column('description', sa.String(length=5000), nullable=True))
<add> if conn.dialect.name == "mysql":
<add> # Handles case where on mysql with utf8mb4 this would exceed the size of row
<add> # We have to set text type in this migration even if originally it was string
<add> # This is permanently fixed in the follow-up migration 64a7d6477aae
<add> batch_op.add_column(sa.Column('description', sa.Text(length=5000), nullable=True))
<add> else:
<add> batch_op.add_column(sa.Column('description', sa.String(length=5000), nullable=True))
<ide>
<ide>
<ide> def downgrade():
<ide><path>airflow/migrations/versions/64a7d6477aae_fix_description_field_in_connection_to_.py
<add>#
<add># Licensed to the Apache Software Foundation (ASF) under one
<add># or more contributor license agreements. See the NOTICE file
<add># distributed with this work for additional information
<add># regarding copyright ownership. The ASF licenses this file
<add># to you under the Apache License, Version 2.0 (the
<add># "License"); you may not use this file except in compliance
<add># with the License. You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing,
<add># software distributed under the License is distributed on an
<add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<add># KIND, either express or implied. See the License for the
<add># specific language governing permissions and limitations
<add># under the License.
<add>
<add>"""fix description field in connection to be text
<add>
<add>Revision ID: 64a7d6477aae
<add>Revises: f5b5ec089444
<add>Create Date: 2020-11-25 08:56:11.866607
<add>
<add>"""
<add>
<add>import sqlalchemy as sa # noqa
<add>from alembic import op # noqa
<add>
<add># revision identifiers, used by Alembic.
<add>revision = '64a7d6477aae'
<add>down_revision = '61ec73d9401f'
<add>branch_labels = None
<add>depends_on = None
<add>
<add>
<add>def upgrade():
<add> """Apply fix description field in connection to be text"""
<add> conn = op.get_bind() # pylint: disable=no-member
<add> if conn.dialect.name == "sqlite":
<add> # in sqlite TEXT and STRING column types are the same
<add> return
<add> if conn.dialect.name == "mysql":
<add> op.alter_column(
<add> 'connection',
<add> 'description',
<add> existing_type=sa.String(length=5000),
<add> type_=sa.Text(length=5000),
<add> existing_nullable=True,
<add> )
<add> else:
<add> # postgres does not allow size modifier for text type
<add> op.alter_column('connection', 'description', existing_type=sa.String(length=5000), type_=sa.Text())
<add>
<add>
<add>def downgrade():
<add> """Unapply fix description field in connection to be text"""
<add> conn = op.get_bind() # pylint: disable=no-member
<add> if conn.dialect.name == "sqlite":
<add> # in sqlite TEXT and STRING column types are the same
<add> return
<add> if conn.dialect.name == "mysql":
<add> op.alter_column(
<add> 'connection',
<add> 'description',
<add> existing_type=sa.Text(5000),
<add> type_=sa.String(length=5000),
<add> existing_nullable=True,
<add> )
<add> else:
<add> # postgres does not allow size modifier for text type
<add> op.alter_column(
<add> 'connection',
<add> 'description',
<add> existing_type=sa.Text(),
<add> type_=sa.String(length=5000),
<add> existing_nullable=True,
<add> )
<ide><path>airflow/models/connection.py
<ide> from typing import Dict, List, Optional
<ide> from urllib.parse import parse_qsl, quote, unquote, urlencode, urlparse
<ide>
<del>from sqlalchemy import Boolean, Column, Integer, String
<add>from sqlalchemy import Boolean, Column, Integer, String, Text
<ide> from sqlalchemy.ext.declarative import declared_attr
<ide> from sqlalchemy.orm import synonym
<ide>
<ide> class Connection(Base, LoggingMixin): # pylint: disable=too-many-instance-attri
<ide> id = Column(Integer(), primary_key=True)
<ide> conn_id = Column(String(ID_LEN), unique=True, nullable=False)
<ide> conn_type = Column(String(500), nullable=False)
<del> description = Column(String(5000))
<add> description = Column(Text(5000))
<ide> host = Column(String(500))
<ide> schema = Column(String(500))
<ide> login = Column(String(500)) | 3 |
Go | Go | fix typo for download and upload retry messages | f8d14bd4c6a0e3c58130be159b05b8aa63374f6e | <ide><path>distribution/xfer/download.go
<ide> func (ldm *LayerDownloadManager) makeDownloadFunc(descriptor DownloadDescriptor,
<ide>
<ide> selectLoop:
<ide> for {
<del> progress.Updatef(progressOutput, descriptor.ID(), "Retrying in %d seconds", delay)
<add> progress.Updatef(progressOutput, descriptor.ID(), "Retrying in %d second%s", delay, (map[bool]string{true: "s"})[delay != 1])
<ide> select {
<ide> case <-ticker.C:
<ide> delay--
<ide><path>distribution/xfer/upload.go
<ide> func (lum *LayerUploadManager) makeUploadFunc(descriptor UploadDescriptor) DoFun
<ide>
<ide> selectLoop:
<ide> for {
<del> progress.Updatef(progressOutput, descriptor.ID(), "Retrying in %d seconds", delay)
<add> progress.Updatef(progressOutput, descriptor.ID(), "Retrying in %d second%s", delay, (map[bool]string{true: "s"})[delay != 1])
<ide> select {
<ide> case <-ticker.C:
<ide> delay-- | 2 |
Javascript | Javascript | add regression test for smuggling content length | 7beff4de6f09ded170f9363e9e57dd32a42943b6 | <ide><path>test/parallel/test-http-request-smuggling-content-length.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const http = require('http');
<add>const net = require('net');
<add>const assert = require('assert');
<add>
<add>// Verify that a request with a space before the content length will result
<add>// in a 400 Bad Request.
<add>
<add>const server = http.createServer(common.mustNotCall());
<add>
<add>server.listen(0, common.mustCall(start));
<add>
<add>function start() {
<add> const sock = net.connect(server.address().port);
<add>
<add> sock.write('GET / HTTP/1.1\r\nHost: localhost:5000\r\n' +
<add> 'Content-Length : 5\r\n\r\nhello');
<add>
<add> let body = '';
<add> sock.setEncoding('utf8');
<add> sock.on('data', (chunk) => {
<add> body += chunk;
<add> });
<add> sock.on('end', common.mustCall(function() {
<add> assert.strictEqual(body, 'HTTP/1.1 400 Bad Request\r\n' +
<add> 'Connection: close\r\n\r\n');
<add> server.close();
<add> }));
<add>} | 1 |
Python | Python | fix seq2seqtrainer predict without labels | 02b63702d9f9d5d992908e57c70f020a0d105808 | <ide><path>src/transformers/trainer_seq2seq.py
<ide> def prediction_step(
<ide> generated_tokens = self._pad_tensors_to_max_len(generated_tokens, gen_kwargs["max_new_tokens"] + 1)
<ide>
<ide> with torch.no_grad():
<del> with self.compute_loss_context_manager():
<del> outputs = model(**inputs)
<ide> if has_labels:
<add> with self.compute_loss_context_manager():
<add> outputs = model(**inputs)
<ide> if self.label_smoother is not None:
<ide> loss = self.label_smoother(outputs, inputs["labels"]).mean().detach()
<ide> else: | 1 |
Python | Python | fix small grammatical error in comment | 8e737cf28212ba65d93e62b58a21d929e0bced26 | <ide><path>django/db/models/sql/subqueries.py
<ide> def delete_qs(self, query, using):
<ide> if innerq.alias_refcount[t]]
<ide> if ((not innerq_used_tables or innerq_used_tables == self.tables)
<ide> and not len(innerq.having)):
<del> # There is only the base table in use in the query, and there are
<add> # There is only the base table in use in the query, and there is
<ide> # no aggregate filtering going on.
<ide> self.where = innerq.where
<ide> else: | 1 |
Javascript | Javascript | fix benchmark linter issues | 54977cd33181b325e4b3523cbb7bdc808106e77c | <ide><path>benchmark/benchmark.js
<ide> const benchmarkOptions = {
<ide> };
<ide>
<ide> function runTimes(compiler, times, deferred) {
<del> fs.writeFileSync(path.join(fixtures, "0.js"), "module.exports = " + Math.random(), "utf-8");
<add> fs.writeFileSync(
<add> path.join(fixtures, "0.js"),
<add> "module.exports = " + Math.random(),
<add> "utf-8"
<add> );
<ide> compiler.run(err => {
<del> if(err) throw err;
<del> if(times === 1)
<del> deferred.resolve();
<del> else
<del> runTimes(compiler, times - 1, deferred);
<add> if (err) throw err;
<add> if (times === 1) deferred.resolve();
<add> else runTimes(compiler, times - 1, deferred);
<ide> });
<ide> }
<ide>
<ide> const tests = {
<ide> "normal build": [
<ide> [0, 1, 5, 10, 50, 100, 200],
<ide> (size, deferred) => {
<del> webpack({
<del> context: fixtures,
<del> entry: `./${size}.js`,
<del> output: {
<del> path: outputPath,
<del> filename: "bundle.js"
<add> webpack(
<add> {
<add> context: fixtures,
<add> entry: `./${size}.js`,
<add> output: {
<add> path: outputPath,
<add> filename: "bundle.js"
<add> }
<add> },
<add> err => {
<add> if (err) throw err;
<add> deferred.resolve();
<ide> }
<del> }, err => {
<del> if(err) throw err;
<del> deferred.resolve();
<del> });
<add> );
<ide> }
<ide> ],
<ide> "eval dev build": [
<ide> [0, 1, 2, 5, 10, 15],
<ide> (size, deferred) => {
<del> webpack({
<del> context: fixtures,
<del> entry: `./${size}.big.js`,
<del> output: {
<del> path: outputPath,
<del> filename: "bundle.js"
<add> webpack(
<add> {
<add> context: fixtures,
<add> entry: `./${size}.big.js`,
<add> output: {
<add> path: outputPath,
<add> filename: "bundle.js"
<add> },
<add> devtool: "eval"
<ide> },
<del> devtool: "eval"
<del> }, err => {
<del> if(err) throw err;
<del> deferred.resolve();
<del> });
<add> err => {
<add> if (err) throw err;
<add> deferred.resolve();
<add> }
<add> );
<ide> }
<ide> ],
<ide> "sourcemap build": [
<ide> [0, 1, 2, 5, 10, 15],
<ide> (size, deferred) => {
<del> webpack({
<del> context: fixtures,
<del> entry: `./${size}.big.js`,
<del> output: {
<del> path: outputPath,
<del> filename: "bundle.js"
<add> webpack(
<add> {
<add> context: fixtures,
<add> entry: `./${size}.big.js`,
<add> output: {
<add> path: outputPath,
<add> filename: "bundle.js"
<add> },
<add> devtool: "source-map"
<ide> },
<del> devtool: "source-map"
<del> }, err => {
<del> if(err) throw err;
<del> deferred.resolve();
<del> });
<add> err => {
<add> if (err) throw err;
<add> deferred.resolve();
<add> }
<add> );
<ide> }
<ide> ],
<ide> "cheap sourcemap build": [
<ide> [0, 1, 2, 5, 10, 15],
<ide> (size, deferred) => {
<del> webpack({
<del> context: fixtures,
<del> entry: `./${size}.big.js`,
<del> output: {
<del> path: outputPath,
<del> filename: "bundle.js"
<add> webpack(
<add> {
<add> context: fixtures,
<add> entry: `./${size}.big.js`,
<add> output: {
<add> path: outputPath,
<add> filename: "bundle.js"
<add> },
<add> devtool: "cheap-source-map"
<ide> },
<del> devtool: "cheap-source-map"
<del> }, err => {
<del> if(err) throw err;
<del> deferred.resolve();
<del> });
<del> }
<del> ],
<del> "build w/ chunks": [
<del> [0, 1, 5, 10, 50, 100, 200],
<del> (size, deferred) => {
<del> webpack({
<del> context: fixtures,
<del> entry: `./${size}.async.js`,
<del> output: {
<del> path: outputPath,
<del> filename: "bundle.js"
<add> err => {
<add> if (err) throw err;
<add> deferred.resolve();
<ide> }
<del> }, err => {
<del> if(err) throw err;
<del> deferred.resolve();
<del> });
<add> );
<ide> }
<ide> ],
<ide> "build w/ chunks": [
<ide> [0, 1, 5, 10, 50, 100, 200],
<ide> (size, deferred) => {
<del> webpack({
<del> context: fixtures,
<del> entry: "./" + size + ".async.js",
<del> output: {
<del> path: outputPath,
<del> filename: "bundle.js"
<add> webpack(
<add> {
<add> context: fixtures,
<add> entry: `./${size}.async.js`,
<add> output: {
<add> path: outputPath,
<add> filename: "bundle.js"
<add> }
<add> },
<add> err => {
<add> if (err) throw err;
<add> deferred.resolve();
<ide> }
<del> }, err => {
<del> if(err) throw err;
<del> deferred.resolve();
<del> });
<add> );
<ide> }
<ide> ],
<del> "incremental": [
<add> incremental: [
<ide> [0, 1, 5, 10, 50, 100, 200],
<ide> (size, deferred) => {
<ide> var compiler = webpack({
<ide> const tests = {
<ide> runTimes(compiler, size, deferred);
<ide> }
<ide> ],
<del> "incremental2": [
<add> incremental2: [
<ide> [0, 1, 5, 10, 50, 100, 200],
<ide> (size, deferred) => {
<ide> var compiler = webpack({
<ide> const tests = {
<ide> runTimes(compiler, 3, deferred);
<ide> }
<ide> ],
<del> "incremental4": [
<add> incremental4: [
<ide> [0, 1, 5, 10, 50, 100, 200],
<ide> (size, deferred) => {
<ide> var compiler = webpack({
<ide> const tests = {
<ide> runTimes(compiler, 5, deferred);
<ide> }
<ide> ],
<del> "incremental16": [
<add> incremental16: [
<ide> [0, 1, 5, 10, 50, 100, 200],
<ide> (size, deferred) => {
<ide> var compiler = webpack({
<ide> const tests = {
<ide> });
<ide> runTimes(compiler, 17, deferred);
<ide> }
<del> ],
<add> ]
<ide> };
<ide>
<del>const suite = new Benchmark.Suite;
<add>const suite = new Benchmark.Suite();
<ide>
<del>Object.keys(tests).filter(name => process.argv.length > 2 ? name.includes(process.argv[2]) : true)
<add>Object.keys(tests)
<add> .filter(
<add> name => (process.argv.length > 2 ? name.includes(process.argv[2]) : true)
<add> )
<ide> .forEach(name => {
<ide> const test = tests[name];
<ide> test[0].forEach(size => {
<del> suite.add(`${name} ${size}`, deferred => {
<del> test[1](size, deferred);
<del> }, benchmarkOptions);
<add> suite.add(
<add> `${name} ${size}`,
<add> deferred => {
<add> test[1](size, deferred);
<add> },
<add> benchmarkOptions
<add> );
<ide> });
<ide> });
<ide>
<ide> suite.on("cycle", event => {
<ide> process.stderr.write("\n");
<ide> const b = event.target;
<del> console.log(b.name + "\t" + Math.floor(1000 * (b.stats.mean - b.stats.moe)) + "\t" + Math.floor(1000 * (b.stats.mean + b.stats.moe)));
<add> console.log(
<add> b.name +
<add> "\t" +
<add> Math.floor(1000 * (b.stats.mean - b.stats.moe)) +
<add> "\t" +
<add> Math.floor(1000 * (b.stats.mean + b.stats.moe))
<add> );
<ide> });
<ide>
<ide> suite.run({
<ide><path>benchmark/createBenchmark.js
<add>// eslint-disable-next-line node/no-extraneous-require
<ide> const webpack = require("webpack");
<ide> const path = require("path");
<ide>
<del>webpack({
<del> context: __dirname,
<del> entry: "./createBenchmark/entry.js",
<del> output: {
<del> path: __dirname,
<del> filename: "benchmark-bundle.js"
<add>webpack(
<add> {
<add> context: __dirname,
<add> entry: "./createBenchmark/entry.js",
<add> output: {
<add> path: __dirname,
<add> filename: "benchmark-bundle.js"
<add> },
<add> target: "node",
<add> node: {
<add> __dirname: false
<add> },
<add> plugins: [
<add> new webpack.NamedModulesPlugin(),
<add> new webpack.IgnorePlugin(/^(fsevents|uglify-js)$/),
<add> new webpack.NormalModuleReplacementPlugin(
<add> /^.\/loadLoader$/,
<add> path.resolve(__dirname, "./createBenchmark/loadLoader")
<add> )
<add> ]
<ide> },
<del> target: "node",
<del> node: {
<del> __dirname: false
<del> },
<del> plugins: [
<del> new webpack.NamedModulesPlugin(),
<del> new webpack.IgnorePlugin(/^(fsevents|uglify-js)$/),
<del> new webpack.NormalModuleReplacementPlugin(/^.\/loadLoader$/, path.resolve(__dirname, "./createBenchmark/loadLoader"))
<del> ]
<del>}, (err, stats) => {
<del> console.log(stats.toString());
<del>});
<add> (err, stats) => {
<add> console.log(stats.toString());
<add> }
<add>);
<ide><path>benchmark/createBenchmark/entry.js
<add>// eslint-disable-next-line node/no-extraneous-require
<ide> const webpack = require("webpack");
<del>const MemoryFs = require("memory-fs");
<ide> const path = require("path");
<ide>
<ide> const testCase = process.argv[2];
<ide> const config = {
<ide>
<ide> const compiler = webpack(config);
<ide> compiler.run((err, stats) => {
<del> if(err) {
<add> if (err) {
<ide> console.error(err);
<ide> } else {
<del> console.log(stats.toString({
<del> errorDetails: true
<del> }));
<add> console.log(
<add> stats.toString({
<add> errorDetails: true
<add> })
<add> );
<ide> }
<ide> });
<ide><path>benchmark/createBenchmark/loadLoader.js
<ide> module.exports = (loader, callback) => {
<ide> callback(new Error("Loaders are not supported"));
<del>}
<add>};
<ide><path>benchmark/createFixtures.js
<ide> const fixtures = path.join(__dirname, "fixtures");
<ide>
<ide> try {
<ide> fs.mkdirSync(fixtures);
<del>} catch(e) {}
<add>} catch (e) {
<add> // catch here
<add>}
<ide>
<ide> function generateRequireString(conditional, suffix) {
<ide> const prefixedSuffix = suffix ? `.${suffix}` : "";
<ide> return `require(${JSON.stringify(`./${conditional}${prefixedSuffix}.js`)});`;
<ide> }
<ide>
<del>for(let i = 0; i < 10000; i++) {
<add>for (let i = 0; i < 10000; i++) {
<ide> const source = [];
<del> if(i > 8)
<del> source.push(generateRequireString((i / 8 | 0)));
<del> if(i > 4)
<del> source.push(generateRequireString((i / 4 | 0)));
<del> if(i > 2)
<del> source.push(generateRequireString((i / 2 | 0)));
<del> if(i > 0)
<del> source.push(generateRequireString((i - 1)));
<add> if (i > 8) source.push(generateRequireString((i / 8) | 0));
<add> if (i > 4) source.push(generateRequireString((i / 4) | 0));
<add> if (i > 2) source.push(generateRequireString((i / 2) | 0));
<add> if (i > 0) source.push(generateRequireString(i - 1));
<ide> source.push("module.exports = " + i + ";");
<ide> fs.writeFileSync(path.join(fixtures, i + ".js"), source.join("\n"), "utf-8");
<ide> }
<ide>
<del>for(let i = 0; i < 10000; i++) {
<add>for (let i = 0; i < 10000; i++) {
<ide> const source = [];
<ide> source.push("require.ensure([], function(require) {");
<del> if(i > 8)
<del> source.push(generateRequireString((i / 8 | 0), "async"));
<del> if(i > 4)
<del> source.push(generateRequireString((i / 4 | 0), "async"));
<del> if(i > 2)
<del> source.push(generateRequireString((i / 2 | 0), "async"));
<del> if(i > 0)
<del> source.push(generateRequireString((i - 1), "async"));
<add> if (i > 8) source.push(generateRequireString((i / 8) | 0, "async"));
<add> if (i > 4) source.push(generateRequireString((i / 4) | 0, "async"));
<add> if (i > 2) source.push(generateRequireString((i / 2) | 0, "async"));
<add> if (i > 0) source.push(generateRequireString(i - 1, "async"));
<ide> source.push("});");
<ide> source.push("module.exports = " + i + ";");
<del> fs.writeFileSync(path.join(fixtures, i + ".async.js"), source.join("\n"), "utf-8");
<add> fs.writeFileSync(
<add> path.join(fixtures, i + ".async.js"),
<add> source.join("\n"),
<add> "utf-8"
<add> );
<ide> }
<ide>
<del>for(let i = 0; i < 100; i++) {
<add>for (let i = 0; i < 100; i++) {
<ide> const source = [];
<del> if(i > 8)
<del> source.push(generateRequireString((i / 8 | 0), "big"));
<del> if(i > 4)
<del> source.push(generateRequireString((i / 4 | 0), "big"));
<del> if(i > 2)
<del> source.push(generateRequireString((i / 2 | 0), "big"));
<del> if(i > 0)
<del> source.push(generateRequireString((i - 1), "big"));
<del> for(let j = 0; j < 300; j++)
<del> source.push("if(Math.random())hello.world();test.a.b.c.d();x(1,2,3,4);var a,b,c,d,e,f;");
<add> if (i > 8) source.push(generateRequireString((i / 8) | 0, "big"));
<add> if (i > 4) source.push(generateRequireString((i / 4) | 0, "big"));
<add> if (i > 2) source.push(generateRequireString((i / 2) | 0, "big"));
<add> if (i > 0) source.push(generateRequireString(i - 1, "big"));
<add> for (let j = 0; j < 300; j++)
<add> source.push(
<add> "if(Math.random())hello.world();test.a.b.c.d();x(1,2,3,4);var a,b,c,d,e,f;"
<add> );
<ide> source.push("module.exports = " + i + ";");
<del> fs.writeFileSync(path.join(fixtures, i + ".big.js"), source.join("\n"), "utf-8");
<add> fs.writeFileSync(
<add> path.join(fixtures, i + ".big.js"),
<add> source.join("\n"),
<add> "utf-8"
<add> );
<ide> }
<ide><path>benchmark/createFixtures2.js
<ide> const fixtures = path.join(__dirname, "fixtures");
<ide>
<ide> try {
<ide> fs.mkdirSync(fixtures);
<del>} catch(e) {}
<add>} catch (e) {
<add> // catch here
<add>}
<ide>
<ide> function genModule(prefix, depth, asyncDepth, multiplex, r, circular) {
<ide> const source = [];
<ide> const isAsync = depth >= asyncDepth;
<del> if(!isAsync)
<del> circular.push(path.resolve(fixtures, prefix + "/index.js"));
<add> if (!isAsync) circular.push(path.resolve(fixtures, prefix + "/index.js"));
<ide> source.push("(function() {");
<del> const m = (r % multiplex) + 1;
<add> const m = r % multiplex + 1;
<ide> let sum = 1;
<ide> let item;
<ide> try {
<ide> fs.mkdirSync(path.resolve(fixtures, prefix));
<del> } catch(e) {}
<del> if(depth > 0) {
<del> for(let i = 0; i < m; i++) {
<del> sum += genModule(prefix + "/" + i, depth - 1, asyncDepth, multiplex, (r + i + depth) * m + i + depth, circular);
<add> } catch (e) {
<add> // catch here
<add> }
<add> if (depth > 0) {
<add> for (let i = 0; i < m; i++) {
<add> sum += genModule(
<add> prefix + "/" + i,
<add> depth - 1,
<add> asyncDepth,
<add> multiplex,
<add> (r + i + depth) * m + i + depth,
<add> circular
<add> );
<ide> source.push("require(" + JSON.stringify("./" + i) + ");");
<del> if(i === 0) {
<del> if(isAsync)
<del> source.push("}); require.ensure([], function() {");
<add> if (i === 0) {
<add> if (isAsync) source.push("}); require.ensure([], function() {");
<ide> }
<ide> }
<ide> item = circular[r % circular.length];
<ide> }
<ide> source.push("}, " + JSON.stringify(prefix) + ");");
<del> if(item)
<del> source.push("require(" + JSON.stringify(item) + ");");
<add> if (item) source.push("require(" + JSON.stringify(item) + ");");
<ide> source.push("module.exports = " + JSON.stringify(prefix) + ";");
<del> fs.writeFileSync(path.resolve(fixtures, prefix + "/index.js"), source.join("\n"), "utf-8");
<add> fs.writeFileSync(
<add> path.resolve(fixtures, prefix + "/index.js"),
<add> source.join("\n"),
<add> "utf-8"
<add> );
<ide> return sum;
<ide> }
<ide>
<del>for(let i = 2; i < 14; i++) {
<add>for (let i = 2; i < 14; i++) {
<ide> const count = genModule("tree-" + i, 6, 100, i, 0, []);
<ide> console.log("generated tree", i, count);
<ide> }
<ide>
<del>for(let i = 2; i < 14; i++) {
<add>for (let i = 2; i < 14; i++) {
<ide> const count = genModule("async-tree-" + i, 6, 1, i, 0, []);
<ide> console.log("generated async tree", i, count);
<ide> }
<ide><path>benchmark/createTestCases.js
<ide> function c() {}
<ide> function d() {}
<ide> function e() {}
<ide> function f() {}
<del>`
<add>`;
<ide>
<del>for(let i = 0; i < 2; i++) {
<add>for (let i = 0; i < 2; i++) {
<ide> avgJs += `(function() {${avgJs}}());`;
<ide> }
<ide>
<ide> function createTree(fs, count, folder) {
<ide> let remaining = count - 1;
<ide>
<ide> function make(prefix, count, depth) {
<del> if(count === 0) {
<add> if (count === 0) {
<ide> fs.writeFileSync(`${folder}/${prefix}.js`, `export default 1;\n${avgJs}`);
<ide> } else {
<ide> const list = [];
<del> for(let i = 0; i < count; i++) {
<del> if(remaining-- <= 0) break;
<del> if(depth <= 4 && i >= 3 && i <= 4) {
<del> list.push(`const module${i} = import("./${prefix}-${i}");\ncounter += module${i};`);
<add> for (let i = 0; i < count; i++) {
<add> if (remaining-- <= 0) break;
<add> if (depth <= 4 && i >= 3 && i <= 4) {
<add> list.push(
<add> `const module${i} = import("./${prefix}-${i}");\ncounter += module${i};`
<add> );
<ide> } else {
<del> list.push(`import module${i} from "./${prefix}-${i}";\ncounter += module${i};`);
<add> list.push(
<add> `import module${i} from "./${prefix}-${i}";\ncounter += module${i};`
<add> );
<ide> }
<del> make(`${prefix}-${i}`, depth > 4 || count > 30 ? 0 : count + depth + i ** 2, depth + 1);
<add> make(
<add> `${prefix}-${i}`,
<add> // eslint-disable-next-line node/no-unsupported-features
<add> depth > 4 || count > 30 ? 0 : count + depth + i ** 2,
<add> depth + 1
<add> );
<ide> }
<del> fs.writeFileSync(`${folder}/${prefix}.js`, `let counter = 0;\n${list.join("\n")};\nexport default counter;\n${avgJs}`)
<add> fs.writeFileSync(
<add> `${folder}/${prefix}.js`,
<add> `let counter = 0;\n${list.join(
<add> "\n"
<add> )};\nexport default counter;\n${avgJs}`
<add> );
<ide> }
<ide> }
<ide> make("index", 2, 0); | 7 |
Ruby | Ruby | extend ext list | b109e4f1f1c39fb4d7ba49dc954c4de9ab3d286b | <ide><path>Library/Homebrew/metafiles.rb
<ide> class Metafiles
<del> EXTENSIONS = %w[.md .html .rtf .txt]
<add> # https://github.com/github/markup#markups
<add> EXTENSIONS = %w[
<add> .adoc .asc .asciidoc .creole .html .markdown .md .mdown .mediawiki .mkdn
<add> .org .pod .rdoc .rst .rtf .textile .txt .wiki
<add> ]
<ide> BASENAMES = %w[
<ide> about authors changelog changes copying copyright history license licence
<ide> news notes notice readme todo | 1 |
Ruby | Ruby | update rdoc comments for #redirect | d0bd1e93a1c26e5206a71d7966f2230f0823700e | <ide><path>actionpack/lib/action_dispatch/routing/redirection.rb
<ide> module Redirection
<ide> # This will redirect the user, while ignoring certain parts of the request, including query string, etc.
<ide> # <tt>/stories</tt>, <tt>/stories?foo=bar</tt>, etc all redirect to <tt>/posts</tt>.
<ide> #
<add> # The redirect will use a <tt>301 Moved Permanently</tt> status code by
<add> # default. This can be overridden with the +:status+ option:
<add> #
<add> # get "/stories" => redirect("/posts", status: 307)
<add> #
<ide> # You can also use interpolation in the supplied redirect argument:
<ide> #
<ide> # get 'docs/:article', to: redirect('/wiki/%{article}') | 1 |
Ruby | Ruby | combine duplicated postfix conditionals | 2f542f657e656d2e13a5a7cd0acc406c71c036ab | <ide><path>Library/Homebrew/keg.rb
<ide> def link mode=OpenStruct.new
<ide> end
<ide> end
<ide>
<del> linked_keg_record.make_relative_symlink(self) unless mode.dry_run
<del>
<del> optlink unless mode.dry_run
<add> unless mode.dry_run
<add> linked_keg_record.make_relative_symlink(self)
<add> optlink
<add> end
<ide>
<ide> return $n + $d
<ide> rescue Exception | 1 |
Python | Python | update return value | 35c0aff93069b331a56d5e76ae7f842be527030d | <ide><path>airflow/models.py
<ide> ID_LEN = 250
<ide> SQL_ALCHEMY_CONN = conf.get('core', 'SQL_ALCHEMY_CONN')
<ide> DAGS_FOLDER = os.path.expanduser(conf.get('core', 'DAGS_FOLDER'))
<del>RETURN_XCOM = '<Returned XCom>'
<add>RETURN_XCOM = '__return_value__'
<ide>
<ide>
<ide> if 'mysql' in SQL_ALCHEMY_CONN: | 1 |
PHP | PHP | fix missing precision, and remove charset/collate | b3acb2ef1e888d9e80cc93751856ce9fd48c04b5 | <ide><path>lib/Cake/Database/Schema/MysqlSchema.php
<ide> public function convertColumn($column) {
<ide> }
<ide>
<ide> $col = strtolower($matches[1]);
<del> $length = null;
<add> $length = $precision = null;
<ide> if (isset($matches[2])) {
<del> $length = (int)$matches[2];
<add> $length = $matches[2];
<add> if (strpos($matches[2], ',') !== false) {
<add> list($length, $precision) = explode(',', $length);
<add> }
<add> $length = (int)$length;
<add> $precision = (int)$precision;
<ide> }
<ide>
<ide> if (in_array($col, array('date', 'time', 'datetime', 'timestamp'))) {
<ide> public function convertColumn($column) {
<ide> return ['type' => 'binary', 'length' => $length];
<ide> }
<ide> if (strpos($col, 'float') !== false || strpos($col, 'double') !== false) {
<del> return ['type' => 'float', 'length' => $length];
<add> return ['type' => 'float', 'length' => $length, 'precision' => $precision];
<ide> }
<ide> if (strpos($col, 'decimal') !== false) {
<del> return ['type' => 'decimal', 'length' => null];
<add> return ['type' => 'decimal', 'length' => $length, 'precision' => $precision];
<ide> }
<ide> return ['type' => 'text', 'length' => null];
<ide> }
<ide> public function columnSql(Table $table, $name) {
<ide> break;
<ide> }
<ide> }
<del> $hasLength = [
<del> 'integer', 'string', 'float'
<del> ];
<add> $hasLength = ['integer', 'string'];
<ide> if (in_array($data['type'], $hasLength, true) && isset($data['length'])) {
<del> $out .= '(' . $data['length'] . ')';
<add> $out .= '(' . (int)$data['length'] . ')';
<add> }
<add> $hasPrecision = ['float', 'decimal'];
<add> if (
<add> in_array($data['type'], $hasPrecision, true) &&
<add> (isset($data['length']) || isset($data['precision']))
<add> ) {
<add> $data += ['length' => 11, 'precision' => 3];
<add> $out .= '(' . (int)$data['length'] . ', ' . (int)$data['precision'] . ')';
<ide> }
<ide> if (isset($data['null']) && $data['null'] === false) {
<ide> $out .= ' NOT NULL';
<ide><path>lib/Cake/Database/Schema/Table.php
<ide> class Table {
<ide> protected $_columnKeys = [
<ide> 'type' => null,
<ide> 'length' => null,
<add> 'precision' => null,
<ide> 'null' => null,
<ide> 'default' => null,
<ide> 'fixed' => null,
<ide> 'comment' => null,
<del> 'collate' => null,
<del> 'charset' => null,
<ide> ];
<ide>
<ide> /**
<ide><path>lib/Cake/Test/TestCase/Database/Schema/MysqlSchemaTest.php
<ide> public static function columnProvider() {
<ide> ],
<ide> [
<ide> 'FLOAT',
<del> ['type' => 'float', 'length' => null]
<add> ['type' => 'float', 'length' => null, 'precision' => null]
<ide> ],
<ide> [
<ide> 'DOUBLE',
<del> ['type' => 'float', 'length' => null]
<add> ['type' => 'float', 'length' => null, 'precision' => null]
<ide> ],
<ide> [
<ide> 'DECIMAL(11,2)',
<del> ['type' => 'decimal', 'length' => null]
<add> ['type' => 'decimal', 'length' => 11, 'precision' => 2]
<add> ],
<add> [
<add> 'FLOAT(11,2)',
<add> ['type' => 'float', 'length' => 11, 'precision' => 2]
<add> ],
<add> [
<add> 'DOUBLE(10,4)',
<add> ['type' => 'float', 'length' => 10, 'precision' => 4]
<ide> ],
<ide> ];
<ide> }
<ide> public function testDescribeTable() {
<ide> 'null' => false,
<ide> 'default' => null,
<ide> 'length' => 20,
<add> 'precision' => null,
<ide> 'fixed' => null,
<ide> 'comment' => null,
<del> 'collate' => null,
<del> 'charset' => null,
<ide> ],
<ide> 'title' => [
<ide> 'type' => 'string',
<ide> 'null' => true,
<ide> 'default' => null,
<ide> 'length' => 20,
<del> 'collate' => 'utf8_general_ci',
<add> 'precision' => null,
<ide> 'comment' => 'A title',
<ide> 'fixed' => null,
<del> 'charset' => null,
<ide> ],
<ide> 'body' => [
<ide> 'type' => 'text',
<ide> 'null' => true,
<ide> 'default' => null,
<ide> 'length' => null,
<del> 'collate' => 'utf8_general_ci',
<add> 'precision' => null,
<ide> 'fixed' => null,
<ide> 'comment' => null,
<del> 'charset' => null,
<ide> ],
<ide> 'author_id' => [
<ide> 'type' => 'integer',
<ide> 'null' => false,
<ide> 'default' => null,
<ide> 'length' => 11,
<add> 'precision' => null,
<ide> 'fixed' => null,
<ide> 'comment' => null,
<del> 'collate' => null,
<del> 'charset' => null,
<ide> ],
<ide> 'published' => [
<ide> 'type' => 'boolean',
<ide> 'null' => true,
<ide> 'default' => 0,
<ide> 'length' => null,
<add> 'precision' => null,
<ide> 'fixed' => null,
<ide> 'comment' => null,
<del> 'collate' => null,
<del> 'charset' => null,
<ide> ],
<ide> 'allow_comments' => [
<ide> 'type' => 'boolean',
<ide> 'null' => true,
<ide> 'default' => 0,
<ide> 'length' => null,
<add> 'precision' => null,
<ide> 'fixed' => null,
<ide> 'comment' => null,
<del> 'collate' => null,
<del> 'charset' => null,
<ide> ],
<ide> 'created' => [
<ide> 'type' => 'datetime',
<ide> 'null' => true,
<ide> 'default' => null,
<ide> 'length' => null,
<add> 'precision' => null,
<ide> 'fixed' => null,
<ide> 'comment' => null,
<del> 'collate' => null,
<del> 'charset' => null,
<ide> ],
<ide> ];
<ide> $this->assertEquals(['id'], $result->primaryKey());
<ide> public static function columnSqlProvider() {
<ide> ['type' => 'biginteger', 'length' => 20],
<ide> '`post_id` BIGINT'
<ide> ],
<add> // Decimal
<add> [
<add> 'value',
<add> ['type' => 'decimal'],
<add> '`value` DECIMAL'
<add> ],
<add> [
<add> 'value',
<add> ['type' => 'decimal', 'length' => 11],
<add> '`value` FLOAT(11, 3)'
<add> ],
<add> [
<add> 'value',
<add> ['type' => 'decimal', 'length' => 12, 'precision' => 5],
<add> '`value` FLOAT(12, 5)'
<add> ],
<ide> // Float
<ide> [
<ide> 'value',
<ide> ['type' => 'float'],
<ide> '`value` FLOAT'
<ide> ],
<add> [
<add> 'value',
<add> ['type' => 'float', 'length' => 11],
<add> '`value` FLOAT(11, 3)'
<add> ],
<ide> // Boolean
<ide> [
<ide> 'checked',
<ide><path>lib/Cake/Test/TestCase/Database/Schema/TableTest.php
<ide> public function testAddColumnFiltersAttributes() {
<ide> $expected = [
<ide> 'type' => 'string',
<ide> 'length' => null,
<add> 'precision' => null,
<ide> 'default' => null,
<ide> 'null' => null,
<ide> 'fixed' => null,
<ide> 'comment' => null,
<del> 'collate' => null,
<del> 'charset' => null,
<ide> ];
<ide> $this->assertEquals($expected, $result);
<ide> } | 4 |
Javascript | Javascript | update some apis/datastructures | f5ae5027ccca043fa67138f04d38a9ce57be7f15 | <ide><path>api-server/server/boot/settings.js
<ide> function updateMyCurrentChallenge(req, res, next) {
<ide> user,
<ide> body: { currentChallengeId }
<ide> } = req;
<del> return user
<del> .update$({ currentChallengeId })
<del> .subscribe(() => res.status(200), next);
<add> return user.updateAttribute(
<add> 'currentChallengeId',
<add> currentChallengeId,
<add> (err, updatedUser) => {
<add> if (err) {
<add> return next(err);
<add> }
<add> const { currentChallengeId } = updatedUser;
<add> return res.status(200).json(currentChallengeId);
<add> }
<add> );
<ide> }
<ide>
<ide> const updateMyThemeValidators = [
<ide><path>client/src/components/profile/components/TimeLine.js
<ide> const propTypes = {
<ide> completedDate: PropTypes.number,
<ide> challengeType: PropTypes.number,
<ide> solution: PropTypes.string,
<del> files: PropTypes.shape({
<del> ext: PropTypes.string,
<del> contents: PropTypes.string
<del> })
<add> files: PropTypes.arrayOf(
<add> PropTypes.shape({
<add> ext: PropTypes.string,
<add> contents: PropTypes.string
<add> })
<add> )
<ide> })
<ide> ),
<ide> fetchIdToNameMap: PropTypes.func.isRequired, | 2 |
Java | Java | improve javadocs of connectable sources | c573219f520c30583f8a62f9c996c6c17b2de447 | <ide><path>src/main/java/io/reactivex/rxjava3/flowables/ConnectableFlowable.java
<ide> import java.util.Objects;
<ide> import java.util.concurrent.TimeUnit;
<ide>
<del>import org.reactivestreams.Subscriber;
<add>import org.reactivestreams.*;
<ide>
<ide> import io.reactivex.rxjava3.annotations.*;
<ide> import io.reactivex.rxjava3.core.*;
<ide> * <img width="640" height="510" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/publishConnect.v3.png" alt="">
<ide> * <p>
<ide> * When the upstream terminates, the {@code ConnectableFlowable} remains in this terminated state and,
<del> * depending on the actual underlying implementation, relays cached events to late {@link Subscriber}s.
<add> * depending on the actual underlying implementation, relays cached events to late {@code Subscriber}s.
<ide> * In order to reuse and restart this {@code ConnectableFlowable}, the {@link #reset()} method has to be called.
<del> * When called, this {@code ConnectableFlowable} will appear as fresh, unconnected source to new {@link Subscriber}s.
<add> * When called, this {@code ConnectableFlowable} will appear as fresh, unconnected source to new {@code Subscriber}s.
<ide> * Disposing the connection will reset the {@code ConnectableFlowable} to its fresh state and there is no need to call
<ide> * {@code reset()} in this case.
<ide> * <p>
<ide> * there is no unwanted signal loss due to early {@code connect()} or {@code reset()} calls while {@code Subscriber}s are
<ide> * still being subscribed to to this {@code ConnectableFlowable} to receive signals from the get go.
<ide> * <p>
<del> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Connectable-Observable-Operators">RxJava Wiki:
<del> * Connectable Observable Operators</a>
<add> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Connectable-Observable-Operators">RxJava Wiki: Connectable Observable Operators</a>
<ide> * @param <T>
<ide> * the type of items emitted by the {@code ConnectableFlowable}
<ide> * @since 2.0.0
<ide> public abstract void connect(@NonNull Consumer<? super Disposable> connection);
<ide>
<ide> /**
<del> * Resets this ConnectableFlowable into its fresh state if it has terminated.
<add> * Resets this {@code ConnectableFlowable} into its fresh state if it has terminated.
<ide> * <p>
<ide> * Calling this method on a fresh or active {@code ConnectableFlowable} has no effect.
<ide> * <dl>
<ide> public final Disposable connect() {
<ide> }
<ide>
<ide> /**
<del> * Returns a {@code Flowable} that stays connected to this {@code ConnectableFlowable} as long as there
<add> * Returns a {@link Flowable} that stays connected to this {@code ConnectableFlowable} as long as there
<ide> * is at least one subscription to this {@code ConnectableFlowable}.
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<ide> public final Disposable connect() {
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>This {@code refCount} overload does not operate on any particular {@link Scheduler}.</dd>
<ide> * </dl>
<del> * @return a {@link Flowable}
<add> * @return the new {@code Flowable} instance
<ide> * @see <a href="http://reactivex.io/documentation/operators/refcount.html">ReactiveX documentation: RefCount</a>
<ide> * @see #refCount(int)
<ide> * @see #refCount(long, TimeUnit)
<ide> public Flowable<T> refCount() {
<ide> * </dl>
<ide> * <p>History: 2.1.14 - experimental
<ide> * @param subscriberCount the number of subscribers required to connect to the upstream
<del> * @return the new Flowable instance
<add> * @return the new {@link Flowable} instance
<add> * @throws IllegalArgumentException if {@code subscriberCount} is non-positive
<ide> * @since 2.2
<ide> */
<ide> @CheckReturnValue
<ide> public final Flowable<T> refCount(int subscriberCount) {
<ide> * <p>History: 2.1.14 - experimental
<ide> * @param timeout the time to wait before disconnecting after all subscribers unsubscribed
<ide> * @param unit the time unit of the timeout
<del> * @return the new Flowable instance
<add> * @return the new {@link Flowable} instance
<ide> * @throws NullPointerException if {@code unit} is {@code null}
<ide> * @see #refCount(long, TimeUnit, Scheduler)
<ide> * @since 2.2
<ide> public final Flowable<T> refCount(long timeout, @NonNull TimeUnit unit) {
<ide> * @param timeout the time to wait before disconnecting after all subscribers unsubscribed
<ide> * @param unit the time unit of the timeout
<ide> * @param scheduler the target scheduler to wait on before disconnecting
<del> * @return the new Flowable instance
<add> * @return the new {@link Flowable} instance
<ide> * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null}
<ide> * @since 2.2
<ide> */
<ide> public final Flowable<T> refCount(long timeout, @NonNull TimeUnit unit, @NonNull
<ide> * @param subscriberCount the number of subscribers required to connect to the upstream
<ide> * @param timeout the time to wait before disconnecting after all subscribers unsubscribed
<ide> * @param unit the time unit of the timeout
<del> * @return the new Flowable instance
<add> * @return the new {@link Flowable} instance
<ide> * @throws NullPointerException if {@code unit} is {@code null}
<add> * @throws IllegalArgumentException if {@code subscriberCount} is non-positive
<ide> * @see #refCount(int, long, TimeUnit, Scheduler)
<ide> * @since 2.2
<ide> */
<ide> public final Flowable<T> refCount(int subscriberCount, long timeout, @NonNull Ti
<ide> * @param timeout the time to wait before disconnecting after all subscribers unsubscribed
<ide> * @param unit the time unit of the timeout
<ide> * @param scheduler the target scheduler to wait on before disconnecting
<del> * @return the new Flowable instance
<add> * @return the new {@link Flowable} instance
<ide> * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null}
<ide> * @throws IllegalArgumentException if {@code subscriberCount} is non-positive
<ide> * @since 2.2
<ide> public final Flowable<T> refCount(int subscriberCount, long timeout, @NonNull Ti
<ide> }
<ide>
<ide> /**
<del> * Returns a Flowable that automatically connects (at most once) to this ConnectableFlowable
<del> * when the first Subscriber subscribes.
<add> * Returns a {@link Flowable} that automatically connects (at most once) to this {@code ConnectableFlowable}
<add> * when the first {@link Subscriber} subscribes.
<ide> * <p>
<ide> * <img width="640" height="392" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/autoConnect.f.png" alt="">
<ide> * <p>
<ide> * The connection happens after the first subscription and happens at most once
<del> * during the lifetime of the returned Flowable. If this ConnectableFlowable
<del> * terminates, the connection is never renewed, no matter how Subscribers come
<add> * during the lifetime of the returned {@code Flowable}. If this {@code ConnectableFlowable}
<add> * terminates, the connection is never renewed, no matter how {@code Subscriber}s come
<ide> * and go. Use {@link #refCount()} to renew a connection or dispose an active
<del> * connection when all {@code Subscriber}s have cancelled their {@code Subscription}s.
<add> * connection when all {@code Subscriber}s have cancelled their {@link Subscription}s.
<ide> * <p>
<ide> * This overload does not allow disconnecting the connection established via
<ide> * {@link #connect(Consumer)}. Use the {@link #autoConnect(int, Consumer)} overload
<del> * to gain access to the {@code Disposable} representing the only connection.
<add> * to gain access to the {@link Disposable} representing the only connection.
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<ide> * <dd>The operator itself doesn't interfere with backpressure which is determined by
<ide> public final Flowable<T> refCount(int subscriberCount, long timeout, @NonNull Ti
<ide> * <dd>{@code autoConnect} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> * </dl>
<ide> *
<del> * @return a Flowable that automatically connects to this ConnectableFlowable
<del> * when the first Subscriber subscribes
<add> * @return a new {@code Flowable} instance that automatically connects to this {@code ConnectableFlowable}
<add> * when the first {@code Subscriber} subscribes
<ide> * @see #refCount()
<ide> * @see #autoConnect(int, Consumer)
<ide> */
<ide> public Flowable<T> autoConnect() {
<ide> return autoConnect(1);
<ide> }
<ide> /**
<del> * Returns a Flowable that automatically connects (at most once) to this ConnectableFlowable
<del> * when the specified number of Subscribers subscribe to it.
<add> * Returns a {@link Flowable} that automatically connects (at most once) to this {@code ConnectableFlowable}
<add> * when the specified number of {@link Subscriber}s subscribe to it.
<ide> * <p>
<ide> * <img width="640" height="392" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/autoConnect.f.png" alt="">
<ide> * <p>
<ide> * The connection happens after the given number of subscriptions and happens at most once
<del> * during the lifetime of the returned Flowable. If this ConnectableFlowable
<del> * terminates, the connection is never renewed, no matter how Subscribers come
<add> * during the lifetime of the returned {@code Flowable}. If this {@code ConnectableFlowable}
<add> * terminates, the connection is never renewed, no matter how {@code Subscriber}s come
<ide> * and go. Use {@link #refCount()} to renew a connection or dispose an active
<del> * connection when all {@code Subscriber}s have cancelled their {@code Subscription}s.
<add> * connection when all {@code Subscriber}s have cancelled their {@link Subscription}s.
<ide> * <p>
<ide> * This overload does not allow disconnecting the connection established via
<ide> * {@link #connect(Consumer)}. Use the {@link #autoConnect(int, Consumer)} overload
<del> * to gain access to the {@code Disposable} representing the only connection.
<add> * to gain access to the {@link Disposable} representing the only connection.
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<ide> * <dd>The operator itself doesn't interfere with backpressure which is determined by
<ide> public Flowable<T> autoConnect() {
<ide> * </dl>
<ide> *
<ide> * @param numberOfSubscribers the number of subscribers to await before calling connect
<del> * on the ConnectableFlowable. A non-positive value indicates
<add> * on the {@code ConnectableFlowable}. A non-positive value indicates
<ide> * an immediate connection.
<del> * @return a Flowable that automatically connects to this ConnectableFlowable
<del> * when the specified number of Subscribers subscribe to it
<add> * @return a new {@code Flowable} instance that automatically connects to this {@code ConnectableFlowable}
<add> * when the specified number of {@code Subscriber}s subscribe to it
<ide> */
<ide> @NonNull
<ide> @CheckReturnValue
<ide> public Flowable<T> autoConnect(int numberOfSubscribers) {
<ide> }
<ide>
<ide> /**
<del> * Returns a Flowable that automatically connects (at most once) to this ConnectableFlowable
<del> * when the specified number of Subscribers subscribe to it and calls the
<del> * specified callback with the Subscription associated with the established connection.
<add> * Returns a {@link Flowable} that automatically connects (at most once) to this {@code ConnectableFlowable}
<add> * when the specified number of {@link Subscriber}s subscribe to it and calls the
<add> * specified callback with the {@link Disposable} associated with the established connection.
<ide> * <p>
<ide> * <img width="640" height="392" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/autoConnect.f.png" alt="">
<ide> * <p>
<ide> * The connection happens after the given number of subscriptions and happens at most once
<del> * during the lifetime of the returned Flowable. If this ConnectableFlowable
<del> * terminates, the connection is never renewed, no matter how Subscribers come
<add> * during the lifetime of the returned {@code Flowable}. If this {@code ConnectableFlowable}
<add> * terminates, the connection is never renewed, no matter how {@code Subscriber}s come
<ide> * and go. Use {@link #refCount()} to renew a connection or dispose an active
<del> * connection when all {@code Subscriber}s have cancelled their {@code Subscription}s.
<add> * connection when all {@code Subscriber}s have cancelled their {@link Subscription}s.
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<ide> * <dd>The operator itself doesn't interfere with backpressure which is determined by
<ide> public Flowable<T> autoConnect(int numberOfSubscribers) {
<ide> * </dl>
<ide> *
<ide> * @param numberOfSubscribers the number of subscribers to await before calling connect
<del> * on the ConnectableFlowable. A non-positive value indicates
<add> * on the {@code ConnectableFlowable}. A non-positive value indicates
<ide> * an immediate connection.
<del> * @param connection the callback Consumer that will receive the Subscription representing the
<add> * @param connection the callback {@link Consumer} that will receive the {@code Disposable} representing the
<ide> * established connection
<del> * @return a Flowable that automatically connects to this ConnectableFlowable
<del> * when the specified number of Subscribers subscribe to it and calls the
<del> * specified callback with the Subscription associated with the established connection
<add> * @return a new {@code Flowable} instance that automatically connects to this {@code ConnectableFlowable}
<add> * when the specified number of {@code Subscriber}s subscribe to it and calls the
<add> * specified callback with the {@code Disposable} associated with the established connection
<ide> * @throws NullPointerException if {@code connection} is {@code null}
<ide> */
<ide> @NonNull
<ide><path>src/main/java/io/reactivex/rxjava3/observables/ConnectableObservable.java
<ide> * <img width="640" height="510" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/publishConnect.v3.png" alt="">
<ide> * <p>
<ide> * When the upstream terminates, the {@code ConnectableObservable} remains in this terminated state and,
<del> * depending on the actual underlying implementation, relays cached events to late {@link Observer}s.
<add> * depending on the actual underlying implementation, relays cached events to late {@code Observer}s.
<ide> * In order to reuse and restart this {@code ConnectableObservable}, the {@link #reset()} method has to be called.
<del> * When called, this {@code ConnectableObservable} will appear as fresh, unconnected source to new {@link Observer}s.
<del> * Disposing the connection will reset the {@code ConnectableFlowable} to its fresh state and there is no need to call
<del> * {@code reset()} in this case.
<add> * When called, this {@code ConnectableObservable} will appear as fresh, unconnected source to new {@code Observer}s.
<add> * Disposing the connection will reset the {@code ConnectableObservable} to its fresh state and there is no need to call
<add> * {@link #reset()} in this case.
<ide> * <p>
<ide> * Note that although {@link #connect()} and {@link #reset()} are safe to call from multiple threads, it is recommended
<ide> * a dedicated thread or business logic manages the connection or resetting of a {@code ConnectableObservable} so that
<ide> * there is no unwanted signal loss due to early {@code connect()} or {@code reset()} calls while {@code Observer}s are
<ide> * still being subscribed to to this {@code ConnectableObservable} to receive signals from the get go.
<ide> *
<del> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Connectable-Observable-Operators">RxJava Wiki:
<del> * Connectable Observable Operators</a>
<add> * @see <a href="https://github.com/ReactiveX/RxJava/wiki/Connectable-Observable-Operators">RxJava Wiki: Connectable Observable Operators</a>
<ide> * @param <T>
<ide> * the type of items emitted by the {@code ConnectableObservable}
<ide> */
<ide> public abstract void connect(@NonNull Consumer<? super Disposable> connection);
<ide>
<ide> /**
<del> * Resets this ConnectableObservable into its fresh state if it has terminated
<add> * Resets this {@code ConnectableObservable} into its fresh state if it has terminated
<ide> * or has been disposed.
<ide> * <p>
<ide> * Calling this method on a fresh or active {@code ConnectableObservable} has no effect.
<ide> * <dd>The behavior is determined by the implementor of this abstract class.</dd>
<ide> * </dl>
<ide> *
<del> * @return the subscription representing the connection
<add> * @return the {@link Disposable} representing the connection
<ide> * @see <a href="http://reactivex.io/documentation/operators/connect.html">ReactiveX documentation: Connect</a>
<ide> */
<ide> @NonNull
<ide> public final Disposable connect() {
<ide> }
<ide>
<ide> /**
<del> * Returns an {@code Observable} that stays connected to this {@code ConnectableObservable} as long as there
<add> * Returns an {@link Observable} that stays connected to this {@code ConnectableObservable} as long as there
<ide> * is at least one subscription to this {@code ConnectableObservable}.
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>This {@code refCount} overload does not operate on any particular {@link Scheduler}.</dd>
<ide> * </dl>
<del> * @return an {@link Observable}
<add> * @return a new {@code Observable} instance
<ide> * @see <a href="http://reactivex.io/documentation/operators/refcount.html">ReactiveX documentation: RefCount</a>
<ide> * @see #refCount(int)
<ide> * @see #refCount(long, TimeUnit)
<ide> public Observable<T> refCount() {
<ide>
<ide> /**
<ide> * Connects to the upstream {@code ConnectableObservable} if the number of subscribed
<del> * observers reaches the specified count and disconnect if all subscribers have unsubscribed.
<add> * observers reaches the specified count and disconnect if all {@link Observer}s have unsubscribed.
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>This {@code refCount} overload does not operate on any particular {@link Scheduler}.</dd>
<ide> * </dl>
<ide> * <p>History: 2.1.14 - experimental
<del> * @param subscriberCount the number of subscribers required to connect to the upstream
<del> * @return the new Observable instance
<add> * @param observerCount the number of {@code Observer}s required to connect to the upstream
<add> * @return the new {@link Observable} instance
<add> * @throws IllegalArgumentException if {@code observerCount} is non-positive
<ide> * @since 2.2
<ide> */
<ide> @CheckReturnValue
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> @NonNull
<del> public final Observable<T> refCount(int subscriberCount) {
<del> return refCount(subscriberCount, 0, TimeUnit.NANOSECONDS, Schedulers.trampoline());
<add> public final Observable<T> refCount(int observerCount) {
<add> return refCount(observerCount, 0, TimeUnit.NANOSECONDS, Schedulers.trampoline());
<ide> }
<ide>
<ide> /**
<ide> * Connects to the upstream {@code ConnectableObservable} if the number of subscribed
<ide> * observers reaches 1 and disconnect after the specified
<del> * timeout if all subscribers have unsubscribed.
<add> * timeout if all {@link Observer}s have unsubscribed.
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>This {@code refCount} overload operates on the {@code computation} {@link Scheduler}.</dd>
<ide> * </dl>
<ide> * <p>History: 2.1.14 - experimental
<del> * @param timeout the time to wait before disconnecting after all subscribers unsubscribed
<add> * @param timeout the time to wait before disconnecting after all {@code Observer}s unsubscribed
<ide> * @param unit the time unit of the timeout
<del> * @return the new Observable instance
<add> * @return the new {@link Observable} instance
<ide> * @throws NullPointerException if {@code unit} is {@code null}
<ide> * @see #refCount(long, TimeUnit, Scheduler)
<ide> * @since 2.2
<ide> public final Observable<T> refCount(long timeout, @NonNull TimeUnit unit) {
<ide> /**
<ide> * Connects to the upstream {@code ConnectableObservable} if the number of subscribed
<ide> * observers reaches 1 and disconnect after the specified
<del> * timeout if all subscribers have unsubscribed.
<add> * timeout if all {@link Observer}s have unsubscribed.
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>This {@code refCount} overload operates on the specified {@link Scheduler}.</dd>
<ide> * </dl>
<ide> * <p>History: 2.1.14 - experimental
<del> * @param timeout the time to wait before disconnecting after all subscribers unsubscribed
<add> * @param timeout the time to wait before disconnecting after all {@code Observer}s unsubscribed
<ide> * @param unit the time unit of the timeout
<ide> * @param scheduler the target scheduler to wait on before disconnecting
<del> * @return the new Observable instance
<add> * @return the new {@link Observable} instance
<ide> * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null}
<ide> * @since 2.2
<ide> */
<ide> public final Observable<T> refCount(long timeout, @NonNull TimeUnit unit, @NonNu
<ide> /**
<ide> * Connects to the upstream {@code ConnectableObservable} if the number of subscribed
<ide> * observers reaches the specified count and disconnect after the specified
<del> * timeout if all subscribers have unsubscribed.
<add> * timeout if all {@link Observer}s have unsubscribed.
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>This {@code refCount} overload operates on the {@code computation} {@link Scheduler}.</dd>
<ide> * </dl>
<ide> * <p>History: 2.1.14 - experimental
<del> * @param subscriberCount the number of subscribers required to connect to the upstream
<del> * @param timeout the time to wait before disconnecting after all subscribers unsubscribed
<add> * @param observerCount the number of {@code Observer}s required to connect to the upstream
<add> * @param timeout the time to wait before disconnecting after all {@code Observer}s unsubscribed
<ide> * @param unit the time unit of the timeout
<del> * @return the new Observable instance
<add> * @return the new {@link Observable} instance
<ide> * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null}
<add> * @throws IllegalArgumentException if {@code observerCount} is non-positive
<ide> * @see #refCount(int, long, TimeUnit, Scheduler)
<ide> * @since 2.2
<ide> */
<ide> @CheckReturnValue
<ide> @SchedulerSupport(SchedulerSupport.COMPUTATION)
<ide> @NonNull
<del> public final Observable<T> refCount(int subscriberCount, long timeout, @NonNull TimeUnit unit) {
<del> return refCount(subscriberCount, timeout, unit, Schedulers.computation());
<add> public final Observable<T> refCount(int observerCount, long timeout, @NonNull TimeUnit unit) {
<add> return refCount(observerCount, timeout, unit, Schedulers.computation());
<ide> }
<ide>
<ide> /**
<ide> * Connects to the upstream {@code ConnectableObservable} if the number of subscribed
<ide> * observers reaches the specified count and disconnect after the specified
<del> * timeout if all subscribers have unsubscribed.
<add> * timeout if all {@link Observer}s have unsubscribed.
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>This {@code refCount} overload operates on the specified {@link Scheduler}.</dd>
<ide> * </dl>
<ide> * <p>History: 2.1.14 - experimental
<del> * @param subscriberCount the number of subscribers required to connect to the upstream
<del> * @param timeout the time to wait before disconnecting after all subscribers unsubscribed
<add> * @param observerCount the number of {@code Observer}s required to connect to the upstream
<add> * @param timeout the time to wait before disconnecting after all {@code Observer}s unsubscribed
<ide> * @param unit the time unit of the timeout
<ide> * @param scheduler the target scheduler to wait on before disconnecting
<del> * @return the new Observable instance
<add> * @return the new {@link Observable} instance
<ide> * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null}
<del> * @throws IllegalArgumentException if {@code subscriberCount} is non-positive
<add> * @throws IllegalArgumentException if {@code observerCount} is non-positive
<ide> * @since 2.2
<ide> */
<ide> @CheckReturnValue
<ide> @SchedulerSupport(SchedulerSupport.CUSTOM)
<ide> @NonNull
<del> public final Observable<T> refCount(int subscriberCount, long timeout, @NonNull TimeUnit unit, @NonNull Scheduler scheduler) {
<del> ObjectHelper.verifyPositive(subscriberCount, "subscriberCount");
<add> public final Observable<T> refCount(int observerCount, long timeout, @NonNull TimeUnit unit, @NonNull Scheduler scheduler) {
<add> ObjectHelper.verifyPositive(observerCount, "observerCount");
<ide> Objects.requireNonNull(unit, "unit is null");
<ide> Objects.requireNonNull(scheduler, "scheduler is null");
<del> return RxJavaPlugins.onAssembly(new ObservableRefCount<>(this, subscriberCount, timeout, unit, scheduler));
<add> return RxJavaPlugins.onAssembly(new ObservableRefCount<>(this, observerCount, timeout, unit, scheduler));
<ide> }
<ide>
<ide> /**
<del> * Returns an Observable that automatically connects (at most once) to this ConnectableObservable
<del> * when the first Observer subscribes.
<add> * Returns an {@link Observable} that automatically connects (at most once) to this {@code ConnectableObservable}
<add> * when the first {@link Observer} subscribes.
<ide> * <p>
<ide> * <img width="640" height="348" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/autoConnect.o.png" alt="">
<ide> * <p>
<ide> * The connection happens after the first subscription and happens at most once
<del> * during the lifetime of the returned Observable. If this ConnectableObservable
<del> * terminates, the connection is never renewed, no matter how Observers come
<add> * during the lifetime of the returned {@code Observable}. If this {@code ConnectableObservable}
<add> * terminates, the connection is never renewed, no matter how {@code Observer}s come
<ide> * and go. Use {@link #refCount()} to renew a connection or dispose an active
<del> * connection when all {@code Observer}s have disposed their {@code Disposable}s.
<add> * connection when all {@code Observer}s have disposed their {@link Disposable}s.
<ide> * <p>
<ide> * This overload does not allow disconnecting the connection established via
<ide> * {@link #connect(Consumer)}. Use the {@link #autoConnect(int, Consumer)} overload
<ide> public final Observable<T> refCount(int subscriberCount, long timeout, @NonNull
<ide> * <dd>{@code autoConnect} overload does not operate on any particular {@link Scheduler}.</dd>
<ide> * </dl>
<ide> *
<del> * @return an Observable that automatically connects to this ConnectableObservable
<del> * when the first Observer subscribes
<add> * @return a new {@code Observable} instance that automatically connects to this {@code ConnectableObservable}
<add> * when the first {@code Observer} subscribes
<ide> */
<ide> @NonNull
<ide> @CheckReturnValue
<ide> public Observable<T> autoConnect() {
<ide> }
<ide>
<ide> /**
<del> * Returns an Observable that automatically connects (at most once) to this ConnectableObservable
<del> * when the specified number of Observers subscribe to it.
<add> * Returns an {@link Observable} that automatically connects (at most once) to this {@code ConnectableObservable}
<add> * when the specified number of {@link Observer}s subscribe to it.
<ide> * <p>
<ide> * <img width="640" height="348" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/autoConnect.o.png" alt="">
<ide> * <p>
<ide> * The connection happens after the given number of subscriptions and happens at most once
<del> * during the lifetime of the returned Observable. If this ConnectableObservable
<del> * terminates, the connection is never renewed, no matter how Observers come
<add> * during the lifetime of the returned {@code Observable}. If this {@code ConnectableObservable}
<add> * terminates, the connection is never renewed, no matter how {@code Observer}s come
<ide> * and go. Use {@link #refCount()} to renew a connection or dispose an active
<del> * connection when all {@code Observer}s have disposed their {@code Disposable}s.
<add> * connection when all {@code Observer}s have disposed their {@link Disposable}s.
<ide> * <p>
<ide> * This overload does not allow disconnecting the connection established via
<ide> * {@link #connect(Consumer)}. Use the {@link #autoConnect(int, Consumer)} overload
<ide> public Observable<T> autoConnect() {
<ide> * <dd>{@code autoConnect} overload does not operate on any particular {@link Scheduler}.</dd>
<ide> * </dl>
<ide> *
<del> * @param numberOfSubscribers the number of subscribers to await before calling connect
<del> * on the ConnectableObservable. A non-positive value indicates
<add> * @param numberOfObservers the number of subscribers to await before calling connect
<add> * on the {@code ConnectableObservable}. A non-positive value indicates
<ide> * an immediate connection.
<del> * @return an Observable that automatically connects to this ConnectableObservable
<del> * when the specified number of Subscribers subscribe to it
<add> * @return a new {@code Observable} instance that automatically connects to this {@code ConnectableObservable}
<add> * when the specified number of {@code Observer}s subscribe to it
<ide> */
<ide> @NonNull
<ide> @CheckReturnValue
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<del> public Observable<T> autoConnect(int numberOfSubscribers) {
<del> return autoConnect(numberOfSubscribers, Functions.emptyConsumer());
<add> public Observable<T> autoConnect(int numberOfObservers) {
<add> return autoConnect(numberOfObservers, Functions.emptyConsumer());
<ide> }
<ide>
<ide> /**
<del> * Returns an Observable that automatically connects (at most once) to this ConnectableObservable
<del> * when the specified number of Subscribers subscribe to it and calls the
<del> * specified callback with the Subscription associated with the established connection.
<add> * Returns an {@link Observable} that automatically connects (at most once) to this {@code ConnectableObservable}
<add> * when the specified number of {@link Observer}s subscribe to it and calls the
<add> * specified callback with the {@link Disposable} associated with the established connection.
<ide> * <p>
<ide> * <img width="640" height="348" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/autoConnect.o.png" alt="">
<ide> * <p>
<ide> * The connection happens after the given number of subscriptions and happens at most once
<del> * during the lifetime of the returned Observable. If this ConnectableObservable
<del> * terminates, the connection is never renewed, no matter how Observers come
<add> * during the lifetime of the returned {@code Observable}. If this {@code ConnectableObservable}
<add> * terminates, the connection is never renewed, no matter how {@code Observer}s come
<ide> * and go. Use {@link #refCount()} to renew a connection or dispose an active
<ide> * connection when all {@code Observer}s have disposed their {@code Disposable}s.
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code autoConnect} overload does not operate on any particular {@link Scheduler}.</dd>
<ide> * </dl>
<ide> *
<del> * @param numberOfSubscribers the number of subscribers to await before calling connect
<del> * on the ConnectableObservable. A non-positive value indicates
<add> * @param numberOfObservers the number of subscribers to await before calling connect
<add> * on the {@code ConnectableObservable}. A non-positive value indicates
<ide> * an immediate connection.
<del> * @param connection the callback Consumer that will receive the Subscription representing the
<add> * @param connection the callback {@link Consumer} that will receive the {@code Disposable} representing the
<ide> * established connection
<del> * @return an Observable that automatically connects to this ConnectableObservable
<del> * when the specified number of Subscribers subscribe to it and calls the
<del> * specified callback with the Subscription associated with the established connection
<add> * @return a new {@code Observable} instance that automatically connects to this {@code ConnectableObservable}
<add> * when the specified number of {@code Observer}s subscribe to it and calls the
<add> * specified callback with the {@code Disposable} associated with the established connection
<ide> * @throws NullPointerException if {@code connection} is {@code null}
<ide> */
<ide> @NonNull
<ide> @CheckReturnValue
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<del> public Observable<T> autoConnect(int numberOfSubscribers, @NonNull Consumer<? super Disposable> connection) {
<add> public Observable<T> autoConnect(int numberOfObservers, @NonNull Consumer<? super Disposable> connection) {
<ide> Objects.requireNonNull(connection, "connection is null");
<del> if (numberOfSubscribers <= 0) {
<add> if (numberOfObservers <= 0) {
<ide> this.connect(connection);
<ide> return RxJavaPlugins.onAssembly(this);
<ide> }
<del> return RxJavaPlugins.onAssembly(new ObservableAutoConnect<>(this, numberOfSubscribers, connection));
<add> return RxJavaPlugins.onAssembly(new ObservableAutoConnect<>(this, numberOfObservers, connection));
<ide> }
<ide> }
<ide><path>src/test/java/io/reactivex/rxjava3/validators/JavadocCodesAndLinks.java
<ide> public void checkCompositeDisposable() throws Exception {
<ide> checkSource("CompositeDisposable", "io.reactivex.rxjava3.disposables");
<ide> }
<ide>
<add> @Test
<add> public void checkConnectableFlowable() throws Exception {
<add> checkSource("ConnectableFlowable", "io.reactivex.rxjava3.flowables");
<add> }
<add>
<add> @Test
<add> public void checkConnectableObservable() throws Exception {
<add> checkSource("ConnectableObservable", "io.reactivex.rxjava3.observables");
<add> }
<add>
<ide> static void checkSource(String baseClassName, String packageName) throws Exception {
<ide> File f = TestHelper.findSource(baseClassName, packageName);
<ide> if (f == null) { | 3 |
Text | Text | remove a link | b494bb9d01da2a596c97aef55a9c66c39dbba9ea | <ide><path>readme.md
<ide> Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable, creative experience to be truly fulfilling. Laravel attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as:
<ide>
<ide> - [Simple, fast routing engine](https://laravel.com/docs/routing).
<del>- [Painless request validation](https://laravel.com/docs/validation).
<ide> - [Powerful dependency injection container](https://laravel.com/docs/container).
<ide> - Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
<ide> - Database agnostic [schema migrations](https://laravel.com/docs/migrations). | 1 |
Javascript | Javascript | update mutable_array example | 8ebca79ae105752cfd8452a8b2f41aeb1aedb54a | <ide><path>packages/ember-runtime/lib/mixins/mutable_array.js
<ide> export default Mixin.create(EmberArray, MutableEnumerable, {
<ide> want to reuse an existing array without having to recreate it.
<ide>
<ide> ```javascript
<del> var colors = ["red", "green", "blue"];
<add> var colors = ['red', 'green', 'blue'];
<add>
<ide> color.length(); // 3
<ide> colors.clear(); // []
<ide> colors.length(); // 0
<ide> export default Mixin.create(EmberArray, MutableEnumerable, {
<ide> specified index.
<ide>
<ide> ```javascript
<del> var colors = ["red", "green", "blue"];
<del> colors.insertAt(2, "yellow"); // ["red", "green", "yellow", "blue"]
<del> colors.insertAt(5, "orange"); // Error: Index out of range
<add> var colors = ['red', 'green', 'blue'];
<add>
<add> colors.insertAt(2, 'yellow'); // ['red', 'green', 'yellow', 'blue']
<add> colors.insertAt(5, 'orange'); // Error: Index out of range
<ide> ```
<ide>
<ide> @method insertAt
<ide> export default Mixin.create(EmberArray, MutableEnumerable, {
<ide> length this method will throw an `OUT_OF_RANGE_EXCEPTION`.
<ide>
<ide> ```javascript
<del> var colors = ["red", "green", "blue", "yellow", "orange"];
<del> colors.removeAt(0); // ["green", "blue", "yellow", "orange"]
<del> colors.removeAt(2, 2); // ["green", "blue"]
<add> var colors = ['red', 'green', 'blue', 'yellow', 'orange'];
<add>
<add> colors.removeAt(0); // ['green', 'blue', 'yellow', 'orange']
<add> colors.removeAt(2, 2); // ['green', 'blue']
<ide> colors.removeAt(4, 2); // Error: Index out of range
<ide> ```
<ide>
<ide> export default Mixin.create(EmberArray, MutableEnumerable, {
<ide> is KVO-compliant.
<ide>
<ide> ```javascript
<del> var colors = ["red", "green"];
<del> colors.pushObject("black"); // ["red", "green", "black"]
<del> colors.pushObject(["yellow"]); // ["red", "green", ["yellow"]]
<add> var colors = ['red', 'green'];
<add>
<add> colors.pushObject('black'); // ['red', 'green', 'black']
<add> colors.pushObject(['yellow']); // ['red', 'green', ['yellow']]
<ide> ```
<ide>
<ide> @method pushObject
<ide> export default Mixin.create(EmberArray, MutableEnumerable, {
<ide> notifying observers of the change until all objects are added.
<ide>
<ide> ```javascript
<del> var colors = ["red"];
<del> colors.pushObjects(["yellow", "orange"]); // ["red", "yellow", "orange"]
<add> var colors = ['red'];
<add>
<add> colors.pushObjects(['yellow', 'orange']); // ['red', 'yellow', 'orange']
<ide> ```
<ide>
<ide> @method pushObjects
<ide> export default Mixin.create(EmberArray, MutableEnumerable, {
<ide> it is KVO-compliant.
<ide>
<ide> ```javascript
<del> var colors = ["red", "green", "blue"];
<del> colors.popObject(); // "blue"
<del> console.log(colors); // ["red", "green"]
<add> var colors = ['red', 'green', 'blue'];
<add>
<add> colors.popObject(); // 'blue'
<add> console.log(colors); // ['red', 'green']
<ide> ```
<ide>
<ide> @method popObject
<ide> export default Mixin.create(EmberArray, MutableEnumerable, {
<ide> like `shift()` but it is KVO-compliant.
<ide>
<ide> ```javascript
<del> var colors = ["red", "green", "blue"];
<del> colors.shiftObject(); // "red"
<del> console.log(colors); // ["green", "blue"]
<add> var colors = ['red', 'green', 'blue'];
<add>
<add> colors.shiftObject(); // 'red'
<add> console.log(colors); // ['green', 'blue']
<ide> ```
<ide>
<ide> @method shiftObject
<ide> export default Mixin.create(EmberArray, MutableEnumerable, {
<ide> KVO-compliant.
<ide>
<ide> ```javascript
<del> var colors = ["red"];
<del> colors.unshiftObject("yellow"); // ["yellow", "red"]
<del> colors.unshiftObject(["black"]); // [["black"], "yellow", "red"]
<add> var colors = ['red'];
<add>
<add> colors.unshiftObject('yellow'); // ['yellow', 'red']
<add> colors.unshiftObject(['black']); // [['black'], 'yellow', 'red']
<ide> ```
<ide>
<ide> @method unshiftObject
<ide> export default Mixin.create(EmberArray, MutableEnumerable, {
<ide> observers until all objects have been added.
<ide>
<ide> ```javascript
<del> var colors = ["red"];
<del> colors.unshiftObjects(["black", "white"]); // ["black", "white", "red"]
<del> colors.unshiftObjects("yellow"); // Type Error: 'undefined' is not a function
<add> var colors = ['red'];
<add>
<add> colors.unshiftObjects(['black', 'white']); // ['black', 'white', 'red']
<add> colors.unshiftObjects('yellow'); // Type Error: 'undefined' is not a function
<ide> ```
<ide>
<ide> @method unshiftObjects
<ide> export default Mixin.create(EmberArray, MutableEnumerable, {
<ide> If argument is an empty array receiver will be cleared.
<ide>
<ide> ```javascript
<del> var colors = ["red", "green", "blue"];
<del> colors.setObjects(["black", "white"]); // ["black", "white"]
<add> var colors = ['red', 'green', 'blue'];
<add>
<add> colors.setObjects(['black', 'white']); // ['black', 'white']
<ide> colors.setObjects([]); // []
<ide> ```
<ide>
<ide> export default Mixin.create(EmberArray, MutableEnumerable, {
<ide> Remove all occurrences of an object in the array.
<ide>
<ide> ```javascript
<del> var cities = ["Chicago", "Berlin", "Lima", "Chicago"];
<del> cities.removeObject("Chicago"); // ["Berlin", "Lima"]
<del> cities.removeObject("Lima"); // ["Berlin"]
<del> cities.removeObject("Tokyo") // ["Berlin"]
<add> var cities = ['Chicago', 'Berlin', 'Lima', 'Chicago'];
<add>
<add> cities.removeObject('Chicago'); // ['Berlin', 'Lima']
<add> cities.removeObject('Lima'); // ['Berlin']
<add> cities.removeObject('Tokyo') // ['Berlin']
<ide> ```
<ide>
<ide> @method removeObject
<ide> export default Mixin.create(EmberArray, MutableEnumerable, {
<ide> present in the array.
<ide>
<ide> ```javascript
<del> var cities = ["Chicago", "Berlin"];
<del> cities.addObject("Lima"); // ["Chicago", "Berlin", "Lima"]
<del> cities.addObject("Berlin"); // ["Chicago", "Berlin", "Lima"]
<add> var cities = ['Chicago', 'Berlin'];
<add>
<add> cities.addObject('Lima'); // ['Chicago', 'Berlin', 'Lima']
<add> cities.addObject('Berlin'); // ['Chicago', 'Berlin', 'Lima']
<ide> ```
<ide>
<ide> @method addObject
<ide> export default Mixin.create(EmberArray, MutableEnumerable, {
<ide>
<ide> return this;
<ide> }
<del>
<ide> }); | 1 |
Javascript | Javascript | use consistent option context for scales | fc65679a07d2d0ab20e252cee292c671569e9aab | <ide><path>src/core/core.scale.js
<ide> export default class Scale extends Element {
<ide> const items = [];
<ide>
<ide> let context = {
<add> chart,
<ide> scale: me,
<ide> tick: ticks[0],
<add> index: 0,
<ide> };
<ide> const axisWidth = gridLines.drawBorder ? resolve([gridLines.borderWidth, gridLines.lineWidth, 0], context, 0) : 0;
<ide> const axisHalfWidth = axisWidth / 2;
<ide> export default class Scale extends Element {
<ide> const tick = ticks[i] || {};
<ide>
<ide> context = {
<add> chart,
<ide> scale: me,
<ide> tick,
<add> index: i,
<ide> };
<ide>
<ide> const lineWidth = resolve([gridLines.lineWidth], context, i);
<ide> export default class Scale extends Element {
<ide> const ctx = me.ctx;
<ide> const chart = me.chart;
<ide> let context = {
<add> chart,
<ide> scale: me,
<ide> tick: me.ticks[0],
<add> index: 0,
<ide> };
<ide> const axisWidth = gridLines.drawBorder ? resolve([gridLines.borderWidth, gridLines.lineWidth, 0], context, 0) : 0;
<ide> const items = me._gridLineItems || (me._gridLineItems = me._computeGridLineItems(chartArea));
<ide> export default class Scale extends Element {
<ide> // Draw the line at the edge of the axis
<ide> const firstLineWidth = axisWidth;
<ide> context = {
<add> chart,
<ide> scale: me,
<ide> tick: me.ticks[me._ticksLength - 1],
<add> index: me._ticksLength - 1,
<ide> };
<ide> const lastLineWidth = resolve([gridLines.lineWidth, 1], context, me._ticksLength - 1);
<ide> const borderValue = me._borderValue; | 1 |
PHP | PHP | add example test file | ae7faf1e45161d58f01c355b81ffdec6f5ff5a4b | <ide><path>phpunit.php
<ide> // --------------------------------------------------------------
<ide> // Override the framework paths if testing Laravel.
<ide> // --------------------------------------------------------------
<del>if (in_array('build.xml', $_SERVER['argv']))
<add>foreach ($_SERVER['argv'] as $argument)
<ide> {
<del> define('APP_PATH', realpath('bundles/laravel-tests/application').DS);
<add> if (strpos($argument, 'build.xml') !== false)
<add> {
<add> define('APP_PATH', realpath('bundles/laravel-tests/application').DS);
<ide>
<del> define('BUNDLE_PATH', realpath('bundles/laravel-tests/bundles').DS);
<add> define('BUNDLE_PATH', realpath('bundles/laravel-tests/bundles').DS);
<ide>
<del> define('STORAGE_PATH', realpath('bundles/laravel-tests/storage').DS);
<add> define('STORAGE_PATH', realpath('bundles/laravel-tests/storage').DS);
<add> }
<ide> }
<ide>
<ide> // --------------------------------------------------------------
<ide><path>tests/application/example.test.php
<add><?php
<add>
<add>class TestExample extends PHPUnit_Framework_TestCase {
<add>
<add> /**
<add> * Test that a given condition is met.
<add> *
<add> * @return void
<add> */
<add> public function testSomethingIsTrue()
<add> {
<add> $this->assertTrue(true);
<add> }
<add>
<add>}
<ide>\ No newline at end of file | 2 |
Javascript | Javascript | improve error property inspection | f7c96856f90f4fcd53bc3c166736a53e9c25d729 | <ide><path>lib/internal/util/inspect.js
<ide> function formatProperty(ctx, value, recurseTimes, key, type) {
<ide> return `${name}:${extra}${str}`;
<ide> }
<ide>
<del>function isBelowBreakLength(ctx, output, start) {
<add>function isBelowBreakLength(ctx, output, start, base) {
<ide> // Each entry is separated by at least a comma. Thus, we start with a total
<ide> // length of at least `output.length`. In addition, some cases have a
<ide> // whitespace in-between each other that is added to the total as well.
<ide> function isBelowBreakLength(ctx, output, start) {
<ide> return false;
<ide> }
<ide> }
<del> return true;
<add> // Do not line up properties on the same line if `base` contains line breaks.
<add> return base === '' || !base.includes('\n');
<ide> }
<ide>
<ide> function reduceToSingleString(ctx, output, base, braces, combine = false) {
<ide> function reduceToSingleString(ctx, output, base, braces, combine = false) {
<ide> // that may reduce `breakLength`.
<ide> const start = output.length + ctx.indentationLvl +
<ide> braces[0].length + base.length + 10;
<del> if (isBelowBreakLength(ctx, output, start)) {
<add> if (isBelowBreakLength(ctx, output, start, base)) {
<ide> return `${base ? `${base} ` : ''}${braces[0]} ${join(output, ', ')} ` +
<ide> braces[1];
<ide> }
<ide> function reduceToSingleString(ctx, output, base, braces, combine = false) {
<ide> }
<ide> // Line up all entries on a single line in case the entries do not exceed
<ide> // `breakLength`.
<del> if (isBelowBreakLength(ctx, output, 0)) {
<add> if (isBelowBreakLength(ctx, output, 0, base)) {
<ide> return `${braces[0]}${base ? ` ${base}` : ''} ${join(output, ', ')} ` +
<ide> braces[1];
<ide> }
<ide><path>test/parallel/test-repl-pretty-stack.js
<ide> const tests = [
<ide> {
<ide> command: '(() => { const err = Error(\'Whoops!\'); ' +
<ide> 'err.foo = \'bar\'; throw err; })()',
<del> expected: 'Thrown:\n{ Error: Whoops!\n at repl:1:22 foo: \'bar\' }\n',
<add> expected: 'Thrown:\n{ Error: Whoops!\n at repl:1:22\n foo: \'bar\' }\n',
<ide> },
<ide> {
<ide> command: '(() => { const err = Error(\'Whoops!\'); ' +
<ide> 'err.foo = \'bar\'; throw err; })()',
<del> expected: 'Thrown:\n{ Error: Whoops!\n at repl:1:22 foo: ' +
<add> expected: 'Thrown:\n{ Error: Whoops!\n at repl:1:22\n foo: ' +
<ide> "\u001b[32m'bar'\u001b[39m }\n",
<ide> useColors: true
<ide> },
<ide><path>test/parallel/test-repl.js
<ide> const errorTests = [
<ide> /^ at .*/,
<ide> /^ at .*/,
<ide> /^ at .*/,
<del> /^ at .*/
<add> /^ at .*/,
<add> " code: 'MODULE_NOT_FOUND',",
<add> " requireStack: [ '<repl>' ] }"
<ide> ]
<ide> },
<ide> // REPL should handle quotes within regexp literal in multiline mode
<ide><path>test/parallel/test-util-inspect.js
<ide> assert.strictEqual(util.inspect(-5e-324), '-5e-324');
<ide> );
<ide> assert.strictEqual(
<ide> util.inspect(err2, { compact: true }),
<del> '{ [Error: foo\nbar] bar: true }'
<add> '{ [Error: foo\nbar]\n bar: true }'
<ide> );
<ide> assert.strictEqual(
<ide> util.inspect(err, { compact: true, breakLength: 5 }), | 4 |
Javascript | Javascript | add resource by @mikesherov to gruntfile | 8cc217eac3c49515b8aff591a9a5a7e304f6e597 | <ide><path>grunt.js
<add>// Resources
<add>// https://gist.github.com/2489540
<add>
<ide> /*global config:true, task:true*/
<ide> module.exports = function( grunt ) {
<ide> | 1 |
Text | Text | remove use of you | e3f4ec94b8360414ecff65d8c04d9fa15d510c7f | <ide><path>doc/api/n-api.md
<ide> available to the module code.
<ide>
<ide> N-API versions are additive and versioned independently from Node.js.
<ide> Version 4 is an extension to version 3 in that it has all of the APIs
<del>from version 3 with some additions. This means that you
<del>do not need to recompile for new versions of Node.js which are
<add>from version 3 with some additions. This means that it is not necessary
<add>to recompile for new versions of Node.js which are
<ide> listed as supporting a later version.
<ide>
<ide> | | 1 | 2 | 3 | 4 | | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.