content_type stringclasses 8
values | main_lang stringclasses 7
values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
PHP | PHP | pass model binding value to callback | c3d3a52d670e1514ea9b9106c24982cb19d0280d | <ide><path>src/Illuminate/Routing/Router.php
<ide> public function model($key, $class, Closure $callback = null)
<ide> // developer a little greater flexibility to decide what will happen.
<ide> if ($callback instanceof Closure)
<ide> {
<del> return call_user_func($callback);
<add> return call_user_func_array($callback, [$value]);
<ide> }
<ide>
<ide> throw new NotFoundHttpException;
<ide><path>tests/Routing/RoutingRouteTest.php
<ide> public function testModelBindingWithCustomNullReturn()
<ide> $this->assertEquals('missing', $router->dispatch(Request::create('foo/taylor', 'GET'))->getContent());
<ide> }
<ide>
<add> public function testModelBindingWithBindingClosure()
<add> {
<add> $router = $this->getRouter();
<add> $router->get('foo/{bar}', function($name) { return $name; });
<add> $router->model('bar', 'RouteModelBindingNullStub', function($value) { return (new RouteModelBindingClosureStub())->findAlternate($value); });
<add> $this->assertEquals('tayloralt', $router->dispatch(Request::create('foo/TAYLOR', 'GET'))->getContent());
<add> }
<add>
<ide>
<ide> public function testGroupMerging()
<ide> {
<ide> class RouteModelBindingNullStub {
<ide> public function find($value) {}
<ide> }
<ide>
<add>class RouteModelBindingClosureStub {
<add> public function findAlternate($value) { return strtolower($value) . "alt"; }
<add>}
<add>
<ide> class RouteTestFilterStub {
<ide> public function filter()
<ide> { | 2 |
Ruby | Ruby | remove duplicate code | e2be6eacb86aa11f2c606d45a639802e946e911a | <ide><path>activerecord/lib/active_record/associations/belongs_to_association.rb
<ide> def replace(record)
<ide> set_inverse_instance(record)
<ide> @updated = true
<ide> else
<del> update_counters_without_record
<add> decrement_counters
<ide> remove_keys
<ide> end
<ide>
<ide> def update_counters(record)
<ide> counter_cache_name = reflection.counter_cache_column
<ide>
<ide> return unless counter_cache_name && owner.persisted?
<del>
<del> update_with_record record, counter_cache_name
<del> end
<del>
<del> def update_counters_without_record
<del> counter_cache_name = reflection.counter_cache_column
<del>
<del> return unless counter_cache_name && owner.persisted?
<del>
<del> update_without_record counter_cache_name
<del> end
<del>
<del> def update_with_record record, counter_cache_name
<ide> return unless different_target? record
<ide>
<ide> record.class.increment_counter(counter_cache_name, record.id)
<ide>
<ide> decrement_counter counter_cache_name
<ide> end
<ide>
<del> def update_without_record counter_cache_name
<add> def decrement_counters
<add> counter_cache_name = reflection.counter_cache_column
<add>
<add> return unless counter_cache_name && owner.persisted?
<add>
<ide> decrement_counter counter_cache_name
<ide> end
<ide> | 1 |
Python | Python | remove test for backend.is_successful | 5692bb1c893182e5aac7271161e64fa9d1a03f2f | <ide><path>celery/tests/test_backends/test_base.py
<ide> class TestBaseBackendInterface(unittest.TestCase):
<ide>
<ide> def test_get_status(self):
<ide> self.assertRaises(NotImplementedError,
<del> b.is_successful, "SOMExx-N0Nex1stant-IDxx-")
<add> b.get_status, "SOMExx-N0Nex1stant-IDxx-")
<ide>
<ide> def test_store_result(self):
<ide> self.assertRaises(NotImplementedError, | 1 |
Mixed | Javascript | add retrydelay option to rimraf | b7cdeb8a3a39000944106ddcd8ebcd5d1a8a5486 | <ide><path>doc/api/fs.md
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/30644
<ide> description: The `maxBusyTries` option is renamed to `maxRetries`, and its
<ide> default is 0. The `emfileWait` option has been removed, and
<del> `EMFILE` errors use the same retry logic as other errors.
<add> `EMFILE` errors use the same retry logic as other errors. The
<add> `retryDelay` option is now supported.
<ide> - version: v12.10.0
<ide> pr-url: https://github.com/nodejs/node/pull/29168
<ide> description: The `recursive`, `maxBusyTries`, and `emfileWait` options are
<ide> changes:
<ide> * `options` {Object}
<ide> * `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENOTEMPTY`, or `EPERM`
<ide> error is encountered, Node.js will retry the operation with a linear backoff
<del> wait of 100ms longer on each try. This option represents the number of
<del> retries. This option is ignored if the `recursive` option is not `true`.
<add> wait of `retryDelay` ms longer on each try. This option represents the number
<add> of retries. This option is ignored if the `recursive` option is not `true`.
<ide> **Default:** `0`.
<ide> * `recursive` {boolean} If `true`, perform a recursive directory removal. In
<ide> recursive mode, errors are not reported if `path` does not exist, and
<ide> operations are retried on failure. **Default:** `false`.
<add> * `retryDelay` {integer} The amount of time in milliseconds to wait between
<add> retries. This option is ignored if the `recursive` option is not `true`.
<add> **Default:** `100`.
<ide> * `callback` {Function}
<ide> * `err` {Error}
<ide>
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/30644
<ide> description: The `maxBusyTries` option is renamed to `maxRetries`, and its
<ide> default is 0. The `emfileWait` option has been removed, and
<del> `EMFILE` errors use the same retry logic as other errors.
<add> `EMFILE` errors use the same retry logic as other errors. The
<add> `retryDelay` option is now supported.
<ide> - version: v12.10.0
<ide> pr-url: https://github.com/nodejs/node/pull/29168
<ide> description: The `recursive`, `maxBusyTries`, and `emfileWait` options are
<ide> changes:
<ide> * `recursive` {boolean} If `true`, perform a recursive directory removal. In
<ide> recursive mode, errors are not reported if `path` does not exist, and
<ide> operations are retried on failure. **Default:** `false`.
<add> * `retryDelay` {integer} The amount of time in milliseconds to wait between
<add> retries. This option is ignored if the `recursive` option is not `true`.
<add> **Default:** `100`.
<ide>
<ide> Synchronous rmdir(2). Returns `undefined`.
<ide>
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/30644
<ide> description: The `maxBusyTries` option is renamed to `maxRetries`, and its
<ide> default is 0. The `emfileWait` option has been removed, and
<del> `EMFILE` errors use the same retry logic as other errors.
<add> `EMFILE` errors use the same retry logic as other errors. The
<add> `retryDelay` option is now supported.
<ide> - version: v12.10.0
<ide> pr-url: https://github.com/nodejs/node/pull/29168
<ide> description: The `recursive`, `maxBusyTries`, and `emfileWait` options are
<ide> changes:
<ide> * `options` {Object}
<ide> * `maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENOTEMPTY`, or `EPERM`
<ide> error is encountered, Node.js will retry the operation with a linear backoff
<del> wait of 100ms longer on each try. This option represents the number of
<del> retries. This option is ignored if the `recursive` option is not `true`.
<add> wait of `retryDelay` ms longer on each try. This option represents the number
<add> of retries. This option is ignored if the `recursive` option is not `true`.
<ide> **Default:** `0`.
<ide> * `recursive` {boolean} If `true`, perform a recursive directory removal. In
<ide> recursive mode, errors are not reported if `path` does not exist, and
<ide> operations are retried on failure. **Default:** `false`.
<add> * `retryDelay` {integer} The amount of time in milliseconds to wait between
<add> retries. This option is ignored if the `recursive` option is not `true`.
<add> **Default:** `100`.
<ide> * Returns: {Promise}
<ide>
<ide> Removes the directory identified by `path` then resolves the `Promise` with
<ide><path>lib/internal/fs/rimraf.js
<ide> function rimraf(path, options, callback) {
<ide> if (err) {
<ide> if (retryErrorCodes.has(err.code) && retries < options.maxRetries) {
<ide> retries++;
<del> return setTimeout(_rimraf, retries * 100, path, options, CB);
<add> const delay = retries * options.retryDelay;
<add> return setTimeout(_rimraf, delay, path, options, CB);
<ide> }
<ide>
<ide> // The file is already gone.
<ide><path>lib/internal/fs/utils.js
<ide> const {
<ide> const { once } = require('internal/util');
<ide> const { toPathIfFileURL } = require('internal/url');
<ide> const {
<add> validateInt32,
<ide> validateUint32
<ide> } = require('internal/validators');
<ide> const pathModule = require('path');
<ide> function warnOnNonPortableTemplate(template) {
<ide> }
<ide>
<ide> const defaultRmdirOptions = {
<add> retryDelay: 100,
<ide> maxRetries: 0,
<ide> recursive: false,
<ide> };
<ide> const validateRmdirOptions = hideStackFrames((options) => {
<ide> if (typeof options.recursive !== 'boolean')
<ide> throw new ERR_INVALID_ARG_TYPE('recursive', 'boolean', options.recursive);
<ide>
<add> validateInt32(options.retryDelay, 'retryDelay', 0);
<ide> validateUint32(options.maxRetries, 'maxRetries');
<ide>
<ide> return options;
<ide><path>test/parallel/test-fs-rmdir-recursive.js
<ide> function removeAsync(dir) {
<ide> // Test input validation.
<ide> {
<ide> const defaults = {
<add> retryDelay: 100,
<ide> maxRetries: 0,
<ide> recursive: false
<ide> };
<ide> const modified = {
<add> retryDelay: 953,
<ide> maxRetries: 5,
<ide> recursive: true
<ide> };
<ide> function removeAsync(dir) {
<ide> assert.deepStrictEqual(validateRmdirOptions({
<ide> maxRetries: 99
<ide> }), {
<add> retryDelay: 100,
<ide> maxRetries: 99,
<ide> recursive: false
<ide> });
<ide> function removeAsync(dir) {
<ide> });
<ide> });
<ide>
<add> common.expectsError(() => {
<add> validateRmdirOptions({ retryDelay: -1 });
<add> }, {
<add> code: 'ERR_OUT_OF_RANGE',
<add> type: RangeError,
<add> message: /^The value of "retryDelay" is out of range\./
<add> });
<add>
<ide> common.expectsError(() => {
<ide> validateRmdirOptions({ maxRetries: -1 });
<ide> }, { | 4 |
PHP | PHP | add unit testing for the withouttouchingon method | 53510ea30b58dd4510b20b241202a896db1cd261 | <ide><path>tests/Database/DatabaseEloquentModelTest.php
<ide> public function testWithoutTouchingCallback()
<ide> $this->assertTrue($model->shouldTouch());
<ide> }
<ide>
<add> public function testWithoutTouchingOnCallback()
<add> {
<add> $model = new EloquentModelStub(['id' => 1]);
<add>
<add> $called = false;
<add>
<add> $this->assertTrue($model->shouldTouch());
<add>
<add> Model::withoutTouchingOn([EloquentModelStub::class], function () use (&$called, $model) {
<add> $this->assertFalse($model->shouldTouch());
<add> $called = true;
<add> });
<add>
<add> $this->assertTrue($called);
<add> $this->assertTrue($model->shouldTouch());
<add> }
<add>
<ide> protected function addMockConnection($model)
<ide> {
<ide> $model->setConnectionResolver($resolver = m::mock('Illuminate\Database\ConnectionResolverInterface')); | 1 |
Javascript | Javascript | remove globals from ember.select documentation | a13e9894a027b28b9ad05bde62d103acb881532f | <ide><path>packages/ember-handlebars/lib/controls/select.js
<ide> Ember.SelectOptgroup = Ember.CollectionView.extend({
<ide> Example:
<ide>
<ide> ```javascript
<del> App.names = ["Yehuda", "Tom"];
<add> App.ApplicationController = Ember.Controller.extend({
<add> names: ["Yehuda", "Tom"]
<add> });
<ide> ```
<ide>
<ide> ```handlebars
<del> {{view Ember.Select contentBinding="App.names"}}
<add> {{view Ember.Select contentBinding="names"}}
<ide> ```
<ide>
<ide> Would result in the following HTML:
<ide> Ember.SelectOptgroup = Ember.CollectionView.extend({
<ide> `value` property directly or as a binding:
<ide>
<ide> ```javascript
<del> App.names = Ember.Object.create({
<del> selected: 'Tom',
<del> content: ["Yehuda", "Tom"]
<add> App.ApplicationController = Ember.Controller.extend({
<add> selectedName: 'Tom',
<add> names: ["Yehuda", "Tom"]
<ide> });
<ide> ```
<ide>
<ide> ```handlebars
<ide> {{view Ember.Select
<del> contentBinding="App.names.content"
<del> valueBinding="App.names.selected"
<add> contentBinding="names"
<add> valueBinding="selectedName"
<ide> }}
<ide> ```
<ide>
<ide> Ember.SelectOptgroup = Ember.CollectionView.extend({
<ide> ```
<ide>
<ide> A user interacting with the rendered `<select>` to choose "Yehuda" would
<del> update the value of `App.names.selected` to "Yehuda".
<add> update the value of `selectedName` to "Yehuda".
<ide>
<ide> ### `content` as an Array of Objects
<ide>
<ide> Ember.SelectOptgroup = Ember.CollectionView.extend({
<ide> element's text. Both paths must reference each object itself as `content`:
<ide>
<ide> ```javascript
<del> App.programmers = [
<del> Ember.Object.create({firstName: "Yehuda", id: 1}),
<del> Ember.Object.create({firstName: "Tom", id: 2})
<del> ];
<add> App.ApplicationController = Ember.Controller.extend({
<add> programmers: [
<add> {firstName: "Yehuda", id: 1},
<add> {firstName: "Tom", id: 2}
<add> ]
<add> });
<ide> ```
<ide>
<ide> ```handlebars
<ide> {{view Ember.Select
<del> contentBinding="App.programmers"
<add> contentBinding="programmers"
<ide> optionValuePath="content.id"
<ide> optionLabelPath="content.firstName"}}
<ide> ```
<ide> Ember.SelectOptgroup = Ember.CollectionView.extend({
<ide> `valueBinding` option:
<ide>
<ide> ```javascript
<del> App.programmers = [
<del> Ember.Object.create({firstName: "Yehuda", id: 1}),
<del> Ember.Object.create({firstName: "Tom", id: 2})
<del> ];
<del>
<del> App.currentProgrammer = Ember.Object.create({
<del> id: 2
<add> App.ApplicationController = Ember.Controller.extend({
<add> programmers: [
<add> {firstName: "Yehuda", id: 1},
<add> {firstName: "Tom", id: 2}
<add> ],
<add> currentProgrammer: {
<add> id: 2
<add> }
<ide> });
<ide> ```
<ide>
<ide> ```handlebars
<ide> {{view Ember.Select
<del> contentBinding="App.programmers"
<add> contentBinding="programmers"
<ide> optionValuePath="content.id"
<ide> optionLabelPath="content.firstName"
<del> valueBinding="App.currentProgrammer.id"}}
<add> valueBinding="currentProgrammer.id"}}
<ide> ```
<ide>
<ide> Would result in the following HTML with a selected option:
<ide> Ember.SelectOptgroup = Ember.CollectionView.extend({
<ide> ```
<ide>
<ide> Interacting with the rendered element by selecting the first option
<del> ('Yehuda') will update the `id` value of `App.currentProgrammer`
<add> ('Yehuda') will update the `id` of `currentProgrammer`
<ide> to match the `value` property of the newly selected `<option>`.
<ide>
<ide> Alternatively, you can control selection through the underlying objects
<ide> Ember.SelectOptgroup = Ember.CollectionView.extend({
<ide> element:
<ide>
<ide> ```javascript
<del> App.controller = Ember.Object.create({
<add> App.ApplicationController = Ember.Controller.extend({
<ide> selectedPerson: null,
<del> content: [
<del> Ember.Object.create({firstName: "Yehuda", id: 1}),
<del> Ember.Object.create({firstName: "Tom", id: 2})
<add> programmers: [
<add> {firstName: "Yehuda", id: 1},
<add> {firstName: "Tom", id: 2}
<ide> ]
<ide> });
<ide> ```
<ide>
<ide> ```handlebars
<ide> {{view Ember.Select
<del> contentBinding="App.controller.content"
<add> contentBinding="programmers"
<ide> optionValuePath="content.id"
<ide> optionLabelPath="content.firstName"
<del> selectionBinding="App.controller.selectedPerson"}}
<add> selectionBinding="selectedPerson"}}
<ide> ```
<ide>
<ide> Would result in the following HTML with a selected option:
<ide> Ember.SelectOptgroup = Ember.CollectionView.extend({
<ide> ```
<ide>
<ide> Interacting with the rendered element by selecting the first option
<del> ('Yehuda') will update the `selectedPerson` value of `App.controller`
<del> to match the content object of the newly selected `<option>`. In this
<del> case it is the first object in the `App.controller.content`
<add> ('Yehuda') will update the `selectedPerson` to match the object of
<add> the newly selected `<option>`. In this case it is the first object
<add> in the `programmers`
<ide>
<ide> ### Supplying a Prompt
<ide>
<ide> A `null` value for the `Ember.Select`'s `value` or `selection` property
<ide> results in there being no `<option>` with a `selected` attribute:
<ide>
<ide> ```javascript
<del> App.controller = Ember.Object.create({
<del> selected: null,
<del> content: [
<add> App.ApplicationController = Ember.Controller.extend({
<add> selectedProgrammer: null,
<add> programmers: [
<ide> "Yehuda",
<ide> "Tom"
<ide> ]
<ide> Ember.SelectOptgroup = Ember.CollectionView.extend({
<ide>
<ide> ``` handlebars
<ide> {{view Ember.Select
<del> contentBinding="App.controller.content"
<del> valueBinding="App.controller.selected"
<add> contentBinding="programmers"
<add> valueBinding="selectedProgrammer"
<ide> }}
<ide> ```
<ide>
<ide> Ember.SelectOptgroup = Ember.CollectionView.extend({
<ide> </select>
<ide> ```
<ide>
<del> Although `App.controller.selected` is `null` and no `<option>`
<add> Although `selectedProgrammer` is `null` and no `<option>`
<ide> has a `selected` attribute the rendered HTML will display the
<ide> first item as though it were selected. You can supply a string
<ide> value for the `Ember.Select` to display when there is no selection
<ide> with the `prompt` option:
<ide>
<ide> ```javascript
<del> App.controller = Ember.Object.create({
<del> selected: null,
<del> content: [
<add> App.ApplicationController = Ember.Controller.extend({
<add> selectedProgrammer: null,
<add> programmers: [
<ide> "Yehuda",
<ide> "Tom"
<ide> ]
<ide> Ember.SelectOptgroup = Ember.CollectionView.extend({
<ide>
<ide> ```handlebars
<ide> {{view Ember.Select
<del> contentBinding="App.controller.content"
<del> valueBinding="App.controller.selected"
<add> contentBinding="programmers"
<add> valueBinding="selectedProgrammer"
<ide> prompt="Please select a name"
<ide> }}
<ide> ```
<ide> Ember.Select = Ember.View.extend(
<ide> */
<ide> multiple: false,
<ide>
<add> /**
<add> The `disabled` attribute of the select element. Indicates whether
<add> the element is disabled from interactions.
<add>
<add> @property multiple
<add> @type Boolean
<add> @default false
<add> */
<ide> disabled: false,
<ide>
<ide> /** | 1 |
Go | Go | run build session tests on non-experimental | becd29c6651dffc253027e15f903ae7e7c918594 | <ide><path>integration/build/build_session_test.go
<ide> import (
<ide> "testing"
<ide>
<ide> "github.com/docker/docker/api/types"
<add> "github.com/docker/docker/api/types/versions"
<ide> dclient "github.com/docker/docker/client"
<del> "github.com/docker/docker/internal/test/daemon"
<ide> "github.com/docker/docker/internal/test/fakecontext"
<ide> "github.com/docker/docker/internal/test/request"
<ide> "github.com/moby/buildkit/session"
<ide> import (
<ide>
<ide> func TestBuildWithSession(t *testing.T) {
<ide> skip.If(t, testEnv.DaemonInfo.OSType == "windows")
<add> skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.39"), "experimental in older versions")
<ide>
<del> var client dclient.APIClient
<del> if !testEnv.DaemonInfo.ExperimentalBuild {
<del> skip.If(t, testEnv.IsRemoteDaemon, "cannot run daemon when remote daemon")
<del>
<del> d := daemon.New(t, daemon.WithExperimental)
<del> d.StartWithBusybox(t)
<del> defer d.Stop(t)
<del> client = d.NewClientT(t)
<del> } else {
<del> client = testEnv.APIClient()
<del> }
<add> client := testEnv.APIClient()
<ide>
<ide> dockerfile := `
<ide> FROM busybox
<ide><path>integration/session/session_test.go
<ide> import (
<ide> "net/http"
<ide> "testing"
<ide>
<del> "github.com/docker/docker/internal/test/daemon"
<add> "github.com/docker/docker/api/types/versions"
<ide> req "github.com/docker/docker/internal/test/request"
<ide> "gotest.tools/assert"
<ide> is "gotest.tools/assert/cmp"
<ide> import (
<ide>
<ide> func TestSessionCreate(t *testing.T) {
<ide> skip.If(t, testEnv.OSType == "windows", "FIXME")
<add> skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.39"), "experimental in older versions")
<ide>
<ide> defer setupTest(t)()
<ide> daemonHost := req.DaemonHost()
<del> if !testEnv.DaemonInfo.ExperimentalBuild {
<del> skip.If(t, testEnv.IsRemoteDaemon, "cannot run daemon when remote daemon")
<del>
<del> d := daemon.New(t, daemon.WithExperimental)
<del> d.StartWithBusybox(t)
<del> defer d.Stop(t)
<del> daemonHost = d.Sock()
<del> }
<ide>
<ide> res, body, err := req.Post("/session",
<ide> req.Host(daemonHost),
<ide> func TestSessionCreate(t *testing.T) {
<ide>
<ide> func TestSessionCreateWithBadUpgrade(t *testing.T) {
<ide> skip.If(t, testEnv.OSType == "windows", "FIXME")
<add> skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.39"), "experimental in older versions")
<ide>
<ide> defer setupTest(t)()
<ide> daemonHost := req.DaemonHost()
<del> if !testEnv.DaemonInfo.ExperimentalBuild {
<del> skip.If(t, testEnv.IsRemoteDaemon, "cannot run daemon when remote daemon")
<del>
<del> d := daemon.New(t, daemon.WithExperimental)
<del> d.StartWithBusybox(t)
<del> defer d.Stop(t)
<del> daemonHost = d.Sock()
<del> }
<ide>
<ide> res, body, err := req.Post("/session", req.Host(daemonHost))
<ide> assert.NilError(t, err) | 2 |
Javascript | Javascript | remove use of jquery#each second argument | a4715f4216ace92fba6991106053415e66289686 | <ide><path>src/ajax/load.js
<ide> jQuery.fn.load = function( url, params, callback ) {
<ide> // but they are ignored because response was set above.
<ide> // If it fails, this function gets "jqXHR", "status", "error"
<ide> }).always( callback && function( jqXHR, status ) {
<del> self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
<add> self.each( function() {
<add> callback.apply( self, response || [ jqXHR.responseText, status, jqXHR ] );
<add> });
<ide> });
<ide> }
<ide> | 1 |
Javascript | Javascript | remove unused variables | 6ebee18d1348441f2f201e6a6faf5d14bc7fe361 | <ide><path>IntegrationTests/ImageSnapshotTest.js
<ide>
<ide> const React = require('react');
<ide> const ReactNative = require('react-native');
<del>const {Image, View} = ReactNative;
<add>const {Image} = ReactNative;
<ide> const {TestModule} = ReactNative.NativeModules;
<ide>
<ide> class ImageSnapshotTest extends React.Component<{}> {
<ide><path>IntegrationTests/WebSocketTest.js
<ide> const {TestModule} = ReactNative.NativeModules;
<ide> const DEFAULT_WS_URL = 'ws://localhost:5555/';
<ide>
<ide> const WS_EVENTS = ['close', 'error', 'message', 'open'];
<del>const WS_STATES = [
<del> /* 0 */ 'CONNECTING',
<del> /* 1 */ 'OPEN',
<del> /* 2 */ 'CLOSING',
<del> /* 3 */ 'CLOSED',
<del>];
<ide>
<ide> type State = {
<ide> url: string,
<ide> class WebSocketTest extends React.Component<{}, State> {
<ide>
<ide> _waitFor = (condition: any, timeout: any, callback: any) => {
<ide> let remaining = timeout;
<del> let t;
<ide> const timeoutFunction = function() {
<ide> if (condition()) {
<ide> callback(true);
<ide> class WebSocketTest extends React.Component<{}, State> {
<ide> if (remaining === 0) {
<ide> callback(false);
<ide> } else {
<del> t = setTimeout(timeoutFunction, 1000);
<add> setTimeout(timeoutFunction, 1000);
<ide> }
<ide> };
<del> t = setTimeout(timeoutFunction, 1000);
<add> setTimeout(timeoutFunction, 1000);
<ide> };
<ide>
<ide> _connect = () => {
<ide> class WebSocketTest extends React.Component<{}, State> {
<ide> }
<ide>
<ide> testConnect = () => {
<del> const component = this;
<del> component._connect();
<del> component._waitFor(component._socketIsConnected, 5, function(
<del> connectSucceeded,
<del> ) {
<add> this._connect();
<add> this._waitFor(this._socketIsConnected, 5, connectSucceeded => {
<ide> if (!connectSucceeded) {
<ide> TestModule.markTestPassed(false);
<ide> return;
<ide> }
<del> component.testSendAndReceive();
<add> this.testSendAndReceive();
<ide> });
<ide> };
<ide>
<ide> testSendAndReceive = () => {
<del> const component = this;
<del> component._sendTestMessage();
<del> component._waitFor(component._receivedTestExpectedResponse, 5, function(
<del> messageReceived,
<del> ) {
<add> this._sendTestMessage();
<add> this._waitFor(this._receivedTestExpectedResponse, 5, messageReceived => {
<ide> if (!messageReceived) {
<ide> TestModule.markTestPassed(false);
<ide> return;
<ide> }
<del> component.testDisconnect();
<add> this.testDisconnect();
<ide> });
<ide> };
<ide>
<ide> testDisconnect = () => {
<del> const component = this;
<del> component._disconnect();
<del> component._waitFor(component._socketIsDisconnected, 5, function(
<del> disconnectSucceeded,
<del> ) {
<add> this._disconnect();
<add> this._waitFor(this._socketIsDisconnected, 5, disconnectSucceeded => {
<ide> TestModule.markTestPassed(disconnectSucceeded);
<ide> });
<ide> };
<ide><path>Libraries/Components/ScrollView/ScrollView.js
<ide> const flattenStyle = require('flattenStyle');
<ide> const invariant = require('fbjs/lib/invariant');
<ide> const processDecelerationRate = require('processDecelerationRate');
<ide> const requireNativeComponent = require('requireNativeComponent');
<del>const warning = require('fbjs/lib/warning');
<ide> const resolveAssetSource = require('resolveAssetSource');
<ide>
<ide> import type {PressEvent} from 'CoreEventTypes';
<ide><path>Libraries/Core/Devtools/setupDevtools.js
<ide>
<ide> 'use strict';
<ide>
<del>type DevToolsPluginConnection = {
<del> isAppActive: () => boolean,
<del> host: string,
<del> port: number,
<del>};
<del>
<del>type DevToolsPlugin = {
<del> connectToDevTools: (connection: DevToolsPluginConnection) => void,
<del>};
<del>
<ide> let register = function() {
<ide> // noop
<ide> };
<ide><path>Libraries/Experimental/Incremental.js
<ide> export type Props = {
<ide> name: string,
<ide> children: React.Node,
<ide> };
<del>
<ide> type State = {
<ide> doIncrementalRender: boolean,
<ide> };
<ide><path>local-cli/link/__tests__/ios/getProducts.spec.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> *
<del> * @format
<del> * @emails oncall+javascript_foundation
<del> */
<del>
<del>'use strict';
<del>
<del>const xcode = require('xcode');
<del>const getProducts = require('../../ios/getProducts');
<del>const path = require('path');
<del>
<del>const project = xcode.project(
<del> path.join(__dirname, '../../__fixtures__/project.pbxproj'),
<del>);
<del>
<del>describe('ios::getProducts', () => {
<del> beforeEach(() => {
<del> project.parseSync();
<del> });
<del>
<del> it('should return an array of static libraries project exports', () => {
<del> const products = getProducts(project);
<del> expect(products.length).toBe(1);
<del> expect(products).toContain('libRCTActionSheet.a');
<del> });
<del>});
<ide><path>local-cli/link/ios/getProducts.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> *
<del> * @format
<del> */
<del>
<del>/**
<del> * Given xcodeproj it returns list of products ending with
<del> * .a extension, so that we know what elements add to target
<del> * project static library
<del> */
<del>module.exports = function getProducts(project) {
<del> return project
<del> .pbxGroupByName('Products')
<del> .children.map(c => c.comment)
<del> .filter(c => c.indexOf('.a') > -1);
<del>};
<ide><path>local-cli/link/ios/registerNativeModule.js
<ide> const xcode = require('xcode');
<ide> const fs = require('fs');
<ide> const path = require('path');
<del>const log = require('npmlog');
<ide>
<ide> const addToHeaderSearchPaths = require('./addToHeaderSearchPaths');
<ide> const getHeadersInFolder = require('./getHeadersInFolder');
<ide> const getHeaderSearchPath = require('./getHeaderSearchPath');
<del>const getProducts = require('./getProducts');
<ide> const getTargets = require('./getTargets');
<ide> const createGroupWithMessage = require('./createGroupWithMessage');
<ide> const addFileToProject = require('./addFileToProject');
<ide> const addProjectToLibraries = require('./addProjectToLibraries');
<ide> const addSharedLibraries = require('./addSharedLibraries');
<ide> const isEmpty = require('lodash').isEmpty;
<del>const getGroup = require('./getGroup');
<ide>
<ide> /**
<ide> * Register native module IOS adds given dependency to project by adding
<ide><path>scripts/android-e2e-test.js
<ide> describe('Android Test App', function() {
<ide> });
<ide>
<ide> it('should have Debug In Chrome working', function() {
<del> const androidAppCode = fs.readFileSync('index.js', 'utf-8');
<ide> // http://developer.android.com/reference/android/view/KeyEvent.html#KEYCODE_MENU
<ide> return driver
<ide> .waitForElementByXPath( | 9 |
Java | Java | fix bug with the order of messaging arg resolvers | 750930fa25dde35fcab82f9a210e42ce02d65d7d | <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/handler/AnnotationMethodMessageHandler.java
<ide> public void afterPropertiesSet() {
<ide>
<ide> initHandlerMethods();
<ide>
<del> // Annotation-based argument resolution
<del> this.argumentResolvers.addResolver(new MessageBodyMethodArgumentResolver(this.messageConverter));
<del>
<ide> // Type-based argument resolution
<ide> this.argumentResolvers.addResolver(new PrincipalMethodArgumentResolver());
<ide> this.argumentResolvers.addResolver(new MessageMethodArgumentResolver());
<ide>
<ide> // custom arguments
<ide> this.argumentResolvers.addResolvers(this.customArgumentResolvers);
<ide>
<add> // catch-all argument resolver
<add> this.argumentResolvers.addResolver(new MessageBodyMethodArgumentResolver(this.messageConverter));
<add>
<ide> // Annotation-based return value types
<ide> this.returnValueHandlers.addHandler(new ReplyToMethodReturnValueHandler(this.dispatchMessagingTemplate));
<ide> this.returnValueHandlers.addHandler(new SubscriptionMethodReturnValueHandler(this.webSocketSessionMessagingTemplate)); | 1 |
PHP | PHP | throw exception for invalid log level | 91b1db37740017e0c8480bfc639378a4e222cfc3 | <ide><path>Cake/Log/Log.php
<ide> public static function engine($name) {
<ide> * @param string|array $scope The scope(s) a log message is being created in.
<ide> * See Cake\Log\Log::config() for more information on logging scopes.
<ide> * @return boolean Success
<add> * @throws Cake\Error\Exception If invalid level is passed.
<ide> */
<ide> public static function write($level, $message, $scope = array()) {
<ide> static::_init();
<ide> if (is_int($level) && isset(static::$_levels[$level])) {
<ide> $level = static::$_levels[$level];
<ide> }
<add>
<add> if (!in_array($level, static::$_levels)) {
<add> throw new Error\Exception(__d('cake_dev', 'Invalid log level "%s"', $level));
<add> }
<add>
<ide> $logged = false;
<ide> foreach (static::$_registry->loaded() as $streamName) {
<ide> $logger = static::$_registry->{$streamName};
<ide><path>Cake/Test/TestCase/Log/LogTest.php
<ide> public function testDrop() {
<ide> $this->assertNotContains('file', $result);
<ide> }
<ide>
<add>/**
<add> * test config() with valid key name
<add> *
<add> * @expectedException Cake\Error\Exception
<add> * @return void
<add> */
<add> public function testInvalidLevel() {
<add> Log::config('myengine', array('engine' => 'File'));
<add> Log::write('invalid', 'This will not be logged');
<add> }
<add>
<ide> /**
<ide> * Provider for config() tests.
<ide> * | 2 |
PHP | PHP | assertcount() | ad6928baacb69939fa0bfe4ea3083c3c178a3568 | <ide><path>src/Illuminate/Support/Facades/Notification.php
<ide> * @method static \Illuminate\Support\Collection sent(mixed $notifiable, string $notification, callable $callback = null)
<ide> * @method static bool hasSent(mixed $notifiable, string $notification)
<ide> * @method static mixed channel(string|null $name = null)
<add> * @method static void assertCount(int $expectedCount)
<ide> * @method static void assertNotSentTo(mixed $notifiable, string|\Closure $notification, callable $callback = null)
<ide> * @method static void assertNothingSent()
<ide> * @method static void assertNothingSentTo(mixed $notifiable) | 1 |
Text | Text | update translation bubble-sort | 94b2b1cd8fd3e1bba6af19c2145d1f09f0bf4577 | <ide><path>guide/portuguese/algorithms/sorting-algorithms/bubble-sort/index.md
<ide> localeTitle: Tipo de bolha
<ide>
<ide> O Bubble Sort é o algoritmo de ordenação mais simples que funciona trocando repetidamente os elementos adjacentes se eles estiverem na ordem errada.
<ide>
<del>Este é um algoritmo de ordenação muito lento em comparação com algoritmos como o quicksort, com a complexidade do pior caso O (n ^ 2). No entanto, a desvantagem é que o bubble sort é um dos algoritmos de ordenação mais fáceis de implementar do zero.
<add>Este é um algoritmo de ordenação muito lento em comparação com algoritmos como o quicksort, com a complexidade do pior caso O (n^2). No entanto, a desvantagem é que o bubble sort é um dos algoritmos de ordenação mais fáceis de implementar do zero. Como resultado, o algoritmo de classificação de bolhas é comumente ensinado como o primeiro algoritmo de ordenação em classes de estrutura de dados e algoritmos. Do ponto de vista técnico, o Bubble Sort é razoável para classificar matrizes de pequeno porte ou especialmente ao executar algoritmos de ordenação em computadores com recursos de memória extremamente limitados.
<ide>
<ide> ### Exemplo:
<ide>
<ide> #### Primeiro passe:
<ide>
<del>(5 1 4 2 8) -> (1 5 4 2 8), Aqui, o algoritmo compara os dois primeiros elementos e troca desde 5> 1.
<add>( **5 1** 4 2 8 ) –> ( 1 5 4 2 8 ), Aqui, o algoritmo compara os dois primeiros elementos e troca desde 5> 1.
<ide>
<del>(1 5 4 2 8) -> (1 4 5 2 8), Trocar desde 5> 4
<add>( 1 **5 4** 2 8 ) –> ( 1 4 5 2 8 ), Trocar desde 5> 4
<ide>
<del>(1 4 5 2 8) -> (1 4 2 5 8), Trocar desde 5> 2
<add>( 1 4 **5 2** 8 ) –> ( 1 4 2 5 8 ), Trocar desde 5> 2
<ide>
<del>(1 4 2 5 8) -> (1 4 2 5 8), Agora, como esses elementos já estão em ordem (8> 5), o algoritmo não os troca.
<add>( 1 4 2 **5 8** ) –> ( 1 4 2 5 8 ), Agora, como esses elementos já estão em ordem (8> 5), o algoritmo não os troca.
<ide>
<ide> #### Segundo Passe:
<ide>
<del>(1 4 2 5 8) -> (1 4 2 5 8)
<add>( **1 4** 2 5 8 ) –> ( 1 4 2 5 8 )
<ide>
<del>(1 4 2 5 8) -> (1 2 4 5 8), Troca desde 4> 2
<add>( 1 **4 2** 5 8 ) –> ( 1 2 4 5 8 ), Troca desde 4> 2
<ide>
<del>(1 2 4 5 8) -> (1 2 4 5 8)
<add>( 1 2 **4 5** 8 ) –> ( 1 2 4 5 8 )
<ide>
<del>(1 2 4 5 8) -> (1 2 4 5 8)
<add>( 1 2 4 **5 8** ) –> ( 1 2 4 5 8 )
<ide>
<ide> Agora, a matriz já está classificada, mas nosso algoritmo não sabe se está concluído. O algoritmo precisa de um passe inteiro sem qualquer troca para saber se está classificado.
<ide>
<ide> #### Terceira passagem:
<ide>
<del>(1 2 4 5 8) -> (1 2 4 5 8)
<add>( **1 2** 4 5 8 ) –> ( 1 2 4 5 8 )
<ide>
<del>(1 2 4 5 8) -> (1 2 4 5 8)
<add>( 1 **2 4** 5 8 ) –> ( 1 2 4 5 8 )
<ide>
<del>(1 2 4 5 8) -> (1 2 4 5 8)
<add>( 1 2 **4 5** 8 ) –> ( 1 2 4 5 8 )
<ide>
<del>(1 2 4 5 8) -> (1 2 4 5 8)
<add>( 1 2 4 **5 8** ) –> ( 1 2 4 5 8 )
<ide>
<ide> #### Propriedades
<ide>
<ide> Agora, a matriz já está classificada, mas nosso algoritmo não sabe se está c
<ide>
<ide> [Tipo de bolha de maneira fácil](https://www.youtube.com/watch?v=Jdtq5uKz-w4)
<ide>
<add>### Exemplo em Java.
<add>```java
<add>public int[] bubSort(int []ar)
<add>{
<add> int i, j, temp;
<add> for (i = 0; i < n; i++)
<add> {
<add> for (j = 0; j < n - 1 - i; j++)
<add> {
<add> if (ar[j] > ar[j+1])
<add> {
<add> temp = ar[j];
<add> ar[j] = ar[j + 1];
<add> ar[j + 1] = temp;
<add> }
<add> }
<add> }
<add> return ar[];
<add>}
<add>```
<add>### Exemplo em C++
<add>```cpp
<add>#include <iostream>
<add>using namespace std;
<add>int BubbleSort[] (int arr[], int n)
<add>{
<add> int i, j, temp;
<add> for (i = 0; i < n; ++i)
<add> {
<add> for (j = 0; j < n-i-1; ++j)
<add> {
<add> if (arr[j] > arr[j+1])
<add> {
<add> temp = arr[j]
<add> arr[j] = arr[j+1];
<add> arr[j+1] = temp;
<add> }
<add> }
<add> }
<add> return arr;
<add>}
<add>```
<add>### Exemplo em Swift
<add>```swift
<add>func bubbleSort(_ inputArray: [Int]) -> [Int] {
<add> guard inputArray.count > 1 else { return inputArray } // make sure our input array has more than 1 element
<add> var numbers = inputArray // function arguments are constant by default in Swift, so we make a copy
<add> for i in 0..<(numbers.count - 1) {
<add> for j in 0..<(numbers.count - i - 1) {
<add> if numbers[j] > numbers[j + 1] {
<add> numbers.swapAt(j, j + 1)
<add> }
<add> }
<add> }
<add> return numbers // return the sorted array
<add>}
<add>```
<add>### Exemplo em Python
<add>```python
<add>def bubblesort( A ):
<add> for i in range( len( A ) ):
<add> for k in range( len( A ) - 1, i, -1 ):
<add> if ( A[k] < A[k - 1] ):
<add> swap( A, k, k - 1 )
<add>
<add>def swap( A, x, y ):
<add> tmp = A[x]
<add> A[x] = A[y]
<add> A[y] = tmp
<add>```
<add>
<add>### Bubble Sort modificada
<add>
<add>Agora sabemos que o Bubble Sort tem uma complexidade geral de O (n^2) para todos os casos de entrada. Como esse é um tipo muito lento, uma das otimizações comumente sugeridas e bastante fáceis pode ser feita para incluir o melhor caso (onde a lista / array fornecida como entrada já está classificada). Se conseguirmos verificar essa condição (fazendo N comparações), poderemos terminar a execução imediatamente após validar o fato de que a matriz está classificada.
<add>
<add>Isso significa que, no melhor dos casos, nosso Algoritmo de classificação de bolhas modificado teria uma complexidade de O (n). Isso não muda a média ou o pior caso, é claro, mas pode mostrar um aumento decente na velocidade se você pretende classificar um número de instâncias, algumas das quais provavelmente já serão classificadas.
<add>
<ide> Este código usará bubble sort para classificar o array.
<ide>
<add>### Exemplo em JavaScript
<add>
<ide> ```js
<del>let arr = [1, 4, 7, 45, 7,43, 44, 25, 6, 4, 6, 9];
<del> let sorted = false
<add>let arr = [1, 4, 7, 45, 7,43, 44, 25, 6, 4, 6, 9];
<add>let sorted = false
<ide>
<del> while(!sorted) {
<del> sorted = true
<del> for(var i=0; i < arr.length; i++) {
<del> if(arr[i] < arr[i-1]) {
<del> let temp = arr[i];
<add>while(!sorted) {
<add> sorted = true
<add> for(var i=0; i < arr.length; i++) {
<add> if(arr[i] < arr[i-1]) {
<add> let temp = arr[i];
<ide> arr[i] = arr[i-1];
<del> arr[i-1] = temp;
<del> sorted = false;
<del> }
<del> }
<del> }
<add> arr[i-1] = temp;
<add> sorted = false;
<add> }
<add> }
<add>}
<ide> ```
<add>### Exemplo em Java
<ide>
<del>### Propriedades:
<add>Exemplo 1:
<ide>
<del>* Complexidade Espacial: O (1)
<del>* Complexidade do Tempo: O (n), O (n \* n), O (n \* n) para os casos Melhor, Médio e Pior, respectivamente.
<del>* No lugar: sim
<del>* Estável: sim
<add>```java
<add>public int[] bubSortModified(int []ar)
<add>{
<add> int i, j, temp;
<add> boolean sorted;
<add> for (i = 0; i < n; i++)
<add> {
<add> sorted = true;
<add> for (j = 0; j < n - 1 - i; j++)
<add> {
<add> if (ar[j] > ar[j+1])
<add> {
<add> sorted = false; //implying array was not sorted already, swaps are needed
<add> temp = ar[j];
<add> ar[j] = ar[j + 1];
<add> ar[j + 1] = temp;
<add> }
<add> }
<add> if (sorted == true)
<add> break; //if array is sorted, stop iterating
<add> }
<add> return ar[];
<add>}
<add>```
<ide>
<del>\======= Aqui está o algoritmo escrito em Java.
<add>Exemplo 2:
<ide>
<ide> ```java
<del>public class bubble-sort {
<del> static void sort(int[] arr) {
<del> int n = arr.length;
<del> int temp = 0;
<del> for(int i=0; i < n; i++){
<del> for(int x=1; x < (ni); x++){
<del> if(arr[x-1] > arr[x]){
<del> temp = arr[x-1];
<del> arr[x-1] = arr[x];
<del> arr[x] = temp;
<del> }
<del>
<del> }
<del> }
<add>public class bubble-sort {
<add> static void sort(int[] arr) {
<add> int n = arr.length;
<add> int temp = 0;
<add> for(int i=0; i < n; i++){
<add> for(int x=1; x < (ni); x++){
<add> if(arr[x-1] > arr[x]){
<add> temp = arr[x-1];
<add> arr[x-1] = arr[x];
<add> arr[x] = temp;
<add> }
<add> }
<add> }
<add> }
<add>
<add> public static void main(String[] args) {
<add> for(int i=0; i < 15; i++){
<add> int arr[i] = (int)(Math.random() * 100 + 1);
<add> }
<ide>
<del> }
<del> public static void main(String[] args) {
<del>
<del> for(int i=0; i < 15; i++){
<del> int arr[i] = (int)(Math.random() * 100 + 1);
<del> }
<del>
<del> System.out.println("array before sorting\n");
<del> for(int i=0; i < arr.length; i++){
<del> System.out.print(arr[i] + " ");
<del> }
<del> bubbleSort(arr);
<del> System.out.println("\n array after sorting\n");
<del> for(int i=0; i < arr.length; i++){
<del> System.out.print(arr[i] + " ");
<del> }
<del>
<del> }
<del> }
<add> System.out.println("array before sorting\n");
<add> for(int i=0; i < arr.length; i++){
<add> System.out.print(arr[i] + " ");
<add> }
<add> bubbleSort(arr);
<add> System.out.println("\n array after sorting\n");
<add> for(int i=0; i < arr.length; i++){
<add> System.out.print(arr[i] + " ");
<add> }
<add> }
<add> }
<ide> ```
<ide>
<del>\=======
<add>### Exemplo em C++
<ide>
<del>### A implementação recursiva do Bubble Sort.
<add>Exemplo 1:
<add>
<add>```cpp
<add>// Implementação Recursiva
<add>void bubblesort(int arr[], int n)
<add>{
<add> if(n==1) //Initial Case
<add> return;
<add> bool swap_flag = false;
<add> for(int i=0;i<n-1;i++) //After this pass the largest element will move to its desired location.
<add> {
<add> if(arr[i]>arr[i+1])
<add> {
<add> int temp=arr[i];
<add> arr[i]=arr[i+1];
<add> arr[i+1]=temp;
<add> swap_flag = true;
<add> }
<add> }
<add>// IF no two elements were swapped in the loop, then return, as array is sorted
<add> if(swap_flag == false)
<add> return;
<add> bubblesort(arr,n-1); //Recursion for remaining array
<add>}
<add>```
<add>
<add>Exemplo 2:
<ide>
<ide> ```cpp
<ide> void bubblesort(int arr[], int n)
<del> {
<del> if(n==1) //Initial Case
<del> return;
<del>
<del> for(int i=0;i<n-1;i++) //After this pass the largest element will move to its desired location.
<add>{
<add> if(n==1) //Initial Case
<add> return;
<add> for(int i=0;i<n-1;i++) //After this pass the largest element will move to its desired location.
<add> {
<add> if(arr[i]>arr[i+1])
<ide> {
<del> if(arr[i]>arr[i+1])
<del> {
<del> temp=arr[i];
<del> arr[i]=arr[i+1];
<del> arr[i+1]=temp;
<del> }
<add> temp=arr[i];
<add> arr[i]=arr[i+1];
<add> arr[i+1]=temp;
<ide> }
<del>
<del> bubblesort(arr,n-1); //Recursion for remaining array
<del> }
<add> }
<add> bubblesort(arr,n-1); //Recursion for remaining array
<add>}
<add>```
<add>
<add>### Exemplo em Ruby
<add>```ruby
<add>def bubble_sort(arr)
<add> sorted = false
<add> until sorted
<add> sorted = true
<add> (arr.count-1).times do|i|
<add> if arr[i] > arr[i + 1]
<add> arr[i], arr[i +1] = arr[i +1], arr[i]
<add> sorted = false
<add> end
<add> end
<add> end
<add>arr end
<add>```
<add>
<add>### Exemplo em PHP
<add>```php
<add>function bubble_sort($arr) {
<add> $size = count($arr)-1;
<add> for ($i=0; $i<$size; $i++) {
<add> for ($j=0; $j<$size-$i; $j++) {
<add> $k = $j+1;
<add> if ($arr[$k] < $arr[$j]) {
<add> // Swap elements at indices: $j, $k
<add> list($arr[$j], $arr[$k]) = array($arr[$k], $arr[$j]);
<add> }
<add> }
<add> }
<add> return $arr;// return the sorted array
<add>}
<add>
<add>$arr = array(1,3,2,8,5,7,4,0);
<add>print("Before sorting");
<add>print_r($arr);
<add>
<add>$arr = bubble_sort($arr);
<add>print("After sorting by using bubble sort");
<add>print_r($arr);
<add>```
<add>
<add>### Exemplo em C
<add>```c
<add>#include <stdio.h>
<add>
<add>int BubbleSort(int array[], int n);
<add>
<add>int main(void) {
<add> int arr[] = {10, 2, 3, 1, 4, 5, 8, 9, 7, 6};
<add> BubbleSort(arr, 10);
<add>
<add> for (int i = 0; i < 10; i++) {
<add> printf("%d", arr[i]);
<add> }
<add> return 0;
<add>}
<add>
<add>int BubbleSort(int array[], n)
<add>{
<add>for (int i = 0 ; i < n - 1; i++)
<add> {
<add> for (int j = 0 ; j < n - i - 1; j++) //n is length of array
<add> {
<add> if (array[j] > array[j+1]) // For decreasing order use
<add> {
<add> int swap = array[j];
<add> array[j] = array[j+1];
<add> array[j+1] = swap;
<add> }
<add> }
<add> }
<add>}
<ide> ```
<ide>
<ide> ### Mais Informações
<ide> void bubblesort(int arr[], int n)
<ide> * [Algoritmo de Classificação de Bolhas - MyCodeSchool (video)](https://www.youtube.com/watch?v=Jdtq5uKz-w4)
<ide> * [Algoritmos: Bubble Sort - HackerRank (vídeo)](https://www.youtube.com/watch?v=6Gv8vg0kcHc)
<ide> * [Algoritmo de classificação de bolhas - GeeksForGeeks (vídeo)](https://www.youtube.com/watch?v=nmhjrI-aW5o)
<del>* [Visualização de classificação de bolhas](https://www.hackerearth.com/practice/algorithms/sorting/bubble-sort/visualize/)
<ide>\ No newline at end of file
<add>* [Visualização de classificação de bolhas](https://www.hackerearth.com/practice/algorithms/sorting/bubble-sort/visualize/) | 1 |
Javascript | Javascript | add some missing glyphs | 84c2e99bef768bfb7a47376ab08275dc3213aba3 | <ide><path>PDFFont.js
<ide> Type1Font.prototype = {
<ide> var familyName = fontInfo.get("FamilyName");
<ide> var weight = fontInfo.get("Weight");
<ide> var strings = [version, notice, fullName,
<del> familyName, weight];
<add> familyName, weight, "asteriskmath"];
<ide> var stringsIndex = this.createCFFIndexHeader(strings);
<ide> var stringsDataLength = stringsIndex.length;
<ide>
<ide> Type1Font.prototype = {
<ide> var charset = [0x00];
<ide> for (var i = 0; i < glyphs.length; i++) {
<ide> var index = CFFStrings.indexOf(charstrings[i].glyph);
<add> if (index == -1)
<add> index = CFFStrings.length + strings.indexOf(glyph);
<ide> var bytes = this.integerToBytes(index, 2);
<ide> charset.push(bytes[0]);
<ide> charset.push(bytes[1]);
<ide> Type1Font.prototype = {
<ide> for (var i = 1; i < maxPower; i++)
<ide> value *= 2;
<ide>
<add> if (fontCount == 5) {
<add> log ("mp2: " + aNumber + "::" + value);
<add> }
<add>
<ide> return value;
<ide> },
<ide>
<ide> Type1Font.prototype = {
<ide> for (var i = 0; i < currentOffset; i++)
<ide> fontData.push(otf[i]);
<ide>
<del> //writeToFile(fontData, "/tmp/pdf.js." + fontCount + ".otf");
<add> writeToFile(fontData, "/tmp/pdf.js." + fontCount + ".otf");
<ide> return fontData;
<ide> }
<ide> };
<ide><path>glyphlist.js
<ide> var GlyphsUnicode = {
<ide> zretroflexhook: "0290",
<ide> zstroke: "01B6",
<ide> zuhiragana: "305A",
<del> zukatakana: "30BA",
<add> zukatakana: "30BA"
<ide> };
<add>
<add>// Add missing glyphs from the original Adobe's list
<add>GlyphsUnicode["angbracketleft"] = "3008";
<add>GlyphsUnicode["angbracketright"] = "3009";
<add>GlyphsUnicode["circlecopyrt"] = "00A9";
<add> | 2 |
Text | Text | use yaml code fence [ci-skip] | a4dbfc0089eb1c8d512b7572e4d1fce35bfd3e4a | <ide><path>guides/source/command_line.md
<ide> $ rails new petstore --database=postgresql
<ide> ...
<ide> ```
<ide>
<del>Let's see what it put in our database configuration:
<add>Let's see what it put in our `config/database.yml`:
<ide>
<del>```bash
<del>$ cd petstore
<del>$ cat config/database.yml
<add>```yaml
<ide> # PostgreSQL. Versions 9.3 and up are supported.
<ide> #
<ide> # Install the pg driver:
<ide> default: &default
<ide> # https://guides.rubyonrails.org/configuring.html#database-pooling
<ide> pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
<ide>
<del>..development:
<add>development:
<ide> <<: *default
<del> database: petstore_development.
<add> database: petstore_development
<ide> ...
<ide> ```
<ide>
<del>It generated some lines in our `database.yml` configuration corresponding
<del>to our choice of PostgreSQL for database.
<add>It generated a database configuration corresponding to our choice of PostgreSQL.
<ide>
<ide> Command Line Basics
<ide> ------------------- | 1 |
Javascript | Javascript | add missing space | b383fd9568f4e01f408b8c869a551bc386183887 | <ide><path>examples/real-world/middleware/api.js
<ide> function callApi(endpoint, schema) {
<ide>
<ide> return fetch(endpoint)
<ide> .then(response =>
<del> response.json().then(json => ({ json, response}))
<add> response.json().then(json => ({ json, response }))
<ide> ).then(({ json, response }) => {
<ide> if (!response.ok) {
<ide> return Promise.reject(json); | 1 |
Python | Python | add a new bar class to display bar in curse ui | f4cca4071770679b1ed3dd52584b17261f27ce1a | <ide><path>glances/outputs/glances_bars.py
<add># -*- coding: utf-8 -*-
<add>#
<add># This file is part of Glances.
<add>#
<add># Copyright (C) 2015 Nicolargo <nicolas@nicolargo.com>
<add>#
<add># Glances is free software; you can redistribute it and/or modify
<add># it under the terms of the GNU Lesser General Public License as published by
<add># the Free Software Foundation, either version 3 of the License, or
<add># (at your option) any later version.
<add>#
<add># Glances is distributed in the hope that it will be useful,
<add># but WITHOUT ANY WARRANTY; without even the implied warranty of
<add># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
<add># GNU Lesser General Public License for more details.
<add>#
<add># You should have received a copy of the GNU Lesser General Public License
<add># along with this program. If not, see <http://www.gnu.org/licenses/>.
<add>
<add>"""Manage bars for Glances output."""
<add>
<add># Import system lib
<add>from math import modf
<add>
<add># Global vars
<add>curses_bars = [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉", "█"]
<add>
<add>
<add>class Bar(object):
<add> """Manage bar (progression or status)
<add>
<add> import sys
<add> import time
<add> b = Bar(10)
<add> for p in range(0, 100):
<add> b.set_percent(p)
<add> print("\r%s" % b),
<add> time.sleep(0.1)
<add> sys.stdout.flush()
<add>
<add> """
<add>
<add> def __init__(self, size):
<add> # Bar size
<add> self.__size = size
<add> # Bar current percent
<add> self.__percent = 0
<add>
<add> def get_size(self):
<add> return self.__size
<add>
<add> def set_size(self, size):
<add> self.__size = size
<add> return self.__size
<add>
<add> def get_percent(self):
<add> return self.__percent
<add>
<add> def set_percent(self, percent):
<add> assert percent >= 0
<add> assert percent <= 100
<add> self.__percent = percent
<add> return self.__percent
<add>
<add> def __str__(self):
<add> """Return the bars"""
<add> frac, whole = modf(self.get_size() * self.get_percent() / 100.0)
<add> ret = curses_bars[8] * int(whole)
<add> if frac > 0:
<add> ret += curses_bars[int(frac * 8)]
<add> whole += 1
<add> ret += '_' * int(self.get_size() - whole)
<add> return ret | 1 |
Javascript | Javascript | use tty methods instead of control sequences | 8c9b2d1066380b3637ce77148a05127296999bf9 | <ide><path>lib/readline.js
<ide> Interface.prototype._refreshLine = function() {
<ide> if (this._closed) return;
<ide>
<ide> // Cursor to left edge.
<del> this.output.write('\x1b[0G');
<add> this.output.cursorTo(0);
<ide>
<ide> // Write the prompt and the current buffer content.
<ide> this.output.write(this._prompt);
<ide> this.output.write(this.line);
<ide>
<ide> // Erase to right.
<del> this.output.write('\x1b[0K');
<add> this.output.clearLine(1);
<ide>
<ide> // Move cursor to original position.
<del> this.output.write('\x1b[0G\x1b[' + (this._promptLength + this.cursor) + 'C');
<add> this.output.cursorTo(this._promptLength + this.cursor);
<ide> };
<ide>
<ide>
<ide> Interface.prototype._ttyWrite = function(b) {
<ide> // left arrow
<ide> if (this.cursor > 0) {
<ide> this.cursor--;
<del> this.output.write('\x1b[0D');
<add> this.output.moveCursor(-1, 0);
<ide> }
<ide>
<ide> } else if (b[1] === 91 && b[2] === 67) {
<ide> // right arrow
<ide> if (this.cursor != this.line.length) {
<ide> this.cursor++;
<del> this.output.write('\x1b[0C');
<add> this.output.moveCursor(1, 0);
<ide> }
<ide>
<ide> } else if ((b[1] === 91 && b[2] === 72) || | 1 |
Javascript | Javascript | fix error message string | 70c5bcea209bcf9037e29526d5005efe60557bc1 | <ide><path>common/models/user.js
<ide> module.exports = function(User) {
<ide> if (!username) {
<ide> // Zalgo!!
<ide> return nextTick(() => {
<del> cb(
<del> new TypeError('FCC: username should be a string but got %s', username)
<del> );
<add> cb(new TypeError(
<add> `username should be a string but got ${ username }`
<add> ));
<ide> });
<ide> }
<ide> User.findOne({ where: { username } }, (err, user) => {
<ide> if (err) {
<ide> return cb(err);
<ide> }
<ide> if (!user || user.username !== username) {
<del> return cb(new Error('FCC: no user found for %s', username));
<add> return cb(new Error(`no user found for ${ username }`));
<ide> }
<ide> const aboutUser = getAboutProfile(user);
<ide> return cb(null, aboutUser); | 1 |
Javascript | Javascript | improve coverage for 'internal/errors' | 09d8b3576fbe473608e11c5045f42bb1d8df6137 | <ide><path>test/parallel/test-internal-errors.js
<ide> assert.strictEqual(
<ide> 'Request path contains unescaped characters'
<ide> );
<ide>
<add>// Test ERR_DNS_SET_SERVERS_FAILED
<add>assert.strictEqual(
<add> errors.message('ERR_DNS_SET_SERVERS_FAILED', ['err', 'servers']),
<add> 'c-ares failed to set servers: "err" [servers]');
<add>
<add>// Test ERR_ENCODING_NOT_SUPPORTED
<add>assert.strictEqual(
<add> errors.message('ERR_ENCODING_NOT_SUPPORTED', ['enc']),
<add> 'The "enc" encoding is not supported');
<add>
<add>// Test ERR_HTTP2_HEADER_REQUIRED
<add>assert.strictEqual(
<add> errors.message('ERR_HTTP2_HEADER_REQUIRED', ['test']),
<add> 'The test header is required');
<ide>
<ide> // Test error messages for async_hooks
<ide> assert.strictEqual( | 1 |
Mixed | Ruby | fix in_order_of for integer enums | 8565463bfdc3371561dbafe06e603ddc0f96934a | <ide><path>activerecord/CHANGELOG.md
<add>* Fix `ActiveRecord::QueryMethods#in_order_of` behavior for integer enums
<add>
<add> `ActiveRecord::QueryMethods#in_order_of` didn't work as expected for enums stored as integers in the database when passing an array of strings or symbols as the order argument. This unexpected behavior occurred because the string or symbol values were not casted to match the integers in the database.
<add>
<add> The following example now works as expected:
<add>
<add> ```rb
<add> class Book < ApplicationRecord
<add> enum status: [:proposed, :written, :published]
<add> end
<add>
<add> Book.in_order_of(:status, %w[written published proposed])
<add> ```
<add>
<add> *Alexandre Ruban*
<add>
<ide> * Add option to lazily load the schema cache on the connection.
<ide>
<ide> Previously, the only way to load the schema cache in Active Record was through the Railtie on boot. This option provides the ability to load the schema cache on the connection after it's been established. Loading the cache lazily on the connection can be beneficial for Rails applications that use multiple databases because it will load the cache at the time the connection is established. Currently Railties doesn't have access to the connections before boot.
<ide><path>activerecord/lib/active_record/relation/query_methods.rb
<ide> def in_order_of(column, values)
<ide> references = column_references([column])
<ide> self.references_values |= references unless references.empty?
<ide>
<add> values = values.map { |value| type_caster.type_cast_for_database(column, value) }
<ide> column = order_column(column.to_s) if column.is_a?(Symbol)
<ide>
<ide> spawn.order!(connection.field_ordered_value(column, values))
<ide><path>activerecord/test/cases/relation/field_ordered_values_test.rb
<ide>
<ide> require "cases/helper"
<ide> require "models/post"
<add>require "models/book"
<ide>
<ide> class FieldOrderedValuesTest < ActiveRecord::TestCase
<ide> fixtures :posts
<ide> def test_in_order_of
<ide> assert_equal(order, posts.map(&:id))
<ide> end
<ide>
<add> def test_in_order_of_with_enums_values
<add> Book.destroy_all
<add> Book.create!(status: :proposed)
<add> Book.create!(status: :written)
<add> Book.create!(status: :published)
<add>
<add> order = %w[written published proposed]
<add> books = Book.in_order_of(:status, order)
<add>
<add> assert_equal(order, books.map(&:status))
<add> end
<add>
<add> def test_in_order_of_with_enums_keys
<add> Book.destroy_all
<add> Book.create!(status: :proposed)
<add> Book.create!(status: :written)
<add> Book.create!(status: :published)
<add>
<add> order = [Book.statuses[:written], Book.statuses[:published], Book.statuses[:proposed]]
<add> books = Book.in_order_of(:status, order)
<add>
<add> assert_equal(order, books.map { |book| Book.statuses[book.status] })
<add> end
<add>
<ide> def test_in_order_of_expression
<ide> order = [3, 4, 1]
<ide> posts = Post.in_order_of(Arel.sql("id * 2"), order.map { |id| id * 2 }).limit(3) | 3 |
Ruby | Ruby | use json to marshal child errors | 86b964745038eebff6218e97735e6344b6f3e42a | <ide><path>Library/Homebrew/build.rb
<ide> def fixopt(f)
<ide> build = Build.new(formula, options)
<ide> build.install
<ide> rescue Exception => e # rubocop:disable Lint/RescueException
<del> Marshal.dump(e, error_pipe)
<add> error_hash = JSON.parse e.to_json
<add>
<add> # Special case: need to recreate BuildErrors in full
<add> # for proper analytics reporting and error messages.
<add> # BuildErrors are specific to build processses and not other
<add> # children, which is why we create the necessary state here
<add> # and not in Utils.safe_fork.
<add> if error_hash["json_class"] == "BuildError"
<add> error_hash["cmd"] = e.cmd
<add> error_hash["args"] = e.args
<add> error_hash["env"] = e.env
<add> end
<add>
<add> error_pipe.puts error_hash.to_json
<ide> error_pipe.close
<ide> exit! 1
<ide> end
<ide><path>Library/Homebrew/dev-cmd/test.rb
<ide> def test
<ide> exec(*args)
<ide> end
<ide> end
<del> rescue ::Test::Unit::AssertionFailedError => e
<del> ofail "#{f.full_name}: failed"
<del> puts e.message
<ide> rescue Exception => e # rubocop:disable Lint/RescueException
<ide> ofail "#{f.full_name}: failed"
<ide> puts e, e.backtrace
<ide><path>Library/Homebrew/exceptions.rb
<ide> def initialize(formula)
<ide> end
<ide>
<ide> class BuildError < RuntimeError
<del> attr_reader :formula, :env
<del> attr_accessor :options
<add> attr_reader :cmd, :args, :env
<add> attr_accessor :formula, :options
<ide>
<ide> def initialize(formula, cmd, args, env)
<ide> @formula = formula
<add> @cmd = cmd
<add> @args = args
<ide> @env = env
<del> args = args.map { |arg| arg.to_s.gsub " ", "\\ " }.join(" ")
<del> super "Failed executing: #{cmd} #{args}"
<add> pretty_args = args.map { |arg| arg.to_s.gsub " ", "\\ " }.join(" ")
<add> super "Failed executing: #{cmd} #{pretty_args}"
<ide> end
<ide>
<ide> def issues
<ide> def initialize(cause)
<ide>
<ide> # raised by safe_system in utils.rb
<ide> class ErrorDuringExecution < RuntimeError
<add> attr_reader :cmd
<ide> attr_reader :status
<add> attr_reader :output
<ide>
<ide> def initialize(cmd, status:, output: nil)
<add> @cmd = cmd
<ide> @status = status
<add> @output = output
<ide>
<del> s = "Failure while executing; `#{cmd.shelljoin.gsub(/\\=/, "=")}` exited with #{status.exitstatus}."
<add> exitstatus = if status.respond_to?(:exitstatus)
<add> status.exitstatus
<add> else
<add> status
<add> end
<add>
<add> s = "Failure while executing; `#{cmd.shelljoin.gsub(/\\=/, "=")}` exited with #{exitstatus}."
<ide>
<ide> unless [*output].empty?
<ide> format_output_line = lambda do |type, line|
<ide> def initialize(bottle_path, formula_path)
<ide> EOS
<ide> end
<ide> end
<add>
<add># Raised when a child process sends us an exception over its error pipe.
<add>class ChildProcessError < RuntimeError
<add> attr_reader :inner
<add> attr_reader :inner_class
<add>
<add> def initialize(inner)
<add> @inner = inner
<add> @inner_class = Object.const_get inner["json_class"]
<add>
<add> super <<~EOS
<add> An exception occured within a build process:
<add> #{inner_class}: #{inner["m"]}
<add> EOS
<add>
<add> # Clobber our real (but irrelevant) backtrace with that of the inner exception.
<add> set_backtrace inner["b"]
<add> end
<add>end
<ide><path>Library/Homebrew/formula_installer.rb
<ide> def build
<ide> raise "Empty installation"
<ide> end
<ide> rescue Exception => e # rubocop:disable Lint/RescueException
<del> e.options = display_options(formula) if e.is_a?(BuildError)
<add> if e.is_a? BuildError
<add> e.formula = formula
<add> e.options = options
<add> end
<add>
<ide> ignore_interrupts do
<ide> # any exceptions must leave us with nothing installed
<ide> formula.update_head_version
<ide> formula.prefix.rmtree if formula.prefix.directory?
<ide> formula.rack.rmdir_if_possible
<ide> end
<del> raise
<add> raise e
<ide> end
<ide>
<ide> def link(keg)
<ide><path>Library/Homebrew/global.rb
<ide> require "pathname"
<ide> require "English"
<add>require "json"
<add>require "json/add/core"
<ide>
<ide> HOMEBREW_LIBRARY_PATH = Pathname.new(__FILE__).realpath.parent
<ide>
<ide><path>Library/Homebrew/postinstall.rb
<ide> formula.extend(Debrew::Formula) if ARGV.debug?
<ide> formula.run_post_install
<ide> rescue Exception => e # rubocop:disable Lint/RescueException
<del> Marshal.dump(e, error_pipe)
<add> error_pipe.puts e.to_json
<ide> error_pipe.close
<ide> exit! 1
<ide> end
<ide><path>Library/Homebrew/test.rb
<ide> raise "test returned false" if formula.run_test == false
<ide> end
<ide> rescue Exception => e # rubocop:disable Lint/RescueException
<del> Marshal.dump(e, error_pipe)
<add> error_pipe.puts e.to_json
<ide> error_pipe.close
<ide> exit! 1
<ide> end
<ide><path>Library/Homebrew/test/formula_installer_spec.rb
<ide> require "tab"
<ide> require "test/support/fixtures/testball"
<ide> require "test/support/fixtures/testball_bottle"
<add>require "test/support/fixtures/failball"
<ide>
<ide> describe FormulaInstaller do
<ide> define_negated_matcher :need_bottle, :be_bottle_unneeded
<ide> def temporary_install(formula)
<ide> Tab.clear_cache
<ide> expect(Tab.for_keg(keg)).not_to be_poured_from_bottle
<ide>
<del> yield formula
<add> yield formula if block_given?
<ide> ensure
<ide> Tab.clear_cache
<ide> keg.unlink
<ide> class #{Formulary.class_s(dep_name)} < Formula
<ide> fi.check_install_sanity
<ide> }.to raise_error(CannotInstallFormulaError)
<ide> end
<add>
<add> specify "install fails with BuildError when a system() call fails" do
<add> ENV["HOMEBREW_TEST_NO_EXIT_CLEANUP"] = "1"
<add> ENV["FAILBALL_BUILD_ERROR"] = "1"
<add>
<add> expect {
<add> temporary_install(Failball.new)
<add> }.to raise_error(BuildError)
<add> end
<add>
<add> specify "install fails with a RuntimeError when #install raises" do
<add> ENV["HOMEBREW_TEST_NO_EXIT_CLEANUP"] = "1"
<add>
<add> expect {
<add> temporary_install(Failball.new)
<add> }.to raise_error(RuntimeError)
<add> end
<ide> end
<ide><path>Library/Homebrew/test/support/fixtures/failball.rb
<add>class Failball < Formula
<add> def initialize(name = "failball", path = Pathname.new(__FILE__).expand_path, spec = :stable, alias_path: nil)
<add> self.class.instance_eval do
<add> stable.url "file://#{TEST_FIXTURE_DIR}/tarballs/testball-0.1.tbz"
<add> stable.sha256 TESTBALL_SHA256
<add> end
<add> super
<add> end
<add>
<add> def install
<add> prefix.install "bin"
<add> prefix.install "libexec"
<add>
<add> # This should get marshalled into a BuildError.
<add> system "/usr/bin/false" if ENV["FAILBALL_BUILD_ERROR"]
<add>
<add> # This should get marshalled into a RuntimeError.
<add> raise "something that isn't a build error happened!"
<add> end
<add>end
<ide><path>Library/Homebrew/test/support/lib/config.rb
<ide>
<ide> TEST_TMPDIR = ENV.fetch("HOMEBREW_TEST_TMPDIR") do |k|
<ide> dir = Dir.mktmpdir("homebrew-tests-", ENV["HOMEBREW_TEMP"] || "/tmp")
<del> at_exit { FileUtils.remove_entry(dir) }
<add> at_exit do
<add> # Child processes inherit this at_exit handler, but we don't want them
<add> # to clean TEST_TMPDIR up prematurely (i.e., when they exit early for a test).
<add> FileUtils.remove_entry(dir) unless ENV["HOMEBREW_TEST_NO_EXIT_CLEANUP"]
<add> end
<ide> ENV[k] = dir
<ide> end
<ide>
<ide><path>Library/Homebrew/test/utils/fork_spec.rb
<add>require "utils/fork"
<add>
<add>describe Utils do
<add> describe "#safe_fork" do
<add> it "raises a RuntimeError on an error that isn't ErrorDuringExecution" do
<add> expect {
<add> described_class.safe_fork do
<add> raise "this is an exception in the child"
<add> end
<add> }.to raise_error(RuntimeError)
<add> end
<add>
<add> it "raises an ErrorDuringExecution on one in the child" do
<add> expect {
<add> described_class.safe_fork do
<add> safe_system "/usr/bin/false"
<add> end
<add> }.to raise_error(ErrorDuringExecution)
<add> end
<add> end
<add>end
<ide><path>Library/Homebrew/utils/fork.rb
<ide> require "socket"
<ide>
<ide> module Utils
<add> def self.rewrite_child_error(child_error)
<add> error = if child_error.inner_class == ErrorDuringExecution
<add> ErrorDuringExecution.new(child_error.inner["cmd"],
<add> status: child_error.inner["status"],
<add> output: child_error.inner["output"])
<add> elsif child_error.inner_class == BuildError
<add> # We fill `BuildError#formula` and `BuildError#options` in later,
<add> # when we rescue this in `FormulaInstaller#build`.
<add> BuildError.new(nil, child_error.inner["cmd"],
<add> child_error.inner["args"], child_error.inner["env"])
<add> else
<add> # Everything other error in the child just becomes a RuntimeError.
<add> RuntimeError.new(child_error.message)
<add> end
<add>
<add> error.set_backtrace child_error.backtrace
<add>
<add> error
<add> end
<add>
<ide> def self.safe_fork(&_block)
<ide> Dir.mktmpdir("homebrew", HOMEBREW_TEMP) do |tmpdir|
<ide> UNIXServer.open("#{tmpdir}/socket") do |server|
<ide> def self.safe_fork(&_block)
<ide> write.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
<ide> yield
<ide> rescue Exception => e # rubocop:disable Lint/RescueException
<del> Marshal.dump(e, write)
<add> error_hash = JSON.parse e.to_json
<add>
<add> # Special case: We need to recreate ErrorDuringExecutions
<add> # for proper error messages and because other code expects
<add> # to rescue them further down.
<add> if e.is_a?(ErrorDuringExecution)
<add> error_hash["cmd"] = e.cmd
<add> error_hash["status"] = e.status.exitstatus
<add> error_hash["output"] = e.output
<add> end
<add>
<add> write.puts error_hash.to_json
<ide> write.close
<ide> exit!
<ide> else
<ide> def self.safe_fork(&_block)
<ide> socket.close
<ide> end
<ide> write.close
<del> data = read.read
<add> # Each line on the error pipe contains a JSON-serialized exception.
<add> # We read the first, since only one is necessary for a failure.
<add> data = read.gets
<ide> read.close
<ide> Process.wait(pid) unless socket.nil?
<del> raise Marshal.load(data) unless data.nil? || data.empty? # rubocop:disable Security/MarshalLoad
<add>
<add> if data && !data.empty?
<add> error_hash = JSON.parse(data) unless data.nil? || data.empty?
<add>
<add> e = ChildProcessError.new(error_hash)
<add>
<add> raise rewrite_child_error(e)
<add> end
<add>
<ide> raise Interrupt if $CHILD_STATUS.exitstatus == 130
<ide> raise "Forked child process failed: #{$CHILD_STATUS}" unless $CHILD_STATUS.success?
<ide> end | 12 |
Python | Python | use _state.default_app for none check (issue ) | 28c1c8da3737bb33186a8a1ade152acd633dcca5 | <ide><path>celery/fixups/django.py
<ide> from datetime import datetime
<ide> from importlib import import_module
<ide>
<add>from celery import _state
<ide> from celery import signals
<del>from celery.app import default_app
<ide> from celery.exceptions import FixupWarning
<ide>
<ide> __all__ = ['DjangoFixup', 'fixup']
<ide> class DjangoFixup(object):
<ide>
<ide> def __init__(self, app):
<ide> self.app = app
<del> if default_app is None:
<add> if _state.default_app is None:
<ide> self.app.set_default()
<ide> self._worker_fixup = None
<ide>
<ide><path>t/unit/fixups/test_django.py
<ide> class test_DjangoFixup(FixupCase):
<ide> Fixup = DjangoFixup
<ide>
<ide> def test_setting_default_app(self):
<add> from celery import _state
<ide> from celery.fixups import django
<del> prev, django.default_app = django.default_app, None
<add> prev, _state.default_app = _state.default_app, None
<ide> try:
<ide> app = Mock(name='app')
<ide> DjangoFixup(app)
<ide> app.set_default.assert_called_with()
<ide> finally:
<del> django.default_app = prev
<add> _state.default_app = prev
<ide>
<ide> @patch('celery.fixups.django.DjangoWorkerFixup')
<ide> def test_worker_fixup_property(self, DjangoWorkerFixup): | 2 |
Python | Python | use _umath_linalg for eigh() | cc7b048fafeb93150f118651438faf06aefe807b | <ide><path>numpy/linalg/linalg.py
<ide> def eigh(a, UPLO='L'):
<ide>
<ide> Parameters
<ide> ----------
<del> a : (M, M) array_like
<del> A complex Hermitian or real symmetric matrix.
<add> A : (..., M, M) array
<add> Hermitian/Symmetric matrices whose eigenvalues and
<add> eigenvectors are to be computed.
<ide> UPLO : {'L', 'U'}, optional
<ide> Specifies whether the calculation is done with the lower triangular
<ide> part of `a` ('L', default) or the upper triangular part ('U').
<ide>
<ide> Returns
<ide> -------
<del> w : (M,) ndarray
<add> w : (..., M) ndarray
<ide> The eigenvalues, not necessarily ordered.
<del> v : {(M, M) ndarray, (M, M) matrix}
<add> v : {(..., M, M) ndarray, (..., M, M) matrix}
<ide> The column ``v[:, i]`` is the normalized eigenvector corresponding
<ide> to the eigenvalue ``w[i]``. Will return a matrix object if `a` is
<ide> a matrix object.
<ide> def eigh(a, UPLO='L'):
<ide>
<ide> Notes
<ide> -----
<del> This is a simple interface to the LAPACK routines dsyevd and zheevd,
<del> which compute the eigenvalues and eigenvectors of real symmetric and
<del> complex Hermitian arrays, respectively.
<add> Broadcasting rules apply, see the `numpy.linalg` documentation for
<add> details.
<add>
<add> The eigenvalues/eigenvectors are computed using LAPACK routines _ssyevd,
<add> _heevd
<ide>
<ide> The eigenvalues of real symmetric or complex Hermitian matrices are
<ide> always real. [1]_ The array `v` of (column) eigenvectors is unitary
<ide> def eigh(a, UPLO='L'):
<ide>
<ide> """
<ide> UPLO = asbytes(UPLO)
<add>
<ide> a, wrap = _makearray(a)
<del> _assertRank2(a)
<del> _assertSquareness(a)
<add> _assertRankAtLeast2(a)
<add> _assertNdSquareness(a)
<ide> t, result_t = _commonType(a)
<del> real_t = _linalgRealType(t)
<del> a = _fastCopyAndTranspose(t, a)
<del> a = _to_native_byte_order(a)
<del> n = a.shape[0]
<del> liwork = 5*n+3
<del> iwork = zeros((liwork,), fortran_int)
<del> if isComplexType(t):
<del> lapack_routine = lapack_lite.zheevd
<del> w = zeros((n,), real_t)
<del> lwork = 1
<del> work = zeros((lwork,), t)
<del> lrwork = 1
<del> rwork = zeros((lrwork,), real_t)
<del> results = lapack_routine(_V, UPLO, n, a, n, w, work, -1,
<del> rwork, -1, iwork, liwork, 0)
<del> lwork = int(abs(work[0]))
<del> work = zeros((lwork,), t)
<del> lrwork = int(rwork[0])
<del> rwork = zeros((lrwork,), real_t)
<del> results = lapack_routine(_V, UPLO, n, a, n, w, work, lwork,
<del> rwork, lrwork, iwork, liwork, 0)
<add>
<add> extobj = get_linalg_error_extobj(
<add> _raise_linalgerror_eigenvalues_nonconvergence)
<add> if 'L' == UPLO:
<add> gufunc = _umath_linalg.eigh_lo
<ide> else:
<del> lapack_routine = lapack_lite.dsyevd
<del> w = zeros((n,), t)
<del> lwork = 1
<del> work = zeros((lwork,), t)
<del> results = lapack_routine(_V, UPLO, n, a, n, w, work, -1,
<del> iwork, liwork, 0)
<del> lwork = int(work[0])
<del> work = zeros((lwork,), t)
<del> results = lapack_routine(_V, UPLO, n, a, n, w, work, lwork,
<del> iwork, liwork, 0)
<del> if results['info'] > 0:
<del> raise LinAlgError('Eigenvalues did not converge')
<del> at = a.transpose().astype(result_t)
<del> return w.astype(_realType(result_t)), wrap(at)
<add> gufunc = _umath_linalg.eigh_up
<add>
<add> w, vt = gufunc(a.astype(t), extobj=extobj)
<add> w = w.astype(_realType(result_t))
<add> vt = vt.astype(result_t)
<add> return w, wrap(vt)
<ide>
<ide>
<ide> # Singular value decomposition | 1 |
Python | Python | add system tests for cloudkmshook | 23f27c1b1cdbcb6bb50fd2aa772aeda7151d5634 | <ide><path>airflow/providers/google/cloud/hooks/kms.py
<ide> def decrypt(
<ide> metadata=metadata,
<ide> )
<ide>
<del> plaintext = response.plaintext
<del> return plaintext
<add> return response.plaintext
<ide><path>tests/providers/google/cloud/hooks/test_kms_system.py
<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>import base64
<add>import os
<add>from tempfile import TemporaryDirectory
<add>
<add>import pytest
<add>
<add>from airflow.providers.google.cloud.hooks.kms import CloudKMSHook
<add>from tests.providers.google.cloud.utils.gcp_authenticator import GCP_KMS_KEY
<add>from tests.test_utils.gcp_system_helpers import GoogleSystemTest, provide_gcp_context
<add>
<add># To prevent resource name collisions, key ring and key resources CANNOT be deleted, so
<add># to avoid cluttering the project, we only create the key once during project initialization.
<add># See: https://cloud.google.com/kms/docs/faq#cannot_delete
<add>GCP_KMS_KEYRING_NAME = os.environ.get('GCP_KMS_KEYRING_NAME', 'test-airflow-system-tests-keyring')
<add>GCP_KMS_KEY_NAME = os.environ.get('GCP_KMS_KEY_NAME', 'test-airflow-system-tests-key')
<add>
<add>
<add>@pytest.mark.credential_file(GCP_KMS_KEY)
<add>class TestKmsHook(GoogleSystemTest):
<add> @provide_gcp_context(GCP_KMS_KEY)
<add> def test_encrypt(self):
<add> with TemporaryDirectory() as tmp_dir:
<add> kms_hook = CloudKMSHook()
<add> content = kms_hook.encrypt(
<add> key_name=(
<add> f"projects/{kms_hook.project_id}/locations/global/keyRings/"
<add> f"{GCP_KMS_KEYRING_NAME}/cryptoKeys/{GCP_KMS_KEY_NAME}"
<add> ),
<add> plaintext=b"TEST-SECRET",
<add> )
<add> with open(f"{tmp_dir}/mysecret.txt.encrypted", "wb") as encrypted_file:
<add> encrypted_file.write(base64.b64decode(content))
<add> self.execute_cmd(
<add> [
<add> "gcloud",
<add> "kms",
<add> "decrypt",
<add> "--location",
<add> "global",
<add> "--keyring",
<add> GCP_KMS_KEYRING_NAME,
<add> "--key",
<add> GCP_KMS_KEY_NAME,
<add> "--ciphertext-file",
<add> f"{tmp_dir}/mysecret.txt.encrypted",
<add> "--plaintext-file",
<add> f"{tmp_dir}/mysecret.txt",
<add> ]
<add> )
<add> with open(f"{tmp_dir}/mysecret.txt", "rb") as secret_file:
<add> secret = secret_file.read()
<add> self.assertEqual(secret, b"TEST-SECRET")
<add>
<add> @provide_gcp_context(GCP_KMS_KEY)
<add> def test_decrypt(self):
<add> with TemporaryDirectory() as tmp_dir:
<add> with open(f"{tmp_dir}/mysecret.txt", "w") as secret_file:
<add> secret_file.write("TEST-SECRET")
<add> self.execute_cmd(
<add> [
<add> "gcloud",
<add> "kms",
<add> "encrypt",
<add> "--location",
<add> "global",
<add> "--keyring",
<add> GCP_KMS_KEYRING_NAME,
<add> "--key",
<add> GCP_KMS_KEY_NAME,
<add> "--plaintext-file",
<add> f"{tmp_dir}/mysecret.txt",
<add> "--ciphertext-file",
<add> f"{tmp_dir}/mysecret.txt.encrypted",
<add> ]
<add> )
<add> with open(f"{tmp_dir}/mysecret.txt.encrypted", "rb") as encrypted_file:
<add> encrypted_secret = base64.b64encode(encrypted_file.read()).decode()
<add>
<add> kms_hook = CloudKMSHook()
<add> content = kms_hook.decrypt(
<add> key_name=(
<add> f"projects/{kms_hook.project_id}/locations/global/keyRings/"
<add> f"{GCP_KMS_KEYRING_NAME}/cryptoKeys/{GCP_KMS_KEY_NAME}"
<add> ),
<add> ciphertext=encrypted_secret,
<add> )
<add> self.assertEqual(content, b"TEST-SECRET")
<ide><path>tests/providers/google/cloud/utils/gcp_authenticator.py
<ide> GCP_GCS_KEY = 'gcp_gcs.json'
<ide> GCP_GCS_TRANSFER_KEY = 'gcp_gcs_transfer.json'
<ide> GCP_GKE_KEY = "gcp_gke.json"
<add>GCP_KMS_KEY = "gcp_kms.json"
<ide> GCP_LIFE_SCIENCES_KEY = 'gcp_life_sciences.json'
<ide> GCP_MEMORYSTORE = 'gcp_memorystore.json'
<ide> GCP_PUBSUB_KEY = "gcp_pubsub.json"
<ide><path>tests/test_utils/gcp_system_helpers.py
<ide> def provide_gcp_context(
<ide> :param scopes: OAuth scopes for the connection
<ide> :type scopes: Sequence
<ide> :param project_id: The id of GCP project for the connection.
<add> Default: ``os.environ["GCP_PROJECT_ID"]`` or None
<ide> :type project_id: str
<ide> """
<ide> key_file_path = resolve_full_gcp_key_path(key_file_path) # type: ignore
<add> if project_id is None:
<add> project_id = os.environ.get("GCP_PROJECT_ID")
<ide> with provide_gcp_conn_and_credentials(
<ide> key_file_path, scopes, project_id
<ide> ), tempfile.TemporaryDirectory() as gcloud_config_tmp, mock.patch.dict( | 4 |
Javascript | Javascript | add tests and fix wasted render calculation | 7b241d1d7fa285218fcdb3522b24de1bce9c8b25 | <ide><path>src/isomorphic/ReactPerf.js
<ide> function getExclusive(flushHistory = getFlushHistory()) {
<ide> var aggregatedStats = {};
<ide> var affectedIDs = {};
<ide>
<del> function updateAggregatedStats(treeSnapshot, instanceID, applyUpdate) {
<add> function updateAggregatedStats(treeSnapshot, instanceID, timerType, applyUpdate) {
<ide> var {displayName} = treeSnapshot[instanceID];
<del>
<ide> var key = displayName;
<ide> var stats = aggregatedStats[key];
<del>
<ide> if (!stats) {
<ide> affectedIDs[key] = {};
<ide> stats = aggregatedStats[key] = {
<ide> function getExclusive(flushHistory = getFlushHistory()) {
<ide> totalDuration: 0,
<ide> };
<ide> }
<del>
<add> if (!stats.durations[timerType]) {
<add> stats.durations[timerType] = 0;
<add> }
<add> if (!stats.counts[timerType]) {
<add> stats.counts[timerType] = 0;
<add> }
<ide> affectedIDs[key][instanceID] = true;
<ide> applyUpdate(stats);
<ide> }
<ide> function getExclusive(flushHistory = getFlushHistory()) {
<ide> var {measurements, treeSnapshot} = flush;
<ide> measurements.forEach(measurement => {
<ide> var {duration, instanceID, timerType} = measurement;
<del> updateAggregatedStats(treeSnapshot, instanceID, stats => {
<add> updateAggregatedStats(treeSnapshot, instanceID, timerType, stats => {
<ide> stats.totalDuration += duration;
<del>
<del> if (!stats.durations[timerType]) {
<del> stats.durations[timerType] = 0;
<del> }
<ide> stats.durations[timerType] += duration;
<del>
<del> if (!stats.counts[timerType]) {
<del> stats.counts[timerType] = 0;
<del> }
<ide> stats.counts[timerType]++;
<ide> });
<ide> });
<ide> function getExclusive(flushHistory = getFlushHistory()) {
<ide> ...aggregatedStats[key],
<ide> instanceCount: Object.keys(affectedIDs[key]).length,
<ide> }))
<del> .sort((a, b) => b.totalDuration - a.totalDuration);
<add> .sort((a, b) =>
<add> b.totalDuration - a.totalDuration
<add> );
<ide> }
<ide>
<del>function getInclusive(flushHistory = getFlushHistory(), wastedOnly) {
<add>function getInclusive(flushHistory = getFlushHistory()) {
<ide> var aggregatedStats = {};
<ide> var affectedIDs = {};
<ide>
<ide> function updateAggregatedStats(treeSnapshot, instanceID, applyUpdate) {
<ide> var {displayName, ownerID} = treeSnapshot[instanceID];
<del>
<ide> var owner = treeSnapshot[ownerID];
<ide> var key = `${owner ? owner.displayName + ' >' : ''} ${displayName}`;
<ide> var stats = aggregatedStats[key];
<del>
<ide> if (!stats) {
<ide> affectedIDs[key] = {};
<ide> stats = aggregatedStats[key] = {
<ide> function getInclusive(flushHistory = getFlushHistory(), wastedOnly) {
<ide> renderCount: 0,
<ide> };
<ide> }
<del>
<ide> affectedIDs[key][instanceID] = true;
<ide> applyUpdate(stats);
<ide> }
<ide>
<del> var hasRenderedByID = {};
<add> var isCompositeByID = {};
<ide> flushHistory.forEach(flush => {
<ide> var {measurements} = flush;
<ide> measurements.forEach(measurement => {
<ide> var {instanceID, timerType} = measurement;
<ide> if (timerType !== 'render') {
<ide> return;
<ide> }
<del> hasRenderedByID[instanceID] = true;
<add> isCompositeByID[instanceID] = true;
<ide> });
<ide> });
<ide>
<ide> function getInclusive(flushHistory = getFlushHistory(), wastedOnly) {
<ide> });
<ide> var nextParentID = instanceID;
<ide> while (nextParentID) {
<del> if (hasRenderedByID[nextParentID]) {
<add> // As we traverse parents, only count inclusive time towards composites.
<add> // We know something is a composite if its render() was called.
<add> if (isCompositeByID[nextParentID]) {
<ide> updateAggregatedStats(treeSnapshot, nextParentID, stats => {
<ide> stats.inclusiveRenderDuration += duration;
<ide> });
<ide> function getInclusive(flushHistory = getFlushHistory(), wastedOnly) {
<ide> ...aggregatedStats[key],
<ide> instanceCount: Object.keys(affectedIDs[key]).length,
<ide> }))
<del> .sort((a, b) => b.inclusiveRenderDuration - a.inclusiveRenderDuration);
<add> .sort((a, b) =>
<add> b.inclusiveRenderDuration - a.inclusiveRenderDuration
<add> );
<ide> }
<ide>
<ide> function getWasted(flushHistory = getFlushHistory()) {
<ide> function getWasted(flushHistory = getFlushHistory()) {
<ide>
<ide> function updateAggregatedStats(treeSnapshot, instanceID, applyUpdate) {
<ide> var {displayName, ownerID} = treeSnapshot[instanceID];
<del>
<ide> var owner = treeSnapshot[ownerID];
<ide> var key = (owner ? owner.displayName + ' > ' : '') + displayName;
<ide> var stats = aggregatedStats[key];
<del>
<ide> if (!stats) {
<ide> affectedIDs[key] = {};
<ide> stats = aggregatedStats[key] = {
<ide> function getWasted(flushHistory = getFlushHistory()) {
<ide> renderCount: 0,
<ide> };
<ide> }
<del>
<ide> affectedIDs[key][instanceID] = true;
<ide> applyUpdate(stats);
<ide> }
<ide>
<ide> flushHistory.forEach(flush => {
<ide> var {measurements, treeSnapshot, operations} = flush;
<del> var dirtyInstanceIDs = {};
<add> var isDefinitelyNotWastedByID = {};
<ide>
<add> // Find native components associated with an operation in this batch.
<add> // Mark all components in their parent tree as definitely not wasted.
<ide> operations.forEach(operation => {
<ide> var {instanceID} = operation;
<del>
<ide> var nextParentID = instanceID;
<ide> while (nextParentID) {
<del> dirtyInstanceIDs[nextParentID] = true;
<add> isDefinitelyNotWastedByID[nextParentID] = true;
<ide> nextParentID = treeSnapshot[nextParentID].parentID;
<ide> }
<ide> });
<ide>
<add> // Find composite components that rendered in this batch.
<add> // These are potential candidates for being wasted renders.
<ide> var renderedCompositeIDs = {};
<ide> measurements.forEach(measurement => {
<ide> var {instanceID, timerType} = measurement;
<ide> function getWasted(flushHistory = getFlushHistory()) {
<ide> if (timerType !== 'render') {
<ide> return;
<ide> }
<add>
<add> // If there was a DOM update below this component, or it has just been
<add> // mounted, its render() is not considered wasted.
<ide> var { updateCount } = treeSnapshot[instanceID];
<del> if (dirtyInstanceIDs[instanceID] || updateCount === 0) {
<add> if (isDefinitelyNotWastedByID[instanceID] || updateCount === 0) {
<ide> return;
<ide> }
<add>
<add> // We consider this render() wasted.
<ide> updateAggregatedStats(treeSnapshot, instanceID, stats => {
<ide> stats.renderCount++;
<ide> });
<add>
<ide> var nextParentID = instanceID;
<ide> while (nextParentID) {
<del> if (!renderedCompositeIDs[nextParentID]) {
<del> break;
<add> // Any parents rendered during this batch are considered wasted
<add> // unless we previously marked them as dirty.
<add> var isWasted =
<add> renderedCompositeIDs[nextParentID] &&
<add> !isDefinitelyNotWastedByID[nextParentID];
<add> if (isWasted) {
<add> updateAggregatedStats(treeSnapshot, nextParentID, stats => {
<add> stats.inclusiveRenderDuration += duration;
<add> });
<ide> }
<del> updateAggregatedStats(treeSnapshot, nextParentID, stats => {
<del> stats.inclusiveRenderDuration += duration;
<del> });
<ide> nextParentID = treeSnapshot[nextParentID].parentID;
<ide> }
<ide> });
<ide> function getWasted(flushHistory = getFlushHistory()) {
<ide> ...aggregatedStats[key],
<ide> instanceCount: Object.keys(affectedIDs[key]).length,
<ide> }))
<del> .sort((a, b) => b.inclusiveRenderDuration - a.inclusiveRenderDuration);
<add> .sort((a, b) =>
<add> b.inclusiveRenderDuration - a.inclusiveRenderDuration
<add> );
<ide> }
<ide>
<ide> function getOperations(flushHistory = getFlushHistory()) {
<ide><path>src/isomorphic/__tests__/ReactPerf-test.js
<add>/**
<add> * Copyright 2013-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @emails react-core
<add> */
<add>
<add>'use strict';
<add>
<add>describe('ReactPerf', function() {
<add> var React;
<add> var ReactDOM;
<add> var ReactPerf;
<add> var ReactTestUtils;
<add>
<add> var App;
<add> var Box;
<add> var Div;
<add>
<add> beforeEach(function() {
<add> var now = 0;
<add> jest.setMock('fbjs/lib/performanceNow', function() {
<add> return now++;
<add> });
<add>
<add> if (typeof console.table !== 'function') {
<add> console.table = () => {};
<add> console.table.isFake = true;
<add> }
<add>
<add> React = require('React');
<add> ReactDOM = require('ReactDOM');
<add> ReactPerf = require('ReactPerf');
<add> ReactTestUtils = require('ReactTestUtils');
<add>
<add> App = React.createClass({
<add> render: function() {
<add> return <div><Box /><Box flip={this.props.flipSecond} /></div>;
<add> },
<add> });
<add>
<add> Box = React.createClass({
<add> render: function() {
<add> return <div key={!!this.props.flip}><input /></div>;
<add> },
<add> });
<add>
<add> // ReactPerf only measures composites, so we put everything in one.
<add> Div = React.createClass({
<add> render: function() {
<add> return <div {...this.props} />;
<add> },
<add> });
<add> });
<add>
<add> afterEach(function() {
<add> if (console.table.isFake) {
<add> delete console.table;
<add> }
<add> });
<add>
<add> function measure(fn) {
<add> ReactPerf.start();
<add> fn();
<add> ReactPerf.stop();
<add> return ReactPerf.getLastMeasurements();
<add> }
<add>
<add> it('should count no-op update as waste', function() {
<add> var container = document.createElement('div');
<add> ReactDOM.render(<App />, container);
<add> var measurements = measure(() => {
<add> ReactDOM.render(<App />, container);
<add> });
<add>
<add> var summary = ReactPerf.getWasted(measurements);
<add> expect(summary).toEqual([{
<add> key: 'App',
<add> instanceCount: 1,
<add> inclusiveRenderDuration: 3,
<add> renderCount: 1,
<add> }, {
<add> key: 'App > Box',
<add> instanceCount: 2,
<add> inclusiveRenderDuration: 2,
<add> renderCount: 2,
<add> }]);
<add> });
<add>
<add> it('should count no-op update in child as waste', function() {
<add> var container = document.createElement('div');
<add> ReactDOM.render(<App />, container);
<add>
<add> // Here, we add a Box -- two of the <Box /> updates are wasted time (but the
<add> // addition of the third is not)
<add> var measurements = measure(() => {
<add> ReactDOM.render(<App flipSecond={true} />, container);
<add> });
<add>
<add> var summary = ReactPerf.getWasted(measurements);
<add> expect(summary).toEqual([{
<add> key: 'App > Box',
<add> instanceCount: 1,
<add> inclusiveRenderDuration: 1,
<add> renderCount: 1,
<add> }]);
<add> });
<add>
<add> function expectNoWaste(fn) {
<add> var measurements = measure(fn);
<add> var summary = ReactPerf.getWasted(measurements);
<add> expect(summary).toEqual([]);
<add> }
<add>
<add> it('should not count initial render as waste', function() {
<add> expectNoWaste(() => {
<add> ReactTestUtils.renderIntoDocument(<App />);
<add> });
<add> });
<add>
<add> it('should not count unmount as waste', function() {
<add> var container = document.createElement('div');
<add> ReactDOM.render(<Div>hello</Div>, container);
<add> expectNoWaste(() => {
<add> ReactDOM.unmountComponentAtNode(container);
<add> });
<add> });
<add>
<add> it('should not count content update as waste', function() {
<add> var container = document.createElement('div');
<add> ReactDOM.render(<Div>hello</Div>, container);
<add> expectNoWaste(() => {
<add> ReactDOM.render(<Div>hello world</Div>, container);
<add> });
<add> });
<add>
<add> it('should not count child addition as waste', function() {
<add> var container = document.createElement('div');
<add> ReactDOM.render(<Div><span /></Div>, container);
<add> expectNoWaste(() => {
<add> ReactDOM.render(<Div><span /><span /></Div>, container);
<add> });
<add> });
<add>
<add> it('should not count child removal as waste', function() {
<add> var container = document.createElement('div');
<add> ReactDOM.render(<Div><span /><span /></Div>, container);
<add> expectNoWaste(() => {
<add> ReactDOM.render(<Div><span /></Div>, container);
<add> });
<add> });
<add>
<add> it('should not count property update as waste', function() {
<add> var container = document.createElement('div');
<add> ReactDOM.render(<Div className="yellow">hey</Div>, container);
<add> expectNoWaste(() => {
<add> ReactDOM.render(<Div className="blue">hey</Div>, container);
<add> });
<add> });
<add>
<add> it('should not count style update as waste', function() {
<add> var container = document.createElement('div');
<add> ReactDOM.render(<Div style={{color: 'yellow'}}>hey</Div>, container);
<add> expectNoWaste(() => {
<add> ReactDOM.render(<Div style={{color: 'blue'}}>hey</Div>, container);
<add> });
<add> });
<add>
<add> it('should not count property removal as waste', function() {
<add> var container = document.createElement('div');
<add> ReactDOM.render(<Div className="yellow">hey</Div>, container);
<add> expectNoWaste(() => {
<add> ReactDOM.render(<Div>hey</Div>, container);
<add> });
<add> });
<add>
<add> it('should not count raw HTML update as waste', function() {
<add> var container = document.createElement('div');
<add> ReactDOM.render(
<add> <Div dangerouslySetInnerHTML={{__html: 'me'}} />,
<add> container
<add> );
<add> expectNoWaste(() => {
<add> ReactDOM.render(
<add> <Div dangerouslySetInnerHTML={{__html: 'you'}} />,
<add> container
<add> );
<add> });
<add> });
<add>
<add> it('should not count child reordering as waste', function() {
<add> var container = document.createElement('div');
<add> ReactDOM.render(<Div><div key="A" /><div key="B" /></Div>, container);
<add> expectNoWaste(() => {
<add> ReactDOM.render(<Div><div key="B" /><div key="A" /></Div>, container);
<add> });
<add> });
<add>
<add> it('should not count text update as waste', function() {
<add> var container = document.createElement('div');
<add> ReactDOM.render(<Div>{'hello'}{'world'}</Div>, container);
<add> expectNoWaste(() => {
<add> ReactDOM.render(<Div>{'hello'}{'friend'}</Div>, container);
<add> });
<add> });
<add>
<add> it('warns once when using getMeasurementsSummaryMap', function() {
<add> var measurements = measure(() => {});
<add> spyOn(console, 'error');
<add> ReactPerf.getMeasurementsSummaryMap(measurements);
<add> expect(console.error.calls.length).toBe(1);
<add> expect(console.error.argsForCall[0][0]).toContain(
<add> '`ReactPerf.getMeasurementsSummaryMap(...)` is deprecated. Use ' +
<add> '`ReactPerf.getWasted(...)` instead.'
<add> );
<add>
<add> ReactPerf.getMeasurementsSummaryMap(measurements);
<add> expect(console.error.calls.length).toBe(1);
<add> });
<add>
<add> it('warns once when using printDOM', function() {
<add> var measurements = measure(() => {});
<add> spyOn(console, 'error');
<add> ReactPerf.printDOM(measurements);
<add> expect(console.error.calls.length).toBe(1);
<add> expect(console.error.argsForCall[0][0]).toContain(
<add> '`ReactPerf.printDOM(...)` is deprecated. Use ' +
<add> '`ReactPerf.printOperations(...)` instead.'
<add> );
<add>
<add> ReactPerf.printDOM(measurements);
<add> expect(console.error.calls.length).toBe(1);
<add> });
<add>}); | 2 |
Javascript | Javascript | remove a leftover console.log | 64c4bfd566c3047c05656cf60c6f67cdda6051a5 | <ide><path>controllers/courseware.js
<ide> var _ = require('lodash'),
<ide> */
<ide>
<ide> exports.showAllCoursewares = function(req, res) {
<del> console.log('i made it!');
<del> var completedCoursewares = req.user.completedCoursewares.map(function(elem) {
<add> var completedCoursewares = req.user.completedCoursewares.map(function(elem) {
<ide> return elem._id;
<ide> });
<ide> | 1 |
Python | Python | add head masking and pruning to openai gpt | f12007e4216e2bdb278b40c731eb62626181cd28 | <ide><path>pytorch_pretrained_bert/modeling_openai.py
<ide>
<ide> from .file_utils import cached_path, CONFIG_NAME, WEIGHTS_NAME
<ide> from .modeling import BertLayerNorm as LayerNorm
<add>from .modeling_gpt2 import prune_conv1d_layer
<ide>
<ide> logger = logging.getLogger(__name__)
<ide>
<ide> def forward(self, x):
<ide>
<ide>
<ide> class Attention(nn.Module):
<del> def __init__(self, nx, n_ctx, config, scale=False, output_attentions=False):
<add> def __init__(self, nx, n_ctx, config, scale=False, output_attentions=False, keep_multihead_output=False):
<ide> super(Attention, self).__init__()
<ide> n_state = nx # in Attention: n_state=768 (nx=n_embd)
<ide> # [switch nx => n_state from Block to Attention to keep identical to TF implem]
<ide> def __init__(self, nx, n_ctx, config, scale=False, output_attentions=False):
<ide> self.n_head = config.n_head
<ide> self.split_size = n_state
<ide> self.scale = scale
<add>
<ide> self.output_attentions = output_attentions
<add> self.keep_multihead_output = keep_multihead_output
<add> self.multihead_output = None
<add>
<ide> self.c_attn = Conv1D(n_state * 3, 1, nx)
<ide> self.c_proj = Conv1D(n_state, 1, nx)
<ide> self.attn_dropout = nn.Dropout(config.attn_pdrop)
<ide> self.resid_dropout = nn.Dropout(config.resid_pdrop)
<ide>
<del> def _attn(self, q, k, v):
<add> def prune_heads(self, heads):
<add> mask = torch.ones(self.n_head, self.split_size // self.n_head)
<add> for head in heads:
<add> mask[head] = 0
<add> mask = mask.view(-1).contiguous().eq(1)
<add> index = torch.arange(len(mask))[mask].long()
<add> index_attn = torch.cat([index, index + self.split_size, index + (2*self.split_size)])
<add> # Prune conv1d layers
<add> self.c_attn = prune_conv1d_layer(self.c_attn, index_attn, dim=1)
<add> self.c_proj = prune_conv1d_layer(self.c_proj, index, dim=0)
<add> # Update hyper params
<add> self.split_size = (self.split_size // self.n_head) * (self.n_head - len(heads))
<add> self.n_head = self.n_head - len(heads)
<add>
<add> def _attn(self, q, k, v, head_mask=None):
<ide> w = torch.matmul(q, k)
<ide> if self.scale:
<ide> w = w / math.sqrt(v.size(-1))
<ide> def _attn(self, q, k, v):
<ide>
<ide> w = nn.Softmax(dim=-1)(w)
<ide> w = self.attn_dropout(w)
<add>
<add> # Mask heads if we want to
<add> if head_mask is not None:
<add> w = w * head_mask
<add>
<ide> if self.output_attentions:
<ide> return w, torch.matmul(w, v)
<ide> return torch.matmul(w, v)
<ide> def split_heads(self, x, k=False):
<ide> else:
<ide> return x.permute(0, 2, 1, 3)
<ide>
<del> def forward(self, x):
<add> def forward(self, x, head_mask=None):
<ide> x = self.c_attn(x)
<ide> query, key, value = x.split(self.split_size, dim=2)
<ide> query = self.split_heads(query)
<ide> key = self.split_heads(key, k=True)
<ide> value = self.split_heads(value)
<del> a = self._attn(query, key, value)
<add>
<add> a = self._attn(query, key, value, head_mask)
<add> if self.keep_multihead_output:
<add> self.multihead_output = a
<add> self.multihead_output.retain_grad()
<add>
<ide> if self.output_attentions:
<ide> attentions, a = a
<ide> a = self.merge_heads(a)
<ide> def forward(self, x):
<ide>
<ide>
<ide> class Block(nn.Module):
<del> def __init__(self, n_ctx, config, scale=False, output_attentions=False):
<add> def __init__(self, n_ctx, config, scale=False, output_attentions=False, keep_multihead_output=False):
<ide> super(Block, self).__init__()
<ide> nx = config.n_embd
<ide> self.output_attentions = output_attentions
<del> self.attn = Attention(nx, n_ctx, config, scale, output_attentions)
<add> self.attn = Attention(nx, n_ctx, config, scale, output_attentions, keep_multihead_output)
<ide> self.ln_1 = LayerNorm(nx, eps=config.layer_norm_epsilon)
<ide> self.mlp = MLP(4 * nx, config)
<ide> self.ln_2 = LayerNorm(nx, eps=config.layer_norm_epsilon)
<ide>
<del> def forward(self, x):
<del> a = self.attn(x)
<add> def forward(self, x, head_mask=None):
<add> a = self.attn(x, head_mask=head_mask)
<ide> if self.output_attentions:
<ide> attentions, a = a
<ide> n = self.ln_1(x + a)
<ide> class OpenAIGPTModel(OpenAIGPTPreTrainedModel):
<ide> ```
<ide> """
<ide>
<del> def __init__(self, config, output_attentions=False):
<add> def __init__(self, config, output_attentions=False, keep_multihead_output=False):
<ide> super(OpenAIGPTModel, self).__init__(config)
<ide> self.output_attentions = output_attentions
<ide> self.tokens_embed = nn.Embedding(config.total_tokens_embeddings, config.n_embd)
<ide> self.positions_embed = nn.Embedding(config.n_positions, config.n_embd)
<ide> self.drop = nn.Dropout(config.embd_pdrop)
<del> block = Block(config.n_ctx, config, scale=True, output_attentions=output_attentions)
<add> block = Block(config.n_ctx, config, scale=True, output_attentions=output_attentions,
<add> keep_multihead_output=keep_multihead_output)
<ide> self.h = nn.ModuleList([copy.deepcopy(block) for _ in range(config.n_layer)])
<ide>
<ide> self.apply(self.init_weights)
<ide> def set_num_special_tokens(self, num_special_tokens):
<ide> # Copy word embeddings from the previous weights
<ide> self.tokens_embed.weight.data[:self.config.vocab_size, :] = old_embed.weight.data[:self.config.vocab_size, :]
<ide>
<del> def forward(self, input_ids, position_ids=None, token_type_ids=None):
<add> def prune_heads(self, heads_to_prune):
<add> """ Prunes heads of the model.
<add> heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
<add> """
<add> for layer, heads in heads_to_prune.items():
<add> self.h[layer].attn.prune_heads(heads)
<add>
<add> def get_multihead_outputs(self):
<add> """ Gather all multi-head outputs.
<add> Return: list (layers) of multihead module outputs with gradients
<add> """
<add> return [h.attn.multihead_output for h in self.h]
<add>
<add> def forward(self, input_ids, position_ids=None, token_type_ids=None, head_mask=None):
<ide> if position_ids is None:
<ide> # This was used when we had a single embedding matrice from position and token embeddings
<ide> # start = self.config.vocab_size + self.config.n_special
<ide> def forward(self, input_ids, position_ids=None, token_type_ids=None):
<ide> position_ids = torch.arange(input_ids.size(-1), dtype=torch.long, device=input_ids.device)
<ide> position_ids = position_ids.unsqueeze(0).expand_as(input_ids)
<ide>
<add> # Prepare head mask if needed
<add> # 1.0 in head_mask indicate we mask the head
<add> # attention_probs has shape bsz x n_heads x N x N
<add> if head_mask is not None:
<add> if head_mask.dim() == 1:
<add> head_mask = head_mask.unsqueeze(0).unsqueeze(-1).unsqueeze(-1)
<add> elif head_mask.dim() == 2:
<add> head_mask = head_mask.unsqueeze(-1).unsqueeze(-1) # We can specify head_mask for each instance in batch
<add> head_mask = head_mask.to(dtype=next(self.parameters()).dtype) # switch to fload if need + fp16 compatibility
<add> head_mask = (1.0 - head_mask)
<add>
<ide> input_shape = input_ids.size()
<ide> input_ids = input_ids.view(-1, input_ids.size(-1))
<ide> position_ids = position_ids.view(-1, position_ids.size(-1))
<ide> def forward(self, input_ids, position_ids=None, token_type_ids=None):
<ide>
<ide> all_attentions = []
<ide> for block in self.h:
<add> outputs = block(hidden_states, head_mask)
<ide> if self.output_attentions:
<del> attentions, hidden_states = block(hidden_states)
<add> attentions, hidden_states = outputs
<ide> all_attentions.append(attentions)
<ide> else:
<del> hidden_states = block(hidden_states)
<add> hidden_states = outputs
<ide> output_shape = input_shape + (hidden_states.size(-1),)
<ide> if self.output_attentions:
<ide> return all_attentions, hidden_states.view(*output_shape)
<ide> class OpenAIGPTLMHeadModel(OpenAIGPTPreTrainedModel):
<ide> ```
<ide> """
<ide>
<del> def __init__(self, config, output_attentions=False):
<add> def __init__(self, config, output_attentions=False, keep_multihead_output=False):
<ide> super(OpenAIGPTLMHeadModel, self).__init__(config)
<del> self.transformer = OpenAIGPTModel(config, output_attentions=output_attentions)
<add> self.transformer = OpenAIGPTModel(config, output_attentions=output_attentions,
<add> keep_multihead_output=keep_multihead_output)
<ide> self.lm_head = OpenAIGPTLMHead(self.transformer.tokens_embed.weight, config)
<ide> self.apply(self.init_weights)
<ide>
<ide> def set_num_special_tokens(self, num_special_tokens, predict_special_tokens=True
<ide> self.transformer.set_num_special_tokens(num_special_tokens)
<ide> self.lm_head.set_embeddings_weights(self.transformer.tokens_embed.weight, predict_special_tokens=predict_special_tokens)
<ide>
<del> def forward(self, input_ids, position_ids=None, token_type_ids=None, lm_labels=None):
<del> hidden_states = self.transformer(input_ids, position_ids, token_type_ids)
<add> def forward(self, input_ids, position_ids=None, token_type_ids=None, lm_labels=None, head_mask=None):
<add> hidden_states = self.transformer(input_ids, position_ids, token_type_ids, head_mask)
<ide> if self.transformer.output_attentions:
<ide> all_attentions, hidden_states = hidden_states
<ide> lm_logits = self.lm_head(hidden_states)
<ide> class OpenAIGPTDoubleHeadsModel(OpenAIGPTPreTrainedModel):
<ide> ```
<ide> """
<ide>
<del> def __init__(self, config, output_attentions=False):
<add> def __init__(self, config, output_attentions=False, keep_multihead_output=False):
<ide> super(OpenAIGPTDoubleHeadsModel, self).__init__(config)
<del> self.transformer = OpenAIGPTModel(config, output_attentions=output_attentions)
<add> self.transformer = OpenAIGPTModel(config, output_attentions=output_attentions,
<add> keep_multihead_output=keep_multihead_output)
<ide> self.lm_head = OpenAIGPTLMHead(self.transformer.tokens_embed.weight, config)
<ide> self.multiple_choice_head = OpenAIGPTMultipleChoiceHead(config)
<ide> self.apply(self.init_weights)
<ide> def set_num_special_tokens(self, num_special_tokens, predict_special_tokens=True
<ide> self.transformer.set_num_special_tokens(num_special_tokens)
<ide> self.lm_head.set_embeddings_weights(self.transformer.tokens_embed.weight, predict_special_tokens=predict_special_tokens)
<ide>
<del> def forward(self, input_ids, mc_token_ids, lm_labels=None, mc_labels=None, token_type_ids=None, position_ids=None):
<del> hidden_states = self.transformer(input_ids, position_ids, token_type_ids)
<add> def forward(self, input_ids, mc_token_ids, lm_labels=None, mc_labels=None, token_type_ids=None,
<add> position_ids=None, head_mask=None):
<add> hidden_states = self.transformer(input_ids, position_ids, token_type_ids, head_mask)
<ide> if self.transformer.output_attentions:
<ide> all_attentions, hidden_states = hidden_states
<ide> lm_logits = self.lm_head(hidden_states)
<ide><path>tests/modeling_openai_test.py
<ide> def check_openai_double_heads_loss_output(self, result):
<ide> [list(l.size()) for l in result["loss"]],
<ide> [[], []])
<ide>
<add> def create_and_check_openai_for_headmasking(self, config, input_ids, token_type_ids, position_ids,
<add> mc_labels, lm_labels, mc_token_ids):
<add> for model_class in (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel):
<add> model = model_class(config=config, keep_multihead_output=True)
<add> model.eval()
<add> head_mask = torch.ones(self.n_head).to(input_ids.device)
<add> head_mask[0] = 0.0
<add> head_mask[-1] = 0.0 # Mask all but the first and last heads
<add> if isinstance(model, OpenAIGPTDoubleHeadsModel):
<add> output = model(input_ids, mc_token_ids, head_mask=head_mask)
<add> else:
<add> output = model(input_ids, head_mask=head_mask)
<add>
<add> output = sum(t.sum() for t in output[:-1])
<add> output = output.sum()
<add> output.backward()
<add> multihead_outputs = (model if isinstance(model, OpenAIGPTModel) else model.transformer).get_multihead_outputs()
<add>
<add> self.parent.assertEqual(len(multihead_outputs), self.n_layer)
<add> self.parent.assertListEqual(
<add> list(multihead_outputs[0].size()),
<add> [self.batch_size * self.n_choices, self.n_head,
<add> self.seq_length, self.n_embd // self.n_head])
<add> self.parent.assertEqual(
<add> len(multihead_outputs[0][:, 1:(self.n_head-1), :, :].nonzero()),
<add> 0)
<add> self.parent.assertEqual(
<add> len(multihead_outputs[0][:, 0, :, :].nonzero()),
<add> self.batch_size * self.n_choices * self.seq_length * self.n_embd // self.n_head)
<add> self.parent.assertEqual(
<add> len(multihead_outputs[0][:, self.n_head-1, :, :].nonzero()),
<add> self.batch_size * self.n_choices * self.seq_length * self.n_embd // self.n_head)
<add>
<add> def create_and_check_openai_for_head_pruning(self, config, input_ids, token_type_ids, position_ids,
<add> mc_labels, lm_labels, mc_token_ids):
<add> for model_class in (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel):
<add> model = model_class(config=config, keep_multihead_output=True)
<add> model.eval()
<add> transformer = model if isinstance(model, OpenAIGPTModel) else model.transformer
<add> heads_to_prune = {0: list(range(1, self.n_head)),
<add> -1: [0]}
<add> transformer.prune_heads(heads_to_prune)
<add> if isinstance(model, OpenAIGPTDoubleHeadsModel):
<add> output = model(input_ids, mc_token_ids)
<add> else:
<add> output = model(input_ids)
<add>
<add> output = sum(t.sum() for t in output[:-1])
<add> output = output.sum()
<add> output.backward()
<add> multihead_outputs = transformer.get_multihead_outputs()
<add>
<add> self.parent.assertEqual(len(multihead_outputs), self.n_layer)
<add> self.parent.assertListEqual(
<add> list(multihead_outputs[0].size()),
<add> [self.batch_size * self.n_choices, 1,
<add> self.seq_length, self.n_embd // self.n_head])
<add> self.parent.assertListEqual(
<add> list(multihead_outputs[1].size()),
<add> [self.batch_size * self.n_choices, self.n_head,
<add> self.seq_length, self.n_embd // self.n_head])
<add> self.parent.assertListEqual(
<add> list(multihead_outputs[-1].size()),
<add> [self.batch_size * self.n_choices, self.n_head-1,
<add> self.seq_length, self.n_embd // self.n_head])
<add>
<add>
<ide> def test_default(self):
<ide> self.run_tester(OpenAIGPTModelTest.OpenAIGPTModelTester(self))
<ide>
<ide> def run_tester(self, tester):
<ide> tester.check_openai_double_heads_output(output_result)
<ide> tester.check_openai_double_heads_loss_output(output_result)
<ide>
<add> tester.create_and_check_openai_for_headmasking(*config_and_inputs)
<add> tester.create_and_check_openai_for_head_pruning(*config_and_inputs)
<add>
<ide> @classmethod
<ide> def ids_tensor(cls, shape, vocab_size, rng=None, name=None):
<ide> """Creates a random int32 tensor of the shape within the vocab size.""" | 2 |
Ruby | Ruby | fix typo in action_view/template.rb [ci skip] | 1d40743af7a98c22faec11af8d1a9f7fe322e67a | <ide><path>actionview/lib/action_view/template.rb
<ide> def initialize(source, identifier, handler, details)
<ide> end
<ide>
<ide> # Returns whether the underlying handler supports streaming. If so,
<del> # a streaming buffer *may* be passed when it start rendering.
<add> # a streaming buffer *may* be passed when it starts rendering.
<ide> def supports_streaming?
<ide> handler.respond_to?(:supports_streaming?) && handler.supports_streaming?
<ide> end | 1 |
Javascript | Javascript | add missing intry case | c0a79c02572579f92e6e4d2d702cf1eb013405f0 | <ide><path>lib/Compilation.js
<ide> class Compilation {
<ide> if (source !== sourceFromCache) {
<ide> this.cache.store(cacheName, usedHash, source, err => {
<ide> if (err) return errorAndCallback(err);
<add> inTry = false;
<ide> return callback();
<ide> });
<ide> } else { | 1 |
Python | Python | make benchmark script work in react 15 | cab835d3a0b4a128ddc3e612fc05e432df20204d | <ide><path>scripts/bench/measure.py
<ide> def _measure_ssr_ms(engine, react_path, bench_name, bench_path, measure_warm):
<ide> var START = now();
<ide> globalEval(reactCode);
<ide> var END = now();
<add> ReactDOMServer = React.__SECRET_DOM_SERVER_DO_NOT_USE_OR_YOU_WILL_BE_FIRED || React;
<ide> if (typeof React !== 'object') throw new Error('React not laoded');
<ide> report('factory_ms', END - START);
<ide>
<ide> def _measure_ssr_ms(engine, react_path, bench_name, bench_path, measure_warm):
<ide> throw new Error('benchmark not loaded');
<ide> }
<ide> var START = now();
<del> var html = React.renderToString(React.createElement(Benchmark));
<add> var html = ReactDOMServer.renderToString(React.createElement(Benchmark));
<ide> html.charCodeAt(0); // flatten ropes
<ide> var END = now();
<ide> report('ssr_' + ENV.bench_name + '_cold_ms', END - START);
<ide> def _measure_ssr_ms(engine, react_path, bench_name, bench_path, measure_warm):
<ide> var trials = ENV.measure_warm ? 40 : 0;
<ide>
<ide> for (var i = 0; i < warmup; i++) {
<del> React.renderToString(React.createElement(Benchmark));
<add> ReactDOMServer.renderToString(React.createElement(Benchmark));
<ide> }
<ide>
<ide> for (var i = 0; i < trials; i++) {
<ide> var START = now();
<del> var html = React.renderToString(React.createElement(Benchmark));
<add> var html = ReactDOMServer.renderToString(React.createElement(Benchmark));
<ide> html.charCodeAt(0); // flatten ropes
<ide> var END = now();
<ide> report('ssr_' + ENV.bench_name + '_warm_ms', END - START); | 1 |
Python | Python | fix linting errors | 325f52e7cdf4aff135ec68a71e4fa451fb888312 | <ide><path>libcloud/test/compute/test_dimensiondata.py
<ide> def test_ex_update_node(self):
<ide>
<ide> def test_ex_reconfigure_node(self):
<ide> node = self.driver.list_nodes()[0]
<del> result = self.driver.ex_reconfigure_node(node, 4, 4, 1,'HIGHPERFORMANCE')
<add> result = self.driver.ex_reconfigure_node(node, 4, 4, 1, 'HIGHPERFORMANCE')
<ide> self.assertTrue(result)
<del>
<add>
<ide>
<ide> class InvalidRequestError(Exception):
<ide> def __init__(self, tag):
<ide> def _caas_2_1_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_reconfigureServer(self
<ide> 'caas_2_1_8a8f6abc_2745_4d8a_9cbc_8dabe5a7d0e4_server_reconfigureServer.xml')
<ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
<ide>
<del>
<del>
<ide> if __name__ == '__main__':
<ide> sys.exit(unittest.main()) | 1 |
Go | Go | use dockercmd in integration-cli tests | 71868228c787f54501abec6556364d2ceaa4e645 | <ide><path>integration-cli/docker_cli_rename_test.go
<ide> package main
<ide>
<ide> import (
<del> "os/exec"
<ide> "strings"
<ide>
<ide> "github.com/docker/docker/pkg/stringid"
<ide> "github.com/go-check/check"
<ide> )
<ide>
<ide> func (s *DockerSuite) TestRenameStoppedContainer(c *check.C) {
<del> runCmd := exec.Command(dockerBinary, "run", "--name", "first_name", "-d", "busybox", "sh")
<del> out, _, err := runCommandWithOutput(runCmd)
<del> if err != nil {
<del> c.Fatalf(out, err)
<del> }
<add> out, _ := dockerCmd(c, "run", "--name", "first_name", "-d", "busybox", "sh")
<ide>
<ide> cleanedContainerID := strings.TrimSpace(out)
<del>
<del> runCmd = exec.Command(dockerBinary, "wait", cleanedContainerID)
<del> out, _, err = runCommandWithOutput(runCmd)
<del> if err != nil {
<del> c.Fatalf(out, err)
<del> }
<add> dockerCmd(c, "wait", cleanedContainerID)
<ide>
<ide> name, err := inspectField(cleanedContainerID, "Name")
<del>
<ide> newName := "new_name" + stringid.GenerateRandomID()
<del> runCmd = exec.Command(dockerBinary, "rename", "first_name", newName)
<del> out, _, err = runCommandWithOutput(runCmd)
<del> if err != nil {
<del> c.Fatalf(out, err)
<del> }
<add> dockerCmd(c, "rename", "first_name", newName)
<ide>
<ide> name, err = inspectField(cleanedContainerID, "Name")
<ide> if err != nil {
<ide> func (s *DockerSuite) TestRenameStoppedContainer(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRenameRunningContainer(c *check.C) {
<del> runCmd := exec.Command(dockerBinary, "run", "--name", "first_name", "-d", "busybox", "sh")
<del> out, _, err := runCommandWithOutput(runCmd)
<del> if err != nil {
<del> c.Fatalf(out, err)
<del> }
<add> out, _ := dockerCmd(c, "run", "--name", "first_name", "-d", "busybox", "sh")
<ide>
<ide> newName := "new_name" + stringid.GenerateRandomID()
<ide> cleanedContainerID := strings.TrimSpace(out)
<del> runCmd = exec.Command(dockerBinary, "rename", "first_name", newName)
<del> out, _, err = runCommandWithOutput(runCmd)
<del> if err != nil {
<del> c.Fatalf(out, err)
<del> }
<add> dockerCmd(c, "rename", "first_name", newName)
<ide>
<ide> name, err := inspectField(cleanedContainerID, "Name")
<ide> if err != nil {
<ide> func (s *DockerSuite) TestRenameRunningContainer(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRenameCheckNames(c *check.C) {
<del> runCmd := exec.Command(dockerBinary, "run", "--name", "first_name", "-d", "busybox", "sh")
<del> out, _, err := runCommandWithOutput(runCmd)
<del> if err != nil {
<del> c.Fatalf(out, err)
<del> }
<add> dockerCmd(c, "run", "--name", "first_name", "-d", "busybox", "sh")
<ide>
<ide> newName := "new_name" + stringid.GenerateRandomID()
<del> runCmd = exec.Command(dockerBinary, "rename", "first_name", newName)
<del> out, _, err = runCommandWithOutput(runCmd)
<del> if err != nil {
<del> c.Fatalf(out, err)
<del> }
<add> dockerCmd(c, "rename", "first_name", newName)
<ide>
<ide> name, err := inspectField(newName, "Name")
<ide> if err != nil {
<ide> func (s *DockerSuite) TestRenameCheckNames(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRenameInvalidName(c *check.C) {
<del> runCmd := exec.Command(dockerBinary, "run", "--name", "myname", "-d", "busybox", "top")
<del> if out, _, err := runCommandWithOutput(runCmd); err != nil {
<del> c.Fatalf(out, err)
<del> }
<add> dockerCmd(c, "run", "--name", "myname", "-d", "busybox", "top")
<ide>
<del> runCmd = exec.Command(dockerBinary, "rename", "myname", "new:invalid")
<del> if out, _, err := runCommandWithOutput(runCmd); err == nil || !strings.Contains(out, "Invalid container name") {
<add> if out, _, err := dockerCmdWithError(c, "rename", "myname", "new:invalid"); err == nil || !strings.Contains(out, "Invalid container name") {
<ide> c.Fatalf("Renaming container to invalid name should have failed: %s\n%v", out, err)
<ide> }
<ide>
<del> runCmd = exec.Command(dockerBinary, "ps", "-a")
<del> if out, _, err := runCommandWithOutput(runCmd); err != nil || !strings.Contains(out, "myname") {
<add> if out, _, err := dockerCmdWithError(c, "ps", "-a"); err != nil || !strings.Contains(out, "myname") {
<ide> c.Fatalf("Output of docker ps should have included 'myname': %s\n%v", out, err)
<ide> }
<ide> }
<ide><path>integration-cli/docker_cli_restart_test.go
<ide> package main
<ide>
<ide> import (
<del> "os/exec"
<ide> "strings"
<ide> "time"
<ide>
<ide> "github.com/go-check/check"
<ide> )
<ide>
<ide> func (s *DockerSuite) TestRestartStoppedContainer(c *check.C) {
<del>
<del> runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "echo", "foobar")
<del> out, _, err := runCommandWithOutput(runCmd)
<del> if err != nil {
<del> c.Fatal(out, err)
<del> }
<add> out, _ := dockerCmd(c, "run", "-d", "busybox", "echo", "foobar")
<ide>
<ide> cleanedContainerID := strings.TrimSpace(out)
<add> dockerCmd(c, "wait", cleanedContainerID)
<ide>
<del> runCmd = exec.Command(dockerBinary, "wait", cleanedContainerID)
<del> if out, _, err = runCommandWithOutput(runCmd); err != nil {
<del> c.Fatal(out, err)
<del> }
<del>
<del> runCmd = exec.Command(dockerBinary, "logs", cleanedContainerID)
<del> out, _, err = runCommandWithOutput(runCmd)
<del> if err != nil {
<del> c.Fatal(out, err)
<del> }
<del>
<add> out, _ = dockerCmd(c, "logs", cleanedContainerID)
<ide> if out != "foobar\n" {
<ide> c.Errorf("container should've printed 'foobar'")
<ide> }
<ide>
<del> runCmd = exec.Command(dockerBinary, "restart", cleanedContainerID)
<del> if out, _, err = runCommandWithOutput(runCmd); err != nil {
<del> c.Fatal(out, err)
<del> }
<del>
<del> runCmd = exec.Command(dockerBinary, "logs", cleanedContainerID)
<del> out, _, err = runCommandWithOutput(runCmd)
<del> if err != nil {
<del> c.Fatal(out, err)
<del> }
<add> dockerCmd(c, "restart", cleanedContainerID)
<ide>
<add> out, _ = dockerCmd(c, "logs", cleanedContainerID)
<ide> if out != "foobar\nfoobar\n" {
<ide> c.Errorf("container should've printed 'foobar' twice")
<ide> }
<del>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRestartRunningContainer(c *check.C) {
<del>
<del> runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "sh", "-c", "echo foobar && sleep 30 && echo 'should not print this'")
<del> out, _, err := runCommandWithOutput(runCmd)
<del> if err != nil {
<del> c.Fatal(out, err)
<del> }
<add> out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", "echo foobar && sleep 30 && echo 'should not print this'")
<ide>
<ide> cleanedContainerID := strings.TrimSpace(out)
<ide>
<ide> time.Sleep(1 * time.Second)
<ide>
<del> runCmd = exec.Command(dockerBinary, "logs", cleanedContainerID)
<del> out, _, err = runCommandWithOutput(runCmd)
<del> if err != nil {
<del> c.Fatal(out, err)
<del> }
<del>
<add> out, _ = dockerCmd(c, "logs", cleanedContainerID)
<ide> if out != "foobar\n" {
<ide> c.Errorf("container should've printed 'foobar'")
<ide> }
<ide>
<del> runCmd = exec.Command(dockerBinary, "restart", "-t", "1", cleanedContainerID)
<del> if out, _, err = runCommandWithOutput(runCmd); err != nil {
<del> c.Fatal(out, err)
<del> }
<add> dockerCmd(c, "restart", "-t", "1", cleanedContainerID)
<ide>
<del> runCmd = exec.Command(dockerBinary, "logs", cleanedContainerID)
<del> out, _, err = runCommandWithOutput(runCmd)
<del> if err != nil {
<del> c.Fatal(out, err)
<del> }
<add> out, _ = dockerCmd(c, "logs", cleanedContainerID)
<ide>
<ide> time.Sleep(1 * time.Second)
<ide>
<ide> if out != "foobar\nfoobar\n" {
<ide> c.Errorf("container should've printed 'foobar' twice")
<ide> }
<del>
<ide> }
<ide>
<ide> // Test that restarting a container with a volume does not create a new volume on restart. Regression test for #819.
<ide> func (s *DockerSuite) TestRestartWithVolumes(c *check.C) {
<del>
<del> runCmd := exec.Command(dockerBinary, "run", "-d", "-v", "/test", "busybox", "top")
<del> out, _, err := runCommandWithOutput(runCmd)
<del> if err != nil {
<del> c.Fatal(out, err)
<del> }
<add> out, _ := dockerCmd(c, "run", "-d", "-v", "/test", "busybox", "top")
<ide>
<ide> cleanedContainerID := strings.TrimSpace(out)
<del>
<del> runCmd = exec.Command(dockerBinary, "inspect", "--format", "{{ len .Volumes }}", cleanedContainerID)
<del> out, _, err = runCommandWithOutput(runCmd)
<del> if err != nil {
<del> c.Fatal(out, err)
<del> }
<add> out, _ = dockerCmd(c, "inspect", "--format", "{{ len .Volumes }}", cleanedContainerID)
<ide>
<ide> if out = strings.Trim(out, " \n\r"); out != "1" {
<ide> c.Errorf("expect 1 volume received %s", out)
<ide> func (s *DockerSuite) TestRestartWithVolumes(c *check.C) {
<ide> volumes, err := inspectField(cleanedContainerID, "Volumes")
<ide> c.Assert(err, check.IsNil)
<ide>
<del> runCmd = exec.Command(dockerBinary, "restart", cleanedContainerID)
<del> if out, _, err = runCommandWithOutput(runCmd); err != nil {
<del> c.Fatal(out, err)
<del> }
<del>
<del> runCmd = exec.Command(dockerBinary, "inspect", "--format", "{{ len .Volumes }}", cleanedContainerID)
<del> out, _, err = runCommandWithOutput(runCmd)
<del> if err != nil {
<del> c.Fatal(out, err)
<del> }
<add> dockerCmd(c, "restart", cleanedContainerID)
<ide>
<add> out, _ = dockerCmd(c, "inspect", "--format", "{{ len .Volumes }}", cleanedContainerID)
<ide> if out = strings.Trim(out, " \n\r"); out != "1" {
<ide> c.Errorf("expect 1 volume after restart received %s", out)
<ide> }
<ide> func (s *DockerSuite) TestRestartWithVolumes(c *check.C) {
<ide> if volumes != volumesAfterRestart {
<ide> c.Errorf("expected volume path: %s Actual path: %s", volumes, volumesAfterRestart)
<ide> }
<del>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRestartPolicyNO(c *check.C) {
<del>
<del> cmd := exec.Command(dockerBinary, "run", "-d", "--restart=no", "busybox", "false")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "-d", "--restart=no", "busybox", "false")
<ide>
<ide> id := strings.TrimSpace(string(out))
<ide> name, err := inspectField(id, "HostConfig.RestartPolicy.Name")
<ide> c.Assert(err, check.IsNil)
<ide> if name != "no" {
<ide> c.Fatalf("Container restart policy name is %s, expected %s", name, "no")
<ide> }
<del>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRestartPolicyAlways(c *check.C) {
<del>
<del> cmd := exec.Command(dockerBinary, "run", "-d", "--restart=always", "busybox", "false")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "-d", "--restart=always", "busybox", "false")
<ide>
<ide> id := strings.TrimSpace(string(out))
<ide> name, err := inspectField(id, "HostConfig.RestartPolicy.Name")
<ide> func (s *DockerSuite) TestRestartPolicyAlways(c *check.C) {
<ide> if MaximumRetryCount != "0" {
<ide> c.Fatalf("Container Maximum Retry Count is %s, expected %s", MaximumRetryCount, "0")
<ide> }
<del>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRestartPolicyOnFailure(c *check.C) {
<del>
<del> cmd := exec.Command(dockerBinary, "run", "-d", "--restart=on-failure:1", "busybox", "false")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:1", "busybox", "false")
<ide>
<ide> id := strings.TrimSpace(string(out))
<ide> name, err := inspectField(id, "HostConfig.RestartPolicy.Name")
<ide> func (s *DockerSuite) TestRestartPolicyOnFailure(c *check.C) {
<ide> // a good container with --restart=on-failure:3
<ide> // MaximumRetryCount!=0; RestartCount=0
<ide> func (s *DockerSuite) TestContainerRestartwithGoodContainer(c *check.C) {
<del> out, err := exec.Command(dockerBinary, "run", "-d", "--restart=on-failure:3", "busybox", "true").CombinedOutput()
<del> if err != nil {
<del> c.Fatal(string(out), err)
<del> }
<add> out, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "true")
<add>
<ide> id := strings.TrimSpace(string(out))
<ide> if err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false false", 5); err != nil {
<ide> c.Fatal(err)
<ide><path>integration-cli/docker_cli_rm_test.go
<ide> package main
<ide>
<ide> import (
<ide> "os"
<del> "os/exec"
<ide> "strings"
<ide>
<ide> "github.com/go-check/check"
<ide> import (
<ide> func (s *DockerSuite) TestRmContainerWithRemovedVolume(c *check.C) {
<ide> testRequires(c, SameHostDaemon)
<ide>
<del> cmd := exec.Command(dockerBinary, "run", "--name", "losemyvolumes", "-v", "/tmp/testing:/test", "busybox", "true")
<del> if _, err := runCommand(cmd); err != nil {
<del> c.Fatal(err)
<del> }
<add> dockerCmd(c, "run", "--name", "losemyvolumes", "-v", "/tmp/testing:/test", "busybox", "true")
<ide>
<ide> if err := os.Remove("/tmp/testing"); err != nil {
<ide> c.Fatal(err)
<ide> }
<ide>
<del> cmd = exec.Command(dockerBinary, "rm", "-v", "losemyvolumes")
<del> if out, _, err := runCommandWithOutput(cmd); err != nil {
<del> c.Fatal(out, err)
<del> }
<del>
<add> dockerCmd(c, "rm", "-v", "losemyvolumes")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRmContainerWithVolume(c *check.C) {
<add> dockerCmd(c, "run", "--name", "foo", "-v", "/srv", "busybox", "true")
<ide>
<del> cmd := exec.Command(dockerBinary, "run", "--name", "foo", "-v", "/srv", "busybox", "true")
<del> if _, err := runCommand(cmd); err != nil {
<del> c.Fatal(err)
<del> }
<del>
<del> cmd = exec.Command(dockerBinary, "rm", "-v", "foo")
<del> if _, err := runCommand(cmd); err != nil {
<del> c.Fatal(err)
<del> }
<del>
<add> dockerCmd(c, "rm", "-v", "foo")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRmRunningContainer(c *check.C) {
<del>
<ide> createRunningContainer(c, "foo")
<ide>
<del> // Test cannot remove running container
<del> cmd := exec.Command(dockerBinary, "rm", "foo")
<del> if _, err := runCommand(cmd); err == nil {
<add> if _, _, err := dockerCmdWithError(c, "rm", "foo"); err == nil {
<ide> c.Fatalf("Expected error, can't rm a running container")
<ide> }
<del>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRmForceRemoveRunningContainer(c *check.C) {
<del>
<ide> createRunningContainer(c, "foo")
<ide>
<ide> // Stop then remove with -s
<del> cmd := exec.Command(dockerBinary, "rm", "-f", "foo")
<del> if _, err := runCommand(cmd); err != nil {
<del> c.Fatal(err)
<del> }
<del>
<add> dockerCmd(c, "rm", "-f", "foo")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRmContainerOrphaning(c *check.C) {
<ide> func (s *DockerSuite) TestRmContainerOrphaning(c *check.C) {
<ide> c.Fatalf("Could not build image %s: %v", img, err)
<ide> }
<ide> // run container on first image
<del> if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", img)); err != nil {
<add> if out, _, err := dockerCmdWithError(c, "run", img); err != nil {
<ide> c.Fatalf("Could not run image %s: %v: %s", img, err, out)
<ide> }
<add>
<ide> // rebuild dockerfile with a small addition at the end
<ide> if _, err := buildImage(img, dockerfile2, true); err != nil {
<ide> c.Fatalf("Could not rebuild image %s: %v", img, err)
<ide> }
<ide> // try to remove the image, should error out.
<del> if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "rmi", img)); err == nil {
<add> if out, _, err := dockerCmdWithError(c, "rmi", img); err == nil {
<ide> c.Fatalf("Expected to error out removing the image, but succeeded: %s", out)
<ide> }
<add>
<ide> // check if we deleted the first image
<del> out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "images", "-q", "--no-trunc"))
<add> out, _, err := dockerCmdWithError(c, "images", "-q", "--no-trunc")
<ide> if err != nil {
<ide> c.Fatalf("%v: %s", err, out)
<ide> }
<ide> if !strings.Contains(out, img1) {
<ide> c.Fatalf("Orphaned container (could not find %q in docker images): %s", img1, out)
<ide> }
<del>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRmInvalidContainer(c *check.C) {
<del> if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "rm", "unknown")); err == nil {
<add> if out, _, err := dockerCmdWithError(c, "rm", "unknown"); err == nil {
<ide> c.Fatal("Expected error on rm unknown container, got none")
<ide> } else if !strings.Contains(out, "failed to remove containers") {
<ide> c.Fatalf("Expected output to contain 'failed to remove containers', got %q", out)
<ide> }
<del>
<ide> }
<ide>
<ide> func createRunningContainer(c *check.C, name string) {
<del> cmd := exec.Command(dockerBinary, "run", "-dt", "--name", name, "busybox", "top")
<del> if _, err := runCommand(cmd); err != nil {
<del> c.Fatal(err)
<del> }
<add> dockerCmd(c, "run", "-dt", "--name", name, "busybox", "top")
<ide> }
<ide><path>integration-cli/docker_cli_rmi_test.go
<ide> func (s *DockerSuite) TestRmiWithContainerFails(c *check.C) {
<ide> errSubstr := "is using it"
<ide>
<ide> // create a container
<del> runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "true")
<del> out, _, err := runCommandWithOutput(runCmd)
<add> out, _, err := dockerCmdWithError(c, "run", "-d", "busybox", "true")
<ide> if err != nil {
<ide> c.Fatalf("failed to create a container: %s, %v", out, err)
<ide> }
<ide>
<ide> cleanedContainerID := strings.TrimSpace(out)
<ide>
<ide> // try to delete the image
<del> runCmd = exec.Command(dockerBinary, "rmi", "busybox")
<del> out, _, err = runCommandWithOutput(runCmd)
<add> out, _, err = dockerCmdWithError(c, "rmi", "busybox")
<ide> if err == nil {
<ide> c.Fatalf("Container %q is using image, should not be able to rmi: %q", cleanedContainerID, out)
<ide> }
<ide> func (s *DockerSuite) TestRmiTag(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRmiImgIDMultipleTag(c *check.C) {
<del> runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir '/busybox-one'")
<del> out, _, err := runCommandWithOutput(runCmd)
<add> out, _, err := dockerCmdWithError(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir '/busybox-one'")
<ide> if err != nil {
<ide> c.Fatalf("failed to create a container:%s, %v", out, err)
<ide> }
<add>
<ide> containerID := strings.TrimSpace(out)
<del> runCmd = exec.Command(dockerBinary, "commit", containerID, "busybox-one")
<del> out, _, err = runCommandWithOutput(runCmd)
<add> out, _, err = dockerCmdWithError(c, "commit", containerID, "busybox-one")
<ide> if err != nil {
<ide> c.Fatalf("failed to commit a new busybox-one:%s, %v", out, err)
<ide> }
<ide> func (s *DockerSuite) TestRmiImgIDMultipleTag(c *check.C) {
<ide> c.Assert(err, check.IsNil)
<ide>
<ide> // run a container with the image
<del> out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "busybox-one", "top"))
<add> out, _, err = dockerCmdWithError(c, "run", "-d", "busybox-one", "top")
<ide> if err != nil {
<ide> c.Fatalf("failed to create a container:%s, %v", out, err)
<ide> }
<add>
<ide> containerID = strings.TrimSpace(out)
<ide>
<ide> // first checkout without force it fails
<del> out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "rmi", imgID))
<add> out, _, err = dockerCmdWithError(c, "rmi", imgID)
<ide> expected := fmt.Sprintf("Conflict, cannot delete %s because the running container %s is using it, stop it and use -f to force", imgID[:12], containerID[:12])
<ide> if err == nil || !strings.Contains(out, expected) {
<ide> c.Fatalf("rmi tagged in multiple repos should have failed without force: %s, %v, expected: %s", out, err, expected)
<ide> func (s *DockerSuite) TestRmiImgIDMultipleTag(c *check.C) {
<ide> if strings.Contains(imagesAfter, imgID[:12]) {
<ide> c.Fatalf("rmi -f %s failed, image still exists: %q\n\n", imgID, imagesAfter)
<ide> }
<del>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRmiImgIDForce(c *check.C) {
<del> runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir '/busybox-test'")
<del> out, _, err := runCommandWithOutput(runCmd)
<add> out, _, err := dockerCmdWithError(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir '/busybox-test'")
<ide> if err != nil {
<ide> c.Fatalf("failed to create a container:%s, %v", out, err)
<ide> }
<add>
<ide> containerID := strings.TrimSpace(out)
<del> runCmd = exec.Command(dockerBinary, "commit", containerID, "busybox-test")
<del> out, _, err = runCommandWithOutput(runCmd)
<add> out, _, err = dockerCmdWithError(c, "commit", containerID, "busybox-test")
<ide> if err != nil {
<ide> c.Fatalf("failed to commit a new busybox-test:%s, %v", out, err)
<ide> }
<ide> func (s *DockerSuite) TestRmiImgIDForce(c *check.C) {
<ide> c.Assert(err, check.IsNil)
<ide>
<ide> // first checkout without force it fails
<del> runCmd = exec.Command(dockerBinary, "rmi", imgID)
<del> out, _, err = runCommandWithOutput(runCmd)
<add> out, _, err = dockerCmdWithError(c, "rmi", imgID)
<ide> if err == nil || !strings.Contains(out, fmt.Sprintf("Conflict, cannot delete image %s because it is tagged in multiple repositories, use -f to force", imgID)) {
<ide> c.Fatalf("rmi tagged in multiple repos should have failed without force:%s, %v", out, err)
<ide> }
<ide> func (s *DockerSuite) TestRmiImgIDForce(c *check.C) {
<ide> if strings.Contains(imagesAfter, imgID[:12]) {
<ide> c.Fatalf("rmi -f %s failed, image still exists: %q\n\n", imgID, imagesAfter)
<ide> }
<del>
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRmiTagWithExistingContainers(c *check.C) {
<ide> container := "test-delete-tag"
<ide> newtag := "busybox:newtag"
<ide> bb := "busybox:latest"
<del> if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "tag", bb, newtag)); err != nil {
<add> if out, _, err := dockerCmdWithError(c, "tag", bb, newtag); err != nil {
<ide> c.Fatalf("Could not tag busybox: %v: %s", err, out)
<ide> }
<del> if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--name", container, bb, "/bin/true")); err != nil {
<add> if out, _, err := dockerCmdWithError(c, "run", "--name", container, bb, "/bin/true"); err != nil {
<ide> c.Fatalf("Could not run busybox: %v: %s", err, out)
<ide> }
<del> out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "rmi", newtag))
<add> out, _, err := dockerCmdWithError(c, "rmi", newtag)
<ide> if err != nil {
<ide> c.Fatalf("Could not remove tag %s: %v: %s", newtag, err, out)
<ide> }
<ide> if d := strings.Count(out, "Untagged: "); d != 1 {
<ide> c.Fatalf("Expected 1 untagged entry got %d: %q", d, out)
<ide> }
<del>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRmiForceWithExistingContainers(c *check.C) {
<del>
<ide> image := "busybox-clone"
<ide>
<ide> cmd := exec.Command(dockerBinary, "build", "--no-cache", "-t", image, "-")
<ide> MAINTAINER foo`)
<ide> c.Fatalf("Could not build %s: %s, %v", image, out, err)
<ide> }
<ide>
<del> if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--name", "test-force-rmi", image, "/bin/true")); err != nil {
<add> if out, _, err := dockerCmdWithError(c, "run", "--name", "test-force-rmi", image, "/bin/true"); err != nil {
<ide> c.Fatalf("Could not run container: %s, %v", out, err)
<ide> }
<ide>
<del> out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "rmi", "-f", image))
<del> if err != nil {
<add> if out, _, err := dockerCmdWithError(c, "rmi", "-f", image); err != nil {
<ide> c.Fatalf("Could not remove image %s: %s, %v", image, out, err)
<ide> }
<del>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRmiWithMultipleRepositories(c *check.C) {
<ide> newRepo := "127.0.0.1:5000/busybox"
<ide> oldRepo := "busybox"
<ide> newTag := "busybox:test"
<del> cmd := exec.Command(dockerBinary, "tag", oldRepo, newRepo)
<del> out, _, err := runCommandWithOutput(cmd)
<add> out, _, err := dockerCmdWithError(c, "tag", oldRepo, newRepo)
<ide> if err != nil {
<ide> c.Fatalf("Could not tag busybox: %v: %s", err, out)
<ide> }
<del> cmd = exec.Command(dockerBinary, "run", "--name", "test", oldRepo, "touch", "/home/abcd")
<del> out, _, err = runCommandWithOutput(cmd)
<add>
<add> out, _, err = dockerCmdWithError(c, "run", "--name", "test", oldRepo, "touch", "/home/abcd")
<ide> if err != nil {
<ide> c.Fatalf("failed to run container: %v, output: %s", err, out)
<ide> }
<del> cmd = exec.Command(dockerBinary, "commit", "test", newTag)
<del> out, _, err = runCommandWithOutput(cmd)
<add>
<add> out, _, err = dockerCmdWithError(c, "commit", "test", newTag)
<ide> if err != nil {
<ide> c.Fatalf("failed to commit container: %v, output: %s", err, out)
<ide> }
<del> cmd = exec.Command(dockerBinary, "rmi", newTag)
<del> out, _, err = runCommandWithOutput(cmd)
<add>
<add> out, _, err = dockerCmdWithError(c, "rmi", newTag)
<ide> if err != nil {
<ide> c.Fatalf("failed to remove image: %v, output: %s", err, out)
<ide> }
<ide> if !strings.Contains(out, "Untagged: "+newTag) {
<ide> c.Fatalf("Could not remove image %s: %s, %v", newTag, out, err)
<ide> }
<del>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRmiBlank(c *check.C) {
<ide> // try to delete a blank image name
<del> runCmd := exec.Command(dockerBinary, "rmi", "")
<del> out, _, err := runCommandWithOutput(runCmd)
<del>
<add> out, _, err := dockerCmdWithError(c, "rmi", "")
<ide> if err == nil {
<ide> c.Fatal("Should have failed to delete '' image")
<ide> }
<del>
<ide> if strings.Contains(out, "No such image") {
<ide> c.Fatalf("Wrong error message generated: %s", out)
<ide> }
<del>
<ide> if !strings.Contains(out, "Image name can not be blank") {
<ide> c.Fatalf("Expected error message not generated: %s", out)
<ide> }
<ide>
<del> runCmd = exec.Command(dockerBinary, "rmi", " ")
<del> out, _, err = runCommandWithOutput(runCmd)
<del>
<add> out, _, err = dockerCmdWithError(c, "rmi", " ")
<ide> if err == nil {
<ide> c.Fatal("Should have failed to delete '' image")
<ide> }
<del>
<ide> if !strings.Contains(out, "No such image") {
<ide> c.Fatalf("Expected error message not generated: %s", out)
<ide> }
<ide><path>integration-cli/docker_cli_run_unix_test.go
<ide> func (s *DockerSuite) TestRunWithVolumesIsRecursive(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestRunWithUlimits(c *check.C) {
<ide> testRequires(c, NativeExecDriver)
<del> out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--name=testulimits", "--ulimit", "nofile=42", "busybox", "/bin/sh", "-c", "ulimit -n"))
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<ide>
<add> out, _ := dockerCmd(c, "run", "--name=testulimits", "--ulimit", "nofile=42", "busybox", "/bin/sh", "-c", "ulimit -n")
<ide> ul := strings.TrimSpace(out)
<ide> if ul != "42" {
<ide> c.Fatalf("expected `ulimit -n` to be 42, got %s", ul)
<ide> func (s *DockerSuite) TestRunContainerWithCgroupParent(c *check.C) {
<ide> c.Fatalf("unable to find self cpu cgroup path. CgroupsPath: %v", selfCgroupPaths)
<ide> }
<ide>
<del> out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--cgroup-parent", cgroupParent, "--rm", "busybox", "cat", "/proc/self/cgroup"))
<add> out, _, err := dockerCmdWithError(c, "run", "--cgroup-parent", cgroupParent, "--rm", "busybox", "cat", "/proc/self/cgroup")
<ide> if err != nil {
<ide> c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err)
<ide> }
<ide> func (s *DockerSuite) TestRunContainerWithCgroupParentAbsPath(c *check.C) {
<ide> testRequires(c, NativeExecDriver)
<ide>
<ide> cgroupParent := "/cgroup-parent/test"
<del>
<del> out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--cgroup-parent", cgroupParent, "--rm", "busybox", "cat", "/proc/self/cgroup"))
<add> out, _, err := dockerCmdWithError(c, "run", "--cgroup-parent", cgroupParent, "--rm", "busybox", "cat", "/proc/self/cgroup")
<ide> if err != nil {
<ide> c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err)
<ide> }
<ide> func (s *DockerSuite) TestRunContainerWithCgroupMountRO(c *check.C) {
<ide> testRequires(c, NativeExecDriver)
<ide>
<ide> filename := "/sys/fs/cgroup/devices/test123"
<del> cmd := exec.Command(dockerBinary, "run", "busybox", "touch", filename)
<del> out, _, err := runCommandWithOutput(cmd)
<add> out, _, err := dockerCmdWithError(c, "run", "busybox", "touch", filename)
<ide> if err == nil {
<ide> c.Fatal("expected cgroup mount point to be read-only, touch file should fail")
<ide> }
<ide> func (s *DockerSuite) TestRunContainerWithCgroupMountRO(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestRunDeviceDirectory(c *check.C) {
<ide> testRequires(c, NativeExecDriver)
<del> cmd := exec.Command(dockerBinary, "run", "--device", "/dev/snd:/dev/snd", "busybox", "sh", "-c", "ls /dev/snd/")
<del>
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<ide>
<add> out, _ := dockerCmd(c, "run", "--device", "/dev/snd:/dev/snd", "busybox", "sh", "-c", "ls /dev/snd/")
<ide> if actual := strings.Trim(out, "\r\n"); !strings.Contains(out, "timer") {
<ide> c.Fatalf("expected output /dev/snd/timer, received %s", actual)
<ide> }
<ide>
<del> cmd = exec.Command(dockerBinary, "run", "--device", "/dev/snd:/dev/othersnd", "busybox", "sh", "-c", "ls /dev/othersnd/")
<del>
<del> out, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<del>
<add> out, _ = dockerCmd(c, "run", "--device", "/dev/snd:/dev/othersnd", "busybox", "sh", "-c", "ls /dev/othersnd/")
<ide> if actual := strings.Trim(out, "\r\n"); !strings.Contains(out, "seq") {
<ide> c.Fatalf("expected output /dev/othersnd/seq, received %s", actual)
<ide> }
<ide> func (s *DockerSuite) TestRunAttachDetach(c *check.C) {
<ide> // "test" should be printed
<ide> func (s *DockerSuite) TestRunEchoStdoutWithCPUQuota(c *check.C) {
<ide> testRequires(c, CpuCfsQuota)
<del> runCmd := exec.Command(dockerBinary, "run", "--cpu-quota", "8000", "--name", "test", "busybox", "echo", "test")
<del> out, _, _, err := runCommandWithStdoutStderr(runCmd)
<add>
<add> out, _, err := dockerCmdWithError(c, "run", "--cpu-quota", "8000", "--name", "test", "busybox", "echo", "test")
<ide> if err != nil {
<ide> c.Fatalf("failed to run container: %v, output: %q", err, out)
<ide> }
<ide> func (s *DockerSuite) TestRunEchoStdoutWithCPUQuota(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestRunWithCpuPeriod(c *check.C) {
<ide> testRequires(c, CpuCfsPeriod)
<del> runCmd := exec.Command(dockerBinary, "run", "--cpu-period", "50000", "--name", "test", "busybox", "true")
<del> if _, err := runCommand(runCmd); err != nil {
<add>
<add> if _, _, err := dockerCmdWithError(c, "run", "--cpu-period", "50000", "--name", "test", "busybox", "true"); err != nil {
<ide> c.Fatalf("failed to run container: %v", err)
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunOOMExitCode(c *check.C) {
<ide> errChan := make(chan error)
<ide> go func() {
<ide> defer close(errChan)
<del> runCmd := exec.Command(dockerBinary, "run", "-m", "4MB", "busybox", "sh", "-c", "x=a; while true; do x=$x$x$x$x; done")
<del> out, exitCode, _ := runCommandWithOutput(runCmd)
<add> out, exitCode, _ := dockerCmdWithError(c, "run", "-m", "4MB", "busybox", "sh", "-c", "x=a; while true; do x=$x$x$x$x; done")
<ide> if expected := 137; exitCode != expected {
<ide> errChan <- fmt.Errorf("wrong exit code for OOM container: expected %d, got %d (output: %q)", expected, exitCode, out)
<ide> }
<ide> func (s *DockerSuite) TestRunOOMExitCode(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestContainerNetworkModeToSelf(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--name=me", "--net=container:me", "busybox", "true")
<del> out, _, err := runCommandWithOutput(cmd)
<add> out, _, err := dockerCmdWithError(c, "run", "--name=me", "--net=container:me", "busybox", "true")
<ide> if err == nil || !strings.Contains(out, "cannot join own network") {
<ide> c.Fatalf("using container net mode to self should result in an error")
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunContainerNetModeWithDnsMacHosts(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "-d", "--name", "parent", "busybox", "top")
<del> out, _, err := runCommandWithOutput(cmd)
<add> out, _, err := dockerCmdWithError(c, "run", "-d", "--name", "parent", "busybox", "top")
<ide> if err != nil {
<ide> c.Fatalf("failed to run container: %v, output: %q", err, out)
<ide> }
<ide>
<del> cmd = exec.Command(dockerBinary, "run", "--dns", "1.2.3.4", "--net=container:parent", "busybox")
<del> out, _, err = runCommandWithOutput(cmd)
<add> out, _, err = dockerCmdWithError(c, "run", "--dns", "1.2.3.4", "--net=container:parent", "busybox")
<ide> if err == nil || !strings.Contains(out, "Conflicting options: --dns and the network mode") {
<ide> c.Fatalf("run --net=container with --dns should error out")
<ide> }
<ide>
<del> cmd = exec.Command(dockerBinary, "run", "--mac-address", "92:d0:c6:0a:29:33", "--net=container:parent", "busybox")
<del> out, _, err = runCommandWithOutput(cmd)
<add> out, _, err = dockerCmdWithError(c, "run", "--mac-address", "92:d0:c6:0a:29:33", "--net=container:parent", "busybox")
<ide> if err == nil || !strings.Contains(out, "--mac-address and the network mode") {
<ide> c.Fatalf("run --net=container with --mac-address should error out")
<ide> }
<ide>
<del> cmd = exec.Command(dockerBinary, "run", "--add-host", "test:192.168.2.109", "--net=container:parent", "busybox")
<del> out, _, err = runCommandWithOutput(cmd)
<add> out, _, err = dockerCmdWithError(c, "run", "--add-host", "test:192.168.2.109", "--net=container:parent", "busybox")
<ide> if err == nil || !strings.Contains(out, "--add-host and the network mode") {
<ide> c.Fatalf("run --net=container with --add-host should error out")
<ide> }
<del>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunContainerNetModeWithExposePort(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "-d", "--name", "parent", "busybox", "top")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatalf("failed to run container: %v, output: %q", err, out)
<del> }
<add> dockerCmd(c, "run", "-d", "--name", "parent", "busybox", "top")
<ide>
<del> cmd = exec.Command(dockerBinary, "run", "-p", "5000:5000", "--net=container:parent", "busybox")
<del> out, _, err = runCommandWithOutput(cmd)
<add> out, _, err := dockerCmdWithError(c, "run", "-p", "5000:5000", "--net=container:parent", "busybox")
<ide> if err == nil || !strings.Contains(out, "Conflicting options: -p, -P, --publish-all, --publish and the network mode (--net)") {
<ide> c.Fatalf("run --net=container with -p should error out")
<ide> }
<ide>
<del> cmd = exec.Command(dockerBinary, "run", "-P", "--net=container:parent", "busybox")
<del> out, _, err = runCommandWithOutput(cmd)
<add> out, _, err = dockerCmdWithError(c, "run", "-P", "--net=container:parent", "busybox")
<ide> if err == nil || !strings.Contains(out, "Conflicting options: -p, -P, --publish-all, --publish and the network mode (--net)") {
<ide> c.Fatalf("run --net=container with -P should error out")
<ide> }
<ide>
<del> cmd = exec.Command(dockerBinary, "run", "--expose", "5000", "--net=container:parent", "busybox")
<del> out, _, err = runCommandWithOutput(cmd)
<add> out, _, err = dockerCmdWithError(c, "run", "--expose", "5000", "--net=container:parent", "busybox")
<ide> if err == nil || !strings.Contains(out, "Conflicting options: --expose and the network mode (--expose)") {
<ide> c.Fatalf("run --net=container with --expose should error out")
<ide> }
<del>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunLinkToContainerNetMode(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--name", "test", "-d", "busybox", "top")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatalf("failed to run container: %v, output: %q", err, out)
<del> }
<del> cmd = exec.Command(dockerBinary, "run", "--name", "parent", "-d", "--net=container:test", "busybox", "top")
<del> out, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatalf("failed to run container: %v, output: %q", err, out)
<del> }
<del> cmd = exec.Command(dockerBinary, "run", "-d", "--link=parent:parent", "busybox", "top")
<del> out, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatalf("failed to run container: %v, output: %q", err, out)
<del> }
<del>
<del> cmd = exec.Command(dockerBinary, "run", "--name", "child", "-d", "--net=container:parent", "busybox", "top")
<del> out, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatalf("failed to run container: %v, output: %q", err, out)
<del> }
<del> cmd = exec.Command(dockerBinary, "run", "-d", "--link=child:child", "busybox", "top")
<del> out, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatalf("failed to run container: %v, output: %q", err, out)
<del> }
<add> dockerCmd(c, "run", "--name", "test", "-d", "busybox", "top")
<add> dockerCmd(c, "run", "--name", "parent", "-d", "--net=container:test", "busybox", "top")
<add> dockerCmd(c, "run", "-d", "--link=parent:parent", "busybox", "top")
<add> dockerCmd(c, "run", "--name", "child", "-d", "--net=container:parent", "busybox", "top")
<add> dockerCmd(c, "run", "-d", "--link=child:child", "busybox", "top")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunLoopbackOnlyExistsWhenNetworkingDisabled(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--net=none", "busybox", "ip", "-o", "-4", "a", "show", "up")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err, out)
<del> }
<add> out, _ := dockerCmd(c, "run", "--net=none", "busybox", "ip", "-o", "-4", "a", "show", "up")
<ide>
<ide> var (
<ide> count = 0
<ide> func (s *DockerSuite) TestRunLoopbackOnlyExistsWhenNetworkingDisabled(c *check.C
<ide>
<ide> // Issue #4681
<ide> func (s *DockerSuite) TestRunLoopbackWhenNetworkDisabled(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "--net=none", "busybox", "ping", "-c", "1", "127.0.0.1")
<del> if _, err := runCommand(cmd); err != nil {
<del> c.Fatal(err)
<del> }
<add> dockerCmd(c, "run", "--net=none", "busybox", "ping", "-c", "1", "127.0.0.1")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunModeNetContainerHostname(c *check.C) {
<ide> testRequires(c, ExecSupport)
<del> cmd := exec.Command(dockerBinary, "run", "-i", "-d", "--name", "parent", "busybox", "top")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatalf("failed to run container: %v, output: %q", err, out)
<del> }
<del> cmd = exec.Command(dockerBinary, "exec", "parent", "cat", "/etc/hostname")
<del> out, _, err = runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatalf("failed to exec command: %v, output: %q", err, out)
<del> }
<ide>
<del> cmd = exec.Command(dockerBinary, "run", "--net=container:parent", "busybox", "cat", "/etc/hostname")
<del> out1, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatalf("failed to run container: %v, output: %q", err, out1)
<del> }
<add> dockerCmd(c, "run", "-i", "-d", "--name", "parent", "busybox", "top")
<add> out, _ := dockerCmd(c, "exec", "parent", "cat", "/etc/hostname")
<add> out1, _ := dockerCmd(c, "run", "--net=container:parent", "busybox", "cat", "/etc/hostname")
<add>
<ide> if out1 != out {
<ide> c.Fatal("containers with shared net namespace should have same hostname")
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunNetworkNotInitializedNoneMode(c *check.C) {
<del> cmd := exec.Command(dockerBinary, "run", "-d", "--net=none", "busybox", "top")
<del> out, _, err := runCommandWithOutput(cmd)
<del> if err != nil {
<del> c.Fatal(err)
<del> }
<add> out, _, err := dockerCmdWithError(c, "run", "-d", "--net=none", "busybox", "top")
<ide> id := strings.TrimSpace(out)
<ide> res, err := inspectField(id, "NetworkSettings.IPAddress")
<ide> c.Assert(err, check.IsNil) | 5 |
Mixed | Text | allow num_proxies=0 and include more docs | 83da4949c099fcf7e7636c98b9052b502e1bf74b | <ide><path>docs/api-guide/settings.md
<ide> The name of a parameter in the URL conf that may be used to provide a format suf
<ide>
<ide> Default: `'format'`
<ide>
<add>#### NUM_PROXIES
<add>
<add>An integer of 0 or more, that may be used to specify the number of application proxies that the API runs behind. This allows throttling to more accurately identify client IP addresses. If set to `None` then less strict IP matching will be used by the throttle classes.
<add>
<add>Default: `None`
<add>
<ide> [cite]: http://www.python.org/dev/peps/pep-0020/
<ide> [strftime]: http://docs.python.org/2/library/time.html#time.strftime
<ide><path>docs/api-guide/throttling.md
<ide> The default throttling policy may be set globally, using the `DEFAULT_THROTTLE_C
<ide> 'DEFAULT_THROTTLE_RATES': {
<ide> 'anon': '100/day',
<ide> 'user': '1000/day'
<del> },
<del> 'NUM_PROXIES': 2,
<add> }
<ide> }
<ide>
<ide> The rate descriptions used in `DEFAULT_THROTTLE_RATES` may include `second`, `minute`, `hour` or `day` as the throttle period.
<ide>
<del>By default Django REST Framework will try to use the `HTTP_X_FORWARDED_FOR` header to uniquely identify client machines for throttling. If `HTTP_X_FORWARDED_FOR` is not present `REMOTE_ADDR` header value will be used.
<del>
<del>To help Django REST Framework identify unique clients the number of application proxies can be set using `NUM_PROXIES`. This setting will allow the throttle to correctly identify unique requests when there are multiple application side proxies in front of the server. `NUM_PROXIES` should be set to an integer. It is important to understand that if you configure `NUM_PROXIES > 0` all clients behind a unique [NAT'd](http://en.wikipedia.org/wiki/Network_address_translation) gateway will be treated as a single client.
<del>
<ide> You can also set the throttling policy on a per-view or per-viewset basis,
<ide> using the `APIView` class based views.
<ide>
<ide> Or, if you're using the `@api_view` decorator with function based views.
<ide> }
<ide> return Response(content)
<ide>
<add>## How clients are identified
<add>
<add>By default the `X-Forwarded-For` HTTP header is used to uniquely identify client machines for throttling. If the `X-Forwarded-For` header is not present, then the value of the `Remote-Addr` header will be used.
<add>
<add>If you need to more strictly identify unique clients, you'll need to configure the number of application proxies that the API runs behind by setting the `NUM_PROXIES` setting. This setting should be an integer of 0 or more, and will allow the throttle to identify the client IP as being the last IP address in the `X-Forwarded-For` header, once any application proxy IP addresses have first been excluded.
<add>
<add>It is important to understand that if you configure the `NUM_PROXIES` setting, then all clients behind a unique [NAT'd](http://en.wikipedia.org/wiki/Network_address_translation) gateway will be treated as a single client.
<add>
<add>Further context on how the `X-Forwarded-For` header works, and identifier a remote client IP can be [found here][identifing-clients].
<add>
<ide> ## Setting up the cache
<ide>
<ide> The throttle classes provided by REST framework use Django's cache backend. You should make sure that you've set appropriate [cache settings][cache-setting]. The default value of `LocMemCache` backend should be okay for simple setups. See Django's [cache documentation][cache-docs] for more details.
<ide> The following is an example of a rate throttle, that will randomly throttle 1 in
<ide>
<ide> [cite]: https://dev.twitter.com/docs/error-codes-responses
<ide> [permissions]: permissions.md
<add>[identifing-clients]: http://oxpedia.org/wiki/index.php?title=AppSuite:Grizzly#Multiple_Proxies_in_front_of_the_cluster
<ide> [cache-setting]: https://docs.djangoproject.com/en/dev/ref/settings/#caches
<ide> [cache-docs]: https://docs.djangoproject.com/en/dev/topics/cache/#setting-up-the-cache
<ide><path>rest_framework/throttling.py
<ide> def get_ident(self, request):
<ide> remote_addr = request.META.get('REMOTE_ADDR')
<ide> num_proxies = api_settings.NUM_PROXIES
<ide>
<del> if xff and num_proxies:
<del> return xff.split(',')[-min(num_proxies, len(xff))].strip()
<add> if num_proxies is not None:
<add> if num_proxies == 0 or xff is None:
<add> return remote_addr
<add> addrs = xff.split(',')
<add> client_addr = addrs[-min(num_proxies, len(xff))]
<add> return client_addr.strip()
<ide>
<ide> return xff if xff else remote_addr
<ide> | 3 |
Javascript | Javascript | fix typo in protocol handler installer popup | d848c15d4230221dae8e4e003639a661203c5512 | <ide><path>src/protocol-handler-installer.js
<ide> class ProtocolHandlerInstaller {
<ide> notification = notifications.addInfo('Register as default atom:// URI handler?', {
<ide> dismissable: true,
<ide> icon: 'link',
<del> description: 'Atom is not currently set as the defaut handler for atom:// URIs. Would you like Atom to handle ' +
<add> description: 'Atom is not currently set as the default handler for atom:// URIs. Would you like Atom to handle ' +
<ide> 'atom:// URIs?',
<ide> buttons: [
<ide> { | 1 |
Javascript | Javascript | add plugin handling and forked paths | 8e6a08ea4f3beb2127ec3d1595cf5f83df5816b6 | <ide><path>packages/react-dom/src/__tests__/ReactBrowserEventEmitter-test.internal.js
<ide> let ReactDOMComponentTree;
<ide> let listenToEvent;
<ide> let ReactDOMEventListener;
<ide> let ReactTestUtils;
<add>let ReactFeatureFlags;
<ide>
<ide> let idCallOrder;
<ide> const recordID = function(id) {
<ide> describe('ReactBrowserEventEmitter', () => {
<ide> jest.resetModules();
<ide> LISTENER.mockClear();
<ide>
<add> ReactFeatureFlags = require('shared/ReactFeatureFlags');
<ide> EventPluginGetListener = require('legacy-events/getListener').default;
<ide> EventPluginRegistry = require('legacy-events/EventPluginRegistry');
<ide> React = require('react');
<ide> ReactDOM = require('react-dom');
<ide> ReactDOMComponentTree = require('../client/ReactDOMComponentTree');
<del> listenToEvent = require('../events/DOMLegacyEventPluginSystem')
<del> .legacyListenToEvent;
<add> if (ReactFeatureFlags.enableModernEventSystem) {
<add> listenToEvent = require('../events/DOMModernPluginEventSystem')
<add> .listenToEvent;
<add> } else {
<add> listenToEvent = require('../events/DOMLegacyEventPluginSystem')
<add> .legacyListenToEvent;
<add> }
<add>
<ide> ReactDOMEventListener = require('../events/ReactDOMEventListener');
<ide> ReactTestUtils = require('react-dom/test-utils');
<ide>
<ide><path>packages/react-dom/src/__tests__/ReactDOMEventListener-test.js
<ide> describe('ReactDOMEventListener', () => {
<ide> let React;
<ide> let ReactDOM;
<add> let ReactFeatureFlags = require('shared/ReactFeatureFlags');
<ide>
<ide> beforeEach(() => {
<ide> jest.resetModules();
<ide> React = require('react');
<ide> ReactDOM = require('react-dom');
<ide> });
<ide>
<del> it('should dispatch events from outside React tree', () => {
<del> const mock = jest.fn();
<add> // We attached events to roots with the modern system,
<add> // so this test is no longer valid.
<add> if (!ReactFeatureFlags.enableModernEventSystem) {
<add> it('should dispatch events from outside React tree', () => {
<add> const mock = jest.fn();
<ide>
<del> const container = document.createElement('div');
<del> const node = ReactDOM.render(<div onMouseEnter={mock} />, container);
<del> const otherNode = document.createElement('h1');
<del> document.body.appendChild(container);
<del> document.body.appendChild(otherNode);
<add> const container = document.createElement('div');
<add> const node = ReactDOM.render(<div onMouseEnter={mock} />, container);
<add> const otherNode = document.createElement('h1');
<add> document.body.appendChild(container);
<add> document.body.appendChild(otherNode);
<ide>
<del> try {
<del> otherNode.dispatchEvent(
<del> new MouseEvent('mouseout', {
<del> bubbles: true,
<del> cancelable: true,
<del> relatedTarget: node,
<del> }),
<del> );
<del> expect(mock).toBeCalled();
<del> } finally {
<del> document.body.removeChild(container);
<del> document.body.removeChild(otherNode);
<del> }
<del> });
<add> try {
<add> otherNode.dispatchEvent(
<add> new MouseEvent('mouseout', {
<add> bubbles: true,
<add> cancelable: true,
<add> relatedTarget: node,
<add> }),
<add> );
<add> expect(mock).toBeCalled();
<add> } finally {
<add> document.body.removeChild(container);
<add> document.body.removeChild(otherNode);
<add> }
<add> });
<add> }
<ide>
<ide> describe('Propagation', () => {
<ide> it('should propagate events one level down', () => {
<ide> describe('ReactDOMEventListener', () => {
<ide> // The first call schedules a render of '1' into the 'Child'.
<ide> // However, we're batching so it isn't flushed yet.
<ide> expect(mock.mock.calls[0][0]).toBe('Child');
<del> // The first call schedules a render of '2' into the 'Child'.
<del> // We're still batching so it isn't flushed yet either.
<del> expect(mock.mock.calls[1][0]).toBe('Child');
<add> if (ReactFeatureFlags.enableModernEventSystem) {
<add> // As we have two roots, it means we have two event listeners.
<add> // This also means we enter the event batching phase twice,
<add> // flushing the child to be 1.
<add>
<add> // We don't have any good way of knowing if another event will
<add> // occur because another event handler might invoke
<add> // stopPropagation() along the way. After discussions internally
<add> // with Sebastian, it seems that for now over-flushing should
<add> // be fine, especially as the new event system is a breaking
<add> // change anyway. We can maybe revisit this later as part of
<add> // the work to refine this in the scheduler (maybe by leveraging
<add> // isInputPending?).
<add> expect(mock.mock.calls[1][0]).toBe('1');
<add> } else {
<add> // The first call schedules a render of '2' into the 'Child'.
<add> // We're still batching so it isn't flushed yet either.
<add> expect(mock.mock.calls[1][0]).toBe('Child');
<add> }
<ide> // By the time we leave the handler, the second update is flushed.
<ide> expect(childNode.textContent).toBe('2');
<ide> } finally {
<ide> describe('ReactDOMEventListener', () => {
<ide> bubbles: false,
<ide> }),
<ide> );
<del> // Historically, we happened to not support onLoadStart
<del> // on <img>, and this test documents that lack of support.
<del> // If we decide to support it in the future, we should change
<del> // this line to expect 1 call. Note that fixing this would
<del> // be simple but would require attaching a handler to each
<del> // <img>. So far nobody asked us for it.
<del> expect(handleImgLoadStart).toHaveBeenCalledTimes(0);
<add> if (ReactFeatureFlags.enableModernEventSystem) {
<add> // As of the modern event system refactor, we now support
<add> // this on <img>. The reason for this, is because we now
<add> // attach all media events to the "root" or "portal" in the
<add> // capture phase, rather than the bubble phase. This allows
<add> // us to assign less event listeners to individual elements,
<add> // which also nicely allows us to support more without needing
<add> // to add more individual code paths to support various
<add> // events that do not bubble.
<add> expect(handleImgLoadStart).toHaveBeenCalledTimes(1);
<add> } else {
<add> // Historically, we happened to not support onLoadStart
<add> // on <img>, and this test documents that lack of support.
<add> // If we decide to support it in the future, we should change
<add> // this line to expect 1 call. Note that fixing this would
<add> // be simple but would require attaching a handler to each
<add> // <img>. So far nobody asked us for it.
<add> expect(handleImgLoadStart).toHaveBeenCalledTimes(0);
<add> }
<ide>
<ide> videoRef.current.dispatchEvent(
<ide> new ProgressEvent('loadstart', {
<ide><path>packages/react-dom/src/__tests__/ReactTreeTraversal-test.js
<ide>
<ide> let React;
<ide> let ReactDOM;
<add>let ReactFeatureFlags = require('shared/ReactFeatureFlags');
<ide>
<ide> const ChildComponent = ({id, eventHandler}) => (
<ide> <div
<ide> describe('ReactTreeTraversal', () => {
<ide> expect(mockFn.mock.calls).toEqual(expectedCalls);
<ide> });
<ide>
<del> it('should enter from the window', () => {
<del> const enterNode = document.getElementById('P_P1_C1__DIV');
<del>
<del> const expectedCalls = [
<del> ['P', 'mouseenter'],
<del> ['P_P1', 'mouseenter'],
<del> ['P_P1_C1__DIV', 'mouseenter'],
<del> ];
<del>
<del> outerNode1.dispatchEvent(
<del> new MouseEvent('mouseout', {
<del> bubbles: true,
<del> cancelable: true,
<del> relatedTarget: enterNode,
<del> }),
<del> );
<del>
<del> expect(mockFn.mock.calls).toEqual(expectedCalls);
<del> });
<del>
<del> it('should enter from the window to the shallowest', () => {
<del> const enterNode = document.getElementById('P');
<del>
<del> const expectedCalls = [['P', 'mouseenter']];
<del>
<del> outerNode1.dispatchEvent(
<del> new MouseEvent('mouseout', {
<del> bubbles: true,
<del> cancelable: true,
<del> relatedTarget: enterNode,
<del> }),
<del> );
<del>
<del> expect(mockFn.mock.calls).toEqual(expectedCalls);
<del> });
<add> // This will not work with the modern event system that
<add> // attaches event listeners to roots as the event below
<add> // is being triggered on a node that React does not listen
<add> // to any more. Instead we should fire mouseover.
<add> if (ReactFeatureFlags.enableModernEventSystem) {
<add> it('should enter from the window', () => {
<add> const enterNode = document.getElementById('P_P1_C1__DIV');
<add>
<add> const expectedCalls = [
<add> ['P', 'mouseenter'],
<add> ['P_P1', 'mouseenter'],
<add> ['P_P1_C1__DIV', 'mouseenter'],
<add> ];
<add>
<add> enterNode.dispatchEvent(
<add> new MouseEvent('mouseover', {
<add> bubbles: true,
<add> cancelable: true,
<add> relatedTarget: outerNode1,
<add> }),
<add> );
<add>
<add> expect(mockFn.mock.calls).toEqual(expectedCalls);
<add> });
<add> } else {
<add> it('should enter from the window', () => {
<add> const enterNode = document.getElementById('P_P1_C1__DIV');
<add>
<add> const expectedCalls = [
<add> ['P', 'mouseenter'],
<add> ['P_P1', 'mouseenter'],
<add> ['P_P1_C1__DIV', 'mouseenter'],
<add> ];
<add>
<add> outerNode1.dispatchEvent(
<add> new MouseEvent('mouseout', {
<add> bubbles: true,
<add> cancelable: true,
<add> relatedTarget: enterNode,
<add> }),
<add> );
<add>
<add> expect(mockFn.mock.calls).toEqual(expectedCalls);
<add> });
<add> }
<add>
<add> // This will not work with the modern event system that
<add> // attaches event listeners to roots as the event below
<add> // is being triggered on a node that React does not listen
<add> // to any more. Instead we should fire mouseover.
<add> if (ReactFeatureFlags.enableModernEventSystem) {
<add> it('should enter from the window to the shallowest', () => {
<add> const enterNode = document.getElementById('P');
<add>
<add> const expectedCalls = [['P', 'mouseenter']];
<add>
<add> enterNode.dispatchEvent(
<add> new MouseEvent('mouseover', {
<add> bubbles: true,
<add> cancelable: true,
<add> relatedTarget: outerNode1,
<add> }),
<add> );
<add>
<add> expect(mockFn.mock.calls).toEqual(expectedCalls);
<add> });
<add> } else {
<add> it('should enter from the window to the shallowest', () => {
<add> const enterNode = document.getElementById('P');
<add>
<add> const expectedCalls = [['P', 'mouseenter']];
<add>
<add> outerNode1.dispatchEvent(
<add> new MouseEvent('mouseout', {
<add> bubbles: true,
<add> cancelable: true,
<add> relatedTarget: enterNode,
<add> }),
<add> );
<add>
<add> expect(mockFn.mock.calls).toEqual(expectedCalls);
<add> });
<add> }
<ide>
<ide> it('should leave to the window', () => {
<ide> const leaveNode = document.getElementById('P_P1_C1__DIV');
<ide><path>packages/react-dom/src/events/DOMModernPluginEventSystem.js
<ide> import type {AnyNativeEvent} from 'legacy-events/PluginModuleType';
<ide> import type {DOMTopLevelEventType} from 'legacy-events/TopLevelEventTypes';
<ide> import type {EventSystemFlags} from 'legacy-events/EventSystemFlags';
<ide> import type {Fiber} from 'react-reconciler/src/ReactFiber';
<add>import type {PluginModule} from 'legacy-events/PluginModuleType';
<add>import type {ReactSyntheticEvent} from 'legacy-events/ReactSyntheticEventType';
<ide>
<ide> import {registrationNameDependencies} from 'legacy-events/EventPluginRegistry';
<add>import {batchedEventUpdates} from 'legacy-events/ReactGenericBatching';
<add>import {executeDispatchesInOrder} from 'legacy-events/EventPluginUtils';
<add>import {plugins} from 'legacy-events/EventPluginRegistry';
<ide>
<ide> import {trapEventForPluginEventSystem} from './ReactDOMEventListener';
<add>import getEventTarget from './getEventTarget';
<ide> import {getListenerMapForElement} from './DOMEventListenerMap';
<ide> import {
<ide> TOP_FOCUS,
<ide> const capturePhaseEvents = new Set([
<ide> TOP_WAITING,
<ide> ]);
<ide>
<add>const isArray = Array.isArray;
<add>
<add>function dispatchEventsForPlugins(
<add> topLevelType: DOMTopLevelEventType,
<add> eventSystemFlags: EventSystemFlags,
<add> nativeEvent: AnyNativeEvent,
<add> targetInst: null | Fiber,
<add> rootContainer: Element | Document,
<add>): void {
<add> const nativeEventTarget = getEventTarget(nativeEvent);
<add> const syntheticEvents: Array<ReactSyntheticEvent> = [];
<add>
<add> for (let i = 0; i < plugins.length; i++) {
<add> const possiblePlugin: PluginModule<AnyNativeEvent> = plugins[i];
<add> if (possiblePlugin !== undefined) {
<add> const extractedEvents = possiblePlugin.extractEvents(
<add> topLevelType,
<add> targetInst,
<add> nativeEvent,
<add> nativeEventTarget,
<add> eventSystemFlags,
<add> rootContainer,
<add> );
<add> if (isArray(extractedEvents)) {
<add> // Flow complains about @@iterator being missing in ReactSyntheticEvent,
<add> // so we cast to avoid the Flow error.
<add> const arrOfExtractedEvents = ((extractedEvents: any): Array<ReactSyntheticEvent>);
<add> syntheticEvents.push(...arrOfExtractedEvents);
<add> } else if (extractedEvents != null) {
<add> syntheticEvents.push(extractedEvents);
<add> }
<add> }
<add> }
<add> for (let i = 0; i < syntheticEvents.length; i++) {
<add> const syntheticEvent = syntheticEvents[i];
<add> executeDispatchesInOrder(syntheticEvent);
<add> // Release the event from the pool if needed
<add> if (!syntheticEvent.isPersistent()) {
<add> syntheticEvent.constructor.release(syntheticEvent);
<add> }
<add> }
<add>}
<add>
<ide> export function listenToTopLevelEvent(
<ide> topLevelType: DOMTopLevelEventType,
<ide> rootContainerElement: Element,
<ide> export function dispatchEventForPluginEventSystem(
<ide> targetInst: null | Fiber,
<ide> rootContainer: Document | Element,
<ide> ): void {
<del> // TODO
<add> let ancestorInst = targetInst;
<add>
<add> batchedEventUpdates(() =>
<add> dispatchEventsForPlugins(
<add> topLevelType,
<add> eventSystemFlags,
<add> nativeEvent,
<add> ancestorInst,
<add> rootContainer,
<add> ),
<add> );
<ide> }
<ide><path>packages/react-dom/src/events/EnterLeaveEventPlugin.js
<ide> import {
<ide> } from '../client/ReactDOMComponentTree';
<ide> import {HostComponent, HostText} from 'shared/ReactWorkTags';
<ide> import {getNearestMountedFiber} from 'react-reconciler/reflection';
<add>import {enableModernEventSystem} from 'shared/ReactFeatureFlags';
<ide>
<ide> const eventTypes = {
<ide> mouseEnter: {
<ide> const EnterLeaveEventPlugin = {
<ide> const isOutEvent =
<ide> topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_POINTER_OUT;
<ide>
<del> if (
<del> isOverEvent &&
<del> (eventSystemFlags & IS_REPLAYED) === 0 &&
<del> (nativeEvent.relatedTarget || nativeEvent.fromElement)
<del> ) {
<del> // If this is an over event with a target, then we've already dispatched
<del> // the event in the out event of the other target. If this is replayed,
<del> // then it's because we couldn't dispatch against this target previously
<del> // so we have to do it now instead.
<del> return null;
<add> if (isOverEvent && (eventSystemFlags & IS_REPLAYED) === 0) {
<add> const related = nativeEvent.relatedTarget || nativeEvent.fromElement;
<add> if (related) {
<add> if (enableModernEventSystem) {
<add> // Due to the fact we don't add listeners to the document with the
<add> // modern event system and instead attach listeners to roots, we
<add> // need to handle the over event case. To ensure this, we just need to
<add> // make sure the node that we're coming from is managed by React.
<add> const inst = getClosestInstanceFromNode(related);
<add> if (inst !== null) {
<add> return null;
<add> }
<add> } else {
<add> // If this is an over event with a target, then we've already dispatched
<add> // the event in the out event of the other target. If this is replayed,
<add> // then it's because we couldn't dispatch against this target previously
<add> // so we have to do it now instead.
<add> return null;
<add> }
<add> }
<ide> }
<ide>
<ide> if (!isOutEvent && !isOverEvent) {
<ide> const EnterLeaveEventPlugin = {
<ide>
<ide> accumulateEnterLeaveDispatches(leave, enter, from, to);
<ide>
<del> // If we are not processing the first ancestor, then we
<del> // should not process the same nativeEvent again, as we
<del> // will have already processed it in the first ancestor.
<del> if ((eventSystemFlags & IS_FIRST_ANCESTOR) === 0) {
<del> return [leave];
<add> if (!enableModernEventSystem) {
<add> // If we are not processing the first ancestor, then we
<add> // should not process the same nativeEvent again, as we
<add> // will have already processed it in the first ancestor.
<add> if ((eventSystemFlags & IS_FIRST_ANCESTOR) === 0) {
<add> return [leave];
<add> }
<ide> }
<ide>
<ide> return [leave, enter];
<ide><path>packages/react-dom/src/events/__tests__/DOMModernPluginEventSystem-test.internal.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @emails react-core
<add> */
<add>
<add>'use strict';
<add>
<add>let React;
<add>let ReactFeatureFlags;
<add>let ReactDOM;
<add>
<add>function dispatchClickEvent(element) {
<add> const event = document.createEvent('Event');
<add> event.initEvent('click', true, true);
<add> element.dispatchEvent(event);
<add>}
<add>
<add>describe('DOMModernPluginEventSystem', () => {
<add> let container;
<add>
<add> beforeEach(() => {
<add> jest.resetModules();
<add> ReactFeatureFlags = require('shared/ReactFeatureFlags');
<add> ReactFeatureFlags.enableModernEventSystem = true;
<add>
<add> React = require('react');
<add> ReactDOM = require('react-dom');
<add> container = document.createElement('div');
<add> document.body.appendChild(container);
<add> });
<add>
<add> afterEach(() => {
<add> document.body.removeChild(container);
<add> container = null;
<add> });
<add>
<add> it('handle propagation of click events', () => {
<add> const buttonRef = React.createRef();
<add> const divRef = React.createRef();
<add> const log = [];
<add> const onClick = jest.fn(e => log.push(['bubble', e.currentTarget]));
<add> const onClickCapture = jest.fn(e => log.push(['capture', e.currentTarget]));
<add>
<add> function Test() {
<add> return (
<add> <button
<add> ref={buttonRef}
<add> onClick={onClick}
<add> onClickCapture={onClickCapture}>
<add> <div ref={divRef} onClick={onClick} onClickCapture={onClickCapture}>
<add> Click me!
<add> </div>
<add> </button>
<add> );
<add> }
<add>
<add> ReactDOM.render(<Test />, container);
<add>
<add> let buttonElement = buttonRef.current;
<add> dispatchClickEvent(buttonElement);
<add> expect(onClick).toHaveBeenCalledTimes(1);
<add> expect(onClickCapture).toHaveBeenCalledTimes(1);
<add> expect(log[0]).toEqual(['capture', buttonElement]);
<add> expect(log[1]).toEqual(['bubble', buttonElement]);
<add>
<add> let divElement = divRef.current;
<add> dispatchClickEvent(divElement);
<add> expect(onClick).toHaveBeenCalledTimes(3);
<add> expect(onClickCapture).toHaveBeenCalledTimes(3);
<add> expect(log[2]).toEqual(['capture', buttonElement]);
<add> expect(log[3]).toEqual(['capture', divElement]);
<add> expect(log[4]).toEqual(['bubble', divElement]);
<add> expect(log[5]).toEqual(['bubble', buttonElement]);
<add> });
<add>
<add> it('handle propagation of focus events', () => {
<add> const buttonRef = React.createRef();
<add> const divRef = React.createRef();
<add> const log = [];
<add> const onFocus = jest.fn(e => log.push(['bubble', e.currentTarget]));
<add> const onFocusCapture = jest.fn(e => log.push(['capture', e.currentTarget]));
<add>
<add> function Test() {
<add> return (
<add> <button
<add> ref={buttonRef}
<add> onFocus={onFocus}
<add> onFocusCapture={onFocusCapture}>
<add> <div
<add> ref={divRef}
<add> onFocus={onFocus}
<add> onFocusCapture={onFocusCapture}
<add> tabIndex={0}>
<add> Click me!
<add> </div>
<add> </button>
<add> );
<add> }
<add>
<add> ReactDOM.render(<Test />, container);
<add>
<add> let buttonElement = buttonRef.current;
<add> buttonElement.focus();
<add> expect(onFocus).toHaveBeenCalledTimes(1);
<add> expect(onFocusCapture).toHaveBeenCalledTimes(1);
<add> expect(log[0]).toEqual(['capture', buttonElement]);
<add> expect(log[1]).toEqual(['bubble', buttonElement]);
<add>
<add> let divElement = divRef.current;
<add> divElement.focus();
<add> expect(onFocus).toHaveBeenCalledTimes(3);
<add> expect(onFocusCapture).toHaveBeenCalledTimes(3);
<add> expect(log[2]).toEqual(['capture', buttonElement]);
<add> expect(log[3]).toEqual(['capture', divElement]);
<add> expect(log[4]).toEqual(['bubble', divElement]);
<add> expect(log[5]).toEqual(['bubble', buttonElement]);
<add> });
<add>}); | 6 |
Ruby | Ruby | fix rubocop warnings | 6cfb84152464097901a9b9a437b37cc8c5aeb45c | <ide><path>Library/Homebrew/utils/github.rb
<ide> def api_credentials_error_message(response_headers)
<ide> end
<ide> end
<ide>
<del> def open(url, data=nil)
<add> def open(url, data = nil)
<ide> # This is a no-op if the user is opting out of using the GitHub API.
<ide> return if ENV["HOMEBREW_NO_GITHUB_API"]
<ide>
<ide> def open(url, data=nil)
<ide> args += ["--data", "@#{data_tmpfile.path}"]
<ide> end
<ide>
<del> args += ["--dump-header", "#{headers_tmpfile.path}"]
<add> args += ["--dump-header", headers_tmpfile.path.to_s]
<ide>
<ide> output, errors, status = curl_output(url.to_s, *args)
<ide> output, _, http_code = output.rpartition("\n")
<ide> def raise_api_error(output, errors, http_code, headers)
<ide>
<ide> case http_code
<ide> when "401", "403"
<del> raise AuthenticationFailedError.new(output)
<add> raise AuthenticationFailedError, output
<ide> when "404"
<ide> raise HTTPNotFoundError, output
<ide> else
<del> error = Utils::JSON.load(output)["message"] rescue nil
<add> error = begin
<add> Utils::JSON.load(output)["message"]
<add> rescue
<add> nil
<add> end
<ide> error ||= "curl failed! #{errors}"
<ide> raise Error, error
<ide> end
<ide> def build_query_string(query, qualifiers)
<ide> def build_search_qualifier_string(qualifiers)
<ide> {
<ide> :repo => "Homebrew/homebrew-core",
<del> :in => "title"
<add> :in => "title",
<ide> }.update(qualifiers).map do |qualifier, value|
<ide> "#{qualifier}:#{value}"
<ide> end.join("+") | 1 |
Python | Python | add args to log_received (fixes ) | ad994719bafe6747af6cf8251efb0925284a9260 | <ide><path>celery/app/trace.py
<ide> def trace_task(uuid, args, kwargs, request=None):
<ide> 'name': get_task_name(task_request, name),
<ide> 'return_value': Rstr,
<ide> 'runtime': T,
<add> 'args': safe_repr(args),
<add> 'kwargs': safe_repr(kwargs),
<ide> })
<ide>
<ide> # -* POST *-
<ide><path>celery/worker/strategy.py
<ide> import logging
<ide>
<ide> from kombu.asynchronous.timer import to_timestamp
<add>from kombu.utils.encoding import safe_repr
<ide>
<ide> from celery import signals
<ide> from celery.app import trace as _app_trace
<ide> def task_message_handler(message, body, ack, reject, callbacks,
<ide> if _does_info:
<ide> # Similar to `app.trace.info()`, we pass the formatting args as the
<ide> # `extra` kwarg for custom log handlers
<del> context = {'id': req.id, 'name': req.name}
<add> context = {
<add> 'id': req.id,
<add> 'name': req.name,
<add> 'args': safe_repr(req.args),
<add> 'kwargs': safe_repr(req.kwargs),
<add> }
<ide> info(_app_trace.LOG_RECEIVED, context, extra={'data': context})
<ide> if (req.expires or req.id in revoked_tasks) and req.revoked():
<ide> return
<ide><path>t/unit/worker/test_strategy.py
<ide> def test_log_task_received_custom(self, caplog):
<ide> C()
<ide> for record in caplog.records:
<ide> if record.msg == custom_fmt:
<del> assert set(record.args) == {"id", "name"}
<add> assert set(record.args) == {"id", "name", "kwargs", "args"}
<ide> break
<ide> else:
<ide> raise ValueError("Expected message not in captured log records") | 3 |
Javascript | Javascript | fix external links in presentation mode (issue ) | 87eb2dccbe0cc8257924f3bcd0cab155fdf5fdfa | <ide><path>web/page_view.js
<ide> var PageView = function pageView(container, id, scale,
<ide> }
<ide> return false;
<ide> };
<del> link.className = 'internalLink';
<add> if (dest) {
<add> link.className = 'internalLink';
<add> }
<ide> }
<ide>
<ide> function bindNamedAction(link, action) { | 1 |
Javascript | Javascript | remove duplicated call from navigatorsceneconfigs | 176f96d7b6f752368efb12d5fbbdd5d7a92fdd4f | <ide><path>Libraries/CustomComponents/Navigator/NavigatorBreadcrumbNavigationBar.js
<ide> function navStatePresentedIndex(navState) {
<ide> }
<ide> // TODO: rename `observedTopOfStack` to `presentedIndex` in `NavigatorIOS`
<ide> return navState.observedTopOfStack;
<del>};
<add>}
<ide>
<ide>
<ide> /**
<ide> function initStyle(index, presentedIndex) {
<ide> return index === presentedIndex ? NavigatorBreadcrumbNavigationBarStyles.Center[index] :
<ide> index < presentedIndex ? NavigatorBreadcrumbNavigationBarStyles.Left[index] :
<ide> NavigatorBreadcrumbNavigationBarStyles.Right[index];
<del>};
<add>}
<ide>
<ide> class NavigatorBreadcrumbNavigationBar extends React.Component {
<ide> static propTypes = {
<ide><path>Libraries/CustomComponents/Navigator/NavigatorSceneConfigs.js
<ide> var IS_RTL = I18nManager.isRTL;
<ide>
<ide> var SCREEN_WIDTH = Dimensions.get('window').width;
<ide> var SCREEN_HEIGHT = Dimensions.get('window').height;
<add>var PIXEL_RATIO = PixelRatio.get();
<ide>
<ide> var ToTheLeftIOS = {
<ide> transformTranslate: {
<ide> var ToTheLeftIOS = {
<ide> max: 1,
<ide> type: 'linear',
<ide> extrapolate: true,
<del> round: PixelRatio.get(),
<add> round: PIXEL_RATIO,
<ide> },
<ide> opacity: {
<ide> value: 1.0,
<ide> var FadeToTheLeft = {
<ide> // rotation (x, y, z, w)
<ide> transformTranslate: {
<ide> from: {x: 0, y: 0, z: 0},
<del> to: {x: -Math.round(Dimensions.get('window').width * 0.3), y: 0, z: 0},
<add> to: {x: -Math.round(SCREEN_WIDTH * 0.3), y: 0, z: 0},
<ide> min: 0,
<ide> max: 1,
<ide> type: 'linear',
<ide> extrapolate: true,
<del> round: PixelRatio.get(),
<add> round: PIXEL_RATIO,
<ide> },
<ide> // Uncomment to try rotation:
<ide> // Quick guide to reasoning about rotations:
<ide> var FadeToTheLeft = {
<ide> },
<ide> translateX: {
<ide> from: 0,
<del> to: -Math.round(Dimensions.get('window').width * 0.3),
<add> to: -Math.round(SCREEN_WIDTH * 0.3),
<ide> min: 0,
<ide> max: 1,
<ide> type: 'linear',
<ide> extrapolate: true,
<del> round: PixelRatio.get(),
<add> round: PIXEL_RATIO,
<ide> },
<ide> scaleX: {
<ide> from: 1,
<ide> var FadeOut = {
<ide> var ToTheLeft = {
<ide> transformTranslate: {
<ide> from: {x: 0, y: 0, z: 0},
<del> to: {x: -Dimensions.get('window').width, y: 0, z: 0},
<add> to: {x: -SCREEN_WIDTH, y: 0, z: 0},
<ide> min: 0,
<ide> max: 1,
<ide> type: 'linear',
<ide> extrapolate: true,
<del> round: PixelRatio.get(),
<add> round: PIXEL_RATIO,
<ide> },
<ide> opacity: {
<ide> value: 1.0,
<ide> var ToTheLeft = {
<ide>
<ide> translateX: {
<ide> from: 0,
<del> to: -Dimensions.get('window').width,
<add> to: -SCREEN_WIDTH,
<ide> min: 0,
<ide> max: 1,
<ide> type: 'linear',
<ide> extrapolate: true,
<del> round: PixelRatio.get(),
<add> round: PIXEL_RATIO,
<ide> },
<ide> };
<ide>
<ide> var ToTheRight = {
<ide> transformTranslate: {
<ide> from: {x: 0, y: 0, z: 0},
<del> to: {x: Dimensions.get('window').width, y: 0, z: 0},
<add> to: {x: SCREEN_WIDTH, y: 0, z: 0},
<ide> min: 0,
<ide> max: 1,
<ide> type: 'linear',
<ide> extrapolate: true,
<del> round: PixelRatio.get(),
<add> round: PIXEL_RATIO,
<ide> },
<ide> opacity: {
<ide> value: 1.0,
<ide> var ToTheRight = {
<ide>
<ide> translateX: {
<ide> from: 0,
<del> to: Dimensions.get('window').width,
<add> to: SCREEN_WIDTH,
<ide> min: 0,
<ide> max: 1,
<ide> type: 'linear',
<ide> extrapolate: true,
<del> round: PixelRatio.get(),
<add> round: PIXEL_RATIO,
<ide> },
<ide> };
<ide>
<ide> var ToTheUp = {
<ide> transformTranslate: {
<ide> from: {x: 0, y: 0, z: 0},
<del> to: {x: 0, y: -Dimensions.get('window').height, z: 0},
<add> to: {x: 0, y: -SCREEN_HEIGHT, z: 0},
<ide> min: 0,
<ide> max: 1,
<ide> type: 'linear',
<ide> extrapolate: true,
<del> round: PixelRatio.get(),
<add> round: PIXEL_RATIO,
<ide> },
<ide> opacity: {
<ide> value: 1.0,
<ide> type: 'constant',
<ide> },
<ide> translateY: {
<ide> from: 0,
<del> to: -Dimensions.get('window').height,
<add> to: -SCREEN_HEIGHT,
<ide> min: 0,
<ide> max: 1,
<ide> type: 'linear',
<ide> extrapolate: true,
<del> round: PixelRatio.get(),
<add> round: PIXEL_RATIO,
<ide> },
<ide> };
<ide>
<ide> var ToTheDown = {
<ide> transformTranslate: {
<ide> from: {x: 0, y: 0, z: 0},
<del> to: {x: 0, y: Dimensions.get('window').height, z: 0},
<add> to: {x: 0, y: SCREEN_HEIGHT, z: 0},
<ide> min: 0,
<ide> max: 1,
<ide> type: 'linear',
<ide> extrapolate: true,
<del> round: PixelRatio.get(),
<add> round: PIXEL_RATIO,
<ide> },
<ide> opacity: {
<ide> value: 1.0,
<ide> type: 'constant',
<ide> },
<ide> translateY: {
<ide> from: 0,
<del> to: Dimensions.get('window').height,
<add> to: SCREEN_HEIGHT,
<ide> min: 0,
<ide> max: 1,
<ide> type: 'linear',
<ide> extrapolate: true,
<del> round: PixelRatio.get(),
<add> round: PIXEL_RATIO,
<ide> },
<ide> };
<ide>
<ide> var FromTheRight = {
<ide> },
<ide>
<ide> transformTranslate: {
<del> from: {x: Dimensions.get('window').width, y: 0, z: 0},
<add> from: {x: SCREEN_WIDTH, y: 0, z: 0},
<ide> to: {x: 0, y: 0, z: 0},
<ide> min: 0,
<ide> max: 1,
<ide> type: 'linear',
<ide> extrapolate: true,
<del> round: PixelRatio.get(),
<add> round: PIXEL_RATIO,
<ide> },
<ide>
<ide> translateX: {
<del> from: Dimensions.get('window').width,
<add> from: SCREEN_WIDTH,
<ide> to: 0,
<ide> min: 0,
<ide> max: 1,
<ide> type: 'linear',
<ide> extrapolate: true,
<del> round: PixelRatio.get(),
<add> round: PIXEL_RATIO,
<ide> },
<ide>
<ide> scaleX: {
<ide> var FromTheLeft = {
<ide> max: 1,
<ide> type: 'linear',
<ide> extrapolate: true,
<del> round: PixelRatio.get(),
<add> round: PIXEL_RATIO,
<ide> },
<ide> translateX: {
<ide> from: -SCREEN_WIDTH,
<ide> var FromTheLeft = {
<ide> max: 1,
<ide> type: 'linear',
<ide> extrapolate: true,
<del> round: PixelRatio.get(),
<add> round: PIXEL_RATIO,
<ide> },
<ide> };
<ide>
<ide> var FromTheDown = {
<ide> max: 1,
<ide> type: 'linear',
<ide> extrapolate: true,
<del> round: PixelRatio.get(),
<add> round: PIXEL_RATIO,
<ide> },
<ide> translateY: {
<ide> from: SCREEN_HEIGHT,
<ide> var FromTheDown = {
<ide> max: 1,
<ide> type: 'linear',
<ide> extrapolate: true,
<del> round: PixelRatio.get(),
<add> round: PIXEL_RATIO,
<ide> },
<ide> };
<ide>
<ide> var FromTheTop = {
<ide> max: 1,
<ide> type: 'linear',
<ide> extrapolate: true,
<del> round: PixelRatio.get(),
<add> round: PIXEL_RATIO,
<ide> },
<ide> translateY: {
<ide> from: -SCREEN_HEIGHT,
<ide> var FromTheTop = {
<ide> max: 1,
<ide> type: 'linear',
<ide> extrapolate: true,
<del> round: PixelRatio.get(),
<add> round: PIXEL_RATIO,
<ide> },
<ide> };
<ide>
<ide> var ToTheBack = {
<ide> max: 1,
<ide> type: 'linear',
<ide> extrapolate: true,
<del> round: PixelRatio.get(),
<add> round: PIXEL_RATIO,
<ide> },
<ide> transformScale: {
<ide> from: {x: 1, y: 1, z: 1},
<ide> var FromTheFront = {
<ide> },
<ide>
<ide> transformTranslate: {
<del> from: {x: 0, y: Dimensions.get('window').height, z: 0},
<add> from: {x: 0, y: SCREEN_HEIGHT, z: 0},
<ide> to: {x: 0, y: 0, z: 0},
<ide> min: 0,
<ide> max: 1,
<ide> type: 'linear',
<ide> extrapolate: true,
<del> round: PixelRatio.get(),
<add> round: PIXEL_RATIO,
<ide> },
<ide> translateY: {
<del> from: Dimensions.get('window').height,
<add> from: SCREEN_HEIGHT,
<ide> to: 0,
<ide> min: 0,
<ide> max: 1,
<ide> type: 'linear',
<ide> extrapolate: true,
<del> round: PixelRatio.get(),
<add> round: PIXEL_RATIO,
<ide> },
<ide> scaleX: {
<ide> value: 1,
<ide> var FromTheFrontAndroid = {
<ide> max: 1,
<ide> type: 'linear',
<ide> extrapolate: true,
<del> round: PixelRatio.get(),
<add> round: PIXEL_RATIO,
<ide> },
<ide> translateY: {
<ide> from: 100,
<ide> var FromTheFrontAndroid = {
<ide> max: 1,
<ide> type: 'linear',
<ide> extrapolate: true,
<del> round: PixelRatio.get(),
<add> round: PIXEL_RATIO,
<ide> },
<ide> };
<ide> | 2 |
Javascript | Javascript | add tabindex attribute to searchbar | 6a828328e17c64a026b447357a619a00f0356425 | <ide><path>website/core/AlgoliaDocSearch.js
<ide> var AlgoliaDocSearch = React.createClass({
<ide> render: function() {
<ide> return (
<ide> <div className="algolia-search-wrapper">
<del> <input id="algolia-doc-search" type="text" placeholder="Search docs..." />
<add> <input id="algolia-doc-search" tabindex="0" type="text" placeholder="Search docs..." />
<ide> </div>
<ide> );
<ide> } | 1 |
Ruby | Ruby | fix a typo in s3service | 993283a1ae9e9c7f07c78c2ac8372a6e91228cc2 | <ide><path>lib/active_storage/service/s3_service.rb
<ide> def initialize(access_key_id:, secret_access_key:, region:, bucket:, endpoint: n
<ide> access_key_id: access_key_id,
<ide> secret_access_key: secret_access_key,
<ide> region: region,
<del> bucket: bucket,
<ide> endpoint: endpoint
<ide> )
<ide> else
<ide> Aws::S3::Resource.new(
<ide> access_key_id: access_key_id,
<ide> secret_access_key: secret_access_key,
<del> region: region,
<del> bucket: bucket
<add> region: region
<ide> )
<ide> end
<ide> | 1 |
Ruby | Ruby | fix some types in schema_test.rb | 7e1328464518e6cd85ab8a3c413bf811c87ffa48 | <ide><path>activeresource/test/cases/base/schema_test.rb
<ide> def teardown
<ide> assert_nothing_raised {
<ide> Person.schema = new_schema
<ide> assert_equal new_schema, Person.schema, "should have saved the schema on the class"
<del> assert_equal new_schema, Person.new.schema, "should have mde the schema available to every instance"
<add> assert_equal new_schema, Person.new.schema, "should have made the schema available to every instance"
<ide> }
<ide> end
<ide>
<ide> def teardown
<ide> new_attr_name_two = :another_new_schema_attribute
<ide> assert Person.schema.blank?, "sanity check - should have a blank class schema"
<ide>
<del> assert !Person.new.respond_do?(new_attr_name), "sanity check - should not respond to the brand-new attribute yet"
<del> assert !Person.new.respond_do?(new_attr_name_two), "sanity check - should not respond to the brand-new attribute yet"
<add> assert !Person.new.respond_to?(new_attr_name), "sanity check - should not respond to the brand-new attribute yet"
<add> assert !Person.new.respond_to?(new_attr_name_two), "sanity check - should not respond to the brand-new attribute yet"
<ide>
<ide> assert_nothing_raised do
<ide> Person.schema = {new_attr_name.to_s => 'string'}
<ide> def teardown
<ide>
<ide> assert Person.schema.blank?, "sanity check - should have a blank class schema"
<ide>
<del> assert !Person.new.respond_do?(new_attr_name), "sanity check - should not respond to the brand-new attribute yet"
<del> assert !Person.new.respond_do?(new_attr_name_two), "sanity check - should not respond to the brand-new attribute yet"
<add> assert !Person.new.respond_to?(new_attr_name), "sanity check - should not respond to the brand-new attribute yet"
<add> assert !Person.new.respond_to?(new_attr_name_two), "sanity check - should not respond to the brand-new attribute yet"
<ide>
<ide> assert_nothing_raised do
<ide> Person.schema { string new_attr_name_two } | 1 |
Python | Python | add the number of sample points as suggested | fa5c5d1d66f7db17cb2bea137b5bb54deccd06b6 | <ide><path>numpy/polynomial/_polybase.py
<ide> def fit(cls, x, y, deg, domain=None, rcond=None, full=False, w=None,
<ide> x : array_like, shape (M,)
<ide> x-coordinates of the M sample points ``(x[i], y[i])``.
<ide> y : array_like, shape (M,)
<del> y-coordinates of the sample points ``(x[i], y[i])``.
<add> y-coordinates of the M sample points ``(x[i], y[i])``.
<ide> deg : int or 1-D array_like
<ide> Degree(s) of the fitting polynomials. If `deg` is a single integer
<ide> all terms up to and including the `deg`'th term are included in the | 1 |
Ruby | Ruby | improve flag passing for debug-symbols | 91065b9ddd24bcc3c279b1b120ec34a2b3810f8b | <ide><path>Library/Homebrew/formula_installer.rb
<ide> def sanitized_argv_options
<ide> args << "--debug" if debug?
<ide> args << "--cc=#{@cc}" if @cc
<ide> args << "--keep-tmp" if keep_tmp?
<del> args << "--debug-symbols" if debug_symbols?
<del> # Avoids dependecy error on flag
<del> args << "--build-from-source" if build_from_source? && debug_symbols?
<add>
<add> if debug_symbols?
<add> args << "--debug-symbols"
<add> args << "--build-from-source"
<add> end
<ide>
<ide> if @env.present?
<ide> args << "--env=#{@env}" | 1 |
PHP | PHP | increment 4.1 version | 1bbb6f16aa03c1de6d89ccbf4ca81bf98e1330ab | <ide><path>src/Illuminate/Foundation/Application.php
<ide> class Application extends Container implements HttpKernelInterface, TerminableIn
<ide> *
<ide> * @var string
<ide> */
<del> const VERSION = '4.1.29';
<add> const VERSION = '4.1.30';
<ide>
<ide> /**
<ide> * Indicates if the application has "booted". | 1 |
PHP | PHP | remove default email for setcc | 8538990434fc9fa425bfee6199ef2316595c4593 | <ide><path>src/Mailer/Email.php
<ide> public function addTo($email, $name = null)
<ide> * @param string|null $name Name
<ide> * @return $this
<ide> */
<del> public function setCc($email = null, $name = null)
<add> public function setCc($email, $name = null)
<ide> {
<ide> return $this->_setEmail('_cc', $email, $name);
<ide> }
<ide><path>src/Mailer/Mailer.php
<ide> * @method array getReturnPath()
<ide> * @method \Cake\Mailer\Email returnPath($email = null, $name = null)
<ide> * @method \Cake\Mailer\Email addTo($email, $name = null)
<del> * @method \Cake\Mailer\Email setCc($email = null, $name = null)
<add> * @method \Cake\Mailer\Email setCc($email, $name = null)
<ide> * @method array getCc()
<ide> * @method \Cake\Mailer\Email cc($email = null, $name = null)
<ide> * @method \Cake\Mailer\Email addCc($email, $name = null) | 2 |
Javascript | Javascript | move buffer constants at the top of net.js | fdae14070cde99d19de2ec03697b3151c1b8cb7f | <ide><path>lib/net.js
<ide> var sys = require("sys");
<ide> var fs = require("fs");
<ide> var events = require("events");
<ide>
<add>var kMinPoolSpace = 128;
<add>var kPoolSize = 40*1024;
<add>
<ide> var debugLevel = process.env['NODE_DEBUG'] ? 1 : 0;
<ide> function debug () {
<ide> if (debugLevel > 0) sys.error.apply(this, arguments);
<ide> var ioWatchers = new FreeList("iowatcher", 100, function () {
<ide> });
<ide>
<ide>
<del>var nb = 0;
<del>var buffers = new FreeList("buffer", 100, function (l) {
<del> return new Buffer(l);
<del>});
<del>
<del>
<ide> // Allocated on demand.
<ide> var pool = null;
<ide> function allocNewPool () {
<del> pool = new Buffer(40*1024);
<add> pool = new Buffer(kPoolSize);
<ide> pool.used = 0;
<ide> }
<ide>
<ide> function initStream (self) {
<ide> self._readWatcher.callback = function () {
<ide> // If this is the first recv (pool doesn't exist) or we've used up
<ide> // most of the pool, allocate a new one.
<del> if (pool) {
<del> if (pool.length - pool.used < 128) {
<del> // discard the old pool. Can't add to the free list because
<del> // users might have refernces to slices on it.
<del> pool = null;
<del> allocNewPool();
<del> }
<del> } else {
<add> if (!pool || pool.length - pool.used < kMinPoolSpace) {
<add> // discard the old pool. Can't add to the free list because
<add> // users might have refernces to slices on it.
<add> pool = null;
<ide> allocNewPool();
<ide> }
<ide>
<ide> function initStream (self) {
<ide> };
<ide> self.readable = false;
<ide>
<del> // queue of buffers that need to be written to socket
<del> // XXX use link list?
<add> // Queue of buffers and string that need to be written to socket.
<ide> self._writeQueue = [];
<ide> self._writeQueueEncoding = [];
<ide>
<ide> Stream.prototype._writeOut = function (data, encoding) {
<ide> } else {
<ide> assert(typeof data == 'string')
<ide>
<del> if (!pool || pool.length - pool.used < 128) {
<add> if (!pool || pool.length - pool.used < kMinPoolSpace) {
<ide> pool = null;
<ide> allocNewPool();
<ide> }
<ide> Stream.prototype.forceClose = function (exception) {
<ide> // pool is shared between sockets, so don't need to free it here.
<ide> var self = this;
<ide>
<del> var b;
<del> while (this._writeQueue.length) {
<del> b = this._writeQueue.shift();
<del> if (b instanceof Buffer) buffers.free(b);
<del> }
<add> // TODO would like to set _writeQueue to null to avoid extra object alloc,
<add> // but lots of code assumes this._writeQueue is always an array.
<add> this._writeQueue = [];
<ide>
<ide> if (this._writeWatcher) {
<ide> this._writeWatcher.stop(); | 1 |
PHP | PHP | apply fixes from styleci | 7a0318ca268d8c60c37e156a601bf843d8864c55 | <ide><path>src/Illuminate/Queue/DatabaseQueue.php
<ide>
<ide> namespace Illuminate\Queue;
<ide>
<del>use DateTime;
<ide> use Carbon\Carbon;
<ide> use Illuminate\Database\Connection;
<ide> use Illuminate\Queue\Jobs\DatabaseJob; | 1 |
Ruby | Ruby | use the body proxy to freeze headers | 3df07d093a1e4207caa63fd2e3b67599211f5800 | <ide><path>actionpack/lib/action_controller/metal/live.rb
<ide> def write(string)
<ide> end
<ide>
<ide> def each
<add> @response.sending!
<ide> while str = @buf.pop
<ide> yield str
<ide> end
<add> @response.sent!
<ide> end
<ide>
<ide> def close
<ide> def to_hash
<ide>
<ide> private
<ide>
<del> def finalize_response
<add> def before_committed
<ide> super
<ide> jar = request.cookie_jar
<ide> # The response can be committed multiple times
<ide> jar.write self unless committed?
<del> jar.commit!
<add> end
<add>
<add> def before_sending
<add> super
<add> request.cookie_jar.commit!
<ide> headers.freeze
<ide> end
<ide>
<ide><path>actionpack/lib/action_controller/test_case.rb
<ide> def process(action, http_method = 'GET', *args)
<ide> @controller.process(name)
<ide>
<ide> if cookies = @request.env['action_dispatch.cookies']
<del> unless cookies.committed?
<add> unless @response.committed?
<ide> cookies.write(@response)
<ide> end
<ide> end
<ide><path>actionpack/lib/action_dispatch/http/response.rb
<ide> def write(string)
<ide> end
<ide>
<ide> def each(&block)
<del> @buf.each(&block)
<add> @response.sending!
<add> x = @buf.each(&block)
<add> @response.sent!
<add> x
<ide> end
<ide>
<ide> def close
<ide> def initialize(status = 200, header = {}, body = [])
<ide> @blank = false
<ide> @cv = new_cond
<ide> @committed = false
<add> @sending = false
<add> @sent = false
<ide> @content_type = nil
<ide> @charset = nil
<ide>
<ide> def await_commit
<ide> end
<ide> end
<ide>
<add> def await_sent
<add> synchronize { @cv.wait_until { @sent } }
<add> end
<add>
<ide> def commit!
<ide> synchronize do
<del> finalize_response
<add> before_committed
<ide> @committed = true
<ide> @cv.broadcast
<ide> end
<ide> end
<ide>
<del> def committed?
<del> @committed
<add> def sending!
<add> synchronize do
<add> before_sending
<add> @sending = true
<add> @cv.broadcast
<add> end
<ide> end
<ide>
<add> def sent!
<add> synchronize do
<add> @sent = true
<add> @cv.broadcast
<add> end
<add> end
<add>
<add> def sending?; synchronize { @sending }; end
<add> def committed?; synchronize { @committed }; end
<add> def sent?; synchronize { @sent }; end
<add>
<ide> # Sets the HTTP status code.
<ide> def status=(status)
<ide> @status = Rack::Utils.status_code(status)
<ide> def cookies
<ide>
<ide> private
<ide>
<del> def finalize_response
<add> def before_committed
<add> end
<add>
<add> def before_sending
<ide> end
<ide>
<ide> def merge_default_headers(original, default)
<ide><path>actionpack/test/controller/live_stream_test.rb
<ide> def sse_with_id
<ide> tests SSETestController
<ide>
<ide> def wait_for_response_stream_close
<del> response.stream.await_close
<add> response.body
<ide> end
<ide>
<ide> def test_basic_sse
<ide> def exception_in_exception_callback
<ide> tests TestController
<ide>
<ide> def assert_stream_closed
<del> response.stream.await_close
<ide> assert response.stream.closed?, 'stream should be closed'
<add> assert response.sent?, 'stream should be sent'
<ide> end
<ide>
<ide> def capture_log_output
<ide> def test_async_stream
<ide> @controller.response = @response
<ide>
<ide> t = Thread.new(@response) { |resp|
<add> resp.await_commit
<ide> resp.stream.each do |part|
<ide> assert_equal parts.shift, part
<ide> ol = @controller.latch
<ide> def test_exception_handling_html
<ide> assert_raises(ActionView::MissingTemplate) do
<ide> get :exception_in_view
<ide> end
<add> assert response.body
<ide> assert_stream_closed
<ide> end
<ide>
<ide><path>actionpack/test/dispatch/live_response_test.rb
<ide> def test_parallel
<ide> @response.stream.close
<ide> }
<ide>
<add> @response.await_commit
<ide> @response.each do |part|
<ide> assert_equal 'foo', part
<ide> latch.release
<ide> def test_content_length_is_removed
<ide> assert_nil @response.headers['Content-Length']
<ide> end
<ide>
<del> def test_headers_cannot_be_written_after_write
<add> def test_headers_cannot_be_written_after_webserver_reads
<ide> @response.stream.write 'omg'
<add> latch = ActiveSupport::Concurrency::Latch.new
<ide>
<add> t = Thread.new {
<add> @response.stream.each do |chunk|
<add> latch.release
<add> end
<add> }
<add>
<add> latch.await
<ide> assert @response.headers.frozen?
<ide> e = assert_raises(ActionDispatch::IllegalStateError) do
<ide> @response.headers['Content-Length'] = "zomg"
<ide> end
<ide>
<ide> assert_equal 'header already sent', e.message
<add> @response.stream.close
<add> t.join
<ide> end
<ide>
<ide> def test_headers_cannot_be_written_after_close
<ide> @response.stream.close
<ide>
<del> assert @response.headers.frozen?
<ide> e = assert_raises(ActionDispatch::IllegalStateError) do
<ide> @response.headers['Content-Length'] = "zomg"
<ide> end | 5 |
PHP | PHP | fix typos in doc blocks | 838c5fd086ebec1eb0fd0575bf6ec5df9fede920 | <ide><path>src/Database/Expression/Comparison.php
<ide> class Comparison implements ExpressionInterface, FieldInterface
<ide> protected $_operator;
<ide>
<ide> /**
<del> * Whether or not the value in this expressions is a traversable
<add> * Whether or not the value in this expression is a traversable
<ide> *
<ide> * @var bool
<ide> */
<ide> protected function _flattenValue($value, $generator, $type = 'string')
<ide> }
<ide>
<ide> /**
<del> * Returns an array with the original $values in the first poisition
<add> * Returns an array with the original $values in the first position
<ide> * and all ExpressionInterface objects that could be found in the second
<ide> * position.
<ide> *
<ide><path>src/Database/Type/ExpressionTypeCasterTrait.php
<ide> trait ExpressionTypeCasterTrait
<ide>
<ide> /**
<ide> * Conditionally converts the passed value to an ExpressionInterface object
<del> * if the type class implementes the ExpressionTypeInterface. Otherwise,
<add> * if the type class implements the ExpressionTypeInterface. Otherwise,
<ide> * returns the value unmodified.
<ide> *
<ide> * @param mixed $value The value to converto to ExpressionInterface
<ide><path>src/Database/ValueBinder.php
<ide> public function placeholder($token)
<ide>
<ide> /**
<ide> * Creates unique named placeholders for each of the passed values
<del> * and binds them with the specifed type.
<add> * and binds them with the specified type.
<ide> *
<ide> * @param array|Traversable $values The list of values to be bound
<del> * @param string $type The type with wich all values will be bound
<del> * @return array with the placeholders to put in the query
<add> * @param string $type The type with which all values will be bound
<add> * @return array with the placeholders to insert in the query
<ide> */
<ide> public function generateManyNamed($values, $type = 'string')
<ide> { | 3 |
Go | Go | move legacy stuff outside the job | 16ca6a1c12ffe9a02da4e823646bee6461ffbad5 | <ide><path>api.go
<ide> import (
<ide> "fmt"
<ide> "github.com/dotcloud/docker/archive"
<ide> "github.com/dotcloud/docker/auth"
<add> "github.com/dotcloud/docker/engine"
<ide> "github.com/dotcloud/docker/pkg/systemd"
<ide> "github.com/dotcloud/docker/utils"
<ide> "github.com/gorilla/mux"
<ide> func getImagesJSON(srv *Server, version float64, w http.ResponseWriter, r *http.
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<del> job := srv.Eng.Job("images")
<add>
<add> var (
<add> buffer *bytes.Buffer
<add> job = srv.Eng.Job("images")
<add> )
<add>
<ide> job.Setenv("filter", r.Form.Get("filter"))
<ide> job.Setenv("all", r.Form.Get("all"))
<del> job.SetenvBool("list", version <= 1.8)
<del> job.SetenvBool("legacy", version <= 1.7)
<del> job.Stdout.Add(w)
<del> w.WriteHeader(http.StatusOK)
<add>
<add> if version >= 1.9 {
<add> job.Stdout.Add(w)
<add> } else {
<add> buffer = bytes.NewBuffer(nil)
<add> job.Stdout.Add(buffer)
<add> }
<add>
<ide> if err := job.Run(); err != nil {
<ide> return err
<ide> }
<add>
<add> if version < 1.9 { // Send as a valide JSON array
<add> outs := engine.NewTable("Created", 0)
<add> if _, err := outs.ReadFrom(buffer); err != nil {
<add> return err
<add> }
<add> if version < 1.8 { // Convert to legacy format
<add> outsLegacy := engine.NewTable("Created", 0)
<add> for _, out := range outs.Data {
<add> for _, repoTag := range out.GetList("RepoTags") {
<add> parts := strings.Split(repoTag, ":")
<add> outLegacy := &engine.Env{}
<add> outLegacy.Set("Repository", parts[0])
<add> outLegacy.Set("Tag", parts[1])
<add> outLegacy.Set("ID", out.Get("ID"))
<add> outLegacy.SetInt64("Created", out.GetInt64("Created"))
<add> outLegacy.SetInt64("Size", out.GetInt64("Size"))
<add> outLegacy.SetInt64("VirtualSize", out.GetInt64("VirtualSize"))
<add> outsLegacy.Add(outLegacy)
<add> }
<add> }
<add> if _, err := outsLegacy.WriteListTo(w); err != nil {
<add> return err
<add> }
<add> } else if _, err := outs.WriteListTo(w); err != nil {
<add> return err
<add> }
<add> }
<add>
<ide> return nil
<ide> }
<ide>
<ide><path>engine/table_test.go
<ide> package engine
<ide>
<ide> import (
<del> "testing"
<ide> "bytes"
<ide> "encoding/json"
<add> "testing"
<ide> )
<ide>
<ide> func TestTableWriteTo(t *testing.T) {
<ide> func TestTableWriteTo(t *testing.T) {
<ide> if err := json.Unmarshal(buf.Bytes(), &output); err != nil {
<ide> t.Fatal(err)
<ide> }
<del> if len(output) != 1 {
<add> if len(output) != 1 {
<ide> t.Fatalf("Incorrect output: %v", output)
<ide> }
<ide> if val, exists := output["foo"]; !exists || val != "bar" {
<ide><path>registry/registry.go
<ide> func pingRegistryEndpoint(endpoint string) (bool, error) {
<ide> // versions of the registry
<ide> if standalone == "" {
<ide> return true, nil
<del> // Accepted values are "true" (case-insensitive) and "1".
<add> // Accepted values are "true" (case-insensitive) and "1".
<ide> } else if strings.EqualFold(standalone, "true") || standalone == "1" {
<ide> return true, nil
<ide> }
<ide><path>server.go
<ide> func (srv *Server) Images(job *engine.Job) engine.Status {
<ide> }
<ide>
<ide> if out, exists := lookup[id]; exists {
<del> if job.GetenvBool("legacy") {
<del> out2 := &engine.Env{}
<del> out2.Set("Repository", name)
<del> out2.Set("Tag", tag)
<del> out2.Set("ID", out.Get("ID"))
<del> out2.SetInt64("Created", out.GetInt64("Created"))
<del> out2.SetInt64("Size", out.GetInt64("Size"))
<del> out2.SetInt64("VirtualSize", out.GetInt64("VirtualSize"))
<del> } else {
<del> out.SetList("RepoTags", append(out.GetList("RepoTags"), fmt.Sprintf("%s:%s", name, tag)))
<del> }
<add> out.SetList("RepoTags", append(out.GetList("RepoTags"), fmt.Sprintf("%s:%s", name, tag)))
<ide> } else {
<ide> out := &engine.Env{}
<ide> delete(allImages, id)
<del> if job.GetenvBool("legacy") {
<del> out.Set("Repository", name)
<del> out.Set("Tag", tag)
<del> } else {
<del> out.Set("ParentId", image.Parent)
<del> out.SetList("RepoTags", []string{fmt.Sprintf("%s:%s", name, tag)})
<del> }
<add> out.Set("ParentId", image.Parent)
<add> out.SetList("RepoTags", []string{fmt.Sprintf("%s:%s", name, tag)})
<ide> out.Set("ID", image.ID)
<ide> out.SetInt64("Created", image.Created.Unix())
<ide> out.SetInt64("Size", image.Size)
<ide> func (srv *Server) Images(job *engine.Job) engine.Status {
<ide> if job.Getenv("filter") == "" {
<ide> for _, image := range allImages {
<ide> out := &engine.Env{}
<del> if job.GetenvBool("legacy") {
<del> out.Set("Repository", "<none>")
<del> out.Set("Tag", "<none>")
<del> } else {
<del> out.Set("ParentId", image.Parent)
<del> out.SetList("RepoTags", []string{"<none>:<none>"})
<del> }
<add> out.Set("ParentId", image.Parent)
<add> out.SetList("RepoTags", []string{"<none>:<none>"})
<ide> out.Set("ID", image.ID)
<ide> out.SetInt64("Created", image.Created.Unix())
<ide> out.SetInt64("Size", image.Size)
<ide> func (srv *Server) Images(job *engine.Job) engine.Status {
<ide> }
<ide>
<ide> outs.ReverseSort()
<del> if job.GetenvBool("list") {
<del> if _, err := outs.WriteListTo(job.Stdout); err != nil {
<del> job.Errorf("%s", err)
<del> return engine.StatusErr
<del> }
<del> } else if _, err := outs.WriteTo(job.Stdout); err != nil {
<add> if _, err := outs.WriteTo(job.Stdout); err != nil {
<ide> job.Errorf("%s", err)
<ide> return engine.StatusErr
<ide> }
<ide><path>vendor/src/github.com/gorilla/context/context.go
<ide> func Purge(maxAge int) int {
<ide> datat = make(map[*http.Request]int64)
<ide> } else {
<ide> min := time.Now().Unix() - int64(maxAge)
<del> for r, _ := range data {
<add> for r := range data {
<ide> if datat[r] < min {
<ide> clear(r)
<ide> count++
<ide><path>vendor/src/github.com/gorilla/mux/old_test.go
<ide> func TestRouteMatchers(t *testing.T) {
<ide> method = "GET"
<ide> headers = map[string]string{"X-Requested-With": "XMLHttpRequest"}
<ide> resultVars = map[bool]map[string]string{
<del> true: map[string]string{"var1": "www", "var2": "product", "var3": "42"},
<del> false: map[string]string{},
<add> true: {"var1": "www", "var2": "product", "var3": "42"},
<add> false: {},
<ide> }
<ide> }
<ide>
<ide> func TestRouteMatchers(t *testing.T) {
<ide> method = "POST"
<ide> headers = map[string]string{"Content-Type": "application/json"}
<ide> resultVars = map[bool]map[string]string{
<del> true: map[string]string{"var4": "google", "var5": "product", "var6": "42"},
<del> false: map[string]string{},
<add> true: {"var4": "google", "var5": "product", "var6": "42"},
<add> false: {},
<ide> }
<ide> }
<ide> | 6 |
Java | Java | fix minor test issues | 497944f0dd9a9cb49b5f41397cb41a07a67eaf25 | <ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/broker/DefaultSubscriptionRegistryTests.java
<ide> public void unregisterSubscription() {
<ide>
<ide> MultiValueMap<String, String> actual = this.registry.findSubscriptions(message(dest));
<ide>
<del> assertEquals("Expected three elements " + actual, 2, actual.size());
<add> assertEquals("Expected two elements: " + actual, 2, actual.size());
<ide> assertEquals(subscriptionIds, sort(actual.get(sessIds.get(1))));
<ide> assertEquals(subscriptionIds, sort(actual.get(sessIds.get(2))));
<ide> }
<ide> public void unregisterAllSubscriptions() {
<ide>
<ide> MultiValueMap<String, String> actual = this.registry.findSubscriptions(message(dest));
<ide>
<del> assertEquals("Expected three elements " + actual, 1, actual.size());
<add> assertEquals("Expected one element: " + actual, 1, actual.size());
<ide> assertEquals(subscriptionIds, sort(actual.get(sessIds.get(2))));
<ide> }
<ide>
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/broker/SimpleBrokerMessageHandlerTests.java
<ide> /*
<del> * Copyright 2002-2014 the original author or authors.
<add> * Copyright 2002-2015 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> package org.springframework.messaging.simp.broker;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertTrue;
<ide> import static org.mockito.Mockito.times;
<ide> import static org.mockito.Mockito.verify;
<ide>
<ide> public void subcribePublish() {
<ide> this.messageHandler.handleMessage(createMessage("/bar", "message2"));
<ide>
<ide> verify(this.clientOutboundChannel, times(6)).send(this.messageCaptor.capture());
<del> assertCapturedMessage("sess1", "sub1", "/foo");
<del> assertCapturedMessage("sess1", "sub2", "/foo");
<del> assertCapturedMessage("sess2", "sub1", "/foo");
<del> assertCapturedMessage("sess2", "sub2", "/foo");
<del> assertCapturedMessage("sess1", "sub3", "/bar");
<del> assertCapturedMessage("sess2", "sub3", "/bar");
<add> assertTrue(messageCaptured("sess1", "sub1", "/foo"));
<add> assertTrue(messageCaptured("sess1", "sub2", "/foo"));
<add> assertTrue(messageCaptured("sess2", "sub1", "/foo"));
<add> assertTrue(messageCaptured("sess2", "sub2", "/foo"));
<add> assertTrue(messageCaptured("sess1", "sub3", "/bar"));
<add> assertTrue(messageCaptured("sess2", "sub3", "/bar"));
<ide> }
<ide>
<ide> @Test
<ide> public void subcribeDisconnectPublish() {
<ide> assertEquals(sess1, SimpMessageHeaderAccessor.getSessionId(captured.getHeaders()));
<ide> assertEquals("joe", SimpMessageHeaderAccessor.getUser(captured.getHeaders()).getName());
<ide>
<del> assertCapturedMessage(sess2, "sub1", "/foo");
<del> assertCapturedMessage(sess2, "sub2", "/foo");
<del> assertCapturedMessage(sess2, "sub3", "/bar");
<add> assertTrue(messageCaptured(sess2, "sub1", "/foo"));
<add> assertTrue(messageCaptured(sess2, "sub2", "/foo"));
<add> assertTrue(messageCaptured(sess2, "sub3", "/bar"));
<ide> }
<ide>
<ide> @Test
<ide> public void connect() {
<ide> }
<ide>
<ide>
<del> protected Message<String> createSubscriptionMessage(String sessionId, String subcriptionId, String destination) {
<add> private Message<String> createSubscriptionMessage(String sessionId, String subcriptionId, String destination) {
<ide> SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.SUBSCRIBE);
<ide> headers.setSubscriptionId(subcriptionId);
<ide> headers.setDestination(destination);
<ide> headers.setSessionId(sessionId);
<ide> return MessageBuilder.createMessage("", headers.getMessageHeaders());
<ide> }
<ide>
<del> protected Message<String> createConnectMessage(String sessionId) {
<add> private Message<String> createConnectMessage(String sessionId) {
<ide> SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT);
<ide> headers.setSessionId(sessionId);
<ide> headers.setUser(new TestPrincipal("joe"));
<ide> return MessageBuilder.createMessage("", headers.getMessageHeaders());
<ide> }
<ide>
<del> protected Message<String> createMessage(String destination, String payload) {
<add> private Message<String> createMessage(String destination, String payload) {
<ide> SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
<ide> headers.setDestination(destination);
<ide> return MessageBuilder.createMessage("", headers.getMessageHeaders());
<ide> }
<ide>
<del> protected boolean assertCapturedMessage(String sessionId, String subcriptionId, String destination) {
<add> private boolean messageCaptured(String sessionId, String subcriptionId, String destination) {
<ide> for (Message<?> message : this.messageCaptor.getAllValues()) {
<ide> SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
<ide> if (sessionId.equals(headers.getSessionId())) { | 2 |
Go | Go | fix config.cpuset from api < 1.20 | 8c63ce4f6b78bd1d87c92ecfbcc20ccfd80f7d63 | <ide><path>api/types/versions/v1p19/types.go
<ide> type ContainerConfig struct {
<ide> Memory int64
<ide> MemorySwap int64
<ide> CPUShares int64 `json:"CpuShares"`
<del> CPUSet string `json:"CpuSet"`
<add> CPUSet string `json:"Cpuset"`
<ide> }
<ide><path>api/types/versions/v1p20/types.go
<ide> type ContainerJSON struct {
<ide> // ContainerConfig is a backcompatibility struct used in ContainerJSON for the API 1.20
<ide> type ContainerConfig struct {
<ide> *runconfig.Config
<del> // backward compatibility, it lives now in HostConfig
<add>
<add> // backward compatibility, they now live in HostConfig
<ide> VolumeDriver string
<ide> }
<ide>
<ide><path>integration-cli/docker_api_inspect_unix_test.go
<add>// +build !windows
<add>
<add>package main
<add>
<add>import (
<add> "encoding/json"
<add> "fmt"
<add> "net/http"
<add>
<add> "github.com/go-check/check"
<add>)
<add>
<add>// #16665
<add>func (s *DockerSuite) TestInspectApiCpusetInConfigPre120(c *check.C) {
<add> testRequires(c, DaemonIsLinux)
<add> testRequires(c, cgroupCpuset)
<add>
<add> name := "cpusetinconfig-pre120"
<add> dockerCmd(c, "run", "--name", name, "--cpuset", "0-1", "busybox", "true")
<add>
<add> status, body, err := sockRequest("GET", fmt.Sprintf("/v1.19/containers/%s/json", name), nil)
<add> c.Assert(status, check.Equals, http.StatusOK)
<add> c.Assert(err, check.IsNil)
<add>
<add> var inspectJSON map[string]interface{}
<add> if err = json.Unmarshal(body, &inspectJSON); err != nil {
<add> c.Fatalf("unable to unmarshal body for version 1.19: %v", err)
<add> }
<add>
<add> config, ok := inspectJSON["Config"]
<add> if !ok {
<add> c.Fatal("Unable to find 'Config'")
<add> }
<add> cfg := config.(map[string]interface{})
<add> if _, ok := cfg["Cpuset"]; !ok {
<add> c.Fatal("Api version 1.19 expected to include Cpuset in 'Config'")
<add> }
<add>}
<ide><path>integration-cli/docker_cli_kill_test.go
<ide> func (s *DockerSuite) TestKillWithInvalidSignal(c *check.C) {
<ide> }
<ide> }
<ide>
<del>func (s *DockerSuite) TestKillofStoppedContainerAPIPre120(c *check.C) {
<add>func (s *DockerSuite) TestKillStoppedContainerAPIPre120(c *check.C) {
<ide> testRequires(c, DaemonIsLinux)
<ide> dockerCmd(c, "run", "--name", "docker-kill-test-api", "-d", "busybox", "top")
<ide> dockerCmd(c, "stop", "docker-kill-test-api") | 4 |
Python | Python | allow specification of terms to fit in chebfit | 942f294c06b0285ea3cf2bf223a63700a1ed50f5 | <ide><path>numpy/polynomial/chebyshev.py
<ide> def chebfit(x, y, deg, rcond=None, full=False, w=None):
<ide> y-coordinates of the sample points. Several data sets of sample
<ide> points sharing the same x-coordinates can be fitted at once by
<ide> passing in a 2D-array that contains one dataset per column.
<del> deg : int
<del> Degree of the fitting series
<add> deg : int or array_like
<add> Degree of the fitting series. If `deg` is a single integer
<add> all terms up to and including the `deg`'th term are included.
<add> `deg` may alternatively be a list or array specifying which
<add> terms in the Legendre expansion to include in the fit.
<add>
<add> .. versionchanged:: 1.11.0
<add> `deg` may be a list specifying which terms to fit
<ide> rcond : float, optional
<ide> Relative condition number of the fit. Singular values smaller than
<ide> this relative to the largest singular value will be ignored. The
<ide> def chebfit(x, y, deg, rcond=None, full=False, w=None):
<ide> --------
<ide>
<ide> """
<del> order = int(deg) + 1
<ide> x = np.asarray(x) + 0.0
<ide> y = np.asarray(y) + 0.0
<add> deg = np.asarray([deg,], dtype=int).flatten()
<ide>
<ide> # check arguments.
<del> if deg < 0:
<add> if deg.size < 1:
<add> raise TypeError("expected deg to be one or more integers")
<add> if deg.min() < 0:
<ide> raise ValueError("expected deg >= 0")
<ide> if x.ndim != 1:
<ide> raise TypeError("expected 1D vector for x")
<ide> def chebfit(x, y, deg, rcond=None, full=False, w=None):
<ide> if len(x) != len(y):
<ide> raise TypeError("expected x and y to have same length")
<ide>
<add> if deg.size == 1:
<add> restricted_fit = False
<add> lmax = deg[0]
<add> order = lmax + 1
<add> else:
<add> restricted_fit = True
<add> lmax = deg.max()
<add> order = deg.size
<add>
<ide> # set up the least squares matrices in transposed form
<del> lhs = chebvander(x, deg).T
<add> van = chebvander(x, lmax)
<add> if restricted_fit:
<add> van = van[:, deg]
<add> lhs = van.T
<ide> rhs = y.T
<ide> if w is not None:
<ide> w = np.asarray(w) + 0.0
<ide> def chebfit(x, y, deg, rcond=None, full=False, w=None):
<ide> c, resids, rank, s = la.lstsq(lhs.T/scl, rhs.T, rcond)
<ide> c = (c.T/scl).T
<ide>
<add> # Expand c to include non-fitted coefficients which are set to zero
<add> if restricted_fit:
<add> if c.ndim == 2:
<add> cc = np.zeros((lmax+1, c.shape[1]), dtype=c.dtype)
<add> else:
<add> cc = np.zeros(lmax+1, dtype=c.dtype)
<add> cc[deg] = c
<add> c = cc
<add>
<ide> # warn on rank reduction
<ide> if rank != order and not full:
<ide> msg = "The fit may be poorly conditioned" | 1 |
PHP | PHP | apply fixes from styleci | 1242c57e64b1ab37096cca4d3b57e621d662ecf2 | <ide><path>tests/View/Blade/BladeComponentTagCompilerTest.php
<ide>
<ide> class BladeComponentTagCompilerTest extends AbstractBladeTestCase
<ide> {
<del> public function tearDown() : void
<add> public function tearDown(): void
<ide> {
<ide> Mockery::close();
<ide> } | 1 |
Ruby | Ruby | make linkapps official | 907ac79606537189a0a7c822be1210c4d4801df3 | <ide><path>Library/Contributions/cmd/brew-linkapps.rb
<del># Links any Applications (.app) found in installed prefixes to /Applications
<del>require 'keg'
<del>
<del>TARGET_DIR = ARGV.include?("--local") ? File.expand_path("~/Applications") : "/Applications"
<del>
<del>unless File.exist? TARGET_DIR
<del> opoo "#{TARGET_DIR} does not exist, stopping."
<del> puts "Run `mkdir #{TARGET_DIR}` first."
<del> exit 1
<del>end
<del>
<del>HOMEBREW_CELLAR.subdirs.each do |rack|
<del> kegs = rack.subdirs.map { |d| Keg.new(d) }
<del> next if kegs.empty?
<del>
<del> keg = kegs.detect(&:linked?) || kegs.max {|a,b| a.version <=> b.version}
<del>
<del> Dir["#{keg}/*.app", "#{keg}/bin/*.app", "#{keg}/libexec/*.app"].each do |app|
<del> puts "Linking #{app}"
<del> app_name = File.basename(app)
<del> target = "#{TARGET_DIR}/#{app_name}"
<del>
<del> if File.exist?(target) && !File.symlink?(target)
<del> onoe "#{target} already exists, skipping."
<del> next
<del> end
<del> system "ln", "-sf", app, TARGET_DIR
<del> end
<del>end
<del>
<del>puts "Finished linking. Find the links under #{TARGET_DIR}."
<ide><path>Library/Homebrew/cmd/linkapps.rb
<add># Links any Applications (.app) found in installed prefixes to /Applications
<add>require 'keg'
<add>
<add>module Homebrew extend self
<add>
<add> def linkapps
<add> target_dir = ARGV.include?("--local") ? File.expand_path("~/Applications") : "/Applications"
<add>
<add> unless File.exist? target_dir
<add> opoo "#{target_dir} does not exist, stopping."
<add> puts "Run `mkdir #{target_dir}` first."
<add> exit 1
<add> end
<add>
<add> HOMEBREW_CELLAR.subdirs.each do |rack|
<add> kegs = rack.subdirs.map { |d| Keg.new(d) }
<add> next if kegs.empty?
<add>
<add> keg = kegs.detect(&:linked?) || kegs.max {|a,b| a.version <=> b.version}
<add>
<add> Dir["#{keg}/*.app", "#{keg}/bin/*.app", "#{keg}/libexec/*.app"].each do |app|
<add> puts "Linking #{app}"
<add> app_name = File.basename(app)
<add> target = "#{target_dir}/#{app_name}"
<add>
<add> if File.exist?(target) && !File.symlink?(target)
<add> onoe "#{target} already exists, skipping."
<add> next
<add> end
<add> system "ln", "-sf", app, target_dir
<add> end
<add> end
<add>
<add> puts "Finished linking. Find the links under #{target_dir}."
<add> end
<add>end | 2 |
Javascript | Javascript | run all the tests 😸 | 955d5a02e4c72310ac82a26421c3d2bffbaae067 | <ide><path>karma.conf.js
<ide> module.exports = function(config) {
<ide> if (runAll || process.env.SAUCE_IE) {
<ide> // TODO These need to be fixed
<ide> // customLaunchers.SL_IE8 = createCustomLauncher('internet explorer', 8, 'Windows 7');
<del> customLaunchers.SL_IE9 = createCustomLauncher('internet explorer', 9, 'Windows 2008');
<add> // customLaunchers.SL_IE9 = createCustomLauncher('internet explorer', 9, 'Windows 2008');
<ide> customLaunchers.SL_IE10 = createCustomLauncher('internet explorer', 10, 'Windows 2012');
<ide> customLaunchers.SL_IE11 = createCustomLauncher('internet explorer', 11, 'Windows 8.1');
<ide> }
<ide><path>test/specs/interceptors.spec.js
<ide> describe('interceptors', function () {
<ide> });
<ide> });
<ide>
<del> fit('should add a request interceptor that returns a promise', function (done) {
<add> it('should add a request interceptor that returns a promise', function (done) {
<ide> axios.interceptors.request.use(function (config) {
<ide> return new Promise(function (resolve) {
<ide> // do something async | 2 |
Mixed | Go | add support for reading logs extra attrs | bd9d14a07b9f1c82625dc8483245caf3fa7fe9e6 | <ide><path>api/client/logs.go
<ide> func (cli *DockerCli) CmdLogs(args ...string) error {
<ide> follow := cmd.Bool([]string{"f", "-follow"}, false, "Follow log output")
<ide> since := cmd.String([]string{"-since"}, "", "Show logs since timestamp")
<ide> times := cmd.Bool([]string{"t", "-timestamps"}, false, "Show timestamps")
<add> details := cmd.Bool([]string{"-details"}, false, "Show extra details provided to logs")
<ide> tail := cmd.String([]string{"-tail"}, "all", "Number of lines to show from the end of the logs")
<ide> cmd.Require(flag.Exact, 1)
<ide>
<ide> func (cli *DockerCli) CmdLogs(args ...string) error {
<ide> Timestamps: *times,
<ide> Follow: *follow,
<ide> Tail: *tail,
<add> Details: *details,
<ide> }
<ide> responseBody, err := cli.client.ContainerLogs(context.Background(), name, options)
<ide> if err != nil {
<ide><path>api/server/router/container/container_routes.go
<ide> func (s *containerRouter) getContainersLogs(ctx context.Context, w http.Response
<ide> Tail: r.Form.Get("tail"),
<ide> ShowStdout: stdout,
<ide> ShowStderr: stderr,
<add> Details: httputils.BoolValue(r, "details"),
<ide> },
<ide> OutStream: w,
<ide> }
<ide><path>daemon/logger/jsonfilelog/read.go
<ide> func decodeLogLine(dec *json.Decoder, l *jsonlog.JSONLog) (*logger.Message, erro
<ide> Source: l.Stream,
<ide> Timestamp: l.Created,
<ide> Line: []byte(l.Log),
<add> Attrs: l.Attrs,
<ide> }
<ide> return msg, nil
<ide> }
<ide><path>daemon/logger/logger.go
<ide> package logger
<ide>
<ide> import (
<ide> "errors"
<add> "sort"
<add> "strings"
<ide> "time"
<ide>
<ide> "github.com/docker/docker/pkg/jsonlog"
<ide> type Message struct {
<ide> Line []byte
<ide> Source string
<ide> Timestamp time.Time
<add> Attrs LogAttributes
<add>}
<add>
<add>// LogAttributes is used to hold the extra attributes available in the log message
<add>// Primarily used for converting the map type to string and sorting.
<add>type LogAttributes map[string]string
<add>type byKey []string
<add>
<add>func (s byKey) Len() int { return len(s) }
<add>func (s byKey) Less(i, j int) bool {
<add> keyI := strings.Split(s[i], "=")
<add> keyJ := strings.Split(s[j], "=")
<add> return keyI[0] < keyJ[0]
<add>}
<add>func (s byKey) Swap(i, j int) {
<add> s[i], s[j] = s[j], s[i]
<add>}
<add>
<add>func (a LogAttributes) String() string {
<add> var ss byKey
<add> for k, v := range a {
<add> ss = append(ss, k+"="+v)
<add> }
<add> sort.Sort(ss)
<add> return strings.Join(ss, ",")
<ide> }
<ide>
<ide> // Logger is the interface for docker logging drivers.
<ide><path>daemon/logs.go
<ide> func (daemon *Daemon) ContainerLogs(ctx context.Context, containerName string, c
<ide> return nil
<ide> }
<ide> logLine := msg.Line
<add> if config.Details {
<add> logLine = append([]byte(msg.Attrs.String()+" "), logLine...)
<add> }
<ide> if config.Timestamps {
<ide> logLine = append([]byte(msg.Timestamp.Format(logger.TimeFormat)+" "), logLine...)
<ide> }
<ide><path>docs/reference/api/docker_remote_api.md
<ide> This section lists each version from latest to oldest. Each listing includes a
<ide> * `POST /auth` now returns an `IdentityToken` when supported by a registry.
<ide> * `POST /containers/create` with both `Hostname` and `Domainname` fields specified will result in the container's hostname being set to `Hostname`, rather than `Hostname.Domainname`.
<ide> * `GET /volumes` now supports more filters, new added filters are `name` and `driver`.
<add>* `GET /containers/(id or name)/logs` now accepts a `details` query parameter to stream the extra attributes that were provided to the containers `LogOpts`, such as environment variables and labels, with the logs.
<ide>
<ide> ### v1.22 API changes
<ide>
<ide><path>docs/reference/api/docker_remote_api_v1.24.md
<ide> Get `stdout` and `stderr` logs from the container ``id``
<ide>
<ide> Query Parameters:
<ide>
<add>- **details** - 1/True/true or 0/False/flase, Show extra details provided to logs. Default `false`.
<ide> - **follow** – 1/True/true or 0/False/false, return stream. Default `false`.
<ide> - **stdout** – 1/True/true or 0/False/false, show `stdout` log. Default `false`.
<ide> - **stderr** – 1/True/true or 0/False/false, show `stderr` log. Default `false`.
<ide><path>docs/reference/commandline/logs.md
<ide> parent = "smn_cli"
<ide>
<ide> Fetch the logs of a container
<ide>
<add> --details Show extra details provided to logs
<ide> -f, --follow Follow log output
<ide> --help Print usage
<ide> --since="" Show logs since timestamp
<ide> The `docker logs --timestamps` command will add an [RFC3339Nano timestamp](https
<ide> log entry. To ensure that the timestamps are aligned the
<ide> nano-second part of the timestamp will be padded with zero when necessary.
<ide>
<add>The `docker logs --details` command will add on extra attributes, such as
<add>environment variables and labels, provided to `--log-opt` when creating the
<add>container.
<add>
<ide> The `--since` option shows only the container logs generated after
<ide> a given date. You can specify the date as an RFC 3339 date, a UNIX
<ide> timestamp, or a Go duration string (e.g. `1m30s`, `3h`). Besides RFC3339 date
<ide><path>integration-cli/docker_cli_logs_test.go
<ide> func (s *DockerSuite) TestLogsCLIContainerNotFound(c *check.C) {
<ide> message := fmt.Sprintf("Error: No such container: %s\n", name)
<ide> c.Assert(out, checker.Equals, message)
<ide> }
<add>
<add>func (s *DockerSuite) TestLogsWithDetails(c *check.C) {
<add> dockerCmd(c, "run", "--name=test", "--label", "foo=bar", "-e", "baz=qux", "--log-opt", "labels=foo", "--log-opt", "env=baz", "busybox", "echo", "hello")
<add> out, _ := dockerCmd(c, "logs", "--details", "--timestamps", "test")
<add>
<add> logFields := strings.Fields(strings.TrimSpace(out))
<add> c.Assert(len(logFields), checker.Equals, 3, check.Commentf(out))
<add>
<add> details := strings.Split(logFields[1], ",")
<add> c.Assert(details, checker.HasLen, 2)
<add> c.Assert(details[0], checker.Equals, "baz=qux")
<add> c.Assert(details[1], checker.Equals, "foo=bar")
<add>}
<ide><path>man/docker-logs.1.md
<ide> logging drivers.
<ide> **--help**
<ide> Print usage statement
<ide>
<add>**--details**=*true*|*false*
<add> Show extra details provided to logs
<add>
<ide> **-f**, **--follow**=*true*|*false*
<ide> Follow log output. The default is *false*.
<ide>
<ide> epoch or Unix time), and the optional .nanoseconds field is a fraction of a
<ide> second no more than nine digits long. You can combine the `--since` option with
<ide> either or both of the `--follow` or `--tail` options.
<ide>
<add>The `docker logs --details` command will add on extra attributes, such as
<add>environment variables and labels, provided to `--log-opt` when creating the
<add>container.
<add>
<ide> # HISTORY
<ide> April 2014, Originally compiled by William Henry (whenry at redhat dot com)
<ide> based on docker.com source material and internal work.
<ide><path>pkg/jsonlog/jsonlog.go
<ide> type JSONLog struct {
<ide> Stream string `json:"stream,omitempty"`
<ide> // Created is the created timestamp of log
<ide> Created time.Time `json:"time"`
<add> // Attrs is the list of extra attributes provided by the user
<add> Attrs map[string]string `json:"attrs,omitempty"`
<ide> }
<ide>
<ide> // Format returns the log formatted according to format
<ide><path>pkg/jsonlog/jsonlog_marshalling_test.go
<ide> import (
<ide> )
<ide>
<ide> func TestJSONLogMarshalJSON(t *testing.T) {
<del> logs := map[JSONLog]string{
<del> JSONLog{Log: `"A log line with \\"`}: `^{\"log\":\"\\\"A log line with \\\\\\\\\\\"\",\"time\":\".{20,}\"}$`,
<del> JSONLog{Log: "A log line"}: `^{\"log\":\"A log line\",\"time\":\".{20,}\"}$`,
<del> JSONLog{Log: "A log line with \r"}: `^{\"log\":\"A log line with \\r\",\"time\":\".{20,}\"}$`,
<del> JSONLog{Log: "A log line with & < >"}: `^{\"log\":\"A log line with \\u0026 \\u003c \\u003e\",\"time\":\".{20,}\"}$`,
<del> JSONLog{Log: "A log line with utf8 : 🚀 ψ ω β"}: `^{\"log\":\"A log line with utf8 : 🚀 ψ ω β\",\"time\":\".{20,}\"}$`,
<del> JSONLog{Stream: "stdout"}: `^{\"stream\":\"stdout\",\"time\":\".{20,}\"}$`,
<del> JSONLog{}: `^{\"time\":\".{20,}\"}$`,
<add> logs := map[*JSONLog]string{
<add> &JSONLog{Log: `"A log line with \\"`}: `^{\"log\":\"\\\"A log line with \\\\\\\\\\\"\",\"time\":\".{20,}\"}$`,
<add> &JSONLog{Log: "A log line"}: `^{\"log\":\"A log line\",\"time\":\".{20,}\"}$`,
<add> &JSONLog{Log: "A log line with \r"}: `^{\"log\":\"A log line with \\r\",\"time\":\".{20,}\"}$`,
<add> &JSONLog{Log: "A log line with & < >"}: `^{\"log\":\"A log line with \\u0026 \\u003c \\u003e\",\"time\":\".{20,}\"}$`,
<add> &JSONLog{Log: "A log line with utf8 : 🚀 ψ ω β"}: `^{\"log\":\"A log line with utf8 : 🚀 ψ ω β\",\"time\":\".{20,}\"}$`,
<add> &JSONLog{Stream: "stdout"}: `^{\"stream\":\"stdout\",\"time\":\".{20,}\"}$`,
<add> &JSONLog{}: `^{\"time\":\".{20,}\"}$`,
<ide> // These ones are a little weird
<del> JSONLog{Log: "\u2028 \u2029"}: `^{\"log\":\"\\u2028 \\u2029\",\"time\":\".{20,}\"}$`,
<del> JSONLog{Log: string([]byte{0xaF})}: `^{\"log\":\"\\ufffd\",\"time\":\".{20,}\"}$`,
<del> JSONLog{Log: string([]byte{0x7F})}: `^{\"log\":\"\x7f\",\"time\":\".{20,}\"}$`,
<add> &JSONLog{Log: "\u2028 \u2029"}: `^{\"log\":\"\\u2028 \\u2029\",\"time\":\".{20,}\"}$`,
<add> &JSONLog{Log: string([]byte{0xaF})}: `^{\"log\":\"\\ufffd\",\"time\":\".{20,}\"}$`,
<add> &JSONLog{Log: string([]byte{0x7F})}: `^{\"log\":\"\x7f\",\"time\":\".{20,}\"}$`,
<ide> }
<ide> for jsonLog, expression := range logs {
<ide> data, err := jsonLog.MarshalJSON() | 12 |
Text | Text | reduce abbreviations in async_hooks.md | ddb1cbac476372360e68c7f77470763ce4d2e5a7 | <ide><path>doc/api/async_hooks.md
<ide> asyncHook.disable();
<ide> function init(asyncId, type, triggerAsyncId, resource) { }
<ide>
<ide> // Before is called just before the resource's callback is called. It can be
<del>// called 0-N times for handles (e.g. TCPWrap), and will be called exactly 1
<del>// time for requests (e.g. FSReqCallback).
<add>// called 0-N times for handles (such as TCPWrap), and will be called exactly 1
<add>// time for requests (such as FSReqCallback).
<ide> function before(asyncId) { }
<ide>
<ide> // After is called just after the resource's callback has finished.
<ide> const server = net.createServer((conn) => {
<ide> async_hooks.executionAsyncId();
<ide>
<ide> }).listen(port, () => {
<del> // Returns the ID of a TickObject (i.e. process.nextTick()) because all
<add> // Returns the ID of a TickObject (process.nextTick()) because all
<ide> // callbacks passed to .listen() are wrapped in a nextTick().
<ide> async_hooks.executionAsyncId();
<ide> });
<ide> added:
<ide>
<ide> This methods runs a function synchronously outside of a context and return its
<ide> return value. The store is not accessible within the callback function or
<del>the asynchronous operations created within the callback, i.e. any `getStore`
<add>the asynchronous operations created within the callback. Any `getStore()`
<ide> call done within the callback function will always return `undefined`.
<ide>
<ide> Optionally, arguments can be passed to the function. They will be passed to | 1 |
Javascript | Javascript | add test cases for fspromises" | 4bfc03b57dfbf6ac245b56c62b718ccd68e12cd7 | <ide><path>test/parallel/test-fs-promises.js
<ide> const fsPromises = require('fs/promises');
<ide> const {
<ide> access,
<ide> chmod,
<del> chown,
<ide> copyFile,
<ide> fchmod,
<del> fchown,
<ide> fdatasync,
<ide> fstat,
<ide> fsync,
<ide> const {
<ide> realpath,
<ide> rename,
<ide> rmdir,
<del> lchmod,
<del> lchown,
<ide> stat,
<ide> symlink,
<ide> write,
<ide> function verifyStatObject(stat) {
<ide>
<ide> await chmod(dest, 0o666);
<ide> await fchmod(handle, 0o666);
<del> // lchmod is only available on OSX
<del> if (common.isOSX) {
<del> await lchmod(dest, 0o666);
<del> }
<del>
<del> if (!common.isWindows) {
<del> const gid = process.getgid();
<del> const uid = process.getuid();
<del> await chown(dest, uid, gid);
<del> await fchown(handle, uid, gid);
<del> // lchown is only available on OSX
<del> if (common.isOSX) {
<del> await lchown(dest, uid, gid);
<del> }
<del> }
<ide>
<ide> await utimes(dest, new Date(), new Date());
<ide> | 1 |
Go | Go | remove client-side for supported logging drivers | 05dc9846e1266e6a3629c26851acb633a380dd17 | <ide><path>cli/command/container/logs.go
<ide> package container
<ide>
<ide> import (
<del> "fmt"
<ide> "io"
<ide>
<ide> "golang.org/x/net/context"
<ide> import (
<ide> "github.com/spf13/cobra"
<ide> )
<ide>
<del>var validDrivers = map[string]bool{
<del> "json-file": true,
<del> "journald": true,
<del>}
<del>
<ide> type logsOptions struct {
<ide> follow bool
<ide> since string
<ide> func NewLogsCommand(dockerCli *command.DockerCli) *cobra.Command {
<ide> func runLogs(dockerCli *command.DockerCli, opts *logsOptions) error {
<ide> ctx := context.Background()
<ide>
<del> c, err := dockerCli.Client().ContainerInspect(ctx, opts.container)
<del> if err != nil {
<del> return err
<del> }
<del>
<del> if !validDrivers[c.HostConfig.LogConfig.Type] {
<del> return fmt.Errorf("\"logs\" command is supported only for \"json-file\" and \"journald\" logging drivers (got: %s)", c.HostConfig.LogConfig.Type)
<del> }
<del>
<ide> options := types.ContainerLogsOptions{
<ide> ShowStdout: true,
<ide> ShowStderr: true,
<ide> func runLogs(dockerCli *command.DockerCli, opts *logsOptions) error {
<ide> }
<ide> defer responseBody.Close()
<ide>
<add> c, err := dockerCli.Client().ContainerInspect(ctx, opts.container)
<add> if err != nil {
<add> return err
<add> }
<add>
<ide> if c.Config.Tty {
<ide> _, err = io.Copy(dockerCli.Out(), responseBody)
<ide> } else {
<ide><path>daemon/logger/logger.go
<ide> import (
<ide> )
<ide>
<ide> // ErrReadLogsNotSupported is returned when the logger does not support reading logs.
<del>var ErrReadLogsNotSupported = errors.New("configured logging reader does not support reading")
<add>var ErrReadLogsNotSupported = errors.New("configured logging driver does not support reading")
<ide>
<ide> const (
<ide> // TimeFormat is the time format used for timestamps sent to log readers.
<ide><path>daemon/logs.go
<ide> import (
<ide> // ContainerLogs hooks up a container's stdout and stderr streams
<ide> // configured with the given struct.
<ide> func (daemon *Daemon) ContainerLogs(ctx context.Context, containerName string, config *backend.ContainerLogsConfig, started chan struct{}) error {
<add> if !(config.ShowStdout || config.ShowStderr) {
<add> return fmt.Errorf("You must choose at least one stream")
<add> }
<ide> container, err := daemon.GetContainer(containerName)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> if !(config.ShowStdout || config.ShowStderr) {
<del> return fmt.Errorf("You must choose at least one stream")
<add> if container.HostConfig.LogConfig.Type == "none" {
<add> return logger.ErrReadLogsNotSupported
<ide> }
<ide>
<ide> cLog, err := daemon.getLogger(container)
<ide><path>integration-cli/docker_cli_daemon_test.go
<ide> func (s *DockerDaemonSuite) TestDaemonLoggingDriverNoneLogsError(c *check.C) {
<ide>
<ide> out, err = s.d.Cmd("logs", "test")
<ide> c.Assert(err, check.NotNil, check.Commentf("Logs should fail with 'none' driver"))
<del> expected := `"logs" command is supported only for "json-file" and "journald" logging drivers (got: none)`
<add> expected := `configured logging driver does not support reading`
<ide> c.Assert(out, checker.Contains, expected)
<ide> }
<ide>
<ide><path>integration-cli/docker_cli_logs_test.go
<ide> func (s *DockerSuite) TestLogsFollowGoroutinesNoOutput(c *check.C) {
<ide> func (s *DockerSuite) TestLogsCLIContainerNotFound(c *check.C) {
<ide> name := "testlogsnocontainer"
<ide> out, _, _ := dockerCmdWithError("logs", name)
<del> message := fmt.Sprintf("Error: No such container: %s\n", name)
<del> c.Assert(out, checker.Equals, message)
<add> message := fmt.Sprintf("No such container: %s\n", name)
<add> c.Assert(out, checker.Contains, message)
<ide> }
<ide>
<ide> func (s *DockerSuite) TestLogsWithDetails(c *check.C) { | 5 |
Python | Python | use float 16 in causal mask and masked bias | 439e7abd2d4e0b2bfb592a1cf0eadbd2042d8a93 | <ide><path>src/transformers/models/megatron_gpt2/convert_megatron_gpt2_checkpoint.py
<ide> def convert_megatron_checkpoint(args, input_state_dict, config):
<ide> ) and weight_or_bias == "weight":
<ide>
<ide> # Insert a tensor of 1x1xDxD bias.
<del> causal_mask = torch.tril(torch.ones((n_embed, n_embed), dtype=torch.uint8)).view(1, 1, n_embed, n_embed)
<add> causal_mask = torch.tril(torch.ones((n_embed, n_embed), dtype=torch.float16)).view(1, 1, n_embed, n_embed)
<ide> output_state_dict[layer_name + ".attn.bias"] = causal_mask
<ide>
<ide> # Insert a "dummy" tensor for masked_bias.
<del> masked_bias = torch.tensor(-1e4)
<add> masked_bias = torch.tensor(-1e4, dtype=torch.float16)
<ide> output_state_dict[layer_name + ".attn.masked_bias"] = masked_bias
<ide>
<ide> out_val = fix_query_key_value_ordering(val, checkpoint_version, 3, heads, hidden_size_per_head) | 1 |
Javascript | Javascript | remove extraneous files from dist during release | 95c7ab68970ce201a2bbff48c8e951d38c228ce8 | <ide><path>build/release.js
<ide> module.exports = function( Release ) {
<ide>
<ide> module.exports.dependencies = [
<ide> "archiver@0.14.2",
<del> "shelljs@0.2.6",
<add> "shelljs@0.7.0",
<ide> "npm@2.3.0",
<ide> "chalk@1.1.1"
<ide> ];
<ide><path>build/release/dist.js
<ide> module.exports = function( Release, files, complete ) {
<ide>
<ide> // Copy dist files
<ide> var distFolder = Release.dir.dist + "/dist",
<del> externalFolder = Release.dir.dist + "/external";
<add> externalFolder = Release.dir.dist + "/external",
<add> rmIgnore = files
<add> .concat( [
<add> "README.md",
<add> "node_modules"
<add> ] )
<add> .map( function( file ) {
<add> return Release.dir.dist + "/" + file;
<add> } );
<add>
<add> shell.config.globOptions = {
<add> ignore: rmIgnore
<add> };
<add>
<add> // Remove extraneous files before copy
<add> shell.rm( "-rf", Release.dir.dist + "/**/*" );
<ide>
<ide> shell.mkdir( "-p", distFolder );
<ide> files.forEach( function( file ) { | 2 |
Javascript | Javascript | fix typo and make it more in line with ngshow | f3e053cb6fec8279e09330481ba8906e185f94c6 | <ide><path>src/ng/directive/ngShowHide.js
<ide> var ngShowDirective = ngDirective(function(scope, element, attr){
<ide> * @name ng.directive:ngHide
<ide> *
<ide> * @description
<del> * The `ngHide` and `ngShow` directives hide or show a portion
<del> * of the HTML conditionally.
<add> * The `ngHide` and `ngShow` directives hide or show a portion of the DOM tree (HTML)
<add> * conditionally.
<ide> *
<ide> * @element ANY
<del> * @param {expression} ngHide If the {@link guide/expression expression} truthy then
<add> * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
<ide> * the element is shown or hidden respectively.
<ide> *
<ide> * @example | 1 |
Ruby | Ruby | update vendor version number | 4a644575c83d78e751f49cb6ba47e1c98af693a8 | <ide><path>actionmailer/lib/action_mailer/vendor.rb
<ide> require 'rubygems'
<ide>
<ide> begin
<del> gem 'tmail', '~> 1.2.1'
<add> gem 'tmail', '~> 1.2.2'
<ide> rescue Gem::LoadError
<del> $:.unshift "#{File.dirname(__FILE__)}/vendor/tmail-1.2.1"
<add> $:.unshift "#{File.dirname(__FILE__)}/vendor/tmail-1.2.2"
<ide> end
<ide>
<ide> begin | 1 |
PHP | PHP | extract a method | 153390164e8f93f6c7a49da03f244448f51c01c9 | <ide><path>src/Illuminate/Session/Middleware/StartSession.php
<ide> public function handle($request, Closure $next)
<ide> // Again, if the session has been configured we will need to close out the session
<ide> // so that the attributes may be persisted to some storage medium. We will also
<ide> // add the session identifier cookie to the application response headers now.
<del> $this->manager->driver()->save();
<add> $this->saveSession();
<ide>
<ide> return $response;
<ide> }
<ide> protected function sessionIsPersistent(array $config = null)
<ide>
<ide> return ! in_array($config['driver'], [null, 'array']);
<ide> }
<add>
<add> /**
<add> * Save the session data to storage.
<add> *
<add> * @return void
<add> */
<add> protected function saveSession()
<add> {
<add> $this->manager->driver()->save();
<add> }
<ide> } | 1 |
Python | Python | fix compatibility for python3 | 8f16def11bd9ef4b874fbd86bb0f2792abbb07a0 | <ide><path>object_detection/utils/variables_helper.py
<ide> def get_variables_available_in_checkpoint(variables, checkpoint_path):
<ide> ckpt_reader = tf.train.NewCheckpointReader(checkpoint_path)
<ide> ckpt_vars = ckpt_reader.get_variable_to_shape_map().keys()
<ide> vars_in_ckpt = {}
<del> for variable_name, variable in sorted(variable_names_map.iteritems()):
<add> for variable_name, variable in sorted(variable_names_map.items()):
<ide> if variable_name in ckpt_vars:
<ide> vars_in_ckpt[variable_name] = variable
<ide> else: | 1 |
Javascript | Javascript | fix broken link to panresponderexample.js | c06a1360a949fd4101a86907f66c0fb72281ce41 | <ide><path>Libraries/Interaction/PanResponder.js
<ide> const currentCentroidY = TouchHistoryMath.currentCentroidY;
<ide> * ### Working Example
<ide> *
<ide> * To see it in action, try the
<del> * [PanResponder example in UIExplorer](https://github.com/facebook/react-native/blob/master/Examples/UIExplorer/PanResponderExample.js)
<add> * [PanResponder example in UIExplorer](https://github.com/facebook/react-native/blob/master/Examples/UIExplorer/js/PanResponderExample.js)
<ide> */
<ide>
<ide> const PanResponder = { | 1 |
Text | Text | create model card for spanbert-finetuned-squadv2 | de697935a20470c1adc772cb1a592254dbdd3cfa | <ide><path>model_cards/mrm8488/spanbert-finetuned-squadv2/README.md
<add>---
<add>language: english
<add>thumbnail:
<add>---
<add>
<add># SpanBERT (spanbert-base-cased) fine-tuned on SQuAD v2
<add>
<add>[SpanBERT](https://github.com/facebookresearch/SpanBERT) created by [Facebook Research](https://github.com/facebookresearch) and fine-tuned on [SQuAD 2.0](https://rajpurkar.github.io/SQuAD-explorer/) for **Q&A** downstream task.
<add>
<add>## Details of SpanBERT
<add>
<add>[SpanBERT: Improving Pre-training by Representing and Predicting Spans](https://arxiv.org/abs/1907.10529)
<add>
<add>## Details of the downstream task (Q&A) - Dataset
<add>
<add>[SQuAD2.0](https://rajpurkar.github.io/SQuAD-explorer/) combines the 100,000 questions in SQuAD1.1 with over 50,000 unanswerable questions written adversarially by crowdworkers to look similar to answerable ones. To do well on SQuAD2.0, systems must not only answer questions when possible, but also determine when no answer is supported by the paragraph and abstain from answering.
<add>
<add>| Dataset | Split | # samples |
<add>| -------- | ----- | --------- |
<add>| SQuAD2.0 | train | 130k |
<add>| SQuAD2.0 | eval | 12.3k |
<add>
<add>## Model training
<add>
<add>The model was trained on a Tesla P100 GPU and 25GB of RAM.
<add>The script for fine tuning can be found [here](https://github.com/huggingface/transformers/blob/master/examples/run_squad.py)
<add>
<add>## Results:
<add>
<add>| Metric | # Value |
<add>| ------ | --------- |
<add>| **EM** | **78.80** |
<add>| **F1** | **82.22** |
<add>
<add>### Raw metrics:
<add>
<add>```json
<add>{
<add> "exact": 78.80064010780762,
<add> "f1": 82.22801347271162,
<add> "total": 11873,
<add> "HasAns_exact": 78.74493927125506,
<add> "HasAns_f1": 85.60951483831069,
<add> "HasAns_total": 5928,
<add> "NoAns_exact": 78.85618166526493,
<add> "NoAns_f1": 78.85618166526493,
<add> "NoAns_total": 5945,
<add> "best_exact": 78.80064010780762,
<add> "best_exact_thresh": 0.0,
<add> "best_f1": 82.2280134727116,
<add> "best_f1_thresh": 0.0
<add>}
<add>```
<add>
<add>## Comparison:
<add>
<add>| Model | EM | F1 score |
<add>| ----------------------------------------------------------------------------------------- | --------- | --------- |
<add>| [SpanBert official repo](https://github.com/facebookresearch/SpanBERT#pre-trained-models) | - | 83.6\* |
<add>| [spanbert-finetuned-squadv2](https://huggingface.co/mrm8488/spanbert-finetuned-squadv2) | **78.80** | **82.22** |
<add>
<add>## Model in action
<add>
<add>Fast usage with **pipelines**:
<add>
<add>```python
<add>from transformers import pipeline
<add>
<add>qa_pipeline = pipeline(
<add> "question-answering",
<add> model="mrm8488/spanbert-finetuned-squadv2",
<add> tokenizer="mrm8488/spanbert-finetuned-squadv2"
<add>)
<add>
<add>qa_pipeline({
<add> 'context': "Manuel Romero has been working hardly in the repository hugginface/transformers lately",
<add> 'question': "Who has been working hard for hugginface/transformers lately?"
<add>
<add>})
<add>
<add># Output: {'answer': 'Manuel Romero','end': 13,'score': 6.836378586818937e-09, 'start': 0}
<add>```
<add>
<add>> Created by [Manuel Romero/@mrm8488](https://twitter.com/mrm8488)
<add>
<add>> Made with <span style="color: #e25555;">♥</span> in Spain | 1 |
Ruby | Ruby | add missing require to inheritance test | e632d035db36092236f01ab1553405de65245d64 | <ide><path>activerecord/test/cases/persistence_test.rb
<ide> require 'models/warehouse_thing'
<ide> require 'models/parrot'
<ide> require 'models/minivan'
<add>require 'models/owner'
<ide> require 'models/person'
<ide> require 'models/pet'
<ide> require 'models/toy'
<ide> require 'rexml/document'
<ide>
<ide> class PersistencesTest < ActiveRecord::TestCase
<del>
<ide> fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, 'warehouse-things', :authors, :categorizations, :categories, :posts, :minivans, :pets, :toys
<ide>
<ide> # Oracle UPDATE does not support ORDER BY
<ide><path>activerecord/test/models/pet.rb
<ide> class Pet < ActiveRecord::Base
<del>
<ide> attr_accessor :current_user
<ide>
<ide> self.primary_key = :pet_id
<ide> class << self
<ide> after_destroy do |record|
<ide> Pet.after_destroy_output = record.current_user
<ide> end
<del>
<ide> end | 2 |
Python | Python | fix typo in documentation | 7e9af6bf4c3d376fd2533aa4bf6edef0dbd972bd | <ide><path>keras/layers/preprocessing/integer_lookup.py
<ide> def adapt(self, data, batch_size=None, steps=None):
<ide> During `adapt()`, the layer will build a vocabulary of all integer tokens
<ide> seen in the dataset, sorted by occurance count, with ties broken by sort
<ide> order of the tokens (high to low). At the end of `adapt()`, if `max_tokens`
<del> is set, the voculary wil be truncated to `max_tokens` size. For example,
<add> is set, the vocabulary wil be truncated to `max_tokens` size. For example,
<ide> adapting a layer with `max_tokens=1000` will compute the 1000 most frequent
<ide> tokens occurring in the input dataset. If `output_mode='tf-idf'`, `adapt()`
<ide> will also learn the document frequencies of each token in the input dataset. | 1 |
Python | Python | improve synthic data performance | c9972ad615c9752fc46bca37102848ba0a06d415 | <ide><path>official/resnet/cifar10_main.py
<ide> def input_fn(is_training, data_dir, batch_size, num_epochs=1, num_gpus=None):
<ide> )
<ide>
<ide>
<del>def get_synth_input_fn():
<add>def get_synth_input_fn(dtype):
<ide> return resnet_run_loop.get_synth_input_fn(
<del> _HEIGHT, _WIDTH, _NUM_CHANNELS, _NUM_CLASSES)
<add> _HEIGHT, _WIDTH, _NUM_CHANNELS, _NUM_CLASSES, dtype=dtype)
<ide>
<ide>
<ide> ###############################################################################
<ide> def run_cifar(flags_obj):
<ide> Args:
<ide> flags_obj: An object containing parsed flag values.
<ide> """
<del> input_function = (flags_obj.use_synthetic_data and get_synth_input_fn()
<del> or input_fn)
<add> input_function = (flags_obj.use_synthetic_data and
<add> get_synth_input_fn(flags_core.get_tf_dtype(flags_obj)) or
<add> input_fn)
<ide> resnet_run_loop.resnet_main(
<ide> flags_obj, cifar10_model_fn, input_function, DATASET_NAME,
<ide> shape=[_HEIGHT, _WIDTH, _NUM_CHANNELS])
<ide><path>official/resnet/cifar10_test.py
<ide> def test_dataset_input_fn(self):
<ide> self.assertAllClose(pixel, np.array([-1.225, 0., 1.225]), rtol=1e-3)
<ide>
<ide> def cifar10_model_fn_helper(self, mode, resnet_version, dtype):
<del> input_fn = cifar10_main.get_synth_input_fn()
<add> input_fn = cifar10_main.get_synth_input_fn(dtype)
<ide> dataset = input_fn(True, '', _BATCH_SIZE)
<del> iterator = dataset.make_one_shot_iterator()
<add> iterator = dataset.make_initializable_iterator()
<ide> features, labels = iterator.get_next()
<ide> spec = cifar10_main.cifar10_model_fn(
<ide> features, labels, mode, {
<ide><path>official/resnet/imagenet_main.py
<ide> def input_fn(is_training, data_dir, batch_size, num_epochs=1, num_gpus=None):
<ide> )
<ide>
<ide>
<del>def get_synth_input_fn():
<add>def get_synth_input_fn(dtype):
<ide> return resnet_run_loop.get_synth_input_fn(
<del> _DEFAULT_IMAGE_SIZE, _DEFAULT_IMAGE_SIZE, _NUM_CHANNELS, _NUM_CLASSES)
<add> _DEFAULT_IMAGE_SIZE, _DEFAULT_IMAGE_SIZE, _NUM_CHANNELS, _NUM_CLASSES,
<add> dtype=dtype)
<ide>
<ide>
<ide> ###############################################################################
<ide> def run_imagenet(flags_obj):
<ide> Args:
<ide> flags_obj: An object containing parsed flag values.
<ide> """
<del> input_function = (flags_obj.use_synthetic_data and get_synth_input_fn()
<del> or input_fn)
<add> input_function = (flags_obj.use_synthetic_data and
<add> get_synth_input_fn(flags_core.get_tf_dtype(flags_obj)) or
<add> input_fn)
<ide>
<ide> resnet_run_loop.resnet_main(
<ide> flags_obj, imagenet_model_fn, input_function, DATASET_NAME,
<ide><path>official/resnet/imagenet_test.py
<ide> def resnet_model_fn_helper(self, mode, resnet_version, dtype):
<ide> """Tests that the EstimatorSpec is given the appropriate arguments."""
<ide> tf.train.create_global_step()
<ide>
<del> input_fn = imagenet_main.get_synth_input_fn()
<add> input_fn = imagenet_main.get_synth_input_fn(dtype)
<ide> dataset = input_fn(True, '', _BATCH_SIZE)
<del> iterator = dataset.make_one_shot_iterator()
<add> iterator = dataset.make_initializable_iterator()
<ide> features, labels = iterator.get_next()
<ide> spec = imagenet_main.imagenet_model_fn(
<ide> features, labels, mode, {
<ide><path>official/resnet/resnet_run_loop.py
<ide> def process_record_dataset(dataset, is_training, batch_size, shuffle_buffer,
<ide> return dataset
<ide>
<ide>
<del>def get_synth_input_fn(height, width, num_channels, num_classes):
<del> """Returns an input function that returns a dataset with zeroes.
<add>def get_synth_input_fn(height, width, num_channels, num_classes,
<add> dtype=tf.float32):
<add> """Returns an input function that returns a dataset with random data.
<ide>
<del> This is useful in debugging input pipeline performance, as it removes all
<del> elements of file reading and image preprocessing.
<add> This input_fn removed all aspects of the input pipeline other than the
<add> host to device copy. This is useful in debugging input pipeline performance.
<ide>
<ide> Args:
<ide> height: Integer height that will be used to create a fake image tensor.
<ide> width: Integer width that will be used to create a fake image tensor.
<ide> num_channels: Integer depth that will be used to create a fake image tensor.
<ide> num_classes: Number of classes that should be represented in the fake labels
<ide> tensor
<add> dtype: Data type for features/images.
<ide>
<ide> Returns:
<ide> An input_fn that can be used in place of a real one to return a dataset
<ide> that can be used for iteration.
<ide> """
<del> def input_fn(is_training, data_dir, batch_size, *args, **kwargs): # pylint: disable=unused-argument
<del> return model_helpers.generate_synthetic_data(
<del> input_shape=tf.TensorShape([batch_size, height, width, num_channels]),
<del> input_dtype=tf.float32,
<del> label_shape=tf.TensorShape([batch_size]),
<del> label_dtype=tf.int32)
<add> # pylint: disable=unused-argument
<add> def input_fn(is_training, data_dir, batch_size, *args, **kwargs):
<add> """Returns dataset filled with random data."""
<add> # Synthetic input should be within [0, 255].
<add> inputs = tf.truncated_normal(
<add> [batch_size] + [height, width, num_channels],
<add> dtype=dtype,
<add> mean=127,
<add> stddev=60,
<add> name='synthetic_inputs')
<add>
<add> labels = tf.random_uniform(
<add> [batch_size],
<add> minval=0,
<add> maxval=num_classes - 1,
<add> dtype=tf.int32,
<add> name='synthetic_labels')
<add> data = tf.data.Dataset.from_tensors((inputs, labels)).repeat()
<add> data = data.prefetch(buffer_size=tf.contrib.data.AUTOTUNE)
<add> return data
<ide>
<ide> return input_fn
<ide>
<ide> def resnet_model_fn(features, labels, mode, model_class,
<ide>
<ide> # Generate a summary node for the images
<ide> tf.summary.image('images', features, max_outputs=6)
<del>
<add> # TODO(tobyboyd): Add cast as part of input pipeline on cpu and remove.
<ide> features = tf.cast(features, dtype)
<ide>
<ide> model = model_class(resnet_size, data_format, resnet_version=resnet_version, | 5 |
Ruby | Ruby | use the as_flags method instead of map | c7444d34f783c7716d87ae7ea1074bec62f703bc | <ide><path>Library/Homebrew/formula.rb
<ide> def to_hash
<ide>
<ide> hsh["installed"] << {
<ide> "version" => keg.version.to_s,
<del> "used_options" => tab.used_options.map(&:flag),
<add> "used_options" => tab.used_options.as_flags,
<ide> "built_as_bottle" => tab.built_bottle,
<ide> "poured_from_bottle" => tab.poured_from_bottle
<ide> }
<ide><path>Library/Homebrew/tab.rb
<ide> class Tab < OpenStruct
<ide> FILENAME = 'INSTALL_RECEIPT.json'
<ide>
<ide> def self.create(formula, compiler, stdlib, build)
<del> Tab.new :used_options => build.used_options.map(&:to_s),
<del> :unused_options => build.unused_options.map(&:to_s),
<add> Tab.new :used_options => build.used_options.as_flags,
<add> :unused_options => build.unused_options.as_flags,
<ide> :tabfile => formula.prefix.join(FILENAME),
<ide> :built_as_bottle => !!ARGV.build_bottle?,
<ide> :poured_from_bottle => false,
<ide> def cxxstdlib
<ide>
<ide> def to_json
<ide> Utils::JSON.dump({
<del> :used_options => used_options.map(&:to_s),
<del> :unused_options => unused_options.map(&:to_s),
<add> :used_options => used_options.as_flags,
<add> :unused_options => unused_options.as_flags,
<ide> :built_as_bottle => built_as_bottle,
<ide> :poured_from_bottle => poured_from_bottle,
<ide> :tapped_from => tapped_from,
<ide><path>Library/Homebrew/test/test_tab.rb
<ide> def setup
<ide> @unused = Options.create(%w(--with-baz --without-qux))
<ide>
<ide> @tab = Tab.new({
<del> :used_options => @used.map(&:to_s),
<del> :unused_options => @unused.map(&:to_s),
<add> :used_options => @used.as_flags,
<add> :unused_options => @unused.as_flags,
<ide> :built_as_bottle => false,
<ide> :poured_from_bottle => true,
<ide> :tapped_from => "Homebrew/homebrew", | 3 |
Ruby | Ruby | use bind params in select with query monkeypatch | 5c6978608d0b05613df6f9ebcb930d0850f44121 | <ide><path>activerecord/test/connections/native_oracle/connection.rb
<ide> ActiveRecord::Base.connection.class.class_eval do
<ide> IGNORED_SELECT_SQL = [/^select .*nextval/i, /^SAVEPOINT/, /^ROLLBACK TO/, /^\s*select .* from ((all|user)_tab_columns|(all|user)_triggers|(all|user)_constraints)/im]
<ide>
<del> def select_with_query_record(sql, name = nil)
<add> def select_with_query_record(sql, name = nil, binds = [])
<ide> $queries_executed ||= []
<ide> $queries_executed << sql unless IGNORED_SELECT_SQL.any? { |r| sql =~ r }
<del> select_without_query_record(sql, name)
<add> select_without_query_record(sql, name, binds)
<ide> end
<ide>
<ide> alias_method_chain :select, :query_record | 1 |
Javascript | Javascript | use imagesource type in logbox implementation | 7374dba6b0c13283341edc4d6fd55257b3cd2053 | <ide><path>Libraries/LogBox/UI/LogBoxInspectorHeader.js
<ide> import StatusBar from '../../Components/StatusBar/StatusBar';
<ide> import LogBoxButton from './LogBoxButton';
<ide> import * as LogBoxStyle from './LogBoxStyle';
<ide> import type {LogLevel} from '../Data/LogBoxLog';
<add>import type {ImageSource} from '../../Image/ImageSource';
<ide> type Props = $ReadOnly<{|
<ide> onSelectIndex: (selectedIndex: number) => void,
<ide> selectedIndex: number,
<ide> const backgroundForLevel = (level: LogLevel) =>
<ide> function LogBoxInspectorHeaderButton(
<ide> props: $ReadOnly<{|
<ide> disabled: boolean,
<del> image: number,
<add> image: ImageSource,
<ide> level: LogLevel,
<ide> onPress?: ?() => void,
<ide> |}>, | 1 |
Text | Text | fix typo in radial linear scale docs | 0ed652b39f7fc96cfcbfd916081d5d930850a231 | <ide><path>docs/axes/radial/linear.md
<ide> # Linear Radial Axis
<ide>
<del>The linear scale is use to chart numerical data. As the name suggests, linear interpolation is used to determine where a value lies in relation the center of the axis.
<add>The linear scale is used to chart numerical data. As the name suggests, linear interpolation is used to determine where a value lies in relation the center of the axis.
<ide>
<ide> The following additional configuration options are provided by the radial linear scale.
<ide> | 1 |
Python | Python | add note clarifying why ifftshift is needed | 1ab96d234d950f7d1232179deb38e73128b28194 | <ide><path>numpy/fft/helper.py
<ide> def fftshift(x, axes=None):
<ide>
<ide> def ifftshift(x, axes=None):
<ide> """
<del> The inverse of fftshift.
<add> The inverse of `fftshift`. Though identical for even-length `x`, the
<add> functions differ by one sample for odd-length `x`.
<ide>
<ide> Parameters
<ide> ---------- | 1 |
Javascript | Javascript | fix wrong greek tests | 3e98e6fb3c5ca8bb36aed6f50ebfaaa888756c5c | <ide><path>src/test/locale/el.js
<ide> test('parse meridiem', function (assert) {
<ide> ['10 Μ', 22, true],
<ide> ['10 am', 10, false],
<ide> ['10 pm', 10, false]
<del> ];
<add> ],
<add> parsed;
<ide>
<ide> // test that a formatted moment including meridiem string can be parsed back to the same moment
<ide> assert.ok(b.isSame(moment(b.format('h:mm:ss a'), 'h:mm:ss a', 'el', true), 'seconds'), b.format('h:mm:ss a') + ' should be equal to ' + moment(b.format('h:mm:ss a'), 'h:mm:ss a', 'el', true).format('h:mm:ss a'));
<ide> test('parse meridiem', function (assert) {
<ide> assert.ok(moment(b.format('h:mm:ss a'), 'h:mm:ss a', 'el', true).isValid(), b.format('h:mm:ss a') + ' should be parsed as valid');
<ide>
<ide> for (i = 0; i < meridiemTests.length; i++) {
<del> assert.equal(moment(meridiemTests[i][0], 'h a', 'el', true).hours(), meridiemTests[i][1], moment(meridiemTests[i][0], 'h a', 'el', true).hours() + ' should be ' + meridiemTests[i][1]);
<del> assert.ok(moment(meridiemTests[i][0], 'h a', 'el', true).isValid() === meridiemTests[i][2], meridiemTests[i][0] + ' ----> ' + meridiemTests[i][2]);
<add> parsed = moment(meridiemTests[i][0], 'h a', 'el', true);
<add> assert.equal(parsed.isValid(), meridiemTests[i][2], "validity for " + meridiemTests[i][0]);
<add> if (parsed.isValid()) {
<add> assert.equal(parsed.hours(), meridiemTests[i][1], "hours for " + meridiemTests[i][0]);
<add> }
<ide> }
<ide> });
<ide> | 1 |
Javascript | Javascript | kill last remaining use of `$` in react | 89819de4f2a0eb506251290a72d662186a59d161 | <ide><path>src/core/ReactMount.js
<ide> var DOMProperty = require('DOMProperty');
<ide> var ReactEventEmitter = require('ReactEventEmitter');
<ide> var ReactInstanceHandles = require('ReactInstanceHandles');
<ide>
<del>var $ = require('$');
<ide> var containsNode = require('containsNode');
<ide> var getReactRootElementInContainer = require('getReactRootElementInContainer');
<ide> var invariant = require('invariant');
<ide> function findDeepestCachedAncestor(targetID) {
<ide> * representative DOM elements and inserting them into a supplied `container`.
<ide> * Any prior content inside `container` is destroyed in the process.
<ide> *
<del> * ReactMount.renderComponent(component, $('container'));
<add> * ReactMount.renderComponent(
<add> * component,
<add> * document.getElementById('container')
<add> * );
<ide> *
<ide> * <div id="container"> <-- Supplied `container`.
<ide> * <div data-reactid=".r[3]"> <-- Rendered reactRoot of React
<ide> var ReactMount = {
<ide> * @return {ReactComponent} Component instance rendered in the container node.
<ide> */
<ide> constructAndRenderComponentByID: function(constructor, props, id) {
<del> return ReactMount.constructAndRenderComponent(constructor, props, $(id));
<add> var domNode = document.getElementById(id);
<add> invariant(
<add> domNode,
<add> 'Tried to get element with id of "%s" but it is not present on the page.',
<add> id
<add> );
<add> return ReactMount.constructAndRenderComponent(constructor, props, domNode);
<ide> },
<ide>
<ide> /**
<ide><path>src/core/__tests__/ReactMount-test.js
<ide> describe('ReactMount', function() {
<ide> var React = require('React');
<ide> var ReactMount = require('ReactMount');
<ide>
<add> describe('constructAndRenderComponentByID', function() {
<add> it('throws if given an id for a component that doesn\'t exist', function() {
<add> expect(function() {
<add> ReactMount.constructAndRenderComponentByID(
<add> function dummyComponentConstructor() {},
<add> {},
<add> 'SOME_ID_THAT_DOESNT_EXIST'
<add> );
<add> }).toThrow();
<add> });
<add> });
<add>
<ide> it('should render different components in same root', function() {
<ide> var container = document.createElement('container');
<ide> document.documentElement.appendChild(container);
<ide><path>src/vendor/core/$.js
<del>/**
<del> * Copyright 2013 Facebook, Inc.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> *
<del> * @providesModule $
<del> * @typechecks
<del> */
<del>
<del>var ex = require('ex');
<del>
<del>/**
<del> * Find a node by ID.
<del> *
<del> * If your application code depends on the existence of the element, use $,
<del> * which will throw if the element doesn't exist.
<del> *
<del> * If you're not sure whether or not the element exists, use ge instead, and
<del> * manually check for the element's existence in your application code.
<del> */
<del>function getRequiredElement(id) {
<del> var element = typeof id === 'string' ? document.getElementById(id) : id;
<del> if (!element) {
<del> throw new Error(ex(
<del> 'Tried to get element with id of "%s" but it is not present on the page.',
<del> id
<del> ));
<del> }
<del> return element;
<del>}
<del>
<del>/**
<del> * Find a node by ID with typechecked input and output.
<del> *
<del> * @param {string|DOMDocument|DOMElement|DOMTextNode|Comment} id
<del> * @return {DOMDocument|DOMElement|DOMTextNode|Comment}
<del> */
<del>function $(id) {
<del> return getRequiredElement(id);
<del>}
<del>
<del>/**
<del> * Find a node by ID without typechecks.
<del> *
<del> * This is micro-optimization for the small subset of users who have typechecks
<del> * enabled. It should only be used by frequently called core modules that are
<del> * already checking their params and return values.
<del> */
<del>$.unsafe = getRequiredElement;
<del>
<del>module.exports = $; | 3 |
Java | Java | publish operator on observable | 2e0d61d338020e1ad27298736528aced62265750 | <ide><path>rxjava-core/src/main/java/rx/Observable.java
<ide> import rx.plugins.RxJavaErrorHandler;
<ide> import rx.plugins.RxJavaObservableExecutionHook;
<ide> import rx.plugins.RxJavaPlugins;
<add>import rx.subjects.PublishSubject;
<ide> import rx.subjects.Subject;
<ide> import rx.subscriptions.BooleanSubscription;
<ide> import rx.subscriptions.Subscriptions;
<ide> public static <T> Observable<T> onErrorReturn(final Observable<T> that, Func1<Ex
<ide> return create(OperationOnErrorReturn.onErrorReturn(that, resumeFunction));
<ide> }
<ide>
<add> /**
<add> * Returns a connectable observable sequence that shares a single subscription to the underlying sequence.
<add> *
<add> * @param that
<add> * the source Observable
<add> * @return a connectable observable sequence that upon connection causes the source sequence to push results into the specified subject.
<add> */
<add> public static <T> ConnectableObservable<T> publish(final Observable<T> that) {
<add> return OperationMulticast.multicast(that, PublishSubject.<T> create());
<add> }
<add>
<ide> /**
<ide> * Returns an Observable that applies a function of your choosing to the first item emitted by a
<ide> * source Observable, then feeds the result of that function along with the second item emitted
<ide> public T call(T t1, T t2) {
<ide> public static <T> Observable<T> aggregate(Observable<T> sequence, Func2<T, T, T> accumulator) {
<ide> return reduce(sequence, accumulator);
<ide> }
<del>
<add>
<ide> /**
<ide> * Used by dynamic languages.
<ide> *
<ide> public static <T> Observable<T> aggregate(Observable<T> sequence, Func2<T, T, T>
<ide> public static <T> Observable<T> aggregate(Observable<T> sequence, Object accumulator) {
<ide> return reduce(sequence, accumulator);
<ide> }
<del>
<add>
<ide> /**
<ide> * Returns an Observable that applies a function of your choosing to the first item emitted by a
<ide> * source Observable, then feeds the result of that function along with the second item emitted
<ide> public R call(R r, T t) {
<ide> public static <T, R> Observable<R> aggregate(Observable<T> sequence, R initialValue, Func2<R, T, R> accumulator) {
<ide> return reduce(sequence, initialValue, accumulator);
<ide> }
<del>
<add>
<ide> /**
<ide> * Used by dynamic languages.
<ide> *
<ide> public static <T, R> Observable<R> aggregate(Observable<T> sequence, R initialVa
<ide> public static <T, R> Observable<R> aggregate(Observable<T> sequence, R initialValue, Object accumulator) {
<ide> return reduce(sequence, initialValue, accumulator);
<ide> }
<del>
<add>
<ide> /**
<ide> * Returns an Observable that applies a function of your choosing to the first item emitted by a
<ide> * source Observable, then feeds the result of that function along with the second item emitted
<ide> public static <T> Observable<T> takeLast(final Observable<T> items, final int co
<ide> * @param items
<ide> * @param predicate
<ide> * a function to test each source element for a condition
<del> * @return the values from the start of the given sequence
<add> * @return the values from the start of the given sequence
<ide> */
<ide> public static <T> Observable<T> takeWhile(final Observable<T> items, Func1<T, Boolean> predicate) {
<ide> return create(OperationTakeWhile.takeWhile(items, predicate));
<ide> public static <T> Observable<T> takeWhile(final Observable<T> items, Func1<T, Bo
<ide> * @param items
<ide> * @param predicate
<ide> * a function to test each source element for a condition
<del> * @return the values from the start of the given sequence
<add> * @return the values from the start of the given sequence
<ide> */
<ide> public static <T> Observable<T> takeWhile(final Observable<T> items, Object predicate) {
<ide> @SuppressWarnings("rawtypes")
<ide> public Boolean call(T t) {
<ide> * @param items
<ide> * @param predicate
<ide> * a function to test each element for a condition; the second parameter of the function represents the index of the source element; otherwise, false.
<del> * @return the values from the start of the given sequence
<add> * @return the values from the start of the given sequence
<ide> */
<ide> public static <T> Observable<T> takeWhileWithIndex(final Observable<T> items, Func2<T, Integer, Boolean> predicate) {
<ide> return create(OperationTakeWhile.takeWhileWithIndex(items, predicate));
<ide> public Boolean call(T t, Integer integer)
<ide>
<ide> /**
<ide> * Adds a timestamp to each item emitted by this observable.
<add> *
<ide> * @return An observable sequence of timestamped items.
<ide> */
<ide> public Observable<Timestamped<T>> timestamp() {
<ide> return create(OperationTimestamp.timestamp(this));
<ide> }
<del>
<add>
<ide> /**
<ide> * Return a Future representing a single value of the Observable.
<ide> * <p>
<ide> public static <T> Observable<T> toObservable(T... items) {
<ide> * @param sequence
<ide> * @throws ClassCastException
<ide> * if T objects do not implement Comparable
<del> * @return an observable containing the sorted list
<add> * @return an observable containing the sorted list
<ide> */
<ide> public static <T> Observable<List<T>> toSortedList(Observable<T> sequence) {
<ide> return create(OperationToObservableSortedList.toSortedList(sequence));
<ide> public static <T> Observable<List<T>> toSortedList(Observable<T> sequence) {
<ide> *
<ide> * @param sequence
<ide> * @param sortFunction
<del> * @return an observable containing the sorted list
<add> * @return an observable containing the sorted list
<ide> */
<ide> public static <T> Observable<List<T>> toSortedList(Observable<T> sequence, Func2<T, T, Integer> sortFunction) {
<ide> return create(OperationToObservableSortedList.toSortedList(sequence, sortFunction));
<ide> public static <T> Observable<List<T>> toSortedList(Observable<T> sequence, Func2
<ide> *
<ide> * @param sequence
<ide> * @param sortFunction
<del> * @return an observable containing the sorted list
<add> * @return an observable containing the sorted list
<ide> */
<ide> public static <T> Observable<List<T>> toSortedList(Observable<T> sequence, final Object sortFunction) {
<ide> @SuppressWarnings("rawtypes")
<ide> public Observable<T> reduce(Func2<T, T, T> accumulator) {
<ide> return reduce(this, accumulator);
<ide> }
<ide>
<add> /**
<add> * Returns a connectable observable sequence that shares a single subscription to the underlying sequence.
<add> *
<add> * @return a connectable observable sequence that upon connection causes the source sequence to push results into the specified subject.
<add> */
<add> public ConnectableObservable<T> publish() {
<add> return OperationMulticast.multicast(this, PublishSubject.<T> create());
<add> }
<add>
<ide> /**
<ide> * Used by dynamic languages.
<ide> *
<ide> public Observable<T> reduce(Object accumulator) {
<ide> public Observable<T> aggregate(Func2<T, T, T> accumulator) {
<ide> return aggregate(this, accumulator);
<ide> }
<del>
<add>
<ide> /**
<ide> * Used by dynamic languages.
<ide> *
<ide> public Observable<T> aggregate(Func2<T, T, T> accumulator) {
<ide> public Observable<T> aggregate(Object accumulator) {
<ide> return aggregate(this, accumulator);
<ide> }
<del>
<add>
<ide> /**
<ide> * Returns an Observable that applies a function of your choosing to the first item emitted by a
<ide> * source Observable, then feeds the result of that function along with the second item emitted
<ide> public <R> Observable<R> aggregate(R initialValue, Func2<R, T, R> accumulator) {
<ide> public <R> Observable<R> aggregate(R initialValue, Object accumulator) {
<ide> return aggregate(this, initialValue, accumulator);
<ide> }
<del>
<add>
<ide> /**
<ide> * Returns an Observable that applies a function of your choosing to the first item emitted by a
<ide> * source Observable, then feeds the result of that function along with the second item emitted
<ide> public Observable<T> scan(Func2<T, T, T> accumulator) {
<ide> public Observable<T> sample(long period, TimeUnit unit) {
<ide> return create(OperationSample.sample(this, period, unit));
<ide> }
<del>
<add>
<ide> /**
<ide> * Samples the observable sequence at each interval.
<ide> *
<ide> public Observable<T> sample(long period, TimeUnit unit) {
<ide> public Observable<T> sample(long period, TimeUnit unit, Scheduler scheduler) {
<ide> return create(OperationSample.sample(this, period, unit, scheduler));
<ide> }
<del>
<add>
<ide> /**
<ide> * Used by dynamic languages.
<del> *
<add> *
<ide> * @see #scan(Func2)
<ide> */
<ide> public Observable<T> scan(final Object accumulator) {
<ide> public <R> Observable<R> scan(R initialValue, Func2<R, T, R> accumulator) {
<ide>
<ide> /**
<ide> * Used by dynamic languages.
<del> *
<add> *
<ide> * @see #scan(Object, Func2)
<ide> */
<ide> public <R> Observable<R> scan(final R initialValue, final Object accumulator) {
<ide> public Observable<T> take(final int num) {
<ide> *
<ide> * @param predicate
<ide> * a function to test each source element for a condition
<del> * @return the values from the start of the given sequence
<add> * @return the values from the start of the given sequence
<ide> */
<ide> public Observable<T> takeWhile(final Func1<T, Boolean> predicate) {
<ide> return takeWhile(this, predicate);
<ide> public Observable<T> takeWhile(final Func1<T, Boolean> predicate) {
<ide> *
<ide> * @param predicate
<ide> * a function to test each source element for a condition
<del> * @return the values from the start of the given sequence
<add> * @return the values from the start of the given sequence
<ide> */
<ide> public Observable<T> takeWhile(final Object predicate) {
<ide> return takeWhile(this, predicate);
<ide> public Observable<T> takeWhile(final Object predicate) {
<ide> *
<ide> * @param predicate
<ide> * a function to test each element for a condition; the second parameter of the function represents the index of the source element; otherwise, false.
<del> * @return the values from the start of the given sequence
<add> * @return the values from the start of the given sequence
<ide> */
<ide> public Observable<T> takeWhileWithIndex(final Func2<T, Integer, Boolean> predicate) {
<ide> return takeWhileWithIndex(this, predicate);
<ide> public Observable<T> takeWhileWithIndex(final Func2<T, Integer, Boolean> predica
<ide> *
<ide> * @param predicate
<ide> * a function to test each element for a condition; the second parameter of the function represents the index of the source element; otherwise, false.
<del> * @return the values from the start of the given sequence
<add> * @return the values from the start of the given sequence
<ide> */
<ide> public Observable<T> takeWhileWithIndex(final Object predicate) {
<ide> return takeWhileWithIndex(this, predicate);
<ide> public Observable<List<T>> toList() {
<ide> *
<ide> * @throws ClassCastException
<ide> * if T objects do not implement Comparable
<del> * @return an observable containing the sorted list
<add> * @return an observable containing the sorted list
<ide> */
<ide> public Observable<List<T>> toSortedList() {
<ide> return toSortedList(this);
<ide> public Observable<List<T>> toSortedList() {
<ide> * <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toSortedList.png">
<ide> *
<ide> * @param sortFunction
<del> * @return an observable containing the sorted list
<add> * @return an observable containing the sorted list
<ide> */
<ide> public Observable<List<T>> toSortedList(Func2<T, T, Integer> sortFunction) {
<ide> return toSortedList(this, sortFunction);
<ide> public Observable<List<T>> toSortedList(Func2<T, T, Integer> sortFunction) {
<ide> * <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/toSortedList.png">
<ide> *
<ide> * @param sortFunction
<del> * @return an observable containing the sorted list
<add> * @return an observable containing the sorted list
<ide> */
<ide> public Observable<List<T>> toSortedList(final Object sortFunction) {
<ide> return toSortedList(this, sortFunction);
<ide> public void call(String t1) {
<ide> }
<ide> }
<ide>
<add> @Test
<add> public void testPublish() throws InterruptedException {
<add> final AtomicInteger counter = new AtomicInteger();
<add> ConnectableObservable<String> o = Observable.create(new Func1<Observer<String>, Subscription>() {
<add>
<add> @Override
<add> public Subscription call(final Observer<String> observer) {
<add> final BooleanSubscription subscription = new BooleanSubscription();
<add> new Thread(new Runnable() {
<add>
<add> @Override
<add> public void run() {
<add> System.out.println("published observable being executed");
<add> observer.onNext("one");
<add> observer.onCompleted();
<add> counter.incrementAndGet();
<add> }
<add> }).start();
<add> return subscription;
<add> }
<add> }).publish();
<add>
<add> final CountDownLatch latch = new CountDownLatch(2);
<add>
<add> // subscribe once
<add> o.subscribe(new Action1<String>() {
<add>
<add> @Override
<add> public void call(String v) {
<add> assertEquals("one", v);
<add> System.out.println("v: " + v);
<add> latch.countDown();
<add> }
<add> });
<add>
<add> // subscribe again
<add> o.subscribe(new Action1<String>() {
<add>
<add> @Override
<add> public void call(String v) {
<add> assertEquals("one", v);
<add> System.out.println("v: " + v);
<add> latch.countDown();
<add> }
<add> });
<add>
<add> Subscription s = o.connect();
<add> try {
<add> if (!latch.await(1000, TimeUnit.MILLISECONDS)) {
<add> fail("subscriptions did not receive values");
<add> }
<add> assertEquals(1, counter.get());
<add> } finally {
<add> s.unsubscribe();
<add> }
<add> }
<add>
<ide> private static class TestException extends RuntimeException {
<ide> private static final long serialVersionUID = 1L;
<ide> } | 1 |
Javascript | Javascript | add missing semicolon in paintvivecontroller | f1db9e5f4d701cacf58dafc12595014f65407c43 | <ide><path>examples/js/vr/PaintViveController.js
<ide> THREE.PaintViveController = function ( id ) {
<ide> mesh.position.set( 0, 0.005, 0.0495 );
<ide> mesh.rotation.x = - 1.45;
<ide> mesh.scale.setScalar( 0.02 );
<del> this.add( mesh )
<add> this.add( mesh );
<ide>
<ide> var geometry = new THREE.IcosahedronGeometry( 0.1, 2 );
<ide> var material = new THREE.MeshBasicMaterial(); | 1 |
Python | Python | fix integration test levit | da71df1afcff0d119299393fabcfa2a808c5c9dc | <ide><path>tests/models/levit/test_modeling_levit.py
<ide> def test_inference_image_classification_head(self):
<ide> expected_shape = torch.Size((1, 1000))
<ide> self.assertEqual(outputs.logits.shape, expected_shape)
<ide>
<del> expected_slice = torch.tensor([0.0096, -1.0084, -1.4318]).to(torch_device)
<add> expected_slice = torch.tensor([1.0448, -0.3745, -1.8317]).to(torch_device)
<ide>
<ide> self.assertTrue(torch.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4)) | 1 |
Javascript | Javascript | fix typo in counter container test | 489968069a076f824f2148be03b55e19cb5d45d4 | <ide><path>examples/counter/test/containers/App.spec.js
<ide> describe('containers', () => {
<ide> expect(p.textContent).toMatch(/^Clicked: 1 times/);
<ide> });
<ide>
<del> it('should display updated count after descrement button click', () => {
<add> it('should display updated count after decrement button click', () => {
<ide> const { buttons, p } = setup();
<ide> TestUtils.Simulate.click(buttons[1]);
<ide> expect(p.textContent).toMatch(/^Clicked: -1 times/); | 1 |
PHP | PHP | return the status of $model->push() | 9ba285a2ad66c9c6f57a2dc8253cb03713f680fb | <ide><path>laravel/database/eloquent/model.php
<ide> public function has_many_and_belongs_to($model, $table = null, $foreign = null,
<ide> */
<ide> public function push()
<ide> {
<del> $this->save();
<add> if (!$this->save()) return false;
<ide>
<ide> // To sync all of the relationships to the database, we will simply spin through
<ide> // the relationships, calling the "push" method on each of the models in that
<ide> public function push()
<ide>
<ide> foreach ($models as $model)
<ide> {
<del> $model->push();
<add> if (!$model->push()) return false;
<ide> }
<ide> }
<add>
<add> return true;
<ide> }
<ide>
<ide> /** | 1 |
PHP | PHP | fix bug in connection with custom grammars | 5fd1ea527f9ad51760ae59ac8621724ebf78f4b9 | <ide><path>laravel/database/connection.php
<ide> protected function grammar()
<ide>
<ide> if (isset(\Laravel\Database::$registrar[$this->driver()]))
<ide> {
<del> \Laravel\Database::$registrar[$this->driver()]['query']();
<add> return $this->grammar = \Laravel\Database::$registrar[$this->driver()]['query']();
<ide> }
<ide>
<ide> switch ($this->driver()) | 1 |
Javascript | Javascript | improve ember.array slice implementation | 531db2ef0b3b62315ba322fa69d0257ff34c9193 | <ide><path>packages/ember-runtime/lib/mixins/array.js
<ide> Ember.Array = Ember.Mixin.create(Ember.Enumerable, /** @scope Ember.Array.protot
<ide> var length = get(this, 'length') ;
<ide> if (none(beginIndex)) beginIndex = 0 ;
<ide> if (none(endIndex) || (endIndex > length)) endIndex = length ;
<add>
<add> if (beginIndex < 0) beginIndex = length + beginIndex;
<add> if (endIndex < 0) endIndex = length + endIndex;
<add>
<ide> while(beginIndex < endIndex) {
<ide> ret[ret.length] = this.objectAt(beginIndex++) ;
<ide> }
<ide><path>packages/ember-runtime/tests/mixins/array_test.js
<ide> var TestArray = Ember.Object.extend(Ember.Array, {
<ide>
<ide> length: Ember.computed(function() {
<ide> return this._content.length;
<del> }),
<del>
<del> slice: function() {
<del> return this._content.slice();
<del> }
<del>
<add> })
<ide> });
<ide>
<ide>
<ide> test("the return value of slice has Ember.Array applied", function(){
<ide> equal(Ember.Array.detect(y), true, "mixin should be applied");
<ide> });
<ide>
<add>test("slice supports negative index arguments", function(){
<add> var testArray = new TestArray([1,2,3,4]);
<add>
<add> deepEqual(testArray.slice(-2), [3, 4], 'slice(-2)');
<add> deepEqual(testArray.slice(-2, -1), [3], 'slice(-2, -1');
<add> deepEqual(testArray.slice(-2, -2), [], 'slice(-2, -2)');
<add> deepEqual(testArray.slice(-1, -2), [], 'slice(-1, -2)');
<add>
<add> deepEqual(testArray.slice(-4, 1), [1], 'slice(-4, 1)');
<add> deepEqual(testArray.slice(-4, 5), [1,2,3,4], 'slice(-4, 5)');
<add> deepEqual(testArray.slice(-4), [1,2,3,4], 'slice(-4)');
<add>
<add> deepEqual(testArray.slice(0, -1), [1,2,3], 'slice(0, -1)');
<add> deepEqual(testArray.slice(0, -4), [], 'slice(0, -4)');
<add> deepEqual(testArray.slice(0, -3), [1], 'slice(0, -3)');
<add>
<add>});
<add>
<ide> // ..........................................................
<ide> // CONTENT DID CHANGE
<ide> // | 2 |
Text | Text | add missing comma | 8e2374964904b41a753368224265706453848511 | <ide><path>model_cards/mrm8488/t5-base-finetuned-question-generation-ap/README.md
<ide> Dataset ID: ```squad``` from [HugginFace/NLP](https://github.com/huggingface/nl
<ide> How to load it from [nlp](https://github.com/huggingface/nlp)
<ide>
<ide> ```python
<del>train_dataset = nlp.load_dataset('squad, split=nlp.Split.TRAIN)
<add>train_dataset = nlp.load_dataset('squad', split=nlp.Split.TRAIN)
<ide> valid_dataset = nlp.load_dataset('squad', split=nlp.Split.VALIDATION)
<ide> ```
<ide> Check out more about this dataset and others in [NLP Viewer](https://huggingface.co/nlp/viewer/) | 1 |
Python | Python | improve a number of error messages in core layers | 1e8d286537fd10b328f1a307ff9727b97b8a8219 | <ide><path>keras/layers/core/dense.py
<ide> def __init__(self,
<ide> self.units = int(units) if not isinstance(units, int) else units
<ide> if self.units < 0:
<ide> raise ValueError(f'Received an invalid value for `units`, expected '
<del> f'a positive integer, got {units}.')
<add> f'a positive integer. Received: units={units}')
<ide> self.activation = activations.get(activation)
<ide> self.use_bias = use_bias
<ide> self.kernel_initializer = initializers.get(kernel_initializer)
<ide> def __init__(self,
<ide> def build(self, input_shape):
<ide> dtype = tf.as_dtype(self.dtype or K.floatx())
<ide> if not (dtype.is_floating or dtype.is_complex):
<del> raise TypeError('Unable to build `Dense` layer with non-floating point '
<del> 'dtype %s' % (dtype,))
<add> raise TypeError('A Dense layer can only be built with a floating-point '
<add> f'dtype. Received: dtype={dtype}')
<ide>
<ide> input_shape = tf.TensorShape(input_shape)
<ide> last_dim = tf.compat.dimension_value(input_shape[-1])
<ide> if last_dim is None:
<del> raise ValueError('The last dimension of the inputs to `Dense` '
<del> 'should be defined. Found `None`.')
<add> raise ValueError('The last dimension of the inputs to a Dense layer '
<add> 'should be defined. Found None. '
<add> f'Full input shape received: {input_shape}')
<ide> self.input_spec = InputSpec(min_ndim=2, axes={-1: last_dim})
<ide> self.kernel = self.add_weight(
<ide> 'kernel',
<ide> def compute_output_shape(self, input_shape):
<ide> input_shape = tf.TensorShape(input_shape)
<ide> input_shape = input_shape.with_rank_at_least(2)
<ide> if tf.compat.dimension_value(input_shape[-1]) is None:
<del> raise ValueError(
<del> 'The innermost dimension of input_shape must be defined, but saw: %s'
<del> % (input_shape,))
<add> raise ValueError('The last dimension of the input shape of a Dense layer '
<add> 'should be defined. Found None. '
<add> f'Received: input_shape={input_shape}')
<ide> return input_shape[:-1].concatenate(self.units)
<ide>
<ide> def get_config(self):
<ide><path>keras/layers/core/permute.py
<ide> def __init__(self, dims, **kwargs):
<ide> self.dims = tuple(dims)
<ide> if sorted(dims) != list(range(1, len(dims) + 1)):
<ide> raise ValueError(
<del> 'Invalid permutation `dims` for Permute Layer: %s. '
<del> 'The set of indices in `dims` must be consecutive and start from 1.' %
<del> (dims,))
<add> 'Invalid permutation argument `dims` for Permute Layer. '
<add> 'The set of indices in `dims` must be consecutive and start from 1. '
<add> f'Received dims={dims}')
<ide> self.input_spec = InputSpec(ndim=len(self.dims) + 1)
<ide>
<ide> def compute_output_shape(self, input_shape):
<ide><path>keras/layers/core/tf_op_layer.py
<ide> import tensorflow.compat.v2 as tf
<ide> # pylint: enable=g-bad-import-order
<ide>
<del>import textwrap
<ide> from keras import backend as K
<ide> from keras.engine import keras_tensor
<ide> from keras.engine.base_layer import Layer
<ide> def call(self, args, kwargs):
<ide>
<ide> def get_config(self):
<ide> if not self.cls_symbol:
<del> raise ValueError('This Keras class method conversion tried to convert '
<del> 'a method belonging to class %s, a class '
<del> 'that is not an exposed in the TensorFlow API. '
<del> 'To ensure cross-version compatibility of Keras models '
<del> 'that use op layers, only op layers produced from '
<del> 'exported TF API symbols can be serialized.' %
<del> self.cls_symbol)
<del> config = {'cls_symbol': self.cls_symbol, 'method_name': self.method_name}
<add> raise ValueError(
<add> 'This Keras class method conversion tried to convert '
<add> f'a method belonging to class {self.cls_symbol}, a class '
<add> 'that is not publicly exposed in the TensorFlow API. '
<add> 'To ensure cross-version compatibility of Keras models '
<add> 'that use op layers, only op layers produced from '
<add> 'public TensorFlow API symbols can be serialized.')
<ide>
<add> config = {'cls_symbol': self.cls_symbol, 'method_name': self.method_name}
<ide> base_config = super(ClassMethod, self).get_config()
<ide> return dict(list(base_config.items()) + list(config.items()))
<ide>
<ide> def from_config(cls, config, custom_objects=None):
<ide> symbol_name = config.pop('cls_symbol')
<ide> cls_ref = get_symbol_from_name(symbol_name)
<ide> if not cls_ref:
<del> raise ValueError('TF symbol `tf.%s` could not be found.' % symbol_name)
<add> raise ValueError(f'TensorFlow symbol `{symbol_name}` could not be found.')
<ide>
<ide> config['cls_ref'] = cls_ref
<ide>
<ide> def _check_variables(self, created_variables, accessed_variables):
<ide> ]
<ide> if untracked_new_vars:
<ide> variable_str = '\n'.join(' {}'.format(i) for i in untracked_new_vars)
<del> error_str = textwrap.dedent("""
<del> The following Variables were created within a Lambda layer ({name})
<del> but are not tracked by said layer:
<del> {variable_str}
<del> The layer cannot safely ensure proper Variable reuse across multiple
<del> calls, and consquently this behavior is disallowed for safety. Lambda
<del> layers are not well suited to stateful computation; instead, writing a
<del> subclassed Layer is the recommend way to define layers with
<del> Variables.""").format(
<del> name=self.name, variable_str=variable_str)
<del> raise ValueError(error_str)
<add> raise ValueError(
<add> 'The following Variables were created within a Lambda layer '
<add> f'({self.name}) but are not tracked by said layer: {variable_str}\n'
<add> 'The layer cannot safely ensure proper Variable reuse '
<add> 'across multiple calls, and consquently this behavior is disallowed '
<add> 'for safety reasons. Lambda layers are not well suited for stateful '
<add> 'computation; instead, writing a subclassed Layer is the recommend '
<add> 'way to define layers with Variables.')
<ide>
<ide> untracked_used_vars = [
<ide> v for v in accessed_variables if v.ref() not in tracked_weights
<ide> ]
<ide> if untracked_used_vars and not self._already_warned:
<ide> variable_str = '\n'.join(' {}'.format(i) for i in untracked_used_vars)
<ide> self._warn(
<del> textwrap.dedent("""
<del> The following Variables were used a Lambda layer's call ({name}), but
<del> are not present in its tracked objects:
<del> {variable_str}
<del> It is possible that this is intended behavior, but it is more likely
<del> an omission. This is a strong indication that this layer should be
<del> formulated as a subclassed Layer rather than a Lambda layer.""")
<del> .format(name=self.name, variable_str=variable_str))
<add> 'The following Variables were used in a Lambda layer\'s call '
<add> f'({self.name}), but are not present in its tracked objects: '
<add> f'{variable_str}. This is a strong indication that the Lambda layer '
<add> 'should be rewritten as a subclassed Layer.')
<ide> self._already_warned = True
<ide>
<ide> def _warn(self, msg):
<ide> def _warn(self, msg):
<ide>
<ide> def get_config(self):
<ide> if not self.symbol:
<del> raise ValueError('This Keras op layer was generated from %s, a method '
<del> 'that is not an exposed in the TensorFlow API. This '
<del> 'may have happened if the method was explicitly '
<del> 'decorated to add dispatching support, and it was used '
<del> 'during Functional model construction. '
<del> 'To ensure cross-version compatibility of Keras models '
<del> 'that use op layers, only op layers produced from '
<del> 'exported TF API symbols can be serialized.' %
<del> self.function)
<add> raise ValueError(
<add> f'This Keras op layer was generated from {self.function}, a method '
<add> 'that is not publicly exposed in the TensorFlow API. This '
<add> 'may have happened if the method was explicitly '
<add> 'decorated to add dispatching support, and it was used '
<add> 'during Functional model construction. '
<add> 'To ensure cross-version compatibility of Keras models '
<add> 'that use op layers, only op layers produced from '
<add> 'public TensorFlow API symbols can be serialized.')
<ide> config = {'function': self.symbol}
<ide>
<ide> base_config = super(TFOpLambda, self).get_config()
<ide> def from_config(cls, config, custom_objects=None):
<ide> symbol_name = config['function']
<ide> function = get_symbol_from_name(symbol_name)
<ide> if not function:
<del> raise ValueError('TF symbol `tf.%s` could not be found.' % symbol_name)
<add> raise ValueError(f'TF symbol `{symbol_name}` could not be found.')
<ide>
<ide> config['function'] = function
<ide> | 3 |
Text | Text | update the getting started tutorial | f591762ccf9a6ef373a5c4b279900e4a136fa89e | <ide><path>guides/source/getting_started.md
<ide> are generated in Rails they are empty by default, unless you tell it
<ide> your wanted actions during the generation process.
<ide>
<ide> To manually define an action inside a controller, all you need to do is to
<del>define a new method inside the controller.
<del>Open `app/controllers/articles_controller.rb` and inside the `ArticlesController`
<del>class, define a `new` method like this:
<add>define a new method inside the controller. Open
<add>`app/controllers/articles_controller.rb` and inside the `ArticlesController`
<add>class, define a `new` method so that the controller now looks like this:
<ide>
<ide> ```ruby
<del>def new
<add>class ArticlesController < ApplicationController
<add>
<add> def new
<add> end
<add>
<ide> end
<ide> ```
<ide>
<ide> method called `form_for`. To use this method, add this code into
<ide>
<ide> ```html+erb
<ide> <%= form_for :article do |f| %>
<add>
<ide> <p>
<ide> <%= f.label :title %><br>
<ide> <%= f.text_field :title %>
<ide> method called `form_for`. To use this method, add this code into
<ide> <p>
<ide> <%= f.submit %>
<ide> </p>
<add>
<ide> <% end %>
<ide> ```
<ide>
<ide> form and then click the submit button to begin the process of creating a new
<ide> article, so go ahead and do that. When you submit the form, you should see a
<ide> familiar error:
<ide>
<del>
<add>![Unknown action create for ArticlesController]
<add>(images/getting_started/unknown_action_create_for_articles.png)
<ide>
<ide> You now need to create the `create` action within the `ArticlesController` for
<ide> this to work.
<ide> this to work.
<ide>
<ide> To make the "Unknown action" go away, you can define a `create` action within
<ide> the `ArticlesController` class in `app/controllers/articles_controller.rb`,
<del>underneath the `new` action:
<add>underneath the `new` action, as shown:
<ide>
<ide> ```ruby
<ide> class ArticlesController < ApplicationController
<add>
<ide> def new
<ide> end
<ide>
<ide> def create
<ide> end
<add>
<ide> end
<ide> ```
<ide>
<ide> or worse.
<ide> We have to whitelist our controller parameters to prevent wrongful
<ide> mass assignment. In this case, we want to both allow and require the
<ide> `title` and `text` parameters for valid use of `create`. The syntax for
<del>this introduces `require` and `permit`. The change will involve one line:
<add>this introduces `require` and `permit`. The change will involve one line
<add>in the `create` action:
<ide>
<ide> ```ruby
<ide> @article = Article.new(params.require(:article).permit(:title, :text))
<ide> parameter, which in our case will be the id of the article.
<ide> As we did before, we need to add the `show` action in
<ide> `app/controllers/articles_controller.rb` and its respective view.
<ide>
<add>NOTE: A frequent practice is to place the standard CRUD actions in each
<add>controller in the following order: `index`, `show`, `new`, `edit`, `create`,
<add>`update` and `destroy`. You may use any order you choose, but keep in mind that
<add>these are public methods; as mentioned earlier in this guide, they must be
<add>placed before any private or protected method in the controller in order to
<add>work.
<add>
<add>Given that, let's add the `show` action, as follows:
<add>
<ide> ```ruby
<del>def show
<del> @article = Article.find(params[:id])
<del>end
<add>class ArticlesController < ApplicationController
<add>
<add> def show
<add> @article = Article.find(params[:id])
<add> end
<add>
<add> def new
<add> end
<add>
<add> # snipped for brevity
<ide> ```
<ide>
<ide> A couple of things to note. We use `Article.find` to find the article we're
<ide> articles GET /articles(.:format) articles#index
<ide> ```
<ide>
<ide> Add the corresponding `index` action for that route inside the
<del>`ArticlesController` in the `app/controllers/articles_controller.rb` file:
<add>`ArticlesController` in the `app/controllers/articles_controller.rb` file.
<add>When we write an `index` action, the usual practice is to place it as the
<add>first method in the controller. Let's do it:
<ide>
<ide> ```ruby
<del>def index
<del> @articles = Article.all
<del>end
<add>class ArticlesController < ApplicationController
<add>
<add> def index
<add> @articles = Article.all
<add> end
<add>
<add> def show
<add> @article = Article.find(params[:id])
<add> end
<add>
<add> def new
<add> end
<add>
<add> # snipped for brevity
<ide> ```
<ide>
<ide> And then finally, add the view for this action, located at
<ide> Let's add links to the other views as well, starting with adding this
<ide>
<ide> This link will allow you to bring up the form that lets you create a new article.
<ide>
<del>Also add a link in `app/views/articles/new.html.erb`, underneath the form, to
<del>go back to the `index` action:
<add>Now, add another link in `app/views/articles/new.html.erb`, underneath the
<add>form, to go back to the `index` action:
<ide>
<ide> ```erb
<ide> <%= form_for :article, url: articles_path do |f| %>
<ide> go back to the `index` action:
<ide> <%= link_to 'Back', articles_path %>
<ide> ```
<ide>
<del>Finally, add another link to the `app/views/articles/show.html.erb` template to
<add>Finally, add a link to the `app/views/articles/show.html.erb` template to
<ide> go back to the `index` action as well, so that people who are viewing a single
<ide> article can go back and view the whole list again:
<ide>
<ide> you attempt to do just that on the new article form
<ide> We've covered the "CR" part of CRUD. Now let's focus on the "U" part, updating
<ide> articles.
<ide>
<del>The first step we'll take is adding an `edit` action to the `ArticlesController`.
<add>The first step we'll take is adding an `edit` action to the `ArticlesController`,
<add>generally between the `new` and `create` actions, as shown:
<ide>
<ide> ```ruby
<add>def new
<add> @article = Article.new
<add>end
<add>
<ide> def edit
<ide> @article = Article.find(params[:id])
<ide> end
<add>
<add>def create
<add> @article = Article.new(article_params)
<add>
<add> if @article.save
<add> redirect_to @article
<add> else
<add> render 'new'
<add> end
<add>end
<ide> ```
<ide>
<ide> The view will contain a form similar to the one we used when creating
<ide> via the `PATCH` HTTP method which is the HTTP method you're expected to use to
<ide>
<ide> The first parameter of `form_for` can be an object, say, `@article` which would
<ide> cause the helper to fill in the form with the fields of the object. Passing in a
<del>symbol (`:article`) with the same name as the instance variable (`@article`) also
<del>automagically leads to the same behavior. This is what is happening here. More details
<del>can be found in [form_for documentation](http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for).
<add>symbol (`:article`) with the same name as the instance variable (`@article`)
<add>also automagically leads to the same behavior. This is what is happening here.
<add>More details can be found in [form_for documentation]
<add>(http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for).
<ide>
<del>Next we need to create the `update` action in
<del>`app/controllers/articles_controller.rb`:
<add>Next, we need to create the `update` action in
<add>`app/controllers/articles_controller.rb`.
<add>Add it between the `create` action and the `private` method:
<ide>
<ide> ```ruby
<add>def create
<add> @article = Article.new(article_params)
<add>
<add> if @article.save
<add> redirect_to @article
<add> else
<add> render 'new'
<add> end
<add>end
<add>
<ide> def update
<ide> @article = Article.find(params[:id])
<ide>
<ide> bottom of the template:
<ide> ```html+erb
<ide> ...
<ide>
<del><%= link_to 'Back', articles_path %>
<del>| <%= link_to 'Edit', edit_article_path(@article) %>
<add><%= link_to 'Back', articles_path %> |
<add><%= link_to 'Edit', edit_article_path(@article) %>
<ide> ```
<ide>
<ide> And here's how our app looks so far:
<ide> And here's how our app looks so far:
<ide>
<ide> ### Using partials to clean up duplication in views
<ide>
<del>Our `edit` page looks very similar to the `new` page, in fact they
<del>both share the same code for displaying the form. Let's remove some duplication
<del>by using a view partial. By convention, partial files are prefixed by an
<del>underscore.
<add>Our `edit` page looks very similar to the `new` page; in fact, they
<add>both share the same code for displaying the form. Let's remove this
<add>duplication by using a view partial. By convention, partial files are
<add>prefixed by an underscore.
<ide>
<ide> TIP: You can read more about partials in the
<ide> [Layouts and Rendering in Rails](layouts_and_rendering.html) guide.
<ide> people to craft malicious URLs like this:
<ide> <a href='http://example.com/articles/1/destroy'>look at this cat!</a>
<ide> ```
<ide>
<del>We use the `delete` method for destroying resources, and this route is mapped to
<del>the `destroy` action inside `app/controllers/articles_controller.rb`, which
<del>doesn't exist yet, but is provided below:
<add>We use the `delete` method for destroying resources, and this route is mapped
<add>to the `destroy` action inside `app/controllers/articles_controller.rb`, which
<add>doesn't exist yet. The `destroy` method is generally the last CRUD action in
<add>the controller, and like the other public CRUD actions, it must be placed
<add>before any `private` or `protected` methods. Let's add it:
<ide>
<ide> ```ruby
<ide> def destroy
<ide> def destroy
<ide> end
<ide> ```
<ide>
<add>The complete `ArticlesController` in the
<add>`app/controllers/articles_controller.rb` file should now look like this:
<add>
<add>```ruby
<add>class ArticlesController < ApplicationController
<add>
<add> def index
<add> @articles = Article.all
<add> end
<add>
<add> def show
<add> @article = Article.find(params[:id])
<add> end
<add>
<add> def new
<add> @article = Article.new
<add> end
<add>
<add> def edit
<add> @article = Article.find(params[:id])
<add> end
<add>
<add> def create
<add> @article = Article.new(article_params)
<add>
<add> if @article.save
<add> redirect_to @article
<add> else
<add> render 'new'
<add> end
<add> end
<add>
<add> def update
<add> @article = Article.find(params[:id])
<add>
<add> if @article.update(article_params)
<add> redirect_to @article
<add> else
<add> render 'edit'
<add> end
<add> end
<add>
<add> def destroy
<add> @article = Article.find(params[:id])
<add> @article.destroy
<add>
<add> redirect_to articles_path
<add> end
<add>
<add> private
<add> def article_params
<add> params.require(:article).permit(:title, :text)
<add> end
<add>end
<add>```
<add>
<ide> You can call `destroy` on Active Record objects when you want to delete
<ide> them from the database. Note that we don't need to add a view for this
<ide> action since we're redirecting to the `index` action.
<ide> Congratulations, you can now create, show, list, update and destroy
<ide> articles.
<ide>
<ide> TIP: In general, Rails encourages the use of resources objects in place
<del>of declaring routes manually.
<del>For more information about routing, see
<add>of declaring routes manually. For more information about routing, see
<ide> [Rails Routing from the Outside In](routing.html).
<ide>
<ide> Adding a Second Model
<ide> database and send us back to the show action for the article.
<ide> ### Deleting Associated Objects
<ide>
<ide> If you delete an article, its associated comments will also need to be
<del>deleted. Otherwise they would simply occupy space in the database. Rails allows
<add>deleted, otherwise they would simply occupy space in the database. Rails allows
<ide> you to use the `dependent` option of an association to achieve this. Modify the
<ide> Article model, `app/models/article.rb`, as follows:
<ide>
<ide> class CommentsController < ApplicationController
<ide>
<ide> def create
<ide> @article = Article.find(params[:article_id])
<del> ...
<add> # ...
<ide> end
<ide>
<ide> # snipped for brevity | 1 |
Python | Python | explain the behavior of diff on unsigned types | ae3d1fa3e0f4a048618cb4e7c8fd694185df69b6 | <ide><path>numpy/lib/function_base.py
<ide> def diff(a, n=1, axis=-1):
<ide> will contain `False` when consecutive elements are the same and
<ide> `True` when they differ.
<ide>
<add> For unsigned integer arrays, the results will also be unsigned. This should
<add> not be surprising, as the result is consistent with calculating the
<add> difference directly:
<add>
<add> >>> u8_arr = np.array([1, 0], dtype=np.uint8)
<add> >>> np.diff(u8_arr)
<add> array([255], dtype=uint8)
<add> >>> u8_arr[1,...] - u8_arr[0,...]
<add> array(255, np.uint8)
<add>
<add> If this is not desirable, then the array should be cast to a larger integer
<add> type first:
<add>
<add> >>> i16_arr = u8_arr.astype(np.int16)
<add> >>> np.diff(i16_arr)
<add> array([-1], dtype=int16)
<add>
<ide> Examples
<ide> --------
<ide> >>> x = np.array([1, 2, 4, 7, 0]) | 1 |
PHP | PHP | use assertcount() where applicable | 196b5f2e2d1f6112d72d6e5c5c92ec52886e16ba | <ide><path>tests/TestCase/ORM/QueryTest.php
<ide> public function testContainFinderHasMany()
<ide> ]
<ide> ]);
<ide>
<del> $this->assertSame(2, count($resultWithArticles->first()->articles));
<del> $this->assertSame(2, count($resultWithArticlesArray->first()->articles));
<add> $this->assertCount(2, $resultWithArticles->first()->articles);
<add> $this->assertCount(2, $resultWithArticlesArray->first()->articles);
<ide>
<del> $this->assertSame(1, count($resultWithArticlesArrayOptions->first()->articles));
<del> $this->assertSame('First Article', $resultWithArticlesArrayOptions->first()->articles[0]->title);
<add> $this->assertCount(1, $resultWithArticlesArrayOptions->first()->articles);
<add> $this->assertSame(
<add> 'First Article',
<add> $resultWithArticlesArrayOptions->first()->articles[0]->title
<add> );
<ide>
<del> $this->assertSame(0, count($resultWithoutArticles->first()->articles));
<add> $this->assertCount(0, $resultWithoutArticles->first()->articles);
<ide> }
<ide>
<ide> /**
<ide> public function testContainFinderHasManyClosure()
<ide> }
<ide> ]);
<ide>
<del> $this->assertSame(2, count($resultWithArticles->first()->articles));
<add> $this->assertCount(2, $resultWithArticles->first()->articles);
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | set event.target on ie<8 | ce80576e0b8ac9ed5a5b1f1a4dbc2446434a0002 | <ide><path>src/jqLite.js
<ide> forEach({
<ide> event.cancelBubble = true; //ie
<ide> };
<ide> }
<add> if (!event.target) {
<add> event.target = event.srcElement || document;
<add> }
<ide> forEach(eventHandler.fns, function(fn){
<ide> fn.call(element, event);
<ide> });
<ide><path>test/jqLiteSpec.js
<ide> describe('jqLite', function(){
<ide> expect(callback).toHaveBeenCalled();
<ide> expect(callback.callCount).toBe(1);
<ide> });
<add>
<add> it('should set event.target on IE', function() {
<add> var elm = jqLite(a);
<add> elm.bind('click', function(event) {
<add> expect(event.target).toBe(a);
<add> });
<add>
<add> browserTrigger(a, 'click');
<add> });
<ide> });
<ide>
<ide> | 2 |
PHP | PHP | remove invalid annotation | c55316cdfc8f90b07087428593344e24b15d71f9 | <ide><path>src/TestSuite/TestCase.php
<ide> protected function skipUnless($condition, $message = '')
<ide> */
<ide> public function getMockForModel(string $alias, ?array $methods = [], array $options = [])
<ide> {
<del> /** @var string|\Cake\ORM\Table $className */
<ide> $className = $this->_getTableClassName($alias, $options);
<ide> $connectionName = $className::defaultConnectionName();
<ide> $connection = ConnectionManager::get($connectionName); | 1 |
Javascript | Javascript | handle comments properly | 6cf19103b63f4c33eb2c33590bc533ffa5a3e7e1 | <ide><path>lib/repl.js
<ide> const BLOCK_SCOPED_ERROR = 'Block-scoped declarations (let, ' +
<ide> 'const, function, class) not yet supported outside strict mode';
<ide>
<ide>
<add>class LineParser {
<add>
<add> constructor() {
<add> this.reset();
<add> }
<add>
<add> reset() {
<add> this._literal = null;
<add> this.shouldFail = false;
<add> this.blockComment = false;
<add> }
<add>
<add> parseLine(line) {
<add> var previous = null;
<add> this.shouldFail = false;
<add> const wasWithinStrLiteral = this._literal !== null;
<add>
<add> for (const current of line) {
<add> if (previous === '\\') {
<add> // valid escaping, skip processing. previous doesn't matter anymore
<add> previous = null;
<add> continue;
<add> }
<add>
<add> if (!this._literal) {
<add> if (previous === '*' && current === '/') {
<add> if (this.blockComment) {
<add> this.blockComment = false;
<add> previous = null;
<add> continue;
<add> } else {
<add> this.shouldFail = true;
<add> break;
<add> }
<add> }
<add>
<add> // ignore rest of the line if `current` and `previous` are `/`s
<add> if (previous === current && previous === '/' && !this.blockComment) {
<add> break;
<add> }
<add>
<add> if (previous === '/' && current === '*') {
<add> this.blockComment = true;
<add> previous = null;
<add> }
<add> }
<add>
<add> if (this.blockComment) continue;
<add>
<add> if (current === this._literal) {
<add> this._literal = null;
<add> } else if (current === '\'' || current === '"') {
<add> this._literal = this._literal || current;
<add> }
<add>
<add> previous = current;
<add> }
<add>
<add> const isWithinStrLiteral = this._literal !== null;
<add>
<add> if (!wasWithinStrLiteral && !isWithinStrLiteral) {
<add> // Current line has nothing to do with String literals, trim both ends
<add> line = line.trim();
<add> } else if (wasWithinStrLiteral && !isWithinStrLiteral) {
<add> // was part of a string literal, but it is over now, trim only the end
<add> line = line.trimRight();
<add> } else if (isWithinStrLiteral && !wasWithinStrLiteral) {
<add> // was not part of a string literal, but it is now, trim only the start
<add> line = line.trimLeft();
<add> }
<add>
<add> const lastChar = line.charAt(line.length - 1);
<add>
<add> this.shouldFail = this.shouldFail ||
<add> ((!this._literal && lastChar === '\\') ||
<add> (this._literal && lastChar !== '\\'));
<add>
<add> return line;
<add> }
<add>}
<add>
<add>
<ide> function REPLServer(prompt,
<ide> stream,
<ide> eval_,
<ide> function REPLServer(prompt,
<ide> debug('domain error');
<ide> const top = replMap.get(self);
<ide> top.outputStream.write((e.stack || e) + '\n');
<del> top._currentStringLiteral = null;
<add> top.lineParser.reset();
<ide> top.bufferedCommand = '';
<ide> top.lines.level = [];
<ide> top.displayPrompt();
<ide> function REPLServer(prompt,
<ide> self.outputStream = output;
<ide>
<ide> self.resetContext();
<del> // Initialize the current string literal found, to be null
<del> self._currentStringLiteral = null;
<add> self.lineParser = new LineParser();
<ide> self.bufferedCommand = '';
<ide> self.lines.level = [];
<ide>
<ide> function REPLServer(prompt,
<ide> sawSIGINT = false;
<ide> }
<ide>
<del> self._currentStringLiteral = null;
<add> self.lineParser.reset();
<ide> self.bufferedCommand = '';
<ide> self.lines.level = [];
<ide> self.displayPrompt();
<ide> });
<ide>
<del> function parseLine(line, currentStringLiteral) {
<del> var previous = null, current = null;
<del>
<del> for (var i = 0; i < line.length; i += 1) {
<del> if (previous === '\\') {
<del> // if it is a valid escaping, then skip processing and the previous
<del> // character doesn't matter anymore.
<del> previous = null;
<del> continue;
<del> }
<del>
<del> current = line.charAt(i);
<del> if (current === currentStringLiteral) {
<del> currentStringLiteral = null;
<del> } else if (current === '\'' ||
<del> current === '"' &&
<del> currentStringLiteral === null) {
<del> currentStringLiteral = current;
<del> }
<del> previous = current;
<del> }
<del>
<del> return currentStringLiteral;
<del> }
<del>
<del> function getFinisherFunction(cmd, defaultFn) {
<del> if ((self._currentStringLiteral === null &&
<del> cmd.charAt(cmd.length - 1) === '\\') ||
<del> (self._currentStringLiteral !== null &&
<del> cmd.charAt(cmd.length - 1) !== '\\')) {
<del>
<del> // If the line continuation is used outside string literal or if the
<del> // string continuation happens with out line continuation, then fail hard.
<del> // Even if the error is recoverable, get the underlying error and use it.
<del> return function(e, ret) {
<del> var error = e instanceof Recoverable ? e.err : e;
<del>
<del> if (arguments.length === 2) {
<del> // using second argument only if it is actually passed. Otherwise
<del> // `undefined` will be printed when invalid REPL commands are used.
<del> return defaultFn(error, ret);
<del> }
<del>
<del> return defaultFn(error);
<del> };
<del> }
<del> return defaultFn;
<del> }
<del>
<ide> self.on('line', function(cmd) {
<ide> debug('line %j', cmd);
<ide> sawSIGINT = false;
<ide> var skipCatchall = false;
<del> var finisherFn = finish;
<ide>
<ide> // leading whitespaces in template literals should not be trimmed.
<ide> if (self._inTemplateLiteral) {
<ide> self._inTemplateLiteral = false;
<ide> } else {
<del> const wasWithinStrLiteral = self._currentStringLiteral !== null;
<del> self._currentStringLiteral = parseLine(cmd, self._currentStringLiteral);
<del> const isWithinStrLiteral = self._currentStringLiteral !== null;
<del>
<del> if (!wasWithinStrLiteral && !isWithinStrLiteral) {
<del> // Current line has nothing to do with String literals, trim both ends
<del> cmd = cmd.trim();
<del> } else if (wasWithinStrLiteral && !isWithinStrLiteral) {
<del> // was part of a string literal, but it is over now, trim only the end
<del> cmd = cmd.trimRight();
<del> } else if (isWithinStrLiteral && !wasWithinStrLiteral) {
<del> // was not part of a string literal, but it is now, trim only the start
<del> cmd = cmd.trimLeft();
<del> }
<del>
<del> finisherFn = getFinisherFunction(cmd, finish);
<add> cmd = self.lineParser.parseLine(cmd);
<ide> }
<ide>
<ide> // Check to see if a REPL keyword was used. If it returns true,
<ide> function REPLServer(prompt,
<ide> }
<ide>
<ide> debug('eval %j', evalCmd);
<del> self.eval(evalCmd, self.context, 'repl', finisherFn);
<add> self.eval(evalCmd, self.context, 'repl', finish);
<ide> } else {
<del> finisherFn(null);
<add> finish(null);
<ide> }
<ide>
<ide> function finish(e, ret) {
<ide> function REPLServer(prompt,
<ide> self.outputStream.write('npm should be run outside of the ' +
<ide> 'node repl, in your normal shell.\n' +
<ide> '(Press Control-D to exit.)\n');
<del> self._currentStringLiteral = null;
<add> self.lineParser.reset();
<ide> self.bufferedCommand = '';
<ide> self.displayPrompt();
<ide> return;
<ide> }
<ide>
<ide> // If error was SyntaxError and not JSON.parse error
<ide> if (e) {
<del> if (e instanceof Recoverable) {
<add> if (e instanceof Recoverable && !self.lineParser.shouldFail) {
<ide> // Start buffering data like that:
<ide> // {
<ide> // ... x: 1
<ide> function REPLServer(prompt,
<ide> self.displayPrompt();
<ide> return;
<ide> } else {
<del> self._domain.emit('error', e);
<add> self._domain.emit('error', e.err || e);
<ide> }
<ide> }
<ide>
<ide> // Clear buffer if no SyntaxErrors
<del> self._currentStringLiteral = null;
<add> self.lineParser.reset();
<ide> self.bufferedCommand = '';
<ide>
<ide> // If we got any output - print it (if no error)
<ide> function defineDefaultCommands(repl) {
<ide> repl.defineCommand('break', {
<ide> help: 'Sometimes you get stuck, this gets you out',
<ide> action: function() {
<del> this._currentStringLiteral = null;
<add> this.lineParser.reset();
<ide> this.bufferedCommand = '';
<ide> this.displayPrompt();
<ide> }
<ide> function defineDefaultCommands(repl) {
<ide> repl.defineCommand('clear', {
<ide> help: clearMessage,
<ide> action: function() {
<del> this._currentStringLiteral = null;
<add> this.lineParser.reset();
<ide> this.bufferedCommand = '';
<ide> if (!this.useGlobal) {
<ide> this.outputStream.write('Clearing context...\n');
<ide><path>test/parallel/test-repl.js
<ide> function error_test() {
<ide> { client: client_unix, send: 'function x() {\nreturn \'\\\\\';\n }',
<ide> expect: prompt_multiline + prompt_multiline +
<ide> 'undefined\n' + prompt_unix },
<add> // regression tests for https://github.com/nodejs/node/issues/3421
<add> { client: client_unix, send: 'function x() {\n//\'\n }',
<add> expect: prompt_multiline + prompt_multiline +
<add> 'undefined\n' + prompt_unix },
<add> { client: client_unix, send: 'function x() {\n//"\n }',
<add> expect: prompt_multiline + prompt_multiline +
<add> 'undefined\n' + prompt_unix },
<add> { client: client_unix, send: 'function x() {//\'\n }',
<add> expect: prompt_multiline + 'undefined\n' + prompt_unix },
<add> { client: client_unix, send: 'function x() {//"\n }',
<add> expect: prompt_multiline + 'undefined\n' + prompt_unix },
<add> { client: client_unix, send: 'function x() {\nvar i = "\'";\n }',
<add> expect: prompt_multiline + prompt_multiline +
<add> 'undefined\n' + prompt_unix },
<add> { client: client_unix, send: 'function x(/*optional*/) {}',
<add> expect: 'undefined\n' + prompt_unix },
<add> { client: client_unix, send: 'function x(/* // 5 */) {}',
<add> expect: 'undefined\n' + prompt_unix },
<add> { client: client_unix, send: '// /* 5 */',
<add> expect: 'undefined\n' + prompt_unix },
<add> { client: client_unix, send: '"//"',
<add> expect: '\'//\'\n' + prompt_unix },
<add> { client: client_unix, send: '"data /*with*/ comment"',
<add> expect: '\'data /*with*/ comment\'\n' + prompt_unix },
<add> { client: client_unix, send: 'function x(/*fn\'s optional params*/) {}',
<add> expect: 'undefined\n' + prompt_unix },
<add> { client: client_unix, send: '/* \'\n"\n\'"\'\n*/',
<add> expect: 'undefined\n' + prompt_unix },
<ide> ]);
<ide> }
<ide> | 2 |
Python | Python | remove input and target reset after preprocessing | a63bd3675f3fa1a6154c8bf1d085c66eaea67e56 | <ide><path>examples/pytorch/summarization/run_summarization.py
<ide> def preprocess_function(examples):
<ide> inputs.append(examples[text_column][i])
<ide> targets.append(examples[summary_column][i])
<ide>
<del> inputs = examples[text_column]
<del> targets = examples[summary_column]
<ide> inputs = [prefix + inp for inp in inputs]
<ide> model_inputs = tokenizer(inputs, max_length=data_args.max_source_length, padding=padding, truncation=True)
<ide> | 1 |
Python | Python | return dataset (pytorch) | ce158a076f7089bf11d44e1581f5bcab4dcc5396 | <ide><path>transformers/data/processors/squad.py
<ide>
<ide> from ...tokenization_bert import BasicTokenizer, whitespace_tokenize
<ide> from .utils import DataProcessor, InputExample, InputFeatures
<del>from ...file_utils import is_tf_available
<add>from ...file_utils import is_tf_available, is_torch_available
<add>
<add>if is_torch_available:
<add> import torch
<add> from torch.utils.data import TensorDataset
<ide>
<ide> if is_tf_available():
<ide> import tensorflow as tf
<ide> def _is_whitespace(c):
<ide> return False
<ide>
<ide> def squad_convert_examples_to_features(examples, tokenizer, max_seq_length,
<del> doc_stride, max_query_length, is_training):
<add> doc_stride, max_query_length, is_training,
<add> return_dataset=False):
<ide> """
<ide> Converts a list of examples into a list of features that can be directly given as input to a model.
<ide> It is model-dependant and takes advantage of many of the tokenizer's features to create the model's inputs.
<ide> def squad_convert_examples_to_features(examples, tokenizer, max_seq_length,
<ide> max_seq_length: The maximum sequence length of the inputs.
<ide> doc_stride: The stride used when the context is too large and is split across several features.
<ide> max_query_length: The maximum length of the query.
<del> is_training: wheter to create features for model evaluation or model training.
<add> is_training: whether to create features for model evaluation or model training.
<add> return_dataset: Default False. Either 'pt' or 'tf'.
<add> if 'pt': returns a torch.data.TensorDataset,
<add> if 'tf': returns a tf.data.Dataset
<ide>
<ide> Returns:
<ide> list of :class:`~transformers.data.processors.squad.SquadFeatures`
<ide> def squad_convert_examples_to_features(examples, tokenizer, max_seq_length,
<ide>
<ide> unique_id += 1
<ide>
<add> if return_dataset == 'pt':
<add> if not is_torch_available():
<add> raise ImportError("Pytorch must be installed to return a pytorch dataset.")
<add>
<add> # Convert to Tensors and build dataset
<add> all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)
<add> all_input_mask = torch.tensor([f.attention_mask for f in features], dtype=torch.long)
<add> all_segment_ids = torch.tensor([f.token_type_ids for f in features], dtype=torch.long)
<add> all_cls_index = torch.tensor([f.cls_index for f in features], dtype=torch.long)
<add> all_p_mask = torch.tensor([f.p_mask for f in features], dtype=torch.float)
<add>
<add> if not is_training:
<add> all_example_index = torch.arange(all_input_ids.size(0), dtype=torch.long)
<add> dataset = TensorDataset(all_input_ids, all_input_mask, all_segment_ids,
<add> all_example_index, all_cls_index, all_p_mask)
<add> else:
<add> all_start_positions = torch.tensor([f.start_position for f in features], dtype=torch.long)
<add> all_end_positions = torch.tensor([f.end_position for f in features], dtype=torch.long)
<add> dataset = TensorDataset(all_input_ids, all_input_mask, all_segment_ids,
<add> all_start_positions, all_end_positions,
<add> all_cls_index, all_p_mask)
<add>
<add> return features, dataset
<add>
<add>
<ide> return features
<ide>
<ide>
<ide> def get_dev_examples(self, data_dir, filename=None):
<ide> if self.dev_file is None:
<ide> raise ValueError("SquadProcessor should be instantiated via SquadV1Processor or SquadV2Processor")
<ide>
<del> with open(os.path.join(data_dir, self.dev_file if filename is not None else filename), "r", encoding='utf-8') as reader:
<add> with open(os.path.join(data_dir, self.dev_file if filename is None else filename), "r", encoding='utf-8') as reader:
<ide> input_data = json.load(reader)["data"]
<ide> return self._create_examples(input_data, "dev")
<ide> | 1 |
Javascript | Javascript | enable third cert | 30d14b34e4ae9225c6759504ea6f3c698e4a28fb | <ide><path>config/i18n/all-langs.js
<ide> const auditedCerts = {
<ide> ],
<ide> italian: [
<ide> 'responsive-web-design',
<del> 'javascript-algorithms-and-data-structures'
<add> 'javascript-algorithms-and-data-structures',
<add> 'front-end-libraries'
<ide> ],
<ide> portuguese: ['responsive-web-design']
<ide> }; | 1 |
Java | Java | replace use of pubsub header name literals | 78d1063e37874b7ef0ed70d14f503aa3ab75ade6 | <ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/service/method/MessageBodyArgumentResolver.java
<ide> import org.springframework.core.MethodParameter;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.messaging.Message;
<add>import org.springframework.web.messaging.PubSubHeaders;
<ide> import org.springframework.web.messaging.annotation.MessageBody;
<ide> import org.springframework.web.messaging.converter.CompositeMessageConverter;
<ide> import org.springframework.web.messaging.converter.MessageConversionException;
<ide> public Object resolveArgument(MethodParameter parameter, Message<?> message) thr
<ide> Object arg = null;
<ide>
<ide> MessageBody annot = parameter.getParameterAnnotation(MessageBody.class);
<del> MediaType contentType = (MediaType) message.getHeaders().get("content-type");
<add> MediaType contentType = (MediaType) message.getHeaders().get(PubSubHeaders.CONTENT_TYPE);
<ide>
<ide> if (annot == null || annot.required()) {
<ide> Class<?> sourceType = message.getPayload().getClass();
<ide><path>spring-websocket/src/main/java/org/springframework/web/messaging/stomp/support/StompRelayPubSubMessageHandler.java
<ide> import org.springframework.messaging.SubscribableChannel;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.web.messaging.MessageType;
<add>import org.springframework.web.messaging.PubSubHeaders;
<ide> import org.springframework.web.messaging.converter.CompositeMessageConverter;
<ide> import org.springframework.web.messaging.converter.MessageConverter;
<ide> import org.springframework.web.messaging.service.AbstractPubSubMessageHandler;
<ide> protected Collection<MessageType> getSupportedMessageTypes() {
<ide> @Override
<ide> public void handleConnect(Message<?> message) {
<ide>
<del> String sessionId = (String) message.getHeaders().get("sessionId");
<add> String sessionId = (String) message.getHeaders().get(PubSubHeaders.SESSION_ID);
<ide>
<ide> RelaySession session = new RelaySession();
<ide> this.relaySessions.put(sessionId, session);
<ide> public void handleDisconnect(Message<?> message) {
<ide>
<ide> @Override
<ide> public void handleOther(Message<?> message) {
<del> StompCommand command = (StompCommand) message.getHeaders().get("stompCommand");
<add> StompCommand command = (StompCommand) message.getHeaders().get(PubSubHeaders.PROTOCOL_MESSAGE_TYPE);
<ide> Assert.notNull(command, "Expected STOMP command: " + message.getHeaders());
<ide> forwardMessage(message, command);
<ide> } | 2 |
Ruby | Ruby | fix documentation of number_to_currency helper | d261c5cc28d35ae3d493c42edd20d362b61556dc | <ide><path>actionview/lib/action_view/helpers/number_helper.rb
<ide> def number_to_phone(number, options = {})
<ide> #
<ide> # number_to_currency(-1234567890.50, negative_format: "(%u%n)")
<ide> # # => ($1,234,567,890.50)
<del> # number_to_currency(1234567890.50, unit: "£", separator: ",", delimiter: "")
<del> # # => £1234567890,50
<del> # number_to_currency(1234567890.50, unit: "£", separator: ",", delimiter: "", format: "%n %u")
<del> # # => 1234567890,50 £
<add> # number_to_currency(1234567890.50, unit: "R$", separator: ",", delimiter: "")
<add> # # => R$1234567890,50
<add> # number_to_currency(1234567890.50, unit: "R$", separator: ",", delimiter: "", format: "%n %u")
<add> # # => 1234567890,50 R$
<ide> def number_to_currency(number, options = {})
<ide> delegate_number_helper_method(:number_to_currency, number, options)
<ide> end | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.