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 |
|---|---|---|---|---|---|
Javascript | Javascript | add dutch locale | 4c6b47ff932ddd5a0d3e72c8105e4b2826dc8b1b | <ide><path>src/locale/nl-NL.js
<add>import "locale";
<add>
<add>d3.locale.nl_NL = d3.locale({
<add> decimal: ",",
<add> thousands: ".",
<add> grouping: [3],
<add> currency: ["€ ", ""],
<add> dateTime: "%a %e %B %Y %T",
<add> date: "%d-%m-%Y",
<add> time: "%H:%M:%S",
<add> periods: ["AM", "PM"], // unused
<add> days: ["Zondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag"],
<add> shortDays: ["Zo", "Ma", "Di", "Wo", "Do", "Vr", "Za"],
<add> months: ["Januari", "Februari", "Maart", "April", "Mei", "Juni", "Juli", "Augustus", "September", "Oktober", "November", "December"],
<add> shortMonths: ["Jan", "Feb", "Mrt", "Apr", "Mei", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"]
<add>}); | 1 |
Python | Python | add skip logic for attentions test - levit | fd1e67033e9ef79a9a2211f9a97c2ebbf0332b57 | <ide><path>tests/models/levit/test_modeling_levit.py
<ide> def test_inputs_embeds(self):
<ide> def test_model_common_attributes(self):
<ide> pass
<ide>
<add> @unittest.skip(reason="Levit does not output attentions")
<add> def test_attention_outputs(self):
<add> pass
<add>
<ide> def test_forward_signature(self):
<ide> config, _ = self.model_tester.prepare_config_and_inputs_for_common()
<ide> | 1 |
Ruby | Ruby | raise custom error on empty join | 33d0d962b777a98f3bdda0be41ee03acc0410676 | <ide><path>lib/arel.rb
<add>require 'arel/errors'
<add>
<ide> require 'arel/crud'
<ide> require 'arel/factory_methods'
<ide>
<ide><path>lib/arel/errors.rb
<add>module Arel
<add> class ArelError < StandardError
<add> end
<add>
<add> class EmptyJoinError < ArelError
<add> end
<add>end
<ide><path>lib/arel/select_manager.rb
<ide> def join relation, klass = Nodes::InnerJoin
<ide>
<ide> case relation
<ide> when String, Nodes::SqlLiteral
<del> raise if relation.empty?
<add> raise EmptyJoinError if relation.empty?
<ide> klass = Nodes::StringJoin
<ide> end
<ide>
<ide><path>lib/arel/table.rb
<ide> def join relation, klass = Nodes::InnerJoin
<ide>
<ide> case relation
<ide> when String, Nodes::SqlLiteral
<del> raise if relation.empty?
<add> raise EmptyJoinError if relation.empty?
<ide> klass = Nodes::StringJoin
<ide> end
<ide>
<ide><path>test/test_select_manager.rb
<ide> def test_manager_stores_bind_values
<ide> manager = Arel::SelectManager.new
<ide> manager.join(nil).must_equal manager
<ide> end
<add>
<add> it 'raises EmptyJoinError on empty' do
<add> left = Table.new :users
<add> manager = Arel::SelectManager.new
<add>
<add> manager.from left
<add> assert_raises(EmptyJoinError) do
<add> manager.join("")
<add> end
<add> end
<ide> end
<ide>
<ide> describe 'outer join' do
<ide><path>test/test_table.rb
<ide> module Arel
<ide> mgr.to_sql.must_be_like %{ SELECT FROM "users" }
<ide> end
<ide>
<add> it 'raises EmptyJoinError on empty' do
<add> assert_raises(EmptyJoinError) do
<add> @relation.join ""
<add> end
<add> end
<add>
<ide> it 'takes a second argument for join type' do
<ide> right = @relation.alias
<ide> predicate = @relation[:id].eq(right[:id]) | 6 |
PHP | PHP | fix remaining deprecations for table methods | 990eb1cda3edc1595e630b398702bb0a62070ccc | <ide><path>tests/TestCase/Auth/FormAuthenticateTest.php
<ide> public function testAuthenticateSuccess()
<ide> public function testAuthenticateIncludesVirtualFields()
<ide> {
<ide> $users = TableRegistry::get('Users');
<del> $users->entityClass('TestApp\Model\Entity\VirtualUser');
<add> $users->setEntityClass('TestApp\Model\Entity\VirtualUser');
<ide>
<ide> $request = new ServerRequest('posts/index');
<ide> $request->data = [
<ide><path>tests/TestCase/Controller/Component/PaginatorComponentTest.php
<ide> public function setUp()
<ide> $this->registry = new ComponentRegistry($controller);
<ide> $this->Paginator = new PaginatorComponent($this->registry, []);
<ide>
<del> $this->Post = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')
<del> ->disableOriginalConstructor()
<del> ->getMock();
<add> $this->Post = $this->getMockRepository();
<ide> }
<ide>
<ide> /**
<ide> public function testInvalidPaginatorOption()
<ide> public function testPageParamCasting()
<ide> {
<ide> $this->Post->expects($this->any())
<del> ->method('alias')
<add> ->method('getAlias')
<ide> ->will($this->returnValue('Posts'));
<ide>
<ide> $query = $this->_getMockFindQuery();
<ide> public function testValidateSortInvalid()
<ide> */
<ide> public function testValidateSortInvalidDirection()
<ide> {
<del> $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
<add> $model = $this->getMockRepository();
<ide> $model->expects($this->any())
<del> ->method('alias')
<add> ->method('getAlias')
<ide> ->will($this->returnValue('model'));
<ide> $model->expects($this->any())
<ide> ->method('hasField')
<ide> public function testOutOfVeryBigPageNumberGetsClamped()
<ide> */
<ide> public function testValidateSortWhitelistFailure()
<ide> {
<del> $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
<add> $model = $this->getMockRepository();
<ide> $model->expects($this->any())
<del> ->method('alias')
<add> ->method('getAlias')
<ide> ->will($this->returnValue('model'));
<ide> $model->expects($this->any())->method('hasField')->will($this->returnValue(true));
<ide>
<ide> public function testValidateSortWhitelistFailure()
<ide> */
<ide> public function testValidateSortWhitelistTrusted()
<ide> {
<del> $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
<add> $model = $this->getMockRepository();
<ide> $model->expects($this->any())
<del> ->method('alias')
<add> ->method('getAlias')
<ide> ->will($this->returnValue('model'));
<ide> $model->expects($this->once())
<ide> ->method('hasField')
<ide> public function testValidateSortWhitelistTrusted()
<ide> */
<ide> public function testValidateSortWhitelistEmpty()
<ide> {
<del> $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
<add> $model = $this->getMockRepository();
<ide> $model->expects($this->any())
<del> ->method('alias')
<add> ->method('getAlias')
<ide> ->will($this->returnValue('model'));
<ide> $model->expects($this->any())->method('hasField')
<ide> ->will($this->returnValue(true));
<ide> public function testValidateSortWhitelistEmpty()
<ide> */
<ide> public function testValidateSortWhitelistNotInSchema()
<ide> {
<del> $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
<add> $model = $this->getMockRepository();
<ide> $model->expects($this->any())
<del> ->method('alias')
<add> ->method('getAlias')
<ide> ->will($this->returnValue('model'));
<ide> $model->expects($this->once())->method('hasField')
<ide> ->will($this->returnValue(false));
<ide> public function testValidateSortWhitelistNotInSchema()
<ide> */
<ide> public function testValidateSortWhitelistMultiple()
<ide> {
<del> $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
<add> $model = $this->getMockRepository();
<ide> $model->expects($this->any())
<del> ->method('alias')
<add> ->method('getAlias')
<ide> ->will($this->returnValue('model'));
<ide> $model->expects($this->once())
<ide> ->method('hasField')
<ide> public function testValidateSortWhitelistMultiple()
<ide> */
<ide> public function testValidateSortMultiple()
<ide> {
<del> $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
<add> $model = $this->getMockRepository();
<ide> $model->expects($this->any())
<del> ->method('alias')
<add> ->method('getAlias')
<ide> ->will($this->returnValue('model'));
<ide> $model->expects($this->any())->method('hasField')->will($this->returnValue(true));
<ide>
<ide> public function testValidateSortMultiple()
<ide> */
<ide> public function testValidateSortWithString()
<ide> {
<del> $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
<add> $model = $this->getMockRepository();
<ide> $model->expects($this->any())
<del> ->method('alias')
<add> ->method('getAlias')
<ide> ->will($this->returnValue('model'));
<ide> $model->expects($this->any())->method('hasField')->will($this->returnValue(true));
<ide>
<ide> public function testValidateSortWithString()
<ide> */
<ide> public function testValidateSortNoSort()
<ide> {
<del> $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
<add> $model = $this->getMockRepository();
<ide> $model->expects($this->any())
<del> ->method('alias')
<add> ->method('getAlias')
<ide> ->will($this->returnValue('model'));
<ide> $model->expects($this->any())->method('hasField')
<ide> ->will($this->returnValue(true));
<ide> public function testValidateSortNoSort()
<ide> */
<ide> public function testValidateSortInvalidAlias()
<ide> {
<del> $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')->getMock();
<add> $model = $this->getMockRepository();
<ide> $model->expects($this->any())
<del> ->method('alias')
<add> ->method('getAlias')
<ide> ->will($this->returnValue('model'));
<ide> $model->expects($this->any())->method('hasField')->will($this->returnValue(true));
<ide>
<ide> protected function _getMockFindQuery($table = null)
<ide>
<ide> return $query;
<ide> }
<add>
<add> protected function getMockRepository()
<add> {
<add> $model = $this->getMockBuilder('Cake\Datasource\RepositoryInterface')
<add> ->setMethods([
<add> 'getAlias', 'hasField', 'alias', 'find', 'get', 'query', 'updateAll', 'deleteAll',
<add> 'exists', 'save', 'delete', 'newEntity', 'newEntities', 'patchEntity', 'patchEntities'
<add> ])
<add> ->getMock();
<add>
<add> return $model;
<add> }
<add>
<ide> }
<ide><path>tests/TestCase/Database/Schema/TableTest.php
<ide> public function testAddConstraintForeignKey()
<ide> public function testConstraintForeignKey()
<ide> {
<ide> $table = TableRegistry::get('ArticlesTags');
<del> $compositeConstraint = $table->schema()->getConstraint('tag_id_fk');
<add> $compositeConstraint = $table->getSchema()->getConstraint('tag_id_fk');
<ide> $expected = [
<ide> 'type' => 'foreign',
<ide> 'columns' => ['tag_id'],
<ide> public function testConstraintForeignKey()
<ide> $this->assertEquals($expected, $compositeConstraint);
<ide>
<ide> $expectedSubstring = 'CONSTRAINT <tag_id_fk> FOREIGN KEY \(<tag_id>\) REFERENCES <tags> \(<id>\)';
<del> $this->assertQuotedQuery($expectedSubstring, $table->schema()->createSql(ConnectionManager::get('test'))[0]);
<add> $this->assertQuotedQuery($expectedSubstring, $table->getSchema()->createSql(ConnectionManager::get('test'))[0]);
<ide> }
<ide>
<ide> /**
<ide> public function testConstraintForeignKey()
<ide> public function testConstraintForeignKeyTwoColumns()
<ide> {
<ide> $table = TableRegistry::get('Orders');
<del> $compositeConstraint = $table->schema()->getConstraint('product_category_fk');
<add> $compositeConstraint = $table->getSchema()->getConstraint('product_category_fk');
<ide> $expected = [
<ide> 'type' => 'foreign',
<ide> 'columns' => [
<ide> public function testConstraintForeignKeyTwoColumns()
<ide> $expectedSubstring = 'CONSTRAINT <product_category_fk> FOREIGN KEY \(<product_category>, <product_id>\)' .
<ide> ' REFERENCES <products> \(<category>, <id>\)';
<ide>
<del> $this->assertQuotedQuery($expectedSubstring, $table->schema()->createSql(ConnectionManager::get('test'))[0]);
<add> $this->assertQuotedQuery($expectedSubstring, $table->getSchema()->createSql(ConnectionManager::get('test'))[0]);
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Network/Session/DatabaseSessionTest.php
<ide> public function testConstructionSettings()
<ide>
<ide> $session = TableRegistry::get('Sessions');
<ide> $this->assertInstanceOf('Cake\ORM\Table', $session);
<del> $this->assertEquals('Sessions', $session->alias());
<del> $this->assertEquals(ConnectionManager::get('test'), $session->connection());
<del> $this->assertEquals('sessions', $session->table());
<add> $this->assertEquals('Sessions', $session->getAlias());
<add> $this->assertEquals(ConnectionManager::get('test'), $session->getConnection());
<add> $this->assertEquals('sessions', $session->getTable());
<ide> }
<ide>
<ide> /** | 4 |
Javascript | Javascript | add renovationfind app to the showcase | 74eb9a8bb3df1b4164525e87b0c8987db1f58304 | <ide><path>website/src/react-native/showcase.js
<ide> var apps = [
<ide> link: 'https://itunes.apple.com/us/app/reactto36/id989009293?mt=8',
<ide> author: 'Jonathan Solichin',
<ide> },
<add> {
<add> name: 'RenovationFind',
<add> icon: 'http://a2.mzstatic.com/us/r30/Purple3/v4/4f/89/af/4f89af72-9733-2f59-6876-161983a0ee82/icon175x175.png',
<add> link: 'https://itunes.apple.com/ca/app/renovationfind/id1040331641?mt=8',
<add> author: 'Christopher Lord'
<add> },
<ide> {
<ide> name: 'RepairShopr',
<ide> icon: 'http://a3.mzstatic.com/us/r30/Purple69/v4/fa/96/ee/fa96ee57-c5f0-0c6f-1a34-64c9d3266b86/icon175x175.jpeg', | 1 |
Ruby | Ruby | remove useless conditional | 9d549986dd67df15ae45bb679ef1d9b40b4a1252 | <ide><path>activerecord/lib/active_record/transactions.rb
<ide> def restore_transaction_record_state(force = false) #:nodoc
<ide> @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1
<ide> if @_start_transaction_state[:level] < 1
<ide> restore_state = remove_instance_variable(:@_start_transaction_state)
<del> if restore_state
<del> @attributes = @attributes.dup if @attributes.frozen?
<del> @new_record = restore_state[:new_record]
<del> @destroyed = restore_state[:destroyed]
<del> if restore_state.has_key?(:id)
<del> self.id = restore_state[:id]
<del> else
<del> @attributes.delete(self.class.primary_key)
<del> @attributes_cache.delete(self.class.primary_key)
<del> end
<add> @attributes = @attributes.dup if @attributes.frozen?
<add> @new_record = restore_state[:new_record]
<add> @destroyed = restore_state[:destroyed]
<add> if restore_state.has_key?(:id)
<add> self.id = restore_state[:id]
<add> else
<add> @attributes.delete(self.class.primary_key)
<add> @attributes_cache.delete(self.class.primary_key)
<ide> end
<ide> end
<ide> end | 1 |
Ruby | Ruby | fix an error when using multiple gid identifiers | e95e598b43d4468107b23097e44700275d11af5e | <ide><path>lib/action_cable/connection/identification.rb
<ide> def connection_identifier
<ide> def connection_gid(ids)
<ide> ids.map do |o|
<ide> if o.respond_to? :to_global_id
<del> o.to_global_id
<add> o.to_global_id.to_s
<ide> else
<ide> o.to_s
<ide> end | 1 |
Ruby | Ruby | avoid assignment in argument list | 2633f888d40314dee794dfba614c6e42f97f8c8a | <ide><path>Library/Homebrew/extend/ARGV.rb
<ide> def resolved_formulae
<ide> f = Formulary.factory(name, spec)
<ide> if f.any_version_installed?
<ide> tab = Tab.for_formula(f)
<del> resolved_spec = spec(default=nil) || tab.spec
<add> resolved_spec = spec(nil) || tab.spec
<ide> f.set_active_spec(resolved_spec) if f.send(resolved_spec)
<ide> f.build = tab
<ide> end
<ide> f
<ide> else
<ide> rack = Formulary.to_rack(name)
<del> Formulary.from_rack(rack, spec(default=nil))
<add> Formulary.from_rack(rack, spec(nil))
<ide> end
<ide> end
<ide> end | 1 |
PHP | PHP | fix description | fe48f2cff966e1193aab240ffb4c90072aed89e6 | <ide><path>src/Illuminate/Queue/Middleware/ThrottlesExceptions.php
<ide> public function withPrefix(string $prefix)
<ide> }
<ide>
<ide> /**
<del> * Specify the number of seconds a job should be delayed when it is released (before it has reached its max exceptions).
<add> * Specify the number of minutes a job should be delayed when it is released (before it has reached its max exceptions).
<ide> *
<ide> * @param int $backoff
<ide> * @return $this | 1 |
Python | Python | use unicode internally everywhere for 'repr' | 72e08a3e8b6427cb93f0f98b42724e31e5b3d8f9 | <ide><path>rest_framework/compat.py
<ide> import django
<ide>
<ide>
<add>def unicode_repr(instance):
<add> # Get the repr of an instance, but ensure it is a unicode string
<add> # on both python 3 (already the case) and 2 (not the case).
<add> if six.PY2:
<add> repr(instance).decode('utf-8')
<add> return repr(instance)
<add>
<add>
<add>def unicode_to_repr(value):
<add> # Coerce a unicode string to the correct repr return type, depending on
<add> # the Python version. We wrap all our `__repr__` implementations with
<add> # this and then use unicode throughout internally.
<add> if six.PY2:
<add> return value.encode('utf-8')
<add> return value
<add>
<add>
<ide> # OrderedDict only available in Python 2.7.
<ide> # This will always be the case in Django 1.7 and above, as these versions
<ide> # no longer support Python 2.6.
<ide><path>rest_framework/fields.py
<add>from __future__ import unicode_literals
<ide> from django.conf import settings
<ide> from django.core.exceptions import ObjectDoesNotExist
<ide> from django.core.exceptions import ValidationError as DjangoValidationError
<ide> from rest_framework import ISO_8601
<ide> from rest_framework.compat import (
<ide> EmailValidator, MinValueValidator, MaxValueValidator,
<del> MinLengthValidator, MaxLengthValidator, URLValidator, OrderedDict
<add> MinLengthValidator, MaxLengthValidator, URLValidator, OrderedDict,
<add> unicode_repr, unicode_to_repr
<ide> )
<ide> from rest_framework.exceptions import ValidationError
<ide> from rest_framework.settings import api_settings
<ide> def __call__(self):
<ide> return self.default
<ide>
<ide> def __repr__(self):
<del> return '%s(%s)' % (self.__class__.__name__, repr(self.default))
<add> return unicode_to_repr(
<add> '%s(%s)' % (self.__class__.__name__, unicode_repr(self.default))
<add> )
<ide>
<ide>
<ide> class CurrentUserDefault:
<ide> def __call__(self):
<ide> return self.user
<ide>
<ide> def __repr__(self):
<del> return '%s()' % self.__class__.__name__
<add> return unicode_to_repr('%s()' % self.__class__.__name__)
<ide>
<ide>
<ide> class SkipField(Exception):
<ide> def __repr__(self):
<ide> This allows us to create descriptive representations for serializer
<ide> instances that show all the declared fields on the serializer.
<ide> """
<del> return representation.field_repr(self)
<add> return unicode_to_repr(representation.field_repr(self))
<ide>
<ide>
<ide> # Boolean types...
<ide><path>rest_framework/serializers.py
<ide> 2. The process of marshalling between python primitives and request and
<ide> response content is handled by parsers and renderers.
<ide> """
<del>import warnings
<del>
<add>from __future__ import unicode_literals
<ide> from django.db import models
<ide> from django.db.models.fields import FieldDoesNotExist
<ide> from django.utils.translation import ugettext_lazy as _
<del>
<add>from rest_framework.compat import unicode_to_repr
<ide> from rest_framework.utils import model_meta
<ide> from rest_framework.utils.field_mapping import (
<ide> get_url_kwargs, get_field_kwargs,
<ide> UniqueForDateValidator, UniqueForMonthValidator, UniqueForYearValidator,
<ide> UniqueTogetherValidator
<ide> )
<add>import warnings
<ide>
<ide>
<ide> # Note: We do the following so that users of the framework can use this style:
<ide> def validate(self, attrs):
<ide> return attrs
<ide>
<ide> def __repr__(self):
<del> return representation.serializer_repr(self, indent=1)
<add> return unicode_to_repr(representation.serializer_repr(self, indent=1))
<ide>
<ide> # The following are used for accessing `BoundField` instances on the
<ide> # serializer, for the purposes of presenting a form-like API onto the
<ide> def save(self, **kwargs):
<ide> return self.instance
<ide>
<ide> def __repr__(self):
<del> return representation.list_repr(self, indent=1)
<add> return unicode_to_repr(representation.list_repr(self, indent=1))
<ide>
<ide> # Include a backlink to the serializer class on return objects.
<ide> # Allows renderers such as HTMLFormRenderer to get the full field info.
<ide><path>rest_framework/utils/representation.py
<ide> Helper functions for creating user-friendly representations
<ide> of serializer classes and serializer fields.
<ide> """
<add>from __future__ import unicode_literals
<ide> from django.db import models
<ide> from django.utils.encoding import force_text
<ide> from django.utils.functional import Promise
<add>from rest_framework.compat import unicode_repr
<ide> import re
<ide>
<ide>
<ide> def smart_repr(value):
<ide> if isinstance(value, Promise) and value._delegate_text:
<ide> value = force_text(value)
<ide>
<del> value = repr(value)
<add> value = unicode_repr(value)
<ide>
<ide> # Representations like u'help text'
<ide> # should simply be presented as 'help text'
<add> print type(value), value
<ide> if value.startswith("u'") and value.endswith("'"):
<ide> return value[1:]
<ide>
<ide><path>rest_framework/utils/serializer_helpers.py
<add>from __future__ import unicode_literals
<ide> import collections
<del>from rest_framework.compat import OrderedDict
<add>from rest_framework.compat import OrderedDict, unicode_to_repr
<ide>
<ide>
<ide> class ReturnDict(OrderedDict):
<ide> def _proxy_class(self):
<ide> return self._field.__class__
<ide>
<ide> def __repr__(self):
<del> return '<%s value=%s errors=%s>' % (
<add> return unicode_to_repr('<%s value=%s errors=%s>' % (
<ide> self.__class__.__name__, self.value, self.errors
<del> )
<add> ))
<ide>
<ide>
<ide> class NestedBoundField(BoundField):
<ide><path>rest_framework/validators.py
<ide> object creation, and makes it possible to switch between using the implicit
<ide> `ModelSerializer` class and an equivalent explicit `Serializer` class.
<ide> """
<add>from __future__ import unicode_literals
<ide> from django.utils.translation import ugettext_lazy as _
<add>from rest_framework.compat import unicode_to_repr
<ide> from rest_framework.exceptions import ValidationError
<ide> from rest_framework.utils.representation import smart_repr
<ide>
<ide> def __call__(self, value):
<ide> raise ValidationError(self.message)
<ide>
<ide> def __repr__(self):
<del> return '<%s(queryset=%s)>' % (
<add> return unicode_to_repr('<%s(queryset=%s)>' % (
<ide> self.__class__.__name__,
<ide> smart_repr(self.queryset)
<del> )
<add> ))
<ide>
<ide>
<ide> class UniqueTogetherValidator:
<ide> def __call__(self, attrs):
<ide> raise ValidationError(self.message.format(field_names=field_names))
<ide>
<ide> def __repr__(self):
<del> return '<%s(queryset=%s, fields=%s)>' % (
<add> return unicode_to_repr('<%s(queryset=%s, fields=%s)>' % (
<ide> self.__class__.__name__,
<ide> smart_repr(self.queryset),
<ide> smart_repr(self.fields)
<del> )
<add> ))
<ide>
<ide>
<ide> class BaseUniqueForValidator:
<ide> def __call__(self, attrs):
<ide> raise ValidationError({self.field: message})
<ide>
<ide> def __repr__(self):
<del> return '<%s(queryset=%s, field=%s, date_field=%s)>' % (
<add> return unicode_to_repr('<%s(queryset=%s, field=%s, date_field=%s)>' % (
<ide> self.__class__.__name__,
<ide> smart_repr(self.queryset),
<ide> smart_repr(self.field),
<ide> smart_repr(self.date_field)
<del> )
<add> ))
<ide>
<ide>
<ide> class UniqueForDateValidator(BaseUniqueForValidator):
<ide><path>tests/test_fields.py
<ide> def test_allow_blank(self):
<ide> """
<ide> field = serializers.CharField(allow_blank=True)
<ide> output = field.run_validation('')
<del> assert output is ''
<add> assert output == ''
<ide>
<ide> def test_default(self):
<ide> """
<ide> def test_allow_blank(self):
<ide> ]
<ide> )
<ide> output = field.run_validation('')
<del> assert output is ''
<add> assert output == ''
<ide>
<ide>
<ide> class TestChoiceFieldWithType(FieldValues):
<ide><path>tests/test_serializer.py
<add># coding: utf-8
<ide> from __future__ import unicode_literals
<ide> from rest_framework import serializers
<add>from rest_framework.compat import unicode_repr
<ide> import pytest
<ide>
<ide>
<ide> def __init__(self):
<ide> "The serializer field might be named incorrectly and not match any attribute or key on the `ExampleObject` instance.\n"
<ide> "Original exception text was:"
<ide> )
<add>
<add>
<add>class TestUnicodeRepr:
<add> def test_unicode_repr(self):
<add> class ExampleSerializer(serializers.Serializer):
<add> example = serializers.CharField()
<add>
<add> class ExampleObject:
<add> def __init__(self):
<add> self.example = '한국'
<add>
<add> def __repr__(self):
<add> return unicode_repr(self.example)
<add>
<add> instance = ExampleObject()
<add> serializer = ExampleSerializer(instance)
<add> repr(serializer) # Should not error. | 8 |
Text | Text | add translation for titles | 6beda74bae1e916594eb585de89c08a98dcd8e34 | <ide><path>curriculum/challenges/portuguese/03-front-end-libraries/jquery/change-text-inside-an-element-using-jquery.portuguese.md
<ide> videoUrl: ''
<ide> localeTitle: Alterar texto dentro de um elemento usando jQuery
<ide> ---
<ide>
<del>## Description
<add>## Descrição
<ide> <section id="description"> Usando jQuery, você pode alterar o texto entre as tags de início e fim de um elemento. Você pode até mesmo alterar a marcação HTML. jQuery tem uma função chamada <code>.html()</code> que permite adicionar tags HTML e texto dentro de um elemento. Qualquer conteúdo anteriormente dentro do elemento será completamente substituído pelo conteúdo que você fornecer usando essa função. Aqui está como você iria reescrever e enfatizar o texto do nosso título: <code>$("h3").html("<em>jQuery Playground</em>");</code> O jQuery também possui uma função similar chamada <code>.text()</code> que apenas altera o texto sem adicionar tags. Em outras palavras, essa função não avaliará nenhuma tag HTML passada a ela, mas a tratará como o texto com o qual você deseja substituir o conteúdo existente. Altere o botão com o ID <code>target4</code> , enfatizando seu texto. Confira este <a href="https://developer.mozilla.org/en/docs/Web/HTML/Element/em" target="_blank">link</a> para saber mais sobre a diferença entre <code><i></code> e <code><em></code> e seus usos. Observe que, embora a tag <code><i></code> tenha sido usada tradicionalmente para enfatizar o texto, ela já foi cooptada para uso como tag para ícones. A tag <code><em></code> agora é amplamente aceita como a tag para ênfase. Ou trabalharemos para este desafio. </section>
<ide>
<del>## Instructions
<add>## Instruções
<ide> <section id="instructions">
<ide> </section>
<ide>
<del>## Tests
<add>## Testes
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<ide>
<ide> </section>
<ide>
<del>## Challenge Seed
<add>## Desafio
<ide> <section id='challengeSeed'>
<ide>
<ide> <div id='html-seed'>
<ide> tests:
<ide> });
<ide> </script>
<ide>
<del><!-- Only change code above this line. -->
<add><!-- Apenas altere o código acima dessa linha. -->
<ide>
<ide> <div class="container-fluid">
<ide> <h3 class="text-primary text-center">jQuery Playground</h3>
<ide> tests:
<ide>
<ide> </section>
<ide>
<del>## Solution
<add>## Solução
<ide> <section id='solution'>
<ide>
<ide> ```js | 1 |
Javascript | Javascript | fix lint errors | 3b6f98b446b7ac581f555542677afd986523d1f9 | <ide><path>src/selection.js
<ide> class Selection {
<ide> // Remove trailing whitespace from the current line
<ide> const scanRange = this.cursor.getCurrentLineBufferRange()
<ide> let trailingWhitespaceRange = null
<del> this.editor.scanInBufferRange(/[ \t]+$/, scanRange, ({range}) => trailingWhitespaceRange = range)
<add> this.editor.scanInBufferRange(/[ \t]+$/, scanRange, ({range}) => {
<add> trailingWhitespaceRange = range
<add> })
<ide> if (trailingWhitespaceRange) {
<ide> this.setBufferRange(trailingWhitespaceRange)
<ide> this.deleteSelectedText()
<ide> class Selection {
<ide> */
<ide>
<ide> setGoalScreenRange (range) {
<del> return this.goalScreenRange = Range.fromObject(range)
<add> this.goalScreenRange = Range.fromObject(range)
<ide> }
<ide>
<ide> getGoalScreenRange () { | 1 |
PHP | PHP | update minimal.blade.php | 0361686e40835a1f48674cf884d67609018d64b4 | <ide><path>src/Illuminate/Foundation/Exceptions/views/minimal.blade.php
<ide> <div class="ml-4 text-lg text-gray-500 uppercase tracking-wider">
<ide> @yield('message')
<ide> </div>
<add> </div>
<ide> </div>
<ide> </div>
<ide> </body> | 1 |
Python | Python | remove some parens in iteration | e499615c036871d42b09c96312ca0dd2da1b25c0 | <ide><path>numpy/lib/_iotools.py
<ide> def upgrade_mapper(cls, func, default=None):
<ide> else:
<ide> default = list(default)
<ide> default.append([None] * (len(func) - len(default)))
<del> for (fct, dft) in zip(func, default):
<add> for fct, dft in zip(func, default):
<ide> cls._mapper.insert(-1, (cls._getsubdtype(dft), fct, dft))
<ide>
<ide> def __init__(self, dtype_or_func=None, default=None, missing_values=None,
<ide> def __init__(self, dtype_or_func=None, default=None, missing_values=None,
<ide> dtype = self._getdtype(default)
<ide> # Set the status according to the dtype
<ide> _status = -1
<del> for (i, (deftype, func, default_def)) in enumerate(self._mapper):
<add> for i, (deftype, func, default_def) in enumerate(self._mapper):
<ide> if np.issubdtype(dtype.type, deftype):
<ide> _status = i
<ide> if default is None:
<ide> def __init__(self, dtype_or_func=None, default=None, missing_values=None,
<ide> break
<ide> # if a converter for the specific dtype is available use that
<ide> last_func = func
<del> for (i, (deftype, func, default_def)) in enumerate(self._mapper):
<add> for i, (deftype, func, default_def) in enumerate(self._mapper):
<ide> if dtype.type == deftype:
<ide> _status = i
<ide> last_func = func | 1 |
Python | Python | move db call out of ``databrickshook.__init__`` | 0b7b13372f6dbf18a35d5346d3955f65b31dd00d | <ide><path>airflow/providers/databricks/hooks/databricks.py
<ide> def __init__(
<ide> ) -> None:
<ide> super().__init__()
<ide> self.databricks_conn_id = databricks_conn_id
<del> self.databricks_conn = self.get_connection(databricks_conn_id)
<add> self.databricks_conn = None
<ide> self.timeout_seconds = timeout_seconds
<ide> if retry_limit < 1:
<ide> raise ValueError('Retry limit must be greater than equal to 1')
<ide> def _do_api_call(self, endpoint_info, json):
<ide> """
<ide> method, endpoint = endpoint_info
<ide>
<add> self.databricks_conn = self.get_connection(self.databricks_conn_id)
<add>
<ide> if 'token' in self.databricks_conn.extra_dejson:
<ide> self.log.info('Using token auth. ')
<ide> auth = _TokenAuth(self.databricks_conn.extra_dejson['token']) | 1 |
Python | Python | use full version string for deprecated config | 4291de218e0738f32f516afe0f9d6adce7f3220d | <ide><path>airflow/configuration.py
<ide> class AirflowConfigParser(ConfigParser):
<ide> ('core', 'max_active_tasks_per_dag'): ('core', 'dag_concurrency', '2.2.0'),
<ide> ('logging', 'worker_log_server_port'): ('celery', 'worker_log_server_port', '2.2.0'),
<ide> ('api', 'access_control_allow_origins'): ('api', 'access_control_allow_origin', '2.2.0'),
<del> ('api', 'auth_backends'): ('api', 'auth_backend', '2.3'),
<del> ('database', 'sql_alchemy_conn'): ('core', 'sql_alchemy_conn', '2.3'),
<del> ('database', 'sql_engine_encoding'): ('core', 'sql_engine_encoding', '2.3'),
<del> ('database', 'sql_engine_collation_for_ids'): ('core', 'sql_engine_collation_for_ids', '2.3'),
<del> ('database', 'sql_alchemy_pool_enabled'): ('core', 'sql_alchemy_pool_enabled', '2.3'),
<del> ('database', 'sql_alchemy_pool_size'): ('core', 'sql_alchemy_pool_size', '2.3'),
<del> ('database', 'sql_alchemy_max_overflow'): ('core', 'sql_alchemy_max_overflow', '2.3'),
<del> ('database', 'sql_alchemy_pool_recycle'): ('core', 'sql_alchemy_pool_recycle', '2.3'),
<del> ('database', 'sql_alchemy_pool_pre_ping'): ('core', 'sql_alchemy_pool_pre_ping', '2.3'),
<del> ('database', 'sql_alchemy_schema'): ('core', 'sql_alchemy_schema', '2.3'),
<del> ('database', 'sql_alchemy_connect_args'): ('core', 'sql_alchemy_connect_args', '2.3'),
<del> ('database', 'load_default_connections'): ('core', 'load_default_connections', '2.3'),
<del> ('database', 'max_db_retries'): ('core', 'max_db_retries', '2.3'),
<add> ('api', 'auth_backends'): ('api', 'auth_backend', '2.3.0'),
<add> ('database', 'sql_alchemy_conn'): ('core', 'sql_alchemy_conn', '2.3.0'),
<add> ('database', 'sql_engine_encoding'): ('core', 'sql_engine_encoding', '2.3.0'),
<add> ('database', 'sql_engine_collation_for_ids'): ('core', 'sql_engine_collation_for_ids', '2.3.0'),
<add> ('database', 'sql_alchemy_pool_enabled'): ('core', 'sql_alchemy_pool_enabled', '2.3.0'),
<add> ('database', 'sql_alchemy_pool_size'): ('core', 'sql_alchemy_pool_size', '2.3.0'),
<add> ('database', 'sql_alchemy_max_overflow'): ('core', 'sql_alchemy_max_overflow', '2.3.0'),
<add> ('database', 'sql_alchemy_pool_recycle'): ('core', 'sql_alchemy_pool_recycle', '2.3.0'),
<add> ('database', 'sql_alchemy_pool_pre_ping'): ('core', 'sql_alchemy_pool_pre_ping', '2.3.0'),
<add> ('database', 'sql_alchemy_schema'): ('core', 'sql_alchemy_schema', '2.3.0'),
<add> ('database', 'sql_alchemy_connect_args'): ('core', 'sql_alchemy_connect_args', '2.3.0'),
<add> ('database', 'load_default_connections'): ('core', 'load_default_connections', '2.3.0'),
<add> ('database', 'max_db_retries'): ('core', 'max_db_retries', '2.3.0'),
<ide> }
<ide>
<ide> # A mapping of old default values that we want to change and warn the user | 1 |
Ruby | Ruby | fix some validators when used on model instance | 088c11658aa6b79d05e9014201d585c7700669aa | <ide><path>activemodel/lib/active_model/validations/with.rb
<ide> def validates_with(*args, &block)
<ide> # class version of this method for more information.
<ide> def validates_with(*args, &block)
<ide> options = args.extract_options!
<add> options[:class] = self.class
<add>
<ide> args.each do |klass|
<ide> validator = klass.new(options, &block)
<ide> validator.validate(self)
<ide><path>activemodel/test/cases/validations_test.rb
<ide> def test_validations_on_the_instance_level
<ide> auto = Automobile.new
<ide>
<ide> assert auto.invalid?
<del> assert_equal 2, auto.errors.size
<add> assert_equal 3, auto.errors.size
<ide>
<ide> auto.make = 'Toyota'
<ide> auto.model = 'Corolla'
<add> auto.approved = '1'
<ide>
<ide> assert auto.valid?
<ide> end
<ide><path>activemodel/test/models/automobile.rb
<ide> class Automobile
<ide>
<ide> validate :validations
<ide>
<del> attr_accessor :make, :model
<add> attr_accessor :make, :model, :approved
<ide>
<ide> def validations
<ide> validates_presence_of :make
<ide> validates_length_of :model, within: 2..10
<add> validates_acceptance_of :approved, allow_nil: false
<ide> end
<ide> end | 3 |
Go | Go | add hostconfig check before starting a container | 4177b0bae04bb41dfff65ea87b2efb87811e08e6 | <ide><path>daemon/daemon_unix.go
<ide> func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *runconfig.HostC
<ide> if hostConfig.LxcConf.Len() > 0 && !strings.Contains(daemon.ExecutionDriver().Name(), "lxc") {
<ide> return warnings, fmt.Errorf("Cannot use --lxc-conf with execdriver: %s", daemon.ExecutionDriver().Name())
<ide> }
<add>
<add> // memory subsystem checks and adjustments
<ide> if hostConfig.Memory != 0 && hostConfig.Memory < 4194304 {
<ide> return warnings, fmt.Errorf("Minimum memory limit allowed is 4MB")
<ide> }
<ide> if hostConfig.Memory > 0 && !sysInfo.MemoryLimit {
<ide> warnings = append(warnings, "Your kernel does not support memory limit capabilities. Limitation discarded.")
<ide> logrus.Warnf("Your kernel does not support memory limit capabilities. Limitation discarded.")
<ide> hostConfig.Memory = 0
<add> hostConfig.MemorySwap = -1
<ide> }
<ide> if hostConfig.Memory > 0 && hostConfig.MemorySwap != -1 && !sysInfo.SwapLimit {
<ide> warnings = append(warnings, "Your kernel does not support swap limit capabilities, memory limited without swap.")
<ide> func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *runconfig.HostC
<ide> if hostConfig.Memory == 0 && hostConfig.MemorySwap > 0 {
<ide> return warnings, fmt.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage.")
<ide> }
<del> if hostConfig.MemorySwappiness != nil && !sysInfo.MemorySwappiness {
<add> if hostConfig.MemorySwappiness != nil && *hostConfig.MemorySwappiness != -1 && !sysInfo.MemorySwappiness {
<ide> warnings = append(warnings, "Your kernel does not support memory swappiness capabilities, memory swappiness discarded.")
<ide> logrus.Warnf("Your kernel does not support memory swappiness capabilities, memory swappiness discarded.")
<ide> hostConfig.MemorySwappiness = nil
<ide> func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *runconfig.HostC
<ide> if hostConfig.BlkioWeight > 0 && (hostConfig.BlkioWeight < 10 || hostConfig.BlkioWeight > 1000) {
<ide> return warnings, fmt.Errorf("Range of blkio weight is from 10 to 1000.")
<ide> }
<add>
<ide> if hostConfig.OomKillDisable && !sysInfo.OomKillDisable {
<ide> hostConfig.OomKillDisable = false
<ide> return warnings, fmt.Errorf("Your kernel does not support oom kill disable.")
<ide> }
<add>
<ide> if sysInfo.IPv4ForwardingDisabled {
<ide> warnings = append(warnings, "IPv4 forwarding is disabled. Networking will not work.")
<ide> logrus.Warnf("IPv4 forwarding is disabled. Networking will not work")
<ide><path>daemon/start.go
<ide> func (daemon *Daemon) ContainerStart(name string, hostConfig *runconfig.HostConf
<ide> return fmt.Errorf("Container already started")
<ide> }
<ide>
<del> if _, err = daemon.verifyContainerSettings(hostConfig, nil); err != nil {
<del> return err
<del> }
<del>
<ide> // Windows does not have the backwards compatibilty issue here.
<ide> if runtime.GOOS != "windows" {
<ide> // This is kept for backward compatibility - hostconfig should be passed when
<ide> func (daemon *Daemon) ContainerStart(name string, hostConfig *runconfig.HostConf
<ide> }
<ide> }
<ide>
<add> // check if hostConfig is in line with the current system settings.
<add> // It may happen cgroups are umounted or the like.
<add> if _, err = daemon.verifyContainerSettings(container.hostConfig, nil); err != nil {
<add> return err
<add> }
<add>
<ide> if err := container.Start(); err != nil {
<ide> return fmt.Errorf("Cannot start container %s: %s", name, err)
<ide> }
<ide><path>runconfig/parse.go
<ide> func Parse(cmd *flag.FlagSet, args []string) (*Config, *HostConfig, *flag.FlagSe
<ide> flMemory = parsedMemory
<ide> }
<ide>
<del> var MemorySwap int64
<add> var memorySwap int64
<ide> if *flMemorySwap != "" {
<ide> if *flMemorySwap == "-1" {
<del> MemorySwap = -1
<add> memorySwap = -1
<ide> } else {
<ide> parsedMemorySwap, err := units.RAMInBytes(*flMemorySwap)
<ide> if err != nil {
<ide> return nil, nil, cmd, err
<ide> }
<del> MemorySwap = parsedMemorySwap
<add> memorySwap = parsedMemorySwap
<ide> }
<ide> }
<ide>
<ide> func Parse(cmd *flag.FlagSet, args []string) (*Config, *HostConfig, *flag.FlagSe
<ide> ContainerIDFile: *flContainerIDFile,
<ide> LxcConf: lxcConf,
<ide> Memory: flMemory,
<del> MemorySwap: MemorySwap,
<add> MemorySwap: memorySwap,
<ide> CPUShares: *flCPUShares,
<ide> CPUPeriod: *flCPUPeriod,
<ide> CpusetCpus: *flCpusetCpus, | 3 |
Mixed | Python | add spacy prefix to ngram_suggester.v1 | 64fac754fee4d701d07326178d8c19c4301de963 | <ide><path>spacy/pipeline/spancat.py
<ide> DEFAULT_SPANCAT_MODEL = Config().from_str(spancat_default_config)["model"]
<ide>
<ide>
<del>@registry.misc("ngram_suggester.v1")
<add>@registry.misc("spacy.ngram_suggester.v1")
<ide> def build_ngram_suggester(sizes: List[int]) -> Callable[[List[Doc]], Ragged]:
<ide> """Suggest all spans of the given lengths. Spans are returned as a ragged
<ide> array of integers. The array has two columns, indicating the start and end
<ide> def ngram_suggester(docs: List[Doc], *, ops: Optional[Ops] = None) -> Ragged:
<ide> "spans_key": "sc",
<ide> "max_positive": None,
<ide> "model": DEFAULT_SPANCAT_MODEL,
<del> "suggester": {"@misc": "ngram_suggester.v1", "sizes": [1, 2, 3]},
<add> "suggester": {"@misc": "spacy.ngram_suggester.v1", "sizes": [1, 2, 3]},
<ide> },
<ide> default_score_weights={"spans_sc_f": 1.0, "spans_sc_p": 0.0, "spans_sc_r": 0.0},
<ide> )
<ide><path>spacy/tests/pipeline/test_spancat.py
<ide> def test_simple_train():
<ide> def test_ngram_suggester(en_tokenizer):
<ide> # test different n-gram lengths
<ide> for size in [1, 2, 3]:
<del> ngram_suggester = registry.misc.get("ngram_suggester.v1")(sizes=[size])
<add> ngram_suggester = registry.misc.get("spacy.ngram_suggester.v1")(sizes=[size])
<ide> docs = [
<ide> en_tokenizer(text)
<ide> for text in [
<ide> def test_ngram_suggester(en_tokenizer):
<ide> assert_equal(ngrams.lengths, [max(0, len(doc) - (size - 1)) for doc in docs])
<ide>
<ide> # test 1-3-gram suggestions
<del> ngram_suggester = registry.misc.get("ngram_suggester.v1")(sizes=[1, 2, 3])
<add> ngram_suggester = registry.misc.get("spacy.ngram_suggester.v1")(sizes=[1, 2, 3])
<ide> docs = [
<ide> en_tokenizer(text) for text in ["a", "a b", "a b c", "a b c d", "a b c d e"]
<ide> ]
<ide> def test_ngram_suggester(en_tokenizer):
<ide> )
<ide>
<ide> # test some empty docs
<del> ngram_suggester = registry.misc.get("ngram_suggester.v1")(sizes=[1])
<add> ngram_suggester = registry.misc.get("spacy.ngram_suggester.v1")(sizes=[1])
<ide> docs = [en_tokenizer(text) for text in ["", "a", ""]]
<ide> ngrams = ngram_suggester(docs)
<ide> assert_equal(ngrams.lengths, [len(doc) for doc in docs])
<ide>
<ide> # test all empty docs
<del> ngram_suggester = registry.misc.get("ngram_suggester.v1")(sizes=[1])
<add> ngram_suggester = registry.misc.get("spacy.ngram_suggester.v1")(sizes=[1])
<ide> docs = [en_tokenizer(text) for text in ["", "", ""]]
<ide> ngrams = ngram_suggester(docs)
<ide> assert_equal(ngrams.lengths, [len(doc) for doc in docs])
<ide><path>website/docs/api/spancategorizer.md
<ide> architectures and their arguments and hyperparameters.
<ide> > "spans_key": "labeled_spans",
<ide> > "max_positive": None,
<ide> > "model": DEFAULT_SPANCAT_MODEL,
<del>> "suggester": {"@misc": "ngram_suggester.v1", "sizes": [1, 2, 3]},
<add>> "suggester": {"@misc": "spacy.ngram_suggester.v1", "sizes": [1, 2, 3]},
<ide> > }
<ide> > nlp.add_pipe("spancat", config=config)
<ide> > ``` | 3 |
Go | Go | add freebsd client support | 547ac421995860f99d1d0803c3c1e7ea51dc681e | <ide><path>pkg/term/termios_bsd.go
<add>package term
<add>
<add>import (
<add> "syscall"
<add> "unsafe"
<add>)
<add>
<add>const (
<add> getTermios = syscall.TIOCGETA
<add> setTermios = syscall.TIOCSETA
<add>
<add> IGNBRK = syscall.IGNBRK
<add> PARMRK = syscall.PARMRK
<add> INLCR = syscall.INLCR
<add> IGNCR = syscall.IGNCR
<add> ECHONL = syscall.ECHONL
<add> CSIZE = syscall.CSIZE
<add> ICRNL = syscall.ICRNL
<add> ISTRIP = syscall.ISTRIP
<add> PARENB = syscall.PARENB
<add> ECHO = syscall.ECHO
<add> ICANON = syscall.ICANON
<add> ISIG = syscall.ISIG
<add> IXON = syscall.IXON
<add> BRKINT = syscall.BRKINT
<add> INPCK = syscall.INPCK
<add> OPOST = syscall.OPOST
<add> CS8 = syscall.CS8
<add> IEXTEN = syscall.IEXTEN
<add>)
<add>
<add>type Termios struct {
<add> Iflag uint32
<add> Oflag uint32
<add> Cflag uint32
<add> Lflag uint32
<add> Cc [20]byte
<add> Ispeed uint32
<add> Ospeed uint32
<add>}
<add>
<add>// MakeRaw put the terminal connected to the given file descriptor into raw
<add>// mode and returns the previous state of the terminal so that it can be
<add>// restored.
<add>func MakeRaw(fd uintptr) (*State, error) {
<add> var oldState State
<add> if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(getTermios), uintptr(unsafe.Pointer(&oldState.termios))); err != 0 {
<add> return nil, err
<add> }
<add> // C.makeraw()
<add> // return &oldState, nil
<add>
<add> newState := oldState.termios
<add> newState.Iflag &^= (IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON)
<add> newState.Oflag &^= OPOST
<add> newState.Lflag &^= (ECHO | ECHONL | ICANON | ISIG | IEXTEN)
<add> newState.Cflag &^= (CSIZE | PARENB)
<add> newState.Cflag |= CS8
<add> newState.Cc[syscall.VMIN] = 1
<add> newState.Cc[syscall.VTIME] = 0
<add>
<add> if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(setTermios), uintptr(unsafe.Pointer(&newState))); err != 0 {
<add> return nil, err
<add> }
<add>
<add> return &oldState, nil
<add>}
<ide><path>utils/signal_freebsd.go
<add>package utils
<add>
<add>import (
<add> "os"
<add> "os/signal"
<add> "syscall"
<add>)
<add>
<add>func CatchAll(sigc chan os.Signal) {
<add> signal.Notify(sigc,
<add> syscall.SIGABRT,
<add> syscall.SIGALRM,
<add> syscall.SIGBUS,
<add> syscall.SIGCHLD,
<add> syscall.SIGCONT,
<add> syscall.SIGFPE,
<add> syscall.SIGHUP,
<add> syscall.SIGILL,
<add> syscall.SIGINT,
<add> syscall.SIGIO,
<add> syscall.SIGIOT,
<add> syscall.SIGKILL,
<add> syscall.SIGPIPE,
<add> syscall.SIGPROF,
<add> syscall.SIGQUIT,
<add> syscall.SIGSEGV,
<add> syscall.SIGSTOP,
<add> syscall.SIGSYS,
<add> syscall.SIGTERM,
<add> syscall.SIGTRAP,
<add> syscall.SIGTSTP,
<add> syscall.SIGTTIN,
<add> syscall.SIGTTOU,
<add> syscall.SIGURG,
<add> syscall.SIGUSR1,
<add> syscall.SIGUSR2,
<add> syscall.SIGVTALRM,
<add> syscall.SIGWINCH,
<add> syscall.SIGXCPU,
<add> syscall.SIGXFSZ,
<add> )
<add>} | 2 |
PHP | PHP | use directory_separator instead of / | 84ddb6c54c5caca72c51ea8e1006f8e0a17947ec | <ide><path>src/Mailer/Email.php
<ide> protected function _renderTemplates($content)
<ide>
<ide> foreach ($types as $type) {
<ide> $View->hasRendered = false;
<del> $View->templatePath('Email/' . $type);
<del> $View->layoutPath('Email/' . $type);
<add> $View->templatePath('Email' . DIRECTORY_SEPARATOR . $type);
<add> $View->layoutPath('Email' . DIRECTORY_SEPARATOR . $type);
<ide>
<ide> $render = $View->render();
<ide> $render = str_replace(["\r\n", "\r"], "\n", $render); | 1 |
Javascript | Javascript | use less code to detect replace instead of push | b0cad3370d2a3f3184f57da99313ff6c93ccf768 | <ide><path>packages/next/client/link.js
<ide> class Link extends Component {
<ide> }
<ide>
<ide> // replace state instead of push if prop is present
<del> const { replace } = this.props
<del> const changeMethod = replace ? 'replace' : 'push'
<del>
<del> // straight up redirect
<del> Router[changeMethod](href, as, { shallow: this.props.shallow })
<add> Router[this.props.replace ? 'replace' : 'push'](href, as, { shallow: this.props.shallow })
<ide> .then((success) => {
<ide> if (!success) return
<ide> if (scroll) { | 1 |
Text | Text | integrate suggested changes | 33b8e0faa0fed21ef8428da8d2709e99843b19f5 | <ide><path>docs/Updating-Software-in-Homebrew.md
<ide>
<ide> Did you find something in Homebrew that wasn't the latest version? You can help yourself and others by submitting a pull request to update the formula.
<ide>
<del>If you want to update software that is either closed source, or a GUI only program you want to follow the guide for Casks. Otherwise follow the guide for Formulae.
<del>See also: [Homebrew Terminology](https://docs.brew.sh/Formula-Cookbook#homebrew-terminology)
<del>
<del>First, check the pull requests in the [homebrew-core](https://github.com/Homebrew/homebrew-core/pulls) or [homebrew-cask](https://github.com/Homebrew/homebrew-cask/pulls) repositories to make sure there isn't already an open PR. You may also want to look through closed pull requests in the repositories, as sometimes packages run into problems preventing them from being updated and it's better to be aware of any issues before putting significant effort into an update.
<add>First, check the pull requests in the Homebrew tap repositories to make sure a PR isn't already open. If you're submitting a [formula](https://docs.brew.sh/Formula-Cookbook#homebrew-terminology), check [homebrew-core](https://github.com/Homebrew/homebrew-core/pulls). If you're submitting a [cask](https://docs.brew.sh/Formula-Cookbook#homebrew-terminology), check [homebrew-cask](https://github.com/Homebrew/homebrew-cask/pulls). You may also want to look through closed pull requests in the repositories, as sometimes packages run into problems preventing them from being updated and it's better to be aware of any issues before putting significant effort into an update.
<ide>
<ide> The [How To Open a Homebrew Pull Request](How-To-Open-a-Homebrew-Pull-Request.md) documentation should explain most everything you need to know about the process of creating a PR for a version update. For simple updates, this typically involves changing the URL and sha256.
<ide> | 1 |
Text | Text | fix broken link on controlled input tip | f6f3d4262b29aa4f453998f585676eb9fff6bb50 | <ide><path>docs/tips/08-controlled-input-null-value.md
<ide> prev: children-props-type.html
<ide> next: componentWillReceiveProps-not-triggered-after-mounting.html
<ide> ---
<ide>
<del>Specifying the `value` prop on a [controlled component](/react/docs/tips/forms.html) prevents the user from changing the input unless you desire so.
<add>Specifying the `value` prop on a [controlled component](/react/docs/forms.html) prevents the user from changing the input unless you desire so.
<ide>
<ide> You might have run into a problem where `value` is specified, but the input can still be changed without consent. In this case, you might have accidentally set `value` to `undefined` or `null`.
<ide> | 1 |
Python | Python | add tool to find functions missing types | a08586a0a6e86148c85d09ffba167c686d52a8b0 | <ide><path>tools/functions_missing_types.py
<add>#!/usr/bin/env python
<add>import argparse
<add>import ast
<add>import importlib
<add>import os
<add>
<add>NUMPY_ROOT = os.path.dirname(os.path.join(
<add> os.path.abspath(__file__), "..",
<add>))
<add>
<add># Technically "public" functions (they don't start with an underscore)
<add># that we don't want to include.
<add>EXCLUDE_LIST = {
<add> "numpy": {
<add> # Stdlib modules in the namespace by accident
<add> "absolute_import",
<add> "division",
<add> "print_function",
<add> "warnings",
<add> # Accidentally public, deprecated, or shouldn't be used
<add> "Tester",
<add> "add_docstring",
<add> "add_newdoc",
<add> "add_newdoc_ufunc",
<add> "core",
<add> "fastCopyAndTranspose",
<add> "get_array_wrap",
<add> "int_asbuffer",
<add> "oldnumeric",
<add> "safe_eval",
<add> "set_numeric_ops",
<add> "test",
<add> # Builtins
<add> "bool",
<add> "complex",
<add> "float",
<add> "int",
<add> "long",
<add> "object",
<add> "str",
<add> "unicode",
<add> # Should use numpy_financial instead
<add> "fv",
<add> "ipmt",
<add> "irr",
<add> "mirr",
<add> "nper",
<add> "npv",
<add> "pmt",
<add> "ppmt",
<add> "pv",
<add> "rate",
<add> # More standard names should be preferred
<add> "alltrue", # all
<add> "sometrue", # any
<add> }
<add>}
<add>
<add>
<add>class FindAttributes(ast.NodeVisitor):
<add> """Find top-level attributes/functions/classes a stubs file.
<add>
<add> Do this by walking the stubs ast. See e.g.
<add>
<add> https://greentreesnakes.readthedocs.io/en/latest/index.html
<add>
<add> for more information on working with Python's ast.
<add>
<add> """
<add>
<add> def __init__(self):
<add> self.attributes = set()
<add>
<add> def visit_FunctionDef(self, node):
<add> if node.name == "__getattr__":
<add> # Not really a module member.
<add> return
<add> self.attributes.add(node.name)
<add> # Do not call self.generic_visit; we are only interested in
<add> # top-level functions.
<add> return
<add>
<add> def visit_ClassDef(self, node):
<add> if not node.name.startswith("_"):
<add> self.attributes.add(node.name)
<add> return
<add>
<add> def visit_AnnAssign(self, node):
<add> self.attributes.add(node.target.id)
<add>
<add>
<add>def find_missing(module_name):
<add> module_path = os.path.join(
<add> NUMPY_ROOT,
<add> module_name.replace(".", os.sep),
<add> "__init__.pyi",
<add> )
<add>
<add> module = importlib.import_module(module_name)
<add> module_attributes = {
<add> attribute for attribute in dir(module) if not attribute.startswith("_")
<add> }
<add>
<add> if os.path.isfile(module_path):
<add> with open(module_path) as f:
<add> tree = ast.parse(f.read())
<add> ast_visitor = FindAttributes()
<add> ast_visitor.visit(tree)
<add> stubs_attributes = ast_visitor.attributes
<add> else:
<add> # No stubs for this module yet.
<add> stubs_attributes = set()
<add>
<add> exclude_list = EXCLUDE_LIST.get(module_name, set())
<add>
<add> missing = module_attributes - stubs_attributes - exclude_list
<add> print("\n".join(sorted(missing)))
<add>
<add>
<add>def main():
<add> parser = argparse.ArgumentParser()
<add> parser.add_argument("module")
<add> args = parser.parse_args()
<add>
<add> find_missing(args.module)
<add>
<add>
<add>if __name__ == "__main__":
<add> main() | 1 |
Java | Java | use repeatablecontainers.none() in annotationutils | f273fa990c5231684b0dedf4895d9e6bd8f66235 | <ide><path>spring-core/src/main/java/org/springframework/core/annotation/AnnotationUtils.java
<ide> public static <A extends Annotation> A getAnnotation(Annotation annotation, Clas
<ide> return null;
<ide> }
<ide> // Exhaustive retrieval of merged annotations...
<del> return MergedAnnotations.from(annotation)
<add> return MergedAnnotations.from(null, new Annotation[] {annotation},
<add> RepeatableContainers.none(), AnnotationFilter.PLAIN)
<ide> .get(annotationType).withNonMergedAttributes()
<ide> .synthesize(AnnotationUtils::isSingleLevelPresent).orElse(null);
<ide> }
<ide> public static <A extends Annotation> A findAnnotation(
<ide> return annotatedElement.getDeclaredAnnotation(annotationType);
<ide> }
<ide> // Exhaustive retrieval of merged annotations...
<del> return MergedAnnotations.from(annotatedElement, SearchStrategy.INHERITED_ANNOTATIONS)
<add> return MergedAnnotations.from(annotatedElement, SearchStrategy.INHERITED_ANNOTATIONS,
<add> RepeatableContainers.none(), AnnotationFilter.PLAIN)
<ide> .get(annotationType).withNonMergedAttributes()
<ide> .synthesize(MergedAnnotation::isPresent).orElse(null);
<ide> }
<ide> public static <A extends Annotation> A findAnnotation(Method method, @Nullable C
<ide> return method.getDeclaredAnnotation(annotationType);
<ide> }
<ide> // Exhaustive retrieval of merged annotations...
<del> return MergedAnnotations.from(method, SearchStrategy.EXHAUSTIVE)
<add> return MergedAnnotations.from(method, SearchStrategy.EXHAUSTIVE,
<add> RepeatableContainers.none(), AnnotationFilter.PLAIN)
<ide> .get(annotationType).withNonMergedAttributes()
<ide> .synthesize(MergedAnnotation::isPresent).orElse(null);
<ide> }
<ide> public static <A extends Annotation> A findAnnotation(Class<?> clazz, @Nullable
<ide> return clazz.getDeclaredAnnotation(annotationType);
<ide> }
<ide> // Exhaustive retrieval of merged annotations...
<del> return MergedAnnotations.from(clazz, SearchStrategy.EXHAUSTIVE)
<add> return MergedAnnotations.from(clazz, SearchStrategy.EXHAUSTIVE,
<add> RepeatableContainers.none(), AnnotationFilter.PLAIN)
<ide> .get(annotationType).withNonMergedAttributes()
<ide> .synthesize(MergedAnnotation::isPresent).orElse(null);
<ide> }
<ide><path>spring-core/src/test/java/org/springframework/core/annotation/AnnotationUtilsTests.java
<ide> public void synthesizeAnnotationFromAnnotationAttributesWithoutAttributeAliases(
<ide> assertEquals("value from synthesized component: ", "webController", synthesizedComponent.value());
<ide> }
<ide>
<add> @Test // gh-22702
<add> public void findAnnotationWithRepeatablesElements() {
<add> assertNull(AnnotationUtils.findAnnotation(TestRepeatablesClass.class,
<add> TestRepeatable.class));
<add> assertNotNull(AnnotationUtils.findAnnotation(TestRepeatablesClass.class,
<add> TestRepeatableContainer.class));
<add> }
<ide>
<ide> @SafeVarargs
<ide> static <T> T[] asArray(T... arr) {
<ide> static class ComponentScanSingleFilterClass {
<ide> interface ContextConfigMismatch {
<ide> }
<ide>
<add> @Retention(RetentionPolicy.RUNTIME)
<add> @Repeatable(TestRepeatableContainer.class)
<add> static @interface TestRepeatable {
<add>
<add> String value();
<add> }
<add>
<add> @Retention(RetentionPolicy.RUNTIME)
<add> static @interface TestRepeatableContainer {
<add>
<add> TestRepeatable[] value();
<add> }
<add>
<add> @TestRepeatable("a")
<add> @TestRepeatable("b")
<add> static class TestRepeatablesClass {
<add> }
<ide> } | 2 |
Python | Python | fix linting errors | a7a152100458bdb3dfda64c875c1fea3156fab70 | <ide><path>libcloud/test/storage/test_base.py
<ide> # See the License for the specific language governing permissions and
<ide> # limitations under the License.
<ide>
<del>import sys
<ide> import errno
<ide> import hashlib
<del>
<del>from libcloud.common.base import Response
<del>from libcloud.common.exceptions import RateLimitReachedError
<del>from libcloud.utils.py3 import httplib
<add>import sys
<ide> from io import BytesIO
<ide>
<ide> import mock
<ide> from mock import Mock
<ide>
<del>from libcloud.utils.py3 import StringIO
<del>from libcloud.utils.py3 import b
<del>from libcloud.utils.py3 import PY2
<del>from libcloud.utils.py3 import assertRaisesRegex
<del>
<del>from libcloud.storage.base import StorageDriver
<add>from libcloud.common.exceptions import RateLimitReachedError
<ide> from libcloud.storage.base import DEFAULT_CONTENT_TYPE
<del>
<del>from libcloud.test import unittest
<del>from libcloud.test import MockHttp
<add>from libcloud.storage.base import StorageDriver
<ide> from libcloud.test import BodyStream
<add>from libcloud.test import MockHttp
<add>from libcloud.test import unittest
<ide> from libcloud.test.storage.base import BaseRangeDownloadMockHttp
<add>from libcloud.utils.py3 import PY2
<add>from libcloud.utils.py3 import StringIO
<add>from libcloud.utils.py3 import assertRaisesRegex
<add>from libcloud.utils.py3 import b
<add>from libcloud.utils.py3 import httplib
<ide>
<ide>
<ide> class BaseMockRawResponse(MockHttp):
<ide> def succeed_on_second(*_, **__) -> mock.MagicMock:
<ide> else:
<ide> raise RateLimitReachedError()
<ide>
<del> self.driver1.connection.connection.session.send = Mock(side_effect=succeed_on_second)
<add> self.driver1.connection.connection.session.send = Mock(
<add> side_effect=succeed_on_second
<add> )
<ide> uploaded_object = self.driver1._upload_object(
<ide> object_name="some name",
<ide> content_type="something",
<ide> request_path="/",
<ide> stream=iter([]),
<ide> )
<ide>
<del> self.assertEqual(True, uploaded_object["response"].success(), "Expected to have successful response after retry")
<add> self.assertEqual(
<add> True,
<add> uploaded_object["response"].success(),
<add> "Expected to have successful response after retry",
<add> )
<ide>
<ide>
<ide> class BaseRangeDownloadMockHttpTestCase(unittest.TestCase):
<ide><path>libcloud/test/storage/test_local.py
<ide>
<ide> from __future__ import with_statement
<ide>
<add>import multiprocessing
<ide> import os
<del>import pickle
<del>import sys
<ide> import platform
<ide> import shutil
<del>import unittest
<del>import time
<add>import sys
<ide> import tempfile
<del>import multiprocessing
<del>from typing import Callable
<add>import time
<add>import unittest
<ide>
<ide> from libcloud.common.types import LibcloudError
<ide> from libcloud.storage.base import Container
<ide> from libcloud.storage.base import Object
<del>from libcloud.storage.types import ContainerDoesNotExistError
<ide> from libcloud.storage.types import ContainerAlreadyExistsError
<add>from libcloud.storage.types import ContainerDoesNotExistError
<ide> from libcloud.storage.types import ContainerIsNotEmptyError
<ide> from libcloud.storage.types import InvalidContainerNameError
<ide> from libcloud.utils.files import exhaust_iterator
<ide> def test_lock_local_storage(self):
<ide> expected_msg = "Failed to acquire thread lock"
<ide> self.assertRaisesRegex(LibcloudError, expected_msg, lock.__enter__)
<ide>
<del>
<ide> success_1 = multiprocessing.Value("i", 0)
<ide> success_2 = multiprocessing.Value("i", 0)
<ide>
<ide><path>libcloud/test/test_connection.py
<ide> def test_parse_errors_can_be_retried(self):
<ide> class RetryableThrowingError(Response):
<ide> parse_error_counter: int = 0
<ide> success_counter: int = 0
<add>
<ide> def __init__(self, *_, **__):
<ide> super().__init__(mock.MagicMock(), mock.MagicMock())
<ide> | 3 |
Text | Text | add video link on algorithms | 3ba98401ebf01ea188463f601e5365faf1ba9df9 | <ide><path>guide/english/algorithms/index.md
<ide> This video introduces algorithms and briefly discusses some high profile uses of
<ide>
<ide> This video visually demonstrates some popular sorting algorithms that are commonly taught in programming and Computer Science courses.
<ide>
<add>[How algorithms shape our world | Kevin Slavin](https://www.youtube.com/watch?v=TDaFwnOiKVE)
<add>
<add>This is a short video on how algorithms shape our world and their occurence in everyday life.
<add>
<ide> [Algorithm Visualizer](http://algo-visualizer.jasonpark.me)
<ide>
<ide> This is also a really good open source project that helps you visualize algorithms. | 1 |
Text | Text | add poppler to dev dependency guide [ci skip] | 410bc52fa51d99b60f5f19123458eeab33c4774a | <ide><path>guides/source/development_dependencies_install.md
<ide> Here's the list of each gems' additional dependencies:
<ide> * Action Cable depends on Redis
<ide> * Active Record depends on SQLite3, MySQL and PostgreSQL
<ide> * Active Storage depends on Yarn (additionally Yarn depends on
<del> [Node.js](https://nodejs.org/)), ImageMagick, libvips, FFmpeg, muPDF, and on
<del> macOS also XQuartz and Poppler.
<add> [Node.js](https://nodejs.org/)), ImageMagick, libvips, FFmpeg, muPDF,
<add> Poppler, and on macOS also XQuartz.
<ide> * Active Support depends on memcached and Redis
<ide> * Railties depend on a JavaScript runtime environment, such as having
<ide> [Node.js](https://nodejs.org/) installed.
<ide> To install all run:
<ide>
<ide> ```bash
<ide> $ sudo apt-get update
<del>$ sudo apt-get install sqlite3 libsqlite3-dev mysql-server libmysqlclient-dev postgresql postgresql-client postgresql-contrib libpq-dev redis-server memcached imagemagick ffmpeg mupdf mupdf-tools libxml2-dev libvips42
<add>$ sudo apt-get install sqlite3 libsqlite3-dev mysql-server libmysqlclient-dev postgresql postgresql-client postgresql-contrib libpq-dev redis-server memcached imagemagick ffmpeg mupdf mupdf-tools libxml2-dev libvips42 poppler-utils
<ide>
<ide> # Install Yarn
<ide> $ curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
<ide> $ sudo apt-get install yarn
<ide> To install all run:
<ide>
<ide> ```bash
<del>$ sudo dnf install sqlite-devel sqlite-libs mysql-server mysql-devel postgresql-server postgresql-devel redis memcached imagemagick ffmpeg mupdf libxml2-devel vips
<add>$ sudo dnf install sqlite-devel sqlite-libs mysql-server mysql-devel postgresql-server postgresql-devel redis memcached imagemagick ffmpeg mupdf libxml2-devel vips poppler-utils
<ide>
<ide> # Install Yarn
<ide> # Use this command if you do not have Node.js installed
<ide> $ sudo dnf install yarn
<ide> To install all run:
<ide>
<ide> ```bash
<del>$ sudo pacman -S sqlite mariadb libmariadbclient mariadb-clients postgresql postgresql-libs redis memcached imagemagick ffmpeg mupdf mupdf-tools poppler yarn libxml2 libvips
<add>$ sudo pacman -S sqlite mariadb libmariadbclient mariadb-clients postgresql postgresql-libs redis memcached imagemagick ffmpeg mupdf mupdf-tools poppler yarn libxml2 libvips poppler
<ide> $ sudo mariadb-install-db --user=mysql --basedir=/usr --datadir=/var/lib/mysql
<ide> $ sudo systemctl start redis mariadb memcached
<ide> ```
<ide> use MariaDB instead (see [this announcement](https://www.archlinux.org/news/mari
<ide> To install all run:
<ide>
<ide> ```bash
<del>$ pkg install sqlite3 mysql80-client mysql80-server postgresql11-client postgresql11-server memcached imagemagick ffmpeg mupdf yarn libxml2 vips
<add>$ pkg install sqlite3 mysql80-client mysql80-server postgresql11-client postgresql11-server memcached imagemagick ffmpeg mupdf yarn libxml2 vips poppler-utils
<ide> # portmaster databases/redis
<ide> ```
<ide> | 1 |
PHP | PHP | convert prefix names to be camelcased | 753caebd9f8de6d0e560c25f7efe683ba0d57475 | <ide><path>src/Routing/RouteBuilder.php
<ide> public function prefix(string $name, $params = [], $callback = null)
<ide> $params = [];
<ide> }
<ide> $path = '/' . Inflector::dasherize($name);
<del> $name = Inflector::underscore($name);
<add> $name = Inflector::camelize($name);
<ide> if (isset($params['path'])) {
<ide> $path = $params['path'];
<ide> unset($params['path']);
<ide><path>src/Routing/Router.php
<ide> public static function prefix(string $name, $params = [], $callback = null): voi
<ide> $path = $params['path'] ?? '/' . Inflector::dasherize($name);
<ide> unset($params['path']);
<ide>
<del> $params = array_merge($params, ['prefix' => Inflector::underscore($name)]);
<add> $params = array_merge($params, ['prefix' => Inflector::camelize($name)]);
<ide> static::scope($path, $params, $callback);
<ide> }
<ide>
<ide><path>tests/TestCase/Controller/Component/AuthComponentTest.php
<ide> public function testAdminRoute(): void
<ide> 'controller' => 'AuthTest',
<ide> 'action' => 'add',
<ide> 'plugin' => null,
<del> 'prefix' => 'admin',
<add> 'prefix' => 'Admin',
<ide> ],
<ide> 'url' => '/admin/auth_test/add',
<ide> 'session' => $this->Auth->session,
<ide> public function testAdminRoute(): void
<ide> Router::setRequest($this->Controller->getRequest());
<ide>
<ide> $this->Auth->setConfig('loginAction', [
<del> 'prefix' => 'admin',
<add> 'prefix' => 'Admin',
<ide> 'controller' => 'auth_test',
<ide> 'action' => 'login',
<ide> ]);
<ide>
<ide> $response = $this->Auth->startup($event);
<ide> $redirectHeader = $response->getHeaderLine('Location');
<ide> $expected = Router::url([
<del> 'prefix' => 'admin',
<add> 'prefix' => 'Admin',
<ide> 'controller' => 'auth_test',
<ide> 'action' => 'login',
<ide> '?' => ['redirect' => '/admin/auth_test/add'],
<ide><path>tests/TestCase/Routing/RouteBuilderTest.php
<ide> public function testPrefix()
<ide> $this->assertInstanceOf(RouteBuilder::class, $r);
<ide> $this->assertCount(0, $this->collection->routes());
<ide> $this->assertSame('/path/admin', $r->path());
<del> $this->assertEquals(['prefix' => 'admin', 'key' => 'value', 'param' => 'value'], $r->params());
<add> $this->assertEquals(['prefix' => 'Admin', 'key' => 'value', 'param' => 'value'], $r->params());
<ide> });
<ide> $this->assertSame($routes, $res);
<ide> }
<ide> public function testPrefixWithNoParams()
<ide> $this->assertInstanceOf(RouteBuilder::class, $r);
<ide> $this->assertCount(0, $this->collection->routes());
<ide> $this->assertSame('/path/admin', $r->path());
<del> $this->assertEquals(['prefix' => 'admin', 'key' => 'value'], $r->params());
<add> $this->assertEquals(['prefix' => 'Admin', 'key' => 'value'], $r->params());
<ide> });
<ide> $this->assertSame($routes, $res);
<ide> }
<ide> public function testNestedPrefix()
<ide> $routes = new RouteBuilder($this->collection, '/admin', ['prefix' => 'admin']);
<ide> $res = $routes->prefix('api', ['_namePrefix' => 'api:'], function ($r) {
<ide> $this->assertSame('/admin/api', $r->path());
<del> $this->assertEquals(['prefix' => 'admin/api'], $r->params());
<add> $this->assertEquals(['prefix' => 'admin/Api'], $r->params());
<ide> $this->assertSame('api:', $r->namePrefix());
<ide> });
<ide> $this->assertSame($routes, $res);
<ide> public function testPathWithDotInPrefix()
<ide> $res = $routes->prefix('api', function ($r) {
<ide> $r->prefix('v10', ['path' => '/v1.0'], function ($r2) {
<ide> $this->assertSame('/admin/api/v1.0', $r2->path());
<del> $this->assertEquals(['prefix' => 'admin/api/v10'], $r2->params());
<add> $this->assertEquals(['prefix' => 'admin/Api/V10'], $r2->params());
<ide> $r2->prefix('b1', ['path' => '/beta.1'], function ($r3) {
<ide> $this->assertSame('/admin/api/v1.0/beta.1', $r3->path());
<del> $this->assertEquals(['prefix' => 'admin/api/v10/b1'], $r3->params());
<add> $this->assertEquals(['prefix' => 'admin/Api/V10/B1'], $r3->params());
<ide> });
<ide> });
<ide> });
<ide><path>tests/TestCase/Routing/RouterTest.php
<ide> public function testUrlGenerationWithPrefix()
<ide> Router::connect('/pages/*', ['controller' => 'pages', 'action' => 'display']);
<ide> Router::connect('/reset/*', ['admin' => true, 'controller' => 'users', 'action' => 'reset']);
<ide> Router::connect('/tests', ['controller' => 'tests', 'action' => 'index']);
<del> Router::connect('/admin/:controller/:action/*', ['prefix' => 'admin']);
<add> Router::connect('/admin/:controller/:action/*', ['prefix' => 'Admin']);
<ide> Router::extensions('rss', false);
<ide>
<ide> $request = new ServerRequest([
<ide> 'params' => [
<ide> 'controller' => 'registrations',
<del> 'action' => 'admin_index',
<add> 'action' => 'index',
<ide> 'plugin' => null,
<del> 'prefix' => 'admin',
<add> 'prefix' => 'Admin',
<ide> '_ext' => 'html',
<ide> ],
<ide> 'url' => '/admin/registrations/index',
<ide> public function testUrlGenerationWithPrefix()
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> Router::reload();
<del> Router::connect('/admin/subscriptions/:action/*', ['controller' => 'subscribe', 'prefix' => 'admin']);
<del> Router::connect('/admin/:controller/:action/*', ['prefix' => 'admin']);
<add> Router::connect('/admin/subscriptions/:action/*', ['controller' => 'Subscribe', 'prefix' => 'Admin']);
<add> Router::connect('/admin/:controller/:action/*', ['prefix' => 'Admin']);
<ide>
<ide> $request = new ServerRequest([
<ide> 'params' => [
<ide> 'action' => 'index',
<ide> 'plugin' => null,
<del> 'controller' => 'subscribe',
<del> 'prefix' => 'admin',
<add> 'controller' => 'Subscribe',
<add> 'prefix' => 'Admin',
<ide> ],
<ide> 'webroot' => '/magazine/',
<ide> 'base' => '/magazine',
<ide> public function testUrlGenerationWithPrefix()
<ide> $expected = '/magazine/admin/subscriptions/edit/1';
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $result = Router::url(['prefix' => 'admin', 'controller' => 'users', 'action' => 'login']);
<add> $result = Router::url(['prefix' => 'Admin', 'controller' => 'users', 'action' => 'login']);
<ide> $expected = '/magazine/admin/users/login';
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> public function testUrlGenerationPrefixedPlugin()
<ide> $routes->fallbacks('InflectedRoute');
<ide> });
<ide> });
<del> $result = Router::url(['prefix' => 'admin', 'plugin' => 'MyPlugin', 'controller' => 'Forms', 'action' => 'edit', 2]);
<add> $result = Router::url([
<add> 'prefix' => 'Admin',
<add> 'plugin' => 'MyPlugin',
<add> 'controller' => 'Forms',
<add> 'action' => 'edit',
<add> 2
<add> ]);
<ide> $expected = '/admin/my-plugin/forms/edit/2';
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide> public function testUrlGenerationMultiplePrefixes()
<ide> });
<ide> });
<ide> $result = Router::url([
<del> 'prefix' => 'admin/backoffice',
<add> 'prefix' => 'Admin/Backoffice',
<ide> 'controller' => 'Dashboards',
<ide> 'action' => 'home',
<ide> ]);
<ide> public function testPrefix()
<ide> {
<ide> Router::prefix('admin', function (RouteBuilder $routes) {
<ide> $this->assertSame('/admin', $routes->path());
<del> $this->assertEquals(['prefix' => 'admin'], $routes->params());
<add> $this->assertEquals(['prefix' => 'Admin'], $routes->params());
<ide> });
<ide>
<ide> Router::prefix('admin', ['_namePrefix' => 'admin:'], function (RouteBuilder $routes) {
<ide> $this->assertSame('admin:', $routes->namePrefix());
<del> $this->assertEquals(['prefix' => 'admin'], $routes->params());
<add> $this->assertEquals(['prefix' => 'Admin'], $routes->params());
<ide> });
<ide> }
<ide>
<ide> public function testPrefixOptions()
<ide> {
<ide> Router::prefix('admin', ['param' => 'value'], function (RouteBuilder $routes) {
<ide> $this->assertSame('/admin', $routes->path());
<del> $this->assertEquals(['prefix' => 'admin', 'param' => 'value'], $routes->params());
<add> $this->assertEquals(['prefix' => 'Admin', 'param' => 'value'], $routes->params());
<ide> });
<ide>
<ide> Router::prefix('CustomPath', ['path' => '/custom-path'], function (RouteBuilder $routes) {
<ide> $this->assertSame('/custom-path', $routes->path());
<del> $this->assertEquals(['prefix' => 'custom_path'], $routes->params());
<add> $this->assertEquals(['prefix' => 'CustomPath'], $routes->params());
<ide> });
<ide> }
<ide> | 5 |
Javascript | Javascript | add stack to non-error error emitted | 751fd9bbc40da8135d745631f38da5cbbb6b1c2a | <ide><path>lib/ErrorHelpers.js
<add>/*
<add> MIT License http://www.opensource.org/licenses/mit-license.php
<add> Author Tobias Koppers @sokra
<add>*/
<add>"use strict";
<add>
<add>const loaderFlag = "LOADER_EXECUTION";
<add>
<add>exports.cutOffLoaderExecution = (stack) => {
<add> stack = stack.split("\n");
<add> for(let i = 0; i < stack.length; i++)
<add> if(stack[i].indexOf(loaderFlag) >= 0)
<add> stack.length = i;
<add> return stack.join("\n");
<add>};
<add>
<add>exports.cutOffMessage = (stack, message) => {
<add> const nextLine = stack.indexOf("\n");
<add> if(nextLine === -1) {
<add> return stack === message ? "" : stack;
<add> } else {
<add> const firstLine = stack.substr(0, nextLine);
<add> return firstLine === message ? stack.substr(nextLine + 1) : stack;
<add> }
<add>};
<add>
<add>exports.cleanUp = (stack, message) => {
<add> stack = exports.cutOffLoaderExecution(stack);
<add> stack = exports.cutOffMessage(stack, message);
<add> return stack;
<add>};
<ide><path>lib/ModuleBuildError.js
<ide> */
<ide> "use strict";
<ide>
<del>const loaderFlag = "LOADER_EXECUTION";
<add>const cutOffLoaderExecution = require("./ErrorHelpers").cutOffLoaderExecution;
<ide>
<ide> class ModuleBuildError extends Error {
<ide>
<ide> class ModuleBuildError extends Error {
<ide> this.message = "Module build failed: ";
<ide> if(err !== null && typeof err === "object") {
<ide> if(typeof err.stack === "string" && err.stack) {
<del> var stack = err.stack.split("\n");
<del> for(var i = 0; i < stack.length; i++)
<del> if(stack[i].indexOf(loaderFlag) >= 0)
<del> stack.length = i;
<del> stack = stack.join("\n");
<add> var stack = cutOffLoaderExecution(err.stack);
<ide> if(!err.hideStack) {
<ide> this.message += stack;
<ide> } else {
<ide><path>lib/ModuleError.js
<ide> */
<ide> "use strict";
<ide>
<add>const cleanUp = require("./ErrorHelpers").cleanUp;
<add>
<ide> class ModuleError extends Error {
<ide>
<ide> constructor(module, err) {
<ide> super();
<ide>
<ide> this.name = "ModuleError";
<ide> this.module = module;
<del> this.message = err;
<add> this.message = err && typeof err === "object" && err.message ? err.message : err;
<ide> this.error = err;
<add> this.details = err && typeof err === "object" && err.stack ? cleanUp(err.stack, this.message) : undefined;
<ide>
<ide> Error.captureStackTrace(this, this.constructor);
<ide> }
<ide><path>lib/ModuleWarning.js
<ide> */
<ide> "use strict";
<ide>
<add>const cleanUp = require("./ErrorHelpers").cleanUp;
<add>
<ide> class ModuleWarning extends Error {
<add>
<ide> constructor(module, warning) {
<ide> super();
<ide>
<ide> this.name = "ModuleWarning";
<ide> this.module = module;
<del> this.message = warning;
<add> this.message = warning && typeof warning === "object" && warning.message ? warning.message : warning;
<ide> this.warning = warning;
<add> this.details = warning && typeof warning === "object" && warning.stack ? cleanUp(warning.stack, this.message) : undefined;
<ide>
<ide> Error.captureStackTrace(this, this.constructor);
<ide> }
<ide><path>lib/NormalModule.js
<ide> function contextify(context, request) {
<ide> }).join("!");
<ide> }
<ide>
<add>class NonErrorEmittedError extends Error {
<add>
<add> constructor(error) {
<add> super();
<add>
<add> this.name = "NonErrorEmittedError";
<add> this.message = "(Emitted value instead of an instance of Error) " + error;
<add>
<add> Error.captureStackTrace(this, this.constructor);
<add> }
<add>}
<add>
<ide> class NormalModule extends Module {
<ide>
<ide> constructor(request, userRequest, rawRequest, loaders, resource, parser) {
<ide> class NormalModule extends Module {
<ide> const loaderContext = {
<ide> version: 2,
<ide> emitWarning: (warning) => {
<add> if(!(warning instanceof Error))
<add> warning = new NonErrorEmittedError(warning);
<ide> this.warnings.push(new ModuleWarning(this, warning));
<ide> },
<ide> emitError: (error) => {
<add> if(!(error instanceof Error))
<add> error = new NonErrorEmittedError(error);
<ide> this.errors.push(new ModuleError(this, error));
<ide> },
<ide> exec: (code, filename) => {
<ide><path>test/cases/errors/loader-error-warning/errors.js
<ide> module.exports = [
<del> [/abc/],
<del> [/def/]
<add> [
<add> /abc/,
<add> /Emitted value instead of an instance of Error/,
<add> /error-loader\.js/
<add> ],
<add> [
<add> /def/,
<add> /Emitted value instead of an instance of Error/,
<add> /error-loader\.js/
<add> ]
<ide> ];
<ide><path>test/cases/errors/loader-error-warning/warnings.js
<ide> module.exports = [
<del> [/xyz/]
<add> [
<add> /xyz/,
<add> /Emitted value instead of an instance of Error/,
<add> /warning-loader\.js/
<add> ]
<ide> ]; | 7 |
Ruby | Ruby | convert ignored_columns to a list of string | e9f82e76e83497db094fe63104f548453fbe512e | <ide><path>activerecord/lib/active_record/model_schema.rb
<ide> module ModelSchema
<ide> # If true, the default table name for a Product class will be "products". If false, it would just be "product".
<ide> # See table_name for the full rules on table/class naming. This is true, by default.
<ide>
<del> ##
<del> # :singleton-method: ignored_columns
<del> # :call-seq: ignored_columns
<del> #
<del> # The list of columns names the model should ignore. Ignored columns won't have attribute
<del> # accessors defined, and won't be referenced in SQL queries.
<del>
<del> ##
<del> # :singleton-method: ignored_columns=
<del> # :call-seq: ignored_columns=(columns)
<del> #
<del> # Sets the columns names the model should ignore. Ignored columns won't have attribute
<del> # accessors defined, and won't be referenced in SQL queries.
<del>
<ide> included do
<ide> mattr_accessor :primary_key_prefix_type, instance_writer: false
<ide>
<ide> module ModelSchema
<ide> class_attribute :internal_metadata_table_name, instance_accessor: false, default: "ar_internal_metadata"
<ide> class_attribute :protected_environments, instance_accessor: false, default: [ "production" ]
<ide> class_attribute :pluralize_table_names, instance_writer: false, default: true
<del> class_attribute :ignored_columns, instance_accessor: false, default: [].freeze
<ide>
<ide> self.inheritance_column = "type"
<add> self.ignored_columns = [].freeze
<ide>
<ide> delegate :type_for_attribute, to: :class
<ide>
<ide> def inheritance_column=(value)
<ide> @explicit_inheritance_column = true
<ide> end
<ide>
<add> # The list of columns names the model should ignore. Ignored columns won't have attribute
<add> # accessors defined, and won't be referenced in SQL queries.
<add> def ignored_columns
<add> if defined?(@ignored_columns)
<add> @ignored_columns
<add> else
<add> superclass.ignored_columns
<add> end
<add> end
<add>
<add> # Sets the columns names the model should ignore. Ignored columns won't have attribute
<add> # accessors defined, and won't be referenced in SQL queries.
<add> def ignored_columns=(columns)
<add> @ignored_columns = columns.map(&:to_s)
<add> end
<add>
<ide> def sequence_name
<ide> if base_class == self
<ide> @sequence_name ||= reset_sequence_name
<ide><path>activerecord/test/cases/base_test.rb
<ide> def test_default_values_are_deeply_dupped
<ide> assert_includes cache_columns.keys, "first_name"
<ide> assert_not_includes Developer.columns_hash.keys, "first_name"
<ide> assert_not_includes SubDeveloper.columns_hash.keys, "first_name"
<add> assert_not_includes SymbolIgnoredDeveloper.columns_hash.keys, "first_name"
<ide> end
<ide>
<ide> test "ignored columns have no attribute methods" do
<ide> def test_default_values_are_deeply_dupped
<ide> refute SubDeveloper.new.respond_to?(:first_name)
<ide> refute SubDeveloper.new.respond_to?(:first_name=)
<ide> refute SubDeveloper.new.respond_to?(:first_name?)
<add> refute SymbolIgnoredDeveloper.new.respond_to?(:first_name)
<add> refute SymbolIgnoredDeveloper.new.respond_to?(:first_name=)
<add> refute SymbolIgnoredDeveloper.new.respond_to?(:first_name?)
<ide> end
<ide>
<ide> test "ignored columns don't prevent explicit declaration of attribute methods" do
<ide> def test_default_values_are_deeply_dupped
<ide> assert SubDeveloper.new.respond_to?(:last_name)
<ide> assert SubDeveloper.new.respond_to?(:last_name=)
<ide> assert SubDeveloper.new.respond_to?(:last_name?)
<add> assert SymbolIgnoredDeveloper.new.respond_to?(:last_name)
<add> assert SymbolIgnoredDeveloper.new.respond_to?(:last_name=)
<add> assert SymbolIgnoredDeveloper.new.respond_to?(:last_name?)
<add> end
<add>
<add> test "ignored columns are stored as an array of string" do
<add> assert_equal(%w(first_name last_name), Developer.ignored_columns)
<add> assert_equal(%w(first_name last_name), SymbolIgnoredDeveloper.ignored_columns)
<ide> end
<ide> end
<ide><path>activerecord/test/models/developer.rb
<ide> def track_instance_count
<ide> class SubDeveloper < Developer
<ide> end
<ide>
<add>class SymbolIgnoredDeveloper < ActiveRecord::Base
<add> self.table_name = "developers"
<add> self.ignored_columns = [:first_name, :last_name]
<add>
<add> attr_accessor :last_name
<add> define_attribute_method "last_name"
<add>end
<add>
<ide> class AuditLog < ActiveRecord::Base
<ide> belongs_to :developer, validate: true
<ide> belongs_to :unvalidated_developer, class_name: "Developer" | 3 |
Mixed | Javascript | add `ticks.precision` option to linear scale. | 9fbac8893865fc6f7efdab7f49d480e6a730c669 | <ide><path>docs/axes/cartesian/linear.md
<ide> The following options are provided by the linear scale. They are all located in
<ide> | `min` | `Number` | | User defined minimum number for the scale, overrides minimum value from data. [more...](#axis-range-settings)
<ide> | `max` | `Number` | | User defined maximum number for the scale, overrides maximum value from data. [more...](#axis-range-settings)
<ide> | `maxTicksLimit` | `Number` | `11` | Maximum number of ticks and gridlines to show.
<add>| `precision` | `Number` | | if defined and `stepSize` is not specified, the step size will be rounded to this many decimal places.
<ide> | `stepSize` | `Number` | | User defined fixed step size for the scale. [more...](#step-size)
<ide> | `suggestedMax` | `Number` | | Adjustment used when calculating the maximum data value. [more...](#axis-range-settings)
<ide> | `suggestedMin` | `Number` | | Adjustment used when calculating the minimum data value. [more...](#axis-range-settings)
<ide><path>docs/axes/radial/linear.md
<ide> The following options are provided by the linear scale. They are all located in
<ide> | `min` | `Number` | | User defined minimum number for the scale, overrides minimum value from data. [more...](#axis-range-settings)
<ide> | `max` | `Number` | | User defined maximum number for the scale, overrides maximum value from data. [more...](#axis-range-settings)
<ide> | `maxTicksLimit` | `Number` | `11` | Maximum number of ticks and gridlines to show.
<add>| `precision` | `Number` | | if defined and `stepSize` is not specified, the step size will be rounded to this many decimal places.
<ide> | `stepSize` | `Number` | | User defined fixed step size for the scale. [more...](#step-size)
<ide> | `suggestedMax` | `Number` | | Adjustment used when calculating the maximum data value. [more...](#axis-range-settings)
<ide> | `suggestedMin` | `Number` | | Adjustment used when calculating the minimum data value. [more...](#axis-range-settings)
<ide><path>src/scales/scale.linearbase.js
<ide> function generateTicks(generationOptions, dataRange) {
<ide> // "nice number" algorithm. See http://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks
<ide> // for details.
<ide>
<add> var factor;
<add> var precision;
<ide> var spacing;
<add>
<ide> if (generationOptions.stepSize && generationOptions.stepSize > 0) {
<ide> spacing = generationOptions.stepSize;
<ide> } else {
<ide> var niceRange = helpers.niceNum(dataRange.max - dataRange.min, false);
<ide> spacing = helpers.niceNum(niceRange / (generationOptions.maxTicks - 1), true);
<add>
<add> precision = generationOptions.precision;
<add> if (precision !== undefined) {
<add> // If the user specified a precision, round to that number of decimal places
<add> factor = Math.pow(10, precision);
<add> spacing = Math.ceil(spacing * factor) / factor;
<add> }
<ide> }
<ide> var niceMin = Math.floor(dataRange.min / spacing) * spacing;
<ide> var niceMax = Math.ceil(dataRange.max / spacing) * spacing;
<ide> function generateTicks(generationOptions, dataRange) {
<ide> numSpaces = Math.ceil(numSpaces);
<ide> }
<ide>
<del> var precision = 1;
<add> precision = 1;
<ide> if (spacing < 1) {
<ide> precision = Math.pow(10, spacing.toString().length - 2);
<ide> niceMin = Math.round(niceMin * precision) / precision;
<ide> module.exports = function(Chart) {
<ide> maxTicks: maxTicks,
<ide> min: tickOpts.min,
<ide> max: tickOpts.max,
<add> precision: tickOpts.precision,
<ide> stepSize: helpers.valueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize)
<ide> };
<ide> var ticks = me.ticks = generateTicks(numericGeneratorOptions, me);
<ide><path>test/specs/scale.linear.tests.js
<ide> describe('Linear Scale', function() {
<ide> expect(chart.scales.yScale0.ticks).toEqual(['11', '9', '7', '5', '3', '1']);
<ide> });
<ide>
<add> describe('precision', function() {
<add> it('Should create integer steps if precision is 0', function() {
<add> var chart = window.acquireChart({
<add> type: 'bar',
<add> data: {
<add> datasets: [{
<add> yAxisID: 'yScale0',
<add> data: [0, 1, 2, 1, 0, 1]
<add> }],
<add> labels: ['a', 'b', 'c', 'd', 'e', 'f']
<add> },
<add> options: {
<add> scales: {
<add> yAxes: [{
<add> id: 'yScale0',
<add> type: 'linear',
<add> ticks: {
<add> precision: 0
<add> }
<add> }]
<add> }
<add> }
<add> });
<add>
<add> expect(chart.scales.yScale0).not.toEqual(undefined); // must construct
<add> expect(chart.scales.yScale0.min).toBe(0);
<add> expect(chart.scales.yScale0.max).toBe(2);
<add> expect(chart.scales.yScale0.ticks).toEqual(['2', '1', '0']);
<add> });
<add>
<add> it('Should round the step size to the given number of decimal places', function() {
<add> var chart = window.acquireChart({
<add> type: 'bar',
<add> data: {
<add> datasets: [{
<add> yAxisID: 'yScale0',
<add> data: [0, 0.001, 0.002, 0.003, 0, 0.001]
<add> }],
<add> labels: ['a', 'b', 'c', 'd', 'e', 'f']
<add> },
<add> options: {
<add> scales: {
<add> yAxes: [{
<add> id: 'yScale0',
<add> type: 'linear',
<add> ticks: {
<add> precision: 2
<add> }
<add> }]
<add> }
<add> }
<add> });
<add>
<add> expect(chart.scales.yScale0).not.toEqual(undefined); // must construct
<add> expect(chart.scales.yScale0.min).toBe(0);
<add> expect(chart.scales.yScale0.max).toBe(0.01);
<add> expect(chart.scales.yScale0.ticks).toEqual(['0.01', '0']);
<add> });
<add> });
<add>
<ide>
<ide> it('should forcibly include 0 in the range if the beginAtZero option is used', function() {
<ide> var chart = window.acquireChart({ | 4 |
Python | Python | fix other pytorch models | 2f3a4210185f5311f6cfab3c91b30616c9a30fc8 | <ide><path>templates/adding_a_new_model/modeling_xxx.py
<ide> def forward(self, input_ids=None, attention_mask=None, token_type_ids=None, posi
<ide> else:
<ide> raise ValueError("You have to specify either input_ids or inputs_embeds")
<ide>
<add> device = input_ids.device if input_ids is not None else inputs_embeds.device
<add>
<ide> if attention_mask is None:
<del> attention_mask = torch.ones(input_shape)
<add> attention_mask = torch.ones(input_shape, device=device)
<ide> if token_type_ids is None:
<del> token_type_ids = torch.zeros(input_shape, dtype=torch.long)
<add> token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
<ide>
<ide> # We create a 3D attention mask from a 2D tensor mask.
<ide> # Sizes are [batch_size, 1, 1, to_seq_length]
<ide><path>transformers/modeling_distilbert.py
<ide> def forward(self,
<ide> else:
<ide> raise ValueError("You have to specify either input_ids or inputs_embeds")
<ide>
<add> device = input_ids.device if input_ids is not None else inputs_embeds.device
<add>
<ide> if attention_mask is None:
<del> attention_mask = torch.ones(input_shape) # (bs, seq_length)
<add> attention_mask = torch.ones(input_shape, device=device) # (bs, seq_length)
<ide>
<ide> # Prepare head mask if needed
<ide> # 1.0 in head_mask indicate we keep the head | 2 |
Java | Java | reinstate tests for deprecated metaannotationutils | 82fa3f3fc10c578a396ed3f97a1445f640f0b2ba | <ide><path>spring-test/src/test/java/org/springframework/test/util/MetaAnnotationUtilsTests.java
<add>/*
<add> * Copyright 2002-2020 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> * https://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.test.util;
<add>
<add>import java.lang.annotation.Annotation;
<add>import java.lang.annotation.Documented;
<add>import java.lang.annotation.ElementType;
<add>import java.lang.annotation.Retention;
<add>import java.lang.annotation.RetentionPolicy;
<add>import java.lang.annotation.Target;
<add>
<add>import org.junit.jupiter.api.Test;
<add>
<add>import org.springframework.core.annotation.AnnotationUtils;
<add>import org.springframework.core.annotation.Order;
<add>import org.springframework.stereotype.Component;
<add>import org.springframework.stereotype.Service;
<add>import org.springframework.test.context.ContextConfiguration;
<add>import org.springframework.test.util.MetaAnnotationUtils.AnnotationDescriptor;
<add>import org.springframework.test.util.MetaAnnotationUtils.UntypedAnnotationDescriptor;
<add>import org.springframework.transaction.annotation.Transactional;
<add>
<add>import static org.assertj.core.api.Assertions.assertThat;
<add>import static org.springframework.test.util.MetaAnnotationUtils.findAnnotationDescriptor;
<add>import static org.springframework.test.util.MetaAnnotationUtils.findAnnotationDescriptorForTypes;
<add>
<add>/**
<add> * Unit tests for {@link MetaAnnotationUtils}.
<add> *
<add> * @author Sam Brannen
<add> * @since 4.0
<add> * @see OverriddenMetaAnnotationAttributesTests
<add> */
<add>@SuppressWarnings("deprecation")
<add>class MetaAnnotationUtilsTests {
<add>
<add> private void assertAtComponentOnComposedAnnotation(
<add> Class<?> rootDeclaringClass, String name, Class<? extends Annotation> composedAnnotationType) {
<add>
<add> assertAtComponentOnComposedAnnotation(rootDeclaringClass, rootDeclaringClass, name, composedAnnotationType);
<add> }
<add>
<add> private void assertAtComponentOnComposedAnnotation(
<add> Class<?> startClass, Class<?> rootDeclaringClass, String name, Class<? extends Annotation> composedAnnotationType) {
<add>
<add> assertAtComponentOnComposedAnnotation(startClass, rootDeclaringClass, composedAnnotationType, name, composedAnnotationType);
<add> }
<add>
<add> private void assertAtComponentOnComposedAnnotation(Class<?> startClass, Class<?> rootDeclaringClass,
<add> Class<?> declaringClass, String name, Class<? extends Annotation> composedAnnotationType) {
<add>
<add> AnnotationDescriptor<Component> descriptor = findAnnotationDescriptor(startClass, Component.class);
<add> assertThat(descriptor).as("AnnotationDescriptor should not be null").isNotNull();
<add> assertThat(descriptor.getRootDeclaringClass()).as("rootDeclaringClass").isEqualTo(rootDeclaringClass);
<add> assertThat(descriptor.getDeclaringClass()).as("declaringClass").isEqualTo(declaringClass);
<add> assertThat(descriptor.getAnnotationType()).as("annotationType").isEqualTo(Component.class);
<add> assertThat(descriptor.getAnnotation().value()).as("component name").isEqualTo(name);
<add> assertThat(descriptor.getComposedAnnotation()).as("composedAnnotation should not be null").isNotNull();
<add> assertThat(descriptor.getComposedAnnotationType()).as("composedAnnotationType").isEqualTo(composedAnnotationType);
<add> }
<add>
<add> private void assertAtComponentOnComposedAnnotationForMultipleCandidateTypes(
<add> Class<?> startClass, String name, Class<? extends Annotation> composedAnnotationType) {
<add>
<add> assertAtComponentOnComposedAnnotationForMultipleCandidateTypes(
<add> startClass, startClass, name, composedAnnotationType);
<add> }
<add>
<add> private void assertAtComponentOnComposedAnnotationForMultipleCandidateTypes(Class<?> startClass,
<add> Class<?> rootDeclaringClass, String name, Class<? extends Annotation> composedAnnotationType) {
<add>
<add> assertAtComponentOnComposedAnnotationForMultipleCandidateTypes(
<add> startClass, rootDeclaringClass, composedAnnotationType, name, composedAnnotationType);
<add> }
<add>
<add> @SuppressWarnings("unchecked")
<add> private void assertAtComponentOnComposedAnnotationForMultipleCandidateTypes(Class<?> startClass,
<add> Class<?> rootDeclaringClass, Class<?> declaringClass, String name,
<add> Class<? extends Annotation> composedAnnotationType) {
<add>
<add> Class<Component> annotationType = Component.class;
<add> UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes(
<add> startClass, Service.class, annotationType, Order.class, Transactional.class);
<add>
<add> assertThat(descriptor).as("UntypedAnnotationDescriptor should not be null").isNotNull();
<add> assertThat(descriptor.getRootDeclaringClass()).as("rootDeclaringClass").isEqualTo(rootDeclaringClass);
<add> assertThat(descriptor.getDeclaringClass()).as("declaringClass").isEqualTo(declaringClass);
<add> assertThat(descriptor.getAnnotationType()).as("annotationType").isEqualTo(annotationType);
<add> assertThat(((Component) descriptor.getAnnotation()).value()).as("component name").isEqualTo(name);
<add> assertThat(descriptor.getComposedAnnotation()).as("composedAnnotation should not be null").isNotNull();
<add> assertThat(descriptor.getComposedAnnotationType()).as("composedAnnotationType").isEqualTo(composedAnnotationType);
<add> }
<add>
<add> @Test
<add> void findAnnotationDescriptorWithNoAnnotationPresent() {
<add> assertThat(findAnnotationDescriptor(NonAnnotatedInterface.class, Transactional.class)).isNull();
<add> assertThat(findAnnotationDescriptor(NonAnnotatedClass.class, Transactional.class)).isNull();
<add> }
<add>
<add> @Test
<add> void findAnnotationDescriptorWithInheritedAnnotationOnClass() {
<add> // Note: @Transactional is inherited
<add> assertThat(findAnnotationDescriptor(InheritedAnnotationClass.class, Transactional.class).getRootDeclaringClass()).isEqualTo(InheritedAnnotationClass.class);
<add> assertThat(findAnnotationDescriptor(SubInheritedAnnotationClass.class, Transactional.class).getRootDeclaringClass()).isEqualTo(InheritedAnnotationClass.class);
<add> }
<add>
<add> @Test
<add> void findAnnotationDescriptorWithInheritedAnnotationOnInterface() {
<add> // Note: @Transactional is inherited
<add> Transactional rawAnnotation = InheritedAnnotationInterface.class.getAnnotation(Transactional.class);
<add>
<add> AnnotationDescriptor<Transactional> descriptor =
<add> findAnnotationDescriptor(InheritedAnnotationInterface.class, Transactional.class);
<add> assertThat(descriptor).isNotNull();
<add> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(InheritedAnnotationInterface.class);
<add> assertThat(descriptor.getDeclaringClass()).isEqualTo(InheritedAnnotationInterface.class);
<add> assertThat(descriptor.getAnnotation()).isEqualTo(rawAnnotation);
<add>
<add> descriptor = findAnnotationDescriptor(SubInheritedAnnotationInterface.class, Transactional.class);
<add> assertThat(descriptor).isNotNull();
<add> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(SubInheritedAnnotationInterface.class);
<add> assertThat(descriptor.getDeclaringClass()).isEqualTo(InheritedAnnotationInterface.class);
<add> assertThat(descriptor.getAnnotation()).isEqualTo(rawAnnotation);
<add>
<add> descriptor = findAnnotationDescriptor(SubSubInheritedAnnotationInterface.class, Transactional.class);
<add> assertThat(descriptor).isNotNull();
<add> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(SubSubInheritedAnnotationInterface.class);
<add> assertThat(descriptor.getDeclaringClass()).isEqualTo(InheritedAnnotationInterface.class);
<add> assertThat(descriptor.getAnnotation()).isEqualTo(rawAnnotation);
<add> }
<add>
<add> @Test
<add> void findAnnotationDescriptorForNonInheritedAnnotationOnClass() {
<add> // Note: @Order is not inherited.
<add> assertThat(findAnnotationDescriptor(NonInheritedAnnotationClass.class, Order.class).getRootDeclaringClass()).isEqualTo(NonInheritedAnnotationClass.class);
<add> assertThat(findAnnotationDescriptor(SubNonInheritedAnnotationClass.class, Order.class).getRootDeclaringClass()).isEqualTo(NonInheritedAnnotationClass.class);
<add> }
<add>
<add> @Test
<add> void findAnnotationDescriptorForNonInheritedAnnotationOnInterface() {
<add> // Note: @Order is not inherited.
<add> Order rawAnnotation = NonInheritedAnnotationInterface.class.getAnnotation(Order.class);
<add>
<add> AnnotationDescriptor<Order> descriptor =
<add> findAnnotationDescriptor(NonInheritedAnnotationInterface.class, Order.class);
<add> assertThat(descriptor).isNotNull();
<add> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(NonInheritedAnnotationInterface.class);
<add> assertThat(descriptor.getDeclaringClass()).isEqualTo(NonInheritedAnnotationInterface.class);
<add> assertThat(descriptor.getAnnotation()).isEqualTo(rawAnnotation);
<add>
<add> descriptor = findAnnotationDescriptor(SubNonInheritedAnnotationInterface.class, Order.class);
<add> assertThat(descriptor).isNotNull();
<add> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(SubNonInheritedAnnotationInterface.class);
<add> assertThat(descriptor.getDeclaringClass()).isEqualTo(NonInheritedAnnotationInterface.class);
<add> assertThat(descriptor.getAnnotation()).isEqualTo(rawAnnotation);
<add> }
<add>
<add> @Test
<add> void findAnnotationDescriptorWithMetaComponentAnnotation() {
<add> assertAtComponentOnComposedAnnotation(HasMetaComponentAnnotation.class, "meta1", Meta1.class);
<add> }
<add>
<add> @Test
<add> void findAnnotationDescriptorWithLocalAndMetaComponentAnnotation() {
<add> Class<Component> annotationType = Component.class;
<add> AnnotationDescriptor<Component> descriptor = findAnnotationDescriptor(
<add> HasLocalAndMetaComponentAnnotation.class, annotationType);
<add>
<add> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(HasLocalAndMetaComponentAnnotation.class);
<add> assertThat(descriptor.getAnnotationType()).isEqualTo(annotationType);
<add> assertThat(descriptor.getComposedAnnotation()).isNull();
<add> assertThat(descriptor.getComposedAnnotationType()).isNull();
<add> }
<add>
<add> @Test
<add> void findAnnotationDescriptorForInterfaceWithMetaAnnotation() {
<add> assertAtComponentOnComposedAnnotation(InterfaceWithMetaAnnotation.class, "meta1", Meta1.class);
<add> }
<add>
<add> @Test
<add> void findAnnotationDescriptorForClassWithMetaAnnotatedInterface() {
<add> Component rawAnnotation = AnnotationUtils.findAnnotation(ClassWithMetaAnnotatedInterface.class, Component.class);
<add> AnnotationDescriptor<Component> descriptor =
<add> findAnnotationDescriptor(ClassWithMetaAnnotatedInterface.class, Component.class);
<add>
<add> assertThat(descriptor).isNotNull();
<add> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(ClassWithMetaAnnotatedInterface.class);
<add> assertThat(descriptor.getDeclaringClass()).isEqualTo(Meta1.class);
<add> assertThat(descriptor.getAnnotation()).isEqualTo(rawAnnotation);
<add> assertThat(descriptor.getComposedAnnotation().annotationType()).isEqualTo(Meta1.class);
<add> }
<add>
<add> @Test
<add> void findAnnotationDescriptorForClassWithLocalMetaAnnotationAndAnnotatedSuperclass() {
<add> AnnotationDescriptor<ContextConfiguration> descriptor = findAnnotationDescriptor(
<add> MetaAnnotatedAndSuperAnnotatedContextConfigClass.class, ContextConfiguration.class);
<add>
<add> assertThat(descriptor).as("AnnotationDescriptor should not be null").isNotNull();
<add> assertThat(descriptor.getRootDeclaringClass()).as("rootDeclaringClass").isEqualTo(MetaAnnotatedAndSuperAnnotatedContextConfigClass.class);
<add> assertThat(descriptor.getDeclaringClass()).as("declaringClass").isEqualTo(MetaConfig.class);
<add> assertThat(descriptor.getAnnotationType()).as("annotationType").isEqualTo(ContextConfiguration.class);
<add> assertThat(descriptor.getComposedAnnotation()).as("composedAnnotation should not be null").isNotNull();
<add> assertThat(descriptor.getComposedAnnotationType()).as("composedAnnotationType").isEqualTo(MetaConfig.class);
<add>
<add> assertThat(descriptor.getAnnotationAttributes().getClassArray("classes")).as("configured classes").isEqualTo(new Class<?>[] {String.class});
<add> }
<add>
<add> @Test
<add> void findAnnotationDescriptorForClassWithLocalMetaAnnotationAndMetaAnnotatedInterface() {
<add> assertAtComponentOnComposedAnnotation(ClassWithLocalMetaAnnotationAndMetaAnnotatedInterface.class, "meta2", Meta2.class);
<add> }
<add>
<add> @Test
<add> void findAnnotationDescriptorForSubClassWithLocalMetaAnnotationAndMetaAnnotatedInterface() {
<add> assertAtComponentOnComposedAnnotation(SubClassWithLocalMetaAnnotationAndMetaAnnotatedInterface.class,
<add> ClassWithLocalMetaAnnotationAndMetaAnnotatedInterface.class, "meta2", Meta2.class);
<add> }
<add>
<add> /**
<add> * @since 4.0.3
<add> */
<add> @Test
<add> void findAnnotationDescriptorOnMetaMetaAnnotatedClass() {
<add> Class<MetaMetaAnnotatedClass> startClass = MetaMetaAnnotatedClass.class;
<add> assertAtComponentOnComposedAnnotation(startClass, startClass, Meta2.class, "meta2", MetaMeta.class);
<add> }
<add>
<add> /**
<add> * @since 4.0.3
<add> */
<add> @Test
<add> void findAnnotationDescriptorOnMetaMetaMetaAnnotatedClass() {
<add> Class<MetaMetaMetaAnnotatedClass> startClass = MetaMetaMetaAnnotatedClass.class;
<add> assertAtComponentOnComposedAnnotation(startClass, startClass, Meta2.class, "meta2", MetaMetaMeta.class);
<add> }
<add>
<add> /**
<add> * @since 4.0.3
<add> */
<add> @Test
<add> void findAnnotationDescriptorOnAnnotatedClassWithMissingTargetMetaAnnotation() {
<add> // InheritedAnnotationClass is NOT annotated or meta-annotated with @Component
<add> AnnotationDescriptor<Component> descriptor = findAnnotationDescriptor(
<add> InheritedAnnotationClass.class, Component.class);
<add> assertThat(descriptor).as("Should not find @Component on InheritedAnnotationClass").isNull();
<add> }
<add>
<add> /**
<add> * @since 4.0.3
<add> */
<add> @Test
<add> void findAnnotationDescriptorOnMetaCycleAnnotatedClassWithMissingTargetMetaAnnotation() {
<add> AnnotationDescriptor<Component> descriptor = findAnnotationDescriptor(
<add> MetaCycleAnnotatedClass.class, Component.class);
<add> assertThat(descriptor).as("Should not find @Component on MetaCycleAnnotatedClass").isNull();
<add> }
<add>
<add> // -------------------------------------------------------------------------
<add>
<add> @Test
<add> @SuppressWarnings("unchecked")
<add> void findAnnotationDescriptorForTypesWithNoAnnotationPresent() {
<add> assertThat(findAnnotationDescriptorForTypes(NonAnnotatedInterface.class, Transactional.class, Component.class)).isNull();
<add> assertThat(findAnnotationDescriptorForTypes(NonAnnotatedClass.class, Transactional.class, Order.class)).isNull();
<add> }
<add>
<add> @Test
<add> @SuppressWarnings("unchecked")
<add> void findAnnotationDescriptorForTypesWithInheritedAnnotationOnClass() {
<add> // Note: @Transactional is inherited
<add> assertThat(findAnnotationDescriptorForTypes(InheritedAnnotationClass.class, Transactional.class).getRootDeclaringClass()).isEqualTo(InheritedAnnotationClass.class);
<add> assertThat(findAnnotationDescriptorForTypes(SubInheritedAnnotationClass.class, Transactional.class).getRootDeclaringClass()).isEqualTo(InheritedAnnotationClass.class);
<add> }
<add>
<add> @Test
<add> @SuppressWarnings("unchecked")
<add> void findAnnotationDescriptorForTypesWithInheritedAnnotationOnInterface() {
<add> // Note: @Transactional is inherited
<add> Transactional rawAnnotation = InheritedAnnotationInterface.class.getAnnotation(Transactional.class);
<add>
<add> UntypedAnnotationDescriptor descriptor =
<add> findAnnotationDescriptorForTypes(InheritedAnnotationInterface.class, Transactional.class);
<add> assertThat(descriptor).isNotNull();
<add> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(InheritedAnnotationInterface.class);
<add> assertThat(descriptor.getDeclaringClass()).isEqualTo(InheritedAnnotationInterface.class);
<add> assertThat(descriptor.getAnnotation()).isEqualTo(rawAnnotation);
<add>
<add> descriptor = findAnnotationDescriptorForTypes(SubInheritedAnnotationInterface.class, Transactional.class);
<add> assertThat(descriptor).isNotNull();
<add> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(SubInheritedAnnotationInterface.class);
<add> assertThat(descriptor.getDeclaringClass()).isEqualTo(InheritedAnnotationInterface.class);
<add> assertThat(descriptor.getAnnotation()).isEqualTo(rawAnnotation);
<add>
<add> descriptor = findAnnotationDescriptorForTypes(SubSubInheritedAnnotationInterface.class, Transactional.class);
<add> assertThat(descriptor).isNotNull();
<add> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(SubSubInheritedAnnotationInterface.class);
<add> assertThat(descriptor.getDeclaringClass()).isEqualTo(InheritedAnnotationInterface.class);
<add> assertThat(descriptor.getAnnotation()).isEqualTo(rawAnnotation);
<add> }
<add>
<add> @Test
<add> @SuppressWarnings("unchecked")
<add> void findAnnotationDescriptorForTypesForNonInheritedAnnotationOnClass() {
<add> // Note: @Order is not inherited.
<add> assertThat(findAnnotationDescriptorForTypes(NonInheritedAnnotationClass.class, Order.class).getRootDeclaringClass()).isEqualTo(NonInheritedAnnotationClass.class);
<add> assertThat(findAnnotationDescriptorForTypes(SubNonInheritedAnnotationClass.class, Order.class).getRootDeclaringClass()).isEqualTo(NonInheritedAnnotationClass.class);
<add> }
<add>
<add> @Test
<add> @SuppressWarnings("unchecked")
<add> void findAnnotationDescriptorForTypesForNonInheritedAnnotationOnInterface() {
<add> // Note: @Order is not inherited.
<add> Order rawAnnotation = NonInheritedAnnotationInterface.class.getAnnotation(Order.class);
<add>
<add> UntypedAnnotationDescriptor descriptor =
<add> findAnnotationDescriptorForTypes(NonInheritedAnnotationInterface.class, Order.class);
<add> assertThat(descriptor).isNotNull();
<add> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(NonInheritedAnnotationInterface.class);
<add> assertThat(descriptor.getDeclaringClass()).isEqualTo(NonInheritedAnnotationInterface.class);
<add> assertThat(descriptor.getAnnotation()).isEqualTo(rawAnnotation);
<add>
<add> descriptor = findAnnotationDescriptorForTypes(SubNonInheritedAnnotationInterface.class, Order.class);
<add> assertThat(descriptor).isNotNull();
<add> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(SubNonInheritedAnnotationInterface.class);
<add> assertThat(descriptor.getDeclaringClass()).isEqualTo(NonInheritedAnnotationInterface.class);
<add> assertThat(descriptor.getAnnotation()).isEqualTo(rawAnnotation);
<add> }
<add>
<add> @Test
<add> @SuppressWarnings("unchecked")
<add> void findAnnotationDescriptorForTypesWithLocalAndMetaComponentAnnotation() {
<add> Class<Component> annotationType = Component.class;
<add> UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes(
<add> HasLocalAndMetaComponentAnnotation.class, Transactional.class, annotationType, Order.class);
<add> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(HasLocalAndMetaComponentAnnotation.class);
<add> assertThat(descriptor.getAnnotationType()).isEqualTo(annotationType);
<add> assertThat(descriptor.getComposedAnnotation()).isNull();
<add> assertThat(descriptor.getComposedAnnotationType()).isNull();
<add> }
<add>
<add> @Test
<add> void findAnnotationDescriptorForTypesWithMetaComponentAnnotation() {
<add> Class<HasMetaComponentAnnotation> startClass = HasMetaComponentAnnotation.class;
<add> assertAtComponentOnComposedAnnotationForMultipleCandidateTypes(startClass, "meta1", Meta1.class);
<add> }
<add>
<add> @Test
<add> @SuppressWarnings("unchecked")
<add> void findAnnotationDescriptorForTypesWithMetaAnnotationWithDefaultAttributes() {
<add> Class<?> startClass = MetaConfigWithDefaultAttributesTestCase.class;
<add> Class<ContextConfiguration> annotationType = ContextConfiguration.class;
<add>
<add> UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes(startClass,
<add> Service.class, ContextConfiguration.class, Order.class, Transactional.class);
<add>
<add> assertThat(descriptor).isNotNull();
<add> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(startClass);
<add> assertThat(descriptor.getAnnotationType()).isEqualTo(annotationType);
<add> assertThat(((ContextConfiguration) descriptor.getAnnotation()).value()).isEqualTo(new Class<?>[] {});
<add> assertThat(descriptor.getAnnotationAttributes().getClassArray("classes")).isEqualTo(new Class<?>[] {MetaConfig.DevConfig.class, MetaConfig.ProductionConfig.class});
<add> assertThat(descriptor.getComposedAnnotation()).isNotNull();
<add> assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaConfig.class);
<add> }
<add>
<add> @Test
<add> @SuppressWarnings("unchecked")
<add> void findAnnotationDescriptorForTypesWithMetaAnnotationWithOverriddenAttributes() {
<add> Class<?> startClass = MetaConfigWithOverriddenAttributesTestCase.class;
<add> Class<ContextConfiguration> annotationType = ContextConfiguration.class;
<add>
<add> UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes(
<add> startClass, Service.class, ContextConfiguration.class, Order.class, Transactional.class);
<add>
<add> assertThat(descriptor).isNotNull();
<add> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(startClass);
<add> assertThat(descriptor.getAnnotationType()).isEqualTo(annotationType);
<add> assertThat(((ContextConfiguration) descriptor.getAnnotation()).value()).isEqualTo(new Class<?>[] {});
<add> assertThat(descriptor.getAnnotationAttributes().getClassArray("classes")).isEqualTo(new Class<?>[] {MetaAnnotationUtilsTests.class});
<add> assertThat(descriptor.getComposedAnnotation()).isNotNull();
<add> assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaConfig.class);
<add> }
<add>
<add> @Test
<add> void findAnnotationDescriptorForTypesForInterfaceWithMetaAnnotation() {
<add> Class<InterfaceWithMetaAnnotation> startClass = InterfaceWithMetaAnnotation.class;
<add> assertAtComponentOnComposedAnnotationForMultipleCandidateTypes(startClass, "meta1", Meta1.class);
<add> }
<add>
<add> @Test
<add> @SuppressWarnings("unchecked")
<add> void findAnnotationDescriptorForTypesForClassWithMetaAnnotatedInterface() {
<add> Component rawAnnotation = AnnotationUtils.findAnnotation(ClassWithMetaAnnotatedInterface.class, Component.class);
<add>
<add> UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes(
<add> ClassWithMetaAnnotatedInterface.class, Service.class, Component.class, Order.class, Transactional.class);
<add>
<add> assertThat(descriptor).isNotNull();
<add> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(ClassWithMetaAnnotatedInterface.class);
<add> assertThat(descriptor.getDeclaringClass()).isEqualTo(Meta1.class);
<add> assertThat(descriptor.getAnnotation()).isEqualTo(rawAnnotation);
<add> assertThat(descriptor.getComposedAnnotation().annotationType()).isEqualTo(Meta1.class);
<add> }
<add>
<add> @Test
<add> void findAnnotationDescriptorForTypesForClassWithLocalMetaAnnotationAndMetaAnnotatedInterface() {
<add> Class<ClassWithLocalMetaAnnotationAndMetaAnnotatedInterface> startClass = ClassWithLocalMetaAnnotationAndMetaAnnotatedInterface.class;
<add> assertAtComponentOnComposedAnnotationForMultipleCandidateTypes(startClass, "meta2", Meta2.class);
<add> }
<add>
<add> @Test
<add> void findAnnotationDescriptorForTypesForSubClassWithLocalMetaAnnotationAndMetaAnnotatedInterface() {
<add> assertAtComponentOnComposedAnnotationForMultipleCandidateTypes(
<add> SubClassWithLocalMetaAnnotationAndMetaAnnotatedInterface.class,
<add> ClassWithLocalMetaAnnotationAndMetaAnnotatedInterface.class, "meta2", Meta2.class);
<add> }
<add>
<add> /**
<add> * @since 4.0.3
<add> */
<add> @Test
<add> void findAnnotationDescriptorForTypesOnMetaMetaAnnotatedClass() {
<add> Class<MetaMetaAnnotatedClass> startClass = MetaMetaAnnotatedClass.class;
<add> assertAtComponentOnComposedAnnotationForMultipleCandidateTypes(
<add> startClass, startClass, Meta2.class, "meta2", MetaMeta.class);
<add> }
<add>
<add> /**
<add> * @since 4.0.3
<add> */
<add> @Test
<add> void findAnnotationDescriptorForTypesOnMetaMetaMetaAnnotatedClass() {
<add> Class<MetaMetaMetaAnnotatedClass> startClass = MetaMetaMetaAnnotatedClass.class;
<add> assertAtComponentOnComposedAnnotationForMultipleCandidateTypes(
<add> startClass, startClass, Meta2.class, "meta2", MetaMetaMeta.class);
<add> }
<add>
<add> /**
<add> * @since 4.0.3
<add> */
<add> @Test
<add> @SuppressWarnings("unchecked")
<add> void findAnnotationDescriptorForTypesOnAnnotatedClassWithMissingTargetMetaAnnotation() {
<add> // InheritedAnnotationClass is NOT annotated or meta-annotated with @Component,
<add> // @Service, or @Order, but it is annotated with @Transactional.
<add> UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes(
<add> InheritedAnnotationClass.class, Service.class, Component.class, Order.class);
<add> assertThat(descriptor).as("Should not find @Component on InheritedAnnotationClass").isNull();
<add> }
<add>
<add> /**
<add> * @since 4.0.3
<add> */
<add> @Test
<add> @SuppressWarnings("unchecked")
<add> void findAnnotationDescriptorForTypesOnMetaCycleAnnotatedClassWithMissingTargetMetaAnnotation() {
<add> UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes(
<add> MetaCycleAnnotatedClass.class, Service.class, Component.class, Order.class);
<add> assertThat(descriptor).as("Should not find @Component on MetaCycleAnnotatedClass").isNull();
<add> }
<add>
<add>
<add> // -------------------------------------------------------------------------
<add>
<add> @Component(value = "meta1")
<add> @Order
<add> @Retention(RetentionPolicy.RUNTIME)
<add> @Target(ElementType.TYPE)
<add> @Documented
<add> static @interface Meta1 {
<add> }
<add>
<add> @Component(value = "meta2")
<add> @Transactional
<add> @Retention(RetentionPolicy.RUNTIME)
<add> @Target(ElementType.TYPE)
<add> @Documented
<add> static @interface Meta2 {
<add> }
<add>
<add> @Meta2
<add> @Retention(RetentionPolicy.RUNTIME)
<add> @Target(ElementType.TYPE)
<add> @Documented
<add> @interface MetaMeta {
<add> }
<add>
<add> @MetaMeta
<add> @Retention(RetentionPolicy.RUNTIME)
<add> @Target(ElementType.TYPE)
<add> @Documented
<add> @interface MetaMetaMeta {
<add> }
<add>
<add> @MetaCycle3
<add> @Retention(RetentionPolicy.RUNTIME)
<add> @Target(ElementType.ANNOTATION_TYPE)
<add> @Documented
<add> @interface MetaCycle1 {
<add> }
<add>
<add> @MetaCycle1
<add> @Retention(RetentionPolicy.RUNTIME)
<add> @Target(ElementType.ANNOTATION_TYPE)
<add> @Documented
<add> @interface MetaCycle2 {
<add> }
<add>
<add> @MetaCycle2
<add> @Retention(RetentionPolicy.RUNTIME)
<add> @Target(ElementType.TYPE)
<add> @Documented
<add> @interface MetaCycle3 {
<add> }
<add>
<add> @ContextConfiguration
<add> @Retention(RetentionPolicy.RUNTIME)
<add> @Target(ElementType.TYPE)
<add> @Documented
<add> static @interface MetaConfig {
<add>
<add> static class DevConfig {
<add> }
<add>
<add> static class ProductionConfig {
<add> }
<add>
<add>
<add> Class<?>[] classes() default { DevConfig.class, ProductionConfig.class };
<add> }
<add>
<add> // -------------------------------------------------------------------------
<add>
<add> @Meta1
<add> static class HasMetaComponentAnnotation {
<add> }
<add>
<add> @Meta1
<add> @Component(value = "local")
<add> @Meta2
<add> static class HasLocalAndMetaComponentAnnotation {
<add> }
<add>
<add> @Meta1
<add> static interface InterfaceWithMetaAnnotation {
<add> }
<add>
<add> static class ClassWithMetaAnnotatedInterface implements InterfaceWithMetaAnnotation {
<add> }
<add>
<add> @Meta2
<add> static class ClassWithLocalMetaAnnotationAndMetaAnnotatedInterface implements InterfaceWithMetaAnnotation {
<add> }
<add>
<add> static class SubClassWithLocalMetaAnnotationAndMetaAnnotatedInterface extends
<add> ClassWithLocalMetaAnnotationAndMetaAnnotatedInterface {
<add> }
<add>
<add> @MetaMeta
<add> static class MetaMetaAnnotatedClass {
<add> }
<add>
<add> @MetaMetaMeta
<add> static class MetaMetaMetaAnnotatedClass {
<add> }
<add>
<add> @MetaCycle3
<add> static class MetaCycleAnnotatedClass {
<add> }
<add>
<add> @MetaConfig
<add> class MetaConfigWithDefaultAttributesTestCase {
<add> }
<add>
<add> @MetaConfig(classes = MetaAnnotationUtilsTests.class)
<add> class MetaConfigWithOverriddenAttributesTestCase {
<add> }
<add>
<add> // -------------------------------------------------------------------------
<add>
<add> @Transactional
<add> static interface InheritedAnnotationInterface {
<add> }
<add>
<add> static interface SubInheritedAnnotationInterface extends InheritedAnnotationInterface {
<add> }
<add>
<add> static interface SubSubInheritedAnnotationInterface extends SubInheritedAnnotationInterface {
<add> }
<add>
<add> @Order
<add> static interface NonInheritedAnnotationInterface {
<add> }
<add>
<add> static interface SubNonInheritedAnnotationInterface extends NonInheritedAnnotationInterface {
<add> }
<add>
<add> static class NonAnnotatedClass {
<add> }
<add>
<add> static interface NonAnnotatedInterface {
<add> }
<add>
<add> @Transactional
<add> static class InheritedAnnotationClass {
<add> }
<add>
<add> static class SubInheritedAnnotationClass extends InheritedAnnotationClass {
<add> }
<add>
<add> @Order
<add> static class NonInheritedAnnotationClass {
<add> }
<add>
<add> static class SubNonInheritedAnnotationClass extends NonInheritedAnnotationClass {
<add> }
<add>
<add> @ContextConfiguration(classes = Number.class)
<add> static class AnnotatedContextConfigClass {
<add> }
<add>
<add> @MetaConfig(classes = String.class)
<add> static class MetaAnnotatedAndSuperAnnotatedContextConfigClass extends AnnotatedContextConfigClass {
<add> }
<add>
<add>}
<ide><path>spring-test/src/test/java/org/springframework/test/util/OverriddenMetaAnnotationAttributesTests.java
<add>/*
<add> * Copyright 2002-2020 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> * https://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.test.util;
<add>
<add>import java.lang.annotation.Retention;
<add>import java.lang.annotation.RetentionPolicy;
<add>
<add>import org.junit.jupiter.api.Test;
<add>
<add>import org.springframework.core.annotation.AnnotationAttributes;
<add>import org.springframework.test.context.ContextConfiguration;
<add>import org.springframework.test.util.MetaAnnotationUtils.AnnotationDescriptor;
<add>
<add>import static org.assertj.core.api.Assertions.assertThat;
<add>import static org.springframework.test.util.MetaAnnotationUtils.findAnnotationDescriptor;
<add>
<add>/**
<add> * Unit tests for {@link MetaAnnotationUtils} that verify support for overridden
<add> * meta-annotation attributes.
<add> *
<add> * <p>See <a href="https://jira.spring.io/browse/SPR-10181">SPR-10181</a>.
<add> *
<add> * @author Sam Brannen
<add> * @since 4.0
<add> * @see MetaAnnotationUtilsTests
<add> */
<add>@SuppressWarnings("deprecation")
<add>class OverriddenMetaAnnotationAttributesTests {
<add>
<add> @Test
<add> void contextConfigurationValue() throws Exception {
<add> Class<MetaValueConfigTestCase> declaringClass = MetaValueConfigTestCase.class;
<add> AnnotationDescriptor<ContextConfiguration> descriptor = findAnnotationDescriptor(declaringClass,
<add> ContextConfiguration.class);
<add> assertThat(descriptor).isNotNull();
<add> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(declaringClass);
<add> assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaValueConfig.class);
<add> assertThat(descriptor.getAnnotationType()).isEqualTo(ContextConfiguration.class);
<add> assertThat(descriptor.getComposedAnnotation()).isNotNull();
<add> assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaValueConfig.class);
<add>
<add> // direct access to annotation value:
<add> assertThat(descriptor.getAnnotation().value()).isEqualTo(new String[] { "foo.xml" });
<add> }
<add>
<add> @Test
<add> void overriddenContextConfigurationValue() throws Exception {
<add> Class<?> declaringClass = OverriddenMetaValueConfigTestCase.class;
<add> AnnotationDescriptor<ContextConfiguration> descriptor = findAnnotationDescriptor(declaringClass,
<add> ContextConfiguration.class);
<add> assertThat(descriptor).isNotNull();
<add> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(declaringClass);
<add> assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaValueConfig.class);
<add> assertThat(descriptor.getAnnotationType()).isEqualTo(ContextConfiguration.class);
<add> assertThat(descriptor.getComposedAnnotation()).isNotNull();
<add> assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaValueConfig.class);
<add>
<add> // direct access to annotation value:
<add> assertThat(descriptor.getAnnotation().value()).isEqualTo(new String[] { "foo.xml" });
<add>
<add> // overridden attribute:
<add> AnnotationAttributes attributes = descriptor.getAnnotationAttributes();
<add>
<add> // NOTE: we would like to be able to override the 'value' attribute; however,
<add> // Spring currently does not allow overrides for the 'value' attribute.
<add> // See SPR-11393 for related discussions.
<add> assertThat(attributes.getStringArray("value")).isEqualTo(new String[] { "foo.xml" });
<add> }
<add>
<add> @Test
<add> void contextConfigurationLocationsAndInheritLocations() throws Exception {
<add> Class<MetaLocationsConfigTestCase> declaringClass = MetaLocationsConfigTestCase.class;
<add> AnnotationDescriptor<ContextConfiguration> descriptor = findAnnotationDescriptor(declaringClass,
<add> ContextConfiguration.class);
<add> assertThat(descriptor).isNotNull();
<add> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(declaringClass);
<add> assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaLocationsConfig.class);
<add> assertThat(descriptor.getAnnotationType()).isEqualTo(ContextConfiguration.class);
<add> assertThat(descriptor.getComposedAnnotation()).isNotNull();
<add> assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaLocationsConfig.class);
<add>
<add> // direct access to annotation attributes:
<add> assertThat(descriptor.getAnnotation().locations()).isEqualTo(new String[] { "foo.xml" });
<add> assertThat(descriptor.getAnnotation().inheritLocations()).isFalse();
<add> }
<add>
<add> @Test
<add> void overriddenContextConfigurationLocationsAndInheritLocations() throws Exception {
<add> Class<?> declaringClass = OverriddenMetaLocationsConfigTestCase.class;
<add> AnnotationDescriptor<ContextConfiguration> descriptor = findAnnotationDescriptor(declaringClass,
<add> ContextConfiguration.class);
<add> assertThat(descriptor).isNotNull();
<add> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(declaringClass);
<add> assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaLocationsConfig.class);
<add> assertThat(descriptor.getAnnotationType()).isEqualTo(ContextConfiguration.class);
<add> assertThat(descriptor.getComposedAnnotation()).isNotNull();
<add> assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaLocationsConfig.class);
<add>
<add> // direct access to annotation attributes:
<add> assertThat(descriptor.getAnnotation().locations()).isEqualTo(new String[] { "foo.xml" });
<add> assertThat(descriptor.getAnnotation().inheritLocations()).isFalse();
<add>
<add> // overridden attributes:
<add> AnnotationAttributes attributes = descriptor.getAnnotationAttributes();
<add> assertThat(attributes.getStringArray("locations")).isEqualTo(new String[] { "bar.xml" });
<add> assertThat(attributes.getBoolean("inheritLocations")).isTrue();
<add> }
<add>
<add>
<add> // -------------------------------------------------------------------------
<add>
<add> @ContextConfiguration("foo.xml")
<add> @Retention(RetentionPolicy.RUNTIME)
<add> static @interface MetaValueConfig {
<add>
<add> String[] value() default {};
<add> }
<add>
<add> @MetaValueConfig
<add> static class MetaValueConfigTestCase {
<add> }
<add>
<add> @MetaValueConfig("bar.xml")
<add> static class OverriddenMetaValueConfigTestCase {
<add> }
<add>
<add> @ContextConfiguration(locations = "foo.xml", inheritLocations = false)
<add> @Retention(RetentionPolicy.RUNTIME)
<add> static @interface MetaLocationsConfig {
<add>
<add> String[] locations() default {};
<add>
<add> boolean inheritLocations();
<add> }
<add>
<add> @MetaLocationsConfig(inheritLocations = true)
<add> static class MetaLocationsConfigTestCase {
<add> }
<add>
<add> @MetaLocationsConfig(locations = "bar.xml", inheritLocations = true)
<add> static class OverriddenMetaLocationsConfigTestCase {
<add> }
<add>
<add>} | 2 |
Java | Java | add serverresponse.async() in webmvc.fn | 4e76a4780c4e0f5d496c9c0b75e1f9dab2d0b57c | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/function/AsyncServerResponse.java
<add>/*
<add> * Copyright 2002-2020 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> * https://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.web.servlet.function;
<add>
<add>import java.io.IOException;
<add>import java.util.concurrent.CompletableFuture;
<add>import java.util.concurrent.atomic.AtomicInteger;
<add>import java.util.function.Function;
<add>
<add>import javax.servlet.AsyncContext;
<add>import javax.servlet.AsyncListener;
<add>import javax.servlet.ServletContext;
<add>import javax.servlet.ServletException;
<add>import javax.servlet.ServletRequest;
<add>import javax.servlet.ServletResponse;
<add>import javax.servlet.http.Cookie;
<add>import javax.servlet.http.HttpServletRequest;
<add>import javax.servlet.http.HttpServletRequestWrapper;
<add>import javax.servlet.http.HttpServletResponse;
<add>
<add>import org.reactivestreams.Publisher;
<add>import org.reactivestreams.Subscriber;
<add>import org.reactivestreams.Subscription;
<add>
<add>import org.springframework.core.ReactiveAdapter;
<add>import org.springframework.core.ReactiveAdapterRegistry;
<add>import org.springframework.http.HttpHeaders;
<add>import org.springframework.http.HttpStatus;
<add>import org.springframework.lang.Nullable;
<add>import org.springframework.util.Assert;
<add>import org.springframework.util.ClassUtils;
<add>import org.springframework.util.MultiValueMap;
<add>import org.springframework.web.servlet.ModelAndView;
<add>
<add>/**
<add> * Implementation of {@link ServerResponse} based on a {@link CompletableFuture}.
<add> *
<add> * @author Arjen Poutsma
<add> * @since 5.3
<add> * @see ServerResponse#async(Object)
<add> */
<add>final class AsyncServerResponse extends ErrorHandlingServerResponse {
<add>
<add> static final boolean reactiveStreamsPresent = ClassUtils.isPresent(
<add> "org.reactivestreams.Publisher", AsyncServerResponse.class.getClassLoader());
<add>
<add>
<add> private final CompletableFuture<ServerResponse> futureResponse;
<add>
<add>
<add> private AsyncServerResponse(CompletableFuture<ServerResponse> futureResponse) {
<add> this.futureResponse = futureResponse;
<add> }
<add>
<add> @Override
<add> public HttpStatus statusCode() {
<add> return delegate(ServerResponse::statusCode);
<add> }
<add>
<add> @Override
<add> public int rawStatusCode() {
<add> return delegate(ServerResponse::rawStatusCode);
<add> }
<add>
<add> @Override
<add> public HttpHeaders headers() {
<add> return delegate(ServerResponse::headers);
<add> }
<add>
<add> @Override
<add> public MultiValueMap<String, Cookie> cookies() {
<add> return delegate(ServerResponse::cookies);
<add> }
<add>
<add> private <R> R delegate(Function<ServerResponse, R> function) {
<add> ServerResponse response = this.futureResponse.getNow(null);
<add> if (response != null) {
<add> return function.apply(response);
<add> }
<add> else {
<add> throw new IllegalStateException("Future ServerResponse has not yet completed");
<add> }
<add> }
<add>
<add> @Nullable
<add> @Override
<add> public ModelAndView writeTo(HttpServletRequest request, HttpServletResponse response, Context context) {
<add>
<add> SharedAsyncContextHttpServletRequest sharedRequest = new SharedAsyncContextHttpServletRequest(request);
<add> AsyncContext asyncContext = sharedRequest.startAsync(request, response);
<add> this.futureResponse.whenComplete((futureResponse, futureThrowable) -> {
<add> try {
<add> if (futureResponse != null) {
<add> ModelAndView mav = futureResponse.writeTo(sharedRequest, response, context);
<add> Assert.state(mav == null, "Asynchronous, rendering ServerResponse implementations are not " +
<add> "supported in WebMvc.fn. Please use WebFlux.fn instead.");
<add> }
<add> else if (futureThrowable != null) {
<add> handleError(futureThrowable, request, response, context);
<add> }
<add> }
<add> catch (Throwable throwable) {
<add> try {
<add> handleError(throwable, request, response, context);
<add> }
<add> catch (ServletException | IOException ex) {
<add> logger.warn("Asynchronous execution resulted in exception", ex);
<add> }
<add> }
<add> finally {
<add> asyncContext.complete();
<add> }
<add> });
<add> return null;
<add> }
<add>
<add>
<add> @SuppressWarnings({"unchecked"})
<add> public static ServerResponse create(Object o) {
<add> Assert.notNull(o, "Argument to async must not be null");
<add>
<add> if (o instanceof CompletableFuture) {
<add> CompletableFuture<ServerResponse> futureResponse = (CompletableFuture<ServerResponse>) o;
<add> return new AsyncServerResponse(futureResponse);
<add> }
<add> else if (reactiveStreamsPresent) {
<add> ReactiveAdapter adapter = ReactiveAdapterRegistry.getSharedInstance().getAdapter(o.getClass());
<add> if (adapter != null) {
<add> Publisher<ServerResponse> publisher = adapter.toPublisher(o);
<add> CompletableFuture<ServerResponse> futureResponse = new CompletableFuture<>();
<add> publisher.subscribe(new ToFutureSubscriber(futureResponse));
<add> return new AsyncServerResponse(futureResponse);
<add> }
<add> }
<add> throw new IllegalArgumentException("Asynchronous type not supported: " + o.getClass());
<add> }
<add>
<add>
<add> /**
<add> * Subscriber that exposes the first result it receives via a CompletableFuture.
<add> */
<add> private static final class ToFutureSubscriber implements Subscriber<ServerResponse> {
<add>
<add> private final CompletableFuture<ServerResponse> future;
<add>
<add> @Nullable
<add> private Subscription subscription;
<add>
<add>
<add> public ToFutureSubscriber(CompletableFuture<ServerResponse> future) {
<add> this.future = future;
<add> }
<add>
<add> @Override
<add> public void onSubscribe(Subscription s) {
<add> if (this.subscription == null) {
<add> this.subscription = s;
<add> s.request(1);
<add> }
<add> else {
<add> s.cancel();
<add> }
<add> }
<add>
<add> @Override
<add> public void onNext(ServerResponse serverResponse) {
<add> if (!this.future.isDone()) {
<add> this.future.complete(serverResponse);
<add> }
<add> }
<add>
<add> @Override
<add> public void onError(Throwable t) {
<add> if (!this.future.isDone()) {
<add> this.future.completeExceptionally(t);
<add> }
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> if (!this.future.isDone()) {
<add> this.future.completeExceptionally(new IllegalStateException("Did not receive ServerResponse"));
<add> }
<add> }
<add> }
<add>
<add>
<add> /**
<add> * HttpServletRequestWrapper that shares its AsyncContext between this
<add> * AsyncServerResponse class and other, subsequent ServerResponse
<add> * implementations, keeping track of how many contexts where
<add> * started with startAsync(). This way, we make sure that
<add> * {@link AsyncContext#complete()} only completes for the response that
<add> * finishes last, and is not closed prematurely.
<add> */
<add> private static final class SharedAsyncContextHttpServletRequest extends HttpServletRequestWrapper {
<add>
<add> private final AsyncContext asyncContext;
<add>
<add> private final AtomicInteger startedContexts;
<add>
<add> public SharedAsyncContextHttpServletRequest(HttpServletRequest request) {
<add> super(request);
<add> this.asyncContext = request.startAsync();
<add> this.startedContexts = new AtomicInteger(0);
<add> }
<add>
<add> private SharedAsyncContextHttpServletRequest(HttpServletRequest request, AsyncContext asyncContext,
<add> AtomicInteger startedContexts) {
<add> super(request);
<add> this.asyncContext = asyncContext;
<add> this.startedContexts = startedContexts;
<add> }
<add>
<add> @Override
<add> public AsyncContext startAsync() throws IllegalStateException {
<add> this.startedContexts.incrementAndGet();
<add> return new SharedAsyncContext(this.asyncContext, this, this.asyncContext.getResponse(),
<add> this.startedContexts);
<add> }
<add>
<add> @Override
<add> public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse)
<add> throws IllegalStateException {
<add> this.startedContexts.incrementAndGet();
<add> SharedAsyncContextHttpServletRequest sharedRequest;
<add> if (servletRequest instanceof SharedAsyncContextHttpServletRequest) {
<add> sharedRequest = (SharedAsyncContextHttpServletRequest) servletRequest;
<add> }
<add> else {
<add> sharedRequest = new SharedAsyncContextHttpServletRequest((HttpServletRequest) servletRequest,
<add> this.asyncContext, this.startedContexts);
<add> }
<add> return new SharedAsyncContext(this.asyncContext, sharedRequest, servletResponse, this.startedContexts);
<add> }
<add>
<add> @Override
<add> public AsyncContext getAsyncContext() {
<add> return new SharedAsyncContext(this.asyncContext, this, this.asyncContext.getResponse(), this.startedContexts);
<add> }
<add>
<add>
<add> private static final class SharedAsyncContext implements AsyncContext {
<add>
<add> private final AsyncContext delegate;
<add>
<add> private final AtomicInteger openContexts;
<add>
<add> private final ServletRequest request;
<add>
<add> private final ServletResponse response;
<add>
<add>
<add> public SharedAsyncContext(AsyncContext delegate, SharedAsyncContextHttpServletRequest request,
<add> ServletResponse response, AtomicInteger usageCount) {
<add>
<add> this.delegate = delegate;
<add> this.request = request;
<add> this.response = response;
<add> this.openContexts = usageCount;
<add> }
<add>
<add> @Override
<add> public void complete() {
<add> if (this.openContexts.decrementAndGet() == 0) {
<add> this.delegate.complete();
<add> }
<add> }
<add>
<add> @Override
<add> public ServletRequest getRequest() {
<add> return this.request;
<add> }
<add>
<add> @Override
<add> public ServletResponse getResponse() {
<add> return this.response;
<add> }
<add>
<add> @Override
<add> public boolean hasOriginalRequestAndResponse() {
<add> return this.delegate.hasOriginalRequestAndResponse();
<add> }
<add>
<add> @Override
<add> public void dispatch() {
<add> this.delegate.dispatch();
<add> }
<add>
<add> @Override
<add> public void dispatch(String path) {
<add> this.delegate.dispatch(path);
<add> }
<add>
<add> @Override
<add> public void dispatch(ServletContext context, String path) {
<add> this.delegate.dispatch(context, path);
<add> }
<add>
<add> @Override
<add> public void start(Runnable run) {
<add> this.delegate.start(run);
<add> }
<add>
<add> @Override
<add> public void addListener(AsyncListener listener) {
<add> this.delegate.addListener(listener);
<add> }
<add>
<add> @Override
<add> public void addListener(AsyncListener listener,
<add> ServletRequest servletRequest,
<add> ServletResponse servletResponse) {
<add>
<add> this.delegate.addListener(listener, servletRequest, servletResponse);
<add> }
<add>
<add> @Override
<add> public <T extends AsyncListener> T createListener(Class<T> clazz) throws ServletException {
<add> return this.delegate.createListener(clazz);
<add> }
<add>
<add> @Override
<add> public void setTimeout(long timeout) {
<add> this.delegate.setTimeout(timeout);
<add> }
<add>
<add> @Override
<add> public long getTimeout() {
<add> return this.delegate.getTimeout();
<add> }
<add> }
<add> }
<add>}
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultEntityResponseBuilder.java
<ide> import org.reactivestreams.Subscription;
<ide>
<ide> import org.springframework.core.ParameterizedTypeReference;
<add>import org.springframework.core.ReactiveAdapter;
<add>import org.springframework.core.ReactiveAdapterRegistry;
<ide> import org.springframework.core.io.InputStreamResource;
<ide> import org.springframework.core.io.Resource;
<ide> import org.springframework.core.io.support.ResourceRegion;
<ide> import org.springframework.http.server.ServletServerHttpResponse;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<del>import org.springframework.util.ClassUtils;
<ide> import org.springframework.util.LinkedMultiValueMap;
<ide> import org.springframework.util.MultiValueMap;
<ide> import org.springframework.web.HttpMediaTypeNotAcceptableException;
<ide> */
<ide> final class DefaultEntityResponseBuilder<T> implements EntityResponse.Builder<T> {
<ide>
<del> private static final boolean reactiveStreamsPresent = ClassUtils.isPresent(
<del> "org.reactivestreams.Publisher", DefaultEntityResponseBuilder.class.getClassLoader());
<del>
<ide> private static final Type RESOURCE_REGION_LIST_TYPE =
<ide> new ParameterizedTypeReference<List<ResourceRegion>>() { }.getType();
<ide>
<ide> public EntityResponse<T> build() {
<ide> return new CompletionStageEntityResponse(this.status, this.headers, this.cookies,
<ide> completionStage, this.entityType);
<ide> }
<del> else if (reactiveStreamsPresent && PublisherEntityResponse.isPublisher(this.entity)) {
<del> Publisher publisher = (Publisher) this.entity;
<del> return new PublisherEntityResponse(this.status, this.headers, this.cookies, publisher, this.entityType);
<del> }
<del> else {
<del> return new DefaultEntityResponse<>(this.status, this.headers, this.cookies, this.entity, this.entityType);
<add> else if (AsyncServerResponse.reactiveStreamsPresent) {
<add> ReactiveAdapter adapter = ReactiveAdapterRegistry.getSharedInstance().getAdapter(this.entity.getClass());
<add> if (adapter != null) {
<add> Publisher<T> publisher = adapter.toPublisher(this.entity);
<add> return new PublisherEntityResponse(this.status, this.headers, this.cookies, publisher, this.entityType);
<add> }
<ide> }
<add> return new DefaultEntityResponse<>(this.status, this.headers, this.cookies, this.entity, this.entityType);
<ide> }
<ide>
<ide>
<ide> private static MediaType getContentType(HttpServletResponse response) {
<ide> }
<ide>
<ide> protected void tryWriteEntityWithMessageConverters(Object entity, HttpServletRequest request,
<del> HttpServletResponse response, ServerResponse.Context context) {
<add> HttpServletResponse response, ServerResponse.Context context) throws ServletException, IOException {
<ide> try {
<ide> writeEntityWithMessageConverters(entity, request, response, context);
<ide> }
<ide> else if (throwable != null) {
<ide> handleError(throwable, servletRequest, servletResponse, context);
<ide> }
<ide> }
<add> catch (ServletException | IOException ex) {
<add> logger.warn("Asynchronous execution resulted in exception", ex);
<add> }
<ide> finally {
<ide> asyncContext.complete();
<ide> }
<ide> else if (throwable != null) {
<ide> }
<ide>
<ide>
<add> /**
<add> * {@link EntityResponse} implementation for asynchronous {@link Publisher} bodies.
<add> */
<ide> private static class PublisherEntityResponse<T> extends DefaultEntityResponse<Publisher<T>> {
<ide>
<ide> public PublisherEntityResponse(int statusCode, HttpHeaders headers,
<ide> protected ModelAndView writeToInternal(HttpServletRequest servletRequest,
<ide> return null;
<ide> }
<ide>
<del> public static boolean isPublisher(Object entity) {
<del> return (entity instanceof Publisher);
<del> }
<del>
<del>
<ide> @SuppressWarnings("SubscriberImplementation")
<ide> private class ProducingSubscriber implements Subscriber<T> {
<ide>
<ide> public void onSubscribe(Subscription s) {
<ide> public void onNext(T element) {
<ide> HttpServletRequest servletRequest = (HttpServletRequest) this.asyncContext.getRequest();
<ide> HttpServletResponse servletResponse = (HttpServletResponse) this.asyncContext.getResponse();
<del> tryWriteEntityWithMessageConverters(element, servletRequest, servletResponse, this.context);
<add> try {
<add> tryWriteEntityWithMessageConverters(element, servletRequest, servletResponse, this.context);
<add> }
<add> catch (ServletException | IOException ex) {
<add> onError(ex);
<add> }
<ide> }
<ide>
<ide> @Override
<ide> public void onError(Throwable t) {
<del> handleError(t, (HttpServletRequest) this.asyncContext.getRequest(),
<del> (HttpServletResponse) this.asyncContext.getResponse(), this.context);
<add> try {
<add> handleError(t, (HttpServletRequest) this.asyncContext.getRequest(),
<add> (HttpServletResponse) this.asyncContext.getResponse(), this.context);
<add> }
<add> catch (ServletException | IOException ex) {
<add> logger.warn("Asynchronous execution resulted in exception", ex);
<add> }
<ide> this.asyncContext.complete();
<ide> }
<ide>
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/function/DefaultServerResponseBuilder.java
<ide> package org.springframework.web.servlet.function;
<ide>
<ide> import java.io.IOException;
<del>import java.io.UncheckedIOException;
<ide> import java.net.URI;
<ide> import java.time.Instant;
<ide> import java.time.ZonedDateTime;
<del>import java.util.ArrayList;
<ide> import java.util.Arrays;
<ide> import java.util.Collection;
<ide> import java.util.EnumSet;
<ide> import java.util.LinkedHashSet;
<del>import java.util.List;
<ide> import java.util.Map;
<ide> import java.util.Set;
<ide> import java.util.function.BiFunction;
<ide> import java.util.function.Consumer;
<del>import java.util.function.Predicate;
<ide>
<ide> import javax.servlet.ServletException;
<ide> import javax.servlet.http.Cookie;
<ide> public ServerResponse render(String name, Map<String, ?> model) {
<ide> /**
<ide> * Abstract base class for {@link ServerResponse} implementations.
<ide> */
<del> abstract static class AbstractServerResponse implements ServerResponse {
<add> abstract static class AbstractServerResponse extends ErrorHandlingServerResponse {
<ide>
<ide> private static final Set<HttpMethod> SAFE_METHODS = EnumSet.of(HttpMethod.GET, HttpMethod.HEAD);
<ide>
<add>
<ide> final int statusCode;
<ide>
<ide> private final HttpHeaders headers;
<ide>
<ide> private final MultiValueMap<String, Cookie> cookies;
<ide>
<del> private final List<ErrorHandler<?>> errorHandlers = new ArrayList<>();
<ide>
<ide> protected AbstractServerResponse(
<ide> int statusCode, HttpHeaders headers, MultiValueMap<String, Cookie> cookies) {
<ide> protected AbstractServerResponse(
<ide> CollectionUtils.unmodifiableMultiValueMap(new LinkedMultiValueMap<>(cookies));
<ide> }
<ide>
<del> protected <T extends ServerResponse> void addErrorHandler(Predicate<Throwable> predicate,
<del> BiFunction<Throwable, ServerRequest, T> errorHandler) {
<del>
<del> Assert.notNull(predicate, "Predicate must not be null");
<del> Assert.notNull(errorHandler, "ErrorHandler must not be null");
<del> this.errorHandlers.add(new ErrorHandler<>(predicate, errorHandler));
<del> }
<del>
<ide>
<ide> @Override
<ide> public final HttpStatus statusCode() {
<ide> protected abstract ModelAndView writeToInternal(
<ide> HttpServletRequest request, HttpServletResponse response, Context context)
<ide> throws ServletException, IOException;
<ide>
<del> @Nullable
<del> protected ModelAndView handleError(Throwable t, HttpServletRequest servletRequest,
<del> HttpServletResponse servletResponse, Context context) {
<del>
<del> return this.errorHandlers.stream()
<del> .filter(errorHandler -> errorHandler.test(t))
<del> .findFirst()
<del> .map(errorHandler -> {
<del> ServerRequest serverRequest = (ServerRequest)
<del> servletRequest.getAttribute(RouterFunctions.REQUEST_ATTRIBUTE);
<del> ServerResponse serverResponse = errorHandler.handle(t, serverRequest);
<del> try {
<del> return serverResponse.writeTo(servletRequest, servletResponse, context);
<del> }
<del> catch (ServletException ex) {
<del> throw new IllegalStateException(ex);
<del> }
<del> catch (IOException ex) {
<del> throw new UncheckedIOException(ex);
<del> }
<del> })
<del> .orElseThrow(() -> new IllegalStateException(t));
<del> }
<del>
<del>
<del> private static class ErrorHandler<T extends ServerResponse> {
<del>
<del> private final Predicate<Throwable> predicate;
<del>
<del> private final BiFunction<Throwable, ServerRequest, T>
<del> responseProvider;
<del>
<del> public ErrorHandler(Predicate<Throwable> predicate,
<del> BiFunction<Throwable, ServerRequest, T> responseProvider) {
<del>
<del> Assert.notNull(predicate, "Predicate must not be null");
<del> Assert.notNull(responseProvider, "ResponseProvider must not be null");
<del> this.predicate = predicate;
<del> this.responseProvider = responseProvider;
<del> }
<del>
<del> public boolean test(Throwable t) {
<del> return this.predicate.test(t);
<del> }
<del>
<del> public T handle(Throwable t, ServerRequest serverRequest) {
<del> return this.responseProvider.apply(t, serverRequest);
<del> }
<del> }
<ide> }
<ide>
<ide>
<ide> private static class WriterFunctionResponse extends AbstractServerResponse {
<ide>
<ide> private final BiFunction<HttpServletRequest, HttpServletResponse, ModelAndView> writeFunction;
<ide>
<del> public WriterFunctionResponse(
<del> int statusCode, HttpHeaders headers, MultiValueMap<String, Cookie> cookies,
<add> public WriterFunctionResponse(int statusCode, HttpHeaders headers, MultiValueMap<String, Cookie> cookies,
<ide> BiFunction<HttpServletRequest, HttpServletResponse, ModelAndView> writeFunction) {
<ide>
<ide> super(statusCode, headers, cookies);
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/function/EntityResponse.java
<ide> /**
<ide> * Create a builder with the given object.
<ide> * @param t the object that represents the body of the response
<del> * @param <T> the type of element contained in the publisher
<add> * @param <T> the type of element contained in the entity
<ide> * @return the created builder
<ide> */
<ide> static <T> Builder<T> fromObject(T t) {
<ide> static <T> Builder<T> fromObject(T t) {
<ide> * Create a builder with the given object and type reference.
<ide> * @param t the object that represents the body of the response
<ide> * @param entityType the type of the entity, used to capture the generic type
<del> * @param <T> the type of element contained in the publisher
<add> * @param <T> the type of element contained in the entity
<ide> * @return the created builder
<ide> */
<ide> static <T> Builder<T> fromObject(T t, ParameterizedTypeReference<T> entityType) {
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/function/ErrorHandlingServerResponse.java
<add>/*
<add> * Copyright 2002-2020 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> * https://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.web.servlet.function;
<add>
<add>import java.io.IOException;
<add>import java.util.ArrayList;
<add>import java.util.List;
<add>import java.util.function.BiFunction;
<add>import java.util.function.Predicate;
<add>
<add>import javax.servlet.ServletException;
<add>import javax.servlet.http.HttpServletRequest;
<add>import javax.servlet.http.HttpServletResponse;
<add>
<add>import org.apache.commons.logging.Log;
<add>import org.apache.commons.logging.LogFactory;
<add>
<add>import org.springframework.lang.Nullable;
<add>import org.springframework.util.Assert;
<add>import org.springframework.web.servlet.ModelAndView;
<add>
<add>/**
<add> * Base class for {@link ServerResponse} implementations with error handling.
<add> *
<add> * @author Arjen Poutsma
<add> * @since 5.3
<add> */
<add>abstract class ErrorHandlingServerResponse implements ServerResponse {
<add>
<add> protected final Log logger = LogFactory.getLog(getClass());
<add>
<add> private final List<ErrorHandler<?>> errorHandlers = new ArrayList<>();
<add>
<add>
<add> protected final <T extends ServerResponse> void addErrorHandler(Predicate<Throwable> predicate,
<add> BiFunction<Throwable, ServerRequest, T> errorHandler) {
<add>
<add> Assert.notNull(predicate, "Predicate must not be null");
<add> Assert.notNull(errorHandler, "ErrorHandler must not be null");
<add> this.errorHandlers.add(new ErrorHandler<>(predicate, errorHandler));
<add> }
<add>
<add> @Nullable
<add> protected ModelAndView handleError(Throwable t, HttpServletRequest servletRequest,
<add> HttpServletResponse servletResponse, Context context) throws ServletException, IOException {
<add>
<add> for (ErrorHandler<?> errorHandler : this.errorHandlers) {
<add> if (errorHandler.test(t)) {
<add> ServerRequest serverRequest = (ServerRequest)
<add> servletRequest.getAttribute(RouterFunctions.REQUEST_ATTRIBUTE);
<add> ServerResponse serverResponse = errorHandler.handle(t, serverRequest);
<add> return serverResponse.writeTo(servletRequest, servletResponse, context);
<add> }
<add> }
<add> throw new ServletException(t);
<add> }
<add>
<add>
<add> private static class ErrorHandler<T extends ServerResponse> {
<add>
<add> private final Predicate<Throwable> predicate;
<add>
<add> private final BiFunction<Throwable, ServerRequest, T> responseProvider;
<add>
<add> public ErrorHandler(Predicate<Throwable> predicate, BiFunction<Throwable, ServerRequest, T> responseProvider) {
<add> Assert.notNull(predicate, "Predicate must not be null");
<add> Assert.notNull(responseProvider, "ResponseProvider must not be null");
<add> this.predicate = predicate;
<add> this.responseProvider = responseProvider;
<add> }
<add>
<add> public boolean test(Throwable t) {
<add> return this.predicate.test(t);
<add> }
<add>
<add> public T handle(Throwable t, ServerRequest serverRequest) {
<add> return this.responseProvider.apply(t, serverRequest);
<add> }
<add> }
<add>
<add>}
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/function/HandlerFilterFunction.java
<ide> default HandlerFunction<R> apply(HandlerFunction<T> handler) {
<ide> return (request, next) -> {
<ide> try {
<ide> T t = next.handle(request);
<del> if (t instanceof DefaultServerResponseBuilder.AbstractServerResponse) {
<del> ((DefaultServerResponseBuilder.AbstractServerResponse) t)
<del> .addErrorHandler(predicate, errorHandler);
<add> if (t instanceof ErrorHandlingServerResponse) {
<add> ((ErrorHandlingServerResponse) t).addErrorHandler(predicate, errorHandler);
<ide> }
<ide> return t;
<ide> }
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/function/ServerResponse.java
<ide> import java.util.List;
<ide> import java.util.Map;
<ide> import java.util.Set;
<add>import java.util.concurrent.CompletableFuture;
<ide> import java.util.concurrent.CompletionStage;
<ide> import java.util.function.BiFunction;
<ide> import java.util.function.Consumer;
<ide> import org.reactivestreams.Publisher;
<ide>
<ide> import org.springframework.core.ParameterizedTypeReference;
<add>import org.springframework.core.ReactiveAdapterRegistry;
<ide> import org.springframework.http.CacheControl;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpMethod;
<ide> static BodyBuilder unprocessableEntity() {
<ide> return status(HttpStatus.UNPROCESSABLE_ENTITY);
<ide> }
<ide>
<add> /**
<add> * Create a (built) response with the given asynchronous response.
<add> * Parameter {@code asyncResponse} can be a
<add> * {@link CompletableFuture CompletableFuture<ServerResponse>} or
<add> * {@link Publisher Publisher<ServerResponse>} (or any
<add> * asynchronous producer of a single {@code ServerResponse} that can be
<add> * adapted via the {@link ReactiveAdapterRegistry}).
<add> *
<add> * <p>This method can be used to set the response status code, headers, and
<add> * body based on an asynchronous result. If only the body is asynchronous,
<add> * {@link BodyBuilder#body(Object)} can be used instead.
<add> *
<add> * <p><strong>Note</strong> that
<add> * {@linkplain RenderingResponse rendering responses}, as returned by
<add> * {@link BodyBuilder#render}, are <strong>not</strong> supported as value
<add> * for {@code asyncResponse}. Use WebFlux.fn for asynchronous rendering.
<add> * @param asyncResponse a {@code CompletableFuture<ServerResponse>} or
<add> * {@code Publisher<ServerResponse>}
<add> * @return the asynchronous response
<add> * @since 5.3
<add> */
<add> static ServerResponse async(Object asyncResponse) {
<add> return AsyncServerResponse.create(asyncResponse);
<add> }
<add>
<ide>
<ide> /**
<ide> * Defines a builder that adds headers to the response.
<ide> interface BodyBuilder extends HeadersBuilder<BodyBuilder> {
<ide> BodyBuilder contentType(MediaType contentType);
<ide>
<ide> /**
<del> * Set the body of the response to the given {@code Object} and return it.
<add> * Set the body of the response to the given {@code Object} and return
<add> * it.
<ide> *
<del> * <p>Asynchronous response bodies are supported by providing a {@link CompletionStage} or
<del> * {@link Publisher} as body.
<add> * <p>Asynchronous response bodies are supported by providing a
<add> * {@link CompletionStage} or {@link Publisher} as body (or any
<add> * asynchronous producer of a single entity that can be adapted via the
<add> * {@link ReactiveAdapterRegistry}).
<ide> * @param body the body of the response
<ide> * @return the built response
<ide> */ | 7 |
Go | Go | simplify the creation of test directories | 5a85456d481a5f88fc0efc02c41b3bff987c0ed1 | <ide><path>runtime_test.go
<ide> package docker
<ide> import (
<ide> "bytes"
<ide> "fmt"
<add> "github.com/dotcloud/docker/engine"
<ide> "github.com/dotcloud/docker/sysinit"
<ide> "github.com/dotcloud/docker/utils"
<ide> "io"
<ide> import (
<ide> "syscall"
<ide> "testing"
<ide> "time"
<add> "net/url"
<ide> )
<ide>
<ide> const (
<ide> func init() {
<ide> }
<ide>
<ide> func setupBaseImage() {
<del> config := &DaemonConfig{
<del> Root: unitTestStoreBase,
<del> AutoRestart: false,
<del> BridgeIface: unitTestNetworkBridge,
<del> }
<del> runtime, err := NewRuntimeFromDirectory(config)
<add> eng, err := engine.New(unitTestStoreBase)
<ide> if err != nil {
<del> log.Fatalf("Unable to create a runtime for tests:", err)
<add> log.Fatalf("Can't initialize engine at %s: %s", unitTestStoreBase, err)
<ide> }
<del>
<del> // Create the "Server"
<del> srv := &Server{
<del> runtime: runtime,
<del> pullingPool: make(map[string]struct{}),
<del> pushingPool: make(map[string]struct{}),
<add> job := eng.Job("initapi")
<add> job.Setenv("Root", unitTestStoreBase)
<add> job.SetenvBool("Autorestart", false)
<add> job.Setenv("BridgeIface", unitTestNetworkBridge)
<add> if err := job.Run(); err != nil {
<add> log.Fatalf("Unable to create a runtime for tests:", err)
<ide> }
<add> srv := mkServerFromEngine(eng, log.New(os.Stderr, "", 0))
<add> runtime := srv.runtime
<ide>
<ide> // If the unit test is not found, try to download it.
<ide> if img, err := runtime.repositories.LookupImage(unitTestImageName); err != nil || img.ID != unitTestImageID {
<ide> func spawnGlobalDaemon() {
<ide> utils.Debugf("Global runtime already exists. Skipping.")
<ide> return
<ide> }
<del> globalRuntime = mkRuntime(log.New(os.Stderr, "", 0))
<del> srv := &Server{
<del> runtime: globalRuntime,
<del> pullingPool: make(map[string]struct{}),
<del> pushingPool: make(map[string]struct{}),
<del> }
<add> t := log.New(os.Stderr, "", 0)
<add> eng := NewTestEngine(t)
<add> srv := mkServerFromEngine(eng, t)
<add> globalRuntime = srv.runtime
<ide>
<ide> // Spawn a Daemon
<ide> go func() {
<ide> utils.Debugf("Spawning global daemon for integration tests")
<del> if err := ListenAndServe(testDaemonProto, testDaemonAddr, srv, os.Getenv("DEBUG") != ""); err != nil {
<del> log.Fatalf("Unable to spawn the test daemon:", err)
<add> listenURL := &url.URL{
<add> Scheme: testDaemonProto,
<add> Host: testDaemonAddr,
<add> }
<add> job := eng.Job("serveapi", listenURL.String())
<add> job.SetenvBool("Logging", os.Getenv("DEBUG") != "")
<add> if err := job.Run(); err != nil {
<add> log.Fatalf("Unable to spawn the test daemon: %s", err)
<ide> }
<ide> }()
<ide> // Give some time to ListenAndServer to actually start
<ide><path>server_test.go
<ide> package docker
<ide>
<ide> import (
<del> "github.com/dotcloud/docker/engine"
<ide> "github.com/dotcloud/docker/utils"
<ide> "strings"
<ide> "testing"
<ide> func TestCreateRm(t *testing.T) {
<ide> }
<ide>
<ide> func TestCreateRmVolumes(t *testing.T) {
<del> eng := engine.NewTestEngine(t)
<add> eng := NewTestEngine(t)
<ide>
<ide> srv := mkServerFromEngine(eng, t)
<ide> runtime := srv.runtime
<ide> func TestCommit(t *testing.T) {
<ide> }
<ide>
<ide> func TestCreateStartRestartStopStartKillRm(t *testing.T) {
<del> eng := engine.NewTestEngine(t)
<add> eng := NewTestEngine(t)
<ide> srv := mkServerFromEngine(eng, t)
<ide> runtime := srv.runtime
<ide> defer nuke(runtime)
<ide> func TestLogEvent(t *testing.T) {
<ide> }
<ide>
<ide> func TestRmi(t *testing.T) {
<del> eng := engine.NewTestEngine(t)
<add> eng := NewTestEngine(t)
<ide> srv := mkServerFromEngine(eng, t)
<ide> runtime := srv.runtime
<ide> defer nuke(runtime)
<ide><path>utils/utils.go
<ide> var (
<ide> INITSHA1 string // sha1sum of separate static dockerinit, if Docker itself was compiled dynamically via ./hack/make.sh dynbinary
<ide> )
<ide>
<add>// A common interface to access the Fatal method of
<add>// both testing.B and testing.T.
<add>type Fataler interface {
<add> Fatal(args ...interface{})
<add>}
<add>
<ide> // ListOpts type
<ide> type ListOpts []string
<ide>
<ide><path>utils_test.go
<ide> var globalTestID string
<ide>
<ide> // Create a temporary runtime suitable for unit testing.
<ide> // Call t.Fatal() at the first error.
<del>func mkRuntime(f Fataler) *Runtime {
<del> // Use the caller function name as a prefix.
<del> // This helps trace temp directories back to their test.
<del> pc, _, _, _ := runtime.Caller(1)
<del> callerLongName := runtime.FuncForPC(pc).Name()
<del> parts := strings.Split(callerLongName, ".")
<del> callerShortName := parts[len(parts)-1]
<del> if globalTestID == "" {
<del> globalTestID = GenerateID()[:4]
<add>func mkRuntime(f utils.Fataler) *Runtime {
<add> root, err := newTestDirectory(unitTestStoreBase)
<add> if err != nil {
<add> f.Fatal(err)
<ide> }
<del> prefix := fmt.Sprintf("docker-test%s-%s-", globalTestID, callerShortName)
<del> utils.Debugf("prefix = '%s'", prefix)
<del>
<del> runtime, err := newTestRuntime(prefix)
<add> config := &DaemonConfig{
<add> Root: root,
<add> AutoRestart: false,
<add> }
<add> r, err := NewRuntimeFromDirectory(config)
<ide> if err != nil {
<ide> f.Fatal(err)
<ide> }
<del> return runtime
<add> r.UpdateCapabilities(true)
<add> return r
<ide> }
<ide>
<del>func mkServerFromEngine(eng *engine.Engine, t Fataler) *Server {
<add>func mkServerFromEngine(eng *engine.Engine, t utils.Fataler) *Server {
<ide> iSrv := eng.Hack_GetGlobalVar("httpapi.server")
<ide> if iSrv == nil {
<ide> t.Fatal("Legacy server field not set in engine")
<ide> func mkServerFromEngine(eng *engine.Engine, t Fataler) *Server {
<ide> return srv
<ide> }
<ide>
<del>// A common interface to access the Fatal method of
<del>// both testing.B and testing.T.
<del>type Fataler interface {
<del> Fatal(args ...interface{})
<del>}
<ide>
<del>func newTestRuntime(prefix string) (runtime *Runtime, err error) {
<del> if prefix == "" {
<del> prefix = "docker-test-"
<del> }
<del> utils.Debugf("prefix = %s", prefix)
<del> utils.Debugf("newTestRuntime start")
<del> root, err := ioutil.TempDir("", prefix)
<del> defer func() {
<del> utils.Debugf("newTestRuntime: %s", root)
<del> }()
<add>func NewTestEngine(t utils.Fataler) *engine.Engine {
<add> root, err := newTestDirectory(unitTestStoreBase)
<ide> if err != nil {
<del> return nil, err
<add> t.Fatal(err)
<ide> }
<del> if err := os.Remove(root); err != nil {
<del> return nil, err
<add> eng, err := engine.New(root)
<add> if err != nil {
<add> t.Fatal(err)
<ide> }
<del> if err := utils.CopyDirectory(unitTestStoreBase, root); err != nil {
<del> return nil, err
<add> // Load default plugins
<add> // (This is manually copied and modified from main() until we have a more generic plugin system)
<add> job := eng.Job("initapi")
<add> job.Setenv("Root", root)
<add> job.SetenvBool("AutoRestart", false)
<add> if err := job.Run(); err != nil {
<add> t.Fatal(err)
<ide> }
<add> return eng
<add>}
<ide>
<del> config := &DaemonConfig{
<del> Root: root,
<del> AutoRestart: false,
<add>func newTestDirectory(templateDir string) (dir string, err error) {
<add> if globalTestID == "" {
<add> globalTestID = GenerateID()[:4]
<ide> }
<del> runtime, err = NewRuntimeFromDirectory(config)
<del> if err != nil {
<del> return nil, err
<add> prefix := fmt.Sprintf("docker-test%s-%s-", globalTestID, getCallerName(2))
<add> if prefix == "" {
<add> prefix = "docker-test-"
<add> }
<add> dir, err = ioutil.TempDir("", prefix)
<add> if err = os.Remove(dir); err != nil {
<add> return
<add> }
<add> if err = utils.CopyDirectory(templateDir, dir); err != nil {
<add> return
<ide> }
<del> runtime.UpdateCapabilities(true)
<del> return runtime, nil
<add> return
<add>}
<add>
<add>func getCallerName(depth int) string {
<add> // Use the caller function name as a prefix.
<add> // This helps trace temp directories back to their test.
<add> pc, _, _, _ := runtime.Caller(depth + 1)
<add> callerLongName := runtime.FuncForPC(pc).Name()
<add> parts := strings.Split(callerLongName, ".")
<add> callerShortName := parts[len(parts)-1]
<add> return callerShortName
<ide> }
<ide>
<ide> // Write `content` to the file at path `dst`, creating it if necessary, | 4 |
Javascript | Javascript | update stats-config for release stats | 61409dd61599ed54e70a4a0bf5da04187ebe2cfb | <ide><path>.github/actions/next-stats-action/src/index.js
<ide> if (!allowedActions.has(actionInfo.actionName) && !actionInfo.isRelease) {
<ide> await checkoutRef(actionInfo.prRef, diffRepoDir)
<ide> }
<ide>
<add> if (actionInfo.isRelease) {
<add> process.env.STATS_IS_RELEASE = 'true'
<add> }
<add>
<ide> // load stats config from allowed locations
<ide> const { statsConfig, relativeStatsAppDir } = loadStatsConfig()
<ide>
<ide><path>test/.stats-app/stats-config.js
<ide> module.exports = {
<ide> generateBuildId: () => 'BUILD_ID',
<ide> experimental: {
<ide> swcLoader: true,
<del> swcMinify: true,
<add> swcMinify: ${
<add> // TODO: remove after stable release > 11.1.2
<add> process.env.STATS_IS_RELEASE ? 'false' : 'true'
<add> },
<ide> },
<ide> webpack(config) {
<ide> config.optimization.minimize = false
<ide> module.exports = {
<ide> module.exports = {
<ide> experimental: {
<ide> swcLoader: true,
<del> swcMinify: true
<add> swcMinify: ${
<add> // TODO: remove after stable release > 11.1.2
<add> process.env.STATS_IS_RELEASE ? 'false' : 'true'
<add> },
<ide> },
<ide> generateBuildId: () => 'BUILD_ID'
<ide> } | 2 |
Go | Go | move security opts to hostconfig | 294843ef23fcff3c080d9fbd12df17ae7006a9f8 | <ide><path>daemon/create.go
<ide> func (daemon *Daemon) Create(config *runconfig.Config, hostConfig *runconfig.Hos
<ide> if warnings, err = daemon.mergeAndVerifyConfig(config, img); err != nil {
<ide> return nil, nil, err
<ide> }
<del> if hostConfig != nil && config.SecurityOpt == nil {
<del> config.SecurityOpt, err = daemon.GenerateSecurityOpt(hostConfig.IpcMode)
<add> if hostConfig != nil && hostConfig.SecurityOpt == nil {
<add> hostConfig.SecurityOpt, err = daemon.GenerateSecurityOpt(hostConfig.IpcMode)
<ide> if err != nil {
<ide> return nil, nil, err
<ide> }
<ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) getEntrypointAndArgs(configEntrypoint, configCmd []string)
<ide> return entrypoint, args
<ide> }
<ide>
<del>func parseSecurityOpt(container *Container, config *runconfig.Config) error {
<add>func parseSecurityOpt(container *Container, config *runconfig.HostConfig) error {
<ide> var (
<del> label_opts []string
<del> err error
<add> labelOpts []string
<add> err error
<ide> )
<ide>
<ide> for _, opt := range config.SecurityOpt {
<ide> func parseSecurityOpt(container *Container, config *runconfig.Config) error {
<ide> }
<ide> switch con[0] {
<ide> case "label":
<del> label_opts = append(label_opts, con[1])
<add> labelOpts = append(labelOpts, con[1])
<ide> case "apparmor":
<ide> container.AppArmorProfile = con[1]
<ide> default:
<ide> return fmt.Errorf("Invalid --security-opt: %q", opt)
<ide> }
<ide> }
<ide>
<del> container.ProcessLabel, container.MountLabel, err = label.InitLabels(label_opts)
<add> container.ProcessLabel, container.MountLabel, err = label.InitLabels(labelOpts)
<ide> return err
<ide> }
<ide>
<ide> func (daemon *Daemon) newContainer(name string, config *runconfig.Config, img *i
<ide> execCommands: newExecStore(),
<ide> }
<ide> container.root = daemon.containerRoot(container.ID)
<del> err = parseSecurityOpt(container, config)
<ide> return container, err
<ide> }
<ide>
<ide><path>daemon/daemon_unit_test.go
<ide> import (
<ide>
<ide> func TestParseSecurityOpt(t *testing.T) {
<ide> container := &Container{}
<del> config := &runconfig.Config{}
<add> config := &runconfig.HostConfig{}
<ide>
<ide> // test apparmor
<ide> config.SecurityOpt = []string{"apparmor:test_profile"}
<ide><path>daemon/start.go
<ide> func (daemon *Daemon) ContainerStart(job *engine.Job) engine.Status {
<ide> }
<ide>
<ide> func (daemon *Daemon) setHostConfig(container *Container, hostConfig *runconfig.HostConfig) error {
<add> if err := parseSecurityOpt(container, hostConfig); err != nil {
<add> return err
<add> }
<ide> // Validate the HostConfig binds. Make sure that:
<ide> // the source exists
<ide> for _, bind := range hostConfig.Binds {
<ide><path>runconfig/config.go
<ide> type Config struct {
<ide> NetworkDisabled bool
<ide> MacAddress string
<ide> OnBuild []string
<del> SecurityOpt []string
<ide> }
<ide>
<ide> func ContainerConfigFromJob(job *engine.Job) *Config {
<ide> func ContainerConfigFromJob(job *engine.Job) *Config {
<ide> }
<ide> job.GetenvJson("ExposedPorts", &config.ExposedPorts)
<ide> job.GetenvJson("Volumes", &config.Volumes)
<del> config.SecurityOpt = job.GetenvList("SecurityOpt")
<ide> if PortSpecs := job.GetenvList("PortSpecs"); PortSpecs != nil {
<ide> config.PortSpecs = PortSpecs
<ide> }
<ide><path>runconfig/hostconfig.go
<ide> type HostConfig struct {
<ide> CapAdd []string
<ide> CapDrop []string
<ide> RestartPolicy RestartPolicy
<add> SecurityOpt []string
<ide> }
<ide>
<ide> // This is used by the create command when you want to set both the
<ide> func ContainerHostConfigFromJob(job *engine.Job) *HostConfig {
<ide> job.GetenvJson("PortBindings", &hostConfig.PortBindings)
<ide> job.GetenvJson("Devices", &hostConfig.Devices)
<ide> job.GetenvJson("RestartPolicy", &hostConfig.RestartPolicy)
<add> hostConfig.SecurityOpt = job.GetenvList("SecurityOpt")
<ide> if Binds := job.GetenvList("Binds"); Binds != nil {
<ide> hostConfig.Binds = Binds
<ide> }
<ide><path>runconfig/parse.go
<ide> func Parse(cmd *flag.FlagSet, args []string) (*Config, *HostConfig, *flag.FlagSe
<ide> MacAddress: *flMacAddress,
<ide> Entrypoint: entrypoint,
<ide> WorkingDir: *flWorkingDir,
<del> SecurityOpt: flSecurityOpt.GetAll(),
<ide> }
<ide>
<ide> hostConfig := &HostConfig{
<ide> func Parse(cmd *flag.FlagSet, args []string) (*Config, *HostConfig, *flag.FlagSe
<ide> CapAdd: flCapAdd.GetAll(),
<ide> CapDrop: flCapDrop.GetAll(),
<ide> RestartPolicy: restartPolicy,
<add> SecurityOpt: flSecurityOpt.GetAll(),
<ide> }
<ide>
<ide> // When allocating stdin in attached mode, close stdin at client disconnect | 7 |
Go | Go | optimize pubsub.publish function | 1e0f1ec52543bc83099fb91cd34dca4d38100e6f | <ide><path>pkg/pubsub/publisher.go
<ide> func (p *Publisher) Evict(sub chan interface{}) {
<ide> // Publish sends the data in v to all subscribers currently registered with the publisher.
<ide> func (p *Publisher) Publish(v interface{}) {
<ide> p.m.RLock()
<add> if len(p.subscribers) == 0 {
<add> p.m.RUnlock()
<add> return
<add> }
<add>
<ide> wg := new(sync.WaitGroup)
<ide> for sub, topic := range p.subscribers {
<ide> wg.Add(1)
<del>
<ide> go p.sendTopic(sub, topic, v, wg)
<ide> }
<ide> wg.Wait() | 1 |
PHP | PHP | add status codes from httpstatuses.com | 1cf041841c28206d894f66dd4c7267d8ae5d82be | <ide><path>src/Network/Response.php
<ide> class Response
<ide> 206 => 'Partial Content',
<ide> 207 => 'Multi-status',
<ide> 208 => 'Already Reported',
<add> 226 => 'IM used',
<ide> 300 => 'Multiple Choices',
<ide> 301 => 'Moved Permanently',
<ide> 302 => 'Found',
<ide> class Response
<ide> 305 => 'Use Proxy',
<ide> 306 => 'Switch Proxy',
<ide> 307 => 'Temporary Redirect',
<add> 308 => 'Permanent Redirect',
<ide> 400 => 'Bad Request',
<ide> 401 => 'Unauthorized',
<ide> 402 => 'Payment Required',
<ide> class Response
<ide> 428 => 'Precondition Required',
<ide> 429 => 'Too Many Requests',
<ide> 431 => 'Request Header Fields Too Large',
<add> 444 => 'Connection Closed Without Response',
<ide> 451 => 'Unavailable For Legal Reasons',
<add> 499 => 'Client Closed Requet',
<ide> 500 => 'Internal Server Error',
<ide> 501 => 'Not Implemented',
<ide> 502 => 'Bad Gateway',
<ide> class Response
<ide> 506 => 'Variant Also Negotiates',
<ide> 507 => 'Insufficient Storage',
<ide> 508 => 'Loop Detected',
<add> 510 => 'Not Extended',
<ide> 511 => 'Network Authentication Required',
<add> 511 => 'Network Connect Timeout Error',
<ide> ];
<ide>
<ide> /** | 1 |
Text | Text | update vggish readme for new path, soundfile | 8b479cc73ce3829903c85612d6e884fe50dd2714 | <ide><path>research/audioset/vggish/README.md
<ide> $ sudo python -m pip install --upgrade pip
<ide>
<ide> # Install dependences. Resampy needs to be installed after NumPy and SciPy
<ide> # are already installed.
<del>$ sudo pip install numpy scipy
<add>$ sudo pip install numpy scipy soundfile
<ide> $ sudo pip install resampy tensorflow six
<ide>
<ide> # Clone TensorFlow models repo into a 'models' directory.
<ide> $ git clone https://github.com/tensorflow/models.git
<del>$ cd models/research/audioset
<add>$ cd models/research/audioset/vggish
<ide> # Download data files into same directory as code.
<ide> $ curl -O https://storage.googleapis.com/audioset/vggish_model.ckpt
<ide> $ curl -O https://storage.googleapis.com/audioset/vggish_pca_params.npz | 1 |
Python | Python | keep functions signatures in decorators | 553bb7af7cb7a50f7141b5b89297713cee6d19f6 | <ide><path>airflow/api/auth/backend/default.py
<ide> # under the License.
<ide> """Default authentication backend - everything is allowed"""
<ide> from functools import wraps
<del>from typing import Optional
<add>from typing import Callable, Optional, TypeVar, cast
<ide>
<ide> from airflow.typing_compat import Protocol
<ide>
<ide> def init_app(_):
<ide> """Initializes authentication backend"""
<ide>
<ide>
<del>def requires_authentication(function):
<add>T = TypeVar("T", bound=Callable) # pylint: disable=invalid-name
<add>
<add>
<add>def requires_authentication(function: T):
<ide> """Decorator for functions that require authentication"""
<ide> @wraps(function)
<ide> def decorated(*args, **kwargs):
<ide> return function(*args, **kwargs)
<ide>
<del> return decorated
<add> return cast(T, decorated)
<ide><path>airflow/api/auth/backend/deny_all.py
<ide> # under the License.
<ide> """Authentication backend that denies all requests"""
<ide> from functools import wraps
<del>from typing import Optional
<add>from typing import Callable, Optional, TypeVar, cast
<ide>
<ide> from flask import Response
<ide>
<ide> def init_app(_):
<ide> """Initializes authentication"""
<ide>
<ide>
<del>def requires_authentication(function):
<add>T = TypeVar("T", bound=Callable) # pylint: disable=invalid-name
<add>
<add>
<add>def requires_authentication(function: T):
<ide> """Decorator for functions that require authentication"""
<ide>
<ide> # noinspection PyUnusedLocal
<ide> @wraps(function)
<ide> def decorated(*args, **kwargs): # pylint: disable=unused-argument
<ide> return Response("Forbidden", 403)
<ide>
<del> return decorated
<add> return cast(T, decorated)
<ide><path>airflow/api/auth/backend/kerberos_auth.py
<ide> import os
<ide> from functools import wraps
<ide> from socket import getfqdn
<add>from typing import Callable, TypeVar, cast
<ide>
<ide> import kerberos
<ide> # noinspection PyProtectedMember
<ide> def _gssapi_authenticate(token):
<ide> kerberos.authGSSServerClean(state)
<ide>
<ide>
<del>def requires_authentication(function):
<add>T = TypeVar("T", bound=Callable) # pylint: disable=invalid-name
<add>
<add>
<add>def requires_authentication(function: T):
<ide> """Decorator for functions that require authentication with Kerberos"""
<ide> @wraps(function)
<ide> def decorated(*args, **kwargs):
<ide> def decorated(*args, **kwargs):
<ide> if return_code != kerberos.AUTH_GSS_CONTINUE:
<ide> return _forbidden()
<ide> return _unauthorized()
<del> return decorated
<add> return cast(T, decorated)
<ide><path>airflow/api_connexion/parameters.py
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<ide> from functools import wraps
<del>from typing import Callable, Dict
<add>from typing import Callable, Dict, TypeVar, cast
<ide>
<ide> from pendulum.parsing import ParserError
<ide>
<ide> def check_limit(value: int):
<ide> return value
<ide>
<ide>
<del>def format_parameters(params_formatters: Dict[str, Callable[..., bool]]):
<add>T = TypeVar("T", bound=Callable) # pylint: disable=invalid-name
<add>
<add>
<add>def format_parameters(params_formatters: Dict[str, Callable[..., bool]]) -> Callable[[T], T]:
<ide> """
<ide> Decorator factory that create decorator that convert parameters using given formatters.
<ide>
<ide> def format_parameters(params_formatters: Dict[str, Callable[..., bool]]):
<ide> :param params_formatters: Map of key name and formatter function
<ide> """
<ide>
<del> def format_parameters_decorator(func):
<add> def format_parameters_decorator(func: T):
<ide> @wraps(func)
<ide> def wrapped_function(*args, **kwargs):
<ide> for key, formatter in params_formatters.items():
<ide> if key in kwargs:
<ide> kwargs[key] = formatter(kwargs[key])
<ide> return func(*args, **kwargs)
<ide>
<del> return wrapped_function
<add> return cast(T, wrapped_function)
<ide>
<ide> return format_parameters_decorator
<ide><path>airflow/lineage/__init__.py
<ide> import json
<ide> import logging
<ide> from functools import wraps
<del>from typing import Any, Dict, Optional
<add>from typing import Any, Callable, Dict, Optional, TypeVar, cast
<ide>
<ide> import attr
<ide> import jinja2
<ide> def _to_dataset(obj: Any, source: str) -> Optional[Metadata]:
<ide> return Metadata(type_name, source, data)
<ide>
<ide>
<del>def apply_lineage(func):
<add>T = TypeVar("T", bound=Callable) # pylint: disable=invalid-name
<add>
<add>
<add>def apply_lineage(func: T) -> T:
<ide> """
<ide> Saves the lineage to XCom and if configured to do so sends it
<ide> to the backend.
<ide> def wrapper(self, context, *args, **kwargs):
<ide>
<ide> return ret_val
<ide>
<del> return wrapper
<add> return cast(T, wrapper)
<ide>
<ide>
<del>def prepare_lineage(func):
<add>def prepare_lineage(func: T) -> T:
<ide> """
<ide> Prepares the lineage inlets and outlets. Inlets can be:
<ide>
<ide> def wrapper(self, context, *args, **kwargs):
<ide> self.log.debug("inlets: %s, outlets: %s", self.inlets, self.outlets)
<ide> return func(self, context, *args, **kwargs)
<ide>
<del> return wrapper
<add> return cast(T, wrapper)
<ide><path>airflow/migrations/versions/3c20cacc0044_add_dagrun_run_type.py
<ide> Base = declarative_base()
<ide>
<ide>
<del>class DagRun(Base):
<add>class DagRun(Base): # type: ignore
<ide> """
<ide> DagRun describes an instance of a Dag. It can be created
<ide> by the scheduler (for regular runs) or by an external trigger
<ide><path>airflow/migrations/versions/6e96a59344a4_make_taskinstance_pool_not_nullable.py
<ide> ID_LEN = 250
<ide>
<ide>
<del>class TaskInstance(Base):
<add>class TaskInstance(Base): # type: ignore
<ide> """
<ide> Task instances store the state of a task instance. This table is the
<ide> authority and single source of truth around what tasks have run and the
<ide><path>airflow/migrations/versions/cc1e65623dc7_add_max_tries_column_to_task_instance.py
<ide> ID_LEN = 250
<ide>
<ide>
<del>class TaskInstance(Base): # noqa: D101
<add>class TaskInstance(Base): # noqa: D101 # type: ignore
<ide> __tablename__ = "task_instance"
<ide>
<ide> task_id = Column(String(ID_LEN, **COLLATION_ARGS), primary_key=True)
<ide><path>airflow/operators/python.py
<ide> from itertools import islice
<ide> from tempfile import TemporaryDirectory
<ide> from textwrap import dedent
<del>from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple
<add>from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, TypeVar, cast
<ide>
<ide> import dill
<ide>
<ide> def execute(self, context: Dict):
<ide> return return_value
<ide>
<ide>
<del>def task(python_callable: Optional[Callable] = None, multiple_outputs: bool = False, **kwargs):
<add>T = TypeVar("T", bound=Callable) # pylint: disable=invalid-name
<add>
<add>
<add>def task(
<add> python_callable: Optional[Callable] = None,
<add> multiple_outputs: bool = False,
<add> **kwargs
<add>) -> Callable[[T], T]:
<ide> """
<ide> Python operator decorator. Wraps a function into an Airflow operator.
<ide> Accepts kwargs for operator kwarg. Can be reused in a single DAG.
<ide> def task(python_callable: Optional[Callable] = None, multiple_outputs: bool = Fa
<ide> :type multiple_outputs: bool
<ide>
<ide> """
<del> def wrapper(f):
<add> def wrapper(f: T):
<ide> """
<ide> Python wrapper to generate PythonFunctionalOperator out of simple python functions.
<ide> Used for Airflow functional interface
<ide> def factory(*args, **f_kwargs):
<ide> op = _PythonFunctionalOperator(python_callable=f, op_args=args, op_kwargs=f_kwargs,
<ide> multiple_outputs=multiple_outputs, **kwargs)
<ide> return XComArg(op)
<del> return factory
<add> return cast(T, factory)
<ide> if callable(python_callable):
<ide> return wrapper(python_callable)
<ide> elif python_callable is not None:
<ide><path>airflow/providers/amazon/aws/hooks/s3.py
<ide> from functools import wraps
<ide> from inspect import signature
<ide> from tempfile import NamedTemporaryFile
<del>from typing import Optional
<add>from typing import Callable, Optional, TypeVar, cast
<ide> from urllib.parse import urlparse
<ide>
<ide> from botocore.exceptions import ClientError
<ide> from airflow.providers.amazon.aws.hooks.base_aws import AwsBaseHook
<ide> from airflow.utils.helpers import chunks
<ide>
<add>T = TypeVar("T", bound=Callable) # pylint: disable=invalid-name
<ide>
<del>def provide_bucket_name(func):
<add>
<add>def provide_bucket_name(func: T) -> T:
<ide> """
<ide> Function decorator that provides a bucket name taken from the connection
<ide> in case no bucket name has been passed to the function.
<ide> def wrapper(*args, **kwargs):
<ide>
<ide> return func(*bound_args.args, **bound_args.kwargs)
<ide>
<del> return wrapper
<add> return cast(T, wrapper)
<ide>
<ide>
<del>def unify_bucket_name_and_key(func):
<add>def unify_bucket_name_and_key(func: T) -> T:
<ide> """
<ide> Function decorator that unifies bucket name and key taken from the key
<ide> in case no bucket name and at least a key has been passed to the function.
<ide> def get_key_name():
<ide>
<ide> return func(*bound_args.args, **bound_args.kwargs)
<ide>
<del> return wrapper
<add> return cast(T, wrapper)
<ide>
<ide>
<ide> class S3Hook(AwsBaseHook):
<ide><path>airflow/providers/google/cloud/hooks/dataflow.py
<ide> import warnings
<ide> from copy import deepcopy
<ide> from tempfile import TemporaryDirectory
<del>from typing import Any, Callable, Dict, List, Optional, TypeVar
<add>from typing import Any, Callable, Dict, List, Optional, TypeVar, cast
<ide>
<ide> from googleapiclient.discovery import build
<ide>
<ide> r'Submitted job: (?P<job_id_java>.*)|Created job with id: \[(?P<job_id_python>.*)\]'
<ide> )
<ide>
<del>RT = TypeVar('RT') # pylint: disable=invalid-name
<add>T = TypeVar("T", bound=Callable) # pylint: disable=invalid-name
<ide>
<ide>
<del>def _fallback_variable_parameter(parameter_name, variable_key_name):
<add>def _fallback_variable_parameter(parameter_name: str, variable_key_name: str) -> Callable[[T], T]:
<ide>
<del> def _wrapper(func: Callable[..., RT]) -> Callable[..., RT]:
<add> def _wrapper(func: T) -> T:
<ide> """
<ide> Decorator that provides fallback for location from `region` key in `variables` parameters.
<ide>
<ide> :param func: function to wrap
<ide> :return: result of the function call
<ide> """
<ide> @functools.wraps(func)
<del> def inner_wrapper(self: "DataflowHook", *args, **kwargs) -> RT:
<add> def inner_wrapper(self: "DataflowHook", *args, **kwargs):
<ide> if args:
<ide> raise AirflowException(
<ide> "You must use keyword arguments in this methods rather than positional")
<ide> def inner_wrapper(self: "DataflowHook", *args, **kwargs) -> RT:
<ide> kwargs['variables'] = copy_variables
<ide>
<ide> return func(self, *args, **kwargs)
<del> return inner_wrapper
<add> return cast(T, inner_wrapper)
<ide>
<ide> return _wrapper
<ide>
<ide><path>airflow/providers/google/cloud/hooks/gcs.py
<ide> from io import BytesIO
<ide> from os import path
<ide> from tempfile import NamedTemporaryFile
<del>from typing import Optional, Set, Tuple, TypeVar, Union
<add>from typing import Callable, Optional, Set, Tuple, TypeVar, Union, cast
<ide> from urllib.parse import urlparse
<ide>
<ide> from google.api_core.exceptions import NotFound
<ide> from airflow.version import version
<ide>
<ide> RT = TypeVar('RT') # pylint: disable=invalid-name
<add>T = TypeVar("T", bound=Callable) # pylint: disable=invalid-name
<ide>
<ide>
<ide> def _fallback_object_url_to_object_name_and_bucket_name(
<ide> object_url_keyword_arg_name='object_url',
<ide> bucket_name_keyword_arg_name='bucket_name',
<ide> object_name_keyword_arg_name='object_name',
<del>):
<add>) -> Callable[[T], T]:
<ide> """
<ide> Decorator factory that convert object URL parameter to object name and bucket name parameter.
<ide>
<ide> def _fallback_object_url_to_object_name_and_bucket_name(
<ide> :type object_name_keyword_arg_name: str
<ide> :return: Decorator
<ide> """
<del> def _wrapper(func):
<add> def _wrapper(func: T):
<ide>
<ide> @functools.wraps(func)
<ide> def _inner_wrapper(self: "GCSHook", * args, **kwargs) -> RT:
<ide> def _inner_wrapper(self: "GCSHook", * args, **kwargs) -> RT:
<ide> )
<ide>
<ide> return func(self, *args, **kwargs)
<del> return _inner_wrapper
<add> return cast(T, _inner_wrapper)
<ide> return _wrapper
<ide>
<ide>
<ide><path>airflow/providers/google/common/hooks/base_google.py
<ide> import tempfile
<ide> from contextlib import contextmanager
<ide> from subprocess import check_output
<del>from typing import Any, Callable, Dict, Optional, Sequence, Tuple, TypeVar
<add>from typing import Any, Callable, Dict, Optional, Sequence, Tuple, TypeVar, cast
<ide>
<ide> import google.auth
<ide> import google.auth.credentials
<ide> def __init__(self):
<ide> super().__init__(is_operation_in_progress_exception)
<ide>
<ide>
<add>T = TypeVar("T", bound=Callable) # pylint: disable=invalid-name
<ide> RT = TypeVar('RT') # pylint: disable=invalid-name
<ide>
<ide>
<ide> def decorator(fun: Callable):
<ide> return decorator
<ide>
<ide> @staticmethod
<del> def operation_in_progress_retry(*args, **kwargs) -> Callable:
<add> def operation_in_progress_retry(*args, **kwargs) -> Callable[[T], T]:
<ide> """
<ide> A decorator that provides a mechanism to repeat requests in response to
<ide> operation in progress (HTTP 409)
<ide> limit.
<ide> """
<del> def decorator(fun: Callable):
<add> def decorator(fun: T):
<ide> default_kwargs = {
<ide> 'wait': tenacity.wait_exponential(multiplier=1, max=300),
<ide> 'retry': retry_if_operation_in_progress(),
<ide> 'before': tenacity.before_log(log, logging.DEBUG),
<ide> 'after': tenacity.after_log(log, logging.DEBUG),
<ide> }
<ide> default_kwargs.update(**kwargs)
<del> return tenacity.retry(
<add> return cast(T, tenacity.retry(
<ide> *args, **default_kwargs
<del> )(fun)
<add> )(fun))
<ide> return decorator
<ide>
<ide> @staticmethod
<ide> def inner_wrapper(self: GoogleBaseHook, *args, **kwargs) -> RT:
<ide> return inner_wrapper
<ide>
<ide> @staticmethod
<del> def provide_gcp_credential_file(func: Callable[..., RT]) -> Callable[..., RT]:
<add> def provide_gcp_credential_file(func: T) -> T:
<ide> """
<ide> Function decorator that provides a GCP credentials for application supporting Application
<ide> Default Credentials (ADC) strategy.
<ide> def provide_gcp_credential_file(func: Callable[..., RT]) -> Callable[..., RT]:
<ide> makes it easier to use multiple connection in one function.
<ide> """
<ide> @functools.wraps(func)
<del> def wrapper(self: GoogleBaseHook, *args, **kwargs) -> RT:
<add> def wrapper(self: GoogleBaseHook, *args, **kwargs):
<ide> with self.provide_gcp_credential_file_as_context():
<ide> return func(self, *args, **kwargs)
<del> return wrapper
<add> return cast(T, wrapper)
<ide>
<ide> @contextmanager
<ide> def provide_gcp_credential_file_as_context(self):
<ide><path>airflow/stats.py
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<ide>
<del>
<ide> import logging
<ide> import socket
<ide> import string
<ide> import textwrap
<ide> from functools import wraps
<del>from typing import TYPE_CHECKING, Callable, Optional
<add>from typing import TYPE_CHECKING, Callable, Optional, TypeVar, cast
<ide>
<ide> from airflow.configuration import conf
<ide> from airflow.exceptions import AirflowConfigException, InvalidStatsNameException
<ide> def get_current_handler_stat_name_func() -> Callable[[str], str]:
<ide> return conf.getimport('scheduler', 'stat_name_handler') or stat_name_default_handler
<ide>
<ide>
<del>def validate_stat(fn):
<add>T = TypeVar("T", bound=Callable) # pylint: disable=invalid-name
<add>
<add>
<add>def validate_stat(fn: T) -> T:
<ide> """Check if stat name contains invalid characters.
<ide> Log and not emit stats if name is invalid
<ide> """
<ide> def wrapper(_self, stat, *args, **kwargs):
<ide> log.error('Invalid stat name: %s.', stat, exc_info=True)
<ide> return
<ide>
<del> return wrapper
<add> return cast(T, wrapper)
<ide>
<ide>
<ide> class AllowListValidator:
<ide><path>airflow/utils/cli.py
<ide> import traceback
<ide> from argparse import Namespace
<ide> from datetime import datetime
<del>from typing import Optional
<add>from typing import Callable, Optional, TypeVar, cast
<ide>
<ide> from airflow import settings
<ide> from airflow.exceptions import AirflowException
<ide> from airflow.utils.platform import is_terminal_support_colors
<ide> from airflow.utils.session import provide_session
<ide>
<add>T = TypeVar("T", bound=Callable) # pylint: disable=invalid-name
<ide>
<del>def action_logging(f):
<add>
<add>def action_logging(f: T) -> T:
<ide> """
<ide> Decorates function to execute function at the same time submitting action_logging
<ide> but in CLI context. It will call action logger callbacks twice,
<ide> def wrapper(*args, **kwargs):
<ide> metrics['end_datetime'] = datetime.utcnow()
<ide> cli_action_loggers.on_post_execution(**metrics)
<ide>
<del> return wrapper
<add> return cast(T, wrapper)
<ide>
<ide>
<ide> def _build_metrics(func_name, namespace):
<ide><path>airflow/www/decorators.py
<ide> import functools
<ide> import gzip
<ide> from io import BytesIO as IO
<add>from typing import Callable, TypeVar, cast
<ide>
<ide> import pendulum
<ide> from flask import after_this_request, flash, g, redirect, request, url_for
<ide>
<ide> from airflow.models import Log
<ide> from airflow.utils.session import create_session
<ide>
<add>T = TypeVar("T", bound=Callable) # pylint: disable=invalid-name
<ide>
<del>def action_logging(f):
<add>
<add>def action_logging(f: T) -> T:
<ide> """
<ide> Decorator to log user actions
<ide> """
<ide> def wrapper(*args, **kwargs):
<ide>
<ide> return f(*args, **kwargs)
<ide>
<del> return wrapper
<add> return cast(T, wrapper)
<ide>
<ide>
<del>def gzipped(f):
<add>def gzipped(f: T) -> T:
<ide> """
<ide> Decorator to make a view compressed
<ide> """
<ide> def zipper(response): # pylint: disable=unused-variable
<ide>
<ide> return f(*args, **kwargs)
<ide>
<del> return view_func
<add> return cast(T, view_func)
<ide>
<ide>
<del>def has_dag_access(**dag_kwargs):
<add>def has_dag_access(**dag_kwargs) -> Callable[[T], T]:
<ide> """
<ide> Decorator to check whether the user has read / write permission on the dag.
<ide> """
<del> def decorator(f):
<add> def decorator(f: T):
<ide> @functools.wraps(f)
<ide> def wrapper(self, *args, **kwargs):
<ide> has_access = self.appbuilder.sm.has_access
<ide> def wrapper(self, *args, **kwargs):
<ide> flash("Access is Denied", "danger")
<ide> return redirect(url_for(self.appbuilder.sm.auth_view.
<ide> __class__.__name__ + ".login"))
<del> return wrapper
<add> return cast(T, wrapper)
<ide> return decorator | 16 |
Python | Python | fix tag and filename conversion for conllu | e237472cdcc32276d042ce56ed0ce3cef560b37e | <ide><path>spacy/cli/converters/conllu2json.py
<ide> def conllu2json(input_path, output_path, n_sents=10, use_morphology=False):
<ide> sentences = []
<ide>
<ide> output_filename = input_path.parts[-1].replace(".conllu", ".json")
<del> output_filename = input_path.parts[-1].replace(".conll", ".json")
<add> output_filename = output_filename.parts[-1].replace(".conll", ".json")
<ide> output_file = output_path / output_filename
<ide> with output_file.open('w', encoding='utf-8') as f:
<ide> f.write(json_dumps(docs))
<ide> def read_conllx(input_path, use_morphology=False, n=0):
<ide> id_ = int(id_) - 1
<ide> head = (int(head) - 1) if head != '0' else id_
<ide> dep = 'ROOT' if dep == 'root' else dep
<add> tag = pos if tag == '_' else tag
<ide> tag = tag+'__'+morph if use_morphology else tag
<ide> tokens.append((id_, word, tag, head, dep, 'O'))
<ide> except: | 1 |
Text | Text | fix typo in #to_s deprecation in 7.0 release notes | c10d1bef13af91bfb12d13dcf3e0d8cf6b3001b6 | <ide><path>guides/source/7_0_release_notes.md
<ide> Please refer to the [Changelog][active-support] for detailed changes.
<ide> `BigDecimal`, `Float` and, `Integer`.
<ide>
<ide> This deprecation is to allow Rails application to take advantage of a Ruby 3.1
<del> [optimization][https://github.com/ruby/ruby/commit/b08dacfea39ad8da3f1fd7fdd0e4538cc892ec44] that makes
<add> [optimization](https://github.com/ruby/ruby/commit/b08dacfea39ad8da3f1fd7fdd0e4538cc892ec44) that makes
<ide> interpolation of some types of objects faster.
<ide>
<ide> New applications will not have the `#to_s` method overridden on those classes, existing applications can use | 1 |
Go | Go | add hasvalidgitprefix to utils/utils.go | d3ac9ea98e872fee808693c736bc5a465d6426e2 | <ide><path>api/client/commands.go
<ide> func (cli *DockerCli) CmdBuild(args ...string) error {
<ide> root := cmd.Arg(0)
<ide> if utils.IsGIT(root) {
<ide> remoteURL := cmd.Arg(0)
<del> if !strings.HasPrefix(remoteURL, "git://") && !strings.HasPrefix(remoteURL, "git@") && !utils.IsURL(remoteURL) {
<add> if !utils.ValidGitTransport(remoteURL) {
<ide> remoteURL = "https://" + remoteURL
<ide> }
<ide>
<ide><path>builder/job.go
<ide> import (
<ide> "io/ioutil"
<ide> "os"
<ide> "os/exec"
<del> "strings"
<ide>
<ide> "github.com/docker/docker/daemon"
<ide> "github.com/docker/docker/engine"
<ide> func (b *BuilderJob) CmdBuild(job *engine.Job) engine.Status {
<ide> if remoteURL == "" {
<ide> context = ioutil.NopCloser(job.Stdin)
<ide> } else if utils.IsGIT(remoteURL) {
<del> if !strings.HasPrefix(remoteURL, "git://") {
<add> if !utils.ValidGitTransport(remoteURL) {
<ide> remoteURL = "https://" + remoteURL
<ide> }
<ide> root, err := ioutil.TempDir("", "docker-build-git")
<ide><path>utils/utils.go
<ide> func IsGIT(str string) bool {
<ide> return strings.HasPrefix(str, "git://") || strings.HasPrefix(str, "github.com/") || strings.HasPrefix(str, "git@github.com:") || (strings.HasSuffix(str, ".git") && IsURL(str))
<ide> }
<ide>
<add>func ValidGitTransport(str string) bool {
<add> return strings.HasPrefix(str, "git://") || strings.HasPrefix(str, "git@") || IsURL(str)
<add>}
<add>
<ide> var (
<ide> localHostRx = regexp.MustCompile(`(?m)^nameserver 127[^\n]+\n*`)
<ide> )
<ide><path>utils/utils_test.go
<ide> func TestReadSymlinkedDirectoryToFile(t *testing.T) {
<ide> t.Errorf("failed to remove symlink: %s", err)
<ide> }
<ide> }
<add>
<add>func TestValidGitTransport(t *testing.T) {
<add> for _, url := range []string{
<add> "git://github.com/docker/docker",
<add> "git@github.com:docker/docker.git",
<add> "https://github.com/docker/docker.git",
<add> "http://github.com/docker/docker.git",
<add> } {
<add> if ValidGitTransport(url) == false {
<add> t.Fatalf("%q should be detected as valid Git prefix", url)
<add> }
<add> }
<add>
<add> for _, url := range []string{
<add> "github.com/docker/docker",
<add> } {
<add> if ValidGitTransport(url) == true {
<add> t.Fatalf("%q should not be detected as valid Git prefix", url)
<add> }
<add> }
<add>} | 4 |
Ruby | Ruby | remove glob pattern from app/channels load path | dd5a49c14082b559355b1f4d8bc5b686e8f67e3f | <ide><path>railties/lib/rails/engine/configuration.rb
<ide> def paths
<ide> exclude: ["assets", javascript_path]
<ide> paths.add "app/assets", glob: "*"
<ide> paths.add "app/controllers", eager_load: true
<del> paths.add "app/channels", eager_load: true, glob: "**/*_channel.rb"
<add> paths.add "app/channels", eager_load: true
<ide> paths.add "app/helpers", eager_load: true
<ide> paths.add "app/models", eager_load: true
<ide> paths.add "app/mailers", eager_load: true | 1 |
Python | Python | add comments to long_double detection code | 888d37086558d982a8afd92cd13778aca264e406 | <ide><path>numpy/core/setup_common.py
<ide> def long_double_representation(lines):
<ide> # the long double
<ide> if read[-8:] == _AFTER_SEQ:
<ide> saw = copy.copy(read)
<add> # if the content was 12 bytes, we only have 32 - 8 - 12 = 12
<add> # "before" bytes. In other words the first 4 "before" bytes went
<add> # past the sliding window.
<ide> if read[:12] == _BEFORE_SEQ[4:]:
<ide> if read[12:-8] == _INTEL_EXTENDED_12B:
<ide> return 'INTEL_EXTENDED_12_BYTES_LE'
<ide> if read[12:-8] == _MOTOROLA_EXTENDED_12B:
<ide> return 'MOTOROLA_EXTENDED_12_BYTES_BE'
<add> # if the content was 16 bytes, we are left with 32-8-16 = 16
<add> # "before" bytes, so 8 went past the sliding window.
<ide> elif read[:8] == _BEFORE_SEQ[8:]:
<ide> if read[8:-8] == _INTEL_EXTENDED_16B:
<ide> return 'INTEL_EXTENDED_16_BYTES_LE'
<ide> def long_double_representation(lines):
<ide> return 'DOUBLE_DOUBLE_BE'
<ide> elif read[8:-8] == _DOUBLE_DOUBLE_LE:
<ide> return 'DOUBLE_DOUBLE_LE'
<add> # if the content was 8 bytes, left with 32-8-8 = 16 bytes
<ide> elif read[:16] == _BEFORE_SEQ:
<ide> if read[16:-8] == _IEEE_DOUBLE_LE:
<ide> return 'IEEE_DOUBLE_LE' | 1 |
Python | Python | remove unused warning | db2dbc8e59d1a61a0d16fea371925e4667c8dec9 | <ide><path>spacy/errors.py
<ide> class Warnings:
<ide> "loaded. (Shape: {shape})")
<ide> W021 = ("Unexpected hash collision in PhraseMatcher. Matches may be "
<ide> "incorrect. Modify PhraseMatcher._terminal_hash to fix.")
<del> W022 = ("Training a new part-of-speech tagger using a model with no "
<del> "lemmatization rules or data. This means that the trained model "
<del> "may not be able to lemmatize correctly. If this is intentional "
<del> "or the language you're using doesn't have lemmatization data, "
<del> "you can ignore this warning. If this is surprising, make sure you "
<del> "have the spacy-lookups-data package installed.")
<ide> W024 = ("Entity '{entity}' - Alias '{alias}' combination already exists in "
<ide> "the Knowledge Base.")
<ide> W026 = ("Unable to set all sentence boundaries from dependency parses.") | 1 |
Text | Text | add graphql stub and opening paragraph for guide | f606d9cc6d16597b95fafff7a77599a48df9db25 | <ide><path>guide/english/graphql/index.md
<ide> title: GraphQL
<ide> ---
<ide>
<del>## GraphQL
<add># GraphQL
<add>Developed by Facebook and launched in 2015, GraphQL is an API standard defined by its use of a declarative request that returns only the data the client requested, in the shape they desire. Unlike traditional REST APIs, GraphQL allows the client side of an application to ask for the exact pieces of data it requires in a readable way.
<ide>
<del>GraphQL is a query language developed by Facebook that provides a syntax to query data in from API. Unlike traditional REST APIs, GraphQL allows the client side of an application to ask for the exact pieces of data it requires in a readable way.
<add>An alternative to the fixed endpoints of REST, its flexible approach makes aggregating data from multiple sources simpler, analytics are more refined and minimising the data fetched puts less pressure on slower networks, which speeds up responses for users
<ide>
<ide> GraphQL schemas are often coupled with frameworks such as [Relay](https://facebook.github.io/relay/) or [Apollo](https://www.apollographql.com/) to make these requests from the client. GraphQL powers how [GatsbyJS](https://www.gatsbyjs.org) fetches data.
<ide>
<del>
<del>### Installation
<del>
<add>## Installation
<ide> From the command line run:
<ide>
<del>```bash
<add>```sh
<ide> npm init
<ide> npm install graphql --save
<ide> ```
<ide>
<del>#### More Information:
<del>For tutorials and more information check out the GraphQL official site: [Getting Started With GraphQL.js](https://graphql.org/graphql-js/)
<add>## Queries
<add><!-- This section is a stub. Consider contributing by forking this repository and submitting a Pull Request with your changes! -->
<add>
<add>## Mutations
<add><!-- This section is a stub. Consider contributing by forking this repository and submitting a Pull Request with your changes! -->
<add>
<add>## Resolvers
<add><!-- This section is a stub. Consider contributing by forking this repository and submitting a Pull Request with your changes! -->
<add>
<add>## Schemas
<add><!-- This section is a stub. Consider contributing by forking this repository and submitting a Pull Request with your changes! -->
<add>
<add>## Additional Resources
<add>- For tutorials and more information check out the GraphQL official site: [Getting Started With GraphQL.js](https://graphql.org/graphql-js/)
<add>- [GraphQL Site and Documentation](https://graphql.org/)
<add>- [How to GraphQL Tutorial](https://www.howtographql.com/) | 1 |
Ruby | Ruby | use new syntax correctly | f7e308ab44f15db2e2d3536e1d8deb829705102e | <ide><path>Library/Homebrew/cmd/list.rb
<ide> def list
<ide> switch "--pinned"
<ide> switch "--versions"
<ide> switch "--full-name"
<del> switch "--multiple", required_for: "--versions"
<add> switch "--multiple", depends_on: "--versions"
<ide> switch :verbose
<ide> end
<ide> | 1 |
Mixed | Go | allow filtering containers by any status | f30364c5835452598e58781f360681f2d77fa16c | <ide><path>daemon/list.go
<ide> func (daemon *Daemon) foldFilter(config *ContainersConfig) (*listContext, error)
<ide> if !isValidStateString(value) {
<ide> return nil, errors.New("Unrecognised filter value for status")
<ide> }
<del> if value == "exited" || value == "created" {
<del> config.All = true
<del> }
<add>
<add> config.All = true
<ide> }
<ide> }
<ide>
<ide><path>docs/reference/api/docker_remote_api_v1.22.md
<ide> Query Parameters:
<ide> sizes
<ide> - **filters** - a JSON encoded value of the filters (a `map[string][]string`) to process on the containers list. Available filters:
<ide> - `exited=<int>`; -- containers with exit code of `<int>` ;
<del> - `status=`(`created`|`restarting`|`running`|`paused`|`exited`)
<add> - `status=`(`created`|`restarting`|`running`|`paused`|`exited`|`dead`)
<ide> - `label=key` or `label="key=value"` of a container label
<ide> - `isolation=`(`default`|`process`|`hyperv`) (Windows daemon only)
<ide> | 2 |
PHP | PHP | handle loose % signs in __() function | 5334fe04c364100b031740eeea77b7d91c381d16 | <ide><path>lib/Cake/Test/Case/BasicsTest.php
<ide> public function testTranslate() {
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<add>/**
<add> * testTranslatePercent
<add> *
<add> * @return void
<add> */
<add> public function testTranslatePercent() {
<add> $result = __('%s are 100% real fruit', 'Apples');
<add> $expected = 'Apples are 100% real fruit';
<add> $this->assertEquals($expected, $result, 'Percent sign at end of word should be considered literal');
<add>
<add> $result = __('%s are %d% real fruit', 'Apples', 100);
<add> $expected = 'Apples are 100% real fruit';
<add> $this->assertEquals($expected, $result, 'A digit marker should not be misinterpreted');
<add>
<add> $result = __('%s are %s% real fruit', 'Apples', 100);
<add> $expected = 'Apples are 100% real fruit';
<add> $this->assertEquals($expected, $result, 'A string marker should not be misinterpreted');
<add>
<add> $result = __('%nonsense %s', 'Apples');
<add> $expected = '%nonsense Apples';
<add> $this->assertEquals($expected, $result, 'A percent sign at the start of the string should be considered literal');
<add>
<add> $result = __('%s are awesome%', 'Apples');
<add> $expected = 'Apples are awesome%';
<add> $this->assertEquals($expected, $result, 'A percent sign at the end of the string should be considered literal');
<add>
<add> $result = __('%2$d %1$s entered the bowl', 'Apples', 2);
<add> $expected = '2 Apples entered the bowl';
<add> $this->assertEquals($expected, $result, 'Positional replacement markers should not be misinterpreted');
<add>
<add> $result = __('%.2f% of all %s agree', 99.44444, 'Cats');
<add> $expected = '99.44% of all Cats agree';
<add> $this->assertEquals($expected, $result, 'significant-digit placeholder should not be misinterpreted');
<add> }
<add>
<ide> /**
<ide> * test __n()
<ide> *
<ide><path>lib/Cake/basics.php
<ide> function __($singular, $args = null) {
<ide> } elseif (!is_array($args)) {
<ide> $args = array_slice(func_get_args(), 1);
<ide> }
<add>
<add> $translated = preg_replace('/(?<!%)%(?![%bcdeEfFgGosuxX\d\.])/', '%%', $translated);
<ide> return vsprintf($translated, $args);
<ide> }
<ide>
<ide> function __n($singular, $plural, $count, $args = null) {
<ide> } elseif (!is_array($args)) {
<ide> $args = array_slice(func_get_args(), 3);
<ide> }
<add>
<add> $translated = preg_replace('/(?<!%)%(?![%bcdeEfFgGosuxX\d\.])/', '%%', $translated);
<ide> return vsprintf($translated, $args);
<ide> }
<ide>
<ide> function __d($domain, $msg, $args = null) {
<ide> } elseif (!is_array($args)) {
<ide> $args = array_slice(func_get_args(), 2);
<ide> }
<add>
<add> $translated = preg_replace('/(?<!%)%(?![%bcdeEfFgGosuxX\d\.])/', '%%', $translated);
<ide> return vsprintf($translated, $args);
<ide> }
<ide>
<ide> function __dn($domain, $singular, $plural, $count, $args = null) {
<ide> } elseif (!is_array($args)) {
<ide> $args = array_slice(func_get_args(), 4);
<ide> }
<add>
<add> $translated = preg_replace('/(?<!%)%(?![%bcdeEfFgGosuxX\d\.])/', '%%', $translated);
<ide> return vsprintf($translated, $args);
<ide> }
<ide>
<ide> function __dc($domain, $msg, $category, $args = null) {
<ide> } elseif (!is_array($args)) {
<ide> $args = array_slice(func_get_args(), 3);
<ide> }
<add>
<add> $translated = preg_replace('/(?<!%)%(?![%bcdeEfFgGosuxX\d\.])/', '%%', $translated);
<ide> return vsprintf($translated, $args);
<ide> }
<ide>
<ide> function __dcn($domain, $singular, $plural, $count, $category, $args = null) {
<ide> } elseif (!is_array($args)) {
<ide> $args = array_slice(func_get_args(), 5);
<ide> }
<add>
<add> $translated = preg_replace('/(?<!%)%(?![%bcdeEfFgGosuxX\d\.])/', '%%', $translated);
<ide> return vsprintf($translated, $args);
<ide> }
<ide>
<ide> function __c($msg, $category, $args = null) {
<ide> } elseif (!is_array($args)) {
<ide> $args = array_slice(func_get_args(), 2);
<ide> }
<add>
<add> $translated = preg_replace('/(?<!%)%(?![%bcdeEfFgGosuxX\d\.])/', '%%', $translated);
<ide> return vsprintf($translated, $args);
<ide> }
<ide> | 2 |
Python | Python | remove log groups in the lambda system test | ed9bab09f34fbfd36e4b597f0a891ffd0f83cebc | <ide><path>tests/system/providers/amazon/aws/example_lambda.py
<ide> import json
<ide> import zipfile
<ide> from datetime import datetime
<add>from typing import List, Optional, Tuple
<ide>
<ide> import boto3
<ide>
<ide> from airflow.models.baseoperator import chain
<ide> from airflow.providers.amazon.aws.operators.lambda_function import AwsLambdaInvokeFunctionOperator
<ide> from airflow.utils.trigger_rule import TriggerRule
<del>from tests.system.providers.amazon.aws.utils import ENV_ID_KEY, SystemTestContextBuilder
<add>from tests.system.providers.amazon.aws.utils import ENV_ID_KEY, SystemTestContextBuilder, purge_logs
<ide>
<ide> DAG_ID = 'example_lambda'
<ide>
<ide> def test(*args):
<ide>
<ide>
<ide> # Create a zip file containing one file "lambda_function.py" to deploy to the lambda function
<del>def create_zip(content):
<add>def create_zip(content: str):
<ide> zip_output = io.BytesIO()
<ide> with zipfile.ZipFile(zip_output, "w", zipfile.ZIP_DEFLATED) as zip_file:
<ide> info = zipfile.ZipInfo("lambda_function.py")
<ide> def create_zip(content):
<ide>
<ide>
<ide> @task
<del>def create_lambda(function_name, role_arn):
<add>def create_lambda(function_name: str, role_arn: str):
<ide> client = boto3.client('lambda')
<ide> client.create_function(
<ide> FunctionName=function_name,
<ide> def create_lambda(function_name, role_arn):
<ide>
<ide>
<ide> @task
<del>def await_lambda(function_name):
<add>def await_lambda(function_name: str):
<ide> client = boto3.client('lambda')
<ide> waiter = client.get_waiter('function_active_v2')
<ide> waiter.wait(FunctionName=function_name)
<ide>
<ide>
<ide> @task(trigger_rule=TriggerRule.ALL_DONE)
<del>def delete_lambda(function_name):
<add>def delete_lambda(function_name: str):
<ide> client = boto3.client('lambda')
<ide> client.delete_function(
<ide> FunctionName=function_name,
<ide> )
<ide>
<ide>
<add>@task(trigger_rule=TriggerRule.ALL_DONE)
<add>def delete_logs(function_name: str) -> None:
<add> generated_log_groups: List[Tuple[str, Optional[str]]] = [
<add> (f'/aws/lambda/{function_name}', None),
<add> ]
<add>
<add> purge_logs(test_logs=generated_log_groups, force_delete=True, retry=True)
<add>
<add>
<ide> with models.DAG(
<ide> DAG_ID,
<ide> schedule_interval='@once',
<ide> def delete_lambda(function_name):
<ide> invoke_lambda_function,
<ide> # TEST TEARDOWN
<ide> delete_lambda(lambda_function_name),
<add> delete_logs(lambda_function_name),
<ide> )
<ide>
<ide> from tests.system.utils.watcher import watcher
<ide><path>tests/system/providers/amazon/aws/utils/__init__.py
<ide> import logging
<ide> import os
<ide> from os.path import basename, splitext
<add>from time import sleep
<ide> from typing import List, Optional, Tuple
<ide> from uuid import uuid4
<ide>
<ide> import boto3
<ide> from botocore.client import BaseClient
<del>from botocore.exceptions import NoCredentialsError
<add>from botocore.exceptions import ClientError, NoCredentialsError
<ide>
<ide> from airflow.decorators import task
<ide>
<ide> DEFAULT_ENV_ID_PREFIX: str = 'env'
<ide> DEFAULT_ENV_ID_LEN: int = 8
<ide> DEFAULT_ENV_ID: str = f'{DEFAULT_ENV_ID_PREFIX}{str(uuid4())[:DEFAULT_ENV_ID_LEN]}'
<add>PURGE_LOGS_INTERVAL_PERIOD = 5
<ide>
<ide> # All test file names will contain this string.
<ide> TEST_FILE_IDENTIFIER: str = 'example'
<ide> def fetch_variable(key: str, default_value: Optional[str] = None, test_name: Opt
<ide>
<ide> :param key: The name of the Parameter to fetch a value for.
<ide> :param default_value: The default value to use if no value can be found.
<add> :param test_name: The system test name.
<ide> :return: The value of the parameter.
<ide> """
<ide>
<ide> def set_env_id() -> str:
<ide> return env_id
<ide>
<ide>
<del>def purge_logs(test_logs: List[Tuple[str, Optional[str]]]) -> None:
<add>def purge_logs(
<add> test_logs: List[Tuple[str, Optional[str]]],
<add> force_delete: bool = False,
<add> retry: bool = False,
<add> retry_times: int = 3,
<add>) -> None:
<ide> """
<ide> Accepts a tuple in the format: ('log group name', 'log stream prefix').
<ide> For each log group, it will delete any log streams matching the provided
<del> prefix then if the log group is empty, delete the group. If the group
<add> prefix then if the log group is empty, delete the group. If the group
<ide> is not empty that indicates there are logs not generated by the test and
<del> those are left intact.
<add> those are left intact. If `check_log_streams` is True, it will simply delete the log group regardless
<add> of log streams within that log group.
<ide>
<ide> :param test_logs: A list of log_group/stream_prefix tuples to delete.
<add> :param force_delete: Whether to check log streams within the log group before removal. If True,
<add> removes the log group and all its log streams inside it
<add> :param retry: Whether to retry if the log group/stream was not found. In some cases, the log group/stream
<add> is created seconds after the main resource has been created. By default, it retries for 3 times
<add> with a 5s waiting period
<add> :param retry_times: Number of retries
<ide> """
<ide> client: BaseClient = boto3.client('logs')
<ide>
<ide> for group, prefix in test_logs:
<del> if prefix:
<del> log_streams = client.describe_log_streams(
<del> logGroupName=group,
<del> logStreamNamePrefix=prefix,
<del> )['logStreams']
<del>
<del> for stream_name in [stream['logStreamName'] for stream in log_streams]:
<del> client.delete_log_stream(logGroupName=group, logStreamName=stream_name)
<del>
<del> if not client.describe_log_streams(logGroupName=group)['logStreams']:
<del> client.delete_log_group(logGroupName=group)
<add> try:
<add> if prefix:
<add> log_streams = client.describe_log_streams(
<add> logGroupName=group,
<add> logStreamNamePrefix=prefix,
<add> )['logStreams']
<add>
<add> for stream_name in [stream['logStreamName'] for stream in log_streams]:
<add> client.delete_log_stream(logGroupName=group, logStreamName=stream_name)
<add>
<add> if force_delete or not client.describe_log_streams(logGroupName=group)['logStreams']:
<add> client.delete_log_group(logGroupName=group)
<add> except ClientError as e:
<add> if not retry or retry_times == 0 or e.response['Error']['Code'] != 'ResourceNotFoundException':
<add> raise e
<add>
<add> sleep(PURGE_LOGS_INTERVAL_PERIOD)
<add> purge_logs(
<add> test_logs=test_logs,
<add> force_delete=force_delete,
<add> retry=retry,
<add> retry_times=retry_times - 1,
<add> )
<ide>
<ide>
<ide> @task | 2 |
Javascript | Javascript | remove headmanager property as it’s unused | b41c85e32ad8f23bf1cd10918d8ef472e2ceaaf0 | <ide><path>packages/next/client/index.js
<ide> function renderReactElement (reactEl, domEl) {
<ide> }
<ide> }
<ide>
<del>async function doRender ({ App, Component, props, err, emitter: emitterProp = emitter }) {
<add>async function doRender ({ App, Component, props, err }) {
<ide> // Usual getInitialProps fetching is handled in next/router
<ide> // this is for when ErrorComponent gets replaced by Component by HMR
<ide> if (!props && Component &&
<ide> async function doRender ({ App, Component, props, err, emitter: emitterProp = em
<ide> Component = Component || lastAppProps.Component
<ide> props = props || lastAppProps.props
<ide>
<del> const appProps = { Component, err, router, headManager, ...props }
<add> const appProps = { Component, err, router, ...props }
<ide> // lastAppProps has to be set before ReactDom.render to account for ReactDom throwing an error.
<ide> lastAppProps = appProps
<ide>
<del> emitterProp.emit('before-reactdom-render', { Component, ErrorComponent, appProps })
<add> emitter.emit('before-reactdom-render', { Component, ErrorComponent, appProps })
<ide>
<ide> // In development runtime errors are caught by react-error-overlay.
<ide> if (process.env.NODE_ENV === 'development') {
<ide> async function doRender ({ App, Component, props, err, emitter: emitterProp = em
<ide> ), appContainer)
<ide> }
<ide>
<del> emitterProp.emit('after-reactdom-render', { Component, ErrorComponent, appProps })
<add> emitter.emit('after-reactdom-render', { Component, ErrorComponent, appProps })
<ide> } | 1 |
Javascript | Javascript | terminate statement in page.js | 55a697a86d6febe44d03ac740592abd3f5e293fc | <ide><path>docs/page.js
<ide> var onDocumentLoad = function ( event ) {
<ide>
<ide> prettyPrint();
<ide>
<del> }
<add> };
<ide>
<ide> document.head.appendChild( prettify );
<ide> | 1 |
PHP | PHP | use 3rd param instead | f4179e3b2db4b3351a8acd0f18007571e385994e | <ide><path>src/View/Helper/PaginatorHelper.php
<ide> public function sort($key, $title = null, array $options = [])
<ide> /**
<ide> * Merges passed URL options with current pagination state to generate a pagination URL.
<ide> *
<del> * ### Options:
<add> * ### Url options:
<ide> *
<ide> * - `escape`: If false, the URL will be returned unescaped, do only use if it is manually
<ide> * escaped afterwards before being displayed.
<ide> * - `fullBase`: If true, the full base URL will be prepended to the result
<ide> *
<ide> * @param array $options Pagination/URL options array
<ide> * @param string|null $model Which model to paginate on
<del> * @param bool $full If true, the full base URL will be prepended to the result @deprecated Use $options and `fullBase`.
<add> * @param array|bool $urlOptions Array of options or bool `fullBase` for BC reasons.
<ide> * @return string By default, returns a full pagination URL string for use in non-standard contexts (i.e. JavaScript)
<ide> * @link http://book.cakephp.org/3.0/en/views/helpers/paginator.html#generating-pagination-urls
<ide> */
<del> public function generateUrl(array $options = [], $model = null, $full = false)
<add> public function generateUrl(array $options = [], $model = null, $urlOptions = false)
<ide> {
<ide> $paging = $this->params($model);
<ide> $paging += ['page' => null, 'sort' => null, 'direction' => null, 'limit' => null];
<ide>
<del> $defaults = [
<add> if (!is_array($urlOptions)) {
<add> $urlOptions = ['fullBase' => $urlOptions];
<add> }
<add> $urlOptions += [
<ide> 'escape' => true,
<del> 'fullBase' => $full
<add> 'fullBase' => false
<ide> ];
<del> $options += $defaults;
<ide>
<ide> $url = [
<ide> 'page' => $paging['page'],
<ide> public function generateUrl(array $options = [], $model = null, $full = false)
<ide> }
<ide> }
<ide>
<del> return $this->Url->build($url, $options);
<add> return $this->Url->build($url, $urlOptions);
<ide> }
<ide>
<ide> /** | 1 |
Text | Text | clarify the use of numeric uids | a7cfb098d48b9b9ce19bc57fd2c219981b24b75b | <ide><path>docs/reference/run.md
<ide> volume mounted on the host).
<ide>
<ide> ### USER
<ide>
<del>The default user within a container is `root` (id = 0), but if the
<del>developer created additional users, those are accessible too. The
<del>developer can set a default user to run the first process with the
<del>Dockerfile `USER` instruction, but the operator can override it:
<add>The default user within a container is `root` (id = 0), but if the developer
<add>created additional users, those are accessible by name. When passing a numeric
<add>ID, the user doesn't have to exist in the container. The developer can set a
<add>default user to run the first process with the Dockerfile `USER` instruction,
<add>but the operator can override it:
<ide>
<ide> -u="": Username or UID
<ide> | 1 |
PHP | PHP | use a boolean default | 3c55601e25c28148f4328e913f5d19ec97d34edd | <ide><path>src/Http/ServerRequestFactory.php
<ide> public static function fromGlobals(
<ide> 'webroot' => $uri->webroot,
<ide> 'base' => $uri->base,
<ide> 'session' => $session,
<del> 'mergeFilesAsObjects' => Configure::read('App.uploadedFilesAsObjects'),
<add> 'mergeFilesAsObjects' => Configure::read('App.uploadedFilesAsObjects', false),
<ide> ]);
<ide>
<ide> return $request; | 1 |
Text | Text | unify coverage of collection helpers [ci skip] | d118875dced86d2fb2bc27dea807e09779293fba | <ide><path>guides/source/form_helpers.md
<ide> Notice that the appropriate option was automatically marked `selected="selected"
<ide>
<ide> ### Time Zone and Country Select
<ide>
<del>To leverage time zone support in Rails, you have to ask your users what time zone they are in. Doing so would require generating select options from a list of pre-defined [`ActiveSupport::TimeZone`](https://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html) objects using `collection_select`, but you can simply use the `time_zone_select` helper that already wraps this:
<add>To leverage time zone support in Rails, you have to ask your users what time zone they are in. Doing so would require generating select options from a list of pre-defined [`ActiveSupport::TimeZone`](https://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html) objects, but you can simply use the `time_zone_select` helper that already wraps this:
<ide>
<ide> ```erb
<ide> <%= time_zone_select(:person, :time_zone) %>
<ide> The first parameter specifies which value should be selected and can either be a
<ide>
<ide> will produce the same output and the value chosen by the user can be retrieved by `params[:date][:year]`.
<ide>
<del>Creating Checkboxes for Relations
<del>------------------------------------------
<del>
<del>Generating checkboxes options that act appropriately with Active Record models
<del>and strong parameters can be a confusing undertaking. Luckily there is a helper
<del>function to significantly reduce the work required.
<add>Choices from a Collection of Arbitrary Objects
<add>----------------------------------------------
<ide>
<del>Here is what the markup may look like:
<add>Often, we want to generate a set of choices in a form from a collection of objects. For example, when we want the user to choose from cities in our database, and we have a `City` model like:
<ide>
<del>```html
<del><input type="checkbox" value="1" checked="checked" name="person[city_ids][]" id="person_cities_1" />
<del><label for="person_cities_1">Pittsburgh</label>
<del><input type="checkbox" value="2" checked="checked" name="person[city_ids][]" id="person_cities_2"/>
<del><label for="person_cities_2">Madison</label>
<del><input type="checkbox" value="3" checked="checked" name="person[city_ids][]" id="person_cities_3"/>
<del><label for="person_cities_3">Santa Rosa</label>
<add>```ruby
<add>City.order(:name).to_a
<add># => [
<add># #<City id: 3, name: "Berlin">,
<add># #<City id: 1, name: "Lisbon">,
<add># #<City id: 2, name: "Madrid">
<add># ]
<ide> ```
<ide>
<del>You have a list of cities whose names are shown to the user and associated
<del>checkboxes that hold the id of each cities database entry.
<del>
<del>### The Collection Check Boxes tag
<add>Rails provides helpers that generate choices from a collection without having to explicitly iterate over it. These helpers determine the value and text label of each choice by calling specified methods on each object in the collection.
<ide>
<del>The `collection_check_boxes` exists to help create these checkboxes with the
<del>name for each input that maps to params that can be passed directly to model
<del>relationships.
<add>### The `collection_select` Helper
<ide>
<del>In this example we show the currently associated records in a collection:
<add>To generate a select box for our cities, we can use [`collection_select`](https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-collection_select):
<ide>
<ide> ```erb
<del><%= form_with model: @person do |person_form| %>
<del> <%= person_form.collection_check_boxes :city_ids, person.object.cities, :id, :name %>
<del><% end %>
<add><%= form.collection_select :city_id, City.order(:name), :id, :name %>
<ide> ```
<ide>
<del>This returns
<add>Output:
<ide>
<ide> ```html
<del><input type="checkbox" value="1" checked="checked" name="person[city_ids][]" id="person_cities_1" checked="checked" />
<del><label for="person_cities_1">Pittsburgh</label>
<del><input type="checkbox" value="2" checked="checked" name="person[city_ids][]" id="person_cities_2" checked="checked" />
<del><label for="person_cities_2">Madison</label>
<del><input type="checkbox" value="3" checked="checked" name="person[city_ids][]" id="person_cities_3" checked="checked" />
<del><label for="person_cities_3">Santa Rosa</label>
<add><select name="city_id" id="city_id">
<add> <option value="3">Berlin</option>
<add> <option value="1">Lisbon</option>
<add> <option value="2">Madrid</option>
<add></select>
<ide> ```
<ide>
<del>You can also pass a block to format the html as you'd like:
<add>NOTE: With `collection_select` we specify the value method first (`:id` in the example above), and the text label method second (`:name` in the example above). This is opposite of the order used when specifying choices for the `select` helper, where the text label comes first and the value second.
<add>
<add>### The `collection_radio_buttons` Helper
<add>
<add>To generate a set of radio buttons for our cities, we can use [`collection_radio_buttons`](https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-collection_radio_buttons):
<ide>
<ide> ```erb
<del><%= form_with model: @person do |person_form| %>
<del> <%= person_form.collection_check_boxes :city_ids, City.all, :id, :name do |city| %>
<del> <div>
<del> <%= city.check_box %><%= city.label %>
<del> </div>
<del> <% end %>
<del><% end %>
<add><%= form.collection_radio_buttons :city_id, City.order(:name), :id, :name %>
<ide> ```
<ide>
<del>This returns
<add>Output:
<ide>
<ide> ```html
<del><div>
<del> <input type="checkbox" value="1" checked="checked" name="person[city_ids][]" id="person_cities_1" checked="checked" />
<del> <label for="person_cities_1">Pittsburgh</label>
<del></div>
<del><div>
<del> <input type="checkbox" value="2" checked="checked" name="person[city_ids][]" id="person_cities_2" checked="checked" />
<del> <label for="person_cities_2">Madison</label>
<del></div>
<del><div>
<del> <input type="checkbox" value="3" checked="checked" name="person[city_ids][]" id="person_cities_3" checked="checked" />
<del> <label for="person_cities_3">Santa Rosa</label>
<del></div>
<del>```
<del>
<del>The method signature is
<add><input type="radio" name="city_id" value="3" id="city_id_3">
<add><label for="city_id_3">Berlin</label>
<add><input type="radio" name="city_id" value="1" id="city_id_1">
<add><label for="city_id_1">Lisbon</label>
<add><input type="radio" name="city_id" value="2" id="city_id_2">
<add><label for="city_id_2">Madrid</label>
<add>```
<add>
<add>### The `collection_check_boxes` Helper
<add>
<add>To generate a set of check boxes for our cities (which allows users to choose more than one), we can use [`collection_check_boxes`](https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-collection_check_boxes):
<ide>
<ide> ```erb
<del>collection_check_boxes(object, method, collection, value_method, text_method, options = {}, html_options = {}, &block)
<del>```
<del>* `object` - the form object, this is unnecessary if using the
<del> `form.collection_check_boxes` method call
<del>* `method` - the association method for the model relation
<del>* `collection` - an array of objects to show in checkboxes
<del>* `value_method` - the method to call when populating the value attribute in
<del> the checkbox
<del>* `text` - the method to call when populating the text of the label
<add><%= form.collection_check_boxes :city_id, City.order(:name), :id, :name %>
<add>```
<add>
<add>Output:
<add>
<add>```html
<add><input type="checkbox" name="city_id[]" value="3" id="city_id_3">
<add><label for="city_id_3">Berlin</label>
<add><input type="checkbox" name="city_id[]" value="1" id="city_id_1">
<add><label for="city_id_1">Lisbon</label>
<add><input type="checkbox" name="city_id[]" value="2" id="city_id_2">
<add><label for="city_id_2">Madrid</label>
<add>```
<ide>
<ide> Uploading Files
<ide> --------------- | 1 |
Javascript | Javascript | remove jquery integration in eventdispatcher | 28804ab8c82f765b521e4959cd3a8e3d216b69dd | <ide><path>packages/@ember/-internals/glimmer/tests/integration/event-dispatcher-test.js
<del>import { RenderingTestCase, moduleFor, runTask } from 'internal-test-helpers';
<add>import { moduleFor, RenderingTestCase, runTask } from 'internal-test-helpers';
<ide>
<ide> import { Component } from '../utils/helpers';
<ide> import { _getCurrentRunLoop } from '@ember/runloop';
<ide> import {
<del> subscribe as instrumentationSubscribe,
<ide> reset as instrumentationReset,
<add> subscribe as instrumentationSubscribe,
<ide> } from '@ember/instrumentation';
<ide> import { EMBER_IMPROVED_INSTRUMENTATION } from '@ember/canary-features';
<del>import { jQueryDisabled, jQuery } from '@ember/-internals/views';
<del>import { DEBUG } from '@glimmer/env';
<ide>
<ide> let canDataTransfer = Boolean(document.createEvent('HTMLEvents').dataTransfer);
<ide>
<ide> moduleFor(
<ide> this.$('#is-done').trigger('click');
<ide> }
<ide>
<add> ['@test native event on text node does not throw on hasAttribute [ISSUE #16730]'](assert) {
<add> this.registerComponent('x-foo', {
<add> ComponentClass: Component.extend({
<add> actions: {
<add> someAction() {},
<add> },
<add> }),
<add> template: `<a id="inner" href="#" {{action 'someAction'}}>test</a>`,
<add> });
<add>
<add> this.render(`{{x-foo id="outer"}}`);
<add>
<add> let node = this.$('#inner')[0].childNodes[0];
<add>
<add> runTask(() => {
<add> let event = document.createEvent('HTMLEvents');
<add> event.initEvent('mousemove', true, true);
<add> node.dispatchEvent(event);
<add> });
<add>
<add> assert.ok(true);
<add> }
<add>
<ide> ['@test [DEPRECATED] delegated event listeners work for mouseEnter/Leave'](assert) {
<ide> let receivedEnterEvents = [];
<ide> let receivedLeaveEvents = [];
<ide> if (canDataTransfer) {
<ide> }
<ide> );
<ide> }
<del>
<del>if (jQueryDisabled) {
<del> moduleFor(
<del> 'EventDispatcher#native-events',
<del> class extends RenderingTestCase {
<del> ['@test native events are passed when jQuery is not present'](assert) {
<del> let receivedEvent;
<del>
<del> this.registerComponent('x-foo', {
<del> ComponentClass: Component.extend({
<del> click(event) {
<del> receivedEvent = event;
<del> },
<del> }),
<del> template: `<button id="foo">bar</button>`,
<del> });
<del>
<del> this.render(`{{x-foo}}`);
<del>
<del> runTask(() => this.$('#foo').click());
<del> assert.ok(receivedEvent, 'click event was triggered');
<del> assert.notOk(receivedEvent.originalEvent, 'event is not a jQuery.Event');
<del> }
<del>
<del> ['@test native event on text node does not throw on hasAttribute [ISSUE #16730]'](assert) {
<del> this.registerComponent('x-foo', {
<del> ComponentClass: Component.extend({
<del> actions: {
<del> someAction() {},
<del> },
<del> }),
<del> template: `<a id="inner" href="#" {{action 'someAction'}}>test</a>`,
<del> });
<del>
<del> this.render(`{{x-foo id="outer"}}`);
<del>
<del> let node = this.$('#inner')[0].childNodes[0];
<del>
<del> runTask(() => {
<del> let event = document.createEvent('HTMLEvents');
<del> event.initEvent('mousemove', true, true);
<del> node.dispatchEvent(event);
<del> });
<del>
<del> assert.ok(true);
<del> }
<del> }
<del> );
<del>} else {
<del> moduleFor(
<del> 'EventDispatcher#jquery-events',
<del> class extends RenderingTestCase {
<del> beforeEach() {
<del> this.jqueryIntegration = window.EmberENV._JQUERY_INTEGRATION;
<del> }
<del>
<del> afterEach() {
<del> window.EmberENV._JQUERY_INTEGRATION = this.jqueryIntegration;
<del> }
<del>
<del> ['@test jQuery events are passed when jQuery is present'](assert) {
<del> let receivedEvent;
<del>
<del> this.registerComponent('x-foo', {
<del> ComponentClass: Component.extend({
<del> click(event) {
<del> receivedEvent = event;
<del> },
<del> }),
<del> template: `<button id="foo">bar</button>`,
<del> });
<del>
<del> this.render(`{{x-foo}}`);
<del>
<del> runTask(() => this.$('#foo').click());
<del> assert.ok(receivedEvent, 'click event was triggered');
<del> assert.ok(receivedEvent instanceof jQuery.Event, 'event is a jQuery.Event');
<del> }
<del>
<del> ['@test accessing jQuery.Event#originalEvent is deprecated'](assert) {
<del> let receivedEvent;
<del>
<del> this.registerComponent('x-foo', {
<del> ComponentClass: Component.extend({
<del> click(event) {
<del> receivedEvent = event;
<del> },
<del> }),
<del> template: `<button id="foo">bar</button>`,
<del> });
<del>
<del> this.render(`{{x-foo}}`);
<del>
<del> runTask(() => this.$('#foo').click());
<del> expectDeprecation(() => {
<del> let { originalEvent } = receivedEvent;
<del> assert.ok(originalEvent, 'jQuery event has originalEvent property');
<del> assert.equal(originalEvent.type, 'click', 'properties of originalEvent are available');
<del> }, 'Accessing jQuery.Event specific properties is deprecated. Either use the ember-jquery-legacy addon to normalize events to native events, or explicitly opt into jQuery integration using @ember/optional-features.');
<del> }
<del>
<del> ['@test other jQuery.Event properties do not trigger deprecation'](assert) {
<del> let receivedEvent;
<del>
<del> this.registerComponent('x-foo', {
<del> ComponentClass: Component.extend({
<del> click(event) {
<del> receivedEvent = event;
<del> },
<del> }),
<del> template: `<button id="foo">bar</button>`,
<del> });
<del>
<del> this.render(`{{x-foo}}`);
<del>
<del> runTask(() => this.$('#foo').click());
<del> expectNoDeprecation(() => {
<del> receivedEvent.stopPropagation();
<del> receivedEvent.stopImmediatePropagation();
<del> receivedEvent.preventDefault();
<del> assert.ok(receivedEvent.bubbles, 'properties of jQuery event are available');
<del> assert.equal(receivedEvent.type, 'click', 'properties of jQuery event are available');
<del> });
<del> }
<del>
<del> ['@test accessing jQuery.Event#originalEvent does not trigger deprecations when jquery integration is explicitly enabled'](
<del> assert
<del> ) {
<del> let receivedEvent;
<del> window.EmberENV._JQUERY_INTEGRATION = true;
<del>
<del> this.registerComponent('x-foo', {
<del> ComponentClass: Component.extend({
<del> click(event) {
<del> receivedEvent = event;
<del> },
<del> }),
<del> template: `<button id="foo">bar</button>`,
<del> });
<del>
<del> this.render(`{{x-foo}}`);
<del>
<del> runTask(() => this.$('#foo').click());
<del> expectNoDeprecation(() => {
<del> let { originalEvent } = receivedEvent;
<del> assert.ok(originalEvent, 'jQuery event has originalEvent property');
<del> assert.equal(originalEvent.type, 'click', 'properties of originalEvent are available');
<del> });
<del> }
<del>
<del> [`@${
<del> DEBUG ? 'test' : 'skip'
<del> } accessing jQuery.Event#__originalEvent does not trigger deprecations to support ember-jquery-legacy`](
<del> assert
<del> ) {
<del> let receivedEvent;
<del>
<del> this.registerComponent('x-foo', {
<del> ComponentClass: Component.extend({
<del> click(event) {
<del> receivedEvent = event;
<del> },
<del> }),
<del> template: `<button id="foo">bar</button>`,
<del> });
<del>
<del> this.render(`{{x-foo}}`);
<del>
<del> runTask(() => this.$('#foo').click());
<del> expectNoDeprecation(() => {
<del> let { __originalEvent: originalEvent } = receivedEvent;
<del> assert.ok(originalEvent, 'jQuery event has __originalEvent property');
<del> assert.equal(originalEvent.type, 'click', 'properties of __originalEvent are available');
<del> });
<del> }
<del> }
<del> );
<del>}
<ide><path>packages/@ember/-internals/views/lib/system/event_dispatcher.js
<ide> import { assert } from '@ember/debug';
<ide> import { get, set } from '@ember/-internals/metal';
<ide> import { Object as EmberObject } from '@ember/-internals/runtime';
<ide> import { getElementView } from '@ember/-internals/views';
<del>import { jQuery, jQueryDisabled } from './jquery';
<ide> import ActionManager from './action_manager';
<del>import addJQueryEventDeprecation from './jquery_event_deprecation';
<ide> import { contains } from './utils';
<del>import { JQUERY_INTEGRATION, MOUSE_ENTER_LEAVE_MOVE_EVENTS } from '@ember/deprecated-features';
<add>import { MOUSE_ENTER_LEAVE_MOVE_EVENTS } from '@ember/deprecated-features';
<ide>
<ide> /**
<ide> @module ember
<ide> export default EmberObject.extend({
<ide>
<ide> let rootElementSelector = get(this, 'rootElement');
<ide> let rootElement;
<del> if (!JQUERY_INTEGRATION || jQueryDisabled) {
<del> if (typeof rootElementSelector !== 'string') {
<del> rootElement = rootElementSelector;
<del> } else {
<del> rootElement = document.querySelector(rootElementSelector);
<del> }
<del>
<del> assert(
<del> `You cannot use the same root element (${
<del> get(this, 'rootElement') || rootElement.tagName
<del> }) multiple times in an Ember.Application`,
<del> !rootElement.classList.contains(ROOT_ELEMENT_CLASS)
<del> );
<del> assert(
<del> 'You cannot make a new Ember.Application using a root element that is a descendent of an existing Ember.Application',
<del> (() => {
<del> let target = rootElement.parentNode;
<del> do {
<del> if (target.classList.contains(ROOT_ELEMENT_CLASS)) {
<del> return false;
<del> }
<del>
<del> target = target.parentNode;
<del> } while (target && target.nodeType === 1);
<del>
<del> return true;
<del> })()
<del> );
<del> assert(
<del> 'You cannot make a new Ember.Application using a root element that is an ancestor of an existing Ember.Application',
<del> !rootElement.querySelector(ROOT_ELEMENT_SELECTOR)
<del> );
<del>
<del> rootElement.classList.add(ROOT_ELEMENT_CLASS);
<del>
<del> assert(
<del> `Unable to add '${ROOT_ELEMENT_CLASS}' class to root element (${
<del> get(this, 'rootElement') || rootElement.tagName
<del> }). Make sure you set rootElement to the body or an element in the body.`,
<del> rootElement.classList.contains(ROOT_ELEMENT_CLASS)
<del> );
<add> if (typeof rootElementSelector !== 'string') {
<add> rootElement = rootElementSelector;
<ide> } else {
<del> rootElement = jQuery(rootElementSelector);
<del> assert(
<del> `You cannot use the same root element (${
<del> rootElement.selector || rootElement[0].tagName
<del> }) multiple times in an Ember.Application`,
<del> !rootElement.is(ROOT_ELEMENT_SELECTOR)
<del> );
<del> assert(
<del> 'You cannot make a new Ember.Application using a root element that is a descendent of an existing Ember.Application',
<del> !rootElement.closest(ROOT_ELEMENT_SELECTOR).length
<del> );
<del> assert(
<del> 'You cannot make a new Ember.Application using a root element that is an ancestor of an existing Ember.Application',
<del> !rootElement.find(ROOT_ELEMENT_SELECTOR).length
<del> );
<del>
<del> rootElement.addClass(ROOT_ELEMENT_CLASS);
<del>
<del> if (!rootElement.is(ROOT_ELEMENT_SELECTOR)) {
<del> throw new TypeError(
<del> `Unable to add '${ROOT_ELEMENT_CLASS}' class to root element (${
<del> rootElement.selector || rootElement[0].tagName
<del> }). Make sure you set rootElement to the body or an element in the body.`
<del> );
<del> }
<add> rootElement = document.querySelector(rootElementSelector);
<ide> }
<ide>
<add> assert(
<add> `You cannot use the same root element (${
<add> get(this, 'rootElement') || rootElement.tagName
<add> }) multiple times in an Ember.Application`,
<add> !rootElement.classList.contains(ROOT_ELEMENT_CLASS)
<add> );
<add> assert(
<add> 'You cannot make a new Ember.Application using a root element that is a descendent of an existing Ember.Application',
<add> (() => {
<add> let target = rootElement.parentNode;
<add> do {
<add> if (target.classList.contains(ROOT_ELEMENT_CLASS)) {
<add> return false;
<add> }
<add>
<add> target = target.parentNode;
<add> } while (target && target.nodeType === 1);
<add>
<add> return true;
<add> })()
<add> );
<add> assert(
<add> 'You cannot make a new Ember.Application using a root element that is an ancestor of an existing Ember.Application',
<add> !rootElement.querySelector(ROOT_ELEMENT_SELECTOR)
<add> );
<add>
<add> rootElement.classList.add(ROOT_ELEMENT_CLASS);
<add>
<add> assert(
<add> `Unable to add '${ROOT_ELEMENT_CLASS}' class to root element (${
<add> get(this, 'rootElement') || rootElement.tagName
<add> }). Make sure you set rootElement to the body or an element in the body.`,
<add> rootElement.classList.contains(ROOT_ELEMENT_CLASS)
<add> );
<add>
<ide> // save off the final sanitized root element (for usage in setupHandler)
<ide> this._sanitizedRootElement = rootElement;
<ide>
<ide> export default EmberObject.extend({
<ide> return; // nothing to do
<ide> }
<ide>
<del> if (!JQUERY_INTEGRATION || jQueryDisabled) {
<del> let viewHandler = (target, event) => {
<del> let view = getElementView(target);
<del> let result = true;
<add> let viewHandler = (target, event) => {
<add> let view = getElementView(target);
<add> let result = true;
<ide>
<del> if (view) {
<del> result = view.handleEvent(eventName, event);
<del> }
<add> if (view) {
<add> result = view.handleEvent(eventName, event);
<add> }
<ide>
<del> return result;
<del> };
<add> return result;
<add> };
<ide>
<del> let actionHandler = (target, event) => {
<del> let actionId = target.getAttribute('data-ember-action');
<del> let actions = ActionManager.registeredActions[actionId];
<add> let actionHandler = (target, event) => {
<add> let actionId = target.getAttribute('data-ember-action');
<add> let actions = ActionManager.registeredActions[actionId];
<ide>
<del> // In Glimmer2 this attribute is set to an empty string and an additional
<del> // attribute it set for each action on a given element. In this case, the
<del> // attributes need to be read so that a proper set of action handlers can
<del> // be coalesced.
<del> if (actionId === '') {
<del> let attributes = target.attributes;
<del> let attributeCount = attributes.length;
<add> // In Glimmer2 this attribute is set to an empty string and an additional
<add> // attribute it set for each action on a given element. In this case, the
<add> // attributes need to be read so that a proper set of action handlers can
<add> // be coalesced.
<add> if (actionId === '') {
<add> let attributes = target.attributes;
<add> let attributeCount = attributes.length;
<ide>
<del> actions = [];
<add> actions = [];
<ide>
<del> for (let i = 0; i < attributeCount; i++) {
<del> let attr = attributes.item(i);
<del> let attrName = attr.name;
<add> for (let i = 0; i < attributeCount; i++) {
<add> let attr = attributes.item(i);
<add> let attrName = attr.name;
<ide>
<del> if (attrName.indexOf('data-ember-action-') === 0) {
<del> actions = actions.concat(ActionManager.registeredActions[attr.value]);
<del> }
<add> if (attrName.indexOf('data-ember-action-') === 0) {
<add> actions = actions.concat(ActionManager.registeredActions[attr.value]);
<ide> }
<ide> }
<add> }
<ide>
<del> // We have to check for actions here since in some cases, jQuery will trigger
<del> // an event on `removeChild` (i.e. focusout) after we've already torn down the
<del> // action handlers for the view.
<del> if (!actions) {
<del> return;
<del> }
<add> // We have to check for actions here since in some cases, jQuery will trigger
<add> // an event on `removeChild` (i.e. focusout) after we've already torn down the
<add> // action handlers for the view.
<add> if (!actions) {
<add> return;
<add> }
<ide>
<del> let result = true;
<del> for (let index = 0; index < actions.length; index++) {
<del> let action = actions[index];
<add> let result = true;
<add> for (let index = 0; index < actions.length; index++) {
<add> let action = actions[index];
<ide>
<del> if (action && action.eventName === eventName) {
<del> // return false if any of the action handlers returns false
<del> result = action.handler(event) && result;
<del> }
<add> if (action && action.eventName === eventName) {
<add> // return false if any of the action handlers returns false
<add> result = action.handler(event) && result;
<ide> }
<del> return result;
<del> };
<del>
<del> // Special handling of events that don't bubble (event delegation does not work).
<del> // Mimics the way this is handled in jQuery,
<del> // see https://github.com/jquery/jquery/blob/899c56f6ada26821e8af12d9f35fa039100e838e/src/event.js#L666-L700
<del> if (MOUSE_ENTER_LEAVE_MOVE_EVENTS && EVENT_MAP[event] !== undefined) {
<del> let mappedEventType = EVENT_MAP[event];
<del> let origEventType = event;
<del>
<del> let createFakeEvent = (eventType, event) => {
<del> let fakeEvent = document.createEvent('MouseEvent');
<del> fakeEvent.initMouseEvent(
<del> eventType,
<del> false,
<del> false,
<del> event.view,
<del> event.detail,
<del> event.screenX,
<del> event.screenY,
<del> event.clientX,
<del> event.clientY,
<del> event.ctrlKey,
<del> event.altKey,
<del> event.shiftKey,
<del> event.metaKey,
<del> event.button,
<del> event.relatedTarget
<del> );
<del>
<del> // fake event.target as we don't dispatch the event
<del> Object.defineProperty(fakeEvent, 'target', { value: event.target, enumerable: true });
<del>
<del> return fakeEvent;
<del> };
<del>
<del> let handleMappedEvent = (this._eventHandlers[mappedEventType] = (event) => {
<del> let target = event.target;
<del> let related = event.relatedTarget;
<del>
<del> while (
<del> target &&
<del> target.nodeType === 1 &&
<del> (related === null || (related !== target && !contains(target, related)))
<del> ) {
<del> // mouseEnter/Leave don't bubble, so there is no logic to prevent it as with other events
<del> if (getElementView(target)) {
<del> viewHandler(target, createFakeEvent(origEventType, event));
<del> } else if (target.hasAttribute('data-ember-action')) {
<del> actionHandler(target, createFakeEvent(origEventType, event));
<del> }
<add> }
<add> return result;
<add> };
<add>
<add> // Special handling of events that don't bubble (event delegation does not work).
<add> // Mimics the way this is handled in jQuery,
<add> // see https://github.com/jquery/jquery/blob/899c56f6ada26821e8af12d9f35fa039100e838e/src/event.js#L666-L700
<add> if (MOUSE_ENTER_LEAVE_MOVE_EVENTS && EVENT_MAP[event] !== undefined) {
<add> let mappedEventType = EVENT_MAP[event];
<add> let origEventType = event;
<add>
<add> let createFakeEvent = (eventType, event) => {
<add> let fakeEvent = document.createEvent('MouseEvent');
<add> fakeEvent.initMouseEvent(
<add> eventType,
<add> false,
<add> false,
<add> event.view,
<add> event.detail,
<add> event.screenX,
<add> event.screenY,
<add> event.clientX,
<add> event.clientY,
<add> event.ctrlKey,
<add> event.altKey,
<add> event.shiftKey,
<add> event.metaKey,
<add> event.button,
<add> event.relatedTarget
<add> );
<ide>
<del> // separate mouseEnter/Leave events are dispatched for each listening element
<del> // until the element (related) has been reached that the pointing device exited from/to
<del> target = target.parentNode;
<del> }
<del> });
<del>
<del> rootElement.addEventListener(mappedEventType, handleMappedEvent);
<del> } else {
<del> let handleEvent = (this._eventHandlers[event] = (event) => {
<del> let target = event.target;
<del>
<del> do {
<del> if (getElementView(target)) {
<del> if (viewHandler(target, event) === false) {
<del> event.preventDefault();
<del> event.stopPropagation();
<del> break;
<del> } else if (event.cancelBubble === true) {
<del> break;
<del> }
<del> } else if (
<del> typeof target.hasAttribute === 'function' &&
<del> target.hasAttribute('data-ember-action')
<del> ) {
<del> if (actionHandler(target, event) === false) {
<del> break;
<del> }
<del> }
<add> // fake event.target as we don't dispatch the event
<add> Object.defineProperty(fakeEvent, 'target', { value: event.target, enumerable: true });
<ide>
<del> target = target.parentNode;
<del> } while (target && target.nodeType === 1);
<del> });
<add> return fakeEvent;
<add> };
<ide>
<del> rootElement.addEventListener(event, handleEvent);
<del> }
<del> } else {
<del> rootElement.on(`${event}.ember`, '.ember-view', function (evt) {
<del> let view = getElementView(this);
<del> let result = true;
<add> let handleMappedEvent = (this._eventHandlers[mappedEventType] = (event) => {
<add> let target = event.target;
<add> let related = event.relatedTarget;
<add>
<add> while (
<add> target &&
<add> target.nodeType === 1 &&
<add> (related === null || (related !== target && !contains(target, related)))
<add> ) {
<add> // mouseEnter/Leave don't bubble, so there is no logic to prevent it as with other events
<add> if (getElementView(target)) {
<add> viewHandler(target, createFakeEvent(origEventType, event));
<add> } else if (target.hasAttribute('data-ember-action')) {
<add> actionHandler(target, createFakeEvent(origEventType, event));
<add> }
<ide>
<del> if (view) {
<del> result = view.handleEvent(eventName, addJQueryEventDeprecation(evt));
<add> // separate mouseEnter/Leave events are dispatched for each listening element
<add> // until the element (related) has been reached that the pointing device exited from/to
<add> target = target.parentNode;
<ide> }
<del>
<del> return result;
<ide> });
<ide>
<del> rootElement.on(`${event}.ember`, '[data-ember-action]', (evt) => {
<del> let attributes = evt.currentTarget.attributes;
<del> let handledActions = [];
<del>
<del> evt = addJQueryEventDeprecation(evt);
<del>
<del> for (let i = 0; i < attributes.length; i++) {
<del> let attr = attributes.item(i);
<del> let attrName = attr.name;
<del>
<del> if (attrName.lastIndexOf('data-ember-action-', 0) !== -1) {
<del> let action = ActionManager.registeredActions[attr.value];
<del>
<del> // We have to check for action here since in some cases, jQuery will trigger
<del> // an event on `removeChild` (i.e. focusout) after we've already torn down the
<del> // action handlers for the view.
<del> if (action && action.eventName === eventName && handledActions.indexOf(action) === -1) {
<del> action.handler(evt);
<del> // Action handlers can mutate state which in turn creates new attributes on the element.
<del> // This effect could cause the `data-ember-action` attribute to shift down and be invoked twice.
<del> // To avoid this, we keep track of which actions have been handled.
<del> handledActions.push(action);
<add> rootElement.addEventListener(mappedEventType, handleMappedEvent);
<add> } else {
<add> let handleEvent = (this._eventHandlers[event] = (event) => {
<add> let target = event.target;
<add>
<add> do {
<add> if (getElementView(target)) {
<add> if (viewHandler(target, event) === false) {
<add> event.preventDefault();
<add> event.stopPropagation();
<add> break;
<add> } else if (event.cancelBubble === true) {
<add> break;
<add> }
<add> } else if (
<add> typeof target.hasAttribute === 'function' &&
<add> target.hasAttribute('data-ember-action')
<add> ) {
<add> if (actionHandler(target, event) === false) {
<add> break;
<ide> }
<ide> }
<del> }
<add>
<add> target = target.parentNode;
<add> } while (target && target.nodeType === 1);
<ide> });
<del> }
<ide>
<add> rootElement.addEventListener(event, handleEvent);
<add> }
<ide> this.lazyEvents.delete(event);
<ide> },
<ide>
<ide> export default EmberObject.extend({
<ide> return;
<ide> }
<ide>
<del> if (!JQUERY_INTEGRATION || jQueryDisabled) {
<del> for (let event in this._eventHandlers) {
<del> rootElement.removeEventListener(event, this._eventHandlers[event]);
<del> }
<del> } else {
<del> jQuery(rootElementSelector).off('.ember', '**');
<add> for (let event in this._eventHandlers) {
<add> rootElement.removeEventListener(event, this._eventHandlers[event]);
<ide> }
<ide>
<ide> rootElement.classList.remove(ROOT_ELEMENT_CLASS);
<ide><path>packages/@ember/-internals/views/lib/system/jquery_event_deprecation.js
<del>/* global Proxy */
<del>import { deprecate } from '@ember/debug';
<del>import { global } from '@ember/-internals/environment';
<del>import { DEBUG } from '@glimmer/env';
<del>import { JQUERY_INTEGRATION } from '@ember/deprecated-features';
<del>
<del>export default function addJQueryEventDeprecation(jqEvent) {
<del> if (DEBUG && JQUERY_INTEGRATION) {
<del> let boundFunctions = new Map();
<del>
<del> // wrap the jQuery event in a Proxy to add the deprecation message for originalEvent, according to RFC#294
<del> // we need a native Proxy here, so we can make sure that the internal use of originalEvent in jQuery itself does
<del> // not trigger a deprecation
<del> return new Proxy(jqEvent, {
<del> get(target, name) {
<del> switch (name) {
<del> case 'originalEvent':
<del> deprecate(
<del> 'Accessing jQuery.Event specific properties is deprecated. Either use the ember-jquery-legacy addon to normalize events to native events, or explicitly opt into jQuery integration using @ember/optional-features.',
<del> ((EmberENV) => {
<del> // this deprecation is intentionally checking `global.EmberENV` so
<del> // that we can ensure we _only_ deprecate in the case where jQuery
<del> // integration is enabled implicitly (e.g. "defaulted" to enabled)
<del> // as opposed to when the user explicitly opts in to using jQuery
<del> if (typeof EmberENV !== 'object' || EmberENV === null) return false;
<del>
<del> return EmberENV._JQUERY_INTEGRATION === true;
<del> })(global.EmberENV),
<del> {
<del> id: 'ember-views.event-dispatcher.jquery-event',
<del> until: '4.0.0',
<del> url: 'https://deprecations.emberjs.com/v3.x#toc_jquery-event',
<del> for: 'ember-source',
<del> since: {
<del> enabled: '3.9.0',
<del> },
<del> }
<del> );
<del> return target[name];
<del>
<del> // provide an escape hatch for ember-jquery-legacy to access originalEvent without a deprecation
<del> case '__originalEvent':
<del> return target.originalEvent;
<del>
<del> default:
<del> if (typeof target[name] === 'function') {
<del> // cache functions for reuse
<del> if (!boundFunctions.has(name)) {
<del> // for jQuery.Event methods call them with `target` as the `this` context, so they will access
<del> // `originalEvent` from the original jQuery event, not our proxy, thus not trigger the deprecation
<del> boundFunctions.set(name, target[name].bind(target));
<del> }
<del>
<del> return boundFunctions.get(name);
<del> }
<del> // same for jQuery's getter functions for simple properties
<del> return target[name];
<del> }
<del> },
<del> });
<del> }
<del>
<del> return jqEvent;
<del>} | 3 |
Java | Java | remove a pointless concatmapiterable overload | 479a7a28f982ccdf236c3afb494556decef9ab72 | <ide><path>src/main/java/io/reactivex/rxjava3/core/Observable.java
<ide> public final <U> Observable<U> concatMapIterable(@NonNull Function<? super T, ?
<ide> return RxJavaPlugins.onAssembly(new ObservableFlattenIterable<>(this, mapper));
<ide> }
<ide>
<del> /**
<del> * Returns an {@code Observable} that concatenate each item emitted by the current {@code Observable} with the values in an
<del> * {@link Iterable} corresponding to that item that is generated by a selector.
<del> * <p>
<del> * <img width="640" height="275" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatMapIterable.o.png" alt="">
<del> *
<del> * <dl>
<del> * <dt><b>Scheduler:</b></dt>
<del> * <dd>{@code concatMapIterable} does not operate by default on a particular {@link Scheduler}.</dd>
<del> * </dl>
<del> *
<del> * @param <U>
<del> * the type of item emitted by the resulting {@code Observable}
<del> * @param mapper
<del> * a function that returns an {@code Iterable} sequence of values for when given an item emitted by the
<del> * current {@code Observable}
<del> * @param bufferSize
<del> * the number of elements expected from the current {@code Observable} to be buffered
<del> * @return an {@code Observable} that emits the results of concatenating the items emitted by the current {@code Observable} with
<del> * the values in the {@code Iterable}s corresponding to those items
<del> * @throws NullPointerException if {@code mapper} is {@code null}
<del> * @throws IllegalArgumentException if {@code bufferSize} is non-positive
<del> * @see <a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX operators documentation: FlatMap</a>
<del> */
<del> @CheckReturnValue
<del> @SchedulerSupport(SchedulerSupport.NONE)
<del> @NonNull
<del> public final <U> Observable<U> concatMapIterable(@NonNull Function<? super T, ? extends Iterable<? extends U>> mapper, int bufferSize) {
<del> Objects.requireNonNull(mapper, "mapper is null");
<del> ObjectHelper.verifyPositive(bufferSize, "bufferSize");
<del> return concatMap(ObservableInternalHelper.flatMapIntoIterable(mapper), bufferSize);
<del> }
<del>
<ide> /**
<ide> * Maps the upstream items into {@link MaybeSource}s and subscribes to them one after the
<ide> * other succeeds or completes, emits their success value if available or terminates immediately if
<ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableConcatTest.java
<ide> public void concatMapIterableBufferSize() {
<ide> public Iterable<Integer> apply(Integer v) throws Exception {
<ide> return Arrays.asList(1, 2, 3, 4, 5);
<ide> }
<del> }, 1)
<add> })
<ide> .test()
<ide> .assertResult(1, 2, 3, 4, 5, 1, 2, 3, 4, 5);
<ide> } | 2 |
Javascript | Javascript | make sizesdiffer and matricesdiffer type-safe | d29a6a116e1e6639526dd16e254ae957a4fd8425 | <ide><path>Libraries/Utilities/differ/matricesDiffer.js
<ide> * LICENSE file in the root directory of this source tree.
<ide> *
<ide> * @format
<add> * @flow strict
<ide> */
<ide>
<ide> 'use strict';
<ide> * @param {MatrixMath.Matrix} two Second matrix.
<ide> * @return {boolean} Whether or not the two matrices differ.
<ide> */
<del>const matricesDiffer = function (one, two) {
<add>const matricesDiffer = function (
<add> one: ?Array<number>,
<add> two: ?Array<number>,
<add>): boolean {
<ide> if (one === two) {
<ide> return false;
<ide> }
<ide><path>Libraries/Utilities/differ/sizesDiffer.js
<ide> * This source code is licensed under the MIT license found in the
<ide> * LICENSE file in the root directory of this source tree.
<ide> *
<add> * @flow strict
<ide> * @format
<ide> */
<ide>
<ide> 'use strict';
<ide>
<ide> const dummySize = {width: undefined, height: undefined};
<add>type Size = {width: ?number, height: ?number};
<ide>
<del>const sizesDiffer = function (one, two) {
<del> one = one || dummySize;
<del> two = two || dummySize;
<del> return one !== two && (one.width !== two.width || one.height !== two.height);
<add>const sizesDiffer = function (one: Size, two: Size): boolean {
<add> const defaultedOne = one || dummySize;
<add> const defaultedTwo = two || dummySize;
<add> return (
<add> defaultedOne !== defaultedTwo &&
<add> (defaultedOne.width !== defaultedTwo.width ||
<add> defaultedOne.height !== defaultedTwo.height)
<add> );
<ide> };
<ide>
<ide> module.exports = sizesDiffer; | 2 |
Ruby | Ruby | add missing require | c6dc50fcf05c8c4956ac86345360fefcb00f664e | <ide><path>Library/Homebrew/compat/macos.rb
<add>require "development_tools"
<add>
<ide> module OS
<ide> module Mac
<ide> def xcode_folder | 1 |
Python | Python | add functionality for network support | d4508d37973f34054947e1c1117ab84b9f6b9559 | <ide><path>libcloud/container/drivers/lxd.py
<ide> def __init__(self, name, driver, used_by, config, managed):
<ide> self.managed = managed
<ide>
<ide>
<add>class LXDNetwork(object):
<add> """
<add> Utility class representing an LXD network
<add> """
<add>
<add> @classmethod
<add> def build_from_response(cls, metadata):
<add> lxd_network = LXDNetwork()
<add> lxd_network.name = metadata.get("name", None)
<add> lxd_network.id = metadata.get("name", None)
<add> lxd_network.description = metadata.get("description", None)
<add> lxd_network.type = metadata.get("type", None)
<add> lxd_network.config = metadata.get("config", None)
<add> lxd_network.status = metadata.get("status", None)
<add> lxd_network.locations = metadata.get("locations", None)
<add> lxd_network.managed = metadata.get("managed", None)
<add> lxd_network.used_by = metadata.get("used_by", None)
<add> return lxd_network
<add>
<add> def __init__(self):
<add> self.name = None
<add> self.id = None
<add> self.description = None
<add> self.type = None
<add> self.config = None
<add> self.status = None
<add> self.locations = None
<add> self.managed = None
<add> self.used_by = None
<add> self.extra = {}
<add>
<add>
<ide> class LXDServerInfo(object):
<ide> """
<ide> Wraps the response form /1.0
<ide> def ex_delete_storage_pool_volume(self, pool_id, type, name):
<ide> assert_response(response_dict=response_dict, status_code=200)
<ide> return True
<ide>
<add> def ex_get_networks(self):
<add> """
<add> Returns a list of networks.
<add> Implements GET /1.0/networks
<add> Authentication: trusted
<add> Operation: sync
<add>
<add> :rtype: list of LXDNetwork objects
<add> """
<add>
<add> req = "/%s/networks" % (self.version)
<add> response = self.connection.request(req)
<add>
<add> response_dict = response.parse_body()
<add> assert_response(response_dict=response_dict, status_code=200)
<add>
<add> nets = response_dict["metadata"]
<add> networks = []
<add> for net in nets:
<add> name = net.split('/')[-1]
<add> networks.append(self.ex_get_network(name=name))
<add> return networks
<add>
<add> def ex_get_network(self, name):
<add> """
<add> Retunrs the LXD network with the given name.
<add> Implements GET /1.0/networks/<name>
<add>
<add> Authentication: trusted
<add> Operation: sync
<add>
<add> :param name: The name of the network to return
<add> :type name: str
<add>
<add> :rtype: LXDNetwork
<add> """
<add> req = '/%s/networks/%s' % (self.version, name)
<add> response = self.connection.request(req)
<add> response_dict = response.parse_body()
<add> assert_response(response_dict=response_dict, status_code=200)
<add>
<add> return LXDNetwork.build_from_response(response_dict["metadata"])
<add>
<add> def ex_create_network(self, **kwargs):
<add> pass
<add>
<add> def ex_delete_network(self, name):
<add> """
<add> Delete the network with the given name
<add> Authentication: trusted
<add> Operation: sync
<add>
<add> :param name: The network name to delete
<add> :type name: str
<add>
<add> :return: True is successfully deleted the network
<add> """
<add>
<add> req = '/%s/networks/%s' % (self.version, name)
<add> response = self.connection.request(req, method='DELETE')
<add> response_dict = response.parse_body()
<add> assert_response(response_dict=response_dict, status_code=200)
<add>
<add> return True
<add>
<add>
<ide> def _to_container(self, metadata):
<ide> """
<ide> Returns Container instance built from the given metadata | 1 |
Python | Python | use tag in conll converter, not pos | 3bf4a28d8de979b12865cb2746780b4c48bd15aa | <ide><path>spacy/cli/converters/conllu2json.py
<ide> def read_conllx(input_path, use_morphology=False, n=0):
<ide> id_ = int(id_) - 1
<ide> head = (int(head) - 1) if head != '0' else id_
<ide> dep = 'ROOT' if dep == 'root' else dep
<del> tag = pos+'__'+morph if use_morphology else pos
<add> tag = tag+'__'+morph if use_morphology else tag
<ide> tokens.append((id_, word, tag, head, dep, 'O'))
<ide> except:
<ide> print(line) | 1 |
Python | Python | use r = ts.run(); r.join() instead | 2b1769c54d22ab5c055d5a0059c0ef0b6f704b23 | <ide><path>celery/task/base.py
<ide> def run(self, connect_timeout=conf.AMQP_CONNECTION_TIMEOUT):
<ide> conn.close()
<ide> return TaskSetResult(taskset_id, subtasks)
<ide>
<del> def join(self, timeout=None):
<del> """Gather the results for all of the tasks in the taskset,
<del> and return a list with them ordered by the order of which they
<del> were called.
<del>
<del> :keyword timeout: The time in seconds, how long
<del> it will wait for results, before the operation times out.
<del>
<del> :raises TimeoutError: if ``timeout`` is not ``None``
<del> and the operation takes longer than ``timeout`` seconds.
<del>
<del> If any of the tasks raises an exception, the exception
<del> will be reraised by :meth:`join`.
<del>
<del> :returns: list of return values for all tasks in the taskset.
<del>
<del> """
<del> return self.run().join(timeout=timeout)
<del>
<ide> @classmethod
<ide> def remote_execute(cls, func, args):
<ide> """Apply ``args`` to function by distributing the args to the | 1 |
Text | Text | add the description of how it was introduced | bebf3af07256347718e514b1683dd1a678ec6ffe | <ide><path>guide/spanish/canvas/index.md
<ide> localeTitle: Lona
<ide> ## Lienzo HTML5
<ide>
<ide> Canvas es una tecnología introducida en HTML5 a la que se puede acceder mediante la etiqueta `<canvas>` . Permite dibujar gráficos a través de Javascript y es una herramienta poderosa para la interactividad en la web.
<del>
<add>El elemento fue introducido por Apple para el tablero de OS X y Safari
<ide> #### Más información:
<ide>
<del>* [API MDN Canvas](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API)
<ide>\ No newline at end of file
<add>* [API MDN Canvas](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API) | 1 |
PHP | PHP | add teststepmaybeset, fix mock values | d4157a41b4768d7f6600b9999bff577fb293d72b | <ide><path>tests/Database/DatabaseMigrationMigrateCommandTest.php
<ide> public function testBasicMigrationsCallMigratorWithProperArguments()
<ide> $app->useDatabasePath(__DIR__);
<ide> $command->setLaravel($app);
<ide> $migrator->shouldReceive('setConnection')->once()->with(null);
<del> $migrator->shouldReceive('run')->once()->with(__DIR__.'/migrations', false, null);
<add> $migrator->shouldReceive('run')->once()->with(__DIR__.'/migrations', false, false);
<ide> $migrator->shouldReceive('getNotes')->andReturn([]);
<ide> $migrator->shouldReceive('repositoryExists')->once()->andReturn(true);
<ide>
<ide> public function testMigrationRepositoryCreatedWhenNecessary()
<ide> $app->useDatabasePath(__DIR__);
<ide> $command->setLaravel($app);
<ide> $migrator->shouldReceive('setConnection')->once()->with(null);
<del> $migrator->shouldReceive('run')->once()->with(__DIR__.'/migrations', false, null);
<add> $migrator->shouldReceive('run')->once()->with(__DIR__.'/migrations', false, false);
<ide> $migrator->shouldReceive('getNotes')->andReturn([]);
<ide> $migrator->shouldReceive('repositoryExists')->once()->andReturn(false);
<ide> $command->expects($this->once())->method('call')->with($this->equalTo('migrate:install'), $this->equalTo(['--database' => null]));
<ide> public function testTheCommandMayBePretended()
<ide> $app->useDatabasePath(__DIR__);
<ide> $command->setLaravel($app);
<ide> $migrator->shouldReceive('setConnection')->once()->with(null);
<del> $migrator->shouldReceive('run')->once()->with(__DIR__.'/migrations', true, null);
<add> $migrator->shouldReceive('run')->once()->with(__DIR__.'/migrations', true, false);
<ide> $migrator->shouldReceive('getNotes')->andReturn([]);
<ide> $migrator->shouldReceive('repositoryExists')->once()->andReturn(true);
<ide>
<ide> public function testTheDatabaseMayBeSet()
<ide> $app->useDatabasePath(__DIR__);
<ide> $command->setLaravel($app);
<ide> $migrator->shouldReceive('setConnection')->once()->with('foo');
<del> $migrator->shouldReceive('run')->once()->with(__DIR__.'/migrations', false, null);
<add> $migrator->shouldReceive('run')->once()->with(__DIR__.'/migrations', false, false);
<ide> $migrator->shouldReceive('getNotes')->andReturn([]);
<ide> $migrator->shouldReceive('repositoryExists')->once()->andReturn(true);
<ide>
<ide> $this->runCommand($command, ['--database' => 'foo']);
<ide> }
<ide>
<add> public function testStepMayBeSet()
<add> {
<add> $command = new MigrateCommand($migrator = m::mock('Illuminate\Database\Migrations\Migrator'), __DIR__.'/vendor');
<add> $app = new ApplicationDatabaseMigrationStub(['path.database' => __DIR__]);
<add> $app->useDatabasePath(__DIR__);
<add> $command->setLaravel($app);
<add> $migrator->shouldReceive('setConnection')->once()->with(null);
<add> $migrator->shouldReceive('run')->once()->with(__DIR__.'/migrations', false, true);
<add> $migrator->shouldReceive('getNotes')->andReturn([]);
<add> $migrator->shouldReceive('repositoryExists')->once()->andReturn(true);
<add>
<add> $this->runCommand($command, ['--step' => true]);
<add> }
<add>
<ide> protected function runCommand($command, $input = [])
<ide> {
<ide> return $command->run(new Symfony\Component\Console\Input\ArrayInput($input), new Symfony\Component\Console\Output\NullOutput); | 1 |
PHP | PHP | remove unnecessary commentted line | fbbbeb3b6c5cd966f0af0ca614ac9314aff78aa1 | <ide><path>src/Illuminate/Foundation/Exceptions/Handler.php
<ide> protected function context()
<ide> try {
<ide> return array_filter([
<ide> 'userId' => Auth::id(),
<del> // 'email' => optional(Auth::user())->email,
<ide> ]);
<ide> } catch (Throwable $e) {
<ide> return []; | 1 |
PHP | PHP | add no suffix tests | ac393c4c737a6869622842f38411e4177d71837b | <ide><path>Cake/Test/TestCase/Core/AppTest.php
<ide> public function classnameProvider() {
<ide> ['Also/Exists', 'In', 'App', true, 'TestApp\In\Also\ExistsApp'],
<ide> ['Also', 'Exists/In', 'App', true, 'TestApp\Exists\In\AlsoApp'],
<ide> ['Also', 'Exists/In/Subfolder', 'App', true, 'TestApp\Exists\In\Subfolder\AlsoApp'],
<add> ['No', 'Suffix', '', true, 'TestApp\Suffix\No'],
<ide>
<ide> ['MyPlugin.Exists', 'In', 'Suffix', true, 'MyPlugin\In\ExistsSuffix'],
<ide> ['MyPlugin.Also/Exists', 'In', 'Suffix', true, 'MyPlugin\In\Also\ExistsSuffix'],
<ide> ['MyPlugin.Also', 'Exists/In', 'Suffix', true, 'MyPlugin\Exists\In\AlsoSuffix'],
<ide> ['MyPlugin.Also', 'Exists/In/Subfolder', 'Suffix', true, 'MyPlugin\Exists\In\Subfolder\AlsoSuffix'],
<add> ['MyPlugin.No', 'Suffix', '', true, 'MyPlugin\Suffix\No'],
<ide>
<ide> ['Exists', 'In', 'Cake', false, 'Cake\In\ExistsCake'],
<ide> ['Also/Exists', 'In', 'Cake', false, 'Cake\In\Also\ExistsCake'],
<ide> ['Also', 'Exists/In', 'Cake', false, 'Cake\Exists\In\AlsoCake'],
<ide> ['Also', 'Exists/In/Subfolder', 'Cake', false, 'Cake\Exists\In\Subfolder\AlsoCake'],
<add> ['No', 'Suffix', '', false, 'Cake\Suffix\No'],
<ide>
<ide> // Realistic examples returning nothing
<ide> ['App', 'Core', 'Suffix'], | 1 |
Text | Text | update changelog and remove the duplicate log | 2cb6043feb4632bd7f45ef9a1470d37f1c4523d9 | <ide><path>CHANGELOG.md
<ide> * [FEATURE ember-routing-consistent-resources]
<ide> * `uuid` is now consistently used across the project.
<ide> * `Ember.uuid` is now an internal function instead of a property on `Ember` itself.
<del>* [BUGFIX] sync back burner: workaround IE's issue with try/finally without Catch.
<del> Also no longer force deoptimization of the run loop queue flush.
<del>* [BREAKING BUGFIX] An empty array are treated as falsy value in `bind-attr` to be in consistent
<del> with `if` helper. Breaking for apps that relies on the previous behaviour which treats an empty
<del> array as truthy value in `bind-attr`.
<ide> * [BREAKING BUGFIX] On Controllers, the content property is now derived from model. This reduces many
<ide> caveats with model/content, and also sets a simple ground rule: Never set a controllers content,
<ide> rather always set it's model and ember will do the right thing.
<ide>
<ide> ### Ember 1.6.0 (July, 7, 2014)
<ide>
<add>* [BREAKING BUGFIX] An empty array is treated as falsy value in `bind-attr` to be in consistent
<add> with `if` helper. Breaking for apps that relies on the previous behaviour which treats an empty
<add> array as truthy value in `bind-attr`.
<ide> * [BUGFIX] Ensure itemController's do not leak by tying them to the parent controller lifecycle.
<ide> * [BUGFIX] Spaces in brace expansion throws an error.
<ide> * [BUGFIX] Fix `MutableEnumerable.removeObjects`. | 1 |
Text | Text | allow opening examples in gitpod | 3f2ef030e001547eb06060499f8a2e3f002b5a14 | <ide><path>examples/README.md
<ide> To run the examples:
<ide> 4. `grunt build`
<ide> 5. `npm run examples`
<ide> 6. [http://localhost:3000](http://localhost:3000)
<add>
<add>Or use Gitpod, a free dev environment for GitHub:
<add>
<add>[](https://gitpod.io/#https://github.com/axios/axios/blob/master/examples/server.js) | 1 |
Java | Java | use full package names in reactiveadapterregistry | 729551f375a2fb9675c337873ae6cf4341735139 | <ide><path>spring-core/src/main/java/org/springframework/core/ReactiveAdapterRegistry.java
<ide> import java.util.function.Function;
<ide>
<ide> import io.reactivex.BackpressureStrategy;
<del>import io.reactivex.Completable;
<del>import io.reactivex.Flowable;
<del>import io.reactivex.Maybe;
<del>import io.reactivex.Observable;
<ide> import org.reactivestreams.Publisher;
<ide> import reactor.core.publisher.Flux;
<ide> import reactor.core.publisher.Mono;
<ide> import rx.RxReactiveStreams;
<ide>
<ide> import org.springframework.util.ClassUtils;
<ide>
<add>import static org.springframework.core.ReactiveTypeDescriptor.multiValue;
<add>import static org.springframework.core.ReactiveTypeDescriptor.noValue;
<add>import static org.springframework.core.ReactiveTypeDescriptor.singleOptionalValue;
<add>import static org.springframework.core.ReactiveTypeDescriptor.singleRequiredValue;
<add>
<ide> /**
<ide> * A registry of adapters to adapt a Reactive Streams {@link Publisher} to/from
<ide> * various async/reactive types such as {@code CompletableFuture}, RxJava
<ide> void registerAdapters(ReactiveAdapterRegistry registry) {
<ide> // Flux and Mono ahead of Publisher...
<ide>
<ide> registry.registerReactiveType(
<del> ReactiveTypeDescriptor.singleOptionalValue(Mono.class, Mono::empty),
<add> singleOptionalValue(Mono.class, Mono::empty),
<ide> source -> (Mono<?>) source,
<ide> Mono::from
<ide> );
<ide>
<del> registry.registerReactiveType(ReactiveTypeDescriptor.multiValue(Flux.class, Flux::empty),
<add> registry.registerReactiveType(multiValue(Flux.class, Flux::empty),
<ide> source -> (Flux<?>) source,
<ide> Flux::from);
<ide>
<del> registry.registerReactiveType(ReactiveTypeDescriptor.multiValue(Publisher.class, Flux::empty),
<add> registry.registerReactiveType(multiValue(Publisher.class, Flux::empty),
<ide> source -> (Publisher<?>) source,
<ide> source -> source);
<ide>
<ide> registry.registerReactiveType(
<del> ReactiveTypeDescriptor.singleOptionalValue(CompletableFuture.class, () -> {
<add> singleOptionalValue(CompletableFuture.class, () -> {
<ide> CompletableFuture<?> empty = new CompletableFuture<>();
<ide> empty.complete(null);
<ide> return empty;
<ide> private static class RxJava1Registrar {
<ide>
<ide> void registerAdapters(ReactiveAdapterRegistry registry) {
<ide> registry.registerReactiveType(
<del> ReactiveTypeDescriptor.multiValue(rx.Observable.class, rx.Observable::empty),
<add> multiValue(rx.Observable.class, rx.Observable::empty),
<ide> source -> RxReactiveStreams.toPublisher((rx.Observable<?>) source),
<ide> RxReactiveStreams::toObservable
<ide> );
<ide> registry.registerReactiveType(
<del> ReactiveTypeDescriptor.singleRequiredValue(rx.Single.class),
<add> singleRequiredValue(rx.Single.class),
<ide> source -> RxReactiveStreams.toPublisher((rx.Single<?>) source),
<ide> RxReactiveStreams::toSingle
<ide> );
<ide> registry.registerReactiveType(
<del> ReactiveTypeDescriptor.noValue(rx.Completable.class, Completable::complete),
<add> noValue(rx.Completable.class, rx.Completable::complete),
<ide> source -> RxReactiveStreams.toPublisher((rx.Completable) source),
<ide> RxReactiveStreams::toCompletable
<ide> );
<ide> private static class RxJava2Registrar {
<ide>
<ide> void registerAdapters(ReactiveAdapterRegistry registry) {
<ide> registry.registerReactiveType(
<del> ReactiveTypeDescriptor.multiValue(Flowable.class, Flowable::empty),
<del> source -> (Flowable<?>) source,
<del> source-> Flowable.fromPublisher(source)
<add> multiValue(io.reactivex.Flowable.class, io.reactivex.Flowable::empty),
<add> source -> (io.reactivex.Flowable<?>) source,
<add> source-> io.reactivex.Flowable.fromPublisher(source)
<ide> );
<ide> registry.registerReactiveType(
<del> ReactiveTypeDescriptor.multiValue(Observable.class, Observable::empty),
<del> source -> ((Observable<?>) source).toFlowable(BackpressureStrategy.BUFFER),
<del> source -> Flowable.fromPublisher(source).toObservable()
<add> multiValue(io.reactivex.Observable.class, io.reactivex.Observable::empty),
<add> source -> ((io.reactivex.Observable<?>) source).toFlowable(BackpressureStrategy.BUFFER),
<add> source -> io.reactivex.Flowable.fromPublisher(source).toObservable()
<ide> );
<ide> registry.registerReactiveType(
<del> ReactiveTypeDescriptor.singleRequiredValue(io.reactivex.Single.class),
<add> singleRequiredValue(io.reactivex.Single.class),
<ide> source -> ((io.reactivex.Single<?>) source).toFlowable(),
<del> source -> Flowable.fromPublisher(source).toObservable().singleElement().toSingle()
<add> source -> io.reactivex.Flowable.fromPublisher(source).toObservable().singleElement().toSingle()
<ide> );
<ide> registry.registerReactiveType(
<del> ReactiveTypeDescriptor.singleOptionalValue(Maybe.class, Maybe::empty),
<del> source -> ((Maybe<?>) source).toFlowable(),
<del> source -> Flowable.fromPublisher(source).toObservable().singleElement()
<add> singleOptionalValue(io.reactivex.Maybe.class, io.reactivex.Maybe::empty),
<add> source -> ((io.reactivex.Maybe<?>) source).toFlowable(),
<add> source -> io.reactivex.Flowable.fromPublisher(source).toObservable().singleElement()
<ide> );
<ide> registry.registerReactiveType(
<del> ReactiveTypeDescriptor.noValue(Completable.class, Completable::complete),
<del> source -> ((Completable) source).toFlowable(),
<del> source -> Flowable.fromPublisher(source).toObservable().ignoreElements()
<add> noValue(io.reactivex.Completable.class, io.reactivex.Completable::complete),
<add> source -> ((io.reactivex.Completable) source).toFlowable(),
<add> source -> io.reactivex.Flowable.fromPublisher(source).toObservable().ignoreElements()
<ide> );
<ide> }
<ide> } | 1 |
PHP | PHP | add more test to _basename | 43df0176da72c2127f862b716454b7f18aaadb2b | <ide><path>tests/TestCase/Filesystem/FileTest.php
<ide> public function baseNameValueProvider()
<ide> ['/نام فارسی.txt', '.txt'],
<ide> //
<ide> ['/etc/sudoers.d', null],
<add> ['/etc/.d', '.d'],
<ide> ['/etc/sudoers.d', '.d'],
<ide> ['/etc/passwd', null],
<ide> ['/etc/', null], | 1 |
Javascript | Javascript | reduce list of globals in eslint config | 5c9ea80fa77f39618d0e24a07a04cf99faa0ebd9 | <ide><path>.eslintrc.js
<ide> module.exports = {
<ide> 'node-core/no-duplicate-requires': 'error',
<ide> },
<ide> globals: {
<del> AbortController: 'readable',
<del> AbortSignal: 'readable',
<ide> Atomics: 'readable',
<ide> BigInt: 'readable',
<del> BigInt64Array: 'readable',
<del> BigUint64Array: 'readable',
<del> Blob: 'readable',
<del> DOMException: 'readable',
<del> Event: 'readable',
<del> EventTarget: 'readable',
<del> MessageChannel: 'readable',
<del> BroadcastChannel: 'readable',
<del> MessageEvent: 'readable',
<del> MessagePort: 'readable',
<del> TextEncoder: 'readable',
<del> TextDecoder: 'readable',
<del> queueMicrotask: 'readable',
<del> globalThis: 'readable',
<del> btoa: 'readable',
<del> atob: 'readable',
<del> performance: 'readable',
<del> structuredClone: 'readable',
<del> fetch: 'readable',
<del> Headers: 'readable',
<del> Request: 'readable',
<del> Response: 'readable',
<del> crypto: 'readable',
<ide> Crypto: 'readable',
<ide> CryptoKey: 'readable',
<add> fetch: 'readable',
<add> globalThis: 'readable',
<add> Response: 'readable',
<ide> SubtleCrypto: 'readable',
<ide> },
<ide> }; | 1 |
Mixed | Go | add docker server version to /info | 7cf343d1064e3d8211597c67574ff4ddff316fa1 | <ide><path>api/client/info.go
<ide> func (cli *DockerCli) CmdInfo(args ...string) error {
<ide>
<ide> fmt.Fprintf(cli.out, "Containers: %d\n", info.Containers)
<ide> fmt.Fprintf(cli.out, "Images: %d\n", info.Images)
<add> fmt.Fprintf(cli.out, "Engine Version: %s\n", info.ServerVersion)
<ide> ioutils.FprintfIfNotEmpty(cli.out, "Storage Driver: %s\n", info.Driver)
<ide> if info.DriverStatus != nil {
<ide> for _, pair := range info.DriverStatus {
<ide><path>api/types/types.go
<ide> type Info struct {
<ide> Name string
<ide> Labels []string
<ide> ExperimentalBuild bool
<add> ServerVersion string
<ide> }
<ide>
<ide> // ExecStartCheck is a temp struct used by execStart
<ide><path>daemon/info.go
<ide> func (daemon *Daemon) SystemInfo() (*types.Info, error) {
<ide> DockerRootDir: daemon.config().Root,
<ide> Labels: daemon.config().Labels,
<ide> ExperimentalBuild: utils.ExperimentalBuild(),
<add> ServerVersion: dockerversion.VERSION,
<ide> }
<ide>
<ide> // TODO Windows. Refactor this more once sysinfo is refactored into
<ide><path>docs/reference/api/docker_remote_api.md
<ide> This section lists each version from latest to oldest. Each listing includes a
<ide> list of DNS options to be used in the container.
<ide> * `POST /build` now optionally takes a serialized map of build-time variables.
<ide> * `GET /events` now includes a `timenano` field, in addition to the existing `time` field.
<add>* `GET /info` now lists engine version information.
<ide>
<ide> ### v1.20 API changes
<ide>
<ide><path>docs/reference/api/docker_remote_api_v1.21.md
<ide> Display system-wide information
<ide> },
<ide> "SwapLimit": false,
<ide> "SystemTime": "2015-03-10T11:11:23.730591467-07:00"
<add> "ServerVersion": "1.9.0"
<ide> }
<ide>
<ide> Status Codes:
<ide><path>docs/reference/commandline/info.md
<ide> For example:
<ide> $ docker -D info
<ide> Containers: 14
<ide> Images: 52
<add> Engine Version: 1.9.0
<ide> Storage Driver: aufs
<ide> Root Dir: /var/lib/docker/aufs
<ide> Backing Filesystem: extfs
<ide><path>integration-cli/docker_api_info_test.go
<ide> func (s *DockerSuite) TestInfoApi(c *check.C) {
<ide> "NCPU",
<ide> "MemTotal",
<ide> "KernelVersion",
<del> "Driver"}
<add> "Driver",
<add> "ServerVersion"}
<ide>
<ide> out := string(body)
<ide> for _, linePrefix := range stringsToCheck {
<ide><path>man/docker-info.1.md
<ide> Here is a sample output:
<ide> # docker info
<ide> Containers: 14
<ide> Images: 52
<add> Engine Version: 1.9.0
<ide> Storage Driver: aufs
<ide> Root Dir: /var/lib/docker/aufs
<ide> Dirs: 80 | 8 |
Text | Text | add missing example | 525b441f039af23429e06196b96e6097affb49d2 | <ide><path>threejs/lessons/threejs-backgrounds.md
<ide> let bgMesh;
<ide> }
<ide> ```
<ide>
<add>{{{example url="../threejs-background-equirectangularmap.html" }}}
<add>
<ide> Using equirectagular images requires more complicated shaders and so is slower than using cubemaps. Fortunately it's easy to convert from an equirectangular image to a cubemap. [Here's a site that will do it for you](https://matheowis.github.io/HDRI-to-CubeMap/).
<ide>\ No newline at end of file | 1 |
Mixed | Javascript | allow broadcastchannel in receivemessageonport | 9dd2f9f19dd35a91eabd0aa5acff9011db59e238 | <ide><path>doc/api/worker_threads.md
<ide> if (isMainThread) {
<ide> ## `worker.receiveMessageOnPort(port)`
<ide> <!-- YAML
<ide> added: v12.3.0
<add>changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/37535
<add> description: The port argument can also refer to a `BroadcastChannel` now.
<ide> -->
<ide>
<del>* `port` {MessagePort}
<add>* `port` {MessagePort|BroadcastChannel}
<ide>
<ide> * Returns: {Object|undefined}
<ide>
<ide><path>lib/internal/worker/io.js
<ide> function createWorkerStdio() {
<ide> }
<ide>
<ide> function receiveMessageOnPort(port) {
<del> const message = receiveMessageOnPort_(port);
<add> const message = receiveMessageOnPort_(port?.[kHandle] ?? port);
<ide> if (message === noMessageSymbol) return undefined;
<ide> return { message };
<ide> }
<ide><path>test/parallel/test-worker-broadcastchannel.js
<ide> const common = require('../common');
<ide> const {
<ide> BroadcastChannel,
<ide> Worker,
<add> receiveMessageOnPort
<ide> } = require('worker_threads');
<ide> const assert = require('assert');
<ide>
<ide> assert.throws(() => new BroadcastChannel(), {
<ide> message: /BroadcastChannel is closed/
<ide> });
<ide> }
<add>
<add>{
<add> const bc1 = new BroadcastChannel('channel4');
<add> const bc2 = new BroadcastChannel('channel4');
<add> bc1.postMessage('some data');
<add> assert.strictEqual(receiveMessageOnPort(bc2).message, 'some data');
<add> assert.strictEqual(receiveMessageOnPort(bc2), undefined);
<add> bc1.close();
<add> bc2.close();
<add>} | 3 |
Javascript | Javascript | add hooks back for devtools | b80f676d275d3a88f4d5524731c5398fa04afab6 | <ide><path>src/renderers/dom/ReactDOM.js
<ide>
<ide> 'use strict';
<ide>
<add>var ReactDOMComponentTree = require('ReactDOMComponentTree');
<ide> var ReactDefaultInjection = require('ReactDefaultInjection');
<ide> var ReactMount = require('ReactMount');
<ide> var ReactPerf = require('ReactPerf');
<ide> var ReactUpdates = require('ReactUpdates');
<ide> var ReactVersion = require('ReactVersion');
<ide>
<ide> var findDOMNode = require('findDOMNode');
<add>var getNativeComponentFromComposite = require('getNativeComponentFromComposite');
<ide> var renderSubtreeIntoContainer = require('renderSubtreeIntoContainer');
<ide> var warning = require('warning');
<ide>
<ide> if (
<ide> typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
<ide> typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') {
<ide> __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({
<add> ComponentTree: {
<add> getClosestInstanceFromNode:
<add> ReactDOMComponentTree.getClosestInstanceFromNode,
<add> getNodeFromInstance: function(inst) {
<add> // inst is an internal instance (but could be a composite)
<add> if (inst._renderedComponent) {
<add> inst = getNativeComponentFromComposite(inst);
<add> }
<add> if (inst) {
<add> return ReactDOMComponentTree.getNodeFromInstance(inst);
<add> } else {
<add> return null;
<add> }
<add> },
<add> },
<ide> Mount: ReactMount,
<ide> Reconciler: ReactReconciler,
<ide> });
<ide><path>src/renderers/dom/client/ReactMount.js
<ide> var ELEMENT_NODE_TYPE = 1;
<ide> var DOC_NODE_TYPE = 9;
<ide> var DOCUMENT_FRAGMENT_NODE_TYPE = 11;
<ide>
<add>var instancesByReactRootID = {};
<add>
<ide> /**
<ide> * Finds the index of the first character
<ide> * that's not common between the two given strings.
<ide> function hasNonRootReactChild(container) {
<ide> );
<ide> }
<ide>
<del>function getTopLevelWrapperInContainer(container) {
<add>function getNativeRootInstanceInContainer(container) {
<ide> var rootEl = getReactRootElementInContainer(container);
<ide> var prevNativeInstance =
<ide> rootEl && ReactDOMComponentTree.getInstanceFromNode(rootEl);
<del> return !prevNativeInstance || prevNativeInstance._nativeParent ? null :
<del> prevNativeInstance._nativeContainerInfo._topLevelWrapper;
<add> return (
<add> prevNativeInstance && !prevNativeInstance._nativeParent ?
<add> prevNativeInstance : null
<add> );
<add>}
<add>
<add>function getTopLevelWrapperInContainer(container) {
<add> var root = getNativeRootInstanceInContainer(container);
<add> return root ? root._nativeContainerInfo._topLevelWrapper : null;
<ide> }
<ide>
<ide> /**
<ide> * Temporary (?) hack so that we can store all top-level pending updates on
<ide> * composites instead of having to worry about different types of components
<ide> * here.
<ide> */
<del>var TopLevelWrapper = function() {};
<add>var topLevelRootCounter = 1;
<add>var TopLevelWrapper = function() {
<add> this.rootID = topLevelRootCounter++;
<add>};
<ide> TopLevelWrapper.prototype.isReactComponent = {};
<ide> if (__DEV__) {
<ide> TopLevelWrapper.displayName = 'TopLevelWrapper';
<ide> var ReactMount = {
<ide>
<ide> TopLevelWrapper: TopLevelWrapper,
<ide>
<add> /**
<add> * Used by devtools. The keys are not important.
<add> */
<add> _instancesByReactRootID: instancesByReactRootID,
<add>
<ide> /**
<ide> * This is a hook provided to support rendering React components while
<ide> * ensuring that the apparent scroll position of its `container` does not
<ide> var ReactMount = {
<ide> },
<ide>
<ide> /**
<del> * Render a new component into the DOM.
<add> * Render a new component into the DOM. Hooked by devtools!
<add> *
<ide> * @param {ReactElement} nextElement element to render
<ide> * @param {DOMElement} container container to render into
<ide> * @param {boolean} shouldReuseMarkup if we should skip the markup insertion
<ide> var ReactMount = {
<ide> context
<ide> );
<ide>
<add> var wrapperID = componentInstance._instance.rootID;
<add> instancesByReactRootID[wrapperID] = componentInstance;
<add>
<ide> return componentInstance;
<ide> },
<ide>
<ide> var ReactMount = {
<ide>
<ide> return false;
<ide> }
<add> delete instancesByReactRootID[prevComponent._instance.rootID];
<ide> ReactUpdates.batchedUpdates(
<ide> unmountComponentFromNode,
<ide> prevComponent,
<ide><path>src/renderers/dom/client/__tests__/ReactMount-test.js
<ide>
<ide> 'use strict';
<ide>
<add>var React;
<add>var ReactDOM;
<add>var ReactDOMServer;
<add>var ReactMount;
<add>var ReactTestUtils;
<add>var WebComponents;
<add>
<ide> describe('ReactMount', function() {
<del> var React = require('React');
<del> var ReactDOM = require('ReactDOM');
<del> var ReactDOMServer = require('ReactDOMServer');
<del> var ReactMount = require('ReactMount');
<del> var ReactTestUtils = require('ReactTestUtils');
<del> var WebComponents = WebComponents;
<del>
<del> try {
<del> if (WebComponents === undefined && typeof jest !== 'undefined') {
<del> WebComponents = require('WebComponents');
<add> beforeEach(function() {
<add> jest.resetModuleRegistry();
<add>
<add> React = require('React');
<add> ReactDOM = require('ReactDOM');
<add> ReactDOMServer = require('ReactDOMServer');
<add> ReactMount = require('ReactMount');
<add> ReactTestUtils = require('ReactTestUtils');
<add>
<add> try {
<add> if (WebComponents === undefined && typeof jest !== 'undefined') {
<add> WebComponents = require('WebComponents');
<add> }
<add> } catch (e) {
<add> // Parse error expected on engines that don't support setters
<add> // or otherwise aren't supportable by the polyfill.
<add> // Leave WebComponents undefined.
<ide> }
<del> } catch (e) {
<del> // Parse error expected on engines that don't support setters
<del> // or otherwise aren't supportable by the polyfill.
<del> // Leave WebComponents undefined.
<del> }
<add> });
<ide>
<ide> describe('unmountComponentAtNode', function() {
<ide> it('throws when given a non-node', function() {
<ide> describe('ReactMount', function() {
<ide>
<ide> expect(calls).toBe(5);
<ide> });
<add>
<add> it('tracks root instances', function() {
<add> // Used by devtools.
<add> expect(Object.keys(ReactMount._instancesByReactRootID).length).toBe(0);
<add> ReactTestUtils.renderIntoDocument(<span />);
<add> expect(Object.keys(ReactMount._instancesByReactRootID).length).toBe(1);
<add> var container = document.createElement('div');
<add> ReactDOM.render(<span />, container);
<add> expect(Object.keys(ReactMount._instancesByReactRootID).length).toBe(2);
<add> ReactDOM.unmountComponentAtNode(container);
<add> expect(Object.keys(ReactMount._instancesByReactRootID).length).toBe(1);
<add> });
<ide> });
<ide><path>src/renderers/dom/client/findDOMNode.js
<ide> var ReactCurrentOwner = require('ReactCurrentOwner');
<ide> var ReactDOMComponentTree = require('ReactDOMComponentTree');
<ide> var ReactInstanceMap = require('ReactInstanceMap');
<del>var ReactNodeTypes = require('ReactNodeTypes');
<ide>
<add>var getNativeComponentFromComposite = require('getNativeComponentFromComposite');
<ide> var invariant = require('invariant');
<ide> var warning = require('warning');
<ide>
<del>function getNativeComponentFromComposite(inst) {
<del> var type;
<del>
<del> while ((type = inst._renderedNodeType) === ReactNodeTypes.COMPOSITE) {
<del> inst = inst._renderedComponent;
<del> }
<del>
<del> if (type === ReactNodeTypes.NATIVE) {
<del> return inst._renderedComponent;
<del> } else if (type === ReactNodeTypes.EMPTY) {
<del> return null;
<del> }
<del>}
<del>
<ide> /**
<ide> * Returns the DOM node rendered by this element.
<ide> *
<ide><path>src/shared/utils/getNativeComponentFromComposite.js
<add>/**
<add> * Copyright 2013-2015, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule getNativeComponentFromComposite
<add> */
<add>
<add>'use strict';
<add>
<add>var ReactNodeTypes = require('ReactNodeTypes');
<add>
<add>function getNativeComponentFromComposite(inst) {
<add> var type;
<add>
<add> while ((type = inst._renderedNodeType) === ReactNodeTypes.COMPOSITE) {
<add> inst = inst._renderedComponent;
<add> }
<add>
<add> if (type === ReactNodeTypes.NATIVE) {
<add> return inst._renderedComponent;
<add> } else if (type === ReactNodeTypes.EMPTY) {
<add> return null;
<add> }
<add>}
<add>
<add>module.exports = getNativeComponentFromComposite; | 5 |
Javascript | Javascript | fix mixture of tabs and spaces | da6dba24740522ffd18163fd49afa4a55ba93754 | <ide><path>test/binCases/errors/child-compilation-error/test.js
<ide> module.exports = function testAssertions(code, stdout, stderr) {
<ide> code.should.be.eql(2);
<ide>
<del> stdout[0].should.containEql("Hash: ");
<del> stdout[1].should.containEql("Version: ");
<del> stdout[2].should.containEql("Time: ");
<del> stdout[5].should.containEql("./index.js");
<del> stdout[8].should.containEql("ERROR in child compilation");
<add> stdout[0].should.containEql("Hash: ");
<add> stdout[1].should.containEql("Version: ");
<add> stdout[2].should.containEql("Time: ");
<add> stdout[5].should.containEql("./index.js");
<add> stdout[8].should.containEql("ERROR in child compilation");
<ide>
<del> stderr.should.be.empty();
<add> stderr.should.be.empty();
<ide> };
<ide><path>test/binCases/errors/child-compilation-error/webpack.config.js
<ide> "use strict";
<ide>
<ide> module.exports = {
<del> entry: "./index",
<del> output: {
<del> filename: "bundle.js"
<del> },
<del> plugins: [{
<add> entry: "./index",
<add> output: {
<add> filename: "bundle.js"
<add> },
<add> plugins: [{
<ide> apply(compiler) {
<ide> compiler.plugin("make", (compilation, cb) => {
<ide> const child = compilation.createChildCompiler("child", {}); | 2 |
Python | Python | add tests for "_get_instance_vhd" method | 91ea09116afa5b5e969a6a2184c3a68fc192c485 | <ide><path>libcloud/test/compute/test_azure_arm.py
<ide> # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<ide> # See the License for the specific language governing permissions and
<ide> # limitations under the License.import libcloud
<add>
<ide> import json
<ide> import sys
<ide> import functools
<ide> from datetime import datetime
<ide>
<add>import mock
<add>
<ide> from libcloud.compute.base import (NodeLocation, NodeSize, VolumeSnapshot,
<ide> StorageVolume)
<ide> from libcloud.compute.drivers.azure_arm import AzureImage, NodeAuthPassword
<ide> def test_destroy_volume_snapshot(self):
<ide> res_value = snapshot.destroy()
<ide> self.assertTrue(res_value)
<ide>
<add> def test_get_instance_vhd(self):
<add> with mock.patch.object(self.driver, '_ex_delete_old_vhd'):
<add> # Default storage suffix
<add> vhd_url = self.driver._get_instance_vhd(name='test1',
<add> ex_resource_group='000000',
<add> ex_storage_account='sga1')
<add> self.assertEqual(vhd_url, 'https://sga1.blob.core.windows.net/vhds/test1-os_0.vhd')
<add>
<add> # Custom storage suffix
<add> self.driver.connection.storage_suffix = '.core.chinacloudapi.cn'
<add> vhd_url = self.driver._get_instance_vhd(name='test1',
<add> ex_resource_group='000000',
<add> ex_storage_account='sga1')
<add> self.assertEqual(vhd_url, 'https://sga1.blob.core.chinacloudapi.cn/vhds/test1-os_0.vhd')
<add>
<ide>
<ide> class AzureMockHttp(MockHttp):
<ide> fixtures = ComputeFileFixtures('azure_arm') | 1 |
Javascript | Javascript | add config schema for version pinned packages | 6740952c1cb36a974d5c7da540fbc1a249e34ddd | <ide><path>src/config-schema.js
<ide> const configSchema = {
<ide>
<ide> description: 'List of names of installed packages which are not loaded at startup.'
<ide> },
<add> versionPinnedPackages: {
<add> type: 'array',
<add> default: [],
<add>
<add> items: {
<add> type: 'string'
<add> },
<add>
<add> description: 'List of names of installed packages which are not automatically updated.'
<add> },
<ide> customFileTypes: {
<ide> type: 'object',
<ide> default: {}, | 1 |
Javascript | Javascript | replace fixturesdir with common.fixtures | 6e1948ea06b5413c493c744b9409e7c6ef60c958 | <ide><path>test/parallel/test-http2-respond-file-fd.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>const fixtures = require('../common/fixtures');
<ide> if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<ide> const http2 = require('http2');
<ide> const assert = require('assert');
<del>const path = require('path');
<ide> const fs = require('fs');
<ide>
<ide> const {
<ide> HTTP2_HEADER_CONTENT_TYPE,
<ide> HTTP2_HEADER_CONTENT_LENGTH
<ide> } = http2.constants;
<ide>
<del>const fname = path.resolve(common.fixturesDir, 'elipses.txt');
<add>const fname = fixtures.path('elipses.txt');
<ide> const data = fs.readFileSync(fname);
<ide> const stat = fs.statSync(fname);
<ide> const fd = fs.openSync(fname, 'r'); | 1 |
Javascript | Javascript | report user activity on touchmove if userwasactive | 75a23135e62ad23fec6a6bb1d39a02af104fcf09 | <ide><path>src/js/media/media.js
<ide> vjs.MediaTechController.prototype.initControlsListeners = function(){
<ide> };
<ide>
<ide> vjs.MediaTechController.prototype.addControlsListeners = function(){
<add> var userWasActive;
<add>
<ide> // Some browsers (Chrome & IE) don't trigger a click on a flash swf, but do
<ide> // trigger mousedown/up.
<ide> // http://stackoverflow.com/questions/1444562/javascript-onclick-event-over-flash-object
<ide> vjs.MediaTechController.prototype.addControlsListeners = function(){
<ide> this.on('touchstart', function(event) {
<ide> // Stop the mouse events from also happening
<ide> event.preventDefault();
<add> userWasActive = this.player_.userActive();
<ide> });
<ide>
<ide> this.on('touchmove', function(event) {
<del> this.player().reportUserActivity();
<add> if (userWasActive){
<add> this.player().reportUserActivity();
<add> }
<ide> });
<ide>
<ide> // Turn on component tap events | 1 |
PHP | PHP | add test class i forgot earlier | 5e3c347722f2ccd763e29090daf3d301f2f9e98c | <ide><path>tests/test_app/TestApp/Command/Helper/CommandHelper.php
<add><?php
<add>namespace TestApp\Command\Helper;
<add>
<add>use Cake\Console\Helper;
<add>
<add>class CommandHelper extends Helper
<add>{
<add> public function output($args)
<add> {
<add> $this->_io->out('I am helping ' . implode(' ', $args));
<add> }
<add>} | 1 |
Mixed | Javascript | relax requirements on upgrade listener | f7fbbeedc609f56c898230971b44d3dde0934dc9 | <ide><path>doc/api/http.md
<ide> added: v0.1.94
<ide> * `head` {Buffer}
<ide>
<ide> Emitted each time a server responds to a request with an upgrade. If this
<del>event is not being listened for, clients receiving an upgrade header will have
<del>their connections closed.
<add>event is not being listened for and the response status code is 101 Switching
<add>Protocols, clients receiving an upgrade header will have their connections
<add>closed.
<ide>
<ide> A client server pair demonstrating how to listen for the `'upgrade'` event.
<ide>
<ide> per connection (in the case of HTTP Keep-Alive connections).
<ide> ### Event: 'upgrade'
<ide> <!-- YAML
<ide> added: v0.1.94
<add>changes:
<add> - version: REPLACEME
<add> pr-url: REPLACEME
<add> description: Not listening to this event no longer causes the socket
<add> to be destroyed if a client sends an Upgrade header.
<ide> -->
<ide>
<ide> * `request` {http.IncomingMessage} Arguments for the HTTP request, as it is in
<ide> the [`'request'`][] event
<ide> * `socket` {net.Socket} Network socket between the server and client
<ide> * `head` {Buffer} The first packet of the upgraded stream (may be empty)
<ide>
<del>Emitted each time a client requests an HTTP upgrade. If this event is not
<del>listened for, then clients requesting an upgrade will have their connections
<del>closed.
<add>Emitted each time a client requests an HTTP upgrade. Listening to this event
<add>is optional and clients cannot insist on a protocol change.
<ide>
<ide> After this event is emitted, the request's socket will not have a `'data'`
<ide> event listener, meaning it will need to be bound in order to handle data
<ide><path>lib/_http_client.js
<ide> function socketOnData(d) {
<ide> req.socket._hadError = true;
<ide> req.emit('error', ret);
<ide> } else if (parser.incoming && parser.incoming.upgrade) {
<del> // Upgrade or CONNECT
<add> // Upgrade (if status code 101) or CONNECT
<ide> var bytesParsed = ret;
<ide> var res = parser.incoming;
<ide> req.res = res;
<ide> function socketOnData(d) {
<ide> req.emit(eventName, res, socket, bodyHead);
<ide> req.emit('close');
<ide> } else {
<del> // Got Upgrade header or CONNECT method, but have no handler.
<add> // Requested Upgrade or used CONNECT method, but have no handler.
<ide> socket.destroy();
<ide> }
<ide> } else if (parser.incoming && parser.incoming.complete &&
<ide> function parserOnIncomingClient(res, shouldKeepAlive) {
<ide> }
<ide> req.res = res;
<ide>
<add> // Skip body and treat as Upgrade.
<add> if (res.upgrade)
<add> return 2;
<add>
<ide> // Responses to CONNECT request is handled as Upgrade.
<ide> const method = req.method;
<ide> if (method === 'CONNECT') {
<ide><path>lib/_http_common.js
<ide> function parserOnHeadersComplete(versionMajor, versionMinor, headers, method,
<ide> parser.incoming.httpVersionMinor = versionMinor;
<ide> parser.incoming.httpVersion = `${versionMajor}.${versionMinor}`;
<ide> parser.incoming.url = url;
<add> parser.incoming.upgrade = upgrade;
<ide>
<ide> var n = headers.length;
<ide>
<ide> function parserOnHeadersComplete(versionMajor, versionMinor, headers, method,
<ide> parser.incoming.statusMessage = statusMessage;
<ide> }
<ide>
<del> if (upgrade && parser.outgoing !== null && !parser.outgoing.upgrading) {
<del> // The client made non-upgrade request, and server is just advertising
<del> // supported protocols.
<del> //
<del> // See RFC7230 Section 6.7
<del> upgrade = false;
<del> }
<del>
<del> parser.incoming.upgrade = upgrade;
<del>
<del> if (upgrade)
<del> return 2; // Skip body and treat as Upgrade.
<del>
<ide> return parser.onIncoming(parser.incoming, shouldKeepAlive);
<ide> }
<ide>
<ide><path>lib/_http_outgoing.js
<ide> function OutgoingMessage() {
<ide> this.writable = true;
<ide>
<ide> this._last = false;
<del> this.upgrading = false;
<ide> this.chunkedEncoding = false;
<ide> this.shouldKeepAlive = true;
<ide> this.useChunkedEncodingByDefault = true;
<ide> function _storeHeader(firstLine, headers) {
<ide> // in the case of response it is: 'HTTP/1.1 200 OK\r\n'
<ide> var state = {
<ide> connection: false,
<del> connUpgrade: false,
<ide> contLen: false,
<ide> te: false,
<ide> date: false,
<ide> function _storeHeader(firstLine, headers) {
<ide> }
<ide> }
<ide>
<del> // Are we upgrading the connection?
<del> if (state.connUpgrade && state.upgrade)
<del> this.upgrading = true;
<del>
<ide> // Date header
<ide> if (this.sendDate && !state.date) {
<ide> state.header += 'Date: ' + utcDate() + CRLF;
<ide> function matchConnValue(self, state, value) {
<ide> while (m) {
<ide> if (m[0].length === 5)
<ide> sawClose = true;
<del> else
<del> state.connUpgrade = true;
<ide> m = RE_CONN_VALUES.exec(value);
<ide> }
<ide> if (sawClose)
<ide><path>lib/_http_server.js
<ide> function onParserExecuteCommon(server, socket, parser, state, ret, d) {
<ide> parser = null;
<ide>
<ide> var eventName = req.method === 'CONNECT' ? 'connect' : 'upgrade';
<del> if (server.listenerCount(eventName) > 0) {
<add> if (eventName === 'upgrade' || server.listenerCount(eventName) > 0) {
<ide> debug('SERVER have listener for %s', eventName);
<ide> var bodyHead = d.slice(bytesParsed, d.length);
<ide>
<ide> socket.readableFlowing = null;
<ide> server.emit(eventName, req, socket, bodyHead);
<ide> } else {
<del> // Got upgrade header or CONNECT method, but have no handler.
<add> // Got CONNECT method, but have no handler.
<ide> socket.destroy();
<ide> }
<ide> }
<ide> function resOnFinish(req, res, socket, state, server) {
<ide> function parserOnIncoming(server, socket, state, req, keepAlive) {
<ide> resetSocketTimeout(server, socket, state);
<ide>
<add> if (req.upgrade) {
<add> req.upgrade = req.method === 'CONNECT' ||
<add> server.listenerCount('upgrade') > 0;
<add> if (req.upgrade)
<add> return 2;
<add> }
<add>
<ide> state.incoming.push(req);
<ide>
<ide> // If the writable end isn't consuming, then stop reading
<ide><path>test/parallel/test-http-upgrade-advertise.js
<ide> const tests = [
<ide> { headers: {}, expected: 'regular' },
<ide> { headers: { upgrade: 'h2c' }, expected: 'regular' },
<ide> { headers: { connection: 'upgrade' }, expected: 'regular' },
<del> { headers: { connection: 'upgrade', upgrade: 'h2c' }, expected: 'upgrade' }
<add> { headers: { connection: 'upgrade', upgrade: 'h2c' }, expected: 'upgrade' },
<add> { headers: { connection: 'upgrade', upgrade: 'h2c' }, expected: 'destroy' },
<add> { headers: { connection: 'upgrade', upgrade: 'h2c' }, expected: 'regular' },
<ide> ];
<ide>
<ide> function fire() {
<ide> function fire() {
<ide> done('regular');
<ide> });
<ide>
<del> req.on('upgrade', function onUpgrade(res, socket) {
<del> socket.destroy();
<del> done('upgrade');
<del> });
<add> if (test.expected === 'destroy') {
<add> req.on('socket', () => req.socket.on('close', () => {
<add> server.removeAllListeners('upgrade');
<add> done('destroy');
<add> }));
<add> } else {
<add> req.on('upgrade', function onUpgrade(res, socket) {
<add> socket.destroy();
<add> done('upgrade');
<add> });
<add> }
<ide>
<ide> req.end();
<ide> }
<ide><path>test/parallel/test-http-upgrade-server.js
<ide> function test_upgrade_with_listener() {
<ide> /*-----------------------------------------------
<ide> connection: Upgrade, no listener
<ide> -----------------------------------------------*/
<del>let test_upgrade_no_listener_ended = false;
<del>
<ide> function test_upgrade_no_listener() {
<ide> const conn = net.createConnection(server.address().port);
<ide> conn.setEncoding('utf8');
<ide> function test_upgrade_no_listener() {
<ide> '\r\n');
<ide> });
<ide>
<del> conn.on('end', function() {
<del> test_upgrade_no_listener_ended = true;
<add> conn.once('data', (data) => {
<add> assert.strictEqual(typeof data, 'string');
<add> assert.strictEqual(data.substr(0, 12), 'HTTP/1.1 200');
<ide> conn.end();
<ide> });
<ide>
<ide> server.listen(0, function() {
<ide> process.on('exit', function() {
<ide> assert.strictEqual(3, requests_recv);
<ide> assert.strictEqual(3, requests_sent);
<del> assert.ok(test_upgrade_no_listener_ended);
<ide> }); | 7 |
Python | Python | get default logger from common place | 54668397a5f27ab6e380a65e8d6460ad8a6ca191 | <ide><path>celery/beat.py
<ide> from UserDict import UserDict
<ide> from datetime import datetime
<ide>
<add>from celery import log
<ide> from celery import conf
<ide> from celery import registry
<ide> from celery.log import setup_logger
<ide>
<ide>
<ide> def humanize_seconds(secs, prefix=""):
<add> """Show seconds in human form, e.g. 60 is "1 minute", 7200 is "2
<add> hours"."""
<ide> for unit, divider, formatter in TIME_UNITS:
<ide> if secs >= divider:
<ide> w = secs / divider
<ide> def __init__(self, name, last_run_at=None,
<ide> self.total_run_count = total_run_count or 0
<ide>
<ide> def next(self):
<add> """Returns a new instance of the same class, but with
<add> its date and count fields updated."""
<ide> return self.__class__(self.name, datetime.now(),
<ide> self.total_run_count + 1)
<ide>
<ide> def is_due(self, task):
<add> """See :meth:`celery.task.base.PeriodicTask.is_due`."""
<ide> return task.is_due(self.last_run_at)
<ide>
<ide>
<ide> class Scheduler(UserDict):
<ide>
<ide> def __init__(self, **kwargs):
<ide>
<del> def _get_default_logger():
<del> import multiprocessing
<del> return multiprocessing.get_logger()
<del>
<ide> attr_defaults = {"registry": lambda: {},
<ide> "schedule": lambda: {},
<ide> "interval": lambda: self.interval,
<del> "logger": _get_default_logger}
<add> "logger": log.get_default_logger}
<ide>
<ide> for attr_name, attr_default_gen in attr_defaults.items():
<ide> if attr_name in kwargs:
<ide><path>celery/events.py
<ide>
<ide>
<ide> def Event(type, **fields):
<add> """Create an event.
<add>
<add> An event is a dictionary, the only required field is the type.
<add>
<add> """
<ide> return dict(fields, type=type, timestamp=time.time())
<ide>
<ide>
<ide><path>celery/log.py
<ide>
<ide>
<ide> def get_default_logger(loglevel=None):
<del> import multiprocessing
<del> logger = multiprocessing.get_logger()
<add> from multiprocessing.util import get_logger
<add> logger = get_logger()
<ide> loglevel is not None and logger.setLevel(loglevel)
<ide> return logger
<ide>
<ide><path>celery/worker/pool.py
<ide> Process Pools.
<ide>
<ide> """
<del>from multiprocessing.util import get_logger
<del>
<ide> from billiard.pool import DynamicPool
<ide> from billiard.utils.functional import curry
<ide>
<add>from celery import log
<ide> from celery.utils import noop
<ide> from celery.datastructures import ExceptionInfo
<ide>
<ide> class TaskPool(object):
<ide>
<ide> def __init__(self, limit, logger=None, initializer=None):
<ide> self.limit = limit
<del> self.logger = logger or get_logger()
<add> self.logger = logger or log.get_default_logger()
<ide> self.initializer = initializer
<ide> self._pool = None
<ide> | 4 |
Javascript | Javascript | add reactdomselection module | 8f15eea910c097893c7bdc24725cf7ceff93cf32 | <ide><path>src/core/ReactDOMSelection.js
<add>/**
<add> * Copyright 2013 Facebook, Inc.
<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> * @providesModule ReactDOMSelection
<add> */
<add>
<add>"use strict";
<add>
<add>var getNodeForCharacterOffset = require('getNodeForCharacterOffset');
<add>var getTextContentAccessor = require('getTextContentAccessor');
<add>
<add>/**
<add> * Get the appropriate anchor and focus node/offset pairs for IE.
<add> *
<add> * The catch here is that IE's selection API doesn't provide information
<add> * about whether the selection is forward or backward, so we have to
<add> * behave as though it's always forward.
<add> *
<add> * IE text differs from modern selection in that it behaves as though
<add> * block elements end with a new line. This means character offsets will
<add> * differ between the two APIs.
<add> *
<add> * @param {DOMElement} node
<add> */
<add>function getIESelection(node) {
<add> var selection = document.selection;
<add> var selectedRange = selection.createRange();
<add> var selectedLength = selectedRange.text.length;
<add>
<add> // Duplicate selection so we can move range without breaking user selection.
<add> var fromStart = selectedRange.duplicate();
<add> fromStart.moveToElementText(node);
<add> fromStart.setEndPoint('EndToStart', selectedRange);
<add>
<add> var startOffset = fromStart.text.length;
<add> var endOffset = startOffset + selectedLength;
<add>
<add> return {
<add> start: startOffset,
<add> end: endOffset
<add> };
<add>}
<add>
<add>/**
<add> * @param {DOMElement} node
<add> */
<add>function getModernSelection(node) {
<add> var selection = global.getSelection();
<add> var anchorNode = selection.anchorNode;
<add> var anchorOffset = selection.anchorOffset;
<add> var focusNode = selection.focusNode;
<add> var focusOffset = selection.focusOffset;
<add>
<add> var currentRange = selection.getRangeAt(0);
<add> var rangeLength = currentRange.toString().length;
<add>
<add> var tempRange = currentRange.cloneRange();
<add> tempRange.selectNodeContents(node);
<add> tempRange.setEnd(currentRange.startContainer, currentRange.startOffset);
<add>
<add> var start = tempRange.toString().length;
<add> var end = start + rangeLength;
<add>
<add> // Detect whether the selection is backward.
<add> var detectionRange = document.createRange();
<add> detectionRange.setStart(anchorNode, anchorOffset);
<add> detectionRange.setEnd(focusNode, focusOffset);
<add> var isBackward = detectionRange.collapsed;
<add> detectionRange.detach();
<add>
<add> return {
<add> start: isBackward ? end : start,
<add> end: isBackward ? start : end
<add> };
<add>}
<add>
<add>/**
<add> * @param {DOMElement|DOMTextNode} node
<add> * @param {object} offsets
<add> */
<add>function setIESelection(node, offsets) {
<add> var range = document.selection.createRange().duplicate();
<add> var start, end;
<add>
<add> if (typeof offsets.end === 'undefined') {
<add> start = offsets.start;
<add> end = start;
<add> } else if (offsets.start > offsets.end) {
<add> start = offsets.end;
<add> end = offsets.start;
<add> } else {
<add> start = offsets.start;
<add> end = offsets.end;
<add> }
<add>
<add> range.moveToElementText(node);
<add> range.moveStart('character', start);
<add> range.setEndPoint('EndToStart', range);
<add> range.moveEnd('character', end - start);
<add> range.select();
<add>}
<add>
<add>/**
<add> * In modern non-IE browsers, we can support both forward and backward
<add> * selections.
<add> *
<add> * Note: IE10+ supports the Selection object, but it does not support
<add> * the `extend` method, which means that even in modern IE, it's not possible
<add> * to programatically create a backward selection. Thus, for all IE
<add> * versions, we use the old IE API to create our selections.
<add> *
<add> * @param {DOMElement|DOMTextNode} node
<add> * @param {object} offsets
<add> */
<add>function setModernSelection(node, offsets) {
<add> var selection = global.getSelection();
<add>
<add> var length = node[getTextContentAccessor()].length;
<add> var start = Math.min(offsets.start, length);
<add> var end = typeof offsets.end === 'undefined' ?
<add> start : Math.min(offsets.end, length);
<add>
<add> var startMarker = getNodeForCharacterOffset(node, start);
<add> var endMarker = getNodeForCharacterOffset(node, end);
<add>
<add> if (startMarker && endMarker) {
<add> var range = document.createRange();
<add> range.setStart(startMarker.node, startMarker.offset);
<add> selection.removeAllRanges();
<add> selection.addRange(range);
<add> selection.extend(endMarker.node, endMarker.offset);
<add> range.detach();
<add> }
<add>}
<add>
<add>var ReactDOMSelection = {
<add> /**
<add> * @param {DOMElement} node
<add> */
<add> get: document.selection ? getIESelection : getModernSelection,
<add>
<add> /**
<add> * @param {DOMElement|DOMTextNode} node
<add> * @param {object} offsets
<add> */
<add> set: document.selection ? setIESelection : setModernSelection
<add>};
<add>
<add>module.exports = ReactDOMSelection;
<ide><path>src/core/ReactInputSelection.js
<ide>
<ide> "use strict";
<ide>
<del>var getTextContentAccessor = require('getTextContentAccessor');
<add>var ReactDOMSelection = require('ReactDOMSelection');
<ide>
<ide> // It is not safe to read the document.activeElement property in IE if there's
<ide> // nothing focused.
<ide> var ReactInputSelection = {
<ide> * -@return {start: selectionStart, end: selectionEnd}
<ide> */
<ide> getSelection: function(input) {
<del> var range;
<del> if (input.contentEditable === 'true' && window.getSelection) {
<del> var selection = window.getSelection();
<del> if (selection.rangeCount > 0) {
<del> range = selection.getRangeAt(0);
<del> var commonAncestor = range.commonAncestorContainer;
<del> if (commonAncestor && commonAncestor.nodeType === 3) {
<del> commonAncestor = commonAncestor.parentNode;
<del> }
<del> if (commonAncestor === input) {
<del> return {start: range.startOffset, end: range.endOffset};
<del> }
<del> }
<del> return {start: 0, end: 0};
<del> }
<del>
<del> if (!document.selection) {
<del> // Mozilla, Safari, etc.
<del> return {start: input.selectionStart, end: input.selectionEnd};
<del> }
<del>
<del> range = document.selection.createRange();
<del> if (range.parentElement() !== input) {
<del> // There can only be one selection per document in IE, so if the
<del> // containing element of the document's selection isn't our text field,
<del> // our text field must have no selection.
<del> return {start: 0, end: 0};
<del> }
<del>
<del> var value = input.value || input[getTextContentAccessor()];
<del> var length = value.length;
<add> var selection;
<ide>
<del> if (input.nodeName === 'INPUT') {
<del> return {
<del> start: -range.moveStart('character', -length),
<del> end: -range.moveEnd('character', -length)
<add> if ('selectionStart' in input) {
<add> // Modern browser with input or textarea.
<add> selection = {
<add> start: input.selectionStart,
<add> end: input.selectionEnd
<ide> };
<add> } else if (document.selection && input.nodeName === 'INPUT') {
<add> // IE8 input.
<add> var range = document.selection.createRange();
<add> // There can only be one selection per document in IE, so it must
<add> // be in our element.
<add> if (range.parentElement() === input) {
<add> selection = {
<add> start: -range.moveStart('character', -input.value.length),
<add> end: -range.moveEnd('character', -input.value.length)
<add> };
<add> }
<ide> } else {
<del> var range2 = range.duplicate();
<del> range2.moveToElementText(input);
<del> range2.setEndPoint('StartToEnd', range);
<del> var end = length - range2.text.length;
<del> range2.setEndPoint('StartToStart', range);
<del> return {
<del> start: length - range2.text.length,
<del> end: end
<del> };
<add> // Content editable or old IE textarea.
<add> selection = ReactDOMSelection.get(input);
<ide> }
<add>
<add> return selection || {start: 0, end: 0};
<ide> },
<ide>
<ide> /**
<ide> * @setSelection: Sets the selection bounds of a textarea or input and focuses
<ide> * the input.
<ide> * -@input Set selection bounds of this input or textarea
<del> * -@rangeObj Object of same form that is returned from get*
<add> * -@offsets Object of same form that is returned from get*
<ide> */
<del> setSelection: function(input, rangeObj) {
<del> var range;
<del> var start = rangeObj.start;
<del> var end = rangeObj.end;
<add> setSelection: function(input, offsets) {
<add> var start = offsets.start;
<add> var end = offsets.end;
<ide> if (typeof end === 'undefined') {
<ide> end = start;
<ide> }
<del> if (document.selection) {
<del> // IE is inconsistent about character offsets when it comes to carriage
<del> // returns, so we need to manually take them into account
<del> if (input.tagName === 'TEXTAREA') {
<del> var cr_before =
<del> (input.value.slice(0, start).match(/\r/g) || []).length;
<del> var cr_inside =
<del> (input.value.slice(start, end).match(/\r/g) || []).length;
<del> start -= cr_before;
<del> end -= cr_before + cr_inside;
<del> }
<del> range = input.createTextRange();
<add>
<add> if ('selectionStart' in input) {
<add> input.selectionStart = start;
<add> input.selectionEnd = Math.min(end, input.value.length);
<add> } else if (document.selection && input.nodeName === 'INPUT') {
<add> var range = input.createTextRange();
<ide> range.collapse(true);
<ide> range.moveStart('character', start);
<ide> range.moveEnd('character', end - start);
<ide> range.select();
<ide> } else {
<del> if (input.contentEditable === 'true') {
<del> if (input.childNodes.length === 1) {
<del> range = document.createRange();
<del> range.setStart(input.childNodes[0], start);
<del> range.setEnd(input.childNodes[0], end);
<del> var sel = window.getSelection();
<del> sel.removeAllRanges();
<del> sel.addRange(range);
<del> }
<del> } else {
<del> input.selectionStart = start;
<del> input.selectionEnd = Math.min(end, input.value.length);
<del> input.focus();
<del> }
<add> ReactDOMSelection.set(input, offsets);
<ide> }
<ide> }
<del>
<ide> };
<ide>
<ide> module.exports = ReactInputSelection;
<ide><path>src/dom/__tests__/getNodeForCharacterOffset-test.js
<add>/**
<add> * Copyright 2013 Facebook, Inc.
<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> * @jsx React.DOM
<add> * @emails react-core
<add> */
<add>
<add>/*jslint evil: true */
<add>
<add>"use strict";
<add>
<add>var getTestDocument = require('getTestDocument');
<add>
<add>var getNodeForCharacterOffset = require('getNodeForCharacterOffset');
<add>
<add>// Create node from HTML string
<add>function createNode(html) {
<add> var node = (getTestDocument() || document).createElement('div');
<add> node.innerHTML = html;
<add> return node;
<add>}
<add>
<add>// Check getNodeForCharacterOffset return value matches expected result.
<add>function expectNodeOffset(result, textContent, nodeOffset) {
<add> expect(result.node.textContent).toBe(textContent);
<add> expect(result.offset).toBe(nodeOffset);
<add>}
<add>
<add>describe('getNodeForCharacterOffset', function() {
<add> it('should handle siblings', function() {
<add> var node = createNode('<i>123</i><i>456</i><i>789</i>');
<add>
<add> expectNodeOffset(getNodeForCharacterOffset(node, 0), '123', 0);
<add> expectNodeOffset(getNodeForCharacterOffset(node, 4), '456', 1);
<add> });
<add>
<add> it('should handle trailing chars', function() {
<add> var node = createNode('<i>123</i><i>456</i><i>789</i>');
<add>
<add> expectNodeOffset(getNodeForCharacterOffset(node, 3), '123', 3);
<add> expectNodeOffset(getNodeForCharacterOffset(node, 9), '789', 3);
<add> });
<add>
<add> it('should handle trees', function() {
<add> var node = createNode(
<add> '<i>' +
<add> '<i>1</i>' +
<add> '<i>' +
<add> '<i>' +
<add> '<i>2</i>' +
<add> '<i></i>' +
<add> '</i>' +
<add> '</i>' +
<add> '<i>' +
<add> '3' +
<add> '<i>45</i>' +
<add> '</i>' +
<add> '</i>'
<add> );
<add>
<add> expectNodeOffset(getNodeForCharacterOffset(node, 3), '3', 1);
<add> expectNodeOffset(getNodeForCharacterOffset(node, 5), '45', 2);
<add> expect(getNodeForCharacterOffset(node, 10)).toBeUndefined();
<add> });
<add>
<add> it('should handle non-existent offset', function() {
<add> var node = createNode('<i>123</i>');
<add>
<add> expect(getNodeForCharacterOffset(node, -1)).toBeUndefined();
<add> expect(getNodeForCharacterOffset(node, 4)).toBeUndefined();
<add> });
<add>});
<ide><path>src/dom/getNodeForCharacterOffset.js
<add>/**
<add> * Copyright 2013 Facebook, Inc.
<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> * @providesModule getNodeForCharacterOffset
<add> */
<add>
<add>"use strict";
<add>
<add>/**
<add> * Given any node return the first leaf node without children.
<add> *
<add> * @param {DOMElement|DOMTextNode} node
<add> * @return {DOMElement|DOMTextNode}
<add> */
<add>function getLeafNode(node) {
<add> while (node && node.firstChild) {
<add> node = node.firstChild;
<add> }
<add> return node;
<add>}
<add>
<add>/**
<add> * Get the next sibling within a container. This will walk up the
<add> * DOM if a node's siblings have been exhausted.
<add> *
<add> * @param {DOMElement|DOMTextNode} node
<add> * @return {?DOMElement|DOMTextNode}
<add> */
<add>function getSiblingNode(node) {
<add> while (node) {
<add> if (node.nextSibling) {
<add> return node.nextSibling;
<add> }
<add> node = node.parentNode;
<add> }
<add>}
<add>
<add>/**
<add> * Get object describing the nodes which contain characters at offset.
<add> *
<add> * @param {DOMElement|DOMTextNode} root
<add> * @param {number} offset
<add> * @return {?object}
<add> */
<add>function getNodeForCharacterOffset(root, offset) {
<add> var node = getLeafNode(root);
<add> var nodeStart = 0;
<add> var nodeEnd = 0;
<add>
<add> while (node) {
<add> if (node.nodeType == 3) {
<add> nodeEnd = nodeStart + node.textContent.length;
<add>
<add> if (nodeStart <= offset && nodeEnd >= offset) {
<add> return {
<add> node: node,
<add> offset: offset - nodeStart
<add> };
<add> }
<add>
<add> nodeStart = nodeEnd;
<add> }
<add>
<add> node = getLeafNode(getSiblingNode(node));
<add> }
<add>}
<add>
<add>module.exports = getNodeForCharacterOffset; | 4 |
Javascript | Javascript | simplify branching logic | a62c35080418299eb3171ffb336c3e70a22a7138 | <ide><path>lib/optimize/ConcatenatedModule.js
<ide> class ConcatenatedModule extends Module {
<ide> for (const identifier of allIdentifiers) {
<ide> const r = identifier.range;
<ide> const path = getPathInAst(info.ast, identifier);
<del> if (
<del> path &&
<del> path.length > 1 &&
<del> path[1].type === "Property" &&
<del> path[1].shorthand
<del> ) {
<del> source.insert(r[1], `: ${newName}`);
<del> } else if (
<del> path &&
<del> path.length &&
<del> path[1].type === "AssignmentPattern" &&
<del> path[2].type === "Property" &&
<del> path[2].shorthand
<del> ) {
<del> source.insert(r[1], `: ${newName}`);
<del> } else {
<del> source.replace(r[0], r[1] - 1, newName);
<add> if (path && path.length > 1) {
<add> const maybeProperty =
<add> path[1].type === "AssignmentPattern" ? path[2] : path[1];
<add> if (
<add> maybeProperty.type === "Property" &&
<add> maybeProperty.shorthand
<add> ) {
<add> source.insert(r[1], `: ${newName}`);
<add> continue;
<add> }
<ide> }
<add> source.replace(r[0], r[1] - 1, newName);
<ide> }
<ide> } else {
<ide> allUsedNames.add(name); | 1 |
Javascript | Javascript | fix broken assertion | 38ae95bb0c0c002b7b04040b0aa060e00b760cdd | <ide><path>test/parallel/test-cli-eval.js
<ide> child.exec(nodejs + ' --eval "require(\'./test/parallel/test-cli-eval.js\')"',
<ide> child.exec(nodejs + ' -e', common.mustCall(function(err, stdout, stderr) {
<ide> assert.strictEqual(err.code, 9);
<ide> assert.strictEqual(stdout, '');
<del> assert(stderr.match(/node: -e requires an argument\n/));
<add> assert.strictEqual(stderr.trim(),
<add> `${process.execPath}: -e requires an argument`);
<ide> }));
<ide>
<ide> // empty program should do nothing | 1 |
Python | Python | enable added tokens | 09b0bcfea98eb9e863248fd29566b6d1caf9a0ea | <ide><path>src/transformers/models/herbert/tokenization_herbert.py
<ide> class HerbertTokenizer(XLMTokenizer):
<ide> pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
<ide> max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
<ide>
<del> def __init__(self, *args, **kwargs):
<del>
<del> kwargs["cls_token"] = "<s>"
<del> kwargs["unk_token"] = "<unk>"
<del> kwargs["pad_token"] = "<pad>"
<del> kwargs["mask_token"] = "<mask>"
<del> kwargs["sep_token"] = "</s>"
<del> kwargs["do_lowercase_and_remove_accent"] = False
<del> kwargs["additional_special_tokens"] = []
<del>
<del> super().__init__(*args, **kwargs)
<add> def __init__(
<add> self,
<add> vocab_file,
<add> merges_file,
<add> tokenizer_file=None,
<add> cls_token="<s>",
<add> unk_token="<unk>",
<add> pad_token="<pad>",
<add> mask_token="<mask>",
<add> sep_token="</s>",
<add> do_lowercase_and_remove_accent=False,
<add> **kwargs
<add> ):
<add>
<add> super().__init__(
<add> vocab_file,
<add> merges_file,
<add> tokenizer_file=None,
<add> cls_token=cls_token,
<add> unk_token=unk_token,
<add> pad_token=pad_token,
<add> mask_token=mask_token,
<add> sep_token=sep_token,
<add> do_lowercase_and_remove_accent=do_lowercase_and_remove_accent,
<add> **kwargs,
<add> )
<ide> self.bert_pre_tokenizer = BasicTokenizer(
<del> do_lower_case=False, never_split=self.all_special_tokens, tokenize_chinese_chars=False, strip_accents=False
<add> do_lower_case=False,
<add> never_split=self.all_special_tokens,
<add> tokenize_chinese_chars=False,
<add> strip_accents=False,
<ide> )
<ide>
<ide> def _tokenize(self, text):
<ide><path>src/transformers/models/herbert/tokenization_herbert_fast.py
<ide> class HerbertTokenizerFast(PreTrainedTokenizerFast):
<ide> max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
<ide> slow_tokenizer_class = HerbertTokenizer
<ide>
<del> def __init__(self, vocab_file, merges_file, tokenizer_file=None, **kwargs):
<del>
<del> kwargs["cls_token"] = "<s>"
<del> kwargs["unk_token"] = "<unk>"
<del> kwargs["pad_token"] = "<pad>"
<del> kwargs["mask_token"] = "<mask>"
<del> kwargs["sep_token"] = "</s>"
<add> def __init__(
<add> self,
<add> vocab_file,
<add> merges_file,
<add> tokenizer_file=None,
<add> cls_token="<s>",
<add> unk_token="<unk>",
<add> pad_token="<pad>",
<add> mask_token="<mask>",
<add> sep_token="</s>",
<add> **kwargs
<add> ):
<ide>
<ide> super().__init__(
<ide> vocab_file,
<ide> merges_file,
<ide> tokenizer_file=tokenizer_file,
<add> cls_token=cls_token,
<add> unk_token=unk_token,
<add> pad_token=pad_token,
<add> mask_token=mask_token,
<add> sep_token=sep_token,
<ide> **kwargs,
<ide> )
<ide>
<ide><path>src/transformers/models/mbart/tokenization_mbart.py
<ide> class MBartTokenizer(XLMRobertaTokenizer):
<ide> prefix_tokens: List[int] = []
<ide> suffix_tokens: List[int] = []
<ide>
<del> def __init__(self, *args, tokenizer_file=None, src_lang=None, tgt_lang=None, **kwargs):
<del> super().__init__(*args, tokenizer_file=tokenizer_file, src_lang=src_lang, tgt_lang=tgt_lang, **kwargs)
<add> def __init__(
<add> self, *args, tokenizer_file=None, src_lang=None, tgt_lang=None, additional_special_tokens=None, **kwargs
<add> ):
<add> super().__init__(
<add> *args,
<add> tokenizer_file=tokenizer_file,
<add> src_lang=src_lang,
<add> tgt_lang=tgt_lang,
<add> additional_special_tokens=additional_special_tokens,
<add> **kwargs,
<add> )
<ide>
<ide> self.sp_model_size = len(self.sp_model)
<ide> self.lang_code_to_id = {
<ide> def __init__(self, *args, tokenizer_file=None, src_lang=None, tgt_lang=None, **k
<ide> self.fairseq_ids_to_tokens = {v: k for k, v in self.fairseq_tokens_to_ids.items()}
<ide> self._additional_special_tokens = list(self.lang_code_to_id.keys())
<ide>
<add> if additional_special_tokens is not None:
<add> self._additional_special_tokens.extend(additional_special_tokens)
<add>
<ide> self._src_lang = src_lang if src_lang is not None else "en_XX"
<ide> self.cur_lang_code_id = self.lang_code_to_id[self._src_lang]
<ide> self.tgt_lang = tgt_lang
<ide><path>src/transformers/models/mbart/tokenization_mbart_fast.py
<ide> class MBartTokenizerFast(XLMRobertaTokenizerFast):
<ide> prefix_tokens: List[int] = []
<ide> suffix_tokens: List[int] = []
<ide>
<del> def __init__(self, *args, tokenizer_file=None, src_lang=None, tgt_lang=None, **kwargs):
<del> super().__init__(*args, tokenizer_file=tokenizer_file, src_lang=src_lang, tgt_lang=tgt_lang, **kwargs)
<add> def __init__(
<add> self, *args, tokenizer_file=None, src_lang=None, tgt_lang=None, additional_special_tokens=None, **kwargs
<add> ):
<add> super().__init__(
<add> *args,
<add> tokenizer_file=tokenizer_file,
<add> src_lang=src_lang,
<add> tgt_lang=tgt_lang,
<add> additional_special_tokens=additional_special_tokens,
<add> **kwargs,
<add> )
<add>
<add> _additional_special_tokens = FAIRSEQ_LANGUAGE_CODES.copy()
<add>
<add> if additional_special_tokens is not None:
<add> _additional_special_tokens.extend(additional_special_tokens)
<ide>
<del> self.add_special_tokens({"additional_special_tokens": FAIRSEQ_LANGUAGE_CODES})
<add> self.add_special_tokens({"additional_special_tokens": _additional_special_tokens})
<ide>
<ide> self._src_lang = src_lang if src_lang is not None else "en_XX"
<ide> self.cur_lang_code = self.convert_tokens_to_ids(self._src_lang)
<ide><path>src/transformers/models/t5/tokenization_t5.py
<ide> def __init__(
<ide> additional_special_tokens = [f"<extra_id_{i}>" for i in range(extra_ids)]
<ide> elif extra_ids > 0 and additional_special_tokens is not None:
<ide> # Check that we have the right number of extra_id special tokens
<del> extra_tokens = len(set(filter(lambda x: bool("extra_id" in x), additional_special_tokens)))
<add> extra_tokens = len(set(filter(lambda x: bool("extra_id" in str(x)), additional_special_tokens)))
<ide> if extra_tokens != extra_ids:
<ide> raise ValueError(
<ide> f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are provided to T5Tokenizer. "
<ide><path>src/transformers/models/t5/tokenization_t5_fast.py
<ide> def __init__(
<ide> additional_special_tokens = [f"<extra_id_{i}>" for i in range(extra_ids)]
<ide> elif extra_ids > 0 and additional_special_tokens is not None:
<ide> # Check that we have the right number of extra special tokens
<del> extra_tokens = len(set(filter(lambda x: bool("extra_id_" in x), additional_special_tokens)))
<add> extra_tokens = len(set(filter(lambda x: bool("extra_id_" in str(x)), additional_special_tokens)))
<ide> if extra_tokens != extra_ids:
<ide> raise ValueError(
<ide> f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are provided to T5Tokenizer. "
<ide><path>tests/test_tokenization_common.py
<ide> def test_compare_prepare_for_model(self):
<ide> for key in python_output:
<ide> self.assertEqual(python_output[key], rust_output[key])
<ide>
<add> def test_special_tokens_initialization(self):
<add> for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
<add> with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
<add>
<add> added_tokens = [AddedToken("<special>", lstrip=True)]
<add>
<add> tokenizer_r = self.rust_tokenizer_class.from_pretrained(
<add> pretrained_name, additional_special_tokens=added_tokens, **kwargs
<add> )
<add> tokenizer_cr = self.rust_tokenizer_class.from_pretrained(
<add> pretrained_name, additional_special_tokens=added_tokens, **kwargs, from_slow=True
<add> )
<add> tokenizer_p = self.tokenizer_class.from_pretrained(
<add> pretrained_name, additional_special_tokens=added_tokens, **kwargs
<add> )
<add>
<add> p_output = tokenizer_p.encode("Hey this is a <special> token")
<add> r_output = tokenizer_r.encode("Hey this is a <special> token")
<add> cr_output = tokenizer_cr.encode("Hey this is a <special> token")
<add>
<add> special_token_id = tokenizer_r.encode("<special>", add_special_tokens=False)[0]
<add>
<add> self.assertEqual(p_output, r_output)
<add> self.assertEqual(cr_output, r_output)
<add> self.assertTrue(special_token_id in p_output)
<add> self.assertTrue(special_token_id in r_output)
<add> self.assertTrue(special_token_id in cr_output)
<add>
<ide>
<ide> @is_staging_test
<ide> class TokenizerPushToHubTester(unittest.TestCase):
<ide><path>tests/test_tokenization_t5.py
<ide>
<ide> import unittest
<ide>
<del>from transformers import SPIECE_UNDERLINE, BatchEncoding, T5Tokenizer, T5TokenizerFast
<add>from transformers import SPIECE_UNDERLINE, AddedToken, BatchEncoding, T5Tokenizer, T5TokenizerFast
<ide> from transformers.file_utils import cached_property, is_tf_available, is_torch_available
<ide> from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers
<ide>
<ide> def test_fast_and_slow_same_result(self):
<ide> slow_text = self.t5_base_tokenizer.decode(fast_ids)
<ide> self.assertEqual(tgt_text, fast_text)
<ide> self.assertEqual(tgt_text, slow_text)
<add>
<add> def test_special_tokens_initialization(self):
<add> for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
<add> with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
<add>
<add> added_tokens = [f"<extra_id_{i}>" for i in range(100)] + [AddedToken("<special>", lstrip=True)]
<add>
<add> tokenizer_r = self.rust_tokenizer_class.from_pretrained(
<add> pretrained_name, additional_special_tokens=added_tokens, **kwargs
<add> )
<add> tokenizer_cr = self.rust_tokenizer_class.from_pretrained(
<add> pretrained_name, additional_special_tokens=added_tokens, **kwargs, from_slow=True
<add> )
<add> tokenizer_p = self.tokenizer_class.from_pretrained(
<add> pretrained_name, additional_special_tokens=added_tokens, **kwargs
<add> )
<add>
<add> p_output = tokenizer_p.encode("Hey this is a <special> token")
<add> r_output = tokenizer_r.encode("Hey this is a <special> token")
<add> cr_output = tokenizer_cr.encode("Hey this is a <special> token")
<add>
<add> special_token_id = tokenizer_r.encode("<special>", add_special_tokens=False)[0]
<add>
<add> self.assertEqual(p_output, r_output)
<add> self.assertEqual(cr_output, r_output)
<add> self.assertTrue(special_token_id in p_output)
<add> self.assertTrue(special_token_id in r_output)
<add> self.assertTrue(special_token_id in cr_output) | 8 |
Python | Python | adjust message [ci skip] | 1bce432b4af2c3bc3ea98a8bad54690f6ff01ec3 | <ide><path>spacy/cli/_util.py
<ide> def git_sparse_checkout(repo: str, subpath: str, dest: Path, *, branch: str = "m
<ide> msg.warn(
<ide> f"You're running an old version of Git (v{git_version[0]}.{git_version[1]}) "
<ide> f"that doesn't fully support sparse checkout yet. This means that "
<del> f"more files than necessary may be cloned. To only download the "
<del> f"files needed, upgrade to Git v2.22 or above."
<add> f"more files than necessary may be downloaded temporarily. To "
<add> f"only download the files needed, upgrade to Git v2.22 or above."
<ide> )
<ide> _attempt_run_command(cmd)
<ide> # Now we need to find the missing filenames for the subpath we want. | 1 |
PHP | PHP | add returntypewillchange for eventlist | 2a853c3b5e554d8b44c728aee504e12c68b11a38 | <ide><path>src/Event/EventList.php
<ide>
<ide> use ArrayAccess;
<ide> use Countable;
<add>use ReturnTypeWillChange;
<ide>
<ide> /**
<ide> * The Event List
<ide> public function offsetExists($offset): bool
<ide> * @param mixed $offset The offset to retrieve.
<ide> * @return mixed Can return all value types.
<ide> */
<add> #[ReturnTypeWillChange]
<ide> public function offsetGet($offset)
<ide> {
<ide> if ($this->offsetExists($offset)) { | 1 |
Text | Text | remove extra space | db5f8d181fb15a7a0390bf9af5d0264ae5740ba9 | <ide><path>docs/recipes/WritingTests.md
<ide> and configure it to use [babel-preset-env](https://github.com/babel/babel/tree/m
<ide>
<ide> ```js
<ide> {
<del> "presets": ["@babel/preset-env"]
<add> "presets": ["@babel/preset-env"]
<ide> }
<ide> ```
<ide> | 1 |
Javascript | Javascript | reintroduce use of requestanimationframe | 72119e0023dcc0d9807caf6d988598b74abdc937 | <ide><path>src/effects.js
<ide> var
<ide> } ]
<ide> };
<ide>
<add>function raf() {
<add> if ( timerId ) {
<add> window.requestAnimationFrame( raf );
<add> jQuery.fx.tick();
<add> }
<add>}
<add>
<add>// Will get false negative for old browsers which is okay
<add>function isDocumentHidden() {
<add> return "hidden" in document && document.hidden;
<add>}
<add>
<ide> // Animations created synchronously will run synchronously
<ide> function createFxNow() {
<ide> setTimeout(function() {
<ide> jQuery.speed = function( speed, easing, fn ) {
<ide>
<ide> jQuery.fn.extend({
<ide> fadeTo: function( speed, to, easing, callback ) {
<add> if ( isDocumentHidden() ) {
<add> return this;
<add> }
<ide>
<ide> // Show any hidden elements after setting opacity to 0
<ide> return this.filter( isHidden ).css( "opacity", 0 ).show()
<ide> jQuery.fn.extend({
<ide> .end().animate({ opacity: to }, speed, easing, callback );
<ide> },
<ide> animate: function( prop, speed, easing, callback ) {
<add> if ( isDocumentHidden() ) {
<add> return this;
<add> }
<add>
<ide> var empty = jQuery.isEmptyObject( prop ),
<ide> optall = jQuery.speed( speed, easing, callback ),
<ide> doAnimation = function() {
<ide> jQuery.fx.timer = function( timer ) {
<ide> };
<ide>
<ide> jQuery.fx.interval = 13;
<del>
<ide> jQuery.fx.start = function() {
<ide> if ( !timerId ) {
<del> timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
<add> if ( window.requestAnimationFrame ) {
<add> timerId = true;
<add> window.requestAnimationFrame( raf );
<add> } else {
<add> timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
<add> }
<ide> }
<ide> };
<ide>
<ide><path>test/unit/effects.js
<ide> if ( !jQuery.fx ) {
<ide> return;
<ide> }
<ide>
<add>var oldRaf = window.requestAnimationFrame;
<add>
<ide> module("effects", {
<ide> setup: function() {
<add> window.requestAnimationFrame = null;
<ide> this.clock = sinon.useFakeTimers( 505877050 );
<ide> this._oldInterval = jQuery.fx.interval;
<ide> jQuery.fx.interval = 10;
<ide> module("effects", {
<ide> jQuery.now = Date.now;
<ide> jQuery.fx.stop();
<ide> jQuery.fx.interval = this._oldInterval;
<add> window.requestAnimationFrame = oldRaf;
<ide> return moduleTeardown.apply( this, arguments );
<ide> }
<ide> }); | 2 |
Ruby | Ruby | revert the user-path fix | 05c708b9fc2a97dd890bdfb478b749b3e6e215e5 | <ide><path>Library/Homebrew/build.rb
<ide> def main
<ide> end
<ide> end
<ide>
<del>def install f
<add>def pre_superenv_hacks f
<ide> # TODO replace with Formula DSL
<ide> # Python etc. build but then pip can't build stuff.
<ide> # Scons resets ENV and then can't find superenv's build-tools.
<add> # In some cases we should only apply in the case of an option I suggest the
<add> # following:
<add> #
<add> # option 'with-passenger' do
<add> # env :userpaths # for superenv
<add> # end
<add> # option 'without-foo' do
<add> # env :std, :x11
<add> # end
<add> #
<add> # NOTE I think all ENV stuff should be specified with a DSL like this now.
<add> case f.name
<add> when 'lilypond', 'nginx'
<add> paths = ORIGINAL_PATHS.map{|pn| pn.realpath.to_s rescue nil } - %w{/usr/X11/bin /opt/X11/bin}
<add> ENV['PATH'] = "#{ENV['PATH']}:#{paths.join(':')}"
<add> end
<ide> stdenvs = %w{fontforge python python3 ruby ruby-enterprise-edition jruby wine}
<ide> ARGV.unshift '--env=std' if (stdenvs.include?(f.name) or
<ide> f.recursive_deps.detect{|d| d.name == 'scons' }) and
<ide> not ARGV.include? '--env=super'
<add>end
<ide>
<add>def install f
<ide> keg_only_deps = f.recursive_deps.uniq.select{|dep| dep.keg_only? }
<ide>
<add> pre_superenv_hacks(f)
<ide> require 'superenv'
<ide>
<ide> ENV.setup_build_environment unless superenv?
<ide><path>Library/Homebrew/superenv.rb
<ide> def determine_path
<ide> paths << HOMEBREW_PREFIX/:bin
<ide> paths << "#{MacSystem.x11_prefix}/bin" if x11?
<ide> paths += %w{/usr/bin /bin /usr/sbin /sbin}
<del> paths += ORIGINAL_PATHS.map{|pn| pn.realpath.to_s rescue nil } - %w{/usr/X11/bin /opt/X11/bin}
<ide> paths.to_path_s
<ide> end
<ide> | 2 |
PHP | PHP | remove unused dispatcher | e82a78c40f4c8b353cab2d55488d4da400eba5fc | <ide><path>app/Providers/EventServiceProvider.php
<ide> <?php namespace App\Providers;
<ide>
<del>use Illuminate\Contracts\Events\Dispatcher;
<ide> use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
<ide>
<ide> class EventServiceProvider extends ServiceProvider { | 1 |
Javascript | Javascript | fix style and add var declaration | 9650df5c10a51976d1b8600d79ff244274e5764c | <ide><path>src/colorspace.js
<ide> var DeviceCmykCS = (function DeviceCmykCSClosure() {
<ide> var c = color[0], m = color[1], y = color[2], k = color[3];
<ide>
<ide> // CMYK -> CMY: http://www.easyrgb.com/index.php?X=MATH&H=14#text14
<del> c = (c * (1-k) + k);
<del> m = (m * (1-k) + k);
<del> y = (y * (1-k) + k);
<add> c = (c * (1 - k) + k);
<add> m = (m * (1 - k) + k);
<add> y = (y * (1 - k) + k);
<ide>
<ide> // CMY -> RGB: http://www.easyrgb.com/index.php?X=MATH&H=12#text12
<del> r = (1-c);
<del> g = (1-m);
<del> b = (1-y);
<add> var r = (1 - c);
<add> var g = (1 - m);
<add> var b = (1 - y);
<ide>
<ide> return [r, g, b];
<ide> }, | 1 |
Javascript | Javascript | simplify nexttick() usage | 5abd4ac079b390467360d671a186a061b5aba736 | <ide><path>lib/_stream_writable.js
<ide> function doWrite(stream, state, writev, len, chunk, encoding, cb) {
<ide> }
<ide>
<ide> function onwriteError(stream, state, sync, er, cb) {
<add> --state.pendingcb;
<ide> if (sync)
<del> process.nextTick(onwriteErrorNT, state, cb, er);
<del> else {
<del> state.pendingcb--;
<add> process.nextTick(cb, er);
<add> else
<ide> cb(er);
<del> }
<ide>
<ide> stream._writableState.errorEmitted = true;
<ide> stream.emit('error', er);
<ide> }
<ide>
<del>function onwriteErrorNT(state, cb, er) {
<del> state.pendingcb--;
<del> cb(er);
<del>}
<del>
<ide> function onwriteStateUpdate(state) {
<ide> state.writing = false;
<ide> state.writecb = null;
<ide><path>lib/_tls_legacy.js
<ide> CryptoStream.prototype.destroy = function(err) {
<ide> }
<ide> this._opposite.destroy();
<ide>
<del> process.nextTick(destroyNT, this, err);
<add> process.nextTick(destroyNT, this, err ? true : false);
<ide> };
<ide>
<ide>
<del>function destroyNT(self, err) {
<add>function destroyNT(self, hadErr) {
<ide> // Force EOF
<ide> self.push(null);
<ide>
<ide> // Emit 'close' event
<del> self.emit('close', err ? true : false);
<add> self.emit('close', hadErr);
<ide> }
<ide>
<ide>
<ide><path>lib/_tls_wrap.js
<ide> TLSSocket.prototype.renegotiate = function(options, callback) {
<ide> }
<ide> if (!this._handle.renegotiate()) {
<ide> if (callback) {
<del> process.nextTick(function() {
<del> callback(new Error('Failed to renegotiate'));
<del> });
<add> process.nextTick(callback, new Error('Failed to renegotiate'));
<ide> }
<ide> return false;
<ide> }
<ide><path>lib/dgram.js
<ide> Socket.prototype.send = function(buffer,
<ide> !!callback);
<ide> if (err && callback) {
<ide> // don't emit as error, dgram_legacy.js compatibility
<del> process.nextTick(sendEmitErrorNT, err, address, port, callback);
<add> var ex = exceptionWithHostPort(err, 'send', address, port);
<add> process.nextTick(callback, ex);
<ide> }
<ide> }
<ide> });
<ide> };
<ide>
<ide>
<del>function sendEmitErrorNT(err, address, port, callback) {
<del> var ex = exceptionWithHostPort(err, 'send', address, port);
<del> callback(ex);
<del>}
<del>
<del>
<ide> function afterSend(err) {
<ide> if (err) {
<ide> err = exceptionWithHostPort(err, 'send', this.address, this.port);
<ide><path>lib/dns.js
<ide> function makeAsync(callback) {
<ide> // The API already returned, we can invoke the callback immediately.
<ide> callback.apply(null, arguments);
<ide> } else {
<del> process.nextTick(callMakeAsyncCbNT, callback, arguments);
<add> var args = new Array(arguments.length + 1);
<add> args[0] = callback;
<add> for (var i = 1, a = 0; a < arguments.length; ++i, ++a)
<add> args[i] = arguments[a];
<add> process.nextTick.apply(null, args);
<ide> }
<ide> };
<ide> }
<ide>
<ide>
<del>function callMakeAsyncCbNT(callback, args) {
<del> callback.apply(null, args);
<del>}
<del>
<del>
<ide> function onlookup(err, addresses) {
<ide> if (err) {
<ide> return this.callback(errnoException(err, 'getaddrinfo', this.hostname));
<ide><path>lib/net.js
<ide> function writeAfterFIN(chunk, encoding, cb) {
<ide> // TODO: defer error events consistently everywhere, not just the cb
<ide> self.emit('error', er);
<ide> if (typeof cb === 'function') {
<del> process.nextTick(writeAfterFINNT, cb, er);
<add> process.nextTick(cb, er);
<ide> }
<ide> }
<ide>
<del>function writeAfterFINNT(cb, er) {
<del> cb(er);
<del>}
<del>
<ide> exports.Socket = Socket;
<ide> exports.Stream = Socket; // Legacy naming.
<ide>
<ide> Socket.prototype._destroy = function(exception, cb) {
<ide> function fireErrorCallbacks() {
<ide> if (cb) cb(exception);
<ide> if (exception && !self._writableState.errorEmitted) {
<del> process.nextTick(function() {
<del> self.emit('error', exception);
<del> });
<add> process.nextTick(emitErrorNT, self, exception);
<ide> self._writableState.errorEmitted = true;
<ide> }
<ide> }
<ide> function lookupAndConnect(self, options) {
<ide> // immediately calls net.Socket.connect() on it (that's us).
<ide> // There are no event listeners registered yet so defer the
<ide> // error event to the next tick.
<del> process.nextTick(connectErrorNT, self, err, options);
<add> err.host = options.host;
<add> err.port = options.port;
<add> err.message = err.message + ' ' + options.host + ':' + options.port;
<add> process.nextTick(connectErrorNT, self, err);
<ide> } else {
<ide> self._unrefTimer();
<ide> connect(self,
<ide> function lookupAndConnect(self, options) {
<ide> }
<ide>
<ide>
<del>function connectErrorNT(self, err, options) {
<del> err.host = options.host;
<del> err.port = options.port;
<del> err.message = err.message + ' ' + options.host + ':' + options.port;
<add>function connectErrorNT(self, err) {
<ide> self.emit('error', err);
<ide> self._destroy();
<ide> }
<ide> Server.prototype._listen2 = function(address, port, addressType, backlog, fd) {
<ide>
<ide> if (typeof rval === 'number') {
<ide> var error = exceptionWithHostPort(rval, 'listen', address, port);
<del> process.nextTick(function() {
<del> self.emit('error', error);
<del> });
<add> process.nextTick(emitErrorNT, self, error);
<ide> return;
<ide> }
<ide> self._handle = rval;
<ide> Server.prototype._listen2 = function(address, port, addressType, backlog, fd) {
<ide> var ex = exceptionWithHostPort(err, 'listen', address, port);
<ide> self._handle.close();
<ide> self._handle = null;
<del> process.nextTick(function() {
<del> self.emit('error', ex);
<del> });
<add> process.nextTick(emitErrorNT, self, ex);
<ide> return;
<ide> }
<ide>
<ide> Server.prototype._listen2 = function(address, port, addressType, backlog, fd) {
<ide> };
<ide>
<ide>
<add>function emitErrorNT(self, err) {
<add> self.emit('error', err);
<add>}
<add>
<add>
<ide> function emitListeningNT(self) {
<ide> // ensure handle hasn't closed
<ide> if (self._handle)
<ide> function onconnection(err, clientHandle) {
<ide>
<ide> Server.prototype.getConnections = function(cb) {
<ide> function end(err, connections) {
<del> process.nextTick(function() {
<del> cb(err, connections);
<del> });
<add> process.nextTick(cb, err, connections);
<ide> }
<ide>
<ide> if (!this._usingSlaves) {
<ide> Server.prototype._emitCloseIfDrained = function() {
<ide> return;
<ide> }
<ide>
<del> process.nextTick(function() {
<del> debug('SERVER: emit close');
<del> self.emit('close');
<del> });
<add> process.nextTick(emitCloseNT, self);
<ide> };
<ide>
<ide>
<add>function emitCloseNT(self) {
<add> debug('SERVER: emit close');
<add> self.emit('close');
<add>}
<add>
<add>
<ide> Server.prototype.listenFD = util.deprecate(function(fd, type) {
<ide> return this.listen({ fd: fd });
<ide> }, 'listenFD is deprecated. Use listen({fd: <number>}).');
<ide><path>lib/timers.js
<ide> function listOnTimeout() {
<ide> // when the timeout threw its exception.
<ide> var oldDomain = process.domain;
<ide> process.domain = null;
<del> process.nextTick(function() {
<del> list[kOnTimeout]();
<del> });
<add> process.nextTick(listOnTimeoutNT, list);
<ide> process.domain = oldDomain;
<ide> }
<ide> }
<ide> function listOnTimeout() {
<ide> }
<ide>
<ide>
<add>function listOnTimeoutNT(list) {
<add> list[kOnTimeout]();
<add>}
<add>
<add>
<ide> const unenroll = exports.unenroll = function(item) {
<ide> L.remove(item);
<ide> | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.