content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Ruby
Ruby
remove deprecated options from brew-diy
ecc9407fed2ab64c45c9499f896f0191a741c8ff
<ide><path>Library/Homebrew/cmd/diy.rb <ide> <ide> module Homebrew <ide> def diy <del> %w[name version].each do |opt| <del> if ARGV.include? "--set-#{opt}" <del> opoo "--set-#{opt} is deprecated, please use --#{opt}=<#{opt}> instead" <del> end <del> end <del> <ide> path = Pathname.getwd <ide> <del> version = ARGV.value "version" <del> version ||= if ARGV.include? "--set-version" <del> ARGV.next <del> elsif path.version.to_s.empty? <del> raise "Couldn't determine version, set it with --version=<version>" <del> else <del> path.version <del> end <del> <del> name = ARGV.value "name" <del> name ||= ARGV.next if ARGV.include? "--set-name" <del> name ||= detected_name(path, version) <add> version = ARGV.value("version") || detect_version(path) <add> name = ARGV.value("name") || detect_name(path, version) <ide> <ide> prefix = HOMEBREW_CELLAR/name/version <ide> <ide> def diy <ide> end <ide> end <ide> <del> def detected_name(path, version) <add> def detect_version(path) <add> version = path.version.to_s <add> <add> if version.empty? <add> raise "Couldn't determine version, set it with --version=<version>" <add> else <add> version <add> end <add> end <add> <add> def detect_name(path, version) <ide> basename = path.basename.to_s <ide> detected_name = basename[/(.*?)-?#{Regexp.escape(version)}/, 1] || basename <ide> canonical_name = Formulary.canonical_name(detected_name)
1
Ruby
Ruby
remove request reference from chained jars
e18ebd2e62f0878a27ac3e6c810ae533f91556fa
<ide><path>actionpack/lib/action_dispatch/middleware/cookies.rb <ide> module ChainedCookieJars <ide> # cookies.permanent.signed[:remember_me] = current_user.id <ide> # # => Set-Cookie: remember_me=BAhU--848956038e692d7046deab32b7131856ab20e14e; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT <ide> def permanent <del> @permanent ||= PermanentCookieJar.new(self, @request) <add> @permanent ||= PermanentCookieJar.new(self) <ide> end <ide> <ide> # Returns a jar that'll automatically generate a signed representation of cookie value and verify it when reading from <ide> def permanent <ide> def signed <ide> @signed ||= <ide> if upgrade_legacy_signed_cookies? <del> UpgradeLegacySignedCookieJar.new(self, @request) <add> UpgradeLegacySignedCookieJar.new(self) <ide> else <del> SignedCookieJar.new(self, @request) <add> SignedCookieJar.new(self) <ide> end <ide> end <ide> <ide> def signed <ide> def encrypted <ide> @encrypted ||= <ide> if upgrade_legacy_signed_cookies? <del> UpgradeLegacyEncryptedCookieJar.new(self, @request) <add> UpgradeLegacyEncryptedCookieJar.new(self) <ide> else <del> EncryptedCookieJar.new(self, @request) <add> EncryptedCookieJar.new(self) <ide> end <ide> end <ide> <ide> # Returns the +signed+ or +encrypted+ jar, preferring +encrypted+ if +secret_key_base+ is set. <ide> # Used by ActionDispatch::Session::CookieStore to avoid the need to introduce new cookie stores. <ide> def signed_or_encrypted <ide> @signed_or_encrypted ||= <del> if @request.secret_key_base.present? <add> if request.secret_key_base.present? <ide> encrypted <ide> else <ide> signed <ide> end <ide> end <ide> <add> protected <add> <add> def request; @parent_jar.request; end <add> <ide> private <ide> <ide> def upgrade_legacy_signed_cookies? <del> @request.secret_token.present? && @request.secret_key_base.present? <add> request.secret_token.present? && request.secret_key_base.present? <ide> end <ide> <ide> def key_generator <del> @request.key_generator <add> request.key_generator <ide> end <ide> end <ide> <ide> def key_generator <ide> module VerifyAndUpgradeLegacySignedMessage # :nodoc: <ide> def initialize(*args) <ide> super <del> @legacy_verifier = ActiveSupport::MessageVerifier.new(@request.secret_token, serializer: ActiveSupport::MessageEncryptor::NullSerializer) <add> @legacy_verifier = ActiveSupport::MessageVerifier.new(request.secret_token, serializer: ActiveSupport::MessageEncryptor::NullSerializer) <ide> end <ide> <ide> def verify_and_upgrade_legacy_signed_message(name, signed_message) <ide> def self.build(req, cookies) <ide> end <ide> end <ide> <add> attr_reader :request <add> <ide> def initialize(request) <ide> @set_cookies = {} <ide> @delete_cookies = {} <ide> def handle_options(options) #:nodoc: <ide> <ide> # if host is not ip and matches domain regexp <ide> # (ip confirms to domain regexp so we explicitly check for ip) <del> options[:domain] = if (@request.host !~ /^[\d.]+$/) && (@request.host =~ domain_regexp) <add> options[:domain] = if (request.host !~ /^[\d.]+$/) && (request.host =~ domain_regexp) <ide> ".#{$&}" <ide> end <ide> elsif options[:domain].is_a? Array <ide> # if host matches one of the supplied domains without a dot in front of it <del> options[:domain] = options[:domain].find {|domain| @request.host.include? domain.sub(/^\./, '') } <add> options[:domain] = options[:domain].find {|domain| request.host.include? domain.sub(/^\./, '') } <ide> end <ide> end <ide> <ide> def recycle! #:nodoc: <ide> <ide> private <ide> def write_cookie?(cookie) <del> @request.ssl? || !cookie[:secure] || always_write_cookie <add> request.ssl? || !cookie[:secure] || always_write_cookie <ide> end <ide> end <ide> <ide> class PermanentCookieJar #:nodoc: <ide> include ChainedCookieJars <ide> <del> def initialize(parent_jar, request) <add> def initialize(parent_jar) <ide> @parent_jar = parent_jar <del> @request = request <ide> end <ide> <ide> def [](name) <ide> module SerializedCookieJars # :nodoc: <ide> <ide> protected <ide> def needs_migration?(value) <del> @request.cookies_serializer == :hybrid && value.start_with?(MARSHAL_SIGNATURE) <add> request.cookies_serializer == :hybrid && value.start_with?(MARSHAL_SIGNATURE) <ide> end <ide> <ide> def serialize(value) <ide> def deserialize(name, value) <ide> end <ide> <ide> def serializer <del> serializer = @request.cookies_serializer || :marshal <add> serializer = request.cookies_serializer || :marshal <ide> case serializer <ide> when :marshal <ide> Marshal <ide> def serializer <ide> end <ide> <ide> def digest <del> @request.cookies_digest || 'SHA1' <add> request.cookies_digest || 'SHA1' <ide> end <ide> end <ide> <ide> class SignedCookieJar #:nodoc: <ide> include ChainedCookieJars <ide> include SerializedCookieJars <ide> <del> def initialize(parent_jar, request) <add> def initialize(parent_jar) <ide> @parent_jar = parent_jar <del> @request = request <ide> secret = key_generator.generate_key(request.signed_cookie_salt) <ide> @verifier = ActiveSupport::MessageVerifier.new(secret, digest: digest, serializer: ActiveSupport::MessageEncryptor::NullSerializer) <ide> end <ide> class EncryptedCookieJar #:nodoc: <ide> include ChainedCookieJars <ide> include SerializedCookieJars <ide> <del> def initialize(parent_jar, request) <del> @request = request <add> def initialize(parent_jar) <add> @parent_jar = parent_jar <ide> <ide> if ActiveSupport::LegacyKeyGenerator === key_generator <ide> raise "You didn't set secrets.secret_key_base, which is required for this cookie jar. " + <ide> "Read the upgrade documentation to learn more about this new config option." <ide> end <ide> <del> @parent_jar = parent_jar <ide> secret = key_generator.generate_key(request.encrypted_cookie_salt || '') <ide> sign_secret = key_generator.generate_key(request.encrypted_signed_cookie_salt || '') <ide> @encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret, digest: digest, serializer: ActiveSupport::MessageEncryptor::NullSerializer)
1
Ruby
Ruby
extract a method to simplify setup code
49223c9bc9bab1d827e98763ee49892b8c4faa72
<ide><path>activerecord/test/cases/associations/eager_singularization_test.rb <ide> class Compress < ActiveRecord::Base <ide> end <ide> <ide> def setup <del> skip 'Does not support migrations' unless ActiveRecord::Base.connection.supports_migrations? <add> skip 'Does not support migrations' unless connection.supports_migrations? <ide> <del> ActiveRecord::Base.connection.create_table :viri do |t| <add> connection.create_table :viri do |t| <ide> t.column :octopus_id, :integer <ide> t.column :species, :string <ide> end <del> ActiveRecord::Base.connection.create_table :octopi do |t| <add> connection.create_table :octopi do |t| <ide> t.column :species, :string <ide> end <del> ActiveRecord::Base.connection.create_table :passes do |t| <add> connection.create_table :passes do |t| <ide> t.column :bus_id, :integer <ide> t.column :rides, :integer <ide> end <del> ActiveRecord::Base.connection.create_table :buses do |t| <add> connection.create_table :buses do |t| <ide> t.column :name, :string <ide> end <del> ActiveRecord::Base.connection.create_table :crises_messes, :id => false do |t| <add> connection.create_table :crises_messes, :id => false do |t| <ide> t.column :crisis_id, :integer <ide> t.column :mess_id, :integer <ide> end <del> ActiveRecord::Base.connection.create_table :messes do |t| <add> connection.create_table :messes do |t| <ide> t.column :name, :string <ide> end <del> ActiveRecord::Base.connection.create_table :crises do |t| <add> connection.create_table :crises do |t| <ide> t.column :name, :string <ide> end <del> ActiveRecord::Base.connection.create_table :successes do |t| <add> connection.create_table :successes do |t| <ide> t.column :name, :string <ide> end <del> ActiveRecord::Base.connection.create_table :analyses do |t| <add> connection.create_table :analyses do |t| <ide> t.column :crisis_id, :integer <ide> t.column :success_id, :integer <ide> end <del> ActiveRecord::Base.connection.create_table :dresses do |t| <add> connection.create_table :dresses do |t| <ide> t.column :crisis_id, :integer <ide> end <del> ActiveRecord::Base.connection.create_table :compresses do |t| <add> connection.create_table :compresses do |t| <ide> t.column :dress_id, :integer <ide> end <ide> end <ide> <ide> def teardown <del> ActiveRecord::Base.connection.drop_table :viri <del> ActiveRecord::Base.connection.drop_table :octopi <del> ActiveRecord::Base.connection.drop_table :passes <del> ActiveRecord::Base.connection.drop_table :buses <del> ActiveRecord::Base.connection.drop_table :crises_messes <del> ActiveRecord::Base.connection.drop_table :messes <del> ActiveRecord::Base.connection.drop_table :crises <del> ActiveRecord::Base.connection.drop_table :successes <del> ActiveRecord::Base.connection.drop_table :analyses <del> ActiveRecord::Base.connection.drop_table :dresses <del> ActiveRecord::Base.connection.drop_table :compresses <add> connection.drop_table :viri <add> connection.drop_table :octopi <add> connection.drop_table :passes <add> connection.drop_table :buses <add> connection.drop_table :crises_messes <add> connection.drop_table :messes <add> connection.drop_table :crises <add> connection.drop_table :successes <add> connection.drop_table :analyses <add> connection.drop_table :dresses <add> connection.drop_table :compresses <add> end <add> <add> def connection <add> ActiveRecord::Base.connection <ide> end <ide> <ide> def test_eager_no_extra_singularization_belongs_to
1
Ruby
Ruby
add [email protected] handling
c92a3d3f84ff9dc1a2c566e9d5fd5a21cf2e3bee
<ide><path>Library/Homebrew/language/python.rb <ide> def needs_python?(python) <ide> def virtualenv_install_with_resources(options = {}) <ide> python = options[:using] <ide> if python.nil? <del> wanted = %w[python python@2 python2 python3 python@3 pypy pypy3].select { |py| needs_python?(py) } <add> pythons = %w[python python@2 python2 python3 python@3 [email protected] pypy pypy3] <add> wanted = pythons.select { |py| needs_python?(py) } <ide> raise FormulaAmbiguousPythonError, self if wanted.size > 1 <ide> <ide> python = wanted.first || "python2.7"
1
PHP
PHP
fix a styling issue
c97a8572eca62441705d7d39af3ecae000c35386
<ide><path>src/Illuminate/Database/Schema/Builder.php <ide> namespace Illuminate\Database\Schema; <ide> <ide> use Closure; <del>use Doctrine\DBAL\Types\Type; <ide> use LogicException; <add>use Doctrine\DBAL\Types\Type; <ide> use Illuminate\Database\Connection; <ide> <ide> class Builder <ide> public function registerCustomDBALType($class, $name, $type) <ide> <ide> if (! Type::hasType($name)) { <ide> Type::addType($name, $class); <del> <add> <ide> $this->connection <ide> ->getDoctrineSchemaManager() <ide> ->getDatabasePlatform() <ide><path>src/Illuminate/Database/Schema/Types/TinyInteger.php <ide> <ide> namespace Illuminate\Database\Schema\Types; <ide> <del>use Doctrine\DBAL\Platforms\AbstractPlatform; <ide> use Doctrine\DBAL\Types\Type; <add>use Doctrine\DBAL\Platforms\AbstractPlatform; <ide> <ide> class TinyInteger extends Type <ide> { <ide><path>tests/Integration/Database/SchemaBuilderTest.php <ide> namespace Illuminate\Tests\Integration\Database\SchemaTest; <ide> <ide> use Doctrine\DBAL\Types\Type; <del>use Illuminate\Database\Schema\Types\TinyInteger; <ide> use Illuminate\Support\Facades\DB; <ide> use Illuminate\Support\Facades\Schema; <ide> use Illuminate\Database\Schema\Blueprint; <add>use Illuminate\Database\Schema\Types\TinyInteger; <ide> use Illuminate\Tests\Integration\Database\DatabaseTestCase; <ide> <ide> /**
3
Javascript
Javascript
upgrade requirecontextplugin to es6
a06903302296c3b2fe5f00a2b5e86c33dc766e49
<ide><path>lib/dependencies/RequireContextPlugin.js <ide> class RequireContextPlugin { <ide> } <ide> } <ide> module.exports = RequireContextPlugin; <del> <ide>\ No newline at end of file
1
PHP
PHP
remove legacy non-breaking code
b8c2b869f36dc730c4eaf563614d9d7f1a69ab9f
<ide><path>src/Illuminate/Support/Collection.php <ide> public function zip($items) <ide> return new static(call_user_func_array('array_map', $params)); <ide> } <ide> <del> /** <del> * Return self to allow compatibility with Illuminate\Database\Eloquent\Collection. <del> * <del> * @return \Illuminate\Support\Collection <del> */ <del> public function toBase() <del> { <del> return $this; <del> } <del> <ide> /** <ide> * Get the collection of items as a plain array. <ide> * <ide><path>tests/Support/SupportCollectionTest.php <ide> public function testSliceNegativeOffsetAndNegativeLength() <ide> $collection = new Collection([1, 2, 3, 4, 5, 6, 7, 8]); <ide> $this->assertEquals([3, 4, 5, 6], $collection->slice(-6, -2)->values()->toArray()); <ide> } <del> <del> public function testToBase() <del> { <del> $collection = new Collection([1, 2, 3]); <del> $this->assertSame($collection, $collection->toBase()); <del> } <ide> } <ide> <ide> class TestAccessorEloquentTestStub
2
Javascript
Javascript
add a handler for an `unhandledrejection`
d2cd05ebdcdc6f0631367d62cadb212bb3d8e840
<ide><path>static/index.js <ide> window.onload = function() { <ide> try { <ide> var startTime = Date.now(); <ide> <add> process.on('unhandledRejection', function(error, promise) { <add> console.error('Unhandled promise rejection %o with error: %o', promise, error); <add> }); <add> <ide> // Ensure ATOM_HOME is always set before anything else is required <ide> setupAtomHome(); <ide>
1
Javascript
Javascript
add status-changed on reload spec
9081a891e6629f79e47986f4bacadf7ca2f8b56a
<ide><path>spec/git-repository-async-spec.js <ide> describe('GitRepositoryAsync', () => { <ide> expect(called).toEqual({path: editor.getPath(), pathStatus: 256}) <ide> }) <ide> }) <add> <add> it('emits a status-changed event when a buffer is reloaded', () => { <add> let editor <add> let statusHandler = jasmine.createSpy('statusHandler') <add> let reloadHandler = jasmine.createSpy('reloadHandler') <add> <add> waitsForPromise(function () { <add> return atom.workspace.open('other.txt').then((o) => { <add> editor = o <add> }) <add> }) <add> <add> runs(() => { <add> fs.writeFileSync(editor.getPath(), 'changed') <add> atom.project.getRepositories()[0].async.onDidChangeStatus(statusHandler) <add> editor.getBuffer().reload() <add> }) <add> <add> waitsFor(() => { <add> return statusHandler.callCount > 0 <add> }) <add> <add> runs(() => { <add> expect(statusHandler.callCount).toBe(1) <add> expect(statusHandler).toHaveBeenCalledWith({path: editor.getPath(), pathStatus: 256}) <add> let buffer = editor.getBuffer() <add> buffer.onDidReload(reloadHandler) <add> buffer.reload() <add> }) <add> <add> waitsFor(() => { return reloadHandler.callCount > 0 }) <add> runs(() => { expect(statusHandler.callCount).toBe(1) }) <add> }) <ide> }) <ide> <ide> })
1
Go
Go
fix typos in create.go
318b4f0b5f0639149f5e88aba805cdd454d4d9ee
<ide><path>daemon/execdriver/native/create.go <ide> func (d *Driver) setupRlimits(container *configs.Config, c *execdriver.Command) <ide> <ide> // If rootfs mount propagation is RPRIVATE, that means all the volumes are <ide> // going to be private anyway. There is no need to apply per volume <del>// propagation on top. This is just an optimzation so that cost of per volume <add>// propagation on top. This is just an optimization so that cost of per volume <ide> // propagation is paid only if user decides to make some volume non-private <ide> // which will force rootfs mount propagation to be non RPRIVATE. <ide> func checkResetVolumePropagation(container *configs.Config) { <ide> func getSourceMount(source string) (string, string, error) { <ide> return "", "", fmt.Errorf("Could not find source mount of %s", source) <ide> } <ide> <del>// Ensure mount point on which path is mouted, is shared. <add>// Ensure mount point on which path is mounted, is shared. <ide> func ensureShared(path string) error { <ide> sharedMount := false <ide> <ide> func (d *Driver) setupMounts(container *configs.Config, c *execdriver.Command) e <ide> } <ide> <ide> // Determine property of RootPropagation based on volume <del> // properties. If a volume is shared, then keep root propagtion <add> // properties. If a volume is shared, then keep root propagation <ide> // shared. This should work for slave and private volumes too. <ide> // <ide> // For slave volumes, it can be either [r]shared/[r]slave.
1
Javascript
Javascript
remove trailing whitespace
49d6d2169d981eb56b7cd8574eda59511e661f3b
<ide><path>src/dom/isEventSupported.js <ide> function isEventSupported(eventNameSuffix, capture) { <ide> capture && !('addEventListener' in document)) { <ide> return false; <ide> } <del> <add> <ide> var eventName = 'on' + eventNameSuffix; <ide> var isSupported = eventName in document; <ide> <ide><path>src/event/synthetic/SyntheticWheelEvent.js <ide> var WheelEventInterface = { <ide> ); <ide> }, <ide> deltaZ: null, <del> <add> <ide> // Browsers without "deltaMode" is reporting in raw wheel delta where one <ide> // notch on the scroll is always +/- 120, roughly equivalent to pixels. <ide> // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
2
Java
Java
fix a bug with comment box positioning
e674185ea1f4d5dece37284a774bf882772c601d
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatUIImplementation.java <ide> private void measureHelper(int reactTag, boolean relativeToWindow, Callback call <ide> callback); <ide> } <ide> <del> private void ensureMountsToViewAndBackingViewIsCreated(int reactTag) { <add> private boolean ensureMountsToViewAndBackingViewIsCreated(int reactTag) { <ide> FlatShadowNode node = (FlatShadowNode) resolveShadowNode(reactTag); <add> if (node.isBackingViewCreated()) { <add> return false; <add> } <ide> node.forceMountToView(); <ide> mStateBuilder.ensureBackingViewIsCreated(node); <add> return true; <ide> } <ide> <ide> @Override <ide> public void addAnimation(int reactTag, int animationID, Callback onSuccess) { <ide> <ide> @Override <ide> public void dispatchViewManagerCommand(int reactTag, int commandId, ReadableArray commandArgs) { <del> ensureMountsToViewAndBackingViewIsCreated(reactTag); <del> mStateBuilder.applyUpdates((FlatShadowNode) resolveShadowNode(reactTag)); <add> if (ensureMountsToViewAndBackingViewIsCreated(reactTag)) { <add> // need to make sure any ui operations (UpdateViewGroup, for example, etc) have already <add> // happened before we actually dispatch the view manager command (since otherwise, the command <add> // may go to an empty shell parent without its children, which is against the specs). note <add> // that we only want to applyUpdates if the view has not yet been created so that it does <add> // get created (otherwise, we may end up changing the View's position when we're not supposed <add> // to, for example). <add> mStateBuilder.applyUpdates((FlatShadowNode) resolveShadowNode(reactTag)); <add> } <ide> super.dispatchViewManagerCommand(reactTag, commandId, commandArgs); <ide> } <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatViewGroup.java <ide> public boolean interceptsTouchEvent(float touchX, float touchY) { <ide> <ide> @Override <ide> public void dispatchDraw(Canvas canvas) { <del> super.dispatchDraw(canvas); <del> <ide> if (mRemoveClippedSubviews) { <ide> for (DrawCommand drawCommand : mDrawCommands) { <ide> if (drawCommand instanceof DrawView) {
2
Javascript
Javascript
remove sync from render to buffer
434cb04c5612bf8b1fa1fda075e6a25acab1f130
<ide><path>packages/ember-views/lib/views/view.js <ide> Ember.CoreView = Ember.Object.extend(Ember.Evented, { <ide> }, <ide> <ide> _renderToBuffer: function(parentBuffer, bufferOperation) { <del> Ember.run.sync(); <del> <ide> // If this is the top-most view, start a new buffer. Otherwise, <ide> // create a new buffer relative to the original using the <ide> // provided buffer operation (for example, `insertAfter` will
1
Python
Python
add test for jsonify padded=false, #495
d90f0afe39724040d0be92df054e2b1438886134
<ide><path>flask/testsuite/helpers.py <ide> def return_kwargs(): <ide> @app.route('/dict') <ide> def return_dict(): <ide> return flask.jsonify(d) <add> @app.route("/unpadded") <add> def return_padded_false(): <add> return flask.jsonify(d, padded=False) <ide> @app.route("/padded") <del> def return_padded_json(): <add> def return_padded_true(): <ide> return flask.jsonify(d, padded=True) <ide> @app.route("/padded_custom") <ide> def return_padded_json_custom_callback(): <ide> return flask.jsonify(d, padded='my_func_name') <ide> c = app.test_client() <del> for url in '/kw', '/dict': <add> for url in '/kw', '/dict', '/unpadded': <ide> rv = c.get(url) <ide> self.assert_equal(rv.mimetype, 'application/json') <ide> self.assert_equal(flask.json.loads(rv.data), d)
1
Python
Python
remove uses of the warningmanager class
05a15c8b621f953607429f3b67e079dfe1b439d6
<ide><path>numpy/core/tests/test_api.py <ide> from __future__ import division, absolute_import, print_function <ide> <ide> import sys <add>import warnings <ide> <ide> import numpy as np <ide> from numpy.testing import * <del>from numpy.testing.utils import WarningManager <del>import warnings <ide> from numpy.compat import sixu <ide> <ide> # Switch between new behaviour when NPY_RELAXED_STRIDES_CHECKING is set. <ide><path>numpy/core/tests/test_einsum.py <ide> from __future__ import division, absolute_import, print_function <ide> <ide> import sys <add>import warnings <ide> from decimal import Decimal <ide> <ide> import numpy as np <ide> from numpy.testing import * <del>from numpy.testing.utils import WarningManager <del>import warnings <ide> <ide> class TestEinSum(TestCase): <ide> def test_einsum_errors(self): <ide> def check_einsum_sums(self, dtype): <ide> assert_equal(np.einsum(a, [0], b, [1]), np.outer(a, b)) <ide> <ide> # Suppress the complex warnings for the 'as f8' tests <del> ctx = WarningManager() <del> ctx.__enter__() <del> try: <add> with warnings.catch_warnings(): <ide> warnings.simplefilter('ignore', np.ComplexWarning) <ide> <ide> # matvec(a,b) / a.dot(b) where a is matrix, b is vector <ide> def check_einsum_sums(self, dtype): <ide> dtype='f8', casting='unsafe') <ide> assert_equal(c, np.tensordot(a.astype('f8'), b.astype('f8'), <ide> axes=([1,0],[0,1])).astype(dtype)) <del> finally: <del> ctx.__exit__() <ide> <ide> # logical_and(logical_and(a!=0, b!=0), c!=0) <ide> a = np.array([1, 3, -2, 0, 12, 13, 0, 1], dtype=dtype) <ide><path>numpy/core/tests/test_multiarray.py <ide> import numpy as np <ide> from nose import SkipTest <ide> from numpy.core import * <del>from numpy.testing.utils import WarningManager <ide> from numpy.compat import asbytes, getexception, strchar, sixu <ide> from test_print import in_foreign_locale <ide> from numpy.core.multiarray_tests import ( <ide> def test_diagonal(self): <ide> assert_equal(b.diagonal(0, 2, 1), [[0, 3], [4, 7]]) <ide> <ide> def test_diagonal_deprecation(self): <del> import warnings <del> from numpy.testing.utils import WarningManager <add> <ide> def collect_warning_types(f, *args, **kwargs): <del> ctx = WarningManager(record=True) <del> warning_log = ctx.__enter__() <del> warnings.simplefilter("always") <del> try: <add> with warnings.catch_warnings(record=True) as log: <add> warnings.simplefilter("always") <ide> f(*args, **kwargs) <del> finally: <del> ctx.__exit__() <del> return [w.category for w in warning_log] <add> return [w.category for w in log] <add> <ide> a = np.arange(9).reshape(3, 3) <ide> # All the different functions raise a warning, but not an error, and <ide> # 'a' is not modified: <ide> def test_field_names(self): <ide> assert_raises(ValueError, a.__getitem__, sixu('\u03e0')) <ide> <ide> def test_field_names_deprecation(self): <del> import warnings <del> from numpy.testing.utils import WarningManager <add> <ide> def collect_warning_types(f, *args, **kwargs): <del> ctx = WarningManager(record=True) <del> warning_log = ctx.__enter__() <del> warnings.simplefilter("always") <del> try: <add> with warnings.catch_warnings(record=True) as log: <add> warnings.simplefilter("always") <ide> f(*args, **kwargs) <del> finally: <del> ctx.__exit__() <del> return [w.category for w in warning_log] <add> return [w.category for w in log] <add> <ide> a = np.zeros((1,), dtype=[('f1', 'i4'), <ide> ('f2', 'i4'), <ide> ('f3', [('sf1', 'i4')])]) <ide> def test_simple_strict_within(self): <ide> assert_array_equal(l, r) <ide> <ide> class TestWarnings(object): <add> <ide> def test_complex_warning(self): <ide> x = np.array([1,2]) <ide> y = np.array([1-2j,1+2j]) <ide> <del> warn_ctx = WarningManager() <del> warn_ctx.__enter__() <del> try: <add> with warnings.catch_warnings(): <ide> warnings.simplefilter("error", np.ComplexWarning) <ide> assert_raises(np.ComplexWarning, x.__setitem__, slice(None), y) <ide> assert_equal(x, [1,2]) <del> finally: <del> warn_ctx.__exit__() <ide> <ide> class TestMinScalarType(object): <add> <ide> def test_usigned_shortshort(self): <ide> dt = np.min_scalar_type(2**8-1) <ide> wanted = np.dtype('uint8') <ide> assert_equal(wanted, dt) <add> <ide> def test_usigned_short(self): <ide> dt = np.min_scalar_type(2**16-1) <ide> wanted = np.dtype('uint16') <ide> assert_equal(wanted, dt) <add> <ide> def test_usigned_int(self): <ide> dt = np.min_scalar_type(2**32-1) <ide> wanted = np.dtype('uint32') <ide> assert_equal(wanted, dt) <add> <ide> def test_usigned_longlong(self): <ide> dt = np.min_scalar_type(2**63-1) <ide> wanted = np.dtype('uint64') <ide> assert_equal(wanted, dt) <add> <ide> def test_object(self): <ide> dt = np.min_scalar_type(2**64) <ide> wanted = np.dtype('O') <ide><path>numpy/core/tests/test_regression.py <ide> assert_almost_equal, assert_array_equal, assert_array_almost_equal, <ide> assert_raises, assert_warns, dec <ide> ) <del>from numpy.testing.utils import _assert_valid_refcount, WarningManager <add>from numpy.testing.utils import _assert_valid_refcount <ide> from numpy.compat import asbytes, asunicode, asbytes_nested, long, sixu <ide> <ide> rlevel = 1 <ide> def test_complex_scalar_warning(self): <ide> for tp in [np.csingle, np.cdouble, np.clongdouble]: <ide> x = tp(1+2j) <ide> assert_warns(np.ComplexWarning, float, x) <del> warn_ctx = WarningManager() <del> warn_ctx.__enter__() <del> try: <add> with warnings.catch_warnings(): <ide> warnings.simplefilter('ignore') <ide> assert_equal(float(x), float(x.real)) <del> finally: <del> warn_ctx.__exit__() <ide> <ide> def test_complex_scalar_complex_cast(self): <ide> for tp in [np.csingle, np.cdouble, np.clongdouble]: <ide><path>numpy/lib/tests/test_io.py <ide> import gc <ide> from io import BytesIO <ide> from datetime import datetime <del>from numpy.testing.utils import WarningManager <ide> <ide> import numpy as np <ide> import numpy.ma as ma <ide> def test_3d_shaped_dtype(self): <ide> dt = np.dtype([('name', 'S4'), ('x', float), ('y', float), <ide> ('block', int, (2, 2, 3))]) <ide> x = np.loadtxt(c, dtype=dt) <del> a = np.array([('aaaa', 1.0, 8.0, [[[1, 2, 3], [4, 5, 6]],[[7, 8, 9], [10, 11, 12]]])], <del> dtype=dt) <add> a = np.array([('aaaa', 1.0, 8.0, <add> [[[1, 2, 3], [4, 5, 6]],[[7, 8, 9], [10, 11, 12]]])], <add> dtype=dt) <ide> assert_array_equal(x, a) <ide> <ide> def test_empty_file(self): <del> warn_ctx = WarningManager() <del> warn_ctx.__enter__() <del> try: <add> with warnings.catch_warnings(): <ide> warnings.filterwarnings("ignore", <ide> message="loadtxt: Empty input file:") <ide> c = TextIO() <ide> def test_empty_file(self): <ide> x = np.loadtxt(c, dtype=np.int64) <ide> assert_equal(x.shape, (0,)) <ide> assert_(x.dtype == np.int64) <del> finally: <del> warn_ctx.__exit__() <ide> <ide> <ide> def test_unused_converter(self): <ide> def test_ndmin_keyword(self): <ide> assert_(x.shape == (3,)) <ide> <ide> # Test ndmin kw with empty file. <del> warn_ctx = WarningManager() <del> warn_ctx.__enter__() <del> try: <add> with warnings.catch_warnings(): <ide> warnings.filterwarnings("ignore", <ide> message="loadtxt: Empty input file:") <ide> f = TextIO() <ide> assert_(np.loadtxt(f, ndmin=2).shape == (0, 1,)) <ide> assert_(np.loadtxt(f, ndmin=1).shape == (0,)) <del> finally: <del> warn_ctx.__exit__() <ide> <ide> def test_generator_source(self): <ide> def count(): <ide> def test_skip_footer(self): <ide> assert_equal(test, ctrl) <ide> <ide> def test_skip_footer_with_invalid(self): <del> warn_ctx = WarningManager() <del> warn_ctx.__enter__() <del> try: <del> basestr = '1 1\n2 2\n3 3\n4 4\n5 \n6 \n7 \n' <add> with warnings.catch_warnings(): <ide> warnings.filterwarnings("ignore") <add> basestr = '1 1\n2 2\n3 3\n4 4\n5 \n6 \n7 \n' <ide> # Footer too small to get rid of all invalid values <ide> assert_raises(ValueError, np.genfromtxt, <ide> TextIO(basestr), skip_footer=1) <ide> def test_skip_footer_with_invalid(self): <ide> assert_equal(a, np.array([[1., 1.], [3., 3.], [4., 4.], [6., 6.]])) <ide> a = np.genfromtxt(TextIO(basestr), skip_footer=3, invalid_raise=False) <ide> assert_equal(a, np.array([[1., 1.], [3., 3.], [4., 4.]])) <del> finally: <del> warn_ctx.__exit__() <del> <ide> <ide> def test_header(self): <ide> "Test retrieving a header" <ide> def test_usecols_with_named_columns(self): <ide> <ide> def test_empty_file(self): <ide> "Test that an empty file raises the proper warning." <del> warn_ctx = WarningManager() <del> warn_ctx.__enter__() <del> try: <del> warnings.filterwarnings("ignore", message="genfromtxt: Empty input file:") <add> with warnings.catch_warnings(): <add> warnings.filterwarnings("ignore", <add> message="genfromtxt: Empty input file:") <ide> data = TextIO() <ide> test = np.genfromtxt(data) <ide> assert_equal(test, np.array([])) <del> finally: <del> warn_ctx.__exit__() <ide> <ide> def test_fancy_dtype_alt(self): <ide> "Check that a nested dtype isn't MIA" <ide><path>numpy/lib/utils.py <ide> def safe_eval(source): <ide> """ <ide> # Local imports to speed up numpy's import time. <ide> import warnings <del> from numpy.testing.utils import WarningManager <del> warn_ctx = WarningManager() <del> warn_ctx.__enter__() <del> try: <add> <add> with warnings.catch_warnings(): <ide> # compiler package is deprecated for 3.x, which is already solved here <ide> warnings.simplefilter('ignore', DeprecationWarning) <ide> try: <ide> import compiler <ide> except ImportError: <ide> import ast as compiler <del> finally: <del> warn_ctx.__exit__() <ide> <ide> walker = SafeEval() <ide> try: <ide><path>numpy/ma/tests/test_core.py <ide> from numpy.ma.testutils import * <ide> from numpy.ma.core import * <ide> from numpy.compat import asbytes, asbytes_nested <del>from numpy.testing.utils import WarningManager <ide> <ide> pi = np.pi <ide> <ide> def test_topython(self): <ide> assert_equal(1.0, float(array([[1]]))) <ide> self.assertRaises(TypeError, float, array([1, 1])) <ide> # <del> warn_ctx = WarningManager() <del> warn_ctx.__enter__() <del> try: <add> with warnings.catch_warnings(): <ide> warnings.simplefilter('ignore', UserWarning) <ide> assert_(np.isnan(float(array([1], mask=[1])))) <del> finally: <del> warn_ctx.__exit__() <ide> # <ide> a = array([1, 2, 3], mask=[1, 0, 0]) <ide> self.assertRaises(TypeError, lambda:float(a)) <ide> def test_varstd_specialcases(self): <ide> self.assertTrue(method(0) is masked) <ide> self.assertTrue(method(-1) is masked) <ide> # Using a masked array as explicit output <del> warn_ctx = WarningManager() <del> warn_ctx.__enter__() <del> try: <add> with warnings.catch_warnings(): <ide> warnings.simplefilter('ignore') <ide> _ = method(out=mout) <del> finally: <del> warn_ctx.__exit__() <ide> self.assertTrue(mout is not masked) <ide> assert_equal(mout.mask, True) <ide> # Using a ndarray as explicit output <del> warn_ctx = WarningManager() <del> warn_ctx.__enter__() <del> try: <add> with warnings.catch_warnings(): <ide> warnings.simplefilter('ignore') <ide> _ = method(out=nout) <del> finally: <del> warn_ctx.__exit__() <ide> self.assertTrue(np.isnan(nout)) <ide> # <ide> x = array(arange(10), mask=True) <ide><path>numpy/ma/tests/test_mrecords.py <ide> from numpy.compat import asbytes, asbytes_nested <ide> from numpy.ma.testutils import * <ide> from numpy.ma import masked, nomask <del>from numpy.testing.utils import WarningManager <ide> from numpy.ma.mrecords import MaskedRecords, mrecarray, fromarrays, \ <ide> fromtextfile, fromrecords, addfield <ide> <ide> def test_set_fields(self): <ide> rdata = data.view(MaskedRecords) <ide> val = ma.array([10,20,30], mask=[1,0,0]) <ide> # <del> warn_ctx = WarningManager() <del> warn_ctx.__enter__() <del> try: <add> with warnings.catch_warnings(): <ide> warnings.simplefilter("ignore") <ide> rdata['num'] = val <ide> assert_equal(rdata.num, val) <ide> assert_equal(rdata.num.mask, [1,0,0]) <del> finally: <del> warn_ctx.__exit__() <ide> <ide> def test_set_fields_mask(self): <ide> "Tests setting the mask of a field." <ide><path>numpy/random/__init__.py <ide> """ <ide> from __future__ import division, absolute_import, print_function <ide> <add>import warnings <add> <ide> # To get sub-modules <ide> from .info import __doc__, __all__ <ide> <del>import warnings <del>from numpy.testing.utils import WarningManager <ide> <del>warn_ctx = WarningManager() <del>warn_ctx.__enter__() <del>try: <add>with warnings.catch_warnings(): <ide> warnings.filterwarnings("ignore", message="numpy.ndarray size changed") <ide> from .mtrand import * <del>finally: <del> warn_ctx.__exit__() <ide> <ide> # Some aliases: <ide> ranf = random = sample = random_sample <ide><path>numpy/testing/decorators.py <ide> """ <ide> from __future__ import division, absolute_import, print_function <ide> <del>import warnings <ide> import sys <del> <del>from numpy.testing.utils import \ <del> WarningManager, WarningMessage <add>import warnings <ide> import collections <ide> <ide> def slow(t): <ide> def deprecate_decorator(f): <ide> <ide> def _deprecated_imp(*args, **kwargs): <ide> # Poor man's replacement for the with statement <del> ctx = WarningManager(record=True) <del> l = ctx.__enter__() <del> warnings.simplefilter('always') <del> try: <add> with warnings.catch_warnings(record=True) as l: <add> warnings.simplefilter('always') <ide> f(*args, **kwargs) <ide> if not len(l) > 0: <ide> raise AssertionError("No warning raised when calling %s" <ide> % f.__name__) <ide> if not l[0].category is DeprecationWarning: <ide> raise AssertionError("First warning for %s is not a " \ <ide> "DeprecationWarning( is %s)" % (f.__name__, l[0])) <del> finally: <del> ctx.__exit__() <ide> <ide> if isinstance(conditional, collections.Callable): <ide> cond = conditional() <ide><path>numpy/testing/nosetester.py <ide> def test(self, label='fast', verbose=1, extra_argv=None, <ide> if raise_warnings in _warn_opts.keys(): <ide> raise_warnings = _warn_opts[raise_warnings] <ide> <del> # Preserve the state of the warning filters <del> warn_ctx = numpy.testing.utils.WarningManager() <del> warn_ctx.__enter__() <del> # Reset the warning filters to the default state, <del> # so that running the tests is more repeatable. <del> warnings.resetwarnings() <del> # If deprecation warnings are not set to 'error' below, <del> # at least set them to 'warn'. <del> warnings.filterwarnings('always', category=DeprecationWarning) <del> # Force the requested warnings to raise <del> for warningtype in raise_warnings: <del> warnings.filterwarnings('error', category=warningtype) <del> # Filter out annoying import messages. <del> warnings.filterwarnings('ignore', message='Not importing directory') <del> warnings.filterwarnings("ignore", message="numpy.dtype size changed") <del> warnings.filterwarnings("ignore", message="numpy.ufunc size changed") <del> warnings.filterwarnings("ignore", category=ModuleDeprecationWarning) <del> <del> try: <add> with warnings.catch_warnings(): <add> # Reset the warning filters to the default state, <add> # so that running the tests is more repeatable. <add> warnings.resetwarnings() <add> # If deprecation warnings are not set to 'error' below, <add> # at least set them to 'warn'. <add> warnings.filterwarnings('always', category=DeprecationWarning) <add> # Force the requested warnings to raise <add> for warningtype in raise_warnings: <add> warnings.filterwarnings('error', category=warningtype) <add> # Filter out annoying import messages. <add> warnings.filterwarnings('ignore', message='Not importing directory') <add> warnings.filterwarnings("ignore", message="numpy.dtype size changed") <add> warnings.filterwarnings("ignore", message="numpy.ufunc size changed") <add> warnings.filterwarnings("ignore", category=ModuleDeprecationWarning) <add> <ide> from .noseclasses import NumpyTestProgram <ide> <del> argv, plugins = self.prepare_test_args(label, <del> verbose, extra_argv, doctests, coverage) <add> argv, plugins = self.prepare_test_args( <add> label, verbose, extra_argv, doctests, coverage) <ide> t = NumpyTestProgram(argv=argv, exit=False, plugins=plugins) <del> finally: <del> warn_ctx.__exit__() <ide> <ide> return t.result <ide> <ide><path>numpy/testing/utils.py <ide> class WarningMessage(object): <ide> """ <ide> Holds the result of a single showwarning() call. <ide> <add> Deprecated in 1.8.0 <add> <ide> Notes <ide> ----- <ide> `WarningMessage` is copied from the Python 2.6 warnings module, <ide> class WarningManager(object): <ide> named 'warnings' and imported under that name. This argument is only useful <ide> when testing the warnings module itself. <ide> <add> Deprecated in 1.8.0 <add> <ide> Notes <ide> ----- <ide> `WarningManager` is a copy of the ``catch_warnings`` context manager <ide> def assert_warns(warning_class, func, *args, **kw): <ide> The value returned by `func`. <ide> <ide> """ <del> <del> # XXX: once we may depend on python >= 2.6, this can be replaced by the <del> # warnings module context manager. <del> ctx = WarningManager(record=True) <del> l = ctx.__enter__() <del> warnings.simplefilter('always') <del> try: <add> with warnings.catch_warnings(record=True) as l: <add> warnings.simplefilter('always') <ide> result = func(*args, **kw) <ide> if not len(l) > 0: <ide> raise AssertionError("No warning raised when calling %s" <ide> % func.__name__) <ide> if not l[0].category is warning_class: <ide> raise AssertionError("First warning for %s is not a " \ <ide> "%s( is %s)" % (func.__name__, warning_class, l[0])) <del> finally: <del> ctx.__exit__() <ide> return result <ide> <ide> def assert_no_warnings(func, *args, **kw): <ide> def assert_no_warnings(func, *args, **kw): <ide> The value returned by `func`. <ide> <ide> """ <del> # XXX: once we may depend on python >= 2.6, this can be replaced by the <del> # warnings module context manager. <del> ctx = WarningManager(record=True) <del> l = ctx.__enter__() <del> warnings.simplefilter('always') <del> try: <add> with warnings.catch_warnings(record=True) as l: <add> warnings.simplefilter('always') <ide> result = func(*args, **kw) <ide> if len(l) > 0: <ide> raise AssertionError("Got warnings when calling %s: %s" <ide> % (func.__name__, l)) <del> finally: <del> ctx.__exit__() <ide> return result <ide> <ide>
12
Java
Java
fix spel comparison operator for comparable types
d178eafc11f6576188df8bbb569d82e9d5569bc2
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/Operator.java <ide> else if (leftNumber instanceof Byte || rightNumber instanceof Byte) { <ide> return true; <ide> } <ide> <del> if (left instanceof Comparable && right instanceof Comparable) { <del> Class<?> ancestor = ClassUtils.determineCommonAncestor(left.getClass(), right.getClass()); <del> if (ancestor != null && Comparable.class.isAssignableFrom(ancestor)) { <del> return (context.getTypeComparator().compare(left, right) == 0); <del> } <add> if (context.getTypeComparator().canCompare(left, right)) { <add> return context.getTypeComparator().compare(left, right) == 0; <ide> } <ide> <ide> return false; <ide><path>spring-expression/src/main/java/org/springframework/expression/spel/support/StandardTypeComparator.java <ide> import org.springframework.expression.spel.SpelEvaluationException; <ide> import org.springframework.expression.spel.SpelMessage; <ide> import org.springframework.lang.Nullable; <add>import org.springframework.util.ClassUtils; <ide> import org.springframework.util.NumberUtils; <ide> <ide> /** <ide> public boolean canCompare(@Nullable Object left, @Nullable Object right) { <ide> if (left instanceof Number && right instanceof Number) { <ide> return true; <ide> } <del> if (left instanceof Comparable) { <del> return true; <add> if (left instanceof Comparable && right instanceof Comparable) { <add> Class<?> ancestor = ClassUtils.determineCommonAncestor(left.getClass(), right.getClass()); <add> return ancestor != null && Comparable.class.isAssignableFrom(ancestor); <ide> } <ide> return false; <ide> } <ide><path>spring-expression/src/test/java/org/springframework/expression/spel/AlternativeComparatorTests.java <add>/* <add> * Copyright 2002-2014 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * 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> <add>package org.springframework.expression.spel; <add> <add>import org.junit.Test; <add>import org.springframework.lang.Nullable; <add>import org.springframework.expression.Expression; <add>import org.springframework.expression.TypeComparator; <add>import org.springframework.expression.EvaluationException; <add>import org.springframework.expression.ExpressionParser; <add>import org.springframework.expression.spel.standard.SpelExpressionParser; <add>import org.springframework.expression.spel.support.StandardEvaluationContext; <add> <add>import static org.junit.Assert.*; <add> <add>/** <add> * Test construction of arrays. <add> * <add> * @author Andy Clement <add> */ <add>public class AlternativeComparatorTests { <add> private ExpressionParser parser = new SpelExpressionParser(); <add> <add> // A silly comparator declaring everything to be equal <add> private TypeComparator customComparator = new TypeComparator() { <add> @Override <add> public boolean canCompare(@Nullable Object firstObject, @Nullable Object secondObject) { <add> return true; <add> } <add> <add> @Override <add> public int compare(@Nullable Object firstObject, @Nullable Object secondObject) throws EvaluationException { <add> return 0; <add> } <add> <add> }; <add> <add> @Test <add> public void customComparatorWorksWithEquality() { <add> final StandardEvaluationContext ctx = new StandardEvaluationContext(); <add> ctx.setTypeComparator(customComparator); <add> <add> Expression expr = parser.parseExpression("'1' == 1"); <add> <add> assertEquals(true, expr.getValue(ctx, Boolean.class)); <add> <add> } <add>} <ide><path>spring-expression/src/test/java/org/springframework/expression/spel/DefaultComparatorUnitTests.java <ide> void testCanCompare() throws EvaluationException { <ide> <ide> assertThat(comparator.canCompare(2,1)).isTrue(); <ide> assertThat(comparator.canCompare("abc","def")).isTrue(); <del> assertThat(comparator.canCompare("abc",3)).isTrue(); <add> assertThat(comparator.canCompare("abc",3)).isFalse(); <ide> assertThat(comparator.canCompare(String.class,3)).isFalse(); <ide> } <ide>
4
Ruby
Ruby
replace open-uri with curl
ccfd01ba389ed638f0c67bbf82e01b3108314449
<ide><path>Library/Homebrew/livecheck/strategy.rb <ide> def self.page_headers(url) <ide> *args, url, <ide> print_stdout: false, print_stderr: false, <ide> debug: false, verbose: false, <del> user_agent: user_agent, retry: false <add> user_agent: user_agent, timeout: 20, <add> retry: false <ide> ) <ide> <ide> while stdout.match?(/\AHTTP.*\r$/) <ide> def self.page_headers(url) <ide> <ide> # Fetches the content at the URL and returns a hash containing the <ide> # content and, if there are any redirections, the final URL. <add> # If `curl` encounters an error, the hash will contain a `:messages` <add> # array with the error message instead. <ide> # <ide> # @param url [String] the URL of the content to check <ide> # @return [Hash] <ide> sig { params(url: String).returns(T::Hash[Symbol, T.untyped]) } <ide> def self.page_content(url) <ide> original_url = url <ide> <del> # Manually handling `URI#open` redirections allows us to detect the <del> # resolved URL while also supporting HTTPS to HTTP redirections (which <del> # are normally forbidden by `OpenURI`). <del> begin <del> content = URI.parse(url).open(redirect: false, &:read) <del> rescue OpenURI::HTTPRedirect => e <del> url = e.uri.to_s <del> retry <add> args = curl_args( <add> "--compressed", <add> # Include HTTP response headers in output, so we can identify the <add> # final URL after any redirections <add> "--include", <add> # Follow redirections to handle mirrors, relocations, etc. <add> "--location", <add> # cURL's default timeout can be up to two minutes, so we need to <add> # set our own timeout settings to avoid a lengthy wait <add> "--connect-timeout", "10", <add> "--max-time", "15" <add> ) <add> <add> stdout, stderr, status = curl_with_workarounds( <add> *args, url, <add> print_stdout: false, print_stderr: false, <add> debug: false, verbose: false, <add> user_agent: :default, timeout: 20, <add> retry: false <add> ) <add> <add> unless status.success? <add> /^(?<error_msg>curl: \(\d+\) .+)/ =~ stderr <add> return { <add> messages: [error_msg.presence || "cURL failed without an error"], <add> } <ide> end <ide> <del> data = { content: content } <del> data[:final_url] = url unless url == original_url <add> # stdout contains the header information followed by the page content. <add> # We use #scrub here to avoid "invalid byte sequence in UTF-8" errors. <add> output = stdout.scrub <add> <add> # Separate the head(s)/body and identify the final URL (after any <add> # redirections) <add> max_iterations = 5 <add> iterations = 0 <add> output = output.lstrip <add> while output.match?(%r{\AHTTP/[\d.]+ \d+}) && output.include?("\r\n\r\n") <add> iterations += 1 <add> raise "Too many redirects (max = #{max_iterations})" if iterations > max_iterations <add> <add> head_text, _, output = output.partition("\r\n\r\n") <add> output = output.lstrip <add> <add> location = head_text[/^Location:\s*(.*)$/i, 1] <add> next if location.blank? <add> <add> location.chomp! <add> # Convert a relative redirect URL to an absolute URL <add> location = URI.join(url, location) unless location.match?(PageMatch::URL_MATCH_REGEX) <add> final_url = location <add> end <add> <add> data = { content: output } <add> data[:final_url] = final_url if final_url.present? && final_url != original_url <ide> data <ide> end <ide> end <ide><path>Library/Homebrew/livecheck/strategy/page_match.rb <ide> # typed: true <ide> # frozen_string_literal: true <ide> <del>require "open-uri" <del> <ide> module Homebrew <ide> module Livecheck <ide> module Strategy
2
PHP
PHP
add more meaty doc blocks
1bd9c74f76c8d6371e10eef14f096165d438499c
<ide><path>src/Console/CommandRunner.php <ide> class CommandRunner <ide> { <ide> /** <add> * The application console commands are being run for. <add> * <ide> * @var \Cake\Http\BaseApplication <ide> */ <ide> protected $app; <ide> <ide> /** <add> * The root command name. Defaults to `cake`. <add> * <ide> * @var string <ide> */ <ide> protected $root;
1
Python
Python
remove creation of np.asarray in to_categorical
1db555a530ce433f39c9d8af0592e6e81468d6eb
<ide><path>keras/utils/np_utils.py <ide> def to_categorical(y, nb_classes=None): <ide> '''Convert class vector (integers from 0 to nb_classes) <ide> to binary class matrix, for use with categorical_crossentropy. <ide> ''' <del> y = np.asarray(y, dtype='int32') <ide> if not nb_classes: <ide> nb_classes = np.max(y)+1 <ide> Y = np.zeros((len(y), nb_classes))
1
Javascript
Javascript
add lithuanian (lt) translation
3ef2ff7db405d9c6fb1a4595c923d84bca5be20e
<ide><path>lang/lt.js <add>// moment.js language configuration <add>// language : Lithuanian (lt) <add>// author : Mindaugas Mozūras : https://github.com/mmozuras <add> <add>var units = { <add> "m" : "minutė_minutės_minutę", <add> "mm": "minutės_minučių_minutes", <add> "h" : "valanda_valandos_valandą", <add> "hh": "valandos_valandų_valandas", <add> "d" : "diena_dienos_dieną", <add> "dd": "dienos_dienų_dienas", <add> "M" : "mėnuo_mėnesio_mėnesį", <add> "MM": "mėnesiai_mėnesių_mėnesius", <add> "y" : "metai_metų_metus", <add> "yy": "metai_metų_metus" <add>}; <add> <add>function translateSeconds(number, withoutSuffix, key, isFuture) { <add> if (withoutSuffix) { <add> return "kelios sekundės"; <add> } else { <add> return isFuture ? "kelių sekundžių" : "kelias sekundes"; <add> } <add>} <add> <add>function translateSingular(number, withoutSuffix, key, isFuture) { <add> return withoutSuffix ? forms(key)[0] : (isFuture ? forms(key)[1] : forms(key)[2]); <add>} <add> <add>function special(number) { <add> return number % 10 === 0 || (number > 10 && number < 20); <add>} <add> <add>function forms(key) { <add> return units[key].split("_"); <add>} <add> <add>function translate(number, withoutSuffix, key, isFuture) { <add> var result = number + " "; <add> if (number === 1) { <add> return result + translateSingular(number, withoutSuffix, key[0], isFuture); <add> } else if (withoutSuffix) { <add> return result + (special(number) ? forms(key)[1] : forms(key)[0]); <add> } else { <add> if (isFuture) { <add> return result + forms(key)[1]; <add> } else { <add> return result + (special(number) ? forms(key)[1] : forms(key)[2]); <add> } <add> } <add>} <add> <add>var weekDays = "pirmadienis_antradienis_trečiadienis_ketvirtadienis_penktadienis_šeštadienis_sekmadienis".split("_"); <add> <add>function relativeWeekDay(moment, format) { <add> var nominative = format.indexOf('dddd LT') === -1, <add> weekDay = weekDays[moment.weekday()]; <add> <add> return nominative ? weekDay : weekDay.substring(0, weekDay.length - 2) + "į"; <add>} <add> <add>require("../moment").lang("lt", { <add> months : "sausio_vasario_kovo_balandžio_gegužės_biržėlio_liepos_rugpjūčio_rugsėjo_spalio_lapkričio_gruodžio".split("_"), <add> monthsShort : "sau_vas_kov_bal_geg_bir_lie_rgp_rgs_spa_lap_grd".split("_"), <add> weekdays : relativeWeekDay, <add> weekdaysShort : "Sek_Pir_Ant_Tre_Ket_Pen_Šeš".split("_"), <add> weekdaysMin : "S_P_A_T_K_Pn_Š".split("_"), <add> longDateFormat : { <add> LT : "HH:mm", <add> L : "YYYY-MM-DD", <add> LL : "YYYY [m.] MMMM D [d.]", <add> LLL : "YYYY [m.] MMMM D [d.], LT [val.]", <add> LLLL : "YYYY [m.] MMMM D [d.], dddd, LT [val.]", <add> l : "YYYY-MM-DD", <add> ll : "YYYY [m.] MMMM D [d.]", <add> lll : "YYYY [m.] MMMM D [d.], LT [val.]", <add> llll : "YYYY [m.] MMMM D [d.], ddd, LT [val.]" <add> }, <add> calendar : { <add> sameDay : "[Šiandien] LT", <add> nextDay : "[Rytoj] LT", <add> nextWeek : "dddd LT", <add> lastDay : "[Vakar] LT", <add> lastWeek : "[Praėjusį] dddd LT", <add> sameElse : "L" <add> }, <add> relativeTime : { <add> future : "po %s", <add> past : "prieš %s", <add> s : translateSeconds, <add> m : translateSingular, <add> mm : translate, <add> h : translateSingular, <add> hh : translate, <add> d : translateSingular, <add> dd : translate, <add> M : translateSingular, <add> MM : translate, <add> y : translateSingular, <add> yy : translate <add> }, <add> ordinal : function (number) { <add> return number + '-oji'; <add> }, <add> week : { <add> dow : 1, // Monday is the first day of the week. <add> doy : 4 // The week that contains Jan 4th is the first week of the year. <add> } <add>}); <ide><path>test/lang/lt.js <add>var moment = require("../../moment"); <add> <add> <add> /************************************************** <add> Lithuanian <add> *************************************************/ <add> <add>exports["lang:lt"] = { <add> setUp : function (cb) { <add> moment.lang('lt'); <add> cb(); <add> }, <add> <add> tearDown : function (cb) { <add> moment.lang('en'); <add> cb(); <add> }, <add> <add> "parse" : function (test) { <add> test.expect(96); <add> <add> var tests = 'sausio sau_vasario vas_kovo kov_balandžio bal_gegužės geg_biržėlio bir_liepos lie_rugpjūčio rgp_rugsėjo rgs_spalio spa_lapkričio lap_gruodžio grd'.split("_"), i; <add> function equalTest(input, mmm, i) { <add> test.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); <add> } <add> for (i = 0; i < 12; i++) { <add> tests[i] = tests[i].split(' '); <add> equalTest(tests[i][0], 'MMM', i); <add> equalTest(tests[i][1], 'MMM', i); <add> equalTest(tests[i][0], 'MMMM', i); <add> equalTest(tests[i][1], 'MMMM', i); <add> equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); <add> equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); <add> equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); <add> equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); <add> } <add> test.done(); <add> }, <add> <add> "format" : function (test) { <add> test.expect(22); <add> <add> var a = [ <add> ['dddd, Do MMMM YYYY, h:mm:ss a', 'sekmadienis, 14-oji vasario 2010, 3:25:50 pm'], <add> ['ddd, hA', 'Sek, 3PM'], <add> ['M Mo MM MMMM MMM', '2 2-oji 02 vasario vas'], <add> ['YYYY YY', '2010 10'], <add> ['D Do DD', '14 14-oji 14'], <add> ['d do dddd ddd dd', '0 0-oji sekmadienis Sek S'], <add> ['DDD DDDo DDDD', '45 45-oji 045'], <add> ['w wo ww', '6 6-oji 06'], <add> ['h hh', '3 03'], <add> ['H HH', '15 15'], <add> ['m mm', '25 25'], <add> ['s ss', '50 50'], <add> ['a A', 'pm PM'], <add> ['DDDo [metų diena]', '45-oji metų diena'], <add> ['L', '2010-02-14'], <add> ['LL', '2010 m. vasario 14 d.'], <add> ['LLL', '2010 m. vasario 14 d., 15:25 val.'], <add> ['LLLL', '2010 m. vasario 14 d., sekmadienis, 15:25 val.'], <add> ['l', '2010-02-14'], <add> ['ll', '2010 m. vasario 14 d.'], <add> ['lll', '2010 m. vasario 14 d., 15:25 val.'], <add> ['llll', '2010 m. vasario 14 d., Sek, 15:25 val.'] <add> ], <add> b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), <add> i; <add> for (i = 0; i < a.length; i++) { <add> test.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); <add> } <add> test.done(); <add> }, <add> <add> "format ordinal" : function (test) { <add> test.expect(31); <add> <add> test.equal(moment([2011, 0, 1]).format('DDDo'), '1-oji', '1-oji'); <add> test.equal(moment([2011, 0, 2]).format('DDDo'), '2-oji', '2-oji'); <add> test.equal(moment([2011, 0, 3]).format('DDDo'), '3-oji', '3-oji'); <add> test.equal(moment([2011, 0, 4]).format('DDDo'), '4-oji', '4-oji'); <add> test.equal(moment([2011, 0, 5]).format('DDDo'), '5-oji', '5-oji'); <add> test.equal(moment([2011, 0, 6]).format('DDDo'), '6-oji', '6-oji'); <add> test.equal(moment([2011, 0, 7]).format('DDDo'), '7-oji', '7-oji'); <add> test.equal(moment([2011, 0, 8]).format('DDDo'), '8-oji', '8-oji'); <add> test.equal(moment([2011, 0, 9]).format('DDDo'), '9-oji', '9-oji'); <add> test.equal(moment([2011, 0, 10]).format('DDDo'), '10-oji', '10-oji'); <add> <add> test.equal(moment([2011, 0, 11]).format('DDDo'), '11-oji', '11-oji'); <add> test.equal(moment([2011, 0, 12]).format('DDDo'), '12-oji', '12-oji'); <add> test.equal(moment([2011, 0, 13]).format('DDDo'), '13-oji', '13-oji'); <add> test.equal(moment([2011, 0, 14]).format('DDDo'), '14-oji', '14-oji'); <add> test.equal(moment([2011, 0, 15]).format('DDDo'), '15-oji', '15-oji'); <add> test.equal(moment([2011, 0, 16]).format('DDDo'), '16-oji', '16-oji'); <add> test.equal(moment([2011, 0, 17]).format('DDDo'), '17-oji', '17-oji'); <add> test.equal(moment([2011, 0, 18]).format('DDDo'), '18-oji', '18-oji'); <add> test.equal(moment([2011, 0, 19]).format('DDDo'), '19-oji', '19-oji'); <add> test.equal(moment([2011, 0, 20]).format('DDDo'), '20-oji', '20-oji'); <add> <add> test.equal(moment([2011, 0, 21]).format('DDDo'), '21-oji', '21-oji'); <add> test.equal(moment([2011, 0, 22]).format('DDDo'), '22-oji', '22-oji'); <add> test.equal(moment([2011, 0, 23]).format('DDDo'), '23-oji', '23-oji'); <add> test.equal(moment([2011, 0, 24]).format('DDDo'), '24-oji', '24-oji'); <add> test.equal(moment([2011, 0, 25]).format('DDDo'), '25-oji', '25-oji'); <add> test.equal(moment([2011, 0, 26]).format('DDDo'), '26-oji', '26-oji'); <add> test.equal(moment([2011, 0, 27]).format('DDDo'), '27-oji', '27-oji'); <add> test.equal(moment([2011, 0, 28]).format('DDDo'), '28-oji', '28-oji'); <add> test.equal(moment([2011, 0, 29]).format('DDDo'), '29-oji', '29-oji'); <add> test.equal(moment([2011, 0, 30]).format('DDDo'), '30-oji', '30-oji'); <add> <add> test.equal(moment([2011, 0, 31]).format('DDDo'), '31-oji', '31-oji'); <add> test.done(); <add> }, <add> <add> "format month" : function (test) { <add> test.expect(12); <add> <add> var expected = 'sausio sau_vasario vas_kovo kov_balandžio bal_gegužės geg_biržėlio bir_liepos lie_rugpjūčio rgp_rugsėjo rgs_spalio spa_lapkričio lap_gruodžio grd'.split("_"), i; <add> for (i = 0; i < expected.length; i++) { <add> test.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); <add> } <add> test.done(); <add> }, <add> <add> "format week" : function (test) { <add> test.expect(7); <add> <add> var expected = 'sekmadienis Sek S_pirmadienis Pir P_antradienis Ant A_trečiadienis Tre T_ketvirtadienis Ket K_penktadienis Pen Pn_šeštadienis Šeš Š'.split("_"), i; <add> for (i = 0; i < expected.length; i++) { <add> test.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); <add> } <add> test.done(); <add> }, <add> <add> "from" : function (test) { <add> test.expect(37); <add> <add> var start = moment([2007, 1, 28]); <add> test.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), "kelios sekundės", "44 seconds = seconds"); <add> test.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), "minutė", "45 seconds = a minute"); <add> test.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), "minutė", "89 seconds = a minute"); <add> test.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), "2 minutės", "90 seconds = 2 minutes"); <add> test.equal(start.from(moment([2007, 1, 28]).add({m: 10}), true), "10 minučių", "10 minutes = 10 minutes"); <add> test.equal(start.from(moment([2007, 1, 28]).add({m: 11}), true), "11 minučių", "11 minutes = 11 minutes"); <add> test.equal(start.from(moment([2007, 1, 28]).add({m: 19}), true), "19 minučių", "19 minutes = 19 minutes"); <add> test.equal(start.from(moment([2007, 1, 28]).add({m: 20}), true), "20 minučių", "20 minutes = 20 minutes"); <add> test.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), "44 minutės", "44 minutes = 44 minutes"); <add> test.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), "valanda", "45 minutes = an hour"); <add> test.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), "valanda", "89 minutes = an hour"); <add> test.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), "2 valandos", "90 minutes = 2 hours"); <add> test.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), "5 valandos", "5 hours = 5 hours"); <add> test.equal(start.from(moment([2007, 1, 28]).add({h: 10}), true), "10 valandų", "10 hours = 10 hours"); <add> test.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), "21 valandos", "21 hours = 21 hours"); <add> test.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), "diena", "22 hours = a day"); <add> test.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), "diena", "35 hours = a day"); <add> test.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), "2 dienos", "36 hours = 2 days"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), "diena", "1 day = a day"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), "5 dienos", "5 days = 5 days"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 10}), true), "10 dienų", "10 days = 10 days"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), "25 dienos", "25 days = 25 days"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), "mėnuo", "26 days = a month"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), "mėnuo", "30 days = a month"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 45}), true), "mėnuo", "45 days = a month"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), "2 mėnesiai", "46 days = 2 months"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), "2 mėnesiai", "75 days = 2 months"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), "3 mėnesiai", "76 days = 3 months"); <add> test.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), "mėnuo", "1 month = a month"); <add> test.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), "5 mėnesiai", "5 months = 5 months"); <add> test.equal(start.from(moment([2007, 1, 28]).add({M: 10}), true), "10 mėnesių", "10 months = 10 months"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 344}), true), "11 mėnesių", "344 days = 11 months"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), "metai", "345 days = a year"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 547}), true), "metai", "547 days = a year"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), "2 metai", "548 days = 2 years"); <add> test.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), "metai", "1 year = a year"); <add> test.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), "5 metai", "5 years = 5 years"); <add> test.done(); <add> }, <add> <add> "suffix" : function (test) { <add> test.expect(2); <add> test.equal(moment(30000).from(0), "po kelių sekundžių", "prefix"); <add> test.equal(moment(0).from(30000), "prieš kelias sekundes", "suffix"); <add> test.done(); <add> }, <add> <add> "now from now" : function (test) { <add> test.expect(1); <add> test.equal(moment().fromNow(), "prieš kelias sekundes", "now from now should display as in the past"); <add> test.done(); <add> }, <add> <add> "fromNow" : function (test) { <add> test.expect(2); <add> test.equal(moment().add({s: 30}).fromNow(), "po kelių sekundžių", "in seconds"); <add> test.equal(moment().add({d: 5}).fromNow(), "po 5 dienų", "in 5 days"); <add> test.done(); <add> }, <add> <add> "calendar day" : function (test) { <add> test.expect(6); <add> <add> var a = moment().hours(2).minutes(0).seconds(0); <add> <add> test.equal(moment(a).calendar(), "Šiandien 02:00", "today at the same time"); <add> test.equal(moment(a).add({ m: 25 }).calendar(), "Šiandien 02:25", "Now plus 25 min"); <add> test.equal(moment(a).add({ h: 1 }).calendar(), "Šiandien 03:00", "Now plus 1 hour"); <add> test.equal(moment(a).add({ d: 1 }).calendar(), "Rytoj 02:00", "tomorrow at the same time"); <add> test.equal(moment(a).subtract({ h: 1 }).calendar(), "Šiandien 01:00", "Now minus 1 hour"); <add> test.equal(moment(a).subtract({ d: 1 }).calendar(), "Vakar 02:00", "yesterday at the same time"); <add> test.done(); <add> }, <add> <add> "calendar next week" : function (test) { <add> test.expect(15); <add> <add> var i, m; <add> for (i = 2; i < 7; i++) { <add> m = moment().add({ d: i }); <add> test.equal(m.calendar(), m.format('dddd LT'), "Today + " + i + " days current time"); <add> m.hours(0).minutes(0).seconds(0).milliseconds(0); <add> test.equal(m.calendar(), m.format('dddd LT'), "Today + " + i + " days beginning of day"); <add> m.hours(23).minutes(59).seconds(59).milliseconds(999); <add> test.equal(m.calendar(), m.format('dddd LT'), "Today + " + i + " days end of day"); <add> } <add> test.done(); <add> }, <add> <add> "calendar last week" : function (test) { <add> test.expect(15); <add> <add> var i, m; <add> for (i = 2; i < 7; i++) { <add> m = moment().subtract({ d: i }); <add> test.equal(m.calendar(), m.format('[Praėjusį] dddd LT'), "Today - " + i + " days current time"); <add> m.hours(0).minutes(0).seconds(0).milliseconds(0); <add> test.equal(m.calendar(), m.format('[Praėjusį] dddd LT'), "Today - " + i + " days beginning of day"); <add> m.hours(23).minutes(59).seconds(59).milliseconds(999); <add> test.equal(m.calendar(), m.format('[Praėjusį] dddd LT'), "Today - " + i + " days end of day"); <add> } <add> test.done(); <add> }, <add> <add> "calendar all else" : function (test) { <add> test.expect(4); <add> var weeksAgo = moment().subtract({ w: 1 }), <add> weeksFromNow = moment().add({ w: 1 }); <add> <add> test.equal(weeksAgo.calendar(), weeksAgo.format('L'), "1 week ago"); <add> test.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), "in 1 week"); <add> <add> weeksAgo = moment().subtract({ w: 2 }); <add> weeksFromNow = moment().add({ w: 2 }); <add> <add> test.equal(weeksAgo.calendar(), weeksAgo.format('L'), "2 weeks ago"); <add> test.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), "in 2 weeks"); <add> test.done(); <add> }, <add> <add> // Monday is the first day of the week. <add> // The week that contains Jan 4th is the first week of the year. <add> <add> "weeks year starting sunday" : function (test) { <add> test.expect(5); <add> <add> test.equal(moment([2012, 0, 1]).week(), 52, "Jan 1 2012 should be week 52"); <add> test.equal(moment([2012, 0, 2]).week(), 1, "Jan 2 2012 should be week 1"); <add> test.equal(moment([2012, 0, 8]).week(), 1, "Jan 8 2012 should be week 1"); <add> test.equal(moment([2012, 0, 9]).week(), 2, "Jan 9 2012 should be week 2"); <add> test.equal(moment([2012, 0, 15]).week(), 2, "Jan 15 2012 should be week 2"); <add> <add> test.done(); <add> }, <add> <add> "weeks year starting monday" : function (test) { <add> test.expect(5); <add> <add> test.equal(moment([2007, 0, 1]).week(), 1, "Jan 1 2007 should be week 1"); <add> test.equal(moment([2007, 0, 7]).week(), 1, "Jan 7 2007 should be week 1"); <add> test.equal(moment([2007, 0, 8]).week(), 2, "Jan 8 2007 should be week 2"); <add> test.equal(moment([2007, 0, 14]).week(), 2, "Jan 14 2007 should be week 2"); <add> test.equal(moment([2007, 0, 15]).week(), 3, "Jan 15 2007 should be week 3"); <add> <add> test.done(); <add> }, <add> <add> "weeks year starting tuesday" : function (test) { <add> test.expect(6); <add> <add> test.equal(moment([2007, 11, 31]).week(), 1, "Dec 31 2007 should be week 1"); <add> test.equal(moment([2008, 0, 1]).week(), 1, "Jan 1 2008 should be week 1"); <add> test.equal(moment([2008, 0, 6]).week(), 1, "Jan 6 2008 should be week 1"); <add> test.equal(moment([2008, 0, 7]).week(), 2, "Jan 7 2008 should be week 2"); <add> test.equal(moment([2008, 0, 13]).week(), 2, "Jan 13 2008 should be week 2"); <add> test.equal(moment([2008, 0, 14]).week(), 3, "Jan 14 2008 should be week 3"); <add> <add> test.done(); <add> }, <add> <add> "weeks year starting wednesday" : function (test) { <add> test.expect(6); <add> <add> test.equal(moment([2002, 11, 30]).week(), 1, "Dec 30 2002 should be week 1"); <add> test.equal(moment([2003, 0, 1]).week(), 1, "Jan 1 2003 should be week 1"); <add> test.equal(moment([2003, 0, 5]).week(), 1, "Jan 5 2003 should be week 1"); <add> test.equal(moment([2003, 0, 6]).week(), 2, "Jan 6 2003 should be week 2"); <add> test.equal(moment([2003, 0, 12]).week(), 2, "Jan 12 2003 should be week 2"); <add> test.equal(moment([2003, 0, 13]).week(), 3, "Jan 13 2003 should be week 3"); <add> <add> test.done(); <add> }, <add> <add> "weeks year starting thursday" : function (test) { <add> test.expect(6); <add> <add> test.equal(moment([2008, 11, 29]).week(), 1, "Dec 29 2008 should be week 1"); <add> test.equal(moment([2009, 0, 1]).week(), 1, "Jan 1 2009 should be week 1"); <add> test.equal(moment([2009, 0, 4]).week(), 1, "Jan 4 2009 should be week 1"); <add> test.equal(moment([2009, 0, 5]).week(), 2, "Jan 5 2009 should be week 2"); <add> test.equal(moment([2009, 0, 11]).week(), 2, "Jan 11 2009 should be week 2"); <add> test.equal(moment([2009, 0, 13]).week(), 3, "Jan 12 2009 should be week 3"); <add> <add> test.done(); <add> }, <add> <add> "weeks year starting friday" : function (test) { <add> test.expect(6); <add> <add> test.equal(moment([2009, 11, 28]).week(), 53, "Dec 28 2009 should be week 53"); <add> test.equal(moment([2010, 0, 1]).week(), 53, "Jan 1 2010 should be week 53"); <add> test.equal(moment([2010, 0, 3]).week(), 53, "Jan 3 2010 should be week 53"); <add> test.equal(moment([2010, 0, 4]).week(), 1, "Jan 4 2010 should be week 1"); <add> test.equal(moment([2010, 0, 10]).week(), 1, "Jan 10 2010 should be week 1"); <add> test.equal(moment([2010, 0, 11]).week(), 2, "Jan 11 2010 should be week 2"); <add> <add> test.done(); <add> }, <add> <add> "weeks year starting saturday" : function (test) { <add> test.expect(6); <add> <add> test.equal(moment([2010, 11, 27]).week(), 52, "Dec 27 2010 should be week 52"); <add> test.equal(moment([2011, 0, 1]).week(), 52, "Jan 1 2011 should be week 52"); <add> test.equal(moment([2011, 0, 2]).week(), 52, "Jan 2 2011 should be week 52"); <add> test.equal(moment([2011, 0, 3]).week(), 1, "Jan 3 2011 should be week 1"); <add> test.equal(moment([2011, 0, 9]).week(), 1, "Jan 9 2011 should be week 1"); <add> test.equal(moment([2011, 0, 10]).week(), 2, "Jan 10 2011 should be week 2"); <add> <add> test.done(); <add> }, <add> <add> "weeks year starting sunday formatted" : function (test) { <add> test.expect(5); <add> <add> test.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52-oji', "Jan 1 2012 should be week 52"); <add> test.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1-oji', "Jan 2 2012 should be week 1"); <add> test.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1-oji', "Jan 8 2012 should be week 1"); <add> test.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2-oji', "Jan 9 2012 should be week 2"); <add> test.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2-oji', "Jan 15 2012 should be week 2"); <add> <add> test.done(); <add> } <add>};
2
PHP
PHP
fix phpstan and phpcs errors
ce5ae5e687911c92aa8c9eb99947d9383307c981
<ide><path>src/Database/Expression/QueryExpression.php <ide> public function type($conjunction = null) <ide> 'QueryExpression::type() is deprecated. ' . <ide> 'Use QueryExpression::setConjunction()/getConjunction() instead.' <ide> ); <add> <ide> return $this->tieWith($conjunction); <ide> } <ide> <ide><path>src/Datasource/ConnectionInterface.php <ide> * @method object getLogger() Get the current logger instance <ide> * @method $this setLogger($logger) Set the current logger. <ide> * @method bool supportsDynamicConstraints() <del> * @method \Cake\Database\Schema\Collection schemaCollection() <add> * @method \Cake\Database\Schema\Collection getSchemaCollection() <ide> * @method \Cake\Database\Query newQuery() <ide> * @method \Cake\Database\StatementInterface prepare($sql) <ide> * @method \Cake\Database\StatementInterface execute($query, $params = [], array $types = [])
2
Javascript
Javascript
use arrow functions instead of functions
afb3e1c93dc889cf99cb9d6dd4030cfc8b269577
<ide><path>gulpfile.js <ide> require('laravel-elixir-vue'); <ide> | <ide> */ <ide> <del>elixir(function(mix) { <add>elixir(mix => { <ide> mix.sass('app.scss') <ide> .webpack('app.js'); <ide> }); <ide><path>resources/assets/js/bootstrap.js <ide> require('vue-resource'); <ide> * included with Laravel will automatically verify the header's value. <ide> */ <ide> <del>Vue.http.interceptors.push(function (request, next) { <add>Vue.http.interceptors.push((request, next) => { <ide> request.headers['X-CSRF-TOKEN'] = Laravel.csrfToken; <ide> <ide> next();
2
Text
Text
provide correct command imformation and url
d8e6241989cdfda4513dd30faef00f1f71afa489
<ide><path>man/src/container/top.md <ide> All displayed information is from host's point of view. <ide> <ide> Run **docker container top** with the ps option of -x: <ide> <del> $ docker top 8601afda2b -x <add> $ docker container top 8601afda2b -x <ide> PID TTY STAT TIME COMMAND <ide> 16623 ? Ss 0:00 sleep 99999 <ide><path>man/src/container/unpause.md <ide> The `docker container unpause` command un-suspends all processes in a container. <ide> On Linux, it does this using the cgroups freezer. <ide> <ide> See the [cgroups freezer documentation] <del>(https://www.kernel.org/doc/Documentation/cgroups/freezer-subsystem.txt) for <add>(https://www.kernel.org/doc/Documentation/cgroup-v1/freezer-subsystem.txt) for <ide> further details.
2
Javascript
Javascript
remove the abstract `baseviewer`-class
6dc4c994b8f848ae2ad128fc0e516cc6e4c1cda1
<ide><path>test/unit/base_viewer_spec.js <ide> <ide> import { PDFPageViewBuffer } from "../../web/base_viewer.js"; <ide> <del>describe("BaseViewer", function () { <add>describe("PDFViewer", function () { <ide> describe("PDFPageViewBuffer", function () { <ide> function createViewsMap(startId, endId) { <ide> const map = new Map(); <ide><path>web/app.js <ide> import { PDFScriptingManager } from "./pdf_scripting_manager.js"; <ide> import { PDFSidebar } from "./pdf_sidebar.js"; <ide> import { PDFSidebarResizer } from "./pdf_sidebar_resizer.js"; <ide> import { PDFThumbnailViewer } from "./pdf_thumbnail_viewer.js"; <del>import { PDFViewer } from "./pdf_viewer.js"; <add>import { PDFViewer } from "./base_viewer.js"; <ide> import { SecondaryToolbar } from "./secondary_toolbar.js"; <ide> import { Toolbar } from "./toolbar.js"; <ide> import { ViewHistory } from "./view_history.js"; <ide><path>web/base_viewer.js <ide> class PDFPageViewBuffer { <ide> * @implements {IPDFTextLayerFactory} <ide> * @implements {IPDFXfaLayerFactory} <ide> */ <del>class BaseViewer { <add>class PDFViewer { <ide> #buffer = null; <ide> <ide> #annotationEditorMode = AnnotationEditorType.DISABLE; <ide> class BaseViewer { <ide> * @param {PDFViewerOptions} options <ide> */ <ide> constructor(options) { <del> if (this.constructor === BaseViewer) { <del> throw new Error("Cannot initialize BaseViewer."); <del> } <ide> const viewerVersion = <ide> typeof PDFJSDev !== "undefined" ? PDFJSDev.eval("BUNDLE_VERSION") : null; <ide> if (version !== viewerVersion) { <ide> class BaseViewer { <ide> ) { <ide> if (this.pageColors.background || this.pageColors.foreground) { <ide> console.warn( <del> "BaseViewer: Ignoring `pageColors`-option, since the browser doesn't support the values used." <add> "PDFViewer: Ignoring `pageColors`-option, since the browser doesn't support the values used." <ide> ); <ide> } <ide> this.pageColors = null; <ide> class BaseViewer { <ide> } <ide> } <ide> <del>export { BaseViewer, PagesCountLimit, PDFPageViewBuffer }; <add>export { PagesCountLimit, PDFPageViewBuffer, PDFViewer }; <add><path>web/pdf_single_page_viewer.js <del><path>web/pdf_viewer.js <ide> */ <ide> <ide> import { ScrollMode, SpreadMode } from "./ui_utils.js"; <del>import { BaseViewer } from "./base_viewer.js"; <add>import { PDFViewer } from "./base_viewer.js"; <ide> <del>class PDFViewer extends BaseViewer {} <del> <del>class PDFSinglePageViewer extends BaseViewer { <add>class PDFSinglePageViewer extends PDFViewer { <ide> _resetView() { <ide> super._resetView(); <ide> this._scrollMode = ScrollMode.PAGE; <ide> class PDFSinglePageViewer extends BaseViewer { <ide> _updateSpreadMode() {} <ide> } <ide> <del>export { PDFSinglePageViewer, PDFViewer }; <add>export { PDFSinglePageViewer }; <ide><path>web/pdf_viewer.component.js <ide> import { <ide> ScrollMode, <ide> SpreadMode, <ide> } from "./ui_utils.js"; <del>import { PDFSinglePageViewer, PDFViewer } from "./pdf_viewer.js"; <ide> import { AnnotationLayerBuilder } from "./annotation_layer_builder.js"; <ide> import { DownloadManager } from "./download_manager.js"; <ide> import { EventBus } from "./event_utils.js"; <ide> import { PDFFindController } from "./pdf_find_controller.js"; <ide> import { PDFHistory } from "./pdf_history.js"; <ide> import { PDFPageView } from "./pdf_page_view.js"; <ide> import { PDFScriptingManager } from "./pdf_scripting_manager.js"; <add>import { PDFSinglePageViewer } from "./pdf_single_page_viewer.js"; <add>import { PDFViewer } from "./base_viewer.js"; <ide> import { StructTreeLayerBuilder } from "./struct_tree_layer_builder.js"; <ide> import { TextLayerBuilder } from "./text_layer_builder.js"; <ide> import { XfaLayerBuilder } from "./xfa_layer_builder.js";
5
Text
Text
update the title
17e1ea20f6da4b85af25cc12a45f44787d346a2f
<ide><path>guide/spanish/bootstrap/index.md <ide> --- <ide> title: Bootstrap <del>localeTitle: Oreja <add>localeTitle: Bootstrap <ide> --- <del>## Oreja <add>## Bootstrap <ide> <ide> Bootstrap es un framework de front-end popular para el desarrollo web. Contiene componentes pre-construidos y elementos de diseño para estilizar el contenido HTML. Los navegadores modernos como Chrome, Firefox, Opera, Safari e Internet Explorer son compatibles con Bootstrap. <ide>
1
Javascript
Javascript
update error messages
a86d25d584d085aef7d70bec2779accd12fd7db9
<ide><path>src/isomorphic/classic/types/ReactPropTypes.js <ide> function createArrayOfTypeChecker(typeChecker) { <ide> function validate(props, propName, componentName, location, propFullName) { <ide> if (typeof typeChecker !== 'function') { <ide> return new Error( <del> `Invalid argument \`${propFullName}\` supplied to \`${componentName}\`, expected valid PropType.` <add> `Property \`${propFullName}\` of component \`${componentName}\` has invalid PropType notation inside arrayOf.` <ide> ); <ide> } <ide> var propValue = props[propName]; <ide> function createObjectOfTypeChecker(typeChecker) { <ide> function validate(props, propName, componentName, location, propFullName) { <ide> if (typeof typeChecker !== 'function') { <ide> return new Error( <del> `Invalid argument \`${propFullName}\` supplied to \`${componentName}\`, expected valid PropType.` <add> `Property \`${propFullName}\` of component \`${componentName}\` has invalid PropType notation inside objectOf.` <ide> ); <ide> } <ide> var propValue = props[propName]; <ide><path>src/isomorphic/classic/types/__tests__/ReactPropTypes-test.js <ide> describe('ReactPropTypes', function() { <ide> typeCheckFail( <ide> PropTypes.arrayOf({ foo: PropTypes.string }), <ide> { foo: 'bar' }, <del> 'Invalid argument `testProp` supplied to `testComponent`, expected valid PropType.' <add> 'Property `testProp` of component `testComponent` has invalid PropType notation inside arrayOf.' <ide> ); <ide> }); <ide> <ide> describe('ReactPropTypes', function() { <ide> typeCheckFail( <ide> PropTypes.objectOf({ foo: PropTypes.string }), <ide> { foo: 'bar' }, <del> 'Invalid argument `testProp` supplied to `testComponent`, expected valid PropType.' <add> 'Property `testProp` of component `testComponent` has invalid PropType notation inside objectOf.' <ide> ); <ide> }); <ide>
2
PHP
PHP
simplify method
fbf68a431f65ccbdb1b16c9eec6e878e7e6d645c
<ide><path>src/Illuminate/Auth/Access/Gate.php <ide> public function denies($ability, $arguments = []) <ide> public function check($ability, $arguments = []) <ide> { <ide> try { <del> $result = $this->raw($ability, $arguments); <add> return (bool) $this->raw($ability, $arguments); <ide> } catch (AuthorizationException $e) { <ide> return false; <ide> } <del> <del> return (bool) $result; <ide> } <ide> <ide> /**
1
Javascript
Javascript
remove unused property
2cb3f3fed24ba32e906a54568ecd7f9bedafadf5
<ide><path>packages/ember-runtime/lib/system/core_object.js <ide> CoreObject.PrototypeMixin = Mixin.create({ <ide> return this; <ide> }, <ide> <del> isInstance: true, <del> <ide> /** <ide> An overridable method called when objects are instantiated. By default, <ide> does nothing unless it is overridden during class definition. <ide><path>packages/ember-runtime/tests/system/object/extend_test.js <ide> test('Basic extend', function() { <ide> ok(SomeClass.isClass, "A class has isClass of true"); <ide> var obj = new SomeClass(); <ide> equal(obj.foo, 'BAR'); <del> ok(obj.isInstance, "An instance of a class has isInstance of true"); <ide> }); <ide> <ide> test('Sub-subclass', function() {
2
Javascript
Javascript
convert reactdomtextarea to not be a wrapper
d2e7e56cc4b05ffc7731bef5b7555fc23339fa55
<ide><path>src/renderers/dom/client/wrappers/ReactDOMInput.js <ide> <ide> 'use strict'; <ide> <del>var AutoFocusUtils = require('AutoFocusUtils'); <ide> var ReactDOMIDOperations = require('ReactDOMIDOperations'); <ide> var LinkedValueUtils = require('LinkedValueUtils'); <ide> var ReactMount = require('ReactMount'); <ide> var ReactDOMInput = { <ide> instancesByReactID[inst._rootNodeID] = inst; <ide> }, <ide> <del> postMountWrapper: function(inst, transaction, props) { <del> if (props.autoFocus) { <del> transaction.getReactMountReady().enqueue( <del> AutoFocusUtils.focusDOMComponent, <del> inst <del> ); <del> } <del> }, <del> <ide> unmountWrapper: function(inst) { <ide> delete instancesByReactID[inst._rootNodeID]; <ide> }, <ide><path>src/renderers/dom/client/wrappers/ReactDOMTextarea.js <ide> <ide> 'use strict'; <ide> <del>var AutoFocusUtils = require('AutoFocusUtils'); <del>var DOMPropertyOperations = require('DOMPropertyOperations'); <ide> var LinkedValueUtils = require('LinkedValueUtils'); <del>var ReactBrowserComponentMixin = require('ReactBrowserComponentMixin'); <del>var ReactClass = require('ReactClass'); <del>var ReactElement = require('ReactElement'); <del>var ReactInstanceMap = require('ReactInstanceMap'); <add>var ReactDOMIDOperations = require('ReactDOMIDOperations'); <ide> var ReactUpdates = require('ReactUpdates'); <ide> <ide> var assign = require('Object.assign'); <del>var findDOMNode = require('findDOMNode'); <ide> var invariant = require('invariant'); <del> <ide> var warning = require('warning'); <ide> <del>var textarea = ReactElement.createFactory('textarea'); <del> <ide> function forceUpdateIfMounted() { <del> if (this.isMounted()) { <del> this.forceUpdate(); <add> if (this._rootNodeID) { <add> // DOM component is still mounted; update <add> ReactDOMTextarea.updateWrapper(this); <ide> } <ide> } <ide> <ide> function forceUpdateIfMounted() { <ide> * The rendered element will be initialized with an empty value, the prop <ide> * `defaultValue` if specified, or the children content (deprecated). <ide> */ <del>var ReactDOMTextarea = ReactClass.createClass({ <del> displayName: 'ReactDOMTextarea', <del> tagName: 'TEXTAREA', <add>var ReactDOMTextarea = { <add> getNativeProps: function(inst, props, context) { <add> invariant( <add> props.dangerouslySetInnerHTML == null, <add> '`dangerouslySetInnerHTML` does not make sense on <textarea>.' <add> ); <ide> <del> mixins: [AutoFocusUtils.Mixin, ReactBrowserComponentMixin], <add> // Always set children to the same thing. In IE9, the selection range will <add> // get reset if `textContent` is mutated. <add> var nativeProps = assign({}, props, { <add> defaultValue: undefined, <add> value: undefined, <add> children: inst._wrapperState.initialValue, <add> onChange: inst._wrapperState.onChange, <add> }); <add> <add> return nativeProps; <add> }, <ide> <del> componentWillMount: function() { <add> mountWrapper: function(inst, props) { <ide> LinkedValueUtils.checkPropTypes( <ide> 'textarea', <del> this.props, <del> ReactInstanceMap.get(this)._currentElement._owner <add> props, <add> inst._currentElement._owner <ide> ); <del> }, <ide> <del> getInitialState: function() { <del> var defaultValue = this.props.defaultValue; <add> var defaultValue = props.defaultValue; <ide> // TODO (yungsters): Remove support for children content in <textarea>. <del> var children = this.props.children; <add> var children = props.children; <ide> if (children != null) { <ide> if (__DEV__) { <ide> warning( <ide> var ReactDOMTextarea = ReactClass.createClass({ <ide> if (defaultValue == null) { <ide> defaultValue = ''; <ide> } <del> var value = LinkedValueUtils.getValue(this.props); <del> return { <add> var value = LinkedValueUtils.getValue(props); <add> <add> inst._wrapperState = { <ide> // We save the initial value so that `ReactDOMComponent` doesn't update <ide> // `textContent` (unnecessary since we update value). <ide> // The initial value can be a boolean or object so that's why it's <ide> // forced to be a string. <ide> initialValue: '' + (value != null ? value : defaultValue), <add> onChange: _handleChange.bind(inst), <ide> }; <ide> }, <ide> <del> render: function() { <del> // Clone `this.props` so we don't mutate the input. <del> var props = assign({}, this.props); <del> <del> invariant( <del> props.dangerouslySetInnerHTML == null, <del> '`dangerouslySetInnerHTML` does not make sense on <textarea>.' <del> ); <del> <del> props.defaultValue = null; <del> props.value = null; <del> props.onChange = this._handleChange; <del> <del> // Always set children to the same thing. In IE9, the selection range will <del> // get reset if `textContent` is mutated. <del> return textarea(props, this.state.initialValue); <del> }, <del> <del> componentDidUpdate: function(prevProps, prevState, prevContext) { <del> var value = LinkedValueUtils.getValue(this.props); <add> updateWrapper: function(inst) { <add> var props = inst._currentElement.props; <add> var value = LinkedValueUtils.getValue(props); <ide> if (value != null) { <del> var rootNode = findDOMNode(this); <ide> // Cast `value` to a string to ensure the value is set correctly. While <ide> // browsers typically do this as necessary, jsdom doesn't. <del> DOMPropertyOperations.setValueForProperty(rootNode, 'value', '' + value); <add> ReactDOMIDOperations.updatePropertyByID( <add> inst._rootNodeID, <add> 'value', <add> '' + value <add> ); <ide> } <ide> }, <add>}; <ide> <del> _handleChange: function(event) { <del> var returnValue = LinkedValueUtils.executeOnChange(this.props, event); <del> ReactUpdates.asap(forceUpdateIfMounted, this); <del> return returnValue; <del> }, <del> <del>}); <add>function _handleChange(event) { <add> var props = this._currentElement.props; <add> var returnValue = LinkedValueUtils.executeOnChange(props, event); <add> ReactUpdates.asap(forceUpdateIfMounted, this); <add> return returnValue; <add>} <ide> <ide> module.exports = ReactDOMTextarea; <ide><path>src/renderers/dom/shared/ReactDOMComponent.js <ide> <ide> 'use strict'; <ide> <add>var AutoFocusUtils = require('AutoFocusUtils'); <ide> var CSSPropertyOperations = require('CSSPropertyOperations'); <ide> var DOMProperty = require('DOMProperty'); <ide> var DOMPropertyOperations = require('DOMPropertyOperations'); <ide> var ReactBrowserEventEmitter = require('ReactBrowserEventEmitter'); <ide> var ReactComponentBrowserEnvironment = <ide> require('ReactComponentBrowserEnvironment'); <ide> var ReactDOMInput = require('ReactDOMInput'); <add>var ReactDOMTextarea = require('ReactDOMTextarea'); <ide> var ReactMount = require('ReactMount'); <ide> var ReactMultiChild = require('ReactMultiChild'); <ide> var ReactPerf = require('ReactPerf'); <ide> ReactDOMComponent.Mixin = { <ide> ReactDOMInput.mountWrapper(this, props); <ide> props = ReactDOMInput.getNativeProps(this, props, context); <ide> break; <add> case 'textarea': <add> ReactDOMTextarea.mountWrapper(this, props); <add> props = ReactDOMTextarea.getNativeProps(this, props, context); <add> break; <ide> } <ide> <ide> assertValidProps(this, props); <ide> ReactDOMComponent.Mixin = { <ide> <ide> switch (this._tag) { <ide> case 'input': <del> ReactDOMInput.postMountWrapper(this, transaction, props); <add> case 'textarea': <add> if (props.autoFocus) { <add> transaction.getReactMountReady().enqueue( <add> AutoFocusUtils.focusDOMComponent, <add> this <add> ); <add> } <ide> break; <ide> } <ide> <ide> ReactDOMComponent.Mixin = { <ide> lastProps = ReactDOMInput.getNativeProps(this, lastProps); <ide> nextProps = ReactDOMInput.getNativeProps(this, nextProps); <ide> break; <add> case 'textarea': <add> ReactDOMTextarea.updateWrapper(this); <add> lastProps = ReactDOMTextarea.getNativeProps(this, lastProps); <add> nextProps = ReactDOMTextarea.getNativeProps(this, nextProps); <add> break; <ide> } <ide> <ide> assertValidProps(this, nextProps); <ide> ReactDOMComponent.Mixin = { <ide> case 'input': <ide> ReactDOMInput.unmountWrapper(this); <ide> break; <add> case 'textarea': <add> ReactDOMTextarea.unmountWrapper(this); <add> break; <ide> case 'html': <ide> case 'head': <ide> case 'body': <ide><path>src/renderers/dom/shared/ReactDefaultInjection.js <ide> var ReactDOMIDOperations = require('ReactDOMIDOperations'); <ide> var ReactDOMIframe = require('ReactDOMIframe'); <ide> var ReactDOMOption = require('ReactDOMOption'); <ide> var ReactDOMSelect = require('ReactDOMSelect'); <del>var ReactDOMTextarea = require('ReactDOMTextarea'); <ide> var ReactDOMTextComponent = require('ReactDOMTextComponent'); <ide> var ReactElement = require('ReactElement'); <ide> var ReactEventListener = require('ReactEventListener'); <ide> function inject() { <ide> 'img': ReactDOMImg, <ide> 'option': ReactDOMOption, <ide> 'select': ReactDOMSelect, <del> 'textarea': ReactDOMTextarea, <ide> }); <ide> <ide> ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig);
4
Javascript
Javascript
remove ember.button from yuidoc output
7fb13eb533bec382278b4a3e665dfe6af6bc386e
<ide><path>packages/ember-handlebars/lib/controls/button.js <ide> require('ember-runtime/mixins/target_action_support'); <ide> <del>/** <add>/* <ide> @module ember <ide> @submodule ember-handlebars <ide> */ <ide> <ide> var get = Ember.get, set = Ember.set; <ide> <del>/** <add>/* <ide> @class Button <ide> @namespace Ember <ide> @extends Ember.View <ide> Ember.Button = Ember.View.extend(Ember.TargetActionSupport, { <ide> <ide> attributeBindings: ['type', 'disabled', 'href', 'tabindex'], <ide> <del> /** <add> /* <ide> @private <ide> <ide> Overrides `TargetActionSupport`'s `targetObject` computed
1
Javascript
Javascript
set date to initial value when reset
64287af8d1f9f89f4493644ddc9c205dddf36c44
<ide><path>fixtures/dom/src/components/fixtures/date-inputs/switch-date-test-case.js <ide> const React = window.React; <ide> <add>const startDate = new Date(); <ide> /** <ide> * This test case was originally provided by @richsoni, <ide> * https://github.com/facebook/react/issues/8116 <ide> */ <ide> class SwitchDateTestCase extends React.Component { <ide> state = { <ide> fullDate: false, <del> date: new Date(), <add> date: startDate, <ide> }; <ide> <ide> render() { <ide> class SwitchDateTestCase extends React.Component { <ide> } <ide> } <ide> <del> onInputChange = event => { <del> this.setState({ <del> date: new Date(Date.parse(event.target.value)), <del> }); <add> onInputChange = ({target: {value}}) => { <add> const date = value ? new Date(Date.parse(value)) : startDate; <add> this.setState({date}); <ide> }; <ide> <ide> updateFullDate = () => {
1
PHP
PHP
add validation to exception handler
3310063b59502585162b4cdcd05b13c31701e93c
<ide><path>app/Exceptions/Handler.php <ide> <ide> use Exception; <ide> use Illuminate\Auth\AuthenticationException; <add>use Illuminate\Validation\ValidationException; <ide> use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; <ide> <ide> class Handler extends ExceptionHandler <ide> public function render($request, Exception $exception) <ide> } <ide> <ide> /** <del> * Convert an authentication exception into an unauthenticated response. <add> * Convert a validation exception into a response. <add> * <add> * @param \Illuminate\Http\Request $request <add> * @param Illuminate\Validation\ValidationException $exception <add> * @return \Illuminate\Http\Response <add> */ <add> protected function invalid($request, ValidationException $exception) <add> { <add> $errors = $exception->validator->errors()->messages(); <add> <add> return $request->expectsJson() <add> ? response()->json(['message' => $exception->getMessage(), 'errors' => $errors]) <add> : redirect()->back()->withInput()->withErrors( <add> $errors, $exception->errorBag <add> ); <add> } <add> <add> /** <add> * Convert an authentication exception into a response. <ide> * <ide> * @param \Illuminate\Http\Request $request <ide> * @param \Illuminate\Auth\AuthenticationException $exception
1
Python
Python
add a decorator to add custom template filter
a9bb965b6dcd931cefdc7dd05fa4c672b5dff69c
<ide><path>flask.py <ide> from __future__ import with_statement <ide> import os <ide> import sys <add>import types <ide> <ide> from jinja2 import Environment, PackageLoader, FileSystemLoader <ide> from werkzeug import Request as RequestBase, Response as ResponseBase, \ <ide> def decorator(f): <ide> return f <ide> return decorator <ide> <add> def template_filter(self, arg=None): <add> """A decorator that is used to register custom template filter. <add> You can specify a name for the filter, otherwise the function <add> name will be used. Example:: <add> <add> @app.template_filter <add> def reverse(s): <add> return s[::-1] <add> <add> :param name: the optional name of the filter, otherwise the <add> function name will be used. <add> """ <add> if type(arg) is types.FunctionType: <add> self.jinja_env.filters[arg.__name__] = arg <add> return arg <add> <add> def decorator(f): <add> self.jinja_env.filters[arg or f.__name__] = f <add> return f <add> return decorator <add> <ide> def before_request(self, f): <ide> """Registers a function to run before each request.""" <ide> self.before_request_funcs.append(f) <ide><path>tests/flask_tests.py <ide> def test_macros(self): <ide> macro = flask.get_template_attribute('_macro.html', 'hello') <ide> assert macro('World') == 'Hello World!' <ide> <add> def test_template_filter_not_called(self): <add> app = flask.Flask(__name__) <add> @app.template_filter <add> def my_reverse(s): <add> return s[::-1] <add> assert 'my_reverse' in app.jinja_env.filters.keys() <add> assert app.jinja_env.filters['my_reverse'] == my_reverse <add> assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba' <add> <add> def test_template_filter_called(self): <add> app = flask.Flask(__name__) <add> @app.template_filter() <add> def my_reverse(s): <add> return s[::-1] <add> assert 'my_reverse' in app.jinja_env.filters.keys() <add> assert app.jinja_env.filters['my_reverse'] == my_reverse <add> assert app.jinja_env.filters['my_reverse']('abcd') == 'dcba' <add> <add> def test_template_filter_with_name(self): <add> app = flask.Flask(__name__) <add> @app.template_filter('strrev') <add> def my_reverse(s): <add> return s[::-1] <add> assert 'strrev' in app.jinja_env.filters.keys() <add> assert app.jinja_env.filters['strrev'] == my_reverse <add> assert app.jinja_env.filters['strrev']('abcd') == 'dcba' <ide> <ide> def suite(): <ide> from minitwit_tests import MiniTwitTestCase
2
Javascript
Javascript
fix jshint error
a7fede4f465277dd0cb6ce1675153f6e4a6472e2
<ide><path>src/scales/scale.category.js <ide> module.exports = function(Chart) { <ide> <ide> if (this.options.ticks.min !== undefined) { <ide> // user specified min value <del> findIndex = helpers.indexOf(this.chart.data.labels, this.options.ticks.min) <add> findIndex = helpers.indexOf(this.chart.data.labels, this.options.ticks.min); <ide> this.startIndex = findIndex !== -1 ? findIndex : this.startIndex; <ide> } <ide>
1
Python
Python
parametrize sort test
42228fcb513c08729f822fa6be70e16a7a68067f
<ide><path>numpy/core/tests/test_multiarray.py <ide> def test_sort(self): <ide> b = np.sort(a) <ide> assert_equal(b, a[::-1], msg) <ide> <del> # all c scalar sorts use the same code with different types <del> # so it suffices to run a quick check with one type. The number <del> # of sorted items must be greater than ~50 to check the actual <del> # algorithm because quick and merge sort fall over to insertion <del> # sort for small arrays. <del> # Test unsigned dtypes and nonnegative numbers <del> for dtype in [np.uint8, np.uint16, np.uint32, np.uint64, np.float16, np.float32, np.float64, np.longdouble]: <del> a = np.arange(101, dtype=dtype) <del> b = a[::-1].copy() <del> for kind in self.sort_kinds: <del> msg = "scalar sort, kind=%s, dtype=%s" % (kind, dtype) <del> c = a.copy() <del> c.sort(kind=kind) <del> assert_equal(c, a, msg) <del> c = b.copy() <del> c.sort(kind=kind) <del> assert_equal(c, a, msg) <del> <del> # Test signed dtypes and negative numbers as well <del> for dtype in [np.int8, np.int16, np.int32, np.int64, np.float16, np.float32, np.float64, np.longdouble]: <del> a = np.arange(-50, 51, dtype=dtype) <del> b = a[::-1].copy() <del> for kind in self.sort_kinds: <del> msg = "scalar sort, kind=%s, dtype=%s" % (kind, dtype) <del> c = a.copy() <del> c.sort(kind=kind) <del> assert_equal(c, a, msg) <del> c = b.copy() <del> c.sort(kind=kind) <del> assert_equal(c, a, msg) <add> # all c scalar sorts use the same code with different types <add> # so it suffices to run a quick check with one type. The number <add> # of sorted items must be greater than ~50 to check the actual <add> # algorithm because quick and merge sort fall over to insertion <add> # sort for small arrays. <add> <add> @pytest.mark.parametrize('dtype', [np.uint8, np.uint16, np.uint32, np.uint64, <add> np.float16, np.float32, np.float64, <add> np.longdouble]) <add> def test_sort_unsigned(self, dtype): <add> a = np.arange(101, dtype=dtype) <add> b = a[::-1].copy() <add> for kind in self.sort_kinds: <add> msg = "scalar sort, kind=%s" % kind <add> c = a.copy() <add> c.sort(kind=kind) <add> assert_equal(c, a, msg) <add> c = b.copy() <add> c.sort(kind=kind) <add> assert_equal(c, a, msg) <ide> <del> # test complex sorts. These use the same code as the scalars <del> # but the compare function differs. <del> ai = a*1j + 1 <del> bi = b*1j + 1 <add> @pytest.mark.parametrize('dtype', <add> [np.int8, np.int16, np.int32, np.int64, np.float16, <add> np.float32, np.float64, np.longdouble]) <add> def test_sort_signed(self, dtype): <add> a = np.arange(-50, 51, dtype=dtype) <add> b = a[::-1].copy() <ide> for kind in self.sort_kinds: <del> msg = "complex sort, real part == 1, kind=%s" % kind <del> c = ai.copy() <add> msg = "scalar sort, kind=%s" % (kind) <add> c = a.copy() <ide> c.sort(kind=kind) <del> assert_equal(c, ai, msg) <del> c = bi.copy() <add> assert_equal(c, a, msg) <add> c = b.copy() <ide> c.sort(kind=kind) <del> assert_equal(c, ai, msg) <del> ai = a + 1j <del> bi = b + 1j <add> assert_equal(c, a, msg) <add> <add> @pytest.mark.parametrize('dtype', [np.float32, np.float64, np.longdouble]) <add> @pytest.mark.parametrize('part', ['real', 'imag']) <add> def test_sort_complex(self, part, dtype): <add> # test complex sorts. These use the same code as the scalars <add> # but the compare function differs. <add> cdtype = { <add> np.single: np.csingle, <add> np.double: np.cdouble, <add> np.longdouble: np.clongdouble, <add> }[dtype] <add> a = np.arange(-50, 51, dtype=dtype) <add> b = a[::-1].copy() <add> ai = (a * (1+1j)).astype(cdtype) <add> bi = (b * (1+1j)).astype(cdtype) <add> setattr(ai, part, 1) <add> setattr(bi, part, 1) <ide> for kind in self.sort_kinds: <del> msg = "complex sort, imag part == 1, kind=%s" % kind <add> msg = "complex sort, %s part == 1, kind=%s" % (part, kind) <ide> c = ai.copy() <ide> c.sort(kind=kind) <ide> assert_equal(c, ai, msg) <ide> c = bi.copy() <ide> c.sort(kind=kind) <ide> assert_equal(c, ai, msg) <ide> <add> def test_sort_complex_byte_swapping(self): <ide> # test sorting of complex arrays requiring byte-swapping, gh-5441 <ide> for endianness in '<>': <ide> for dt in np.typecodes['Complex']: <ide> def test_sort(self): <ide> msg = 'byte-swapped complex sort, dtype={0}'.format(dt) <ide> assert_equal(c, arr, msg) <ide> <del> # test string sorts. <del> s = 'aaaaaaaa' <del> a = np.array([s + chr(i) for i in range(101)]) <add> @pytest.mark.parametrize('dtype', [np.bytes_, np.unicode_]) <add> def test_sort_string(self, dtype): <add> # np.array will perform the encoding to bytes for us in the bytes test <add> a = np.array(['aaaaaaaa' + chr(i) for i in range(101)], dtype=dtype) <ide> b = a[::-1].copy() <ide> for kind in self.sort_kinds: <del> msg = "string sort, kind=%s" % kind <del> c = a.copy() <del> c.sort(kind=kind) <del> assert_equal(c, a, msg) <del> c = b.copy() <del> c.sort(kind=kind) <del> assert_equal(c, a, msg) <del> <del> # test unicode sorts. <del> s = 'aaaaaaaa' <del> a = np.array([s + chr(i) for i in range(101)], dtype=np.unicode_) <del> b = a[::-1].copy() <del> for kind in self.sort_kinds: <del> msg = "unicode sort, kind=%s" % kind <add> msg = "kind=%s" % kind <ide> c = a.copy() <ide> c.sort(kind=kind) <ide> assert_equal(c, a, msg) <ide> c = b.copy() <ide> c.sort(kind=kind) <ide> assert_equal(c, a, msg) <ide> <add> def test_sort_object(self): <ide> # test object array sorts. <ide> a = np.empty((101,), dtype=object) <ide> a[:] = list(range(101)) <ide> b = a[::-1] <ide> for kind in ['q', 'h', 'm']: <del> msg = "object sort, kind=%s" % kind <add> msg = "kind=%s" % kind <ide> c = a.copy() <ide> c.sort(kind=kind) <ide> assert_equal(c, a, msg) <ide> c = b.copy() <ide> c.sort(kind=kind) <ide> assert_equal(c, a, msg) <del> <add> <add> def test_sort_structured(self): <ide> # test record array sorts. <ide> dt = np.dtype([('f', float), ('i', int)]) <ide> a = np.array([(i, i) for i in range(101)], dtype=dt) <ide> b = a[::-1] <ide> for kind in ['q', 'h', 'm']: <del> msg = "object sort, kind=%s" % kind <add> msg = "kind=%s" % kind <ide> c = a.copy() <ide> c.sort(kind=kind) <ide> assert_equal(c, a, msg) <ide> c = b.copy() <ide> c.sort(kind=kind) <ide> assert_equal(c, a, msg) <ide> <del> # test datetime64 sorts. <del> a = np.arange(0, 101, dtype='datetime64[D]') <add> @pytest.mark.parametrize('dtype', ['datetime64[D]', 'timedelta64[D]']) <add> def test_sort_time(self, dtype): <add> # test datetime64 and timedelta64 sorts. <add> a = np.arange(0, 101, dtype=dtype) <ide> b = a[::-1] <ide> for kind in ['q', 'h', 'm']: <del> msg = "datetime64 sort, kind=%s" % kind <del> c = a.copy() <del> c.sort(kind=kind) <del> assert_equal(c, a, msg) <del> c = b.copy() <del> c.sort(kind=kind) <del> assert_equal(c, a, msg) <del> <del> # test timedelta64 sorts. <del> a = np.arange(0, 101, dtype='timedelta64[D]') <del> b = a[::-1] <del> for kind in ['q', 'h', 'm']: <del> msg = "timedelta64 sort, kind=%s" % kind <add> msg = "kind=%s" % kind <ide> c = a.copy() <ide> c.sort(kind=kind) <ide> assert_equal(c, a, msg) <ide> c = b.copy() <ide> c.sort(kind=kind) <ide> assert_equal(c, a, msg) <ide> <add> def test_sort_axis(self): <ide> # check axis handling. This should be the same for all type <ide> # specific sorts, so we only check it for one type and one kind <ide> a = np.array([[3, 2], [1, 0]]) <ide> def test_sort(self): <ide> d.sort() <ide> assert_equal(d, c, "test sort with default axis") <ide> <add> def test_sort_size_0(self): <ide> # check axis handling for multidimensional empty arrays <ide> a = np.array([]) <ide> a.shape = (3, 2, 1, 0) <ide> def test_sort(self): <ide> msg = 'test empty array sort with axis=None' <ide> assert_equal(np.sort(a, axis=None), a.ravel(), msg) <ide> <add> def test_sort_bad_ordering(self): <ide> # test generic class with bogus ordering, <ide> # should not segfault. <ide> class Boom: <ide> def __lt__(self, other): <ide> return True <ide> <del> a = np.array([Boom()]*100, dtype=object) <add> a = np.array([Boom()] * 100, dtype=object) <ide> for kind in self.sort_kinds: <del> msg = "bogus comparison object sort, kind=%s" % kind <add> msg = "kind=%s" % kind <add> c = a.copy() <ide> c.sort(kind=kind) <add> assert_equal(c, a, msg) <ide> <ide> def test_void_sort(self): <ide> # gh-8210 - previously segfaulted
1
Ruby
Ruby
silence a jenkins doctor warning
e330047ff9881eee9cbad8828ed1ef2f16b3050e
<ide><path>Library/Homebrew/diagnostic.rb <ide> def check_access_cellar <ide> def check_homebrew_prefix <ide> return if HOMEBREW_PREFIX.to_s == "/usr/local" <ide> <add> # Allow our Jenkins CI tests to live outside of /usr/local. <add> if ENV["JENKINS_HOME"] && <add> ENV["GIT_URL"].to_s.start_with?("https://github.com/Homebrew/brew") <add> return <add> end <add> <ide> <<-EOS.undent <ide> Your Homebrew's prefix is not /usr/local. <ide> You can install Homebrew anywhere you want but some bottles (binary packages) <ide><path>Library/Homebrew/test/diagnostic_test.rb <ide> def test_check_access_cellar <ide> end <ide> <ide> def test_check_homebrew_prefix <add> ENV.delete("JENKINS_HOME") <ide> # the integration tests are run in a special prefix <ide> assert_match "Your Homebrew's prefix is not /usr/local.", <ide> @checks.check_homebrew_prefix
2
Python
Python
add a blank line to make lint happier
a0049dd4897577950c3804163aa501d1d08cd369
<ide><path>tests/test_fields.py <ide> class TestIPv6AddressField(FieldValues): <ide> outputs = {} <ide> field = serializers.IPAddressField(protocol='IPv6') <ide> <add> <ide> # Number types... <ide> <ide> class TestIntegerField(FieldValues):
1
Text
Text
add option r.md
91cfdcfefccd56a9715685e0f06766dd03803343
<ide><path>guide/english/bash/bash-ls/index.md <ide> Most used options: <ide> * `-l`, List in long format <ide> * `-G`, enable colorized output. <ide> * `-s`, List File Size. <add>* `-R`, displays the contents of the directory, and its subdirectories. <ide> <ide> ### Example: <ide>
1
Go
Go
set bigger grpc limit for getconfigs api
3fbbeb703c1d04e9eb723459960fbfc7f3bbfc40
<ide><path>daemon/cluster/configs.go <ide> import ( <ide> types "github.com/docker/docker/api/types/swarm" <ide> "github.com/docker/docker/daemon/cluster/convert" <ide> swarmapi "github.com/docker/swarmkit/api" <add> "google.golang.org/grpc" <ide> ) <ide> <ide> // GetConfig returns a config from a managed swarm cluster <ide> func (c *Cluster) GetConfigs(options apitypes.ConfigListOptions) ([]types.Config <ide> defer cancel() <ide> <ide> r, err := state.controlClient.ListConfigs(ctx, <del> &swarmapi.ListConfigsRequest{Filters: filters}) <add> &swarmapi.ListConfigsRequest{Filters: filters}, <add> grpc.MaxCallRecvMsgSize(defaultRecvSizeForListResponse)) <ide> if err != nil { <ide> return nil, err <ide> }
1
Text
Text
add os x to instead of only macos
d462f8cfe34019ab8bf1d57d33bf16e64c8fb815
<ide><path>BUILDING.md <ide> platforms in production. <ide> |--------------|--------------|----------------------------------|----------------------|------------------| <ide> | GNU/Linux | Tier 1 | kernel >= 2.6.32, glibc >= 2.12 | x64, arm | | <ide> | GNU/Linux | Tier 1 | kernel >= 3.10, glibc >= 2.17 | arm64 | | <del>| macOS | Tier 1 | >= 10.10 | x64 | | <add>| macOS/OS X | Tier 1 | >= 10.10 | x64 | | <ide> | Windows | Tier 1 | >= Windows 7/2008 R2/2012 R2 | x86, x64 | vs2017 | <ide> | SmartOS | Tier 2 | >= 15 < 16.4 | x86, x64 | see note1 | <ide> | FreeBSD | Tier 2 | >= 10 | x64 | | <ide> | GNU/Linux | Tier 2 | kernel >= 3.13.0, glibc >= 2.19 | ppc64le >=power8 | | <ide> | AIX | Tier 2 | >= 7.1 TL04 | ppc64be >=power7 | | <ide> | GNU/Linux | Tier 2 | kernel >= 3.10, glibc >= 2.17 | s390x | | <del>| macOS | Experimental | >= 10.8 < 10.10 | x64 | no test coverage | <add>| OS X | Experimental | >= 10.8 < 10.10 | x64 | no test coverage | <ide> | GNU/Linux | Experimental | kernel >= 2.6.32, glibc >= 2.12 | x86 | limited CI | <ide> | Linux (musl) | Experimental | musl >= 1.0 | x64 | | <ide> <ide> This version of Node.js does not support FIPS. <ide> It is possible to specify one or more JavaScript text files to be bundled in <ide> the binary as builtin modules when building Node.js. <ide> <del>### Unix / macOS <add>### Unix/macOS <ide> <ide> This command will make `/root/myModule.js` available via <ide> `require('/root/myModule')` and `./myModule2.js` available via
1
PHP
PHP
write the dotenv to stderr rather than stdout
8c7e45305c2f83089b2a47f63d95e051531a1221
<ide><path>src/Illuminate/Foundation/Bootstrap/LoadEnvironmentVariables.php <ide> use Dotenv\Exception\InvalidFileException; <ide> use Symfony\Component\Console\Input\ArgvInput; <ide> use Illuminate\Contracts\Foundation\Application; <add>use Symfony\Component\Console\Output\ConsoleOutput; <ide> <ide> class LoadEnvironmentVariables <ide> { <ide> public function bootstrap(Application $app) <ide> try { <ide> Dotenv::create($app->environmentPath(), $app->environmentFile())->safeLoad(); <ide> } catch (InvalidFileException $e) { <del> echo 'The environment file is invalid: '.$e->getMessage(); <del> die(1); <add> $this->writeErrorAndDie($e); <ide> } <ide> } <ide> <ide> protected function setEnvironmentFilePath($app, $file) <ide> <ide> return false; <ide> } <add> <add> /** <add> * Write the error information to the screen and exit. <add> * <add> * @param \Dotenv\Exception\InvalidFileException $e <add> * @return void <add> */ <add> protected function writeErrorAndDie(InvalidFileException $e) <add> { <add> $output = (new ConsoleOutput())->getErrorOutput(); <add> <add> $output->writeln('The environment file is invalid!'); <add> $output->writeln($e->getMessage()); <add> <add> die(1); <add> } <ide> }
1
Python
Python
fix bug in flaxwav2vec2 slow test
8fd4731072104462aed8e7da119f25b5137c3d8f
<ide><path>tests/wav2vec2/test_modeling_flax_wav2vec2.py <ide> def test_inference_ctc_robust_batched(self): <ide> <ide> input_speech = self._load_datasamples(4) <ide> <del> inputs = processor(input_speech, return_tensors="pt", padding=True, truncation=True) <add> inputs = processor(input_speech, return_tensors="np", padding=True) <ide> <ide> input_values = inputs.input_values <ide> attention_mask = inputs.attention_mask
1
Java
Java
improve autoconnect() javadoc + add its marble
ec40a5e6c8f0ab39c334a9073692d24b30b414a9
<ide><path>src/main/java/io/reactivex/flowables/ConnectableFlowable.java <ide> public Flowable<T> refCount() { <ide> } <ide> <ide> /** <del> * Returns a Flowable that automatically connects to this ConnectableFlowable <add> * Returns a Flowable that automatically connects (at most once) to this ConnectableFlowable <ide> * when the first Subscriber subscribes. <add> * <p> <add> * <img width="640" height="392" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/autoConnect.f.png" alt=""> <add> * <p> <add> * The connection happens after the first subscription and happens at most once <add> * during the lifetime of the returned Flowable. If this ConnectableFlowable <add> * terminates, the connection is never renewed, no matter how Subscribers come <add> * and go. Use {@link #refCount()} to renew a connection or dispose an active <add> * connection when all {@code Subscriber}s have cancelled their {@code Subscription}s. <add> * <p> <add> * This overload does not allow disconnecting the connection established via <add> * {@link #connect(Consumer)}. Use the {@link #autoConnect(int, Consumer)} overload <add> * to gain access to the {@code Disposable} representing the only connection. <ide> * <ide> * @return a Flowable that automatically connects to this ConnectableFlowable <ide> * when the first Subscriber subscribes <add> * @see #refCount() <add> * @see #autoConnect(int, Consumer) <ide> */ <ide> @NonNull <ide> public Flowable<T> autoConnect() { <ide> return autoConnect(1); <ide> } <ide> /** <del> * Returns a Flowable that automatically connects to this ConnectableFlowable <add> * Returns a Flowable that automatically connects (at most once) to this ConnectableFlowable <ide> * when the specified number of Subscribers subscribe to it. <add> * <p> <add> * <img width="640" height="392" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/autoConnect.f.png" alt=""> <add> * <p> <add> * The connection happens after the given number of subscriptions and happens at most once <add> * during the lifetime of the returned Flowable. If this ConnectableFlowable <add> * terminates, the connection is never renewed, no matter how Subscribers come <add> * and go. Use {@link #refCount()} to renew a connection or dispose an active <add> * connection when all {@code Subscriber}s have cancelled their {@code Subscription}s. <add> * <p> <add> * This overload does not allow disconnecting the connection established via <add> * {@link #connect(Consumer)}. Use the {@link #autoConnect(int, Consumer)} overload <add> * to gain access to the {@code Disposable} representing the only connection. <ide> * <ide> * @param numberOfSubscribers the number of subscribers to await before calling connect <ide> * on the ConnectableFlowable. A non-positive value indicates <ide> public Flowable<T> autoConnect(int numberOfSubscribers) { <ide> } <ide> <ide> /** <del> * Returns a Flowable that automatically connects to this ConnectableFlowable <add> * Returns a Flowable that automatically connects (at most once) to this ConnectableFlowable <ide> * when the specified number of Subscribers subscribe to it and calls the <ide> * specified callback with the Subscription associated with the established connection. <add> * <p> <add> * <img width="640" height="392" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/autoConnect.f.png" alt=""> <add> * <p> <add> * The connection happens after the given number of subscriptions and happens at most once <add> * during the lifetime of the returned Flowable. If this ConnectableFlowable <add> * terminates, the connection is never renewed, no matter how Subscribers come <add> * and go. Use {@link #refCount()} to renew a connection or dispose an active <add> * connection when all {@code Subscriber}s have cancelled their {@code Subscription}s. <ide> * <ide> * @param numberOfSubscribers the number of subscribers to await before calling connect <ide> * on the ConnectableFlowable. A non-positive value indicates <ide><path>src/main/java/io/reactivex/observables/ConnectableObservable.java <ide> public Observable<T> refCount() { <ide> } <ide> <ide> /** <del> * Returns an Observable that automatically connects to this ConnectableObservable <add> * Returns an Observable that automatically connects (at most once) to this ConnectableObservable <ide> * when the first Observer subscribes. <add> * <p> <add> * <img width="640" height="348" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/autoConnect.o.png" alt=""> <add> * <p> <add> * The connection happens after the first subscription and happens at most once <add> * during the lifetime of the returned Observable. If this ConnectableObservable <add> * terminates, the connection is never renewed, no matter how Observers come <add> * and go. Use {@link #refCount()} to renew a connection or dispose an active <add> * connection when all {@code Observers}s have disposed their {@code Disposable}s. <add> * <p> <add> * This overload does not allow disconnecting the connection established via <add> * {@link #connect(Consumer)}. Use the {@link #autoConnect(int, Consumer)} overload <add> * to gain access to the {@code Disposable} representing the only connection. <ide> * <ide> * @return an Observable that automatically connects to this ConnectableObservable <ide> * when the first Observer subscribes <ide> public Observable<T> autoConnect() { <ide> } <ide> <ide> /** <del> * Returns an Observable that automatically connects to this ConnectableObservable <add> * Returns an Observable that automatically connects (at most once) to this ConnectableObservable <ide> * when the specified number of Observers subscribe to it. <add> * <p> <add> * <img width="640" height="348" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/autoConnect.o.png" alt=""> <add> * <p> <add> * The connection happens after the given number of subscriptions and happens at most once <add> * during the lifetime of the returned Observable. If this ConnectableObservable <add> * terminates, the connection is never renewed, no matter how Observers come <add> * and go. Use {@link #refCount()} to renew a connection or dispose an active <add> * connection when all {@code Observers}s have disposed their {@code Disposable}s. <add> * <p> <add> * This overload does not allow disconnecting the connection established via <add> * {@link #connect(Consumer)}. Use the {@link #autoConnect(int, Consumer)} overload <add> * to gain access to the {@code Disposable} representing the only connection. <ide> * <ide> * @param numberOfSubscribers the number of subscribers to await before calling connect <ide> * on the ConnectableObservable. A non-positive value indicates <ide> public Observable<T> autoConnect(int numberOfSubscribers) { <ide> } <ide> <ide> /** <del> * Returns an Observable that automatically connects to this ConnectableObservable <add> * Returns an Observable that automatically connects (at most once) to this ConnectableObservable <ide> * when the specified number of Subscribers subscribe to it and calls the <ide> * specified callback with the Subscription associated with the established connection. <add> * <p> <add> * <img width="640" height="348" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/autoConnect.o.png" alt=""> <add> * <p> <add> * The connection happens after the given number of subscriptions and happens at most once <add> * during the lifetime of the returned Observable. If this ConnectableObservable <add> * terminates, the connection is never renewed, no matter how Observers come <add> * and go. Use {@link #refCount()} to renew a connection or dispose an active <add> * connection when all {@code Observers}s have disposed their {@code Disposable}s. <ide> * <ide> * @param numberOfSubscribers the number of subscribers to await before calling connect <ide> * on the ConnectableObservable. A non-positive value indicates
2
Python
Python
remove add_configres function which did nothing..
76a7161aa8bc7755059b250313778602aa473b6f
<ide><path>numpy/core/setupscons.py <ide> def add_generated_files(): <ide> add_numpyconfig_header() <ide> add_array_api() <ide> add_ufunc_api() <del> config.add_configres() <ide> <ide> config.add_sconscript('SConstruct', <ide> post_hook = add_generated_files, <ide><path>numpy/distutils/misc_util.py <ide> def add_sconscript(self, sconscript, subpackage_path=None, <ide> # options in distutils command. <ide> self.add_extension('', sources = []) <ide> <del> def add_configres(self): <del> from numscons import get_scons_configres_dir, get_scons_configres_filename <del> file = os.path.join(get_scons_configres_dir(), self.local_path, <del> get_scons_configres_filename()) <del> <ide> def add_scripts(self,*files): <ide> """Add scripts to configuration. <ide> """ <ide><path>numpy/linalg/setupscons.py <ide> def configuration(parent_package='',top_path=None): <ide> source_files = ['lapack_litemodule.c', <ide> 'zlapack_lite.c', 'dlapack_lite.c', <ide> 'blas_lite.c', 'dlamch.c', <del> 'f2c_lite.c','f2c.h'], <del> post_hook = config.add_configres) <add> 'f2c_lite.c','f2c.h']) <ide> <ide> return config <ide>
3
Javascript
Javascript
add debug message for invalid header value
d93ab5108875e22b25190b486682c3a3526a1926
<ide><path>lib/_http_outgoing.js <ide> function storeHeader(self, state, field, value) { <ide> 'Header name must be a valid HTTP Token ["' + field + '"]'); <ide> } <ide> if (common._checkInvalidHeaderChar(value) === true) { <add> debug('Header "%s" contains invalid characters', field); <ide> throw new TypeError('The header content contains invalid characters'); <ide> } <ide> state.messageHeader += field + ': ' + escapeHeaderValue(value) + CRLF; <ide> OutgoingMessage.prototype.setHeader = function setHeader(name, value) { <ide> if (this._header) <ide> throw new Error('Can\'t set headers after they are sent.'); <ide> if (common._checkInvalidHeaderChar(value) === true) { <add> debug('Header "%s" contains invalid characters', name); <ide> throw new TypeError('The header content contains invalid characters'); <ide> } <ide> if (this._headers === null) <ide> OutgoingMessage.prototype.addTrailers = function addTrailers(headers) { <ide> 'Trailer name must be a valid HTTP Token ["' + field + '"]'); <ide> } <ide> if (common._checkInvalidHeaderChar(value) === true) { <add> debug('Trailer "%s" contains invalid characters', field); <ide> throw new TypeError('The trailer content contains invalid characters'); <ide> } <ide> this._trailer += field + ': ' + escapeHeaderValue(value) + CRLF;
1
Go
Go
fix docker pull on windows
18c7c34d4be593110a1c3df3f00c40eec4603dea
<ide><path>graph/graph.go <ide> func (graph *Graph) storeImage(id, parent string, config []byte, layerData io.Re <ide> return err <ide> } <ide> <del> if img.ParentID.Validate() == nil && parent != img.ParentID.Hex() { <add> if (img.ParentID.Validate() == nil && parent != img.ParentID.Hex()) || (allowBaseParentImage && img.ParentID == "" && parent != "") { <add> // save compatibilityID parent if it doesn't match parentID <add> // on windows always save a parent file pointing to the base layer <ide> if err := ioutil.WriteFile(filepath.Join(root, parentFileName), []byte(parent), 0600); err != nil { <ide> return err <ide> } <ide><path>graph/graph_unix.go <add>// +build !windows <add> <add>package graph <add> <add>// allowBaseParentImage allows images to define a custom parent that is not <add>// transported with push/pull but already included with the installation. <add>// Only used in Windows. <add>const allowBaseParentImage = false <ide><path>graph/graph_windows.go <add>// +build windows <add> <add>package graph <add> <add>// allowBaseParentImage allows images to define a custom parent that is not <add>// transported with push/pull but already included with the installation. <add>// Only used in Windows. <add>const allowBaseParentImage = true <ide><path>graph/pull_v2.go <ide> func fixManifestLayers(m *schema1.Manifest) error { <ide> } <ide> } <ide> <del> if images[len(images)-1].Parent != "" { <add> if images[len(images)-1].Parent != "" && !allowBaseParentImage { <add> // Windows base layer can point to a base layer parent that is not in manifest. <ide> return errors.New("Invalid parent ID in the base layer of the image.") <ide> } <ide> <ide> func (p *v2Puller) getImageInfos(m *schema1.Manifest) ([]contentAddressableDescr <ide> <ide> p.attemptIDReuse(imgs) <ide> <add> // reset the base layer parent for windows <add> if allowBaseParentImage { <add> var base struct{ Parent string } <add> if err := json.Unmarshal(imgs[len(imgs)-1].v1Compatibility, &base); err != nil { <add> return nil, err <add> } <add> if base.Parent != "" { <add> imgs[len(imgs)-1].parent = base.Parent <add> } <add> } <add> <ide> return imgs, nil <ide> } <ide>
4
Javascript
Javascript
fix blob creation in safari 7.0
b96811df25913926cb686b6b0400bc92d58107fa
<ide><path>src/shared/util.js <ide> var StatTimer = (function StatTimerClosure() { <ide> })(); <ide> <ide> PDFJS.createBlob = function createBlob(data, contentType) { <del> if (typeof Blob === 'function') <add> if (typeof Blob !== 'undefined') <ide> return new Blob([data], { type: contentType }); <ide> // Blob builder is deprecated in FF14 and removed in FF18. <ide> var bb = new MozBlobBuilder();
1
Python
Python
clarify savetxt delimiter and newline docstring
f80ccb0ed74d80a6669d0cd8711ba216bb1b5506
<ide><path>numpy/lib/npyio.py <ide> def savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', <ide> and imaginary part must have separate specifiers, <ide> e.g. `['%.3e + %.3ej', '(%.15e%+.15ej)']` for 2 columns <ide> delimiter : str, optional <del> Character separating columns. <add> String or character separating columns. <ide> newline : str, optional <del> Character separating lines. <add> String or character separating lines. <ide> <ide> .. versionadded:: 1.5.0 <ide> header : str, optional
1
Ruby
Ruby
use jenkins variables when no args
5d03149d816b66ae4375636d8182e99c2b320628
<ide><path>Library/Contributions/cmd/brew-test-bot.rb <ide> def single_commit? start_revision, end_revision <ide> @start_branch = current_branch <ide> <ide> # Use Jenkins environment variables if present. <del> if ENV['GIT_PREVIOUS_COMMIT'] and ENV['GIT_COMMIT'] \ <add> if no_args? and ENV['GIT_PREVIOUS_COMMIT'] and ENV['GIT_COMMIT'] \ <ide> and not ENV['ghprbPullId'] <ide> diff_start_sha1 = shorten_revision ENV['GIT_PREVIOUS_COMMIT'] <ide> diff_end_sha1 = shorten_revision ENV['GIT_COMMIT']
1
Go
Go
add a test for mount leak workaround
1af8ea681fba1935c60c11edbbe19b894c9b286f
<ide><path>daemon/graphdriver/devmapper/devmapper_test.go <ide> package devmapper <ide> import ( <ide> "fmt" <ide> "os" <add> "os/exec" <ide> "syscall" <ide> "testing" <ide> "time" <ide> <ide> "github.com/docker/docker/daemon/graphdriver" <ide> "github.com/docker/docker/daemon/graphdriver/graphtest" <add> "github.com/docker/docker/pkg/parsers/kernel" <add> "golang.org/x/sys/unix" <ide> ) <ide> <ide> func init() { <ide> func TestDevmapperLockReleasedDeviceDeletion(t *testing.T) { <ide> case <-doneChan: <ide> } <ide> } <add> <add>// Ensure that mounts aren't leakedriver. It's non-trivial for us to test the full <add>// reproducer of #34573 in a unit test, but we can at least make sure that a <add>// simple command run in a new namespace doesn't break things horribly. <add>func TestDevmapperMountLeaks(t *testing.T) { <add> if !kernel.CheckKernelVersion(3, 18, 0) { <add> t.Skipf("kernel version <3.18.0 and so is missing torvalds/linux@8ed936b5671bfb33d89bc60bdcc7cf0470ba52fe.") <add> } <add> <add> driver := graphtest.GetDriver(t, "devicemapper", "dm.use_deferred_removal=false", "dm.use_deferred_deletion=false").(*graphtest.Driver).Driver.(*graphdriver.NaiveDiffDriver).ProtoDriver.(*Driver) <add> defer graphtest.PutDriver(t) <add> <add> // We need to create a new (dummy) device. <add> if err := driver.Create("some-layer", "", nil); err != nil { <add> t.Fatalf("setting up some-layer: %v", err) <add> } <add> <add> // Mount the device. <add> _, err := driver.Get("some-layer", "") <add> if err != nil { <add> t.Fatalf("mounting some-layer: %v", err) <add> } <add> <add> // Create a new subprocess which will inherit our mountpoint, then <add> // intentionally leak it and stick around. We can't do this entirely within <add> // Go because forking and namespaces in Go are really not handled well at <add> // all. <add> cmd := exec.Cmd{ <add> Path: "/bin/sh", <add> Args: []string{ <add> "/bin/sh", "-c", <add> "mount --make-rprivate / && sleep 1000s", <add> }, <add> SysProcAttr: &syscall.SysProcAttr{ <add> Unshareflags: syscall.CLONE_NEWNS, <add> }, <add> } <add> if err := cmd.Start(); err != nil { <add> t.Fatalf("starting sub-command: %v", err) <add> } <add> defer func() { <add> unix.Kill(cmd.Process.Pid, unix.SIGKILL) <add> cmd.Wait() <add> }() <add> <add> // Now try to "drop" the device. <add> if err := driver.Put("some-layer"); err != nil { <add> t.Fatalf("unmounting some-layer: %v", err) <add> } <add>}
1
Ruby
Ruby
remove dead code from amo
7ba28d434ceb0401f937e77f19d1c31e2a43f1ac
<ide><path>activemodel/lib/active_model/test_case.rb <ide> module ActiveModel #:nodoc: <ide> class TestCase < ActiveSupport::TestCase #:nodoc: <del> def with_kcode(kcode) <del> if RUBY_VERSION < '1.9' <del> orig_kcode, $KCODE = $KCODE, kcode <del> begin <del> yield <del> ensure <del> $KCODE = orig_kcode <del> end <del> else <del> yield <del> end <del> end <ide> end <ide> end <ide><path>activemodel/test/cases/validations/length_validation_test.rb <ide> def test_validates_length_of_custom_errors_for_is_with_wrong_length <ide> end <ide> <ide> def test_validates_length_of_using_minimum_utf8 <del> with_kcode('UTF8') do <del> Topic.validates_length_of :title, :minimum => 5 <add> Topic.validates_length_of :title, :minimum => 5 <ide> <del> t = Topic.new("title" => "一二三四五", "content" => "whatever") <del> assert t.valid? <add> t = Topic.new("title" => "一二三四五", "content" => "whatever") <add> assert t.valid? <ide> <del> t.title = "一二三四" <del> assert t.invalid? <del> assert t.errors[:title].any? <del> assert_equal ["is too short (minimum is 5 characters)"], t.errors["title"] <del> end <add> t.title = "一二三四" <add> assert t.invalid? <add> assert t.errors[:title].any? <add> assert_equal ["is too short (minimum is 5 characters)"], t.errors["title"] <ide> end <ide> <ide> def test_validates_length_of_using_maximum_utf8 <del> with_kcode('UTF8') do <del> Topic.validates_length_of :title, :maximum => 5 <add> Topic.validates_length_of :title, :maximum => 5 <ide> <del> t = Topic.new("title" => "一二三四五", "content" => "whatever") <del> assert t.valid? <add> t = Topic.new("title" => "一二三四五", "content" => "whatever") <add> assert t.valid? <ide> <del> t.title = "一二34五六" <del> assert t.invalid? <del> assert t.errors[:title].any? <del> assert_equal ["is too long (maximum is 5 characters)"], t.errors["title"] <del> end <add> t.title = "一二34五六" <add> assert t.invalid? <add> assert t.errors[:title].any? <add> assert_equal ["is too long (maximum is 5 characters)"], t.errors["title"] <ide> end <ide> <ide> def test_validates_length_of_using_within_utf8 <del> with_kcode('UTF8') do <del> Topic.validates_length_of(:title, :content, :within => 3..5) <del> <del> t = Topic.new("title" => "一二", "content" => "12三四五六七") <del> assert t.invalid? <del> assert_equal ["is too short (minimum is 3 characters)"], t.errors[:title] <del> assert_equal ["is too long (maximum is 5 characters)"], t.errors[:content] <del> t.title = "一二三" <del> t.content = "12三" <del> assert t.valid? <del> end <add> Topic.validates_length_of(:title, :content, :within => 3..5) <add> <add> t = Topic.new("title" => "一二", "content" => "12三四五六七") <add> assert t.invalid? <add> assert_equal ["is too short (minimum is 3 characters)"], t.errors[:title] <add> assert_equal ["is too long (maximum is 5 characters)"], t.errors[:content] <add> t.title = "一二三" <add> t.content = "12三" <add> assert t.valid? <ide> end <ide> <ide> def test_optionally_validates_length_of_using_within_utf8 <del> with_kcode('UTF8') do <del> Topic.validates_length_of :title, :within => 3..5, :allow_nil => true <add> Topic.validates_length_of :title, :within => 3..5, :allow_nil => true <ide> <del> t = Topic.new(:title => "一二三四五") <del> assert t.valid?, t.errors.inspect <add> t = Topic.new(:title => "一二三四五") <add> assert t.valid?, t.errors.inspect <ide> <del> t = Topic.new(:title => "一二三") <del> assert t.valid?, t.errors.inspect <add> t = Topic.new(:title => "一二三") <add> assert t.valid?, t.errors.inspect <ide> <del> t.title = nil <del> assert t.valid?, t.errors.inspect <del> end <add> t.title = nil <add> assert t.valid?, t.errors.inspect <ide> end <ide> <ide> def test_validates_length_of_using_is_utf8 <del> with_kcode('UTF8') do <del> Topic.validates_length_of :title, :is => 5 <add> Topic.validates_length_of :title, :is => 5 <ide> <del> t = Topic.new("title" => "一二345", "content" => "whatever") <del> assert t.valid? <add> t = Topic.new("title" => "一二345", "content" => "whatever") <add> assert t.valid? <ide> <del> t.title = "一二345六" <del> assert t.invalid? <del> assert t.errors[:title].any? <del> assert_equal ["is the wrong length (should be 5 characters)"], t.errors["title"] <del> end <add> t.title = "一二345六" <add> assert t.invalid? <add> assert t.errors[:title].any? <add> assert_equal ["is the wrong length (should be 5 characters)"], t.errors["title"] <ide> end <ide> <ide> def test_validates_length_of_with_block
2
Javascript
Javascript
add a note about private api dependency for a test
46dd197ceb94ebc4f392a8b4ace347c6e03470fe
<ide><path>packages/events/__tests__/EventPluginRegistry-test.internal.js <ide> describe('EventPluginRegistry', () => { <ide> <ide> beforeEach(() => { <ide> jest.resetModuleRegistry(); <del> // TODO: can we express this test with only public API? <add> // These tests are intentionally testing the private injection interface. <add> // The public API surface of this is covered by other tests so <add> // if `EventPluginRegistry` is ever deleted, these tests should be <add> // safe to remove too. <ide> EventPluginRegistry = require('events/EventPluginRegistry'); <ide> <ide> createPlugin = function(properties) {
1
Javascript
Javascript
throw errors in webglrenderer
6d983ef7f6a2a2ea6d1747b17f8cce68cb4d5ca0
<ide><path>src/renderers/WebGLRenderer.js <ide> function WebGLRenderer( parameters ) { <ide> <ide> if ( _canvas.getContext( 'webgl' ) !== null ) { <ide> <del> throw 'Error creating WebGL context with your selected attributes.'; <add> throw new Error( 'Error creating WebGL context with your selected attributes.' ); <ide> <ide> } else { <ide> <del> throw 'Error creating WebGL context.'; <add> throw new Error( 'Error creating WebGL context.' ); <ide> <ide> } <ide> <ide> function WebGLRenderer( parameters ) { <ide> <ide> } catch ( error ) { <ide> <del> console.error( 'THREE.WebGLRenderer: ' + error ); <add> console.error( 'THREE.WebGLRenderer: ' + error.message ); <ide> <ide> } <ide>
1
Javascript
Javascript
use semantic versions
f6471f4f3668d236211d3d3e353852f0bc3a20ea
<ide><path>build/release.js <ide> function initialize( next ) { <ide> <ide> // First arg should be the version number being released <ide> var newver, oldver, <del> rversion = /^(\d)\.(\d+)\.(\d)((?:a|b|rc)\d|pre)?$/, <del> version = ( process.argv[3] || "" ).toLowerCase().match( rversion ) || {}, <add> rsemver = /^(\d+)\.(\d+)\.(\d+)(?:-([\dA-Za-z\-]+(?:\.[\dA-Za-z\-]+)*))?$/, <add> version = ( process.argv[3] || "" ).toLowerCase().match( rsemver ) || {}, <ide> major = version[1], <ide> minor = version[2], <ide> patch = version[3], <ide> function initialize( next ) { <ide> pkg = JSON.parse( fs.readFileSync( "package.json" ) ); <ide> <ide> console.log( "Current version is " + pkg.version + "; generating release " + releaseVersion ); <del> version = pkg.version.match( rversion ); <add> version = pkg.version.match( rsemver ); <ide> oldver = ( +version[1] ) * 10000 + ( +version[2] * 100 ) + ( +version[3] ) <ide> newver = ( +major ) * 10000 + ( +minor * 100 ) + ( +patch ); <ide> if ( newver < oldver ) { <ide> die( "Next version is older than current version!" ); <ide> } <ide> <del> nextVersion = major + "." + minor + "." + ( isBeta ? patch : +patch + 1 ) + "pre"; <add> nextVersion = major + "." + minor + "." + ( isBeta ? patch : +patch + 1 ) + "-pre"; <ide> next(); <ide> } <ide>
1
PHP
PHP
update exception in log classes
d1610d97dc9fa40c08b7f686738da0df6ec83e2f
<ide><path>src/Log/Engine/ConsoleLog.php <ide> <ide> use Cake\Console\ConsoleOutput; <ide> use Cake\Core\Exception\Exception; <add>use \InvalidArgumentException; <ide> <ide> /** <ide> * Console logging. Writes logs to console output. <ide> class ConsoleLog extends BaseLog { <ide> * - `outputAs` integer or ConsoleOutput::[RAW|PLAIN|COLOR] <ide> * <ide> * @param array $config Options for the FileLog, see above. <del> * @throws \Cake\Core\Exception\Exception <add> * @throws \InvalidArgumentException <ide> */ <ide> public function __construct(array $config = array()) { <ide> if (DS === '\\' && !(bool)env('ANSICON')) { <ide> public function __construct(array $config = array()) { <ide> } elseif (is_string($config['stream'])) { <ide> $this->_output = new ConsoleOutput($config['stream']); <ide> } else { <del> throw new Exception('`stream` not a ConsoleOutput nor string'); <add> throw new InvalidArgumentException('`stream` not a ConsoleOutput nor string'); <ide> } <ide> $this->_output->outputAs($config['outputAs']); <ide> } <ide><path>src/Log/Log.php <ide> namespace Cake\Log; <ide> <ide> use Cake\Core\StaticConfigTrait; <del>use Cake\Core\Exception\Exception; <ide> use Cake\Log\Engine\BaseLog; <add>use InvalidArgumentException; <ide> <ide> /** <ide> * Logs messages to configured Log adapters. One or more adapters <ide> public static function levels() { <ide> * @param string|array $key The name of the logger config, or an array of multiple configs. <ide> * @param array $config An array of name => config data for adapter. <ide> * @return mixed null when adding configuration and an array of configuration data when reading. <del> * @throws \Cake\Core\Exception\Exception When trying to modify an existing config. <add> * @throws \BadMethodCallException When trying to modify an existing config. <ide> */ <ide> public static function config($key, $config = null) { <ide> $return = static::_config($key, $config); <ide> public static function engine($name) { <ide> * @param string|array $scope The scope(s) a log message is being created in. <ide> * See Cake\Log\Log::config() for more information on logging scopes. <ide> * @return bool Success <del> * @throws \Cake\Core\Exception\Exception If invalid level is passed. <add> * @throws \InvalidArgumentException If invalid level is passed. <ide> */ <ide> public static function write($level, $message, $scope = array()) { <ide> static::_init(); <ide> public static function write($level, $message, $scope = array()) { <ide> } <ide> <ide> if (!in_array($level, static::$_levels)) { <del> throw new Exception(sprintf('Invalid log level "%s"', $level)); <add> throw new InvalidArgumentException(sprintf('Invalid log level "%s"', $level)); <ide> } <ide> <ide> $logged = false; <ide><path>src/Log/LogEngineRegistry.php <ide> namespace Cake\Log; <ide> <ide> use Cake\Core\App; <del>use Cake\Core\Exception\Exception; <ide> use Cake\Core\ObjectRegistry; <ide> use Cake\Log\LogInterface; <add>use \RuntimeException; <ide> <ide> /** <ide> * Registry of loaded log engines <ide> protected function _resolveClassName($class) { <ide> * @param string $class The classname that is missing. <ide> * @param string $plugin The plugin the logger is missing in. <ide> * @return void <del> * @throws \Cake\Core\Exception\Exception <add> * @throws \RuntimeException <ide> */ <ide> protected function _throwMissingClassError($class, $plugin) { <del> throw new Exception(sprintf('Could not load class %s', $class)); <add> throw new RuntimeException(sprintf('Could not load class %s', $class)); <ide> } <ide> <ide> /** <ide> protected function _throwMissingClassError($class, $plugin) { <ide> * @param string $alias The alias of the object. <ide> * @param array $settings An array of settings to use for the logger. <ide> * @return \Cake\Log\LogInterface The constructed logger class. <del> * @throws \Cake\Core\Exception\Exception when an object doesn't implement <del> * the correct interface. <add> * @throws \RuntimeException when an object doesn't implement the correct interface. <ide> */ <ide> protected function _create($class, $alias, $settings) { <ide> if (is_object($class)) { <ide> protected function _create($class, $alias, $settings) { <ide> return $instance; <ide> } <ide> <del> throw new Exception( <add> throw new RuntimeException( <ide> 'Loggers must implement Cake\Log\LogInterface.' <ide> ); <ide> } <ide><path>tests/TestCase/Log/LogTest.php <ide> public function testImportingLoggers() { <ide> /** <ide> * test all the errors from failed logger imports <ide> * <del> * @expectedException \Cake\Core\Exception\Exception <add> * @expectedException RuntimeException <ide> * @return void <ide> */ <ide> public function testImportingLoggerFailure() { <ide> public function testValidKeyName() { <ide> /** <ide> * test that loggers have to implement the correct interface. <ide> * <del> * @expectedException \Cake\Core\Exception\Exception <add> * @expectedException \RuntimeException <ide> * @return void <ide> */ <ide> public function testNotImplementingInterface() { <ide> public function testDrop() { <ide> /** <ide> * test config() with valid key name <ide> * <del> * @expectedException \Cake\Core\Exception\Exception <add> * @expectedException \InvalidArgumentException <ide> * @return void <ide> */ <ide> public function testInvalidLevel() { <ide> public function testConfigVariants($settings) { <ide> * Test that config() throws an exception when adding an <ide> * adapter with the wrong type. <ide> * <del> * @expectedException \Cake\Core\Exception\Exception <add> * @expectedException \RuntimeException <ide> * @return void <ide> */ <ide> public function testConfigInjectErrorOnWrongType() { <ide> public function testConfigRead() { <ide> /** <ide> * Ensure you cannot reconfigure a log adapter. <ide> * <del> * @expectedException BadMethodCallException <add> * @expectedException \BadMethodCallException <ide> * @return void <ide> */ <ide> public function testConfigErrorOnReconfigure() {
4
Python
Python
fix configure script to work with apple clang 11
1f143b8625c2985b4317a40f279232f562417077
<ide><path>configure.py <ide> def get_llvm_version(cc): <ide> <ide> def get_xcode_version(cc): <ide> return get_version_helper( <del> cc, r"(^Apple LLVM version) ([0-9]+\.[0-9]+)") <add> cc, r"(^Apple (?:clang|LLVM) version) ([0-9]+\.[0-9]+)") <ide> <ide> def get_gas_version(cc): <ide> try:
1
PHP
PHP
fix failing tests in controllertestcase
21777071806c796a0a9b935db178c97b3fe283c0
<ide><path>src/Routing/DispatcherFactory.php <ide> public static function create() { <ide> return $dispatcher; <ide> } <ide> <add>/** <add> * Get the connected dispatcher filters. <add> * <add> * @return array <add> */ <add> public static function filters() { <add> return static::$_stack; <add> } <add> <ide> /** <ide> * Clear the middleware stack. <ide> * <ide><path>src/TestSuite/ControllerTestCase.php <ide> use Cake\Error; <ide> use Cake\Event\Event; <ide> use Cake\Routing\Dispatcher; <add>use Cake\Routing\DispatcherFactory; <ide> use Cake\Routing\Router; <ide> use Cake\Utility\Inflector; <ide> use Cake\View\Helper; <ide> class ControllerTestDispatcher extends Dispatcher { <ide> */ <ide> public $testController = null; <ide> <del>/** <del> * Use custom routes during tests <del> * <del> * @var bool <del> */ <del> public $loadRoutes = true; <del> <ide> /** <ide> * Returns the test controller <ide> * <ide> protected function _getController($request, $response) { <ide> return $this->testController; <ide> } <ide> <del>/** <del> * Loads routes and resets if the test case dictates it should <del> * <del> * @return void <del> */ <del> protected function _loadRoutes() { <del> parent::_loadRoutes(); <del> if (!$this->loadRoutes) { <del> Router::reload(); <del> } <del> } <del> <ide> } <ide> <ide> /** <ide> protected function _testAction($url = '', $options = array()) { <ide> ->will($this->returnValue($options['data'])); <ide> } <ide> <del> $Dispatch = new ControllerTestDispatcher(); <del> $Dispatch->loadRoutes = $this->loadRoutes; <del> $Dispatch->parseParams(new Event('ControllerTestCase', $Dispatch, array('request' => $request))); <add> if ($this->loadRoutes) { <add> Router::reload(); <add> } <add> $request->addParams(Router::parse($request->url)); <add> <add> // Handle redirect routes. <ide> if (!isset($request->params['controller']) && Router::getRequest()) { <ide> $this->headers = Router::getRequest()->response->header(); <ide> return; <ide> } <add> <add> $Dispatch = new ControllerTestDispatcher(); <add> foreach (DispatcherFactory::filters() as $filter) { <add> $Dispatch->add($filter); <add> } <ide> if ($this->_dirtyController) { <ide> $this->controller = null; <ide> } <del> <ide> $plugin = empty($request->params['plugin']) ? '' : Inflector::camelize($request->params['plugin']) . '.'; <ide> if ($this->controller === null && $this->autoMock) { <ide> $this->generate($plugin . Inflector::camelize($request->params['controller'])); <ide> protected function _testAction($url = '', $options = array()) { <ide> $params['bare'] = 1; <ide> $params['requested'] = 1; <ide> } <add> $request->addParams($params); <add> <ide> $Dispatch->testController = $this->controller; <ide> $Dispatch->response = $this->getMock('Cake\Network\Response', array('send', 'stop')); <del> $this->result = $Dispatch->dispatch($request, $Dispatch->response, $params); <add> $this->result = $Dispatch->dispatch($request, $Dispatch->response); <add> <ide> $this->controller = $Dispatch->testController; <ide> $this->vars = $this->controller->viewVars; <ide> $this->contents = $this->controller->response->body(); <ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php <ide> <?php <ide> /** <del> * RequestHandlerComponentTest file <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide> use Cake\Event\Event; <ide> use Cake\Network\Request; <ide> use Cake\Network\Response; <add>use Cake\Routing\DispatcherFactory; <ide> use Cake\Routing\Router; <ide> use Cake\TestSuite\TestCase; <ide> use TestApp\Controller\RequestHandlerTestController; <ide> class RequestHandlerComponentTest extends TestCase { <ide> public function setUp() { <ide> parent::setUp(); <ide> Configure::write('App.namespace', 'TestApp'); <add> DispatcherFactory::add('RoutingFilter'); <ide> $this->_init(); <ide> } <ide> <ide> protected function _init() { <ide> */ <ide> public function tearDown() { <ide> parent::tearDown(); <add> DispatcherFactory::clear(); <add> $this->_init(); <ide> unset($this->RequestHandler, $this->Controller); <ide> if (!headers_sent()) { <ide> header('Content-type: text/html'); //reset content type. <ide><path>tests/TestCase/Controller/Component/SessionComponentTest.php <ide> <?php <ide> /** <del> * SessionComponentTest file <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide> use Cake\Controller\Controller; <ide> use Cake\Core\Configure; <ide> use Cake\Network\Session; <add>use Cake\Routing\DispatcherFactory; <ide> use Cake\Routing\Router; <ide> use Cake\TestSuite\TestCase; <ide> <ide> public static function setupBeforeClass() { <ide> 'timeout' => 100, <ide> 'cookie' => 'test' <ide> )); <add> DispatcherFactory::add('RoutingFilter'); <ide> } <ide> <ide> /** <ide> public static function setupBeforeClass() { <ide> */ <ide> public static function teardownAfterClass() { <ide> Configure::write('Session', static::$_sessionBackup); <add> DispatcherFactory::clear(); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/TestSuite/ControllerTestCaseTest.php <ide> use Cake\Core\Plugin; <ide> use Cake\ORM\Table; <ide> use Cake\ORM\TableRegistry; <add>use Cake\Routing\DispatcherFactory; <ide> use Cake\Routing\Router; <ide> use Cake\TestSuite\Reporter\HtmlReporter; <ide> use Cake\TestSuite\TestCase; <ide> public function setUp() { <ide> Plugin::load(array('TestPlugin', 'TestPluginTwo')); <ide> <ide> $this->Case = $this->getMockForAbstractClass('Cake\TestSuite\ControllerTestCase'); <add> DispatcherFactory::add('RoutingFilter'); <ide> Router::reload(); <ide> TableRegistry::clear(); <ide> } <ide> public function setUp() { <ide> public function tearDown() { <ide> parent::tearDown(); <ide> Plugin::unload(); <add> DispatcherFactory::clear(); <ide> $this->Case->controller = null; <ide> } <ide>
5
Go
Go
check env var for setting driver in tests
aea6001baf0cd0fb20a607e37e4379bf644b28fd
<ide><path>graphdriver/driver.go <ide> import ( <ide> "fmt" <ide> "github.com/dotcloud/docker/archive" <ide> "github.com/dotcloud/docker/utils" <add> "os" <ide> "path" <ide> ) <ide> <ide> func New(root string) (Driver, error) { <ide> var driver Driver <ide> var lastError error <ide> <del> if DefaultDriver != "" { <del> return GetDriver(DefaultDriver, root) <add> for _, name := range []string{ <add> os.Getenv("DOCKER_DRIVER"), <add> DefaultDriver, <add> } { <add> if name != "" { <add> return GetDriver(name, root) <add> } <ide> } <add> <ide> // Check for priority drivers first <ide> for _, name := range priority { <ide> driver, lastError = GetDriver(name, root)
1
Python
Python
improve error messages
7c08713baa75094726ebafbd8c092911b72f839f
<ide><path>spacy/cli/project.py <del>from typing import List, Dict, Any, Optional <add>from typing import List, Dict, Any, Optional, Sequence <ide> import typer <ide> import srsly <ide> from pathlib import Path <ide> def print_run_help(project_dir: Path, subcommand: Optional[str] = None) -> None: <ide> config_commands = config.get("commands", []) <ide> commands = {cmd["name"]: cmd for cmd in config_commands} <ide> if subcommand: <del> if subcommand not in commands: <del> msg.fail(f"Can't find command '{subcommand}' in project config", exits=1) <add> validate_subcommand(commands.keys(), subcommand) <ide> print(f"Usage: {COMMAND} project run {project_dir} {subcommand}") <ide> help_text = commands[subcommand].get("help") <ide> if help_text: <ide> def project_run(project_dir: Path, subcommand: str, *dvc_args) -> None: <ide> config_commands = config.get("commands", []) <ide> variables = config.get("variables", {}) <ide> commands = {cmd["name"]: cmd for cmd in config_commands} <del> if subcommand not in commands: <del> msg.fail(f"Can't find command '{subcommand}' in project config", exits=1) <add> validate_subcommand(commands.keys(), subcommand) <ide> if subcommand in config.get("run", []): <ide> # This is one of the pipeline commands tracked in DVC <ide> dvc_cmd = ["dvc", "repro", subcommand, *dvc_args] <ide> def load_project_config(path: Path) -> Dict[str, Any]: <ide> config_path = path / CONFIG_FILE <ide> if not config_path.exists(): <ide> msg.fail("Can't find project config", config_path, exits=1) <del> config = srsly.read_yaml(config_path) <add> invalid_err = f"Invalid project config in {CONFIG_FILE}" <add> try: <add> config = srsly.read_yaml(config_path) <add> except ValueError as e: <add> msg.fail(invalid_err, e, exits=1) <ide> errors = validate(ProjectConfigSchema, config) <ide> if errors: <del> msg.fail(f"Invalid project config in {CONFIG_FILE}", "\n".join(errors), exits=1) <add> msg.fail(invalid_err, "\n".join(errors), exits=1) <ide> return config <ide> <ide> <ide> def update_dvc_config( <ide> # commands in project.yml and should be run in sequence <ide> config_commands = {cmd["name"]: cmd for cmd in config.get("commands", [])} <ide> for name in config.get("run", []): <del> if name not in config_commands: <del> msg.fail(f"Can't find command '{name}' in project config", exits=1) <add> validate_subcommand(config_commands.keys(), name) <ide> command = config_commands[name] <ide> deps = command.get("deps", []) <ide> outputs = command.get("outputs", []) <ide> def check_clone(name: str, dest: Path, repo: str) -> None: <ide> ) <ide> <ide> <add>def validate_subcommand(commands: Sequence[str], subcommand: str) -> None: <add> """Check that a subcommand is valid and defined. Raises an error otherwise. <add> <add> commands (Sequence[str]): The available commands. <add> subcommand (str): The subcommand. <add> """ <add> if subcommand not in commands: <add> msg.fail( <add> f"Can't find command '{subcommand}' in {CONFIG_FILE}. " <add> f"Available commands: {', '.join(commands)}", <add> exits=1, <add> ) <add> <add> <ide> def download_file(url: str, dest: Path, chunk_size: int = 1024) -> None: <ide> """Download a file using requests. <ide>
1
Python
Python
remove redundant masking in _step
3f3a1f0e9bc55630acac3efdafb3c1c9fa719dec
<ide><path>keras/layers/recurrent.py <ide> def __init__(self, input_dim, output_dim, <ide> if weights is not None: <ide> self.set_weights(weights) <ide> <del> def _step(self, x_t, mask_t, mask_tm1, h_tm1, u): <add> def _step(self, x_t, mask_tm1, h_tm1, u): <ide> ''' <ide> Variable names follow the conventions from: <ide> http://deeplearning.net/software/theano/library/scan.html <ide> <ide> ''' <del> normal_output = self.activation(x_t + mask_tm1 * T.dot(h_tm1, u)) <del> return mask_t * normal_output <add> return self.activation(x_t + mask_tm1 * T.dot(h_tm1, u)) <ide> <ide> def get_output(self, train): <ide> X = self.get_input(train) # shape: (nb_samples, time (padded with zeros at the end), input_dim) <ide> def get_output(self, train): <ide> # Iterate over the first dimension of the x array (=time). <ide> outputs, updates = theano.scan( <ide> self._step, # this will be called with arguments (sequences[i], outputs[i-1], non_sequences[i]) <del> sequences=[x, dict(input=padded_mask,taps=[0, -1])], # tensors to iterate over, inputs to _step <add> sequences=[x, dict(input=padded_mask, taps=[-1])], # tensors to iterate over, inputs to _step <ide> # initialization of the output. Input to _step with default tap=-1. <ide> outputs_info=T.unbroadcast(alloc_zeros_matrix(X.shape[1], self.output_dim), 1), <ide> non_sequences=self.U, # static inputs to _step <ide> truncate_gradient=self.truncate_gradient <ide> ) <ide> # Apply the mask: <del> outputs = mask*outputs + (1-mask)*self.mask_val <add> outputs = mask * outputs + (1 - mask) * self.mask_val <ide> if self.return_sequences: <ide> return outputs.dimshuffle((1,0,2)) <ide> return outputs[-1] <ide> def __init__(self, input_dim, output_dim, depth=3, <ide> if weights is not None: <ide> self.set_weights(weights) <ide> <del> def _step(self, x_t, mask_t, *args): <add> def _step(self, x_t, *args): <ide> o = x_t <ide> for i in range(self.depth): <ide> mask_tmi = args[i] <ide> h_tmi = args[i + self.depth] <ide> U_tmi = args[i + 2*self.depth] <ide> o += mask_tmi*self.inner_activation(T.dot(h_tmi, U_tmi)) <del> return mask_t*self.activation(o) <add> return self.activation(o) <ide> <ide> def get_output(self, train): <ide> X = self.get_input(train) <ide> def get_output(self, train): <ide> self._step, <ide> sequences=[x, dict( <ide> input = padded_mask, <del> taps = [(-i) for i in range(self.depth+1)] <add> taps = [(-i) for i in range(self.depth)] <ide> )], <ide> outputs_info=[dict( <ide> initial = initial, <ide> def get_output(self, train): <ide> non_sequences=self.Us, <ide> truncate_gradient=self.truncate_gradient <ide> ) <del> outputs = mask*outputs + (1-mask)*self.mask_val <add> outputs = mask * outputs + (1 - mask) * self.mask_val <ide> if self.return_sequences: <ide> return outputs.dimshuffle((1,0,2)) <ide> return outputs[-1]
1
Text
Text
update generation instructions for consistency
d27a2a9294b8384a3f1bee12caa4246b57be65ed
<ide><path>guides/source/engines.md <ide> commenting functionality as well. To do this, you'll need to generate a comment <ide> model, a comment controller, and then modify the articles scaffold to display <ide> comments and allow people to create new ones. <ide> <del>From the application root, run the model generator. Tell it to generate a <add>From the engine root, run the model generator. Tell it to generate a <ide> `Comment` model, with the related table having two columns: an `article_id` integer <ide> and `text` text column. <ide> <ide> end <ide> This creates a nested route for the comments, which is what the form requires. <ide> <ide> The route now exists, but the controller that this route goes to does not. To <del>create it, run this command from the application root: <add>create it, run this command from the engine root: <ide> <ide> ```bash <ide> $ bin/rails generate controller comments
1
Go
Go
remove copyonbuild from the daemon
bd5f92d2631df7c932b93e72e45b39cba19f2f3b
<ide><path>builder/builder.go <ide> import ( <ide> "github.com/docker/docker/api/types/backend" <ide> "github.com/docker/docker/api/types/container" <ide> containerpkg "github.com/docker/docker/container" <add> "github.com/docker/docker/image" <add> "github.com/docker/docker/layer" <add> "github.com/docker/docker/pkg/idtools" <ide> "golang.org/x/net/context" <ide> ) <ide> <ide> type Backend interface { <ide> // ContainerCreateWorkdir creates the workdir <ide> ContainerCreateWorkdir(containerID string) error <ide> <del> // ContainerCopy copies/extracts a source FileInfo to a destination path inside a container <del> // specified by a container object. <del> // TODO: extract in the builder instead of passing `decompress` <del> // TODO: use containerd/fs.changestream instead as a source <del> CopyOnBuild(containerID string, destPath string, srcRoot string, srcPath string, decompress bool) error <add> CreateImage(config []byte, parent string) (string, error) <add> <add> IDMappings() *idtools.IDMappings <ide> <ide> ImageCacheBuilder <ide> } <ide> type ImageCache interface { <ide> type Image interface { <ide> ImageID() string <ide> RunConfig() *container.Config <add> MarshalJSON() ([]byte, error) <add> NewChild(child image.ChildConfig) *image.Image <ide> } <ide> <ide> // ReleaseableLayer is an image layer that can be mounted and released <ide> type ReleaseableLayer interface { <ide> Release() error <ide> Mount() (string, error) <add> DiffID() layer.DiffID <ide> } <ide><path>builder/dockerfile/builder.go <ide> import ( <ide> "github.com/docker/docker/builder/dockerfile/command" <ide> "github.com/docker/docker/builder/dockerfile/parser" <ide> "github.com/docker/docker/builder/remotecontext" <add> "github.com/docker/docker/pkg/archive" <add> "github.com/docker/docker/pkg/chrootarchive" <ide> "github.com/docker/docker/pkg/streamformatter" <ide> "github.com/docker/docker/pkg/stringid" <ide> "github.com/pkg/errors" <ide> type Builder struct { <ide> docker builder.Backend <ide> clientCtx context.Context <ide> <add> archiver *archive.Archiver <ide> buildStages *buildStages <ide> disableCommit bool <ide> buildArgs *buildArgs <ide> func newBuilder(clientCtx context.Context, options builderOptions) *Builder { <ide> Aux: options.ProgressWriter.AuxFormatter, <ide> Output: options.ProgressWriter.Output, <ide> docker: options.Backend, <add> archiver: chrootarchive.NewArchiver(options.Backend.IDMappings()), <ide> buildArgs: newBuildArgs(config.BuildArgs), <ide> buildStages: newBuildStages(), <ide> imageSources: newImageSources(clientCtx, options), <ide><path>builder/dockerfile/copy.go <ide> import ( <ide> <ide> "github.com/docker/docker/builder" <ide> "github.com/docker/docker/builder/remotecontext" <add> "github.com/docker/docker/pkg/archive" <add> "github.com/docker/docker/pkg/idtools" <ide> "github.com/docker/docker/pkg/ioutils" <ide> "github.com/docker/docker/pkg/progress" <ide> "github.com/docker/docker/pkg/streamformatter" <add> "github.com/docker/docker/pkg/symlink" <ide> "github.com/docker/docker/pkg/system" <ide> "github.com/docker/docker/pkg/urlutil" <ide> "github.com/pkg/errors" <ide> type copyInfo struct { <ide> hash string <ide> } <ide> <add>func (c copyInfo) fullPath() (string, error) { <add> return symlink.FollowSymlinkInScope(filepath.Join(c.root, c.path), c.root) <add>} <add> <ide> func newCopyInfoFromSource(source builder.Source, path string, hash string) copyInfo { <ide> return copyInfo{root: source.Root(), path: path, hash: hash} <ide> } <ide> func downloadSource(output io.Writer, stdout io.Writer, srcURL string) (remote b <ide> lc, err := remotecontext.NewLazyContext(tmpDir) <ide> return lc, filename, err <ide> } <add> <add>type copyFileOptions struct { <add> decompress bool <add> archiver *archive.Archiver <add>} <add> <add>func copyFile(dest copyInfo, source copyInfo, options copyFileOptions) error { <add> srcPath, err := source.fullPath() <add> if err != nil { <add> return err <add> } <add> destPath, err := dest.fullPath() <add> if err != nil { <add> return err <add> } <add> <add> archiver := options.archiver <add> rootIDs := archiver.IDMappings.RootPair() <add> <add> src, err := os.Stat(srcPath) <add> if err != nil { <add> return err // TODO: errors.Wrapf <add> } <add> if src.IsDir() { <add> if err := archiver.CopyWithTar(srcPath, destPath); err != nil { <add> return err <add> } <add> return fixPermissions(srcPath, destPath, rootIDs) <add> } <add> <add> if options.decompress && archive.IsArchivePath(srcPath) { <add> // To support the untar feature we need to clean up the path a little bit <add> // because tar is not very forgiving <add> tarDest := dest.path <add> // TODO: could this be just TrimSuffix()? <add> if strings.HasSuffix(tarDest, string(os.PathSeparator)) { <add> tarDest = filepath.Dir(dest.path) <add> } <add> return archiver.UntarPath(srcPath, tarDest) <add> } <add> <add> if err := idtools.MkdirAllAndChownNew(filepath.Dir(destPath), 0755, rootIDs); err != nil { <add> return err <add> } <add> if err := archiver.CopyFileWithTar(srcPath, destPath); err != nil { <add> return err <add> } <add> // TODO: do I have to change destPath to the filename? <add> return fixPermissions(srcPath, destPath, rootIDs) <add>} <ide><path>builder/dockerfile/copy_unix.go <add>package dockerfile <add> <add>import ( <add> "os" <add> "path/filepath" <add> <add> "github.com/docker/docker/pkg/idtools" <add>) <add> <add>func pathExists(path string) (bool, error) { <add> _, err := os.Stat(path) <add> switch { <add> case err == nil: <add> return true, nil <add> case os.IsNotExist(err): <add> return false, nil <add> } <add> return false, err <add>} <add> <add>// TODO: review this <add>func fixPermissions(source, destination string, rootIDs idtools.IDPair) error { <add> doChownDestination, err := chownDestinationRoot(destination) <add> if err != nil { <add> return err <add> } <add> <add> // We Walk on the source rather than on the destination because we don't <add> // want to change permissions on things we haven't created or modified. <add> return filepath.Walk(source, func(fullpath string, info os.FileInfo, err error) error { <add> // Do not alter the walk root iff. it existed before, as it doesn't fall under <add> // the domain of "things we should chown". <add> if !doChownDestination && (source == fullpath) { <add> return nil <add> } <add> <add> // Path is prefixed by source: substitute with destination instead. <add> cleaned, err := filepath.Rel(source, fullpath) <add> if err != nil { <add> return err <add> } <add> <add> fullpath = filepath.Join(destination, cleaned) <add> return os.Lchown(fullpath, rootIDs.UID, rootIDs.GID) <add> }) <add>} <add> <add>// If the destination didn't already exist, or the destination isn't a <add>// directory, then we should Lchown the destination. Otherwise, we shouldn't <add>// Lchown the destination. <add>func chownDestinationRoot(destination string) (bool, error) { <add> destExists, err := pathExists(destination) <add> if err != nil { <add> return false, err <add> } <add> destStat, err := os.Stat(destination) <add> if err != nil { <add> // This should *never* be reached, because the destination must've already <add> // been created while untar-ing the context. <add> return false, err <add> } <add> <add> return !destExists || !destStat.IsDir(), nil <add>} <ide><path>builder/dockerfile/copy_windows.go <add>package dockerfile <add> <add>import "github.com/docker/docker/pkg/idtools" <add> <add>func fixPermissions(source, destination string, rootIDs idtools.IDPair) error { <add> // chown is not supported on Windows <add> return nil <add>} <ide><path>builder/dockerfile/dispatchers.go <ide> import ( <ide> "github.com/docker/docker/api/types/strslice" <ide> "github.com/docker/docker/builder" <ide> "github.com/docker/docker/builder/dockerfile/parser" <add> "github.com/docker/docker/image" <ide> "github.com/docker/docker/pkg/jsonmessage" <ide> "github.com/docker/docker/pkg/signal" <ide> "github.com/docker/go-connections/nat" <ide> func parseBuildStageName(args []string) (string, error) { <ide> return stageName, nil <ide> } <ide> <del>// scratchImage is used as a token for the empty base image. It uses buildStage <del>// as a convenient implementation of builder.Image, but is not actually a <del>// buildStage. <del>var scratchImage builder.Image = &buildStage{} <add>// scratchImage is used as a token for the empty base image. <add>var scratchImage builder.Image = &image.Image{} <ide> <ide> func (b *Builder) getFromImage(shlex *ShellLex, name string) (builder.Image, error) { <ide> substitutionArgs := []string{} <ide> func (b *Builder) getFromImage(shlex *ShellLex, name string) (builder.Image, err <ide> return nil, err <ide> } <ide> <del> if im, ok := b.buildStages.getByName(name); ok { <del> return im, nil <add> if stage, ok := b.buildStages.getByName(name); ok { <add> name = stage.ImageID() <ide> } <ide> <ide> // Windows cannot support a container with no base image. <ide><path>builder/dockerfile/imagecontext.go <ide> import ( <ide> <ide> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/api/types/backend" <del> "github.com/docker/docker/api/types/container" <ide> "github.com/docker/docker/builder" <ide> "github.com/docker/docker/builder/remotecontext" <add> "github.com/docker/docker/layer" <ide> "github.com/pkg/errors" <ide> "golang.org/x/net/context" <ide> ) <ide> <ide> type buildStage struct { <del> id string <del> config *container.Config <add> id string <ide> } <ide> <del>func newBuildStageFromImage(image builder.Image) *buildStage { <del> return &buildStage{id: image.ImageID(), config: image.RunConfig()} <add>func newBuildStage(imageID string) *buildStage { <add> return &buildStage{id: imageID} <ide> } <ide> <ide> func (b *buildStage) ImageID() string { <ide> return b.id <ide> } <ide> <del>func (b *buildStage) RunConfig() *container.Config { <del> return b.config <del>} <del> <del>func (b *buildStage) update(imageID string, runConfig *container.Config) { <add>func (b *buildStage) update(imageID string) { <ide> b.id = imageID <del> b.config = runConfig <ide> } <ide> <del>var _ builder.Image = &buildStage{} <del> <ide> // buildStages tracks each stage of a build so they can be retrieved by index <ide> // or by name. <ide> type buildStages struct { <ide> func newBuildStages() *buildStages { <ide> return &buildStages{byName: make(map[string]*buildStage)} <ide> } <ide> <del>func (s *buildStages) getByName(name string) (builder.Image, bool) { <add>func (s *buildStages) getByName(name string) (*buildStage, bool) { <ide> stage, ok := s.byName[strings.ToLower(name)] <ide> return stage, ok <ide> } <ide> <del>func (s *buildStages) get(indexOrName string) (builder.Image, error) { <add>func (s *buildStages) get(indexOrName string) (*buildStage, error) { <ide> index, err := strconv.Atoi(indexOrName) <ide> if err == nil { <ide> if err := s.validateIndex(index); err != nil { <ide> func (s *buildStages) validateIndex(i int) error { <ide> } <ide> <ide> func (s *buildStages) add(name string, image builder.Image) error { <del> stage := newBuildStageFromImage(image) <add> stage := newBuildStage(image.ImageID()) <ide> name = strings.ToLower(name) <ide> if len(name) > 0 { <ide> if _, ok := s.byName[name]; ok { <ide> func (s *buildStages) add(name string, image builder.Image) error { <ide> return nil <ide> } <ide> <del>func (s *buildStages) update(imageID string, runConfig *container.Config) { <del> s.sequence[len(s.sequence)-1].update(imageID, runConfig) <add>func (s *buildStages) update(imageID string) { <add> s.sequence[len(s.sequence)-1].update(imageID) <ide> } <ide> <ide> type getAndMountFunc func(string) (builder.Image, builder.ReleaseableLayer, error) <ide> func (im *imageMount) Image() builder.Image { <ide> func (im *imageMount) ImageID() string { <ide> return im.image.ImageID() <ide> } <add> <add>func (im *imageMount) DiffID() layer.DiffID { <add> return im.layer.DiffID() <add>} <ide><path>builder/dockerfile/internals.go <ide> import ( <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/backend" <ide> "github.com/docker/docker/api/types/container" <add> "github.com/docker/docker/builder" <add> "github.com/docker/docker/image" <ide> "github.com/docker/docker/pkg/stringid" <ide> "github.com/pkg/errors" <ide> ) <ide> func (b *Builder) commit(dispatchState *dispatchState, comment string) error { <ide> return b.commitContainer(dispatchState, id, runConfigWithCommentCmd) <ide> } <ide> <del>// TODO: see if any args can be dropped <ide> func (b *Builder) commitContainer(dispatchState *dispatchState, id string, containerConfig *container.Config) error { <ide> if b.disableCommit { <ide> return nil <ide> func (b *Builder) commitContainer(dispatchState *dispatchState, id string, conta <ide> } <ide> <ide> dispatchState.imageID = imageID <del> b.buildStages.update(imageID, dispatchState.runConfig) <add> b.buildStages.update(imageID) <ide> return nil <ide> } <ide> <add>func (b *Builder) exportImage(state *dispatchState, image builder.Image) error { <add> config, err := image.MarshalJSON() <add> if err != nil { <add> return errors.Wrap(err, "failed to encode image config") <add> } <add> <add> state.imageID, err = b.docker.CreateImage(config, state.imageID) <add> return err <add>} <add> <ide> func (b *Builder) performCopy(state *dispatchState, inst copyInstruction) error { <ide> srcHash := getSourceHashFromInfos(inst.infos) <ide> <ide> func (b *Builder) performCopy(state *dispatchState, inst copyInstruction) error <ide> return err <ide> } <ide> <add> imageMount, err := b.imageSources.Get(state.imageID) <add> if err != nil { <add> return err <add> } <add> destSource, err := imageMount.Source() <add> if err != nil { <add> return err <add> } <add> <add> destInfo := newCopyInfoFromSource(destSource, dest, "") <add> opts := copyFileOptions{ <add> decompress: inst.allowLocalDecompression, <add> archiver: b.archiver, <add> } <ide> for _, info := range inst.infos { <del> if err := b.docker.CopyOnBuild(containerID, dest, info.root, info.path, inst.allowLocalDecompression); err != nil { <add> if err := copyFile(destInfo, info, opts); err != nil { <ide> return err <ide> } <ide> } <del> return b.commitContainer(state, containerID, runConfigWithCommentCmd) <add> <add> newImage := imageMount.Image().NewChild(image.ChildConfig{ <add> Author: state.maintainer, <add> DiffID: imageMount.DiffID(), <add> ContainerConfig: runConfigWithCommentCmd, <add> // TODO: ContainerID? <add> // TODO: Config? <add> }) <add> return b.exportImage(state, newImage) <ide> } <ide> <ide> // For backwards compat, if there's just one info then use it as the <ide> func (b *Builder) probeCache(dispatchState *dispatchState, runConfig *container. <ide> fmt.Fprint(b.Stdout, " ---> Using cache\n") <ide> <ide> dispatchState.imageID = string(cachedID) <del> b.buildStages.update(dispatchState.imageID, runConfig) <add> b.buildStages.update(dispatchState.imageID) <ide> return true, nil <ide> } <ide> <ide><path>builder/dockerfile/mockbackend_test.go <ide> package dockerfile <ide> <ide> import ( <add> "encoding/json" <ide> "io" <ide> <ide> "github.com/docker/docker/api/types" <ide> "github.com/docker/docker/api/types/backend" <ide> "github.com/docker/docker/api/types/container" <ide> "github.com/docker/docker/builder" <ide> containerpkg "github.com/docker/docker/container" <add> "github.com/docker/docker/image" <add> "github.com/docker/docker/layer" <add> "github.com/docker/docker/pkg/idtools" <ide> "golang.org/x/net/context" <ide> ) <ide> <ide> func (m *MockBackend) MakeImageCache(cacheFrom []string) builder.ImageCache { <ide> return nil <ide> } <ide> <add>func (m *MockBackend) CreateImage(config []byte, parent string) (string, error) { <add> return "c411d1d", nil <add>} <add> <add>func (m *MockBackend) IDMappings() *idtools.IDMappings { <add> return &idtools.IDMappings{} <add>} <add> <ide> type mockImage struct { <ide> id string <ide> config *container.Config <ide> func (i *mockImage) RunConfig() *container.Config { <ide> return i.config <ide> } <ide> <add>func (i *mockImage) MarshalJSON() ([]byte, error) { <add> type rawImage mockImage <add> return json.Marshal(rawImage(*i)) <add>} <add> <add>func (i *mockImage) NewChild(child image.ChildConfig) *image.Image { <add> return nil <add>} <add> <ide> type mockImageCache struct { <ide> getCacheFunc func(parentID string, cfg *container.Config) (string, error) <ide> } <ide> func (l *mockLayer) Release() error { <ide> func (l *mockLayer) Mount() (string, error) { <ide> return "mountPath", nil <ide> } <add> <add>func (l *mockLayer) DiffID() layer.DiffID { <add> return layer.DiffID("abcdef12345") <add>} <ide><path>daemon/archive.go <ide> import ( <ide> "github.com/docker/docker/container" <ide> "github.com/docker/docker/pkg/archive" <ide> "github.com/docker/docker/pkg/chrootarchive" <del> "github.com/docker/docker/pkg/idtools" <ide> "github.com/docker/docker/pkg/ioutils" <del> "github.com/docker/docker/pkg/symlink" <ide> "github.com/docker/docker/pkg/system" <ide> "github.com/pkg/errors" <ide> ) <ide> func (daemon *Daemon) containerCopy(container *container.Container, resource str <ide> }) <ide> daemon.LogContainerEvent(container, "copy") <ide> return reader, nil <del>} <del> <del>// CopyOnBuild copies/extracts a source FileInfo to a destination path inside a container <del>// specified by a container object. <del>// TODO: make sure callers don't unnecessarily convert destPath with filepath.FromSlash (Copy does it already). <del>// CopyOnBuild should take in abstract paths (with slashes) and the implementation should convert it to OS-specific paths. <del>func (daemon *Daemon) CopyOnBuild(cID, destPath, srcRoot, srcPath string, decompress bool) error { <del> fullSrcPath, err := symlink.FollowSymlinkInScope(filepath.Join(srcRoot, srcPath), srcRoot) <del> if err != nil { <del> return err <del> } <del> <del> destExists := true <del> destDir := false <del> rootIDs := daemon.idMappings.RootPair() <del> <del> // Work in daemon-local OS specific file paths <del> destPath = filepath.FromSlash(destPath) <del> <del> c, err := daemon.GetContainer(cID) <del> if err != nil { <del> return err <del> } <del> err = daemon.Mount(c) <del> if err != nil { <del> return err <del> } <del> defer daemon.Unmount(c) <del> <del> dest, err := c.GetResourcePath(destPath) <del> if err != nil { <del> return err <del> } <del> <del> // Preserve the trailing slash <del> // TODO: why are we appending another path separator if there was already one? <del> if strings.HasSuffix(destPath, string(os.PathSeparator)) || destPath == "." { <del> destDir = true <del> dest += string(os.PathSeparator) <del> } <del> <del> destPath = dest <del> <del> destStat, err := os.Stat(destPath) <del> if err != nil { <del> if !os.IsNotExist(err) { <del> //logrus.Errorf("Error performing os.Stat on %s. %s", destPath, err) <del> return err <del> } <del> destExists = false <del> } <del> <del> archiver := chrootarchive.NewArchiver(daemon.idMappings) <del> src, err := os.Stat(fullSrcPath) <del> if err != nil { <del> return err <del> } <del> <del> if src.IsDir() { <del> // copy as directory <del> if err := archiver.CopyWithTar(fullSrcPath, destPath); err != nil { <del> return err <del> } <del> return fixPermissions(fullSrcPath, destPath, rootIDs.UID, rootIDs.GID, destExists) <del> } <del> if decompress && archive.IsArchivePath(fullSrcPath) { <del> // Only try to untar if it is a file and that we've been told to decompress (when ADD-ing a remote file) <del> <del> // First try to unpack the source as an archive <del> // to support the untar feature we need to clean up the path a little bit <del> // because tar is very forgiving. First we need to strip off the archive's <del> // filename from the path but this is only added if it does not end in slash <del> tarDest := destPath <del> if strings.HasSuffix(tarDest, string(os.PathSeparator)) { <del> tarDest = filepath.Dir(destPath) <del> } <del> <del> // try to successfully untar the orig <del> err := archiver.UntarPath(fullSrcPath, tarDest) <del> /* <del> if err != nil { <del> logrus.Errorf("Couldn't untar to %s: %v", tarDest, err) <del> } <del> */ <del> return err <del> } <del> <del> // only needed for fixPermissions, but might as well put it before CopyFileWithTar <del> if destDir || (destExists && destStat.IsDir()) { <del> destPath = filepath.Join(destPath, filepath.Base(srcPath)) <del> } <del> <del> if err := idtools.MkdirAllAndChownNew(filepath.Dir(destPath), 0755, rootIDs); err != nil { <del> return err <del> } <del> if err := archiver.CopyFileWithTar(fullSrcPath, destPath); err != nil { <del> return err <del> } <del> <del> return fixPermissions(fullSrcPath, destPath, rootIDs.UID, rootIDs.GID, destExists) <del>} <add>} <ide>\ No newline at end of file <ide><path>daemon/archive_unix.go <ide> package daemon <ide> <ide> import ( <del> "os" <del> "path/filepath" <del> <ide> "github.com/docker/docker/container" <ide> ) <ide> <ide> func checkIfPathIsInAVolume(container *container.Container, absPath string) (boo <ide> return toVolume, nil <ide> } <ide> <del>func fixPermissions(source, destination string, uid, gid int, destExisted bool) error { <del> // If the destination didn't already exist, or the destination isn't a <del> // directory, then we should Lchown the destination. Otherwise, we shouldn't <del> // Lchown the destination. <del> destStat, err := os.Stat(destination) <del> if err != nil { <del> // This should *never* be reached, because the destination must've already <del> // been created while untar-ing the context. <del> return err <del> } <del> doChownDestination := !destExisted || !destStat.IsDir() <del> <del> // We Walk on the source rather than on the destination because we don't <del> // want to change permissions on things we haven't created or modified. <del> return filepath.Walk(source, func(fullpath string, info os.FileInfo, err error) error { <del> // Do not alter the walk root iff. it existed before, as it doesn't fall under <del> // the domain of "things we should chown". <del> if !doChownDestination && (source == fullpath) { <del> return nil <del> } <del> <del> // Path is prefixed by source: substitute with destination instead. <del> cleaned, err := filepath.Rel(source, fullpath) <del> if err != nil { <del> return err <del> } <del> <del> fullpath = filepath.Join(destination, cleaned) <del> return os.Lchown(fullpath, uid, gid) <del> }) <del>} <del> <ide> // isOnlineFSOperationPermitted returns an error if an online filesystem operation <ide> // is not permitted. <ide> func (daemon *Daemon) isOnlineFSOperationPermitted(container *container.Container) error { <ide><path>daemon/archive_windows.go <ide> func checkIfPathIsInAVolume(container *container.Container, absPath string) (boo <ide> return false, nil <ide> } <ide> <del>func fixPermissions(source, destination string, uid, gid int, destExisted bool) error { <del> // chown is not supported on Windows <del> return nil <del>} <del> <ide> // isOnlineFSOperationPermitted returns an error if an online filesystem operation <ide> // is not permitted (such as stat or for copying). Running Hyper-V containers <ide> // cannot have their file-system interrogated from the host as the filter is <ide><path>daemon/build.go <ide> import ( <ide> "github.com/docker/docker/builder" <ide> "github.com/docker/docker/image" <ide> "github.com/docker/docker/layer" <add> "github.com/docker/docker/pkg/idtools" <ide> "github.com/docker/docker/pkg/stringid" <ide> "github.com/docker/docker/registry" <ide> "github.com/pkg/errors" <ide> func (rl *releaseableLayer) Release() error { <ide> return rl.releaseROLayer() <ide> } <ide> <add>func (rl *releaseableLayer) DiffID() layer.DiffID { <add> return rl.roLayer.DiffID() <add>} <add> <ide> func (rl *releaseableLayer) releaseRWLayer() error { <ide> if rl.rwLayer == nil { <ide> return nil <ide> func (daemon *Daemon) GetImageAndReleasableLayer(ctx context.Context, refOrID st <ide> layer, err := newReleasableLayerForImage(image, daemon.layerStore) <ide> return image, layer, err <ide> } <add> <add>// CreateImage creates a new image by adding a config and ID to the image store. <add>// This is similar to LoadImage() except that it receives JSON encoded bytes of <add>// an image instead of a tar archive. <add>func (daemon *Daemon) CreateImage(config []byte, parent string) (string, error) { <add> id, err := daemon.imageStore.Create(config) <add> if err != nil { <add> return "", err <add> } <add> <add> if parent != "" { <add> if err := daemon.imageStore.SetParent(id, image.ID(parent)); err != nil { <add> return "", err <add> } <add> } <add> // TODO: do we need any daemon.LogContainerEventWithAttributes? <add> return id.String(), nil <add>} <add> <add>// IDMappings returns uid/gid mappings for the builder <add>func (daemon *Daemon) IDMappings() *idtools.IDMappings { <add> return daemon.idMappings <add>} <ide><path>daemon/commit.go <ide> import ( <ide> containertypes "github.com/docker/docker/api/types/container" <ide> "github.com/docker/docker/builder/dockerfile" <ide> "github.com/docker/docker/container" <del> "github.com/docker/docker/dockerversion" <ide> "github.com/docker/docker/image" <ide> "github.com/docker/docker/layer" <ide> "github.com/docker/docker/pkg/ioutils" <ide> func (daemon *Daemon) Commit(name string, c *backend.ContainerCommitConfig) (str <ide> return "", err <ide> } <ide> <del> containerConfig := c.ContainerConfig <del> if containerConfig == nil { <del> containerConfig = container.Config <del> } <del> <ide> // It is not possible to commit a running container on Windows and on Solaris. <ide> if (runtime.GOOS == "windows" || runtime.GOOS == "solaris") && container.IsRunning() { <ide> return "", errors.Errorf("%+v does not support commit of a running container", runtime.GOOS) <ide> func (daemon *Daemon) Commit(name string, c *backend.ContainerCommitConfig) (str <ide> } <ide> }() <ide> <del> var history []image.History <del> rootFS := image.NewRootFS() <del> osVersion := "" <del> var osFeatures []string <del> <del> if container.ImageID != "" { <del> img, err := daemon.imageStore.Get(container.ImageID) <add> var parent *image.Image <add> if container.ImageID == "" { <add> parent = new(image.Image) <add> parent.RootFS = image.NewRootFS() <add> } else { <add> parent, err = daemon.imageStore.Get(container.ImageID) <ide> if err != nil { <ide> return "", err <ide> } <del> history = img.History <del> rootFS = img.RootFS <del> osVersion = img.OSVersion <del> osFeatures = img.OSFeatures <ide> } <ide> <del> l, err := daemon.layerStore.Register(rwTar, rootFS.ChainID()) <add> l, err := daemon.layerStore.Register(rwTar, parent.RootFS.ChainID()) <ide> if err != nil { <ide> return "", err <ide> } <ide> defer layer.ReleaseAndLog(daemon.layerStore, l) <ide> <del> h := image.History{ <del> Author: c.Author, <del> Created: time.Now().UTC(), <del> CreatedBy: strings.Join(containerConfig.Cmd, " "), <del> Comment: c.Comment, <del> EmptyLayer: true, <add> containerConfig := c.ContainerConfig <add> if containerConfig == nil { <add> containerConfig = container.Config <ide> } <del> <del> if diffID := l.DiffID(); layer.DigestSHA256EmptyTar != diffID { <del> h.EmptyLayer = false <del> rootFS.Append(diffID) <add> cc := image.ChildConfig{ <add> ContainerID: container.ID, <add> Author: c.Author, <add> Comment: c.Comment, <add> ContainerConfig: containerConfig, <add> Config: newConfig, <add> DiffID: l.DiffID(), <ide> } <del> <del> history = append(history, h) <del> <del> config, err := json.Marshal(&image.Image{ <del> V1Image: image.V1Image{ <del> DockerVersion: dockerversion.Version, <del> Config: newConfig, <del> Architecture: runtime.GOARCH, <del> OS: runtime.GOOS, <del> Container: container.ID, <del> ContainerConfig: *containerConfig, <del> Author: c.Author, <del> Created: h.Created, <del> }, <del> RootFS: rootFS, <del> History: history, <del> OSFeatures: osFeatures, <del> OSVersion: osVersion, <del> }) <del> <add> config, err := json.Marshal(parent.NewChild(cc)) <ide> if err != nil { <ide> return "", err <ide> } <ide><path>image/image.go <ide> import ( <ide> "time" <ide> <ide> "github.com/docker/docker/api/types/container" <add> "github.com/docker/docker/dockerversion" <add> "github.com/docker/docker/layer" <ide> "github.com/opencontainers/go-digest" <add> "runtime" <add> "strings" <ide> ) <ide> <ide> // ID is the content-addressable ID of an image. <ide> func (img *Image) MarshalJSON() ([]byte, error) { <ide> return json.Marshal(c) <ide> } <ide> <add>// ChildConfig is the configuration to apply to an Image to create a new <add>// Child image. Other properties of the image are copied from the parent. <add>type ChildConfig struct { <add> ContainerID string <add> Author string <add> Comment string <add> DiffID layer.DiffID <add> ContainerConfig *container.Config <add> Config *container.Config <add>} <add> <add>// NewChild creates a new Image as a child of this image. <add>func (img *Image) NewChild(child ChildConfig) *Image { <add> isEmptyLayer := layer.IsEmpty(child.DiffID) <add> rootFS := img.RootFS <add> if !isEmptyLayer { <add> rootFS.Append(child.DiffID) <add> } <add> imgHistory := NewHistory( <add> child.Author, <add> child.Comment, <add> strings.Join(child.ContainerConfig.Cmd, " "), <add> isEmptyLayer) <add> <add> return &Image{ <add> V1Image: V1Image{ <add> DockerVersion: dockerversion.Version, <add> Config: child.Config, <add> Architecture: runtime.GOARCH, <add> OS: runtime.GOOS, <add> Container: child.ContainerID, <add> ContainerConfig: *child.ContainerConfig, <add> Author: child.Author, <add> Created: imgHistory.Created, <add> }, <add> RootFS: rootFS, <add> History: append(img.History, imgHistory), <add> OSFeatures: img.OSFeatures, <add> OSVersion: img.OSVersion, <add> } <add>} <add> <ide> // History stores build commands that were used to create an image <ide> type History struct { <ide> // Created is the timestamp at which the image was created <ide> type History struct { <ide> EmptyLayer bool `json:"empty_layer,omitempty"` <ide> } <ide> <add>// NewHistory creates a new history struct from arguments, and sets the created <add>// time to the current time in UTC <add>func NewHistory(author, comment, createdBy string, isEmptyLayer bool) History { <add> return History{ <add> Author: author, <add> Created: time.Now().UTC(), <add> CreatedBy: createdBy, <add> Comment: comment, <add> EmptyLayer: isEmptyLayer, <add> } <add>} <add> <ide> // Exporter provides interface for loading and saving images <ide> type Exporter interface { <ide> Load(io.ReadCloser, io.Writer, bool) error <ide><path>layer/empty.go <ide> func (el *emptyLayer) DiffSize() (size int64, err error) { <ide> func (el *emptyLayer) Metadata() (map[string]string, error) { <ide> return make(map[string]string), nil <ide> } <add> <add>// IsEmpty returns true if the layer is an EmptyLayer <add>func IsEmpty(diffID DiffID) bool { <add> return diffID == DigestSHA256EmptyTar <add>}
16
PHP
PHP
fix incorrect time handling in deconstruct()
d8bc13f996f69cff47d2aed329a9ce02721a780b
<ide><path>lib/Cake/Model/Model.php <ide> public function deconstruct($field, $data) { <ide> $timeFields = array('H' => 'hour', 'i' => 'min', 's' => 'sec'); <ide> $date = array(); <ide> <del> if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] != 12 && 'pm' == $data['meridian']) { <add> if (isset($data['meridian']) && empty($data['meridian'])) { <add> return null; <add> } <add> <add> if ( <add> isset($data['hour']) && <add> isset($data['meridian']) && <add> !empty($data['hour']) && <add> $data['hour'] != 12 && <add> 'pm' == $data['meridian'] <add> ) { <ide> $data['hour'] = $data['hour'] + 12; <ide> } <ide> if (isset($data['hour']) && isset($data['meridian']) && $data['hour'] == 12 && 'am' == $data['meridian']) { <ide><path>lib/Cake/Test/Case/Model/ModelIntegrationTest.php <ide> public function testSchema() { <ide> } <ide> <ide> /** <del> * test deconstruct() with time fields. <add> * data provider for time tests. <ide> * <add> * @return array <add> */ <add> public static function timeProvider() { <add> $db = ConnectionManager::getDataSource('test'); <add> $now = $db->expression('NOW()'); <add> return array( <add> // blank <add> array( <add> array('hour' => '', 'min' => '', 'meridian' => ''), <add> '' <add> ), <add> // missing hour <add> array( <add> array('hour' => '', 'min' => '00', 'meridian' => 'pm'), <add> '' <add> ), <add> // all blank <add> array( <add> array('hour' => '', 'min' => '', 'sec' => ''), <add> '' <add> ), <add> // set and empty merdian <add> array( <add> array('hour' => '1', 'min' => '00', 'meridian' => ''), <add> '' <add> ), <add> // midnight <add> array( <add> array('hour' => '12', 'min' => '0', 'meridian' => 'am'), <add> '00:00:00' <add> ), <add> array( <add> array('hour' => '00', 'min' => '00'), <add> '00:00:00' <add> ), <add> // 3am <add> array( <add> array('hour' => '03', 'min' => '04', 'sec' => '04'), <add> '03:04:04' <add> ), <add> array( <add> array('hour' => '3', 'min' => '4', 'sec' => '4'), <add> '03:04:04' <add> ), <add> array( <add> array('hour' => '03', 'min' => '4', 'sec' => '4'), <add> '03:04:04' <add> ), <add> array( <add> $now, <add> $now <add> ) <add> ); <add> } <add> <add>/** <add> * test deconstruct with time fields. <add> * <add> * @dataProvider timeProvider <ide> * @return void <ide> */ <del> public function testDeconstructFieldsTime() { <add> public function testDeconstructFieldsTime($input, $result) { <ide> $this->skipIf($this->db instanceof Sqlserver, 'This test is not compatible with SQL Server.'); <ide> <ide> $this->loadFixtures('Apple'); <ide> $TestModel = new Apple(); <ide> <del> $data = array(); <del> $data['Apple']['mytime']['hour'] = ''; <del> $data['Apple']['mytime']['min'] = ''; <del> $data['Apple']['mytime']['sec'] = ''; <del> <del> $TestModel->data = null; <del> $TestModel->set($data); <del> $expected = array('Apple' => array('mytime' => '')); <del> $this->assertEquals($TestModel->data, $expected); <del> <del> $data = array(); <del> $data['Apple']['mytime']['hour'] = ''; <del> $data['Apple']['mytime']['min'] = ''; <del> $data['Apple']['mytime']['meridan'] = ''; <del> <del> $TestModel->data = null; <del> $TestModel->set($data); <del> $expected = array('Apple' => array('mytime' => '')); <del> $this->assertEquals($TestModel->data, $expected, 'Empty values are not returning properly. %s'); <del> <del> $data = array(); <del> $data['Apple']['mytime']['hour'] = '12'; <del> $data['Apple']['mytime']['min'] = '0'; <del> $data['Apple']['mytime']['meridian'] = 'am'; <del> <del> $TestModel->data = null; <del> $TestModel->set($data); <del> $expected = array('Apple' => array('mytime' => '00:00:00')); <del> $this->assertEquals($TestModel->data, $expected, 'Midnight is not returning proper values. %s'); <del> <del> $data = array(); <del> $data['Apple']['mytime']['hour'] = '00'; <del> $data['Apple']['mytime']['min'] = '00'; <del> <del> $TestModel->data = null; <del> $TestModel->set($data); <del> $expected = array('Apple' => array('mytime' => '00:00:00')); <del> $this->assertEquals($TestModel->data, $expected, 'Midnight is not returning proper values. %s'); <del> <del> $data = array(); <del> $data['Apple']['mytime']['hour'] = '03'; <del> $data['Apple']['mytime']['min'] = '04'; <del> $data['Apple']['mytime']['sec'] = '04'; <del> <del> $TestModel->data = null; <del> $TestModel->set($data); <del> $expected = array('Apple' => array('mytime' => '03:04:04')); <del> $this->assertEquals($TestModel->data, $expected); <del> <del> $data = array(); <del> $data['Apple']['mytime']['hour'] = '3'; <del> $data['Apple']['mytime']['min'] = '4'; <del> $data['Apple']['mytime']['sec'] = '4'; <del> <del> $TestModel->data = null; <del> $TestModel->set($data); <del> $expected = array('Apple' => array('mytime' => '03:04:04')); <del> $this->assertEquals($TestModel->data, $expected); <del> <del> $data = array(); <del> $data['Apple']['mytime']['hour'] = '03'; <del> $data['Apple']['mytime']['min'] = '4'; <del> $data['Apple']['mytime']['sec'] = '4'; <add> $data = array( <add> 'Apple' => array( <add> 'mytime' => $input <add> ) <add> ); <ide> <ide> $TestModel->data = null; <ide> $TestModel->set($data); <del> $expected = array('Apple' => array('mytime' => '03:04:04')); <add> $expected = array('Apple' => array('mytime' => $result)); <ide> $this->assertEquals($TestModel->data, $expected); <del> <del> $db = ConnectionManager::getDataSource('test'); <del> $data = array(); <del> $data['Apple']['mytime'] = $db->expression('NOW()'); <del> $TestModel->data = null; <del> $TestModel->set($data); <del> $this->assertEquals($TestModel->data, $data); <ide> } <ide> <ide> /**
2
PHP
PHP
fix lint error
4d962f150c8234e85ea7983f99b7d00a4ec1d4c6
<ide><path>tests/TestCase/Mailer/Transport/SmtpTransportTest.php <ide> public function testConnectEhlo() <ide> $this->socket->expects($this->any()) <ide> ->method('read') <ide> ->will($this->onConsecutiveCalls( <del> "220 Welcome message\r\n", <del> "250 Accepted\r\n" <add> "220 Welcome message\r\n", <add> "250 Accepted\r\n" <ide> )); <ide> $this->socket->expects($this->once())->method('write')->with("EHLO localhost\r\n"); <ide> $this->SmtpTransport->connect();
1
Text
Text
fix valueerror for adversarial_text
7d40b2ac01cbaccf82b34668e5154590dbc815e5
<ide><path>research/adversarial_text/README.md <ide> $ PRETRAIN_DIR=/tmp/models/imdb_pretrain <ide> $ python pretrain.py \ <ide> --train_dir=$PRETRAIN_DIR \ <ide> --data_dir=$IMDB_DATA_DIR \ <del> --vocab_size=86934 \ <add> --vocab_size=87007 \ <ide> --embedding_dims=256 \ <ide> --rnn_cell_size=1024 \ <ide> --num_candidate_samples=1024 \ <ide> $ python train_classifier.py \ <ide> --train_dir=$TRAIN_DIR \ <ide> --pretrained_model_dir=$PRETRAIN_DIR \ <ide> --data_dir=$IMDB_DATA_DIR \ <del> --vocab_size=86934 \ <add> --vocab_size=87007 \ <ide> --embedding_dims=256 \ <ide> --rnn_cell_size=1024 \ <ide> --cl_num_layers=1 \ <ide> $ python evaluate.py \ <ide> --run_once \ <ide> --num_examples=25000 \ <ide> --data_dir=$IMDB_DATA_DIR \ <del> --vocab_size=86934 \ <add> --vocab_size=87007 \ <ide> --embedding_dims=256 \ <ide> --rnn_cell_size=1024 \ <ide> --batch_size=256 \
1
Ruby
Ruby
use the proper encoding comment on the file
48e3c462a2fad7944dcebc54b2ab9fe423f43ffb
<ide><path>activerecord/test/schema/schema.rb <add># encoding: utf-8 <add> <ide> ActiveRecord::Schema.define do <ide> def except(adapter_names_to_exclude) <ide> unless [adapter_names_to_exclude].flatten.include?(adapter_name)
1
Mixed
Text
support all options besides unix sockets
13086f387b28ceea5aff5924e430f41608884a9b
<ide><path>daemon/logger/fluentd/fluentd.go <ide> import ( <ide> "net" <ide> "strconv" <ide> "strings" <add> "time" <ide> <ide> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/daemon/logger" <ide> "github.com/docker/docker/daemon/logger/loggerutils" <add> "github.com/docker/go-units" <ide> "github.com/fluent/fluent-logger-golang/fluent" <ide> ) <ide> <ide> type fluentd struct { <ide> } <ide> <ide> const ( <del> name = "fluentd" <del> defaultHostName = "localhost" <add> name = "fluentd" <add> <add> defaultHost = "127.0.0.1" <ide> defaultPort = 24224 <add> defaultBufferLimit = 1024 * 1024 <ide> defaultTagPrefix = "docker" <del> defaultBufferLimit = 1 * 1024 * 1024 // 1M buffer by default <add> <add> // logger tries to reconnect 2**32 - 1 times <add> // failed (and panic) after 204 years [ 1.5 ** (2**32 - 1) - 1 seconds] <add> defaultRetryWait = 1000 <add> defaultTimeout = 3 * time.Second <add> defaultMaxRetries = math.MaxInt32 <add> defaultReconnectWaitIncreRate = 1.5 <add> <add> addressKey = "fluentd-address" <add> bufferLimitKey = "fluentd-buffer-limit" <add> retryWaitKey = "fluentd-retry-wait" <add> maxRetriesKey = "fluentd-max-retries" <add> asyncConnectKey = "fluentd-async-connect" <ide> ) <ide> <ide> func init() { <ide> func init() { <ide> // the context. Supported context configuration variables are <ide> // fluentd-address & fluentd-tag. <ide> func New(ctx logger.Context) (logger.Logger, error) { <del> host, port, err := parseAddress(ctx.Config["fluentd-address"]) <add> host, port, err := parseAddress(ctx.Config[addressKey]) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func New(ctx logger.Context) (logger.Logger, error) { <ide> if err != nil { <ide> return nil, err <ide> } <add> <ide> extra := ctx.ExtraAttributes(nil) <del> logrus.Debugf("logging driver fluentd configured for container:%s, host:%s, port:%d, tag:%s, extra:%v.", ctx.ContainerID, host, port, tag, extra) <del> // logger tries to reconnect 2**32 - 1 times <del> // failed (and panic) after 204 years [ 1.5 ** (2**32 - 1) - 1 seconds] <del> log, err := fluent.New(fluent.Config{FluentPort: port, FluentHost: host, RetryWait: 1000, MaxRetry: math.MaxInt32}) <add> <add> bufferLimit := defaultBufferLimit <add> if ctx.Config[bufferLimitKey] != "" { <add> bl64, err := units.RAMInBytes(ctx.Config[bufferLimitKey]) <add> if err != nil { <add> return nil, err <add> } <add> bufferLimit = int(bl64) <add> } <add> <add> retryWait := defaultRetryWait <add> if ctx.Config[retryWaitKey] != "" { <add> rwd, err := time.ParseDuration(ctx.Config[retryWaitKey]) <add> if err != nil { <add> return nil, err <add> } <add> retryWait = int(rwd.Seconds() * 1000) <add> } <add> <add> maxRetries := defaultMaxRetries <add> if ctx.Config[maxRetriesKey] != "" { <add> mr64, err := strconv.ParseUint(ctx.Config[maxRetriesKey], 10, strconv.IntSize) <add> if err != nil { <add> return nil, err <add> } <add> maxRetries = int(mr64) <add> } <add> <add> asyncConnect := false <add> if ctx.Config[asyncConnectKey] != "" { <add> if asyncConnect, err = strconv.ParseBool(ctx.Config[asyncConnectKey]); err != nil { <add> return nil, err <add> } <add> } <add> <add> fluentConfig := fluent.Config{ <add> FluentPort: port, <add> FluentHost: host, <add> BufferLimit: bufferLimit, <add> RetryWait: retryWait, <add> MaxRetry: maxRetries, <add> AsyncConnect: asyncConnect, <add> } <add> <add> logrus.WithField("container", ctx.ContainerID).WithField("config", fluentConfig). <add> Debug("logging driver fluentd configured") <add> <add> log, err := fluent.New(fluentConfig) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func (f *fluentd) Name() string { <ide> func ValidateLogOpt(cfg map[string]string) error { <ide> for key := range cfg { <ide> switch key { <del> case "fluentd-address": <add> case "env": <ide> case "fluentd-tag": <del> case "tag": <ide> case "labels": <del> case "env": <add> case "tag": <add> case addressKey: <add> case bufferLimitKey: <add> case retryWaitKey: <add> case maxRetriesKey: <add> case asyncConnectKey: <add> // Accepted <ide> default: <ide> return fmt.Errorf("unknown log opt '%s' for fluentd log driver", key) <ide> } <ide> func ValidateLogOpt(cfg map[string]string) error { <ide> <ide> func parseAddress(address string) (string, int, error) { <ide> if address == "" { <del> return defaultHostName, defaultPort, nil <add> return defaultHost, defaultPort, nil <ide> } <ide> <ide> host, port, err := net.SplitHostPort(address) <ide><path>docs/admin/logging/fluentd.md <ide> connects to this daemon through `localhost:24224` by default. Use the <ide> docker run --log-driver=fluentd --log-opt fluentd-address=myhost.local:24224 <ide> <ide> If container cannot connect to the Fluentd daemon, the container stops <del>immediately. <add>immediately unless the `fluentd-async-connect` option is used. <ide> <ide> ## Options <ide> <ide> the log tag format. <ide> <ide> The `labels` and `env` options each take a comma-separated list of keys. If there is collision between `label` and `env` keys, the value of the `env` takes precedence. Both options add additional fields to the extra attributes of a logging message. <ide> <add>### fluentd-async-connect <add> <add>Docker connects to Fluentd in the background. Messages are buffered until the connection is established. <ide> <ide> ## Fluentd daemon management with Docker <ide> <ide><path>docs/admin/logging/overview.md <ide> run slower but compress more. Default value is 1 (BestSpeed). <ide> You can use the `--log-opt NAME=VALUE` flag to specify these additional Fluentd logging driver options. <ide> <ide> - `fluentd-address`: specify `host:port` to connect [localhost:24224] <del> - `tag`: specify tag for `fluentd` message, <add> - `tag`: specify tag for `fluentd` message <add> - `fluentd-buffer-limit`: specify the maximum size of the fluentd log buffer [8MB] <add> - `fluentd-retry-wait`: initial delay before a connection retry (after which it increases exponentially) [1000ms] <add> - `fluentd-max-retries`: maximum number of connection retries before abrupt failure of docker [1073741824] <add> - `fluentd-async-connect`: whether to block on initial connection or not [false] <ide> <ide> For example, to specify both additional options: <ide> <ide> `docker run --log-driver=fluentd --log-opt fluentd-address=localhost:24224 --log-opt tag=docker.{{.Name}}` <ide> <del>If container cannot connect to the Fluentd daemon on the specified address, <del>the container stops immediately. For detailed information on working with this <del>logging driver, see [the fluentd logging driver](fluentd.md) <add>If container cannot connect to the Fluentd daemon on the specified address and <add>`fluentd-async-connect` is not enabled, the container stops immediately. <add>For detailed information on working with this logging driver, <add>see [the fluentd logging driver](fluentd.md) <ide> <ide> <ide> ## Specify Amazon CloudWatch Logs options
3
Text
Text
fix typos in formula cookbook
87ee0ab3afb407e74162f8b300df5ef14b664916
<ide><path>share/doc/homebrew/Formula-Cookbook.md <ide> so you can override this with `brew create <url> --set-name <name>`. <ide> <ide> A SSL/TLS (https) [`homepage`](http://www.rubydoc.info/github/Homebrew/homebrew/master/Formula#homepage%3D-class_method) is preferred, if one is available. <ide> <del>Try to summarize from the [`homepage`](http://www.rubydoc.info/github/Homebrew/homebrew/master/Formula#homepage%3D-class_method) what the formula does in the [`desc`](http://www.rubydoc.info/github/Homebrew/homebrew/master/Formula#desc%3D-class_method)ription. Note that the [`desc`](http://www.rubydoc.info/github/Homebrew/homebrew/master/Formula#desc%3D-class_method)ription is automatically preprended with the formula name. <add>Try to summarize from the [`homepage`](http://www.rubydoc.info/github/Homebrew/homebrew/master/Formula#homepage%3D-class_method) what the formula does in the [`desc`](http://www.rubydoc.info/github/Homebrew/homebrew/master/Formula#desc%3D-class_method)ription. Note that the [`desc`](http://www.rubydoc.info/github/Homebrew/homebrew/master/Formula#desc%3D-class_method)ription is automatically prepended with the formula name. <ide> <ide> ## Check the build system <ide> <ide> Sometimes there’s hard conflict between formulae, and it can’t be avoided or <ide> `mbedtls` ships and compiles a "Hello World" executable. This is obviously non-essential to `mbedtls`’s functionality, and conflict with the popular GNU `hello` formula would be overkill, so we just remove it. <ide> <ide> [pdftohtml](https://github.com/Homebrew/homebrew/blob/master/Library/Formula/pdftohtml.rb) provides an example of a serious <del>conflict, where both formula ship a identically-named binary that is essential to functionality, so a [`conflicts_with`](http://www.rubydoc.info/github/Homebrew/homebrew/master/Formula#conflicts_with-class_method) is preferable. <add>conflict, where both formula ship an identically-named binary that is essential to functionality, so a [`conflicts_with`](http://www.rubydoc.info/github/Homebrew/homebrew/master/Formula#conflicts_with-class_method) is preferable. <ide> <ide> As a general rule, [`conflicts_with`](http://www.rubydoc.info/github/Homebrew/homebrew/master/Formula#conflicts_with-class_method) should be a last-resort option. It’s a fairly blunt instrument. <ide> <ide> The established standard for Git commit messages is: <ide> <ide> * the first line is a commit summary of *50 characters or less* <ide> * two (2) newlines, then <del>* explain the commit throughly <add>* explain the commit thoroughly <ide> <ide> At Homebrew, we like to put the name of the formula up front like so: `foobar 7.3 (new formula)`. <ide> This may seem crazy short, but you’ll find that forcing yourself to summarise the commit encourages you to be atomic and concise. If you can’t summarise it in 50-80 characters, you’re probably trying to commit two commits as one. For a more thorough explanation, please read Tim Pope’s excellent blog post, [A Note About Git Commit Messages](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html). <ide> When using Homebrew's `gfortran` compiler, the standard `CFLAGS` are used and us <ide> <ide> # How to start over (reset to upstream `master`) <ide> <del>Have you created a real mess in git which stops you from creating a commit you want to submit to us? You might want to consider consider starting again from scratch. Your changes can be reset to the Homebrew's `master` branch by running: <add>Have you created a real mess in git which stops you from creating a commit you want to submit to us? You might want to consider starting again from scratch. Your changes can be reset to the Homebrew's `master` branch by running: <ide> <ide> ```shell <ide> git checkout -f master
1
PHP
PHP
add docblocks to flash methods
ff7ef810ebdf38ad5fbbf0a4481d8a648022dd86
<ide><path>src/Controller/Component/FlashComponent.php <ide> public function __construct(ComponentRegistry $collection, array $config = []) { <ide> $this->_session = $collection->getController()->request->session(); <ide> } <ide> <add>/** <add> * Used to set a session variable that can be used to output messages in the view. <add> * <add> * In your controller: $this->Flash->set('This has been saved'); <add> * <add> * ### Options: <add> * <add> * - `key` The key to set under the session's Message key <add> * - `element` The element used to render the flash message <add> * - `class` The class to give the flash message whenever an element isn't supplied <add> * - `params` An array of variables to make available when using an element <add> * <add> * @param string $message Message to be flashed <add> * @param array $options An array of options <add> * @return void <add> */ <ide> public function set($message, array $options = []) { <ide> $opts = array_merge($this->_defaultConfig, $options); <ide> <ide> public function set($message, array $options = []) { <ide> ]); <ide> } <ide> <add> <add>/** <add> * Magic method for verbose flash methods based on element names. <add> * <add> * @param string $name Element name to use, omitting the "flash_" prefix. <add> * @param array $args Parameters to pass when calling `FlashComponent::set`. <add> * @return void <add> * @throws \Cake\Error\InternalErrorException If missing the flash message. <add>*/ <ide> public function __call($name, $args) { <ide> $options = ['element' => 'flash_' . $name]; <ide> <ide><path>src/View/Helper/FlashHelper.php <ide> class FlashHelper extends Helper { <ide> <ide> use StringTemplateTrait; <ide> <add>/** <add> * Default config for this class <add> * <add> * @var array <add> */ <ide> protected $_defaultConfig = [ <ide> 'templates' => [ <ide> 'flash' => '<div id="{{key}}-message" class="message-{{class}}">{{message}}</div>' <ide> ] <ide> ]; <ide> <add>/** <add> * Used to render the message set in FlashCompnet::set() <add> * <add> * In your view: $this->Flash->out('somekey'); <add> * Will default to flash if no param is passed <add> * <add> * You can pass additional information into the flash message generation. This allows you <add> * to consolidate all the parameters for a given type of flash message into the view. <add> * <add> * {{{ <add> * echo $this->Flash->out('flash', ['class' => 'new-flash']); <add> * }}} <add> * <add> * The above would generate a flash message with a custom class name. Using $attrs['params'] you <add> * can pass additional data into the element rendering that will be made available as local variables <add> * when the element is rendered: <add> * <add> * {{{ <add> * echo $this->Flash->out('flash', ['params' => ['name' => $user['User']['name']]]); <add> * }}} <add> * <add> * This would pass the current user's name into the flash message, so you could create personalized <add> * messages without the controller needing access to that data. <add> * <add> * Lastly you can choose the element that is rendered when creating the flash message. Using <add> * custom elements allows you to fully customize how flash messages are generated. <add> * <add> * {{{ <add> * echo $this->Flash->out('flash', [element' => 'my_custom_element']); <add> * }}} <add> * <add> * If you want to use an element from a plugin for rendering your flash message you can do that using the <add> * plugin param: <add> * <add> * {{{ <add> * echo $this->Session->flash('flash', [ <add> * 'element' => 'my_custom_element', <add> * 'params' => ['plugin' => 'my_plugin']) <add> * ]); <add> * }}} <add> * <add> * @param string $key The [Message.]key you are rendering in the view. <add> * @param array $attrs Additional attributes to use for the creation of this flash message. <add> * Supports the 'params', and 'element' keys that are used in the helper. <add> * @return string <add> */ <ide> public function out($key = 'flash', $attrs = []) { <ide> $flash = $this->request->session()->read("Message.$key"); <ide> $this->request->session()->delete("Message.$key");
2
Ruby
Ruby
remove unused metadata from `bundle` spec
21c502e05fca16948329c600fcb94fcc74243e0b
<ide><path>Library/Homebrew/test/cmd/bundle_spec.rb <ide> # frozen_string_literal: true <ide> <del>describe "brew bundle", :integration_test, :needs_test_cmd_taps do <add>describe "brew bundle", :integration_test do <ide> describe "check" do <ide> it "checks if a Brewfile's dependencies are satisfied", :needs_network do <ide> setup_remote_tap "homebrew/bundle" <ide><path>Library/Homebrew/test/spec_helper.rb <ide> skip "Requires compatibility layer." if ENV["HOMEBREW_NO_COMPAT"] <ide> end <ide> <del> config.before(:each, :needs_official_cmd_taps) do <del> skip "Needs official command Taps." unless ENV["HOMEBREW_TEST_OFFICIAL_CMD_TAPS"] <del> end <del> <ide> config.before(:each, :needs_linux) do <ide> skip "Not on Linux." unless OS.linux? <ide> end
2
Ruby
Ruby
encapsulate "details" into templatedetails
f8f9a085ccf5930a38d7866ab7b7d6532881521e
<ide><path>actionview/lib/action_view.rb <ide> module ActionView <ide> autoload :Rendering <ide> autoload :RoutingUrlFor <ide> autoload :Template <add> autoload :TemplateDetails <ide> autoload :TemplatePath <ide> autoload :UnboundTemplate <ide> autoload :ViewPaths <ide><path>actionview/lib/action_view/template/resolver.rb <ide> class Resolver <ide> Path = ActionView::TemplatePath <ide> deprecate_constant :Path <ide> <del> TemplateDetails = Struct.new(:path, :locale, :handler, :format, :variant) <del> <ide> class PathParser # :nodoc: <add> ParsedPath = Struct.new(:path, :details) <add> <ide> def build_path_regex <ide> handlers = Template::Handlers.extensions.map { |x| Regexp.escape(x) }.join("|") <ide> formats = Template::Types.symbols.map { |x| Regexp.escape(x) }.join("|") <ide> def parse(path) <ide> @regex ||= build_path_regex <ide> match = @regex.match(path) <ide> path = TemplatePath.build(match[:action], match[:prefix] || "", !!match[:partial]) <del> TemplateDetails.new( <del> path, <add> details = TemplateDetails.new( <ide> match[:locale]&.to_sym, <ide> match[:handler]&.to_sym, <ide> match[:format]&.to_sym, <del> match[:variant] <add> match[:variant]&.to_sym <ide> ) <add> ParsedPath.new(path, details) <ide> end <ide> end <ide> <ide> def all_template_paths # :nodoc: <ide> private <ide> def _find_all(name, prefix, partial, details, key, locals) <ide> path = TemplatePath.build(name, prefix, partial) <del> query(path, details, details[:formats], locals, cache: !!key) <add> requested_details = TemplateDetails::Requested.new(**details) <add> query(path, requested_details, locals, cache: !!key) <ide> end <ide> <del> def query(path, details, formats, locals, cache:) <add> def query(path, requested_details, locals, cache:) <ide> cache = cache ? @unbound_templates : Concurrent::Map.new <ide> <ide> unbound_templates = <ide> cache.compute_if_absent(path.virtual) do <ide> unbound_templates_from_path(path) <ide> end <ide> <del> filter_and_sort_by_details(unbound_templates, details).map do |unbound_template| <add> filter_and_sort_by_details(unbound_templates, requested_details).map do |unbound_template| <ide> unbound_template.bind_locals(locals) <ide> end <ide> end <ide> def source_for_template(template) <ide> end <ide> <ide> def build_unbound_template(template) <del> details = @path_parser.parse(template.from(@path.size + 1)) <add> parsed = @path_parser.parse(template.from(@path.size + 1)) <add> details = parsed.details <ide> source = source_for_template(template) <ide> <ide> UnboundTemplate.new( <ide> source, <ide> template, <del> details.handler, <del> virtual_path: details.path.virtual, <del> locale: details.locale, <del> format: details.format, <del> variant: details.variant, <add> details: details, <add> virtual_path: parsed.path.virtual, <ide> ) <ide> end <ide> <ide> def unbound_templates_from_path(path) <ide> end <ide> end <ide> <del> def filter_and_sort_by_details(templates, details) <del> locale = details[:locale] <del> formats = details[:formats] <del> variants = details[:variants] <del> handlers = details[:handlers] <del> <del> results = templates.map do |template| <del> locale_match = details_match_sort_key(template.locale, locale) || next <del> format_match = details_match_sort_key(template.format, formats) || next <del> variant_match = <del> if variants == :any <del> template.variant ? 1 : 0 <del> else <del> details_match_sort_key(template.variant&.to_sym, variants) || next <del> end <del> handler_match = details_match_sort_key(template.handler, handlers) || next <del> <del> [template, [locale_match, format_match, variant_match, handler_match]] <add> def filter_and_sort_by_details(templates, requested_details) <add> filtered_templates = templates.select do |template| <add> template.details.matches?(requested_details) <ide> end <ide> <del> results.compact! <del> results.sort_by!(&:last) if results.size > 1 <del> results.map!(&:first) <del> <del> results <del> end <del> <del> def details_match_sort_key(have, want) <del> if have <del> want.index(have) <del> else <del> want.size <add> if filtered_templates.count > 1 <add> filtered_templates.sort_by! do |template| <add> template.details.sort_key_for(requested_details) <add> end <ide> end <add> <add> filtered_templates <ide> end <ide> <ide> # Safe glob within @path <ide><path>actionview/lib/action_view/template_details.rb <add># frozen_string_literal: true <add> <add>module ActionView <add> class TemplateDetails # :nodoc: <add> class Requested <add> attr_reader :locale, :handlers, :formats, :variants <add> <add> def initialize(locale:, handlers:, formats:, variants:) <add> @locale = locale <add> @handlers = handlers <add> @formats = formats <add> @variants = variants <add> end <add> end <add> <add> attr_reader :locale, :handler, :format, :variant <add> <add> def initialize(locale, handler, format, variant) <add> @locale = locale <add> @handler = handler <add> @format = format <add> @variant = variant <add> end <add> <add> def matches?(requested) <add> return if format && !requested.formats.include?(format) <add> return if locale && !requested.locale.include?(locale) <add> unless requested.variants == :any <add> return if variant && !requested.variants.include?(variant) <add> end <add> return if handler && !requested.handlers.include?(handler) <add> <add> true <add> end <add> <add> def sort_key_for(requested) <add> locale_match = details_match_sort_key(locale, requested.locale) <add> format_match = details_match_sort_key(format, requested.formats) <add> variant_match = <add> if requested.variants == :any <add> variant ? 1 : 0 <add> else <add> details_match_sort_key(variant, requested.variants) <add> end <add> handler_match = details_match_sort_key(handler, requested.handlers) <add> <add> [locale_match, format_match, variant_match, handler_match] <add> end <add> <add> def handler_class <add> Template.handler_for_extension(handler) <add> end <add> <add> def format_or_default <add> format || handler_class.try(:default_format) <add> end <add> <add> private <add> def details_match_sort_key(have, want) <add> if have <add> want.index(have) <add> else <add> want.size <add> end <add> end <add> end <add>end <ide><path>actionview/lib/action_view/unbound_template.rb <ide> <ide> module ActionView <ide> class UnboundTemplate <del> attr_reader :handler, :format, :variant, :locale, :virtual_path <add> attr_reader :virtual_path, :details <add> delegate :locale, :format, :variant, :handler, to: :@details <ide> <del> def initialize(source, identifier, handler, format:, variant:, locale:, virtual_path:) <add> def initialize(source, identifier, details:, virtual_path:) <ide> @source = source <ide> @identifier = identifier <del> @handler = handler <del> <del> @format = format <del> @variant = variant <del> @locale = locale <add> @details = details <ide> @virtual_path = virtual_path <ide> <ide> @templates = Concurrent::Map.new(initial_capacity: 2) <ide> def bind_locals(locals) <ide> <ide> private <ide> def build_template(locals) <del> handler = Template.handler_for_extension(@handler) <del> format = @format || handler.try(:default_format) <del> <ide> Template.new( <ide> @source, <ide> @identifier, <del> handler, <add> details.handler_class, <ide> <del> format: format, <del> variant: @variant, <add> format: details.format_or_default, <add> variant: variant&.to_s, <ide> virtual_path: @virtual_path, <ide> <ide> locals: locals
4
PHP
PHP
add softdeletesintegration test for withcount
4abb185e5a60148676df2333fe36ed9c31f8f480
<ide><path>tests/Database/DatabaseEloquentSoftDeletesIntegrationTest.php <ide> public function testWhereHasWithNestedDeletedRelationshipAndWithTrashedCondition <ide> $this->assertEquals(1, count($users)); <ide> } <ide> <add> /** <add> * @group test <add> */ <add> public function testWithCountWithNestedDeletedRelationshipAndOnlyTrashedCondition() <add> { <add> $this->createUsers(); <add> <add> $abigail = SoftDeletesTestUser::where('email', '[email protected]')->first(); <add> $post1 = $abigail->posts()->create(['title' => 'First Title']); <add> $post1->delete(); <add> $post2 = $abigail->posts()->create(['title' => 'Second Title']); <add> $post3 = $abigail->posts()->create(['title' => 'Third Title']); <add> <add> $user = SoftDeletesTestUser::withCount('posts')->orderBy('postsCount', 'desc')->first(); <add> $this->assertEquals(2, $user->posts_count); <add> <add> $user = SoftDeletesTestUser::withCount(['posts' => function ($q) { <add> $q->onlyTrashed(); <add> }])->orderBy('postsCount', 'desc')->first(); <add> $this->assertEquals(1, $user->posts_count); <add> <add> $user = SoftDeletesTestUser::withCount(['posts' => function ($q) { <add> $q->withTrashed(); <add> }])->orderBy('postsCount', 'desc')->first(); <add> $this->assertEquals(3, $user->posts_count); <add> <add> $user = SoftDeletesTestUser::withCount(['posts' => function ($q) { <add> $q->withTrashed()->where('title', 'First Title'); <add> }])->orderBy('postsCount', 'desc')->first(); <add> $this->assertEquals(1, $user->posts_count); <add> <add> $user = SoftDeletesTestUser::withCount(['posts' => function ($q) { <add> $q->where('title', 'First Title'); <add> }])->orderBy('postsCount', 'desc')->first(); <add> $this->assertEquals(0, $user->posts_count); <add> } <add> <ide> public function testOrWhereWithSoftDeleteConstraint() <ide> { <ide> $this->createUsers();
1
Javascript
Javascript
fix generation of release notes for nightly builds
136ec1474e5f16bd8b6074f2827965950a8e171b
<ide><path>script/vsts/lib/release-notes.js <ide> module.exports.generateForNightly = async function( <ide> ); <ide> } <ide> <del> return output; <add> return output.join('\n'); <ide> }; <ide> <ide> function extractWrittenReleaseNotes(oldReleaseNotes) {
1
Javascript
Javascript
add test for selection.on
9d85f339f806389e0da0ab2019caacccdfec60de
<ide><path>test/core/selection-on-test.js <add>require("../env"); <add>require("../../d3"); <add> <add>var vows = require("vows"), <add> assert = require("assert"); <add> <add>var suite = vows.describe("selection.on"); <add> <add>suite.addBatch({ <add> "select(body)": { <add> topic: function() { <add> return d3.select("body").html(""); <add> }, <add> "registers an event listener for the specified type": function(body) { <add> var form = body.append("form"), count = 0; <add> form.on("submit", function() { ++count; }); // jsdom has spotty event support <add> form.append("input").attr("type", "submit").node().click(); <add> assert.equal(count, 1); <add> }, <add> "replaces an existing event listener for the same type": function(body) { <add> var form = body.append("form"), count = 0, fail = 0; <add> form.on("submit", function() { ++fail; }); <add> form.on("submit", function() { ++count; }); <add> form.append("input").attr("type", "submit").node().click(); <add> assert.equal(count, 1); <add> assert.equal(fail, 0); <add> }, <add> "removes an existing event listener": function(body) { <add> var form = body.append("form"), fail = 0; <add> form.on("submit", function() { ++fail; }); <add> form.on("submit", null); <add> form.append("input").attr("type", "submit").node().click(); <add> assert.equal(fail, 0); <add> }, <add> "ignores removal of non-matching event listener": function(body) { <add> body.append("form").on("submit", null); <add> }, <add> "observes the specified namespace": function(body) { <add> var form = body.append("form"), foo = 0, bar = 0; <add> form.on("submit.foo", function() { ++foo; }); <add> form.on("submit.bar", function() { ++bar; }); <add> form.append("input").attr("type", "submit").node().click(); <add> assert.equal(foo, 1); <add> assert.equal(bar, 1); <add> }, <add> /* <add> Not really sure how to test this one… <add> "observes the specified capture flag": function(body) { <add> }, <add> */ <add> "passes the current data and index to the event listener": function(body) { <add> var forms = body.html("").selectAll("form").data(["a", "b"]).enter().append("form"), dd, ii, data = new Object(); <add> forms.on("submit", function(d, i) { dd = d; ii = i; }); <add> forms.append("input").attr("type", "submit")[0][1].click(); <add> assert.equal(dd, "b"); <add> assert.equal(ii, 1); <add> forms[0][1].__data__ = data; <add> forms.append("input").attr("type", "submit")[0][1].click(); <add> assert.equal(dd, data); <add> assert.equal(ii, 1); <add> }, <add> "uses the current element as the context": function(body) { <add> var forms = body.html("").selectAll("form").data(["a", "b"]).enter().append("form"), context; <add> forms.on("submit", function() { context = this; }); <add> forms.append("input").attr("type", "submit")[0][1].click(); <add> assert.domEqual(context, forms[0][1]); <add> }, <add> "sets the current event as d3.event": function(body) { <add> var form = body.append("form"), event; <add> form.on("submit", function() { event = d3.event; }); <add> form.append("input").attr("type", "submit").node().click(); <add> assert.equal(event.type, "submit"); <add> assert.domEqual(event.target, form[0][0]); <add> }, <add> "restores the original event after notifying listeners": function(body) { <add> var form = body.append("form"), event = d3.event = new Object(); <add> form.on("submit", function() {}); <add> form.append("input").attr("type", "submit").node().click(); <add> assert.equal(d3.event, event); <add> }, <add> "returns the current selection": function(body) { <add> assert.isTrue(body.on("submit", function() {}) === body); <add> } <add> } <add>}); <add> <add>suite.export(module);
1
Text
Text
use code markup/markdown in headers
c956cabcdb55c1b9a1923bcc6f3c96e58f46d1fe
<ide><path>doc/api/perf_hooks.md <ide> doSomeLongRunningProcess(() => { <ide> }); <ide> ``` <ide> <del>## Class: Performance <add>## Class: `Performance` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> <del>### performance.clearMarks(\[name\]) <add>### `performance.clearMarks([name])` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> added: v8.5.0 <ide> If `name` is not provided, removes all `PerformanceMark` objects from the <ide> Performance Timeline. If `name` is provided, removes only the named mark. <ide> <del>### performance.mark(\[name\]) <add>### `performance.mark([name])` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> Creates a new `PerformanceMark` entry in the Performance Timeline. A <ide> `performanceEntry.duration` is always `0`. Performance marks are used <ide> to mark specific significant moments in the Performance Timeline. <ide> <del>### performance.measure(name, startMark, endMark) <add>### `performance.measure(name, startMark, endMark)` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> Performance Timeline or any of the timestamp properties provided by the <ide> `PerformanceNodeTiming` class. If the named `endMark` does not exist, an <ide> error will be thrown. <ide> <del>### performance.nodeTiming <add>### `performance.nodeTiming` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> added: v8.5.0 <ide> An instance of the `PerformanceNodeTiming` class that provides performance <ide> metrics for specific Node.js operational milestones. <ide> <del>### performance.now() <add>### `performance.now()` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> added: v8.5.0 <ide> Returns the current high resolution millisecond timestamp, where 0 represents <ide> the start of the current `node` process. <ide> <del>### performance.timeOrigin <add>### `performance.timeOrigin` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> added: v8.5.0 <ide> The [`timeOrigin`][] specifies the high resolution millisecond timestamp at <ide> which the current `node` process began, measured in Unix time. <ide> <del>### performance.timerify(fn) <add>### `performance.timerify(fn)` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> obs.observe({ entryTypes: ['function'] }); <ide> wrapped(); <ide> ``` <ide> <del>## Class: PerformanceEntry <add>## Class: `PerformanceEntry` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> <del>### performanceEntry.duration <add>### `performanceEntry.duration` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> added: v8.5.0 <ide> The total number of milliseconds elapsed for this entry. This value will not <ide> be meaningful for all Performance Entry types. <ide> <del>### performanceEntry.name <add>### `performanceEntry.name` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> added: v8.5.0 <ide> <ide> The name of the performance entry. <ide> <del>### performanceEntry.startTime <add>### `performanceEntry.startTime` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> added: v8.5.0 <ide> The high resolution millisecond timestamp marking the starting time of the <ide> Performance Entry. <ide> <del>### performanceEntry.entryType <add>### `performanceEntry.entryType` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> added: v8.5.0 <ide> The type of the performance entry. Currently it may be one of: `'node'`, <ide> `'mark'`, `'measure'`, `'gc'`, `'function'`, `'http2'` or `'http'`. <ide> <del>### performanceEntry.kind <add>### `performanceEntry.kind` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> The value may be one of: <ide> * `perf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTAL` <ide> * `perf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB` <ide> <del>## Class: PerformanceNodeTiming extends PerformanceEntry <add>## Class: `PerformanceNodeTiming extends PerformanceEntry` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> <ide> Provides timing details for Node.js itself. <ide> <del>### performanceNodeTiming.bootstrapComplete <add>### `performanceNodeTiming.bootstrapComplete` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> The high resolution millisecond timestamp at which the Node.js process <ide> completed bootstrapping. If bootstrapping has not yet finished, the property <ide> has the value of -1. <ide> <del>### performanceNodeTiming.environment <add>### `performanceNodeTiming.environment` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> added: v8.5.0 <ide> The high resolution millisecond timestamp at which the Node.js environment was <ide> initialized. <ide> <del>### performanceNodeTiming.loopExit <add>### `performanceNodeTiming.loopExit` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> The high resolution millisecond timestamp at which the Node.js event loop <ide> exited. If the event loop has not yet exited, the property has the value of -1. <ide> It can only have a value of not -1 in a handler of the [`'exit'`][] event. <ide> <del>### performanceNodeTiming.loopStart <add>### `performanceNodeTiming.loopStart` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> The high resolution millisecond timestamp at which the Node.js event loop <ide> started. If the event loop has not yet started (e.g., in the first tick of the <ide> main script), the property has the value of -1. <ide> <del>### performanceNodeTiming.nodeStart <add>### `performanceNodeTiming.nodeStart` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> added: v8.5.0 <ide> The high resolution millisecond timestamp at which the Node.js process was <ide> initialized. <ide> <del>### performanceNodeTiming.v8Start <add>### `performanceNodeTiming.v8Start` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> added: v8.5.0 <ide> The high resolution millisecond timestamp at which the V8 platform was <ide> initialized. <ide> <del>## Class: PerformanceObserver <add>## Class: `PerformanceObserver` <ide> <del>### new PerformanceObserver(callback) <add>### `new PerformanceObserver(callback)` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> notified about new `PerformanceEntry` instances. The callback receives a <ide> `PerformanceObserverEntryList` instance and a reference to the <ide> `PerformanceObserver`. <ide> <del>### performanceObserver.disconnect() <add>### `performanceObserver.disconnect()` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> Disconnects the `PerformanceObserver` instance from all notifications. <ide> <del>### performanceObserver.observe(options) <add>### `performanceObserver.observe(options)` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> for (let n = 0; n < 3; n++) <ide> performance.mark(`test${n}`); <ide> ``` <ide> <del>## Class: PerformanceObserverEntryList <add>## Class: `PerformanceObserverEntryList` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> <ide> The `PerformanceObserverEntryList` class is used to provide access to the <ide> `PerformanceEntry` instances passed to a `PerformanceObserver`. <ide> <del>### performanceObserverEntryList.getEntries() <add>### `performanceObserverEntryList.getEntries()` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> added: v8.5.0 <ide> Returns a list of `PerformanceEntry` objects in chronological order <ide> with respect to `performanceEntry.startTime`. <ide> <del>### performanceObserverEntryList.getEntriesByName(name\[, type\]) <add>### `performanceObserverEntryList.getEntriesByName(name[, type])` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> with respect to `performanceEntry.startTime` whose `performanceEntry.name` is <ide> equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to <ide> `type`. <ide> <del>### performanceObserverEntryList.getEntriesByType(type) <add>### `performanceObserverEntryList.getEntriesByType(type)` <ide> <!-- YAML <ide> added: v8.5.0 <ide> --> <ide> Returns a list of `PerformanceEntry` objects in chronological order <ide> with respect to `performanceEntry.startTime` whose `performanceEntry.entryType` <ide> is equal to `type`. <ide> <del>## perf_hooks.monitorEventLoopDelay(\[options\]) <add>## `perf_hooks.monitorEventLoopDelay([options])` <ide> <!-- YAML <ide> added: v11.10.0 <ide> --> <ide> console.log(h.percentile(50)); <ide> console.log(h.percentile(99)); <ide> ``` <ide> <del>### Class: Histogram <add>### Class: `Histogram` <ide> <!-- YAML <ide> added: v11.10.0 <ide> --> <ide> Tracks the event loop delay at a given sampling rate. <ide> <del>#### histogram.disable() <add>#### `histogram.disable()` <ide> <!-- YAML <ide> added: v11.10.0 <ide> --> <ide> added: v11.10.0 <ide> Disables the event loop delay sample timer. Returns `true` if the timer was <ide> stopped, `false` if it was already stopped. <ide> <del>#### histogram.enable() <add>#### `histogram.enable()` <ide> <!-- YAML <ide> added: v11.10.0 <ide> --> <ide> added: v11.10.0 <ide> Enables the event loop delay sample timer. Returns `true` if the timer was <ide> started, `false` if it was already started. <ide> <del>#### histogram.exceeds <add>#### `histogram.exceeds` <ide> <!-- YAML <ide> added: v11.10.0 <ide> --> <ide> added: v11.10.0 <ide> The number of times the event loop delay exceeded the maximum 1 hour event <ide> loop delay threshold. <ide> <del>#### histogram.max <add>#### `histogram.max` <ide> <!-- YAML <ide> added: v11.10.0 <ide> --> <ide> added: v11.10.0 <ide> <ide> The maximum recorded event loop delay. <ide> <del>#### histogram.mean <add>#### `histogram.mean` <ide> <!-- YAML <ide> added: v11.10.0 <ide> --> <ide> added: v11.10.0 <ide> <ide> The mean of the recorded event loop delays. <ide> <del>#### histogram.min <add>#### `histogram.min` <ide> <!-- YAML <ide> added: v11.10.0 <ide> --> <ide> added: v11.10.0 <ide> <ide> The minimum recorded event loop delay. <ide> <del>#### histogram.percentile(percentile) <add>#### `histogram.percentile(percentile)` <ide> <!-- YAML <ide> added: v11.10.0 <ide> --> <ide> added: v11.10.0 <ide> <ide> Returns the value at the given percentile. <ide> <del>#### histogram.percentiles <add>#### `histogram.percentiles` <ide> <!-- YAML <ide> added: v11.10.0 <ide> --> <ide> added: v11.10.0 <ide> <ide> Returns a `Map` object detailing the accumulated percentile distribution. <ide> <del>#### histogram.reset() <add>#### `histogram.reset()` <ide> <!-- YAML <ide> added: v11.10.0 <ide> --> <ide> <ide> Resets the collected histogram data. <ide> <del>#### histogram.stddev <add>#### `histogram.stddev` <ide> <!-- YAML <ide> added: v11.10.0 <ide> -->
1
Ruby
Ruby
return argv from the insert method
36ea8e6a3bb75753dd64032d1a8ebff0ffcdca68
<ide><path>railties/lib/rails/generators/rails/app/app_generator.rb <ide> def handle_rails_rc!(argv) <ide> argv.reject { |arg| arg == '--no-rc' } <ide> else <ide> insert_railsrc_into_argv!(argv, railsrc(argv)) <del> argv <ide> end <ide> end <ide> <ide> def insert_railsrc_into_argv!(argv, railsrc) <ide> extra_args_string = File.read(railsrc) <ide> extra_args = extra_args_string.split(/\n+/).map {|l| l.split}.flatten <ide> puts "Using #{extra_args.join(" ")} from #{railsrc}" <del> argv.insert(1, *extra_args) <add> [argv.first] + extra_args + argv.drop(1) <add> else <add> argv <ide> end <ide> end <ide> end
1
Text
Text
improve readability of testing guide [ci skip]
dcc9bd35e248f9e038c0fbc6a2024cd2d5228cbc
<ide><path>guides/source/testing.md <ide> def test_the_truth <ide> end <ide> ``` <ide> <del>However only the `test` macro allows a more readable test name. You can still use regular method definitions though. <add>Although you can still use regular method definitions, using the `test` macro allows for a more readable test name. <ide> <ide> NOTE: The method name is generated by replacing spaces with underscores. The result does not need to be a valid Ruby identifier though, the name may contain punctuation characters etc. That's because in Ruby technically any string may be a method name. This may require use of `define_method` and `send` calls to function properly, but formally there's little restriction on the name. <ide>
1
PHP
PHP
implement password confirmation
ba3aae6c338314c2ba1779f336278c2532071b7c
<ide><path>app/Http/Controllers/Auth/ConfirmPasswordController.php <add><?php <add> <add>namespace App\Http\Controllers\Auth; <add> <add>use App\Http\Controllers\Controller; <add>use Illuminate\Foundation\Auth\ConfirmsPasswords; <add> <add>class ConfirmPasswordController extends Controller <add>{ <add> /* <add> |-------------------------------------------------------------------------- <add> | Confirm Password Controller <add> |-------------------------------------------------------------------------- <add> | <add> | This controller is responsible for handling password confirmations <add> | and uses a simple trait to include this behavior. You're free to <add> | explore this trait and override any methods you wish to tweak. <add> | <add> */ <add> <add> use ConfirmsPasswords; <add> <add> /** <add> * Where to redirect users when the intended url fails. <add> * <add> * @var string <add> */ <add> protected $redirectTo = '/home'; <add> <add> /** <add> * Create a new controller instance. <add> * <add> * @return void <add> */ <add> public function __construct() <add> { <add> $this->middleware('auth'); <add> } <add>} <ide><path>app/Http/Kernel.php <ide> class Kernel extends HttpKernel <ide> 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class, <ide> 'can' => \Illuminate\Auth\Middleware\Authorize::class, <ide> 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, <add> 'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class, <ide> 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class, <ide> 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, <ide> 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class, <ide><path>config/auth.php <ide> ], <ide> ], <ide> <add> /* <add> |-------------------------------------------------------------------------- <add> | Password Confirmation Timeout <add> |-------------------------------------------------------------------------- <add> | <add> | Here you may specify the amount of seconds before a password confirmation <add> | is timed out and the user's prompted to give their password again on the <add> | confirmation screen. By default the timeout lasts for three hours. <add> | <add> */ <add> <add> 'password_timeout' => 10800, <add> <ide> ];
3
Text
Text
update shell completions instructions
74787ca0eeb3a1d4c19420dced32c9f5965175b0
<ide><path>docs/Shell-Completion.md <ide> Homebrew comes with completion definitions for the `brew` command. Some packages <ide> <ide> `zsh`, `bash` and `fish` are currently supported. <ide> <del>You must configure your shell to enable its completion support. This is because the Homebrew-managed completions are stored under `HOMEBREW_PREFIX` which your system shell may not be aware of, and since it is difficult to automatically configure `bash` and `zsh` completions in a robust manner, the Homebrew installer does not do it for you. <add>Shell completions for built-in Homebrew commands are not automatically installed. To opt-in to using our completions, they need to be linked to `HOMEBREW_PREFIX` by running `brew completions link`. <add> <add>You must then configure your shell to enable its completion support. This is because the Homebrew-managed completions are stored under `HOMEBREW_PREFIX` which your system shell may not be aware of, and since it is difficult to automatically configure `bash` and `zsh` completions in a robust manner, the Homebrew installer does not do it for you. <ide> <ide> ## Configuring Completions in `bash` <ide>
1
Javascript
Javascript
move non-redux to utils
8e87a8991e037e4cb95abaff7d77eafe2242d897
<ide><path>common/app/Panes/redux/index.js <ide> import _ from 'lodash'; <del>import invariant from 'invariant'; <ide> import { <ide> composeReducers, <ide> createAction, <ide> createTypes, <ide> handleActions <ide> } from 'berkeleys-redux-utils'; <ide> <del>import { types as challengeTypes } from '../../routes/Challenges/redux'; <del>import ns from '../ns.json'; <del> <add>import * as utils from './utils.js'; <ide> import windowEpic from './window-epic.js'; <ide> import dividerEpic from './divider-epic.js'; <add>import ns from '../ns.json'; <add>import { types as challengeTypes } from '../../routes/Challenges/redux'; <ide> <ide> export const epics = [ <ide> windowEpic, <ide> export const pressedDividerSelector = <ide> export const widthSelector = state => getNS(state).width; <ide> export const panesMapSelector = state => getNS(state).panesMap; <ide> <del>function isPanesAction({ type } = {}, panesMap) { <del> return !!panesMap[type]; <del>} <del> <del>function getDividerLeft(numOfPanes, index) { <del> let dividerLeft = null; <del> if (numOfPanes > 1 && numOfPanes !== index + 1) { <del> dividerLeft = (100 / numOfPanes) * (index + 1); <del> } <del> return dividerLeft; <del>} <del> <del>function checkForTypeKeys(panesMap) { <del> _.forEach(panesMap, (_, actionType) => { <del> invariant( <del> actionType !== 'undefined', <del> `action type for ${panesMap[actionType]} is undefined` <del> ); <del> }); <del> return panesMap; <del>} <del> <del>const getPane = (panesByName, panes, index) => _.get( <del> panesByName, <del> getPaneName(panes, index), <del> null <del>); <del> <del>const getPaneName = (panes, index) => _.get( <del> panes, <del> index, <del> '' <del>); <del> <del>const createGetBound = isRight => (pane, buffer) => <del> (pane && !pane.isHidden && pane.dividerLeft || (isRight ? 100 : 0)) - buffer; <del>const getRightBound = createGetBound(true); <del>const getLeftBound = createGetBound(false); <del> <del>function normalizePanesMapCreator(createPanesMap) { <del> invariant( <del> _.isFunction(createPanesMap), <del> 'createPanesMap should be a function but got %s', <del> createPanesMap <del> ); <del> const panesMap = createPanesMap({}, { type: '@@panes/test' }); <del> if (typeof panesMap === 'function') { <del> return normalizePanesMapCreator(panesMap); <del> } <del> invariant( <del> !panesMap, <del> 'panesMap test should return undefined or null on test action but got %s', <del> panesMap <del> ); <del> return createPanesMap; <del>} <del> <ide> export default function createPanesAspects({ createPanesMap }) { <del> createPanesMap = normalizePanesMapCreator(createPanesMap); <add> createPanesMap = utils.normalizePanesMapCreator(createPanesMap); <ide> <ide> function middleware({ getState }) { <ide> return next => action => { <ide> let finalAction = action; <ide> const panesMap = panesMapSelector(getState()); <del> if (isPanesAction(action, panesMap)) { <add> if (utils.isPanesAction(action, panesMap)) { <ide> finalAction = { <ide> ...action, <ide> meta: { <ide> export default function createPanesAspects({ createPanesMap }) { <ide> const result = next(finalAction); <ide> const nextPanesMap = createPanesMap(getState(), action); <ide> if (nextPanesMap) { <del> checkForTypeKeys(nextPanesMap); <add> utils.checkForTypeKeys(nextPanesMap); <ide> next(panesMapUpdated(action.type, nextPanesMap)); <ide> } <ide> return result; <ide> export default function createPanesAspects({ createPanesMap }) { <ide> const paneIndex = <ide> _.findIndex(state.panes, ({ name }) => paneName === name); <ide> const currentPane = panesByName[paneName]; <del> const rightPane = getPane(panesByName, panes, paneIndex + 1); <del> const leftPane = getPane(panesByName, panes, paneIndex - 1); <del> const rightBound = getRightBound(rightPane, dividerBuffer); <del> const leftBound = getLeftBound(leftPane, dividerBuffer); <add> const rightPane = utils.getPane(panesByName, panes, paneIndex + 1); <add> const leftPane = utils.getPane(panesByName, panes, paneIndex - 1); <add> const rightBound = utils.getRightBound(rightPane, dividerBuffer); <add> const leftBound = utils.getLeftBound(leftPane, dividerBuffer); <ide> const newPosition = _.clamp( <ide> (clientX / width) * 100, <ide> leftBound, <ide> export default function createPanesAspects({ createPanesMap }) { <ide> panesMap, <ide> panes, <ide> panesByName: panes.reduce((panes, { name }, index) => { <del> const dividerLeft = getDividerLeft(numOfPanes, index); <add> const dividerLeft = utils.getDividerLeft(numOfPanes, index); <ide> panes[name] = { <ide> name, <ide> dividerLeft, <ide> export default function createPanesAspects({ createPanesMap }) { <ide> panesByName: state.panes.reduce( <ide> (panesByName, { name }, index) => { <ide> if (!panesByName[name].isHidden) { <del> const dividerLeft = getDividerLeft( <add> const dividerLeft = utils.getDividerLeft( <ide> numOfPanes, <ide> index - numOfHidden <ide> ); <ide><path>common/app/Panes/redux/utils.js <add>import _ from 'lodash'; <add>import invariant from 'invariant'; <add> <add>export function isPanesAction({ type } = {}, panesMap) { <add> return !!panesMap[type]; <add>} <add> <add>export function getDividerLeft(numOfPanes, index) { <add> let dividerLeft = null; <add> if (numOfPanes > 1 && numOfPanes !== index + 1) { <add> dividerLeft = (100 / numOfPanes) * (index + 1); <add> } <add> return dividerLeft; <add>} <add> <add>export function checkForTypeKeys(panesMap) { <add> _.forEach(panesMap, (_, actionType) => { <add> invariant( <add> actionType !== 'undefined', <add> `action type for ${panesMap[actionType]} is undefined` <add> ); <add> }); <add> return panesMap; <add>} <add> <add>export const getPane = (panesByName, panes, index) => _.get( <add> panesByName, <add> getPaneName(panes, index), <add> null <add>); <add> <add>export const getPaneName = (panes, index) => _.get( <add> panes, <add> [index, 'name'], <add> '' <add>); <add> <add>export const getRightBound = (pane, buffer) => <add> ((pane && !pane.isHidden && pane.dividerLeft) || 100) - buffer; <add>export const getLeftBound = (pane, buffer) => <add> ((pane && !pane.isHidden && pane.dividerLeft) || 0) + buffer; <add> <add>export function normalizePanesMapCreator(createPanesMap) { <add> invariant( <add> _.isFunction(createPanesMap), <add> 'createPanesMap should be a function but got %s', <add> createPanesMap <add> ); <add> const panesMap = createPanesMap({}, { type: '@@panes/test' }); <add> if (typeof panesMap === 'function') { <add> return normalizePanesMapCreator(panesMap); <add> } <add> invariant( <add> !panesMap, <add> 'panesMap test should return undefined or null on test action but got %s', <add> panesMap <add> ); <add> return createPanesMap; <add>} <add>
2
Ruby
Ruby
use parentheses for multi-line method calls
aee1a2802f03d864edc1b856e6461ef8b80a78b5
<ide><path>railties/lib/rails/application.rb <ide> def key_generator <ide> # team. Details at https://github.com/rails/rails/pull/6952#issuecomment-7661220 <ide> @caching_key_generator ||= <ide> if secret_key_base <del> ActiveSupport::CachingKeyGenerator.new \ <add> ActiveSupport::CachingKeyGenerator.new( <ide> ActiveSupport::KeyGenerator.new(secret_key_base, iterations: 1000) <add> ) <ide> else <ide> ActiveSupport::LegacyKeyGenerator.new(secrets.secret_token) <ide> end <ide> def secrets <ide> secrets.secret_token ||= config.secret_token <ide> <ide> if secrets.secret_token.present? <del> ActiveSupport::Deprecation.warn \ <add> ActiveSupport::Deprecation.warn( <ide> "`secrets.secret_token` is deprecated in favor of `secret_key_base` and will be removed in Rails 6.0." <add> ) <ide> end <ide> <ide> secrets <ide> def secret_key_base <ide> if Rails.env.test? || Rails.env.development? <ide> Digest::MD5.hexdigest self.class.name <ide> else <del> validate_secret_key_base \ <add> validate_secret_key_base( <ide> ENV["SECRET_KEY_BASE"] || credentials.secret_key_base || secrets.secret_key_base <add> ) <ide> end <ide> end <ide> <ide> def credentials <ide> # <ide> # Rails.application.encrypted("config/special_tokens.yml.enc", key_path: "config/special_tokens.key") <ide> def encrypted(path, key_path: "config/master.key", env_key: "RAILS_MASTER_KEY") <del> ActiveSupport::EncryptedConfiguration.new \ <add> ActiveSupport::EncryptedConfiguration.new( <ide> config_path: Rails.root.join(path), <ide> key_path: Rails.root.join(key_path), <ide> env_key: env_key <add> ) <ide> end <ide> <ide> def to_app #:nodoc: <ide><path>railties/lib/rails/generators/rails/credentials/credentials_generator.rb <ide> def add_credentials_file_silently(template = nil) <ide> <ide> private <ide> def credentials <del> ActiveSupport::EncryptedConfiguration.new \ <add> ActiveSupport::EncryptedConfiguration.new( <ide> config_path: "config/credentials.yml.enc", <ide> key_path: "config/master.key", <ide> env_key: "RAILS_MASTER_KEY" <add> ) <ide> end <ide> <ide> def credentials_template
2
Javascript
Javascript
remove var in rntester
791fa2d83a615e58b1803c32b342f04c7312c734
<ide><path>RNTester/js/RNTesterExampleContainer.js <ide> const RNTesterPage = require('./RNTesterPage'); <ide> class RNTesterExampleContainer extends React.Component { <ide> renderExample(example, i) { <ide> // Filter platform-specific examples <del> var {title, description, platform} = example; <add> const {description, platform} = example; <add> let {title} = example; <ide> if (platform) { <ide> if (Platform.OS !== platform) { <ide> return null; <ide><path>RNTester/js/RNTesterTitle.js <ide> <ide> 'use strict'; <ide> <del>var React = require('react'); <del>var ReactNative = require('react-native'); <del>var {StyleSheet, Text, View} = ReactNative; <add>const React = require('react'); <add>const ReactNative = require('react-native'); <add>const {StyleSheet, Text, View} = ReactNative; <ide> <ide> class RNTesterTitle extends React.Component<$FlowFixMeProps> { <ide> render() { <ide> class RNTesterTitle extends React.Component<$FlowFixMeProps> { <ide> } <ide> } <ide> <del>var styles = StyleSheet.create({ <add>const styles = StyleSheet.create({ <ide> container: { <ide> borderRadius: 4, <ide> borderWidth: 0.5, <ide><path>RNTester/js/SafeAreaViewExample.js <ide> exports.examples = [ <ide> }, <ide> ]; <ide> <del>var styles = StyleSheet.create({ <add>const styles = StyleSheet.create({ <ide> modal: { <ide> flex: 1, <ide> }, <ide><path>RNTester/js/ScrollViewSimpleExample.js <ide> <ide> 'use strict'; <ide> <del>var React = require('react'); <del>var ReactNative = require('react-native'); <del>var {ScrollView, StyleSheet, Text, TouchableOpacity} = ReactNative; <add>const React = require('react'); <add>const ReactNative = require('react-native'); <add>const {ScrollView, StyleSheet, Text, TouchableOpacity} = ReactNative; <ide> <del>var NUM_ITEMS = 20; <add>const NUM_ITEMS = 20; <ide> <ide> class ScrollViewSimpleExample extends React.Component<{}> { <ide> static title = '<ScrollView>'; <ide> static description = <ide> 'Component that enables scrolling through child components.'; <ide> <ide> makeItems = (nItems: number, styles): Array<any> => { <del> var items = []; <del> for (var i = 0; i < nItems; i++) { <add> const items = []; <add> for (let i = 0; i < nItems; i++) { <ide> items[i] = ( <ide> <TouchableOpacity key={i} style={styles}> <ide> <Text>{'Item ' + i}</Text> <ide> class ScrollViewSimpleExample extends React.Component<{}> { <ide> <ide> render() { <ide> // One of the items is a horizontal scroll view <del> var items = this.makeItems(NUM_ITEMS, styles.itemWrapper); <add> const items = this.makeItems(NUM_ITEMS, styles.itemWrapper); <ide> items[4] = ( <ide> <ScrollView key={'scrollView'} horizontal={true}> <ide> {this.makeItems(NUM_ITEMS, [ <ide> class ScrollViewSimpleExample extends React.Component<{}> { <ide> </ScrollView>, <ide> ); <ide> <del> var verticalScrollView = ( <add> const verticalScrollView = ( <ide> <ScrollView style={styles.verticalScrollView}>{items}</ScrollView> <ide> ); <ide> <ide> return verticalScrollView; <ide> } <ide> } <ide> <del>var styles = StyleSheet.create({ <add>const styles = StyleSheet.create({ <ide> verticalScrollView: { <ide> margin: 10, <ide> }, <ide><path>RNTester/js/SegmentedControlIOSExample.js <ide> <ide> 'use strict'; <ide> <del>var React = require('react'); <del>var ReactNative = require('react-native'); <del>var {SegmentedControlIOS, Text, View, StyleSheet} = ReactNative; <add>const React = require('react'); <add>const ReactNative = require('react-native'); <add>const {SegmentedControlIOS, Text, View, StyleSheet} = ReactNative; <ide> <ide> class BasicSegmentedControlExample extends React.Component<{}> { <ide> render() { <ide> class EventSegmentedControlExample extends React.Component< <ide> }; <ide> } <ide> <del>var styles = StyleSheet.create({ <add>const styles = StyleSheet.create({ <ide> text: { <ide> fontSize: 14, <ide> textAlign: 'center', <ide><path>RNTester/js/ShareExample.js <ide> <ide> 'use strict'; <ide> <del>var React = require('react'); <del>var ReactNative = require('react-native'); <del>var {StyleSheet, View, Text, TouchableHighlight, Share} = ReactNative; <add>const React = require('react'); <add>const ReactNative = require('react-native'); <add>const {StyleSheet, View, Text, TouchableHighlight, Share} = ReactNative; <ide> <ide> exports.framework = 'React'; <ide> exports.title = 'Share'; <ide> class ShareMessageExample extends React.Component<$FlowFixMeProps, any> { <ide> } <ide> } <ide> <del>var styles = StyleSheet.create({ <add>const styles = StyleSheet.create({ <ide> wrapper: { <ide> borderRadius: 5, <ide> marginBottom: 5, <ide><path>RNTester/js/SliderExample.js <ide> <ide> 'use strict'; <ide> <del>var React = require('react'); <del>var ReactNative = require('react-native'); <del>var {Slider, Text, StyleSheet, View} = ReactNative; <add>const React = require('react'); <add>const ReactNative = require('react-native'); <add>const {Slider, Text, StyleSheet, View} = ReactNative; <ide> <ide> class SliderExample extends React.Component<$FlowFixMeProps, $FlowFixMeState> { <ide> static defaultProps = { <ide> class SlidingCompleteExample extends React.Component< <ide> } <ide> } <ide> <del>var styles = StyleSheet.create({ <add>const styles = StyleSheet.create({ <ide> slider: { <ide> height: 10, <ide> margin: 10, <ide><path>RNTester/js/StatusBarExample.js <ide> const examples = [ <ide> <ide> exports.examples = examples; <ide> <del>var styles = StyleSheet.create({ <add>const styles = StyleSheet.create({ <ide> container: { <ide> flex: 1, <ide> justifyContent: 'center', <ide><path>RNTester/js/SwipeableFlatListExample.js <ide> class SwipeableFlatListExample extends React.Component<RNTesterProps> { <ide> } <ide> } <ide> <del>var styles = StyleSheet.create({ <add>const styles = StyleSheet.create({ <ide> row: { <ide> flexDirection: 'row', <ide> justifyContent: 'center', <ide><path>RNTester/js/SwitchExample.js <ide> <ide> 'use strict'; <ide> <del>var React = require('react'); <del>var ReactNative = require('react-native'); <del>var {Platform, Switch, Text, View} = ReactNative; <add>const React = require('react'); <add>const ReactNative = require('react-native'); <add>const {Switch, Text, View} = ReactNative; <ide> <ide> class BasicSwitchExample extends React.Component<{}, $FlowFixMeState> { <ide> state = { <ide> class EventSwitchExample extends React.Component<{}, $FlowFixMeState> { <ide> } <ide> } <ide> <del>var examples = [ <add>const examples = [ <ide> { <ide> title: 'Switches can be set to true or false', <ide> render(): React.Element<any> { <ide><path>RNTester/js/TVEventHandlerExample.js <ide> <ide> 'use strict'; <ide> <del>var React = require('react'); <del>var ReactNative = require('react-native'); <add>const React = require('react'); <add>const ReactNative = require('react-native'); <ide> <del>var { <del> Platform, <del> StyleSheet, <del> View, <del> Text, <del> TouchableOpacity, <del> TVEventHandler, <del>} = ReactNative; <add>const {Platform, View, Text, TouchableOpacity, TVEventHandler} = ReactNative; <ide> <ide> exports.framework = 'React'; <ide> exports.title = 'TVEventHandler example'; <ide><path>RNTester/js/TabBarIOSBarStyleExample.js <ide> <ide> 'use strict'; <ide> <del>var React = require('react'); <del>var ReactNative = require('react-native'); <del>var {StyleSheet, TabBarIOS, Text, View} = ReactNative; <add>const React = require('react'); <add>const ReactNative = require('react-native'); <add>const {StyleSheet, TabBarIOS, Text, View} = ReactNative; <ide> <del>var base64Icon = <add>const base64Icon = <ide> 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABLCAQAAACSR7JhAAADtUlEQVR4Ac3YA2Bj6QLH0XPT1Fzbtm29tW3btm3bfLZtv7e2ObZnms7d8Uw098tuetPzrxv8wiISrtVudrG2JXQZ4VOv+qUfmqCGGl1mqLhoA52oZlb0mrjsnhKpgeUNEs91Z0pd1kvihA3ULGVHiQO2narKSHKkEMulm9VgUyE60s1aWoMQUbpZOWE+kaqs4eLEjdIlZTcFZB0ndc1+lhB1lZrIuk5P2aib1NBpZaL+JaOGIt0ls47SKzLC7CqrlGF6RZ09HGoNy1lYl2aRSWL5GuzqWU1KafRdoRp0iOQEiDzgZPnG6DbldcomadViflnl/cL93tOoVbsOLVM2jylvdWjXolWX1hmfZbGR/wjypDjFLSZIRov09BgYmtUqPQPlQrPapecLgTIy0jMgPKtTeob2zWtrGH3xvjUkPCtNg/tm1rjwrMa+mdUkPd3hWbH0jArPGiU9ufCsNNWFZ40wpwn+62/66R2RUtoso1OB34tnLOcy7YB1fUdc9e0q3yru8PGM773vXsuZ5YIZX+5xmHwHGVvlrGPN6ZSiP1smOsMMde40wKv2VmwPPVXNut4sVpUreZiLBHi0qln/VQeI/LTMYXpsJtFiclUN+5HVZazim+Ky+7sAvxWnvjXrJFneVtLWLyPJu9K3cXLWeOlbMTlrIelbMDlrLenrjEQOtIF+fuI9xRp9ZBFp6+b6WT8RrxEpdK64BuvHgDk+vUy+b5hYk6zfyfs051gRoNO1usU12WWRWL73/MMEy9pMi9qIrR4ZpV16Rrvduxazmy1FSvuFXRkqTnE7m2kdb5U8xGjLw/spRr1uTov4uOgQE+0N/DvFrG/Jt7i/FzwxbA9kDanhf2w+t4V97G8lrT7wc08aA2QNUkuTfW/KimT01wdlfK4yEw030VfT0RtZbzjeMprNq8m8tnSTASrTLti64oBNdpmMQm0eEwvfPwRbUBywG5TzjPCsdwk3IeAXjQblLCoXnDVeoAz6SfJNk5TTzytCNZk/POtTSV40NwOFWzw86wNJRpubpXsn60NJFlHeqlYRbslqZm2jnEZ3qcSKgm0kTli3zZVS7y/iivZTweYXJ26Y+RTbV1zh3hYkgyFGSTKPfRVbRqWWVReaxYeSLarYv1Qqsmh1s95S7G+eEWK0f3jYKTbV6bOwepjfhtafsvUsqrQvrGC8YhmnO9cSCk3yuY984F1vesdHYhWJ5FvASlacshUsajFt2mUM9pqzvKGcyNJW0arTKN1GGGzQlH0tXwLDgQTurS8eIQAAAABJRU5ErkJggg=='; <ide> <ide> class TabBarIOSBarStyleExample extends React.Component<{}> { <ide> class TabBarIOSBarStyleExample extends React.Component<{}> { <ide> } <ide> } <ide> <del>var styles = StyleSheet.create({ <add>const styles = StyleSheet.create({ <ide> tabContent: { <ide> flex: 1, <ide> alignItems: 'center', <ide><path>RNTester/js/TabBarIOSExample.js <ide> <ide> 'use strict'; <ide> <del>var React = require('react'); <del>var ReactNative = require('react-native'); <del>var {StyleSheet, TabBarIOS, Text, View} = ReactNative; <add>const React = require('react'); <add>const ReactNative = require('react-native'); <add>const {StyleSheet, TabBarIOS, Text, View} = ReactNative; <ide> <del>var base64Icon = <add>const base64Icon = <ide> 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABLCAQAAACSR7JhAAADtUlEQVR4Ac3YA2Bj6QLH0XPT1Fzbtm29tW3btm3bfLZtv7e2ObZnms7d8Uw098tuetPzrxv8wiISrtVudrG2JXQZ4VOv+qUfmqCGGl1mqLhoA52oZlb0mrjsnhKpgeUNEs91Z0pd1kvihA3ULGVHiQO2narKSHKkEMulm9VgUyE60s1aWoMQUbpZOWE+kaqs4eLEjdIlZTcFZB0ndc1+lhB1lZrIuk5P2aib1NBpZaL+JaOGIt0ls47SKzLC7CqrlGF6RZ09HGoNy1lYl2aRSWL5GuzqWU1KafRdoRp0iOQEiDzgZPnG6DbldcomadViflnl/cL93tOoVbsOLVM2jylvdWjXolWX1hmfZbGR/wjypDjFLSZIRov09BgYmtUqPQPlQrPapecLgTIy0jMgPKtTeob2zWtrGH3xvjUkPCtNg/tm1rjwrMa+mdUkPd3hWbH0jArPGiU9ufCsNNWFZ40wpwn+62/66R2RUtoso1OB34tnLOcy7YB1fUdc9e0q3yru8PGM773vXsuZ5YIZX+5xmHwHGVvlrGPN6ZSiP1smOsMMde40wKv2VmwPPVXNut4sVpUreZiLBHi0qln/VQeI/LTMYXpsJtFiclUN+5HVZazim+Ky+7sAvxWnvjXrJFneVtLWLyPJu9K3cXLWeOlbMTlrIelbMDlrLenrjEQOtIF+fuI9xRp9ZBFp6+b6WT8RrxEpdK64BuvHgDk+vUy+b5hYk6zfyfs051gRoNO1usU12WWRWL73/MMEy9pMi9qIrR4ZpV16Rrvduxazmy1FSvuFXRkqTnE7m2kdb5U8xGjLw/spRr1uTov4uOgQE+0N/DvFrG/Jt7i/FzwxbA9kDanhf2w+t4V97G8lrT7wc08aA2QNUkuTfW/KimT01wdlfK4yEw030VfT0RtZbzjeMprNq8m8tnSTASrTLti64oBNdpmMQm0eEwvfPwRbUBywG5TzjPCsdwk3IeAXjQblLCoXnDVeoAz6SfJNk5TTzytCNZk/POtTSV40NwOFWzw86wNJRpubpXsn60NJFlHeqlYRbslqZm2jnEZ3qcSKgm0kTli3zZVS7y/iivZTweYXJ26Y+RTbV1zh3hYkgyFGSTKPfRVbRqWWVReaxYeSLarYv1Qqsmh1s95S7G+eEWK0f3jYKTbV6bOwepjfhtafsvUsqrQvrGC8YhmnO9cSCk3yuY984F1vesdHYhWJ5FvASlacshUsajFt2mUM9pqzvKGcyNJW0arTKN1GGGzQlH0tXwLDgQTurS8eIQAAAABJRU5ErkJggg=='; <ide> <ide> class TabBarExample extends React.Component<{}, $FlowFixMeState> { <ide> class TabBarExample extends React.Component<{}, $FlowFixMeState> { <ide> } <ide> } <ide> <del>var styles = StyleSheet.create({ <add>const styles = StyleSheet.create({ <ide> tabContent: { <ide> flex: 1, <ide> alignItems: 'center', <ide><path>RNTester/js/TextExample.android.js <ide> <ide> 'use strict'; <ide> <del>var React = require('react'); <del>var ReactNative = require('react-native'); <del>var {Image, StyleSheet, Text, View} = ReactNative; <del>var RNTesterBlock = require('./RNTesterBlock'); <del>var RNTesterPage = require('./RNTesterPage'); <add>const React = require('react'); <add>const ReactNative = require('react-native'); <add>const {Image, StyleSheet, Text, View} = ReactNative; <add>const RNTesterBlock = require('./RNTesterBlock'); <add>const RNTesterPage = require('./RNTesterPage'); <ide> const TextLegend = require('./Shared/TextLegend'); <ide> <ide> class Entity extends React.Component<$FlowFixMeProps> { <ide> class AttributeToggler extends React.Component<{}, $FlowFixMeState> { <ide> }; <ide> <ide> render() { <del> var curStyle = { <add> const curStyle = { <ide> fontWeight: this.state.fontWeight, <ide> fontSize: this.state.fontSize, <ide> }; <ide> class TextExample extends React.Component<{}> { <ide> } <ide> } <ide> <del>var styles = StyleSheet.create({ <add>const styles = StyleSheet.create({ <ide> backgroundColorText: { <ide> left: 5, <ide> backgroundColor: 'rgba(100, 100, 100, 0.3)', <ide><path>RNTester/js/TextExample.ios.js <ide> class AttributeToggler extends React.Component<{}, $FlowFixMeState> { <ide> }; <ide> <ide> render() { <del> var curStyle = { <add> const curStyle = { <ide> fontWeight: this.state.fontWeight, <ide> fontSize: this.state.fontSize, <ide> }; <ide> class AdjustingFontSize extends React.Component< <ide> <ide> class TextBaseLineLayoutExample extends React.Component<*, *> { <ide> render() { <del> var texts = []; <del> for (var i = 9; i >= 0; i--) { <add> const texts = []; <add> for (let i = 9; i >= 0; i--) { <ide> texts.push( <ide> <Text key={i} style={{fontSize: 8 + i * 5, backgroundColor: '#eee'}}> <ide> {i}
15
Ruby
Ruby
require abstract_unit in parameters tests
b4d9a586bc35e3e611ffdcdc17a3e7bdda6e3323
<ide><path>actionpack/test/controller/parameters/nested_parameters_test.rb <add>require 'abstract_unit' <ide> require 'action_controller/metal/strong_parameters' <ide> <ide> class NestedParametersTest < ActiveSupport::TestCase <ide><path>actionpack/test/controller/parameters/parameters_require_test.rb <add>require 'abstract_unit' <ide> require 'action_controller/metal/strong_parameters' <ide> <ide> class ParametersRequireTest < ActiveSupport::TestCase <ide><path>actionpack/test/controller/parameters/parameters_taint_test.rb <add>require 'abstract_unit' <ide> require 'action_controller/metal/strong_parameters' <ide> <ide> class ParametersTaintTest < ActiveSupport::TestCase
3
Javascript
Javascript
fix typo on max attribute
120b9190ea7b89eb0bcf2c0a63c08e8d75b0f657
<ide><path>src/ng/directive/input.js <ide> var inputType = { <ide> * <ide> * @param {string} ngModel Assignable angular expression to data-bind to. <ide> * @param {string=} name Property name of the form under which the control is published. <del> * @param {string=} min Sets the `min` validation error key if the value entered is less then `min`. <del> * @param {string=} max Sets the `max` validation error key if the value entered is greater then `min`. <add> * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. <add> * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. <ide> * @param {string=} required Sets `required` validation error key if the value is not entered. <ide> * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to <ide> * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
1
Ruby
Ruby
immortalize virtualenvs better
47d57ca99526d47897a0bbe98a1f6a5ba466167f
<ide><path>Library/Homebrew/language/python.rb <ide> def create <ide> f.unlink <ide> f.make_symlink new_target <ide> end <add> <add> Pathname.glob(@venv_root/"lib/python*/orig-prefix.txt").each do |prefix_file| <add> prefix_path = prefix_file.read <add> python = prefix_path.include?("python3") ? "python3" : "python" <add> prefix_path.sub! %r{^#{HOMEBREW_CELLAR}/#{python}/[^/]+}, Formula[python].opt_prefix <add> prefix_file.atomic_write prefix_path <add> end <ide> end <ide> <ide> # Installs packages represented by `targets` into the virtualenv.
1
Ruby
Ruby
record full path to non-core formula
922a4f1b778eb7a0acb03d78f2d0c758f5f6e6e1
<ide><path>Library/Homebrew/formula.rb <ide> class Formula <ide> def initialize name='__UNKNOWN__', path=nil <ide> @name = name <ide> # If we got an explicit path, use that, else determine from the name <del> @path = path.nil? ? self.class.path(name) : Pathname.new(path) <add> @path = path.nil? ? self.class.path(name) : Pathname.new(path).expand_path <ide> @homepage = self.class.homepage <ide> <ide> set_spec :stable
1
Python
Python
change connection message. add snmp client
2fec33adf3c7ad9755d9a2dac85cba75f9ac01a4
<ide><path>glances/core/glances_client.py <ide> def login(self): <ide> # Init screen <ide> self.screen = glancesCurses(args=self.args) <ide> <del> <ide> # Return result <ide> return ret <ide> <ide> def update_snmp(self): <ide> """ <ide> Get stats from SNMP server <ide> Return the client/server connection status: <del> - Connected: Connection OK <add> - SNMP: Connection with SNMP server OK <ide> - Disconnected: Connection NOK <ide> """ <ide> # Update the stats <ide> try: <ide> self.stats.update() <del> except socket.error as e: <add> except: <ide> # Client can not get SNMP server stats <ide> return "Disconnected" <ide> else: <ide> # Grab success <del> return "Connected" <add> return "SNMP" <ide> <ide> def serve_forever(self): <ide> """ <ide><path>glances/outputs/glances_curses.py <ide> def display(self, stats, cs_status="None"): <ide> stats: Stats database to display <ide> cs_status: <ide> "None": standalone or server mode <del> "Connected": Client is connected to the server <add> "Connected": Client is connected to a Glances server <add> "SNMP": Client is connected to a SNMP server <ide> "Disconnected": Client is disconnected from the server <ide> <ide> Return: <ide><path>glances/plugins/glances_system.py <ide> def msg_curse(self, args=None): <ide> if args.cs_status.lower() == "connected": <ide> msg = _("Connected to ") <ide> ret.append(self.curse_add_line(msg, 'OK')) <add> elif args.cs_status.lower() == "snmp": <add> msg = _("SNMP from ") <add> ret.append(self.curse_add_line(msg, 'OK')) <ide> elif args.cs_status.lower() == "disconnected": <ide> msg = _("Disconnected from ") <ide> ret.append(self.curse_add_line(msg, 'CRITICAL'))
3
Mixed
Javascript
validate more properties in expectserror
2a621d40517b8ec17d6b6b15e31bdc6e5d34e768
<ide><path>test/common/README.md <ide> Platform normalizes the `dd` command <ide> Check if there is more than 1gb of total memory. <ide> <ide> ### expectsError([fn, ]settings[, exact]) <del>* `fn` [&lt;Function>] <add>* `fn` [&lt;Function>] a function that should throw. <ide> * `settings` [&lt;Object>] <del> with the following optional properties: <add> that must contain the `code` property plus any of the other following <add> properties (some properties only apply for `AssertionError`): <ide> * `code` [&lt;String>] <del> expected error must have this value for its `code` property <add> expected error must have this value for its `code` property. <ide> * `type` [&lt;Function>] <del> expected error must be an instance of `type` <del> * `message` [&lt;String>] <del> or [&lt;RegExp>] <add> expected error must be an instance of `type` and must be an Error subclass. <add> * `message` [&lt;String>] or [&lt;RegExp>] <ide> if a string is provided for `message`, expected error must have it for its <ide> `message` property; if a regular expression is provided for `message`, the <del> regular expression must match the `message` property of the expected error <add> regular expression must match the `message` property of the expected error. <add> * `name` [&lt;String>] <add> expected error must have this value for its `name` property. <add> * `generatedMessage` [&lt;String>] <add> (`AssertionError` only) expected error must have this value for its <add> `generatedMessage` property. <add> * `actual` &lt;any> <add> (`AssertionError` only) expected error must have this value for its <add> `actual` property. <add> * `expected` &lt;any> <add> (`AssertionError` only) expected error must have this value for its <add> `expected` property. <add> * `operator` &lt;any> <add> (`AssertionError` only) expected error must have this value for its <add> `operator` property. <ide> * `exact` [&lt;Number>] default = 1 <add>* return [&lt;Function>] <ide> <del>* return function suitable for use as a validation function passed as the second <del> argument to e.g. `assert.throws()`. If the returned function has not been <del> called exactly `exact` number of times when the test is complete, then the <del> test will fail. <del> <del>If `fn` is provided, it will be passed to `assert.throws` as first argument. <del> <del>The expected error should be [subclassed by the `internal/errors` module](https://github.com/nodejs/node/blob/master/doc/guides/using-internal-errors.md#api). <add> If `fn` is provided, it will be passed to `assert.throws` as first argument <add> and `undefined` will be returned. <add> Otherwise a function suitable as callback or for use as a validation function <add> passed as the second argument to `assert.throws()` will be returned. If the <add> returned function has not been called exactly `exact` number of times when the <add> test is complete, then the test will fail. <ide> <ide> ### expectWarning(name, expected) <ide> * `name` [&lt;String>] <ide><path>test/common/index.js <ide> Object.defineProperty(exports, 'hasSmallICU', { <ide> }); <ide> <ide> // Useful for testing expected internal/error objects <del>exports.expectsError = function expectsError(fn, options, exact) { <add>exports.expectsError = function expectsError(fn, settings, exact) { <ide> if (typeof fn !== 'function') { <del> exact = options; <del> options = fn; <add> exact = settings; <add> settings = fn; <ide> fn = undefined; <ide> } <del> const { code, type, message } = options; <ide> const innerFn = exports.mustCall(function(error) { <del> assert.strictEqual(error.code, code); <del> if (type !== undefined) { <add> assert.strictEqual(error.code, settings.code); <add> if ('type' in settings) { <add> const type = settings.type; <add> if (type !== Error && !Error.isPrototypeOf(type)) { <add> throw new TypeError('`settings.type` must inherit from `Error`'); <add> } <ide> assert(error instanceof type, <del> `${error} is not the expected type ${type}`); <add> `${error.name} is not instance of ${type.name}`); <add> } <add> if ('message' in settings) { <add> const message = settings.message; <add> if (typeof message === 'string') { <add> assert.strictEqual(error.message, message); <add> } else { <add> assert(message.test(error.message), <add> `${error.message} does not match ${message}`); <add> } <ide> } <del> if (message instanceof RegExp) { <del> assert(message.test(error.message), <del> `${error.message} does not match ${message}`); <del> } else if (typeof message === 'string') { <del> assert.strictEqual(error.message, message); <add> if ('name' in settings) { <add> assert.strictEqual(error.name, settings.name); <add> } <add> if (error.constructor.name === 'AssertionError') { <add> ['generatedMessage', 'actual', 'expected', 'operator'].forEach((key) => { <add> if (key in settings) { <add> const actual = error[key]; <add> const expected = settings[key]; <add> assert.strictEqual(actual, expected, <add> `${key}: expected ${expected}, not ${actual}`); <add> } <add> }); <ide> } <ide> return true; <ide> }, exact); <ide><path>test/parallel/test-internal-errors.js <ide> assert.throws(() => { <ide> }, common.expectsError({ code: 'TEST_ERROR_1', type: RangeError })); <ide> }, common.expectsError({ <ide> code: 'ERR_ASSERTION', <del> message: /^.+ is not the expected type \S/ <add> message: /^.+ is not instance of \S/ <ide> })); <ide> <ide> assert.throws(() => {
3
PHP
PHP
adjust doc blocks
3c18d9581d75868910d047d2d135dca983660a98
<ide><path>src/Illuminate/View/ComponentAttributeBag.php <ide> public function only($keys) <ide> } <ide> <ide> /** <del> * Implode the given attributes into a single HTML ready string. <add> * Merge additional attributes / values into the attribute bag. <ide> * <ide> * @param array $attributes <ide> * @return static <ide> public function setAttributes(array $attributes) <ide> } <ide> <ide> /** <del> * Implode the given attributes into a single HTML ready string. <add> * Merge additional attributes / values into the attribute bag. <ide> * <ide> * @param array $attributes <del> * @return string <add> * @return static <ide> */ <ide> public function __invoke(array $attributeDefaults = []) <ide> {
1
Python
Python
set version to v3.0.0.dev9
25b51f4fc8a102fd1c83d62d078f071823f222eb
<ide><path>spacy/about.py <ide> # fmt: off <ide> __title__ = "spacy" <del>__version__ = "3.0.0.dev8" <add>__version__ = "3.0.0.dev9" <ide> __release__ = True <ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download" <ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json"
1
Javascript
Javascript
handle moment.utc(s) fallback
0ef6ce06d56e56f73efff248001b149c81ecf661
<ide><path>moment.js <ide> 'release. Please refer to ' + <ide> 'https://github.com/moment/moment/issues/1407 for more info.', <ide> function (config) { <del> config._d = new Date(config._i); <add> config._d = new Date(config._i + (config._useUTC ? ' UTC' : '')); <ide> } <ide> ); <ide>
1
PHP
PHP
update isfielderror() to use the context object
5b27f40c1662dfeee7e7eaf371c715de5dd913ae
<ide><path>src/View/Helper/FormHelper.php <ide> protected function _secure($lock, $field, $value = null) { <ide> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::isFieldError <ide> */ <ide> public function isFieldError($field) { <del> $this->setEntity($field); <del> return (bool)$this->tagIsInvalid(); <add> return $this->_getContext()->hasError($field); <ide> } <ide> <ide> /**
1
Text
Text
fix typo in readme
695f03990cdbef12a7224fff29fa4546f76ec8ba
<ide><path>README.md <ide> loaded asynchronously at runtime. This reduces the initial loading time. <ide> webpack can do many optimizations to **reduce the output size of your <ide> JavaScript** by deduplicating frequently used modules, minifying, and giving <ide> you full control of what is loaded initially and what is loaded at runtime <del>through code splitting. It can also can make your code chunks **cache <add>through code splitting. It can also make your code chunks **cache <ide> friendly** by using hashes. <ide> <ide> [Optimization documentation](https://webpack.github.io/docs/optimization.html)
1
Python
Python
correct an issue with loag plugin on windows os
422d3dea01f19b64b5b86574521a38951a5c3329
<ide><path>glances/plugins/glances_load.py <ide> def _getloadavg(self): <ide> pass <ide> try: <ide> return os.getloadavg() <del> except OSError: <add> except (AttributeError, OSError): <ide> return None <ide> <ide> @GlancesPlugin._check_decorator
1
Python
Python
add test for beam parsing
28244df4dafa8b83ea617349c479925663a8d173
<ide><path>spacy/tests/parser/test_beam_parse.py <add>import spacy <add>import pytest <add> <add>@pytest.mark.models <add>def test_beam_parse(): <add> nlp = spacy.load('en_core_web_sm') <add> doc = nlp(u'Australia is a country', disable=['ner']) <add> ents = nlp.entity(doc, beam_width=2) <add> print(ents) <add>
1
Javascript
Javascript
convert functions filter name to camelcase
1ecf31c30ff55a893e434b7608fb9d2d2b37aabb
<ide><path>glances/outputs/static/js/filters.js <ide> import angular from "angular"; <ide> import _ from "lodash"; <ide> <del>function min_size_filter() { <add>function minSizeFilter() { <ide> return function (input, max) { <ide> var max = max || 8; <ide> if (input.length > max) { <ide> function min_size_filter() { <ide> }; <ide> } <ide> <del>function exclamation_filter() { <add>function exclamationFilter() { <ide> return function (input) { <ide> if (input === undefined || input === '') { <ide> return '?'; <ide> function exclamation_filter() { <ide> }; <ide> } <ide> <del>function bytes_filter() { <add>function bytesFilter() { <ide> return function (bytes, low_precision) { <ide> low_precision = low_precision || false; <ide> if (isNaN(parseFloat(bytes)) || !isFinite(bytes) || bytes == 0) { <ide> function bytes_filter() { <ide> } <ide> } <ide> <del>function bits_filter($filter) { <add>function bitsFilter($filter) { <ide> return function (bits, low_precision) { <ide> bits = Math.round(bits) * 8; <ide> return $filter('bytes')(bits, low_precision) + 'b'; <ide> } <ide> } <ide> <del>function leftPad_filter() { <add>function leftPadFilter() { <ide> return function (value, length, chars) { <ide> length = length || 0; <ide> chars = chars || ' '; <ide> return _.padStart(value, length, chars); <ide> } <ide> } <ide> <del>function timemillis_filter() { <add>function timemillisFilter() { <ide> return function (array) { <ide> var sum = 0.0; <ide> for (var i = 0; i < array.length; i++) { <ide> function timemillis_filter() { <ide> } <ide> } <ide> <del>function timedelta_filter($filter) { <add>function timedeltaFilter($filter) { <ide> return function (value) { <ide> var sum = $filter('timemillis')(value); <ide> var d = new Date(sum); <ide> function timedelta_filter($filter) { <ide> } <ide> <ide> export default angular.module("glancesApp") <del> .filter("min_size", min_size_filter) <del> .filter("exclamation", exclamation_filter) <del> .filter("bytes", bytes_filter) <del> .filter("bits", bits_filter) <del> .filter("leftPad", leftPad_filter) <del> .filter("timemillis", timemillis_filter) <del> .filter("timedelta", timedelta_filter); <add> .filter("min_size", minSizeFilter) <add> .filter("exclamation", exclamationFilter) <add> .filter("bytes", bytesFilter) <add> .filter("bits", bitsFilter) <add> .filter("leftPad", leftPadFilter) <add> .filter("timemillis", timemillisFilter) <add> .filter("timedelta", timedeltaFilter);
1
Ruby
Ruby
apply naming suggestions
92bccd2074e7278e3bc71cd2f4c4c92b4b103875
<ide><path>Library/Homebrew/formula.rb <ide> def extract_macho_slice_from(file, arch = Hardware::CPU.arch) <ide> params(base_name: String, shells: T::Array[Symbol], binary: Pathname, cmd: String, <ide> shell_prefix: T.nilable(T.any(Symbol, String))).void <ide> } <del> def generate_completions(base_name: name, <del> shells: [:bash, :zsh, :fish], <del> binary: bin/base_name, <del> cmd: "completion", <del> shell_prefix: nil) <add> def generate_completions_from_executable(base_name: name, <add> shells: [:bash, :zsh, :fish], <add> executable: bin/base_name, <add> cmd: "completion", <add> shell_parameter: nil) <ide> completion_script_path_map = { <ide> bash: bash_completion/base_name, <ide> zsh: zsh_completion/"_#{base_name}", <ide> def generate_completions(base_name: name, <ide> <ide> shells.each do |shell| <ide> script_path = completion_script_path_map[shell] <del> shell_parameter = if shell_prefix.nil? <add> shell_parameter = if shell_parameter.nil? <ide> shell.to_s <del> elsif shell_prefix == :flag <add> elsif shell_parameter == :flag <ide> "--#{shell}" <ide> else <del> "#{shell_prefix}#{shell}" <add> "#{shell_parameter}#{shell}" <ide> end <ide> <ide> script_path.dirname.mkpath <del> script_path.write Utils.safe_popen_read({ "SHELL" => shell }, binary, cmd, shell_parameter) <add> script_path.write Utils.safe_popen_read({ "SHELL" => shell }, executable, cmd, shell_parameter) <ide> end <ide> end <ide>
1
Text
Text
fix typo in the `contributing.md` document
0483c70c8a5c55185f5342d32b4e0e2833e1b0dc
<ide><path>CONTRIBUTING.md <ide> Also, because Atom is so extensible, it's possible that a feature you've become <ide> <ide> #### Package Conventions <ide> <del>Thera are a few conventions that have developed over time around packages: <add>There are a few conventions that have developed over time around packages: <ide> <ide> * Packages that add one or more syntax highlighting grammars are named `language-[language-name]` <ide> * Language packages can add other things besides just a grammar. Many offer commonly-used snippets. Try not to add too much though.
1
Text
Text
add note on unstable versions
943beaec1ed6cbe551db9336a9e8d0c2f87448b5
<ide><path>docs/Versions.md <ide> Versioned formulae we include in [homebrew/core](https://github.com/homebrew/hom <ide> <ide> * Versioned software should build on all Homebrew's supported versions of macOS. <ide> * Versioned formulae should differ in major/minor (not patch) versions from the current stable release. This is because patch versions indicate bug or security updates and we want to ensure you apply security updates. <add>* Unstable versions (alpha, beta, development versions) are not acceptable, not even for versioned formulae. <ide> * Upstream should have a release branch for the versioned formulae version and still make security updates for that version, when necessary. For example, [PHP 5.5 was not a supported version but PHP 7.2 was](https://php.net/supported-versions.php) in January 2018. <ide> * Formulae that depend on versioned formulae must not depend on the same formulae at two different versions twice in their recursive dependencies. For example, if you depend on `[email protected]` and `foo`, and `foo` depends on `openssl` then you must instead use `openssl`. <ide> * Versioned formulae should only be linkable at the same time as their non-versioned counterpart if the upstream project provides support for it, e.g. using suffixed binaries. If this is not possible, use `keg_only :versioned_formula` to allow users to have multiple versions installed at once.
1
Ruby
Ruby
relocate rpaths on macos
8f1cd1288d1bfdd1a48470a8671f7ca940d40426
<ide><path>Library/Homebrew/extend/os/mac/keg_relocate.rb <ide> def relocate_dynamic_linkage(relocation) <ide> <ide> change_install_name(old_name, new_name, file) if new_name <ide> end <add> <add> if ENV["HOMEBREW_RELOCATE_RPATHS"] <add> each_rpath_for(file) do |old_name| <add> if old_name.start_with? relocation.old_cellar <add> new_name = old_name.sub(relocation.old_cellar, relocation.new_cellar) <add> elsif old_name.start_with? relocation.old_prefix <add> new_name = old_name.sub(relocation.old_prefix, relocation.new_prefix) <add> end <add> <add> change_rpath(old_name, new_name, file) if new_name <add> end <add> end <ide> end <ide> end <ide> end <ide> def each_install_name_for(file, &block) <ide> dylibs.each(&block) <ide> end <ide> <add> def each_rpath_for(file, &block) <add> rpaths = file.rpaths <add> rpaths.reject! { |fn| fn =~ /^@(loader|executable)_path/ } <add> rpaths.each(&block) <add> end <add> <ide> def dylib_id_for(file) <ide> # The new dylib ID should have the same basename as the old dylib ID, not <ide> # the basename of the file itself.
1