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
Text
Text
fix indentation [ci skip]
4c18f050b69c4795097255003fe9bb5a650ba7c9
<ide><path>guides/source/5_1_release_notes.md <ide> Please refer to the [Changelog][active-record] for detailed changes. <ide> <ide> ### Removals <ide> <del>* Removed support for passing arguments and block at the same time to <del> `ActiveRecord::QueryMethods#select`. <del> ([Commit](https://github.com/rails/rails/commit/4fc3366d9d99a0eb19e45ad2bf38534efbf8c8ce)) <add>* Removed support for passing arguments and block at the same time to <add> `ActiveRecord::QueryMethods#select`. <add> ([Commit](https://github.com/rails/rails/commit/4fc3366d9d99a0eb19e45ad2bf38534efbf8c8ce)) <ide> <del>* Removed deprecated `activerecord.errors.messages.restrict_dependent_destroy.one` and <add>* Removed deprecated `activerecord.errors.messages.restrict_dependent_destroy.one` and <ide> `activerecord.errors.messages.restrict_dependent_destroy.many` i18n scopes. <del> ([Commit](https://github.com/rails/rails/commit/00e3973a311)) <add> ([Commit](https://github.com/rails/rails/commit/00e3973a311)) <ide> <del>* Removed deprecated force reload argument in singular and collection association readers. <del> ([Commit](https://github.com/rails/rails/commit/09cac8c67af)) <add>* Removed deprecated force reload argument in singular and collection association readers. <add> ([Commit](https://github.com/rails/rails/commit/09cac8c67af)) <ide> <del>* Removed deprecated support to passing a column to `#quote`. <del> ([Commit](https://github.com/rails/rails/commit/e646bad5b7c)) <add>* Removed deprecated support to passing a column to `#quote`. <add> ([Commit](https://github.com/rails/rails/commit/e646bad5b7c)) <ide> <del>* Removed deprecated `name` arguments from `#tables`. <del> ([Commit](https://github.com/rails/rails/commit/d5be101dd02214468a27b6839ffe338cfe8ef5f3)) <add>* Removed deprecated `name` arguments from `#tables`. <add> ([Commit](https://github.com/rails/rails/commit/d5be101dd02214468a27b6839ffe338cfe8ef5f3)) <ide> <del>* Removed deprecated behavior of `#tables` and `#table_exists?` to return tables and views <del> to return only tables and not views. <del> ([Commit](https://github.com/rails/rails/commit/5973a984c369a63720c2ac18b71012b8347479a8)) <add>* Removed deprecated behavior of `#tables` and `#table_exists?` to return tables and views <add> to return only tables and not views. <add> ([Commit](https://github.com/rails/rails/commit/5973a984c369a63720c2ac18b71012b8347479a8)) <ide> <del>* Removed deprecated `original_exception` argument in `ActiveRecord::StatementInvalid#initialize` <del> and `ActiveRecord::StatementInvalid#original_exception`. <del> ([Commit](https://github.com/rails/rails/commit/bc6c5df4699d3f6b4a61dd12328f9e0f1bd6cf46)) <add>* Removed deprecated `original_exception` argument in `ActiveRecord::StatementInvalid#initialize` <add> and `ActiveRecord::StatementInvalid#original_exception`. <add> ([Commit](https://github.com/rails/rails/commit/bc6c5df4699d3f6b4a61dd12328f9e0f1bd6cf46)) <ide> <ide> * Removed deprecated support of passing a class as a value in a query. <ide> ([Commit](https://github.com/rails/rails/commit/b4664864c972463c7437ad983832d2582186e886)) <ide> Please refer to the [Changelog][active-record] for detailed changes. <ide> <ide> ### Deprecations <ide> <del>* Deprecated `error_on_ignored_order_or_limit` flag in favor of <del> `error_on_ignored_order`. <del> ([Commit](https://github.com/rails/rails/commit/451437c6f57e66cc7586ec966e530493927098c7)) <add>* Deprecated `error_on_ignored_order_or_limit` flag in favor of <add> `error_on_ignored_order`. <add> ([Commit](https://github.com/rails/rails/commit/451437c6f57e66cc7586ec966e530493927098c7)) <ide> <del>* Deprecated `sanitize_conditions` in favor of `sanitize_sql`. <del> ([Pull Request](https://github.com/rails/rails/pull/25999)) <add>* Deprecated `sanitize_conditions` in favor of `sanitize_sql`. <add> ([Pull Request](https://github.com/rails/rails/pull/25999)) <ide> <ide> * Deprecated `supports_migrations?` on connection adapters. <ide> ([Pull Request](https://github.com/rails/rails/pull/28172))
1
Go
Go
fix some places where low-level errors bubbled up
2a5e85e2e871bf037c976471cf8a14da22ddd9a9
<ide><path>volume/local/local.go <ide> import ( <ide> "reflect" <ide> "sync" <ide> <add> "github.com/pkg/errors" <add> <ide> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/pkg/idtools" <ide> "github.com/docker/docker/pkg/mount" <ide> func New(scope string, rootUID, rootGID int) (*Root, error) { <ide> if b, err := ioutil.ReadFile(optsFilePath); err == nil { <ide> opts := optsConfig{} <ide> if err := json.Unmarshal(b, &opts); err != nil { <del> return nil, err <add> return nil, errors.Wrapf(err, "error while unmarshaling volume options for volume: %s", name) <ide> } <ide> // Make sure this isn't an empty optsConfig. <ide> // This could be empty due to buggy behavior in older versions of Docker. <ide> func (r *Root) Create(name string, opts map[string]string) (volume.Volume, error <ide> if os.IsExist(err) { <ide> return nil, fmt.Errorf("volume already exists under %s", filepath.Dir(path)) <ide> } <del> return nil, err <add> return nil, errors.Wrapf(err, "error while creating volume path '%s'", path) <ide> } <ide> <ide> var err error <ide> func (r *Root) Create(name string, opts map[string]string) (volume.Volume, error <ide> return nil, err <ide> } <ide> if err = ioutil.WriteFile(filepath.Join(filepath.Dir(path), "opts.json"), b, 600); err != nil { <del> return nil, err <add> return nil, errors.Wrap(err, "error while persisting volume options") <ide> } <ide> } <ide> <ide> func removePath(path string) error { <ide> if os.IsNotExist(err) { <ide> return nil <ide> } <del> return err <add> return errors.Wrapf(err, "error removing volume path '%s'", path) <ide> } <ide> return nil <ide> } <ide> func (v *localVolume) Unmount(id string) error { <ide> if v.active.count == 0 { <ide> if err := mount.Unmount(v.path); err != nil { <ide> v.active.count++ <del> return err <add> return errors.Wrapf(err, "error while unmounting volume path '%s'", v.path) <ide> } <ide> v.active.mounted = false <ide> } <ide><path>volume/local/local_unix.go <ide> import ( <ide> "path/filepath" <ide> "strings" <ide> <add> "src/github.com/pkg/errors" <add> <ide> "github.com/docker/docker/pkg/mount" <ide> ) <ide> <ide> type optsConfig struct { <ide> MountDevice string <ide> } <ide> <add>func (o *optsConfig) String() string { <add> return fmt.Sprintf("type='%s' device='%s' o='%s'", o.MountType, o.MountDevice, o.MountOpts) <add>} <add> <ide> // scopedPath verifies that the path where the volume is located <ide> // is under Docker's root and the valid local paths. <ide> func (r *Root) scopedPath(realPath string) bool { <ide> func (v *localVolume) mount() error { <ide> if v.opts.MountDevice == "" { <ide> return fmt.Errorf("missing device in volume options") <ide> } <del> return mount.Mount(v.opts.MountDevice, v.path, v.opts.MountType, v.opts.MountOpts) <add> err := mount.Mount(v.opts.MountDevice, v.path, v.opts.MountType, v.opts.MountOpts) <add> return errors.Wrapf(err, "error while mounting volume with options: %s", v.opts) <ide> } <ide><path>volume/store/store.go <ide> import ( <ide> "sync" <ide> "time" <ide> <add> "github.com/pkg/errors" <add> <ide> "github.com/Sirupsen/logrus" <ide> "github.com/boltdb/bolt" <ide> "github.com/docker/docker/pkg/locker" <ide> func New(rootPath string) (*VolumeStore, error) { <ide> var err error <ide> vs.db, err = bolt.Open(dbPath, 0600, &bolt.Options{Timeout: 1 * time.Second}) <ide> if err != nil { <del> return nil, err <add> return nil, errors.Wrap(err, "error while opening volume store metadata database") <ide> } <ide> <ide> // initialize volumes bucket <ide> if err := vs.db.Update(func(tx *bolt.Tx) error { <ide> if _, err := tx.CreateBucketIfNotExists([]byte(volumeBucketName)); err != nil { <del> return err <add> return errors.Wrap(err, "error while setting up volume store metadata database") <ide> } <ide> <ide> return nil <ide> func (s *VolumeStore) create(name, driverName string, opts, labels map[string]st <ide> err := b.Put([]byte(name), volData) <ide> return err <ide> }); err != nil { <del> return nil, err <add> return nil, errors.Wrap(err, "error while persisting volume metadata") <ide> } <ide> } <ide> <ide><path>volume/volume.go <ide> import ( <ide> "github.com/docker/docker/pkg/idtools" <ide> "github.com/docker/docker/pkg/stringid" <ide> "github.com/opencontainers/runc/libcontainer/label" <add> "github.com/pkg/errors" <ide> ) <ide> <ide> // DefaultDriverName is the driver name used for the driver <ide> func (m *MountPoint) Setup(mountLabel string, rootUID, rootGID int) (string, err <ide> if m.ID == "" { <ide> m.ID = stringid.GenerateNonCryptoID() <ide> } <del> return m.Volume.Mount(m.ID) <add> path, err := m.Volume.Mount(m.ID) <add> return path, errors.Wrapf(err, "error while mounting volume '%s'", m.Source) <ide> } <ide> if len(m.Source) == 0 { <ide> return "", fmt.Errorf("Unable to setup mount point, neither source nor volume defined") <ide> func (m *MountPoint) Setup(mountLabel string, rootUID, rootGID int) (string, err <ide> if err := idtools.MkdirAllNewAs(m.Source, 0755, rootUID, rootGID); err != nil { <ide> if perr, ok := err.(*os.PathError); ok { <ide> if perr.Err != syscall.ENOTDIR { <del> return "", err <add> return "", errors.Wrapf(err, "error while creating mount source path '%s'", m.Source) <ide> } <ide> } <ide> } <ide> } <ide> if label.RelabelNeeded(m.Mode) { <ide> if err := label.Relabel(m.Source, mountLabel, label.IsShared(m.Mode)); err != nil { <del> return "", err <add> return "", errors.Wrapf(err, "error setting label on mount source '%s'", m.Source) <ide> } <ide> } <ide> return m.Source, nil
4
Javascript
Javascript
add netlify badge
3e350ec3d824432e69c44ceebbd14c10225baa8c
<ide><path>website/docusaurus.config.js <ide> module.exports = { <ide> { <ide> label: 'GitHub', <ide> href: 'https://github.com/reduxjs/redux' <add> }, <add> { <add> html: ` <add> <a href="https://www.netlify.com"> <add> <img <add> src="https://www.netlify.com/img/global/badges/netlify-color-accent.svg" <add> alt="Deploys by Netlify" <add> /> <add> </a> <add> ` <ide> } <ide> ] <ide> } <ide> ], <ide> logo: { <ide> alt: 'Redux Logo', <ide> src: 'img/redux.svg', <del> href: 'https://redux.js.org/', <add> href: 'https://redux.js.org/' <ide> }, <ide> copyright: <ide> 'Copyright (c) 2015-present Dan Abramov and the Redux documentation authors.'
1
Javascript
Javascript
remove jquery.curcss, closes gh-801
2d37b6ccb8a5fb9eb47a43221ec10faa693e63c5
<ide><path>src/css.js <ide> jQuery.extend({ <ide> } <ide> }); <ide> <del>// DEPRECATED in 1.3, Use jQuery.css() instead <del>jQuery.curCSS = jQuery.css; <del> <ide> if ( document.defaultView && document.defaultView.getComputedStyle ) { <ide> curCSS = function( elem, name ) { <ide> var ret, defaultView, computedStyle, width,
1
Text
Text
add example of bubble sort in swift
8fd54d9d482ae253c4c46a67dcc80cb98665cecb
<ide><path>client/src/pages/guide/english/algorithms/sorting-algorithms/bubble-sort/index.md <ide> Now, the array is already sorted, but our algorithm does not know if it is compl <ide> ### Video Explanation <ide> [Bubble sort in easy way](https://www.youtube.com/watch?v=Jdtq5uKz-w4) <ide> <del>This code will use bubble sort to sort the array. <add>----- <add> <add>### Example in JavaScript <ide> ```js <ide> let arr = [1, 4, 7, 45, 7,43, 44, 25, 6, 4, 6, 9]; <ide> let sorted = false <ide> while(!sorted) { <ide> } <ide> } <ide> ``` <del> <del>### Properties: <del>* Space Complexity: O(1) <del>* Time Complexity: O(n), O(n* n), O(n* n) for Best, Average and Worst cases respectively. <del>* In place: Yes <del>* Stable: Yes <del> <del>======= <del>Here is the algorithm written in Java. <del> <add>### Example in Java. <ide> ```java <ide> public class bubble-sort { <ide> static void sort(int[] arr) { <ide> public class bubble-sort { <ide> } <ide> } <ide> ``` <del>======= <del>###The Recursive implementation of the Bubble Sort. <del> <add>### Example in C++ <ide> ```c++ <add>// Recursive Implementation <ide> void bubblesort(int arr[], int n) <ide> { <ide> if(n==1) //Initial Case <ide> void bubblesort(int arr[], int n) <ide> bubblesort(arr,n-1); //Recursion for remaining array <ide> } <ide> ``` <add>### Example in 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>``` <ide> ### More Information <ide> <!-- Please add any articles you think might be helpful to read before writing the article --> <ide> - [Wikipedia](https://en.wikipedia.org/wiki/Bubble_sort)
1
Ruby
Ruby
remove unused variable causing warning in 1.9.3
c4ddc6f693fd63ce047222c1468071a8063f210f
<ide><path>actionpack/test/abstract/abstract_controller_test.rb <ide> def index <ide> class TestLayouts < ActiveSupport::TestCase <ide> test "layouts are included" do <ide> controller = Me4.new <del> result = controller.process(:index) <add> controller.process(:index) <ide> assert_equal "Me4 Enter : Hello from me4/index.erb : Exit", controller.response_body <ide> end <ide> end
1
Text
Text
add note on how to submit a form
772468183f66de15d02de6e29772808c33d61545
<ide><path>docs/docs/07-forms.md <ide> To make an uncontrolled component, `defaultValue` is used instead. <ide> > Note: <ide> > <ide> > You can pass an array into the `value` attribute, allowing you to select multiple options in a `select` tag: `<select multiple={true} value={['B', 'C']}>`. <add> <add>### Imperative operations <add> <add>If you need to imperatively perform an operation, you have to obtain a [reference to the DOM node](/react/docs/more-about-refs.html#the-ref-callback-attribute). <add>For instance, if you want to imperatively submit a form, one approach would be to attach a `ref` to the `form` element and manually call `form.submit()`.
1
Python
Python
update minimum version of sshtunnel to 0.3.2
537963f24d83b08c546112bac33bf0f44d95fe1c
<ide><path>airflow/providers/ssh/hooks/ssh.py <ide> def get_tunnel( <ide> ) <ide> else: <ide> tunnel_kwargs.update( <del> host_pkey_directories=[], <add> host_pkey_directories=None, <ide> ) <ide> <ide> client = SSHTunnelForwarder(self.remote_host, **tunnel_kwargs) <ide><path>setup.py <ide> def write_version(filename: str = os.path.join(*[my_dir, "airflow", "git_version <ide> ssh = [ <ide> 'paramiko>=2.6.0', <ide> 'pysftp>=0.2.9', <del> 'sshtunnel>=0.1.4,<0.2', <add> 'sshtunnel>=0.3.2,<0.5', <ide> ] <ide> statsd = [ <ide> 'statsd>=3.3.0, <4.0', <ide><path>tests/providers/ssh/hooks/test_ssh.py <ide> def test_tunnel_without_password(self, ssh_mock): <ide> ssh_proxy=None, <ide> local_bind_address=('localhost',), <ide> remote_bind_address=('localhost', 1234), <del> host_pkey_directories=[], <add> host_pkey_directories=None, <ide> logger=hook.log, <ide> ) <ide> <ide> def test_tunnel_with_private_key(self, ssh_mock): <ide> ssh_proxy=None, <ide> local_bind_address=('localhost',), <ide> remote_bind_address=('localhost', 1234), <del> host_pkey_directories=[], <add> host_pkey_directories=None, <ide> logger=hook.log, <ide> ) <ide> <ide> def test_tunnel_with_private_key_passphrase(self, ssh_mock): <ide> ssh_proxy=None, <ide> local_bind_address=('localhost',), <ide> remote_bind_address=('localhost', 1234), <del> host_pkey_directories=[], <add> host_pkey_directories=None, <ide> logger=hook.log, <ide> ) <ide> <ide> def test_tunnel_with_private_key_ecdsa(self, ssh_mock): <ide> ssh_proxy=None, <ide> local_bind_address=('localhost',), <ide> remote_bind_address=('localhost', 1234), <del> host_pkey_directories=[], <add> host_pkey_directories=None, <ide> logger=hook.log, <ide> ) <ide> <ide> def test_tunnel(self): <ide> args=["python", "-c", HELLO_SERVER_CMD], <ide> stdout=subprocess.PIPE, <ide> ) <del> with subprocess.Popen(**subprocess_kwargs) as server_handle, hook.create_tunnel(2135, 2134): <add> with subprocess.Popen(**subprocess_kwargs) as server_handle, hook.get_tunnel( <add> local_port=2135, remote_port=2134 <add> ): <ide> server_output = server_handle.stdout.read(5) <ide> assert b"ready" == server_output <ide> socket = socket.socket()
3
Ruby
Ruby
add schema cache to new connection pool after fork
19bc570832e01c47f42ac2096637df59613c0efa
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb <ide> def pool_for(owner) <ide> # A connection was established in an ancestor process that must have <ide> # subsequently forked. We can't reuse the connection, but we can copy <ide> # the specification and establish a new connection with it. <del> establish_connection owner, ancestor_pool.spec <add> establish_connection(owner, ancestor_pool.spec).tap do |pool| <add> pool.schema_cache = ancestor_pool.schema_cache if ancestor_pool.schema_cache <add> end <ide> else <ide> owner_to_pool[owner.name] = nil <ide> end <ide><path>activerecord/test/cases/connection_adapters/connection_handler_test.rb <ide> def test_retrieve_connection_pool_uses_superclass_pool_after_subclass_establish_ <ide> def test_connection_pools <ide> assert_equal([@pool], @handler.connection_pools) <ide> end <add> <add> if Process.respond_to?(:fork) <add> def test_connection_pool_per_pid <add> object_id = ActiveRecord::Base.connection.object_id <add> <add> rd, wr = IO.pipe <add> rd.binmode <add> wr.binmode <add> <add> pid = fork { <add> rd.close <add> wr.write Marshal.dump ActiveRecord::Base.connection.object_id <add> wr.close <add> exit! <add> } <add> <add> wr.close <add> <add> Process.waitpid pid <add> assert_not_equal object_id, Marshal.load(rd.read) <add> rd.close <add> end <add> <add> def test_retrieve_connection_pool_copies_schema_cache_from_ancestor_pool <add> @pool.schema_cache = @pool.connection.schema_cache <add> @pool.schema_cache.add('posts') <add> <add> rd, wr = IO.pipe <add> rd.binmode <add> wr.binmode <add> <add> pid = fork { <add> rd.close <add> pool = @handler.retrieve_connection_pool(@klass) <add> wr.write Marshal.dump pool.schema_cache.size <add> wr.close <add> exit! <add> } <add> <add> wr.close <add> <add> Process.waitpid pid <add> assert_equal @pool.schema_cache.size, Marshal.load(rd.read) <add> rd.close <add> end <add> end <ide> end <ide> end <ide> end <ide><path>activerecord/test/cases/connection_management_test.rb <ide> def setup <ide> assert ActiveRecord::Base.connection_handler.active_connections? <ide> end <ide> <del> if Process.respond_to?(:fork) <del> def test_connection_pool_per_pid <del> object_id = ActiveRecord::Base.connection.object_id <del> <del> rd, wr = IO.pipe <del> rd.binmode <del> wr.binmode <del> <del> pid = fork { <del> rd.close <del> wr.write Marshal.dump ActiveRecord::Base.connection.object_id <del> wr.close <del> exit! <del> } <del> <del> wr.close <del> <del> Process.waitpid pid <del> assert_not_equal object_id, Marshal.load(rd.read) <del> rd.close <del> end <del> end <del> <ide> def test_app_delegation <ide> manager = ConnectionManagement.new(@app) <ide>
3
Javascript
Javascript
add simple tests for closed radial areas
dbee8568b3f1e31cc7867c76105c818d772a934c
<ide><path>test/svg/area-radial-test.js <ide> suite.addBatch({ <ide> <ide> "interpolate(basis)": { <ide> "supports basis interpolation": testInterpolation("basis"), <del> "supports basis-open interpolation": testInterpolation("basis-open") <add> "supports basis-open interpolation": testInterpolation("basis-open"), <add> "supports basis-closed interpolation": testInterpolation("basis-closed") <ide> }, <ide> <ide> "interpolate(cardinal)": { <ide> "supports cardinal interpolation": testInterpolation("cardinal"), <del> "supports cardinal-open interpolation": testInterpolation("cardinal-open") <add> "supports cardinal-open interpolation": testInterpolation("cardinal-open"), <add> "supports cardinal-closed interpolation": testInterpolation("cardinal-open") <ide> }, <ide> <ide> "interpolate(monotone)": {
1
Java
Java
implement snaptoalignment in vertical scrollview
e774c037bce40a4b48e78d2d0a1085a1e4f5a328
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollView.java <ide> private void flingAndSnap(int velocityX) { <ide> itemStartOffset = item.getLeft() - (width - item.getWidth()); <ide> break; <ide> default: <del> throw new IllegalStateException(""); <add> throw new IllegalStateException("Invalid SnapToAlignment value: " + mSnapToAlignment); <ide> } <ide> if (itemStartOffset <= targetOffset) { <ide> if (targetOffset - itemStartOffset < targetOffset - smallerOffset) { <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollView.java <ide> <ide> package com.facebook.react.views.scroll; <ide> <add>import static com.facebook.react.views.scroll.ReactScrollViewHelper.SNAP_ALIGNMENT_CENTER; <ide> import static com.facebook.react.views.scroll.ReactScrollViewHelper.SNAP_ALIGNMENT_DISABLED; <add>import static com.facebook.react.views.scroll.ReactScrollViewHelper.SNAP_ALIGNMENT_END; <add>import static com.facebook.react.views.scroll.ReactScrollViewHelper.SNAP_ALIGNMENT_START; <ide> <ide> import android.animation.Animator; <ide> import android.animation.ObjectAnimator; <ide> private int predictFinalScrollPosition(int velocityY) { <ide> return scroller.getFinalY(); <ide> } <ide> <add> private View getContentView() { <add> return getChildAt(0); <add> } <add> <ide> /** <ide> * This will smooth scroll us to the nearest snap offset point It currently just looks at where <ide> * the content is and slides to the nearest point. It is intended to be run after we are done <ide> private void flingAndSnap(int velocityY) { <ide> } <ide> <ide> // pagingEnabled only allows snapping one interval at a time <del> if (mSnapInterval == 0 && mSnapOffsets == null) { <add> if (mSnapInterval == 0 && mSnapOffsets == null && mSnapToAlignment == SNAP_ALIGNMENT_DISABLED) { <ide> smoothScrollAndSnap(velocityY); <ide> return; <ide> } <ide> private void flingAndSnap(int velocityY) { <ide> } <ide> } <ide> } <add> <add> } else if (mSnapToAlignment != SNAP_ALIGNMENT_DISABLED) { <add> ViewGroup contentView = (ViewGroup) getContentView(); <add> for (int i = 1; i < contentView.getChildCount(); i++) { <add> View item = contentView.getChildAt(i); <add> int itemStartOffset; <add> switch (mSnapToAlignment) { <add> case SNAP_ALIGNMENT_CENTER: <add> itemStartOffset = item.getTop() - (height - item.getHeight()) / 2; <add> break; <add> case SNAP_ALIGNMENT_START: <add> itemStartOffset = item.getTop(); <add> break; <add> case SNAP_ALIGNMENT_END: <add> itemStartOffset = item.getTop() - (height - item.getHeight()); <add> break; <add> default: <add> throw new IllegalStateException("Invalid SnapToAlignment value: " + mSnapToAlignment); <add> } <add> if (itemStartOffset <= targetOffset) { <add> if (targetOffset - itemStartOffset < targetOffset - smallerOffset) { <add> smallerOffset = itemStartOffset; <add> } <add> } <add> <add> if (itemStartOffset >= targetOffset) { <add> if (itemStartOffset - targetOffset < largerOffset - targetOffset) { <add> largerOffset = itemStartOffset; <add> } <add> } <add> } <ide> } else { <ide> double interval = (double) getSnapInterval(); <ide> double ratio = (double) targetOffset / interval;
2
Ruby
Ruby
remove unnecessary method delegations
04e6728dd50cbe80a8f0039e9718dc96bc46e701
<ide><path>lib/active_storage/service/mirror_service.rb <ide> class ActiveStorage::Service::MirrorService < ActiveStorage::Service <ide> attr_reader :services <ide> <del> delegate :download, :exist?, :url, :byte_size, :checksum, to: :primary_service <add> delegate :download, :exist?, :url, to: :primary_service <ide> <ide> def initialize(services:) <ide> @services = services
1
Go
Go
add context.requestid to event stream
26b1064967d9fcefd4c35f60e96bf6d7c9a3b5f8
<ide><path>api/server/container.go <ide> func (s *Server) getContainersJSON(ctx context.Context, w http.ResponseWriter, r <ide> config.Limit = limit <ide> } <ide> <del> containers, err := s.daemon.Containers(config) <add> containers, err := s.daemon.Containers(ctx, config) <ide> if err != nil { <ide> return err <ide> } <ide> func (s *Server) getContainersStats(ctx context.Context, w http.ResponseWriter, <ide> Version: version, <ide> } <ide> <del> return s.daemon.ContainerStats(vars["name"], config) <add> return s.daemon.ContainerStats(ctx, vars["name"], config) <ide> } <ide> <ide> func (s *Server) getContainersLogs(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> func (s *Server) getContainersLogs(ctx context.Context, w http.ResponseWriter, r <ide> closeNotifier = notifier.CloseNotify() <ide> } <ide> <del> c, err := s.daemon.Get(vars["name"]) <add> c, err := s.daemon.Get(ctx, vars["name"]) <ide> if err != nil { <ide> return err <ide> } <ide> func (s *Server) getContainersLogs(ctx context.Context, w http.ResponseWriter, r <ide> Stop: closeNotifier, <ide> } <ide> <del> if err := s.daemon.ContainerLogs(c, logsConfig); err != nil { <add> if err := s.daemon.ContainerLogs(ctx, c, logsConfig); err != nil { <ide> // The client may be expecting all of the data we're sending to <ide> // be multiplexed, so send it through OutStream, which will <ide> // have been set up to handle that if needed. <ide> func (s *Server) getContainersExport(ctx context.Context, w http.ResponseWriter, <ide> return fmt.Errorf("Missing parameter") <ide> } <ide> <del> return s.daemon.ContainerExport(vars["name"], w) <add> return s.daemon.ContainerExport(ctx, vars["name"], w) <ide> } <ide> <ide> func (s *Server) postContainersStart(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> func (s *Server) postContainersStart(ctx context.Context, w http.ResponseWriter, <ide> hostConfig = c <ide> } <ide> <del> if err := s.daemon.ContainerStart(vars["name"], hostConfig); err != nil { <add> if err := s.daemon.ContainerStart(ctx, vars["name"], hostConfig); err != nil { <ide> return err <ide> } <ide> w.WriteHeader(http.StatusNoContent) <ide> func (s *Server) postContainersStop(ctx context.Context, w http.ResponseWriter, <ide> <ide> seconds, _ := strconv.Atoi(r.Form.Get("t")) <ide> <del> if err := s.daemon.ContainerStop(vars["name"], seconds); err != nil { <add> if err := s.daemon.ContainerStop(ctx, vars["name"], seconds); err != nil { <ide> return err <ide> } <ide> w.WriteHeader(http.StatusNoContent) <ide> func (s *Server) postContainersKill(ctx context.Context, w http.ResponseWriter, <ide> } <ide> } <ide> <del> if err := s.daemon.ContainerKill(name, uint64(sig)); err != nil { <add> if err := s.daemon.ContainerKill(ctx, name, uint64(sig)); err != nil { <ide> theErr, isDerr := err.(errcode.ErrorCoder) <ide> isStopped := isDerr && theErr.ErrorCode() == derr.ErrorCodeNotRunning <ide> <ide> func (s *Server) postContainersRestart(ctx context.Context, w http.ResponseWrite <ide> <ide> timeout, _ := strconv.Atoi(r.Form.Get("t")) <ide> <del> if err := s.daemon.ContainerRestart(vars["name"], timeout); err != nil { <add> if err := s.daemon.ContainerRestart(ctx, vars["name"], timeout); err != nil { <ide> return err <ide> } <ide> <ide> func (s *Server) postContainersPause(ctx context.Context, w http.ResponseWriter, <ide> return err <ide> } <ide> <del> if err := s.daemon.ContainerPause(vars["name"]); err != nil { <add> if err := s.daemon.ContainerPause(ctx, vars["name"]); err != nil { <ide> return err <ide> } <ide> <ide> func (s *Server) postContainersUnpause(ctx context.Context, w http.ResponseWrite <ide> return err <ide> } <ide> <del> if err := s.daemon.ContainerUnpause(vars["name"]); err != nil { <add> if err := s.daemon.ContainerUnpause(ctx, vars["name"]); err != nil { <ide> return err <ide> } <ide> <ide> func (s *Server) postContainersWait(ctx context.Context, w http.ResponseWriter, <ide> return fmt.Errorf("Missing parameter") <ide> } <ide> <del> status, err := s.daemon.ContainerWait(vars["name"], -1*time.Second) <add> status, err := s.daemon.ContainerWait(ctx, vars["name"], -1*time.Second) <ide> if err != nil { <ide> return err <ide> } <ide> func (s *Server) getContainersChanges(ctx context.Context, w http.ResponseWriter <ide> return fmt.Errorf("Missing parameter") <ide> } <ide> <del> changes, err := s.daemon.ContainerChanges(vars["name"]) <add> changes, err := s.daemon.ContainerChanges(ctx, vars["name"]) <ide> if err != nil { <ide> return err <ide> } <ide> func (s *Server) getContainersTop(ctx context.Context, w http.ResponseWriter, r <ide> return err <ide> } <ide> <del> procList, err := s.daemon.ContainerTop(vars["name"], r.Form.Get("ps_args")) <add> procList, err := s.daemon.ContainerTop(ctx, vars["name"], r.Form.Get("ps_args")) <ide> if err != nil { <ide> return err <ide> } <ide> func (s *Server) postContainerRename(ctx context.Context, w http.ResponseWriter, <ide> <ide> name := vars["name"] <ide> newName := r.Form.Get("name") <del> if err := s.daemon.ContainerRename(name, newName); err != nil { <add> if err := s.daemon.ContainerRename(ctx, name, newName); err != nil { <ide> return err <ide> } <ide> w.WriteHeader(http.StatusNoContent) <ide> func (s *Server) postContainersCreate(ctx context.Context, w http.ResponseWriter <ide> version := ctx.Version() <ide> adjustCPUShares := version.LessThan("1.19") <ide> <del> container, warnings, err := s.daemon.ContainerCreate(name, config, hostConfig, adjustCPUShares) <add> container, warnings, err := s.daemon.ContainerCreate(ctx, name, config, hostConfig, adjustCPUShares) <ide> if err != nil { <ide> return err <ide> } <ide> func (s *Server) deleteContainers(ctx context.Context, w http.ResponseWriter, r <ide> RemoveLink: boolValue(r, "link"), <ide> } <ide> <del> if err := s.daemon.ContainerRm(name, config); err != nil { <add> if err := s.daemon.ContainerRm(ctx, name, config); err != nil { <ide> // Force a 404 for the empty string <ide> if strings.Contains(strings.ToLower(err.Error()), "prefix can't be empty") { <ide> return fmt.Errorf("no such id: \"\"") <ide> func (s *Server) postContainersResize(ctx context.Context, w http.ResponseWriter <ide> return err <ide> } <ide> <del> return s.daemon.ContainerResize(vars["name"], height, width) <add> return s.daemon.ContainerResize(ctx, vars["name"], height, width) <ide> } <ide> <ide> func (s *Server) postContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> func (s *Server) postContainersAttach(ctx context.Context, w http.ResponseWriter <ide> } <ide> containerName := vars["name"] <ide> <del> if !s.daemon.Exists(containerName) { <add> if !s.daemon.Exists(ctx, containerName) { <ide> return derr.ErrorCodeNoSuchContainer.WithArgs(containerName) <ide> } <ide> <ide> func (s *Server) postContainersAttach(ctx context.Context, w http.ResponseWriter <ide> Stream: boolValue(r, "stream"), <ide> } <ide> <del> if err := s.daemon.ContainerAttachWithLogs(containerName, attachWithLogsConfig); err != nil { <add> if err := s.daemon.ContainerAttachWithLogs(ctx, containerName, attachWithLogsConfig); err != nil { <ide> fmt.Fprintf(outStream, "Error attaching: %s\n", err) <ide> } <ide> <ide> func (s *Server) wsContainersAttach(ctx context.Context, w http.ResponseWriter, <ide> } <ide> containerName := vars["name"] <ide> <del> if !s.daemon.Exists(containerName) { <add> if !s.daemon.Exists(ctx, containerName) { <ide> return derr.ErrorCodeNoSuchContainer.WithArgs(containerName) <ide> } <ide> <ide> func (s *Server) wsContainersAttach(ctx context.Context, w http.ResponseWriter, <ide> Stream: boolValue(r, "stream"), <ide> } <ide> <del> if err := s.daemon.ContainerWsAttachWithLogs(containerName, wsAttachWithLogsConfig); err != nil { <add> if err := s.daemon.ContainerWsAttachWithLogs(ctx, containerName, wsAttachWithLogsConfig); err != nil { <ide> logrus.Errorf("Error attaching websocket: %s", err) <ide> } <ide> }) <ide><path>api/server/copy.go <ide> func (s *Server) postContainersCopy(ctx context.Context, w http.ResponseWriter, <ide> return fmt.Errorf("Path cannot be empty") <ide> } <ide> <del> data, err := s.daemon.ContainerCopy(vars["name"], cfg.Resource) <add> data, err := s.daemon.ContainerCopy(ctx, vars["name"], cfg.Resource) <ide> if err != nil { <ide> if strings.Contains(strings.ToLower(err.Error()), "no such id") { <ide> w.WriteHeader(http.StatusNotFound) <ide> func (s *Server) headContainersArchive(ctx context.Context, w http.ResponseWrite <ide> return err <ide> } <ide> <del> stat, err := s.daemon.ContainerStatPath(v.name, v.path) <add> stat, err := s.daemon.ContainerStatPath(ctx, v.name, v.path) <ide> if err != nil { <ide> return err <ide> } <ide> func (s *Server) getContainersArchive(ctx context.Context, w http.ResponseWriter <ide> return err <ide> } <ide> <del> tarArchive, stat, err := s.daemon.ContainerArchivePath(v.name, v.path) <add> tarArchive, stat, err := s.daemon.ContainerArchivePath(ctx, v.name, v.path) <ide> if err != nil { <ide> return err <ide> } <ide> func (s *Server) putContainersArchive(ctx context.Context, w http.ResponseWriter <ide> } <ide> <ide> noOverwriteDirNonDir := boolValue(r, "noOverwriteDirNonDir") <del> return s.daemon.ContainerExtractToDir(v.name, v.path, noOverwriteDirNonDir, r.Body) <add> return s.daemon.ContainerExtractToDir(ctx, v.name, v.path, noOverwriteDirNonDir, r.Body) <ide> } <ide><path>api/server/daemon.go <ide> func (s *Server) getVersion(ctx context.Context, w http.ResponseWriter, r *http. <ide> } <ide> <ide> func (s *Server) getInfo(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <del> info, err := s.daemon.SystemInfo() <add> info, err := s.daemon.SystemInfo(ctx) <ide> if err != nil { <ide> return err <ide> } <ide> func (s *Server) getEvents(ctx context.Context, w http.ResponseWriter, r *http.R <ide> enc := json.NewEncoder(outStream) <ide> <ide> getContainerID := func(cn string) string { <del> c, err := d.Get(cn) <add> c, err := d.Get(ctx, cn) <ide> if err != nil { <ide> return "" <ide> } <ide><path>api/server/exec.go <ide> func (s *Server) getExecByID(ctx context.Context, w http.ResponseWriter, r *http <ide> return fmt.Errorf("Missing parameter 'id'") <ide> } <ide> <del> eConfig, err := s.daemon.ContainerExecInspect(vars["id"]) <add> eConfig, err := s.daemon.ContainerExecInspect(ctx, vars["id"]) <ide> if err != nil { <ide> return err <ide> } <ide> func (s *Server) postContainerExecCreate(ctx context.Context, w http.ResponseWri <ide> } <ide> <ide> // Register an instance of Exec in container. <del> id, err := s.daemon.ContainerExecCreate(execConfig) <add> id, err := s.daemon.ContainerExecCreate(ctx, execConfig) <ide> if err != nil { <ide> logrus.Errorf("Error setting up exec command in container %s: %s", name, err) <ide> return err <ide> func (s *Server) postContainerExecStart(ctx context.Context, w http.ResponseWrit <ide> } <ide> <ide> // Now run the user process in container. <del> if err := s.daemon.ContainerExecStart(execName, stdin, stdout, stderr); err != nil { <add> if err := s.daemon.ContainerExecStart(ctx, execName, stdin, stdout, stderr); err != nil { <ide> fmt.Fprintf(outStream, "Error running exec in container: %v\n", err) <ide> } <ide> return nil <ide> func (s *Server) postContainerExecResize(ctx context.Context, w http.ResponseWri <ide> return err <ide> } <ide> <del> return s.daemon.ContainerExecResize(vars["name"], height, width) <add> return s.daemon.ContainerExecResize(ctx, vars["name"], height, width) <ide> } <ide><path>api/server/image.go <ide> func (s *Server) postCommit(ctx context.Context, w http.ResponseWriter, r *http. <ide> Config: c, <ide> } <ide> <del> imgID, err := builder.Commit(cname, s.daemon, commitCfg) <add> imgID, err := builder.Commit(ctx, cname, s.daemon, commitCfg) <ide> if err != nil { <ide> return err <ide> } <ide> func (s *Server) postImagesCreate(ctx context.Context, w http.ResponseWriter, r <ide> OutStream: output, <ide> } <ide> <del> err = s.daemon.Repositories().Pull(image, tag, imagePullConfig) <add> err = s.daemon.Repositories(ctx).Pull(ctx, image, tag, imagePullConfig) <ide> } else { //import <ide> if tag == "" { <ide> repo, tag = parsers.ParseRepositoryTag(repo) <ide> func (s *Server) postImagesCreate(ctx context.Context, w http.ResponseWriter, r <ide> // generated from the download to be available to the output <ide> // stream processing below <ide> var newConfig *runconfig.Config <del> newConfig, err = builder.BuildFromConfig(s.daemon, &runconfig.Config{}, r.Form["changes"]) <add> newConfig, err = builder.BuildFromConfig(ctx, s.daemon, &runconfig.Config{}, r.Form["changes"]) <ide> if err != nil { <ide> return err <ide> } <ide> <del> err = s.daemon.Repositories().Import(src, repo, tag, message, r.Body, output, newConfig) <add> err = s.daemon.Repositories(ctx).Import(ctx, src, repo, tag, message, r.Body, output, newConfig) <ide> } <ide> if err != nil { <ide> if !output.Flushed() { <ide> func (s *Server) postImagesPush(ctx context.Context, w http.ResponseWriter, r *h <ide> <ide> w.Header().Set("Content-Type", "application/json") <ide> <del> if err := s.daemon.Repositories().Push(name, imagePushConfig); err != nil { <add> if err := s.daemon.Repositories(ctx).Push(ctx, name, imagePushConfig); err != nil { <ide> if !output.Flushed() { <ide> return err <ide> } <ide> func (s *Server) getImagesGet(ctx context.Context, w http.ResponseWriter, r *htt <ide> names = r.Form["names"] <ide> } <ide> <del> if err := s.daemon.Repositories().ImageExport(names, output); err != nil { <add> if err := s.daemon.Repositories(ctx).ImageExport(names, output); err != nil { <ide> if !output.Flushed() { <ide> return err <ide> } <ide> func (s *Server) getImagesGet(ctx context.Context, w http.ResponseWriter, r *htt <ide> } <ide> <ide> func (s *Server) postImagesLoad(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <del> return s.daemon.Repositories().Load(r.Body, w) <add> return s.daemon.Repositories(ctx).Load(r.Body, w) <ide> } <ide> <ide> func (s *Server) deleteImages(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { <ide> func (s *Server) deleteImages(ctx context.Context, w http.ResponseWriter, r *htt <ide> force := boolValue(r, "force") <ide> prune := !boolValue(r, "noprune") <ide> <del> list, err := s.daemon.ImageDelete(name, force, prune) <add> list, err := s.daemon.ImageDelete(ctx, name, force, prune) <ide> if err != nil { <ide> return err <ide> } <ide> func (s *Server) getImagesByName(ctx context.Context, w http.ResponseWriter, r * <ide> return fmt.Errorf("Missing parameter") <ide> } <ide> <del> imageInspect, err := s.daemon.Repositories().Lookup(vars["name"]) <add> imageInspect, err := s.daemon.Repositories(ctx).Lookup(vars["name"]) <ide> if err != nil { <ide> return err <ide> } <ide> func (s *Server) postBuild(ctx context.Context, w http.ResponseWriter, r *http.R <ide> }() <ide> } <ide> <del> if err := builder.Build(s.daemon, buildConfig); err != nil { <add> if err := builder.Build(ctx, s.daemon, buildConfig); err != nil { <ide> // Do not write the error in the http output if it's still empty. <ide> // This prevents from writing a 200(OK) when there is an interal error. <ide> if !output.Flushed() { <ide> func (s *Server) getImagesJSON(ctx context.Context, w http.ResponseWriter, r *ht <ide> } <ide> <ide> // FIXME: The filter parameter could just be a match filter <del> images, err := s.daemon.Repositories().Images(r.Form.Get("filters"), r.Form.Get("filter"), boolValue(r, "all")) <add> images, err := s.daemon.Repositories(ctx).Images(r.Form.Get("filters"), r.Form.Get("filter"), boolValue(r, "all")) <ide> if err != nil { <ide> return err <ide> } <ide> func (s *Server) getImagesHistory(ctx context.Context, w http.ResponseWriter, r <ide> } <ide> <ide> name := vars["name"] <del> history, err := s.daemon.Repositories().History(name) <add> history, err := s.daemon.Repositories(ctx).History(name) <ide> if err != nil { <ide> return err <ide> } <ide> func (s *Server) postImagesTag(ctx context.Context, w http.ResponseWriter, r *ht <ide> tag := r.Form.Get("tag") <ide> force := boolValue(r, "force") <ide> name := vars["name"] <del> if err := s.daemon.Repositories().Tag(repo, tag, name, force); err != nil { <add> if err := s.daemon.Repositories(ctx).Tag(repo, tag, name, force); err != nil { <ide> return err <ide> } <del> s.daemon.EventsService.Log("tag", utils.ImageReference(repo, tag), "") <add> s.daemon.EventsService.Log(ctx, "tag", utils.ImageReference(repo, tag), "") <ide> w.WriteHeader(http.StatusCreated) <ide> return nil <ide> } <ide><path>api/server/inspect.go <ide> func (s *Server) getContainersByName(ctx context.Context, w http.ResponseWriter, <ide> <ide> switch { <ide> case version.LessThan("1.20"): <del> json, err = s.daemon.ContainerInspectPre120(vars["name"]) <add> json, err = s.daemon.ContainerInspectPre120(ctx, vars["name"]) <ide> case version.Equal("1.20"): <del> json, err = s.daemon.ContainerInspect120(vars["name"]) <add> json, err = s.daemon.ContainerInspect120(ctx, vars["name"]) <ide> default: <del> json, err = s.daemon.ContainerInspect(vars["name"]) <add> json, err = s.daemon.ContainerInspect(ctx, vars["name"]) <ide> } <ide> <ide> if err != nil { <ide><path>api/server/server.go <ide> import ( <ide> "github.com/docker/docker/context" <ide> "github.com/docker/docker/daemon" <ide> "github.com/docker/docker/pkg/sockets" <add> "github.com/docker/docker/pkg/stringid" <ide> "github.com/docker/docker/utils" <ide> ) <ide> <ide> type Server struct { <ide> } <ide> <ide> // New returns a new instance of the server based on the specified configuration. <del>func New(cfg *Config) *Server { <add>func New(ctx context.Context, cfg *Config) *Server { <ide> srv := &Server{ <ide> cfg: cfg, <ide> start: make(chan struct{}), <ide> } <del> srv.router = createRouter(srv) <add> srv.router = createRouter(ctx, srv) <ide> return srv <ide> } <ide> <ide> func (s *Server) initTCPSocket(addr string) (l net.Listener, err error) { <ide> return <ide> } <ide> <del>func (s *Server) makeHTTPHandler(localMethod string, localRoute string, localHandler HTTPAPIFunc) http.HandlerFunc { <add>func (s *Server) makeHTTPHandler(ctx context.Context, localMethod string, localRoute string, localHandler HTTPAPIFunc) http.HandlerFunc { <ide> return func(w http.ResponseWriter, r *http.Request) { <ide> // log the handler generation <ide> logrus.Debugf("Calling %s %s", localMethod, localRoute) <ide> func (s *Server) makeHTTPHandler(localMethod string, localRoute string, localHan <ide> // apply to all requests. Data that is specific to the <ide> // immediate function being called should still be passed <ide> // as 'args' on the function call. <del> ctx := context.Background() <add> reqID := stringid.TruncateID(stringid.GenerateNonCryptoID()) <add> ctx = context.WithValue(ctx, context.RequestID, reqID) <ide> handlerFunc := s.handleWithGlobalMiddlewares(localHandler) <ide> <ide> if err := handlerFunc(ctx, w, r, mux.Vars(r)); err != nil { <ide> func (s *Server) makeHTTPHandler(localMethod string, localRoute string, localHan <ide> <ide> // createRouter initializes the main router the server uses. <ide> // we keep enableCors just for legacy usage, need to be removed in the future <del>func createRouter(s *Server) *mux.Router { <add>func createRouter(ctx context.Context, s *Server) *mux.Router { <ide> r := mux.NewRouter() <ide> if os.Getenv("DEBUG") != "" { <ide> profilerSetup(r, "/debug/") <ide> func createRouter(s *Server) *mux.Router { <ide> localMethod := method <ide> <ide> // build the handler function <del> f := s.makeHTTPHandler(localMethod, localRoute, localFct) <add> f := s.makeHTTPHandler(ctx, localMethod, localRoute, localFct) <ide> <ide> // add the new route <ide> if localRoute == "" { <ide><path>api/server/server_experimental_unix.go <ide> <ide> package server <ide> <del>func (s *Server) registerSubRouter() { <del> httpHandler := s.daemon.NetworkAPIRouter() <add>import ( <add> "github.com/docker/docker/context" <add>) <add> <add>func (s *Server) registerSubRouter(ctx context.Context) { <add> httpHandler := s.daemon.NetworkAPIRouter(ctx) <ide> <ide> subrouter := s.router.PathPrefix("/v{version:[0-9.]+}/networks").Subrouter() <ide> subrouter.Methods("GET", "POST", "PUT", "DELETE").HandlerFunc(httpHandler) <ide><path>api/server/server_stub.go <ide> <ide> package server <ide> <del>func (s *Server) registerSubRouter() { <add>import ( <add> "github.com/docker/docker/context" <add>) <add> <add>func (s *Server) registerSubRouter(ctx context.Context) { <ide> } <ide><path>api/server/server_unix.go <ide> import ( <ide> "net/http" <ide> "strconv" <ide> <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/daemon" <ide> "github.com/docker/docker/pkg/sockets" <ide> "github.com/docker/libnetwork/portallocator" <ide> func (s *Server) newServer(proto, addr string) ([]serverCloser, error) { <ide> // AcceptConnections allows clients to connect to the API server. <ide> // Referenced Daemon is notified about this server, and waits for the <ide> // daemon acknowledgement before the incoming connections are accepted. <del>func (s *Server) AcceptConnections(d *daemon.Daemon) { <add>func (s *Server) AcceptConnections(ctx context.Context, d *daemon.Daemon) { <ide> // Tell the init daemon we are accepting requests <ide> s.daemon = d <del> s.registerSubRouter() <add> s.registerSubRouter(ctx) <ide> go systemdDaemon.SdNotify("READY=1") <ide> // close the lock so the listeners start accepting connections <ide> select { <ide><path>api/server/server_windows.go <ide> import ( <ide> "net" <ide> "net/http" <ide> <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/daemon" <ide> ) <ide> <ide> func (s *Server) newServer(proto, addr string) ([]serverCloser, error) { <ide> } <ide> <ide> // AcceptConnections allows router to start listening for the incoming requests. <del>func (s *Server) AcceptConnections(d *daemon.Daemon) { <add>func (s *Server) AcceptConnections(ctx context.Context, d *daemon.Daemon) { <ide> s.daemon = d <del> s.registerSubRouter() <add> s.registerSubRouter(ctx) <ide> // close the lock so the listeners start accepting connections <ide> select { <ide> case <-s.start: <ide><path>api/server/volume.go <ide> func (s *Server) getVolumesList(ctx context.Context, w http.ResponseWriter, r *h <ide> return err <ide> } <ide> <del> volumes, err := s.daemon.Volumes(r.Form.Get("filters")) <add> volumes, err := s.daemon.Volumes(ctx, r.Form.Get("filters")) <ide> if err != nil { <ide> return err <ide> } <ide> func (s *Server) getVolumeByName(ctx context.Context, w http.ResponseWriter, r * <ide> return err <ide> } <ide> <del> v, err := s.daemon.VolumeInspect(vars["name"]) <add> v, err := s.daemon.VolumeInspect(ctx, vars["name"]) <ide> if err != nil { <ide> return err <ide> } <ide> func (s *Server) postVolumesCreate(ctx context.Context, w http.ResponseWriter, r <ide> return err <ide> } <ide> <del> volume, err := s.daemon.VolumeCreate(req.Name, req.Driver, req.DriverOpts) <add> volume, err := s.daemon.VolumeCreate(ctx, req.Name, req.Driver, req.DriverOpts) <ide> if err != nil { <ide> return err <ide> } <ide> func (s *Server) deleteVolumes(ctx context.Context, w http.ResponseWriter, r *ht <ide> if err := parseForm(r); err != nil { <ide> return err <ide> } <del> if err := s.daemon.VolumeRm(vars["name"]); err != nil { <add> if err := s.daemon.VolumeRm(ctx, vars["name"]); err != nil { <ide> return err <ide> } <ide> w.WriteHeader(http.StatusNoContent) <ide><path>builder/dispatchers.go <ide> import ( <ide> "strings" <ide> <ide> "github.com/Sirupsen/logrus" <add> "github.com/docker/docker/context" <ide> derr "github.com/docker/docker/errors" <ide> flag "github.com/docker/docker/pkg/mflag" <ide> "github.com/docker/docker/pkg/nat" <ide> func nullDispatch(b *builder, args []string, attributes map[string]bool, origina <ide> // Sets the environment variable foo to bar, also makes interpolation <ide> // in the dockerfile available from the next statement on via ${foo}. <ide> // <del>func env(b *builder, args []string, attributes map[string]bool, original string) error { <add>func env(ctx context.Context, b *builder, args []string, attributes map[string]bool, original string) error { <ide> if len(args) == 0 { <ide> return derr.ErrorCodeAtLeastOneArg.WithArgs("ENV") <ide> } <ide> func env(b *builder, args []string, attributes map[string]bool, original string) <ide> j++ <ide> } <ide> <del> return b.commit("", b.Config.Cmd, commitStr) <add> return b.commit(ctx, "", b.Config.Cmd, commitStr) <ide> } <ide> <ide> // MAINTAINER some text <[email protected]> <ide> // <ide> // Sets the maintainer metadata. <del>func maintainer(b *builder, args []string, attributes map[string]bool, original string) error { <add>func maintainer(ctx context.Context, b *builder, args []string, attributes map[string]bool, original string) error { <ide> if len(args) != 1 { <ide> return derr.ErrorCodeExactlyOneArg.WithArgs("MAINTAINER") <ide> } <ide> func maintainer(b *builder, args []string, attributes map[string]bool, original <ide> } <ide> <ide> b.maintainer = args[0] <del> return b.commit("", b.Config.Cmd, fmt.Sprintf("MAINTAINER %s", b.maintainer)) <add> return b.commit(ctx, "", b.Config.Cmd, fmt.Sprintf("MAINTAINER %s", b.maintainer)) <ide> } <ide> <ide> // LABEL some json data describing the image <ide> // <ide> // Sets the Label variable foo to bar, <ide> // <del>func label(b *builder, args []string, attributes map[string]bool, original string) error { <add>func label(ctx context.Context, b *builder, args []string, attributes map[string]bool, original string) error { <ide> if len(args) == 0 { <ide> return derr.ErrorCodeAtLeastOneArg.WithArgs("LABEL") <ide> } <ide> func label(b *builder, args []string, attributes map[string]bool, original strin <ide> b.Config.Labels[args[j]] = args[j+1] <ide> j++ <ide> } <del> return b.commit("", b.Config.Cmd, commitStr) <add> return b.commit(ctx, "", b.Config.Cmd, commitStr) <ide> } <ide> <ide> // ADD foo /path <ide> // <ide> // Add the file 'foo' to '/path'. Tarball and Remote URL (git, http) handling <ide> // exist here. If you do not wish to have this automatic handling, use COPY. <ide> // <del>func add(b *builder, args []string, attributes map[string]bool, original string) error { <add>func add(ctx context.Context, b *builder, args []string, attributes map[string]bool, original string) error { <ide> if len(args) < 2 { <ide> return derr.ErrorCodeAtLeastTwoArgs.WithArgs("ADD") <ide> } <ide> func add(b *builder, args []string, attributes map[string]bool, original string) <ide> return err <ide> } <ide> <del> return b.runContextCommand(args, true, true, "ADD") <add> return b.runContextCommand(ctx, args, true, true, "ADD") <ide> } <ide> <ide> // COPY foo /path <ide> // <ide> // Same as 'ADD' but without the tar and remote url handling. <ide> // <del>func dispatchCopy(b *builder, args []string, attributes map[string]bool, original string) error { <add>func dispatchCopy(ctx context.Context, b *builder, args []string, attributes map[string]bool, original string) error { <ide> if len(args) < 2 { <ide> return derr.ErrorCodeAtLeastTwoArgs.WithArgs("COPY") <ide> } <ide> func dispatchCopy(b *builder, args []string, attributes map[string]bool, origina <ide> return err <ide> } <ide> <del> return b.runContextCommand(args, false, false, "COPY") <add> return b.runContextCommand(ctx, args, false, false, "COPY") <ide> } <ide> <ide> // FROM imagename <ide> // <ide> // This sets the image the dockerfile will build on top of. <ide> // <del>func from(b *builder, args []string, attributes map[string]bool, original string) error { <add>func from(ctx context.Context, b *builder, args []string, attributes map[string]bool, original string) error { <ide> if len(args) != 1 { <ide> return derr.ErrorCodeExactlyOneArg.WithArgs("FROM") <ide> } <ide> func from(b *builder, args []string, attributes map[string]bool, original string <ide> return nil <ide> } <ide> <del> image, err := b.Daemon.Repositories().LookupImage(name) <add> image, err := b.Daemon.Repositories(ctx).LookupImage(name) <ide> if b.Pull { <del> image, err = b.pullImage(name) <add> image, err = b.pullImage(ctx, name) <ide> if err != nil { <ide> return err <ide> } <ide> } <ide> if err != nil { <del> if b.Daemon.Graph().IsNotExist(err, name) { <del> image, err = b.pullImage(name) <add> if b.Daemon.Graph(ctx).IsNotExist(err, name) { <add> image, err = b.pullImage(ctx, name) <ide> } <ide> <ide> // note that the top level err will still be !nil here if IsNotExist is <ide> func from(b *builder, args []string, attributes map[string]bool, original string <ide> } <ide> } <ide> <del> return b.processImageFrom(image) <add> return b.processImageFrom(ctx, image) <ide> } <ide> <ide> // ONBUILD RUN echo yo <ide> func from(b *builder, args []string, attributes map[string]bool, original string <ide> // special cases. search for 'OnBuild' in internals.go for additional special <ide> // cases. <ide> // <del>func onbuild(b *builder, args []string, attributes map[string]bool, original string) error { <add>func onbuild(ctx context.Context, b *builder, args []string, attributes map[string]bool, original string) error { <ide> if len(args) == 0 { <ide> return derr.ErrorCodeAtLeastOneArg.WithArgs("ONBUILD") <ide> } <ide> func onbuild(b *builder, args []string, attributes map[string]bool, original str <ide> original = regexp.MustCompile(`(?i)^\s*ONBUILD\s*`).ReplaceAllString(original, "") <ide> <ide> b.Config.OnBuild = append(b.Config.OnBuild, original) <del> return b.commit("", b.Config.Cmd, fmt.Sprintf("ONBUILD %s", original)) <add> return b.commit(ctx, "", b.Config.Cmd, fmt.Sprintf("ONBUILD %s", original)) <ide> } <ide> <ide> // WORKDIR /tmp <ide> // <ide> // Set the working directory for future RUN/CMD/etc statements. <ide> // <del>func workdir(b *builder, args []string, attributes map[string]bool, original string) error { <add>func workdir(ctx context.Context, b *builder, args []string, attributes map[string]bool, original string) error { <ide> if len(args) != 1 { <ide> return derr.ErrorCodeExactlyOneArg.WithArgs("WORKDIR") <ide> } <ide> func workdir(b *builder, args []string, attributes map[string]bool, original str <ide> <ide> b.Config.WorkingDir = workdir <ide> <del> return b.commit("", b.Config.Cmd, fmt.Sprintf("WORKDIR %v", workdir)) <add> return b.commit(ctx, "", b.Config.Cmd, fmt.Sprintf("WORKDIR %v", workdir)) <ide> } <ide> <ide> // RUN some command yo <ide> func workdir(b *builder, args []string, attributes map[string]bool, original str <ide> // RUN echo hi # cmd /S /C echo hi (Windows) <ide> // RUN [ "echo", "hi" ] # echo hi <ide> // <del>func run(b *builder, args []string, attributes map[string]bool, original string) error { <add>func run(ctx context.Context, b *builder, args []string, attributes map[string]bool, original string) error { <ide> if b.image == "" && !b.noBaseImage { <ide> return derr.ErrorCodeMissingFrom <ide> } <ide> func run(b *builder, args []string, attributes map[string]bool, original string) <ide> } <ide> <ide> b.Config.Cmd = saveCmd <del> hit, err := b.probeCache() <add> hit, err := b.probeCache(ctx) <ide> if err != nil { <ide> return err <ide> } <ide> func run(b *builder, args []string, attributes map[string]bool, original string) <ide> <ide> logrus.Debugf("[BUILDER] Command to be executed: %v", b.Config.Cmd) <ide> <del> c, err := b.create() <add> c, err := b.create(ctx) <ide> if err != nil { <ide> return err <ide> } <ide> <ide> // Ensure that we keep the container mounted until the commit <ide> // to avoid unmounting and then mounting directly again <del> c.Mount() <del> defer c.Unmount() <add> c.Mount(ctx) <add> defer c.Unmount(ctx) <ide> <del> err = b.run(c) <add> err = b.run(ctx, c) <ide> if err != nil { <ide> return err <ide> } <ide> func run(b *builder, args []string, attributes map[string]bool, original string) <ide> // properly match it. <ide> b.Config.Env = env <ide> b.Config.Cmd = saveCmd <del> if err := b.commit(c.ID, cmd, "run"); err != nil { <add> if err := b.commit(ctx, c.ID, cmd, "run"); err != nil { <ide> return err <ide> } <ide> <ide> func run(b *builder, args []string, attributes map[string]bool, original string) <ide> // Set the default command to run in the container (which may be empty). <ide> // Argument handling is the same as RUN. <ide> // <del>func cmd(b *builder, args []string, attributes map[string]bool, original string) error { <add>func cmd(ctx context.Context, b *builder, args []string, attributes map[string]bool, original string) error { <ide> if err := b.BuilderFlags.Parse(); err != nil { <ide> return err <ide> } <ide> func cmd(b *builder, args []string, attributes map[string]bool, original string) <ide> <ide> b.Config.Cmd = stringutils.NewStrSlice(cmdSlice...) <ide> <del> if err := b.commit("", b.Config.Cmd, fmt.Sprintf("CMD %q", cmdSlice)); err != nil { <add> if err := b.commit(ctx, "", b.Config.Cmd, fmt.Sprintf("CMD %q", cmdSlice)); err != nil { <ide> return err <ide> } <ide> <ide> func cmd(b *builder, args []string, attributes map[string]bool, original string) <ide> // Handles command processing similar to CMD and RUN, only b.Config.Entrypoint <ide> // is initialized at NewBuilder time instead of through argument parsing. <ide> // <del>func entrypoint(b *builder, args []string, attributes map[string]bool, original string) error { <add>func entrypoint(ctx context.Context, b *builder, args []string, attributes map[string]bool, original string) error { <ide> if err := b.BuilderFlags.Parse(); err != nil { <ide> return err <ide> } <ide> func entrypoint(b *builder, args []string, attributes map[string]bool, original <ide> b.Config.Cmd = nil <ide> } <ide> <del> if err := b.commit("", b.Config.Cmd, fmt.Sprintf("ENTRYPOINT %q", b.Config.Entrypoint)); err != nil { <add> if err := b.commit(ctx, "", b.Config.Cmd, fmt.Sprintf("ENTRYPOINT %q", b.Config.Entrypoint)); err != nil { <ide> return err <ide> } <ide> <ide> func entrypoint(b *builder, args []string, attributes map[string]bool, original <ide> // Expose ports for links and port mappings. This all ends up in <ide> // b.Config.ExposedPorts for runconfig. <ide> // <del>func expose(b *builder, args []string, attributes map[string]bool, original string) error { <add>func expose(ctx context.Context, b *builder, args []string, attributes map[string]bool, original string) error { <ide> portsTab := args <ide> <ide> if len(args) == 0 { <ide> func expose(b *builder, args []string, attributes map[string]bool, original stri <ide> i++ <ide> } <ide> sort.Strings(portList) <del> return b.commit("", b.Config.Cmd, fmt.Sprintf("EXPOSE %s", strings.Join(portList, " "))) <add> return b.commit(ctx, "", b.Config.Cmd, fmt.Sprintf("EXPOSE %s", strings.Join(portList, " "))) <ide> } <ide> <ide> // USER foo <ide> // <ide> // Set the user to 'foo' for future commands and when running the <ide> // ENTRYPOINT/CMD at container run time. <ide> // <del>func user(b *builder, args []string, attributes map[string]bool, original string) error { <add>func user(ctx context.Context, b *builder, args []string, attributes map[string]bool, original string) error { <ide> if len(args) != 1 { <ide> return derr.ErrorCodeExactlyOneArg.WithArgs("USER") <ide> } <ide> func user(b *builder, args []string, attributes map[string]bool, original string <ide> } <ide> <ide> b.Config.User = args[0] <del> return b.commit("", b.Config.Cmd, fmt.Sprintf("USER %v", args)) <add> return b.commit(ctx, "", b.Config.Cmd, fmt.Sprintf("USER %v", args)) <ide> } <ide> <ide> // VOLUME /foo <ide> // <ide> // Expose the volume /foo for use. Will also accept the JSON array form. <ide> // <del>func volume(b *builder, args []string, attributes map[string]bool, original string) error { <add>func volume(ctx context.Context, b *builder, args []string, attributes map[string]bool, original string) error { <ide> if len(args) == 0 { <ide> return derr.ErrorCodeAtLeastOneArg.WithArgs("VOLUME") <ide> } <ide> func volume(b *builder, args []string, attributes map[string]bool, original stri <ide> } <ide> b.Config.Volumes[v] = struct{}{} <ide> } <del> if err := b.commit("", b.Config.Cmd, fmt.Sprintf("VOLUME %v", args)); err != nil { <add> if err := b.commit(ctx, "", b.Config.Cmd, fmt.Sprintf("VOLUME %v", args)); err != nil { <ide> return err <ide> } <ide> return nil <ide> func volume(b *builder, args []string, attributes map[string]bool, original stri <ide> // STOPSIGNAL signal <ide> // <ide> // Set the signal that will be used to kill the container. <del>func stopSignal(b *builder, args []string, attributes map[string]bool, original string) error { <add>func stopSignal(ctx context.Context, b *builder, args []string, attributes map[string]bool, original string) error { <ide> if len(args) != 1 { <ide> return fmt.Errorf("STOPSIGNAL requires exactly one argument") <ide> } <ide> func stopSignal(b *builder, args []string, attributes map[string]bool, original <ide> } <ide> <ide> b.Config.StopSignal = sig <del> return b.commit("", b.Config.Cmd, fmt.Sprintf("STOPSIGNAL %v", args)) <add> return b.commit(ctx, "", b.Config.Cmd, fmt.Sprintf("STOPSIGNAL %v", args)) <ide> } <ide> <ide> // ARG name[=value] <ide> // <ide> // Adds the variable foo to the trusted list of variables that can be passed <ide> // to builder using the --build-arg flag for expansion/subsitution or passing to 'run'. <ide> // Dockerfile author may optionally set a default value of this variable. <del>func arg(b *builder, args []string, attributes map[string]bool, original string) error { <add>func arg(ctx context.Context, b *builder, args []string, attributes map[string]bool, original string) error { <ide> if len(args) != 1 { <ide> return fmt.Errorf("ARG requires exactly one argument definition") <ide> } <ide> func arg(b *builder, args []string, attributes map[string]bool, original string) <ide> b.buildArgs[name] = value <ide> } <ide> <del> return b.commit("", b.Config.Cmd, fmt.Sprintf("ARG %s", arg)) <add> return b.commit(ctx, "", b.Config.Cmd, fmt.Sprintf("ARG %s", arg)) <ide> } <ide><path>builder/evaluator.go <ide> import ( <ide> "github.com/docker/docker/builder/command" <ide> "github.com/docker/docker/builder/parser" <ide> "github.com/docker/docker/cliconfig" <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/daemon" <ide> "github.com/docker/docker/pkg/fileutils" <ide> "github.com/docker/docker/pkg/streamformatter" <ide> var replaceEnvAllowed = map[string]struct{}{ <ide> command.Arg: {}, <ide> } <ide> <del>var evaluateTable map[string]func(*builder, []string, map[string]bool, string) error <add>var evaluateTable map[string]func(context.Context, *builder, []string, map[string]bool, string) error <ide> <ide> func init() { <del> evaluateTable = map[string]func(*builder, []string, map[string]bool, string) error{ <add> evaluateTable = map[string]func(context.Context, *builder, []string, map[string]bool, string) error{ <ide> command.Env: env, <ide> command.Label: label, <ide> command.Maintainer: maintainer, <ide> type builder struct { <ide> // processing. <ide> // * Print a happy message and return the image ID. <ide> // <del>func (b *builder) Run(context io.Reader) (string, error) { <add>func (b *builder) Run(ctx context.Context, context io.Reader) (string, error) { <ide> if err := b.readContext(context); err != nil { <ide> return "", err <ide> } <ide> func (b *builder) Run(context io.Reader) (string, error) { <ide> default: <ide> // Not cancelled yet, keep going... <ide> } <del> if err := b.dispatch(i, n); err != nil { <add> if err := b.dispatch(ctx, i, n); err != nil { <ide> if b.ForceRemove { <del> b.clearTmp() <add> b.clearTmp(ctx) <ide> } <ide> return "", err <ide> } <ide> fmt.Fprintf(b.OutStream, " ---> %s\n", stringid.TruncateID(b.image)) <ide> if b.Remove { <del> b.clearTmp() <add> b.clearTmp(ctx) <ide> } <ide> } <ide> <ide> func (b *builder) isBuildArgAllowed(arg string) bool { <ide> // such as `RUN` in ONBUILD RUN foo. There is special case logic in here to <ide> // deal with that, at least until it becomes more of a general concern with new <ide> // features. <del>func (b *builder) dispatch(stepN int, ast *parser.Node) error { <add>func (b *builder) dispatch(ctx context.Context, stepN int, ast *parser.Node) error { <ide> cmd := ast.Value <ide> <ide> // To ensure the user is give a decent error message if the platform <ide> func (b *builder) dispatch(stepN int, ast *parser.Node) error { <ide> if f, ok := evaluateTable[cmd]; ok { <ide> b.BuilderFlags = NewBFlags() <ide> b.BuilderFlags.Args = flags <del> return f(b, strList, attrs, original) <add> return f(ctx, b, strList, attrs, original) <ide> } <ide> <ide> return fmt.Errorf("Unknown instruction: %s", strings.ToUpper(cmd)) <ide><path>builder/internals.go <ide> import ( <ide> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/builder/parser" <ide> "github.com/docker/docker/cliconfig" <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/daemon" <ide> "github.com/docker/docker/graph" <ide> "github.com/docker/docker/image" <ide> func (b *builder) readContext(context io.Reader) (err error) { <ide> return <ide> } <ide> <del>func (b *builder) commit(id string, autoCmd *stringutils.StrSlice, comment string) error { <add>func (b *builder) commit(ctx context.Context, id string, autoCmd *stringutils.StrSlice, comment string) error { <ide> if b.disableCommit { <ide> return nil <ide> } <ide> func (b *builder) commit(id string, autoCmd *stringutils.StrSlice, comment strin <ide> } <ide> defer func(cmd *stringutils.StrSlice) { b.Config.Cmd = cmd }(cmd) <ide> <del> hit, err := b.probeCache() <add> hit, err := b.probeCache(ctx) <ide> if err != nil { <ide> return err <ide> } <ide> if hit { <ide> return nil <ide> } <ide> <del> container, err := b.create() <add> container, err := b.create(ctx) <ide> if err != nil { <ide> return err <ide> } <ide> id = container.ID <ide> <del> if err := container.Mount(); err != nil { <add> if err := container.Mount(ctx); err != nil { <ide> return err <ide> } <del> defer container.Unmount() <add> defer container.Unmount(ctx) <ide> } <del> container, err := b.Daemon.Get(id) <add> container, err := b.Daemon.Get(ctx, id) <ide> if err != nil { <ide> return err <ide> } <ide> func (b *builder) commit(id string, autoCmd *stringutils.StrSlice, comment strin <ide> } <ide> <ide> // Commit the container <del> image, err := b.Daemon.Commit(container, commitCfg) <add> image, err := b.Daemon.Commit(ctx, container, commitCfg) <ide> if err != nil { <ide> return err <ide> } <del> b.Daemon.Graph().Retain(b.id, image.ID) <add> b.Daemon.Graph(ctx).Retain(b.id, image.ID) <ide> b.activeImages = append(b.activeImages, image.ID) <ide> b.image = image.ID <ide> return nil <ide> type copyInfo struct { <ide> tmpDir string <ide> } <ide> <del>func (b *builder) runContextCommand(args []string, allowRemote bool, allowDecompression bool, cmdName string) error { <add>func (b *builder) runContextCommand(ctx context.Context, args []string, allowRemote bool, allowDecompression bool, cmdName string) error { <ide> if b.context == nil { <ide> return fmt.Errorf("No context given. Impossible to use %s", cmdName) <ide> } <ide> func (b *builder) runContextCommand(args []string, allowRemote bool, allowDecomp <ide> } <ide> defer func(cmd *stringutils.StrSlice) { b.Config.Cmd = cmd }(cmd) <ide> <del> hit, err := b.probeCache() <add> hit, err := b.probeCache(ctx) <ide> if err != nil { <ide> return err <ide> } <ide> func (b *builder) runContextCommand(args []string, allowRemote bool, allowDecomp <ide> return nil <ide> } <ide> <del> container, _, err := b.Daemon.ContainerCreate("", b.Config, nil, true) <add> container, _, err := b.Daemon.ContainerCreate(ctx, "", b.Config, nil, true) <ide> if err != nil { <ide> return err <ide> } <ide> b.TmpContainers[container.ID] = struct{}{} <ide> <del> if err := container.Mount(); err != nil { <add> if err := container.Mount(ctx); err != nil { <ide> return err <ide> } <del> defer container.Unmount() <add> defer container.Unmount(ctx) <ide> <ide> for _, ci := range copyInfos { <ide> if err := b.addContext(container, ci.origPath, ci.destPath, ci.decompress); err != nil { <ide> return err <ide> } <ide> } <ide> <del> if err := b.commit(container.ID, cmd, fmt.Sprintf("%s %s in %s", cmdName, origPaths, dest)); err != nil { <add> if err := b.commit(ctx, container.ID, cmd, fmt.Sprintf("%s %s in %s", cmdName, origPaths, dest)); err != nil { <ide> return err <ide> } <ide> return nil <ide> func containsWildcards(name string) bool { <ide> return false <ide> } <ide> <del>func (b *builder) pullImage(name string) (*image.Image, error) { <add>func (b *builder) pullImage(ctx context.Context, name string) (*image.Image, error) { <ide> remote, tag := parsers.ParseRepositoryTag(name) <ide> if tag == "" { <ide> tag = "latest" <ide> func (b *builder) pullImage(name string) (*image.Image, error) { <ide> OutStream: ioutils.NopWriteCloser(b.OutOld), <ide> } <ide> <del> if err := b.Daemon.Repositories().Pull(remote, tag, imagePullConfig); err != nil { <add> if err := b.Daemon.Repositories(ctx).Pull(ctx, remote, tag, imagePullConfig); err != nil { <ide> return nil, err <ide> } <ide> <del> image, err := b.Daemon.Repositories().LookupImage(name) <add> image, err := b.Daemon.Repositories(ctx).LookupImage(name) <ide> if err != nil { <ide> return nil, err <ide> } <ide> <ide> return image, nil <ide> } <ide> <del>func (b *builder) processImageFrom(img *image.Image) error { <add>func (b *builder) processImageFrom(ctx context.Context, img *image.Image) error { <ide> b.image = img.ID <ide> <ide> if img.Config != nil { <ide> func (b *builder) processImageFrom(img *image.Image) error { <ide> return fmt.Errorf("%s isn't allowed as an ONBUILD trigger", n.Value) <ide> } <ide> <del> if err := b.dispatch(i, n); err != nil { <add> if err := b.dispatch(ctx, i, n); err != nil { <ide> return err <ide> } <ide> } <ide> func (b *builder) processImageFrom(img *image.Image) error { <ide> // in the current server `b.Daemon`. If an image is found, probeCache returns <ide> // `(true, nil)`. If no image is found, it returns `(false, nil)`. If there <ide> // is any error, it returns `(false, err)`. <del>func (b *builder) probeCache() (bool, error) { <add>func (b *builder) probeCache(ctx context.Context) (bool, error) { <ide> if !b.UtilizeCache || b.cacheBusted { <ide> return false, nil <ide> } <ide> <del> cache, err := b.Daemon.ImageGetCached(b.image, b.Config) <add> cache, err := b.Daemon.ImageGetCached(ctx, b.image, b.Config) <ide> if err != nil { <ide> return false, err <ide> } <ide> func (b *builder) probeCache() (bool, error) { <ide> fmt.Fprintf(b.OutStream, " ---> Using cache\n") <ide> logrus.Debugf("[BUILDER] Use cached version") <ide> b.image = cache.ID <del> b.Daemon.Graph().Retain(b.id, cache.ID) <add> b.Daemon.Graph(ctx).Retain(b.id, cache.ID) <ide> b.activeImages = append(b.activeImages, cache.ID) <ide> return true, nil <ide> } <ide> <del>func (b *builder) create() (*daemon.Container, error) { <add>func (b *builder) create(ctx context.Context) (*daemon.Container, error) { <ide> if b.image == "" && !b.noBaseImage { <ide> return nil, fmt.Errorf("Please provide a source image with `from` prior to run") <ide> } <ide> func (b *builder) create() (*daemon.Container, error) { <ide> config := *b.Config <ide> <ide> // Create the container <del> c, warnings, err := b.Daemon.ContainerCreate("", b.Config, hostConfig, true) <add> c, warnings, err := b.Daemon.ContainerCreate(ctx, "", b.Config, hostConfig, true) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func (b *builder) create() (*daemon.Container, error) { <ide> return c, nil <ide> } <ide> <del>func (b *builder) run(c *daemon.Container) error { <add>func (b *builder) run(ctx context.Context, c *daemon.Container) error { <ide> var errCh chan error <ide> if b.Verbose { <ide> errCh = c.Attach(nil, b.OutStream, b.ErrStream) <ide> } <ide> <ide> //start the container <del> if err := c.Start(); err != nil { <add> if err := c.Start(ctx); err != nil { <ide> return err <ide> } <ide> <ide> func (b *builder) run(c *daemon.Container) error { <ide> select { <ide> case <-b.cancelled: <ide> logrus.Debugln("Build cancelled, killing container:", c.ID) <del> c.Kill() <add> c.Kill(ctx) <ide> case <-finished: <ide> } <ide> }() <ide> func copyAsDirectory(source, destination string, destExisted bool) error { <ide> return fixPermissions(source, destination, 0, 0, destExisted) <ide> } <ide> <del>func (b *builder) clearTmp() { <add>func (b *builder) clearTmp(ctx context.Context) { <ide> for c := range b.TmpContainers { <ide> rmConfig := &daemon.ContainerRmConfig{ <ide> ForceRemove: true, <ide> RemoveVolume: true, <ide> } <del> if err := b.Daemon.ContainerRm(c, rmConfig); err != nil { <add> if err := b.Daemon.ContainerRm(ctx, c, rmConfig); err != nil { <ide> fmt.Fprintf(b.OutStream, "Error removing intermediate container %s: %v\n", stringid.TruncateID(c), err) <ide> return <ide> } <ide><path>builder/job.go <ide> import ( <ide> "github.com/docker/docker/api" <ide> "github.com/docker/docker/builder/parser" <ide> "github.com/docker/docker/cliconfig" <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/daemon" <ide> "github.com/docker/docker/graph/tags" <ide> "github.com/docker/docker/pkg/archive" <ide> func NewBuildConfig() *Config { <ide> <ide> // Build is the main interface of the package, it gathers the Builder <ide> // struct and calls builder.Run() to do all the real build job. <del>func Build(d *daemon.Daemon, buildConfig *Config) error { <add>func Build(ctx context.Context, d *daemon.Daemon, buildConfig *Config) error { <ide> var ( <ide> repoName string <ide> tag string <ide> func Build(d *daemon.Daemon, buildConfig *Config) error { <ide> } <ide> <ide> defer func() { <del> builder.Daemon.Graph().Release(builder.id, builder.activeImages...) <add> builder.Daemon.Graph(ctx).Release(builder.id, builder.activeImages...) <ide> }() <ide> <del> id, err := builder.Run(context) <add> id, err := builder.Run(ctx, context) <ide> if err != nil { <ide> return err <ide> } <ide> if repoName != "" { <del> return d.Repositories().Tag(repoName, tag, id, true) <add> return d.Repositories(ctx).Tag(repoName, tag, id, true) <ide> } <ide> return nil <ide> } <ide> func Build(d *daemon.Daemon, buildConfig *Config) error { <ide> // <ide> // - call parse.Parse() to get AST root from Dockerfile entries <ide> // - do build by calling builder.dispatch() to call all entries' handling routines <del>func BuildFromConfig(d *daemon.Daemon, c *runconfig.Config, changes []string) (*runconfig.Config, error) { <add>func BuildFromConfig(ctx context.Context, d *daemon.Daemon, c *runconfig.Config, changes []string) (*runconfig.Config, error) { <ide> ast, err := parser.Parse(bytes.NewBufferString(strings.Join(changes, "\n"))) <ide> if err != nil { <ide> return nil, err <ide> func BuildFromConfig(d *daemon.Daemon, c *runconfig.Config, changes []string) (* <ide> } <ide> <ide> for i, n := range ast.Children { <del> if err := builder.dispatch(i, n); err != nil { <add> if err := builder.dispatch(ctx, i, n); err != nil { <ide> return nil, err <ide> } <ide> } <ide> type CommitConfig struct { <ide> } <ide> <ide> // Commit will create a new image from a container's changes <del>func Commit(name string, d *daemon.Daemon, c *CommitConfig) (string, error) { <del> container, err := d.Get(name) <add>func Commit(ctx context.Context, name string, d *daemon.Daemon, c *CommitConfig) (string, error) { <add> container, err := d.Get(ctx, name) <ide> if err != nil { <ide> return "", err <ide> } <ide> func Commit(name string, d *daemon.Daemon, c *CommitConfig) (string, error) { <ide> c.Config = &runconfig.Config{} <ide> } <ide> <del> newConfig, err := BuildFromConfig(d, c.Config, c.Changes) <add> newConfig, err := BuildFromConfig(ctx, d, c.Config, c.Changes) <ide> if err != nil { <ide> return "", err <ide> } <ide> func Commit(name string, d *daemon.Daemon, c *CommitConfig) (string, error) { <ide> Config: newConfig, <ide> } <ide> <del> img, err := d.Commit(container, commitCfg) <add> img, err := d.Commit(ctx, container, commitCfg) <ide> if err != nil { <ide> return "", err <ide> } <ide><path>daemon/archive.go <ide> import ( <ide> "strings" <ide> <ide> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/pkg/archive" <ide> "github.com/docker/docker/pkg/chrootarchive" <ide> "github.com/docker/docker/pkg/ioutils" <ide> var ErrExtractPointNotDirectory = errors.New("extraction point is not a director <ide> <ide> // ContainerCopy performs a deprecated operation of archiving the resource at <ide> // the specified path in the conatiner identified by the given name. <del>func (daemon *Daemon) ContainerCopy(name string, res string) (io.ReadCloser, error) { <del> container, err := daemon.Get(name) <add>func (daemon *Daemon) ContainerCopy(ctx context.Context, name string, res string) (io.ReadCloser, error) { <add> container, err := daemon.Get(ctx, name) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func (daemon *Daemon) ContainerCopy(name string, res string) (io.ReadCloser, err <ide> res = res[1:] <ide> } <ide> <del> return container.copy(res) <add> return container.copy(ctx, res) <ide> } <ide> <ide> // ContainerStatPath stats the filesystem resource at the specified path in the <ide> // container identified by the given name. <del>func (daemon *Daemon) ContainerStatPath(name string, path string) (stat *types.ContainerPathStat, err error) { <del> container, err := daemon.Get(name) <add>func (daemon *Daemon) ContainerStatPath(ctx context.Context, name string, path string) (stat *types.ContainerPathStat, err error) { <add> container, err := daemon.Get(ctx, name) <ide> if err != nil { <ide> return nil, err <ide> } <ide> <del> return container.StatPath(path) <add> return container.StatPath(ctx, path) <ide> } <ide> <ide> // ContainerArchivePath creates an archive of the filesystem resource at the <ide> // specified path in the container identified by the given name. Returns a <ide> // tar archive of the resource and whether it was a directory or a single file. <del>func (daemon *Daemon) ContainerArchivePath(name string, path string) (content io.ReadCloser, stat *types.ContainerPathStat, err error) { <del> container, err := daemon.Get(name) <add>func (daemon *Daemon) ContainerArchivePath(ctx context.Context, name string, path string) (content io.ReadCloser, stat *types.ContainerPathStat, err error) { <add> container, err := daemon.Get(ctx, name) <ide> if err != nil { <ide> return nil, nil, err <ide> } <ide> <del> return container.ArchivePath(path) <add> return container.ArchivePath(ctx, path) <ide> } <ide> <ide> // ContainerExtractToDir extracts the given archive to the specified location <ide> func (daemon *Daemon) ContainerArchivePath(name string, path string) (content io <ide> // be ErrExtractPointNotDirectory. If noOverwriteDirNonDir is true then it will <ide> // be an error if unpacking the given content would cause an existing directory <ide> // to be replaced with a non-directory and vice versa. <del>func (daemon *Daemon) ContainerExtractToDir(name, path string, noOverwriteDirNonDir bool, content io.Reader) error { <del> container, err := daemon.Get(name) <add>func (daemon *Daemon) ContainerExtractToDir(ctx context.Context, name, path string, noOverwriteDirNonDir bool, content io.Reader) error { <add> container, err := daemon.Get(ctx, name) <ide> if err != nil { <ide> return err <ide> } <ide> <del> return container.ExtractToDir(path, noOverwriteDirNonDir, content) <add> return container.ExtractToDir(ctx, path, noOverwriteDirNonDir, content) <ide> } <ide> <ide> // resolvePath resolves the given path in the container to a resource on the <ide> func (container *Container) statPath(resolvedPath, absPath string) (stat *types. <ide> <ide> // StatPath stats the filesystem resource at the specified path in this <ide> // container. Returns stat info about the resource. <del>func (container *Container) StatPath(path string) (stat *types.ContainerPathStat, err error) { <add>func (container *Container) StatPath(ctx context.Context, path string) (stat *types.ContainerPathStat, err error) { <ide> container.Lock() <ide> defer container.Unlock() <ide> <del> if err = container.Mount(); err != nil { <add> if err = container.Mount(ctx); err != nil { <ide> return nil, err <ide> } <del> defer container.Unmount() <add> defer container.Unmount(ctx) <ide> <ide> err = container.mountVolumes() <ide> defer container.unmountVolumes(true) <ide> func (container *Container) StatPath(path string) (stat *types.ContainerPathStat <ide> // ArchivePath creates an archive of the filesystem resource at the specified <ide> // path in this container. Returns a tar archive of the resource and stat info <ide> // about the resource. <del>func (container *Container) ArchivePath(path string) (content io.ReadCloser, stat *types.ContainerPathStat, err error) { <add>func (container *Container) ArchivePath(ctx context.Context, path string) (content io.ReadCloser, stat *types.ContainerPathStat, err error) { <ide> container.Lock() <ide> <ide> defer func() { <ide> func (container *Container) ArchivePath(path string) (content io.ReadCloser, sta <ide> } <ide> }() <ide> <del> if err = container.Mount(); err != nil { <add> if err = container.Mount(ctx); err != nil { <ide> return nil, nil, err <ide> } <ide> <ide> func (container *Container) ArchivePath(path string) (content io.ReadCloser, sta <ide> // unmount any volumes <ide> container.unmountVolumes(true) <ide> // unmount the container's rootfs <del> container.Unmount() <add> container.Unmount(ctx) <ide> } <ide> }() <ide> <ide> func (container *Container) ArchivePath(path string) (content io.ReadCloser, sta <ide> content = ioutils.NewReadCloserWrapper(data, func() error { <ide> err := data.Close() <ide> container.unmountVolumes(true) <del> container.Unmount() <add> container.Unmount(ctx) <ide> container.Unlock() <ide> return err <ide> }) <ide> <del> container.logEvent("archive-path") <add> container.logEvent(ctx, "archive-path") <ide> <ide> return content, stat, nil <ide> } <ide> func (container *Container) ArchivePath(path string) (content io.ReadCloser, sta <ide> // noOverwriteDirNonDir is true then it will be an error if unpacking the <ide> // given content would cause an existing directory to be replaced with a non- <ide> // directory and vice versa. <del>func (container *Container) ExtractToDir(path string, noOverwriteDirNonDir bool, content io.Reader) (err error) { <add>func (container *Container) ExtractToDir(ctx context.Context, path string, noOverwriteDirNonDir bool, content io.Reader) (err error) { <ide> container.Lock() <ide> defer container.Unlock() <ide> <del> if err = container.Mount(); err != nil { <add> if err = container.Mount(ctx); err != nil { <ide> return err <ide> } <del> defer container.Unmount() <add> defer container.Unmount(ctx) <ide> <ide> err = container.mountVolumes() <ide> defer container.unmountVolumes(true) <ide> func (container *Container) ExtractToDir(path string, noOverwriteDirNonDir bool, <ide> return err <ide> } <ide> <del> container.logEvent("extract-to-dir") <add> container.logEvent(ctx, "extract-to-dir") <ide> <ide> return nil <ide> } <ide><path>daemon/attach.go <ide> package daemon <ide> import ( <ide> "io" <ide> <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/pkg/stdcopy" <ide> ) <ide> <ide> type ContainerAttachWithLogsConfig struct { <ide> } <ide> <ide> // ContainerAttachWithLogs attaches to logs according to the config passed in. See ContainerAttachWithLogsConfig. <del>func (daemon *Daemon) ContainerAttachWithLogs(prefixOrName string, c *ContainerAttachWithLogsConfig) error { <del> container, err := daemon.Get(prefixOrName) <add>func (daemon *Daemon) ContainerAttachWithLogs(ctx context.Context, prefixOrName string, c *ContainerAttachWithLogsConfig) error { <add> container, err := daemon.Get(ctx, prefixOrName) <ide> if err != nil { <ide> return err <ide> } <ide> func (daemon *Daemon) ContainerAttachWithLogs(prefixOrName string, c *ContainerA <ide> stderr = errStream <ide> } <ide> <del> return container.attachWithLogs(stdin, stdout, stderr, c.Logs, c.Stream) <add> return container.attachWithLogs(ctx, stdin, stdout, stderr, c.Logs, c.Stream) <ide> } <ide> <ide> // ContainerWsAttachWithLogsConfig attach with websockets, since all <ide> type ContainerWsAttachWithLogsConfig struct { <ide> } <ide> <ide> // ContainerWsAttachWithLogs websocket connection <del>func (daemon *Daemon) ContainerWsAttachWithLogs(prefixOrName string, c *ContainerWsAttachWithLogsConfig) error { <del> container, err := daemon.Get(prefixOrName) <add>func (daemon *Daemon) ContainerWsAttachWithLogs(ctx context.Context, prefixOrName string, c *ContainerWsAttachWithLogsConfig) error { <add> container, err := daemon.Get(ctx, prefixOrName) <ide> if err != nil { <ide> return err <ide> } <del> return container.attachWithLogs(c.InStream, c.OutStream, c.ErrStream, c.Logs, c.Stream) <add> return container.attachWithLogs(ctx, c.InStream, c.OutStream, c.ErrStream, c.Logs, c.Stream) <ide> } <ide><path>daemon/changes.go <ide> package daemon <ide> <del>import "github.com/docker/docker/pkg/archive" <add>import ( <add> "github.com/docker/docker/context" <add> "github.com/docker/docker/pkg/archive" <add>) <ide> <ide> // ContainerChanges returns a list of container fs changes <del>func (daemon *Daemon) ContainerChanges(name string) ([]archive.Change, error) { <del> container, err := daemon.Get(name) <add>func (daemon *Daemon) ContainerChanges(ctx context.Context, name string) ([]archive.Change, error) { <add> container, err := daemon.Get(ctx, name) <ide> if err != nil { <ide> return nil, err <ide> } <ide><path>daemon/commit.go <ide> package daemon <ide> <ide> import ( <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/image" <ide> "github.com/docker/docker/runconfig" <ide> ) <ide> type ContainerCommitConfig struct { <ide> <ide> // Commit creates a new filesystem image from the current state of a container. <ide> // The image can optionally be tagged into a repository. <del>func (daemon *Daemon) Commit(container *Container, c *ContainerCommitConfig) (*image.Image, error) { <add>func (daemon *Daemon) Commit(ctx context.Context, container *Container, c *ContainerCommitConfig) (*image.Image, error) { <ide> if c.Pause && !container.isPaused() { <del> container.pause() <del> defer container.unpause() <add> container.pause(ctx) <add> defer container.unpause(ctx) <ide> } <ide> <ide> rwTar, err := container.exportContainerRw() <ide> func (daemon *Daemon) Commit(container *Container, c *ContainerCommitConfig) (*i <ide> return img, err <ide> } <ide> } <del> container.logEvent("commit") <add> container.logEvent(ctx, "commit") <ide> return img, nil <ide> } <ide><path>daemon/container.go <ide> import ( <ide> "github.com/opencontainers/runc/libcontainer/label" <ide> <ide> "github.com/Sirupsen/logrus" <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/daemon/execdriver" <ide> "github.com/docker/docker/daemon/logger" <ide> "github.com/docker/docker/daemon/logger/jsonfilelog" <ide> func (container *Container) writeHostConfig() error { <ide> return ioutil.WriteFile(pth, data, 0666) <ide> } <ide> <del>func (container *Container) logEvent(action string) { <add>func (container *Container) logEvent(ctx context.Context, action string) { <ide> d := container.daemon <ide> d.EventsService.Log( <add> ctx, <ide> action, <ide> container.ID, <ide> container.Config.Image, <ide> func (container *Container) exportContainerRw() (archive.Archive, error) { <ide> // container needs, such as storage and networking, as well as links <ide> // between containers. The container is left waiting for a signal to <ide> // begin running. <del>func (container *Container) Start() (err error) { <add>func (container *Container) Start(ctx context.Context) (err error) { <ide> container.Lock() <ide> defer container.Unlock() <ide> <ide> func (container *Container) Start() (err error) { <ide> container.ExitCode = 128 <ide> } <ide> container.toDisk() <del> container.cleanup() <del> container.logEvent("die") <add> container.cleanup(ctx) <add> container.logEvent(ctx, "die") <ide> } <ide> }() <ide> <del> if err := container.Mount(); err != nil { <add> if err := container.Mount(ctx); err != nil { <ide> return err <ide> } <ide> <ide> // Make sure NetworkMode has an acceptable value. We do this to ensure <ide> // backwards API compatibility. <ide> container.hostConfig = runconfig.SetDefaultNetModeIfBlank(container.hostConfig) <ide> <del> if err := container.initializeNetworking(); err != nil { <add> if err := container.initializeNetworking(ctx); err != nil { <ide> return err <ide> } <del> linkedEnv, err := container.setupLinkedContainers() <add> linkedEnv, err := container.setupLinkedContainers(ctx) <ide> if err != nil { <ide> return err <ide> } <ide> if err := container.setupWorkingDirectory(); err != nil { <ide> return err <ide> } <ide> env := container.createDaemonEnvironment(linkedEnv) <del> if err := populateCommand(container, env); err != nil { <add> if err := populateCommand(ctx, container, env); err != nil { <ide> return err <ide> } <ide> <ide> func (container *Container) Start() (err error) { <ide> mounts = append(mounts, container.ipcMounts()...) <ide> <ide> container.command.Mounts = mounts <del> return container.waitForStart() <add> return container.waitForStart(ctx) <ide> } <ide> <ide> // streamConfig.StdinPipe returns a WriteCloser which can be used to feed data <ide> func (container *Container) isNetworkAllocated() bool { <ide> <ide> // cleanup releases any network resources allocated to the container along with any rules <ide> // around how containers are linked together. It also unmounts the container's root filesystem. <del>func (container *Container) cleanup() { <add>func (container *Container) cleanup(ctx context.Context) { <ide> container.releaseNetwork() <ide> <ide> if err := container.unmountIpcMounts(); err != nil { <ide> logrus.Errorf("%s: Failed to umount ipc filesystems: %v", container.ID, err) <ide> } <ide> <del> if err := container.Unmount(); err != nil { <add> if err := container.Unmount(ctx); err != nil { <ide> logrus.Errorf("%s: Failed to umount filesystem: %v", container.ID, err) <ide> } <ide> <ide> func (container *Container) cleanup() { <ide> // to send the signal. An error is returned if the container is paused <ide> // or not running, or if there is a problem returned from the <ide> // underlying kill command. <del>func (container *Container) killSig(sig int) error { <add>func (container *Container) killSig(ctx context.Context, sig int) error { <ide> logrus.Debugf("Sending %d to %s", sig, container.ID) <ide> container.Lock() <ide> defer container.Unlock() <ide> func (container *Container) killSig(sig int) error { <ide> if err := container.daemon.kill(container, sig); err != nil { <ide> return err <ide> } <del> container.logEvent("kill") <add> container.logEvent(ctx, "kill") <ide> return nil <ide> } <ide> <ide> // Wrapper aroung killSig() suppressing "no such process" error. <del>func (container *Container) killPossiblyDeadProcess(sig int) error { <del> err := container.killSig(sig) <add>func (container *Container) killPossiblyDeadProcess(ctx context.Context, sig int) error { <add> err := container.killSig(ctx, sig) <ide> if err == syscall.ESRCH { <ide> logrus.Debugf("Cannot kill process (pid=%d) with signal %d: no such process.", container.getPID(), sig) <ide> return nil <ide> } <ide> return err <ide> } <ide> <del>func (container *Container) pause() error { <add>func (container *Container) pause(ctx context.Context) error { <ide> container.Lock() <ide> defer container.Unlock() <ide> <ide> func (container *Container) pause() error { <ide> return err <ide> } <ide> container.Paused = true <del> container.logEvent("pause") <add> container.logEvent(ctx, "pause") <ide> return nil <ide> } <ide> <del>func (container *Container) unpause() error { <add>func (container *Container) unpause(ctx context.Context) error { <ide> container.Lock() <ide> defer container.Unlock() <ide> <ide> func (container *Container) unpause() error { <ide> return err <ide> } <ide> container.Paused = false <del> container.logEvent("unpause") <add> container.logEvent(ctx, "unpause") <ide> return nil <ide> } <ide> <ide> // Kill forcefully terminates a container. <del>func (container *Container) Kill() error { <add>func (container *Container) Kill(ctx context.Context) error { <ide> if !container.IsRunning() { <ide> return derr.ErrorCodeNotRunning.WithArgs(container.ID) <ide> } <ide> <ide> // 1. Send SIGKILL <del> if err := container.killPossiblyDeadProcess(int(syscall.SIGKILL)); err != nil { <add> if err := container.killPossiblyDeadProcess(ctx, int(syscall.SIGKILL)); err != nil { <ide> // While normally we might "return err" here we're not going to <ide> // because if we can't stop the container by this point then <ide> // its probably because its already stopped. Meaning, between <ide> func (container *Container) Kill() error { <ide> // process to exit. If a negative duration is given, Stop will wait <ide> // for the initial signal forever. If the container is not running Stop returns <ide> // immediately. <del>func (container *Container) Stop(seconds int) error { <add>func (container *Container) Stop(ctx context.Context, seconds int) error { <ide> if !container.IsRunning() { <ide> return nil <ide> } <ide> <ide> // 1. Send a SIGTERM <del> if err := container.killPossiblyDeadProcess(container.stopSignal()); err != nil { <add> if err := container.killPossiblyDeadProcess(ctx, container.stopSignal()); err != nil { <ide> logrus.Infof("Failed to send SIGTERM to the process, force killing") <del> if err := container.killPossiblyDeadProcess(9); err != nil { <add> if err := container.killPossiblyDeadProcess(ctx, 9); err != nil { <ide> return err <ide> } <ide> } <ide> func (container *Container) Stop(seconds int) error { <ide> if _, err := container.WaitStop(time.Duration(seconds) * time.Second); err != nil { <ide> logrus.Infof("Container %v failed to exit within %d seconds of SIGTERM - using the force", container.ID, seconds) <ide> // 3. If it doesn't, then send SIGKILL <del> if err := container.Kill(); err != nil { <add> if err := container.Kill(ctx); err != nil { <ide> container.WaitStop(-1 * time.Second) <ide> return err <ide> } <ide> } <ide> <del> container.logEvent("stop") <add> container.logEvent(ctx, "stop") <ide> return nil <ide> } <ide> <ide> // Restart attempts to gracefully stop and then start the <ide> // container. When stopping, wait for the given duration in seconds to <ide> // gracefully stop, before forcefully terminating the container. If <ide> // given a negative duration, wait forever for a graceful stop. <del>func (container *Container) Restart(seconds int) error { <add>func (container *Container) Restart(ctx context.Context, seconds int) error { <ide> // Avoid unnecessarily unmounting and then directly mounting <ide> // the container when the container stops and then starts <ide> // again <del> if err := container.Mount(); err == nil { <del> defer container.Unmount() <add> if err := container.Mount(ctx); err == nil { <add> defer container.Unmount(ctx) <ide> } <ide> <del> if err := container.Stop(seconds); err != nil { <add> if err := container.Stop(ctx, seconds); err != nil { <ide> return err <ide> } <ide> <del> if err := container.Start(); err != nil { <add> if err := container.Start(ctx); err != nil { <ide> return err <ide> } <ide> <del> container.logEvent("restart") <add> container.logEvent(ctx, "restart") <ide> return nil <ide> } <ide> <ide> // Resize changes the TTY of the process running inside the container <ide> // to the given height and width. The container must be running. <del>func (container *Container) Resize(h, w int) error { <add>func (container *Container) Resize(ctx context.Context, h, w int) error { <ide> if !container.IsRunning() { <ide> return derr.ErrorCodeNotRunning.WithArgs(container.ID) <ide> } <ide> if err := container.command.ProcessConfig.Terminal.Resize(h, w); err != nil { <ide> return err <ide> } <del> container.logEvent("resize") <add> container.logEvent(ctx, "resize") <ide> return nil <ide> } <ide> <del>func (container *Container) export() (archive.Archive, error) { <del> if err := container.Mount(); err != nil { <add>func (container *Container) export(ctx context.Context) (archive.Archive, error) { <add> if err := container.Mount(ctx); err != nil { <ide> return nil, err <ide> } <ide> <ide> archive, err := archive.Tar(container.basefs, archive.Uncompressed) <ide> if err != nil { <del> container.Unmount() <add> container.Unmount(ctx) <ide> return nil, err <ide> } <ide> arch := ioutils.NewReadCloserWrapper(archive, func() error { <ide> err := archive.Close() <del> container.Unmount() <add> container.Unmount(ctx) <ide> return err <ide> }) <del> container.logEvent("export") <add> container.logEvent(ctx, "export") <ide> return arch, err <ide> } <ide> <ide> // Mount sets container.basefs <del>func (container *Container) Mount() error { <del> return container.daemon.Mount(container) <add>func (container *Container) Mount(ctx context.Context) error { <add> return container.daemon.Mount(ctx, container) <ide> } <ide> <ide> func (container *Container) changes() ([]archive.Change, error) { <ide> func (container *Container) changes() ([]archive.Change, error) { <ide> return container.daemon.changes(container) <ide> } <ide> <del>func (container *Container) getImage() (*image.Image, error) { <add>func (container *Container) getImage(ctx context.Context) (*image.Image, error) { <ide> if container.daemon == nil { <ide> return nil, derr.ErrorCodeImageUnregContainer <ide> } <ide> func (container *Container) getImage() (*image.Image, error) { <ide> <ide> // Unmount asks the daemon to release the layered filesystems that are <ide> // mounted by the container. <del>func (container *Container) Unmount() error { <add>func (container *Container) Unmount(ctx context.Context) error { <ide> return container.daemon.unmount(container) <ide> } <ide> <ide> func validateID(id string) error { <ide> return nil <ide> } <ide> <del>func (container *Container) copy(resource string) (rc io.ReadCloser, err error) { <add>func (container *Container) copy(ctx context.Context, resource string) (rc io.ReadCloser, err error) { <ide> container.Lock() <ide> <ide> defer func() { <ide> func (container *Container) copy(resource string) (rc io.ReadCloser, err error) <ide> } <ide> }() <ide> <del> if err := container.Mount(); err != nil { <add> if err := container.Mount(ctx); err != nil { <ide> return nil, err <ide> } <ide> <ide> func (container *Container) copy(resource string) (rc io.ReadCloser, err error) <ide> // unmount any volumes <ide> container.unmountVolumes(true) <ide> // unmount the container's rootfs <del> container.Unmount() <add> container.Unmount(ctx) <ide> } <ide> }() <ide> <ide> func (container *Container) copy(resource string) (rc io.ReadCloser, err error) <ide> reader := ioutils.NewReadCloserWrapper(archive, func() error { <ide> err := archive.Close() <ide> container.unmountVolumes(true) <del> container.Unmount() <add> container.Unmount(ctx) <ide> container.Unlock() <ide> return err <ide> }) <del> container.logEvent("copy") <add> container.logEvent(ctx, "copy") <ide> return reader, nil <ide> } <ide> <ide> func (container *Container) startLogging() error { <ide> return nil <ide> } <ide> <del>func (container *Container) waitForStart() error { <add>func (container *Container) waitForStart(ctx context.Context) error { <ide> container.monitor = newContainerMonitor(container, container.hostConfig.RestartPolicy) <ide> <ide> // block until we either receive an error from the initial start of the container's <ide> // process or until the process is running in the container <ide> select { <ide> case <-container.monitor.startSignal: <del> case err := <-promise.Go(container.monitor.Start): <add> case err := <-promise.Go(func() error { return container.monitor.Start(ctx) }): <ide> return err <ide> } <ide> <ide> func (container *Container) getExecIDs() []string { <ide> return container.execCommands.List() <ide> } <ide> <del>func (container *Container) exec(ExecConfig *ExecConfig) error { <add>func (container *Container) exec(ctx context.Context, ExecConfig *ExecConfig) error { <ide> container.Lock() <ide> defer container.Unlock() <ide> <del> callback := func(processConfig *execdriver.ProcessConfig, pid int, chOOM <-chan struct{}) error { <add> callback := func(ctx context.Context, processConfig *execdriver.ProcessConfig, pid int, chOOM <-chan struct{}) error { <ide> if processConfig.Tty { <ide> // The callback is called after the process Start() <ide> // so we are in the parent process. In TTY mode, stdin/out/err is the PtySlave <ide> func (container *Container) exec(ExecConfig *ExecConfig) error { <ide> <ide> // We use a callback here instead of a goroutine and an chan for <ide> // synchronization purposes <del> cErr := promise.Go(func() error { return container.monitorExec(ExecConfig, callback) }) <add> cErr := promise.Go(func() error { return container.monitorExec(ctx, ExecConfig, callback) }) <ide> <ide> // Exec should not return until the process is actually running <ide> select { <ide> func (container *Container) exec(ExecConfig *ExecConfig) error { <ide> return nil <ide> } <ide> <del>func (container *Container) monitorExec(ExecConfig *ExecConfig, callback execdriver.DriverCallback) error { <add>func (container *Container) monitorExec(ctx context.Context, ExecConfig *ExecConfig, callback execdriver.DriverCallback) error { <ide> var ( <ide> err error <ide> exitCode int <ide> ) <ide> pipes := execdriver.NewPipes(ExecConfig.streamConfig.stdin, ExecConfig.streamConfig.stdout, ExecConfig.streamConfig.stderr, ExecConfig.OpenStdin) <del> exitCode, err = container.daemon.Exec(container, ExecConfig, pipes, callback) <add> exitCode, err = container.daemon.Exec(ctx, container, ExecConfig, pipes, callback) <ide> if err != nil { <ide> logrus.Errorf("Error running command in existing container %s: %s", container.ID, err) <ide> } <ide> func (container *Container) Attach(stdin io.ReadCloser, stdout io.Writer, stderr <ide> return attach(&container.streamConfig, container.Config.OpenStdin, container.Config.StdinOnce, container.Config.Tty, stdin, stdout, stderr) <ide> } <ide> <del>func (container *Container) attachWithLogs(stdin io.ReadCloser, stdout, stderr io.Writer, logs, stream bool) error { <add>func (container *Container) attachWithLogs(ctx context.Context, stdin io.ReadCloser, stdout, stderr io.Writer, logs, stream bool) error { <ide> if logs { <ide> logDriver, err := container.getLogger() <ide> if err != nil { <ide> func (container *Container) attachWithLogs(stdin io.ReadCloser, stdout, stderr i <ide> } <ide> } <ide> <del> container.logEvent("attach") <add> container.logEvent(ctx, "attach") <ide> <ide> //stream <ide> if stream { <ide><path>daemon/container_unix.go <ide> import ( <ide> "time" <ide> <ide> "github.com/Sirupsen/logrus" <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/daemon/execdriver" <ide> "github.com/docker/docker/daemon/links" <ide> "github.com/docker/docker/daemon/network" <ide> func killProcessDirectly(container *Container) error { <ide> return nil <ide> } <ide> <del>func (container *Container) setupLinkedContainers() ([]string, error) { <add>func (container *Container) setupLinkedContainers(ctx context.Context) ([]string, error) { <ide> var ( <ide> env []string <ide> daemon = container.daemon <ide> ) <del> children, err := daemon.children(container.Name) <add> children, err := daemon.children(ctx, container.Name) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func getDevicesFromPath(deviceMapping runconfig.DeviceMapping) (devs []*configs. <ide> return devs, derr.ErrorCodeDeviceInfo.WithArgs(deviceMapping.PathOnHost, err) <ide> } <ide> <del>func populateCommand(c *Container, env []string) error { <add>func populateCommand(ctx context.Context, c *Container, env []string) error { <ide> var en *execdriver.Network <ide> if !c.Config.NetworkDisabled { <ide> en = &execdriver.Network{} <ide> func populateCommand(c *Container, env []string) error { <ide> <ide> parts := strings.SplitN(string(c.hostConfig.NetworkMode), ":", 2) <ide> if parts[0] == "container" { <del> nc, err := c.getNetworkedContainer() <add> nc, err := c.getNetworkedContainer(ctx) <ide> if err != nil { <ide> return err <ide> } <ide> func populateCommand(c *Container, env []string) error { <ide> } <ide> <ide> if c.hostConfig.IpcMode.IsContainer() { <del> ic, err := c.getIpcContainer() <add> ic, err := c.getIpcContainer(ctx) <ide> if err != nil { <ide> return err <ide> } <ide> func mergeDevices(defaultDevices, userDevices []*configs.Device) []*configs.Devi <ide> } <ide> <ide> // GetSize returns the real size & virtual size of the container. <del>func (container *Container) getSize() (int64, int64) { <add>func (container *Container) getSize(ctx context.Context) (int64, int64) { <ide> var ( <ide> sizeRw, sizeRootfs int64 <ide> err error <ide> driver = container.daemon.driver <ide> ) <ide> <del> if err := container.Mount(); err != nil { <add> if err := container.Mount(ctx); err != nil { <ide> logrus.Errorf("Failed to compute size of container rootfs %s: %s", container.ID, err) <ide> return sizeRw, sizeRootfs <ide> } <del> defer container.Unmount() <add> defer container.Unmount(ctx) <ide> <ide> initID := fmt.Sprintf("%s-init", container.ID) <ide> sizeRw, err = driver.DiffSize(container.ID, initID) <ide> func (container *Container) buildHostnameFile() error { <ide> return ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644) <ide> } <ide> <del>func (container *Container) buildSandboxOptions() ([]libnetwork.SandboxOption, error) { <add>func (container *Container) buildSandboxOptions(ctx context.Context) ([]libnetwork.SandboxOption, error) { <ide> var ( <ide> sboxOptions []libnetwork.SandboxOption <ide> err error <ide> func (container *Container) buildSandboxOptions() ([]libnetwork.SandboxOption, e <ide> <ide> var childEndpoints, parentEndpoints []string <ide> <del> children, err := container.daemon.children(container.Name) <add> children, err := container.daemon.children(ctx, container.Name) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func (container *Container) buildSandboxOptions() ([]libnetwork.SandboxOption, e <ide> continue <ide> } <ide> <del> c, err := container.daemon.Get(ref.ParentID) <add> c, err := container.daemon.Get(ctx, ref.ParentID) <ide> if err != nil { <ide> logrus.Error(err) <ide> } <ide> func (container *Container) updateSandboxNetworkSettings(sb libnetwork.Sandbox) <ide> <ide> // UpdateNetwork is used to update the container's network (e.g. when linked containers <ide> // get removed/unlinked). <del>func (container *Container) updateNetwork() error { <add>func (container *Container) updateNetwork(ctx context.Context) error { <ide> ctrl := container.daemon.netController <ide> sid := container.NetworkSettings.SandboxID <ide> <ide> func (container *Container) updateNetwork() error { <ide> return derr.ErrorCodeNoSandbox.WithArgs(sid, err) <ide> } <ide> <del> options, err := container.buildSandboxOptions() <add> options, err := container.buildSandboxOptions(ctx) <ide> if err != nil { <ide> return derr.ErrorCodeNetworkUpdate.WithArgs(err) <ide> } <ide> func createNetwork(controller libnetwork.NetworkController, dnet string, driver <ide> return controller.NewNetwork(driver, dnet, createOptions...) <ide> } <ide> <del>func (container *Container) secondaryNetworkRequired(primaryNetworkType string) bool { <add>func (container *Container) secondaryNetworkRequired(ctx context.Context, primaryNetworkType string) bool { <ide> switch primaryNetworkType { <ide> case "bridge", "none", "host", "container": <ide> return false <ide> func (container *Container) secondaryNetworkRequired(primaryNetworkType string) <ide> return false <ide> } <ide> <del>func (container *Container) allocateNetwork() error { <add>func (container *Container) allocateNetwork(ctx context.Context) error { <ide> mode := container.hostConfig.NetworkMode <ide> controller := container.daemon.netController <ide> if container.Config.NetworkDisabled || mode.IsContainer() { <ide> func (container *Container) allocateNetwork() error { <ide> service = strings.Replace(service, "/", "", -1) <ide> } <ide> <del> if container.secondaryNetworkRequired(networkDriver) { <add> if container.secondaryNetworkRequired(ctx, networkDriver) { <ide> // Configure Bridge as secondary network for port binding purposes <del> if err := container.configureNetwork("bridge", service, "bridge", false); err != nil { <add> if err := container.configureNetwork(ctx, "bridge", service, "bridge", false); err != nil { <ide> return err <ide> } <ide> } <ide> <del> if err := container.configureNetwork(networkName, service, networkDriver, mode.IsDefault()); err != nil { <add> if err := container.configureNetwork(ctx, networkName, service, networkDriver, mode.IsDefault()); err != nil { <ide> return err <ide> } <ide> <ide> return container.writeHostConfig() <ide> } <ide> <del>func (container *Container) configureNetwork(networkName, service, networkDriver string, canCreateNetwork bool) error { <add>func (container *Container) configureNetwork(ctx context.Context, networkName, service, networkDriver string, canCreateNetwork bool) error { <ide> controller := container.daemon.netController <ide> <ide> n, err := controller.NetworkByName(networkName) <ide> func (container *Container) configureNetwork(networkName, service, networkDriver <ide> return false <ide> }) <ide> if sb == nil { <del> options, err := container.buildSandboxOptions() <add> options, err := container.buildSandboxOptions(ctx) <ide> if err != nil { <ide> return err <ide> } <ide> func (container *Container) configureNetwork(networkName, service, networkDriver <ide> return nil <ide> } <ide> <del>func (container *Container) initializeNetworking() error { <add>func (container *Container) initializeNetworking(ctx context.Context) error { <ide> var err error <ide> <ide> if container.hostConfig.NetworkMode.IsContainer() { <ide> // we need to get the hosts files from the container to join <del> nc, err := container.getNetworkedContainer() <add> nc, err := container.getNetworkedContainer(ctx) <ide> if err != nil { <ide> return err <ide> } <ide> func (container *Container) initializeNetworking() error { <ide> <ide> } <ide> <del> if err := container.allocateNetwork(); err != nil { <add> if err := container.allocateNetwork(ctx); err != nil { <ide> return err <ide> } <ide> <ide> func (container *Container) setNetworkNamespaceKey(pid int) error { <ide> return sandbox.SetKey(path) <ide> } <ide> <del>func (container *Container) getIpcContainer() (*Container, error) { <add>func (container *Container) getIpcContainer(ctx context.Context) (*Container, error) { <ide> containerID := container.hostConfig.IpcMode.Container() <del> c, err := container.daemon.Get(containerID) <add> c, err := container.daemon.Get(ctx, containerID) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func (container *Container) setupWorkingDirectory() error { <ide> return nil <ide> } <ide> <del>func (container *Container) getNetworkedContainer() (*Container, error) { <add>func (container *Container) getNetworkedContainer(ctx context.Context) (*Container, error) { <ide> parts := strings.SplitN(string(container.hostConfig.NetworkMode), ":", 2) <ide> switch parts[0] { <ide> case "container": <ide> if len(parts) != 2 { <ide> return nil, derr.ErrorCodeParseContainer <ide> } <del> nc, err := container.daemon.Get(parts[1]) <add> nc, err := container.daemon.Get(ctx, parts[1]) <ide> if err != nil { <ide> return nil, err <ide> } <ide><path>daemon/container_windows.go <ide> package daemon <ide> import ( <ide> "strings" <ide> <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/daemon/execdriver" <ide> derr "github.com/docker/docker/errors" <ide> ) <ide> func killProcessDirectly(container *Container) error { <ide> return nil <ide> } <ide> <del>func (container *Container) setupLinkedContainers() ([]string, error) { <add>func (container *Container) setupLinkedContainers(ctx context.Context) ([]string, error) { <ide> return nil, nil <ide> } <ide> <ide> func (container *Container) createDaemonEnvironment(linkedEnv []string) []string <ide> return container.Config.Env <ide> } <ide> <del>func (container *Container) initializeNetworking() error { <add>func (container *Container) initializeNetworking(ctx context.Context) error { <ide> return nil <ide> } <ide> <ide> func (container *Container) setupWorkingDirectory() error { <ide> return nil <ide> } <ide> <del>func populateCommand(c *Container, env []string) error { <add>func populateCommand(ctx context.Context, c *Container, env []string) error { <ide> en := &execdriver.Network{ <ide> Interface: nil, <ide> } <ide> func populateCommand(c *Container, env []string) error { <ide> } <ide> <ide> // GetSize returns real size & virtual size <del>func (container *Container) getSize() (int64, int64) { <add>func (container *Container) getSize(ctx context.Context) (int64, int64) { <ide> // TODO Windows <ide> return 0, 0 <ide> } <ide> func (container *Container) allocateNetwork() error { <ide> return nil <ide> } <ide> <del>func (container *Container) updateNetwork() error { <add>func (container *Container) updateNetwork(ctx context.Context) error { <ide> return nil <ide> } <ide> <ide><path>daemon/create.go <ide> import ( <ide> <ide> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/context" <ide> derr "github.com/docker/docker/errors" <ide> "github.com/docker/docker/graph/tags" <ide> "github.com/docker/docker/image" <ide> import ( <ide> ) <ide> <ide> // ContainerCreate takes configs and creates a container. <del>func (daemon *Daemon) ContainerCreate(name string, config *runconfig.Config, hostConfig *runconfig.HostConfig, adjustCPUShares bool) (*Container, []string, error) { <add>func (daemon *Daemon) ContainerCreate(ctx context.Context, name string, config *runconfig.Config, hostConfig *runconfig.HostConfig, adjustCPUShares bool) (*Container, []string, error) { <ide> if config == nil { <ide> return nil, nil, derr.ErrorCodeEmptyConfig <ide> } <ide> <del> warnings, err := daemon.verifyContainerSettings(hostConfig, config) <add> warnings, err := daemon.verifyContainerSettings(ctx, hostConfig, config) <ide> if err != nil { <ide> return nil, warnings, err <ide> } <ide> <ide> daemon.adaptContainerSettings(hostConfig, adjustCPUShares) <ide> <del> container, buildWarnings, err := daemon.Create(config, hostConfig, name) <add> container, buildWarnings, err := daemon.Create(ctx, config, hostConfig, name) <ide> if err != nil { <del> if daemon.Graph().IsNotExist(err, config.Image) { <add> if daemon.Graph(ctx).IsNotExist(err, config.Image) { <ide> if strings.Contains(config.Image, "@") { <ide> return nil, warnings, derr.ErrorCodeNoSuchImageHash.WithArgs(config.Image) <ide> } <ide> func (daemon *Daemon) ContainerCreate(name string, config *runconfig.Config, hos <ide> } <ide> <ide> // Create creates a new container from the given configuration with a given name. <del>func (daemon *Daemon) Create(config *runconfig.Config, hostConfig *runconfig.HostConfig, name string) (retC *Container, retS []string, retErr error) { <add>func (daemon *Daemon) Create(ctx context.Context, config *runconfig.Config, hostConfig *runconfig.HostConfig, name string) (retC *Container, retS []string, retErr error) { <ide> var ( <ide> container *Container <ide> warnings []string <ide> func (daemon *Daemon) Create(config *runconfig.Config, hostConfig *runconfig.Hos <ide> hostConfig = &runconfig.HostConfig{} <ide> } <ide> if hostConfig.SecurityOpt == nil { <del> hostConfig.SecurityOpt, err = daemon.generateSecurityOpt(hostConfig.IpcMode, hostConfig.PidMode) <add> hostConfig.SecurityOpt, err = daemon.generateSecurityOpt(ctx, hostConfig.IpcMode, hostConfig.PidMode) <ide> if err != nil { <ide> return nil, nil, err <ide> } <ide> } <del> if container, err = daemon.newContainer(name, config, imgID); err != nil { <add> if container, err = daemon.newContainer(ctx, name, config, imgID); err != nil { <ide> return nil, nil, err <ide> } <ide> defer func() { <ide> if retErr != nil { <del> if err := daemon.rm(container, false); err != nil { <add> if err := daemon.rm(ctx, container, false); err != nil { <ide> logrus.Errorf("Clean up Error! Cannot destroy container %s: %v", container.ID, err) <ide> } <ide> } <ide> }() <ide> <del> if err := daemon.Register(container); err != nil { <add> if err := daemon.Register(ctx, container); err != nil { <ide> return nil, nil, err <ide> } <ide> if err := daemon.createRootfs(container); err != nil { <ide> return nil, nil, err <ide> } <del> if err := daemon.setHostConfig(container, hostConfig); err != nil { <add> if err := daemon.setHostConfig(ctx, container, hostConfig); err != nil { <ide> return nil, nil, err <ide> } <ide> defer func() { <ide> func (daemon *Daemon) Create(config *runconfig.Config, hostConfig *runconfig.Hos <ide> } <ide> } <ide> }() <del> if err := container.Mount(); err != nil { <add> if err := container.Mount(ctx); err != nil { <ide> return nil, nil, err <ide> } <del> defer container.Unmount() <add> defer container.Unmount(ctx) <ide> <ide> if err := createContainerPlatformSpecificSettings(container, config, hostConfig, img); err != nil { <ide> return nil, nil, err <ide> func (daemon *Daemon) Create(config *runconfig.Config, hostConfig *runconfig.Hos <ide> logrus.Errorf("Error saving new container to disk: %v", err) <ide> return nil, nil, err <ide> } <del> container.logEvent("create") <add> container.logEvent(ctx, "create") <ide> return container, warnings, nil <ide> } <ide> <del>func (daemon *Daemon) generateSecurityOpt(ipcMode runconfig.IpcMode, pidMode runconfig.PidMode) ([]string, error) { <add>func (daemon *Daemon) generateSecurityOpt(ctx context.Context, ipcMode runconfig.IpcMode, pidMode runconfig.PidMode) ([]string, error) { <ide> if ipcMode.IsHost() || pidMode.IsHost() { <ide> return label.DisableSecOpt(), nil <ide> } <ide> if ipcContainer := ipcMode.Container(); ipcContainer != "" { <del> c, err := daemon.Get(ipcContainer) <add> c, err := daemon.Get(ctx, ipcContainer) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func (daemon *Daemon) generateSecurityOpt(ipcMode runconfig.IpcMode, pidMode run <ide> <ide> // VolumeCreate creates a volume with the specified name, driver, and opts <ide> // This is called directly from the remote API <del>func (daemon *Daemon) VolumeCreate(name, driverName string, opts map[string]string) (*types.Volume, error) { <add>func (daemon *Daemon) VolumeCreate(ctx context.Context, name, driverName string, opts map[string]string) (*types.Volume, error) { <ide> if name == "" { <ide> name = stringid.GenerateNonCryptoID() <ide> } <ide><path>daemon/daemon.go <ide> import ( <ide> <ide> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/api" <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/daemon/events" <ide> "github.com/docker/docker/daemon/execdriver" <ide> "github.com/docker/docker/daemon/execdriver/execdrivers" <ide> type Daemon struct { <ide> // - A partial container ID prefix (e.g. short ID) of any length that is <ide> // unique enough to only return a single container object <ide> // If none of these searches succeed, an error is returned <del>func (daemon *Daemon) Get(prefixOrName string) (*Container, error) { <add>func (daemon *Daemon) Get(ctx context.Context, prefixOrName string) (*Container, error) { <ide> if containerByID := daemon.containers.Get(prefixOrName); containerByID != nil { <ide> // prefix is an exact match to a full container ID <ide> return containerByID, nil <ide> } <ide> <ide> // GetByName will match only an exact name provided; we ignore errors <del> if containerByName, _ := daemon.GetByName(prefixOrName); containerByName != nil { <add> if containerByName, _ := daemon.GetByName(ctx, prefixOrName); containerByName != nil { <ide> // prefix is an exact match to a full container Name <ide> return containerByName, nil <ide> } <ide> func (daemon *Daemon) Get(prefixOrName string) (*Container, error) { <ide> <ide> // Exists returns a true if a container of the specified ID or name exists, <ide> // false otherwise. <del>func (daemon *Daemon) Exists(id string) bool { <del> c, _ := daemon.Get(id) <add>func (daemon *Daemon) Exists(ctx context.Context, id string) bool { <add> c, _ := daemon.Get(ctx, id) <ide> return c != nil <ide> } <ide> <ide> func (daemon *Daemon) load(id string) (*Container, error) { <ide> } <ide> <ide> // Register makes a container object usable by the daemon as <container.ID> <del>func (daemon *Daemon) Register(container *Container) error { <del> if container.daemon != nil || daemon.Exists(container.ID) { <add>func (daemon *Daemon) Register(ctx context.Context, container *Container) error { <add> if container.daemon != nil || daemon.Exists(ctx, container.ID) { <ide> return fmt.Errorf("Container is already loaded") <ide> } <ide> if err := validateID(container.ID); err != nil { <ide> func (daemon *Daemon) Register(container *Container) error { <ide> } <ide> daemon.execDriver.Terminate(cmd) <ide> <del> if err := container.unmountIpcMounts(); err != nil { <del> logrus.Errorf("%s: Failed to umount ipc filesystems: %v", container.ID, err) <del> } <del> if err := container.Unmount(); err != nil { <add> if err := container.Unmount(ctx); err != nil { <ide> logrus.Debugf("unmount error %s", err) <ide> } <ide> if err := container.toDiskLocking(); err != nil { <ide> func (daemon *Daemon) ensureName(container *Container) error { <ide> return nil <ide> } <ide> <del>func (daemon *Daemon) restore() error { <add>func (daemon *Daemon) restore(ctx context.Context) error { <ide> type cr struct { <ide> container *Container <ide> registered bool <ide> func (daemon *Daemon) restore() error { <ide> } <ide> } <ide> <del> if err := daemon.Register(container); err != nil { <add> if err := daemon.Register(ctx, container); err != nil { <ide> logrus.Errorf("Failed to register container %s: %s", container.ID, err) <ide> // The container register failed should not be started. <ide> return <ide> func (daemon *Daemon) restore() error { <ide> if daemon.configStore.AutoRestart && container.shouldRestart() { <ide> logrus.Debugf("Starting container %s", container.ID) <ide> <del> if err := container.Start(); err != nil { <add> if err := container.Start(ctx); err != nil { <ide> logrus.Errorf("Failed to start container %s: %s", container.ID, err) <ide> } <ide> } <ide> func (daemon *Daemon) mergeAndVerifyConfig(config *runconfig.Config, img *image. <ide> return nil <ide> } <ide> <del>func (daemon *Daemon) generateIDAndName(name string) (string, string, error) { <add>func (daemon *Daemon) generateIDAndName(ctx context.Context, name string) (string, string, error) { <ide> var ( <ide> err error <ide> id = stringid.GenerateNonCryptoID() <ide> func (daemon *Daemon) generateIDAndName(name string) (string, string, error) { <ide> return id, name, nil <ide> } <ide> <del> if name, err = daemon.reserveName(id, name); err != nil { <add> if name, err = daemon.reserveName(ctx, id, name); err != nil { <ide> return "", "", err <ide> } <ide> <ide> return id, name, nil <ide> } <ide> <del>func (daemon *Daemon) reserveName(id, name string) (string, error) { <add>func (daemon *Daemon) reserveName(ctx context.Context, id, name string) (string, error) { <ide> if !validContainerNamePattern.MatchString(name) { <ide> return "", fmt.Errorf("Invalid container name (%s), only %s are allowed", name, validContainerNameChars) <ide> } <ide> func (daemon *Daemon) reserveName(id, name string) (string, error) { <ide> return "", err <ide> } <ide> <del> conflictingContainer, err := daemon.GetByName(name) <add> conflictingContainer, err := daemon.GetByName(ctx, name) <ide> if err != nil { <ide> if strings.Contains(err.Error(), "Could not find entity") { <ide> return "", err <ide> func (daemon *Daemon) getEntrypointAndArgs(configEntrypoint *stringutils.StrSlic <ide> return entrypoint, args <ide> } <ide> <del>func (daemon *Daemon) newContainer(name string, config *runconfig.Config, imgID string) (*Container, error) { <add>func (daemon *Daemon) newContainer(ctx context.Context, name string, config *runconfig.Config, imgID string) (*Container, error) { <ide> var ( <ide> id string <ide> err error <ide> ) <del> id, name, err = daemon.generateIDAndName(name) <add> id, name, err = daemon.generateIDAndName(ctx, name) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func GetFullContainerName(name string) (string, error) { <ide> } <ide> <ide> // GetByName returns a container given a name. <del>func (daemon *Daemon) GetByName(name string) (*Container, error) { <add>func (daemon *Daemon) GetByName(ctx context.Context, name string) (*Container, error) { <ide> fullName, err := GetFullContainerName(name) <ide> if err != nil { <ide> return nil, err <ide> func (daemon *Daemon) GetByName(name string) (*Container, error) { <ide> // children returns all child containers of the container with the <ide> // given name. The containers are returned as a map from the container <ide> // name to a pointer to Container. <del>func (daemon *Daemon) children(name string) (map[string]*Container, error) { <add>func (daemon *Daemon) children(ctx context.Context, name string) (map[string]*Container, error) { <ide> name, err := GetFullContainerName(name) <ide> if err != nil { <ide> return nil, err <ide> } <ide> children := make(map[string]*Container) <ide> <ide> err = daemon.containerGraphDB.Walk(name, func(p string, e *graphdb.Entity) error { <del> c, err := daemon.Get(e.ID()) <add> c, err := daemon.Get(ctx, e.ID()) <ide> if err != nil { <ide> return err <ide> } <ide> func (daemon *Daemon) registerLink(parent, child *Container, alias string) error <ide> <ide> // NewDaemon sets up everything for the daemon to be able to service <ide> // requests from the webserver. <del>func NewDaemon(config *Config, registryService *registry.Service) (daemon *Daemon, err error) { <add>func NewDaemon(ctx context.Context, config *Config, registryService *registry.Service) (daemon *Daemon, err error) { <ide> setDefaultMtu(config) <ide> <ide> // Ensure we have compatible configuration options <ide> func NewDaemon(config *Config, registryService *registry.Service) (daemon *Daemo <ide> // Ensure the graph driver is shutdown at a later point <ide> defer func() { <ide> if err != nil { <del> if err := d.Shutdown(); err != nil { <add> if err := d.Shutdown(ctx); err != nil { <ide> logrus.Error(err) <ide> } <ide> } <ide> func NewDaemon(config *Config, registryService *registry.Service) (daemon *Daemo <ide> <ide> go d.execCommandGC() <ide> <del> if err := d.restore(); err != nil { <add> if err := d.restore(ctx); err != nil { <ide> return nil, err <ide> } <ide> <ide> return d, nil <ide> } <ide> <ide> // Shutdown stops the daemon. <del>func (daemon *Daemon) Shutdown() error { <add>func (daemon *Daemon) Shutdown(ctx context.Context) error { <ide> daemon.shutdown = true <ide> if daemon.containers != nil { <ide> group := sync.WaitGroup{} <ide> logrus.Debug("starting clean shutdown of all containers...") <del> for _, container := range daemon.List() { <add> for _, container := range daemon.List(ctx) { <ide> c := container <ide> if c.IsRunning() { <ide> logrus.Debugf("stopping %s", c.ID) <ide> func (daemon *Daemon) Shutdown() error { <ide> logrus.Debugf("sending SIGTERM to container %s with error: %v", c.ID, err) <ide> return <ide> } <del> if err := c.unpause(); err != nil { <add> if err := c.unpause(ctx); err != nil { <ide> logrus.Debugf("Failed to unpause container %s with error: %v", c.ID, err) <ide> return <ide> } <ide> func (daemon *Daemon) Shutdown() error { <ide> } <ide> } else { <ide> // If container failed to exit in 10 seconds of SIGTERM, then using the force <del> if err := c.Stop(10); err != nil { <add> if err := c.Stop(ctx, 10); err != nil { <ide> logrus.Errorf("Stop container %s with error: %v", c.ID, err) <ide> } <ide> } <ide> func (daemon *Daemon) Shutdown() error { <ide> <ide> // Mount sets container.basefs <ide> // (is it not set coming in? why is it unset?) <del>func (daemon *Daemon) Mount(container *Container) error { <add>func (daemon *Daemon) Mount(ctx context.Context, container *Container) error { <ide> dir, err := daemon.driver.Get(container.ID, container.getMountLabel()) <ide> if err != nil { <ide> return fmt.Errorf("Error getting container %s from driver %s: %s", container.ID, daemon.driver, err) <ide> func (daemon *Daemon) unmount(container *Container) error { <ide> return nil <ide> } <ide> <del>func (daemon *Daemon) run(c *Container, pipes *execdriver.Pipes, startCallback execdriver.DriverCallback) (execdriver.ExitStatus, error) { <add>func (daemon *Daemon) run(ctx context.Context, c *Container, pipes *execdriver.Pipes, startCallback execdriver.DriverCallback) (execdriver.ExitStatus, error) { <ide> hooks := execdriver.Hooks{ <ide> Start: startCallback, <ide> } <del> hooks.PreStart = append(hooks.PreStart, func(processConfig *execdriver.ProcessConfig, pid int, chOOM <-chan struct{}) error { <add> hooks.PreStart = append(hooks.PreStart, func(ctx context.Context, processConfig *execdriver.ProcessConfig, pid int, chOOM <-chan struct{}) error { <ide> return c.setNetworkNamespaceKey(pid) <ide> }) <del> return daemon.execDriver.Run(c.command, pipes, hooks) <add> return daemon.execDriver.Run(ctx, c.command, pipes, hooks) <ide> } <ide> <ide> func (daemon *Daemon) kill(c *Container, sig int) error { <ide> func (daemon *Daemon) createRootfs(container *Container) error { <ide> // which need direct access to daemon.graph. <ide> // Once the tests switch to using engine and jobs, this method <ide> // can go away. <del>func (daemon *Daemon) Graph() *graph.Graph { <add>func (daemon *Daemon) Graph(ctx context.Context) *graph.Graph { <ide> return daemon.graph <ide> } <ide> <ide> // Repositories returns all repositories. <del>func (daemon *Daemon) Repositories() *graph.TagStore { <add>func (daemon *Daemon) Repositories(ctx context.Context) *graph.TagStore { <ide> return daemon.repositories <ide> } <ide> <ide> func (daemon *Daemon) systemInitPath() string { <ide> <ide> // GraphDriver returns the currently used driver for processing <ide> // container layers. <del>func (daemon *Daemon) GraphDriver() graphdriver.Driver { <add>func (daemon *Daemon) GraphDriver(ctx context.Context) graphdriver.Driver { <ide> return daemon.driver <ide> } <ide> <ide> // ExecutionDriver returns the currently used driver for creating and <ide> // starting execs in a container. <del>func (daemon *Daemon) ExecutionDriver() execdriver.Driver { <add>func (daemon *Daemon) ExecutionDriver(ctx context.Context) execdriver.Driver { <ide> return daemon.execDriver <ide> } <ide> <ide> func (daemon *Daemon) containerGraph() *graphdb.Database { <ide> // of the image with imgID, that had the same config when it was <ide> // created. nil is returned if a child cannot be found. An error is <ide> // returned if the parent image cannot be found. <del>func (daemon *Daemon) ImageGetCached(imgID string, config *runconfig.Config) (*image.Image, error) { <add>func (daemon *Daemon) ImageGetCached(ctx context.Context, imgID string, config *runconfig.Config) (*image.Image, error) { <ide> // Retrieve all images <del> images := daemon.Graph().Map() <add> images := daemon.Graph(ctx).Map() <ide> <ide> // Store the tree in a map of map (map[parentId][childId]) <ide> imageMap := make(map[string]map[string]struct{}) <ide> func tempDir(rootDir string) (string, error) { <ide> return tmpDir, system.MkdirAll(tmpDir, 0700) <ide> } <ide> <del>func (daemon *Daemon) setHostConfig(container *Container, hostConfig *runconfig.HostConfig) error { <add>func (daemon *Daemon) setHostConfig(ctx context.Context, container *Container, hostConfig *runconfig.HostConfig) error { <ide> container.Lock() <ide> if err := parseSecurityOpt(container, hostConfig); err != nil { <ide> container.Unlock() <ide> func (daemon *Daemon) setHostConfig(container *Container, hostConfig *runconfig. <ide> <ide> // Do not lock while creating volumes since this could be calling out to external plugins <ide> // Don't want to block other actions, like `docker ps` because we're waiting on an external plugin <del> if err := daemon.registerMountPoints(container, hostConfig); err != nil { <add> if err := daemon.registerMountPoints(ctx, container, hostConfig); err != nil { <ide> return err <ide> } <ide> <ide> container.Lock() <ide> defer container.Unlock() <ide> // Register any links from the host config before starting the container <del> if err := daemon.registerLinks(container, hostConfig); err != nil { <add> if err := daemon.registerLinks(ctx, container, hostConfig); err != nil { <ide> return err <ide> } <ide> <ide> func getDefaultRouteMtu() (int, error) { <ide> <ide> // verifyContainerSettings performs validation of the hostconfig and config <ide> // structures. <del>func (daemon *Daemon) verifyContainerSettings(hostConfig *runconfig.HostConfig, config *runconfig.Config) ([]string, error) { <add>func (daemon *Daemon) verifyContainerSettings(ctx context.Context, hostConfig *runconfig.HostConfig, config *runconfig.Config) ([]string, error) { <ide> <ide> // First perform verification of settings common across all platforms. <ide> if config != nil { <ide> func (daemon *Daemon) verifyContainerSettings(hostConfig *runconfig.HostConfig, <ide> } <ide> <ide> // Now do platform-specific verification <del> return verifyPlatformContainerSettings(daemon, hostConfig, config) <add> return verifyPlatformContainerSettings(ctx, daemon, hostConfig, config) <ide> } <ide> <ide> func configureVolumes(config *Config) (*store.VolumeStore, error) { <ide><path>daemon/daemon_test.go <ide> import ( <ide> "path/filepath" <ide> "testing" <ide> <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/pkg/graphdb" <ide> "github.com/docker/docker/pkg/stringid" <ide> "github.com/docker/docker/pkg/truncindex" <ide> func TestGet(t *testing.T) { <ide> containerGraphDB: graph, <ide> } <ide> <del> if container, _ := daemon.Get("3cdbd1aa394fd68559fd1441d6eff2ab7c1e6363582c82febfaa8045df3bd8de"); container != c2 { <add> ctx := context.Background() <add> <add> if container, _ := daemon.Get(ctx, "3cdbd1aa394fd68559fd1441d6eff2ab7c1e6363582c82febfaa8045df3bd8de"); container != c2 { <ide> t.Fatal("Should explicitly match full container IDs") <ide> } <ide> <del> if container, _ := daemon.Get("75fb0b8009"); container != c4 { <add> if container, _ := daemon.Get(ctx, "75fb0b8009"); container != c4 { <ide> t.Fatal("Should match a partial ID") <ide> } <ide> <del> if container, _ := daemon.Get("drunk_hawking"); container != c2 { <add> if container, _ := daemon.Get(ctx, "drunk_hawking"); container != c2 { <ide> t.Fatal("Should match a full name") <ide> } <ide> <ide> // c3.Name is a partial match for both c3.ID and c2.ID <del> if c, _ := daemon.Get("3cdbd1aa"); c != c3 { <add> if c, _ := daemon.Get(ctx, "3cdbd1aa"); c != c3 { <ide> t.Fatal("Should match a full name even though it collides with another container's ID") <ide> } <ide> <del> if container, _ := daemon.Get("d22d69a2b896"); container != c5 { <add> if container, _ := daemon.Get(ctx, "d22d69a2b896"); container != c5 { <ide> t.Fatal("Should match a container where the provided prefix is an exact match to the it's name, and is also a prefix for it's ID") <ide> } <ide> <del> if _, err := daemon.Get("3cdbd1"); err == nil { <add> if _, err := daemon.Get(ctx, "3cdbd1"); err == nil { <ide> t.Fatal("Should return an error when provided a prefix that partially matches multiple container ID's") <ide> } <ide> <del> if _, err := daemon.Get("nothing"); err == nil { <add> if _, err := daemon.Get(ctx, "nothing"); err == nil { <ide> t.Fatal("Should return an error when provided a prefix that is neither a name or a partial match to an ID") <ide> } <ide> <ide> func TestRemoveLocalVolumesFollowingSymlinks(t *testing.T) { <ide> t.Fatalf("Expected 1 volume mounted, was 0\n") <ide> } <ide> <add> ctx := context.Background() <add> <ide> m := c.MountPoints["/vol1"] <del> _, err = daemon.VolumeCreate(m.Name, m.Driver, nil) <add> _, err = daemon.VolumeCreate(ctx, m.Name, m.Driver, nil) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> <del> if err := daemon.VolumeRm(m.Name); err != nil { <add> if err := daemon.VolumeRm(ctx, m.Name); err != nil { <ide> t.Fatal(err) <ide> } <ide> <ide><path>daemon/daemon_unix.go <ide> import ( <ide> <ide> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/autogen/dockerversion" <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/daemon/graphdriver" <ide> "github.com/docker/docker/pkg/fileutils" <ide> "github.com/docker/docker/pkg/parsers" <ide> func (daemon *Daemon) adaptContainerSettings(hostConfig *runconfig.HostConfig, a <ide> <ide> // verifyPlatformContainerSettings performs platform-specific validation of the <ide> // hostconfig and config structures. <del>func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *runconfig.HostConfig, config *runconfig.Config) ([]string, error) { <add>func verifyPlatformContainerSettings(ctx context.Context, daemon *Daemon, hostConfig *runconfig.HostConfig, config *runconfig.Config) ([]string, error) { <ide> warnings := []string{} <ide> sysInfo := sysinfo.New(true) <ide> <del> if hostConfig.LxcConf.Len() > 0 && !strings.Contains(daemon.ExecutionDriver().Name(), "lxc") { <del> return warnings, fmt.Errorf("Cannot use --lxc-conf with execdriver: %s", daemon.ExecutionDriver().Name()) <add> if hostConfig.LxcConf.Len() > 0 && !strings.Contains(daemon.ExecutionDriver(ctx).Name(), "lxc") { <add> return warnings, fmt.Errorf("Cannot use --lxc-conf with execdriver: %s", daemon.ExecutionDriver(ctx).Name()) <ide> } <ide> <ide> // memory subsystem checks and adjustments <ide> func setupInitLayer(initLayer string) error { <ide> <ide> // NetworkAPIRouter implements a feature for server-experimental, <ide> // directly calling into libnetwork. <del>func (daemon *Daemon) NetworkAPIRouter() func(w http.ResponseWriter, req *http.Request) { <add>func (daemon *Daemon) NetworkAPIRouter(ctx context.Context) func(w http.ResponseWriter, req *http.Request) { <ide> return nwapi.NewHTTPHandler(daemon.netController) <ide> } <ide> <ide> // registerLinks writes the links to a file. <del>func (daemon *Daemon) registerLinks(container *Container, hostConfig *runconfig.HostConfig) error { <add>func (daemon *Daemon) registerLinks(ctx context.Context, container *Container, hostConfig *runconfig.HostConfig) error { <ide> if hostConfig == nil || hostConfig.Links == nil { <ide> return nil <ide> } <ide> func (daemon *Daemon) registerLinks(container *Container, hostConfig *runconfig. <ide> if err != nil { <ide> return err <ide> } <del> child, err := daemon.Get(name) <add> child, err := daemon.Get(ctx, name) <ide> if err != nil { <ide> //An error from daemon.Get() means this name could not be found <ide> return fmt.Errorf("Could not get container for %s", name) <ide> } <ide> for child.hostConfig.NetworkMode.IsContainer() { <ide> parts := strings.SplitN(string(child.hostConfig.NetworkMode), ":", 2) <del> child, err = daemon.Get(parts[1]) <add> child, err = daemon.Get(ctx, parts[1]) <ide> if err != nil { <ide> return fmt.Errorf("Could not get container for %s", parts[1]) <ide> } <ide><path>daemon/daemon_windows.go <ide> import ( <ide> "syscall" <ide> <ide> "github.com/Sirupsen/logrus" <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/daemon/graphdriver" <ide> // register the windows graph driver <ide> _ "github.com/docker/docker/daemon/graphdriver/windows" <ide> func (daemon *Daemon) adaptContainerSettings(hostConfig *runconfig.HostConfig, a <ide> <ide> // verifyPlatformContainerSettings performs platform-specific validation of the <ide> // hostconfig and config structures. <del>func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *runconfig.HostConfig, config *runconfig.Config) ([]string, error) { <add>func verifyPlatformContainerSettings(ctx context.Context, daemon *Daemon, hostConfig *runconfig.HostConfig, config *runconfig.Config) ([]string, error) { <ide> return nil, nil <ide> } <ide> <ide> func initNetworkController(config *Config) (libnetwork.NetworkController, error) <ide> <ide> // registerLinks sets up links between containers and writes the <ide> // configuration out for persistence. <del>func (daemon *Daemon) registerLinks(container *Container, hostConfig *runconfig.HostConfig) error { <add>func (daemon *Daemon) registerLinks(ctx context.Context, container *Container, hostConfig *runconfig.HostConfig) error { <ide> // TODO Windows. Factored out for network modes. There may be more <ide> // refactoring required here. <ide> <ide> func (daemon *Daemon) registerLinks(container *Container, hostConfig *runconfig. <ide> if err != nil { <ide> return err <ide> } <del> child, err := daemon.Get(name) <add> child, err := daemon.Get(ctx, name) <ide> if err != nil { <ide> //An error from daemon.Get() means this name could not be found <ide> return fmt.Errorf("Could not get container for %s", name) <ide><path>daemon/delete.go <ide> import ( <ide> "os" <ide> "path" <ide> <add> "github.com/docker/docker/context" <add> <ide> "github.com/Sirupsen/logrus" <ide> derr "github.com/docker/docker/errors" <ide> "github.com/docker/docker/volume/store" <ide> type ContainerRmConfig struct { <ide> // is returned if the container is not found, or if the remove <ide> // fails. If the remove succeeds, the container name is released, and <ide> // network links are removed. <del>func (daemon *Daemon) ContainerRm(name string, config *ContainerRmConfig) error { <del> container, err := daemon.Get(name) <add>func (daemon *Daemon) ContainerRm(ctx context.Context, name string, config *ContainerRmConfig) error { <add> container, err := daemon.Get(ctx, name) <ide> if err != nil { <ide> return err <ide> } <ide> func (daemon *Daemon) ContainerRm(name string, config *ContainerRmConfig) error <ide> return err <ide> } <ide> <del> parentContainer, _ := daemon.Get(pe.ID()) <add> parentContainer, _ := daemon.Get(ctx, pe.ID()) <ide> if parentContainer != nil { <del> if err := parentContainer.updateNetwork(); err != nil { <add> if err := parentContainer.updateNetwork(ctx); err != nil { <ide> logrus.Debugf("Could not update network to remove link %s: %v", n, err) <ide> } <ide> } <ide> <ide> return nil <ide> } <ide> <del> if err := daemon.rm(container, config.ForceRemove); err != nil { <add> if err := daemon.rm(ctx, container, config.ForceRemove); err != nil { <ide> // return derr.ErrorCodeCantDestroy.WithArgs(name, utils.GetErrorMessage(err)) <ide> return err <ide> } <ide> func (daemon *Daemon) ContainerRm(name string, config *ContainerRmConfig) error <ide> } <ide> <ide> // Destroy unregisters a container from the daemon and cleanly removes its contents from the filesystem. <del>func (daemon *Daemon) rm(container *Container, forceRemove bool) (err error) { <add>func (daemon *Daemon) rm(ctx context.Context, container *Container, forceRemove bool) (err error) { <ide> if container.IsRunning() { <ide> if !forceRemove { <ide> return derr.ErrorCodeRmRunning <ide> } <del> if err := container.Kill(); err != nil { <add> if err := container.Kill(ctx); err != nil { <ide> return derr.ErrorCodeRmFailed.WithArgs(err) <ide> } <ide> } <ide> func (daemon *Daemon) rm(container *Container, forceRemove bool) (err error) { <ide> <ide> defer container.resetRemovalInProgress() <ide> <del> if err = container.Stop(3); err != nil { <add> if err = container.Stop(ctx, 3); err != nil { <ide> return err <ide> } <ide> <ide> func (daemon *Daemon) rm(container *Container, forceRemove bool) (err error) { <ide> daemon.idIndex.Delete(container.ID) <ide> daemon.containers.Delete(container.ID) <ide> os.RemoveAll(container.root) <del> container.logEvent("destroy") <add> container.logEvent(ctx, "destroy") <ide> } <ide> }() <ide> <ide> func (daemon *Daemon) rm(container *Container, forceRemove bool) (err error) { <ide> daemon.idIndex.Delete(container.ID) <ide> daemon.containers.Delete(container.ID) <ide> <del> container.logEvent("destroy") <add> container.logEvent(ctx, "destroy") <ide> return nil <ide> } <ide> <ide> // VolumeRm removes the volume with the given name. <ide> // If the volume is referenced by a container it is not removed <ide> // This is called directly from the remote API <del>func (daemon *Daemon) VolumeRm(name string) error { <add>func (daemon *Daemon) VolumeRm(ctx context.Context, name string) error { <ide> v, err := daemon.volumes.Get(name) <ide> if err != nil { <ide> return err <ide><path>daemon/events/events.go <ide> import ( <ide> "sync" <ide> "time" <ide> <add> "github.com/docker/docker/context" <add> <ide> "github.com/docker/docker/pkg/jsonmessage" <ide> "github.com/docker/docker/pkg/pubsub" <ide> ) <ide> func (e *Events) Evict(l chan interface{}) { <ide> <ide> // Log broadcasts event to listeners. Each listener has 100 millisecond for <ide> // receiving event or it will be skipped. <del>func (e *Events) Log(action, id, from string) { <add>func (e *Events) Log(ctx context.Context, action, id, from string) { <ide> now := time.Now().UTC() <del> jm := &jsonmessage.JSONMessage{Status: action, ID: id, From: from, Time: now.Unix(), TimeNano: now.UnixNano()} <add> jm := &jsonmessage.JSONMessage{RequestID: ctx.RequestID(), Status: action, ID: id, From: from, Time: now.Unix(), TimeNano: now.UnixNano()} <ide> e.mu.Lock() <ide> if len(e.events) == cap(e.events) { <ide> // discard oldest event <ide><path>daemon/events/events_test.go <ide> import ( <ide> "testing" <ide> "time" <ide> <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/pkg/jsonmessage" <ide> ) <ide> <ide> func TestEventsLog(t *testing.T) { <add> ctx := context.Background() <ide> e := New() <ide> _, l1 := e.Subscribe() <ide> _, l2 := e.Subscribe() <ide> func TestEventsLog(t *testing.T) { <ide> if count != 2 { <ide> t.Fatalf("Must be 2 subscribers, got %d", count) <ide> } <del> e.Log("test", "cont", "image") <add> e.Log(ctx, "test", "cont", "image") <ide> select { <ide> case msg := <-l1: <ide> jmsg, ok := msg.(*jsonmessage.JSONMessage) <ide> func TestEventsLog(t *testing.T) { <ide> } <ide> <ide> func TestEventsLogTimeout(t *testing.T) { <add> ctx := context.Background() <ide> e := New() <ide> _, l := e.Subscribe() <ide> defer e.Evict(l) <ide> <ide> c := make(chan struct{}) <ide> go func() { <del> e.Log("test", "cont", "image") <add> e.Log(ctx, "test", "cont", "image") <ide> close(c) <ide> }() <ide> <ide> func TestEventsLogTimeout(t *testing.T) { <ide> } <ide> <ide> func TestLogEvents(t *testing.T) { <add> ctx := context.Background() <ide> e := New() <ide> <ide> for i := 0; i < eventsLimit+16; i++ { <ide> action := fmt.Sprintf("action_%d", i) <ide> id := fmt.Sprintf("cont_%d", i) <ide> from := fmt.Sprintf("image_%d", i) <del> e.Log(action, id, from) <add> e.Log(ctx, action, id, from) <ide> } <ide> time.Sleep(50 * time.Millisecond) <ide> current, l := e.Subscribe() <ide> func TestLogEvents(t *testing.T) { <ide> action := fmt.Sprintf("action_%d", num) <ide> id := fmt.Sprintf("cont_%d", num) <ide> from := fmt.Sprintf("image_%d", num) <del> e.Log(action, id, from) <add> e.Log(ctx, action, id, from) <ide> } <ide> if len(e.events) != eventsLimit { <ide> t.Fatalf("Must be %d events, got %d", eventsLimit, len(e.events)) <ide><path>daemon/exec.go <ide> import ( <ide> "time" <ide> <ide> "github.com/Sirupsen/logrus" <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/daemon/execdriver" <ide> derr "github.com/docker/docker/errors" <ide> "github.com/docker/docker/pkg/broadcastwriter" <ide> func (d *Daemon) unregisterExecCommand(ExecConfig *ExecConfig) { <ide> d.execCommands.Delete(ExecConfig.ID) <ide> } <ide> <del>func (d *Daemon) getActiveContainer(name string) (*Container, error) { <del> container, err := d.Get(name) <add>func (d *Daemon) getActiveContainer(ctx context.Context, name string) (*Container, error) { <add> container, err := d.Get(ctx, name) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func (d *Daemon) getActiveContainer(name string) (*Container, error) { <ide> } <ide> <ide> // ContainerExecCreate sets up an exec in a running container. <del>func (d *Daemon) ContainerExecCreate(config *runconfig.ExecConfig) (string, error) { <add>func (d *Daemon) ContainerExecCreate(ctx context.Context, config *runconfig.ExecConfig) (string, error) { <ide> // Not all drivers support Exec (LXC for example) <ide> if err := checkExecSupport(d.execDriver.Name()); err != nil { <ide> return "", err <ide> } <ide> <del> container, err := d.getActiveContainer(config.Container) <add> container, err := d.getActiveContainer(ctx, config.Container) <ide> if err != nil { <ide> return "", err <ide> } <ide> func (d *Daemon) ContainerExecCreate(config *runconfig.ExecConfig) (string, erro <ide> <ide> d.registerExecCommand(ExecConfig) <ide> <del> container.logEvent("exec_create: " + ExecConfig.ProcessConfig.Entrypoint + " " + strings.Join(ExecConfig.ProcessConfig.Arguments, " ")) <add> container.logEvent(ctx, "exec_create: "+ExecConfig.ProcessConfig.Entrypoint+" "+strings.Join(ExecConfig.ProcessConfig.Arguments, " ")) <ide> <ide> return ExecConfig.ID, nil <ide> } <ide> <ide> // ContainerExecStart starts a previously set up exec instance. The <ide> // std streams are set up. <del>func (d *Daemon) ContainerExecStart(execName string, stdin io.ReadCloser, stdout io.Writer, stderr io.Writer) error { <add>func (d *Daemon) ContainerExecStart(ctx context.Context, execName string, stdin io.ReadCloser, stdout io.Writer, stderr io.Writer) error { <ide> var ( <ide> cStdin io.ReadCloser <ide> cStdout, cStderr io.Writer <ide> func (d *Daemon) ContainerExecStart(execName string, stdin io.ReadCloser, stdout <ide> logrus.Debugf("starting exec command %s in container %s", ExecConfig.ID, ExecConfig.Container.ID) <ide> container := ExecConfig.Container <ide> <del> container.logEvent("exec_start: " + ExecConfig.ProcessConfig.Entrypoint + " " + strings.Join(ExecConfig.ProcessConfig.Arguments, " ")) <add> container.logEvent(ctx, "exec_start: "+ExecConfig.ProcessConfig.Entrypoint+" "+strings.Join(ExecConfig.ProcessConfig.Arguments, " ")) <ide> <ide> if ExecConfig.OpenStdin { <ide> r, w := io.Pipe() <ide> func (d *Daemon) ContainerExecStart(execName string, stdin io.ReadCloser, stdout <ide> // the exitStatus) even after the cmd is done running. <ide> <ide> go func() { <del> if err := container.exec(ExecConfig); err != nil { <add> if err := container.exec(ctx, ExecConfig); err != nil { <ide> execErr <- derr.ErrorCodeExecCantRun.WithArgs(execName, container.ID, err) <ide> } <ide> }() <ide> func (d *Daemon) ContainerExecStart(execName string, stdin io.ReadCloser, stdout <ide> } <ide> <ide> // Exec calls the underlying exec driver to run <del>func (d *Daemon) Exec(c *Container, ExecConfig *ExecConfig, pipes *execdriver.Pipes, startCallback execdriver.DriverCallback) (int, error) { <add>func (d *Daemon) Exec(ctx context.Context, c *Container, ExecConfig *ExecConfig, pipes *execdriver.Pipes, startCallback execdriver.DriverCallback) (int, error) { <ide> hooks := execdriver.Hooks{ <ide> Start: startCallback, <ide> } <del> exitStatus, err := d.execDriver.Exec(c.command, ExecConfig.ProcessConfig, pipes, hooks) <add> exitStatus, err := d.execDriver.Exec(ctx, c.command, ExecConfig.ProcessConfig, pipes, hooks) <ide> <ide> // On err, make sure we don't leave ExitCode at zero <ide> if err != nil && exitStatus == 0 { <ide><path>daemon/execdriver/driver.go <ide> import ( <ide> "time" <ide> <ide> // TODO Windows: Factor out ulimit <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/pkg/ulimit" <ide> "github.com/opencontainers/runc/libcontainer" <ide> "github.com/opencontainers/runc/libcontainer/configs" <ide> var ( <ide> // through PreStart, Start and PostStop events. <ide> // Callbacks are provided a processConfig pointer and the pid of the child. <ide> // The channel will be used to notify the OOM events. <del>type DriverCallback func(processConfig *ProcessConfig, pid int, chOOM <-chan struct{}) error <add>type DriverCallback func(ctx context.Context, processConfig *ProcessConfig, pid int, chOOM <-chan struct{}) error <ide> <ide> // Hooks is a struct containing function pointers to callbacks <ide> // used by any execdriver implementation exploiting hooks capabilities <ide> type ExitStatus struct { <ide> type Driver interface { <ide> // Run executes the process, blocks until the process exits and returns <ide> // the exit code. It's the last stage on Docker side for running a container. <del> Run(c *Command, pipes *Pipes, hooks Hooks) (ExitStatus, error) <add> Run(ctx context.Context, c *Command, pipes *Pipes, hooks Hooks) (ExitStatus, error) <ide> <ide> // Exec executes the process in an existing container, blocks until the <ide> // process exits and returns the exit code. <del> Exec(c *Command, processConfig *ProcessConfig, pipes *Pipes, hooks Hooks) (int, error) <add> Exec(ctx context.Context, c *Command, processConfig *ProcessConfig, pipes *Pipes, hooks Hooks) (int, error) <ide> <ide> // Kill sends signals to process in container. <ide> Kill(c *Command, sig int) error <ide><path>daemon/execdriver/lxc/driver.go <ide> import ( <ide> "time" <ide> <ide> "github.com/Sirupsen/logrus" <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/daemon/execdriver" <ide> "github.com/docker/docker/pkg/stringutils" <ide> sysinfo "github.com/docker/docker/pkg/system" <ide> func killNetNsProc(proc *os.Process) { <ide> <ide> // Run implements the exec driver Driver interface, <ide> // it calls 'exec.Cmd' to launch lxc commands to run a container. <del>func (d *Driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, hooks execdriver.Hooks) (execdriver.ExitStatus, error) { <add>func (d *Driver) Run(ctx context.Context, c *execdriver.Command, pipes *execdriver.Pipes, hooks execdriver.Hooks) (execdriver.ExitStatus, error) { <ide> var ( <ide> term execdriver.Terminal <ide> err error <ide> func (d *Driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, hooks execd <ide> <ide> if hooks.Start != nil { <ide> logrus.Debugf("Invoking startCallback") <del> hooks.Start(&c.ProcessConfig, pid, oomKillNotification) <add> hooks.Start(ctx, &c.ProcessConfig, pid, oomKillNotification) <ide> <ide> } <ide> <ide> func (t *TtyConsole) Close() error { <ide> <ide> // Exec implements the exec driver Driver interface, <ide> // it is not implemented by lxc. <del>func (d *Driver) Exec(c *execdriver.Command, processConfig *execdriver.ProcessConfig, pipes *execdriver.Pipes, hooks execdriver.Hooks) (int, error) { <add>func (d *Driver) Exec(ctx context.Context, c *execdriver.Command, processConfig *execdriver.ProcessConfig, pipes *execdriver.Pipes, hooks execdriver.Hooks) (int, error) { <ide> return -1, ErrExec <ide> } <ide> <ide><path>daemon/execdriver/native/create.go <ide> import ( <ide> "strings" <ide> "syscall" <ide> <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/daemon/execdriver" <ide> "github.com/opencontainers/runc/libcontainer/apparmor" <ide> "github.com/opencontainers/runc/libcontainer/configs" <ide> import ( <ide> <ide> // createContainer populates and configures the container type with the <ide> // data provided by the execdriver.Command <del>func (d *Driver) createContainer(c *execdriver.Command, hooks execdriver.Hooks) (*configs.Config, error) { <add>func (d *Driver) createContainer(ctx context.Context, c *execdriver.Command, hooks execdriver.Hooks) (*configs.Config, error) { <ide> container := execdriver.InitContainer(c) <ide> <ide> if err := d.createIpc(container, c); err != nil { <ide> func (d *Driver) createContainer(c *execdriver.Command, hooks execdriver.Hooks) <ide> return nil, err <ide> } <ide> <del> if err := d.createNetwork(container, c, hooks); err != nil { <add> if err := d.createNetwork(ctx, container, c, hooks); err != nil { <ide> return nil, err <ide> } <ide> <ide> func generateIfaceName() (string, error) { <ide> return "", errors.New("Failed to find name for new interface") <ide> } <ide> <del>func (d *Driver) createNetwork(container *configs.Config, c *execdriver.Command, hooks execdriver.Hooks) error { <add>func (d *Driver) createNetwork(ctx context.Context, container *configs.Config, c *execdriver.Command, hooks execdriver.Hooks) error { <ide> if c.Network == nil { <ide> return nil <ide> } <ide> func (d *Driver) createNetwork(container *configs.Config, c *execdriver.Command, <ide> // non-blocking and return the correct result when read. <ide> chOOM := make(chan struct{}) <ide> close(chOOM) <del> if err := fnHook(&c.ProcessConfig, s.Pid, chOOM); err != nil { <add> if err := fnHook(ctx, &c.ProcessConfig, s.Pid, chOOM); err != nil { <ide> return err <ide> } <ide> } <ide><path>daemon/execdriver/native/driver.go <ide> import ( <ide> "time" <ide> <ide> "github.com/Sirupsen/logrus" <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/daemon/execdriver" <ide> "github.com/docker/docker/pkg/parsers" <ide> "github.com/docker/docker/pkg/pools" <ide> type execOutput struct { <ide> <ide> // Run implements the exec driver Driver interface, <ide> // it calls libcontainer APIs to run a container. <del>func (d *Driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, hooks execdriver.Hooks) (execdriver.ExitStatus, error) { <add>func (d *Driver) Run(ctx context.Context, c *execdriver.Command, pipes *execdriver.Pipes, hooks execdriver.Hooks) (execdriver.ExitStatus, error) { <ide> // take the Command and populate the libcontainer.Config from it <del> container, err := d.createContainer(c, hooks) <add> container, err := d.createContainer(ctx, c, hooks) <ide> if err != nil { <ide> return execdriver.ExitStatus{ExitCode: -1}, err <ide> } <ide> func (d *Driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, hooks execd <ide> p.Wait() <ide> return execdriver.ExitStatus{ExitCode: -1}, err <ide> } <del> hooks.Start(&c.ProcessConfig, pid, oom) <add> hooks.Start(ctx, &c.ProcessConfig, pid, oom) <ide> } <ide> <ide> waitF := p.Wait <ide><path>daemon/execdriver/native/exec.go <ide> import ( <ide> "os/exec" <ide> "syscall" <ide> <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/daemon/execdriver" <ide> "github.com/opencontainers/runc/libcontainer" <ide> // Blank import 'nsenter' so that init in that package will call c <ide> import ( <ide> <ide> // Exec implements the exec driver Driver interface, <ide> // it calls libcontainer APIs to execute a container. <del>func (d *Driver) Exec(c *execdriver.Command, processConfig *execdriver.ProcessConfig, pipes *execdriver.Pipes, hooks execdriver.Hooks) (int, error) { <add>func (d *Driver) Exec(ctx context.Context, c *execdriver.Command, processConfig *execdriver.ProcessConfig, pipes *execdriver.Pipes, hooks execdriver.Hooks) (int, error) { <ide> active := d.activeContainers[c.ID] <ide> if active == nil { <ide> return -1, fmt.Errorf("No active container exists with ID %s", c.ID) <ide> func (d *Driver) Exec(c *execdriver.Command, processConfig *execdriver.ProcessCo <ide> // non-blocking and return the correct result when read. <ide> chOOM := make(chan struct{}) <ide> close(chOOM) <del> hooks.Start(&c.ProcessConfig, pid, chOOM) <add> hooks.Start(ctx, &c.ProcessConfig, pid, chOOM) <ide> } <ide> <ide> ps, err := p.Wait() <ide><path>daemon/execdriver/windows/exec.go <ide> import ( <ide> "fmt" <ide> <ide> "github.com/Sirupsen/logrus" <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/daemon/execdriver" <ide> "github.com/microsoft/hcsshim" <ide> ) <ide> <ide> // Exec implements the exec driver Driver interface. <del>func (d *Driver) Exec(c *execdriver.Command, processConfig *execdriver.ProcessConfig, pipes *execdriver.Pipes, hooks execdriver.Hooks) (int, error) { <add>func (d *Driver) Exec(ctx context.Context, c *execdriver.Command, processConfig *execdriver.ProcessConfig, pipes *execdriver.Pipes, hooks execdriver.Hooks) (int, error) { <ide> <ide> var ( <ide> term execdriver.Terminal <ide> func (d *Driver) Exec(c *execdriver.Command, processConfig *execdriver.ProcessCo <ide> // non-blocking and return the correct result when read. <ide> chOOM := make(chan struct{}) <ide> close(chOOM) <del> hooks.Start(&c.ProcessConfig, int(pid), chOOM) <add> hooks.Start(ctx, &c.ProcessConfig, int(pid), chOOM) <ide> } <ide> <ide> if exitCode, err = hcsshim.WaitForProcessInComputeSystem(c.ID, pid); err != nil { <ide><path>daemon/execdriver/windows/run.go <ide> import ( <ide> "syscall" <ide> <ide> "github.com/Sirupsen/logrus" <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/daemon/execdriver" <ide> "github.com/microsoft/hcsshim" <ide> ) <ide> type containerInit struct { <ide> const defaultOwner = "docker" <ide> <ide> // Run implements the exec driver Driver interface <del>func (d *Driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, hooks execdriver.Hooks) (execdriver.ExitStatus, error) { <add>func (d *Driver) Run(ctx context.Context, c *execdriver.Command, pipes *execdriver.Pipes, hooks execdriver.Hooks) (execdriver.ExitStatus, error) { <ide> <ide> var ( <ide> term execdriver.Terminal <ide> func (d *Driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, hooks execd <ide> // non-blocking and return the correct result when read. <ide> chOOM := make(chan struct{}) <ide> close(chOOM) <del> hooks.Start(&c.ProcessConfig, int(pid), chOOM) <add> hooks.Start(ctx, &c.ProcessConfig, int(pid), chOOM) <ide> } <ide> <ide> var exitCode int32 <ide><path>daemon/export.go <ide> package daemon <ide> import ( <ide> "io" <ide> <add> "github.com/docker/docker/context" <ide> derr "github.com/docker/docker/errors" <ide> ) <ide> <ide> // ContainerExport writes the contents of the container to the given <ide> // writer. An error is returned if the container cannot be found. <del>func (daemon *Daemon) ContainerExport(name string, out io.Writer) error { <del> container, err := daemon.Get(name) <add>func (daemon *Daemon) ContainerExport(ctx context.Context, name string, out io.Writer) error { <add> container, err := daemon.Get(ctx, name) <ide> if err != nil { <ide> return err <ide> } <ide> <del> data, err := container.export() <add> data, err := container.export(ctx) <ide> if err != nil { <ide> return derr.ErrorCodeExportFailed.WithArgs(name, err) <ide> } <ide><path>daemon/image_delete.go <ide> import ( <ide> "strings" <ide> <ide> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/context" <ide> derr "github.com/docker/docker/errors" <ide> "github.com/docker/docker/graph/tags" <ide> "github.com/docker/docker/image" <ide> import ( <ide> // FIXME: remove ImageDelete's dependency on Daemon, then move to the graph <ide> // package. This would require that we no longer need the daemon to determine <ide> // whether images are being used by a stopped or running container. <del>func (daemon *Daemon) ImageDelete(imageRef string, force, prune bool) ([]types.ImageDelete, error) { <add>func (daemon *Daemon) ImageDelete(ctx context.Context, imageRef string, force, prune bool) ([]types.ImageDelete, error) { <ide> records := []types.ImageDelete{} <ide> <del> img, err := daemon.Repositories().LookupImage(imageRef) <add> img, err := daemon.Repositories(ctx).LookupImage(imageRef) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func (daemon *Daemon) ImageDelete(imageRef string, force, prune bool) ([]types.I <ide> // first. We can only remove this reference if either force is <ide> // true, there are multiple repository references to this <ide> // image, or there are no containers using the given reference. <del> if !(force || daemon.imageHasMultipleRepositoryReferences(img.ID)) { <del> if container := daemon.getContainerUsingImage(img.ID); container != nil { <add> if !(force || daemon.imageHasMultipleRepositoryReferences(ctx, img.ID)) { <add> if container := daemon.getContainerUsingImage(ctx, img.ID); container != nil { <ide> // If we removed the repository reference then <ide> // this image would remain "dangling" and since <ide> // we really want to avoid that the client must <ide> func (daemon *Daemon) ImageDelete(imageRef string, force, prune bool) ([]types.I <ide> } <ide> } <ide> <del> parsedRef, err := daemon.removeImageRef(imageRef) <add> parsedRef, err := daemon.removeImageRef(ctx, imageRef) <ide> if err != nil { <ide> return nil, err <ide> } <ide> <ide> untaggedRecord := types.ImageDelete{Untagged: parsedRef} <ide> <del> daemon.EventsService.Log("untag", img.ID, "") <add> daemon.EventsService.Log(ctx, "untag", img.ID, "") <ide> records = append(records, untaggedRecord) <ide> <ide> removedRepositoryRef = true <ide> func (daemon *Daemon) ImageDelete(imageRef string, force, prune bool) ([]types.I <ide> // repository reference to the image then we will want to <ide> // remove that reference. <ide> // FIXME: Is this the behavior we want? <del> repoRefs := daemon.Repositories().ByID()[img.ID] <add> repoRefs := daemon.Repositories(ctx).ByID()[img.ID] <ide> if len(repoRefs) == 1 { <del> parsedRef, err := daemon.removeImageRef(repoRefs[0]) <add> parsedRef, err := daemon.removeImageRef(ctx, repoRefs[0]) <ide> if err != nil { <ide> return nil, err <ide> } <ide> <ide> untaggedRecord := types.ImageDelete{Untagged: parsedRef} <ide> <del> daemon.EventsService.Log("untag", img.ID, "") <add> daemon.EventsService.Log(ctx, "untag", img.ID, "") <ide> records = append(records, untaggedRecord) <ide> } <ide> } <ide> <del> return records, daemon.imageDeleteHelper(img, &records, force, prune, removedRepositoryRef) <add> return records, daemon.imageDeleteHelper(ctx, img, &records, force, prune, removedRepositoryRef) <ide> } <ide> <ide> // isImageIDPrefix returns whether the given possiblePrefix is a prefix of the <ide> func isImageIDPrefix(imageID, possiblePrefix string) bool { <ide> <ide> // imageHasMultipleRepositoryReferences returns whether there are multiple <ide> // repository references to the given imageID. <del>func (daemon *Daemon) imageHasMultipleRepositoryReferences(imageID string) bool { <del> return len(daemon.Repositories().ByID()[imageID]) > 1 <add>func (daemon *Daemon) imageHasMultipleRepositoryReferences(ctx context.Context, imageID string) bool { <add> return len(daemon.Repositories(ctx).ByID()[imageID]) > 1 <ide> } <ide> <ide> // getContainerUsingImage returns a container that was created using the given <ide> // imageID. Returns nil if there is no such container. <del>func (daemon *Daemon) getContainerUsingImage(imageID string) *Container { <del> for _, container := range daemon.List() { <add>func (daemon *Daemon) getContainerUsingImage(ctx context.Context, imageID string) *Container { <add> for _, container := range daemon.List(ctx) { <ide> if container.ImageID == imageID { <ide> return container <ide> } <ide> func (daemon *Daemon) getContainerUsingImage(imageID string) *Container { <ide> // repositoryRef must not be an image ID but a repository name followed by an <ide> // optional tag or digest reference. If tag or digest is omitted, the default <ide> // tag is used. Returns the resolved image reference and an error. <del>func (daemon *Daemon) removeImageRef(repositoryRef string) (string, error) { <add>func (daemon *Daemon) removeImageRef(ctx context.Context, repositoryRef string) (string, error) { <ide> repository, ref := parsers.ParseRepositoryTag(repositoryRef) <ide> if ref == "" { <ide> ref = tags.DefaultTag <ide> func (daemon *Daemon) removeImageRef(repositoryRef string) (string, error) { <ide> // Ignore the boolean value returned, as far as we're concerned, this <ide> // is an idempotent operation and it's okay if the reference didn't <ide> // exist in the first place. <del> _, err := daemon.Repositories().Delete(repository, ref) <add> _, err := daemon.Repositories(ctx).Delete(repository, ref) <ide> <ide> return utils.ImageReference(repository, ref), err <ide> } <ide> func (daemon *Daemon) removeImageRef(repositoryRef string) (string, error) { <ide> // on the first encountered error. Removed references are logged to this <ide> // daemon's event service. An "Untagged" types.ImageDelete is added to the <ide> // given list of records. <del>func (daemon *Daemon) removeAllReferencesToImageID(imgID string, records *[]types.ImageDelete) error { <del> imageRefs := daemon.Repositories().ByID()[imgID] <add>func (daemon *Daemon) removeAllReferencesToImageID(ctx context.Context, imgID string, records *[]types.ImageDelete) error { <add> imageRefs := daemon.Repositories(ctx).ByID()[imgID] <ide> <ide> for _, imageRef := range imageRefs { <del> parsedRef, err := daemon.removeImageRef(imageRef) <add> parsedRef, err := daemon.removeImageRef(ctx, imageRef) <ide> if err != nil { <ide> return err <ide> } <ide> <ide> untaggedRecord := types.ImageDelete{Untagged: parsedRef} <ide> <del> daemon.EventsService.Log("untag", imgID, "") <add> daemon.EventsService.Log(ctx, "untag", imgID, "") <ide> *records = append(*records, untaggedRecord) <ide> } <ide> <ide> func (idc *imageDeleteConflict) Error() string { <ide> // conflict is encountered, it will be returned immediately without deleting <ide> // the image. If quiet is true, any encountered conflicts will be ignored and <ide> // the function will return nil immediately without deleting the image. <del>func (daemon *Daemon) imageDeleteHelper(img *image.Image, records *[]types.ImageDelete, force, prune, quiet bool) error { <add>func (daemon *Daemon) imageDeleteHelper(ctx context.Context, img *image.Image, records *[]types.ImageDelete, force, prune, quiet bool) error { <ide> // First, determine if this image has any conflicts. Ignore soft conflicts <ide> // if force is true. <del> if conflict := daemon.checkImageDeleteConflict(img, force); conflict != nil { <del> if quiet && !daemon.imageIsDangling(img) { <add> if conflict := daemon.checkImageDeleteConflict(ctx, img, force); conflict != nil { <add> if quiet && !daemon.imageIsDangling(ctx, img) { <ide> // Ignore conflicts UNLESS the image is "dangling" in <ide> // which case we want the user to know. <ide> return nil <ide> func (daemon *Daemon) imageDeleteHelper(img *image.Image, records *[]types.Image <ide> } <ide> <ide> // Delete all repository tag/digest references to this image. <del> if err := daemon.removeAllReferencesToImageID(img.ID, records); err != nil { <add> if err := daemon.removeAllReferencesToImageID(ctx, img.ID, records); err != nil { <ide> return err <ide> } <ide> <del> if err := daemon.Graph().Delete(img.ID); err != nil { <add> if err := daemon.Graph(ctx).Delete(img.ID); err != nil { <ide> return err <ide> } <ide> <del> daemon.EventsService.Log("delete", img.ID, "") <add> daemon.EventsService.Log(ctx, "delete", img.ID, "") <ide> *records = append(*records, types.ImageDelete{Deleted: img.ID}) <ide> <ide> if !prune || img.Parent == "" { <ide> func (daemon *Daemon) imageDeleteHelper(img *image.Image, records *[]types.Image <ide> // We need to prune the parent image. This means delete it if there are <ide> // no tags/digests referencing it and there are no containers using it ( <ide> // either running or stopped). <del> parentImg, err := daemon.Graph().Get(img.Parent) <add> parentImg, err := daemon.Graph(ctx).Get(img.Parent) <ide> if err != nil { <ide> return derr.ErrorCodeImgNoParent.WithArgs(err) <ide> } <ide> <ide> // Do not force prunings, but do so quietly (stopping on any encountered <ide> // conflicts). <del> return daemon.imageDeleteHelper(parentImg, records, false, true, true) <add> return daemon.imageDeleteHelper(ctx, parentImg, records, false, true, true) <ide> } <ide> <ide> // checkImageDeleteConflict determines whether there are any conflicts <ide> func (daemon *Daemon) imageDeleteHelper(img *image.Image, records *[]types.Image <ide> // using the image. A soft conflict is any tags/digest referencing the given <ide> // image or any stopped container using the image. If ignoreSoftConflicts is <ide> // true, this function will not check for soft conflict conditions. <del>func (daemon *Daemon) checkImageDeleteConflict(img *image.Image, ignoreSoftConflicts bool) *imageDeleteConflict { <add>func (daemon *Daemon) checkImageDeleteConflict(ctx context.Context, img *image.Image, ignoreSoftConflicts bool) *imageDeleteConflict { <ide> // Check for hard conflicts first. <del> if conflict := daemon.checkImageDeleteHardConflict(img); conflict != nil { <add> if conflict := daemon.checkImageDeleteHardConflict(ctx, img); conflict != nil { <ide> return conflict <ide> } <ide> <ide> func (daemon *Daemon) checkImageDeleteConflict(img *image.Image, ignoreSoftConfl <ide> return nil <ide> } <ide> <del> return daemon.checkImageDeleteSoftConflict(img) <add> return daemon.checkImageDeleteSoftConflict(ctx, img) <ide> } <ide> <del>func (daemon *Daemon) checkImageDeleteHardConflict(img *image.Image) *imageDeleteConflict { <add>func (daemon *Daemon) checkImageDeleteHardConflict(ctx context.Context, img *image.Image) *imageDeleteConflict { <ide> // Check if the image ID is being used by a pull or build. <del> if daemon.Graph().IsHeld(img.ID) { <add> if daemon.Graph(ctx).IsHeld(img.ID) { <ide> return &imageDeleteConflict{ <ide> hard: true, <ide> imgID: img.ID, <ide> func (daemon *Daemon) checkImageDeleteHardConflict(img *image.Image) *imageDelet <ide> } <ide> <ide> // Check if the image has any descendent images. <del> if daemon.Graph().HasChildren(img) { <add> if daemon.Graph(ctx).HasChildren(img) { <ide> return &imageDeleteConflict{ <ide> hard: true, <ide> imgID: img.ID, <ide> func (daemon *Daemon) checkImageDeleteHardConflict(img *image.Image) *imageDelet <ide> } <ide> <ide> // Check if any running container is using the image. <del> for _, container := range daemon.List() { <add> for _, container := range daemon.List(ctx) { <ide> if !container.IsRunning() { <ide> // Skip this until we check for soft conflicts later. <ide> continue <ide> func (daemon *Daemon) checkImageDeleteHardConflict(img *image.Image) *imageDelet <ide> return nil <ide> } <ide> <del>func (daemon *Daemon) checkImageDeleteSoftConflict(img *image.Image) *imageDeleteConflict { <add>func (daemon *Daemon) checkImageDeleteSoftConflict(ctx context.Context, img *image.Image) *imageDeleteConflict { <ide> // Check if any repository tags/digest reference this image. <del> if daemon.Repositories().HasReferences(img) { <add> if daemon.Repositories(ctx).HasReferences(img) { <ide> return &imageDeleteConflict{ <ide> imgID: img.ID, <ide> message: "image is referenced in one or more repositories", <ide> } <ide> } <ide> <ide> // Check if any stopped containers reference this image. <del> for _, container := range daemon.List() { <add> for _, container := range daemon.List(ctx) { <ide> if container.IsRunning() { <ide> // Skip this as it was checked above in hard conflict conditions. <ide> continue <ide> func (daemon *Daemon) checkImageDeleteSoftConflict(img *image.Image) *imageDelet <ide> // imageIsDangling returns whether the given image is "dangling" which means <ide> // that there are no repository references to the given image and it has no <ide> // child images. <del>func (daemon *Daemon) imageIsDangling(img *image.Image) bool { <del> return !(daemon.Repositories().HasReferences(img) || daemon.Graph().HasChildren(img)) <add>func (daemon *Daemon) imageIsDangling(ctx context.Context, img *image.Image) bool { <add> return !(daemon.Repositories(ctx).HasReferences(img) || daemon.Graph(ctx).HasChildren(img)) <ide> } <ide><path>daemon/info.go <ide> import ( <ide> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/autogen/dockerversion" <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/pkg/fileutils" <ide> "github.com/docker/docker/pkg/parsers/kernel" <ide> "github.com/docker/docker/pkg/parsers/operatingsystem" <ide> import ( <ide> ) <ide> <ide> // SystemInfo returns information about the host server the daemon is running on. <del>func (daemon *Daemon) SystemInfo() (*types.Info, error) { <del> images := daemon.Graph().Map() <add>func (daemon *Daemon) SystemInfo(ctx context.Context) (*types.Info, error) { <add> images := daemon.Graph(ctx).Map() <ide> var imgcount int <ide> if images == nil { <ide> imgcount = 0 <ide> func (daemon *Daemon) SystemInfo() (*types.Info, error) { <ide> <ide> v := &types.Info{ <ide> ID: daemon.ID, <del> Containers: len(daemon.List()), <add> Containers: len(daemon.List(ctx)), <ide> Images: imgcount, <del> Driver: daemon.GraphDriver().String(), <del> DriverStatus: daemon.GraphDriver().Status(), <add> Driver: daemon.GraphDriver(ctx).String(), <add> DriverStatus: daemon.GraphDriver(ctx).Status(), <ide> IPv4Forwarding: !sysInfo.IPv4ForwardingDisabled, <ide> BridgeNfIptables: !sysInfo.BridgeNfCallIptablesDisabled, <ide> BridgeNfIP6tables: !sysInfo.BridgeNfCallIP6tablesDisabled, <ide> Debug: os.Getenv("DEBUG") != "", <ide> NFd: fileutils.GetTotalUsedFds(), <ide> NGoroutines: runtime.NumGoroutine(), <ide> SystemTime: time.Now().Format(time.RFC3339Nano), <del> ExecutionDriver: daemon.ExecutionDriver().Name(), <add> ExecutionDriver: daemon.ExecutionDriver(ctx).Name(), <ide> LoggingDriver: daemon.defaultLogConfig.Type, <ide> NEventsListener: daemon.EventsService.SubscribersCount(), <ide> KernelVersion: kernelVersion, <ide><path>daemon/inspect.go <ide> import ( <ide> "time" <ide> <ide> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/context" <ide> ) <ide> <ide> // ContainerInspect returns low-level information about a <ide> // container. Returns an error if the container cannot be found, or if <ide> // there is an error getting the data. <del>func (daemon *Daemon) ContainerInspect(name string) (*types.ContainerJSON, error) { <del> container, err := daemon.Get(name) <add>func (daemon *Daemon) ContainerInspect(ctx context.Context, name string) (*types.ContainerJSON, error) { <add> container, err := daemon.Get(ctx, name) <ide> if err != nil { <ide> return nil, err <ide> } <ide> <ide> container.Lock() <ide> defer container.Unlock() <ide> <del> base, err := daemon.getInspectData(container) <add> base, err := daemon.getInspectData(ctx, container) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func (daemon *Daemon) ContainerInspect(name string) (*types.ContainerJSON, error <ide> } <ide> <ide> // ContainerInspect120 serializes the master version of a container into a json type. <del>func (daemon *Daemon) ContainerInspect120(name string) (*types.ContainerJSON120, error) { <del> container, err := daemon.Get(name) <add>func (daemon *Daemon) ContainerInspect120(ctx context.Context, name string) (*types.ContainerJSON120, error) { <add> container, err := daemon.Get(ctx, name) <ide> if err != nil { <ide> return nil, err <ide> } <ide> <ide> container.Lock() <ide> defer container.Unlock() <ide> <del> base, err := daemon.getInspectData(container) <add> base, err := daemon.getInspectData(ctx, container) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func (daemon *Daemon) ContainerInspect120(name string) (*types.ContainerJSON120, <ide> return &types.ContainerJSON120{base, mountPoints, config}, nil <ide> } <ide> <del>func (daemon *Daemon) getInspectData(container *Container) (*types.ContainerJSONBase, error) { <add>func (daemon *Daemon) getInspectData(ctx context.Context, container *Container) (*types.ContainerJSONBase, error) { <ide> // make a copy to play with <ide> hostConfig := *container.hostConfig <ide> <del> if children, err := daemon.children(container.Name); err == nil { <add> if children, err := daemon.children(ctx, container.Name); err == nil { <ide> for linkAlias, child := range children { <ide> hostConfig.Links = append(hostConfig.Links, fmt.Sprintf("%s:%s", child.Name, linkAlias)) <ide> } <ide> func (daemon *Daemon) getInspectData(container *Container) (*types.ContainerJSON <ide> <ide> // ContainerExecInspect returns low-level information about the exec <ide> // command. An error is returned if the exec cannot be found. <del>func (daemon *Daemon) ContainerExecInspect(id string) (*ExecConfig, error) { <add>func (daemon *Daemon) ContainerExecInspect(ctx context.Context, id string) (*ExecConfig, error) { <ide> eConfig, err := daemon.getExecConfig(id) <ide> if err != nil { <ide> return nil, err <ide> func (daemon *Daemon) ContainerExecInspect(id string) (*ExecConfig, error) { <ide> <ide> // VolumeInspect looks up a volume by name. An error is returned if <ide> // the volume cannot be found. <del>func (daemon *Daemon) VolumeInspect(name string) (*types.Volume, error) { <add>func (daemon *Daemon) VolumeInspect(ctx context.Context, name string) (*types.Volume, error) { <ide> v, err := daemon.volumes.Get(name) <ide> if err != nil { <ide> return nil, err <ide><path>daemon/inspect_unix.go <ide> <ide> package daemon <ide> <del>import "github.com/docker/docker/api/types" <add>import ( <add> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/context" <add>) <ide> <ide> // This sets platform-specific fields <ide> func setPlatformSpecificContainerFields(container *Container, contJSONBase *types.ContainerJSONBase) *types.ContainerJSONBase { <ide> func setPlatformSpecificContainerFields(container *Container, contJSONBase *type <ide> } <ide> <ide> // ContainerInspectPre120 gets containers for pre 1.20 APIs. <del>func (daemon *Daemon) ContainerInspectPre120(name string) (*types.ContainerJSONPre120, error) { <del> container, err := daemon.Get(name) <add>func (daemon *Daemon) ContainerInspectPre120(ctx context.Context, name string) (*types.ContainerJSONPre120, error) { <add> container, err := daemon.Get(ctx, name) <ide> if err != nil { <ide> return nil, err <ide> } <ide> <ide> container.Lock() <ide> defer container.Unlock() <ide> <del> base, err := daemon.getInspectData(container) <add> base, err := daemon.getInspectData(ctx, container) <ide> if err != nil { <ide> return nil, err <ide> } <ide><path>daemon/inspect_windows.go <ide> package daemon <ide> <del>import "github.com/docker/docker/api/types" <add>import ( <add> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/context" <add>) <ide> <ide> // This sets platform-specific fields <ide> func setPlatformSpecificContainerFields(container *Container, contJSONBase *types.ContainerJSONBase) *types.ContainerJSONBase { <ide> func addMountPoints(container *Container) []types.MountPoint { <ide> } <ide> <ide> // ContainerInspectPre120 get containers for pre 1.20 APIs. <del>func (daemon *Daemon) ContainerInspectPre120(name string) (*types.ContainerJSON, error) { <del> return daemon.ContainerInspect(name) <add>func (daemon *Daemon) ContainerInspectPre120(ctx context.Context, name string) (*types.ContainerJSON, error) { <add> return daemon.ContainerInspect(ctx, name) <ide> } <ide><path>daemon/kill.go <ide> package daemon <ide> <del>import "syscall" <add>import ( <add> "syscall" <add> <add> "github.com/docker/docker/context" <add>) <ide> <ide> // ContainerKill send signal to the container <ide> // If no signal is given (sig 0), then Kill with SIGKILL and wait <ide> // for the container to exit. <ide> // If a signal is given, then just send it to the container and return. <del>func (daemon *Daemon) ContainerKill(name string, sig uint64) error { <del> container, err := daemon.Get(name) <add>func (daemon *Daemon) ContainerKill(ctx context.Context, name string, sig uint64) error { <add> container, err := daemon.Get(ctx, name) <ide> if err != nil { <ide> return err <ide> } <ide> <ide> // If no signal is passed, or SIGKILL, perform regular Kill (SIGKILL + wait()) <ide> if sig == 0 || syscall.Signal(sig) == syscall.SIGKILL { <del> if err := container.Kill(); err != nil { <add> if err := container.Kill(ctx); err != nil { <ide> return err <ide> } <ide> } else { <ide> // Otherwise, just send the requested signal <del> if err := container.killSig(int(sig)); err != nil { <add> if err := container.killSig(ctx, int(sig)); err != nil { <ide> return err <ide> } <ide> } <ide><path>daemon/list.go <ide> import ( <ide> <ide> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/context" <ide> derr "github.com/docker/docker/errors" <ide> "github.com/docker/docker/image" <ide> "github.com/docker/docker/pkg/graphdb" <ide> type iterationAction int <ide> <ide> // containerReducer represents a reducer for a container. <ide> // Returns the object to serialize by the api. <del>type containerReducer func(*Container, *listContext) (*types.Container, error) <add>type containerReducer func(context.Context, *Container, *listContext) (*types.Container, error) <ide> <ide> const ( <ide> // includeContainer is the action to include a container in the reducer. <ide> const ( <ide> var errStopIteration = errors.New("container list iteration stopped") <ide> <ide> // List returns an array of all containers registered in the daemon. <del>func (daemon *Daemon) List() []*Container { <add>func (daemon *Daemon) List(ctx context.Context) []*Container { <ide> return daemon.containers.List() <ide> } <ide> <ide> type listContext struct { <ide> } <ide> <ide> // Containers returns the list of containers to show given the user's filtering. <del>func (daemon *Daemon) Containers(config *ContainersConfig) ([]*types.Container, error) { <del> return daemon.reduceContainers(config, daemon.transformContainer) <add>func (daemon *Daemon) Containers(ctx context.Context, config *ContainersConfig) ([]*types.Container, error) { <add> return daemon.reduceContainers(ctx, config, daemon.transformContainer) <ide> } <ide> <ide> // reduceContainer parses the user filtering and generates the list of containers to return based on a reducer. <del>func (daemon *Daemon) reduceContainers(config *ContainersConfig, reducer containerReducer) ([]*types.Container, error) { <add>func (daemon *Daemon) reduceContainers(ctx context.Context, config *ContainersConfig, reducer containerReducer) ([]*types.Container, error) { <ide> containers := []*types.Container{} <ide> <del> ctx, err := daemon.foldFilter(config) <add> fctx, err := daemon.foldFilter(ctx, config) <ide> if err != nil { <ide> return nil, err <ide> } <ide> <del> for _, container := range daemon.List() { <del> t, err := daemon.reducePsContainer(container, ctx, reducer) <add> for _, container := range daemon.List(ctx) { <add> t, err := daemon.reducePsContainer(ctx, container, fctx, reducer) <ide> if err != nil { <ide> if err != errStopIteration { <ide> return nil, err <ide> func (daemon *Daemon) reduceContainers(config *ContainersConfig, reducer contain <ide> } <ide> if t != nil { <ide> containers = append(containers, t) <del> ctx.idx++ <add> fctx.idx++ <ide> } <ide> } <ide> return containers, nil <ide> } <ide> <ide> // reducePsContainer is the basic representation for a container as expected by the ps command. <del>func (daemon *Daemon) reducePsContainer(container *Container, ctx *listContext, reducer containerReducer) (*types.Container, error) { <add>func (daemon *Daemon) reducePsContainer(ctx context.Context, container *Container, lctx *listContext, reducer containerReducer) (*types.Container, error) { <ide> container.Lock() <ide> defer container.Unlock() <ide> <ide> // filter containers to return <del> action := includeContainerInList(container, ctx) <add> action := includeContainerInList(container, lctx) <ide> switch action { <ide> case excludeContainer: <ide> return nil, nil <ide> func (daemon *Daemon) reducePsContainer(container *Container, ctx *listContext, <ide> } <ide> <ide> // transform internal container struct into api structs <del> return reducer(container, ctx) <add> return reducer(ctx, container, lctx) <ide> } <ide> <ide> // foldFilter generates the container filter based in the user's filtering options. <del>func (daemon *Daemon) foldFilter(config *ContainersConfig) (*listContext, error) { <add>func (daemon *Daemon) foldFilter(ctx context.Context, config *ContainersConfig) (*listContext, error) { <ide> psFilters, err := filters.FromParam(config.Filters) <ide> if err != nil { <ide> return nil, err <ide> func (daemon *Daemon) foldFilter(config *ContainersConfig) (*listContext, error) <ide> var ancestorFilter bool <ide> if ancestors, ok := psFilters["ancestor"]; ok { <ide> ancestorFilter = true <del> byParents := daemon.Graph().ByParent() <add> byParents := daemon.Graph(ctx).ByParent() <ide> // The idea is to walk the graph down the most "efficient" way. <ide> for _, ancestor := range ancestors { <ide> // First, get the imageId of the ancestor filter (yay) <del> image, err := daemon.Repositories().LookupImage(ancestor) <add> image, err := daemon.Repositories(ctx).LookupImage(ancestor) <ide> if err != nil { <ide> logrus.Warnf("Error while looking up for image %v", ancestor) <ide> continue <ide> func (daemon *Daemon) foldFilter(config *ContainersConfig) (*listContext, error) <ide> <ide> var beforeCont, sinceCont *Container <ide> if config.Before != "" { <del> beforeCont, err = daemon.Get(config.Before) <add> beforeCont, err = daemon.Get(ctx, config.Before) <ide> if err != nil { <ide> return nil, err <ide> } <ide> } <ide> <ide> if config.Since != "" { <del> sinceCont, err = daemon.Get(config.Since) <add> sinceCont, err = daemon.Get(ctx, config.Since) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func includeContainerInList(container *Container, ctx *listContext) iterationAct <ide> } <ide> <ide> // transformContainer generates the container type expected by the docker ps command. <del>func (daemon *Daemon) transformContainer(container *Container, ctx *listContext) (*types.Container, error) { <add>func (daemon *Daemon) transformContainer(ctx context.Context, container *Container, lctx *listContext) (*types.Container, error) { <ide> newC := &types.Container{ <ide> ID: container.ID, <del> Names: ctx.names[container.ID], <add> Names: lctx.names[container.ID], <ide> } <ide> <del> img, err := daemon.Repositories().LookupImage(container.Config.Image) <add> img, err := daemon.Repositories(ctx).LookupImage(container.Config.Image) <ide> if err != nil { <ide> // If the image can no longer be found by its original reference, <ide> // it makes sense to show the ID instead of a stale reference. <ide> func (daemon *Daemon) transformContainer(container *Container, ctx *listContext) <ide> } <ide> } <ide> <del> if ctx.Size { <del> sizeRw, sizeRootFs := container.getSize() <add> if lctx.Size { <add> sizeRw, sizeRootFs := container.getSize(ctx) <ide> newC.SizeRw = sizeRw <ide> newC.SizeRootFs = sizeRootFs <ide> } <ide> func (daemon *Daemon) transformContainer(container *Container, ctx *listContext) <ide> <ide> // Volumes lists known volumes, using the filter to restrict the range <ide> // of volumes returned. <del>func (daemon *Daemon) Volumes(filter string) ([]*types.Volume, error) { <add>func (daemon *Daemon) Volumes(ctx context.Context, filter string) ([]*types.Volume, error) { <ide> var volumesOut []*types.Volume <ide> volFilters, err := filters.FromParam(filter) <ide> if err != nil { <ide><path>daemon/logs.go <ide> import ( <ide> "time" <ide> <ide> "github.com/Sirupsen/logrus" <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/daemon/logger" <ide> derr "github.com/docker/docker/errors" <ide> "github.com/docker/docker/pkg/stdcopy" <ide> type ContainerLogsConfig struct { <ide> <ide> // ContainerLogs hooks up a container's stdout and stderr streams <ide> // configured with the given struct. <del>func (daemon *Daemon) ContainerLogs(container *Container, config *ContainerLogsConfig) error { <add>func (daemon *Daemon) ContainerLogs(ctx context.Context, container *Container, config *ContainerLogsConfig) error { <ide> if !(config.UseStdout || config.UseStderr) { <ide> return derr.ErrorCodeNeedStream <ide> } <ide><path>daemon/monitor.go <ide> import ( <ide> "time" <ide> <ide> "github.com/Sirupsen/logrus" <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/daemon/execdriver" <ide> "github.com/docker/docker/pkg/stringid" <ide> "github.com/docker/docker/runconfig" <ide> func (m *containerMonitor) ExitOnNext() { <ide> <ide> // Close closes the container's resources such as networking allocations and <ide> // unmounts the contatiner's root filesystem <del>func (m *containerMonitor) Close() error { <add>func (m *containerMonitor) Close(ctx context.Context) error { <ide> // Cleanup networking and mounts <del> m.container.cleanup() <add> m.container.cleanup(ctx) <ide> <ide> // FIXME: here is race condition between two RUN instructions in Dockerfile <ide> // because they share same runconfig and change image. Must be fixed <ide> func (m *containerMonitor) Close() error { <ide> } <ide> <ide> // Start starts the containers process and monitors it according to the restart policy <del>func (m *containerMonitor) Start() error { <add>func (m *containerMonitor) Start(ctx context.Context) error { <ide> var ( <ide> err error <ide> exitStatus execdriver.ExitStatus <ide> func (m *containerMonitor) Start() error { <ide> m.container.setStopped(&exitStatus) <ide> defer m.container.Unlock() <ide> } <del> m.Close() <add> m.Close(ctx) <ide> }() <ide> // reset stopped flag <ide> if m.container.HasBeenManuallyStopped { <ide> func (m *containerMonitor) Start() error { <ide> <ide> pipes := execdriver.NewPipes(m.container.stdin, m.container.stdout, m.container.stderr, m.container.Config.OpenStdin) <ide> <del> m.container.logEvent("start") <add> m.container.logEvent(ctx, "start") <ide> <ide> m.lastStartTime = time.Now() <ide> <del> if exitStatus, err = m.container.daemon.run(m.container, pipes, m.callback); err != nil { <add> if exitStatus, err = m.container.daemon.run(ctx, m.container, pipes, m.callback); err != nil { <ide> // if we receive an internal error from the initial start of a container then lets <ide> // return it instead of entering the restart loop <ide> if m.container.RestartCount == 0 { <ide> func (m *containerMonitor) Start() error { <ide> <ide> if m.shouldRestart(exitStatus.ExitCode) { <ide> m.container.setRestarting(&exitStatus) <del> m.container.logEvent("die") <add> m.container.logEvent(ctx, "die") <ide> m.resetContainer(true) <ide> <ide> // sleep with a small time increment between each restart to help avoid issues cased by quickly <ide> func (m *containerMonitor) Start() error { <ide> continue <ide> } <ide> <del> m.container.logEvent("die") <add> m.container.logEvent(ctx, "die") <ide> m.resetContainer(true) <ide> return err <ide> } <ide> func (m *containerMonitor) shouldRestart(exitCode int) bool { <ide> <ide> // callback ensures that the container's state is properly updated after we <ide> // received ack from the execution drivers <del>func (m *containerMonitor) callback(processConfig *execdriver.ProcessConfig, pid int, chOOM <-chan struct{}) error { <add>func (m *containerMonitor) callback(ctx context.Context, processConfig *execdriver.ProcessConfig, pid int, chOOM <-chan struct{}) error { <ide> go func() { <ide> _, ok := <-chOOM <ide> if ok { <del> m.container.logEvent("oom") <add> m.container.logEvent(ctx, "oom") <ide> } <ide> }() <ide> <ide><path>daemon/pause.go <ide> package daemon <ide> <ide> import ( <add> "github.com/docker/docker/context" <ide> derr "github.com/docker/docker/errors" <ide> ) <ide> <ide> // ContainerPause pauses a container <del>func (daemon *Daemon) ContainerPause(name string) error { <del> container, err := daemon.Get(name) <add>func (daemon *Daemon) ContainerPause(ctx context.Context, name string) error { <add> container, err := daemon.Get(ctx, name) <ide> if err != nil { <ide> return err <ide> } <ide> <del> if err := container.pause(); err != nil { <add> if err := container.pause(ctx); err != nil { <ide> return derr.ErrorCodePauseError.WithArgs(name, err) <ide> } <ide> <ide><path>daemon/rename.go <ide> package daemon <ide> <ide> import ( <add> "github.com/docker/docker/context" <ide> derr "github.com/docker/docker/errors" <ide> ) <ide> <ide> // ContainerRename changes the name of a container, using the oldName <ide> // to find the container. An error is returned if newName is already <ide> // reserved. <del>func (daemon *Daemon) ContainerRename(oldName, newName string) error { <add>func (daemon *Daemon) ContainerRename(ctx context.Context, oldName, newName string) error { <ide> if oldName == "" || newName == "" { <ide> return derr.ErrorCodeEmptyRename <ide> } <ide> <del> container, err := daemon.Get(oldName) <add> container, err := daemon.Get(ctx, oldName) <ide> if err != nil { <ide> return err <ide> } <ide> func (daemon *Daemon) ContainerRename(oldName, newName string) error { <ide> <ide> container.Lock() <ide> defer container.Unlock() <del> if newName, err = daemon.reserveName(container.ID, newName); err != nil { <add> if newName, err = daemon.reserveName(ctx, container.ID, newName); err != nil { <ide> return derr.ErrorCodeRenameTaken.WithArgs(err) <ide> } <ide> <ide> container.Name = newName <ide> <ide> undo := func() { <ide> container.Name = oldName <del> daemon.reserveName(container.ID, oldName) <add> daemon.reserveName(ctx, container.ID, oldName) <ide> daemon.containerGraphDB.Delete(newName) <ide> } <ide> <ide> func (daemon *Daemon) ContainerRename(oldName, newName string) error { <ide> return err <ide> } <ide> <del> container.logEvent("rename") <add> container.logEvent(ctx, "rename") <ide> return nil <ide> } <ide><path>daemon/resize.go <ide> package daemon <ide> <add>import ( <add> "github.com/docker/docker/context" <add>) <add> <ide> // ContainerResize changes the size of the TTY of the process running <ide> // in the container with the given name to the given height and width. <del>func (daemon *Daemon) ContainerResize(name string, height, width int) error { <del> container, err := daemon.Get(name) <add>func (daemon *Daemon) ContainerResize(ctx context.Context, name string, height, width int) error { <add> container, err := daemon.Get(ctx, name) <ide> if err != nil { <ide> return err <ide> } <ide> <del> return container.Resize(height, width) <add> return container.Resize(ctx, height, width) <ide> } <ide> <ide> // ContainerExecResize changes the size of the TTY of the process <ide> // running in the exec with the given name to the given height and <ide> // width. <del>func (daemon *Daemon) ContainerExecResize(name string, height, width int) error { <add>func (daemon *Daemon) ContainerExecResize(ctx context.Context, name string, height, width int) error { <ide> ExecConfig, err := daemon.getExecConfig(name) <ide> if err != nil { <ide> return err <ide><path>daemon/restart.go <ide> package daemon <ide> <ide> import ( <add> "github.com/docker/docker/context" <ide> derr "github.com/docker/docker/errors" <ide> ) <ide> <ide> import ( <ide> // timeout, ContainerRestart will wait forever until a graceful <ide> // stop. Returns an error if the container cannot be found, or if <ide> // there is an underlying error at any stage of the restart. <del>func (daemon *Daemon) ContainerRestart(name string, seconds int) error { <del> container, err := daemon.Get(name) <add>func (daemon *Daemon) ContainerRestart(ctx context.Context, name string, seconds int) error { <add> container, err := daemon.Get(ctx, name) <ide> if err != nil { <ide> return err <ide> } <del> if err := container.Restart(seconds); err != nil { <add> if err := container.Restart(ctx, seconds); err != nil { <ide> return derr.ErrorCodeCantRestart.WithArgs(name, err) <ide> } <ide> return nil <ide><path>daemon/start.go <ide> package daemon <ide> import ( <ide> "runtime" <ide> <add> "github.com/docker/docker/context" <ide> derr "github.com/docker/docker/errors" <ide> "github.com/docker/docker/runconfig" <ide> "github.com/docker/docker/utils" <ide> ) <ide> <ide> // ContainerStart starts a container. <del>func (daemon *Daemon) ContainerStart(name string, hostConfig *runconfig.HostConfig) error { <del> container, err := daemon.Get(name) <add>func (daemon *Daemon) ContainerStart(ctx context.Context, name string, hostConfig *runconfig.HostConfig) error { <add> container, err := daemon.Get(ctx, name) <ide> if err != nil { <ide> return err <ide> } <ide> func (daemon *Daemon) ContainerStart(name string, hostConfig *runconfig.HostConf <ide> // This is kept for backward compatibility - hostconfig should be passed when <ide> // creating a container, not during start. <ide> if hostConfig != nil { <del> if err := daemon.setHostConfig(container, hostConfig); err != nil { <add> if err := daemon.setHostConfig(ctx, container, hostConfig); err != nil { <ide> return err <ide> } <ide> } <ide> func (daemon *Daemon) ContainerStart(name string, hostConfig *runconfig.HostConf <ide> <ide> // check if hostConfig is in line with the current system settings. <ide> // It may happen cgroups are umounted or the like. <del> if _, err = daemon.verifyContainerSettings(container.hostConfig, nil); err != nil { <add> if _, err = daemon.verifyContainerSettings(ctx, container.hostConfig, nil); err != nil { <ide> return err <ide> } <ide> <del> if err := container.Start(); err != nil { <add> if err := container.Start(ctx); err != nil { <ide> return derr.ErrorCodeCantStart.WithArgs(name, utils.GetErrorMessage(err)) <ide> } <ide> <ide><path>daemon/stats.go <ide> import ( <ide> "io" <ide> <ide> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/daemon/execdriver" <ide> "github.com/docker/docker/pkg/version" <ide> "github.com/docker/libnetwork/osl" <ide> type ContainerStatsConfig struct { <ide> <ide> // ContainerStats writes information about the container to the stream <ide> // given in the config object. <del>func (daemon *Daemon) ContainerStats(prefixOrName string, config *ContainerStatsConfig) error { <add>func (daemon *Daemon) ContainerStats(ctx context.Context, prefixOrName string, config *ContainerStatsConfig) error { <ide> <del> container, err := daemon.Get(prefixOrName) <add> container, err := daemon.Get(ctx, prefixOrName) <ide> if err != nil { <ide> return err <ide> } <ide><path>daemon/stop.go <ide> package daemon <ide> <ide> import ( <add> "github.com/docker/docker/context" <ide> derr "github.com/docker/docker/errors" <ide> ) <ide> <ide> import ( <ide> // will wait for a graceful termination. An error is returned if the <ide> // container is not found, is already stopped, or if there is a <ide> // problem stopping the container. <del>func (daemon *Daemon) ContainerStop(name string, seconds int) error { <del> container, err := daemon.Get(name) <add>func (daemon *Daemon) ContainerStop(ctx context.Context, name string, seconds int) error { <add> container, err := daemon.Get(ctx, name) <ide> if err != nil { <ide> return err <ide> } <ide> if !container.IsRunning() { <ide> return derr.ErrorCodeStopped <ide> } <del> if err := container.Stop(seconds); err != nil { <add> if err := container.Stop(ctx, seconds); err != nil { <ide> return derr.ErrorCodeCantStop.WithArgs(name, err) <ide> } <ide> return nil <ide><path>daemon/top_unix.go <ide> import ( <ide> "strings" <ide> <ide> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/context" <ide> derr "github.com/docker/docker/errors" <ide> ) <ide> <ide> import ( <ide> // "-ef" if no args are given. An error is returned if the container <ide> // is not found, or is not running, or if there are any problems <ide> // running ps, or parsing the output. <del>func (daemon *Daemon) ContainerTop(name string, psArgs string) (*types.ContainerProcessList, error) { <add>func (daemon *Daemon) ContainerTop(ctx context.Context, name string, psArgs string) (*types.ContainerProcessList, error) { <ide> if psArgs == "" { <ide> psArgs = "-ef" <ide> } <ide> <del> container, err := daemon.Get(name) <add> container, err := daemon.Get(ctx, name) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func (daemon *Daemon) ContainerTop(name string, psArgs string) (*types.Container <ide> return nil, derr.ErrorCodeNotRunning.WithArgs(name) <ide> } <ide> <del> pids, err := daemon.ExecutionDriver().GetPidsForContainer(container.ID) <add> pids, err := daemon.ExecutionDriver(ctx).GetPidsForContainer(container.ID) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func (daemon *Daemon) ContainerTop(name string, psArgs string) (*types.Container <ide> } <ide> } <ide> } <del> container.logEvent("top") <add> container.logEvent(ctx, "top") <ide> return procList, nil <ide> } <ide><path>daemon/top_windows.go <ide> package daemon <ide> <ide> import ( <ide> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/context" <ide> derr "github.com/docker/docker/errors" <ide> ) <ide> <ide> // ContainerTop is not supported on Windows and returns an error. <del>func (daemon *Daemon) ContainerTop(name string, psArgs string) (*types.ContainerProcessList, error) { <add>func (daemon *Daemon) ContainerTop(ctx context.Context, name string, psArgs string) (*types.ContainerProcessList, error) { <ide> return nil, derr.ErrorCodeNoTop <ide> } <ide><path>daemon/unpause.go <ide> package daemon <ide> <ide> import ( <add> "github.com/docker/docker/context" <ide> derr "github.com/docker/docker/errors" <ide> ) <ide> <ide> // ContainerUnpause unpauses a container <del>func (daemon *Daemon) ContainerUnpause(name string) error { <del> container, err := daemon.Get(name) <add>func (daemon *Daemon) ContainerUnpause(ctx context.Context, name string) error { <add> container, err := daemon.Get(ctx, name) <ide> if err != nil { <ide> return err <ide> } <ide> <del> if err := container.unpause(); err != nil { <add> if err := container.unpause(ctx); err != nil { <ide> return derr.ErrorCodeCantUnpause.WithArgs(name, err) <ide> } <ide> <ide><path>daemon/volumes_unix.go <ide> import ( <ide> "strings" <ide> <ide> "github.com/Sirupsen/logrus" <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/daemon/execdriver" <ide> derr "github.com/docker/docker/errors" <ide> "github.com/docker/docker/pkg/system" <ide> func parseVolumesFrom(spec string) (string, string, error) { <ide> // 1. Select the previously configured mount points for the containers, if any. <ide> // 2. Select the volumes mounted from another containers. Overrides previously configured mount point destination. <ide> // 3. Select the bind mounts set by the client. Overrides previously configured mount point destinations. <del>func (daemon *Daemon) registerMountPoints(container *Container, hostConfig *runconfig.HostConfig) error { <add>func (daemon *Daemon) registerMountPoints(ctx context.Context, container *Container, hostConfig *runconfig.HostConfig) error { <ide> binds := map[string]bool{} <ide> mountPoints := map[string]*mountPoint{} <ide> <ide> func (daemon *Daemon) registerMountPoints(container *Container, hostConfig *runc <ide> return err <ide> } <ide> <del> c, err := daemon.Get(containerID) <add> c, err := daemon.Get(ctx, containerID) <ide> if err != nil { <ide> return err <ide> } <ide><path>daemon/volumes_windows.go <ide> package daemon <ide> <ide> import ( <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/daemon/execdriver" <ide> "github.com/docker/docker/runconfig" <ide> ) <ide> func (daemon *Daemon) verifyVolumesInfo(container *Container) error { <ide> // registerMountPoints initializes the container mount points with the <ide> // configured volumes and bind mounts. Windows does not support volumes or <ide> // mount points. <del>func (daemon *Daemon) registerMountPoints(container *Container, hostConfig *runconfig.HostConfig) error { <add>func (daemon *Daemon) registerMountPoints(ctx context.Context, container *Container, hostConfig *runconfig.HostConfig) error { <ide> return nil <ide> } <ide><path>daemon/wait.go <ide> package daemon <ide> <del>import "time" <add>import ( <add> "time" <add> <add> "github.com/docker/docker/context" <add>) <ide> <ide> // ContainerWait stops processing until the given container is <ide> // stopped. If the container is not found, an error is returned. On a <ide> // successful stop, the exit code of the container is returned. On a <ide> // timeout, an error is returned. If you want to wait forever, supply <ide> // a negative duration for the timeout. <del>func (daemon *Daemon) ContainerWait(name string, timeout time.Duration) (int, error) { <del> container, err := daemon.Get(name) <add>func (daemon *Daemon) ContainerWait(ctx context.Context, name string, timeout time.Duration) (int, error) { <add> container, err := daemon.Get(ctx, name) <ide> if err != nil { <ide> return -1, err <ide> } <ide><path>docker/daemon.go <ide> import ( <ide> "github.com/docker/docker/autogen/dockerversion" <ide> "github.com/docker/docker/cli" <ide> "github.com/docker/docker/cliconfig" <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/daemon" <ide> "github.com/docker/docker/daemon/logger" <ide> "github.com/docker/docker/opts" <ide> func getGlobalFlag() (globalFlag *flag.Flag) { <ide> <ide> // CmdDaemon is the daemon command, called the raw arguments after `docker daemon`. <ide> func (cli *DaemonCli) CmdDaemon(args ...string) error { <add> // This may need to be made even more global - it all depends <add> // on whether we want the CLI to have a context object too. <add> // For now we'll leave it as a daemon-side object only. <add> ctx := context.Background() <add> <ide> // warn from uuid package when running the daemon <ide> uuid.Loggerf = logrus.Warnf <ide> <ide> func (cli *DaemonCli) CmdDaemon(args ...string) error { <ide> serverConfig.TLSConfig = tlsConfig <ide> } <ide> <del> api := apiserver.New(serverConfig) <add> api := apiserver.New(ctx, serverConfig) <ide> <ide> // The serve API routine never exits unless an error occurs <ide> // We need to start it as a goroutine and wait on it so <ide> func (cli *DaemonCli) CmdDaemon(args ...string) error { <ide> cli.TrustKeyPath = commonFlags.TrustKey <ide> <ide> registryService := registry.NewService(cli.registryOptions) <del> d, err := daemon.NewDaemon(cli.Config, registryService) <add> d, err := daemon.NewDaemon(ctx, cli.Config, registryService) <ide> if err != nil { <ide> if pfile != nil { <ide> if err := pfile.Remove(); err != nil { <ide> func (cli *DaemonCli) CmdDaemon(args ...string) error { <ide> logrus.WithFields(logrus.Fields{ <ide> "version": dockerversion.VERSION, <ide> "commit": dockerversion.GITCOMMIT, <del> "execdriver": d.ExecutionDriver().Name(), <del> "graphdriver": d.GraphDriver().String(), <add> "execdriver": d.ExecutionDriver(ctx).Name(), <add> "graphdriver": d.GraphDriver(ctx).String(), <ide> }).Info("Docker daemon") <ide> <ide> signal.Trap(func() { <ide> api.Close() <ide> <-serveAPIWait <del> shutdownDaemon(d, 15) <add> shutdownDaemon(ctx, d, 15) <ide> if pfile != nil { <ide> if err := pfile.Remove(); err != nil { <ide> logrus.Error(err) <ide> func (cli *DaemonCli) CmdDaemon(args ...string) error { <ide> <ide> // after the daemon is done setting up we can tell the api to start <ide> // accepting connections with specified daemon <del> api.AcceptConnections(d) <add> api.AcceptConnections(ctx, d) <ide> <ide> // Daemon is fully initialized and handling API traffic <ide> // Wait for serve API to complete <ide> errAPI := <-serveAPIWait <del> shutdownDaemon(d, 15) <add> shutdownDaemon(ctx, d, 15) <ide> if errAPI != nil { <ide> if pfile != nil { <ide> if err := pfile.Remove(); err != nil { <ide> func (cli *DaemonCli) CmdDaemon(args ...string) error { <ide> // shutdownDaemon just wraps daemon.Shutdown() to handle a timeout in case <ide> // d.Shutdown() is waiting too long to kill container or worst it's <ide> // blocked there <del>func shutdownDaemon(d *daemon.Daemon, timeout time.Duration) { <add>func shutdownDaemon(ctx context.Context, d *daemon.Daemon, timeout time.Duration) { <ide> ch := make(chan struct{}) <ide> go func() { <del> d.Shutdown() <add> d.Shutdown(ctx) <ide> close(ch) <ide> }() <ide> select { <ide><path>graph/import.go <ide> import ( <ide> "net/http" <ide> "net/url" <ide> <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/pkg/httputils" <ide> "github.com/docker/docker/pkg/progressreader" <ide> "github.com/docker/docker/pkg/streamformatter" <ide> import ( <ide> // inConfig (if src is "-"), or from a URI specified in src. Progress output is <ide> // written to outStream. Repository and tag names can optionally be given in <ide> // the repo and tag arguments, respectively. <del>func (s *TagStore) Import(src string, repo string, tag string, msg string, inConfig io.ReadCloser, outStream io.Writer, containerConfig *runconfig.Config) error { <add>func (s *TagStore) Import(ctx context.Context, src string, repo string, tag string, msg string, inConfig io.ReadCloser, outStream io.Writer, containerConfig *runconfig.Config) error { <ide> var ( <ide> sf = streamformatter.NewJSONStreamFormatter() <ide> archive io.ReadCloser <ide> func (s *TagStore) Import(src string, repo string, tag string, msg string, inCon <ide> logID = utils.ImageReference(logID, tag) <ide> } <ide> <del> s.eventsService.Log("import", logID, "") <add> s.eventsService.Log(ctx, "import", logID, "") <ide> return nil <ide> } <ide><path>graph/pull.go <ide> import ( <ide> <ide> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/cliconfig" <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/pkg/streamformatter" <ide> "github.com/docker/docker/registry" <ide> "github.com/docker/docker/utils" <ide> func NewPuller(s *TagStore, endpoint registry.APIEndpoint, repoInfo *registry.Re <ide> <ide> // Pull initiates a pull operation. image is the repository name to pull, and <ide> // tag may be either empty, or indicate a specific tag to pull. <del>func (s *TagStore) Pull(image string, tag string, imagePullConfig *ImagePullConfig) error { <add>func (s *TagStore) Pull(ctx context.Context, image string, tag string, imagePullConfig *ImagePullConfig) error { <ide> var sf = streamformatter.NewJSONStreamFormatter() <ide> <ide> // Resolve the Repository name from fqn to RepositoryInfo <ide> func (s *TagStore) Pull(image string, tag string, imagePullConfig *ImagePullConf <ide> <ide> } <ide> <del> s.eventsService.Log("pull", logName, "") <add> s.eventsService.Log(ctx, "pull", logName, "") <ide> return nil <ide> } <ide> <ide><path>graph/push.go <ide> import ( <ide> "github.com/Sirupsen/logrus" <ide> "github.com/docker/distribution/digest" <ide> "github.com/docker/docker/cliconfig" <add> "github.com/docker/docker/context" <ide> "github.com/docker/docker/pkg/streamformatter" <ide> "github.com/docker/docker/registry" <ide> ) <ide> func (s *TagStore) NewPusher(endpoint registry.APIEndpoint, localRepo Repository <ide> } <ide> <ide> // Push initiates a push operation on the repository named localName. <del>func (s *TagStore) Push(localName string, imagePushConfig *ImagePushConfig) error { <add>func (s *TagStore) Push(ctx context.Context, localName string, imagePushConfig *ImagePushConfig) error { <ide> // FIXME: Allow to interrupt current push when new push of same image is done. <ide> <ide> var sf = streamformatter.NewJSONStreamFormatter() <ide> func (s *TagStore) Push(localName string, imagePushConfig *ImagePushConfig) erro <ide> <ide> } <ide> <del> s.eventsService.Log("push", repoInfo.LocalName, "") <add> s.eventsService.Log(ctx, "push", repoInfo.LocalName, "") <ide> return nil <ide> } <ide> <ide><path>integration-cli/docker_cli_events_test.go <ide> func (s *DockerSuite) TestEventsFilterContainer(c *check.C) { <ide> } <ide> <ide> // Check the id <del> parsedID := strings.TrimSuffix(e[1], ":") <add> parsedID := strings.TrimSuffix(e[3], ":") <ide> if parsedID != id { <ide> return fmt.Errorf("expected event for container id %s: %s - parsed container id: %s", id, event, parsedID) <ide> } <ide> func (s *DockerRegistrySuite) TestEventsImageFilterPush(c *check.C) { <ide> c.Fatalf("Missing 'push' log event for image %s\n%s", repoName, out) <ide> } <ide> } <add> <add>func (s *DockerSuite) TestEventsReqID(c *check.C) { <add> // Tests for the "[reqid: xxx]" field in Events <add> testRequires(c, DaemonIsLinux) <add> <add> reqIDMatch := `[^ ]+ \[reqid: ([0-9a-z]{12})\] [0-9a-z]+: ` <add> reqIDRE := regexp.MustCompile(reqIDMatch) <add> <add> // Simple test just to make sure it works at all <add> dockerCmd(c, "create", "busybox", "true") <add> <add> out, _ := dockerCmd(c, "events", "--since=0", "--until=0s") <add> events := strings.Split(strings.TrimSpace(out), "\n") <add> <add> if len(events) == 0 { <add> c.Fatalf("Wrong # of events, should just be one, got:\n%v\n", events) <add> } <add> <add> createEvent := events[len(events)-1] <add> <add> matched, err := regexp.MatchString(reqIDMatch, createEvent) <add> if err != nil || !matched { <add> c.Fatalf("Error finding reqID in event: %v\n", createEvent) <add> } <add> <add> reqID1 := reqIDRE.FindStringSubmatch(createEvent)[1] <add> <add> // Now make sure another cmd doesn't get the same reqID <add> dockerCmd(c, "create", "busybox", "true") <add> <add> out, _ = dockerCmd(c, "events", "--since=0", "--until=0s") <add> events = strings.Split(strings.TrimSpace(out), "\n") <add> createEvent = events[len(events)-1] <add> <add> matched, err = regexp.MatchString(reqIDMatch, createEvent) <add> if err != nil || !matched { <add> c.Fatalf("Error finding reqID in event: %v\n", createEvent) <add> } <add> <add> reqID2 := reqIDRE.FindStringSubmatch(createEvent)[1] <add> <add> if reqID1 == reqID2 { <add> c.Fatalf("Should not have the same reqID(%s):\n%v\n", reqID1, createEvent) <add> } <add> <add> // Now make sure a build **does** use the same reqID for all <add> // 4 events that are generated <add> _, err = buildImage("reqidimg", ` <add> FROM busybox <add> RUN echo HI`, true) <add> if err != nil { <add> c.Fatalf("Couldn't create image: %q", err) <add> } <add> <add> out, _ = dockerCmd(c, "events", "--since=0", "--until=0s") <add> events = strings.Split(strings.TrimSpace(out), "\n") <add> <add> // Get last event's reqID - will use it to find other matching events <add> lastEvent := events[len(events)-1] <add> reqID := reqIDRE.FindStringSubmatch(lastEvent)[1] <add> <add> // Find all events with this same reqID <add> eventList := []string{lastEvent} <add> for i := len(events) - 2; i >= 0; i-- { <add> tmpID := reqIDRE.FindStringSubmatch(events[i])[1] <add> if tmpID != reqID { <add> break <add> } <add> eventList = append(eventList, events[i]) <add> } <add> <add> if len(eventList) != 5 { // create, start, die, commit, destroy <add> c.Fatalf("Wrong # of matching events - should be 5:\n%q\n", eventList) <add> } <add>} <ide><path>pkg/jsonmessage/jsonmessage.go <ide> func (p *JSONProgress) String() string { <ide> // the created time, where it from, status, ID of the <ide> // message. It's used for docker events. <ide> type JSONMessage struct { <add> RequestID string `json:"reqid,omitempty"` <ide> Stream string `json:"stream,omitempty"` <ide> Status string `json:"status,omitempty"` <ide> Progress *JSONProgress `json:"progressDetail,omitempty"` <ide> func (jm *JSONMessage) Display(out io.Writer, isTerminal bool) error { <ide> } else if jm.Time != 0 { <ide> fmt.Fprintf(out, "%s ", time.Unix(jm.Time, 0).Format(timeutils.RFC3339NanoFixed)) <ide> } <add> if jm.RequestID != "" { <add> fmt.Fprintf(out, "[reqid: %s] ", jm.RequestID) <add> } <ide> if jm.ID != "" { <ide> fmt.Fprintf(out, "%s: ", jm.ID) <ide> }
68
Go
Go
address some minor linting issues and nits
eeef12f46978c534db8c83f29719692e3d86e6ae
<ide><path>daemon/oci_linux.go <ide> func WithNamespaces(daemon *Daemon, c *container.Container) coci.SpecOpts { <ide> setNamespace(s, nsUser) <ide> } <ide> case ipcMode.IsHost(): <del> oci.RemoveNamespace(s, specs.LinuxNamespaceType("ipc")) <add> oci.RemoveNamespace(s, "ipc") <ide> case ipcMode.IsEmpty(): <ide> // A container was created by an older version of the daemon. <ide> // The default behavior used to be what is now called "shareable". <ide> func WithNamespaces(daemon *Daemon, c *container.Container) coci.SpecOpts { <ide> <ide> // pid <ide> if c.HostConfig.PidMode.IsContainer() { <del> ns := specs.LinuxNamespace{Type: "pid"} <ide> pc, err := daemon.getPidContainer(c) <ide> if err != nil { <ide> return err <ide> } <del> ns.Path = fmt.Sprintf("/proc/%d/ns/pid", pc.State.GetPID()) <add> ns := specs.LinuxNamespace{ <add> Type: "pid", <add> Path: fmt.Sprintf("/proc/%d/ns/pid", pc.State.GetPID()), <add> } <ide> setNamespace(s, ns) <ide> if userNS { <ide> // to share a PID namespace, they must also share a user namespace <del> nsUser := specs.LinuxNamespace{Type: "user"} <del> nsUser.Path = fmt.Sprintf("/proc/%d/ns/user", pc.State.GetPID()) <add> nsUser := specs.LinuxNamespace{ <add> Type: "user", <add> Path: fmt.Sprintf("/proc/%d/ns/user", pc.State.GetPID()), <add> } <ide> setNamespace(s, nsUser) <ide> } <ide> } else if c.HostConfig.PidMode.IsHost() { <del> oci.RemoveNamespace(s, specs.LinuxNamespaceType("pid")) <add> oci.RemoveNamespace(s, "pid") <ide> } else { <ide> ns := specs.LinuxNamespace{Type: "pid"} <ide> setNamespace(s, ns) <ide> } <ide> // uts <ide> if c.HostConfig.UTSMode.IsHost() { <del> oci.RemoveNamespace(s, specs.LinuxNamespaceType("uts")) <add> oci.RemoveNamespace(s, "uts") <ide> s.Hostname = "" <ide> } <ide> <ide><path>daemon/oci_linux_test.go <ide> func setupFakeDaemon(t *testing.T, c *container.Container) *Daemon { <ide> } <ide> <ide> func cleanupFakeContainer(c *container.Container) { <del> os.RemoveAll(c.Root) <add> _ = os.RemoveAll(c.Root) <ide> } <ide> <ide> // TestTmpfsDevShmNoDupMount checks that a user-specified /dev/shm tmpfs
2
Text
Text
add v3.14.2 to changelog.md
432c49d2ceb55067f5cf6893c04a2e609bf1fa0d
<ide><path>CHANGELOG.md <ide> - [#18491](https://github.com/emberjs/ember.js/pull/18491) [DEPRECATION] Deprecate `{{partial}}` per [RFC #449](https://github.com/emberjs/rfcs/blob/master/text/0449-deprecate-partials.md). <ide> - [#18441](https://github.com/emberjs/ember.js/pull/18441) [DEPRECATION] Deprecate window.ENV <ide> <add>### v3.14.2 (November 20, 2019) <add> <add>- [#18539](https://github.com/emberjs/ember.js/pull/18539) / [#18548](https://github.com/emberjs/ember.js/pull/18548) [BUGFIX] Fix issues with the new APIs to be used by ember-inspector for building the "component's tree" including `@glimmer/component`. <add>- [#18549](https://github.com/emberjs/ember.js/pull/18549) [BUGFIX] Add component reference to the mouse event handler deprecation warnings. <add> <ide> ### v3.14.1 (October 30, 2019) <ide> <ide> - [#18244](https://github.com/emberjs/ember.js/pull/18244) [BUGFIX] Fix query param assertion when using the router services `transitionTo` to redirect _during_ an existing transition.
1
Text
Text
add third packages nested-multipart-parser
00cd4ef864a8bf6d6c90819a983017070f9f08a5
<ide><path>docs/community/third-party-packages.md <ide> To submit new content, [open an issue][drf-create-issue] or [create a pull reque <ide> * [djangorestframework-msgpack][djangorestframework-msgpack] - Provides MessagePack renderer and parser support. <ide> * [djangorestframework-jsonapi][djangorestframework-jsonapi] - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec. <ide> * [djangorestframework-camel-case][djangorestframework-camel-case] - Provides camel case JSON renderers and parsers. <add>* [nested-multipart-parser][nested-multipart-parser] - Provides nested parser for http multipart request <ide> <ide> ### Renderers <ide> <ide> To submit new content, [open an issue][drf-create-issue] or [create a pull reque <ide> [wq.db.rest]: https://wq.io/docs/about-rest <ide> [djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack <ide> [djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case <add>[nested-multipart-parser]: https://github.com/remigermain/nested-multipart-parser <ide> [djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv <ide> [drf_ujson2]: https://github.com/Amertz08/drf_ujson2 <ide> [rest-pandas]: https://github.com/wq/django-rest-pandas
1
PHP
PHP
fix "typo"
a10bbfbf21466995d0a8c1843447554700791231
<ide><path>src/Illuminate/Routing/Console/ControllerMakeCommand.php <ide> protected function buildClass($name) <ide> $modelClass = $this->parseModel($this->option('model')); <ide> <ide> if (! class_exists($modelClass)) { <del> if ($this->confirm("A {$modelClass} model not exist. Do you want to generate it?", true)) { <add> if ($this->confirm("A {$modelClass} model does not exist. Do you want to generate it?", true)) { <ide> $this->call('make:model', ['name' => $modelClass]); <ide> } <ide> }
1
Ruby
Ruby
remove dead code
d487c3d97827ac9ff976cde5a5d587236a8ffb4c
<ide><path>Library/Contributions/cmd/brew-test-bot.rb <ide> def test cmd, options={} <ide> end <ide> <ide> def check_results <del> message = "All tests passed and raring to brew." <del> <ide> status = :passed <ide> steps.each do |step| <ide> case step.status <ide> when :passed then next <ide> when :running then raise <del> when :failed then <del> if status == :passed <del> status = :failed <del> message = "" <del> end <del> message += "#{step.command}: #{step.status.to_s.upcase}\n" <add> when :failed then status = :failed <ide> end <ide> end <ide> status == :passed
1
Javascript
Javascript
add tests with multiple re-throw stratiegies
200c3b7b5846e22cb230842fc6fe475531f9eaa3
<ide><path>packages/ember/tests/routing/substates_test.js <ide> QUnit.test('Error events that aren\'t bubbled don\t throw application assertions <ide> bootApplication('/grandma/mom/sally'); <ide> }); <ide> <add>QUnit.test('Non-bubbled errors that re-throw aren\'t swallowed', function() { <add> expect(2); <add> <add> templates['grandma'] = 'GRANDMA {{outlet}}'; <add> <add> Router.map(function() { <add> this.route('grandma', function() { <add> this.route('mom', { resetNamespace: true }, function() { <add> this.route('sally'); <add> }); <add> }); <add> }); <add> <add> App.ApplicationController = Ember.Controller.extend(); <add> <add> App.MomSallyRoute = Ember.Route.extend({ <add> model() { <add> step(1, 'MomSallyRoute#model'); <add> <add> return Ember.RSVP.reject({ <add> msg: 'did it broke?' <add> }); <add> }, <add> actions: { <add> error(err) { <add> // returns undefined which is falsey <add> throw err; <add> } <add> } <add> }); <add> <add> throws(function() { <add> bootApplication('/grandma/mom/sally'); <add> }, function(err) { return err.msg === 'did it broke?';}); <add>}); <add> <add>QUnit.test('Handled errors that re-throw aren\'t swallowed', function() { <add> expect(4); <add> <add> var handledError; <add> <add> templates['grandma'] = 'GRANDMA {{outlet}}'; <add> <add> Router.map(function() { <add> this.route('grandma', function() { <add> this.route('mom', { resetNamespace: true }, function() { <add> this.route('sally'); <add> this.route('this-route-throws'); <add> }); <add> }); <add> }); <add> <add> App.ApplicationController = Ember.Controller.extend(); <add> <add> App.MomSallyRoute = Ember.Route.extend({ <add> model() { <add> step(1, 'MomSallyRoute#model'); <add> <add> return Ember.RSVP.reject({ <add> msg: 'did it broke?' <add> }); <add> }, <add> actions: { <add> error(err) { <add> step(2, 'MomSallyRoute#error'); <add> <add> handledError = err; <add> <add> this.transitionTo('mom.this-route-throws'); <add> <add> // Marks error as handled <add> return false; <add> } <add> } <add> }); <add> <add> App.MomThisRouteThrowsRoute = Ember.Route.extend({ <add> model() { <add> step(3, 'MomThisRouteThrows#model'); <add> <add> throw handledError; <add> } <add> }); <add> <add> throws(function() { <add> bootApplication('/grandma/mom/sally'); <add> }, function(err) { return err.msg === 'did it broke?'; }); <add>}); <add> <add>QUnit.test('Handled errors that are thrown through rejection aren\'t swallowed', function() { <add> expect(4); <add> <add> var handledError; <add> <add> templates['grandma'] = 'GRANDMA {{outlet}}'; <add> <add> Router.map(function() { <add> this.route('grandma', function() { <add> this.route('mom', { resetNamespace: true }, function() { <add> this.route('sally'); <add> this.route('this-route-throws'); <add> }); <add> }); <add> }); <add> <add> App.ApplicationController = Ember.Controller.extend(); <add> <add> App.MomSallyRoute = Ember.Route.extend({ <add> model() { <add> step(1, 'MomSallyRoute#model'); <add> <add> return Ember.RSVP.reject({ <add> msg: 'did it broke?' <add> }); <add> }, <add> actions: { <add> error(err) { <add> step(2, 'MomSallyRoute#error'); <add> <add> handledError = err; <add> <add> this.transitionTo('mom.this-route-throws'); <add> <add> // Marks error as handled <add> return false; <add> } <add> } <add> }); <add> <add> App.MomThisRouteThrowsRoute = Ember.Route.extend({ <add> model() { <add> step(3, 'MomThisRouteThrows#model'); <add> <add> return Ember.RSVP.reject(handledError); <add> } <add> }); <add> <add> throws(function() { <add> bootApplication('/grandma/mom/sally'); <add> }, function(err) { return err.msg === 'did it broke?'; }); <add>}); <add> <ide> QUnit.test('Setting a query param during a slow transition should work', function() { <ide> var deferred = RSVP.defer(); <ide>
1
Javascript
Javascript
remove unused variables
13112710e62209861886b96ffc2052fc249f65ff
<ide><path>src/ng/compile.js <ide> function $CompileProvider($provide, $$sanitizeUriProvider) { <ide> // not be able to attach scope data to them, so we will wrap them in <span> <ide> forEach($compileNodes, function(node, index){ <ide> if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) { <del> $compileNodes[index] = node = jqLite(node).wrap('<span></span>').parent()[0]; <add> $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0]; <ide> } <ide> }); <ide> var compositeLinkFn = <ide><path>src/ng/rootScope.js <ide> function $RootScopeProvider(){ <ide> * <ide> */ <ide> $new: function(isolate) { <del> var ChildScope, <del> child; <add> var child; <ide> <ide> if (isolate) { <ide> child = new Scope();
2
PHP
PHP
trim comment bloat from route class
5ea2974bd634bbf7990ff7e94710b12a23d801bb
<ide><path>system/route.php <ide> public function __construct($key, $callback, $parameters = array()) <ide> * <ide> * @param mixed $route <ide> * @param array $parameters <del> * @return mixed <add> * @return Response <ide> */ <ide> public function call() <ide> { <ide> public function call() <ide> { <ide> $response = isset($this->callback['before']) ? Route\Filter::call($this->callback['before'], array(), true) : null; <ide> <del> // Verify that the before filters did not return a response. Before filters can override <del> // the request cycle to make things like authentication more convenient. <ide> if (is_null($response) and isset($this->callback['do'])) <ide> { <ide> $response = call_user_func_array($this->callback['do'], $this->parameters);
1
Javascript
Javascript
fix polygon.centroid for open polygons
85ad3c16b031f2e21969123fbf3749f796623226
<ide><path>d3.geom.js <ide> d3.geom.polygon = function(coordinates) { <ide> <ide> coordinates.centroid = function(k) { <ide> var i = -1, <del> n = coordinates.length - 1, <add> n = coordinates.length, <ide> x = 0, <ide> y = 0, <ide> a, <del> b, <add> b = coordinates[n - 1], <ide> c; <ide> if (!arguments.length) k = -1 / (6 * coordinates.area()); <ide> while (++i < n) { <del> a = coordinates[i]; <del> b = coordinates[i + 1]; <add> a = b; <add> b = coordinates[i]; <ide> c = a[0] * b[1] - b[0] * a[1]; <ide> x += (a[0] + b[0]) * c; <ide> y += (a[1] + b[1]) * c; <ide><path>d3.geom.min.js <del>(function(){function c(a){var b=0,c=0;for(;;){if(a(b,c))return[b,c];b===0?(b=c+1,c=0):(b-=1,c+=1)}}function d(a,b,c,d){var e,f,g,h,i,j,k;return e=d[a],f=e[0],g=e[1],e=d[b],h=e[0],i=e[1],e=d[c],j=e[0],k=e[1],(k-g)*(h-f)-(i-g)*(j-f)>0}function e(a,b,c){return(c[0]-b[0])*(a[1]-b[1])<(c[1]-b[1])*(a[0]-b[0])}function f(a,b,c,d){var e=a[0],f=b[0],g=c[0],h=d[0],i=a[1],j=b[1],k=c[1],l=d[1],m=e-g,n=f-e,o=h-g,p=i-k,q=j-i,r=l-k,s=(o*p-r*m)/(r*n-o*q);return[e+s*n,i+s*q]}function h(a,b){var c={list:a.map(function(a,b){return{index:b,x:a[0],y:a[1]}}).sort(function(a,b){return a.y<b.y?-1:a.y>b.y?1:a.x<b.x?-1:a.x>b.x?1:0}),bottomSite:null},d={list:[],leftEnd:null,rightEnd:null,init:function(){d.leftEnd=d.createHalfEdge(null,"l"),d.rightEnd=d.createHalfEdge(null,"l"),d.leftEnd.r=d.rightEnd,d.rightEnd.l=d.leftEnd,d.list.unshift(d.leftEnd,d.rightEnd)},createHalfEdge:function(a,b){return{edge:a,side:b,vertex:null,l:null,r:null}},insert:function(a,b){b.l=a,b.r=a.r,a.r.l=b,a.r=b},leftBound:function(a){var b=d.leftEnd;do b=b.r;while(b!=d.rightEnd&&e.rightOf(b,a));return b=b.l,b},del:function(a){a.l.r=a.r,a.r.l=a.l,a.edge=null},right:function(a){return a.r},left:function(a){return a.l},leftRegion:function(a){return a.edge==null?c.bottomSite:a.edge.region[a.side]},rightRegion:function(a){return a.edge==null?c.bottomSite:a.edge.region[g[a.side]]}},e={bisect:function(a,b){var c={region:{l:a,r:b},ep:{l:null,r:null}},d=b.x-a.x,e=b.y-a.y,f=d>0?d:-d,g=e>0?e:-e;return c.c=a.x*d+a.y*e+(d*d+e*e)*.5,f>g?(c.a=1,c.b=e/d,c.c/=d):(c.b=1,c.a=d/e,c.c/=e),c},intersect:function(a,b){var c=a.edge,d=b.edge;if(!c||!d||c.region.r==d.region.r)return null;var e=c.a*d.b-c.b*d.a;if(Math.abs(e)<1e-10)return null;var f=(c.c*d.b-d.c*c.b)/e,g=(d.c*c.a-c.c*d.a)/e,h=c.region.r,i=d.region.r,j,k;h.y<i.y||h.y==i.y&&h.x<i.x?(j=a,k=c):(j=b,k=d);var l=f>=k.region.r.x;return l&&j.side==="l"||!l&&j.side==="r"?null:{x:f,y:g}},rightOf:function(a,b){var c=a.edge,d=c.region.r,e=b.x>d.x;if(e&&a.side==="l")return 1;if(!e&&a.side==="r")return 0;if(c.a===1){var f=b.y-d.y,g=b.x-d.x,h=0,i=0;!e&&c.b<0||e&&c.b>=0?i=h=f>=c.b*g:(i=b.x+b.y*c.b>c.c,c.b<0&&(i=!i),i||(h=1));if(!h){var j=d.x-c.region.l.x;i=c.b*(g*g-f*f)<j*f*(1+2*g/j+c.b*c.b),c.b<0&&(i=!i)}}else{var k=c.c-c.a*b.x,l=b.y-k,m=b.x-d.x,n=k-d.y;i=l*l>m*m+n*n}return a.side==="l"?i:!i},endPoint:function(a,c,d){a.ep[c]=d;if(!a.ep[g[c]])return;b(a)},distance:function(a,b){var c=a.x-b.x,d=a.y-b.y;return Math.sqrt(c*c+d*d)}},f={list:[],insert:function(a,b,c){a.vertex=b,a.ystar=b.y+c;for(var d=0,e=f.list,g=e.length;d<g;d++){var h=e[d];if(a.ystar>h.ystar||a.ystar==h.ystar&&b.x>h.vertex.x)continue;break}e.splice(d,0,a)},del:function(a){for(var b=0,c=f.list,d=c.length;b<d&&c[b]!=a;++b);c.splice(b,1)},empty:function(){return f.list.length===0},nextEvent:function(a){for(var b=0,c=f.list,d=c.length;b<d;++b)if(c[b]==a)return c[b+1];return null},min:function(){var a=f.list[0];return{x:a.vertex.x,y:a.ystar}},extractMin:function(){return f.list.shift()}};d.init(),c.bottomSite=c.list.shift();var h=c.list.shift(),i,j,k,l,m,n,o,p,q,r,s,t,u;for(;;){f.empty()||(i=f.min());if(h&&(f.empty()||h.y<i.y||h.y==i.y&&h.x<i.x))j=d.leftBound(h),k=d.right(j),o=d.rightRegion(j),t=e.bisect(o,h),n=d.createHalfEdge(t,"l"),d.insert(j,n),r=e.intersect(j,n),r&&(f.del(j),f.insert(j,r,e.distance(r,h))),j=n,n=d.createHalfEdge(t,"r"),d.insert(j,n),r=e.intersect(n,k),r&&f.insert(n,r,e.distance(r,h)),h=c.list.shift();else if(!f.empty())j=f.extractMin(),l=d.left(j),k=d.right(j),m=d.right(k),o=d.leftRegion(j),p=d.rightRegion(k),s=j.vertex,e.endPoint(j.edge,j.side,s),e.endPoint(k.edge,k.side,s),d.del(j),f.del(k),d.del(k),u="l",o.y>p.y&&(q=o,o=p,p=q,u="r"),t=e.bisect(o,p),n=d.createHalfEdge(t,u),d.insert(l,n),e.endPoint(t,g[u],s),r=e.intersect(l,n),r&&(f.del(l),f.insert(l,r,e.distance(r,o))),r=e.intersect(n,m),r&&f.insert(n,r,e.distance(r,o));else break}for(j=d.right(d.leftEnd);j!=d.rightEnd;j=d.right(j))b(j.edge)}function i(){return{leaf:!0,nodes:[],point:null}}function j(a,b,c,d,e,f){if(!a(b,c,d,e,f)){var g=(c+e)*.5,h=(d+f)*.5,i=b.nodes;i[0]&&j(a,i[0],c,d,g,h),i[1]&&j(a,i[1],g,d,e,h),i[2]&&j(a,i[2],c,h,g,f),i[3]&&j(a,i[3],g,h,e,f)}}function k(a){return{x:a[0],y:a[1]}}d3.geom={},d3.geom.contour=function(d,e){var f=e||c(d),g=[],h=f[0],i=f[1],j=0,k=0,l=NaN,m=NaN,n=0;do n=0,d(h-1,i-1)&&(n+=1),d(h,i-1)&&(n+=2),d(h-1,i)&&(n+=4),d(h,i)&&(n+=8),n===6?(j=m===-1?-1:1,k=0):n===9?(j=0,k=l===1?-1:1):(j=a[n],k=b[n]),j!=l&&k!=m&&(g.push([h,i]),l=j,m=k),h+=j,i+=k;while(f[0]!=h||f[1]!=i);return g};var a=[1,0,1,1,-1,0,-1,1,0,0,0,0,-1,0,-1,NaN],b=[0,-1,0,0,0,-1,0,0,1,-1,1,1,0,-1,0,NaN];d3.geom.hull=function(a){if(a.length<3)return[];var b=a.length,c=b-1,e=[],f=[],g,h,i=0,j,k,l,m,n,o,p,q;for(g=1;g<b;++g)a[g][1]<a[i][1]?i=g:a[g][1]==a[i][1]&&(i=a[g][0]<a[i][0]?g:i);for(g=0;g<b;++g){if(g===i)continue;k=a[g][1]-a[i][1],j=a[g][0]-a[i][0],e.push({angle:Math.atan2(k,j),index:g})}e.sort(function(a,b){return a.angle-b.angle}),p=e[0].angle,o=e[0].index,n=0;for(g=1;g<c;++g)h=e[g].index,p==e[g].angle?(j=a[o][0]-a[i][0],k=a[o][1]-a[i][1],l=a[h][0]-a[i][0],m=a[h][1]-a[i][1],j*j+k*k>=l*l+m*m?e[g].index=-1:(e[n].index=-1,p=e[g].angle,n=g,o=h)):(p=e[g].angle,n=g,o=h);f.push(i);for(g=0,h=0;g<2;++h)e[h].index!==-1&&(f.push(e[h].index),g++);q=f.length;for(;h<c;++h){if(e[h].index===-1)continue;while(!d(f[q-2],f[q-1],e[h].index,a))--q;f[q++]=e[h].index}var r=[];for(g=0;g<q;++g)r.push(a[f[g]]);return r},d3.geom.polygon=function(a){return a.area=function(){var b=0,c=a.length,d=a[c-1][0]*a[0][1],e=a[c-1][1]*a[0][0];while(++b<c)d+=a[b-1][0]*a[b][1],e+=a[b-1][1]*a[b][0];return(e-d)*.5},a.centroid=function(b){var c=-1,d=a.length-1,e=0,f=0,g,h,i;arguments.length||(b=-1/(6*a.area()));while(++c<d)g=a[c],h=a[c+1],i=g[0]*h[1]-h[0]*g[1],e+=(g[0]+h[0])*i,f+=(g[1]+h[1])*i;return[e*b,f*b]},a.clip=function(b){var c,d=-1,g=a.length,h,i,j=a[g-1],k,l,m;while(++d<g){c=b.slice(),b.length=0,k=a[d],l=c[(i=c.length)-1],h=-1;while(++h<i)m=c[h],e(m,j,k)?(e(l,j,k)||b.push(f(l,m,j,k)),b.push(m)):e(l,j,k)&&b.push(f(l,m,j,k)),l=m;j=k}return b},a},d3.geom.voronoi=function(a){var b=a.map(function(){return[]});return h(a,function(a){var c,d,e,f,g,h;a.a===1&&a.b>=0?(c=a.ep.r,d=a.ep.l):(c=a.ep.l,d=a.ep.r),a.a===1?(g=c?c.y:-1e6,e=a.c-a.b*g,h=d?d.y:1e6,f=a.c-a.b*h):(e=c?c.x:-1e6,g=a.c-a.a*e,f=d?d.x:1e6,h=a.c-a.a*f);var i=[e,g],j=[f,h];b[a.region.l.index].push(i,j),b[a.region.r.index].push(i,j)}),b.map(function(b,c){var d=a[c][0],e=a[c][1];return b.forEach(function(a){a.angle=Math.atan2(a[0]-d,a[1]-e)}),b.sort(function(a,b){return a.angle-b.angle}).filter(function(a,c){return!c||a.angle-b[c-1].angle>1e-10})})};var g={l:"r",r:"l"};d3.geom.delaunay=function(a){var b=a.map(function(){return[]}),c=[];return h(a,function(c){b[c.region.l.index].push(a[c.region.r.index])}),b.forEach(function(b,d){var e=a[d],f=e[0],g=e[1];b.forEach(function(a){a.angle=Math.atan2(a[0]-f,a[1]-g)}),b.sort(function(a,b){return a.angle-b.angle});for(var h=0,i=b.length-1;h<i;h++)c.push([e,b[h],b[h+1]])}),c},d3.geom.quadtree=function(a,b,c,d,e){function n(a,b,c,d,e,f){if(isNaN(b.x)||isNaN(b.y))return;if(a.leaf){var g=a.point;g?Math.abs(g.x-b.x)+Math.abs(g.y-b.y)<.01?o(a,b,c,d,e,f):(a.point=null,o(a,g,c,d,e,f),o(a,b,c,d,e,f)):a.point=b}else o(a,b,c,d,e,f)}function o(a,b,c,d,e,f){var g=(c+e)*.5,h=(d+f)*.5,j=b.x>=g,k=b.y>=h,l=(k<<1)+j;a.leaf=!1,a=a.nodes[l]||(a.nodes[l]=i()),j?c=g:e=g,k?d=h:f=h,n(a,b,c,d,e,f)}var f,g=-1,h=a.length;h&&isNaN(a[0].x)&&(a=a.map(k));if(arguments.length<5)if(arguments.length===3)e=d=c,c=b;else{b=c=Infinity,d=e=-Infinity;while(++g<h)f=a[g],f.x<b&&(b=f.x),f.y<c&&(c=f.y),f.x>d&&(d=f.x),f.y>e&&(e=f.y);var l=d-b,m=e-c;l>m?e=c+l:d=b+m}var p=i();return p.add=function(a){n(p,a,b,c,d,e)},p.visit=function(a){j(a,p,b,c,d,e)},a.forEach(p.add),p}})(); <ide>\ No newline at end of file <add>(function(){function c(a){var b=0,c=0;for(;;){if(a(b,c))return[b,c];b===0?(b=c+1,c=0):(b-=1,c+=1)}}function d(a,b,c,d){var e,f,g,h,i,j,k;return e=d[a],f=e[0],g=e[1],e=d[b],h=e[0],i=e[1],e=d[c],j=e[0],k=e[1],(k-g)*(h-f)-(i-g)*(j-f)>0}function e(a,b,c){return(c[0]-b[0])*(a[1]-b[1])<(c[1]-b[1])*(a[0]-b[0])}function f(a,b,c,d){var e=a[0],f=b[0],g=c[0],h=d[0],i=a[1],j=b[1],k=c[1],l=d[1],m=e-g,n=f-e,o=h-g,p=i-k,q=j-i,r=l-k,s=(o*p-r*m)/(r*n-o*q);return[e+s*n,i+s*q]}function h(a,b){var c={list:a.map(function(a,b){return{index:b,x:a[0],y:a[1]}}).sort(function(a,b){return a.y<b.y?-1:a.y>b.y?1:a.x<b.x?-1:a.x>b.x?1:0}),bottomSite:null},d={list:[],leftEnd:null,rightEnd:null,init:function(){d.leftEnd=d.createHalfEdge(null,"l"),d.rightEnd=d.createHalfEdge(null,"l"),d.leftEnd.r=d.rightEnd,d.rightEnd.l=d.leftEnd,d.list.unshift(d.leftEnd,d.rightEnd)},createHalfEdge:function(a,b){return{edge:a,side:b,vertex:null,l:null,r:null}},insert:function(a,b){b.l=a,b.r=a.r,a.r.l=b,a.r=b},leftBound:function(a){var b=d.leftEnd;do b=b.r;while(b!=d.rightEnd&&e.rightOf(b,a));return b=b.l,b},del:function(a){a.l.r=a.r,a.r.l=a.l,a.edge=null},right:function(a){return a.r},left:function(a){return a.l},leftRegion:function(a){return a.edge==null?c.bottomSite:a.edge.region[a.side]},rightRegion:function(a){return a.edge==null?c.bottomSite:a.edge.region[g[a.side]]}},e={bisect:function(a,b){var c={region:{l:a,r:b},ep:{l:null,r:null}},d=b.x-a.x,e=b.y-a.y,f=d>0?d:-d,g=e>0?e:-e;return c.c=a.x*d+a.y*e+(d*d+e*e)*.5,f>g?(c.a=1,c.b=e/d,c.c/=d):(c.b=1,c.a=d/e,c.c/=e),c},intersect:function(a,b){var c=a.edge,d=b.edge;if(!c||!d||c.region.r==d.region.r)return null;var e=c.a*d.b-c.b*d.a;if(Math.abs(e)<1e-10)return null;var f=(c.c*d.b-d.c*c.b)/e,g=(d.c*c.a-c.c*d.a)/e,h=c.region.r,i=d.region.r,j,k;h.y<i.y||h.y==i.y&&h.x<i.x?(j=a,k=c):(j=b,k=d);var l=f>=k.region.r.x;return l&&j.side==="l"||!l&&j.side==="r"?null:{x:f,y:g}},rightOf:function(a,b){var c=a.edge,d=c.region.r,e=b.x>d.x;if(e&&a.side==="l")return 1;if(!e&&a.side==="r")return 0;if(c.a===1){var f=b.y-d.y,g=b.x-d.x,h=0,i=0;!e&&c.b<0||e&&c.b>=0?i=h=f>=c.b*g:(i=b.x+b.y*c.b>c.c,c.b<0&&(i=!i),i||(h=1));if(!h){var j=d.x-c.region.l.x;i=c.b*(g*g-f*f)<j*f*(1+2*g/j+c.b*c.b),c.b<0&&(i=!i)}}else{var k=c.c-c.a*b.x,l=b.y-k,m=b.x-d.x,n=k-d.y;i=l*l>m*m+n*n}return a.side==="l"?i:!i},endPoint:function(a,c,d){a.ep[c]=d;if(!a.ep[g[c]])return;b(a)},distance:function(a,b){var c=a.x-b.x,d=a.y-b.y;return Math.sqrt(c*c+d*d)}},f={list:[],insert:function(a,b,c){a.vertex=b,a.ystar=b.y+c;for(var d=0,e=f.list,g=e.length;d<g;d++){var h=e[d];if(a.ystar>h.ystar||a.ystar==h.ystar&&b.x>h.vertex.x)continue;break}e.splice(d,0,a)},del:function(a){for(var b=0,c=f.list,d=c.length;b<d&&c[b]!=a;++b);c.splice(b,1)},empty:function(){return f.list.length===0},nextEvent:function(a){for(var b=0,c=f.list,d=c.length;b<d;++b)if(c[b]==a)return c[b+1];return null},min:function(){var a=f.list[0];return{x:a.vertex.x,y:a.ystar}},extractMin:function(){return f.list.shift()}};d.init(),c.bottomSite=c.list.shift();var h=c.list.shift(),i,j,k,l,m,n,o,p,q,r,s,t,u;for(;;){f.empty()||(i=f.min());if(h&&(f.empty()||h.y<i.y||h.y==i.y&&h.x<i.x))j=d.leftBound(h),k=d.right(j),o=d.rightRegion(j),t=e.bisect(o,h),n=d.createHalfEdge(t,"l"),d.insert(j,n),r=e.intersect(j,n),r&&(f.del(j),f.insert(j,r,e.distance(r,h))),j=n,n=d.createHalfEdge(t,"r"),d.insert(j,n),r=e.intersect(n,k),r&&f.insert(n,r,e.distance(r,h)),h=c.list.shift();else if(!f.empty())j=f.extractMin(),l=d.left(j),k=d.right(j),m=d.right(k),o=d.leftRegion(j),p=d.rightRegion(k),s=j.vertex,e.endPoint(j.edge,j.side,s),e.endPoint(k.edge,k.side,s),d.del(j),f.del(k),d.del(k),u="l",o.y>p.y&&(q=o,o=p,p=q,u="r"),t=e.bisect(o,p),n=d.createHalfEdge(t,u),d.insert(l,n),e.endPoint(t,g[u],s),r=e.intersect(l,n),r&&(f.del(l),f.insert(l,r,e.distance(r,o))),r=e.intersect(n,m),r&&f.insert(n,r,e.distance(r,o));else break}for(j=d.right(d.leftEnd);j!=d.rightEnd;j=d.right(j))b(j.edge)}function i(){return{leaf:!0,nodes:[],point:null}}function j(a,b,c,d,e,f){if(!a(b,c,d,e,f)){var g=(c+e)*.5,h=(d+f)*.5,i=b.nodes;i[0]&&j(a,i[0],c,d,g,h),i[1]&&j(a,i[1],g,d,e,h),i[2]&&j(a,i[2],c,h,g,f),i[3]&&j(a,i[3],g,h,e,f)}}function k(a){return{x:a[0],y:a[1]}}d3.geom={},d3.geom.contour=function(d,e){var f=e||c(d),g=[],h=f[0],i=f[1],j=0,k=0,l=NaN,m=NaN,n=0;do n=0,d(h-1,i-1)&&(n+=1),d(h,i-1)&&(n+=2),d(h-1,i)&&(n+=4),d(h,i)&&(n+=8),n===6?(j=m===-1?-1:1,k=0):n===9?(j=0,k=l===1?-1:1):(j=a[n],k=b[n]),j!=l&&k!=m&&(g.push([h,i]),l=j,m=k),h+=j,i+=k;while(f[0]!=h||f[1]!=i);return g};var a=[1,0,1,1,-1,0,-1,1,0,0,0,0,-1,0,-1,NaN],b=[0,-1,0,0,0,-1,0,0,1,-1,1,1,0,-1,0,NaN];d3.geom.hull=function(a){if(a.length<3)return[];var b=a.length,c=b-1,e=[],f=[],g,h,i=0,j,k,l,m,n,o,p,q;for(g=1;g<b;++g)a[g][1]<a[i][1]?i=g:a[g][1]==a[i][1]&&(i=a[g][0]<a[i][0]?g:i);for(g=0;g<b;++g){if(g===i)continue;k=a[g][1]-a[i][1],j=a[g][0]-a[i][0],e.push({angle:Math.atan2(k,j),index:g})}e.sort(function(a,b){return a.angle-b.angle}),p=e[0].angle,o=e[0].index,n=0;for(g=1;g<c;++g)h=e[g].index,p==e[g].angle?(j=a[o][0]-a[i][0],k=a[o][1]-a[i][1],l=a[h][0]-a[i][0],m=a[h][1]-a[i][1],j*j+k*k>=l*l+m*m?e[g].index=-1:(e[n].index=-1,p=e[g].angle,n=g,o=h)):(p=e[g].angle,n=g,o=h);f.push(i);for(g=0,h=0;g<2;++h)e[h].index!==-1&&(f.push(e[h].index),g++);q=f.length;for(;h<c;++h){if(e[h].index===-1)continue;while(!d(f[q-2],f[q-1],e[h].index,a))--q;f[q++]=e[h].index}var r=[];for(g=0;g<q;++g)r.push(a[f[g]]);return r},d3.geom.polygon=function(a){return a.area=function(){var b=0,c=a.length,d=a[c-1][0]*a[0][1],e=a[c-1][1]*a[0][0];while(++b<c)d+=a[b-1][0]*a[b][1],e+=a[b-1][1]*a[b][0];return(e-d)*.5},a.centroid=function(b){var c=-1,d=a.length,e=0,f=0,g,h=a[d-1],i;arguments.length||(b=-1/(6*a.area()));while(++c<d)g=h,h=a[c],i=g[0]*h[1]-h[0]*g[1],e+=(g[0]+h[0])*i,f+=(g[1]+h[1])*i;return[e*b,f*b]},a.clip=function(b){var c,d=-1,g=a.length,h,i,j=a[g-1],k,l,m;while(++d<g){c=b.slice(),b.length=0,k=a[d],l=c[(i=c.length)-1],h=-1;while(++h<i)m=c[h],e(m,j,k)?(e(l,j,k)||b.push(f(l,m,j,k)),b.push(m)):e(l,j,k)&&b.push(f(l,m,j,k)),l=m;j=k}return b},a},d3.geom.voronoi=function(a){var b=a.map(function(){return[]});return h(a,function(a){var c,d,e,f,g,h;a.a===1&&a.b>=0?(c=a.ep.r,d=a.ep.l):(c=a.ep.l,d=a.ep.r),a.a===1?(g=c?c.y:-1e6,e=a.c-a.b*g,h=d?d.y:1e6,f=a.c-a.b*h):(e=c?c.x:-1e6,g=a.c-a.a*e,f=d?d.x:1e6,h=a.c-a.a*f);var i=[e,g],j=[f,h];b[a.region.l.index].push(i,j),b[a.region.r.index].push(i,j)}),b.map(function(b,c){var d=a[c][0],e=a[c][1];return b.forEach(function(a){a.angle=Math.atan2(a[0]-d,a[1]-e)}),b.sort(function(a,b){return a.angle-b.angle}).filter(function(a,c){return!c||a.angle-b[c-1].angle>1e-10})})};var g={l:"r",r:"l"};d3.geom.delaunay=function(a){var b=a.map(function(){return[]}),c=[];return h(a,function(c){b[c.region.l.index].push(a[c.region.r.index])}),b.forEach(function(b,d){var e=a[d],f=e[0],g=e[1];b.forEach(function(a){a.angle=Math.atan2(a[0]-f,a[1]-g)}),b.sort(function(a,b){return a.angle-b.angle});for(var h=0,i=b.length-1;h<i;h++)c.push([e,b[h],b[h+1]])}),c},d3.geom.quadtree=function(a,b,c,d,e){function n(a,b,c,d,e,f){if(isNaN(b.x)||isNaN(b.y))return;if(a.leaf){var g=a.point;g?Math.abs(g.x-b.x)+Math.abs(g.y-b.y)<.01?o(a,b,c,d,e,f):(a.point=null,o(a,g,c,d,e,f),o(a,b,c,d,e,f)):a.point=b}else o(a,b,c,d,e,f)}function o(a,b,c,d,e,f){var g=(c+e)*.5,h=(d+f)*.5,j=b.x>=g,k=b.y>=h,l=(k<<1)+j;a.leaf=!1,a=a.nodes[l]||(a.nodes[l]=i()),j?c=g:e=g,k?d=h:f=h,n(a,b,c,d,e,f)}var f,g=-1,h=a.length;h&&isNaN(a[0].x)&&(a=a.map(k));if(arguments.length<5)if(arguments.length===3)e=d=c,c=b;else{b=c=Infinity,d=e=-Infinity;while(++g<h)f=a[g],f.x<b&&(b=f.x),f.y<c&&(c=f.y),f.x>d&&(d=f.x),f.y>e&&(e=f.y);var l=d-b,m=e-c;l>m?e=c+l:d=b+m}var p=i();return p.add=function(a){n(p,a,b,c,d,e)},p.visit=function(a){j(a,p,b,c,d,e)},a.forEach(p.add),p}})(); <ide>\ No newline at end of file <ide><path>src/geom/polygon.js <ide> d3.geom.polygon = function(coordinates) { <ide> <ide> coordinates.centroid = function(k) { <ide> var i = -1, <del> n = coordinates.length - 1, <add> n = coordinates.length, <ide> x = 0, <ide> y = 0, <ide> a, <del> b, <add> b = coordinates[n - 1], <ide> c; <ide> if (!arguments.length) k = -1 / (6 * coordinates.area()); <ide> while (++i < n) { <del> a = coordinates[i]; <del> b = coordinates[i + 1]; <add> a = b; <add> b = coordinates[i]; <ide> c = a[0] * b[1] - b[0] * a[1]; <ide> x += (a[0] + b[0]) * c; <ide> y += (a[1] + b[1]) * c; <ide><path>test/geom/polygon-test.js <ide> var vows = require("vows"), <ide> var suite = vows.describe("d3.geom.polygon"); <ide> <ide> suite.addBatch({ <del> "counterclockwise polygon (last point equal to start point)": { <add> "closed counterclockwise unit square": { <ide> topic: function() { <ide> return d3.geom.polygon([[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]]); <ide> }, <del> "area": function(polygon) { <add> "has area 1": function(polygon) { <ide> assert.equal(polygon.area(), 1); <ide> }, <del> "centroid": function(polygon) { <add> "has centroid ⟨.5,.5⟩": function(polygon) { <ide> assert.deepEqual(polygon.centroid(), [.5, .5]); <ide> } <ide> }, <del> "counterclockwise polygon (implicitly ending at start point)": { <add> "closed clockwise unit square": { <ide> topic: function() { <del> return d3.geom.polygon([[0, 0], [0, 1], [1, 1], [1, 0]]); <add> return d3.geom.polygon([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]); <ide> }, <del> "area": function(polygon) { <del> assert.equal(polygon.area(), 1); <add> "has area 1": function(polygon) { <add> assert.equal(polygon.area(), -1); <ide> }, <del> "centroid": function(polygon) { <add> "has centroid ⟨.5,.5⟩": function(polygon) { <ide> assert.deepEqual(polygon.centroid(), [.5, .5]); <ide> } <ide> }, <del> "clockwise polygon (last point equal to start point)": { <add> "closed clockwise triangle": { <ide> topic: function() { <del> return d3.geom.polygon([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]); <add> return d3.geom.polygon([[1, 1], [3, 2], [2, 3], [1, 1]]); <ide> }, <del> "area": function(polygon) { <del> assert.equal(polygon.area(), -1); <add> "has area 1.5": function(polygon) { <add> assert.equal(polygon.area(), -1.5); <add> }, <add> "has centroid ⟨2,2⟩": function(polygon) { <add> var centroid = polygon.centroid(); <add> assert.inDelta(centroid[0], 2, 1e-6); <add> assert.inDelta(centroid[1], 2, 1e-6); <add> } <add> }, <add> "open counterclockwise unit square": { <add> topic: function() { <add> return d3.geom.polygon([[0, 0], [0, 1], [1, 1], [1, 0]]); <ide> }, <del> "centroid": function(polygon) { <add> "has area 1": function(polygon) { <add> assert.equal(polygon.area(), 1); <add> }, <add> "has centroid ⟨.5,.5⟩": function(polygon) { <ide> assert.deepEqual(polygon.centroid(), [.5, .5]); <ide> } <ide> }, <del> "clockwise polygon (implicitly ending at start point)": { <add> "open clockwise unit square": { <ide> topic: function() { <ide> return d3.geom.polygon([[0, 0], [1, 0], [1, 1], [0, 1]]); <ide> }, <del> "area": function(polygon) { <add> "has area 1": function(polygon) { <ide> assert.equal(polygon.area(), -1); <ide> }, <del> "centroid": function(polygon) { <add> "has centroid ⟨.5,.5⟩": function(polygon) { <ide> assert.deepEqual(polygon.centroid(), [.5, .5]); <ide> } <add> }, <add> "open clockwise triangle": { <add> topic: function() { <add> return d3.geom.polygon([[1, 1], [3, 2], [2, 3]]); <add> }, <add> "has area 1.5": function(polygon) { <add> assert.equal(polygon.area(), -1.5); <add> }, <add> "has centroid ⟨2,2⟩": function(polygon) { <add> var centroid = polygon.centroid(); <add> assert.inDelta(centroid[0], 2, 1e-6); <add> assert.inDelta(centroid[1], 2, 1e-6); <add> } <ide> } <ide> }); <ide>
4
Text
Text
add 2.12.1 to changelog.md
3ce075b880e130508e4d7e253ae2930a0d80016c
<ide><path>CHANGELOG.md <ide> - [#14919](https://github.com/emberjs/ember.js/pull/14919) [DEPRECATION] Deprecate the private `Ember.Router.router` property in favor of `Ember.Router._routerMicrolib`. <ide> - [#14970](https://github.com/emberjs/ember.js/pull/14970) [BUGFIX] Generate integration tests for template helpers by default. <ide> - [#14976](https://github.com/emberjs/ember.js/pull/14976) [BUGFIX] Remove "no use strict" workaround for old versions of iOS 8. <del>- [#14981](https://github.com/emberjs/ember.js/pull/14981) [FEATURE ember-testing-resume-test] Enable by default. <add> <add>### 2.12.1 (April 7, 2017) <add> <add>- [#14961](https://github.com/emberjs/ember.js/pull/14961) [BUGIX] Remove duplicate trailing `/` in pathname. <add>- [#15029](https://github.com/emberjs/ember.js/pull/15029) [PERF] [BUGFIX] cache `factoryFor` injections when possible <add>- [#15089](https://github.com/emberjs/ember.js/pull/15089) [BUGFIX] Fixing IE and Edge issue causing action handlers to be fired twice. <ide> <ide> ### 2.12.0 (March 14, 2017) <ide>
1
Javascript
Javascript
add default operator to `assert.fail()`
eee5adfab5af5f7eb672cbc3cbbad141c455c54d
<ide><path>lib/assert.js <ide> function innerFail(obj) { <ide> function fail(actual, expected, message, operator, stackStartFn) { <ide> const argsLen = arguments.length; <ide> <add> let internalMessage; <ide> if (argsLen === 0) { <del> message = 'Failed'; <add> internalMessage = 'Failed'; <ide> } else if (argsLen === 1) { <ide> message = actual; <ide> actual = undefined; <ide> function fail(actual, expected, message, operator, stackStartFn) { <ide> operator = '!='; <ide> } <ide> <del> innerFail({ <add> if (message instanceof Error) throw message; <add> <add> const errArgs = { <ide> actual, <ide> expected, <del> message, <del> operator, <add> operator: operator === undefined ? 'fail' : operator, <ide> stackStartFn: stackStartFn || fail <del> }); <add> }; <add> if (message !== undefined) { <add> errArgs.message = message; <add> } <add> const err = new AssertionError(errArgs); <add> if (internalMessage) { <add> err.message = internalMessage; <add> err.generatedMessage = true; <add> } <add> throw err; <ide> } <ide> <ide> assert.fail = fail; <ide><path>test/parallel/test-assert-fail-deprecation.js <ide> assert.throws(() => { <ide> message: '\'first\' != \'second\'', <ide> operator: '!=', <ide> actual: 'first', <del> expected: 'second' <add> expected: 'second', <add> generatedMessage: true <ide> }); <ide> <ide> // Three args <ide> assert.throws(() => { <ide> code: 'ERR_ASSERTION', <ide> name: 'AssertionError [ERR_ASSERTION]', <ide> message: 'another custom message', <del> operator: undefined, <add> operator: 'fail', <ide> actual: 'ignored', <del> expected: 'ignored' <add> expected: 'ignored', <add> generatedMessage: false <ide> }); <ide> <ide> // Three args with custom Error <ide><path>test/parallel/test-assert-fail.js <ide> assert.throws( <ide> code: 'ERR_ASSERTION', <ide> name: 'AssertionError [ERR_ASSERTION]', <ide> message: 'Failed', <del> operator: undefined, <add> operator: 'fail', <ide> actual: undefined, <del> expected: undefined <add> expected: undefined, <add> generatedMessage: true <ide> } <ide> ); <ide> <ide> assert.throws(() => { <ide> code: 'ERR_ASSERTION', <ide> name: 'AssertionError [ERR_ASSERTION]', <ide> message: 'custom message', <del> operator: undefined, <add> operator: 'fail', <ide> actual: undefined, <del> expected: undefined <add> expected: undefined, <add> generatedMessage: false <ide> }); <ide> <ide> // One arg = Error
3
Go
Go
remove dead code
1d2b62ceae17238f842bb2a7febf1bead8a982d5
<ide><path>pkg/plugins/discovery.go <ide> var ( <ide> specsPaths = []string{"/etc/docker/plugins", "/usr/lib/docker/plugins"} <ide> ) <ide> <del>// Registry defines behavior of a registry of plugins. <del>type Registry interface { <del> // Plugins lists all plugins. <del> Plugins() ([]*Plugin, error) <del> // Plugin returns the plugin registered with the given name (or returns an error). <del> Plugin(name string) (*Plugin, error) <del>} <del> <del>// LocalRegistry defines a registry that is local (using unix socket). <del>type LocalRegistry struct{} <add>// localRegistry defines a registry that is local (using unix socket). <add>type localRegistry struct{} <ide> <del>func newLocalRegistry() LocalRegistry { <del> return LocalRegistry{} <add>func newLocalRegistry() localRegistry { <add> return localRegistry{} <ide> } <ide> <ide> // Plugin returns the plugin registered with the given name (or returns an error). <del>func (l *LocalRegistry) Plugin(name string) (*Plugin, error) { <add>func (l *localRegistry) Plugin(name string) (*Plugin, error) { <ide> socketpaths := pluginPaths(socketsPath, name, ".sock") <ide> <ide> for _, p := range socketpaths {
1
Javascript
Javascript
add color import
e4702c1b0f2bcab36ffcd3585ba3e77bbe3fce83
<ide><path>src/renderers/WebGLRenderer.js <ide> import { WebGLUniforms } from './webgl/WebGLUniforms.js'; <ide> import { WebGLUtils } from './webgl/WebGLUtils.js'; <ide> import { WebXRManager } from './webxr/WebXRManager.js'; <ide> import { WebGLMaterials } from "./webgl/WebGLMaterials.js"; <add>import { Color } from '../math/Color.js'; <ide> <ide> function createCanvasElement() { <ide>
1
Java
Java
fix resetting margins and borders on android
9e670a64fcb0062f20e89a9b0bca07f99ec23548
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/LayoutShadowNode.java <ide> public void setJustifyContent(@Nullable String justifyContent) { <ide> ViewProps.MARGIN_RIGHT, <ide> ViewProps.MARGIN_TOP, <ide> ViewProps.MARGIN_BOTTOM, <del> }, defaultFloat = 0f) <add> }, defaultFloat = CSSConstants.UNDEFINED) <ide> public void setMargins(int index, float margin) { <ide> setMargin(ViewProps.PADDING_MARGIN_SPACING_TYPES[index], PixelUtil.toPixelFromDIP(margin)); <ide> } <ide> public void setPaddings(int index, float padding) { <ide> ViewProps.BORDER_RIGHT_WIDTH, <ide> ViewProps.BORDER_TOP_WIDTH, <ide> ViewProps.BORDER_BOTTOM_WIDTH, <del> }, defaultFloat = 0f) <add> }, defaultFloat = CSSConstants.UNDEFINED) <ide> public void setBorderWidths(int index, float borderWidth) { <ide> setBorder(ViewProps.BORDER_SPACING_TYPES[index], PixelUtil.toPixelFromDIP(borderWidth)); <ide> }
1
Text
Text
add pkuseg warnings and auto-format [ci skip]
44af53bdd93713b24ac28459c5d2543f03c47a18
<ide><path>website/docs/usage/models.md <ide> The Chinese language class supports three word segmentation options: <ide> better segmentation for Chinese OntoNotes and the new <ide> [Chinese models](/models/zh). <ide> <add><Infobox variant="warning"> <add> <add>Note that [`pkuseg`](https://github.com/lancopku/pkuseg-python) doesn't yet ship <add>with pre-compiled wheels for Python 3.8. If you're running Python 3.8, you can <add>install it from our fork and compile it locally: <add> <add>```bash <add>$ pip install https://github.com/honnibal/pkuseg-python/archive/master.zip <add>``` <add> <add></Infobox> <add> <ide> <Accordion title="Details on spaCy's PKUSeg API"> <ide> <ide> The `meta` argument of the `Chinese` language class supports the following <ide> nlp = Chinese(meta={"tokenizer": {"config": {"pkuseg_model": "/path/to/pkuseg_mo <ide> <ide> The Japanese language class uses <ide> [SudachiPy](https://github.com/WorksApplications/SudachiPy) for word <del>segmentation and part-of-speech tagging. The default Japanese language class <del>and the provided Japanese models use SudachiPy split mode `A`. <add>segmentation and part-of-speech tagging. The default Japanese language class and <add>the provided Japanese models use SudachiPy split mode `A`. <ide> <ide> The `meta` argument of the `Japanese` language class can be used to configure <ide> the split mode to `A`, `B` or `C`. <ide><path>website/docs/usage/v2-3.md <ide> all language models, and decreased model size and loading times for models with <ide> vectors. We've added pretrained models for **Chinese, Danish, Japanese, Polish <ide> and Romanian** and updated the training data and vectors for most languages. <ide> Model packages with vectors are about **2&times** smaller on disk and load <del>**2-4&times;** faster. For the full changelog, see the [release notes on <del>GitHub](https://github.com/explosion/spaCy/releases/tag/v2.3.0). For more <del>details and a behind-the-scenes look at the new release, [see our blog <del>post](https://explosion.ai/blog/spacy-v2-3). <add>**2-4&times;** faster. For the full changelog, see the <add>[release notes on GitHub](https://github.com/explosion/spaCy/releases/tag/v2.3.0). <add>For more details and a behind-the-scenes look at the new release, <add>[see our blog post](https://explosion.ai/blog/spacy-v2-3). <ide> <ide> ### Expanded model families with vectors {#models} <ide> <ide> post](https://explosion.ai/blog/spacy-v2-3). <ide> <ide> With new model families for Chinese, Danish, Polish, Romanian and Chinese plus <ide> `md` and `lg` models with word vectors for all languages, this release provides <del>a total of 46 model packages. For models trained using [Universal <del>Dependencies](https://universaldependencies.org) corpora, the training data has <del>been updated to UD v2.5 (v2.6 for Japanese, v2.3 for Polish) and Dutch has been <del>extended to include both UD Dutch Alpino and LassySmall. <add>a total of 46 model packages. For models trained using <add>[Universal Dependencies](https://universaldependencies.org) corpora, the <add>training data has been updated to UD v2.5 (v2.6 for Japanese, v2.3 for Polish) <add>and Dutch has been extended to include both UD Dutch Alpino and LassySmall. <ide> <ide> <Infobox> <ide> <ide> extended to include both UD Dutch Alpino and LassySmall. <ide> ### Chinese {#chinese} <ide> <ide> > #### Example <add>> <ide> > ```python <ide> > from spacy.lang.zh import Chinese <ide> > <ide> extended to include both UD Dutch Alpino and LassySmall. <ide> > <ide> > # Append words to user dict <ide> > nlp.tokenizer.pkuseg_update_user_dict(["中国", "ABC"]) <add>> ``` <ide> <ide> This release adds support for <del>[pkuseg](https://github.com/lancopku/pkuseg-python) for word segmentation and <del>the new Chinese models ship with a custom pkuseg model trained on OntoNotes. <del>The Chinese tokenizer can be initialized with both `pkuseg` and custom models <del>and the `pkuseg` user dictionary is easy to customize. <add>[`pkuseg`](https://github.com/lancopku/pkuseg-python) for word segmentation and <add>the new Chinese models ship with a custom pkuseg model trained on OntoNotes. The <add>Chinese tokenizer can be initialized with both `pkuseg` and custom models and <add>the `pkuseg` user dictionary is easy to customize. Note that <add>[`pkuseg`](https://github.com/lancopku/pkuseg-python) doesn't yet ship with <add>pre-compiled wheels for Python 3.8. See the <add>[usage documentation](/usage/models#chinese) for details on how to install it on <add>Python 3.8. <ide> <ide> <Infobox> <ide> <del>**Chinese:** [Chinese tokenizer usage](/usage/models#chinese) <add>**Models:** [Chinese models](/models/zh) **Usage: ** <add>[Chinese tokenizer usage](/usage/models#chinese) <ide> <ide> </Infobox> <ide> <ide> ### Japanese {#japanese} <ide> <ide> The updated Japanese language class switches to <del>[SudachiPy](https://github.com/WorksApplications/SudachiPy) for word <del>segmentation and part-of-speech tagging. Using `sudachipy` greatly simplifies <add>[`SudachiPy`](https://github.com/WorksApplications/SudachiPy) for word <add>segmentation and part-of-speech tagging. Using `SudachiPy` greatly simplifies <ide> installing spaCy for Japanese, which is now possible with a single command: <ide> `pip install spacy[ja]`. <ide> <ide> <Infobox> <ide> <del>**Japanese:** [Japanese tokenizer usage](/usage/models#japanese) <add>**Models:** [Japanese models](/models/ja) **Usage:** <add>[Japanese tokenizer usage](/usage/models#japanese) <ide> <ide> </Infobox> <ide> <ide> ### Small CLI updates <ide> <del>- `spacy debug-data` provides the coverage of the vectors in a base model with <del> `spacy debug-data lang train dev -b base_model` <del>- `spacy evaluate` supports `blank:lg` (e.g. `spacy evaluate blank:en <del> dev.json`) to evaluate the tokenization accuracy without loading a model <del>- `spacy train` on GPU restricts the CPU timing evaluation to the first <del> iteration <add>- [`spacy debug-data`](/api/cli#debug-data) provides the coverage of the vectors <add> in a base model with `spacy debug-data lang train dev -b base_model` <add>- [`spacy evaluate`](/api/cli#evaluate) supports `blank:lg` (e.g. <add> `spacy evaluate blank:en dev.json`) to evaluate the tokenization accuracy <add> without loading a model <add>- [`spacy train`](/api/cli#train) on GPU restricts the CPU timing evaluation to <add> the first iteration <ide> <ide> ## Backwards incompatibilities {#incompat} <ide> <ide> installing spaCy for Japanese, which is now possible with a single command: <ide> If you've been training **your own models**, you'll need to **retrain** them <ide> with the new version. Also don't forget to upgrade all models to the latest <ide> versions. Models for earlier v2 releases (v2.0, v2.1, v2.2) aren't compatible <del>with models for v2.3. To check if all of your models are up to date, you can <del>run the [`spacy validate`](/api/cli#validate) command. <add>with models for v2.3. To check if all of your models are up to date, you can run <add>the [`spacy validate`](/api/cli#validate) command. <ide> <ide> </Infobox> <ide> <ide> run the [`spacy validate`](/api/cli#validate) command. <ide> > directly. <ide> <ide> - If you're training new models, you'll want to install the package <del> [`spacy-lookups-data`](https://github.com/explosion/spacy-lookups-data), <del> which now includes both the lemmatization tables (as in v2.2) and the <del> normalization tables (new in v2.3). If you're using pretrained models, <del> **nothing changes**, because the relevant tables are included in the model <del> packages. <add> [`spacy-lookups-data`](https://github.com/explosion/spacy-lookups-data), which <add> now includes both the lemmatization tables (as in v2.2) and the normalization <add> tables (new in v2.3). If you're using pretrained models, **nothing changes**, <add> because the relevant tables are included in the model packages. <ide> - Due to the updated Universal Dependencies training data, the fine-grained <ide> part-of-speech tags will change for many provided language models. The <ide> coarse-grained part-of-speech tagset remains the same, but the mapping from <ide> particular fine-grained to coarse-grained tags may show minor differences. <ide> - For French, Italian, Portuguese and Spanish, the fine-grained part-of-speech <del> tagsets contain new merged tags related to contracted forms, such as <del> `ADP_DET` for French `"au"`, which maps to UPOS `ADP` based on the head <del> `"à"`. This increases the accuracy of the models by improving the alignment <del> between spaCy's tokenization and Universal Dependencies multi-word tokens <del> used for contractions. <add> tagsets contain new merged tags related to contracted forms, such as `ADP_DET` <add> for French `"au"`, which maps to UPOS `ADP` based on the head `"à"`. This <add> increases the accuracy of the models by improving the alignment between <add> spaCy's tokenization and Universal Dependencies multi-word tokens used for <add> contractions. <ide> <ide> ### Migrating from spaCy 2.2 {#migrating} <ide> <ide> v2.3 so that `token_match` has priority over prefixes and suffixes as in v2.2.1 <ide> and earlier versions. <ide> <ide> A new tokenizer setting `url_match` has been introduced in v2.3.0 to handle <del>cases like URLs where the tokenizer should remove prefixes and suffixes (e.g., <del>a comma at the end of a URL) before applying the match. See the full [tokenizer <del>documentation](/usage/linguistic-features#tokenization) and try out <add>cases like URLs where the tokenizer should remove prefixes and suffixes (e.g., a <add>comma at the end of a URL) before applying the match. See the full <add>[tokenizer documentation](/usage/linguistic-features#tokenization) and try out <ide> [`nlp.tokenizer.explain()`](/usage/linguistic-features#tokenizer-debug) when <ide> debugging your tokenizer configuration. <ide> <ide> #### Warnings configuration <ide> <del>spaCy's custom warnings have been replaced with native python <add>spaCy's custom warnings have been replaced with native Python <ide> [`warnings`](https://docs.python.org/3/library/warnings.html). Instead of <del>setting `SPACY_WARNING_IGNORE`, use the [warnings <del>filters](https://docs.python.org/3/library/warnings.html#the-warnings-filter) <add>setting `SPACY_WARNING_IGNORE`, use the <add>[`warnings` filters](https://docs.python.org/3/library/warnings.html#the-warnings-filter) <ide> to manage warnings. <ide> <ide> #### Normalization tables <ide> <ide> The normalization tables have moved from the language data in <del>[`spacy/lang`](https://github.com/explosion/spaCy/tree/master/spacy/lang) to <del>the package <del>[`spacy-lookups-data`](https://github.com/explosion/spacy-lookups-data). If <del>you're adding data for a new language, the normalization table should be added <del>to `spacy-lookups-data`. See [adding norm <del>exceptions](/usage/adding-languages#norm-exceptions). <add>[`spacy/lang`](https://github.com/explosion/spaCy/tree/master/spacy/lang) to the <add>package [`spacy-lookups-data`](https://github.com/explosion/spacy-lookups-data). <add>If you're adding data for a new language, the normalization table should be <add>added to `spacy-lookups-data`. See <add>[adding norm exceptions](/usage/adding-languages#norm-exceptions). <ide> <ide> #### Probability and cluster features <ide> <ide> exceptions](/usage/adding-languages#norm-exceptions). <ide> <ide> The `Token.prob` and `Token.cluster` features, which are no longer used by the <ide> core pipeline components as of spaCy v2, are no longer provided in the <del>pretrained models to reduce the model size. To keep these features available <del>for users relying on them, the `prob` and `cluster` features for the most <del>frequent 1M tokens have been moved to <add>pretrained models to reduce the model size. To keep these features available for <add>users relying on them, the `prob` and `cluster` features for the most frequent <add>1M tokens have been moved to <ide> [`spacy-lookups-data`](https://github.com/explosion/spacy-lookups-data) as <ide> `extra` features for the relevant languages (English, German, Greek and <ide> Spanish). <ide> <ide> The extra tables are loaded lazily, so if you have `spacy-lookups-data` <del>installed and your code accesses `Token.prob`, the full table is loaded into <del>the model vocab, which will take a few seconds on initial loading. When you <del>save this model after loading the `prob` table, the full `prob` table will be <del>saved as part of the model vocab. <add>installed and your code accesses `Token.prob`, the full table is loaded into the <add>model vocab, which will take a few seconds on initial loading. When you save <add>this model after loading the `prob` table, the full `prob` table will be saved <add>as part of the model vocab. <ide> <del>If you'd like to include custom `cluster`, `prob`, or `sentiment` tables as <del>part of a new model, add the data to <add>If you'd like to include custom `cluster`, `prob`, or `sentiment` tables as part <add>of a new model, add the data to <ide> [`spacy-lookups-data`](https://github.com/explosion/spacy-lookups-data) under <ide> the entry point `lg_extra`, e.g. `en_extra` for English. Alternatively, you can <ide> initialize your [`Vocab`](/api/vocab) with the `lookups_extra` argument with a <ide> [`Lookups`](/api/lookups) object that includes the tables `lexeme_cluster`, <ide> `lexeme_prob`, `lexeme_sentiment` or `lexeme_settings`. `lexeme_settings` is <del>currently only used to provide a custom `oov_prob`. See examples in the [`data` <del>directory](https://github.com/explosion/spacy-lookups-data/tree/master/spacy_lookups_data/data) <add>currently only used to provide a custom `oov_prob`. See examples in the <add>[`data` directory](https://github.com/explosion/spacy-lookups-data/tree/master/spacy_lookups_data/data) <ide> in `spacy-lookups-data`. <ide> <ide> #### Initializing new models without extra lookups tables
2
Go
Go
create docker forward chain on driver init
2865373894f1532fa725481e8f04db4a5d7a0aa8
<ide><path>daemon/networkdriver/bridge/driver.go <ide> func InitDriver(job *engine.Job) engine.Status { <ide> } <ide> <ide> // We can always try removing the iptables <del> if err := iptables.RemoveExistingChain("DOCKER"); err != nil { <add> if err := iptables.RemoveExistingChain("DOCKER", iptables.Nat); err != nil { <ide> return job.Error(err) <ide> } <ide> <ide> if enableIPTables { <del> chain, err := iptables.NewChain("DOCKER", bridgeIface) <add> _, err := iptables.NewChain("DOCKER", bridgeIface, iptables.Nat) <add> if err != nil { <add> return job.Error(err) <add> } <add> chain, err := iptables.NewChain("DOCKER", bridgeIface, iptables.Filter) <ide> if err != nil { <ide> return job.Error(err) <ide> } <ide><path>pkg/iptables/iptables.go <ide> import ( <ide> ) <ide> <ide> type Action string <add>type Table string <ide> <ide> const ( <ide> Append Action = "-A" <ide> Delete Action = "-D" <ide> Insert Action = "-I" <add> Nat Table = "nat" <add> Filter Table = "filter" <ide> ) <ide> <ide> var ( <del> nat = []string{"-t", "nat"} <ide> supportsXlock = false <ide> ErrIptablesNotFound = errors.New("Iptables not found") <ide> ) <ide> <ide> type Chain struct { <ide> Name string <ide> Bridge string <add> Table Table <ide> } <ide> <ide> type ChainError struct { <ide> func init() { <ide> supportsXlock = exec.Command("iptables", "--wait", "-L", "-n").Run() == nil <ide> } <ide> <del>func NewChain(name, bridge string) (*Chain, error) { <del> if output, err := Raw("-t", "nat", "-N", name); err != nil { <del> return nil, err <del> } else if len(output) != 0 { <del> return nil, fmt.Errorf("Error creating new iptables chain: %s", output) <del> } <del> chain := &Chain{ <add>func NewChain(name, bridge string, table Table) (*Chain, error) { <add> c := &Chain{ <ide> Name: name, <ide> Bridge: bridge, <add> Table: table, <add> } <add> <add> if string(c.Table) == "" { <add> c.Table = Filter <ide> } <ide> <del> if err := chain.Prerouting(Append, "-m", "addrtype", "--dst-type", "LOCAL"); err != nil { <del> return nil, fmt.Errorf("Failed to inject docker in PREROUTING chain: %s", err) <add> // Add chain if it doesn't exist <add> if _, err := Raw("-t", string(c.Table), "-n", "-L", c.Name); err != nil { <add> if output, err := Raw("-t", string(c.Table), "-N", c.Name); err != nil { <add> return nil, err <add> } else if len(output) != 0 { <add> return nil, fmt.Errorf("Could not create %s/%s chain: %s", c.Table, c.Name, output) <add> } <ide> } <del> if err := chain.Output(Append, "-m", "addrtype", "--dst-type", "LOCAL", "!", "--dst", "127.0.0.0/8"); err != nil { <del> return nil, fmt.Errorf("Failed to inject docker in OUTPUT chain: %s", err) <add> <add> switch table { <add> case Nat: <add> preroute := []string{ <add> "-m", "addrtype", <add> "--dst-type", "LOCAL"} <add> if !Exists(preroute...) { <add> if err := c.Prerouting(Append, preroute...); err != nil { <add> return nil, fmt.Errorf("Failed to inject docker in PREROUTING chain: %s", err) <add> } <add> } <add> output := []string{ <add> "-m", "addrtype", <add> "--dst-type", "LOCAL", <add> "!", "--dst", "127.0.0.0/8"} <add> if !Exists(output...) { <add> if err := c.Output(Append, output...); err != nil { <add> return nil, fmt.Errorf("Failed to inject docker in OUTPUT chain: %s", err) <add> } <add> } <add> case Filter: <add> link := []string{"FORWARD", <add> "-o", c.Bridge, <add> "-j", c.Name} <add> if !Exists(link...) { <add> insert := append([]string{string(Insert)}, link...) <add> if output, err := Raw(insert...); err != nil { <add> return nil, err <add> } else if len(output) != 0 { <add> return nil, fmt.Errorf("Could not create linking rule to %s/%s: %s", c.Table, c.Name, output) <add> } <add> } <ide> } <del> return chain, nil <add> return c, nil <ide> } <ide> <del>func RemoveExistingChain(name string) error { <del> chain := &Chain{ <del> Name: name, <add>func RemoveExistingChain(name string, table Table) error { <add> c := &Chain{ <add> Name: name, <add> Table: table, <add> } <add> if string(c.Table) == "" { <add> c.Table = Filter <ide> } <del> return chain.Remove() <add> return c.Remove() <ide> } <ide> <add>// Add forwarding rule to 'filter' table and corresponding nat rule to 'nat' table <ide> func (c *Chain) Forward(action Action, ip net.IP, port int, proto, dest_addr string, dest_port int) error { <ide> daddr := ip.String() <ide> if ip.IsUnspecified() { <ide> func (c *Chain) Forward(action Action, ip net.IP, port int, proto, dest_addr str <ide> // value" by both iptables and ip6tables. <ide> daddr = "0/0" <ide> } <del> if output, err := Raw("-t", "nat", string(action), c.Name, <add> if output, err := Raw("-t", string(Nat), string(action), c.Name, <ide> "-p", proto, <ide> "-d", daddr, <ide> "--dport", strconv.Itoa(port), <ide> func (c *Chain) Forward(action Action, ip net.IP, port int, proto, dest_addr str <ide> return &ChainError{Chain: "FORWARD", Output: output} <ide> } <ide> <del> if action != Delete { <del> if err := c.createForwardChain(); err != nil { <del> return err <del> } <del> } <del> <del> if output, err := Raw(string(action), c.Name, <add> if output, err := Raw("-t", string(Filter), string(action), c.Name, <ide> "!", "-i", c.Bridge, <ide> "-o", c.Bridge, <ide> "-p", proto, <ide> func (c *Chain) Forward(action Action, ip net.IP, port int, proto, dest_addr str <ide> return nil <ide> } <ide> <add>// Add reciprocal ACCEPT rule for two supplied IP addresses. <add>// Traffic is allowed from ip1 to ip2 and vice-versa <ide> func (c *Chain) Link(action Action, ip1, ip2 net.IP, port int, proto string) error { <del> if action != Delete { <del> if err := c.createForwardChain(); err != nil { <del> return err <del> } <del> } <del> if output, err := Raw(string(action), c.Name, <add> if output, err := Raw("-t", string(Filter), string(action), c.Name, <ide> "-i", c.Bridge, "-o", c.Bridge, <ide> "-p", proto, <ide> "-s", ip1.String(), <ide> func (c *Chain) Link(action Action, ip1, ip2 net.IP, port int, proto string) err <ide> "-j", "ACCEPT"); err != nil { <ide> return err <ide> } else if len(output) != 0 { <del> return fmt.Errorf("Error toggle iptables forward: %s", output) <add> return fmt.Errorf("Error iptables forward: %s", output) <ide> } <del> <del> if output, err := Raw(string(action), c.Name, <add> if output, err := Raw("-t", string(Filter), string(action), c.Name, <ide> "-i", c.Bridge, "-o", c.Bridge, <ide> "-p", proto, <ide> "-s", ip2.String(), <ide> func (c *Chain) Link(action Action, ip1, ip2 net.IP, port int, proto string) err <ide> "-j", "ACCEPT"); err != nil { <ide> return err <ide> } else if len(output) != 0 { <del> return fmt.Errorf("Error toggle iptables forward: %s", output) <add> return fmt.Errorf("Error iptables forward: %s", output) <ide> } <del> <ide> return nil <ide> } <ide> <add>// Add linking rule to nat/PREROUTING chain. <ide> func (c *Chain) Prerouting(action Action, args ...string) error { <del> a := append(nat, fmt.Sprint(action), "PREROUTING") <add> a := []string{"-t", string(Nat), string(action), "PREROUTING"} <ide> if len(args) > 0 { <ide> a = append(a, args...) <ide> } <ide> func (c *Chain) Prerouting(action Action, args ...string) error { <ide> return nil <ide> } <ide> <add>// Add linking rule to an OUTPUT chain <ide> func (c *Chain) Output(action Action, args ...string) error { <del> a := append(nat, fmt.Sprint(action), "OUTPUT") <add> a := []string{"-t", string(c.Table), string(action), "OUTPUT"} <ide> if len(args) > 0 { <ide> a = append(a, args...) <ide> } <ide> func (c *Chain) Output(action Action, args ...string) error { <ide> } <ide> <ide> func (c *Chain) Remove() error { <del> // Ignore errors - This could mean the chains were never set up <del> c.Prerouting(Delete, "-m", "addrtype", "--dst-type", "LOCAL") <del> c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "!", "--dst", "127.0.0.0/8") <del> c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL") // Created in versions <= 0.1.6 <del> <del> c.Prerouting(Delete) <del> c.Output(Delete) <add> if c.Table == Nat { <add> // Ignore errors - This could mean the chains were never set up <add> c.Prerouting(Delete, "-m", "addrtype", "--dst-type", "LOCAL") <add> c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "!", "--dst", "127.0.0.0/8") <add> c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL") // Created in versions <= 0.1.6 <ide> <del> Raw("-t", "nat", "-F", c.Name) <del> Raw("-t", "nat", "-X", c.Name) <add> c.Prerouting(Delete) <add> c.Output(Delete) <ide> <add> Raw("-t", string(Nat), "-F", c.Name) <add> Raw("-t", string(Nat), "-X", c.Name) <add> } <ide> return nil <ide> } <ide> <del>// Check if an existing rule exists <add>// Check if a rule exists <ide> func Exists(args ...string) bool { <ide> // iptables -C, --check option was added in v.1.4.11 <ide> // http://ftp.netfilter.org/pub/iptables/changes-iptables-1.4.11.txt <ide> func Exists(args ...string) bool { <ide> ) <ide> } <ide> <add>// Call 'iptables' system command, passing supplied arguments <ide> func Raw(args ...string) ([]byte, error) { <ide> path, err := exec.LookPath("iptables") <ide> if err != nil { <ide> func Raw(args ...string) ([]byte, error) { <ide> <ide> return output, err <ide> } <del> <del>func (c *Chain) createForwardChain() error { <del> // Add chain if doesn't exist <del> if _, err := Raw("-n", "-L", c.Name); err != nil { <del> output, err := Raw("-N", c.Name) <del> if err != nil { <del> return err <del> } else if len(output) != 0 { <del> return fmt.Errorf("Error iptables forward: %s", output) <del> } <del> } <del> // Add linking rule if it doesn't exist <del> if !Exists("FORWARD", <del> "-o", c.Bridge, <del> "-j", c.Name) { <del> if output2, err := Raw(string(Insert), "FORWARD", <del> "-o", c.Bridge, <del> "-j", c.Name); err != nil { <del> return err <del> } else if len(output2) != 0 { <del> return fmt.Errorf("Error iptables forward: %s", output2) <del> } <del> } <del> return nil <del>}
2
PHP
PHP
add test for
ed5ffb779eca8b5c095c44dd340cbcb17970fb57
<ide><path>tests/TestCase/ORM/TableTest.php <ide> class_alias($class, 'TestApp\Model\Entity\TestUser'); <ide> $this->assertEquals('TestApp\Model\Entity\TestUser', $table->getEntityClass()); <ide> } <ide> <add> /** <add> * Test that entity class inflection works for compound nouns <add> * <add> * @return void <add> */ <add> public function testEntityClassInflection() <add> { <add> $class = $this->getMockClass('\Cake\ORM\Entity'); <add> <add> if (!class_exists('TestApp\Model\Entity\CustomCookie')) { <add> class_alias($class, 'TestApp\Model\Entity\CustomCookie'); <add> } <add> <add> $table = $this->getTableLocator()->get('CustomCookies'); <add> $this->assertEquals('TestApp\Model\Entity\CustomCookie', $table->getEntityClass()); <add> } <add> <ide> /** <ide> * Tests that using a simple string for entityClass will try to <ide> * load the class from the Plugin namespace when using plugin notation <ide><path>tests/test_app/TestApp/Model/Table/CustomCookiesTable.php <add><?php <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * Redistributions of files must retain the above copyright notice <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @since 3.6.8 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace TestApp\Model\Table; <add> <add>use Cake\ORM\Table; <add> <add>/** <add> * CustomCookies table class <add> */ <add>class CustomCookiesTable extends Table <add>{ <add>}
2
Mixed
Ruby
add guide for inline around_action
012b1e3281115b1b3fd5a13a0058e18c13a0b46f
<ide><path>actionpack/test/controller/filters_test.rb <ide> def test_non_yielding_around_actions_do_not_raise <ide> end <ide> end <ide> <add> def test_around_action_can_use_yield_inline_with_passed_action <add> controller = Class.new(ActionController::Base) do <add> around_action do |c, a| <add> c.values << "before" <add> a.call <add> c.values << "after" <add> end <add> <add> def index <add> values << "action" <add> render inline: "index" <add> end <add> <add> def values <add> @values ||= [] <add> end <add> end.new <add> <add> assert_nothing_raised do <add> test_process(controller, "index") <add> end <add> <add> assert_equal ["before", "action", "after"], controller.values <add> end <add> <ide> def test_after_actions_are_not_run_if_around_action_does_not_yield <ide> controller = NonYieldingAroundFilterController.new <ide> test_process(controller, "index") <ide><path>guides/source/action_controller_overview.md <ide> end <ide> <ide> Note that the filter in this case uses `send` because the `logged_in?` method is private and the filter does not run in the scope of the controller. This is not the recommended way to implement this particular filter, but in more simple cases it might be useful. <ide> <add>Specifically for `around_action`, the block also yields in the `action`: <add> <add>```ruby <add>around_action { |_controller, action| time(&action) } <add>``` <add> <ide> The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex and cannot be implemented in a readable and reusable way using the two other methods. As an example, you could rewrite the login filter again to use a class: <ide> <ide> ```ruby
2
Text
Text
add missing comma in crypto doc
0fa579ac2a682355f7463d2593ae5f6cc09c81e3
<ide><path>doc/api/crypto.md <ide> randomFill(buf, 5, 5, (err, buf) => { <ide> }); <ide> ``` <ide> <del>Any `ArrayBuffer` `TypedArray` or `DataView` instance may be passed as <add>Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as <ide> `buffer`. <ide> <ide> ```mjs
1
PHP
PHP
remove redundant input value
1c96e31a245a675fef0dca353102124d1ed69b7c
<ide><path>tests/TestCase/Console/ConsoleOptionParserTest.php <ide> public function testAddOptionWithPromptAndProvidedValue(): void <ide> 'prompt' => 'What is your favorite?', <ide> ]); <ide> $out = new ConsoleOutput(); <del> $io = new ConsoleIo($out, new ConsoleOutput(), new ConsoleInput(['red'])); <add> $io = new ConsoleIo($out, new ConsoleOutput(), new ConsoleInput([])); <ide> <ide> $result = $parser->parse(['--color', 'blue'], $io); <ide> $this->assertEquals(['color' => 'blue', 'help' => false], $result[0]);
1
Ruby
Ruby
use the env block
df7ae5eb26a9552ff61c66ed5680c701bf0be7df
<ide><path>Library/Homebrew/requirements/ruby_requirement.rb <ide> def initialize(tags) <ide> super <ide> end <ide> <del> satisfy build_env: false do <del> found_ruby = rubies.detect { |ruby| suitable?(ruby) } <del> return unless found_ruby <del> ENV.prepend_path "PATH", found_ruby.dirname <del> found_ruby <add> satisfy build_env: false { suitable_ruby } <add> <add> env do <add> ENV.prepend_path "PATH", suitable_ruby <ide> end <ide> <ide> def message <ide> def display_s <ide> <ide> private <ide> <add> def suitable_ruby <add> rubies.detect { |ruby| suitable?(ruby) } <add> end <add> <ide> def rubies <ide> rubies = which_all("ruby") <ide> if ruby_formula.installed?
1
Ruby
Ruby
use the config value directly when call `secrets`
827bfe4f41c39eade078e26ad5653979891d89c7
<ide><path>railties/lib/rails/application.rb <ide> def config=(configuration) #:nodoc: <ide> def secrets <ide> @secrets ||= begin <ide> secrets = ActiveSupport::OrderedOptions.new <del> secrets.merge! Rails::Secrets.parse(config.paths["config/secrets"].existent, env: Rails.env) <add> files = config.paths["config/secrets"].existent <add> files = files.reject { |path| path.end_with?(".enc") } unless config.read_encrypted_secrets <add> secrets.merge! Rails::Secrets.parse(files, env: Rails.env) <ide> <ide> # Fallback to config.secret_key_base if secrets.secret_key_base isn't set <ide> secrets.secret_key_base ||= config.secret_key_base <ide><path>railties/lib/rails/application/bootstrap.rb <ide> module Bootstrap <ide> <ide> initializer :set_secrets_root, group: :all do <ide> Rails::Secrets.root = root <del> Rails::Secrets.read_encrypted_secrets = config.read_encrypted_secrets <ide> end <ide> end <ide> end <ide><path>railties/lib/rails/secrets.rb <ide> def initialize <ide> end <ide> <ide> @cipher = "aes-128-gcm" <del> @read_encrypted_secrets = false <ide> @root = File # Wonky, but ensures `join` uses the current directory. <ide> <ide> class << self <del> attr_writer :root <del> attr_accessor :read_encrypted_secrets <add> attr_writer :root <ide> <ide> def parse(paths, env:) <ide> paths.each_with_object(Hash.new) do |path, all_secrets| <ide> def path <ide> <ide> def preprocess(path) <ide> if path.end_with?(".enc") <del> if @read_encrypted_secrets <del> decrypt(IO.binread(path)) <del> else <del> "" <del> end <add> decrypt(IO.binread(path)) <ide> else <ide> IO.read(path) <ide> end <ide><path>railties/test/secrets_test.rb <ide> class Rails::SecretsTest < ActiveSupport::TestCase <ide> <ide> def setup <ide> build_app <del> <del> @old_read_encrypted_secrets, Rails::Secrets.read_encrypted_secrets = <del> Rails::Secrets.read_encrypted_secrets, true <ide> end <ide> <ide> def teardown <del> Rails::Secrets.read_encrypted_secrets = @old_read_encrypted_secrets <del> <ide> teardown_app <ide> end <ide> <ide> test "setting read to false skips parsing" do <del> Rails::Secrets.read_encrypted_secrets = false <add> run_secrets_generator do <add> Rails::Secrets.write(<<-end_of_secrets) <add> test: <add> yeah_yeah: lets-walk-in-the-cool-evening-light <add> end_of_secrets <ide> <del> Dir.chdir(app_path) do <del> assert_equal Hash.new, Rails::Secrets.parse(%w( config/secrets.yml.enc ), env: "production") <add> Rails.application.config.read_encrypted_secrets = false <add> Rails.application.instance_variable_set(:@secrets, nil) # Dance around caching 💃🕺 <add> assert_not Rails.application.secrets.yeah_yeah <ide> end <ide> end <ide> <ide> def teardown <ide> end_of_secrets <ide> <ide> Rails.application.config.root = app_path <add> Rails.application.config.read_encrypted_secrets = true <ide> Rails.application.instance_variable_set(:@secrets, nil) # Dance around caching 💃🕺 <ide> assert_equal "lets-walk-in-the-cool-evening-light", Rails.application.secrets.yeah_yeah <ide> end <ide> end <ide> <add> test "refer secrets inside env config" do <add> run_secrets_generator do <add> Rails::Secrets.write(<<-end_of_yaml) <add> production: <add> some_secret: yeah yeah <add> end_of_yaml <add> <add> add_to_env_config "production", <<-end_of_config <add> config.dereferenced_secret = Rails.application.secrets.some_secret <add> end_of_config <add> <add> Dir.chdir(app_path) do <add> assert_equal "yeah yeah\n", `bin/rails runner -e production "puts Rails.application.config.dereferenced_secret"` <add> end <add> end <add> end <add> <ide> private <ide> def run_secrets_generator <ide> Dir.chdir(app_path) do
4
Text
Text
update egghead links in learning resources
9ee5cab9fec008a4a406230ab7754eab0e9ad22c
<ide><path>docs/introduction/LearningResources.md <ide> This page includes our recommendations for some of the best external resources a <ide> _Tutorials that teach the basic concepts of Redux and how to use it_ <ide> <ide> - **Getting Started with Redux - Video Series** <br/> <del> https://egghead.io/series/getting-started-with-redux <br/> <add> https://app.egghead.io/courses/getting-started-with-redux <br/> <ide> https://github.com/tayiorbeii/egghead.io_redux_course_notes <br/> <ide> Dan Abramov, the creator of Redux, demonstrates various concepts in 30 short (2-5 minute) videos. The linked Github repo contains notes and transcriptions of the videos. <ide> <ide> - **Building React Applications with Idiomatic Redux - Video Series** <br/> <del> https://egghead.io/series/building-react-applications-with-idiomatic-redux <br/> <add> https://app.egghead.io/courses/building-react-applications-with-idiomatic-redux <br/> <ide> https://github.com/tayiorbeii/egghead.io_idiomatic_redux_course_notes <br/> <ide> Dan Abramov's second video tutorial series, continuing directly after the first. Includes lessons on store initial state, using Redux with React Router, using "selector" functions, normalizing state, use of Redux middleware, async action creators, and more. The linked Github repo contains notes and transcriptions of the videos. <ide>
1
Text
Text
create model card
0039b965db7e2d077363583ae95e1487a81ee0af
<ide><path>model_cards/mrm8488/t5-small-finetuned-squadv2/README.md <add>--- <add>language: english <add>datasets: <add>- squad_v2 <add>--- <add> <add># T5-small fine-tuned on SQuAD v2 <add> <add>[Google's T5](https://ai.googleblog.com/2020/02/exploring-transfer-learning-with-t5.html) [(small)](https://huggingface.co/t5-small) fine-tuned on [SQuAD v2](https://rajpurkar.github.io/SQuAD-explorer/) for **Q&A** downstream task. <add> <add>## Details of T5 <add> <add>The **T5** model was presented in [Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer](https://arxiv.org/pdf/1910.10683.pdf) by *Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan Narang, Michael Matena, Yanqi Zhou, Wei Li, Peter J. Liu* in Here the abstract: <add> <add>Transfer learning, where a model is first pre-trained on a data-rich task before being fine-tuned on a downstream task, has emerged as a powerful technique in natural language processing (NLP). The effectiveness of transfer learning has given rise to a diversity of approaches, methodology, and practice. In this paper, we explore the landscape of transfer learning techniques for NLP by introducing a unified framework that converts every language problem into a text-to-text format. Our systematic study compares pre-training objectives, architectures, unlabeled datasets, transfer approaches, and other factors on dozens of language understanding tasks. By combining the insights from our exploration with scale and our new “Colossal Clean Crawled Corpus”, we achieve state-of-the-art results on many benchmarks covering summarization, question answering, text classification, and more. To facilitate future work on transfer learning for NLP, we release our dataset, pre-trained models, and code. <add> <add>![model image](https://i.imgur.com/jVFMMWR.png) <add> <add> <add>## Details of the downstream task (Q&A) - Dataset 📚 🧐 ❓ <add> <add>Dataset ID: ```squad_v2``` from [HugginFace/NLP](https://github.com/huggingface/nlp) <add> <add>| Dataset | Split | # samples | <add>| -------- | ----- | --------- | <add>| squad_v2 | train | 130319 | <add>| squad_v2 | valid | 11873 | <add> <add>How to load it from [nlp](https://github.com/huggingface/nlp) <add> <add>```python <add>train_dataset = nlp.load_dataset('squad_v2, split=nlp.Split.TRAIN) <add>valid_dataset = nlp.load_dataset('squad_v2', split=nlp.Split.VALIDATION) <add>``` <add>Check out more about this dataset and others in [NLP Viewer](https://huggingface.co/nlp/viewer/) <add> <add> <add>## Model fine-tuning 🏋️‍ <add> <add>The training script is a slightly modified version of [this awesome one](https://colab.research.google.com/github/patil-suraj/exploring-T5/blob/master/T5_on_TPU.ipynb) by [Suraj Patil](https://twitter.com/psuraj28) <add> <add>## Results 📝 <add> <add>| Metric | # Value | <add>| ------ | --------- | <add>| **EM** | **69.46** | <add>| **F1** | **73.01** | <add> <add> <add> <add>## Model in Action 🚀 <add> <add>```python <add>from transformers import AutoModelWithLMHead, AutoTokenizer <add> <add>tokenizer = AutoTokenizer.from_pretrained("mrm8488/t5-small-finetuned-squadv2") <add>model = AutoModelWithLMHead.from_pretrained("mrm8488/t5-small-finetuned-squadv2") <add> <add>def get_answer(question, context): <add> input_text = "question: %s context: %s </s>" % (question, context) <add> features = tokenizer([input_text], return_tensors='pt') <add> <add> output = model.generate(input_ids=features['input_ids'], <add> attention_mask=features['attention_mask']) <add> <add> return tokenizer.decode(output[0]) <add> <add>context = "Manuel have created RuPERTa-base (a Spanish RoBERTa) with the support of HF-Transformers and Google" <add>question = "Who has supported Manuel?" <add> <add>get_answer(question, context) <add> <add># output: 'HF-Transformers and Google' <add>``` <add> <add>> Created by [Manuel Romero/@mrm8488](https://twitter.com/mrm8488) | [LinkedIn](https://www.linkedin.com/in/manuel-romero-cs/) <add> <add>> Made with <span style="color: #e25555;">&hearts;</span> in Spain
1
Text
Text
modify sample css so that it works in safari
a18c7549dff1e29e2728857d18428775661e7571
<ide><path>docs/docs/10.1-animation.md <ide> You can use these classes to trigger a CSS animation or transition. For example, <ide> ```css <ide> .example-enter { <ide> opacity: 0.01; <del> transition: opacity .5s ease-in; <ide> } <ide> <ide> .example-enter.example-enter-active { <ide> opacity: 1; <add> transition: opacity .5s ease-in; <ide> } <ide> ``` <ide> <ide> You'll notice that when you try to remove an item `ReactCSSTransitionGroup` keep <ide> ```css <ide> .example-leave { <ide> opacity: 1; <del> transition: opacity .5s ease-in; <ide> } <ide> <ide> .example-leave.example-leave-active { <ide> opacity: 0.01; <add> transition: opacity .5s ease-in; <ide> } <ide> ``` <ide>
1
Ruby
Ruby
remove dead constant
2d8d7184f6317bd8ad56382eec292a1360815a5e
<ide><path>Library/Homebrew/os/mac/xcode.rb <ide> module Xcode <ide> V4_BUNDLE_ID = "com.apple.dt.Xcode" <ide> V3_BUNDLE_ID = "com.apple.Xcode" <ide> V4_BUNDLE_PATH = Pathname.new("/Applications/Xcode.app") <del> V3_BUNDLE_PATH = Pathname.new("/Developer/Applications/Xcode.app") <ide> <ide> # Locate the "current Xcode folder" via xcode-select. See: <ide> # man xcode-select
1
Go
Go
fix race in deletenetwork
c772d14e58c52168348a549bbb9c637e7c433ffc
<ide><path>libnetwork/networkdb/networkdb.go <ide> func (nDB *NetworkDB) addNetworkNode(nid string, nodeName string) { <ide> // this <ide> func (nDB *NetworkDB) deleteNetworkNode(nid string, nodeName string) { <ide> nodes := nDB.networkNodes[nid] <del> for i, name := range nodes { <add> newNodes := make([]string, 0, len(nodes)-1) <add> for _, name := range nodes { <ide> if name == nodeName { <del> nodes[i] = nodes[len(nodes)-1] <del> nodes = nodes[:len(nodes)-1] <del> break <add> continue <ide> } <add> newNodes = append(newNodes, name) <ide> } <del> nDB.networkNodes[nid] = nodes <add> nDB.networkNodes[nid] = newNodes <ide> } <ide> <ide> // findCommonnetworks find the networks that both this node and the
1
Python
Python
fix typo in the word 'available'
58edc38f45c903637564c1e07e07933c41b2ca44
<ide><path>tests/providers/apache/hive/transfers/test_mssql_to_hive.py <ide> pymssql = None <ide> <ide> <del>@unittest.skipIf(PY38, "Mssql package not avaible when Python >= 3.8.") <add>@unittest.skipIf(PY38, "Mssql package not available when Python >= 3.8.") <ide> @unittest.skipIf(pymssql is None, 'pymssql package not present') <ide> class TestMsSqlToHiveTransfer(unittest.TestCase): <ide> <ide><path>tests/providers/google/cloud/transfers/test_mssql_to_gcs.py <ide> ] <ide> <ide> <del>@unittest.skipIf(PY38, "Mssql package not avaible when Python >= 3.8.") <add>@unittest.skipIf(PY38, "Mssql package not available when Python >= 3.8.") <ide> class TestMsSqlToGoogleCloudStorageOperator(unittest.TestCase): <ide> <ide> def test_init(self): <ide><path>tests/providers/microsoft/mssql/operators/test_mssql.py <ide> <ide> <ide> class TestMsSqlOperator: <del> @unittest.skipIf(PY38, "Mssql package not avaible when Python >= 3.8.") <add> @unittest.skipIf(PY38, "Mssql package not available when Python >= 3.8.") <ide> @mock.patch('airflow.hooks.base_hook.BaseHook.get_connection') <ide> def test_get_hook(self, get_connection): <ide> """ <ide><path>tests/test_core_to_contrib.py <ide> def skip_test_with_mssql_in_py38(self, path_a="", path_b=""): <ide> py_38 = sys.version_info >= (3, 8) <ide> if py_38: <ide> if "mssql" in path_a or "mssql" in path_b: <del> raise self.skipTest("Mssql package not avaible when Python >= 3.8.") <add> raise self.skipTest("Mssql package not available when Python >= 3.8.") <ide> <ide> @staticmethod <ide> def get_class_from_path(path_to_class, parent=False):
4
Python
Python
improve textcat model slightly
f8a0614527a656a50100fa784be23c698f706673
<ide><path>spacy/_ml.py <ide> def build_text_classifier(nr_class, width=64, **cfg): <ide> >> with_flatten( <ide> LN(Maxout(width, vectors_width)) <ide> >> Residual( <del> (ExtractWindow(nW=1) >> zero_init(Maxout(width, width*3))) <add> (ExtractWindow(nW=1) >> LN(Maxout(width, width*3))) <ide> ) ** 2, pad=2 <ide> ) <ide> >> flatten_add_lengths
1
PHP
PHP
move email config to test
22e150bd0fc6a4cb60e1ee00ce1da73c333b8161
<ide><path>tests/TestCase/TestSuite/EmailAssertTraitTest.php <ide> */ <ide> namespace Cake\Test\TestCase\TestSuite; <ide> <add>use Cake\Mailer\Email; <add>use Cake\Mailer\Transport\DebugTransport; <ide> use Cake\TestSuite\EmailAssertTrait; <ide> use Cake\TestSuite\TestCase; <ide> use TestApp\Mailer\TestUserMailer; <ide> class EmailAssertTraitTest extends TestCase <ide> <ide> use EmailAssertTrait; <ide> <add> public function setUp() <add> { <add> parent::setUp(); <add> Email::configTransport('debug', ['className' => DebugTransport::class]); <add> } <add> <add> public function tearDown() <add> { <add> parent::tearDown(); <add> Email::dropTransport('debug'); <add> } <add> <ide> public function testFunctional() <ide> { <ide> $mailer = $this->getMockForMailer(TestUserMailer::class); <ide><path>tests/bootstrap.php <ide> use Cake\Core\Configure; <ide> use Cake\Datasource\ConnectionManager; <ide> use Cake\Log\Log; <del>use Cake\Mailer\Email; <del>use Cake\Mailer\Transport\DebugTransport; <ide> <ide> require_once 'vendor/autoload.php'; <ide> <ide> 'defaults' => 'php' <ide> ]); <ide> <del>Email::configTransport('debug', ['className' => DebugTransport::class]); <del> <ide> Log::config([ <ide> // 'queries' => [ <ide> // 'className' => 'Console',
2
Javascript
Javascript
incorect comparison of dates
ffa84418862a9f768ce5b9b681916438f14a0d79
<ide><path>src/Angular.js <ide> function equals(o1, o2) { <ide> } <ide> return true; <ide> } <add> } else if (isDate(o1)) { <add> return isDate(o2) && o1.getTime() == o2.getTime(); <ide> } else { <ide> if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2)) return false; <ide> keySet = {}; <ide><path>test/AngularSpec.js <ide> describe('angular', function() { <ide> expect(equals(window, window.parent)).toBe(false); <ide> expect(equals(window, undefined)).toBe(false); <ide> }); <add> <add> it('should compare dates', function() { <add> expect(equals(new Date(0), new Date(0))).toBe(true); <add> expect(equals(new Date(0), new Date(1))).toBe(false); <add> expect(equals(new Date(0), 0)).toBe(false); <add> expect(equals(0, new Date(0))).toBe(false); <add> }); <ide> }); <ide> <ide> describe('size', function() {
2
Javascript
Javascript
replace var with let/const
b551c6570059ede6d5f90a2b4d5234db1f508b52
<ide><path>lib/querystring.js <ide> const unhexTable = [ <ide> // A safe fast alternative to decodeURIComponent <ide> function unescapeBuffer(s, decodeSpaces) { <ide> const out = Buffer.allocUnsafe(s.length); <del> var index = 0; <del> var outIndex = 0; <del> var currentChar; <del> var nextChar; <del> var hexHigh; <del> var hexLow; <add> let index = 0; <add> let outIndex = 0; <add> let currentChar; <add> let nextChar; <add> let hexHigh; <add> let hexLow; <ide> const maxLength = s.length - 2; <ide> // Flag to know if some hex chars have been decoded <del> var hasHex = false; <add> let hasHex = false; <ide> while (index < s.length) { <ide> currentChar = s.charCodeAt(index); <ide> if (currentChar === 43 /* '+' */ && decodeSpaces) { <ide> function stringify(obj, sep, eq, options) { <ide> sep = sep || '&'; <ide> eq = eq || '='; <ide> <del> var encode = QueryString.escape; <add> let encode = QueryString.escape; <ide> if (options && typeof options.encodeURIComponent === 'function') { <ide> encode = options.encodeURIComponent; <ide> } <ide> <ide> if (obj !== null && typeof obj === 'object') { <del> var keys = Object.keys(obj); <del> var len = keys.length; <del> var flast = len - 1; <del> var fields = ''; <del> for (var i = 0; i < len; ++i) { <del> var k = keys[i]; <del> var v = obj[k]; <del> var ks = encode(stringifyPrimitive(k)); <add> const keys = Object.keys(obj); <add> const len = keys.length; <add> const flast = len - 1; <add> let fields = ''; <add> for (let i = 0; i < len; ++i) { <add> const k = keys[i]; <add> const v = obj[k]; <add> let ks = encode(stringifyPrimitive(k)); <ide> ks += eq; <ide> <ide> if (Array.isArray(v)) { <del> var vlen = v.length; <add> const vlen = v.length; <ide> if (vlen === 0) continue; <del> var vlast = vlen - 1; <del> for (var j = 0; j < vlen; ++j) { <add> const vlast = vlen - 1; <add> for (let j = 0; j < vlen; ++j) { <ide> fields += ks; <ide> fields += encode(stringifyPrimitive(v[j])); <ide> if (j < vlast) <ide> function charCodes(str) { <ide> if (str.length === 0) return []; <ide> if (str.length === 1) return [str.charCodeAt(0)]; <ide> const ret = new Array(str.length); <del> for (var i = 0; i < str.length; ++i) <add> for (let i = 0; i < str.length; ++i) <ide> ret[i] = str.charCodeAt(i); <ide> return ret; <ide> } <ide> function parse(qs, sep, eq, options) { <ide> const sepLen = sepCodes.length; <ide> const eqLen = eqCodes.length; <ide> <del> var pairs = 1000; <add> let pairs = 1000; <ide> if (options && typeof options.maxKeys === 'number') { <ide> // -1 is used in place of a value like Infinity for meaning <ide> // "unlimited pairs" because of additional checks V8 (at least as of v5.4) <ide> function parse(qs, sep, eq, options) { <ide> pairs = (options.maxKeys > 0 ? options.maxKeys : -1); <ide> } <ide> <del> var decode = QueryString.unescape; <add> let decode = QueryString.unescape; <ide> if (options && typeof options.decodeURIComponent === 'function') { <ide> decode = options.decodeURIComponent; <ide> } <ide> const customDecode = (decode !== qsUnescape); <ide> <del> var lastPos = 0; <del> var sepIdx = 0; <del> var eqIdx = 0; <del> var key = ''; <del> var value = ''; <del> var keyEncoded = customDecode; <del> var valEncoded = customDecode; <add> let lastPos = 0; <add> let sepIdx = 0; <add> let eqIdx = 0; <add> let key = ''; <add> let value = ''; <add> let keyEncoded = customDecode; <add> let valEncoded = customDecode; <ide> const plusChar = (customDecode ? '%20' : ' '); <del> var encodeCheck = 0; <del> for (var i = 0; i < qs.length; ++i) { <add> let encodeCheck = 0; <add> for (let i = 0; i < qs.length; ++i) { <ide> const code = qs.charCodeAt(i); <ide> <ide> // Try matching key/value pair separator (e.g. '&')
1
PHP
PHP
fix phpcs and invert condition to bail early
4a977003bd71f5231ba071c45031c6bbdfdc9acb
<ide><path>src/Routing/Middleware/RoutingMiddleware.php <ide> class RoutingMiddleware <ide> { <ide> <ide> /** <add> * Apply routing and update the request. <add> * <add> * Any route/path specific middleware will be wrapped around $next and then the new middleware stack <add> * will be invoked. <add> * <ide> * @param \Psr\Http\Message\ServerRequestInterface $request The request. <ide> * @param \Psr\Http\Message\ResponseInterface $response The response. <ide> * @param callable $next The next middleware to call. <ide> public function __invoke(ServerRequestInterface $request, ResponseInterface $res <ide> ); <ide> } <ide> $middleware = Router::getMatchingMiddleware($request->getUri()->getPath()); <del> if ($middleware) { <del> $middleware->add($next); <del> $runner = new Runner(); <del> <del> return $runner->run($middleware, $request, $response); <add> if (!$middleware) { <add> return $next($request, $response); <ide> } <del> return $next($request, $response); <add> $middleware->add($next); <add> $runner = new Runner(); <add> <add> return $runner->run($middleware, $request, $response); <add> <ide> } <ide> }
1
Java
Java
relax configurablewebenvironment signatures
3cdb866bda078a24d3fccb36b08a449a970a524f
<ide><path>spring-web/src/main/java/org/springframework/web/context/ConfigurableWebApplicationContext.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2013 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public interface ConfigurableWebApplicationContext extends WebApplicationContext <ide> */ <ide> ServletConfig getServletConfig(); <ide> <del> /** <del> * Return the {@link ConfigurableWebEnvironment} used by this web application context. <del> */ <del> ConfigurableWebEnvironment getEnvironment(); <del> <ide> /** <ide> * Set the namespace for this web application context, <ide> * to be used for building a default context config location. <ide><path>spring-web/src/main/java/org/springframework/web/context/ContextLoader.java <ide> import org.springframework.context.access.ContextSingletonBeanFactoryLocator; <ide> import org.springframework.core.GenericTypeResolver; <ide> import org.springframework.core.annotation.AnnotationAwareOrderComparator; <add>import org.springframework.core.env.ConfigurableEnvironment; <ide> import org.springframework.core.io.ClassPathResource; <ide> import org.springframework.core.io.support.PropertiesLoaderUtils; <ide> import org.springframework.util.Assert; <ide> protected void customizeContext(ServletContext servletContext, ConfigurableWebAp <ide> initializerInstances.add(BeanUtils.instantiateClass(initializerClass)); <ide> } <ide> <del> applicationContext.getEnvironment().initPropertySources(servletContext, null); <add> ConfigurableEnvironment env = applicationContext.getEnvironment(); <add> if (env instanceof ConfigurableWebEnvironment) { <add> ((ConfigurableWebEnvironment)env).initPropertySources(servletContext, null); <add> } <ide> <ide> Collections.sort(initializerInstances, new AnnotationAwareOrderComparator()); <ide> for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : initializerInstances) { <ide><path>spring-web/src/main/java/org/springframework/web/context/support/AbstractRefreshableWebApplicationContext.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2013 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import org.springframework.ui.context.Theme; <ide> import org.springframework.ui.context.ThemeSource; <ide> import org.springframework.ui.context.support.UiApplicationContextUtils; <del>import org.springframework.util.Assert; <ide> import org.springframework.web.context.ConfigurableWebApplicationContext; <ide> import org.springframework.web.context.ConfigurableWebEnvironment; <ide> import org.springframework.web.context.ServletConfigAware; <ide> protected ConfigurableEnvironment createEnvironment() { <ide> return new StandardServletEnvironment(); <ide> } <ide> <del> @Override <del> public ConfigurableWebEnvironment getEnvironment() { <del> ConfigurableEnvironment env = super.getEnvironment(); <del> Assert.isInstanceOf(ConfigurableWebEnvironment.class, env, <del> "ConfigurableWebApplicationContext environment must be of type " + <del> "ConfigurableWebEnvironment"); <del> return (ConfigurableWebEnvironment) env; <del> } <del> <ide> /** <ide> * Register request/session scopes, a {@link ServletContextAwareProcessor}, etc. <ide> */ <ide> protected void onRefresh() { <ide> @Override <ide> protected void initPropertySources() { <ide> super.initPropertySources(); <del> this.getEnvironment().initPropertySources(this.servletContext, this.servletConfig); <add> ConfigurableEnvironment env = this.getEnvironment(); <add> if (env instanceof ConfigurableWebEnvironment) { <add> ((ConfigurableWebEnvironment)env).initPropertySources( <add> this.servletContext, this.servletConfig); <add> } <ide> } <ide> <ide> public Theme getTheme(String themeName) { <ide><path>spring-web/src/main/java/org/springframework/web/context/support/GenericWebApplicationContext.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2013 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> protected ConfigurableEnvironment createEnvironment() { <ide> return new StandardServletEnvironment(); <ide> } <ide> <del> @Override <del> public ConfigurableWebEnvironment getEnvironment() { <del> ConfigurableEnvironment env = super.getEnvironment(); <del> Assert.isInstanceOf(ConfigurableWebEnvironment.class, env, <del> "ConfigurableWebApplicationContext environment must be of type " + <del> "ConfigurableWebEnvironment"); <del> return (ConfigurableWebEnvironment) env; <del> } <del> <ide> /** <ide> * Register ServletContextAwareProcessor. <ide> * @see ServletContextAwareProcessor <ide> protected void onRefresh() { <ide> @Override <ide> protected void initPropertySources() { <ide> super.initPropertySources(); <del> this.getEnvironment().initPropertySources(this.servletContext, null); <add> ConfigurableEnvironment env = this.getEnvironment(); <add> if (env instanceof ConfigurableWebEnvironment) { <add> ((ConfigurableWebEnvironment)env).initPropertySources( <add> this.servletContext, null); <add> } <ide> } <ide> <ide> public Theme getTheme(String themeName) { <ide><path>spring-web/src/main/java/org/springframework/web/context/support/StaticWebApplicationContext.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2013 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import org.springframework.ui.context.Theme; <ide> import org.springframework.ui.context.ThemeSource; <ide> import org.springframework.ui.context.support.UiApplicationContextUtils; <del>import org.springframework.util.Assert; <ide> import org.springframework.web.context.ConfigurableWebApplicationContext; <del>import org.springframework.web.context.ConfigurableWebEnvironment; <ide> import org.springframework.web.context.ServletConfigAware; <ide> import org.springframework.web.context.ServletContextAware; <ide> <ide> protected ConfigurableEnvironment createEnvironment() { <ide> return new StandardServletEnvironment(); <ide> } <ide> <del> @Override <del> public ConfigurableWebEnvironment getEnvironment() { <del> ConfigurableEnvironment env = super.getEnvironment(); <del> Assert.isInstanceOf(ConfigurableWebEnvironment.class, env, <del> "ConfigurableWebApplication environment must be of type " + <del> "ConfigurableWebEnvironment"); <del> return (ConfigurableWebEnvironment) env; <del> } <del> <ide> /** <ide> * Initialize the theme capability. <ide> */ <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/FrameworkServlet.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2013 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import org.springframework.context.i18n.LocaleContextHolder; <ide> import org.springframework.context.i18n.SimpleLocaleContext; <ide> import org.springframework.core.annotation.AnnotationAwareOrderComparator; <add>import org.springframework.core.env.ConfigurableEnvironment; <ide> import org.springframework.util.ClassUtils; <ide> import org.springframework.util.ObjectUtils; <ide> import org.springframework.util.StringUtils; <ide> import org.springframework.web.bind.annotation.RequestMethod; <ide> import org.springframework.web.context.ConfigurableWebApplicationContext; <add>import org.springframework.web.context.ConfigurableWebEnvironment; <ide> import org.springframework.web.context.WebApplicationContext; <ide> import org.springframework.web.context.request.NativeWebRequest; <ide> import org.springframework.web.context.request.RequestAttributes; <ide> protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicati <ide> // the context is refreshed; do it eagerly here to ensure servlet property sources <ide> // are in place for use in any post-processing or initialization that occurs <ide> // below prior to #refresh <del> wac.getEnvironment().initPropertySources(getServletContext(), getServletConfig()); <add> ConfigurableEnvironment env = wac.getEnvironment(); <add> if (env instanceof ConfigurableWebEnvironment) { <add> ((ConfigurableWebEnvironment)env).initPropertySources(getServletContext(), getServletConfig()); <add> } <ide> <ide> postProcessWebApplicationContext(wac); <ide> <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/HttpServletBean.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2013 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <del> <ide> import org.springframework.beans.BeanWrapper; <ide> import org.springframework.beans.BeansException; <ide> import org.springframework.beans.MutablePropertyValues; <ide> import org.springframework.beans.PropertyAccessorFactory; <ide> import org.springframework.beans.PropertyValue; <ide> import org.springframework.beans.PropertyValues; <ide> import org.springframework.context.EnvironmentAware; <add>import org.springframework.core.env.ConfigurableEnvironment; <ide> import org.springframework.core.env.Environment; <ide> import org.springframework.core.env.EnvironmentCapable; <ide> import org.springframework.core.io.Resource; <ide> import org.springframework.core.io.ResourceEditor; <ide> import org.springframework.core.io.ResourceLoader; <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.StringUtils; <del>import org.springframework.web.context.ConfigurableWebEnvironment; <del>import org.springframework.web.context.support.StandardServletEnvironment; <ide> import org.springframework.web.context.support.ServletContextResourceLoader; <add>import org.springframework.web.context.support.StandardServletEnvironment; <ide> <ide> /** <ide> * Simple extension of {@link javax.servlet.http.HttpServlet} which treats <ide> public abstract class HttpServletBean extends HttpServlet <ide> */ <ide> private final Set<String> requiredProperties = new HashSet<String>(); <ide> <del> private ConfigurableWebEnvironment environment; <add> private ConfigurableEnvironment environment; <ide> <ide> <ide> /** <ide> protected void initServletBean() throws ServletException { <ide> /** <ide> * {@inheritDoc} <ide> * @throws IllegalArgumentException if environment is not assignable to <del> * {@code ConfigurableWebEnvironment}. <add> * {@code ConfigurableEnvironment}. <ide> */ <ide> public void setEnvironment(Environment environment) { <del> Assert.isInstanceOf(ConfigurableWebEnvironment.class, environment); <del> this.environment = (ConfigurableWebEnvironment)environment; <add> Assert.isInstanceOf(ConfigurableEnvironment.class, environment); <add> this.environment = (ConfigurableEnvironment) environment; <ide> } <ide> <ide> /** <ide> * {@inheritDoc} <ide> * <p>If {@code null}, a new environment will be initialized via <ide> * {@link #createEnvironment()}. <ide> */ <del> public ConfigurableWebEnvironment getEnvironment() { <add> public ConfigurableEnvironment getEnvironment() { <ide> if (this.environment == null) { <ide> this.environment = this.createEnvironment(); <ide> } <ide> public ConfigurableWebEnvironment getEnvironment() { <ide> * Create and return a new {@link StandardServletEnvironment}. Subclasses may override <ide> * in order to configure the environment or specialize the environment type returned. <ide> */ <del> protected ConfigurableWebEnvironment createEnvironment() { <add> protected ConfigurableEnvironment createEnvironment() { <ide> return new StandardServletEnvironment(); <ide> } <ide> <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java <ide> public void testDispatcherServletContextRefresh() throws ServletException { <ide> <ide> public void testEnvironmentOperations() { <ide> DispatcherServlet servlet = new DispatcherServlet(); <del> ConfigurableWebEnvironment defaultEnv = servlet.getEnvironment(); <add> ConfigurableEnvironment defaultEnv = servlet.getEnvironment(); <ide> assertThat(defaultEnv, notNullValue()); <ide> ConfigurableEnvironment env1 = new StandardServletEnvironment(); <ide> servlet.setEnvironment(env1); // should succeed
8
Ruby
Ruby
remove intelligence from statementcache#initialize
249fd686fb86c89463d791f44114fd829cb05bd2
<ide><path>activerecord/lib/active_record/core.rb <ide> def find(*ids) <ide> key = primary_key <ide> <ide> s = find_by_statement_cache[key] || find_by_statement_cache.synchronize { <del> find_by_statement_cache[key] ||= StatementCache.new { |params| <add> find_by_statement_cache[key] ||= StatementCache.create { |params| <ide> where(key => params[key]).limit(1) <ide> } <ide> } <ide> def find_by(*args) <ide> <ide> klass = self <ide> s = find_by_statement_cache[key] || find_by_statement_cache.synchronize { <del> find_by_statement_cache[key] ||= StatementCache.new { |params| <add> find_by_statement_cache[key] ||= StatementCache.create { |params| <ide> wheres = key.each_with_object({}) { |param,o| <ide> o[param] = params[param] <ide> } <ide><path>activerecord/lib/active_record/statement_cache.rb <ide> def bind(values) <ide> <ide> attr_reader :bind_map, :query_builder <ide> <del> def initialize(block = Proc.new) <del> relation = block.call Params.new <del> @bind_map = BindMap.new relation.bind_values <add> def self.create(block = Proc.new) <add> relation = block.call Params.new <add> bind_map = BindMap.new relation.bind_values <ide> klass = relation.klass <del> @query_builder = make_query_builder klass.connection, relation.arel <add> connection = klass.connection <add> query_builder = connection.cacheable_query relation.arel <add> new query_builder, bind_map <add> end <add> <add> def initialize(query_builder, bind_map) <add> @query_builder = query_builder <add> @bind_map = bind_map <ide> end <ide> <ide> def execute(params, klass, connection) <ide> def execute(params, klass, connection) <ide> klass.find_by_sql sql, bind_values <ide> end <ide> alias :call :execute <del> <del> private <del> def make_query_builder(connection, arel) <del> connection.cacheable_query(arel) <del> end <ide> end <ide> end <ide><path>activerecord/test/cases/statement_cache_test.rb <ide> def test_statement_cache <ide> Book.create(name: "my book") <ide> Book.create(name: "my other book") <ide> <del> cache = StatementCache.new do |params| <add> cache = StatementCache.create do |params| <ide> Book.where(:name => params[:name]) <ide> end <ide> <ide> def test_statement_cache_id <ide> b1 = Book.create(name: "my book") <ide> b2 = Book.create(name: "my other book") <ide> <del> cache = StatementCache.new do |params| <add> cache = StatementCache.create do |params| <ide> Book.where(id: params[:id]) <ide> end <ide> <ide> def test_find_or_create_by <ide> #End <ide> <ide> def test_statement_cache_with_simple_statement <del> cache = ActiveRecord::StatementCache.new do |params| <add> cache = ActiveRecord::StatementCache.create do |params| <ide> Book.where(name: "my book").where("author_id > 3") <ide> end <ide> <ide> def test_statement_cache_with_simple_statement <ide> end <ide> <ide> def test_statement_cache_with_complex_statement <del> cache = ActiveRecord::StatementCache.new do |params| <add> cache = ActiveRecord::StatementCache.create do |params| <ide> Liquid.joins(:molecules => :electrons).where('molecules.name' => 'dioxane', 'electrons.name' => 'lepton') <ide> end <ide> <ide> def test_statement_cache_with_complex_statement <ide> end <ide> <ide> def test_statement_cache_values_differ <del> cache = ActiveRecord::StatementCache.new do |params| <add> cache = ActiveRecord::StatementCache.create do |params| <ide> Book.where(name: "my book") <ide> end <ide>
3
Python
Python
drop print statement
69083c3668b363bd9cb85674255d260808bbeeff
<ide><path>rest_framework/urlpatterns.py <ide> def apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required): <ide> ret.append(url(regex, view, kwargs, name)) <ide> else: <ide> # Set of included URL patterns <del> print(type(urlpattern)) <ide> regex = urlpattern.regex.pattern <ide> namespace = urlpattern.namespace <ide> app_name = urlpattern.app_name
1
Java
Java
fix javadocs broken by google-java-format
cd05a85fe5d056cd617ee6b5d82becab57e9c412
<ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactIntegrationTestCase.java <ide> * <p>Keep in mind that all JS remote method calls and script load calls are asynchronous and you <ide> * should not expect them to return results immediately. <ide> * <del> * <p>In order to write catalyst integration: 1) Make {@link ReactIntegrationTestCase} a base class <del> * of your test case 2) Use {@link ReactTestHelper#catalystInstanceBuilder()} instead of {@link <del> * com.facebook.react.bridge.CatalystInstanceImpl.Builder} to build catalyst instance for testing <del> * purposes <add> * <p>In order to write catalyst integration: <add> * <add> * <ol> <add> * <li>Make {@link ReactIntegrationTestCase} a base class of your test case <add> * <li>Use {@link ReactTestHelper#catalystInstanceBuilder()} instead of {@link <add> * com.facebook.react.bridge.CatalystInstanceImpl.Builder} to build catalyst instance for <add> * testing purposes <add> * </ol> <ide> */ <ide> public abstract class ReactIntegrationTestCase extends AndroidTestCase { <ide> <ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystMeasureLayoutTest.java <ide> * UIManagerModule#measureLayoutRelativeToParent}. Tests measurement for views in the following <ide> * hierarchy: <ide> * <del> * <p>+---------------------------------------------+ | A | | | | +-----------+ +---------+ | | | B <del> * | | D | | | | +---+ | | | | | | | C | | | | | | | | | | +---------+ | | | +---+ | | | <del> * +-----------+ | | | | | | | +---------------------------------------------+ <add> * <pre> <add> * +---------------------------------------------+ <add> * | A | <add> * | | <add> * | +-----------+ +---------+ | <add> * | | B | | D | | <add> * | | +---+ | | | | <add> * | | | C | | | | | <add> * | | | | | +---------+ | <add> * | | +---+ | | <add> * | +-----------+ | <add> * | | <add> * | | <add> * | | <add> * +---------------------------------------------+ <add> * </pre> <ide> * <ide> * <p>View locations and dimensions: A - (0,0) to (500, 500) (500x500) B - (50,80) to (250, 380) <ide> * (200x300) C - (150,150) to (200, 300) (50x150) D - (400,100) to (450, 300) (50x200) <ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystMultitouchHandlingTestCase.java <ide> public void run() { <ide> * This method "replay" multi-touch gesture recorded with modified TouchesHelper class that <ide> * generated this piece of code (see https://phabricator.fb.com/P19756940). This is not intended <ide> * to be copied/reused and once we need to have more multitouch gestures in instrumentation tests <del> * we should either: - implement nice generator similar to {@link SingleTouchGestureGenerator} - <del> * implement gesture recorded that will record touch data using arbitrary format and then read <del> * this recorded touch sequence during tests instead of generating code like this <add> * we should either: <add> * <add> * <ul> <add> * <li>implement nice generator similar to {@link SingleTouchGestureGenerator} <add> * <li>implement gesture recorded that will record touch data using arbitrary format and then <add> * read this recorded touch sequence during tests instead of generating code like this <add> * </ul> <ide> */ <ide> private void generateRecordedPinchTouchEvents() { <ide> // START OF GENERATED CODE <ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystSubviewsClippingTestCase.java <ide> protected ReactInstanceSpecForTest createReactInstanceSpecForTest() { <ide> } <ide> <ide> /** <del> * In this test view are layout in a following way: +-----------------------------+ | | | <del> * +---------------------+ | | | inner1 | | | +---------------------+ | | <del> * +-------------------------+ | | | outer (clip=true) | | | | +---------------------+ | | | | | <del> * inner2 | | | | | +---------------------+ | | | | | | | +-------------------------+ | | <del> * +---------------------+ | | | inner3 | | | +---------------------+ | | | <add> * In this test view are layout in a following way: <add> * <add> * <pre> <add> * +-----------------------------+ <add> * | | <add> * | +---------------------+ | <add> * | | inner1 | | <add> * | +---------------------+ | <add> * | +-------------------------+ | <add> * | | outer (clip=true) | | <add> * | | +---------------------+ | | <add> * | | | inner2 | | | <add> * | | +---------------------+ | | <add> * | | | | <add> * | +-------------------------+ | <add> * | +---------------------+ | <add> * | | inner3 | | <add> * | +---------------------+ | <add> * | | <ide> * +-----------------------------+ <add> * </pre> <ide> * <ide> * <p>We expect only outer and inner2 to be attached <ide> */ <ide> public void XtestOneLevelClippingInView() throws Throwable { <ide> } <ide> <ide> /** <del> * In this test view are layout in a following way: +-----------------------------+ | outer <del> * (clip=true) | | | | | | | | +-----------------------------+ | | complexInner (clip=true) | | | <del> * +----------+ | +---------+ | | | | inner1 | | | inner2 | | | | | | | | | | | | +----------+ | <del> * +---------+ | +--------------+--------------+ | | +----------+ +---------+ | | | inner3 | | <del> * inner4 | | | | | | | | | +----------+ +---------+ | | | +-----------------------------+ <add> * In this test view are layout in a following way: <add> * <add> * <pre> <add> * In this test view are layout in a following way: <add> * +-----------------------------+ <add> * | outer (clip=true) | <add> * | | <add> * | | <add> * | | <add> * | +-----------------------------+ <add> * | | complexInner (clip=true) | <add> * | | +----------+ | +---------+ | <add> * | | | inner1 | | | inner2 | | <add> * | | | | | | | | <add> * | | +----------+ | +---------+ | <add> * +--------------+--------------+ | <add> * | +----------+ +---------+ | <add> * | | inner3 | | inner4 | | <add> * | | | | | | <add> * | +----------+ +---------+ | <add> * | | <add> * +-----------------------------+ <add> * </pre> <ide> * <ide> * <p>We expect outer, complexInner & inner1 to be attached <ide> */ <ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystTouchBubblingTestCase.java <ide> * This test is to verify that touch events bubbles up to the right handler. We emulate couple of <ide> * different gestures on top of the application reflecting following layout: <ide> * <del> * <p>+---------------------------------------------------------------------------------------+ | | <del> * | +----------------------------------------------------------------------------------+ | | | <del> * +-------------+ +----------------+ | | | | | +---+ | | | | | | | | | A | | | | | | | | | +---+ | <del> * | C | | | | | | {B} | | | | | | | | | {D} | | | | | | +-------------+ +----------------+ | | | | <del> * | | | | | | | <del> * +----------------------------------------------------------------------------------+ | | | <del> * +----------------------------------------------------------------------------------+ | | | | | | <del> * | | | | | | | | | {E} | | | | | | | | | | | <del> * +----------------------------------------------------------------------------------+ | <add> * <pre> <ide> * +---------------------------------------------------------------------------------------+ <add> * | | <add> * | +----------------------------------------------------------------------------------+ | <add> * | | +-------------+ +----------------+ | | <add> * | | | +---+ | | | | | <add> * | | | | A | | | | | | <add> * | | | +---+ | | C | | | <add> * | | | {B} | | | | | <add> * | | | | {D} | | | | <add> * | | +-------------+ +----------------+ | | <add> * | | | | <add> * | | | | <add> * | +----------------------------------------------------------------------------------+ | <add> * | <add> * | +----------------------------------------------------------------------------------+ | <add> * | | | | <add> * | | | | <add> * | | | | <add> * | | {E} | | <add> * | | | | <add> * | | | | <add> * | +----------------------------------------------------------------------------------+ | <add> * +---------------------------------------------------------------------------------------+ <add> * </pre> <ide> * <ide> * <p>Then in each test case we either tap the center of a particular view (from A to E) or we start <ide> * a gesture in one view and end it with another. View with names in brackets (e.g. {D}) have touch <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactPackage.java <ide> <ide> /** <ide> * Main interface for providing additional capabilities to the catalyst framework by couple of <del> * different means: 1) Registering new native modules 2) Registering new JS modules that may be <del> * accessed from native modules or from other parts of the native code (requiring JS modules from <del> * the package doesn't mean it will automatically be included as a part of the JS bundle, so there <del> * should be a corresponding piece of code on JS side that will require implementation of that JS <del> * module so that it gets bundled) 3) Registering custom native views (view managers) and custom <del> * event types 4) Registering natively packaged assets/resources (e.g. images) exposed to JS <add> * different means: <add> * <add> * <ol> <add> * <li>Registering new native modules <add> * <li>Registering new JS modules that may be accessed from native modules or from other parts of <add> * the native code (requiring JS modules from the package doesn't mean it will automatically <add> * be included as a part of the JS bundle, so there should be a corresponding piece of code on <add> * JS side that will require implementation of that JS module so that it gets bundled) <add> * <li>Registering custom native views (view managers) and custom event types <add> * <li>Registering natively packaged assets/resources (e.g. images) exposed to JS <add> * </ol> <ide> * <ide> * <p>TODO(6788500, 6788507): Implement support for adding custom views, events and resources <ide> */ <ide><path>ReactAndroid/src/main/java/com/facebook/react/animated/NativeAnimatedModule.java <ide> * operations (such as interpolation, addition, etc) and connection are used to describe how change <ide> * of the value in one node can affect other nodes. <ide> * <del> * <p>Few examples of the nodes that can be created on the JS side: - Animated.Value is a simplest <del> * type of node with a numeric value which can be driven by an animation engine (spring, decay, etc) <del> * or by calling setValue on it directly from JS - Animated.add is a type of node that may have two <del> * or more input nodes. It outputs the sum of all the input node values - interpolate - is actually <del> * a method you can call on any node and it creates a new node that takes the parent node as an <del> * input and outputs its interpolated value (e.g. if you have value that can animate from 0 to 1 you <del> * can create interpolated node and set output range to be 0 to 100 and when the input node changes <del> * the output of interpolated node will multiply the values by 100) <add> * <p>Few examples of the nodes that can be created on the JS side: <add> * <add> * <ul> <add> * <li>Animated.Value is a simplest type of node with a numeric value which can be driven by an <add> * animation engine (spring, decay, etc) or by calling setValue on it directly from JS <add> * <li>Animated.add is a type of node that may have two or more input nodes. It outputs the sum of <add> * all the input node values <add> * <li>interpolate - is actually a method you can call on any node and it creates a new node that <add> * takes the parent node as an input and outputs its interpolated value (e.g. if you have <add> * value that can animate from 0 to 1 you can create interpolated node and set output range to <add> * be 0 to 100 and when the input node changes the output of interpolated node will multiply <add> * the values by 100) <add> * </ul> <ide> * <ide> * <p>You can mix and chain nodes however you like and this way create nodes graph with connections <ide> * between them. <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/BaseJavaModule.java <ide> * occurs. <ide> * <ide> * <p>Native methods can be exposed to JS with {@link ReactMethod} annotation. Those methods may <del> * only use limited number of types for their arguments: 1/ primitives (boolean, int, float, double <del> * 2/ {@link String} mapped from JS string 3/ {@link ReadableArray} mapped from JS Array 4/ {@link <del> * ReadableMap} mapped from JS Object 5/ {@link Callback} mapped from js function and can be used <del> * only as a last parameter or in the case when it express success & error callback pair as two last <del> * arguments respectively. <add> * only use limited number of types for their arguments: <add> * <add> * <ol> <add> * <li>primitives (boolean, int, float, double <add> * <li>{@link String} mapped from JS string <add> * <li>{@link ReadableArray} mapped from JS Array <add> * <li>{@link ReadableMap} mapped from JS Object <add> * <li>{@link Callback} mapped from js function and can be used only as a last parameter or in the <add> * case when it express success & error callback pair as two last arguments respectively. <add> * </ol> <ide> * <ide> * <p>All methods exposed as native to JS with {@link ReactMethod} annotation must return {@code <ide> * void}. <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/JSApplicationCausedNativeException.java <ide> * app outside of this catalyst instance still in a good state to allow reloading and restarting <ide> * this catalyst instance? <ide> * <del> * <p>Examples where this class is appropriate to throw: - JS tries to update a view with a tag that <del> * hasn't been created yet - JS tries to show a static image that isn't in resources - JS tries to <del> * use an unsupported view class <add> * <p>Examples where this class is appropriate to throw: <add> * <add> * <ul> <add> * <li>JS tries to update a view with a tag that hasn't been created yet <add> * <li>JS tries to show a static image that isn't in resources <add> * <li>JS tries to use an unsupported view class <add> * </ul> <ide> * <ide> * <p>Examples where this class **isn't** appropriate to throw: - Failed to write to localStorage <ide> * because disk is full - Assertions about internal state (e.g. that <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/LifecycleEventListener.java <ide> * <p>When multiple activities share a react instance, only the most recent one's lifecycle events <ide> * get forwarded to listeners. Consider the following scenarios: <ide> * <del> * <p>1. Navigating from Activity A to B will trigger two events: A#onHostPause and B#onHostResume. <del> * Any subsequent lifecycle events coming from Activity A, such as onHostDestroy, will be ignored. <del> * 2. Navigating back from Activity B to Activity A will trigger the same events: B#onHostPause and <del> * A#onHostResume. Any subsequent events coming from Activity B, such as onHostDestroy, are ignored. <del> * 3. Navigating back from Activity A to a non-React Activity or to the home screen will trigger two <del> * events: onHostPause and onHostDestroy. 4. Navigating from Activity A to a non-React Activity B <del> * will trigger one event: onHostPause. Later, if Activity A is destroyed (e.g. because of resource <del> * contention), onHostDestroy is triggered. <add> * <ol> <add> * <li>Navigating from Activity A to B will trigger two events: A#onHostPause and B#onHostResume. <add> * Any subsequent lifecycle events coming from Activity A, such as onHostDestroy, will be <add> * ignored. <add> * <li>Navigating back from Activity B to Activity A will trigger the same events: B#onHostPause <add> * and A#onHostResume. Any subsequent events coming from Activity B, such as onHostDestroy, <add> * are ignored. <add> * <li>Navigating back from Activity A to a non-React Activity or to the home screen will trigger <add> * two events: onHostPause and onHostDestroy. <add> * <li>Navigating from Activity A to a non-React Activity B will trigger one event: onHostPause. <add> * Later, if Activity A is destroyed (e.g. because of resource contention), onHostDestroy is <add> * triggered. <add> * </ol> <ide> */ <ide> public interface LifecycleEventListener { <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/DevServerHelper.java <ide> * <ide> * <p>One can use 'debug_http_host' shared preferences key to provide a host name for the debug <ide> * server. If the setting is empty we support and detect two basic configuration that works well for <del> * android emulators connection to debug server running on emulator's host: - Android stock emulator <del> * with standard non-configurable local loopback alias: 10.0.2.2, - Genymotion emulator with default <del> * settings: 10.0.3.2 <add> * android emulators connection to debug server running on emulator's host: <add> * <add> * <ul> <add> * <li>Android stock emulator with standard non-configurable local loopback alias: 10.0.2.2 <add> * <li>Genymotion emulator with default settings: 10.0.3.2 <add> * </ul> <ide> */ <ide> public class DevServerHelper { <ide> public static final String RELOAD_APP_EXTRA_JS_PROXY = "jsproxy"; <ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/debug/DidJSUpdateUiDuringFrameDetector.java <ide> public synchronized void onViewHierarchyUpdateFinished() { <ide> * <p>There are two 'success' cases that will cause {@link #getDidJSHitFrameAndCleanup} to return <ide> * true for a given frame: <ide> * <del> * <p>1) UIManagerModule finished dispatching a batched UI update on the UI thread during the <del> * frame. This means that during the next hierarchy traversal, new UI will be drawn if needed <del> * (good). 2) The bridge ended the frame idle (meaning there were no JS nor native module calls <del> * still in flight) AND there was no UiManagerModule update enqueued that didn't also finish. NB: <del> * if there was one enqueued that actually finished, we'd have case 1), so effectively we just <del> * look for whether one was enqueued. <add> * <ol> <add> * <li>UIManagerModule finished dispatching a batched UI update on the UI thread during the <add> * frame. This means that during the next hierarchy traversal, new UI will be drawn if <add> * needed (good). <add> * <li>The bridge ended the frame idle (meaning there were no JS nor native module calls still <add> * in flight) AND there was no UiManagerModule update enqueued that didn't also finish. NB: <add> * if there was one enqueued that actually finished, we'd have case 1), so effectively we <add> * just look for whether one was enqueued. <add> * </ol> <ide> * <ide> * <p>NB: This call can only be called once for a given frame time range because it cleans up <ide> * events it recorded for that frame. <ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/i18nmanager/I18nUtil.java <ide> public static I18nUtil getInstance() { <ide> } <ide> <ide> /** <del> * Check if the device is currently running on an RTL locale. This only happens when the app: - is <del> * forcing RTL layout, regardless of the active language (for development purpose) - allows RTL <del> * layout when using RTL locale <add> * Check if the device is currently running on an RTL locale. This only happens when the app: <add> * <add> * <ul> <add> * <li>is forcing RTL layout, regardless of the active language (for development purpose) <add> * <li>allows RTL layout when using RTL locale <add> * </ul> <ide> */ <ide> public boolean isRTL(Context context) { <ide> if (isRTLForced(context)) { <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/NativeViewHierarchyManager.java <ide> /** <ide> * Delegate of {@link UIManagerModule} that owns the native view hierarchy and mapping between <ide> * native view names used in JS and corresponding instances of {@link ViewManager}. The {@link <del> * UIManagerModule} communicates with this class by it's public interface methods: - {@link <del> * #updateProperties} - {@link #updateLayout} - {@link #createView} - {@link #manageChildren} <add> * UIManagerModule} communicates with this class by it's public interface methods: <add> * <add> * <ul> <add> * <li>{@link #updateProperties} <add> * <li>{@link #updateLayout} <add> * <li>{@link #createView} <add> * <li>{@link #manageChildren} <add> * </ul> <add> * <ide> * executing all the scheduled UI operations at the end of JS batch. <ide> * <ide> * <p>NB: All native view management methods listed above must be called from the UI thread. <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManager.java <ide> public void receiveCommand(@Nonnull T root, String commandId, @Nullable Readable <ide> * native views. This should return bubbling directly-dispatched event types and specify what <ide> * names should be used to subscribe to either form (bubbling/capturing). <ide> * <del> * <p>Returned map should be of the form: { "onTwirl": { "phasedRegistrationNames": { "bubbled": <del> * "onTwirl", "captured": "onTwirlCaptured" } } } <add> * <p>Returned map should be of the form: <add> * <add> * <pre> <add> * { <add> * "onTwirl": { <add> * "phasedRegistrationNames": { <add> * "bubbled": "onTwirl", <add> * "captured": "onTwirlCaptured" <add> * } <add> * } <add> * } <add> * </pre> <ide> */ <ide> public @Nullable Map<String, Object> getExportedCustomBubblingEventTypeConstants() { <ide> return null; <ide> public void receiveCommand(@Nonnull T root, String commandId, @Nullable Readable <ide> * Returns a map of config data passed to JS that defines eligible events that can be placed on <ide> * native views. This should return non-bubbling directly-dispatched event types. <ide> * <del> * <p>Returned map should be of the form: { "onTwirl": { "registrationName": "onTwirl" } } <add> * <p>Returned map should be of the form: <add> * <add> * <pre> <add> * { <add> * "onTwirl": { <add> * "registrationName": "onTwirl" <add> * } <add> * } <add> * </pre> <ide> */ <ide> public @Nullable Map<String, Object> getExportedCustomDirectEventTypeConstants() { <ide> return null; <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/annotations/ReactProp.java <ide> * <p>Each annotated method should return {@code void} and take exactly two arguments: first being a <ide> * view instance to be updated and second a value that should be set. <ide> * <del> * <p>Allowed types of values are: - primitives (int, boolean, double, float) - {@link String} - <del> * {@link Boolean} - {@link com.facebook.react.bridge.ReadableArray} - {@link <del> * com.facebook.react.bridge.ReadableMap} <add> * <p>Allowed types of values are: <add> * <add> * <ul> <add> * <li>primitives (int, boolean, double, float) <add> * <li>{@link String} <add> * <li>{@link Boolean} <add> * <li>{@link com.facebook.react.bridge.ReadableArray} <add> * <li>{@link com.facebook.react.bridge.ReadableMap} <add> * </ul> <ide> * <ide> * <p>When property gets removed from the corresponding component in React, annotated setter will be <ide> * called with {@code null} in case of non-primitive value type or with a default value in case when <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostView.java <ide> /** <ide> * ReactModalHostView is a view that sits in the view hierarchy representing a Modal view. <ide> * <del> * <p>It does a number of things: 1. It creates a Dialog. We use this Dialog to actually display the <del> * Modal in the window. 2. It creates a DialogRootViewGroup. This view is the view that is displayed <del> * by the Dialog. To display a view within a Dialog, that view must have its parent set to the <del> * window the Dialog creates. Because of this, we can not use the ReactModalHostView since it sits <del> * in the normal React view hierarchy. We do however want all of the layout magic to happen as if <del> * the DialogRootViewGroup were part of the hierarchy. Therefore, we forward all view changes around <del> * addition and removal of views to the DialogRootViewGroup. <add> * <p>It does a number of things: <add> * <add> * <ol> <add> * <li>It creates a Dialog. We use this Dialog to actually display the Modal in the window. <add> * <li>It creates a DialogRootViewGroup. This view is the view that is displayed by the Dialog. To <add> * display a view within a Dialog, that view must have its parent set to the window the Dialog <add> * creates. Because of this, we can not use the ReactModalHostView since it sits in the normal <add> * React view hierarchy. We do however want all of the layout magic to happen as if the <add> * DialogRootViewGroup were part of the hierarchy. Therefore, we forward all view changes <add> * around addition and removal of views to the DialogRootViewGroup. <add> * </ol> <ide> */ <ide> public class ReactModalHostView extends ViewGroup implements LifecycleEventListener { <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/ReactBaseTextShadowNode.java <ide> private static int parseNumericFontWeight(String fontWeightString) { <ide> /** <ide> * NB: If a font family is used that does not have a style in a certain Android version (ie. <ide> * monospace bold pre Android 5.0), that style (ie. bold) will not be inherited by nested Text <del> * nodes. To retain that style, you have to add it to those nodes explicitly. Example, Android <del> * 4.4: <Text style={{fontFamily="serif" fontWeight="bold"}}>Bold Text</Text> <Text <del> * style={{fontFamily="sans-serif"}}>Bold Text</Text> <Text style={{fontFamily="serif}}>Bold <del> * Text</Text> <add> * nodes. To retain that style, you have to add it to those nodes explicitly. <ide> * <del> * <p><Text style={{fontFamily="monospace" fontWeight="bold"}}>Not Bold Text</Text> <Text <del> * style={{fontFamily="sans-serif"}}>Not Bold Text</Text> <Text style={{fontFamily="serif}}>Not <del> * Bold Text</Text> <add> * <p>Example, Android 4.4: <ide> * <del> * <p><Text style={{fontFamily="monospace" fontWeight="bold"}}>Not Bold Text</Text> <Text <del> * style={{fontFamily="sans-serif" fontWeight="bold"}}>Bold Text</Text> <Text <del> * style={{fontFamily="serif}}>Bold Text</Text> <add> * <pre> <add> * <Text style={{fontFamily="serif" fontWeight="bold"}}>Bold Text</Text> <add> * <Text style={{fontFamily="sans-serif"}}>Bold Text</Text> <add> * <Text style={{fontFamily="serif}}>Bold Text</Text> <add> * <add> * <Text style={{fontFamily="monospace" fontWeight="bold"}}>Not Bold Text</Text> <add> * <Text style={{fontFamily="sans-serif"}}>Not Bold Text</Text> <add> * <Text style={{fontFamily="serif}}>Not Bold Text</Text> <add> * <add> * <Text style={{fontFamily="monospace" fontWeight="bold"}}>Not Bold Text</Text> <add> * <Text style={{fontFamily="sans-serif" fontWeight="bold"}}>Bold Text</Text> <add> * <Text style={{fontFamily="serif}}>Bold Text</Text> <add> * </pre> <ide> */ <ide> protected @Nullable String mFontFamily = null; <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/TextAttributeProps.java <ide> public class TextAttributeProps { <ide> /** <ide> * NB: If a font family is used that does not have a style in a certain Android version (ie. <ide> * monospace bold pre Android 5.0), that style (ie. bold) will not be inherited by nested Text <del> * nodes. To retain that style, you have to add it to those nodes explicitly. Example, Android <del> * 4.4: <Text style={{fontFamily="serif" fontWeight="bold"}}>Bold Text</Text> <Text <del> * style={{fontFamily="sans-serif"}}>Bold Text</Text> <Text style={{fontFamily="serif}}>Bold <del> * Text</Text> <add> * nodes. To retain that style, you have to add it to those nodes explicitly. <ide> * <del> * <p><Text style={{fontFamily="monospace" fontWeight="bold"}}>Not Bold Text</Text> <Text <del> * style={{fontFamily="sans-serif"}}>Not Bold Text</Text> <Text style={{fontFamily="serif}}>Not <del> * Bold Text</Text> <add> * <p>Example, Android 4.4: <ide> * <del> * <p><Text style={{fontFamily="monospace" fontWeight="bold"}}>Not Bold Text</Text> <Text <del> * style={{fontFamily="sans-serif" fontWeight="bold"}}>Bold Text</Text> <Text <del> * style={{fontFamily="serif}}>Bold Text</Text> <add> * <pre> <add> * <Text style={{fontFamily="serif" fontWeight="bold"}}>Bold Text</Text> <add> * <Text style={{fontFamily="sans-serif"}}>Bold Text</Text> <add> * <Text style={{fontFamily="serif}}>Bold Text</Text> <add> * <add> * <Text style={{fontFamily="monospace" fontWeight="bold"}}>Not Bold Text</Text> <add> * <Text style={{fontFamily="sans-serif"}}>Not Bold Text</Text> <add> * <Text style={{fontFamily="serif}}>Not Bold Text</Text> <add> * <add> * <Text style={{fontFamily="monospace" fontWeight="bold"}}>Not Bold Text</Text> <add> * <Text style={{fontFamily="sans-serif" fontWeight="bold"}}>Bold Text</Text> <add> * <Text style={{fontFamily="serif}}>Bold Text</Text> <add> * </pre> <ide> */ <ide> protected @Nullable String mFontFamily = null; <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/viewpager/PageScrollEvent.java <ide> * Event emitted by {@link ReactViewPager} when user scrolls between pages (or when animating <ide> * between pages). <ide> * <del> * <p>Additional data provided by this event: - position - index of first page from the left that is <del> * currently visible - offset - value from range [0,1) describing stage between page transitions. <del> * Value x means that (1 - x) fraction of the page at "position" index is visible, and x fraction of <del> * the next page is visible. <add> * <p>Additional data provided by this event: <add> * <add> * <ul> <add> * <li>position - index of first page from the left that is currently visible <add> * <li>offset - value from range [0,1) describing stage between page transitions. Value x means <add> * that (1 - x) fraction of the page at "position" index is visible, and x fraction of the <add> * next page is visible. <add> * </ul> <ide> */ <ide> /* package */ class PageScrollEvent extends Event<PageScrollEvent> { <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/viewpager/PageScrollStateChangedEvent.java <ide> /** <ide> * Event emitted by {@link ReactViewPager} when user scrolling state changed. <ide> * <del> * <p>Additional data provided by this event: - pageScrollState - {Idle,Dragging,Settling} <add> * <p>Additional data provided by this event: <add> * <add> * <ul> <add> * <li>pageScrollState - {Idle,Dragging,Settling} <add> * </ul> <ide> */ <ide> class PageScrollStateChangedEvent extends Event<PageScrollStateChangedEvent> { <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/viewpager/PageSelectedEvent.java <ide> /** <ide> * Event emitted by {@link ReactViewPager} when selected page changes. <ide> * <del> * <p>Additional data provided by this event: - position - index of page that has been selected <add> * <p>Additional data provided by this event: <add> * <add> * <ul> <add> * <li>position - index of page that has been selected <add> * </ul> <ide> */ <ide> /* package */ class PageSelectedEvent extends Event<PageSelectedEvent> { <ide>
22
Go
Go
remove error return from rootpair
93fbdb69acf9248283a91a1c5c6ea24711c26eda
<ide><path>daemon/archive.go <ide> func (daemon *Daemon) CopyOnBuild(cID, destPath, srcRoot, srcPath string, decomp <ide> <ide> destExists := true <ide> destDir := false <del> rootIDs, _ := daemon.idMappings.RootPair() <add> rootIDs := daemon.idMappings.RootPair() <ide> <ide> // Work in daemon-local OS specific file paths <ide> destPath = filepath.FromSlash(destPath) <ide><path>daemon/container_operations_unix.go <ide> func (daemon *Daemon) setupIpcDirs(c *container.Container) error { <ide> } <ide> c.ShmPath = "/dev/shm" <ide> } else { <del> rootIDs, _ := daemon.idMappings.RootPair() <add> rootIDs := daemon.idMappings.RootPair() <ide> if !c.HasMountFor("/dev/shm") { <ide> shmPath, err := c.ShmResourcePath() <ide> if err != nil { <ide> func (daemon *Daemon) setupSecretDir(c *container.Container) (setupErr error) { <ide> logrus.Debugf("secrets: setting up secret dir: %s", localMountPath) <ide> <ide> // retrieve possible remapped range start for root UID, GID <del> rootIDs, _ := daemon.idMappings.RootPair() <add> rootIDs := daemon.idMappings.RootPair() <ide> // create tmpfs <ide> if err := idtools.MkdirAllAndChown(localMountPath, 0700, rootIDs); err != nil { <ide> return errors.Wrap(err, "error creating secret local mount path") <ide> func (daemon *Daemon) setupConfigDir(c *container.Container) (setupErr error) { <ide> logrus.Debugf("configs: setting up config dir: %s", localPath) <ide> <ide> // retrieve possible remapped range start for root UID, GID <del> rootIDs, _ := daemon.idMappings.RootPair() <add> rootIDs := daemon.idMappings.RootPair() <ide> // create tmpfs <ide> if err := idtools.MkdirAllAndChown(localPath, 0700, rootIDs); err != nil { <ide> return errors.Wrap(err, "error creating config dir") <ide><path>daemon/create.go <ide> func (daemon *Daemon) create(params types.ContainerCreateConfig, managed bool) ( <ide> return nil, err <ide> } <ide> <del> rootIDs, err := daemon.idMappings.RootPair() <del> if err != nil { <del> return nil, err <del> } <add> rootIDs := daemon.idMappings.RootPair() <ide> if err := idtools.MkdirAndChown(container.Root, 0700, rootIDs); err != nil { <ide> return nil, err <ide> } <ide><path>daemon/create_unix.go <ide> func (daemon *Daemon) createContainerPlatformSpecificSettings(container *contain <ide> } <ide> defer daemon.Unmount(container) <ide> <del> rootIDs, _ := daemon.idMappings.RootPair() <add> rootIDs := daemon.idMappings.RootPair() <ide> if err := container.SetupWorkingDirectory(rootIDs); err != nil { <ide> return err <ide> } <ide><path>daemon/daemon.go <ide> func NewDaemon(config *config.Config, registryService registry.Service, containe <ide> if err != nil { <ide> return nil, err <ide> } <del> rootIDs, err := idMappings.RootPair() <del> if err != nil { <del> return nil, err <del> } <del> <add> rootIDs := idMappings.RootPair() <ide> if err := setupDaemonProcess(config); err != nil { <ide> return nil, err <ide> } <ide> func prepareTempDir(rootDir string, rootIDs idtools.IDPair) (string, error) { <ide> } <ide> <ide> func (daemon *Daemon) setupInitLayer(initPath string) error { <del> rootIDs, _ := daemon.idMappings.RootPair() <add> rootIDs := daemon.idMappings.RootPair() <ide> return initlayer.Setup(initPath, rootIDs) <ide> } <ide> <ide> func CreateDaemonRoot(config *config.Config) error { <ide> if err != nil { <ide> return err <ide> } <del> rootIDs, err := idMappings.RootPair() <del> if err != nil { <del> return err <del> } <del> <del> if err := setupDaemonRoot(config, realRoot, rootIDs); err != nil { <del> return err <del> } <del> <del> return nil <add> return setupDaemonRoot(config, realRoot, idMappings.RootPair()) <ide> } <ide><path>daemon/graphdriver/vfs/driver.go <ide> func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (grap <ide> home: home, <ide> idMappings: idtools.NewIDMappingsFromMaps(uidMaps, gidMaps), <ide> } <del> rootIDs, err := d.idMappings.RootPair() <del> if err != nil { <del> return nil, err <del> } <add> rootIDs := d.idMappings.RootPair() <ide> if err := idtools.MkdirAllAndChown(home, 0700, rootIDs); err != nil { <ide> return nil, err <ide> } <ide> func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) error { <ide> } <ide> <ide> dir := d.dir(id) <del> rootIDs, err := d.idMappings.RootPair() <del> if err != nil { <del> return err <del> } <add> rootIDs := d.idMappings.RootPair() <ide> if err := idtools.MkdirAllAndChown(filepath.Dir(dir), 0700, rootIDs); err != nil { <ide> return err <ide> } <ide><path>daemon/info.go <ide> func (daemon *Daemon) SystemInfo() (*types.Info, error) { <ide> if selinuxEnabled() { <ide> securityOptions = append(securityOptions, "name=selinux") <ide> } <del> rootIDs, _ := daemon.idMappings.RootPair() <add> rootIDs := daemon.idMappings.RootPair() <ide> if rootIDs.UID != 0 || rootIDs.GID != 0 { <ide> securityOptions = append(securityOptions, "name=userns") <ide> } <ide><path>daemon/oci_linux.go <ide> func (daemon *Daemon) populateCommonSpec(s *specs.Spec, c *container.Container) <ide> Path: c.BaseFS, <ide> Readonly: c.HostConfig.ReadonlyRootfs, <ide> } <del> rootIDs, _ := daemon.idMappings.RootPair() <del> if err := c.SetupWorkingDirectory(rootIDs); err != nil { <add> if err := c.SetupWorkingDirectory(daemon.idMappings.RootPair()); err != nil { <ide> return err <ide> } <ide> cwd := c.Config.WorkingDir <ide><path>daemon/oci_solaris.go <ide> func (daemon *Daemon) populateCommonSpec(s *specs.Spec, c *container.Container) <ide> Path: filepath.Dir(c.BaseFS), <ide> Readonly: c.HostConfig.ReadonlyRootfs, <ide> } <del> rootIDs, _ := daemon.idMappings.RootPair() <del> if err := c.SetupWorkingDirectory(rootIDs); err != nil { <add> if err := c.SetupWorkingDirectory(daemon.idMappings.RootPair()); err != nil { <ide> return err <ide> } <ide> cwd := c.Config.WorkingDir <ide><path>daemon/volumes_unix.go <ide> func (daemon *Daemon) setupMounts(c *container.Container) ([]container.Mount, er <ide> return nil <ide> } <ide> <del> rootIDs, _ := daemon.idMappings.RootPair() <del> path, err := m.Setup(c.MountLabel, rootIDs, checkfunc) <add> path, err := m.Setup(c.MountLabel, daemon.idMappings.RootPair(), checkfunc) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func (daemon *Daemon) setupMounts(c *container.Container) ([]container.Mount, er <ide> // if we are going to mount any of the network files from container <ide> // metadata, the ownership must be set properly for potential container <ide> // remapped root (user namespaces) <del> rootIDs, _ := daemon.idMappings.RootPair() <add> rootIDs := daemon.idMappings.RootPair() <ide> for _, mount := range netMounts { <ide> if err := os.Chown(mount.Source, rootIDs.UID, rootIDs.GID); err != nil { <ide> return nil, err <ide><path>daemon/workdir.go <ide> func (daemon *Daemon) ContainerCreateWorkdir(cID string) error { <ide> return err <ide> } <ide> defer daemon.Unmount(container) <del> rootIDs, _ := daemon.idMappings.RootPair() <del> return container.SetupWorkingDirectory(rootIDs) <add> return container.SetupWorkingDirectory(daemon.idMappings.RootPair()) <ide> } <ide><path>pkg/archive/archive.go <ide> func Unpack(decompressedArchive io.Reader, dest string, options *TarOptions) err <ide> <ide> var dirs []*tar.Header <ide> idMappings := idtools.NewIDMappingsFromMaps(options.UIDMaps, options.GIDMaps) <del> rootIDs, err := idMappings.RootPair() <del> if err != nil { <del> return err <del> } <add> rootIDs := idMappings.RootPair() <ide> whiteoutConverter := getWhiteoutConverter(options.WhiteoutFormat) <ide> <ide> // Iterate through the files in the archive. <ide> func (archiver *Archiver) CopyWithTar(src, dst string) error { <ide> // if this archiver is set up with ID mapping we need to create <ide> // the new destination directory with the remapped root UID/GID pair <ide> // as owner <del> rootIDs, err := archiver.IDMappings.RootPair() <del> if err != nil { <del> return err <del> } <add> rootIDs := archiver.IDMappings.RootPair() <ide> // Create dst, copy src's content into it <ide> logrus.Debugf("Creating dest directory: %s", dst) <ide> if err := idtools.MkdirAllAndChownNew(dst, 0755, rootIDs); err != nil { <ide><path>pkg/chrootarchive/archive.go <ide> func untarHandler(tarArchive io.Reader, dest string, options *archive.TarOptions <ide> } <ide> <ide> idMappings := idtools.NewIDMappingsFromMaps(options.UIDMaps, options.GIDMaps) <del> rootIDs, err := idMappings.RootPair() <del> if err != nil { <del> return err <del> } <add> rootIDs := idMappings.RootPair() <ide> <ide> dest = filepath.Clean(dest) <ide> if _, err := os.Stat(dest); os.IsNotExist(err) { <ide><path>pkg/idtools/idtools.go <ide> func NewIDMappingsFromMaps(uids []IDMap, gids []IDMap) *IDMappings { <ide> return &IDMappings{uids: uids, gids: gids} <ide> } <ide> <del>// RootPair returns a uid and gid pair for the root user <del>func (i *IDMappings) RootPair() (IDPair, error) { <del> uid, gid, err := GetRootUIDGID(i.uids, i.gids) <del> return IDPair{UID: uid, GID: gid}, err <add>// RootPair returns a uid and gid pair for the root user. The error is ignored <add>// because a root user always exists, and the defaults are correct when the uid <add>// and gid maps are empty. <add>func (i *IDMappings) RootPair() IDPair { <add> uid, gid, _ := GetRootUIDGID(i.uids, i.gids) <add> return IDPair{UID: uid, GID: gid} <ide> } <ide> <ide> // ToHost returns the host UID and GID for the container uid, gid. <ide> // Remapping is only performed if the ids aren't already the remapped root ids <ide> func (i *IDMappings) ToHost(pair IDPair) (IDPair, error) { <del> target, err := i.RootPair() <del> if err != nil { <del> return IDPair{}, err <del> } <add> var err error <add> target := i.RootPair() <ide> <ide> if pair.UID != target.UID { <ide> target.UID, err = toHost(pair.UID, i.uids)
14
Python
Python
remove debug statement
ebee0a27940adfbb30444d83387b9ea0f1173f40
<ide><path>utils/tests_fetcher.py <ide> def filter_tests(output_file, filters): <ide> print("No tests to filter.") <ide> return <ide> <del> print(test_files) <ide> if test_files == ["tests"]: <ide> test_files = [os.path.join("tests", f) for f in os.listdir("tests") if f not in ["__init__.py"] + filters] <ide> else:
1
Go
Go
preserve hardlinks in tar and untar
f9f80443638fc2d703ee6205c8ef3db8e38db9a3
<ide><path>integration-cli/docker_cli_commit_test.go <ide> func TestCommitNewFile(t *testing.T) { <ide> logDone("commit - commit file and read") <ide> } <ide> <add>func TestCommitHardlink(t *testing.T) { <add> cmd := exec.Command(dockerBinary, "run", "-t", "--name", "hardlinks", "busybox", "sh", "-c", "touch file1 && ln file1 file2 && ls -di file1 file2") <add> firstOuput, _, err := runCommandWithOutput(cmd) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> chunks := strings.Split(strings.TrimSpace(firstOuput), " ") <add> inode := chunks[0] <add> found := false <add> for _, chunk := range chunks[1:] { <add> if chunk == inode { <add> found = true <add> break <add> } <add> } <add> if !found { <add> t.Fatalf("Failed to create hardlink in a container. Expected to find %q in %q", inode, chunks[1:]) <add> } <add> <add> cmd = exec.Command(dockerBinary, "commit", "hardlinks", "hardlinks") <add> imageID, _, err := runCommandWithOutput(cmd) <add> if err != nil { <add> t.Fatal(imageID, err) <add> } <add> imageID = strings.Trim(imageID, "\r\n") <add> <add> cmd = exec.Command(dockerBinary, "run", "-t", "hardlinks", "ls", "-di", "file1", "file2") <add> secondOuput, _, err := runCommandWithOutput(cmd) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> chunks = strings.Split(strings.TrimSpace(secondOuput), " ") <add> inode = chunks[0] <add> found = false <add> for _, chunk := range chunks[1:] { <add> if chunk == inode { <add> found = true <add> break <add> } <add> } <add> if !found { <add> t.Fatalf("Failed to create hardlink in a container. Expected to find %q in %q", inode, chunks[1:]) <add> } <add> <add> deleteAllContainers() <add> deleteImages(imageID) <add> <add> logDone("commit - commit hardlinks") <add>} <add> <ide> func TestCommitTTY(t *testing.T) { <ide> cmd := exec.Command(dockerBinary, "run", "-t", "--name", "tty", "busybox", "/bin/ls") <ide> if _, err := runCommand(cmd); err != nil { <ide><path>pkg/archive/archive.go <ide> func (compression *Compression) Extension() string { <ide> return "" <ide> } <ide> <del>func addTarFile(path, name string, tw *tar.Writer, twBuf *bufio.Writer) error { <add>type tarAppender struct { <add> TarWriter *tar.Writer <add> Buffer *bufio.Writer <add> <add> // for hardlink mapping <add> SeenFiles map[uint64]string <add>} <add> <add>func (ta *tarAppender) addTarFile(path, name string) error { <ide> fi, err := os.Lstat(path) <ide> if err != nil { <ide> return err <ide> func addTarFile(path, name string, tw *tar.Writer, twBuf *bufio.Writer) error { <ide> <ide> } <ide> <add> // if it's a regular file and has more than 1 link, <add> // it's hardlinked, so set the type flag accordingly <add> if fi.Mode().IsRegular() && stat.Nlink > 1 { <add> // a link should have a name that it links too <add> // and that linked name should be first in the tar archive <add> ino := uint64(stat.Ino) <add> if oldpath, ok := ta.SeenFiles[ino]; ok { <add> hdr.Typeflag = tar.TypeLink <add> hdr.Linkname = oldpath <add> hdr.Size = 0 // This Must be here for the writer math to add up! <add> } else { <add> ta.SeenFiles[ino] = name <add> } <add> } <add> <ide> capability, _ := system.Lgetxattr(path, "security.capability") <ide> if capability != nil { <ide> hdr.Xattrs = make(map[string]string) <ide> hdr.Xattrs["security.capability"] = string(capability) <ide> } <ide> <del> if err := tw.WriteHeader(hdr); err != nil { <add> if err := ta.TarWriter.WriteHeader(hdr); err != nil { <ide> return err <ide> } <ide> <ide> func addTarFile(path, name string, tw *tar.Writer, twBuf *bufio.Writer) error { <ide> return err <ide> } <ide> <del> twBuf.Reset(tw) <del> _, err = io.Copy(twBuf, file) <add> ta.Buffer.Reset(ta.TarWriter) <add> _, err = io.Copy(ta.Buffer, file) <ide> file.Close() <ide> if err != nil { <ide> return err <ide> } <del> err = twBuf.Flush() <add> err = ta.Buffer.Flush() <ide> if err != nil { <ide> return err <ide> } <del> twBuf.Reset(nil) <add> ta.Buffer.Reset(nil) <ide> } <ide> <ide> return nil <ide> func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) <ide> return nil, err <ide> } <ide> <del> tw := tar.NewWriter(compressWriter) <del> <ide> go func() { <add> ta := &tarAppender{ <add> TarWriter: tar.NewWriter(compressWriter), <add> Buffer: pools.BufioWriter32KPool.Get(nil), <add> SeenFiles: make(map[uint64]string), <add> } <add> // this buffer is needed for the duration of this piped stream <add> defer pools.BufioWriter32KPool.Put(ta.Buffer) <add> <ide> // In general we log errors here but ignore them because <ide> // during e.g. a diff operation the container can continue <ide> // mutating the filesystem and we can see transient errors <ide> func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) <ide> options.Includes = []string{"."} <ide> } <ide> <del> twBuf := pools.BufioWriter32KPool.Get(nil) <del> defer pools.BufioWriter32KPool.Put(twBuf) <del> <ide> var renamedRelFilePath string // For when tar.Options.Name is set <ide> for _, include := range options.Includes { <ide> filepath.Walk(filepath.Join(srcPath, include), func(filePath string, f os.FileInfo, err error) error { <ide> func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) <ide> relFilePath = strings.Replace(relFilePath, renamedRelFilePath, options.Name, 1) <ide> } <ide> <del> if err := addTarFile(filePath, relFilePath, tw, twBuf); err != nil { <add> if err := ta.addTarFile(filePath, relFilePath); err != nil { <ide> log.Debugf("Can't add file %s to tar: %s", srcPath, err) <ide> } <ide> return nil <ide> }) <ide> } <ide> <ide> // Make sure to check the error on Close. <del> if err := tw.Close(); err != nil { <add> if err := ta.TarWriter.Close(); err != nil { <ide> log.Debugf("Can't close tar writer: %s", err) <ide> } <ide> if err := compressWriter.Close(); err != nil { <ide><path>pkg/archive/archive_test.go <ide> func TestUntarUstarGnuConflict(t *testing.T) { <ide> } <ide> } <ide> <add>func TestTarWithHardLink(t *testing.T) { <add> origin, err := ioutil.TempDir("", "docker-test-tar-hardlink") <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer os.RemoveAll(origin) <add> if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil { <add> t.Fatal(err) <add> } <add> if err := os.Link(path.Join(origin, "1"), path.Join(origin, "2")); err != nil { <add> t.Fatal(err) <add> } <add> <add> var i1, i2 uint64 <add> if i1, err = getNlink(path.Join(origin, "1")); err != nil { <add> t.Fatal(err) <add> } <add> // sanity check that we can hardlink <add> if i1 != 2 { <add> t.Skipf("skipping since hardlinks don't work here; expected 2 links, got %d", i1) <add> } <add> <add> dest, err := ioutil.TempDir("", "docker-test-tar-hardlink-dest") <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer os.RemoveAll(dest) <add> <add> // we'll do this in two steps to separate failure <add> fh, err := Tar(origin, Uncompressed) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> // ensure we can read the whole thing with no error, before writing back out <add> buf, err := ioutil.ReadAll(fh) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> bRdr := bytes.NewReader(buf) <add> err = Untar(bRdr, dest, &TarOptions{Compression: Uncompressed}) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> if i1, err = getInode(path.Join(dest, "1")); err != nil { <add> t.Fatal(err) <add> } <add> if i2, err = getInode(path.Join(dest, "2")); err != nil { <add> t.Fatal(err) <add> } <add> <add> if i1 != i2 { <add> t.Errorf("expected matching inodes, but got %d and %d", i1, i2) <add> } <add>} <add> <ide> func getNlink(path string) (uint64, error) { <ide> stat, err := os.Stat(path) <ide> if err != nil { <ide><path>pkg/archive/changes.go <ide> func minor(device uint64) uint64 { <ide> // ExportChanges produces an Archive from the provided changes, relative to dir. <ide> func ExportChanges(dir string, changes []Change) (Archive, error) { <ide> reader, writer := io.Pipe() <del> tw := tar.NewWriter(writer) <del> <ide> go func() { <del> twBuf := pools.BufioWriter32KPool.Get(nil) <del> defer pools.BufioWriter32KPool.Put(twBuf) <add> ta := &tarAppender{ <add> TarWriter: tar.NewWriter(writer), <add> Buffer: pools.BufioWriter32KPool.Get(nil), <add> SeenFiles: make(map[uint64]string), <add> } <add> // this buffer is needed for the duration of this piped stream <add> defer pools.BufioWriter32KPool.Put(ta.Buffer) <add> <ide> // In general we log errors here but ignore them because <ide> // during e.g. a diff operation the container can continue <ide> // mutating the filesystem and we can see transient errors <ide> func ExportChanges(dir string, changes []Change) (Archive, error) { <ide> AccessTime: timestamp, <ide> ChangeTime: timestamp, <ide> } <del> if err := tw.WriteHeader(hdr); err != nil { <add> if err := ta.TarWriter.WriteHeader(hdr); err != nil { <ide> log.Debugf("Can't write whiteout header: %s", err) <ide> } <ide> } else { <ide> path := filepath.Join(dir, change.Path) <del> if err := addTarFile(path, change.Path[1:], tw, twBuf); err != nil { <add> if err := ta.addTarFile(path, change.Path[1:]); err != nil { <ide> log.Debugf("Can't add file %s to tar: %s", path, err) <ide> } <ide> } <ide> } <ide> <ide> // Make sure to check the error on Close. <del> if err := tw.Close(); err != nil { <add> if err := ta.TarWriter.Close(); err != nil { <ide> log.Debugf("Can't close layer: %s", err) <ide> } <ide> writer.Close()
4
Text
Text
fix documentation nits
f070d784d61f59fc6f97e400ad2f9697acdf32ee
<ide><path>doc/api/errors.md <ide> been closed. <ide> <a id="ERR_HTTP2_STREAM_ERROR"></a> <ide> ### ERR_HTTP2_STREAM_ERROR <ide> <del>Used when a non-zero error code has been specified in an RST_STREAM frame. <add>Used when a non-zero error code has been specified in an `RST_STREAM` frame. <ide> <ide> <a id="ERR_HTTP2_STREAM_SELF_DEPENDENCY"></a> <ide> ### ERR_HTTP2_STREAM_SELF_DEPENDENCY <ide><path>doc/api/http2.md <ide> when: <ide> * A new HTTP/2 `HEADERS` frame with a previously unused stream ID is received; <ide> * The `http2stream.pushStream()` method is called. <ide> <del>On the client side, instances of [`ClientHttp2Stream`[] are created when the <add>On the client side, instances of [`ClientHttp2Stream`][] are created when the <ide> `http2session.request()` method is called. <ide> <ide> *Note*: On the client, the `Http2Stream` instance returned by <ide> added: REPLACEME <ide> * `settings` {[Settings Object][]} <ide> * Returns: {Buffer} <ide> <del>Returns a [Buffer][] instance containing serialized representation of the given <add>Returns a `Buffer` instance containing serialized representation of the given <ide> HTTP/2 settings as specified in the [HTTP/2][] specification. This is intended <ide> for use with the `HTTP2-Settings` header field. <ide> <ide> TBD <ide> [`net.Socket`]: net.html <ide> [`tls.TLSSocket`]: tls.html <ide> [`tls.createServer()`]: tls.html#tls_tls_createserver_options_secureconnectionlistener <del>[ClientHttp2Stream]: #http2_class_clienthttp2stream <del>[Compatibility API: #http2_compatibility_api <add>[`ClientHttp2Stream`]: #http2_class_clienthttp2stream <add>[Compatibility API]: #http2_compatibility_api <ide> [`Duplex`]: stream.html#stream_class_stream_duplex <ide> [Headers Object]: #http2_headers_object <del>[Http2Stream]: #http2_class_http2stream <add>[`Http2Stream`]: #http2_class_http2stream <ide> [Http2Session and Sockets]: #http2_http2sesion_and_sockets <del>[ServerHttp2Stream]: #http2_class_serverhttp2stream <add>[`ServerHttp2Stream`]: #http2_class_serverhttp2stream <ide> [Settings Object]: #http2_settings_object <ide> [Using options.selectPadding]: #http2_using_options_selectpadding <ide> [error code]: #error_codes <ide><path>doc/guides/writing-and-running-benchmarks.md <ide> benchmarker to be used should be specified by providing it as an argument: <ide> <ide> To run the `http2` benchmarks, the `h2load` benchmarker must be used. The <ide> `h2load` tool is a component of the `nghttp2` project and may be installed <del>from [nghttp.org][] or built from source. <add>from [nghttp2.org][] or built from source. <ide> <ide> `node benchmark/http2/simple.js benchmarker=autocannon` <ide>
3
Ruby
Ruby
improve load logic
6ac6cb4fcdc5c162543e14688d41c0b10a1b1e4a
<ide><path>Library/Homebrew/formulary.rb <ide> class TapLoader < FormulaLoader <ide> def initialize(tapped_name) <ide> user, repo, name = tapped_name.split("/", 3).map(&:downcase) <ide> @tap = Tap.fetch user, repo <del> name = @tap.formula_renames.fetch(name, name) <del> path = @tap.formula_files.detect { |file| file.basename(".rb").to_s == name } <add> formula_dir = @tap.formula_dir || @tap.path <add> path = formula_dir/"#{name}.rb" <ide> <del> unless path <add> unless path.file? <ide> if (possible_alias = @tap.alias_dir/name).file? <ide> path = possible_alias.resolved_path <ide> name = path.basename(".rb").to_s <del> else <del> path = @tap.path/"#{name}.rb" <add> elsif (new_name = @tap.formula_renames[name]) && <add> (new_path = formula_dir/"#{new_name}.rb").file? <add> path = new_path <add> name = new_name <ide> end <ide> end <ide>
1
Javascript
Javascript
return the loader after redirect
9337d6ad8217f94a0b96abb1e4b447bbce281f52
<ide><path>client/src/client-only-routes/ShowSettings.js <ide> export function ShowSettings(props) { <ide> } <ide> <ide> if (!showLoading && !isSignedIn) { <del> return navigate(`${apiLocation}/signin?returnTo=settings`); <add> navigate(`${apiLocation}/signin?returnTo=settings`); <add> return <Loader fullScreen={true} />; <ide> } <ide> <ide> return ( <ide> <Fragment> <del> <Helmet> <del> <title>Settings | freeCodeCamp.org</title> <del> </Helmet> <add> <Helmet title='Settings | freeCodeCamp.org'></Helmet> <ide> <Grid> <ide> <main> <ide> <Spacer size={2} /> <ide><path>client/src/client-only-routes/ShowSettings.test.js <ide> import { apiLocation } from '../../config/env.json'; <ide> import { ShowSettings } from './ShowSettings'; <ide> <ide> describe('<ShowSettings />', () => { <del> it('redirects to signin page when user not logged in', () => { <add> it('renders to the DOM when user is logged in', () => { <add> const shallow = new ShallowRenderer(); <add> shallow.render(<ShowSettings {...loggedInProps} />); <add> expect(navigate).toHaveBeenCalledTimes(0); <add> const result = shallow.getRenderOutput(); <add> expect(result.type.toString()).toBe('Symbol(react.fragment)'); <add> // Renders Helmet component rather than Loader <add> expect(result.props.children[0].props.title).toEqual( <add> 'Settings | freeCodeCamp.org' <add> ); <add> }); <add> <add> it('redirects to sign in page when user is not logged in', () => { <ide> const shallow = new ShallowRenderer(); <ide> shallow.render(<ShowSettings {...loggedOutProps} />); <ide> expect(navigate).toHaveBeenCalledTimes(1); <ide> expect(navigate).toHaveBeenCalledWith( <ide> `${apiLocation}/signin?returnTo=settings` <ide> ); <del> expect(true).toBeTruthy(); <add> const result = shallow.getRenderOutput(); <add> // Renders Loader rather than ShowSettings <add> expect(result.type.displayName).toBe('Loader'); <ide> }); <ide> }); <ide> <ide> const navigate = jest.fn(); <del>const loggedOutProps = { <add>const loggedInProps = { <ide> createFlashMessage: jest.fn(), <ide> hardGoTo: jest.fn(), <del> isSignedIn: false, <add> isSignedIn: true, <ide> navigate: navigate, <ide> showLoading: false, <ide> submitNewAbout: jest.fn(), <ide> const loggedOutProps = { <ide> }, <ide> verifyCert: jest.fn() <ide> }; <add>const loggedOutProps = { ...loggedInProps }; <add>loggedOutProps.isSignedIn = false; <ide><path>client/src/pages/donate.js <ide> export class DonatePage extends Component { <ide> } <ide> <ide> if (!showLoading && !isSignedIn) { <del> return navigate(`${apiLocation}/signin?returnTo=donate`); <add> navigate(`${apiLocation}/signin?returnTo=donate`); <add> return <Loader fullScreen={true} />; <ide> } <ide> <ide> return ( <ide><path>client/src/pages/donate.test.js <ide> import { apiLocation } from '../../config/env.json'; <ide> <ide> import { DonatePage } from './donate'; <ide> <del>describe('<ShowSettings />', () => { <del> it('redirects to signin page when user not logged in', () => { <add>describe('<DonatePage />', () => { <add> it('renders to the DOM when user is logged in', () => { <add> const shallow = new ShallowRenderer(); <add> shallow.render(<DonatePage {...loggedInProps} />); <add> expect(navigate).toHaveBeenCalledTimes(0); <add> const result = shallow.getRenderOutput(); <add> expect(result.type.toString()).toBe('Symbol(react.fragment)'); <add> // Renders Helmet component rather than Loader <add> expect(result.props.children[0].props.title).toEqual( <add> 'Support our nonprofit | freeCodeCamp.org' <add> ); <add> }); <add> <add> it('redirects to sign in page when user is not logged in', () => { <ide> const shallow = new ShallowRenderer(); <ide> shallow.render(<DonatePage {...loggedOutProps} />); <ide> expect(navigate).toHaveBeenCalledTimes(1); <ide> expect(navigate).toHaveBeenCalledWith( <ide> `${apiLocation}/signin?returnTo=donate` <ide> ); <del> expect(true).toBeTruthy(); <add> const result = shallow.getRenderOutput(); <add> // Renders Loader rather than DonatePage <add> expect(result.type.displayName).toBe('Loader'); <ide> }); <ide> }); <ide> <ide> const navigate = jest.fn(); <del>const loggedOutProps = { <add>const loggedInProps = { <ide> createFlashMessage: () => {}, <del> isSignedIn: false, <add> isSignedIn: true, <ide> showLoading: false, <ide> navigate: navigate <ide> }; <add>const loggedOutProps = { ...loggedInProps }; <add>loggedOutProps.isSignedIn = false; <ide><path>client/src/pages/portfolio.js <ide> function ProfilePage(props) { <ide> return <Loader fullScreen={true} />; <ide> } <ide> if (!showLoading && !isSignedIn) { <del> return navigate(`${apiLocation}/signin?returnTo=portfolio`); <add> navigate(`${apiLocation}/signin?returnTo=portfolio`); <add> return <Loader fullScreen={true} />; <ide> } <ide> const RedirecUser = createRedirect('/' + username); <ide> return <RedirecUser />;
5
PHP
PHP
fix derp with sprintf
6defae078f672e7996a24caa3fc414ded0e2d578
<ide><path>lib/Cake/Routing/RouteCollection.php <ide> protected function _getNames($url) { <ide> $plugin = $url['plugin']; <ide> } <ide> $fallbacks = array( <del> '%2s::%3s', <del> '%2s::_action', <add> '%2$s::%3$s', <add> '%2$s::_action', <ide> '_controller::_action' <ide> ); <ide> if ($plugin) { <ide> $fallbacks = array( <del> '%1s.%2s::%3s', <del> '%1s.%2s::_action', <add> '%1$s.%2$s::%3$s', <add> '%1$s.%2$s::_action', <ide> '_controller::_action' <ide> ); <ide> }
1
Text
Text
add overhead hints for heap snapshot generation
9e892e22e36c1186ff11cb050c33e5945c52c99d
<ide><path>doc/api/v8.md <ide> This JSON stream format is intended to be used with tools such as <ide> Chrome DevTools. The JSON schema is undocumented and specific to the <ide> V8 engine. Therefore, the schema may change from one version of V8 to the next. <ide> <add>Creating a heap snapshot requires memory about twice the size of the heap at <add>the time the snapshot is created. This results in the risk of OOM killers <add>terminating the process. <add> <add>Generating a snapshot is a synchronous operation which blocks the event loop <add>for a duration depending on the heap size. <add> <ide> ```js <ide> // Print heap snapshot to the console <ide> const v8 = require('v8'); <ide> A heap snapshot is specific to a single V8 isolate. When using <ide> [worker threads][], a heap snapshot generated from the main thread will <ide> not contain any information about the workers, and vice versa. <ide> <add>Creating a heap snapshot requires memory about twice the size of the heap at <add>the time the snapshot is created. This results in the risk of OOM killers <add>terminating the process. <add> <add>Generating a snapshot is a synchronous operation which blocks the event loop <add>for a duration depending on the heap size. <add> <ide> ```js <ide> const { writeHeapSnapshot } = require('v8'); <ide> const {
1
Text
Text
fix 404 link of building.md
8f39f51cbbd3b2de14b9ee896e26421cc5b20121
<ide><path>BUILDING.md <ide> packages: <ide> * [NetWide Assembler](https://chocolatey.org/packages/nasm) <ide> <ide> To install Node.js prerequisites using <del>[Boxstarter WebLauncher](https://boxstarter.org/WebLauncher), open <add>[Boxstarter WebLauncher](https://boxstarter.org/weblauncher), open <ide> <https://boxstarter.org/package/nr/url?https://raw.githubusercontent.com/nodejs/node/HEAD/tools/bootstrap/windows_boxstarter> <ide> with Internet Explorer or Edge browser on the target machine. <ide>
1
Python
Python
use html parser to compare html snippets
585aa11d233b7e3e40fe45fa69ef045d8f282345
<ide><path>tests/regressiontests/admin_inlines/tests.py <ide> def test_non_related_name_inline(self): <ide> response = self.client.get('/admin/admin_inlines/capofamiglia/add/') <ide> <ide> self.assertContains(response, <del> '<input type="hidden" name="-1-0-id" id="id_-1-0-id" />') <add> '<input type="hidden" name="-1-0-id" id="id_-1-0-id" />', html=True) <ide> self.assertContains(response, <del> '<input type="hidden" name="-1-0-capo_famiglia" ' <del> 'id="id_-1-0-capo_famiglia" />') <add> '<input type="hidden" name="-1-0-capo_famiglia" id="id_-1-0-capo_famiglia" />', html=True) <ide> self.assertContains(response, <ide> '<input id="id_-1-0-name" type="text" class="vTextField" ' <ide> 'name="-1-0-name" maxlength="100" />', html=True) <ide> <ide> self.assertContains(response, <del> '<input type="hidden" name="-2-0-id" id="id_-2-0-id" />') <add> '<input type="hidden" name="-2-0-id" id="id_-2-0-id" />', html=True) <ide> self.assertContains(response, <del> '<input type="hidden" name="-2-0-capo_famiglia" ' <del> 'id="id_-2-0-capo_famiglia" />') <add> '<input type="hidden" name="-2-0-capo_famiglia" id="id_-2-0-capo_famiglia" />', html=True) <ide> self.assertContains(response, <ide> '<input id="id_-2-0-name" type="text" class="vTextField" ' <ide> 'name="-2-0-name" maxlength="100" />', html=True) <ide> def test_inline_add_fk_add_perm(self): <ide> # Add permission on inner2s, so we get the inline <ide> self.assertContains(response, '<h2>Inner2s</h2>') <ide> self.assertContains(response, 'Add another Inner2') <del> self.assertContains(response, 'value="3" id="id_inner2_set-TOTAL_FORMS"') <add> self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" ' <add> 'value="3" name="inner2_set-TOTAL_FORMS" />', html=True) <ide> <ide> def test_inline_change_m2m_add_perm(self): <ide> permission = Permission.objects.get(codename='add_book', content_type=self.book_ct) <ide> def test_inline_change_m2m_change_perm(self): <ide> # We have change perm on books, so we can add/change/delete inlines <ide> self.assertContains(response, '<h2>Author-book relationships</h2>') <ide> self.assertContains(response, 'Add another Author-Book Relationship') <del> self.assertContains(response, 'value="4" id="id_Author_books-TOTAL_FORMS"') <del> self.assertContains(response, '<input type="hidden" name="Author_books-0-id" value="%i"' % self.author_book_auto_m2m_intermediate_id) <add> self.assertContains(response, '<input type="hidden" id="id_Author_books-TOTAL_FORMS" ' <add> 'value="4" name="Author_books-TOTAL_FORMS" />', html=True) <add> self.assertContains(response, '<input type="hidden" id="id_Author_books-0-id" ' <add> 'value="%i" name="Author_books-0-id" />' % self.author_book_auto_m2m_intermediate_id, html=True) <ide> self.assertContains(response, 'id="id_Author_books-0-DELETE"') <ide> <ide> def test_inline_change_fk_add_perm(self): <ide> def test_inline_change_fk_add_perm(self): <ide> self.assertContains(response, '<h2>Inner2s</h2>') <ide> self.assertContains(response, 'Add another Inner2') <ide> # 3 extra forms only, not the existing instance form <del> self.assertContains(response, 'value="3" id="id_inner2_set-TOTAL_FORMS"') <del> self.assertNotContains(response, '<input type="hidden" name="inner2_set-0-id" value="%i"' % self.inner2_id) <add> self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" ' <add> 'value="3" name="inner2_set-TOTAL_FORMS" />', html=True) <add> self.assertNotContains(response, '<input type="hidden" id="id_inner2_set-0-id" ' <add> 'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True) <ide> <ide> def test_inline_change_fk_change_perm(self): <ide> permission = Permission.objects.get(codename='change_inner2', content_type=self.inner_ct) <ide> def test_inline_change_fk_change_perm(self): <ide> # Change permission on inner2s, so we can change existing but not add new <ide> self.assertContains(response, '<h2>Inner2s</h2>') <ide> # Just the one form for existing instances <del> self.assertContains(response, 'value="1" id="id_inner2_set-TOTAL_FORMS"') <del> self.assertContains(response, '<input type="hidden" name="inner2_set-0-id" value="%i"' % self.inner2_id) <add> self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" ' <add> 'value="1" name="inner2_set-TOTAL_FORMS" />', html=True) <add> self.assertContains(response, '<input type="hidden" id="id_inner2_set-0-id" ' <add> 'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True) <ide> # max-num 0 means we can't add new ones <del> self.assertContains(response, 'value="0" id="id_inner2_set-MAX_NUM_FORMS"') <add> self.assertContains(response, '<input type="hidden" id="id_inner2_set-MAX_NUM_FORMS" ' <add> 'value="0" name="inner2_set-MAX_NUM_FORMS" />', html=True) <ide> <ide> def test_inline_change_fk_add_change_perm(self): <ide> permission = Permission.objects.get(codename='add_inner2', content_type=self.inner_ct) <ide> def test_inline_change_fk_add_change_perm(self): <ide> # Add/change perm, so we can add new and change existing <ide> self.assertContains(response, '<h2>Inner2s</h2>') <ide> # One form for existing instance and three extra for new <del> self.assertContains(response, 'value="4" id="id_inner2_set-TOTAL_FORMS"') <del> self.assertContains(response, '<input type="hidden" name="inner2_set-0-id" value="%i"' % self.inner2_id) <del> <add> self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" ' <add> 'value="4" name="inner2_set-TOTAL_FORMS" />', html=True) <add> self.assertContains(response, '<input type="hidden" id="id_inner2_set-0-id" ' <add> 'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True) <ide> <ide> def test_inline_change_fk_change_del_perm(self): <ide> permission = Permission.objects.get(codename='change_inner2', content_type=self.inner_ct) <ide> def test_inline_change_fk_change_del_perm(self): <ide> # Change/delete perm on inner2s, so we can change/delete existing <ide> self.assertContains(response, '<h2>Inner2s</h2>') <ide> # One form for existing instance only, no new <del> self.assertContains(response, 'value="1" id="id_inner2_set-TOTAL_FORMS"') <del> self.assertContains(response, '<input type="hidden" name="inner2_set-0-id" value="%i"' % self.inner2_id) <add> self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" ' <add> 'value="1" name="inner2_set-TOTAL_FORMS" />', html=True) <add> self.assertContains(response, '<input type="hidden" id="id_inner2_set-0-id" ' <add> 'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True) <ide> self.assertContains(response, 'id="id_inner2_set-0-DELETE"') <ide> <ide> <ide> def test_inline_change_fk_all_perms(self): <ide> # All perms on inner2s, so we can add/change/delete <ide> self.assertContains(response, '<h2>Inner2s</h2>') <ide> # One form for existing instance only, three for new <del> self.assertContains(response, 'value="4" id="id_inner2_set-TOTAL_FORMS"') <del> self.assertContains(response, '<input type="hidden" name="inner2_set-0-id" value="%i"' % self.inner2_id) <add> self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" ' <add> 'value="4" name="inner2_set-TOTAL_FORMS" />', html=True) <add> self.assertContains(response, '<input type="hidden" id="id_inner2_set-0-id" ' <add> 'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True) <ide> self.assertContains(response, 'id="id_inner2_set-0-DELETE"') <ide> <ide>
1
PHP
PHP
fix failing tests for previous commit
2f157af10087097afdc4e5673cb63369cc446e1b
<ide><path>tests/TestCase/View/Helper/PaginatorHelperTest.php <ide> public function testNumbers() <ide> $result = $this->Paginator->numbers(['first' => 'first', 'last' => 'last']); <ide> $expected = [ <ide> ['li' => ['class' => 'first']], ['a' => ['href' => '/index']], 'first', '/a', '/li', <del> ['li' => ['class' => 'ellipsis']], '...', '/li', <add> ['li' => ['class' => 'ellipsis']], '&hellip;', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4']], '4', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=5']], '5', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=6']], '6', '/a', '/li', <ide> public function testNumbers() <ide> ['li' => []], ['a' => ['href' => '/index?page=10']], '10', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=11']], '11', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=12']], '12', '/a', '/li', <del> ['li' => ['class' => 'ellipsis']], '...', '/li', <add> ['li' => ['class' => 'ellipsis']], '&hellip;', '/li', <ide> ['li' => ['class' => 'last']], ['a' => ['href' => '/index?page=15']], 'last', '/a', '/li', <ide> ]; <ide> $this->assertHtml($expected, $result); <ide> <ide> $result = $this->Paginator->numbers(['first' => '2', 'last' => '8']); <ide> $expected = [ <ide> ['li' => ['class' => 'first']], ['a' => ['href' => '/index']], '2', '/a', '/li', <del> ['li' => ['class' => 'ellipsis']], '...', '/li', <add> ['li' => ['class' => 'ellipsis']], '&hellip;', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4']], '4', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=5']], '5', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=6']], '6', '/a', '/li', <ide> public function testNumbers() <ide> ['li' => []], ['a' => ['href' => '/index?page=10']], '10', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=11']], '11', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=12']], '12', '/a', '/li', <del> ['li' => ['class' => 'ellipsis']], '...', '/li', <add> ['li' => ['class' => 'ellipsis']], '&hellip;', '/li', <ide> ['li' => ['class' => 'last']], ['a' => ['href' => '/index?page=15']], '8', '/a', '/li', <ide> ]; <ide> $this->assertHtml($expected, $result); <ide> <ide> $result = $this->Paginator->numbers(['first' => '8', 'last' => '8']); <ide> $expected = [ <ide> ['li' => ['class' => 'first']], ['a' => ['href' => '/index']], '8', '/a', '/li', <del> ['li' => ['class' => 'ellipsis']], '...', '/li', <add> ['li' => ['class' => 'ellipsis']], '&hellip;', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4']], '4', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=5']], '5', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=6']], '6', '/a', '/li', <ide> public function testNumbers() <ide> ['li' => []], ['a' => ['href' => '/index?page=10']], '10', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=11']], '11', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=12']], '12', '/a', '/li', <del> ['li' => ['class' => 'ellipsis']], '...', '/li', <add> ['li' => ['class' => 'ellipsis']], '&hellip;', '/li', <ide> ['li' => ['class' => 'last']], ['a' => ['href' => '/index?page=15']], '8', '/a', '/li', <ide> ]; <ide> $this->assertHtml($expected, $result); <ide> public function testNumbers() <ide> $result = $this->Paginator->numbers(['first' => 1]); <ide> $expected = [ <ide> ['li' => []], ['a' => ['href' => '/index']], '1', '/a', '/li', <del> ['li' => ['class' => 'ellipsis']], '...', '/li', <add> ['li' => ['class' => 'ellipsis']], '&hellip;', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=7']], '7', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=8']], '8', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=9']], '9', '/a', '/li', <ide> public function testNumbers() <ide> $result = $this->Paginator->numbers(['first' => 1, 'last' => 1]); <ide> $expected = [ <ide> ['li' => []], ['a' => ['href' => '/index']], '1', '/a', '/li', <del> ['li' => ['class' => 'ellipsis']], '...', '/li', <add> ['li' => ['class' => 'ellipsis']], '&hellip;', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=6']], '6', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=7']], '7', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=8']], '8', '/a', '/li', <ide> public function testNumbers() <ide> ['li' => []], ['a' => ['href' => '/index?page=8']], '8', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=9']], '9', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=10']], '10', '/a', '/li', <del> ['li' => ['class' => 'ellipsis']], '...', '/li', <add> ['li' => ['class' => 'ellipsis']], '&hellip;', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=42']], '42', '/a', '/li', <ide> ]; <ide> $this->assertHtml($expected, $result); <ide> public function testNumbers() <ide> $result = $this->Paginator->numbers(['first' => 1, 'last' => 1]); <ide> $expected = [ <ide> ['li' => []], ['a' => ['href' => '/index']], '1', '/a', '/li', <del> ['li' => ['class' => 'ellipsis']], '...', '/li', <add> ['li' => ['class' => 'ellipsis']], '&hellip;', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=33']], '33', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=34']], '34', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=35']], '35', '/a', '/li', <ide> public function testNumbersModulus() <ide> $expected = [ <ide> ['li' => []], ['a' => ['href' => '/index']], '1', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=2']], '2', '/a', '/li', <del> ['li' => ['class' => 'ellipsis']], '...', '/li', <add> ['li' => ['class' => 'ellipsis']], '&hellip;', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4894']], '4894', '/a', '/li', <ide> ['li' => ['class' => 'active']], '<a href=""', '4895', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4896']], '4896', '/a', '/li', <ide> public function testNumbersModulus() <ide> ['li' => []], ['a' => ['href' => '/index?page=2']], '2', '/a', '/li', <ide> ['li' => ['class' => 'active']], '<a href=""', '3', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4']], '4', '/a', '/li', <del> ['li' => ['class' => 'ellipsis']], '...', '/li', <add> ['li' => ['class' => 'ellipsis']], '&hellip;', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4896']], '4896', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4897']], '4897', '/a', '/li', <ide> ]; <ide> public function testNumbersModulus() <ide> ['li' => []], ['a' => ['href' => '/index?page=2']], '2', '/a', '/li', <ide> ['li' => ['class' => 'active']], '<a href=""', '3', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4']], '4', '/a', '/li', <del> ['li' => ['class' => 'ellipsis']], '...', '/li', <add> ['li' => ['class' => 'ellipsis']], '&hellip;', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4896']], '4896', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4897']], '4897', '/a', '/li', <ide> ]; <ide> public function testNumbersModulus() <ide> ['li' => []], ['a' => ['href' => '/index?page=4']], '4', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=5']], '5', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=6']], '6', '/a', '/li', <del> ['li' => ['class' => 'ellipsis']], '...', '/li', <add> ['li' => ['class' => 'ellipsis']], '&hellip;', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4893']], '4893', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4894']], '4894', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4895']], '4895', '/a', '/li', <ide> public function testNumbersModulus() <ide> ['li' => []], ['a' => ['href' => '/index?page=3']], '3', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4']], '4', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=5']], '5', '/a', '/li', <del> ['li' => ['class' => 'ellipsis']], '...', '/li', <add> ['li' => ['class' => 'ellipsis']], '&hellip;', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4891']], '4891', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4892']], '4892', '/a', '/li', <ide> ['li' => ['class' => 'active']], '<a href=""', '4893', '/a', '/li', <ide> public function testNumbersModulus() <ide> ['li' => []], ['a' => ['href' => '/index?page=3']], '3', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4']], '4', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=5']], '5', '/a', '/li', <del> ['li' => ['class' => 'ellipsis']], '...', '/li', <add> ['li' => ['class' => 'ellipsis']], '&hellip;', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=56']], '56', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=57']], '57', '/a', '/li', <ide> ['li' => ['class' => 'active']], '<a href=""', '58', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=59']], '59', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=60']], '60', '/a', '/li', <del> ['li' => ['class' => 'ellipsis']], '...', '/li', <add> ['li' => ['class' => 'ellipsis']], '&hellip;', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4893']], '4893', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4894']], '4894', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4895']], '4895', '/a', '/li', <ide> public function testNumbersModulus() <ide> ['li' => ['class' => 'active']], '<a href=""', '5', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=6']], '6', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=7']], '7', '/a', '/li', <del> ['li' => ['class' => 'ellipsis']], '...', '/li', <add> ['li' => ['class' => 'ellipsis']], '&hellip;', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4893']], '4893', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4894']], '4894', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4895']], '4895', '/a', '/li', <ide> public function testNumbersModulus() <ide> ['li' => []], ['a' => ['href' => '/index?page=2']], '2', '/a', '/li', <ide> ['li' => ['class' => 'active']], '<a href=""', '3', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4']], '4', '/a', '/li', <del> ['li' => ['class' => 'ellipsis']], '...', '/li', <add> ['li' => ['class' => 'ellipsis']], '&hellip;', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4896']], '4896', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4897']], '4897', '/a', '/li', <ide> ]; <ide> public function testNumbersModulus() <ide> ['li' => []], ['a' => ['href' => '/index']], '1', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=2']], '2', '/a', '/li', <ide> ['li' => ['class' => 'active']], '<a href=""', '3', '/a', '/li', <del> ['li' => ['class' => 'ellipsis']], '...', '/li', <add> ['li' => ['class' => 'ellipsis']], '&hellip;', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4896']], '4896', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4897']], '4897', '/a', '/li', <ide> ]; <ide> public function testNumbersWithUrlOptions() <ide> ['li' => []], ['a' => ['href' => '/index?page=2&amp;foo=bar']], '2', '/a', '/li', <ide> ['li' => ['class' => 'active']], '<a href=""', '3', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4&amp;foo=bar']], '4', '/a', '/li', <del> ['li' => ['class' => 'ellipsis']], '...', '/li', <add> ['li' => ['class' => 'ellipsis']], '&hellip;', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4896&amp;foo=bar']], '4896', '/a', '/li', <ide> ['li' => []], ['a' => ['href' => '/index?page=4897&amp;foo=bar']], '4897', '/a', '/li', <ide> ];
1
Text
Text
fix typo in email address in readme
6de9d13f83e297f5347ed0a8dbfdcfc967da5a0a
<ide><path>README.md <ide> more information about the governance of the Node.js project, see <ide> * [iWuzHere](https://github.com/iWuzHere) - <ide> **Imran Iqbal** &lt;[email protected]&gt; <ide> * [JacksonTian](https://github.com/JacksonTian) - <del>**Jackson Tian** &lt;[email protected]&gt; <add>**Jackson Tian** &lt;[email protected]&gt; <ide> * [jbergstroem](https://github.com/jbergstroem) - <ide> **Johan Bergström** &lt;[email protected]&gt; <ide> * [jhamhader](https://github.com/jhamhader) -
1
Ruby
Ruby
remove unneeded reader
1a30b1ed4066cbefc9faacae081655c1da38836f
<ide><path>activerecord/lib/active_record/associations/builder/collection_association.rb <ide> def self.valid_options(options) <ide> :after_add, :before_remove, :after_remove, :extend] <ide> end <ide> <del> attr_reader :block_extension <del> <ide> def initialize(name, scope, options, extension) <ide> super <ide>
1
Go
Go
fix a missing unlock on ingress sandbox failure
f98cfa559725bacb8c7a3c7f4762d45e18deaaba
<ide><path>libnetwork/controller.go <ide> func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (s <ide> <ide> c.Lock() <ide> if sb.ingress && c.ingressSandbox != nil { <add> c.Unlock() <ide> return nil, fmt.Errorf("ingress sandbox already present") <ide> } <ide>
1
Go
Go
add comment clarifying null termination
c626349f651a660302f64101055d65dc6e990307
<ide><path>pkg/netlink/netlink_linux.go <ide> func NetworkChangeName(iface *net.Interface, newName string) error { <ide> defer syscall.Close(fd) <ide> <ide> data := [IFNAMSIZ * 2]byte{} <add> // the "-1"s here are very important for ensuring we get proper null <add> // termination of our new C strings <ide> copy(data[:IFNAMSIZ-1], iface.Name) <ide> copy(data[IFNAMSIZ:IFNAMSIZ*2-1], newName) <ide>
1
Text
Text
update license year
fca4a885deb50f09069ca6c399c8dc2d78c019b3
<ide><path>LICENSE.md <ide> BSD 3-Clause License <ide> <del>Copyright (c) 2019, freeCodeCamp. <add>Copyright (c) 2020, freeCodeCamp. <ide> All rights reserved. <ide> <ide> Redistribution and use in source and binary forms, with or without
1
Text
Text
capitalize non-primitive types
c3fde98d4d2d920ce3df10a7668aa36bcfb49206
<ide><path>doc/api/assert.md <ide> added: v0.1.21 <ide> * `expected` {any} <ide> * `message` {any} **Default:** `'Failed'` <ide> * `operator` {string} **Default:** '!=' <del>* `stackStartFunction` {function} **Default:** `assert.fail` <add>* `stackStartFunction` {Function} **Default:** `assert.fail` <ide> <ide> Throws an `AssertionError`. If `message` is falsy, the error message is set as <ide> the values of `actual` and `expected` separated by the provided `operator`. If <ide> changes: <ide> description: The `error` parameter can now be an arrow function. <ide> --> <ide> * `block` {Function} <del>* `error` {RegExp|Function|object} <add>* `error` {RegExp|Function|Object} <ide> * `message` {any} <ide> <ide> Expects the function `block` to throw an error. <ide><path>doc/api/cluster.md <ide> changes: <ide> `'ipc'` entry. When this option is provided, it overrides `silent`. <ide> * `uid` {number} Sets the user identity of the process. (See setuid(2).) <ide> * `gid` {number} Sets the group identity of the process. (See setgid(2).) <del> * `inspectPort` {number|function} Sets inspector port of worker. <add> * `inspectPort` {number|Function} Sets inspector port of worker. <ide> This can be a number, or a function that takes no arguments and returns a <ide> number. By default each worker gets its own port, incremented from the <ide> master's `process.debugPort`. <ide><path>doc/api/http2.md <ide> added: v8.4.0 <ide> * `options` {Object} <ide> * `endStream` {boolean} Set to `true` to indicate that the response will not <ide> include payload data. <del> * `getTrailers` {function} Callback function invoked to collect trailer <add> * `getTrailers` {Function} Callback function invoked to collect trailer <ide> headers. <ide> * Returns: {undefined} <ide>
3
Javascript
Javascript
fix var redeclarations in test-os
7caeda26c8fc1ae01a6e9481f258dfd91117b89e
<ide><path>test/parallel/test-os.js <ide> if (common.isWindows) { <ide> process.env.TEMP = ''; <ide> assert.equal(os.tmpdir(), '/tmp'); <ide> process.env.TMP = ''; <del> var expected = (process.env.SystemRoot || process.env.windir) + '\\temp'; <add> const expected = (process.env.SystemRoot || process.env.windir) + '\\temp'; <ide> assert.equal(os.tmpdir(), expected); <ide> process.env.TEMP = '\\temp\\'; <ide> assert.equal(os.tmpdir(), '\\temp'); <ide> var interfaces = os.networkInterfaces(); <ide> console.error(interfaces); <ide> switch (platform) { <ide> case 'linux': <del> var filter = function(e) { return e.address == '127.0.0.1'; }; <del> var actual = interfaces.lo.filter(filter); <del> var expected = [{ address: '127.0.0.1', netmask: '255.0.0.0', <del> mac: '00:00:00:00:00:00', family: 'IPv4', <del> internal: true }]; <del> assert.deepEqual(actual, expected); <del> break; <add> { <add> const filter = function(e) { return e.address == '127.0.0.1'; }; <add> const actual = interfaces.lo.filter(filter); <add> const expected = [{ address: '127.0.0.1', netmask: '255.0.0.0', <add> mac: '00:00:00:00:00:00', family: 'IPv4', <add> internal: true }]; <add> assert.deepEqual(actual, expected); <add> break; <add> } <ide> case 'win32': <del> var filter = function(e) { return e.address == '127.0.0.1'; }; <del> var actual = interfaces['Loopback Pseudo-Interface 1'].filter(filter); <del> var expected = [{ address: '127.0.0.1', netmask: '255.0.0.0', <del> mac: '00:00:00:00:00:00', family: 'IPv4', <del> internal: true }]; <del> assert.deepEqual(actual, expected); <del> break; <add> { <add> const filter = function(e) { return e.address == '127.0.0.1'; }; <add> const actual = interfaces['Loopback Pseudo-Interface 1'].filter(filter); <add> const expected = [{ address: '127.0.0.1', netmask: '255.0.0.0', <add> mac: '00:00:00:00:00:00', family: 'IPv4', <add> internal: true }]; <add> assert.deepEqual(actual, expected); <add> break; <add> } <ide> } <ide> <ide> var EOL = os.EOL;
1
PHP
PHP
refactor the encryption class
8a175894b260684b56e110a3b1cd540064de2690
<ide><path>system/crypt.php <ide> public static function encrypt($value) <ide> */ <ide> public static function decrypt($value) <ide> { <del> $value = base64_decode($value, true); <del> <del> if ( ! $value) <add> if ( ! is_string($value = base64_decode($value, true))) <ide> { <ide> throw new \Exception('Decryption error. Input value is not valid base64 data.'); <ide> }
1
Java
Java
add onbackpressurereduce operator
7741c59fd05196d40b5a6214314842552290c156
<ide><path>src/main/java/io/reactivex/rxjava3/core/Flowable.java <ide> public final Flowable<T> onBackpressureLatest() { <ide> return RxJavaPlugins.onAssembly(new FlowableOnBackpressureLatest<>(this)); <ide> } <ide> <add> /** <add> * Reduces a sequence of two not emitted values via a function into a single value if the downstream is not ready to receive <add> * new items (indicated by a lack of {@link Subscription#request(long)} calls from it) and emits this latest <add> * item when the downstream becomes ready. <add> * <p> <add> * <img width="640" height="354" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Flowable.onBackpressureReduce.png" alt=""> <add> * <p> <add> * Note that if the current {@code Flowable} does support backpressure, this operator ignores that capability <add> * and doesn't propagate any backpressure requests from downstream. <add> * <p> <add> * Note that due to the nature of how backpressure requests are propagated through subscribeOn/observeOn, <add> * requesting more than 1 from downstream doesn't guarantee a continuous delivery of {@code onNext} events. <add> * <dl> <add> * <dt><b>Backpressure:</b></dt> <add> * <dd>The operator honors backpressure from downstream and consumes the current {@code Flowable} in an unbounded <add> * manner (i.e., not applying backpressure to it).</dd> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code onBackpressureReduce} does not operate by default on a particular {@link Scheduler}.</dd> <add> * </dl> <add> * @param reducer the bi-function to call when there is more than one non-emitted value to downstream, <add> * the first argument of the bi-function is previous item and the second one is currently emitting from upstream <add> * @return the new {@code Flowable} instance <add> * @throws NullPointerException if {@code reducer} is {@code null} <add> * @since 3.0.9 - experimental <add> */ <add> @Experimental <add> @CheckReturnValue <add> @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) <add> @SchedulerSupport(SchedulerSupport.NONE) <add> @NonNull <add> public final Flowable<T> onBackpressureReduce(@NonNull BiFunction<T, T, T> reducer) { <add> return RxJavaPlugins.onAssembly(new FlowableOnBackpressureReduce<>(this, reducer)); <add> } <add> <ide> /** <ide> * Returns a {@code Flowable} instance that if the current {@code Flowable} emits an error, it will emit an {@code onComplete} <ide> * and swallow the throwable. <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/flowable/AbstractBackpressureThrottlingSubscriber.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.flowable; <add> <add>import io.reactivex.rxjava3.core.FlowableSubscriber; <add>import io.reactivex.rxjava3.internal.subscriptions.SubscriptionHelper; <add>import io.reactivex.rxjava3.internal.util.BackpressureHelper; <add>import org.reactivestreams.Publisher; <add>import org.reactivestreams.Subscriber; <add>import org.reactivestreams.Subscription; <add> <add>import java.util.concurrent.atomic.AtomicInteger; <add>import java.util.concurrent.atomic.AtomicLong; <add>import java.util.concurrent.atomic.AtomicReference; <add> <add>/** <add> * Abstract base class for operators that throttle excessive updates from upstream in case if <add> * downstream {@link Subscriber} is not ready to receive updates <add> * <add> * @param <T> the upstream and downstream value type <add> */ <add>abstract class AbstractBackpressureThrottlingSubscriber<T> extends AtomicInteger implements FlowableSubscriber<T>, Subscription { <add> <add> final Subscriber<? super T> downstream; <add> <add> Subscription upstream; <add> <add> volatile boolean done; <add> Throwable error; <add> <add> volatile boolean cancelled; <add> <add> final AtomicLong requested = new AtomicLong(); <add> <add> final AtomicReference<T> current = new AtomicReference<>(); <add> <add> AbstractBackpressureThrottlingSubscriber(Subscriber<? super T> downstream) { <add> this.downstream = downstream; <add> } <add> <add> @Override <add> public void onSubscribe(Subscription s) { <add> if (SubscriptionHelper.validate(this.upstream, s)) { <add> this.upstream = s; <add> downstream.onSubscribe(this); <add> s.request(Long.MAX_VALUE); <add> } <add> } <add> <add> @Override <add> abstract public void onNext(T t); <add> <add> @Override <add> public void onError(Throwable t) { <add> error = t; <add> done = true; <add> drain(); <add> } <add> <add> @Override <add> public void onComplete() { <add> done = true; <add> drain(); <add> } <add> <add> @Override <add> public void request(long n) { <add> if (SubscriptionHelper.validate(n)) { <add> BackpressureHelper.add(requested, n); <add> drain(); <add> } <add> } <add> <add> @Override <add> public void cancel() { <add> if (!cancelled) { <add> cancelled = true; <add> upstream.cancel(); <add> <add> if (getAndIncrement() == 0) { <add> current.lazySet(null); <add> } <add> } <add> } <add> <add> void drain() { <add> if (getAndIncrement() != 0) { <add> return; <add> } <add> final Subscriber<? super T> a = downstream; <add> int missed = 1; <add> final AtomicLong r = requested; <add> final AtomicReference<T> q = current; <add> <add> for (;;) { <add> long e = 0L; <add> <add> while (e != r.get()) { <add> boolean d = done; <add> T v = q.getAndSet(null); <add> boolean empty = v == null; <add> <add> if (checkTerminated(d, empty, a, q)) { <add> return; <add> } <add> <add> if (empty) { <add> break; <add> } <add> <add> a.onNext(v); <add> <add> e++; <add> } <add> <add> if (e == r.get() && checkTerminated(done, q.get() == null, a, q)) { <add> return; <add> } <add> <add> if (e != 0L) { <add> BackpressureHelper.produced(r, e); <add> } <add> <add> missed = addAndGet(-missed); <add> if (missed == 0) { <add> break; <add> } <add> } <add> } <add> <add> boolean checkTerminated(boolean d, boolean empty, Subscriber<?> a, AtomicReference<T> q) { <add> if (cancelled) { <add> q.lazySet(null); <add> return true; <add> } <add> <add> if (d) { <add> Throwable e = error; <add> if (e != null) { <add> q.lazySet(null); <add> a.onError(e); <add> return true; <add> } else <add> if (empty) { <add> a.onComplete(); <add> return true; <add> } <add> } <add> <add> return false; <add> } <add>} <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableOnBackpressureLatest.java <ide> <ide> package io.reactivex.rxjava3.internal.operators.flowable; <ide> <del>import java.util.concurrent.atomic.*; <del> <del>import org.reactivestreams.*; <del> <del>import io.reactivex.rxjava3.core.*; <del>import io.reactivex.rxjava3.internal.subscriptions.SubscriptionHelper; <del>import io.reactivex.rxjava3.internal.util.BackpressureHelper; <add>import io.reactivex.rxjava3.core.Flowable; <add>import org.reactivestreams.Subscriber; <ide> <ide> public final class FlowableOnBackpressureLatest<T> extends AbstractFlowableWithUpstream<T, T> { <ide> <ide> protected void subscribeActual(Subscriber<? super T> s) { <ide> source.subscribe(new BackpressureLatestSubscriber<>(s)); <ide> } <ide> <del> static final class BackpressureLatestSubscriber<T> extends AtomicInteger implements FlowableSubscriber<T>, Subscription { <add> static final class BackpressureLatestSubscriber<T> extends AbstractBackpressureThrottlingSubscriber<T> { <ide> <ide> private static final long serialVersionUID = 163080509307634843L; <ide> <del> final Subscriber<? super T> downstream; <del> <del> Subscription upstream; <del> <del> volatile boolean done; <del> Throwable error; <del> <del> volatile boolean cancelled; <del> <del> final AtomicLong requested = new AtomicLong(); <del> <del> final AtomicReference<T> current = new AtomicReference<>(); <del> <ide> BackpressureLatestSubscriber(Subscriber<? super T> downstream) { <del> this.downstream = downstream; <del> } <del> <del> @Override <del> public void onSubscribe(Subscription s) { <del> if (SubscriptionHelper.validate(this.upstream, s)) { <del> this.upstream = s; <del> downstream.onSubscribe(this); <del> s.request(Long.MAX_VALUE); <del> } <add> super(downstream); <ide> } <ide> <ide> @Override <ide> public void onNext(T t) { <ide> current.lazySet(t); <ide> drain(); <ide> } <del> <del> @Override <del> public void onError(Throwable t) { <del> error = t; <del> done = true; <del> drain(); <del> } <del> <del> @Override <del> public void onComplete() { <del> done = true; <del> drain(); <del> } <del> <del> @Override <del> public void request(long n) { <del> if (SubscriptionHelper.validate(n)) { <del> BackpressureHelper.add(requested, n); <del> drain(); <del> } <del> } <del> <del> @Override <del> public void cancel() { <del> if (!cancelled) { <del> cancelled = true; <del> upstream.cancel(); <del> <del> if (getAndIncrement() == 0) { <del> current.lazySet(null); <del> } <del> } <del> } <del> <del> void drain() { <del> if (getAndIncrement() != 0) { <del> return; <del> } <del> final Subscriber<? super T> a = downstream; <del> int missed = 1; <del> final AtomicLong r = requested; <del> final AtomicReference<T> q = current; <del> <del> for (;;) { <del> long e = 0L; <del> <del> while (e != r.get()) { <del> boolean d = done; <del> T v = q.getAndSet(null); <del> boolean empty = v == null; <del> <del> if (checkTerminated(d, empty, a, q)) { <del> return; <del> } <del> <del> if (empty) { <del> break; <del> } <del> <del> a.onNext(v); <del> <del> e++; <del> } <del> <del> if (e == r.get() && checkTerminated(done, q.get() == null, a, q)) { <del> return; <del> } <del> <del> if (e != 0L) { <del> BackpressureHelper.produced(r, e); <del> } <del> <del> missed = addAndGet(-missed); <del> if (missed == 0) { <del> break; <del> } <del> } <del> } <del> <del> boolean checkTerminated(boolean d, boolean empty, Subscriber<?> a, AtomicReference<T> q) { <del> if (cancelled) { <del> q.lazySet(null); <del> return true; <del> } <del> <del> if (d) { <del> Throwable e = error; <del> if (e != null) { <del> q.lazySet(null); <del> a.onError(e); <del> return true; <del> } else <del> if (empty) { <del> a.onComplete(); <del> return true; <del> } <del> } <del> <del> return false; <del> } <ide> } <ide> } <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableOnBackpressureReduce.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <p> <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <p> <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <p> <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.flowable; <add> <add>import io.reactivex.rxjava3.core.Flowable; <add>import io.reactivex.rxjava3.exceptions.Exceptions; <add>import io.reactivex.rxjava3.functions.BiFunction; <add>import org.reactivestreams.Subscriber; <add> <add>import java.util.Objects; <add> <add>public final class FlowableOnBackpressureReduce<T> extends AbstractFlowableWithUpstream<T, T> { <add> <add> final BiFunction<T, T, T> reducer; <add> <add> public FlowableOnBackpressureReduce(Flowable<T> source, BiFunction<T, T, T> reducer) { <add> super(source); <add> this.reducer = Objects.requireNonNull(reducer, "reducer is null"); <add> } <add> <add> @Override <add> protected void subscribeActual(Subscriber<? super T> s) { <add> source.subscribe(new BackpressureReduceSubscriber<>(s, reducer)); <add> } <add> <add> static final class BackpressureReduceSubscriber<T> extends AbstractBackpressureThrottlingSubscriber<T> { <add> <add> private static final long serialVersionUID = 821363947659780367L; <add> <add> final BiFunction<T, T, T> reducer; <add> <add> BackpressureReduceSubscriber(Subscriber<? super T> downstream, BiFunction<T, T, T> reducer) { <add> super(downstream); <add> this.reducer = reducer; <add> } <add> <add> @Override <add> public void onNext(T t) { <add> T v = current.get(); <add> if (v == null) { <add> current.lazySet(t); <add> } else if ((v = current.getAndSet(null)) != null) { <add> try { <add> current.lazySet(Objects.requireNonNull(reducer.apply(v, t), "The reducer returned a null value")); <add> } catch (Throwable ex) { <add> Exceptions.throwIfFatal(ex); <add> onError(ex); <add> cancel(); <add> return; <add> } <add> } else { <add> current.lazySet(t); <add> } <add> drain(); <add> } <add> } <add>} <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableOnBackpressureLatestTest.java <ide> public void onNext(Integer t) { <ide> int n = ts.values().size(); <ide> System.out.println("testAsynchronousDrop -> " + n); <ide> Assert.assertTrue("All events received?", n < m); <add> int previous = 0; <add> for (Integer current : ts.values()) { <add> Assert.assertTrue("The sequence must be increasing [current value=" + previous + <add> ", previous value=" + current + "]", previous <= current); <add> previous = current; <add> } <ide> } <ide> <ide> @Test <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableOnBackpressureReduceTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <p> <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <p> <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <p> <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.flowable; <add> <add>import io.reactivex.rxjava3.core.Flowable; <add>import io.reactivex.rxjava3.core.RxJavaTest; <add>import io.reactivex.rxjava3.exceptions.TestException; <add>import io.reactivex.rxjava3.functions.BiFunction; <add>import io.reactivex.rxjava3.processors.PublishProcessor; <add>import io.reactivex.rxjava3.schedulers.Schedulers; <add>import io.reactivex.rxjava3.subscribers.TestSubscriber; <add>import io.reactivex.rxjava3.testsupport.TestHelper; <add>import io.reactivex.rxjava3.testsupport.TestSubscriberEx; <add>import org.junit.Assert; <add>import org.junit.Test; <add> <add>import java.io.IOException; <add>import java.util.Random; <add>import java.util.concurrent.TimeUnit; <add> <add>public class FlowableOnBackpressureReduceTest extends RxJavaTest { <add> <add> static final BiFunction<Integer, Integer, Integer> TEST_INT_REDUCER = (previous, current) -> previous + current + 50; <add> <add> static final BiFunction<Object, Object, Object> TEST_OBJECT_REDUCER = (previous, current) -> current; <add> <add> @Test <add> public void simple() { <add> TestSubscriberEx<Integer> ts = new TestSubscriberEx<>(); <add> <add> Flowable.range(1, 5).onBackpressureReduce(TEST_INT_REDUCER).subscribe(ts); <add> <add> ts.assertNoErrors(); <add> ts.assertTerminated(); <add> ts.assertValues(1, 2, 3, 4, 5); <add> } <add> <add> @Test <add> public void simpleError() { <add> TestSubscriberEx<Integer> ts = new TestSubscriberEx<>(); <add> <add> Flowable.range(1, 5).concatWith(Flowable.error(new TestException())) <add> .onBackpressureReduce(TEST_INT_REDUCER).subscribe(ts); <add> <add> ts.assertTerminated(); <add> ts.assertError(TestException.class); <add> ts.assertValues(1, 2, 3, 4, 5); <add> } <add> <add> @Test <add> public void simpleBackpressure() { <add> TestSubscriber<Integer> ts = new TestSubscriber<>(2L); <add> <add> Flowable.range(1, 5).onBackpressureReduce(TEST_INT_REDUCER).subscribe(ts); <add> <add> ts.assertNoErrors(); <add> ts.assertValues(1, 2); <add> ts.assertNotComplete(); <add> } <add> <add> @Test <add> public void synchronousDrop() { <add> PublishProcessor<Integer> source = PublishProcessor.create(); <add> TestSubscriberEx<Integer> ts = new TestSubscriberEx<>(0L); <add> <add> source.onBackpressureReduce(TEST_INT_REDUCER).subscribe(ts); <add> <add> ts.assertNoValues(); <add> <add> source.onNext(1); <add> ts.request(2); <add> <add> ts.assertValue(1); <add> <add> source.onNext(2); <add> <add> ts.assertValues(1, 2); <add> <add> source.onNext(3); <add> source.onNext(4);//3 + 4 + 50 == 57 <add> source.onNext(5);//57 + 5 + 50 == 112 <add> source.onNext(6);//112 + 6 + 50 == 168 <add> <add> ts.request(2); <add> <add> ts.assertValues(1, 2, 168); <add> <add> source.onNext(7); <add> <add> ts.assertValues(1, 2, 168, 7); <add> <add> source.onNext(8); <add> source.onNext(9);//8 + 9 + 50 == 67 <add> source.onComplete(); <add> <add> ts.request(1); <add> <add> ts.assertValues(1, 2, 168, 7, 67); <add> ts.assertNoErrors(); <add> ts.assertTerminated(); <add> } <add> <add> private <T> TestSubscriberEx<T> createDelayedSubscriber() { <add> return new TestSubscriberEx<T>(1L) { <add> final Random rnd = new Random(); <add> <add> @Override <add> public void onNext(T t) { <add> super.onNext(t); <add> if (rnd.nextDouble() < 0.001) { <add> try { <add> Thread.sleep(1); <add> } catch (InterruptedException ex) { <add> ex.printStackTrace(); <add> } <add> } <add> request(1); <add> } <add> }; <add> } <add> <add> private <T> void assertValuesDropped(TestSubscriberEx<T> ts, int totalValues) { <add> int n = ts.values().size(); <add> System.out.println("testAsynchronousDrop -> " + n); <add> Assert.assertTrue("All events received?", n < totalValues); <add> } <add> <add> private void assertIncreasingSequence(TestSubscriberEx<Integer> ts) { <add> int previous = 0; <add> for (Integer current : ts.values()) { <add> Assert.assertTrue("The sequence must be increasing [current value=" + previous + <add> ", previous value=" + current + "]", previous <= current); <add> previous = current; <add> } <add> } <add> <add> @Test <add> public void asynchronousDrop() { <add> TestSubscriberEx<Integer> ts = createDelayedSubscriber(); <add> int m = 100000; <add> Flowable.range(1, m) <add> .subscribeOn(Schedulers.computation()) <add> .onBackpressureReduce((previous, current) -> { <add> //in that case it works like onBackpressureLatest <add> //the output sequence of number must be increasing <add> return current; <add> }) <add> .observeOn(Schedulers.io()) <add> .subscribe(ts); <add> <add> ts.awaitDone(2, TimeUnit.SECONDS); <add> ts.assertTerminated(); <add> assertValuesDropped(ts, m); <add> assertIncreasingSequence(ts); <add> } <add> <add> @Test <add> public void asynchronousDrop2() { <add> TestSubscriberEx<Long> ts = createDelayedSubscriber(); <add> int m = 100000; <add> Flowable.rangeLong(1, m) <add> .subscribeOn(Schedulers.computation()) <add> .onBackpressureReduce(Long::sum) <add> .observeOn(Schedulers.io()) <add> .subscribe(ts); <add> <add> ts.awaitDone(2, TimeUnit.SECONDS); <add> ts.assertTerminated(); <add> assertValuesDropped(ts, m); <add> long sum = 0; <add> for (Long i : ts.values()) { <add> sum += i; <add> } <add> //sum = (A1 + An) * n / 2 = 100_001 * 50_000 = 50_000_00000 + 50_000 = 50_000_50_000 <add> Assert.assertEquals("Wrong sum: " + sum, 5000050000L, sum); <add> } <add> <add> @Test <add> public void nullPointerFromReducer() { <add> PublishProcessor<Integer> source = PublishProcessor.create(); <add> TestSubscriberEx<Integer> ts = new TestSubscriberEx<>(0); <add> source.onBackpressureReduce((l, r) -> null).subscribe(ts); <add> <add> source.onNext(1); <add> source.onNext(2); <add> <add> TestHelper.assertError(ts.errors(), 0, NullPointerException.class, "The reducer returned a null value"); <add> } <add> <add> @Test <add> public void exceptionFromReducer() { <add> PublishProcessor<Integer> source = PublishProcessor.create(); <add> TestSubscriberEx<Integer> ts = new TestSubscriberEx<>(0); <add> source.onBackpressureReduce((l, r) -> { <add> throw new IOException("Test exception"); <add> }).subscribe(ts); <add> <add> source.onNext(1); <add> source.onNext(2); <add> <add> TestHelper.assertError(ts.errors(), 0, IOException.class, "Test exception"); <add> } <add> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeFlowable(f -> f.onBackpressureReduce(TEST_OBJECT_REDUCER)); <add> } <add> <add> @Test <add> public void take() { <add> Flowable.just(1, 2) <add> .onBackpressureReduce(TEST_INT_REDUCER) <add> .take(1) <add> .test() <add> .assertResult(1); <add> } <add> <add> @Test <add> public void dispose() { <add> TestHelper.checkDisposed(Flowable.never().onBackpressureReduce(TEST_OBJECT_REDUCER)); <add> } <add> <add> @Test <add> public void badRequest() { <add> TestHelper.assertBadRequestReported(Flowable.never().onBackpressureReduce(TEST_OBJECT_REDUCER)); <add> } <add>}
6
Ruby
Ruby
use file.directory? as dir.exists? is only 1.9.2+
8293b10425bfe621b4bed85bf3db57cccd70e43b
<ide><path>railties/lib/rails/paths.rb <ide> def expanded <ide> def existent <ide> expanded.select { |f| File.exists?(f) } <ide> end <del> <add> <ide> def existent_directories <del> expanded.select {|d| Dir.exists?(d) } <add> expanded.select { |d| File.directory?(d) } <ide> end <ide> <ide> alias to_a expanded
1
Python
Python
fix crash when --eval_batch_size is not set.
e4034bef71096e56669483f9a9011a504f6e422a
<ide><path>official/recommendation/ncf_main.py <ide> def run_ncf(_): <ide> num_gpus = flags_core.get_num_gpus(FLAGS) <ide> batch_size = distribution_utils.per_device_batch_size( <ide> int(FLAGS.batch_size), num_gpus) <del> eval_batch_size = int(FLAGS.eval_batch_size) or int(FLAGS.batch_size) <add> eval_batch_size = int(FLAGS.eval_batch_size or FLAGS.batch_size) <ide> ncf_dataset = data_preprocessing.instantiate_pipeline( <ide> dataset=FLAGS.dataset, data_dir=FLAGS.data_dir, <ide> batch_size=batch_size,
1
Python
Python
fix bug in ref-updating code
41bdf821374cd60063f5c5622ddd9e8c9089e3b9
<ide><path>test/test.py <ide> def maybeUpdateRefImages(options, browser): <ide> else: <ide> print ' Yes! The references in tmp/ can be synced with ref/.' <ide> if options.reftest: <del> startReftest(browser) <add> startReftest(browser, options) <ide> if not prompt('Would you like to update the master copy in ref/?'): <ide> print ' OK, not updating.' <ide> else:
1
Text
Text
correct url from github.com/dotcloud/docker{,-py}
64cb7725381740986022eb4633c8f91be3dd7b4f
<ide><path>CONTRIBUTING.md <ide> When considering a design proposal, we are looking for: <ide> * A description of the problem this design proposal solves <ide> * An issue -- not a pull request -- that describes what you will take action on <ide> * Please prefix your issue with `Proposal:` in the title <del>* Please review [the existing Proposals](https://github.com/dotcloud/docker/issues?direction=asc&labels=Proposal&page=1&sort=created&state=open) <add>* Please review [the existing Proposals](https://github.com/docker/docker/issues?direction=asc&labels=Proposal&page=1&sort=created&state=open) <ide> before reporting a new issue. You can always pair with someone if you both <ide> have the same idea. <ide> <ide><path>docs/sources/reference/api/remote_api_client_libraries.md <ide> will add the libraries here. <ide> <tr class="row-odd"> <ide> <td>Python</td> <ide> <td>docker-py</td> <del> <td><a class="reference external" href="https://github.com/dotcloud/docker-py">https://github.com/dotcloud/docker-py</a></td> <add> <td><a class="reference external" href="https://github.com/docker/docker-py">https://github.com/docker/docker-py</a></td> <ide> <td>Active</td> <ide> </tr> <ide> <tr class="row-even">
2
Text
Text
add v3.13.0 to changelog
eb4c26fa6f473dd813797a2ae3f3381725d300c6
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <del>### v3.13.0-beta.5 (September 3, 2019) <del> <add>### v3.13.0 (September 19, 2019) <add> <add>- [#16366](https://github.com/emberjs/ember.js/pull/16366) / [#16903](https://github.com/emberjs/ember.js/pull/16903) / [#17572](https://github.com/emberjs/ember.js/pull/17572) / [#17682](https://github.com/emberjs/ember.js/pull/17682) / [#17765](https://github.com/emberjs/ember.js/pull/17765) / [#17751](https://github.com/emberjs/ember.js/pull/17751) / [#17835](https://github.com/emberjs/ember.js/pull/17835) / [#18059](https://github.com/emberjs/ember.js/pull/18059) / [#17951](https://github.com/emberjs/ember.js/pull/17951) / [#18069](https://github.com/emberjs/ember.js/pull/18069) / [#18074](https://github.com/emberjs/ember.js/pull/18074) / [#18073](https://github.com/emberjs/ember.js/pull/18073) / [#18091](https://github.com/emberjs/ember.js/pull/18091) / [#18186](https://github.com/emberjs/ember.js/pull/18186) / [#18223](https://github.com/emberjs/ember.js/pull/18223) / [#18358](https://github.com/emberjs/ember.js/pull/18358) / [#18266](https://github.com/emberjs/ember.js/pull/18266) [FEATURE] Implement the [Tracked Properties](https://github.com/emberjs/rfcs/blob/master/text/0410-tracked-properties.md) and [Tracked Property Updates](https://github.com/emberjs/rfcs/blob/master/text/0478-tracked-properties-updates.md) RFCs. <add>- [#18158](https://github.com/emberjs/ember.js/pull/18158) / [#18203](https://github.com/emberjs/ember.js/pull/18203) / [#18198](https://github.com/emberjs/ember.js/pull/18198) / [#18190](https://github.com/emberjs/ember.js/pull/18190) / [#18394](https://github.com/emberjs/ember.js/pull/18394) [FEATURE] Implement the [Component Templates Co-location](https://github.com/emberjs/rfcs/blob/master/text/0481-component-templates-co-location.md) RFC, including the setComponentTemplate(), getComponentTemplate() and templateOnlyComponent() APIs. Note that while these low-level APIs are enabled, the co-location feature is only enabled in Octane apps as of this release. This restriction will be removed in a future version. <add>- [#18241](https://github.com/emberjs/ember.js/pull/18241) / [#18383](https://github.com/emberjs/ember.js/pull/18383) [FEATURE] Add `updateHook` component-manager capability <add>- [#18396](https://github.com/emberjs/ember.js/pull/18396) [FEATURE] Implement component-class generator <add>- [#18389](https://github.com/emberjs/ember.js/pull/18389) [FEATURE] Use @ember/edition-utils to detect the edition that is in use <add>- [#18214](https://github.com/emberjs/ember.js/pull/18214) [DEPRECATION] Implement the [Deprecate support for mouseEnter/Leave/Move Ember events RFC](https://github.com/emberjs/rfcs/blob/master/text/0486-deprecate-mouseenter.md). <add>- [#18395](https://github.com/emberjs/ember.js/pull/18395) [BUGFIX] Use `<Nested::Invocation>` in component tests blueprint <add>- [#18406](https://github.com/emberjs/ember.js/pull/18406) [BUGFIX] Prevent infinite cycles from lazy computed computation <ide> - [#18314](https://github.com/emberjs/ember.js/pull/18314) [BUGFIX] Use class inheritance for getters and setters <ide> - [#18329](https://github.com/emberjs/ember.js/pull/18329) [BUGFIX] Eagerly consume aliases <del> <del>### v3.13.0-beta.4 (August 26, 2019) <del> <ide> - [#18278](https://github.com/emberjs/ember.js/pull/18278) [BUGFIX] Bump ember-router-generator from v1.2.3 to v2.0.0 to support parsing `app/router.js` with native class. <ide> - [#18291](https://github.com/emberjs/ember.js/pull/18291) [BUGFIX] Adds the babel-helpers injection plugin back and include `ember-template-compiler` in the vendor folder for Ember. <ide> - [#18296](https://github.com/emberjs/ember.js/pull/18296) [BUGFIX] Ensure {{each-in}} can iterate over keys with periods <del>- [#18304](https://github.com/emberjs/ember.js/pull/18304) [BUGFIX] Check the EMBER_ENV environment variable after it is set <del> <del>### v3.13.0-beta.3 (August 19, 2019) <del> <del>- [#18223](https://github.com/emberjs/ember.js/pull/18223) [FEATURE] Tracked Props Performance Tuning <add>- [#18304](https://github.com/emberjs/ember.js/pull/18304) [BUGFIX] Correctly determine the environment by checking the EMBER_ENV environment variable only after it is set <ide> - [#18208](https://github.com/emberjs/ember.js/pull/18208) [BUGFIX] Compile Ember dynamically in consuming applications <del>- [#18266](https://github.com/emberjs/ember.js/pull/18266) [BUGFIX] Autotrack Modifiers and Helpers <ide> - [#18267](https://github.com/emberjs/ember.js/pull/18267) [BUGFIX] Router#url should not error when `location` is a string <ide> - [#18270](https://github.com/emberjs/ember.js/pull/18270) [BUGFIX] Prevent cycle dependency with owner association. <ide> - [#18274](https://github.com/emberjs/ember.js/pull/18274) [BUGFIX] Allow CPs to depend on nested args <ide> - [#18276](https://github.com/emberjs/ember.js/pull/18276) [BUGFIX] Change the assertion for @each dependencies into a deprecation <ide> - [#18281](https://github.com/emberjs/ember.js/pull/18281) [BUGFIX] Check length of targets <del> <del>### v3.13.0.beta.2 (August 12, 2019) <del> <ide> - [#18248](https://github.com/emberjs/ember.js/pull/18248) [BUGFIX] Ensures that observers are flushed after CPs are updated <del>- [#18241](https://github.com/emberjs/ember.js/pull/18241) [BUGFIX] Adds Component Manager 3.13 Capabilities <del> <del>### v3.13.0-beta.1 (August 6, 2019) <del> <del>- [#16366](https://github.com/emberjs/ember.js/pull/16366) / [#16903](https://github.com/emberjs/ember.js/pull/16903) / [#17572](https://github.com/emberjs/ember.js/pull/17572) / [#17682](https://github.com/emberjs/ember.js/pull/17682) / [#17765](https://github.com/emberjs/ember.js/pull/17765) / [#17751](https://github.com/emberjs/ember.js/pull/17751) / [#17835](https://github.com/emberjs/ember.js/pull/17835) / [#18059](https://github.com/emberjs/ember.js/pull/18059) / [#17951](https://github.com/emberjs/ember.js/pull/17951) / [#18069](https://github.com/emberjs/ember.js/pull/18069) / [#18074](https://github.com/emberjs/ember.js/pull/18074) / [#18073](https://github.com/emberjs/ember.js/pull/18073) / [#18091](https://github.com/emberjs/ember.js/pull/18091) / [#18186](https://github.com/emberjs/ember.js/pull/18186) [FEATURE] Implement the [Tracked Properties](https://github.com/emberjs/rfcs/blob/master/text/0410-tracked-properties.md) and [Tracked Property Updates](https://github.com/emberjs/rfcs/blob/master/text/0478-tracked-properties-updates.md) RFCs. <del>- [#18158](https://github.com/emberjs/ember.js/pull/18158) / [#18203](https://github.com/emberjs/ember.js/pull/18203) / [#18198](https://github.com/emberjs/ember.js/pull/18198) / [#18190](https://github.com/emberjs/ember.js/pull/18190) [FEATURE] Implement the [Component Templates Co-location](https://github.com/emberjs/rfcs/blob/master/text/0481-component-templates-co-location.md). <del>- [#18214](https://github.com/emberjs/ember.js/pull/18214) [DEPRECATION] Implement the [Deprecate support for mouseEnter/Leave/Move Ember events](https://github.com/emberjs/rfcs/blob/master/text/0486-deprecate-mouseenter.md). <ide> - [#18217](https://github.com/emberjs/ember.js/pull/18217) [BUGFIX] Adds ability for computed props to depend on args <ide> - [#18222](https://github.com/emberjs/ember.js/pull/18222) [BUGFIX] Matches assertion behavior for CPs computing after destroy <ide>
1
Text
Text
fix a typo in the 3.8 announcement
d5fe1f66ac534870cbec6b620a51797349c87f7a
<ide><path>docs/topics/3.8-announcement.md <ide> the view: <ide> def perform_create(self, serializer): <ide> serializer.save(owner=self.request.user) <ide> <del>Alternatively you may override `save()` or `create()` or `update()` on the serialiser as appropriate. <add>Alternatively you may override `save()` or `create()` or `update()` on the serializer as appropriate. <ide> <ide> --- <ide>
1
Go
Go
add link between -d and --log-level=debug back in
a85ca8b7c40f05f2b6471cc30fb8d5271605c1d1
<ide><path>docker/docker.go <ide> func main() { <ide> <ide> if *flDebug { <ide> os.Setenv("DEBUG", "1") <add> setLogLevel(logrus.DebugLevel) <ide> } <ide> <ide> if len(flHosts) == 0 { <ide><path>integration-cli/docker_cli_daemon_test.go <ide> func (s *DockerDaemonSuite) TestDaemonFlagD(c *check.C) { <ide> c.Fatal(err) <ide> } <ide> content, _ := ioutil.ReadFile(s.d.logFile.Name()) <del> if strings.Contains(string(content), `level=debug`) { <del> c.Fatalf(`Should not have level="debug" in log file using -D:\n%s`, string(content)) <add> if !strings.Contains(string(content), `level=debug`) { <add> c.Fatalf(`Should have level="debug" in log file using -D:\n%s`, string(content)) <ide> } <ide> } <ide> <ide> func (s *DockerDaemonSuite) TestDaemonFlagDebug(c *check.C) { <ide> c.Fatal(err) <ide> } <ide> content, _ := ioutil.ReadFile(s.d.logFile.Name()) <del> if strings.Contains(string(content), `level=debug`) { <del> c.Fatalf(`Should not have level="debug" in log file using --debug:\n%s`, string(content)) <add> if !strings.Contains(string(content), `level=debug`) { <add> c.Fatalf(`Should have level="debug" in log file using --debug:\n%s`, string(content)) <ide> } <ide> } <ide> <ide> func (s *DockerDaemonSuite) TestDaemonFlagDebugLogLevelFatal(c *check.C) { <ide> c.Fatal(err) <ide> } <ide> content, _ := ioutil.ReadFile(s.d.logFile.Name()) <del> if strings.Contains(string(content), `level=debug`) { <del> c.Fatalf(`Should not have level="debug" in log file when using both --debug and --log-level=fatal:\n%s`, string(content)) <add> if !strings.Contains(string(content), `level=debug`) { <add> c.Fatalf(`Should have level="debug" in log file when using both --debug and --log-level=fatal:\n%s`, string(content)) <ide> } <ide> } <ide>
2
Mixed
Go
refactor the statistics of network in docker stats
d3379946ec96fb6163cb8c4517d7d5a067045801
<ide><path>api/client/stats.go <ide> func (s *containerStats) Collect(cli *DockerCli, streamStats bool) { <ide> ) <ide> go func() { <ide> for { <del> var v *types.Stats <add> var v *types.StatsJSON <ide> if err := dec.Decode(&v); err != nil { <ide> u <- err <ide> return <ide> func (s *containerStats) Collect(cli *DockerCli, streamStats bool) { <ide> s.Memory = float64(v.MemoryStats.Usage) <ide> s.MemoryLimit = float64(v.MemoryStats.Limit) <ide> s.MemoryPercentage = memPercent <del> s.NetworkRx = float64(v.Network.RxBytes) <del> s.NetworkTx = float64(v.Network.TxBytes) <add> s.NetworkRx, s.NetworkTx = calculateNetwork(v.Networks) <ide> s.BlockRead = float64(blkRead) <ide> s.BlockWrite = float64(blkWrite) <ide> s.mu.Unlock() <ide> func (cli *DockerCli) CmdStats(args ...string) error { <ide> return nil <ide> } <ide> <del>func calculateCPUPercent(previousCPU, previousSystem uint64, v *types.Stats) float64 { <add>func calculateCPUPercent(previousCPU, previousSystem uint64, v *types.StatsJSON) float64 { <ide> var ( <ide> cpuPercent = 0.0 <ide> // calculate the change for the cpu usage of the container in between readings <ide> func calculateBlockIO(blkio types.BlkioStats) (blkRead uint64, blkWrite uint64) <ide> } <ide> return <ide> } <add> <add>func calculateNetwork(network map[string]types.NetworkStats) (float64, float64) { <add> var rx, tx float64 <add> <add> for _, v := range network { <add> rx += float64(v.RxBytes) <add> tx += float64(v.TxBytes) <add> } <add> return rx, tx <add>} <ide><path>api/server/container.go <ide> import ( <ide> "github.com/docker/docker/daemon" <ide> "github.com/docker/docker/pkg/ioutils" <ide> "github.com/docker/docker/pkg/signal" <add> "github.com/docker/docker/pkg/version" <ide> "github.com/docker/docker/runconfig" <ide> ) <ide> <ide> func (s *Server) getContainersStats(ctx context.Context, w http.ResponseWriter, <ide> closeNotifier = notifier.CloseNotify() <ide> } <ide> <add> version, _ := ctx.Value("api-version").(version.Version) <ide> config := &daemon.ContainerStatsConfig{ <ide> Stream: stream, <ide> OutStream: out, <ide> Stop: closeNotifier, <add> Version: version, <ide> } <ide> <ide> return s.daemon.ContainerStats(container, config) <ide><path>api/types/stats.go <ide> type NetworkStats struct { <ide> <ide> // Stats is Ultimate struct aggregating all types of stats of one container <ide> type Stats struct { <del> Read time.Time `json:"read"` <del> Network NetworkStats `json:"network,omitempty"` <del> PreCPUStats CPUStats `json:"precpu_stats,omitempty"` <del> CPUStats CPUStats `json:"cpu_stats,omitempty"` <del> MemoryStats MemoryStats `json:"memory_stats,omitempty"` <del> BlkioStats BlkioStats `json:"blkio_stats,omitempty"` <add> Read time.Time `json:"read"` <add> PreCPUStats CPUStats `json:"precpu_stats,omitempty"` <add> CPUStats CPUStats `json:"cpu_stats,omitempty"` <add> MemoryStats MemoryStats `json:"memory_stats,omitempty"` <add> BlkioStats BlkioStats `json:"blkio_stats,omitempty"` <add>} <add> <add>// StatsJSONPre121 is a backcompatibility struct along with ContainerConfig <add>type StatsJSONPre121 struct { <add> Stats <add> <add> // Network is for fallback stats where API Version < 1.21 <add> Network NetworkStats `json:"network,omitempty"` <add>} <add> <add>// StatsJSON is newly used Networks <add>type StatsJSON struct { <add> Stats <add> <add> // Networks request version >=1.21 <add> Networks map[string]NetworkStats `json:"networks,omitempty"` <ide> } <ide><path>daemon/stats.go <ide> import ( <ide> <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/daemon/execdriver" <add> "github.com/docker/docker/pkg/version" <ide> "github.com/docker/libnetwork/osl" <ide> "github.com/opencontainers/runc/libcontainer" <ide> ) <ide> type ContainerStatsConfig struct { <ide> Stream bool <ide> OutStream io.Writer <ide> Stop <-chan bool <add> Version version.Version <ide> } <ide> <ide> // ContainerStats writes information about the container to the stream <ide> func (daemon *Daemon) ContainerStats(container *Container, config *ContainerStat <ide> } <ide> <ide> var preCPUStats types.CPUStats <del> getStat := func(v interface{}) *types.Stats { <add> getStatJSON := func(v interface{}) *types.StatsJSON { <ide> update := v.(*execdriver.ResourceStats) <ide> // Retrieve the nw statistics from libnetwork and inject them in the Stats <ide> if nwStats, err := daemon.getNetworkStats(container); err == nil { <ide> func (daemon *Daemon) ContainerStats(container *Container, config *ContainerStat <ide> return nil <ide> } <ide> <del> s := getStat(v) <add> statsJSON := getStatJSON(v) <add> if config.Version.LessThan("1.21") { <add> var ( <add> rxBytes uint64 <add> rxPackets uint64 <add> rxErrors uint64 <add> rxDropped uint64 <add> txBytes uint64 <add> txPackets uint64 <add> txErrors uint64 <add> txDropped uint64 <add> ) <add> for _, v := range statsJSON.Networks { <add> rxBytes += v.RxBytes <add> rxPackets += v.RxPackets <add> rxErrors += v.RxErrors <add> rxDropped += v.RxDropped <add> txBytes += v.TxBytes <add> txPackets += v.TxPackets <add> txErrors += v.TxErrors <add> txDropped += v.TxDropped <add> } <add> statsJSONPre121 := &types.StatsJSONPre121{ <add> Stats: statsJSON.Stats, <add> Network: types.NetworkStats{ <add> RxBytes: rxBytes, <add> RxPackets: rxPackets, <add> RxErrors: rxErrors, <add> RxDropped: rxDropped, <add> TxBytes: txBytes, <add> TxPackets: txPackets, <add> TxErrors: txErrors, <add> TxDropped: txDropped, <add> }, <add> } <add> <add> if !config.Stream && noStreamFirstFrame { <add> // prime the cpu stats so they aren't 0 in the final output <add> noStreamFirstFrame = false <add> continue <add> } <add> <add> if err := enc.Encode(statsJSONPre121); err != nil { <add> return err <add> } <add> <add> if !config.Stream { <add> return nil <add> } <add> } <add> <ide> if !config.Stream && noStreamFirstFrame { <ide> // prime the cpu stats so they aren't 0 in the final output <ide> noStreamFirstFrame = false <ide> continue <ide> } <ide> <del> if err := enc.Encode(s); err != nil { <add> if err := enc.Encode(statsJSON); err != nil { <ide> return err <ide> } <ide> <ide><path>daemon/stats_freebsd.go <ide> import ( <ide> ) <ide> <ide> // convertStatsToAPITypes converts the libcontainer.Stats to the api specific <del>// structs. This is done to preserve API compatibility and versioning. <del>func convertStatsToAPITypes(ls *libcontainer.Stats) *types.Stats { <add>// structs. This is done to preserve API compatibility and versioning. <add>func convertStatsToAPITypes(ls *libcontainer.Stats) *types.StatsJSON { <ide> // TODO FreeBSD. Refactor accordingly to fill in stats. <del> s := &types.Stats{} <add> s := &types.StatsJSON{} <ide> return s <ide> } <ide><path>daemon/stats_linux.go <ide> import ( <ide> ) <ide> <ide> // convertStatsToAPITypes converts the libcontainer.Stats to the api specific <del>// structs. This is done to preserve API compatibility and versioning. <del>func convertStatsToAPITypes(ls *libcontainer.Stats) *types.Stats { <del> s := &types.Stats{} <add>// structs. This is done to preserve API compatibility and versioning. <add>func convertStatsToAPITypes(ls *libcontainer.Stats) *types.StatsJSON { <add> s := &types.StatsJSON{} <ide> if ls.Interfaces != nil { <del> s.Network = types.NetworkStats{} <add> s.Networks = make(map[string]types.NetworkStats) <ide> for _, iface := range ls.Interfaces { <del> s.Network.RxBytes += iface.RxBytes <del> s.Network.RxPackets += iface.RxPackets <del> s.Network.RxErrors += iface.RxErrors <del> s.Network.RxDropped += iface.RxDropped <del> s.Network.TxBytes += iface.TxBytes <del> s.Network.TxPackets += iface.TxPackets <del> s.Network.TxErrors += iface.TxErrors <del> s.Network.TxDropped += iface.TxDropped <add> // For API Version >= 1.21, the original data of network will <add> // be returned. <add> s.Networks[iface.Name] = types.NetworkStats{ <add> RxBytes: iface.RxBytes, <add> RxPackets: iface.RxPackets, <add> RxErrors: iface.RxErrors, <add> RxDropped: iface.RxDropped, <add> TxBytes: iface.TxBytes, <add> TxPackets: iface.TxPackets, <add> TxErrors: iface.TxErrors, <add> TxDropped: iface.TxDropped, <add> } <ide> } <ide> } <ide> <ide><path>daemon/stats_windows.go <ide> import ( <ide> ) <ide> <ide> // convertStatsToAPITypes converts the libcontainer.Stats to the api specific <del>// structs. This is done to preserve API compatibility and versioning. <del>func convertStatsToAPITypes(ls *libcontainer.Stats) *types.Stats { <add>// structs. This is done to preserve API compatibility and versioning. <add>func convertStatsToAPITypes(ls *libcontainer.Stats) *types.StatsJSON { <ide> // TODO Windows. Refactor accordingly to fill in stats. <del> s := &types.Stats{} <add> s := &types.StatsJSON{} <ide> return s <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> * `VolumeDriver` has been moved from config to hostConfig to make the configuration portable. <ide> * `GET /images/(name)/json` now returns information about tags of the image. <ide> * The `config` option now accepts the field `StopSignal`, which specifies the signal to use to kill a container. <add>* `GET /containers/(id)/stats` will return networking information respectively for each interface. <ide> <ide> <ide> ### v1.20 API changes <ide><path>docs/reference/api/docker_remote_api_v1.21.md <ide> This endpoint returns a live stream of a container's resource usage statistics. <ide> <ide> { <ide> "read" : "2015-01-08T22:57:31.547920715Z", <del> "network" : { <del> "rx_dropped" : 0, <del> "rx_bytes" : 648, <del> "rx_errors" : 0, <del> "tx_packets" : 8, <del> "tx_dropped" : 0, <del> "rx_packets" : 8, <del> "tx_errors" : 0, <del> "tx_bytes" : 648 <add> "network": { <add> "eth0": { <add> "rx_bytes": 5338, <add> "rx_dropped": 0, <add> "rx_errors": 0, <add> "rx_packets": 36, <add> "tx_bytes": 648, <add> "tx_dropped": 0, <add> "tx_errors": 0, <add> "tx_packets": 8 <add> }, <add> "eth5": { <add> "rx_bytes": 4641, <add> "rx_dropped": 0, <add> "rx_errors": 0, <add> "rx_packets": 26, <add> "tx_bytes": 690, <add> "tx_dropped": 0, <add> "tx_errors": 0, <add> "tx_packets": 9 <add> } <ide> }, <ide> "memory_stats" : { <ide> "stats" : { <ide><path>integration-cli/docker_api_stats_test.go <ide> func (s *DockerSuite) TestApiNetworkStats(c *check.C) { <ide> contIP := findContainerIP(c, id) <ide> numPings := 10 <ide> <add> var preRxPackets uint64 <add> var preTxPackets uint64 <add> var postRxPackets uint64 <add> var postTxPackets uint64 <add> <ide> // Get the container networking stats before and after pinging the container <ide> nwStatsPre := getNetworkStats(c, id) <add> for _, v := range nwStatsPre { <add> preRxPackets += v.RxPackets <add> preTxPackets += v.TxPackets <add> } <add> <ide> countParam := "-c" <ide> if runtime.GOOS == "windows" { <ide> countParam = "-n" // Ping count parameter is -n on Windows <ide> func (s *DockerSuite) TestApiNetworkStats(c *check.C) { <ide> pingouts := string(pingout[:]) <ide> c.Assert(err, check.IsNil) <ide> nwStatsPost := getNetworkStats(c, id) <add> for _, v := range nwStatsPost { <add> postRxPackets += v.RxPackets <add> postTxPackets += v.TxPackets <add> } <ide> <ide> // Verify the stats contain at least the expected number of packets (account for ARP) <del> expRxPkts := 1 + nwStatsPre.RxPackets + uint64(numPings) <del> expTxPkts := 1 + nwStatsPre.TxPackets + uint64(numPings) <del> c.Assert(nwStatsPost.TxPackets >= expTxPkts, check.Equals, true, <del> check.Commentf("Reported less TxPackets than expected. Expected >= %d. Found %d. %s", expTxPkts, nwStatsPost.TxPackets, pingouts)) <del> c.Assert(nwStatsPost.RxPackets >= expRxPkts, check.Equals, true, <del> check.Commentf("Reported less Txbytes than expected. Expected >= %d. Found %d. %s", expRxPkts, nwStatsPost.RxPackets, pingouts)) <add> expRxPkts := 1 + preRxPackets + uint64(numPings) <add> expTxPkts := 1 + preTxPackets + uint64(numPings) <add> c.Assert(postTxPackets >= expTxPkts, check.Equals, true, <add> check.Commentf("Reported less TxPackets than expected. Expected >= %d. Found %d. %s", expTxPkts, postTxPackets, pingouts)) <add> c.Assert(postRxPackets >= expRxPkts, check.Equals, true, <add> check.Commentf("Reported less Txbytes than expected. Expected >= %d. Found %d. %s", expRxPkts, postRxPackets, pingouts)) <ide> } <ide> <del>func getNetworkStats(c *check.C, id string) types.NetworkStats { <del> var st *types.Stats <add>func getNetworkStats(c *check.C, id string) map[string]types.NetworkStats { <add> var st *types.StatsJSON <ide> <ide> _, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats?stream=false", id), nil, "") <ide> c.Assert(err, check.IsNil) <ide> func getNetworkStats(c *check.C, id string) types.NetworkStats { <ide> c.Assert(err, check.IsNil) <ide> body.Close() <ide> <del> return st.Network <add> return st.Networks <ide> }
10
Python
Python
add tests for httplib ssl stuff
67f4be07ae34fea768ccee92149572f4bb23b0b2
<ide><path>test/test_httplib_ssl.py <add># Licensed to the Apache Software Foundation (ASF) under one or more <add># contributor license agreements. See the NOTICE file distributed with <add># this work for additional information regarding copyright ownership. <add># The ASF licenses this file to You under the Apache License, Version 2.0 <add># (the "License"); you may not use this file except in compliance with <add># the License. You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add> <add>import sys <add>import unittest <add>import os.path <add> <add>import libcloud.security <add>from libcloud.httplib_ssl import LibcloudHTTPSConnection <add> <add>class TestHttpLibSSLTests(unittest.TestCase): <add> <add> def setUp(self): <add> self.httplib_object = LibcloudHTTPSConnection('foo.bar') <add> <add> def test_connect(self): <add> pass <add> <add> def test_get_subject_alt_names(self): <add> cert1 = {'notAfter': 'Feb 16 16:54:50 2013 GMT', <add> 'subject': ((('countryName', 'US'),), <add> (('stateOrProvinceName', 'Delaware'),), <add> (('localityName', 'Wilmington'),), <add> (('organizationName', 'Python Software Foundation'),), <add> (('organizationalUnitName', 'SSL'),), <add> (('commonName', 'somemachine.python.org'),))} <add> <add> cert2 = {'notAfter': 'Feb 16 16:54:50 2013 GMT', <add> 'subject': ((('countryName', 'US'),), <add> (('stateOrProvinceName', 'Delaware'),), <add> (('localityName', 'Wilmington'),), <add> (('organizationName', 'Python Software Foundation'),), <add> (('organizationalUnitName', 'SSL'),), <add> (('commonName', 'somemachine.python.org'),)), <add> 'subjectAltName': ((('DNS', 'foo.alt.name')), <add> (('DNS', 'foo.alt.name.1')))} <add> <add> self.assertEqual(self.httplib_object._get_subject_alt_names(cert=cert1), <add> []) <add> <add> alt_names = self.httplib_object._get_subject_alt_names(cert=cert2) <add> self.assertEqual(len(alt_names), 2) <add> self.assertTrue('foo.alt.name' in alt_names) <add> self.assertTrue('foo.alt.name.1' in alt_names) <add> <add> def test_get_common_name(self): <add> cert = {'notAfter': 'Feb 16 16:54:50 2013 GMT', <add> 'subject': ((('countryName', 'US'),), <add> (('stateOrProvinceName', 'Delaware'),), <add> (('localityName', 'Wilmington'),), <add> (('organizationName', 'Python Software Foundation'),), <add> (('organizationalUnitName', 'SSL'),), <add> (('commonName', 'somemachine.python.org'),))} <add> <add> self.assertEqual(self.httplib_object._get_common_name(cert)[0], <add> 'somemachine.python.org') <add> self.assertEqual(self.httplib_object._get_common_name({}), <add> None) <add> <add> def test_setup_verify(self): <add> # @TODO: catch warnings <add> libcloud.security.VERIFY_SSL_CERT = True <add> self.httplib_object._setup_verify() <add> <add> libcloud.security.VERIFY_SSL_CERT = False <add> self.httplib_object._setup_verify() <add> <add> def test_setup_ca_cert(self): <add> # @TODO: catch warnings <add> self.httplib_object.verify = False <add> self.httplib_object._setup_ca_cert() <add> <add> self.assertEqual(self.httplib_object.ca_cert, None) <add> <add> self.httplib_object.verify = True <add> <add> libcloud.security.CA_CERTS_PATH = [os.path.abspath(__file__)] <add> self.httplib_object._setup_ca_cert() <add> self.assertTrue(self.httplib_object.ca_cert is not None) <add> <add> libcloud.security.CA_CERTS_PATH = [] <add> self.httplib_object._setup_ca_cert() <add> self.assertFalse(self.httplib_object.ca_cert) <add> self.assertFalse(self.httplib_object.verify) <add> <add>if __name__ == '__main__': <add> sys.exit(unittest.main())
1
Python
Python
fix crash on non-linux platforms
f64533e49c9011a386f0cf0d550694a23802c9c5
<ide><path>glances/plugins/glances_percpu.py <ide> def msg_curse(self, args=None): <ide> msg = ' {0:>6.1%}'.format(cpu['system'] / 100) <ide> ret.append(self.curse_add_line(msg, self.get_alert(cpu['system'], header="system"))) <ide> <del> # IoWait CPU <add> # Idle CPU <ide> if 'user' in self.stats[0]: <ide> # New line <ide> ret.append(self.curse_new_line()) <del> msg = '{0:8}'.format(_("iowait:")) <add> msg = '{0:8}'.format(_("idle:")) <ide> ret.append(self.curse_add_line(msg)) <ide> for cpu in self.stats: <del> msg = ' {0:>6.1%}'.format(cpu['iowait'] / 100) <del> ret.append(self.curse_add_line(msg, self.get_alert(cpu['iowait'], header="iowait"))) <add> msg = ' {0:>6.1%}'.format(cpu['idle'] / 100) <add> ret.append(self.curse_add_line(msg)) <ide> <ide> # Return the message with decoration <ide> return ret
1
Javascript
Javascript
convert moment.js to es6 modules
d5262a01beec4f6ed1b0ad73ba2da66782b2f60b
<ide><path>lib/create/check-overflow.js <add>import { daysInMonth } from "../units/month"; <add>import { YEAR, MONTH, DATE, HOUR, MINUTE, SECOND, MILLISECOND } from "../units/constants"; <add> <add>export default function checkOverflow (m) { <add> var overflow; <add> var a = m._a; <add> <add> if (a && m._pf.overflow === -2) { <add> overflow = <add> a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : <add> a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : <add> a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR : <add> a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : <add> a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : <add> a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : <add> -1; <add> <add> if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { <add> overflow = DATE; <add> } <add> <add> m._pf.overflow = overflow; <add> } <add> <add> return m; <add>} <add> <ide><path>lib/create/date-from-array.js <add>export function createDate (y, m, d, h, M, s, ms) { <add> //can't just apply() to create a date: <add> //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply <add> var date = new Date(y, m, d, h, M, s, ms); <add> <add> //the date constructor doesn't accept years < 1970 <add> if (y < 1970) { <add> date.setFullYear(y); <add> } <add> return date; <add>} <add> <add>export function createUTCDate (y) { <add> var date = new Date(Date.UTC.apply(null, arguments)); <add> if (y < 1970) { <add> date.setUTCFullYear(y); <add> } <add> return date; <add>} <ide><path>lib/create/default-parsing-flags.js <add>export default function defaultParsingFlags() { <add> // We need to deep clone this object. <add> return { <add> empty : false, <add> unusedTokens : [], <add> unusedInput : [], <add> overflow : -2, <add> charsLeftOver : 0, <add> nullInput : false, <add> invalidMonth : null, <add> invalidFormat : false, <add> userInvalidated : false, <add> iso : false <add> }; <add>} <ide><path>lib/create/from-anything.js <add>import defaultParsingFlags from "./default-parsing-flags"; <add>import isArray from "../utils/is-array"; <add>import isDate from "../utils/is-date"; <add>import map from "../utils/map"; <add>import { createInvalid } from "./valid"; <add>import { Moment, isMoment } from "../moment/constructor"; <add>import { getLocale } from "../locale/locales"; <add>import { hooks } from "../utils/hooks"; <add>import checkOverflow from "./check-overflow"; <add> <add>import { configFromStringAndArray } from "./from-string-and-array"; <add>import { configFromStringAndFormat } from "./from-string-and-format"; <add>import { configFromString } from "./from-string"; <add>import { configFromArray } from "./from-array"; <add>import { configFromObject } from "./from-object"; <add> <add>function createFromConfig (config) { <add> var input = config._i, <add> format = config._f, <add> res; <add> <add> config._locale = config._locale || getLocale(config._l); <add> <add> if (input === null || (format === undefined && input === '')) { <add> return createInvalid({nullInput: true}); <add> } <add> <add> if (typeof input === 'string') { <add> config._i = input = config._locale.preparse(input); <add> } <add> <add> if (isMoment(input)) { <add> return new Moment(checkOverflow(input)); <add> } else if (isArray(format)) { <add> configFromStringAndArray(config); <add> } else if (format) { <add> configFromStringAndFormat(config); <add> } else { <add> configFromInput(config); <add> } <add> <add> res = new Moment(checkOverflow(config)); <add> if (res._nextDay) { <add> // Adding is smart enough around DST <add> res.add(1, 'd'); <add> res._nextDay = undefined; <add> } <add> <add> return res; <add>} <add> <add>function configFromInput(config) { <add> var input = config._i; <add> if (input === undefined) { <add> config._d = new Date(); <add> } else if (isDate(input)) { <add> config._d = new Date(+input); <add> } else if (typeof input === 'string') { <add> configFromString(config); <add> } else if (isArray(input)) { <add> config._a = map(input.slice(0), function (obj) { <add> return parseInt(obj, 10); <add> }); <add> configFromArray(config); <add> } else if (typeof(input) === 'object') { <add> configFromObject(config); <add> } else if (typeof(input) === 'number') { <add> // from milliseconds <add> config._d = new Date(input); <add> } else { <add> hooks.createFromInputFallback(config); <add> } <add>} <add> <add>export function createLocalOrUTC (input, format, locale, strict, isUTC) { <add> var c = {}; <add> <add> if (typeof(locale) === 'boolean') { <add> strict = locale; <add> locale = undefined; <add> } <add> // object construction must be done this way. <add> // https://github.com/moment/moment/issues/1423 <add> c._isAMomentObject = true; <add> c._useUTC = c._isUTC = isUTC; <add> c._l = locale; <add> c._i = input; <add> c._f = format; <add> c._strict = strict; <add> c._pf = defaultParsingFlags(); <add> <add> return createFromConfig(c); <add>} <ide><path>lib/create/from-array.js <add>import { createDate, createUTCDate } from "./date-from-array"; <add>import { daysInYear } from "../units/year"; <add>import { weekOfYear } from "../units/week"; <add>import { dayOfYearFromWeeks } from "../units/day-of-year"; <add>import { YEAR, MONTH, DATE, HOUR, MINUTE, SECOND, MILLISECOND } from "../units/constants"; <add>import { createLocal } from "./local"; <add>import defaults from "../utils/defaults"; <add> <add>function currentDateArray(config) { <add> var now = new Date(); <add> if (config._useUTC) { <add> return [now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()]; <add> } <add> return [now.getFullYear(), now.getMonth(), now.getDate()]; <add>} <add> <add>// convert an array to a date. <add>// the array should mirror the parameters below <add>// note: all values past the year are optional and will default to the lowest possible value. <add>// [year, month, day , hour, minute, second, millisecond] <add>export function configFromArray (config) { <add> var i, date, input = [], currentDate, yearToUse; <add> <add> if (config._d) { <add> return; <add> } <add> <add> currentDate = currentDateArray(config); <add> <add> //compute day of the year from weeks and weekdays <add> if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { <add> dayOfYearFromWeekInfo(config); <add> } <add> <add> //if the day of the year is set, figure out what it is <add> if (config._dayOfYear) { <add> yearToUse = defaults(config._a[YEAR], currentDate[YEAR]); <add> <add> if (config._dayOfYear > daysInYear(yearToUse)) { <add> config._pf._overflowDayOfYear = true; <add> } <add> <add> date = createUTCDate(yearToUse, 0, config._dayOfYear); <add> config._a[MONTH] = date.getUTCMonth(); <add> config._a[DATE] = date.getUTCDate(); <add> } <add> <add> // Default to current date. <add> // * if no year, month, day of month are given, default to today <add> // * if day of month is given, default month and year <add> // * if month is given, default only year <add> // * if year is given, don't default anything <add> for (i = 0; i < 3 && config._a[i] == null; ++i) { <add> config._a[i] = input[i] = currentDate[i]; <add> } <add> <add> // Zero out whatever was not defaulted, including time <add> for (; i < 7; i++) { <add> config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; <add> } <add> <add> // Check for 24:00:00.000 <add> if (config._a[HOUR] === 24 && <add> config._a[MINUTE] === 0 && <add> config._a[SECOND] === 0 && <add> config._a[MILLISECOND] === 0) { <add> config._nextDay = true; <add> config._a[HOUR] = 0; <add> } <add> <add> config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input); <add> // Apply timezone offset from input. The actual utcOffset can be changed <add> // with parseZone. <add> if (config._tzm != null) { <add> config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); <add> } <add> <add> if (config._nextDay) { <add> config._a[HOUR] = 24; <add> } <add>} <add> <add>function dayOfYearFromWeekInfo(config) { <add> var w, weekYear, week, weekday, dow, doy, temp; <add> <add> w = config._w; <add> if (w.GG != null || w.W != null || w.E != null) { <add> dow = 1; <add> doy = 4; <add> <add> // TODO: We need to take the current isoWeekYear, but that depends on <add> // how we interpret now (local, utc, fixed offset). So create <add> // a now version of current config (take local/utc/offset flags, and <add> // create now). <add> weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year); <add> week = defaults(w.W, 1); <add> weekday = defaults(w.E, 1); <add> } else { <add> dow = config._locale._week.dow; <add> doy = config._locale._week.doy; <add> <add> weekYear = defaults(w.gg, config._a[YEAR], weekOfYear(createLocal(), dow, doy).year); <add> week = defaults(w.w, 1); <add> <add> if (w.d != null) { <add> // weekday -- low day numbers are considered next week <add> weekday = w.d; <add> if (weekday < dow) { <add> ++week; <add> } <add> } else if (w.e != null) { <add> // local weekday -- counting starts from begining of week <add> weekday = w.e + dow; <add> } else { <add> // default to begining of week <add> weekday = dow; <add> } <add> } <add> temp = dayOfYearFromWeeks(weekYear, week, weekday, doy, dow); <add> <add> config._a[YEAR] = temp.year; <add> config._dayOfYear = temp.dayOfYear; <add>} <ide><path>lib/create/from-object.js <add>import { normalizeObjectUnits } from "../units/aliases"; <add>import { configFromArray } from "./from-array"; <add> <add>export function configFromObject(config) { <add> if (config._d) { <add> return; <add> } <add> <add> var i = normalizeObjectUnits(config._i); <add> config._a = [i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond]; <add> <add> configFromArray(config); <add>} <ide><path>lib/create/from-string-and-array.js <add>import { copyConfig } from "../moment/constructor"; <add>import { configFromStringAndFormat } from "./from-string-and-format"; <add>import defaultParsingFlags from "./default-parsing-flags"; <add>import { isValid } from "./valid"; <add>import extend from "../utils/extend"; <add> <add>// date from string and array of format strings <add>export function configFromStringAndArray(config) { <add> var tempConfig, <add> bestMoment, <add> <add> scoreToBeat, <add> i, <add> currentScore; <add> <add> if (config._f.length === 0) { <add> config._pf.invalidFormat = true; <add> config._d = new Date(NaN); <add> return; <add> } <add> <add> for (i = 0; i < config._f.length; i++) { <add> currentScore = 0; <add> tempConfig = copyConfig({}, config); <add> if (config._useUTC != null) { <add> tempConfig._useUTC = config._useUTC; <add> } <add> tempConfig._pf = defaultParsingFlags(); <add> tempConfig._f = config._f[i]; <add> configFromStringAndFormat(tempConfig); <add> <add> if (!isValid(tempConfig)) { <add> continue; <add> } <add> <add> // if there is any input that was not parsed add a penalty for that format <add> currentScore += tempConfig._pf.charsLeftOver; <add> <add> //or tokens <add> currentScore += tempConfig._pf.unusedTokens.length * 10; <add> <add> tempConfig._pf.score = currentScore; <add> <add> if (scoreToBeat == null || currentScore < scoreToBeat) { <add> scoreToBeat = currentScore; <add> bestMoment = tempConfig; <add> } <add> } <add> <add> extend(config, bestMoment || tempConfig); <add>} <ide><path>lib/create/from-string-and-format.js <add>import { configFromISO } from "./from-string"; <add>import { configFromArray } from "./from-array"; <add>import { getParseRegexForToken } from "../parse/regex"; <add>import { addTimeToArrayFromToken } from "../parse/token"; <add>import { expandFormat, formatTokenFunctions, formattingTokens } from "../format/format"; <add>import checkOverflow from "./check-overflow"; <add>import { HOUR } from "../units/constants"; <add>import { hooks } from "../utils/hooks"; <add> <add>// constant that refers to the ISO standard <add>hooks.ISO_8601 = function () {}; <add> <add>// date from string and format string <add>export function configFromStringAndFormat(config) { <add> // TODO: Move this to another part of the creation flow to prevent circular deps <add> if (config._f === hooks.ISO_8601) { <add> configFromISO(config); <add> return; <add> } <add> <add> config._a = []; <add> config._pf.empty = true; <add> <add> // This array is used to make a Date, either with `new Date` or `Date.UTC` <add> var string = '' + config._i, <add> i, parsedInput, tokens, token, skipped, <add> stringLength = string.length, <add> totalParsedInputLength = 0; <add> <add> tokens = expandFormat(config._f, config._locale).match(formattingTokens) || []; <add> <add> for (i = 0; i < tokens.length; i++) { <add> token = tokens[i]; <add> parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; <add> if (parsedInput) { <add> skipped = string.substr(0, string.indexOf(parsedInput)); <add> if (skipped.length > 0) { <add> config._pf.unusedInput.push(skipped); <add> } <add> string = string.slice(string.indexOf(parsedInput) + parsedInput.length); <add> totalParsedInputLength += parsedInput.length; <add> } <add> // don't parse if it's not a known token <add> if (formatTokenFunctions[token]) { <add> if (parsedInput) { <add> config._pf.empty = false; <add> } <add> else { <add> config._pf.unusedTokens.push(token); <add> } <add> addTimeToArrayFromToken(token, parsedInput, config); <add> } <add> else if (config._strict && !parsedInput) { <add> config._pf.unusedTokens.push(token); <add> } <add> } <add> <add> // add remaining unparsed input length to the string <add> config._pf.charsLeftOver = stringLength - totalParsedInputLength; <add> if (string.length > 0) { <add> config._pf.unusedInput.push(string); <add> } <add> <add> // clear _12h flag if hour is <= 12 <add> if (config._pf.bigHour === true && config._a[HOUR] <= 12) { <add> config._pf.bigHour = undefined; <add> } <add> // handle meridiem <add> config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem); <add> <add> configFromArray(config); <add> checkOverflow(config); <add>} <add> <add> <add>function meridiemFixWrap (locale, hour, meridiem) { <add> var isPm; <add> <add> if (meridiem == null) { <add> // nothing to do <add> return hour; <add> } <add> if (locale.meridiemHour != null) { <add> return locale.meridiemHour(hour, meridiem); <add> } else if (locale.isPM != null) { <add> // Fallback <add> isPm = locale.isPM(meridiem); <add> if (isPm && hour < 12) { <add> hour += 12; <add> } <add> if (!isPm && hour === 12) { <add> hour = 0; <add> } <add> return hour; <add> } else { <add> // this is not supposed to happen <add> return hour; <add> } <add>} <ide><path>lib/create/from-string.js <add>import { matchOffset } from "../parse/regex"; <add>import { configFromStringAndFormat } from "./from-string-and-format"; <add>import { hooks } from "../utils/hooks"; <add>import { deprecate } from "../utils/deprecate"; <add> <add>// iso 8601 regex <add>// 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) <add>var isoRegex = /^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/; <add> <add>var isoDates = [ <add> ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/], <add> ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/], <add> ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/], <add> ['GGGG-[W]WW', /\d{4}-W\d{2}/], <add> ['YYYY-DDD', /\d{4}-\d{3}/] <add>]; <add> <add>// iso time formats and regexes <add>var isoTimes = [ <add> ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/], <add> ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/], <add> ['HH:mm', /(T| )\d\d:\d\d/], <add> ['HH', /(T| )\d\d/] <add>]; <add> <add>var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i; <add> <add>// date from iso format <add>export function configFromISO(config) { <add> var i, l, <add> string = config._i, <add> match = isoRegex.exec(string); <add> <add> if (match) { <add> config._pf.iso = true; <add> for (i = 0, l = isoDates.length; i < l; i++) { <add> if (isoDates[i][1].exec(string)) { <add> // match[5] should be 'T' or undefined <add> config._f = isoDates[i][0] + (match[6] || ' '); <add> break; <add> } <add> } <add> for (i = 0, l = isoTimes.length; i < l; i++) { <add> if (isoTimes[i][1].exec(string)) { <add> config._f += isoTimes[i][0]; <add> break; <add> } <add> } <add> if (string.match(matchOffset)) { <add> config._f += 'Z'; <add> } <add> configFromStringAndFormat(config); <add> } else { <add> config._isValid = false; <add> } <add>} <add> <add>// date from iso format or fallback <add>export function configFromString(config) { <add> var matched = aspNetJsonRegex.exec(config._i); <add> <add> if (matched !== null) { <add> config._d = new Date(+matched[1]); <add> return; <add> } <add> <add> configFromISO(config); <add> if (config._isValid === false) { <add> delete config._isValid; <add> hooks.createFromInputFallback(config); <add> } <add>} <add> <add>hooks.createFromInputFallback = deprecate( <add> 'moment construction falls back to js Date. This is ' + <add> 'discouraged and will be removed in upcoming major ' + <add> 'release. Please refer to ' + <add> 'https://github.com/moment/moment/issues/1407 for more info.', <add> function (config) { <add> config._d = new Date(config._i + (config._useUTC ? ' UTC' : '')); <add> } <add>); <ide><path>lib/create/local.js <add>import { createLocalOrUTC } from "./from-anything"; <add> <add>export function createLocal (input, format, locale, strict) { <add> return createLocalOrUTC(input, format, locale, strict, false); <add>} <ide><path>lib/create/utc.js <add>import { createLocalOrUTC } from "./from-anything"; <add> <add>export function createUTC (input, format, locale, strict) { <add> return createLocalOrUTC(input, format, locale, strict, true).utc(); <add>} <ide><path>lib/create/valid.js <add>import extend from "../utils/extend"; <add>import { createUTC } from "./utc"; <add> <add>export function isValid(m) { <add> if (m._isValid == null) { <add> m._isValid = !isNaN(m._d.getTime()) && <add> m._pf.overflow < 0 && <add> !m._pf.empty && <add> !m._pf.invalidMonth && <add> !m._pf.nullInput && <add> !m._pf.invalidFormat && <add> !m._pf.userInvalidated; <add> <add> if (m._strict) { <add> m._isValid = m._isValid && <add> m._pf.charsLeftOver === 0 && <add> m._pf.unusedTokens.length === 0 && <add> m._pf.bigHour === undefined; <add> } <add> } <add> return m._isValid; <add>} <add> <add>export function createInvalid (flags) { <add> var m = createUTC(NaN); <add> if (flags != null) { <add> extend(m._pf, flags); <add> } <add> else { <add> m._pf.userInvalidated = true; <add> } <add> <add> return m; <add>} <ide><path>lib/duration/abs.js <add>var mathAbs = Math.abs; <add> <add>export function abs () { <add> var data = this._data; <add> <add> this._milliseconds = mathAbs(this._milliseconds); <add> this._days = mathAbs(this._days); <add> this._months = mathAbs(this._months); <add> <add> data.milliseconds = mathAbs(data.milliseconds); <add> data.seconds = mathAbs(data.seconds); <add> data.minutes = mathAbs(data.minutes); <add> data.hours = mathAbs(data.hours); <add> data.months = mathAbs(data.months); <add> data.years = mathAbs(data.years); <add> <add> return this; <add>} <ide><path>lib/duration/add-subtract.js <add>import { createDuration } from "./create"; <add> <add>function addSubtract (duration, input, value, direction) { <add> var other = createDuration(input, value); <add> <add> duration._milliseconds += direction * other._milliseconds; <add> duration._days += direction * other._days; <add> duration._months += direction * other._months; <add> <add> return duration._bubble(); <add>} <add> <add>// supports only 2.0-style add(1, 's') or add(duration) <add>export function add (input, value) { <add> return addSubtract(this, input, value, 1); <add>} <add> <add>// supports only 2.0-style subtract(1, 's') or subtract(duration) <add>export function subtract (input, value) { <add> return addSubtract(this, input, value, -1); <add>} <ide><path>lib/duration/as.js <add>import { daysToYears, yearsToDays } from "./bubble"; <add>import { normalizeUnits } from "../units/aliases"; <add>import toInt from "../utils/to-int"; <add> <add>export function as (units) { <add> var days; <add> var months; <add> var milliseconds = this._milliseconds; <add> <add> units = normalizeUnits(units); <add> <add> if (units === "month" || units === "year") { <add> days = this._days + milliseconds / 864e5; <add> months = this._months + daysToYears(days) * 12; <add> return units === "month" ? months : months / 12; <add> } else { <add> // handle milliseconds separately because of floating point math errors (issue #1867) <add> days = this._days + Math.round(yearsToDays(this._months / 12)); <add> switch (units) { <add> case "week" : return days / 7 + milliseconds / 6048e5; <add> case "day" : return days + milliseconds / 864e5; <add> case "hour" : return days * 24 + milliseconds / 36e5; <add> case "minute" : return days * 24 * 60 + milliseconds / 6e4; <add> case "second" : return days * 24 * 60 * 60 + milliseconds / 1000; <add> // Math.floor prevents floating point math errors here <add> case "millisecond": return Math.floor(days * 24 * 60 * 60 * 1000) + milliseconds; <add> default: throw new Error("Unknown unit " + units); <add> } <add> } <add>} <add> <add>// TODO: Use this.as('ms')? <add>export function valueOf () { <add> return ( <add> this._milliseconds + <add> this._days * 864e5 + <add> (this._months % 12) * 2592e6 + <add> toInt(this._months / 12) * 31536e6 <add> ); <add>} <add> <add>function makeAs (alias) { <add> return function () { <add> return this.as(alias); <add> }; <add>} <add> <add>export var asMilliseconds = makeAs("ms"); <add>export var asSeconds = makeAs("s"); <add>export var asMinutes = makeAs("m"); <add>export var asHours = makeAs("h"); <add>export var asDays = makeAs("d"); <add>export var asWeeks = makeAs("w"); <add>export var asMonths = makeAs("M"); <add>export var asYears = makeAs("y"); <ide><path>lib/duration/bubble.js <add>import absFloor from "../utils/abs-floor"; <add> <add>export function bubble () { <add> var milliseconds = this._milliseconds; <add> var days = this._days; <add> var months = this._months; <add> var data = this._data; <add> var seconds, minutes, hours, years = 0; <add> <add> // The following code bubbles up values, see the tests for <add> // examples of what that means. <add> data.milliseconds = milliseconds % 1000; <add> <add> seconds = absFloor(milliseconds / 1000); <add> data.seconds = seconds % 60; <add> <add> minutes = absFloor(seconds / 60); <add> data.minutes = minutes % 60; <add> <add> hours = absFloor(minutes / 60); <add> data.hours = hours % 24; <add> <add> days += absFloor(hours / 24); <add> <add> // Accurately convert days to years, assume start from year 0. <add> years = absFloor(daysToYears(days)); <add> days -= absFloor(yearsToDays(years)); <add> <add> // 30 days to a month <add> // TODO (iskren): Use anchor date (like 1st Jan) to compute this. <add> months += absFloor(days / 30); <add> days %= 30; <add> <add> // 12 months -> 1 year <add> years += absFloor(months / 12); <add> months %= 12; <add> <add> data.days = days; <add> data.months = months; <add> data.years = years; <add> <add> return this; <add>} <add> <add>export function daysToYears (days) { <add> // 400 years have 146097 days (taking into account leap year rules) <add> return days * 400 / 146097; <add>} <add> <add>export function yearsToDays (years) { <add> // years * 365 + absFloor(years / 4) - <add> // absFloor(years / 100) + absFloor(years / 400); <add> return years * 146097 / 400; <add>} <ide><path>lib/duration/constructor.js <add>import { normalizeObjectUnits } from "../units/aliases"; <add>import { getLocale } from "../locale/locales"; <add> <add>export function Duration (duration) { <add> var normalizedInput = normalizeObjectUnits(duration), <add> years = normalizedInput.year || 0, <add> quarters = normalizedInput.quarter || 0, <add> months = normalizedInput.month || 0, <add> weeks = normalizedInput.week || 0, <add> days = normalizedInput.day || 0, <add> hours = normalizedInput.hour || 0, <add> minutes = normalizedInput.minute || 0, <add> seconds = normalizedInput.second || 0, <add> milliseconds = normalizedInput.millisecond || 0; <add> <add> // representation for dateAddRemove <add> this._milliseconds = +milliseconds + <add> seconds * 1e3 + // 1000 <add> minutes * 6e4 + // 1000 * 60 <add> hours * 36e5; // 1000 * 60 * 60 <add> // Because of dateAddRemove treats 24 hours as different from a <add> // day when working around DST, we need to store them separately <add> this._days = +days + <add> weeks * 7; <add> // It is impossible translate months into days without knowing <add> // which months you are are talking about, so we have to store <add> // it separately. <add> this._months = +months + <add> quarters * 3 + <add> years * 12; <add> <add> this._data = {}; <add> <add> this._locale = getLocale(); <add> <add> this._bubble(); <add>} <add> <add>export function isDuration (obj) { <add> return obj instanceof Duration; <add>} <ide><path>lib/duration/create.js <add>import { Duration, isDuration } from "./constructor"; <add>import toInt from "../utils/to-int"; <add>import hasOwnProp from "../utils/has-own-prop"; <add>import { DATE, HOUR, MINUTE, SECOND, MILLISECOND } from "../units/constants"; <add>import { cloneWithOffset } from "../units/offset"; <add>import { createLocal } from "../create/local"; <add> <add>// ASP.NET json date format regex <add>var aspNetRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/; <add> <add>// from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html <add>// somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere <add>var isoRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/; <add> <add>export function createDuration (input, key) { <add> var duration = input, <add> // matching against regexp is expensive, do it on demand <add> match = null, <add> sign, <add> ret, <add> diffRes; <add> <add> if (isDuration(input)) { <add> duration = { <add> ms : input._milliseconds, <add> d : input._days, <add> M : input._months <add> }; <add> } else if (typeof input === 'number') { <add> duration = {}; <add> if (key) { <add> duration[key] = input; <add> } else { <add> duration.milliseconds = input; <add> } <add> } else if (!!(match = aspNetRegex.exec(input))) { <add> sign = (match[1] === '-') ? -1 : 1; <add> duration = { <add> y : 0, <add> d : toInt(match[DATE]) * sign, <add> h : toInt(match[HOUR]) * sign, <add> m : toInt(match[MINUTE]) * sign, <add> s : toInt(match[SECOND]) * sign, <add> ms : toInt(match[MILLISECOND]) * sign <add> }; <add> } else if (!!(match = isoRegex.exec(input))) { <add> sign = (match[1] === '-') ? -1 : 1; <add> duration = { <add> y : parseIso(match[2], sign), <add> M : parseIso(match[3], sign), <add> d : parseIso(match[4], sign), <add> h : parseIso(match[5], sign), <add> m : parseIso(match[6], sign), <add> s : parseIso(match[7], sign), <add> w : parseIso(match[8], sign) <add> }; <add> } else if (duration == null) {// checks for null or undefined <add> duration = {}; <add> } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) { <add> diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to)); <add> <add> duration = {}; <add> duration.ms = diffRes.milliseconds; <add> duration.M = diffRes.months; <add> } <add> <add> ret = new Duration(duration); <add> <add> if (isDuration(input) && hasOwnProp(input, '_locale')) { <add> ret._locale = input._locale; <add> } <add> <add> return ret; <add>} <add> <add>function parseIso (inp, sign) { <add> // We'd normally use ~~inp for this, but unfortunately it also <add> // converts floats to ints. <add> // inp may be undefined, so careful calling replace on it. <add> var res = inp && parseFloat(inp.replace(',', '.')); <add> // apply sign while we're at it <add> return (isNaN(res) ? 0 : res) * sign; <add>} <add> <add>function positiveMomentsDifference(base, other) { <add> var res = {milliseconds: 0, months: 0}; <add> <add> res.months = other.month() - base.month() + <add> (other.year() - base.year()) * 12; <add> if (base.clone().add(res.months, 'M').isAfter(other)) { <add> --res.months; <add> } <add> <add> res.milliseconds = +other - +(base.clone().add(res.months, 'M')); <add> <add> return res; <add>} <add> <add>function momentsDifference(base, other) { <add> var res; <add> other = cloneWithOffset(other, base); <add> if (base.isBefore(other)) { <add> res = positiveMomentsDifference(base, other); <add> } else { <add> res = positiveMomentsDifference(other, base); <add> res.milliseconds = -res.milliseconds; <add> res.months = -res.months; <add> } <add> <add> return res; <add>} <ide><path>lib/duration/duration.js <add>// Side effect imports <add>import "./prototype"; <add> <add>import { createDuration } from "./create"; <add>import { isDuration } from "./constructor"; <add>import { getSetRelativeTimeThreshold } from "./humanize"; <add> <add>export { <add> createDuration, <add> isDuration, <add> getSetRelativeTimeThreshold <add>}; <ide><path>lib/duration/get.js <add>import { normalizeUnits } from "../units/aliases"; <add>import absFloor from "../utils/abs-floor"; <add> <add>export function get (units) { <add> units = normalizeUnits(units); <add> return this[units + 's'](); <add>} <add> <add>function makeGetter(name) { <add> return function () { <add> return this._data[name]; <add> }; <add>} <add> <add>export var milliseconds = makeGetter('milliseconds'); <add>export var seconds = makeGetter('seconds'); <add>export var minutes = makeGetter('minutes'); <add>export var hours = makeGetter('hours'); <add>export var days = makeGetter('days'); <add>export var months = makeGetter('months'); <add>export var years = makeGetter('years'); <add> <add>export function weeks () { <add> return absFloor(this.days() / 7); <add>} <ide><path>lib/duration/humanize.js <add>import { createDuration } from "./create"; <add> <add>var round = Math.round; <add>var thresholds = { <add> s: 45, // seconds to minute <add> m: 45, // minutes to hour <add> h: 22, // hours to day <add> d: 26, // days to month <add> M: 11 // months to year <add>}; <add> <add>// helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize <add>function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { <add> return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); <add>} <add> <add>function relativeTime (posNegDuration, withoutSuffix, locale) { <add> var duration = createDuration(posNegDuration).abs(); <add> var seconds = round(duration.as('s')); <add> var minutes = round(duration.as('m')); <add> var hours = round(duration.as('h')); <add> var days = round(duration.as('d')); <add> var months = round(duration.as('M')); <add> var years = round(duration.as('y')); <add> <add> var a = seconds < thresholds.s && ['s', seconds] || <add> minutes === 1 && ['m'] || <add> minutes < thresholds.m && ['mm', minutes] || <add> hours === 1 && ['h'] || <add> hours < thresholds.h && ['hh', hours] || <add> days === 1 && ['d'] || <add> days < thresholds.d && ['dd', days] || <add> months === 1 && ['M'] || <add> months < thresholds.M && ['MM', months] || <add> years === 1 && ['y'] || ['yy', years]; <add> <add> a[2] = withoutSuffix; <add> a[3] = +posNegDuration > 0; <add> a[4] = locale; <add> return substituteTimeAgo.apply(null, a); <add>} <add> <add>// This function allows you to set a threshold for relative time strings <add>export function getSetRelativeTimeThreshold (threshold, limit) { <add> if (thresholds[threshold] === undefined) { <add> return false; <add> } <add> if (limit === undefined) { <add> return thresholds[threshold]; <add> } <add> thresholds[threshold] = limit; <add> return true; <add>} <add> <add>export function humanize (withSuffix) { <add> var locale = this.localeData(); <add> var output = relativeTime(this, !withSuffix, locale); <add> <add> if (withSuffix) { <add> output = locale.pastFuture(+this, output); <add> } <add> <add> return locale.postformat(output); <add>} <ide><path>lib/duration/iso-string.js <add>var abs = Math.abs; <add> <add>export function toISOString() { <add> // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js <add> var Y = abs(this.years()); <add> var M = abs(this.months()); <add> var D = abs(this.days()); <add> var h = abs(this.hours()); <add> var m = abs(this.minutes()); <add> var s = abs(this.seconds() + this.milliseconds() / 1000); <add> var total = this.asSeconds(); <add> <add> if (!total) { <add> // this is the same as C#'s (Noda) and python (isodate)... <add> // but not other JS (goog.date) <add> return 'P0D'; <add> } <add> <add> return (total < 0 ? '-' : '') + <add> 'P' + <add> (Y ? Y + 'Y' : '') + <add> (M ? M + 'M' : '') + <add> (D ? D + 'D' : '') + <add> ((h || m || s) ? 'T' : '') + <add> (h ? h + 'H' : '') + <add> (m ? m + 'M' : '') + <add> (s ? s + 'S' : ''); <add>} <ide><path>lib/duration/prototype.js <add>import { Duration } from "./constructor"; <add> <add>var proto = Duration.prototype; <add> <add>import { abs } from "./abs"; <add>import { add, subtract } from "./add-subtract"; <add>import { as, asMilliseconds, asSeconds, asMinutes, asHours, asDays, asWeeks, asMonths, asYears, valueOf } from "./as"; <add>import { bubble } from "./bubble"; <add>import { get, milliseconds, seconds, minutes, hours, days, months, years, weeks } from "./get"; <add>import { humanize } from "./humanize"; <add>import { toISOString } from "./iso-string"; <add>import { lang, locale, localeData } from "../moment/locale"; <add> <add>proto.abs = abs; <add>proto.add = add; <add>proto.subtract = subtract; <add>proto.as = as; <add>proto.asMilliseconds = asMilliseconds; <add>proto.asSeconds = asSeconds; <add>proto.asMinutes = asMinutes; <add>proto.asHours = asHours; <add>proto.asDays = asDays; <add>proto.asWeeks = asWeeks; <add>proto.asMonths = asMonths; <add>proto.asYears = asYears; <add>proto.valueOf = valueOf; <add>proto._bubble = bubble; <add>proto.get = get; <add>proto.milliseconds = milliseconds; <add>proto.seconds = seconds; <add>proto.minutes = minutes; <add>proto.hours = hours; <add>proto.days = days; <add>proto.weeks = weeks; <add>proto.months = months; <add>proto.years = years; <add>proto.humanize = humanize; <add>proto.toISOString = toISOString; <add>proto.toString = toISOString; <add>proto.toJSON = toISOString; <add>proto.locale = locale; <add>proto.localeData = localeData; <add> <add>// Deprecations <add>import { deprecate } from "../utils/deprecate"; <add> <add>proto.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString); <add>proto.lang = lang; <ide><path>lib/format/format.js <add>import zeroFill from "../utils/zero-fill"; <add> <add>export var formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|x|X|zz?|ZZ?|.)/g; <add> <add>var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g; <add> <add>var formatFunctions = {}; <add> <add>export var formatTokenFunctions = {}; <add> <add>// token: "M" <add>// padded: ["MM", 2] <add>// ordinal: "Mo" <add>// callback: function () { this.month() + 1 } <add>export function addFormatToken (token, padded, ordinal, callback) { <add> var func = callback; <add> if (typeof callback === "string") { <add> func = function () { <add> return this[callback](); <add> }; <add> } <add> if (token) { <add> formatTokenFunctions[token] = func; <add> } <add> if (padded) { <add> formatTokenFunctions[padded[0]] = function () { <add> return zeroFill(func.apply(this, arguments), padded[1], padded[2]); <add> }; <add> } <add> if (ordinal) { <add> formatTokenFunctions[ordinal] = function () { <add> return this.localeData().ordinal(func.apply(this, arguments), token); <add> }; <add> } <add>} <add> <add>function removeFormattingTokens(input) { <add> if (input.match(/\[[\s\S]/)) { <add> return input.replace(/^\[|\]$/g, ''); <add> } <add> return input.replace(/\\/g, ''); <add>} <add> <add>function makeFormatFunction(format) { <add> var array = format.match(formattingTokens), i, length; <add> <add> for (i = 0, length = array.length; i < length; i++) { <add> if (formatTokenFunctions[array[i]]) { <add> array[i] = formatTokenFunctions[array[i]]; <add> } else { <add> array[i] = removeFormattingTokens(array[i]); <add> } <add> } <add> <add> return function (mom) { <add> var output = ''; <add> for (i = 0; i < length; i++) { <add> output += array[i] instanceof Function ? array[i].call(mom, format) : array[i]; <add> } <add> return output; <add> }; <add>} <add> <add>// format date using native date object <add>export function formatMoment(m, format) { <add> if (!m.isValid()) { <add> return m.localeData().invalidDate(); <add> } <add> <add> format = expandFormat(format, m.localeData()); <add> <add> if (!formatFunctions[format]) { <add> formatFunctions[format] = makeFormatFunction(format); <add> } <add> <add> return formatFunctions[format](m); <add>} <add> <add>export function expandFormat(format, locale) { <add> var i = 5; <add> <add> function replaceLongDateFormatTokens(input) { <add> return locale.longDateFormat(input) || input; <add> } <add> <add> localFormattingTokens.lastIndex = 0; <add> while (i >= 0 && localFormattingTokens.test(format)) { <add> format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); <add> localFormattingTokens.lastIndex = 0; <add> i -= 1; <add> } <add> <add> return format; <add>} <add> <ide><path>lib/locale/calendar.js <add>export var defaultCalendar = { <add> sameDay : '[Today at] LT', <add> nextDay : '[Tomorrow at] LT', <add> nextWeek : 'dddd [at] LT', <add> lastDay : '[Yesterday at] LT', <add> lastWeek : '[Last] dddd [at] LT', <add> sameElse : 'L' <add>}; <add> <add>export function calendar (key, mom, now) { <add> var output = this._calendar[key]; <add> return typeof output === 'function' ? output.call(mom, now) : output; <add>} <ide><path>lib/locale/constructor.js <add>export function Locale() { <add> <add>} <ide><path>lib/locale/en.js <add>import "./prototype"; <add>import { getSetGlobalLocale } from "./locales"; <add>import toInt from "../utils/to-int"; <add> <add>getSetGlobalLocale('en', { <add> ordinalParse: /\d{1,2}(th|st|nd|rd)/, <add> ordinal : function (number) { <add> var b = number % 10, <add> output = (toInt(number % 100 / 10) === 1) ? 'th' : <add> (b === 1) ? 'st' : <add> (b === 2) ? 'nd' : <add> (b === 3) ? 'rd' : 'th'; <add> return number + output; <add> } <add>}); <ide><path>lib/locale/formats.js <add>export var defaultLongDateFormat = { <add> LTS : 'h:mm:ss A', <add> LT : 'h:mm A', <add> L : 'MM/DD/YYYY', <add> LL : 'MMMM D, YYYY', <add> LLL : 'MMMM D, YYYY LT', <add> LLLL : 'dddd, MMMM D, YYYY LT' <add>}; <add> <add>export function longDateFormat (key) { <add> var output = this._longDateFormat[key]; <add> if (!output && this._longDateFormat[key.toUpperCase()]) { <add> output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) { <add> return val.slice(1); <add> }); <add> this._longDateFormat[key] = output; <add> } <add> return output; <add>} <ide><path>lib/locale/invalid.js <add>export var defaultInvalidDate = 'Invalid date'; <add> <add>export function invalidDate () { <add> return this._invalidDate; <add>} <ide><path>lib/locale/lists.js <add>import { getLocale } from "./locales"; <add>import { createUTC } from "../create/utc"; <add> <add>function get (format, index, field, setter) { <add> var locale = getLocale(); <add> var utc = createUTC().set(setter, index); <add> return locale[field](utc, format); <add>} <add> <add>function list (format, index, field, count, setter) { <add> if (typeof format === 'number') { <add> index = format; <add> format = undefined; <add> } <add> <add> format = format || ''; <add> <add> if (index != null) { <add> return get(format, index, field, setter); <add> } <add> <add> var i; <add> var out = []; <add> for (i = 0; i < count; i++) { <add> out[i] = get(format, i, field, setter); <add> } <add> return out; <add>} <add> <add>export function listMonths (format, index) { <add> return list(format, index, "months", 12, "month"); <add>} <add> <add>export function listMonthsShort (format, index) { <add> return list(format, index, "monthsShort", 12, "month"); <add>} <add> <add>export function listWeekdays (format, index) { <add> return list(format, index, "weekdays", 7, "day"); <add>} <add> <add>export function listWeekdaysShort (format, index) { <add> return list(format, index, "weekdaysShort", 7, "day"); <add>} <add> <add>export function listWeekdaysMin (format, index) { <add> return list(format, index, "weekdaysMin", 7, "day"); <add>} <ide><path>lib/locale/locale.js <add>// Side effect imports <add>import "./prototype"; <add> <add>import { <add> getSetGlobalLocale, <add> defineLocale, <add> getLocale <add>} from "./locales"; <add> <add>import { <add> listMonths, <add> listMonthsShort, <add> listWeekdays, <add> listWeekdaysShort, <add> listWeekdaysMin <add>} from "./lists"; <add> <add>export { <add> getSetGlobalLocale, <add> defineLocale, <add> getLocale, <add> listMonths, <add> listMonthsShort, <add> listWeekdays, <add> listWeekdaysShort, <add> listWeekdaysMin <add>}; <add> <add>import { deprecate } from "../utils/deprecate"; <add>import { hooks } from "../utils/hooks"; <add> <add>hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale); <add>hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale); <add> <add>import "./en"; <ide><path>lib/locale/locales.js <add>import isArray from "../utils/is-array"; <add>import compareArrays from "../utils/compare-arrays"; <add>import { Locale } from "./constructor"; <add> <add>// internal storage for locale config files <add>var locales = {}; <add>var globalLocale; <add> <add>function normalizeLocale(key) { <add> return key ? key.toLowerCase().replace('_', '-') : key; <add>} <add> <add>// pick the locale from the array <add>// try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each <add>// substring from most specific to least, but move to the next array item if it's a more specific variant than the current root <add>function chooseLocale(names) { <add> var i = 0, j, next, locale, split; <add> <add> while (i < names.length) { <add> split = normalizeLocale(names[i]).split('-'); <add> j = split.length; <add> next = normalizeLocale(names[i + 1]); <add> next = next ? next.split('-') : null; <add> while (j > 0) { <add> locale = loadLocale(split.slice(0, j).join('-')); <add> if (locale) { <add> return locale; <add> } <add> if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { <add> //the next array item is better than a shallower substring of this one <add> break; <add> } <add> j--; <add> } <add> i++; <add> } <add> return null; <add>} <add> <add>function loadLocale(name) { <add> // var oldLocale = null; <add> // TODO: Find a better way to register and load all the locales in Node <add> // if (!locales[name] && hasModule) { <add> // try { <add> // oldLocale = moment.locale(); <add> // require('./locale/' + name); <add> // // because defineLocale currently also sets the global locale, we want to undo that for lazy loaded locales <add> // moment.locale(oldLocale); <add> // } catch (e) { } <add> // } <add> return locales[name]; <add>} <add> <add>// This function will load locale and then set the global locale. If <add>// no arguments are passed in, it will simply return the current global <add>// locale key. <add>export function getSetGlobalLocale (key, values) { <add> var data; <add> if (key) { <add> if (typeof values === 'undefined') { <add> data = getLocale(key); <add> } <add> else { <add> data = defineLocale(key, values); <add> } <add> <add> if (data) { <add> // moment.duration._locale = moment._locale = data; <add> globalLocale = data; <add> } <add> } <add> <add> return globalLocale._abbr; <add>} <add> <add>export function defineLocale (name, values) { <add> if (values !== null) { <add> values.abbr = name; <add> if (!locales[name]) { <add> locales[name] = new Locale(); <add> } <add> locales[name].set(values); <add> <add> // backwards compat for now: also set the locale <add> getSetGlobalLocale(name); <add> <add> return locales[name]; <add> } else { <add> // useful for testing <add> delete locales[name]; <add> return null; <add> } <add>} <add> <add>// returns locale data <add>export function getLocale (key) { <add> var locale; <add> <add> if (key && key._locale && key._locale._abbr) { <add> key = key._locale._abbr; <add> } <add> <add> if (!key) { <add> return globalLocale; <add> } <add> <add> if (!isArray(key)) { <add> //short-circuit everything else <add> locale = loadLocale(key); <add> if (locale) { <add> return locale; <add> } <add> key = [key]; <add> } <add> <add> return chooseLocale(key); <add>} <ide><path>lib/locale/ordinal.js <add>export var defaultOrdinal = '%d'; <add>export var defaultOrdinalParse = /\d{1,2}/; <add> <add>export function ordinal (number) { <add> return this._ordinal.replace('%d', number); <add>} <add> <ide><path>lib/locale/pre-post-format.js <add>export function preParsePostFormat (string) { <add> return string; <add>} <ide><path>lib/locale/prototype.js <add>import { Locale } from "./constructor"; <add> <add>var proto = Locale.prototype; <add> <add>import { defaultCalendar, calendar } from "./calendar"; <add>import { defaultLongDateFormat, longDateFormat } from "./formats"; <add>import { defaultInvalidDate, invalidDate } from "./invalid"; <add>import { defaultOrdinal, ordinal, defaultOrdinalParse } from "./ordinal"; <add>import { preParsePostFormat } from "./pre-post-format"; <add>import { defaultRelativeTime, relativeTime, pastFuture } from "./relative"; <add>import { set } from "./set"; <add> <add>proto._calendar = defaultCalendar; <add>proto.calendar = calendar; <add>proto._longDateFormat = defaultLongDateFormat; <add>proto.longDateFormat = longDateFormat; <add>proto._invalidDate = defaultInvalidDate; <add>proto.invalidDate = invalidDate; <add>proto._ordinal = defaultOrdinal; <add>proto.ordinal = ordinal; <add>proto._ordinalParse = defaultOrdinalParse; <add>proto.preparse = preParsePostFormat; <add>proto.postformat = preParsePostFormat; <add>proto._relativeTime = defaultRelativeTime; <add>proto.relativeTime = relativeTime; <add>proto.pastFuture = pastFuture; <add>proto.set = set; <add> <add>// Month <add>import { <add> localeMonthsParse, <add> defaultLocaleMonths, localeMonths, <add> defaultLocaleMonthsShort, localeMonthsShort <add>} from "../units/month"; <add> <add>proto.months = localeMonths; <add>proto._months = defaultLocaleMonths; <add>proto.monthsShort = localeMonthsShort; <add>proto._monthsShort = defaultLocaleMonthsShort; <add>proto.monthsParse = localeMonthsParse; <add> <add>// Week <add>import { localeWeek, defaultLocaleWeek, localeFirstDayOfYear, localeFirstDayOfWeek } from "../units/week"; <add>proto.week = localeWeek; <add>proto._week = defaultLocaleWeek; <add>proto.firstDayOfYear = localeFirstDayOfYear; <add>proto.firstDayOfWeek = localeFirstDayOfWeek; <add> <add>// Day of Week <add>import { <add> localeWeekdaysParse, <add> defaultLocaleWeekdays, localeWeekdays, <add> defaultLocaleWeekdaysMin, localeWeekdaysMin, <add> defaultLocaleWeekdaysShort, localeWeekdaysShort <add>} from "../units/day-of-week"; <add> <add>proto.weekdays = localeWeekdays; <add>proto._weekdays = defaultLocaleWeekdays; <add>proto.weekdaysMin = localeWeekdaysMin; <add>proto._weekdaysMin = defaultLocaleWeekdaysMin; <add>proto.weekdaysShort = localeWeekdaysShort; <add>proto._weekdaysShort = defaultLocaleWeekdaysShort; <add>proto.weekdaysParse = localeWeekdaysParse; <add> <add>// Hours <add>import { localeIsPM, defaultLocaleMeridiemParse, localeMeridiem } from "../units/hour"; <add> <add>proto.isPM = localeIsPM; <add>proto._meridiemParse = defaultLocaleMeridiemParse; <add>proto.meridiem = localeMeridiem; <ide><path>lib/locale/relative.js <add>export var defaultRelativeTime = { <add> future : 'in %s', <add> past : '%s ago', <add> s : 'a few seconds', <add> m : 'a minute', <add> mm : '%d minutes', <add> h : 'an hour', <add> hh : '%d hours', <add> d : 'a day', <add> dd : '%d days', <add> M : 'a month', <add> MM : '%d months', <add> y : 'a year', <add> yy : '%d years' <add>}; <add> <add>export function relativeTime (number, withoutSuffix, string, isFuture) { <add> var output = this._relativeTime[string]; <add> return (typeof output === 'function') ? <add> output(number, withoutSuffix, string, isFuture) : <add> output.replace(/%d/i, number); <add>} <add> <add>export function pastFuture (diff, output) { <add> var format = this._relativeTime[diff > 0 ? 'future' : 'past']; <add> return typeof format === 'function' ? format(output) : format.replace(/%s/i, output); <add>} <ide><path>lib/locale/set.js <add>export function set (config) { <add> var prop, i; <add> for (i in config) { <add> prop = config[i]; <add> if (typeof prop === 'function') { <add> this[i] = prop; <add> } else { <add> this['_' + i] = prop; <add> } <add> } <add> // Lenient ordinal parsing accepts just a number in addition to <add> // number + (possibly) stuff coming from _ordinalParseLenient. <add> this._ordinalParseLenient = new RegExp(this._ordinalParse.source + '|' + /\d{1,2}/.source); <add>} <ide><path>lib/moment.js <add>//! moment.js <add>//! version : 2.8.3 <add>//! authors : Tim Wood, Iskren Chernev, Moment.js contributors <add>//! license : MIT <add>//! momentjs.com <add> <add>import { hooks as moment, setHookCallback } from "./utils/hooks"; <add> <add>moment.version = '2.8.3'; <add> <add>import { <add> min, <add> max, <add> isMoment, <add> momentPrototype as fn, <add> createUTC as utc, <add> createUnix as unix, <add> createLocal as local, <add> createInvalid as invalid, <add> createInZone as parseZone <add>} from "./moment/moment"; <add> <add>import { <add> defineLocale, <add> getSetGlobalLocale as locale, <add> getLocale as localeData, <add> listMonths as months, <add> listMonthsShort as monthsShort, <add> listWeekdays as weekdays, <add> listWeekdaysMin as weekdaysMin, <add> listWeekdaysShort as weekdaysShort <add>} from "./locale/locale"; <add> <add>import { <add> isDuration, <add> createDuration as duration, <add> getSetRelativeTimeThreshold as relativeTimeThreshold <add>} from "./duration/duration"; <add> <add>import { normalizeUnits } from "./units/units"; <add> <add>import isDate from "./utils/is-date"; <add> <add>setHookCallback(local); <add> <add>moment.fn = fn; <add>moment.min = min; <add>moment.max = max; <add>moment.utc = utc; <add>moment.unix = unix; <add>moment.months = months; <add>moment.isDate = isDate; <add>moment.locale = locale; <add>moment.invalid = invalid; <add>moment.duration = duration; <add>moment.isMoment = isMoment; <add>moment.weekdays = weekdays; <add>moment.parseZone = parseZone; <add>moment.localeData = localeData; <add>moment.isDuration = isDuration; <add>moment.monthsShort = monthsShort; <add>moment.weekdaysMin = weekdaysMin; <add>moment.defineLocale = defineLocale; <add>moment.weekdaysShort = weekdaysShort; <add>moment.normalizeUnits = normalizeUnits; <add>moment.relativeTimeThreshold = relativeTimeThreshold; <add> <add>export default moment; <ide><path>lib/moment/add-subtract.js <add>import { get, set } from "./get-set"; <add>import { setMonth } from "../units/month"; <add>import { createDuration } from "../duration/create"; <add>import { deprecateSimple } from "../utils/deprecate"; <add>import { hooks } from "../utils/hooks"; <add> <add>// TODO: remove 'name' arg after deprecation is removed <add>function createAdder(direction, name) { <add> return function (val, period) { <add> var dur, tmp; <add> //invert the arguments, but complain about it <add> if (period !== null && !isNaN(+period)) { <add> deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period).'); <add> tmp = val; val = period; period = tmp; <add> } <add> <add> val = typeof val === 'string' ? +val : val; <add> dur = createDuration(val, period); <add> addSubtract(this, dur, direction); <add> return this; <add> }; <add>} <add> <add>export function addSubtract (mom, duration, isAdding, updateOffset) { <add> var milliseconds = duration._milliseconds, <add> days = duration._days, <add> months = duration._months; <add> updateOffset = updateOffset == null ? true : updateOffset; <add> <add> if (milliseconds) { <add> mom._d.setTime(+mom._d + milliseconds * isAdding); <add> } <add> if (days) { <add> set(mom, 'Date', get(mom, 'Date') + days * isAdding); <add> } <add> if (months) { <add> setMonth(mom, get(mom, 'Month') + months * isAdding); <add> } <add> if (updateOffset) { <add> hooks.updateOffset(mom, days || months); <add> } <add>} <add> <add>export var add = createAdder( 1, 'add'); <add>export var subtract = createAdder(-1, 'subtract'); <add> <ide><path>lib/moment/calendar.js <add>import { createLocal } from "../create/local"; <add>import { cloneWithOffset } from "../units/offset"; <add> <add>export function calendar (time) { <add> // We want to compare the start of today, vs this. <add> // Getting start-of-today depends on whether we're local/utc/offset or not. <add> var now = time || createLocal(), <add> sod = cloneWithOffset(now, this).startOf('day'), <add> diff = this.diff(sod, 'days', true), <add> format = diff < -6 ? 'sameElse' : <add> diff < -1 ? 'lastWeek' : <add> diff < 0 ? 'lastDay' : <add> diff < 1 ? 'sameDay' : <add> diff < 2 ? 'nextDay' : <add> diff < 7 ? 'nextWeek' : 'sameElse'; <add> return this.format(this.localeData().calendar(format, this, createLocal(now))); <add>} <ide><path>lib/moment/clone.js <add>import { Moment } from "./constructor"; <add> <add>export function clone () { <add> return new Moment(this); <add>} <ide><path>lib/moment/compare.js <add>import { isMoment } from "./constructor"; <add>import { normalizeUnits } from "../units/aliases"; <add>import { createLocal } from "../create/local"; <add> <add>export function isAfter (input, units) { <add> var inputMs; <add> units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond'); <add> if (units === 'millisecond') { <add> input = isMoment(input) ? input : createLocal(input); <add> return +this > +input; <add> } else { <add> inputMs = isMoment(input) ? +input : +createLocal(input); <add> return inputMs < +this.clone().startOf(units); <add> } <add>} <add> <add>export function isBefore (input, units) { <add> var inputMs; <add> units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond'); <add> if (units === 'millisecond') { <add> input = isMoment(input) ? input : createLocal(input); <add> return +this < +input; <add> } else { <add> inputMs = isMoment(input) ? +input : +createLocal(input); <add> return +this.clone().endOf(units) < inputMs; <add> } <add>} <add> <add>export function isBetween (from, to, units) { <add> return this.isAfter(from, units) && this.isBefore(to, units); <add>} <add> <add>export function isSame (input, units) { <add> var inputMs; <add> units = normalizeUnits(units || 'millisecond'); <add> if (units === 'millisecond') { <add> input = isMoment(input) ? input : createLocal(input); <add> return +this === +input; <add> } else { <add> inputMs = +createLocal(input); <add> return +(this.clone().startOf(units)) <= inputMs && inputMs <= +(this.clone().endOf(units)); <add> } <add>} <ide><path>lib/moment/constructor.js <add>import { hooks } from "../utils/hooks"; <add>import hasOwnProp from "../utils/has-own-prop"; <add> <add>// Plugins that add properties should also add the key here (null value), <add>// so we can properly clone ourselves. <add>var momentProperties = hooks.momentProperties = []; <add> <add>export function copyConfig(to, from) { <add> var i, prop, val; <add> <add> if (typeof from._isAMomentObject !== 'undefined') { <add> to._isAMomentObject = from._isAMomentObject; <add> } <add> if (typeof from._i !== 'undefined') { <add> to._i = from._i; <add> } <add> if (typeof from._f !== 'undefined') { <add> to._f = from._f; <add> } <add> if (typeof from._l !== 'undefined') { <add> to._l = from._l; <add> } <add> if (typeof from._strict !== 'undefined') { <add> to._strict = from._strict; <add> } <add> if (typeof from._tzm !== 'undefined') { <add> to._tzm = from._tzm; <add> } <add> if (typeof from._isUTC !== 'undefined') { <add> to._isUTC = from._isUTC; <add> } <add> if (typeof from._offset !== 'undefined') { <add> to._offset = from._offset; <add> } <add> if (typeof from._pf !== 'undefined') { <add> to._pf = from._pf; <add> } <add> if (typeof from._locale !== 'undefined') { <add> to._locale = from._locale; <add> } <add> <add> if (momentProperties.length > 0) { <add> for (i in momentProperties) { <add> prop = momentProperties[i]; <add> val = from[prop]; <add> if (typeof val !== 'undefined') { <add> to[prop] = val; <add> } <add> } <add> } <add> <add> return to; <add>} <add> <add>var updateInProgress = false; <add> <add>// Moment prototype object <add>export function Moment(config) { <add> copyConfig(this, config); <add> this._d = new Date(+config._d); <add> // Prevent infinite loop in case updateOffset creates new moment <add> // objects. <add> if (updateInProgress === false) { <add> updateInProgress = true; <add> hooks.updateOffset(this); <add> updateInProgress = false; <add> } <add>} <add> <add>export function isMoment (obj) { <add> return obj instanceof Moment || (obj != null && hasOwnProp(obj, '_isAMomentObject')); <add>} <ide><path>lib/moment/diff.js <add>import absFloor from "../utils/abs-floor"; <add>import { cloneWithOffset } from "../units/offset"; <add>import { normalizeUnits } from "../units/aliases"; <add> <add>export function diff (input, units, asFloat) { <add> var that = cloneWithOffset(input, this), <add> zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4, <add> delta, output; <add> <add> units = normalizeUnits(units); <add> <add> if (units === 'year' || units === 'month' || units === 'quarter') { <add> output = monthDiff(this, that); <add> if (units === 'quarter') { <add> output = output / 3; <add> } else if (units === 'year') { <add> output = output / 12; <add> } <add> } else { <add> delta = this - that; <add> output = units === 'second' ? delta / 1e3 : // 1000 <add> units === 'minute' ? delta / 6e4 : // 1000 * 60 <add> units === 'hour' ? delta / 36e5 : // 1000 * 60 * 60 <add> units === 'day' ? (delta - zoneDelta) / 864e5 : // 1000 * 60 * 60 * 24, negate dst <add> units === 'week' ? (delta - zoneDelta) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst <add> delta; <add> } <add> return asFloat ? output : absFloor(output); <add>} <add> <add>function monthDiff (a, b) { <add> // difference in months <add> var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()), <add> // b is in (anchor - 1 month, anchor + 1 month) <add> anchor = a.clone().add(wholeMonthDiff, 'months'), <add> anchor2, adjust; <add> <add> if (b - anchor < 0) { <add> anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); <add> // linear across the month <add> adjust = (b - anchor) / (anchor - anchor2); <add> } else { <add> anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); <add> // linear across the month <add> adjust = (b - anchor) / (anchor2 - anchor); <add> } <add> <add> return -(wholeMonthDiff + adjust); <add>} <ide><path>lib/moment/format.js <add>import { formatMoment } from "../format/format"; <add>import { hooks } from "../utils/hooks"; <add> <add>hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ'; <add> <add>export function toString () { <add> return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); <add>} <add> <add>export function toISOString () { <add> var m = this.clone().utc(); <add> if (0 < m.year() && m.year() <= 9999) { <add> if ('function' === typeof Date.prototype.toISOString) { <add> // native implementation is ~50x faster, use it when we can <add> return this.toDate().toISOString(); <add> } else { <add> return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); <add> } <add> } else { <add> return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); <add> } <add>} <add> <add>export function format (inputString) { <add> var output = formatMoment(this, inputString || hooks.defaultFormat); <add> return this.localeData().postformat(output); <add>} <ide><path>lib/moment/from.js <add>import { createDuration } from "../duration/create"; <add>import { createLocal } from "../create/local"; <add> <add>export function from (time, withoutSuffix) { <add> return createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix); <add>} <add> <add>export function fromNow (withoutSuffix) { <add> return this.from(createLocal(), withoutSuffix); <add>} <ide><path>lib/moment/get-set.js <add>import { normalizeUnits } from "../units/aliases"; <add>import { hooks } from "../utils/hooks"; <add> <add>export function makeGetSet (unit, keepTime) { <add> return function (value) { <add> if (value != null) { <add> set(this, unit, value); <add> hooks.updateOffset(this, keepTime); <add> return this; <add> } else { <add> return get(this, unit); <add> } <add> }; <add>} <add> <add>export function get (mom, unit) { <add> return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit](); <add>} <add> <add>export function set (mom, unit, value) { <add> return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); <add>} <add> <add>// MOMENTS <add> <add>export function getSet (units, value) { <add> var unit; <add> if (typeof units === 'object') { <add> for (unit in units) { <add> this.set(unit, units[unit]); <add> } <add> } else { <add> units = normalizeUnits(units); <add> if (typeof this[units] === 'function') { <add> return this[units](value); <add> } <add> } <add> return this; <add>} <ide><path>lib/moment/locale.js <add>import { getLocale } from "../locale/locales"; <add>import { deprecate } from "../utils/deprecate"; <add> <add>// If passed a locale key, it will set the locale for this <add>// instance. Otherwise, it will return the locale configuration <add>// variables for this instance. <add>export function locale (key) { <add> var newLocaleData; <add> <add> if (key === undefined) { <add> return this._locale._abbr; <add> } else { <add> newLocaleData = getLocale(key); <add> if (newLocaleData != null) { <add> this._locale = newLocaleData; <add> } <add> return this; <add> } <add>} <add> <add>export var lang = deprecate( <add> 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', <add> function (key) { <add> if (key === undefined) { <add> return this.localeData(); <add> } else { <add> return this.locale(key); <add> } <add> } <add>); <add> <add>export function localeData () { <add> return this._locale; <add>} <ide><path>lib/moment/min-max.js <add>import { deprecate } from "../utils/deprecate"; <add>import isArray from "../utils/is-array"; <add>import { createLocal } from "../create/local"; <add> <add>export var prototypeMin = deprecate( <add> 'moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548', <add> function () { <add> var other = createLocal.apply(null, arguments); <add> return other < this ? this : other; <add> } <add> ); <add> <add>export var prototypeMax = deprecate( <add> 'moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548', <add> function () { <add> var other = createLocal.apply(null, arguments); <add> return other > this ? this : other; <add> } <add>); <add> <add>// Pick a moment m from moments so that m[fn](other) is true for all <add>// other. This relies on the function fn to be transitive. <add>// <add>// moments should either be an array of moment objects or an array, whose <add>// first element is an array of moment objects. <add>function pickBy(fn, moments) { <add> var res, i; <add> if (moments.length === 1 && isArray(moments[0])) { <add> moments = moments[0]; <add> } <add> if (!moments.length) { <add> return createLocal(); <add> } <add> res = moments[0]; <add> for (i = 1; i < moments.length; ++i) { <add> if (moments[i][fn](res)) { <add> res = moments[i]; <add> } <add> } <add> return res; <add>} <add> <add>// TODO: Use [].sort instead? <add>export function min () { <add> var args = [].slice.call(arguments, 0); <add> <add> return pickBy('isBefore', args); <add>} <add> <add>export function max () { <add> var args = [].slice.call(arguments, 0); <add> <add> return pickBy('isAfter', args); <add>} <ide><path>lib/moment/moment.js <add>import { createLocal } from "../create/local"; <add>import { createUTC } from "../create/utc"; <add>import { createInvalid } from "../create/valid"; <add>import { isMoment } from "./constructor"; <add>import { min, max } from "./min-max"; <add>import momentPrototype from "./prototype"; <add> <add>function createUnix (input) { <add> return createLocal(input * 1000); <add>} <add> <add>function createInZone () { <add> return createLocal.apply(null, arguments).parseZone(); <add>} <add> <add>export { <add> min, <add> max, <add> isMoment, <add> createUTC, <add> createUnix, <add> createLocal, <add> createInZone, <add> createInvalid, <add> momentPrototype <add>}; <ide><path>lib/moment/prototype.js <add>import { Moment } from "./constructor"; <add> <add>var proto = Moment.prototype; <add> <add>import { add, subtract } from "./add-subtract"; <add>import { calendar } from "./calendar"; <add>import { clone } from "./clone"; <add>import { isBefore, isBetween, isSame, isAfter } from "./compare"; <add>import { diff } from "./diff"; <add>import { format, toString, toISOString } from "./format"; <add>import { from, fromNow } from "./from"; <add>import { getSet } from "./get-set"; <add>import { locale, localeData, lang } from "./locale"; <add>import { prototypeMin, prototypeMax } from "./min-max"; <add>import { startOf, endOf } from "./start-end-of"; <add>import { valueOf, toDate, toArray, unix } from "./to-type"; <add>import { isValid, parsingFlags, invalidAt } from "./valid"; <add> <add>proto.add = add; <add>proto.calendar = calendar; <add>proto.clone = clone; <add>proto.diff = diff; <add>proto.endOf = endOf; <add>proto.format = format; <add>proto.from = from; <add>proto.fromNow = fromNow; <add>proto.get = getSet; <add>proto.invalidAt = invalidAt; <add>proto.isAfter = isAfter; <add>proto.isBefore = isBefore; <add>proto.isBetween = isBetween; <add>proto.isSame = isSame; <add>proto.isValid = isValid; <add>proto.lang = lang; <add>proto.locale = locale; <add>proto.localeData = localeData; <add>proto.max = prototypeMax; <add>proto.min = prototypeMin; <add>proto.parsingFlags = parsingFlags; <add>proto.set = getSet; <add>proto.startOf = startOf; <add>proto.subtract = subtract; <add>proto.toArray = toArray; <add>proto.toDate = toDate; <add>proto.toISOString = toISOString; <add>proto.toJSON = toISOString; <add>proto.toString = toString; <add>proto.unix = unix; <add>proto.valueOf = valueOf; <add> <add>// Year <add>import { getSetYear, getIsLeapYear } from "../units/year"; <add>proto.year = getSetYear; <add>proto.isLeapYear = getIsLeapYear; <add> <add>// Week Year <add>import { getSetWeekYear, getSetISOWeekYear, getWeeksInYear, getISOWeeksInYear } from "../units/week-year"; <add>proto.weekYear = getSetWeekYear; <add>proto.isoWeekYear = getSetISOWeekYear; <add> <add>// Quarter <add>import { getSetQuarter } from "../units/quarter"; <add>proto.quarter = proto.quarters = getSetQuarter; <add> <add>// Month <add>import { getSetMonth, getDaysInMonth } from "../units/month"; <add>proto.month = getSetMonth; <add>proto.daysInMonth = getDaysInMonth; <add> <add>// Week <add>import { getSetWeek, getSetISOWeek } from "../units/week"; <add>proto.week = proto.weeks = getSetWeek; <add>proto.isoWeek = proto.isoWeeks = getSetISOWeek; <add>proto.weeksInYear = getWeeksInYear; <add>proto.isoWeeksInYear = getISOWeeksInYear; <add> <add>// Day <add>import { getSetDayOfMonth } from "../units/day-of-month"; <add>import { getSetDayOfWeek, getSetISODayOfWeek, getSetLocaleDayOfWeek } from "../units/day-of-week"; <add>import { getSetDayOfYear } from "../units/day-of-year"; <add>proto.date = getSetDayOfMonth; <add>proto.day = proto.days = getSetDayOfWeek; <add>proto.weekday = getSetLocaleDayOfWeek; <add>proto.isoWeekday = getSetISODayOfWeek; <add>proto.dayOfYear = getSetDayOfYear; <add> <add>// Hour <add>import { getSetHour } from "../units/hour"; <add>proto.hour = proto.hours = getSetHour; <add> <add>// Minute <add>import { getSetMinute } from "../units/minute"; <add>proto.minute = proto.minutes = getSetMinute; <add> <add>// Second <add>import { getSetSecond } from "../units/second"; <add>proto.second = proto.seconds = getSetSecond; <add> <add>// Millisecond <add>import { getSetMillisecond } from "../units/millisecond"; <add>proto.millisecond = proto.milliseconds = getSetMillisecond; <add> <add>// Offset <add>import { <add> getSetOffset, <add> setOffsetToUTC, <add> setOffsetToLocal, <add> setOffsetToParsedOffset, <add> hasAlignedHourOffset, <add> isDaylightSavingTime, <add> isDaylightSavingTimeShifted, <add> getSetZone, <add> isLocal, <add> isUtcOffset, <add> isUtc <add>} from "../units/offset"; <add>proto.utcOffset = getSetOffset; <add>proto.utc = setOffsetToUTC; <add>proto.local = setOffsetToLocal; <add>proto.parseZone = setOffsetToParsedOffset; <add>proto.hasAlignedHourOffset = hasAlignedHourOffset; <add>proto.isDST = isDaylightSavingTime; <add>proto.isDSTShifted = isDaylightSavingTimeShifted; <add>proto.isLocal = isLocal; <add>proto.isUtcOffset = isUtcOffset; <add>proto.isUtc = isUtc; <add>proto.isUTC = isUtc; <add> <add>// Timezone <add>import { getZoneAbbr, getZoneName } from "../units/timezone"; <add>proto.zoneAbbr = getZoneAbbr; <add>proto.zoneName = getZoneName; <add> <add>// Deprecations <add>import { deprecate } from "../utils/deprecate"; <add>proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth); <add>proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth); <add>proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear); <add>proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. https://github.com/moment/moment/issues/1779', getSetZone); <add> <add>export default proto; <ide><path>lib/moment/start-end-of.js <add>import { normalizeUnits } from "../units/aliases"; <add> <add>export function startOf (units) { <add> units = normalizeUnits(units); <add> // the following switch intentionally omits break keywords <add> // to utilize falling through the cases. <add> switch (units) { <add> case 'year': <add> this.month(0); <add> /* falls through */ <add> case 'quarter': <add> case 'month': <add> this.date(1); <add> /* falls through */ <add> case 'week': <add> case 'isoWeek': <add> case 'day': <add> this.hours(0); <add> /* falls through */ <add> case 'hour': <add> this.minutes(0); <add> /* falls through */ <add> case 'minute': <add> this.seconds(0); <add> /* falls through */ <add> case 'second': <add> this.milliseconds(0); <add> /* falls through */ <add> } <add> <add> // weeks are a special case <add> if (units === 'week') { <add> this.weekday(0); <add> } <add> if (units === 'isoWeek') { <add> this.isoWeekday(1); <add> } <add> <add> // quarters are also special <add> if (units === 'quarter') { <add> this.month(Math.floor(this.month() / 3) * 3); <add> } <add> <add> return this; <add>} <add> <add>export function endOf (units) { <add> units = normalizeUnits(units); <add> if (units === undefined || units === 'millisecond') { <add> return this; <add> } <add> return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms'); <add>} <ide><path>lib/moment/to-type.js <add>export function valueOf () { <add> return +this._d - ((this._offset || 0) * 60000); <add>} <add> <add>export function unix () { <add> return Math.floor(+this / 1000); <add>} <add> <add>export function toDate () { <add> return this._offset ? new Date(+this) : this._d; <add>} <add> <add>export function toArray () { <add> var m = this; <add> return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()]; <add>} <ide><path>lib/moment/valid.js <add>import { isValid as _isValid } from "../create/valid"; <add>import extend from "../utils/extend"; <add> <add>export function isValid () { <add> return _isValid(this); <add>} <add> <add>export function parsingFlags () { <add> return extend({}, this._pf); <add>} <add> <add>export function invalidAt () { <add> return this._pf.overflow; <add>} <ide><path>lib/parse/regex.js <add>export var match1 = /\d/; // 0 - 9 <add>export var match2 = /\d\d/; // 00 - 99 <add>export var match3 = /\d{3}/; // 000 - 999 <add>export var match4 = /\d{4}/; // 0000 - 9999 <add>export var match6 = /[+-]?\d{6}/; // -999999 - 999999 <add>export var match1to2 = /\d\d?/; // 0 - 99 <add>export var match1to3 = /\d{1,3}/; // 0 - 999 <add>export var match1to4 = /\d{1,4}/; // 0 - 9999 <add>export var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999 <add> <add>export var matchUnsigned = /\d+/; // 0 - inf <add>export var matchSigned = /[+-]?\d+/; // -inf - inf <add> <add>export var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z <add> <add>export var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123 <add> <add>// any word (or two) characters or numbers including two/three word month in arabic. <add>export var matchWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i; <add> <add>import hasOwnProp from "../utils/has-own-prop"; <add> <add>var regexes = {}; <add> <add>export function addRegexToken (token, regex, strictRegex) { <add> regexes[token] = typeof regex === "function" ? regex : function (isStrict) { <add> return (isStrict && strictRegex) ? strictRegex : regex; <add> }; <add>} <add> <add>export function getParseRegexForToken (token, config) { <add> if (!hasOwnProp(regexes, token)) { <add> return new RegExp(unescapeFormat(token)); <add> } <add> <add> return regexes[token](config._strict, config._locale); <add>} <add> <add>// Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript <add>function unescapeFormat(s) { <add> return s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { <add> return p1 || p2 || p3 || p4; <add> }).replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); <add>} <add> <add>addRegexToken("T", /T/i); // TODO: Remove this? <ide><path>lib/parse/token.js <add>import hasOwnProp from "../utils/has-own-prop"; <add>import toInt from "../utils/to-int"; <add> <add>var tokens = {}; <add> <add>export function addParseToken (token, callback) { <add> var i, func = callback; <add> if (typeof token === "string") { <add> token = [token]; <add> } <add> if (typeof callback === "number") { <add> func = function (input, array) { <add> array[callback] = toInt(input); <add> }; <add> } <add> for (i = 0; i < token.length; i++) { <add> tokens[token[i]] = func; <add> } <add>} <add> <add>export function addWeekParseToken (token, callback) { <add> addParseToken(token, function (input, array, config, token) { <add> config._w = config._w || {}; <add> callback(input, config._w, config, token); <add> }); <add>} <add> <add>export function addTimeToArrayFromToken(token, input, config) { <add> if (input != null && hasOwnProp(tokens, token)) { <add> tokens[token](input, config._a, config, token); <add> } <add>} <ide><path>lib/units/aliases.js <add>import hasOwnProp from "../utils/has-own-prop"; <add> <add>var aliases = {}; <add> <add>export function addUnitAlias (unit, shorthand) { <add> var lowerCase = unit.toLowerCase(); <add> aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit; <add>} <add> <add>export function normalizeUnits(units) { <add> return typeof units === "string" ? aliases[units] || aliases[units.toLowerCase()] : undefined; <add>} <add> <add>export function normalizeObjectUnits(inputObject) { <add> var normalizedInput = {}, <add> normalizedProp, <add> prop; <add> <add> for (prop in inputObject) { <add> if (hasOwnProp(inputObject, prop)) { <add> normalizedProp = normalizeUnits(prop); <add> if (normalizedProp) { <add> normalizedInput[normalizedProp] = inputObject[prop]; <add> } <add> } <add> } <add> <add> return normalizedInput; <add>} <ide><path>lib/units/constants.js <add>export var YEAR = 0; <add>export var MONTH = 1; <add>export var DATE = 2; <add>export var HOUR = 3; <add>export var MINUTE = 4; <add>export var SECOND = 5; <add>export var MILLISECOND = 6; <ide><path>lib/units/day-of-month.js <add>import { makeGetSet } from "../moment/get-set"; <add>import { addFormatToken } from "../format/format"; <add>import { addUnitAlias } from "./aliases"; <add>import { addRegexToken, match1to2, match2 } from "../parse/regex"; <add>import { addParseToken } from "../parse/token"; <add>import toInt from "../utils/to-int"; <add> <add>// FORMATTING <add> <add>addFormatToken("D", ["DD", 2], "Do", "date"); <add> <add>// ALIASES <add> <add>addUnitAlias("date", "D"); <add> <add>// PARSING <add> <add>addRegexToken("D", match1to2); <add>addRegexToken("DD", match1to2, match2); <add>addRegexToken("Do", function (isStrict, locale) { <add> return isStrict ? locale._ordinalParse : locale._ordinalParseLenient; <add>}); <add> <add>addParseToken(["D", "DD"], 2); // TODO: use a constant for DATE <add>addParseToken("Do", function (input, array) { <add> array[2] = toInt(input.match(match1to2)[0], 10); // TODO: use a constant for DATE <add>}); <add> <add>// MOMENTS <add> <add>export var getSetDayOfMonth = makeGetSet('Date', true); <ide><path>lib/units/day-of-week.js <add>import { addFormatToken } from "../format/format"; <add>import { addUnitAlias } from "./aliases"; <add>import { addRegexToken, match1to2, matchWord } from "../parse/regex"; <add>import { addWeekParseToken } from "../parse/token"; <add>import toInt from "../utils/to-int"; <add>import { createLocal } from "../create/local"; <add> <add>// FORMATTING <add> <add>addFormatToken("d", 0, "do", "day"); <add> <add>addFormatToken("dd", 0, 0, function (format) { <add> return this.localeData().weekdaysMin(this, format); <add>}); <add> <add>addFormatToken("ddd", 0, 0, function (format) { <add> return this.localeData().weekdaysShort(this, format); <add>}); <add> <add>addFormatToken("dddd", 0, 0, function (format) { <add> return this.localeData().weekdays(this, format); <add>}); <add> <add>addFormatToken("e", 0, 0, "weekday"); <add>addFormatToken("E", 0, 0, "isoWeekday"); <add> <add>// ALIASES <add> <add>addUnitAlias("day", "d"); <add>addUnitAlias("weekday", "e"); <add>addUnitAlias("isoWeekday", "E"); <add> <add>// PARSING <add> <add>addRegexToken("d", match1to2); <add>addRegexToken("e", match1to2); <add>addRegexToken("E", match1to2); <add>addRegexToken("dd", matchWord); <add>addRegexToken("ddd", matchWord); <add>addRegexToken("dddd", matchWord); <add> <add>addWeekParseToken(["dd", "ddd", "dddd"], function (input, week, config) { <add> var weekday = config._locale.weekdaysParse(input); <add> // if we didn't get a weekday name, mark the date as invalid <add> if (weekday != null) { <add> week.d = weekday; <add> } else { <add> config._pf.invalidWeekday = input; <add> } <add>}); <add> <add>addWeekParseToken(["d", "e", "E"], function (input, week, config, token) { <add> week[token] = toInt(input); <add>}); <add> <add>// HELPERS <add> <add>function parseWeekday(input, locale) { <add> if (typeof input === 'string') { <add> if (!isNaN(input)) { <add> input = parseInt(input, 10); <add> } <add> else { <add> input = locale.weekdaysParse(input); <add> if (typeof input !== 'number') { <add> return null; <add> } <add> } <add> } <add> return input; <add>} <add> <add>// LOCALES <add> <add>export var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'); <add>export function localeWeekdays (m) { <add> return this._weekdays[m.day()]; <add>} <add> <add>export var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'); <add>export function localeWeekdaysShort (m) { <add> return this._weekdaysShort[m.day()]; <add>} <add> <add>export var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'); <add>export function localeWeekdaysMin (m) { <add> return this._weekdaysMin[m.day()]; <add>} <add> <add>export function localeWeekdaysParse (weekdayName) { <add> var i, mom, regex; <add> <add> if (!this._weekdaysParse) { <add> this._weekdaysParse = []; <add> } <add> <add> for (i = 0; i < 7; i++) { <add> // make the regex if we don't have it already <add> if (!this._weekdaysParse[i]) { <add> mom = createLocal([2000, 1]).day(i); <add> regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); <add> this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); <add> } <add> // test the regex <add> if (this._weekdaysParse[i].test(weekdayName)) { <add> return i; <add> } <add> } <add>} <add> <add>// MOMENTS <add> <add>export function getSetDayOfWeek (input) { <add> var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); <add> if (input != null) { <add> input = parseWeekday(input, this.localeData()); <add> return this.add(input - day, 'd'); <add> } else { <add> return day; <add> } <add>} <add> <add>export function getSetLocaleDayOfWeek (input) { <add> var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; <add> return input == null ? weekday : this.add(input - weekday, 'd'); <add>} <add> <add>export function getSetISODayOfWeek (input) { <add> // behaves the same as moment#day except <add> // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) <add> // as a setter, sunday should belong to the previous week. <add> return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7); <add>} <ide><path>lib/units/day-of-year.js <add>import { addFormatToken } from "../format/format"; <add>import { addUnitAlias } from "./aliases"; <add>import { addRegexToken, match3, match1to3 } from "../parse/regex"; <add>import { daysInYear } from "./year"; <add>import { createUTCDate } from "../create/date-from-array"; <add>import { addParseToken } from "../parse/token"; <add>import toInt from "../utils/to-int"; <add> <add>// FORMATTING <add> <add>addFormatToken("DDD", ["DDDD", 3], "DDDo", "dayOfYear"); <add> <add>// ALIASES <add> <add>addUnitAlias("dayOfYear", "DDD"); <add> <add>// PARSING <add> <add>addRegexToken("DDD", match1to3); <add>addRegexToken("DDDD", match3); <add>addParseToken(["DDD", "DDDD"], function (input, array, config) { <add> config._dayOfYear = toInt(input); <add>}); <add> <add>// HELPERS <add> <add>//http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday <add>export function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) { <add> var d = createUTCDate(year, 0, 1).getUTCDay(); <add> var daysToAdd; <add> var dayOfYear; <add> <add> d = d === 0 ? 7 : d; <add> weekday = weekday != null ? weekday : firstDayOfWeek; <add> daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0); <add> dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1; <add> <add> return { <add> year : dayOfYear > 0 ? year : year - 1, <add> dayOfYear : dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear <add> }; <add>} <add> <add>// MOMENTS <add> <add>export function getSetDayOfYear (input) { <add> var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1; <add> return input == null ? dayOfYear : this.add((input - dayOfYear), 'd'); <add>} <ide><path>lib/units/hour.js <add>import { makeGetSet } from "../moment/get-set"; <add>import { addFormatToken } from "../format/format"; <add>import { addUnitAlias } from "./aliases"; <add>import { addRegexToken, match1to2, match2 } from "../parse/regex"; <add>import { addParseToken } from "../parse/token"; <add>import toInt from "../utils/to-int"; <add> <add>// FORMATTING <add> <add>addFormatToken("H", ["HH", 2], 0, "hour"); <add>addFormatToken("h", ["hh", 2], 0, function () { <add> return this.hours() % 12 || 12; <add>}); <add> <add>function meridiem (token, lowercase) { <add> addFormatToken(token, 0, 0, function () { <add> return this.localeData().meridiem(this.hours(), this.minutes(), lowercase); <add> }); <add>} <add> <add>meridiem('a', true); <add>meridiem('A', false); <add> <add>// ALIASES <add> <add>addUnitAlias("hour", "h"); <add> <add>// PARSING <add> <add>function matchMeridiem (isStrict, locale) { <add> return locale._meridiemParse; <add>} <add> <add>addRegexToken("a", matchMeridiem); <add>addRegexToken("A", matchMeridiem); <add>addRegexToken("H", match1to2); <add>addRegexToken("h", match1to2); <add>addRegexToken("HH", match1to2, match2); <add>addRegexToken("hh", match1to2, match2); <add> <add>addParseToken(["H", "HH"], 3); // TODO: use a constant for HOUR <add>addParseToken(["a", "A"], function (input, array, config) { <add> config._isPm = config._locale.isPM(input); <add> config._meridiem = input; <add>}); <add>addParseToken(["h", "hh"], function (input, array, config) { <add> array[3] = toInt(input); // TODO: use a constant for HOUR <add> config._pf.bigHour = true; <add>}); <add> <add>// LOCALES <add> <add>export function localeIsPM (input) { <add> // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays <add> // Using charAt should be more compatible. <add> return ((input + '').toLowerCase().charAt(0) === 'p'); <add>} <add> <add>export var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i; <add>export function localeMeridiem (hours, minutes, isLower) { <add> if (hours > 11) { <add> return isLower ? 'pm' : 'PM'; <add> } else { <add> return isLower ? 'am' : 'AM'; <add> } <add>} <add> <add> <add>// MOMENTS <add> <add>// Setting the hour should keep the time, because the user explicitly <add>// specified which hour he wants. So trying to maintain the same hour (in <add>// a new timezone) makes sense. Adding/subtracting hours does not follow <add>// this rule. <add>export var getSetHour = makeGetSet('Hours', true); <ide><path>lib/units/millisecond.js <add>import { makeGetSet } from "../moment/get-set"; <add>import { addFormatToken } from "../format/format"; <add>import { addUnitAlias } from "./aliases"; <add>import { addRegexToken, match1, match2, match3, match1to3, matchUnsigned } from "../parse/regex"; <add>import { addParseToken } from "../parse/token"; <add>import toInt from "../utils/to-int"; <add> <add>// FORMATTING <add> <add>addFormatToken("S", 0, 0, function () { <add> return ~~(this.millisecond() / 100); <add>}); <add> <add>addFormatToken(0, ["SS", 2], 0, function () { <add> return ~~(this.millisecond() / 10); <add>}); <add> <add>function milliseconds (token) { <add> addFormatToken(0, [token, 3], 0, "millisecond"); <add>} <add> <add>milliseconds("SSS"); <add>milliseconds("SSSS"); <add> <add>// ALIASES <add> <add>addUnitAlias("millisecond", "ms"); <add> <add>// PARSING <add> <add>addRegexToken("S", match1to3, match1); <add>addRegexToken("SS", match1to3, match2); <add>addRegexToken("SSS", match1to3, match3); <add>addRegexToken("SSSS", matchUnsigned); <add>addParseToken(["S", "SS", "SSS", "SSSS"], function (input, array) { <add> array[6] = toInt(('0.' + input) * 1000); // TODO: use a constant for MILLISECOND <add>}); <add> <add>// MOMENTS <add> <add>export var getSetMillisecond = makeGetSet('Milliseconds', false); <ide><path>lib/units/minute.js <add>import { makeGetSet } from "../moment/get-set"; <add>import { addFormatToken } from "../format/format"; <add>import { addUnitAlias } from "./aliases"; <add>import { addRegexToken, match1to2, match2 } from "../parse/regex"; <add>import { addParseToken } from "../parse/token"; <add> <add>// FORMATTING <add> <add>addFormatToken("m", ["mm", 2], 0, "minute"); <add> <add>// ALIASES <add> <add>addUnitAlias("minute", "m"); <add> <add>// PARSING <add> <add>addRegexToken("m", match1to2); <add>addRegexToken("mm", match1to2, match2); <add>addParseToken(["m", "mm"], 4); // TODO: use a constant for MINUTE <add> <add>// MOMENTS <add> <add>export var getSetMinute = makeGetSet('Minutes', false); <ide><path>lib/units/month.js <add>import { get } from "../moment/get-set"; <add>import { addFormatToken } from "../format/format"; <add>import { addUnitAlias } from "./aliases"; <add>import { addRegexToken, match1to2, match2, matchWord } from "../parse/regex"; <add>import { addParseToken } from "../parse/token"; <add>import { hooks } from "../utils/hooks"; <add>import toInt from "../utils/to-int"; <add>import { createUTC } from "../create/utc"; <add> <add>export function daysInMonth(year, month) { <add> return new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); <add>} <add> <add>// FORMATTING <add> <add>addFormatToken("M", ["MM", 2], "Mo", function () { <add> return this.month() + 1; <add>}); <add> <add>addFormatToken("MMM", 0, 0, function (format) { <add> return this.localeData().monthsShort(this, format); <add>}); <add> <add>addFormatToken("MMMM", 0, 0, function (format) { <add> return this.localeData().months(this, format); <add>}); <add> <add>// ALIASES <add> <add>addUnitAlias("month", "M"); <add> <add>// PARSING <add> <add>addRegexToken("M", match1to2); <add>addRegexToken("MM", match1to2, match2); <add>addRegexToken("MMM", matchWord); <add>addRegexToken("MMMM", matchWord); <add> <add>addParseToken(["M", "MM"], function (input, array) { <add> array[1] = toInt(input) - 1; // TODO: use a constant for MONTH <add>}); <add> <add>addParseToken(["MMM", "MMMM"], function (input, array, config, token) { <add> var month = config._locale.monthsParse(input, token, config._strict); <add> // if we didn't find a month name, mark the date as invalid. <add> if (month != null) { <add> array[1] = month; // TODO: use a constant for MONTH <add> } else { <add> config._pf.invalidMonth = input; <add> } <add>}); <add> <add>// LOCALES <add> <add>export var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'); <add>export function localeMonths (m) { <add> return this._months[m.month()]; <add>} <add> <add>export var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'); <add>export function localeMonthsShort (m) { <add> return this._monthsShort[m.month()]; <add>} <add> <add>export function localeMonthsParse (monthName, format, strict) { <add> var i, mom, regex; <add> <add> if (!this._monthsParse) { <add> this._monthsParse = []; <add> this._longMonthsParse = []; <add> this._shortMonthsParse = []; <add> } <add> <add> for (i = 0; i < 12; i++) { <add> // make the regex if we don't have it already <add> mom = createUTC([2000, i]); <add> if (strict && !this._longMonthsParse[i]) { <add> this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i'); <add> this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i'); <add> } <add> if (!strict && !this._monthsParse[i]) { <add> regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); <add> this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); <add> } <add> // test the regex <add> if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) { <add> return i; <add> } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) { <add> return i; <add> } else if (!strict && this._monthsParse[i].test(monthName)) { <add> return i; <add> } <add> } <add>} <add> <add>// MOMENTS <add> <add>export function setMonth (mom, value) { <add> var dayOfMonth; <add> <add> // TODO: Move this out of here! <add> if (typeof value === 'string') { <add> value = mom.localeData().monthsParse(value); <add> // TODO: Another silent failure? <add> if (typeof value !== 'number') { <add> return mom; <add> } <add> } <add> <add> dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); <add> mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); <add> return mom; <add>} <add> <add>export function getSetMonth (value) { <add> if (value != null) { <add> setMonth(this, value); <add> hooks.updateOffset(this, true); <add> return this; <add> } else { <add> return get(this, "Month"); <add> } <add>} <add> <add>export function getDaysInMonth () { <add> return daysInMonth(this.year(), this.month()); <add>} <ide><path>lib/units/offset.js <add>import zeroFill from "../utils/zero-fill"; <add>import { createDuration } from "../duration/create"; <add>import { addSubtract } from "../moment/add-subtract"; <add>import { isMoment } from "../moment/constructor"; <add>import { addFormatToken } from "../format/format"; <add>import { addRegexToken, matchOffset } from "../parse/regex"; <add>import { addParseToken } from "../parse/token"; <add>import { createLocal } from "../create/local"; <add>import { createUTC } from "../create/utc"; <add>import isDate from "../utils/is-date"; <add>import toInt from "../utils/to-int"; <add>import compareArrays from "../utils/compare-arrays"; <add>import { hooks } from "../utils/hooks"; <add> <add>// FORMATTING <add> <add>function offset (token, separator) { <add> addFormatToken(token, 0, 0, function () { <add> var offset = this.utcOffset(); <add> var sign = '+'; <add> if (offset < 0) { <add> offset = -offset; <add> sign = '-'; <add> } <add> return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2); <add> }); <add>} <add> <add>offset("Z", ":"); <add>offset("ZZ", ""); <add> <add>// PARSING <add> <add>addRegexToken("Z", matchOffset); <add>addRegexToken("ZZ", matchOffset); <add>addParseToken(["Z", "ZZ"], function (input, array, config) { <add> config._useUTC = true; <add> config._tzm = offsetFromString(input); <add>}); <add> <add>// HELPERS <add> <add>// timezone chunker <add>// '+10:00' > ['10', '00'] <add>// '-1530' > ['-15', '30'] <add>var chunkOffset = /([\+\-]|\d\d)/gi; <add> <add>function offsetFromString(string) { <add> var matches = ((string || "").match(matchOffset) || []); <add> var chunk = matches[matches.length - 1] || []; <add> var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0]; <add> var minutes = +(parts[1] * 60) + toInt(parts[2]); <add> <add> return parts[0] === '+' ? minutes : -minutes; <add>} <add> <add>// Return a moment from input, that is local/utc/zone equivalent to model. <add>export function cloneWithOffset(input, model) { <add> var res, diff; <add> if (model._isUTC) { <add> res = model.clone(); <add> diff = (isMoment(input) || isDate(input) ? +input : +createLocal(input)) - (+res); <add> // Use low-level api, because this fn is low-level api. <add> res._d.setTime(+res._d + diff); <add> hooks.updateOffset(res, false); <add> return res; <add> } else { <add> return createLocal(input).local(); <add> } <add> return model._isUTC ? createLocal(input).zone(model._offset || 0) : createLocal(input).local(); <add>} <add> <add>function getDateOffset (m) { <add> // On Firefox.24 Date#getTimezoneOffset returns a floating point. <add> // https://github.com/moment/moment/pull/1871 <add> return -Math.round(m._d.getTimezoneOffset() / 15) * 15; <add>} <add> <add>// HOOKS <add> <add>// This function will be called whenever a moment is mutated. <add>// It is intended to keep the offset in sync with the timezone. <add>hooks.updateOffset = function () {}; <add> <add>// MOMENTS <add> <add>// keepLocalTime = true means only change the timezone, without <add>// affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]--> <add>// 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset <add>// +0200, so we adjust the time as needed, to be valid. <add>// <add>// Keeping the time actually adds/subtracts (one hour) <add>// from the actual represented time. That is why we call updateOffset <add>// a second time. In case it wants us to change the offset again <add>// _changeInProgress == true case, then we have to adjust, because <add>// there is no such time in the given timezone. <add>export function getSetOffset (input, keepLocalTime) { <add> var offset = this._offset || 0, <add> localAdjust; <add> if (input != null) { <add> if (typeof input === 'string') { <add> input = offsetFromString(input); <add> } <add> if (Math.abs(input) < 16) { <add> input = input * 60; <add> } <add> if (!this._isUTC && keepLocalTime) { <add> localAdjust = getDateOffset(this); <add> } <add> this._offset = input; <add> this._isUTC = true; <add> if (localAdjust != null) { <add> this.add(localAdjust, 'm'); <add> } <add> if (offset !== input) { <add> if (!keepLocalTime || this._changeInProgress) { <add> addSubtract(this, createDuration(input - offset, 'm'), 1, false); <add> } else if (!this._changeInProgress) { <add> this._changeInProgress = true; <add> hooks.updateOffset(this, true); <add> this._changeInProgress = null; <add> } <add> } <add> return this; <add> } else { <add> return this._isUTC ? offset : getDateOffset(this); <add> } <add>} <add> <add>export function getSetZone (input, keepLocalTime) { <add> if (input != null) { <add> if (typeof input !== 'string') { <add> input = -input; <add> } <add> <add> this.utcOffset(input, keepLocalTime); <add> <add> return this; <add> } else { <add> return -this.utcOffset(); <add> } <add>} <add> <add>export function setOffsetToUTC (keepLocalTime) { <add> return this.utcOffset(0, keepLocalTime); <add>} <add> <add>export function setOffsetToLocal (keepLocalTime) { <add> if (this._isUTC) { <add> this.utcOffset(0, keepLocalTime); <add> this._isUTC = false; <add> <add> if (keepLocalTime) { <add> this.subtract(getDateOffset(this), 'm'); <add> } <add> } <add> return this; <add>} <add> <add>export function setOffsetToParsedOffset () { <add> if (this._tzm) { <add> this.utcOffset(this._tzm); <add> } else if (typeof this._i === 'string') { <add> this.utcOffset(offsetFromString(this._i)); <add> } <add> return this; <add>} <add> <add>export function hasAlignedHourOffset (input) { <add> if (!input) { <add> input = 0; <add> } <add> else { <add> input = createLocal(input).utcOffset(); <add> } <add> <add> return (this.utcOffset() - input) % 60 === 0; <add>} <add> <add>export function isDaylightSavingTime () { <add> return ( <add> this.utcOffset() > this.clone().month(0).utcOffset() || <add> this.utcOffset() > this.clone().month(5).utcOffset() <add> ); <add>} <add> <add>export function isDaylightSavingTimeShifted () { <add> if (this._a) { <add> var other = this._isUTC ? createUTC(this._a) : createLocal(this._a); <add> return this.isValid() && compareArrays(this._a, other.toArray()) > 0; <add> } <add> <add> return false; <add>} <add> <add>export function isLocal () { <add> return !this._isUTC; <add>} <add> <add>export function isUtcOffset () { <add> return this._isUTC; <add>} <add> <add>export function isUtc () { <add> return this._isUTC && this._offset === 0; <add>} <ide><path>lib/units/quarter.js <add>import { addFormatToken } from "../format/format"; <add>import { addUnitAlias } from "./aliases"; <add>import { addRegexToken, match1 } from "../parse/regex"; <add>import { addParseToken } from "../parse/token"; <add>import toInt from "../utils/to-int"; <add> <add>// FORMATTING <add> <add>addFormatToken("Q", 0, 0, "quarter"); <add> <add>// ALIASES <add> <add>addUnitAlias("quarter", "Q"); <add> <add>// PARSING <add> <add>addRegexToken("Q", match1); <add>addParseToken("Q", function (input, array) { <add> array[1] = (toInt(input) - 1) * 3; // TODO: use a constant for MONTH <add>}); <add> <add>// MOMENTS <add> <add>export function getSetQuarter (input) { <add> return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); <add>} <ide><path>lib/units/second.js <add>import { makeGetSet } from "../moment/get-set"; <add>import { addFormatToken } from "../format/format"; <add>import { addUnitAlias } from "./aliases"; <add>import { addRegexToken, match1to2, match2 } from "../parse/regex"; <add>import { addParseToken } from "../parse/token"; <add> <add>// FORMATTING <add> <add>addFormatToken("s", ["ss", 2], 0, "second"); <add> <add>// ALIASES <add> <add>addUnitAlias("second", "s"); <add> <add>// PARSING <add> <add>addRegexToken("s", match1to2); <add>addRegexToken("ss", match1to2, match2); <add>addParseToken(["s", "ss"], 5); // TODO: use a constant for SECOND <add> <add>// MOMENTS <add> <add>export var getSetSecond = makeGetSet('Seconds', false); <ide><path>lib/units/timestamp.js <add>import { addFormatToken } from "../format/format"; <add>import { addRegexToken, matchTimestamp, matchSigned } from "../parse/regex"; <add>import { addParseToken } from "../parse/token"; <add>import toInt from "../utils/to-int"; <add> <add>// FORMATTING <add> <add>addFormatToken("X", 0, 0, "unix"); <add>addFormatToken("x", 0, 0, "valueOf"); <add> <add>// PARSING <add> <add>addRegexToken("x", matchSigned); <add>addRegexToken("X", matchTimestamp); <add>addParseToken("X", function (input, array, config) { <add> config._d = new Date(parseFloat(input, 10) * 1000); <add>}); <add>addParseToken("x", function (input, array, config) { <add> config._d = new Date(toInt(input)); <add>}); <ide><path>lib/units/timezone.js <add>import { addFormatToken } from "../format/format"; <add> <add>// FORMATTING <add> <add>addFormatToken("z", 0, 0, "zoneAbbr"); <add>addFormatToken("zz", 0, 0, "zoneName"); <add> <add>// MOMENTS <add> <add>export function getZoneAbbr () { <add> return this._isUTC ? 'UTC' : ''; <add>} <add> <add>export function getZoneName () { <add> return this._isUTC ? 'Coordinated Universal Time' : ''; <add>} <ide><path>lib/units/units.js <add>// Side effect imports <add>import "./day-of-month"; <add>import "./day-of-week"; <add>import "./day-of-year"; <add>import "./hour"; <add>import "./millisecond"; <add>import "./minute"; <add>import "./month"; <add>import "./offset"; <add>import "./quarter"; <add>import "./second"; <add>import "./timestamp"; <add>import "./timezone"; <add>import "./week-year"; <add>import "./week"; <add>import "./year"; <add> <add>import { normalizeUnits } from "./aliases"; <add> <add>export { normalizeUnits }; <ide><path>lib/units/week-year.js <add>import { addFormatToken } from "../format/format"; <add>import { addUnitAlias } from "./aliases"; <add>import { addRegexToken, match1to2, match1to4, match1to6, match2, match4, match6, matchSigned } from "../parse/regex"; <add>import { addWeekParseToken } from "../parse/token"; <add>import { weekOfYear } from "./week"; <add>import toInt from "../utils/to-int"; <add>import { hooks } from "../utils/hooks"; <add>import { createLocal } from "../create/local"; <add> <add>// FORMATTING <add> <add>addFormatToken(0, ["gg", 2], 0, function () { <add> return this.weekYear() % 100; <add>}); <add> <add>addFormatToken(0, ["GG", 2], 0, function () { <add> return this.isoWeekYear() % 100; <add>}); <add> <add>function addWeekYearFormatToken (token, getter) { <add> addFormatToken(0, [token, token.length], 0, getter); <add>} <add> <add>addWeekYearFormatToken("gggg", "weekYear"); <add>addWeekYearFormatToken("ggggg", "weekYear"); <add>addWeekYearFormatToken("GGGG", "isoWeekYear"); <add>addWeekYearFormatToken("GGGGG", "isoWeekYear"); <add> <add>// ALIASES <add> <add>addUnitAlias("weekYear", "gg"); <add>addUnitAlias("isoWeekYear", "GG"); <add> <add>// PARSING <add> <add>addRegexToken("G", matchSigned); <add>addRegexToken("g", matchSigned); <add>addRegexToken("GG", match1to2, match2); <add>addRegexToken("gg", match1to2, match2); <add>addRegexToken("GGGG", match1to4, match4); <add>addRegexToken("gggg", match1to4, match4); <add>addRegexToken("GGGGG", match1to6, match6); <add>addRegexToken("ggggg", match1to6, match6); <add> <add>addWeekParseToken(["gggg", "ggggg", "GGGG", "GGGGG"], function (input, week, config, token) { <add> week[token.substr(0, 2)] = toInt(input); <add>}); <add> <add>addWeekParseToken(["gg", "GG"], function (input, week, config, token) { <add> week[token] = hooks.parseTwoDigitYear(input); <add>}); <add> <add>// HELPERS <add> <add>function weeksInYear(year, dow, doy) { <add> return weekOfYear(createLocal([year, 11, 31 + dow - doy]), dow, doy).week; <add>} <add> <add>// MOMENTS <add> <add>export function getSetWeekYear (input) { <add> var year = weekOfYear(this, this.localeData()._week.dow, this.localeData()._week.doy).year; <add> return input == null ? year : this.add((input - year), 'y'); <add>} <add> <add>export function getSetISOWeekYear (input) { <add> var year = weekOfYear(this, 1, 4).year; <add> return input == null ? year : this.add((input - year), 'y'); <add>} <add> <add>export function getISOWeeksInYear () { <add> return weeksInYear(this.year(), 1, 4); <add>} <add> <add>export function getWeeksInYear () { <add> var weekInfo = this.localeData()._week; <add> return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); <add>} <ide><path>lib/units/week.js <add>import { addFormatToken } from "../format/format"; <add>import { addUnitAlias } from "./aliases"; <add>import { addRegexToken, match1to2, match2 } from "../parse/regex"; <add>import { addWeekParseToken } from "../parse/token"; <add>import toInt from "../utils/to-int"; <add>import { createLocal } from "../create/local"; <add> <add>// FORMATTING <add> <add>addFormatToken("w", ["ww", 2], "wo", "week"); <add>addFormatToken("W", ["WW", 2], "Wo", "isoWeek"); <add> <add>// ALIASES <add> <add>addUnitAlias("week", "w"); <add>addUnitAlias("isoWeek", "W"); <add> <add>// PARSING <add> <add>addRegexToken("w", match1to2); <add>addRegexToken("ww", match1to2, match2); <add>addRegexToken("W", match1to2); <add>addRegexToken("WW", match1to2, match2); <add> <add>addWeekParseToken(["w", "ww", "W", "WW"], function (input, week, config, token) { <add> week[token.substr(0, 1)] = toInt(input); <add>}); <add> <add>// HELPERS <add> <add>// firstDayOfWeek 0 = sun, 6 = sat <add>// the day of the week that starts the week <add>// (usually sunday or monday) <add>// firstDayOfWeekOfYear 0 = sun, 6 = sat <add>// the first week is the week that contains the first <add>// of this day of the week <add>// (eg. ISO weeks use thursday (4)) <add>export function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) { <add> var end = firstDayOfWeekOfYear - firstDayOfWeek, <add> daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(), <add> adjustedMoment; <add> <add> <add> if (daysToDayOfWeek > end) { <add> daysToDayOfWeek -= 7; <add> } <add> <add> if (daysToDayOfWeek < end - 7) { <add> daysToDayOfWeek += 7; <add> } <add> <add> adjustedMoment = createLocal(mom).add(daysToDayOfWeek, 'd'); <add> return { <add> week: Math.ceil(adjustedMoment.dayOfYear() / 7), <add> year: adjustedMoment.year() <add> }; <add>} <add> <add>// LOCALES <add> <add>export function localeWeek (mom) { <add> return weekOfYear(mom, this._week.dow, this._week.doy).week; <add>} <add> <add>export var defaultLocaleWeek = { <add> dow : 0, // Sunday is the first day of the week. <add> doy : 6 // The week that contains Jan 1st is the first week of the year. <add>}; <add> <add>export function localeFirstDayOfWeek () { <add> return this._week.dow; <add>} <add> <add>export function localeFirstDayOfYear () { <add> return this._week.doy; <add>} <add> <add>// MOMENTS <add> <add>export function getSetWeek (input) { <add> var week = this.localeData().week(this); <add> return input == null ? week : this.add((input - week) * 7, 'd'); <add>} <add> <add>export function getSetISOWeek (input) { <add> var week = weekOfYear(this, 1, 4).week; <add> return input == null ? week : this.add((input - week) * 7, 'd'); <add>} <ide><path>lib/units/year.js <add>import { makeGetSet } from "../moment/get-set"; <add>import { addFormatToken } from "../format/format"; <add>import { addUnitAlias } from "./aliases"; <add>import { addRegexToken, match1to2, match1to4, match1to6, match2, match4, match6, matchSigned } from "../parse/regex"; <add>import { addParseToken } from "../parse/token"; <add>import { hooks } from "../utils/hooks"; <add>import toInt from "../utils/to-int"; <add> <add>// FORMATTING <add> <add>addFormatToken(0, ["YY", 2], 0, function () { <add> return this.year() % 100; <add>}); <add> <add>addFormatToken(0, ["YYYY", 4], 0, "year"); <add>addFormatToken(0, ["YYYYY", 5], 0, "year"); <add>addFormatToken(0, ["YYYYYY", 6, true], 0, "year"); <add> <add>// ALIASES <add> <add>addUnitAlias("year", "y"); <add> <add>// PARSING <add> <add>addRegexToken("Y", matchSigned); <add>addRegexToken("YY", match1to2, match2); <add>addRegexToken("YYYY", match1to4, match4); <add>addRegexToken("YYYYY", match1to6, match6); <add>addRegexToken("YYYYYY", match1to6, match6); <add> <add>addParseToken(["YYYY", "YYYYY", "YYYYYY"], 0); <add>addParseToken("YY", function (input, array) { <add> array[0] = hooks.parseTwoDigitYear(input); <add>}); <add> <add>// HELPERS <add> <add>export function daysInYear(year) { <add> return isLeapYear(year) ? 366 : 365; <add>} <add> <add>function isLeapYear(year) { <add> return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; <add>} <add> <add>// HOOKS <add> <add>hooks.parseTwoDigitYear = function (input) { <add> return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); <add>}; <add> <add>// MOMENTS <add> <add>export var getSetYear = makeGetSet('FullYear', false); <add> <add>export function getIsLeapYear () { <add> return isLeapYear(this.year()); <add>} <add> <ide><path>lib/utils/abs-floor.js <add>export default function absFloor (number) { <add> if (number < 0) { <add> return Math.ceil(number); <add> } else { <add> return Math.floor(number); <add> } <add>} <ide><path>lib/utils/compare-arrays.js <add>import toInt from "./to-int"; <add> <add>// compare two arrays, return the number of differences <add>export default function compareArrays(array1, array2, dontConvert) { <add> var len = Math.min(array1.length, array2.length), <add> lengthDiff = Math.abs(array1.length - array2.length), <add> diffs = 0, <add> i; <add> for (i = 0; i < len; i++) { <add> if ((dontConvert && array1[i] !== array2[i]) || <add> (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { <add> diffs++; <add> } <add> } <add> return diffs + lengthDiff; <add>} <ide><path>lib/utils/defaults.js <add>// Pick the first defined of two or three arguments. dfl comes from default. <add>export default function defaults(a, b, c) { <add> switch (arguments.length) { <add> case 2: return a != null ? a : b; <add> case 3: return a != null ? a : b != null ? b : c; <add> default: throw new Error('Implement me'); // TODO: Fix <add> } <add>} <ide><path>lib/utils/deprecate.js <add>import extend from "./extend"; <add>import { hooks } from "./hooks"; <add> <add>function warn(msg) { <add> if (hooks.suppressDeprecationWarnings === false && typeof console !== 'undefined' && console.warn) { <add> console.warn('Deprecation warning: ' + msg); <add> } <add>} <add> <add>export function deprecate(msg, fn) { <add> var firstTime = true; <add> return extend(function () { <add> if (firstTime) { <add> warn(msg); <add> firstTime = false; <add> } <add> return fn.apply(this, arguments); <add> }, fn); <add>} <add> <add>var deprecations = {}; <add> <add>export function deprecateSimple(name, msg) { <add> if (!deprecations[name]) { <add> warn(msg); <add> deprecations[name] = true; <add> } <add>} <add> <add>hooks.suppressDeprecationWarnings = false; <add> <ide><path>lib/utils/extend.js <add>import hasOwnProp from "./has-own-prop"; <add> <add>export default function extend(a, b) { <add> for (var i in b) { <add> if (hasOwnProp(b, i)) { <add> a[i] = b[i]; <add> } <add> } <add> <add> if (hasOwnProp(b, 'toString')) { <add> a.toString = b.toString; <add> } <add> <add> if (hasOwnProp(b, 'valueOf')) { <add> a.valueOf = b.valueOf; <add> } <add> <add> return a; <add>} <ide><path>lib/utils/has-own-prop.js <add>export default function hasOwnProp(a, b) { <add> return Object.prototype.hasOwnProperty.call(a, b); <add>} <ide><path>lib/utils/hooks.js <add>export { hooks, setHookCallback }; <add> <add>var hookCallback; <add> <add>function hooks () { <add> return hookCallback.apply(null, arguments); <add>} <add> <add>// This is done to register the method called with moment() <add>// without creating circular dependencies. <add>function setHookCallback (callback) { <add> hookCallback = callback; <add>} <ide><path>lib/utils/is-array.js <add>export default function isArray(input) { <add> return Object.prototype.toString.call(input) === '[object Array]'; <add>} <ide><path>lib/utils/is-date.js <add>export default function isDate(input) { <add> return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date; <add>} <ide><path>lib/utils/map.js <add>export default function map(arr, fn) { <add> var res = [], i; <add> for (i = 0; i < arr.length; ++i) { <add> res.push(fn(arr[i], i)); <add> } <add> return res; <add>} <ide><path>lib/utils/to-int.js <add>export default function toInt(argumentForCoercion) { <add> var coercedNumber = +argumentForCoercion, <add> value = 0; <add> <add> if (coercedNumber !== 0 && isFinite(coercedNumber)) { <add> if (coercedNumber >= 0) { <add> value = Math.floor(coercedNumber); <add> } else { <add> value = Math.ceil(coercedNumber); <add> } <add> } <add> <add> return value; <add>} <ide><path>lib/utils/zero-fill.js <add>export default function zeroFill(number, targetLength, forceSign) { <add> var output = '' + Math.abs(number), <add> sign = number >= 0; <add> <add> while (output.length < targetLength) { <add> output = '0' + output; <add> } <add> return (sign ? (forceSign ? '+' : '') : '-') + output; <add>} <ide><path>templates/amd-named.js <add>/*global define:false*/ <add> <add>import moment from "./moment"; <add> <add>define("moment", [], function () { <add> return moment; <add>}); <ide><path>templates/amd.js <add>/*global define:false*/ <add> <add>import moment from "./moment"; <add> <add>define([], function () { <add> return moment; <add>}); <ide><path>templates/globals.js <add>/*global window:false*/ <add> <add>import moment from "./moment"; <add> <add>window.moment = moment;
89
PHP
PHP
remove default value for debug's first argument
17be6d04725afcc92d56a51e77e170268886fff9
<ide><path>lib/Cake/basics.php <ide> function config() { <ide> * @link http://book.cakephp.org/2.0/en/development/debugging.html#basic-debugging <ide> * @link http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#debug <ide> */ <del> function debug($var = null, $showHtml = null, $showFrom = true) { <add> function debug($var, $showHtml = null, $showFrom = true) { <ide> if (Configure::read('debug') > 0) { <ide> App::uses('Debugger', 'Utility'); <ide> $file = '';
1
Text
Text
add a link to the facebook community
ff415592809f0af2a7bd91b236083de8ebebcfec
<ide><path>CONTRIBUTING.md <ide> Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe <ide> ## How to Get in Touch <ide> <ide> * IRC - [#reactnative on freenode](http://webchat.freenode.net/?channels=reactnative) <add>* [Facebook group](https://www.facebook.com/groups/react.native.community/) <ide> <ide> ## Style Guide <ide>
1
Javascript
Javascript
update version guard in some link specs to 1.33.0
65eb83510dca57a157598632a9f6ec4a35a28fe1
<ide><path>packages/link/spec/link-spec.js <ide> describe('link package', () => { <ide> expect(shell.openExternal.argsForCall[0][0]).toBe('http://github.com') <ide> }) <ide> <del> // only works in Atom >= 1.32.0 <add> // only works in Atom >= 1.33.0 <ide> // https://github.com/atom/link/pull/33#issuecomment-419643655 <ide> const atomVersion = atom.getVersion().split('.') <del> if (+atomVersion[0] > 1 || +atomVersion[1] >= 32) { <add> console.error("atomVersion", atomVersion) <add> if (+atomVersion[0] > 1 || +atomVersion[1] >= 33) { <ide> it("opens an 'atom:' link", async () => { <ide> await atom.workspace.open('sample.md') <ide>
1
Javascript
Javascript
fix shebang in tools/doc/generate.js
1d99441d3742045bdb7b8e8a8d013f81cdba8f40
<ide><path>tools/doc/generate.js <del>#!node <add>#!/usr/bin/env node <ide> // Copyright Joyent, Inc. and other Node contributors. <ide> // <ide> // Permission is hereby granted, free of charge, to any person obtaining a
1
Text
Text
add section on validation
52832fff9048482a5036a96d0a7c05cc238b9153
<ide><path>guide/english/html/html-forms/index.md <ide> The form tag can also have an attribute named "target" which specifies where the <ide> The action attribute defines the action to be performed when the form is submitted. <ide> Normally, the form data is sent to a web page at the Script URL when the user clicks on the submit button. If the action attribute is omitted, the action is set to the current page. <ide> <add> <add>## Form Validation <add>Form validation guarantees that user provided all the required data in a correct way. There are 2 broad types: **client-side** and **server-side** validation. Client-side validation can be done via JavaScript or HTML5 (required attribute for instance). It gives helpful and instant feedback to the user. Server-side validation is performed before data is saved to the database to avoid saving incorrect or even dangerous data. Usually, both types of validation should be implemented to get the best of the both worlds: great UX and proper security. <add> <ide> ## More information <ide> - [Wikipedia](https://en.wikipedia.org/wiki/Form_(HTML))
1
Python
Python
fix documentation typo
d21a5321a1529a93b0be7346cb04a7113d657004
<ide><path>airflow/operators/python_operator.py <ide> class BranchPythonOperator(PythonOperator): <ide> It derives the PythonOperator and expects a Python function that returns <ide> the task_id to follow. The task_id returned should point to a task <ide> directely downstream from {self}. All other "branches" or <del> directly downstream tasks are marked wit a state of "skipped" so that <add> directly downstream tasks are marked with a state of "skipped" so that <ide> these paths can't move forward. <ide> """ <ide> def execute(self, context):
1
Python
Python
fix backend tests
36392c75d74ab575bd986fcd9ee71078eff13b1e
<ide><path>tests/keras/backend/test_backends.py <ide> import numpy as np <ide> import pytest <ide> <del>from keras.backend import theano_backend as KTH <del>from keras.backend import tensorflow_backend as KTF <add>if sys.version_info.major == 2: <add> from keras.backend import theano_backend as KTH <add> from keras.backend import tensorflow_backend as KTF <ide> <ide> <ide> def check_single_tensor_operation(function_name, input_shape, **kwargs):
1
Python
Python
fix typo in `train_cli` docstring
ee63b2b19994cf9225c7235fade81732aea07e79
<ide><path>spacy/cli/train.py <ide> def train_cli( <ide> """ <ide> Train or update a spaCy pipeline. Requires data in spaCy's binary format. To <ide> convert data from other formats, use the `spacy convert` command. The <del> config file includes all settings and hyperparameters used during traing. <add> config file includes all settings and hyperparameters used during training. <ide> To override settings in the config, e.g. settings that point to local <ide> paths or that you want to experiment with, you can override them as <ide> command line options. For instance, --training.batch_size 128 overrides
1
Text
Text
fix a typo
4fbbcc7eb16abd486c6c73e838279e65cc45a2d9
<ide><path>inception/README.md <ide> batch-splitting the model across multiple GPUs. <ide> permit training the model with higher learning rates. <ide> <ide> * Often the GPU memory is a bottleneck that prevents employing larger batch <del> sizes. Employing more GPUs allows one to user larger batch sizes because <add> sizes. Employing more GPUs allows one to use larger batch sizes because <ide> this model splits the batch across the GPUs. <ide> <ide> **NOTE** If one wishes to train this model with *asynchronous* gradient updates,
1
PHP
PHP
fix psalm error
e2cb43f8ef4f9022065587f90d2a64fd7b46d596
<ide><path>src/View/View.php <ide> public function setLayout(string $name) <ide> * @param string|null $key The key to get or null for the whole config. <ide> * @param mixed $default The return value when the key does not exist. <ide> * @return mixed Config value being read. <add> * @psalm-suppress PossiblyNullArgument <ide> */ <ide> public function getConfig(?string $key = null, $default = null) <ide> {
1
PHP
PHP
add missing types to core class
d484dead0aa101e61bf51bb5573aacf18e4a9888
<ide><path>src/Core/Configure/ConfigEngineInterface.php <ide> interface ConfigEngineInterface <ide> * @param string $key Key to read. <ide> * @return array An array of data to merge into the runtime configuration <ide> */ <del> public function read($key); <add> public function read(string $key): array; <ide> <ide> /** <ide> * Dumps the configure data into the storage key/file of the given `$key`. <ide> public function read($key); <ide> * @param array $data The data to dump. <ide> * @return bool True on success or false on failure. <ide> */ <del> public function dump($key, array $data); <add> public function dump(string $key, array $data): bool; <ide> } <ide><path>src/Core/Configure/Engine/IniConfig.php <ide> public function __construct($path = null, $section = null) <ide> * @throws \Cake\Core\Exception\Exception when files don't exist. <ide> * Or when files contain '..' as this could lead to abusive reads. <ide> */ <del> public function read($key) <add> public function read(string $key): array <ide> { <ide> $file = $this->_getFilePath($key, true); <ide> <ide> public function read($key) <ide> * @param array $values Values to be exploded. <ide> * @return array Array of values exploded <ide> */ <del> protected function _parseNestedValues($values) <add> protected function _parseNestedValues(array $values): array <ide> { <ide> foreach ($values as $key => $value) { <ide> if ($value === '1') { <ide> protected function _parseNestedValues($values) <ide> * @param array $data The data to convert to ini file. <ide> * @return bool Success. <ide> */ <del> public function dump($key, array $data) <add> public function dump(string $key, array $data): bool <ide> { <ide> $result = []; <ide> foreach ($data as $k => $value) { <ide> public function dump($key, array $data) <ide> * @param mixed $value Value to export. <ide> * @return string String value for ini file. <ide> */ <del> protected function _value($value) <add> protected function _value($value): string <ide> { <ide> if ($value === null) { <ide> return 'null'; <ide><path>src/Core/Configure/Engine/JsonConfig.php <ide> public function __construct($path = null) <ide> * files contain '..' (as this could lead to abusive reads) or when there <ide> * is an error parsing the JSON string. <ide> */ <del> public function read($key) <add> public function read(string $key): array <ide> { <ide> $file = $this->_getFilePath($key, true); <ide> <ide> public function read($key) <ide> * @param array $data Data to dump. <ide> * @return bool Success <ide> */ <del> public function dump($key, array $data) <add> public function dump(string $key, array $data): bool <ide> { <ide> $filename = $this->_getFilePath($key); <ide> <ide><path>src/Core/Configure/Engine/PhpConfig.php <ide> * <ide> * ``` <ide> * <?php <del>declare(strict_types=1); <ide> * return [ <ide> * 'debug' => 0, <ide> * 'Security' => [ <ide> public function __construct($path = null) <ide> * @throws \Cake\Core\Exception\Exception when files don't exist or they don't contain `$config`. <ide> * Or when files contain '..' as this could lead to abusive reads. <ide> */ <del> public function read($key) <add> public function read(string $key): array <ide> { <ide> $file = $this->_getFilePath($key, true); <ide> <ide> public function read($key) <ide> * @param array $data Data to dump. <ide> * @return bool Success <ide> */ <del> public function dump($key, array $data) <add> public function dump(string $key, array $data): bool <ide> { <ide> $contents = '<?php' . "\n" . 'return ' . var_export($data, true) . ';'; <ide> <ide><path>src/Core/Configure/FileConfigTrait.php <ide> trait FileConfigTrait <ide> * @throws \Cake\Core\Exception\Exception When files don't exist or when <ide> * files contain '..' as this could lead to abusive reads. <ide> */ <del> protected function _getFilePath($key, $checkExists = false) <add> protected function _getFilePath(string $key, bool $checkExists = false): string <ide> { <ide> if (strpos($key, '..') !== false) { <ide> throw new Exception('Cannot load/dump configuration files with ../ in them.'); <ide><path>src/Core/Retry/RetryStrategyInterface.php <ide> interface RetryStrategyInterface <ide> * @param int $retryCount The number of times the action has been already called <ide> * @return bool Whether or not it is OK to retry the action <ide> */ <del> public function shouldRetry(Exception $exception, $retryCount); <add> public function shouldRetry(Exception $exception, int $retryCount): bool; <ide> } <ide><path>src/Database/Retry/ReconnectStrategy.php <ide> public function __construct(Connection $connection) <ide> * @param int $retryCount The number of times the action has been already called <ide> * @return bool Whether or not it is OK to retry the action <ide> */ <del> public function shouldRetry(Exception $exception, $retryCount) <add> public function shouldRetry(Exception $exception, int $retryCount): bool <ide> { <ide> $message = $exception->getMessage(); <ide>
7
Python
Python
fix the signatures of 3 functions
ed20ff4b4a448a4f38be46256add004ecc0c3471
<ide><path>numpy/core/_add_newdocs.py <ide> <ide> add_newdoc('numpy.core.multiarray', 'compare_chararrays', <ide> """ <del> compare_chararrays(a, b, cmp_op, rstrip) <add> compare_chararrays(a1, a2, cmp, rstrip) <ide> <ide> Performs element-wise comparison of two string arrays using the <ide> comparison operator specified by `cmp_op`. <ide> <ide> Parameters <ide> ---------- <del> a, b : array_like <add> a1, a2 : array_like <ide> Arrays to be compared. <del> cmp_op : {"<", "<=", "==", ">=", ">", "!="} <add> cmp : {"<", "<=", "==", ">=", ">", "!="} <ide> Type of comparison. <ide> rstrip : Boolean <ide> If True, the spaces at the end of Strings are removed before the comparison. <ide> <ide> add_newdoc('numpy.core.umath', 'frompyfunc', <ide> """ <del> frompyfunc(func, nin, nout, *[, identity]) <add> frompyfunc(func, /, nin, nout, *[, identity]) <ide> <ide> Takes an arbitrary Python function and returns a NumPy ufunc. <ide> <ide> <ide> add_newdoc('numpy.core.umath', 'seterrobj', <ide> """ <del> seterrobj(errobj) <add> seterrobj(errobj, /) <ide> <ide> Set the object that defines floating-point error handling. <ide>
1
PHP
PHP
add space between classname(s)
a943ea5c34c140f006d5bfbbf91b15286c86d5ed
<ide><path>lib/Cake/Console/Command/Task/TestTask.php <ide> public function buildTestSubject($type, $class) { <ide> * <ide> * @param string $type The Type of object you are generating tests for eg. controller <ide> * @param string $class the Classname of the class the test is being generated for. <del> * @return string Real classname <add> * @return string Real class name <ide> */ <ide> public function getRealClassName($type, $class) { <ide> if (strtolower($type) === 'model' || empty($this->classTypes[$type])) { <ide> protected function _processController($subject) { <ide> } <ide> <ide> /** <del> * Add classname to the fixture list. <add> * Add class name to the fixture list. <ide> * Sets the app. or plugin.plugin_name. prefix. <ide> * <ide> * @param string $name Name of the Model class that a fixture might be required for. <ide> public function hasMockClass($type) { <ide> } <ide> <ide> /** <del> * Generate a constructor code snippet for the type and classname <add> * Generate a constructor code snippet for the type and class name <ide> * <ide> * @param string $type The Type of object you are generating tests for eg. controller <ide> * @param string $fullClassName The Classname of the class the test is being generated for. <ide> public function generateConstructor($type, $fullClassName, $plugin) { <ide> } <ide> <ide> /** <del> * Generate the uses() calls for a type & classname <add> * Generate the uses() calls for a type & class name <ide> * <ide> * @param string $type The Type of object you are generating tests for eg. controller <ide> * @param string $realType The package name for the class. <ide><path>lib/Cake/Controller/Controller.php <ide> class Controller extends Object implements CakeEventListener { <ide> <ide> /** <ide> * An array containing the names of helpers this controller uses. The array elements should <del> * not contain the "Helper" part of the classname. <add> * not contain the "Helper" part of the class name. <ide> * <ide> * Example: `public $helpers = array('Html', 'Js', 'Time', 'Ajax');` <ide> * <ide> class Controller extends Object implements CakeEventListener { <ide> public $response; <ide> <ide> /** <del> * The classname to use for creating the response object. <add> * The class name to use for creating the response object. <ide> * <ide> * @var string <ide> */ <ide> class Controller extends Object implements CakeEventListener { <ide> <ide> /** <ide> * Array containing the names of components this controller uses. Component names <del> * should not contain the "Component" portion of the classname. <add> * should not contain the "Component" portion of the class name. <ide> * <ide> * Example: `public $components = array('Session', 'RequestHandler', 'Acl');` <ide> * <ide><path>lib/Cake/Log/CakeLog.php <ide> public static function config($key, $config) { <ide> throw new CakeLogException(__d('cake_dev', 'Invalid key name')); <ide> } <ide> if (empty($config['engine'])) { <del> throw new CakeLogException(__d('cake_dev', 'Missing logger classname')); <add> throw new CakeLogException(__d('cake_dev', 'Missing logger class name')); <ide> } <ide> if (empty(self::$_Collection)) { <ide> self::_init(); <ide><path>lib/Cake/Model/Model.php <ide> class Model extends Object implements CakeEventListener { <ide> * <ide> * ### Possible keys in association <ide> * <del> * - `className`: the classname of the model being associated to the current model. <add> * - `className`: the class name of the model being associated to the current model. <ide> * If you're defining a 'Profile belongsTo User' relationship, the className key should equal 'User.' <ide> * - `foreignKey`: the name of the foreign key found in the current model. This is <ide> * especially handy if you need to define multiple belongsTo relationships. The default <ide> class Model extends Object implements CakeEventListener { <ide> * <ide> * ### Possible keys in association <ide> * <del> * - `className`: the classname of the model being associated to the current model. <add> * - `className`: the class name of the model being associated to the current model. <ide> * If you're defining a 'User hasOne Profile' relationship, the className key should equal 'Profile.' <ide> * - `foreignKey`: the name of the foreign key found in the other model. This is <ide> * especially handy if you need to define multiple hasOne relationships. <ide> class Model extends Object implements CakeEventListener { <ide> * <ide> * ### Possible keys in association <ide> * <del> * - `className`: the classname of the model being associated to the current model. <add> * - `className`: the class name of the model being associated to the current model. <ide> * If you're defining a 'User hasMany Comment' relationship, the className key should equal 'Comment.' <ide> * - `foreignKey`: the name of the foreign key found in the other model. This is <ide> * especially handy if you need to define multiple hasMany relationships. The default <ide> class Model extends Object implements CakeEventListener { <ide> * <ide> * ### Possible keys in association <ide> * <del> * - `className`: the classname of the model being associated to the current model. <add> * - `className`: the class name of the model being associated to the current model. <ide> * If you're defining a 'Recipe HABTM Tag' relationship, the className key should equal 'Tag.' <ide> * - `joinTable`: The name of the join table used in this association (if the <ide> * current table doesn't adhere to the naming convention for HABTM join tables). <ide><path>lib/Cake/Network/Email/CakeEmail.php <ide> class CakeEmail { <ide> protected $_emailPattern = null; <ide> <ide> /** <del> * The classname used for email configuration. <add> * The class name used for email configuration. <ide> * <ide> * @var string <ide> */ <ide><path>lib/Cake/Network/Http/HttpSocket.php <ide> class HttpSocket extends CakeSocket { <ide> public $response = null; <ide> <ide> /** <del> * Response classname <add> * Response class name <ide> * <ide> * @var string <ide> */ <ide><path>lib/Cake/Routing/Dispatcher.php <ide> protected function _getController($request, $response) { <ide> } <ide> <ide> /** <del> * Load controller and return controller classname <add> * Load controller and return controller class name <ide> * <ide> * @param CakeRequest $request <ide> * @return string|boolean Name of controller class name <ide><path>lib/Cake/Test/Case/Console/Command/SchemaShellTest.php <ide> public function testName() { <ide> <ide> /** <ide> * test that passing name and file creates the passed filename with the <del> * passed classname <add> * passed class name <ide> * <ide> * @return void <ide> */ <ide><path>lib/Cake/Test/Case/Console/Command/Task/TestTaskTest.php <ide> public function testRegistryClearWhenBuildingTestObjects() { <ide> } <ide> <ide> /** <del> * test that getClassName returns the user choice as a classname. <add> * test that getClassName returns the user choice as a class name. <ide> * <ide> * @return void <ide> */ <ide> public function testGetUserFixtures() { <ide> } <ide> <ide> /** <del> * test that resolving classnames works <add> * test that resolving class names works <ide> * <ide> * @return void <ide> */ <ide> public function testGetRealClassname() { <ide> <ide> /** <ide> * test baking files. The conditionally run tests are known to fail in PHP4 <del> * as PHP4 classnames are all lower case, breaking the plugin path inflection. <add> * as PHP4 class names are all lower case, breaking the plugin path inflection. <ide> * <ide> * @return void <ide> */ <ide><path>lib/Cake/Test/Case/Network/Email/CakeEmailTest.php <ide> class TestCakeEmail extends CakeEmail { <ide> <ide> /** <del> * Config classname. <add> * Config class name. <ide> * <ide> * Use a the testing config class in this file. <ide> * <ide><path>lib/Cake/TestSuite/CakeTestSuiteCommand.php <ide> public function __construct($loader, $params = array()) { <ide> } <ide> <ide> /** <del> * Ugly hack to get around PHPUnit having a hard coded classname for the Runner. :( <add> * Ugly hack to get around PHPUnit having a hard coded class name for the Runner. :( <ide> * <ide> * @param array $argv <ide> * @param boolean $exit <ide><path>lib/Cake/TestSuite/Coverage/HtmlCoverageReport.php <ide> public function generateDiff($filename, $fileLines, $coverageData) { <ide> } <ide> <ide> /** <del> * Guess the classname the test was for based on the test case filename. <add> * Guess the class name the test was for based on the test case filename. <ide> * <ide> * @param ReflectionClass $testReflection. <ide> * @return string Possible test subject name. <ide><path>lib/Cake/Utility/Debugger.php <ide> public function outputError($data) { <ide> } <ide> <ide> /** <del> * Get the type of the given variable. Will return the classname <add> * Get the type of the given variable. Will return the class name <ide> * for objects. <ide> * <ide> * @param mixed $var The variable to get the type of <ide><path>lib/Cake/View/Helper.php <ide> protected function _initInputField($field, $options = array()) { <ide> * Adds the given class to the element options <ide> * <ide> * @param array $options Array options/attributes to add a class to <del> * @param string $class The classname being added. <add> * @param string $class The class name being added. <ide> * @param string $key the key to use for class. <ide> * @return array Array of options with $key set. <ide> */ <ide><path>lib/Cake/View/Helper/FormHelper.php <ide> public function isFieldError($field) { <ide> * - `escape` boolean - Whether or not to html escape the contents of the error. <ide> * - `wrap` mixed - Whether or not the error message should be wrapped in a div. If a <ide> * string, will be used as the HTML tag to use. <del> * - `class` string - The classname for the error message <add> * - `class` string - The class name for the error message <ide> * <ide> * @param string $field A field name, like "Modelname.fieldname" <ide> * @param string|array $text Error message as string or array of messages. <ide> public function label($fieldName = null, $text = null, $options = array()) { <ide> * @param array $blacklist A simple array of fields to not create inputs for. <ide> * @param array $options Options array. Valid keys are: <ide> * - `fieldset` Set to false to disable the fieldset. If a string is supplied it will be used as <del> * the classname for the fieldset element. <add> * the class name for the fieldset element. <ide> * - `legend` Set to false to disable the legend for the generated input set. Or supply a string <ide> * to customize the legend text. <ide> * @return string Completed form inputs. <ide> public function submit($caption = null, $options = array()) { <ide> * that string is displayed as the empty element. <ide> * - `escape` - If true contents of options will be HTML entity encoded. Defaults to true. <ide> * - `value` The selected value of the input. <del> * - `class` - When using multiple = checkbox the classname to apply to the divs. Defaults to 'checkbox'. <add> * - `class` - When using multiple = checkbox the class name to apply to the divs. Defaults to 'checkbox'. <ide> * - `disabled` - Control the disabled attribute. When creating a select box, set to true to disable the <ide> * select box. When creating checkboxes, `true` will disable all checkboxes. You can also set disabled <ide> * to a list of values you want to disable when creating checkboxes. <ide><path>lib/Cake/View/Helper/TimeHelper.php <ide> public function toRSS($dateString, $timezone = null) { <ide> * - `element` - The element to wrap the formatted time in. <ide> * Has a few additional options: <ide> * - `tag` - The tag to use, defaults to 'span'. <del> * - `class` - The classname to use, defaults to `time-ago-in-words`. <add> * - `class` - The class name to use, defaults to `time-ago-in-words`. <ide> * - `title` - Defaults to the $dateTime input. <ide> * <ide> * @param integer|string|DateTime $dateTime UNIX timestamp, strtotime() valid string or DateTime object <ide><path>lib/Cake/basics.php <ide> function h($text, $double = true, $charset = null) { <ide> if (!function_exists('pluginSplit')) { <ide> <ide> /** <del> * Splits a dot syntax plugin name into its plugin and classname. <add> * Splits a dot syntax plugin name into its plugin and class name. <ide> * If $name does not have a dot, then index 0 will be null. <ide> * <ide> * Commonly used like `list($plugin, $name) = pluginSplit($name);` <ide> * <ide> * @param string $name The name you want to plugin split. <ide> * @param boolean $dotAppend Set to true if you want the plugin to have a '.' appended to it. <ide> * @param string $plugin Optional default plugin to use if no plugin is found. Defaults to null. <del> * @return array Array with 2 indexes. 0 => plugin name, 1 => classname <add> * @return array Array with 2 indexes. 0 => plugin name, 1 => class name <ide> * @link http://book.cakephp.org/2.0/en/core-libraries/global-constants-and-functions.html#pluginSplit <ide> */ <ide> function pluginSplit($name, $dotAppend = false, $plugin = null) {
17
Python
Python
move doctest tests to own file with ifmain
199535c5c34360be7238c80b25d810abce62e6e4
<ide><path>numpy/testing/nosetester.py <ide> def bench(self, label='fast', verbose=1, extra_argv=None): <ide> <ide> return nose.run(argv=argv, addplugins=add_plugins) <ide> <del> <del>######################################################################## <del># Doctests for NumPy-specific nose/doctest modifications <del> <del># try the #random directive on the output line <del>def check_random_directive(): <del> ''' <del> >>> 2+2 <del> <BadExample object at 0x084D05AC> #random: may vary on your system <del> ''' <del> <del># check the implicit "import numpy as np" <del>def check_implicit_np(): <del> ''' <del> >>> np.array([1,2,3]) <del> array([1, 2, 3]) <del> ''' <del> <del># there's some extraneous whitespace around the correct responses <del>def check_whitespace_enabled(): <del> ''' <del> # whitespace after the 3 <del> >>> 1+2 <del> 3 <del> <del> # whitespace before the 7 <del> >>> 3+4 <del> 7 <del> ''' <ide><path>numpy/testing/tests/test_doctesting.py <add>""" Doctests for NumPy-specific nose/doctest modifications <add>""" <add># try the #random directive on the output line <add>def check_random_directive(): <add> ''' <add> >>> 2+2 <add> <BadExample object at 0x084D05AC> #random: may vary on your system <add> ''' <add> <add># check the implicit "import numpy as np" <add>def check_implicit_np(): <add> ''' <add> >>> np.array([1,2,3]) <add> array([1, 2, 3]) <add> ''' <add> <add># there's some extraneous whitespace around the correct responses <add>def check_whitespace_enabled(): <add> ''' <add> # whitespace after the 3 <add> >>> 1+2 <add> 3 <add> <add> # whitespace before the 7 <add> >>> 3+4 <add> 7 <add> ''' <add> <add> <add>if __name__ == '__main__': <add> # Run tests outside numpy test rig <add> import nose <add> from numpy.testing.noseclasses import NumpyDoctest <add> argv = ['', __file__, '--with-numpydoctest'] <add> nose.core.TestProgram(argv=argv, addplugins=[NumpyDoctest()])
2
Ruby
Ruby
check value of compiler rather than homebrew_cc
cb873d0833074f4477424a984c08311ef1293334
<ide><path>Library/Homebrew/extend/ENV/super.rb <ide> def cxx11 <ide> end <ide> <ide> def libcxx <del> if self['HOMEBREW_CC'] == 'clang' <del> append 'HOMEBREW_CCCFG', "g", '' <del> end <add> append "HOMEBREW_CCCFG", "g", "" if compiler == :clang <ide> end <ide> <ide> def libstdcxx <del> if self['HOMEBREW_CC'] == 'clang' <del> append 'HOMEBREW_CCCFG', "h", '' <del> end <add> append "HOMEBREW_CCCFG", "h", "" if compiler == :clang <ide> end <ide> <ide> def refurbish_args
1
Javascript
Javascript
remove extra newlines in tests
3b5f686658bbc0bd6de438796b2c2f0cd55b6374
<ide><path>src/test/locale/af.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2de', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/ar-ma.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 14]).format('w ww wo'), '3 03 3', 'Jan 14 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/ar-sa.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 14]).format('w ww wo'), '٣ ٠٣ ٣', 'Jan 14 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/ar-tn.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/ar.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 14]).format('w ww wo'), '٣ ٠٣ ٣', 'Jan 14 2012 should be week 3'); <ide> }); <ide> <del> <del> <del> <ide> test('no leading zeros in long date formats', function (assert) { <ide> var i, j, longDateStr, shortDateStr; <ide> for (i = 1; i <= 9; ++i) { <ide><path>src/test/locale/az.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3-üncü', 'Jan 9 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/be.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3-і', 'Jan 9 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/bg.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3-ти', 'Jan 9 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/bn.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '৩ ০৩ ৩', 'Jan 15 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/bo.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '༣ ༠༣ ༣', 'Jan 15 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/br.js <ide> test('special mutations for years', function (assert) { <ide> assert.equal(start.from(moment([2007, 1, 28]).add({y: 261}), true), '261 bloaz', 'mutation 261 years'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/bs.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3.', 'Jan 9 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/ca.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2a', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/cs.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/cv.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3-мӗш', 'Jan 9 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/cy.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2il', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/da.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/de-at.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/de.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/el.js <ide> test('weeks year starting sunday format', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2η', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/en-ca.js <ide> test('weeks year starting sunday format', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3rd', 'Jan 15 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/en-gb.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2nd', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/en-ie.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2nd', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/en.js <ide> test('weeks year starting sunday format', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3rd', 'Jan 15 2012 should be week 3'); <ide> }); <ide> <del> <ide> test('weekdays strict parsing', function (assert) { <ide> var m = moment('2015-01-01T12', moment.ISO_8601, true), <ide> enLocale = moment.localeData('en'); <ide> test('weekdays strict parsing', function (assert) { <ide> } <ide> }); <ide> <del> <ide><path>src/test/locale/eo.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3a', 'Jan 9 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/es.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2º', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/et.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/eu.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3.', 'Jan 9 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/fa.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 14]).format('w ww wo'), '۳ ۰۳ ۳م', 'Jan 14 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/fi.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/fo.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/fr-ca.js <ide> test('weeks year starting sunday format', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3e', 'Jan 15 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/fr-ch.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2e', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/fr.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/fy.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2de', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/gd.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2na', 'Faoi 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <del> <ide><path>src/test/locale/gl.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3º', 'Jan 9 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/he.js <ide> test('weeks year starting sunday format', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3', 'Jan 15 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/hi.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '३ ०३ ३', 'Jan 15 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide> test('meridiem', function (assert) { <ide> var h, m, t1, t2; <ide> for (h = 0; h < 24; ++h) { <ide><path>src/test/locale/hr.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3.', 'Jan 9 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/hu.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3.', 'Jan 9 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/hy-am.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3-րդ', 'Jan 9 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/id.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3', 'Jan 9 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide> test('meridiem invariant', function (assert) { <ide> var h, m, t1, t2; <ide> for (h = 0; h < 24; ++h) { <ide><path>src/test/locale/is.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/it.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2º', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/ja.js <ide> test('weeks year starting sunday format', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3', 'Jan 15 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/jv.js <ide> import {localeModule, test} from '../qunit'; <ide> import moment from '../../moment'; <ide> localeModule('jv'); <ide> <del> <ide> test('parse', function (assert) { <ide> var tests = 'Januari Jan_Februari Feb_Maret Mar_April Apr_Mei Mei_Juni Jun_Juli Jul_Agustus Ags_September Sep_Oktober Okt_Nopember Nop_Desember Des'.split('_'), i; <ide> function equalTest(input, mmm, i) { <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3', 'Jan 9 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide> test('meridiem invariant', function (assert) { <ide> var h, m, t1, t2; <ide> for (h = 0; h < 24; ++h) { <ide><path>src/test/locale/ka.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 მე-3', 'იან 9 2012 უნდა იყოს კვირა 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/kk.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3-ші', 'Jan 15 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/km.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/ko.js <ide> test('parse meridiem', function (assert) { <ide> expected : '16' <ide> }], i, l, it, actual; <ide> <del> <ide> for (i = 0, l = elements.length; i < l; ++i) { <ide> it = elements[i]; <ide> actual = moment(it.expression, it.inputFormat).format(it.outputFormat); <ide> test('weeks year starting sunday format', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3일', 'Jan 15 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/lb.js <ide> test('calendar last week', function (assert) { <ide> } <ide> }); <ide> <del> <del> <ide><path>src/test/locale/lo.js <ide> test('weeks year starting sunday format', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 ທີ່3', 'Jan 15 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/lt.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2-oji', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/lv.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/me.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3.', 'Jan 9 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/mk.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3-ти', 'Jan 9 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/ml.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3', 'Jan 15 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/mr.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '३ ०३ ३', 'Jan 15 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide> test('meridiem invariant', function (assert) { <ide> var h, m, t1, t2; <ide> for (h = 0; h < 24; ++h) { <ide><path>src/test/locale/ms-my.js <ide> test('weeks year starting sunday format', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3', 'Jan 15 2012 sepatutnya minggu 3'); <ide> }); <ide> <del> <ide> test('meridiem invariant', function (assert) { <ide> var h, m, t1, t2; <ide> for (h = 0; h < 24; ++h) { <ide> test('meridiem invariant', function (assert) { <ide> } <ide> }); <ide> <del> <ide><path>src/test/locale/ms.js <ide> test('weeks year starting sunday format', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3', 'Jan 15 2012 sepatutnya minggu 3'); <ide> }); <ide> <del> <ide> test('meridiem invariant', function (assert) { <ide> var h, m, t1, t2; <ide> for (h = 0; h < 24; ++h) { <ide> test('meridiem invariant', function (assert) { <ide> } <ide> }); <ide> <del> <ide><path>src/test/locale/my.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '၂ ၀၂ ၂', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/nb.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/ne.js <ide> test('meridiem', function (assert) { <ide> assert.equal(moment([2011, 2, 23, 21, 20]).format('A'), 'राति', 'night'); <ide> }); <ide> <del> <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2011, 11, 26]).format('w ww wo'), '५३ ५३ ५३', 'Dec 26 2011 should be week 53'); <ide> assert.equal(moment([2012, 0, 1]).format('w ww wo'), '१ ०१ १', 'Jan 1 2012 should be week 1'); <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '२ ०२ २', 'Jan 9 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide> test('meridiem invariant', function (assert) { <ide> var h, m, t1, t2; <ide> for (h = 0; h < 24; ++h) { <ide><path>src/test/locale/nl.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2de', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/nn.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/pl.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/pt-br.js <ide> test('weeks year starting sunday format', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3º', 'Jan 15 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/pt.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2º', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/ro.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3', 'Jan 9 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/ru.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3-я', 'Jan 9 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/se.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/si.js <ide> test('calendar all else', function (assert) { <ide> assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/sk.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/sl.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3.', 'Jan 9 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/sq.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/sr-cyrl.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3.', 'Jan 9 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/sr.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3.', 'Jan 9 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/sv.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2a', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/sw.js <ide> test('weeks year starting sunday format', function (assert) { <ide> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3', 'Jan 9 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/ta.js <ide> test('meridiem', function (assert) { <ide> assert.equal(moment([2011, 2, 23, 23, 30]).format('a'), ' யாமம்', '(before) midnight'); <ide> }); <ide> <del> <del> <ide> test('meridiem invariant', function (assert) { <ide> var h, m, t1, t2; <ide> for (h = 0; h < 24; ++h) { <ide><path>src/test/locale/te.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3వ', 'Jan 15 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide> test('meridiem', function (assert) { <ide> var h, m, t1, t2; <ide> for (h = 0; h < 24; ++h) { <ide><path>src/test/locale/th.js <ide> test('weeks year starting sunday format', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3', 'Jan 15 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/tl-ph.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/tlh.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/tr.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3\'üncü', 'Jan 9 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/tzl.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/tzm-latn.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 14]).format('w ww wo'), '3 03 3', 'Jan 14 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/tzm.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 14]).format('w ww wo'), '3 03 3', 'Jan 14 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/uk.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3-й', 'Jan 9 2012 should be week 3'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/uz.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/vi.js <ide> test('weeks year starting sunday formatted', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2', 'Jan 15 2012 should be week 2'); <ide> }); <ide> <del> <del> <ide><path>src/test/locale/zh-cn.js <ide> test('weeks year starting sunday format', function (assert) { <ide> assert.equal(moment([2012, 0, 14]).format('w ww wo'), '2 02 2周', 'Jan 14 2012 应该是第 2周'); <ide> }); <ide> <del> <del> <ide> test('meridiem invariant', function (assert) { <ide> var h, m, t1, t2; <ide> for (h = 0; h < 24; ++h) { <ide><path>src/test/locale/zh-tw.js <ide> test('weeks year starting sunday format', function (assert) { <ide> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3週', 'Jan 15 2012 應該是第 3週'); <ide> }); <ide> <del> <del> <ide> test('meridiem invariant', function (assert) { <ide> var h, m, t1, t2; <ide> for (h = 0; h < 24; ++h) {
94
Ruby
Ruby
add test for `formatter.columns`
ef70677e881855f1e7b51f158752e1ee78b27a96
<ide><path>Library/Homebrew/cask/spec/formatter_spec.rb <add>require "spec_helper" <add>require "utils/formatter" <add>require "utils/tty" <add> <add>describe Formatter do <add> describe "::columns" do <add> let(:input) { <add> [ <add> 'aa', <add> 'bbb', <add> 'ccc', <add> 'dd' <add> ] <add> } <add> subject { described_class.columns(input) } <add> <add> it "doesn't output columns if $stdout is not a TTY." do <add> allow_any_instance_of(IO).to receive(:tty?).and_return(false) <add> allow(Tty).to receive(:width).and_return(10) <add> <add> expect(subject).to eq( <add> "aa\n" \ <add> "bbb\n" \ <add> "ccc\n" \ <add> "dd\n" <add> ) <add> end <add> <add> describe "$stdout is a TTY" do <add> it "outputs columns" do <add> allow_any_instance_of(IO).to receive(:tty?).and_return(true) <add> allow(Tty).to receive(:width).and_return(10) <add> <add> expect(subject).to eq( <add> "aa ccc\n" \ <add> "bbb dd\n" <add> ) <add> end <add> <add> it "outputs only one line if everything fits" do <add> allow_any_instance_of(IO).to receive(:tty?).and_return(true) <add> allow(Tty).to receive(:width).and_return(20) <add> <add> expect(subject).to eq( <add> "aa bbb ccc dd\n" <add> ) <add> end <add> end <add> <add> describe "with empty input" do <add> let(:input) { [] } <add> <add> it { is_expected.to eq("\n") } <add> end <add> end <add>end
1
PHP
PHP
remove deprecated calls in cake\mailer
cce7909e1abc65bcb0189e42425f76774933bc69
<ide><path>src/Mailer/Email.php <ide> public static function deliver($to = null, $subject = null, $message = null, $tr <ide> if (is_array($message)) { <ide> $instance->setViewVars($message); <ide> $message = null; <del> } elseif ($message === null && array_key_exists('message', $config = $instance->profile())) { <add> } elseif ($message === null && array_key_exists('message', $config = $instance->getProfile())) { <ide> $message = $config['message']; <ide> } <ide> <ide><path>src/Mailer/Transport/MailTransport.php <ide> public function send(Email $email) <ide> $headers[$key] = str_replace(["\r", "\n"], '', $header); <ide> } <ide> $headers = $this->_headersToString($headers, $eol); <del> $subject = str_replace(["\r", "\n"], '', $email->subject()); <add> $subject = str_replace(["\r", "\n"], '', $email->getSubject()); <ide> $to = str_replace(["\r", "\n"], '', $to); <ide> <ide> $message = implode($eol, $email->message()); <ide><path>src/Mailer/Transport/SmtpTransport.php <ide> protected function _prepareRcptCmd($email) <ide> */ <ide> protected function _prepareFromAddress($email) <ide> { <del> $from = $email->returnPath(); <add> $from = $email->getReturnPath(); <ide> if (empty($from)) { <del> $from = $email->from(); <add> $from = $email->getFrom(); <ide> } <ide> <ide> return $from; <ide> protected function _prepareFromAddress($email) <ide> */ <ide> protected function _prepareRecipientAddresses($email) <ide> { <del> $to = $email->to(); <del> $cc = $email->cc(); <del> $bcc = $email->bcc(); <add> $to = $email->getTo(); <add> $cc = $email->getCc(); <add> $bcc = $email->getBcc(); <ide> <ide> return array_merge(array_keys($to), array_keys($cc), array_keys($bcc)); <ide> } <ide><path>src/TestSuite/EmailAssertTrait.php <ide> public function email($new = false) <ide> { <ide> if ($new || !$this->_email) { <ide> $this->_email = new Email(); <del> $this->_email->profile(['transport' => 'debug'] + $this->_email->profile()); <add> $this->_email->getProfile(['transport' => 'debug'] + $this->_email->getProfile()); <ide> } <ide> <ide> return $this->_email; <ide> public function assertEmailTextMessageContains($needle, $message = null) <ide> */ <ide> public function assertEmailSubject($expected, $message = null) <ide> { <del> $result = $this->email()->subject(); <add> $result = $this->email()->getSubject(); <ide> $this->assertSame($expected, $result, $message); <ide> } <ide> <ide> public function assertEmailFrom($email, $name = null, $message = null) <ide> } <ide> <ide> $expected = [$email => $name]; <del> $result = $this->email()->from(); <add> $result = $this->email()->getFrom(); <ide> $this->assertSame($expected, $result, $message); <ide> } <ide> <ide> public function assertEmailCc($email, $name = null, $message = null) <ide> } <ide> <ide> $expected = [$email => $name]; <del> $result = $this->email()->cc(); <add> $result = $this->email()->getCc(); <ide> $this->assertSame($expected, $result, $message); <ide> } <ide> <ide> public function assertEmailCc($email, $name = null, $message = null) <ide> */ <ide> public function assertEmailCcContains($email, $name = null, $message = null) <ide> { <del> $result = $this->email()->cc(); <add> $result = $this->email()->getCc(); <ide> $this->assertNotEmpty($result[$email], $message); <ide> if ($name !== null) { <ide> $this->assertEquals($result[$email], $name, $message); <ide> public function assertEmailBcc($email, $name = null, $message = null) <ide> } <ide> <ide> $expected = [$email => $name]; <del> $result = $this->email()->bcc(); <add> $result = $this->email()->getBcc(); <ide> $this->assertSame($expected, $result, $message); <ide> } <ide> <ide> public function assertEmailBcc($email, $name = null, $message = null) <ide> */ <ide> public function assertEmailBccContains($email, $name = null, $message = null) <ide> { <del> $result = $this->email()->bcc(); <add> $result = $this->email()->getBcc(); <ide> $this->assertNotEmpty($result[$email], $message); <ide> if ($name !== null) { <ide> $this->assertEquals($result[$email], $name, $message); <ide> public function assertEmailTo($email, $name = null, $message = null) <ide> } <ide> <ide> $expected = [$email => $name]; <del> $result = $this->email()->to(); <add> $result = $this->email()->getTo(); <ide> $this->assertSame($expected, $result, $message); <ide> } <ide> <ide> public function assertEmailTo($email, $name = null, $message = null) <ide> */ <ide> public function assertEmailToContains($email, $name = null, $message = null) <ide> { <del> $result = $this->email()->to(); <add> $result = $this->email()->getTo(); <ide> $this->assertNotEmpty($result[$email], $message); <ide> if ($name !== null) { <ide> $this->assertEquals($result[$email], $name, $message); <ide> public function assertEmailToContains($email, $name = null, $message = null) <ide> */ <ide> public function assertEmailAttachmentsContains($filename, array $file = null, $message = null) <ide> { <del> $result = $this->email()->attachments(); <add> $result = $this->email()->getAttachments(); <ide> $this->assertNotEmpty($result[$filename], $message); <ide> if ($file === null) { <ide> return;
4
Javascript
Javascript
add an index file to make builds happen
9d432f9d092eae7e33452fb453773893c0e93b25
<ide><path>examples/universal/index.js <add>require('./client.js');
1